OILS / ysh / expr_eval.py View on Github | oilshell.org

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