OILS / osh / tdop.py View on Github | oilshell.org

342 lines, 144 significant
1"""
2tdop.py - Library for expression parsing.
3"""
4
5from _devbuild.gen.id_kind_asdl import Id, Id_t
6from _devbuild.gen.syntax_asdl import (loc, arith_expr, arith_expr_e,
7 arith_expr_t, word_e, word_t,
8 CompoundWord, Token)
9from core.error import p_die
10from display import ui
11from mycpp import mylib
12from mycpp.mylib import tagswitch
13from osh import word_
14
15from typing import (Callable, List, Dict, Tuple, Any, cast, TYPE_CHECKING)
16
17if TYPE_CHECKING: # break circular dep
18 from osh.word_parse import WordParser
19 from core import optview
20 LeftFunc = Callable[['TdopParser', word_t, arith_expr_t, int],
21 arith_expr_t]
22 NullFunc = Callable[['TdopParser', word_t, int], arith_expr_t]
23
24
25def IsIndexable(node):
26 # type: (arith_expr_t) -> bool
27 """In POSIX shell arith, a[1] is allowed but a[1][1] isn't.
28
29 We also allow $a[i] and foo$x[i] (formerly parse_dynamic_arith)
30 """
31 with tagswitch(node) as case:
32 if case(arith_expr_e.VarSub, arith_expr_e.Word):
33 return True
34 return False
35
36
37def CheckLhsExpr(node, blame_word):
38 # type: (arith_expr_t, word_t) -> None
39 """Determine if a node is a valid L-value by whitelisting tags.
40
41 Valid:
42 x = y
43 a[1] = y
44 Invalid:
45 a[0][0] = y
46 """
47 UP_node = node
48 if node.tag() == arith_expr_e.Binary:
49 node = cast(arith_expr.Binary, UP_node)
50 if node.op.id == Id.Arith_LBracket and IsIndexable(node.left):
51 return
52 # But a[0][0] = 1 is NOT valid.
53
54 if IsIndexable(node):
55 return
56
57 p_die("Left-hand side of this assignment is invalid", loc.Word(blame_word))
58
59
60#
61# Null Denotation
62#
63
64
65def NullError(p, t, bp):
66 # type: (TdopParser, word_t, int) -> arith_expr_t
67 # TODO: I need position information
68 p_die("Token can't be used in prefix position", loc.Word(t))
69 return None # never reached
70
71
72def NullConstant(p, w, bp):
73 # type: (TdopParser, word_t, int) -> arith_expr_t
74 name_tok = word_.LooksLikeArithVar(w)
75 if name_tok:
76 return name_tok
77
78 # Id.Word_Compound in the spec ensures this cast is valid
79 return cast(CompoundWord, w)
80
81
82def NullParen(p, t, bp):
83 # type: (TdopParser, word_t, int) -> arith_expr_t
84 """Arithmetic grouping."""
85 r = p.ParseUntil(bp)
86 p.Eat(Id.Arith_RParen)
87 return r
88
89
90def NullPrefixOp(p, w, bp):
91 # type: (TdopParser, word_t, int) -> arith_expr_t
92 """Prefix operator.
93
94 Low precedence: return, raise, etc.
95 return x+y is return (x+y), not (return x) + y
96
97 High precedence: logical negation, bitwise complement, etc.
98 !x && y is (!x) && y, not !(x && y)
99 """
100 right = p.ParseUntil(bp)
101 return arith_expr.Unary(word_.ArithId(w), right)
102
103
104#
105# Left Denotation
106#
107
108
109def LeftError(p, t, left, rbp):
110 # type: (TdopParser, word_t, arith_expr_t, int) -> arith_expr_t
111 # Hm is this not called because of binding power?
112 p_die("Token can't be used in infix position", loc.Word(t))
113 return None # never reached
114
115
116def LeftBinaryOp(p, w, left, rbp):
117 # type: (TdopParser, word_t, arith_expr_t, int) -> arith_expr_t
118 """Normal binary operator like 1+2 or 2*3, etc."""
119
120 assert w.tag() == word_e.Operator, w
121 tok = cast(Token, w)
122
123 return arith_expr.Binary(tok, left, p.ParseUntil(rbp))
124
125
126def LeftAssign(p, w, left, rbp):
127 # type: (TdopParser, word_t, arith_expr_t, int) -> arith_expr_t
128 """Normal binary operator like 1+2 or 2*3, etc."""
129 # x += 1, or a[i] += 1
130
131 CheckLhsExpr(left, w)
132 return arith_expr.BinaryAssign(word_.ArithId(w), left, p.ParseUntil(rbp))
133
134
135#
136# Parser definition
137# TODO: To be consistent, move this to osh/tdop_def.py.
138#
139
140if mylib.PYTHON:
141
142 def _ModuleAndFuncName(f):
143 # type: (Any) -> Tuple[str, str]
144 namespace = f.__module__.split('.')[-1]
145 return namespace, f.__name__
146
147 def _CppFuncName(f):
148 # type: (Any) -> str
149 return '%s::%s' % _ModuleAndFuncName(f)
150
151 class LeftInfo(object):
152 """Row for operator.
153
154 In C++ this should be a big array.
155 """
156
157 def __init__(self, led=None, lbp=0, rbp=0):
158 # type: (LeftFunc, int, int) -> None
159 self.led = led or LeftError
160 self.lbp = lbp
161 self.rbp = rbp
162
163 def __str__(self):
164 # type: () -> str
165 """Used by C++ code generation."""
166 return '{ %s, %d, %d },' % (_CppFuncName(
167 self.led), self.lbp, self.rbp)
168
169 def ModuleAndFuncName(self):
170 # type: () -> Tuple[str, str]
171 """Used by C++ code generation."""
172 return _ModuleAndFuncName(self.led)
173
174 class NullInfo(object):
175 """Row for operator.
176
177 In C++ this should be a big array.
178 """
179
180 def __init__(self, nud=None, bp=0):
181 # type: (NullFunc, int) -> None
182 self.nud = nud or LeftError
183 self.bp = bp
184
185 def __str__(self):
186 # type: () -> str
187 """Used by C++ code generation."""
188 return '{ %s, %d },' % (_CppFuncName(self.nud), self.bp)
189
190 def ModuleAndFuncName(self):
191 # type: () -> Tuple[str, str]
192 """Used by C++ code generation."""
193 return _ModuleAndFuncName(self.nud)
194
195 class ParserSpec(object):
196 """Specification for a TDOP parser.
197
198 This can be compiled to a table in C++.
199 """
200
201 def __init__(self):
202 # type: () -> None
203 self.nud_lookup = {} # type: Dict[Id_t, NullInfo]
204 self.led_lookup = {} # type: Dict[Id_t, LeftInfo]
205
206 def Null(self, bp, nud, tokens):
207 # type: (int, NullFunc, List[Id_t]) -> None
208 """Register a token that doesn't take anything on the left.
209
210 Examples: constant, prefix operator, error.
211 """
212 for token in tokens:
213 self.nud_lookup[token] = NullInfo(nud=nud, bp=bp)
214 if token not in self.led_lookup:
215 self.led_lookup[token] = LeftInfo() # error
216
217 def _RegisterLed(self, lbp, rbp, led, tokens):
218 # type: (int, int, LeftFunc, List[Id_t]) -> None
219 for token in tokens:
220 if token not in self.nud_lookup:
221 self.nud_lookup[token] = NullInfo(NullError)
222 self.led_lookup[token] = LeftInfo(lbp=lbp, rbp=rbp, led=led)
223
224 def Left(self, bp, led, tokens):
225 # type: (int, LeftFunc, List[Id_t]) -> None
226 """Register a token that takes an expression on the left."""
227 self._RegisterLed(bp, bp, led, tokens)
228
229 def LeftRightAssoc(self, bp, led, tokens):
230 # type: (int, LeftFunc, List[Id_t]) -> None
231 """Register a right associative operator."""
232 self._RegisterLed(bp, bp - 1, led, tokens)
233
234 def LookupNud(self, token):
235 # type: (Id_t) -> NullInfo
236
237 # As long as the table is complete, this shouldn't fail
238 return self.nud_lookup[token]
239
240 def LookupLed(self, token):
241 # type: (Id_t) -> LeftInfo
242 """Get a left_info for the token."""
243
244 # As long as the table is complete, this shouldn't fail
245 return self.led_lookup[token]
246
247
248class TdopParser(object):
249
250 def __init__(self, spec, w_parser, parse_opts):
251 # type: (ParserSpec, WordParser, optview.Parse) -> None
252 self.spec = spec
253 self.w_parser = w_parser
254 self.parse_opts = parse_opts
255
256 # NOTE: Next() overwrites this state, so we don't need a Reset() method in
257 # between reuses of this TdopParser instance.
258 self.cur_word = None # type: word_t # current token
259 self.op_id = Id.Undefined_Tok
260
261 def CurrentId(self):
262 # type: () -> Id_t
263 """Glue used by the WordParser to check for extra tokens."""
264 return word_.ArithId(self.cur_word)
265
266 def AtToken(self, token_type):
267 # type: (Id_t) -> bool
268 return self.op_id == token_type
269
270 def Eat(self, token_type):
271 # type: (Id_t) -> None
272 """Assert that we're at the current token and advance."""
273 if not self.AtToken(token_type):
274 p_die(
275 'Parser expected %s, got %s' %
276 (ui.PrettyId(token_type), ui.PrettyId(self.op_id)),
277 loc.Word(self.cur_word))
278 self.Next()
279
280 def Next(self):
281 # type: () -> bool
282 self.cur_word = self.w_parser.ReadArithWord()
283 self.op_id = word_.ArithId(self.cur_word)
284 return True
285
286 def ParseUntil(self, rbp):
287 # type: (int) -> arith_expr_t
288 """Parse to the right, eating tokens until we encounter a token with
289 binding power LESS THAN OR EQUAL TO rbp."""
290 # TODO: use Kind.Eof
291 if self.op_id in (Id.Eof_Real, Id.Eof_RParen, Id.Eof_Backtick):
292 p_die('Unexpected end of input', loc.Word(self.cur_word))
293
294 t = self.cur_word
295 null_info = self.spec.LookupNud(self.op_id)
296
297 self.Next() # skip over the token, e.g. ! ~ + -
298 node = null_info.nud(self, t, null_info.bp)
299
300 while True:
301 t = self.cur_word
302 left_info = self.spec.LookupLed(self.op_id)
303
304 # Examples:
305 # If we see 1*2+ , rbp = 27 and lbp = 25, so stop.
306 # If we see 1+2+ , rbp = 25 and lbp = 25, so stop.
307 # If we see 1**2**, rbp = 26 and lbp = 27, so keep going.
308 if rbp >= left_info.lbp:
309 break
310 self.Next() # skip over the token, e.g. / *
311
312 node = left_info.led(self, t, node, left_info.rbp)
313
314 return node
315
316 def Parse(self):
317 # type: () -> arith_expr_t
318
319 self.Next() # may raise ParseError
320
321 if not self.parse_opts.parse_sh_arith():
322 # Affects:
323 # echo $(( x ))
324 # ${a[i]} which should be $[a[i]] -- could have better error
325 #
326 # Note: sh_expr_eval.UnsafeArith has a dynamic e_die() check
327 #
328 # Doesn't affect:
329 # printf -v x # unsafe_arith.ParseLValue
330 # unset x # unsafe_arith.ParseLValue
331 # ${!ref} # unsafe_arith.ParseVarRef
332 # declare -n # not fully implemented yet
333 #
334 # a[i+1]= # parse_sh_assign
335 #
336 # (( a = 1 )) # parse_dparen
337 # for (( i = 0; ... # parse_dparen
338
339 p_die("POSIX shell arithmetic isn't allowed (parse_sh_arith)",
340 loc.Word(self.cur_word))
341
342 return self.ParseUntil(0)