OILS / frontend / match.py View on Github | oilshell.org

310 lines, 166 significant
1"""
2match.py - lexer primitives, implemented with re2c or Python regexes.
3"""
4
5from _devbuild.gen.id_kind_asdl import Id, Id_t
6from _devbuild.gen.types_asdl import lex_mode_t
7from frontend import lexer_def
8
9from typing import Tuple, Callable, Dict, List, Any, TYPE_CHECKING
10
11# bin/osh should work without compiling fastlex? But we want all the unit
12# tests to run with a known version of it.
13try:
14 import fastlex
15except ImportError:
16 fastlex = None
17
18if fastlex:
19 re = None # re module isn't in CPython slice
20else:
21 import re # type: ignore
22
23if TYPE_CHECKING:
24 SRE_Pattern = Any # Do we need a .pyi file for re or _sre?
25 SimpleMatchFunc = Callable[[str, int], Tuple[Id_t, int]]
26 LexerPairs = List[Tuple[SRE_Pattern, Id_t]]
27
28
29def _LongestMatch(re_list, line, start_pos):
30 # type: (LexerPairs, str, int) -> Tuple[Id_t, int]
31
32 # Simulate the rule for \x00, which we generate in frontend/match.re2c.h
33 if start_pos >= len(line):
34 return Id.Eol_Tok, start_pos
35 # Simulate C-style string handling: \x00 is empty string.
36 if line[start_pos] == '\0':
37 return Id.Eol_Tok, start_pos
38
39 matches = []
40 for regex, tok_type in re_list:
41 m = regex.match(line, start_pos) # left-anchored
42 if m:
43 matches.append((m.end(0), tok_type, m.group(0)))
44 if not matches:
45 raise AssertionError('no match at position %d: %r' % (start_pos, line))
46 end_pos, tok_type, tok_val = max(matches, key=lambda m: m[0])
47 #util.log('%s %s', tok_type, end_pos)
48 return tok_type, end_pos
49
50
51def _CompileAll(pat_list):
52 # type: (List[Tuple[bool, str, Id_t]]) -> LexerPairs
53 result = []
54 for is_regex, pat, token_id in pat_list:
55 if not is_regex:
56 pat = re.escape(pat) # type: ignore # turn $ into \$
57 result.append((re.compile(pat), token_id)) # type: ignore
58 return result
59
60
61class _MatchOshToken_Slow(object):
62 """An abstract matcher that doesn't depend on OSH."""
63
64 def __init__(self, lexer_def):
65 # type: (Dict[lex_mode_t, List[Tuple[bool, str, Id_t]]]) -> None
66 self.lexer_def = {} # type: Dict[lex_mode_t, LexerPairs]
67 for lex_mode, pat_list in lexer_def.items():
68 self.lexer_def[lex_mode] = _CompileAll(pat_list)
69
70 def __call__(self, lex_mode, line, start_pos):
71 # type: (lex_mode_t, str, int) -> Tuple[Id_t, int]
72 """Returns (id, end_pos)."""
73 re_list = self.lexer_def[lex_mode]
74
75 return _LongestMatch(re_list, line, start_pos)
76
77
78def _MatchOshToken_Fast(lex_mode, line, start_pos):
79 # type: (lex_mode_t, str, int) -> Tuple[Id_t, int]
80 """Returns (Id, end_pos)."""
81 tok_type, end_pos = fastlex.MatchOshToken(lex_mode, line, start_pos)
82 # IMPORTANT: We're reusing Id instances here. Ids are very common, so this
83 # saves memory.
84 return tok_type, end_pos
85
86
87class _MatchTokenSlow(object):
88
89 def __init__(self, pat_list):
90 # type: (List[Tuple[bool, str, Id_t]]) -> None
91 self.pat_list = _CompileAll(pat_list)
92
93 def __call__(self, line, start_pos):
94 # type: (str, int) -> Tuple[Id_t, int]
95 return _LongestMatch(self.pat_list, line, start_pos)
96
97
98def _MatchEchoToken_Fast(line, start_pos):
99 # type: (str, int) -> Tuple[Id_t, int]
100 tok_type, end_pos = fastlex.MatchEchoToken(line, start_pos)
101 return tok_type, end_pos
102
103
104def _MatchGlobToken_Fast(line, start_pos):
105 # type: (str, int) -> Tuple[Id_t, int]
106 tok_type, end_pos = fastlex.MatchGlobToken(line, start_pos)
107 return tok_type, end_pos
108
109
110def _MatchPS1Token_Fast(line, start_pos):
111 # type: (str, int) -> Tuple[Id_t, int]
112 tok_type, end_pos = fastlex.MatchPS1Token(line, start_pos)
113 return tok_type, end_pos
114
115
116def _MatchHistoryToken_Fast(line, start_pos):
117 # type: (str, int) -> Tuple[Id_t, int]
118 tok_type, end_pos = fastlex.MatchHistoryToken(line, start_pos)
119 return tok_type, end_pos
120
121
122def _MatchBraceRangeToken_Fast(line, start_pos):
123 # type: (str, int) -> Tuple[Id_t, int]
124 tok_type, end_pos = fastlex.MatchBraceRangeToken(line, start_pos)
125 return tok_type, end_pos
126
127
128def _MatchJ8Token_Fast(line, start_pos):
129 # type: (str, int) -> Tuple[Id_t, int]
130 tok_type, end_pos = fastlex.MatchJ8Token(line, start_pos)
131 return tok_type, end_pos
132
133
134def _MatchJ8LinesToken_Fast(line, start_pos):
135 # type: (str, int) -> Tuple[Id_t, int]
136 tok_type, end_pos = fastlex.MatchJ8LinesToken(line, start_pos)
137 return tok_type, end_pos
138
139
140def _MatchJ8StrToken_Fast(line, start_pos):
141 # type: (str, int) -> Tuple[Id_t, int]
142 tok_type, end_pos = fastlex.MatchJ8StrToken(line, start_pos)
143 return tok_type, end_pos
144
145
146def _MatchJsonStrToken_Fast(line, start_pos):
147 # type: (str, int) -> Tuple[Id_t, int]
148 tok_type, end_pos = fastlex.MatchJsonStrToken(line, start_pos)
149 return tok_type, end_pos
150
151
152def _MatchShNumberToken_Fast(line, start_pos):
153 # type: (str, int) -> Tuple[Id_t, int]
154 tok_type, end_pos = fastlex.MatchShNumberToken(line, start_pos)
155 return tok_type, end_pos
156
157
158if fastlex:
159 OneToken = _MatchOshToken_Fast
160 ECHO_MATCHER = _MatchEchoToken_Fast
161 GLOB_MATCHER = _MatchGlobToken_Fast
162 PS1_MATCHER = _MatchPS1Token_Fast
163 HISTORY_MATCHER = _MatchHistoryToken_Fast
164 BRACE_RANGE_MATCHER = _MatchBraceRangeToken_Fast
165
166 MatchJ8Token = _MatchJ8Token_Fast
167 MatchJ8LinesToken = _MatchJ8LinesToken_Fast
168 MatchJ8StrToken = _MatchJ8StrToken_Fast
169 MatchJsonStrToken = _MatchJsonStrToken_Fast
170 MatchShNumberToken = _MatchShNumberToken_Fast
171
172 IsValidVarName = fastlex.IsValidVarName
173 ShouldHijack = fastlex.ShouldHijack
174 LooksLikeInteger = fastlex.LooksLikeInteger
175 LooksLikeYshInt = fastlex.LooksLikeYshInt
176 LooksLikeYshFloat = fastlex.LooksLikeYshFloat
177else:
178 OneToken = _MatchOshToken_Slow(lexer_def.LEXER_DEF)
179 ECHO_MATCHER = _MatchTokenSlow(lexer_def.ECHO_E_DEF)
180 GLOB_MATCHER = _MatchTokenSlow(lexer_def.GLOB_DEF)
181 PS1_MATCHER = _MatchTokenSlow(lexer_def.PS1_DEF)
182 HISTORY_MATCHER = _MatchTokenSlow(lexer_def.HISTORY_DEF)
183 BRACE_RANGE_MATCHER = _MatchTokenSlow(lexer_def.BRACE_RANGE_DEF)
184
185 MatchJ8Token = _MatchTokenSlow(lexer_def.J8_DEF)
186 MatchJ8LinesToken = _MatchTokenSlow(lexer_def.J8_LINES_DEF)
187 MatchJ8StrToken = _MatchTokenSlow(lexer_def.J8_STR_DEF)
188 MatchJsonStrToken = _MatchTokenSlow(lexer_def.JSON_STR_DEF)
189 MatchShNumberToken = _MatchTokenSlow(lexer_def.SH_NUMBER_DEF)
190
191 # Used by osh/cmd_parse.py to validate for loop name. Note it must be
192 # anchored on the right.
193 _VAR_NAME_RE = re.compile(lexer_def.VAR_NAME_RE + '$') # type: ignore
194
195 def IsValidVarName(s):
196 # type: (str) -> bool
197 return bool(_VAR_NAME_RE.match(s))
198
199 # yapf: disable
200 _SHOULD_HIJACK_RE = re.compile(lexer_def.SHOULD_HIJACK_RE + '$') # type: ignore
201
202 def ShouldHijack(s):
203 # type: (str) -> bool
204 return bool(_SHOULD_HIJACK_RE.match(s))
205
206 #
207 # Integer/float
208 #
209
210 _LOOKS_LIKE_INTEGER_RE = re.compile(lexer_def.LOOKS_LIKE_INTEGER + '$') # type: ignore
211
212 def LooksLikeInteger(s):
213 # type: (str) -> bool
214 return bool(_LOOKS_LIKE_INTEGER_RE.match(s))
215
216 _LOOKS_LIKE_YSH_INT_RE = re.compile(lexer_def.LOOKS_LIKE_YSH_INT + '$') # type: ignore
217
218 def LooksLikeYshInt(s):
219 # type: (str) -> bool
220 return bool(_LOOKS_LIKE_YSH_INT_RE.match(s))
221
222 _LOOKS_LIKE_YSH_FLOAT_RE = re.compile(lexer_def.LOOKS_LIKE_YSH_FLOAT + '$') # type: ignore
223
224 def LooksLikeYshFloat(s):
225 # type: (str) -> bool
226 return bool(_LOOKS_LIKE_YSH_FLOAT_RE.match(s))
227 # yapf: enable
228
229
230class SimpleLexer(object):
231
232 def __init__(self, match_func, s):
233 # type: (SimpleMatchFunc, str) -> None
234 self.match_func = match_func
235 self.s = s
236 self.pos = 0
237
238 def Next(self):
239 # type: () -> Tuple[Id_t, str]
240 """
241 Note: match_func will return Id.Eol_Tok repeatedly the terminating NUL
242 """
243 tok_id, end_pos = self.match_func(self.s, self.pos)
244 val = self.s[self.pos:end_pos]
245 self.pos = end_pos
246 return tok_id, val
247
248 def Tokens(self):
249 # type: () -> List[Tuple[Id_t, str]]
250 tokens = [] # type: List[Tuple[Id_t, str]]
251 while True:
252 tok_id, val = self.Next()
253 if tok_id == Id.Eol_Tok: # NUL terminator
254 break
255 tokens.append((tok_id, val))
256 return tokens
257
258
259# Iterated over in builtin/io_osh.py
260def EchoLexer(s):
261 # type: (str) -> SimpleLexer
262 return SimpleLexer(ECHO_MATCHER, s)
263
264
265def BraceRangeLexer(s):
266 # type: (str) -> SimpleLexer
267 return SimpleLexer(BRACE_RANGE_MATCHER, s)
268
269
270def GlobLexer(s):
271 # type: (str) -> SimpleLexer
272 return SimpleLexer(GLOB_MATCHER, s)
273
274
275# These tokens are "slurped"
276
277
278def HistoryTokens(s):
279 # type: (str) -> List[Tuple[Id_t, str]]
280 lex = SimpleLexer(HISTORY_MATCHER, s)
281 return lex.Tokens()
282
283
284def Ps1Tokens(s):
285 # type: (str) -> List[Tuple[Id_t, str]]
286 lex = SimpleLexer(PS1_MATCHER, s)
287 return lex.Tokens()
288
289
290#
291# builtin/bracket_osh.py
292#
293
294
295def BracketUnary(s):
296 # type: (str) -> Id_t
297 from _devbuild.gen.id_kind import TEST_UNARY_LOOKUP # break circular dep
298 return TEST_UNARY_LOOKUP.get(s, Id.Undefined_Tok)
299
300
301def BracketBinary(s):
302 # type: (str) -> Id_t
303 from _devbuild.gen.id_kind import TEST_BINARY_LOOKUP
304 return TEST_BINARY_LOOKUP.get(s, Id.Undefined_Tok)
305
306
307def BracketOther(s):
308 # type: (str) -> Id_t
309 from _devbuild.gen.id_kind import TEST_OTHER_LOOKUP
310 return TEST_OTHER_LOOKUP.get(s, Id.Undefined_Tok)