1 | #!/usr/bin/env python2
|
2 | """expr_eval.py."""
|
3 | from __future__ import print_function
|
4 |
|
5 | from _devbuild.gen.id_kind_asdl import Id
|
6 | from _devbuild.gen.syntax_asdl import (
|
7 | loc,
|
8 | loc_t,
|
9 | re,
|
10 | re_e,
|
11 | re_t,
|
12 | Token,
|
13 | SimpleVarSub,
|
14 | word_part,
|
15 | SingleQuoted,
|
16 | DoubleQuoted,
|
17 | BracedVarSub,
|
18 | ShArrayLiteral,
|
19 | CommandSub,
|
20 | expr,
|
21 | expr_e,
|
22 | expr_t,
|
23 | y_lhs_e,
|
24 | y_lhs_t,
|
25 | Attribute,
|
26 | Subscript,
|
27 | class_literal_term,
|
28 | class_literal_term_e,
|
29 | class_literal_term_t,
|
30 | char_class_term_t,
|
31 | PosixClass,
|
32 | PerlClass,
|
33 | CharCode,
|
34 | CharRange,
|
35 | ArgList,
|
36 | Eggex,
|
37 | )
|
38 | from _devbuild.gen.runtime_asdl import (
|
39 | coerced_e,
|
40 | coerced_t,
|
41 | scope_e,
|
42 | scope_t,
|
43 | part_value,
|
44 | part_value_t,
|
45 | Piece,
|
46 | )
|
47 | from _devbuild.gen.value_asdl import (value, value_e, value_t, y_lvalue,
|
48 | y_lvalue_e, y_lvalue_t, IntBox, LeftName)
|
49 | from core import error
|
50 | from core.error import e_die, e_die_status
|
51 | from core import num
|
52 | from core import pyutil
|
53 | from core import state
|
54 | from core import ui
|
55 | from core import vm
|
56 | from data_lang import j8
|
57 | from frontend import lexer
|
58 | from frontend import match
|
59 | from frontend import typed_args
|
60 | from osh import braces
|
61 | from mycpp import mops
|
62 | from mycpp.mylib import log, NewDict, switch, tagswitch, print_stderr
|
63 | from ysh import func_proc
|
64 | from ysh import val_ops
|
65 |
|
66 | import libc
|
67 |
|
68 | from typing import cast, Optional, Dict, List, Tuple, TYPE_CHECKING
|
69 |
|
70 | if TYPE_CHECKING:
|
71 | from osh import cmd_eval
|
72 | from osh import word_eval
|
73 | from osh import split
|
74 |
|
75 | _ = log
|
76 |
|
77 |
|
78 | def LookupVar(mem, var_name, which_scopes, var_loc):
|
79 | # type: (state.Mem, str, scope_t, loc_t) -> value_t
|
80 |
|
81 | # Lookup WITHOUT dynamic scope.
|
82 | val = mem.GetValue(var_name, which_scopes=which_scopes)
|
83 | if val.tag() == value_e.Undef:
|
84 | e_die('Undefined variable %r' % var_name, var_loc)
|
85 |
|
86 | return val
|
87 |
|
88 |
|
89 | def _ConvertToInt(val, msg, blame_loc):
|
90 | # type: (value_t, str, loc_t) -> mops.BigInt
|
91 | UP_val = val
|
92 | with tagswitch(val) as case:
|
93 | if case(value_e.Int):
|
94 | val = cast(value.Int, UP_val)
|
95 | return val.i
|
96 |
|
97 | elif case(value_e.Str):
|
98 | val = cast(value.Str, UP_val)
|
99 | if match.LooksLikeInteger(val.s):
|
100 | # TODO: Handle ValueError
|
101 | return mops.FromStr(val.s)
|
102 |
|
103 | raise error.TypeErr(val, msg, blame_loc)
|
104 |
|
105 |
|
106 | def _ConvertToNumber(val):
|
107 | # type: (value_t) -> Tuple[coerced_t, mops.BigInt, float]
|
108 | UP_val = val
|
109 | with tagswitch(val) as case:
|
110 | if case(value_e.Int):
|
111 | val = cast(value.Int, UP_val)
|
112 | return coerced_e.Int, val.i, -1.0
|
113 |
|
114 | elif case(value_e.Float):
|
115 | val = cast(value.Float, UP_val)
|
116 | return coerced_e.Float, mops.MINUS_ONE, val.f
|
117 |
|
118 | elif case(value_e.Str):
|
119 | val = cast(value.Str, UP_val)
|
120 | if match.LooksLikeInteger(val.s):
|
121 | # TODO: Handle ValueError
|
122 | return coerced_e.Int, mops.FromStr(val.s), -1.0
|
123 |
|
124 | if match.LooksLikeFloat(val.s):
|
125 | return coerced_e.Float, mops.MINUS_ONE, float(val.s)
|
126 |
|
127 | return coerced_e.Neither, mops.MINUS_ONE, -1.0
|
128 |
|
129 |
|
130 | def _ConvertForBinaryOp(left, right):
|
131 | # type: (value_t, value_t) -> Tuple[coerced_t, mops.BigInt, mops.BigInt, float, float]
|
132 | """
|
133 | Returns one of
|
134 | value_e.Int or value_e.Float
|
135 | 2 ints or 2 floats
|
136 |
|
137 | To indicate which values the operation should be done on
|
138 | """
|
139 | c1, i1, f1 = _ConvertToNumber(left)
|
140 | c2, i2, f2 = _ConvertToNumber(right)
|
141 |
|
142 | nope = mops.MINUS_ONE
|
143 |
|
144 | if c1 == coerced_e.Int and c2 == coerced_e.Int:
|
145 | return coerced_e.Int, i1, i2, -1.0, -1.0
|
146 |
|
147 | elif c1 == coerced_e.Int and c2 == coerced_e.Float:
|
148 | return coerced_e.Float, nope, nope, mops.ToFloat(i1), f2
|
149 |
|
150 | elif c1 == coerced_e.Float and c2 == coerced_e.Int:
|
151 | return coerced_e.Float, nope, nope, f1, mops.ToFloat(i2)
|
152 |
|
153 | elif c1 == coerced_e.Float and c2 == coerced_e.Float:
|
154 | return coerced_e.Float, nope, nope, f1, f2
|
155 |
|
156 | else:
|
157 | # No operation is valid
|
158 | return coerced_e.Neither, nope, nope, -1.0, -1.0
|
159 |
|
160 |
|
161 | class ExprEvaluator(object):
|
162 | """Shared between arith and bool evaluators.
|
163 |
|
164 | They both:
|
165 |
|
166 | 1. Convert strings to integers, respecting shopt -s strict_arith.
|
167 | 2. Look up variables and evaluate words.
|
168 | """
|
169 |
|
170 | def __init__(
|
171 | self,
|
172 | mem, # type: state.Mem
|
173 | mutable_opts, # type: state.MutableOpts
|
174 | methods, # type: Dict[int, Dict[str, vm._Callable]]
|
175 | splitter, # type: split.SplitContext
|
176 | errfmt, # type: ui.ErrorFormatter
|
177 | ):
|
178 | # type: (...) -> None
|
179 | self.shell_ex = None # type: vm._Executor
|
180 | self.cmd_ev = None # type: cmd_eval.CommandEvaluator
|
181 | self.word_ev = None # type: word_eval.AbstractWordEvaluator
|
182 |
|
183 | self.mem = mem
|
184 | self.mutable_opts = mutable_opts
|
185 | self.methods = methods
|
186 | self.splitter = splitter
|
187 | self.errfmt = errfmt
|
188 |
|
189 | def CheckCircularDeps(self):
|
190 | # type: () -> None
|
191 | assert self.shell_ex is not None
|
192 | assert self.word_ev is not None
|
193 |
|
194 | def _LookupVar(self, name, var_loc):
|
195 | # type: (str, loc_t) -> value_t
|
196 | return LookupVar(self.mem, name, scope_e.LocalOrGlobal, var_loc)
|
197 |
|
198 | def EvalAugmented(self, lval, rhs_val, op, which_scopes):
|
199 | # type: (y_lvalue_t, value_t, Token, scope_t) -> None
|
200 | """ setvar x +=1, setvar L[0] -= 1
|
201 |
|
202 | Called by CommandEvaluator
|
203 | """
|
204 | # TODO: It might be nice to do auto d[x] += 1 too
|
205 |
|
206 | UP_lval = lval
|
207 | with tagswitch(lval) as case:
|
208 | if case(y_lvalue_e.Local): # setvar x += 1
|
209 | lval = cast(LeftName, UP_lval)
|
210 | lhs_val = self._LookupVar(lval.name, lval.blame_loc)
|
211 | if op.id in (Id.Arith_PlusEqual, Id.Arith_MinusEqual,
|
212 | Id.Arith_StarEqual, Id.Arith_SlashEqual):
|
213 | new_val = self._ArithIntFloat(lhs_val, rhs_val, op)
|
214 | else:
|
215 | new_val = self._ArithIntOnly(lhs_val, rhs_val, op)
|
216 |
|
217 | self.mem.SetNamed(lval, new_val, which_scopes)
|
218 |
|
219 | elif case(y_lvalue_e.Container): # setvar d.key += 1
|
220 | lval = cast(y_lvalue.Container, UP_lval)
|
221 |
|
222 | obj = lval.obj
|
223 | UP_obj = obj
|
224 |
|
225 | lhs_val_ = None # type: value_t
|
226 | # Similar to command_e.Mutation
|
227 | with tagswitch(obj) as case:
|
228 | if case(value_e.List):
|
229 | obj = cast(value.List, UP_obj)
|
230 | index = val_ops.ToInt(lval.index,
|
231 | 'List index should be Int',
|
232 | loc.Missing)
|
233 | lhs_val_ = obj.items[index]
|
234 |
|
235 | elif case(value_e.Dict):
|
236 | obj = cast(value.Dict, UP_obj)
|
237 | index = -1 # silence C++ warning
|
238 | key = val_ops.ToStr(lval.index,
|
239 | 'Dict index should be Str',
|
240 | loc.Missing)
|
241 | lhs_val_ = obj.d[key]
|
242 |
|
243 | else:
|
244 | raise error.TypeErr(
|
245 | obj, "obj[index] expected List or Dict",
|
246 | loc.Missing)
|
247 |
|
248 | if op.id in (Id.Arith_PlusEqual, Id.Arith_MinusEqual,
|
249 | Id.Arith_StarEqual, Id.Arith_SlashEqual):
|
250 | new_val_ = self._ArithIntFloat(lhs_val_, rhs_val, op)
|
251 | else:
|
252 | new_val_ = self._ArithIntOnly(lhs_val_, rhs_val, op)
|
253 |
|
254 | with tagswitch(obj) as case:
|
255 | if case(value_e.List):
|
256 | obj = cast(value.List, UP_obj)
|
257 | assert index != -1, 'Should have been initialized'
|
258 | obj.items[index] = new_val_
|
259 |
|
260 | elif case(value_e.Dict):
|
261 | obj = cast(value.Dict, UP_obj)
|
262 | obj.d[key] = new_val_
|
263 |
|
264 | else:
|
265 | raise AssertionError()
|
266 |
|
267 | def _EvalLeftLocalOrGlobal(self, lhs, which_scopes):
|
268 | # type: (expr_t, scope_t) -> value_t
|
269 | """Evaluate the LEFT MOST part, respecting setvar/setglobal.
|
270 |
|
271 | Consider this statement:
|
272 |
|
273 | setglobal g[a[i]] = 42
|
274 |
|
275 | - The g is always global, never local. It's the thing to be mutated.
|
276 | - The a can be local or global
|
277 | """
|
278 | UP_lhs = lhs
|
279 | with tagswitch(lhs) as case:
|
280 | if case(expr_e.Var):
|
281 | lhs = cast(expr.Var, UP_lhs)
|
282 |
|
283 | # respect setvar/setglobal with which_scopes
|
284 | return LookupVar(self.mem, lhs.name, which_scopes, lhs.left)
|
285 |
|
286 | elif case(expr_e.Subscript):
|
287 | lhs = cast(Subscript, UP_lhs)
|
288 |
|
289 | # recursive call
|
290 | obj = self._EvalLeftLocalOrGlobal(lhs.obj, which_scopes)
|
291 | index = self._EvalExpr(lhs.index)
|
292 |
|
293 | return self._EvalSubscript(obj, index)
|
294 |
|
295 | elif case(expr_e.Attribute):
|
296 | lhs = cast(Attribute, UP_lhs)
|
297 | assert lhs.op.id == Id.Expr_Dot
|
298 |
|
299 | # recursive call
|
300 | obj = self._EvalLeftLocalOrGlobal(lhs.obj, which_scopes)
|
301 | return self._EvalDot(lhs, obj)
|
302 |
|
303 | else:
|
304 | # Shouldn't happen because of Transformer._CheckLhs
|
305 | raise AssertionError()
|
306 |
|
307 | def _EvalLhsExpr(self, lhs, which_scopes):
|
308 | # type: (y_lhs_t, scope_t) -> y_lvalue_t
|
309 | """
|
310 | Handle setvar x, setvar a[i], ... setglobal x, setglobal a[i]
|
311 | """
|
312 | UP_lhs = lhs
|
313 | with tagswitch(lhs) as case:
|
314 | if case(y_lhs_e.Var):
|
315 | lhs = cast(Token, UP_lhs)
|
316 | return LeftName(lexer.LazyStr(lhs), lhs)
|
317 |
|
318 | elif case(y_lhs_e.Subscript):
|
319 | lhs = cast(Subscript, UP_lhs)
|
320 | # setvar mylist[0] = 42
|
321 | # setvar mydict['key'] = 42
|
322 |
|
323 | lval = self._EvalLeftLocalOrGlobal(lhs.obj, which_scopes)
|
324 | index = self._EvalExpr(lhs.index)
|
325 | return y_lvalue.Container(lval, index)
|
326 |
|
327 | elif case(y_lhs_e.Attribute):
|
328 | lhs = cast(Attribute, UP_lhs)
|
329 | assert lhs.op.id == Id.Expr_Dot
|
330 |
|
331 | # setvar mydict.key = 42
|
332 | lval = self._EvalLeftLocalOrGlobal(lhs.obj, which_scopes)
|
333 |
|
334 | attr = value.Str(lhs.attr_name)
|
335 | return y_lvalue.Container(lval, attr)
|
336 |
|
337 | else:
|
338 | raise AssertionError()
|
339 |
|
340 | def EvalExpr(self, node, blame_loc):
|
341 | # type: (expr_t, loc_t) -> value_t
|
342 | """Public API for _EvalExpr to ensure command_sub_errexit"""
|
343 | self.mem.SetLocationForExpr(blame_loc)
|
344 | # Pure C++ won't need to catch exceptions
|
345 | with state.ctx_YshExpr(self.mutable_opts):
|
346 | val = self._EvalExpr(node)
|
347 | return val
|
348 |
|
349 | def EvalLhsExpr(self, lhs, which_scopes):
|
350 | # type: (y_lhs_t, scope_t) -> y_lvalue_t
|
351 | """Public API for _EvalLhsExpr to ensure command_sub_errexit"""
|
352 | with state.ctx_YshExpr(self.mutable_opts):
|
353 | lval = self._EvalLhsExpr(lhs, which_scopes)
|
354 | return lval
|
355 |
|
356 | def EvalExprSub(self, part):
|
357 | # type: (word_part.ExprSub) -> part_value_t
|
358 |
|
359 | val = self.EvalExpr(part.child, part.left)
|
360 |
|
361 | with switch(part.left.id) as case:
|
362 | if case(Id.Left_DollarBracket): # $[join(x)]
|
363 | s = val_ops.Stringify(val, loc.WordPart(part))
|
364 | return Piece(s, False, False)
|
365 |
|
366 | elif case(Id.Lit_AtLBracket): # @[split(x)]
|
367 | strs = val_ops.ToShellArray(val,
|
368 | loc.WordPart(part),
|
369 | prefix='Expr splice ')
|
370 | return part_value.Array(strs)
|
371 |
|
372 | else:
|
373 | raise AssertionError(part.left)
|
374 |
|
375 | def PluginCall(self, func_val, pos_args):
|
376 | # type: (value.Func, List[value_t]) -> value_t
|
377 | """For renderPrompt()
|
378 |
|
379 | Similar to
|
380 | - WordEvaluator.EvalForPlugin(), which evaluates $PS1 outside main loop
|
381 | - ReadlineCallback.__call__, which executes shell outside main loop
|
382 | """
|
383 | with state.ctx_YshExpr(self.mutable_opts):
|
384 | with state.ctx_Registers(self.mem): # to sandbox globals
|
385 | named_args = {} # type: Dict[str, value_t]
|
386 | arg_list = ArgList.CreateNull() # There's no call site
|
387 | rd = typed_args.Reader(pos_args, named_args, None, arg_list)
|
388 |
|
389 | try:
|
390 | val = func_proc.CallUserFunc(func_val, rd, self.mem,
|
391 | self.cmd_ev)
|
392 | except error.FatalRuntime as e:
|
393 | val = value.Str('<Runtime error: %s>' %
|
394 | e.UserErrorString())
|
395 |
|
396 | except (IOError, OSError) as e:
|
397 | val = value.Str('<I/O error: %s>' % pyutil.strerror(e))
|
398 |
|
399 | except KeyboardInterrupt:
|
400 | val = value.Str('<Ctrl-C>')
|
401 |
|
402 | return val
|
403 |
|
404 | def CallConvertFunc(self, func_val, arg, convert_tok, call_loc):
|
405 | # type: (value_t, value_t, Token, loc_t) -> value_t
|
406 | """ For Eggex captures """
|
407 | with state.ctx_YshExpr(self.mutable_opts):
|
408 | pos_args = [arg]
|
409 | named_args = {} # type: Dict[str, value_t]
|
410 | arg_list = ArgList.CreateNull() # There's no call site
|
411 | rd = typed_args.Reader(pos_args, named_args, None, arg_list)
|
412 | rd.SetFallbackLocation(convert_tok)
|
413 | try:
|
414 | val = self._CallFunc(func_val, rd)
|
415 | except error.FatalRuntime as e:
|
416 | func_name = lexer.TokenVal(convert_tok)
|
417 | self.errfmt.Print_(
|
418 | 'Fatal error calling Eggex conversion func %r from this Match accessor'
|
419 | % func_name, call_loc)
|
420 | print_stderr('')
|
421 | raise
|
422 |
|
423 | return val
|
424 |
|
425 | def SpliceValue(self, val, part):
|
426 | # type: (value_t, word_part.Splice) -> List[str]
|
427 | """ write -- @myvar """
|
428 | return val_ops.ToShellArray(val, loc.WordPart(part), prefix='Splice ')
|
429 |
|
430 | def _EvalConst(self, node):
|
431 | # type: (expr.Const) -> value_t
|
432 | return node.val
|
433 |
|
434 | def _EvalUnary(self, node):
|
435 | # type: (expr.Unary) -> value_t
|
436 |
|
437 | val = self._EvalExpr(node.child)
|
438 |
|
439 | with switch(node.op.id) as case:
|
440 | if case(Id.Arith_Minus):
|
441 | c1, i1, f1 = _ConvertToNumber(val)
|
442 | if c1 == coerced_e.Int:
|
443 | return value.Int(mops.Negate(i1))
|
444 | if c1 == coerced_e.Float:
|
445 | return value.Float(-f1)
|
446 | raise error.TypeErr(val, 'Negation expected Int or Float',
|
447 | node.op)
|
448 |
|
449 | elif case(Id.Arith_Tilde):
|
450 | i = _ConvertToInt(val, '~ expected Int', node.op)
|
451 | return value.Int(mops.BitNot(i))
|
452 |
|
453 | elif case(Id.Expr_Not):
|
454 | b = val_ops.ToBool(val)
|
455 | return value.Bool(False if b else True)
|
456 |
|
457 | # &s &a[0] &d.key &d.nested.other
|
458 | elif case(Id.Arith_Amp):
|
459 | # Only 3 possibilities:
|
460 | # - expr.Var
|
461 | # - expr.Attribute with `.` operator (d.key)
|
462 | # - expr.SubScript
|
463 | #
|
464 | # See _EvalLhsExpr, which gives you y_lvalue
|
465 |
|
466 | # TODO: &x, &a[0], &d.key, creates a value.Place?
|
467 | # If it's Attribute or SubScript, you don't evaluate them.
|
468 | # y_lvalue_t -> place_t
|
469 |
|
470 | raise NotImplementedError(node.op)
|
471 |
|
472 | else:
|
473 | raise AssertionError(node.op)
|
474 |
|
475 | raise AssertionError('for C++ compiler')
|
476 |
|
477 | def _ArithIntFloat(self, left, right, op):
|
478 | # type: (value_t, value_t, Token) -> value_t
|
479 | """
|
480 | Note: may be replaced with arithmetic on tagged integers, e.g. 60 bit
|
481 | with overflow detection
|
482 | """
|
483 | c, i1, i2, f1, f2 = _ConvertForBinaryOp(left, right)
|
484 |
|
485 | op_id = op.id
|
486 |
|
487 | if c == coerced_e.Int:
|
488 | with switch(op_id) as case:
|
489 | if case(Id.Arith_Plus, Id.Arith_PlusEqual):
|
490 | return value.Int(mops.Add(i1, i2))
|
491 | elif case(Id.Arith_Minus, Id.Arith_MinusEqual):
|
492 | return value.Int(mops.Sub(i1, i2))
|
493 | elif case(Id.Arith_Star, Id.Arith_StarEqual):
|
494 | return value.Int(mops.Mul(i1, i2))
|
495 | elif case(Id.Arith_Slash, Id.Arith_SlashEqual):
|
496 | if mops.Equal(i2, mops.ZERO):
|
497 | raise error.Expr('Divide by zero', op)
|
498 | return value.Float(mops.ToFloat(i1) / mops.ToFloat(i2))
|
499 | else:
|
500 | raise AssertionError()
|
501 |
|
502 | elif c == coerced_e.Float:
|
503 | with switch(op_id) as case:
|
504 | if case(Id.Arith_Plus, Id.Arith_PlusEqual):
|
505 | return value.Float(f1 + f2)
|
506 | elif case(Id.Arith_Minus, Id.Arith_MinusEqual):
|
507 | return value.Float(f1 - f2)
|
508 | elif case(Id.Arith_Star, Id.Arith_StarEqual):
|
509 | return value.Float(f1 * f2)
|
510 | elif case(Id.Arith_Slash, Id.Arith_SlashEqual):
|
511 | if f2 == 0.0:
|
512 | raise error.Expr('Divide by zero', op)
|
513 | return value.Float(f1 / f2)
|
514 | else:
|
515 | raise AssertionError()
|
516 |
|
517 | else:
|
518 | raise error.TypeErrVerbose(
|
519 | 'Binary operator expected numbers, got %s and %s (OILS-ERR-201)'
|
520 | % (ui.ValType(left), ui.ValType(right)), op)
|
521 |
|
522 | def _ArithIntOnly(self, left, right, op):
|
523 | # type: (value_t, value_t, Token) -> value_t
|
524 |
|
525 | i1 = _ConvertToInt(left, 'Left operand should be Int', op)
|
526 | i2 = _ConvertToInt(right, 'Right operand should be Int', op)
|
527 |
|
528 | with switch(op.id) as case:
|
529 |
|
530 | # a % b setvar a %= b
|
531 | if case(Id.Arith_Percent, Id.Arith_PercentEqual):
|
532 | if mops.Equal(i2, mops.ZERO):
|
533 | raise error.Expr('Divide by zero', op)
|
534 | if mops.Greater(mops.ZERO, i2):
|
535 | # Disallow this to remove confusion between modulus and remainder
|
536 | raise error.Expr("Divisor can't be negative", op)
|
537 |
|
538 | return value.Int(num.IntRemainder(i1, i2))
|
539 |
|
540 | # a // b setvar a //= b
|
541 | elif case(Id.Expr_DSlash, Id.Expr_DSlashEqual):
|
542 | if mops.Equal(i2, mops.ZERO):
|
543 | raise error.Expr('Divide by zero', op)
|
544 | return value.Int(num.IntDivide(i1, i2))
|
545 |
|
546 | # a ** b setvar a **= b (ysh only)
|
547 | elif case(Id.Arith_DStar, Id.Expr_DStarEqual):
|
548 | # Same as sh_expr_eval.py
|
549 | if mops.Greater(mops.ZERO, i2):
|
550 | raise error.Expr("Exponent can't be a negative number", op)
|
551 | return value.Int(num.Exponent(i1, i2))
|
552 |
|
553 | # Bitwise
|
554 | elif case(Id.Arith_Amp, Id.Arith_AmpEqual): # &
|
555 | return value.Int(mops.BitAnd(i1, i2))
|
556 |
|
557 | elif case(Id.Arith_Pipe, Id.Arith_PipeEqual): # |
|
558 | return value.Int(mops.BitOr(i1, i2))
|
559 |
|
560 | elif case(Id.Arith_Caret, Id.Arith_CaretEqual): # ^
|
561 | return value.Int(mops.BitXor(i1, i2))
|
562 |
|
563 | elif case(Id.Arith_DGreat, Id.Arith_DGreatEqual): # >>
|
564 | return value.Int(mops.RShift(i1, i2))
|
565 |
|
566 | elif case(Id.Arith_DLess, Id.Arith_DLessEqual): # <<
|
567 | return value.Int(mops.LShift(i1, i2))
|
568 |
|
569 | else:
|
570 | raise AssertionError(op.id)
|
571 |
|
572 | def _Concat(self, left, right, op):
|
573 | # type: (value_t, value_t, Token) -> value_t
|
574 | UP_left = left
|
575 | UP_right = right
|
576 |
|
577 | if left.tag() == value_e.Str and right.tag() == value_e.Str:
|
578 | left = cast(value.Str, UP_left)
|
579 | right = cast(value.Str, UP_right)
|
580 |
|
581 | return value.Str(left.s + right.s)
|
582 |
|
583 | elif left.tag() == value_e.List and right.tag() == value_e.List:
|
584 | left = cast(value.List, UP_left)
|
585 | right = cast(value.List, UP_right)
|
586 |
|
587 | c = list(left.items) # mycpp rewrite of L1 + L2
|
588 | c.extend(right.items)
|
589 | return value.List(c)
|
590 |
|
591 | else:
|
592 | raise error.TypeErrVerbose(
|
593 | 'Expected Str ++ Str or List ++ List, got %s ++ %s' %
|
594 | (ui.ValType(left), ui.ValType(right)), op)
|
595 |
|
596 | def _EvalBinary(self, node):
|
597 | # type: (expr.Binary) -> value_t
|
598 |
|
599 | left = self._EvalExpr(node.left)
|
600 |
|
601 | # Logical and/or lazily evaluate
|
602 | with switch(node.op.id) as case:
|
603 | if case(Id.Expr_And):
|
604 | if val_ops.ToBool(left): # no errors
|
605 | return self._EvalExpr(node.right)
|
606 | else:
|
607 | return left
|
608 |
|
609 | elif case(Id.Expr_Or):
|
610 | if val_ops.ToBool(left):
|
611 | return left
|
612 | else:
|
613 | return self._EvalExpr(node.right)
|
614 |
|
615 | # These operators all eagerly evaluate
|
616 | right = self._EvalExpr(node.right)
|
617 |
|
618 | with switch(node.op.id) as case:
|
619 | if case(Id.Arith_DPlus): # a ++ b to concat Str or List
|
620 | return self._Concat(left, right, node.op)
|
621 |
|
622 | elif case(Id.Arith_Plus, Id.Arith_Minus, Id.Arith_Star,
|
623 | Id.Arith_Slash):
|
624 | return self._ArithIntFloat(left, right, node.op)
|
625 |
|
626 | else:
|
627 | return self._ArithIntOnly(left, right, node.op)
|
628 |
|
629 | def _CompareNumeric(self, left, right, op):
|
630 | # type: (value_t, value_t, Token) -> bool
|
631 | c, i1, i2, f1, f2 = _ConvertForBinaryOp(left, right)
|
632 |
|
633 | if c == coerced_e.Int:
|
634 | with switch(op.id) as case:
|
635 | if case(Id.Arith_Less):
|
636 | return mops.Greater(i2, i1)
|
637 | elif case(Id.Arith_Great):
|
638 | return mops.Greater(i1, i2)
|
639 | elif case(Id.Arith_LessEqual):
|
640 | return mops.Greater(i2, i1) or mops.Equal(i1, i2)
|
641 | elif case(Id.Arith_GreatEqual):
|
642 | return mops.Greater(i1, i2) or mops.Equal(i1, i2)
|
643 | else:
|
644 | raise AssertionError()
|
645 |
|
646 | elif c == coerced_e.Float:
|
647 | with switch(op.id) as case:
|
648 | if case(Id.Arith_Less):
|
649 | return f1 < f2
|
650 | elif case(Id.Arith_Great):
|
651 | return f1 > f2
|
652 | elif case(Id.Arith_LessEqual):
|
653 | return f1 <= f2
|
654 | elif case(Id.Arith_GreatEqual):
|
655 | return f1 >= f2
|
656 | else:
|
657 | raise AssertionError()
|
658 |
|
659 | else:
|
660 | raise error.TypeErrVerbose(
|
661 | 'Comparison operator expected numbers, got %s and %s' %
|
662 | (ui.ValType(left), ui.ValType(right)), op)
|
663 |
|
664 | def _EvalCompare(self, node):
|
665 | # type: (expr.Compare) -> value_t
|
666 |
|
667 | left = self._EvalExpr(node.left)
|
668 | result = True # Implicit and
|
669 | for i, op in enumerate(node.ops):
|
670 | right_expr = node.comparators[i]
|
671 |
|
672 | right = self._EvalExpr(right_expr)
|
673 |
|
674 | if op.id in (Id.Arith_Less, Id.Arith_Great, Id.Arith_LessEqual,
|
675 | Id.Arith_GreatEqual):
|
676 | result = self._CompareNumeric(left, right, op)
|
677 |
|
678 | elif op.id == Id.Expr_TEqual:
|
679 | if left.tag() != right.tag():
|
680 | result = False
|
681 | else:
|
682 | result = val_ops.ExactlyEqual(left, right, op)
|
683 | elif op.id == Id.Expr_NotDEqual:
|
684 | if left.tag() != right.tag():
|
685 | result = True
|
686 | else:
|
687 | result = not val_ops.ExactlyEqual(left, right, op)
|
688 |
|
689 | elif op.id == Id.Expr_In:
|
690 | result = val_ops.Contains(left, right)
|
691 | elif op.id == Id.Node_NotIn:
|
692 | result = not val_ops.Contains(left, right)
|
693 |
|
694 | elif op.id == Id.Expr_Is:
|
695 | if left.tag() != right.tag():
|
696 | raise error.TypeErrVerbose('Mismatched types', op)
|
697 | result = left is right
|
698 |
|
699 | elif op.id == Id.Node_IsNot:
|
700 | if left.tag() != right.tag():
|
701 | raise error.TypeErrVerbose('Mismatched types', op)
|
702 | result = left is not right
|
703 |
|
704 | elif op.id == Id.Expr_DTilde:
|
705 | # no extglob in Oil language; use eggex
|
706 | if left.tag() != value_e.Str:
|
707 | raise error.TypeErrVerbose('LHS must be Str', op)
|
708 |
|
709 | if right.tag() != value_e.Str:
|
710 | raise error.TypeErrVerbose('RHS must be Str', op)
|
711 |
|
712 | UP_left = left
|
713 | UP_right = right
|
714 | left = cast(value.Str, UP_left)
|
715 | right = cast(value.Str, UP_right)
|
716 | return value.Bool(libc.fnmatch(right.s, left.s))
|
717 |
|
718 | elif op.id == Id.Expr_NotDTilde:
|
719 | if left.tag() != value_e.Str:
|
720 | raise error.TypeErrVerbose('LHS must be Str', op)
|
721 |
|
722 | if right.tag() != value_e.Str:
|
723 | raise error.TypeErrVerbose('RHS must be Str', op)
|
724 |
|
725 | UP_left = left
|
726 | UP_right = right
|
727 | left = cast(value.Str, UP_left)
|
728 | right = cast(value.Str, UP_right)
|
729 | return value.Bool(not libc.fnmatch(right.s, left.s))
|
730 |
|
731 | elif op.id == Id.Expr_TildeDEqual:
|
732 | # Approximate equality
|
733 | UP_left = left
|
734 | if left.tag() != value_e.Str:
|
735 | e_die('~== expects a string on the left', op)
|
736 |
|
737 | left = cast(value.Str, UP_left)
|
738 | left2 = left.s.strip()
|
739 |
|
740 | UP_right = right
|
741 | with tagswitch(right) as case:
|
742 | if case(value_e.Str):
|
743 | right = cast(value.Str, UP_right)
|
744 | return value.Bool(left2 == right.s)
|
745 |
|
746 | elif case(value_e.Bool):
|
747 | right = cast(value.Bool, UP_right)
|
748 | left2 = left2.lower()
|
749 | lb = False
|
750 | if left2 == 'true':
|
751 | lb = True
|
752 | elif left2 == 'false':
|
753 | lb = False
|
754 | else:
|
755 | return value.Bool(False)
|
756 |
|
757 | #log('left %r left2 %r', left, left2)
|
758 | return value.Bool(lb == right.b)
|
759 |
|
760 | elif case(value_e.Int):
|
761 | right = cast(value.Int, UP_right)
|
762 | if not left2.isdigit():
|
763 | return value.Bool(False)
|
764 |
|
765 | eq = mops.Equal(mops.FromStr(left2), right.i)
|
766 | return value.Bool(eq)
|
767 |
|
768 | e_die('~== expects Str, Int, or Bool on the right', op)
|
769 |
|
770 | else:
|
771 | try:
|
772 | if op.id == Id.Arith_Tilde:
|
773 | result = val_ops.MatchRegex(left, right, self.mem)
|
774 |
|
775 | elif op.id == Id.Expr_NotTilde:
|
776 | # don't pass self.mem to not set a match
|
777 | result = not val_ops.MatchRegex(left, right, None)
|
778 |
|
779 | else:
|
780 | raise AssertionError(op)
|
781 | except ValueError as e:
|
782 | # Status 2 indicates a regex parse error, as with [[ in OSH
|
783 | e_die_status(2, e.message, op)
|
784 |
|
785 | if not result:
|
786 | return value.Bool(result)
|
787 |
|
788 | left = right
|
789 |
|
790 | return value.Bool(result)
|
791 |
|
792 | def _CallFunc(self, to_call, rd):
|
793 | # type: (value_t, typed_args.Reader) -> value_t
|
794 |
|
795 | # Now apply args to either builtin or user-defined function
|
796 | UP_to_call = to_call
|
797 | with tagswitch(to_call) as case:
|
798 | if case(value_e.Func):
|
799 | to_call = cast(value.Func, UP_to_call)
|
800 |
|
801 | return func_proc.CallUserFunc(to_call, rd, self.mem,
|
802 | self.cmd_ev)
|
803 |
|
804 | elif case(value_e.BuiltinFunc):
|
805 | to_call = cast(value.BuiltinFunc, UP_to_call)
|
806 |
|
807 | # C++ cast to work around ASDL 'any'
|
808 | f = cast(vm._Callable, to_call.callable)
|
809 | return f.Call(rd)
|
810 | else:
|
811 | raise AssertionError("Shouldn't have been bound")
|
812 |
|
813 | def _EvalFuncCall(self, node):
|
814 | # type: (expr.FuncCall) -> value_t
|
815 |
|
816 | func = self._EvalExpr(node.func)
|
817 | UP_func = func
|
818 |
|
819 | # The () operator has a 2x2 matrix of
|
820 | # (free, bound) x (builtin, user-defined)
|
821 |
|
822 | # Eval args first
|
823 | with tagswitch(func) as case:
|
824 | if case(value_e.Func, value_e.BuiltinFunc):
|
825 | to_call = func
|
826 | pos_args, named_args = func_proc._EvalArgList(self, node.args)
|
827 | rd = typed_args.Reader(pos_args, named_args, None, node.args)
|
828 |
|
829 | elif case(value_e.BoundFunc):
|
830 | func = cast(value.BoundFunc, UP_func)
|
831 |
|
832 | to_call = func.func
|
833 | pos_args, named_args = func_proc._EvalArgList(self,
|
834 | node.args,
|
835 | me=func.me)
|
836 | rd = typed_args.Reader(pos_args,
|
837 | named_args,
|
838 | None,
|
839 | node.args,
|
840 | is_bound=True)
|
841 | else:
|
842 | raise error.TypeErr(func, 'Expected a function or method',
|
843 | node.args.left)
|
844 |
|
845 | return self._CallFunc(to_call, rd)
|
846 |
|
847 | def _EvalSubscript(self, obj, index):
|
848 | # type: (value_t, value_t) -> value_t
|
849 |
|
850 | UP_obj = obj
|
851 | UP_index = index
|
852 |
|
853 | with tagswitch(obj) as case:
|
854 | if case(value_e.Str):
|
855 | # Note: s[i] and s[i:j] are like Go, on bytes. We may provide
|
856 | # s->numBytes(), s->countRunes(), and iteration over runes.
|
857 | obj = cast(value.Str, UP_obj)
|
858 | with tagswitch(index) as case2:
|
859 | if case2(value_e.Slice):
|
860 | index = cast(value.Slice, UP_index)
|
861 |
|
862 | lower = index.lower.i if index.lower else 0
|
863 | upper = index.upper.i if index.upper else len(obj.s)
|
864 | return value.Str(obj.s[lower:upper])
|
865 |
|
866 | elif case2(value_e.Int):
|
867 | index = cast(value.Int, UP_index)
|
868 | i = mops.BigTruncate(index.i)
|
869 | try:
|
870 | return value.Str(obj.s[i])
|
871 | except IndexError:
|
872 | # TODO: expr.Subscript has no error location
|
873 | raise error.Expr('index out of range', loc.Missing)
|
874 |
|
875 | else:
|
876 | raise error.TypeErr(index,
|
877 | 'Str index expected Int or Slice',
|
878 | loc.Missing)
|
879 |
|
880 | elif case(value_e.List):
|
881 | obj = cast(value.List, UP_obj)
|
882 | with tagswitch(index) as case2:
|
883 | if case2(value_e.Slice):
|
884 | index = cast(value.Slice, UP_index)
|
885 |
|
886 | lower = index.lower.i if index.lower else 0
|
887 | upper = index.upper.i if index.upper else len(
|
888 | obj.items)
|
889 | return value.List(obj.items[lower:upper])
|
890 |
|
891 | elif case2(value_e.Int):
|
892 | index = cast(value.Int, UP_index)
|
893 | i = mops.BigTruncate(index.i)
|
894 | try:
|
895 | return obj.items[i]
|
896 | except IndexError:
|
897 | # TODO: expr.Subscript has no error location
|
898 | raise error.Expr('index out of range', loc.Missing)
|
899 |
|
900 | else:
|
901 | raise error.TypeErr(
|
902 | index, 'List index expected Int or Slice',
|
903 | loc.Missing)
|
904 |
|
905 | elif case(value_e.Dict):
|
906 | obj = cast(value.Dict, UP_obj)
|
907 | if index.tag() != value_e.Str:
|
908 | raise error.TypeErr(index, 'Dict index expected Str',
|
909 | loc.Missing)
|
910 |
|
911 | index = cast(value.Str, UP_index)
|
912 | try:
|
913 | return obj.d[index.s]
|
914 | except KeyError:
|
915 | # TODO: expr.Subscript has no error location
|
916 | raise error.Expr('Dict entry %r not found' % index.s,
|
917 | loc.Missing)
|
918 |
|
919 | raise error.TypeErr(obj, 'Subscript expected Str, List, or Dict',
|
920 | loc.Missing)
|
921 |
|
922 | def _EvalDot(self, node, obj):
|
923 | # type: (Attribute, value_t) -> value_t
|
924 | """ obj.attr on RHS or LHS
|
925 |
|
926 | setvar x = obj.attr
|
927 | setglobal g[obj.attr] = 42
|
928 | """
|
929 | UP_obj = obj
|
930 | with tagswitch(obj) as case:
|
931 | if case(value_e.Dict):
|
932 | obj = cast(value.Dict, UP_obj)
|
933 | attr_name = node.attr_name
|
934 | try:
|
935 | result = obj.d[attr_name]
|
936 | except KeyError:
|
937 | raise error.Expr('Dict entry %r not found' % attr_name,
|
938 | node.op)
|
939 |
|
940 | else:
|
941 | raise error.TypeErr(obj, 'Dot operator expected Dict', node.op)
|
942 |
|
943 | return result
|
944 |
|
945 | def _EvalAttribute(self, node):
|
946 | # type: (Attribute) -> value_t
|
947 |
|
948 | o = self._EvalExpr(node.obj)
|
949 | UP_o = o
|
950 |
|
951 | with switch(node.op.id) as case:
|
952 | # Right now => is a synonym for ->
|
953 | # Later we may enforce that => is pure, and -> is for mutation and
|
954 | # I/O.
|
955 | if case(Id.Expr_RArrow, Id.Expr_RDArrow):
|
956 | name = node.attr_name
|
957 | # Look up builtin methods
|
958 | type_methods = self.methods.get(o.tag())
|
959 | vm_callable = (type_methods.get(name)
|
960 | if type_methods is not None else None)
|
961 | if vm_callable:
|
962 | func_val = value.BuiltinFunc(vm_callable)
|
963 | return value.BoundFunc(o, func_val)
|
964 |
|
965 | # If the operator is ->, fail because we don't have any
|
966 | # user-defined methods
|
967 | if node.op.id == Id.Expr_RArrow:
|
968 | raise error.TypeErrVerbose(
|
969 | 'Method %r does not exist on type %s' %
|
970 | (name, ui.ValType(o)), node.attr)
|
971 |
|
972 | # Operator is =>, so try function chaining.
|
973 |
|
974 | # Instead of str(f()) => upper()
|
975 | # or str(f()).upper() as in Pythohn
|
976 | #
|
977 | # It's more natural to write
|
978 | # f() => str() => upper()
|
979 |
|
980 | # Could improve error message: may give "Undefined variable"
|
981 | val = self._LookupVar(name, node.attr)
|
982 |
|
983 | with tagswitch(val) as case2:
|
984 | if case2(value_e.Func, value_e.BuiltinFunc):
|
985 | return value.BoundFunc(o, val)
|
986 | else:
|
987 | raise error.TypeErr(
|
988 | val, 'Fat arrow => expects method or function',
|
989 | node.attr)
|
990 |
|
991 | elif case(Id.Expr_Dot): # d.key is like d['key']
|
992 | return self._EvalDot(node, o)
|
993 |
|
994 | else:
|
995 | raise AssertionError(node.op)
|
996 |
|
997 | def _EvalExpr(self, node):
|
998 | # type: (expr_t) -> value_t
|
999 | """Turn an expression into a value."""
|
1000 | if 0:
|
1001 | print('_EvalExpr()')
|
1002 | node.PrettyPrint()
|
1003 | print('')
|
1004 |
|
1005 | UP_node = node
|
1006 | with tagswitch(node) as case:
|
1007 | if case(expr_e.Const):
|
1008 | node = cast(expr.Const, UP_node)
|
1009 | return self._EvalConst(node)
|
1010 |
|
1011 | elif case(expr_e.Var):
|
1012 | node = cast(expr.Var, UP_node)
|
1013 | return self._LookupVar(node.name, node.left)
|
1014 |
|
1015 | elif case(expr_e.Place):
|
1016 | node = cast(expr.Place, UP_node)
|
1017 | frame = self.mem.TopNamespace()
|
1018 | return value.Place(LeftName(node.var_name, node.blame_tok),
|
1019 | frame)
|
1020 |
|
1021 | elif case(expr_e.CommandSub):
|
1022 | node = cast(CommandSub, UP_node)
|
1023 |
|
1024 | id_ = node.left_token.id
|
1025 | if id_ == Id.Left_CaretParen: # ^(echo block literal)
|
1026 | # TODO: Propgate location info?
|
1027 | return value.Command(node.child)
|
1028 | else:
|
1029 | stdout_str = self.shell_ex.RunCommandSub(node)
|
1030 | if id_ == Id.Left_AtParen: # @(seq 3)
|
1031 | # YSH splitting algorithm: does not depend on IFS
|
1032 | try:
|
1033 | strs = j8.SplitJ8Lines(stdout_str)
|
1034 | except error.Decode as e:
|
1035 | # status code 4 is special, for encode/decode errors.
|
1036 | raise error.Structured(4, e.Message(),
|
1037 | node.left_token)
|
1038 |
|
1039 | #strs = self.splitter.SplitForWordEval(stdout_str)
|
1040 |
|
1041 | items = [value.Str(s)
|
1042 | for s in strs] # type: List[value_t]
|
1043 | return value.List(items)
|
1044 | else:
|
1045 | return value.Str(stdout_str)
|
1046 |
|
1047 | elif case(expr_e.ShArrayLiteral): # var x = :| foo *.py |
|
1048 | node = cast(ShArrayLiteral, UP_node)
|
1049 | words = braces.BraceExpandWords(node.words)
|
1050 | strs = self.word_ev.EvalWordSequence(words)
|
1051 | #log('ARRAY LITERAL EVALUATED TO -> %s', strs)
|
1052 | #return value.BashArray(strs)
|
1053 |
|
1054 | # It's equivalent to ['foo', 'bar']
|
1055 | items = [value.Str(s) for s in strs]
|
1056 | return value.List(items)
|
1057 |
|
1058 | elif case(expr_e.DoubleQuoted):
|
1059 | node = cast(DoubleQuoted, UP_node)
|
1060 | # In an ideal world, YSH would *statically* disallow:
|
1061 | #
|
1062 | # - "$@" and "${array[@]}"
|
1063 | # - backticks like `echo hi`
|
1064 | # - $(( 1+2 )) and $[] -- although useful for refactoring
|
1065 | # - not sure: ${x%%} -- could disallow this
|
1066 | # - these enters the ArgDQ state: "${a:-foo bar}" ?
|
1067 | #
|
1068 | # But that would complicate the parser/evaluator. So just rely
|
1069 | # on runtime strict_array to disallow the bad parts.
|
1070 | return value.Str(self.word_ev.EvalDoubleQuotedToString(node))
|
1071 |
|
1072 | elif case(expr_e.SingleQuoted):
|
1073 | node = cast(SingleQuoted, UP_node)
|
1074 | return value.Str(node.sval)
|
1075 |
|
1076 | elif case(expr_e.BracedVarSub):
|
1077 | node = cast(BracedVarSub, UP_node)
|
1078 | return value.Str(self.word_ev.EvalBracedVarSubToString(node))
|
1079 |
|
1080 | elif case(expr_e.SimpleVarSub):
|
1081 | node = cast(SimpleVarSub, UP_node)
|
1082 | return value.Str(self.word_ev.EvalSimpleVarSubToString(node))
|
1083 |
|
1084 | elif case(expr_e.Unary):
|
1085 | node = cast(expr.Unary, UP_node)
|
1086 | return self._EvalUnary(node)
|
1087 |
|
1088 | elif case(expr_e.Binary):
|
1089 | node = cast(expr.Binary, UP_node)
|
1090 | return self._EvalBinary(node)
|
1091 |
|
1092 | elif case(expr_e.Slice): # a[:0]
|
1093 | node = cast(expr.Slice, UP_node)
|
1094 |
|
1095 | lower = None # type: Optional[IntBox]
|
1096 | upper = None # type: Optional[IntBox]
|
1097 |
|
1098 | if node.lower:
|
1099 | msg = 'Slice begin should be Int'
|
1100 | i = val_ops.ToInt(self._EvalExpr(node.lower), msg,
|
1101 | loc.Missing)
|
1102 | lower = IntBox(i)
|
1103 |
|
1104 | if node.upper:
|
1105 | msg = 'Slice end should be Int'
|
1106 | i = val_ops.ToInt(self._EvalExpr(node.upper), msg,
|
1107 | loc.Missing)
|
1108 | upper = IntBox(i)
|
1109 |
|
1110 | return value.Slice(lower, upper)
|
1111 |
|
1112 | elif case(expr_e.Range):
|
1113 | node = cast(expr.Range, UP_node)
|
1114 |
|
1115 | assert node.lower is not None
|
1116 | assert node.upper is not None
|
1117 |
|
1118 | msg = 'Range begin should be Int'
|
1119 | i = val_ops.ToInt(self._EvalExpr(node.lower), msg, loc.Missing)
|
1120 |
|
1121 | msg = 'Range end should be Int'
|
1122 | j = val_ops.ToInt(self._EvalExpr(node.upper), msg, loc.Missing)
|
1123 |
|
1124 | return value.Range(i, j)
|
1125 |
|
1126 | elif case(expr_e.Compare):
|
1127 | node = cast(expr.Compare, UP_node)
|
1128 | return self._EvalCompare(node)
|
1129 |
|
1130 | elif case(expr_e.IfExp):
|
1131 | node = cast(expr.IfExp, UP_node)
|
1132 | b = val_ops.ToBool(self._EvalExpr(node.test))
|
1133 | if b:
|
1134 | return self._EvalExpr(node.body)
|
1135 | else:
|
1136 | return self._EvalExpr(node.orelse)
|
1137 |
|
1138 | elif case(expr_e.List):
|
1139 | node = cast(expr.List, UP_node)
|
1140 | items = [self._EvalExpr(e) for e in node.elts]
|
1141 | return value.List(items)
|
1142 |
|
1143 | elif case(expr_e.Tuple):
|
1144 | node = cast(expr.Tuple, UP_node)
|
1145 | # YSH language: Tuple syntax evaluates to LIST !
|
1146 | items = [self._EvalExpr(e) for e in node.elts]
|
1147 | return value.List(items)
|
1148 |
|
1149 | elif case(expr_e.Dict):
|
1150 | node = cast(expr.Dict, UP_node)
|
1151 |
|
1152 | kvals = [self._EvalExpr(e) for e in node.keys]
|
1153 | values = [] # type: List[value_t]
|
1154 |
|
1155 | for i, value_expr in enumerate(node.values):
|
1156 | if value_expr.tag() == expr_e.Implicit: # {key}
|
1157 | # Enforced by parser. Key is expr.Const
|
1158 | assert kvals[i].tag() == value_e.Str, kvals[i]
|
1159 | key = cast(value.Str, kvals[i])
|
1160 | v = self._LookupVar(key.s, loc.Missing)
|
1161 | else:
|
1162 | v = self._EvalExpr(value_expr)
|
1163 |
|
1164 | values.append(v)
|
1165 |
|
1166 | d = NewDict() # type: Dict[str, value_t]
|
1167 | for i, kval in enumerate(kvals):
|
1168 | k = val_ops.ToStr(kval, 'Dict keys must be strings',
|
1169 | loc.Missing)
|
1170 | d[k] = values[i]
|
1171 |
|
1172 | return value.Dict(d)
|
1173 |
|
1174 | elif case(expr_e.ListComp):
|
1175 | e_die_status(
|
1176 | 2, 'List comprehension reserved but not implemented')
|
1177 |
|
1178 | elif case(expr_e.GeneratorExp):
|
1179 | e_die_status(
|
1180 | 2, 'Generator expression reserved but not implemented')
|
1181 |
|
1182 | elif case(expr_e.Literal): # ^[1 + 2]
|
1183 | node = cast(expr.Literal, UP_node)
|
1184 | return value.Expr(node.inner)
|
1185 |
|
1186 | elif case(expr_e.Lambda): # |x| x+1 syntax is reserved
|
1187 | # TODO: Location information for |, or func
|
1188 | # Note: anonymous functions also evaluate to a Lambda, but they shouldn't
|
1189 | e_die_status(2, 'Lambda reserved but not implemented')
|
1190 |
|
1191 | elif case(expr_e.FuncCall):
|
1192 | node = cast(expr.FuncCall, UP_node)
|
1193 | return self._EvalFuncCall(node)
|
1194 |
|
1195 | elif case(expr_e.Subscript):
|
1196 | node = cast(Subscript, UP_node)
|
1197 | obj = self._EvalExpr(node.obj)
|
1198 | index = self._EvalExpr(node.index)
|
1199 | return self._EvalSubscript(obj, index)
|
1200 |
|
1201 | elif case(expr_e.Attribute): # obj->method or mydict.key
|
1202 | node = cast(Attribute, UP_node)
|
1203 | return self._EvalAttribute(node)
|
1204 |
|
1205 | elif case(expr_e.Eggex):
|
1206 | node = cast(Eggex, UP_node)
|
1207 | return self.EvalEggex(node)
|
1208 |
|
1209 | else:
|
1210 | raise NotImplementedError(node.__class__.__name__)
|
1211 |
|
1212 | def EvalEggex(self, node):
|
1213 | # type: (Eggex) -> value.Eggex
|
1214 |
|
1215 | # Splice, check flags consistency, and accumulate convert_funcs indexed
|
1216 | # by capture group
|
1217 | ev = EggexEvaluator(self.mem, node.canonical_flags)
|
1218 | spliced = ev.EvalE(node.regex)
|
1219 |
|
1220 | # as_ere and capture_names filled by ~ operator or Str method
|
1221 | return value.Eggex(spliced, node.canonical_flags, ev.convert_funcs,
|
1222 | ev.convert_toks, None, [])
|
1223 |
|
1224 |
|
1225 | class EggexEvaluator(object):
|
1226 |
|
1227 | def __init__(self, mem, canonical_flags):
|
1228 | # type: (state.Mem, str) -> None
|
1229 | self.mem = mem
|
1230 | self.canonical_flags = canonical_flags
|
1231 | self.convert_funcs = [] # type: List[Optional[value_t]]
|
1232 | self.convert_toks = [] # type: List[Optional[Token]]
|
1233 |
|
1234 | def _LookupVar(self, name, var_loc):
|
1235 | # type: (str, loc_t) -> value_t
|
1236 | """
|
1237 | Duplicated from ExprEvaluator
|
1238 | """
|
1239 | return LookupVar(self.mem, name, scope_e.LocalOrGlobal, var_loc)
|
1240 |
|
1241 | def _EvalClassLiteralTerm(self, term, out):
|
1242 | # type: (class_literal_term_t, List[char_class_term_t]) -> None
|
1243 | UP_term = term
|
1244 |
|
1245 | # These 2 vars will be initialized if we don't return early
|
1246 | s = None # type: str
|
1247 | char_code_tok = None # type: Token
|
1248 |
|
1249 | with tagswitch(term) as case:
|
1250 |
|
1251 | if case(class_literal_term_e.CharCode):
|
1252 | term = cast(CharCode, UP_term)
|
1253 |
|
1254 | # What about \0? At runtime, ERE should disallow it. But we
|
1255 | # can also disallow it here.
|
1256 | out.append(term)
|
1257 | return
|
1258 |
|
1259 | elif case(class_literal_term_e.CharRange):
|
1260 | term = cast(CharRange, UP_term)
|
1261 | out.append(term)
|
1262 | return
|
1263 |
|
1264 | elif case(class_literal_term_e.PosixClass):
|
1265 | term = cast(PosixClass, UP_term)
|
1266 | out.append(term)
|
1267 | return
|
1268 |
|
1269 | elif case(class_literal_term_e.PerlClass):
|
1270 | term = cast(PerlClass, UP_term)
|
1271 | out.append(term)
|
1272 | return
|
1273 |
|
1274 | elif case(class_literal_term_e.SingleQuoted):
|
1275 | term = cast(SingleQuoted, UP_term)
|
1276 |
|
1277 | s = term.sval
|
1278 | char_code_tok = term.left
|
1279 |
|
1280 | elif case(class_literal_term_e.Splice):
|
1281 | term = cast(class_literal_term.Splice, UP_term)
|
1282 |
|
1283 | val = self._LookupVar(term.var_name, term.name)
|
1284 | s = val_ops.ToStr(val, 'Eggex char class splice expected Str',
|
1285 | term.name)
|
1286 | char_code_tok = term.name
|
1287 |
|
1288 | assert s is not None, term
|
1289 | for ch in s:
|
1290 | char_int = ord(ch)
|
1291 | if char_int >= 128:
|
1292 | # / [ '\x7f\xff' ] / is better written as / [ \x7f \xff ] /
|
1293 | e_die(
|
1294 | "Use unquoted char literal for byte %d, which is >= 128"
|
1295 | " (avoid confusing a set of bytes with a sequence)" %
|
1296 | char_int, char_code_tok)
|
1297 | out.append(CharCode(char_code_tok, char_int, False))
|
1298 |
|
1299 | def EvalE(self, node):
|
1300 | # type: (re_t) -> re_t
|
1301 | """Resolve references and eval constants in an Eggex
|
1302 |
|
1303 | Rules:
|
1304 | Splice => re_t # like Hex and @const in / Hex '.' @const /
|
1305 | Speck/Token (syntax) => Primitive (logical)
|
1306 | Chars and Strings => LiteralChars
|
1307 | """
|
1308 | UP_node = node
|
1309 |
|
1310 | with tagswitch(node) as case:
|
1311 | if case(re_e.Seq):
|
1312 | node = cast(re.Seq, UP_node)
|
1313 | new_children = [self.EvalE(child) for child in node.children]
|
1314 | return re.Seq(new_children)
|
1315 |
|
1316 | elif case(re_e.Alt):
|
1317 | node = cast(re.Alt, UP_node)
|
1318 | new_children = [self.EvalE(child) for child in node.children]
|
1319 | return re.Alt(new_children)
|
1320 |
|
1321 | elif case(re_e.Repeat):
|
1322 | node = cast(re.Repeat, UP_node)
|
1323 | return re.Repeat(self.EvalE(node.child), node.op)
|
1324 |
|
1325 | elif case(re_e.Group):
|
1326 | node = cast(re.Group, UP_node)
|
1327 |
|
1328 | # placeholder for non-capturing group
|
1329 | self.convert_funcs.append(None)
|
1330 | self.convert_toks.append(None)
|
1331 | return re.Group(self.EvalE(node.child))
|
1332 |
|
1333 | elif case(re_e.Capture): # Identical to Group
|
1334 | node = cast(re.Capture, UP_node)
|
1335 | convert_func = None # type: Optional[value_t]
|
1336 | convert_tok = None # type: Optional[Token]
|
1337 | if node.func_name:
|
1338 | func_name = lexer.LazyStr(node.func_name)
|
1339 | func_val = self.mem.GetValue(func_name)
|
1340 | with tagswitch(func_val) as case:
|
1341 | if case(value_e.Func, value_e.BuiltinFunc):
|
1342 | convert_func = func_val
|
1343 | convert_tok = node.func_name
|
1344 | else:
|
1345 | raise error.TypeErr(
|
1346 | func_val,
|
1347 | "Expected %r to be a func" % func_name,
|
1348 | node.func_name)
|
1349 |
|
1350 | self.convert_funcs.append(convert_func)
|
1351 | self.convert_toks.append(convert_tok)
|
1352 | return re.Capture(self.EvalE(node.child), node.name,
|
1353 | node.func_name)
|
1354 |
|
1355 | elif case(re_e.CharClassLiteral):
|
1356 | node = cast(re.CharClassLiteral, UP_node)
|
1357 |
|
1358 | new_terms = [] # type: List[char_class_term_t]
|
1359 | for t in node.terms:
|
1360 | # can get multiple char_class_term.CharCode for a
|
1361 | # class_literal_term_t
|
1362 | self._EvalClassLiteralTerm(t, new_terms)
|
1363 | return re.CharClass(node.negated, new_terms)
|
1364 |
|
1365 | elif case(re_e.SingleQuoted):
|
1366 | node = cast(SingleQuoted, UP_node)
|
1367 |
|
1368 | s = node.sval
|
1369 | return re.LiteralChars(node.left, s)
|
1370 |
|
1371 | elif case(re_e.Splice):
|
1372 | node = cast(re.Splice, UP_node)
|
1373 |
|
1374 | val = self._LookupVar(node.var_name, node.name)
|
1375 | UP_val = val
|
1376 | with tagswitch(val) as case:
|
1377 | if case(value_e.Str):
|
1378 | val = cast(value.Str, UP_val)
|
1379 | to_splice = re.LiteralChars(node.name,
|
1380 | val.s) # type: re_t
|
1381 |
|
1382 | elif case(value_e.Eggex):
|
1383 | val = cast(value.Eggex, UP_val)
|
1384 |
|
1385 | # Splicing means we get the conversion funcs too.
|
1386 | self.convert_funcs.extend(val.convert_funcs)
|
1387 | self.convert_toks.extend(val.convert_toks)
|
1388 |
|
1389 | # Splicing requires flags to match. This check is
|
1390 | # transitive.
|
1391 | to_splice = val.spliced
|
1392 |
|
1393 | if val.canonical_flags != self.canonical_flags:
|
1394 | e_die(
|
1395 | "Expected eggex flags %r, but got %r" %
|
1396 | (self.canonical_flags, val.canonical_flags),
|
1397 | node.name)
|
1398 |
|
1399 | else:
|
1400 | raise error.TypeErr(
|
1401 | val, 'Eggex splice expected Str or Eggex',
|
1402 | node.name)
|
1403 | return to_splice
|
1404 |
|
1405 | else:
|
1406 | # These are evaluated at translation time
|
1407 |
|
1408 | # case(re_e.Primitive)
|
1409 | # case(re_e.PosixClass)
|
1410 | # case(re_e.PerlClass)
|
1411 | return node
|
1412 |
|
1413 |
|
1414 | # vim: sw=4
|