Skip to content

Commit a6b1425

Browse files
committed
feat: add token_handler
1 parent a15ff7a commit a6b1425

File tree

1 file changed

+8
-1
lines changed

1 file changed

+8
-1
lines changed

tokenstream/stream.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import re
99
from contextlib import contextmanager
1010
from dataclasses import dataclass, field
11-
from typing import Any, ContextManager, Iterable, Iterator, TypeVar, overload
11+
from typing import Any, Callable, ContextManager, Iterable, Iterator, TypeVar, overload
1212

1313
from .error import InvalidSyntax, UnexpectedEOF, UnexpectedToken
1414
from .location import SourceLocation, set_location
@@ -68,6 +68,9 @@ class TokenStream:
6868
>>> stream.source
6969
'hello world'
7070
71+
token_handler
72+
A callback for modifying tokens before they're emitted.
73+
7174
syntax_rules
7275
A tuple of ``(token_type, pattern)`` pairs that define the recognizable tokens.
7376
@@ -140,6 +143,7 @@ class TokenStream:
140143
"""
141144

142145
source: str
146+
token_handler: Callable[[Token], Token] | None = extra_field(default=None)
143147
syntax_rules: SyntaxRules = extra_field(default=())
144148
regex: re.Pattern[str] = extra_field()
145149

@@ -482,6 +486,9 @@ def emit_token(self, token_type: str, value: str = "") -> Token:
482486
end_location=SourceLocation(end_pos, end_lineno, end_colno),
483487
)
484488

489+
if self.token_handler:
490+
token = self.token_handler(token)
491+
485492
self.location = token.end_location
486493
self.tokens.append(token)
487494

0 commit comments

Comments
 (0)