phy-std-base-tokenizer 0.1.0rc1__cp313-cp313-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,169 @@
1
+ Metadata-Version: 2.2
2
+ Name: phy-std-base-tokenizer
3
+ Version: 0.1.0rc1
4
+ Summary: Base tokenizer for phy project extracted from python 3.14 builtin tokenize module
5
+ Author-Email: alfred-du <ihearmywords@hotmail.com>
6
+ License: MIT
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3.10
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Programming Language :: Python :: 3.13
12
+ Classifier: Programming Language :: Python :: 3.14
13
+ Classifier: Programming Language :: Python :: 3.15
14
+ Project-URL: Homepage, https://github.com/phy-precompiler/std-base-tokenizer
15
+ Project-URL: Repository, https://github.com/phy-precompiler/std-base-tokenizer
16
+ Project-URL: Issues, https://github.com/phy-precompiler/std-base-tokenizer/issues
17
+ Requires-Python: <4,>=3.10
18
+ Description-Content-Type: text/markdown
19
+
20
+ # Consistent Tokenizer Across Python Versions
21
+
22
+ <p align="left">
23
+ <a href="#"><img alt="PyPI" src="https://img.shields.io/pypi/v/phy-std-base-tokenizer.svg"></a>
24
+ <a href="#"><img alt="Python Versions" src="https://img.shields.io/pypi/pyversions/phy-std-base-tokenizer.svg"></a>
25
+ <a href="#"><img alt="License" src="https://img.shields.io/badge/license-MIT-blue.svg"></a>
26
+ </p>
27
+
28
+ This project is part of [`phy`](https://github.com/phy-precompiler).
29
+
30
+ ## Overview
31
+
32
+ This package provides a replacement for Python builtin `tokenize` module and behaves consistently across active python versions.
33
+
34
+ The differences of builtin `tokenize` module among versions includes:
35
+
36
+ - Since Python 3.12, new fstring related token types `FSTRING_START`, `FSTRING_MIDDLE` & `FSTRING_END` were introduced for [PEP 701](https://peps.python.org/pep-0701/), along with notable performance enhancements.
37
+
38
+ - Python 3.14 brings new token types `TSTRING_START`, `TSTRING_MIDDLE` & `TSTRING_END` for new syntax [Template String](https://peps.python.org/pep-0750/).
39
+
40
+ - Python's built-in [`token`](https://docs.python.org/3/library/token.html) module assigns an **integer value** to each token type. However, these numeric values are **not guaranteed to be stable** across Python versions:
41
+
42
+ | token type | python 3.10 | python 3.11 | python 3.12 | python 3.13 | python 3.14+ |
43
+ |------------------|-------------|-------------|-------------|-------------|--------------|
44
+ | ENDMARKER | 0 | 0 | 0 | 0 | 0 |
45
+ | NAME | 1 | 1 | 1 | 1 | 1 |
46
+ | NUMBER | 2 | 2 | 2 | 2 | 2 |
47
+ | STRING | 3 | 3 | 3 | 3 | 3 |
48
+ | NEWLINE | 4 | 4 | 4 | 4 | 4 |
49
+ | INDENT | 5 | 5 | 5 | 5 | 5 |
50
+ | DEDENT | 6 | 6 | 6 | 6 | 6 |
51
+ | LPAR | 7 | 7 | 7 | 7 | 7 |
52
+ | RPAR | 8 | 8 | 8 | 8 | 8 |
53
+ | LSQB | 9 | 9 | 9 | 9 | 9 |
54
+ | RSQB | 10 | 10 | 10 | 10 | 10 |
55
+ | COLON | 11 | 11 | 11 | 11 | 11 |
56
+ | COMMA | 12 | 12 | 12 | 12 | 12 |
57
+ | SEMI | 13 | 13 | 13 | 13 | 13 |
58
+ | PLUS | 14 | 14 | 14 | 14 | 14 |
59
+ | MINUS | 15 | 15 | 15 | 15 | 15 |
60
+ | STAR | 16 | 16 | 16 | 16 | 16 |
61
+ | SLASH | 17 | 17 | 17 | 17 | 17 |
62
+ | VBAR | 18 | 18 | 18 | 18 | 18 |
63
+ | AMPER | 19 | 19 | 19 | 19 | 19 |
64
+ | LESS | 20 | 20 | 20 | 20 | 20 |
65
+ | GREATER | 21 | 21 | 21 | 21 | 21 |
66
+ | EQUAL | 22 | 22 | 22 | 22 | 22 |
67
+ | DOT | 23 | 23 | 23 | 23 | 23 |
68
+ | PERCENT | 24 | 24 | 24 | 24 | 24 |
69
+ | LBRACE | 25 | 25 | 25 | 25 | 25 |
70
+ | RBRACE | 26 | 26 | 26 | 26 | 26 |
71
+ | EQEQUAL | 27 | 27 | 27 | 27 | 27 |
72
+ | NOTEQUAL | 28 | 28 | 28 | 28 | 28 |
73
+ | LESSEQUAL | 29 | 29 | 29 | 29 | 29 |
74
+ | GREATEREQUAL | 30 | 30 | 30 | 30 | 30 |
75
+ | TILDE | 31 | 31 | 31 | 31 | 31 |
76
+ | CIRCUMFLEX | 32 | 32 | 32 | 32 | 32 |
77
+ | LEFTSHIFT | 33 | 33 | 33 | 33 | 33 |
78
+ | RIGHTSHIFT | 34 | 34 | 34 | 34 | 34 |
79
+ | DOUBLESTAR | 35 | 35 | 35 | 35 | 35 |
80
+ | PLUSEQUAL | 36 | 36 | 36 | 36 | 36 |
81
+ | MINEQUAL | 37 | 37 | 37 | 37 | 37 |
82
+ | STAREQUAL | 38 | 38 | 38 | 38 | 38 |
83
+ | SLASHEQUAL | 39 | 39 | 39 | 39 | 39 |
84
+ | PERCENTEQUAL | 40 | 40 | 40 | 40 | 40 |
85
+ | AMPEREQUAL | 41 | 41 | 41 | 41 | 41 |
86
+ | VBAREQUAL | 42 | 42 | 42 | 42 | 42 |
87
+ | CIRCUMFLEXEQUAL | 43 | 43 | 43 | 43 | 43 |
88
+ | LEFTSHIFTEQUAL | 44 | 44 | 44 | 44 | 44 |
89
+ | RIGHTSHIFTEQUAL | 45 | 45 | 45 | 45 | 45 |
90
+ | DOUBLESTAREQUAL | 46 | 46 | 46 | 46 | 46 |
91
+ | DOUBLESLASH | 47 | 47 | 47 | 47 | 47 |
92
+ | DOUBLESLASHEQUAL | 48 | 48 | 48 | 48 | 48 |
93
+ | AT | 49 | 49 | 49 | 49 | 49 |
94
+ | ATEQUAL | 50 | 50 | 50 | 50 | 50 |
95
+ | RARROW | 51 | 51 | 51 | 51 | 51 |
96
+ | ELLIPSIS | 52 | 52 | 52 | 52 | 52 |
97
+ | COLONEQUAL | 53 | 53 | 53 | 53 | 53 |
98
+ | EXCLAMATION | | | 54 | 54 | 54 |
99
+ | OP | 54 | 54 | 55 | 55 | 55 |
100
+ | AWAIT | 55 | 55 | 56 | | |
101
+ | ASYNC | 56 | 56 | 57 | | |
102
+ | TYPE_IGNORE | 57 | 57 | 58 | 56 | 56 |
103
+ | TYPE_COMMENT | 58 | 58 | 59 | 57 | 57 |
104
+ | SOFT_KEYWORD | 59 | 59 | 60 | 58 | 58 |
105
+ | FSTRING_START | | | 61 | 59 | 59 |
106
+ | FSTRING_MIDDLE | | | 62 | 60 | 60 |
107
+ | FSTRING_END | | | 63 | 61 | 61 |
108
+ | TSTRING_START | | | | | 62 |
109
+ | TSTRING_MIDDLE | | | | | 63 |
110
+ | TSTRING_END | | | | | 64 |
111
+ | COMMENT | 61 | 61 | 64 | 62 | 65 |
112
+ | NL | 62 | 62 | 65 | 63 | 66 |
113
+ | ERRORTOKEN | 60 | 60 | 66 | 64 | 67 |
114
+ | N_TOKENS | 64 | 64 | 68 | 66 | 69 |
115
+ | NT_OFFSET | 256 | 256 | 256 | 256 | 256 |
116
+
117
+
118
+ This may lead to necessary extra works about token codes alignment if your project relies on consistent numeric token codes across environments.
119
+
120
+ ---
121
+
122
+ ## What this Project Does
123
+
124
+ This repository extracts the c code related to `lexer` & `tokenize` from CPython 3.15 source code (the latest Python version), and build a standalone python package with the same Python API as built-in `tokenize` module.
125
+
126
+ Use this package to tokenize python codes will produce the same results, regardless of which version of python interpreter is used.
127
+
128
+ This package has **ZERO** dependencies.
129
+
130
+
131
+ ## Installation
132
+
133
+ ```shell
134
+ pip install phy-std-base-tokenizer
135
+ ```
136
+
137
+ If theres is issue in installing on Windows, refer to [build-on-windows](#build-on-windows) to built it by ones own.
138
+
139
+ ## How to use
140
+
141
+ Use this library like builtin `tokenize` module:
142
+
143
+ ```python
144
+ from io import BytesIO, StringIO
145
+ import phy_std_base_tokenzier
146
+
147
+ code = '''print(f"hello world to {greeter}!")\ntemplate=t"input a {name}"\n'''
148
+ code_str_readline = StringIO(code).readline
149
+
150
+ for _token in phy_std_base_tokenzier.generate_toks(code_str_readline):
151
+ print(_token)
152
+ ```
153
+
154
+ The generated token is instance of `phy_core.TokInfo`.
155
+
156
+ ## Build
157
+
158
+ This library use [`scikit-build-core`](https://github.com/scikit-build/scikit-build-core) and
159
+ [`uv`](https://github.com/astral-sh/uv) to build; `cmake` is a dependency of `scikit-build-core`.
160
+
161
+ ```bash
162
+ uv build
163
+ ```
164
+
165
+ ### build on Windows
166
+
167
+ If you use `visual c++` as compiler to build this package, to avoid error "The C compiler identification is unknown", it is better to use `Command Prompt for VS` app to execute the build command.
168
+
169
+ If error "The C compiler identification is unknown. CMAKE_C_COMPILER could be found" encountered but you have Visual C++ installed, try to install the component `Desktop development with C++`.
@@ -0,0 +1,10 @@
1
+ phy_std_base_tokenzier/__init__.py,sha256=-KaDEnBvKcGL_jpaQ4jExQtB4zue_DshsFBGHcDF6sY,734
2
+ phy_std_base_tokenzier/_phy_compat.py,sha256=iFShlRIhLfbZT7SJXOthqy0LiHhat9VHX0b-VEe_DGs,9327
3
+ phy_std_base_tokenzier/_token_type.py,sha256=4XHWMvrq3oXsNmjS9bf9jA05EHrC44BDZGx5GPpjZ8E,2742
4
+ phy_std_base_tokenzier/_tokenize.pyd,sha256=wKoeguaCMnLnOkKy1-YdRJElku9we-8jFVSprtyLKXA,34816
5
+ phy_std_base_tokenzier/_tokenize.pyi,sha256=B75XVfR2MeEyhQi9dUsGDU8kU50_2QKXWNxQU7tDHII,622
6
+ phy_std_base_tokenzier/compat.py,sha256=R-yveG55mGEmvs2Gw-FFfaVflx-WNHFN9uGLkXn_LYw,3686
7
+ phy_std_base_tokenizer-0.1.0rc1.dist-info/METADATA,sha256=JnTh4vRBztuIZFDQFpTRJtBCwxPAngelSoCnfv400hs,10765
8
+ phy_std_base_tokenizer-0.1.0rc1.dist-info/WHEEL,sha256=bzccfTXe5NE7eB86OiS4hIwvwnRsRQgKw2c3BU4To6A,105
9
+ phy_std_base_tokenizer-0.1.0rc1.dist-info/licenses/LICENSE,sha256=VaQ6PPjYAqDAO0LamBpMjpEG0k-6qWSRoD_p1BhVnrs,1089
10
+ phy_std_base_tokenizer-0.1.0rc1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: scikit-build-core 1.1.2
3
+ Root-Is-Purelib: false
4
+ Tag: cp313-cp313-win_amd64
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 PHY PROJECT
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,26 @@
1
+ """ Interfaces of module `std_base_toknzer`.
2
+
3
+ These methods are strictly compatible with builtin `tokenize` module.
4
+ """
5
+ __all__ = [
6
+ 'StdBaseToknzer',
7
+ ]
8
+ __version__ = '0.1.0rc1'
9
+
10
+
11
+ # imports
12
+ from typing import Callable
13
+
14
+ # local imports
15
+ from phy_std_base_tokenzier._phy_compat import TokGen
16
+ from phy_std_base_tokenzier.compat import generate_tokens
17
+
18
+
19
+ class StdBaseToknzer:
20
+ """ class that conform to `BaseToknzer` protocol """
21
+
22
+ def generate_toks(self, str_readline: Callable[[], str]) -> TokGen:
23
+ """ rename method name from `generate_tokens` (builtin tokenize module compatible)
24
+ to `generate_toks` (base tokenizer protocol)
25
+ """
26
+ return generate_tokens(str_readline)
@@ -0,0 +1,272 @@
1
+ """Compatible layer for `phy-core`. This submodule should be removed after adding
2
+ `phy-core` as dependency.
3
+ """
4
+
5
+ # imports
6
+ import token as builtin_token
7
+ from dataclasses import dataclass
8
+ from enum import Enum
9
+ from typing import Generator, Optional, Protocol, Tuple, Union
10
+
11
+
12
+ class TokType(Protocol):
13
+ """structural typing for union `StdTokType` and `NamespacedTokType`"""
14
+
15
+ # instance attributes
16
+ namespace: Optional[str]
17
+ name: str
18
+
19
+ # instance methods
20
+ # these boolean properties are defined in cpython source `Include/internal/pycore_token.h`
21
+ def is_terminal(self) -> bool: ...
22
+ def is_eof(self) -> bool: ...
23
+ def is_whitespace(self) -> bool: ...
24
+ def is_string_lit(self) -> bool: ...
25
+
26
+ # these boolean properties are for untokenizing
27
+ def is_curly_bracket_escaped(self) -> bool: ...
28
+
29
+
30
+ class StdTokType(Enum):
31
+ """Standard token types are enums of token types in latest python versions (for now 3.14). Removed
32
+ token types (like ASYNC / AWAIT in <3.13) are not inclueded.
33
+
34
+ This enum may change regarding python upgrades.
35
+ """
36
+
37
+ # these token types are consistent across python versions
38
+ ENDMARKER = 0
39
+ NAME = 1
40
+ NUMBER = 2
41
+ STRING = 3
42
+ NEWLINE = 4
43
+ INDENT = 5
44
+ DEDENT = 6
45
+ NT_OFFSET = 256
46
+ # Leave room for exact operators token types, which are defined in `StdOpExactTokType` enum and
47
+ # takes int value from 7 ~ 54.
48
+
49
+ # these token types are inconsistent across python versions
50
+ OP = 128
51
+ TYPE_IGNORE = 129
52
+ TYPE_COMMENT = 130
53
+ SOFT_KEYWORD = 131
54
+ ERRORTOKEN = 132
55
+ ENCODING = 133 # this token type is not used in c tokenizer but exists in `tokenize.py`
56
+ N_TOKENS = 134
57
+ COMMENT = (
58
+ 135 # this token type is not used in c tokenizer <3.12, but exists in `tokenize.py`
59
+ )
60
+ NL = 136 # this token type is not used in c tokenizer <3.12, but exists in `tokenize.py`
61
+
62
+ # these token types are absent in earlier python versions
63
+ FSTRING_START = 137
64
+ FSTRING_MIDDLE = 138
65
+ FSTRING_END = 139
66
+ TSTRING_START = 140
67
+ TSTRING_MIDDLE = 141
68
+ TSTRING_END = 142
69
+
70
+ # these token types are not builtin ones, but created for compatible use
71
+ FSTRING_STRING = 143 # compatible with fstring on cpython <3.12
72
+ TSTRING_STRING = 144 # use tstring cpython <3.14
73
+
74
+ # protocol properties
75
+ @property
76
+ def namespace(self) -> None:
77
+ return None
78
+
79
+ def __repr__(self):
80
+ """consistent with namespaced token type"""
81
+ return self.name
82
+
83
+ # these boolean properties are defined in cpython source `Include/internal/pycore_token.h`
84
+ def is_terminal(self) -> bool:
85
+ """(x) < NT_OFFSET"""
86
+ return self != StdTokType.NT_OFFSET
87
+
88
+ def is_eof(self) -> bool:
89
+ """(x) == ENDMARKER"""
90
+ return self == StdTokType.ENDMARKER
91
+
92
+ def is_whitespace(self) -> bool:
93
+ """(x) == ENDMARKER ||
94
+ (x) == NEWLINE ||
95
+ (x) == INDENT ||
96
+ (x) == DEDENT
97
+ """
98
+ return self in (
99
+ StdTokType.ENDMARKER,
100
+ StdTokType.NEWLINE,
101
+ StdTokType.INDENT,
102
+ StdTokType.DEDENT,
103
+ )
104
+
105
+ def is_string_lit(self) -> bool:
106
+ """(x) == STRING ||
107
+ (x) == FSTRING_MIDDLE ||
108
+ (x) == TSTRING_MIDDLE)
109
+ """
110
+ return self in (
111
+ StdTokType.STRING,
112
+ StdTokType.FSTRING_MIDDLE,
113
+ StdTokType.TSTRING_MIDDLE,
114
+ StdTokType.FSTRING_STRING,
115
+ StdTokType.TSTRING_STRING,
116
+ )
117
+
118
+ # these boolean properties are for untokenizing
119
+ def is_curly_bracket_escaped(self) -> bool:
120
+ """Whether curly bracket should be escaped.
121
+
122
+ REMINDER: returned value of this method for compatible token type
123
+ `FSTRING_STRING` & `TSTRING_STRING` SHOULD BE `False`, otherwise
124
+ the result of untokenzie method will raise error.
125
+ """
126
+ return self in (
127
+ StdTokType.FSTRING_MIDDLE,
128
+ StdTokType.TSTRING_MIDDLE,
129
+ )
130
+
131
+
132
+ @dataclass(frozen=True, slots=True, repr=False)
133
+ class NamespacedTokType:
134
+ """New token types that defined in `phy` plugins.
135
+
136
+ Builtin token use integer as token value; however single integer may cause conflicts among
137
+ `phy` plugins, so a combine of namespace & scope-unique value is used instead; although this value can
138
+ be integer like builtin token does, but a string value is more convenient when matching grammar
139
+ defined rules (in grammar definition file, token type is referred with name, not integer value).
140
+ """
141
+
142
+ # instance attributes
143
+ namespace: str
144
+ name: str # should be consist with token variable identifier when defined
145
+
146
+ literal_str: Optional[str] = None # exact token string of Keyword, Soft keyword & OP
147
+
148
+ # these not-required attributes mainly used for boolean properties like `is_terminal()`
149
+ _is_terminal: bool = True
150
+ _is_eof: bool = False
151
+ _is_whitespace: bool = False
152
+ _is_string_lit: bool = False
153
+ _is_curly_bracket_escaped: bool = False
154
+
155
+ def __repr__(self):
156
+ """use double underscore to separate namespace & name"""
157
+ return f'{self.namespace}__{self.name}'
158
+
159
+ def __eq__(self, other: Union['NamespacedTokType', Tuple[str, str]]): # type: ignore[override]
160
+ """overload `==` operator; plain tuple of namespace & name are supported"""
161
+ if isinstance(other, NamespacedTokType):
162
+ return self.namespace == other.namespace and self.name == other.name
163
+ elif isinstance(other, tuple) and len(other) == 2:
164
+ return self.namespace == other[0] and self.name == other[1]
165
+ else:
166
+ # DO NOT return False; return `NotImplemented` can make `==` operator commutative
167
+ return NotImplemented
168
+
169
+ def __hash__(self):
170
+ return hash((self.namespace, self.name))
171
+
172
+ # same boolean properties like standard token types; can be overrode in subclass
173
+ def is_terminal(self) -> bool:
174
+ return self._is_terminal
175
+
176
+ def is_eof(self) -> bool:
177
+ return self._is_eof
178
+
179
+ def is_whitespace(self) -> bool:
180
+ return self._is_whitespace
181
+
182
+ def is_string_lit(self) -> bool:
183
+ return self._is_string_lit
184
+
185
+ # these boolean properties are for untokenizing
186
+ def is_curly_bracket_escaped(self) -> bool:
187
+ """whether curly bracket should be escaped"""
188
+ return self._is_curly_bracket_escaped
189
+
190
+
191
+ @dataclass(frozen=True, slots=True)
192
+ class TokInfo:
193
+ """Counterpart of `phy` to builtin `tokenize.TokenInfo` type.
194
+
195
+ This struct is intended to be fully compatible with builtin ones. Extended attributes are
196
+ named differently.
197
+ """
198
+
199
+ # `None` if self is not builtin type; this attribute is only for compatible with builtin one, and it
200
+ # is not used within `phy` project. Always use `std_type` and `ns_type` instead.
201
+ type: Optional[int]
202
+
203
+ string: str
204
+ start: Tuple[int, int] # (lineno, offset)
205
+ end: Tuple[int, int]
206
+
207
+ # Original code of this token.
208
+ # REMINDER: STRING, FSTRING_MIDDLE & TSTRING_MIDDLE may cross lines, then the line attribute of such
209
+ # token will contains all this lines.
210
+ line: str
211
+
212
+ # standard token type or namespaced token type; the two attributes are mutually exclusive.
213
+ std_type: Optional[StdTokType] = None
214
+ ns_type: Optional[NamespacedTokType] = None
215
+
216
+ @property
217
+ def union_type(self) -> TokType:
218
+ """use this property when common method is called"""
219
+ return self.std_type if self.std_type is not None else self.ns_type
220
+
221
+ def is_type(self, tok_type: TokType) -> bool:
222
+ """whether this token is of given type"""
223
+ return self.std_type == tok_type or self.ns_type == tok_type
224
+
225
+ def __matmul__(self, tok_type: TokType) -> bool:
226
+ """overload operator "@" to provide a shorthand for `is_type()`"""
227
+ return self.std_type == tok_type or self.ns_type == tok_type
228
+
229
+ @classmethod
230
+ def new_op(
231
+ cls,
232
+ op_literal: str,
233
+ start: Tuple[int, int],
234
+ end: Tuple[int, int],
235
+ line: str,
236
+ ) -> 'TokInfo':
237
+ """This is a convenient constructor to create new operator token. Create new operator other
238
+ than std operators is a frequent scenario in new syntax.
239
+ """
240
+ return TokInfo(
241
+ type=builtin_token.OP,
242
+ string=op_literal,
243
+ start=start,
244
+ end=end,
245
+ line=line,
246
+ ns_type=StdTokType.OP,
247
+ )
248
+
249
+ @classmethod
250
+ def new_std(
251
+ cls,
252
+ ns_type: StdTokType,
253
+ string: str,
254
+ start: Tuple[int, int],
255
+ end: Tuple[int, int],
256
+ line: str,
257
+ ) -> 'TokInfo':
258
+ """This is a convenient constructor to create new std token without manually pass corresponding
259
+ builtin token int value.
260
+ """
261
+ return TokInfo(
262
+ type=getattr(builtin_token, ns_type.name, None),
263
+ string=string,
264
+ start=start,
265
+ end=end,
266
+ line=line,
267
+ ns_type=ns_type,
268
+ )
269
+
270
+
271
+ # generator that yields `phy` tokeninfo
272
+ TokGen = Generator[TokInfo, None, None]
@@ -0,0 +1,144 @@
1
+ """ token type int value mapping table; the same as python 3.15 """
2
+ __all__ = ['tok_name', 'ISTERMINAL', 'ISNONTERMINAL', 'ISEOF',
3
+ 'EXACT_TOKEN_TYPES']
4
+
5
+ ENDMARKER = 0
6
+ NAME = 1
7
+ NUMBER = 2
8
+ STRING = 3
9
+ NEWLINE = 4
10
+ INDENT = 5
11
+ DEDENT = 6
12
+ LPAR = 7
13
+ RPAR = 8
14
+ LSQB = 9
15
+ RSQB = 10
16
+ COLON = 11
17
+ COMMA = 12
18
+ SEMI = 13
19
+ PLUS = 14
20
+ MINUS = 15
21
+ STAR = 16
22
+ SLASH = 17
23
+ VBAR = 18
24
+ AMPER = 19
25
+ LESS = 20
26
+ GREATER = 21
27
+ EQUAL = 22
28
+ DOT = 23
29
+ PERCENT = 24
30
+ LBRACE = 25
31
+ RBRACE = 26
32
+ EQEQUAL = 27
33
+ NOTEQUAL = 28
34
+ LESSEQUAL = 29
35
+ GREATEREQUAL = 30
36
+ TILDE = 31
37
+ CIRCUMFLEX = 32
38
+ LEFTSHIFT = 33
39
+ RIGHTSHIFT = 34
40
+ DOUBLESTAR = 35
41
+ PLUSEQUAL = 36
42
+ MINEQUAL = 37
43
+ STAREQUAL = 38
44
+ SLASHEQUAL = 39
45
+ PERCENTEQUAL = 40
46
+ AMPEREQUAL = 41
47
+ VBAREQUAL = 42
48
+ CIRCUMFLEXEQUAL = 43
49
+ LEFTSHIFTEQUAL = 44
50
+ RIGHTSHIFTEQUAL = 45
51
+ DOUBLESTAREQUAL = 46
52
+ DOUBLESLASH = 47
53
+ DOUBLESLASHEQUAL = 48
54
+ AT = 49
55
+ ATEQUAL = 50
56
+ RARROW = 51
57
+ ELLIPSIS = 52
58
+ COLONEQUAL = 53
59
+ EXCLAMATION = 54
60
+ OP = 55
61
+ TYPE_IGNORE = 56
62
+ TYPE_COMMENT = 57
63
+ SOFT_KEYWORD = 58
64
+ FSTRING_START = 59
65
+ FSTRING_MIDDLE = 60
66
+ FSTRING_END = 61
67
+ TSTRING_START = 62
68
+ TSTRING_MIDDLE = 63
69
+ TSTRING_END = 64
70
+ COMMENT = 65
71
+ NL = 66
72
+ # These aren't used by the C tokenizer but are needed for tokenize.py
73
+ ERRORTOKEN = 67
74
+ ENCODING = 68
75
+ N_TOKENS = 69
76
+ # Special definitions for cooperation with parser
77
+ NT_OFFSET = 256
78
+
79
+
80
+ tok_name = {value: name
81
+ for name, value in globals().items()
82
+ if isinstance(value, int) and not name.startswith('_')}
83
+ __all__.extend(tok_name.values())
84
+
85
+ EXACT_TOKEN_TYPES = {
86
+ '!': EXCLAMATION,
87
+ '!=': NOTEQUAL,
88
+ '%': PERCENT,
89
+ '%=': PERCENTEQUAL,
90
+ '&': AMPER,
91
+ '&=': AMPEREQUAL,
92
+ '(': LPAR,
93
+ ')': RPAR,
94
+ '*': STAR,
95
+ '**': DOUBLESTAR,
96
+ '**=': DOUBLESTAREQUAL,
97
+ '*=': STAREQUAL,
98
+ '+': PLUS,
99
+ '+=': PLUSEQUAL,
100
+ ',': COMMA,
101
+ '-': MINUS,
102
+ '-=': MINEQUAL,
103
+ '->': RARROW,
104
+ '.': DOT,
105
+ '...': ELLIPSIS,
106
+ '/': SLASH,
107
+ '//': DOUBLESLASH,
108
+ '//=': DOUBLESLASHEQUAL,
109
+ '/=': SLASHEQUAL,
110
+ ':': COLON,
111
+ ':=': COLONEQUAL,
112
+ ';': SEMI,
113
+ '<': LESS,
114
+ '<<': LEFTSHIFT,
115
+ '<<=': LEFTSHIFTEQUAL,
116
+ '<=': LESSEQUAL,
117
+ '=': EQUAL,
118
+ '==': EQEQUAL,
119
+ '>': GREATER,
120
+ '>=': GREATEREQUAL,
121
+ '>>': RIGHTSHIFT,
122
+ '>>=': RIGHTSHIFTEQUAL,
123
+ '@': AT,
124
+ '@=': ATEQUAL,
125
+ '[': LSQB,
126
+ ']': RSQB,
127
+ '^': CIRCUMFLEX,
128
+ '^=': CIRCUMFLEXEQUAL,
129
+ '{': LBRACE,
130
+ '|': VBAR,
131
+ '|=': VBAREQUAL,
132
+ '}': RBRACE,
133
+ '~': TILDE,
134
+ }
135
+
136
+ # pylint: disable=missing-function-docstring,invalid-name
137
+ def ISTERMINAL(x):
138
+ return x < NT_OFFSET
139
+
140
+ def ISNONTERMINAL(x):
141
+ return x >= NT_OFFSET
142
+
143
+ def ISEOF(x):
144
+ return x == ENDMARKER
Binary file
@@ -0,0 +1,21 @@
1
+ """ Interfaces of c module. """
2
+ # imports
3
+ from typing import Callable, Iterator, Tuple, Optional
4
+
5
+ # typings
6
+ _Pos = Tuple[int, int]
7
+ _BareTokenInfo = Tuple[int, str, _Pos, Optional[_Pos]]
8
+
9
+
10
+ class TokenizerIter(Iterator[_BareTokenInfo]):
11
+ """ interface of c method which creates iterator of tokens """
12
+
13
+ # pylint: disable=unused-argument
14
+ def __init__(
15
+ self,
16
+ readline: Callable[[], bytes],
17
+ encoding: str = None,
18
+ extra_tokens: bool = False
19
+ ): ...
20
+ def __iter__(self) -> 'TokenizerIter': ...
21
+ def __next__(self) -> _BareTokenInfo: ...
@@ -0,0 +1,94 @@
1
+ """ These methods are strictly compatible with builtin `tokenize` module. """
2
+
3
+ # imports
4
+ from tokenize import detect_encoding, TokenError
5
+ import itertools
6
+
7
+ # local imports; pylint: disable=import-error,no-name-in-module
8
+ from phy_std_base_tokenzier._tokenize import TokenizerIter
9
+ from phy_std_base_tokenzier._token_type import tok_name
10
+ from phy_std_base_tokenzier._phy_compat import TokInfo, TokGen, StdTokType
11
+
12
+
13
+ def tokenize(readline) -> TokGen:
14
+ """
15
+ The tokenize() generator requires one argument, readline, which
16
+ must be a callable object which provides the same interface as the
17
+ readline() method of built-in file objects. Each call to the function
18
+ should return one line of input as bytes. Alternatively, readline
19
+ can be a callable function terminating with StopIteration:
20
+ readline = open(myfile, 'rb').__next__ # Example of alternate readline
21
+
22
+ The generator produces 5-tuples with these members: the token type; the
23
+ token string; a 2-tuple (srow, scol) of ints specifying the row and
24
+ column where the token begins in the source; a 2-tuple (erow, ecol) of
25
+ ints specifying the row and column where the token ends in the source;
26
+ and the line on which the token was found. The line passed is the
27
+ physical line.
28
+
29
+ The first token sequence will always be an ENCODING token
30
+ which tells you which encoding was used to decode the bytes stream.
31
+ """
32
+ encoding, consumed = detect_encoding(readline)
33
+ rl_gen = itertools.chain(consumed, iter(readline, b""))
34
+ if encoding is not None:
35
+ if encoding == "utf-8-sig":
36
+ # BOM will already have been stripped.
37
+ encoding = "utf-8"
38
+
39
+ yield TokInfo.new_std(
40
+ ns_type=StdTokType.ENCODING,
41
+ string=encoding,
42
+ start=(0, 0),
43
+ end=(0, 0),
44
+ line=''
45
+ )
46
+
47
+ yield from _generate_tokens_from_c_tokenizer(rl_gen.__next__, encoding, extra_tokens=True)
48
+
49
+
50
+ def generate_tokens(readline) -> TokGen:
51
+ """Tokenize a source reading Python code as unicode strings.
52
+
53
+ This has the same API as tokenize(), except that it expects the *readline*
54
+ callable to return str objects instead of bytes.
55
+ """
56
+ return _generate_tokens_from_c_tokenizer(readline, extra_tokens=True)
57
+
58
+
59
+ def _transform_msg(msg):
60
+ """Transform error messages from the C tokenizer into the Python tokenize
61
+
62
+ The C tokenizer is more picky than the Python one, so we need to massage
63
+ the error messages a bit for backwards compatibility.
64
+ """
65
+ if "unterminated triple-quoted string literal" in msg:
66
+ return "EOF in multi-line string"
67
+ return msg
68
+
69
+
70
+ def _generate_tokens_from_c_tokenizer(source, encoding=None, extra_tokens=False) -> TokGen:
71
+ """Tokenize a source reading Python code as unicode strings using the internal C tokenizer"""
72
+ if encoding is None:
73
+ it = TokenizerIter(source, extra_tokens=extra_tokens)
74
+ else:
75
+ it = TokenizerIter(source, encoding=encoding, extra_tokens=extra_tokens)
76
+ try:
77
+ for info in it:
78
+ _token_type, _token_string, _start, _end, _line = tuple(info)
79
+ _token_type_name = tok_name[_token_type]
80
+
81
+ yield TokInfo.new_std(
82
+ ns_type=StdTokType[_token_type_name],
83
+ string=_token_string,
84
+ start=_start,
85
+ end=_end,
86
+ line=_line,
87
+ )
88
+
89
+ except SyntaxError as e:
90
+ if type(e) is not SyntaxError:
91
+ raise e from None
92
+ msg = _transform_msg(e.msg)
93
+ raise TokenError(msg, (e.lineno, e.offset)) from None
94
+