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

284 lines, 152 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 _MatchJ8StrToken_Fast(line, start_pos):
135 # type: (str, int) -> Tuple[Id_t, int]
136 tok_type, end_pos = fastlex.MatchJ8StrToken(line, start_pos)
137 return tok_type, end_pos
138
139
140def _MatchJsonStrToken_Fast(line, start_pos):
141 # type: (str, int) -> Tuple[Id_t, int]
142 tok_type, end_pos = fastlex.MatchJsonStrToken(line, start_pos)
143 return tok_type, end_pos
144
145
146if fastlex:
147 OneToken = _MatchOshToken_Fast
148 ECHO_MATCHER = _MatchEchoToken_Fast
149 GLOB_MATCHER = _MatchGlobToken_Fast
150 PS1_MATCHER = _MatchPS1Token_Fast
151 HISTORY_MATCHER = _MatchHistoryToken_Fast
152 BRACE_RANGE_MATCHER = _MatchBraceRangeToken_Fast
153
154 MatchJ8Token = _MatchJ8Token_Fast
155 MatchJ8StrToken = _MatchJ8StrToken_Fast
156 MatchJsonStrToken = _MatchJsonStrToken_Fast
157
158 IsValidVarName = fastlex.IsValidVarName
159 ShouldHijack = fastlex.ShouldHijack
160 LooksLikeInteger = fastlex.LooksLikeInteger
161 LooksLikeFloat = fastlex.LooksLikeFloat
162else:
163 OneToken = _MatchOshToken_Slow(lexer_def.LEXER_DEF)
164 ECHO_MATCHER = _MatchTokenSlow(lexer_def.ECHO_E_DEF)
165 GLOB_MATCHER = _MatchTokenSlow(lexer_def.GLOB_DEF)
166 PS1_MATCHER = _MatchTokenSlow(lexer_def.PS1_DEF)
167 HISTORY_MATCHER = _MatchTokenSlow(lexer_def.HISTORY_DEF)
168 BRACE_RANGE_MATCHER = _MatchTokenSlow(lexer_def.BRACE_RANGE_DEF)
169
170 MatchJ8Token = _MatchTokenSlow(lexer_def.J8_DEF)
171 MatchJ8StrToken = _MatchTokenSlow(lexer_def.J8_STR_DEF)
172 MatchJsonStrToken = _MatchTokenSlow(lexer_def.JSON_STR_DEF)
173
174 # Used by osh/cmd_parse.py to validate for loop name. Note it must be
175 # anchored on the right.
176 _VAR_NAME_RE = re.compile(lexer_def.VAR_NAME_RE + '$') # type: ignore
177
178 def IsValidVarName(s):
179 # type: (str) -> bool
180 return bool(_VAR_NAME_RE.match(s))
181
182 # yapf: disable
183 _SHOULD_HIJACK_RE = re.compile(lexer_def.SHOULD_HIJACK_RE + '$') # type: ignore
184
185 def ShouldHijack(s):
186 # type: (str) -> bool
187 return bool(_SHOULD_HIJACK_RE.match(s))
188
189 _LOOKS_LIKE_INTEGER_RE = re.compile(lexer_def.LOOKS_LIKE_INTEGER + '$') # type: ignore
190
191 def LooksLikeInteger(s):
192 # type: (str) -> bool
193 return bool(_LOOKS_LIKE_INTEGER_RE.match(s))
194
195 _LOOKS_LIKE_FLOAT_RE = re.compile(lexer_def.LOOKS_LIKE_FLOAT + '$') # type: ignore
196 # yapf: enable
197
198
199 def LooksLikeFloat(s):
200 # type: (str) -> bool
201 return bool(_LOOKS_LIKE_FLOAT_RE.match(s))
202
203
204class SimpleLexer(object):
205
206 def __init__(self, match_func, s):
207 # type: (SimpleMatchFunc, str) -> None
208 self.match_func = match_func
209 self.s = s
210 self.pos = 0
211
212 def Next(self):
213 # type: () -> Tuple[Id_t, str]
214 """
215 Note: match_func will return Id.Eol_Tok repeatedly the terminating NUL
216 """
217 tok_id, end_pos = self.match_func(self.s, self.pos)
218 val = self.s[self.pos:end_pos]
219 self.pos = end_pos
220 return tok_id, val
221
222 def Tokens(self):
223 # type: () -> List[Tuple[Id_t, str]]
224 tokens = [] # type: List[Tuple[Id_t, str]]
225 while True:
226 tok_id, val = self.Next()
227 if tok_id == Id.Eol_Tok: # NUL terminator
228 break
229 tokens.append((tok_id, val))
230 return tokens
231
232
233# Iterated over in builtin/io_osh.py
234def EchoLexer(s):
235 # type: (str) -> SimpleLexer
236 return SimpleLexer(ECHO_MATCHER, s)
237
238
239def BraceRangeLexer(s):
240 # type: (str) -> SimpleLexer
241 return SimpleLexer(BRACE_RANGE_MATCHER, s)
242
243
244def GlobLexer(s):
245 # type: (str) -> SimpleLexer
246 return SimpleLexer(GLOB_MATCHER, s)
247
248
249# These tokens are "slurped"
250
251
252def HistoryTokens(s):
253 # type: (str) -> List[Tuple[Id_t, str]]
254 lex = SimpleLexer(HISTORY_MATCHER, s)
255 return lex.Tokens()
256
257
258def Ps1Tokens(s):
259 # type: (str) -> List[Tuple[Id_t, str]]
260 lex = SimpleLexer(PS1_MATCHER, s)
261 return lex.Tokens()
262
263
264#
265# builtin/bracket_osh.py
266#
267
268
269def BracketUnary(s):
270 # type: (str) -> Id_t
271 from _devbuild.gen.id_kind import TEST_UNARY_LOOKUP # break circular dep
272 return TEST_UNARY_LOOKUP.get(s, Id.Undefined_Tok)
273
274
275def BracketBinary(s):
276 # type: (str) -> Id_t
277 from _devbuild.gen.id_kind import TEST_BINARY_LOOKUP
278 return TEST_BINARY_LOOKUP.get(s, Id.Undefined_Tok)
279
280
281def BracketOther(s):
282 # type: (str) -> Id_t
283 from _devbuild.gen.id_kind import TEST_OTHER_LOOKUP
284 return TEST_OTHER_LOOKUP.get(s, Id.Undefined_Tok)