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

1534 lines, 1019 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, val):
974 # type: (Attribute, value_t) -> value_t
975 """ foo.attr on RHS or LHS
976
977 setvar x = foo.attr
978 setglobal g[foo.attr] = 42
979 """
980 UP_val = val
981 with tagswitch(val) as case:
982 if case(value_e.Dict):
983 val = cast(value.Dict, UP_val)
984 attr_name = node.attr_name
985
986 # Dict key / normal attribute lookup
987 result = val.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_val)
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('Attribute %r not found on Obj' % 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(val.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(val, func_val)
1023
1024 raise error.TypeErrVerbose(
1025 "Method %r not found on builtin type %s" %
1026 (name, ui.ValType(val)), node.attr)
1027
1028 raise AssertionError()
1029
1030 def _EvalRArrow(self, node, val):
1031 # type: (Attribute, value_t) -> value_t
1032 mut_name = 'M/' + node.attr_name
1033
1034 UP_val = val
1035 with tagswitch(val) as case:
1036 if case(value_e.Obj):
1037 obj = cast(Obj, UP_val)
1038
1039 if obj.prototype is not None:
1040 result = self._ChainedLookup(obj, obj.prototype, mut_name)
1041 if result is not None:
1042 return result
1043
1044 # TODO: we could have different errors for:
1045 # - no prototype
1046 # - found in the properties, not in the prototype chain (not
1047 # sure if this error is common.)
1048 raise error.Expr(
1049 "Mutating method %r not found on Obj prototype chain" % mut_name,
1050 node.attr)
1051 else:
1052 # Look up methods on builtin types
1053 # TODO: These should also be called M/append, M/erase, etc.
1054
1055 type_methods = self.methods.get(val.tag())
1056 vm_callable = (type_methods.get(mut_name)
1057 if type_methods is not None else None)
1058 if vm_callable:
1059 func_val = value.BuiltinFunc(vm_callable)
1060 return value.BoundFunc(val, func_val)
1061
1062 raise error.TypeErrVerbose(
1063 "Mutating method %r not found on builtin type %s" %
1064 (mut_name, ui.ValType(val)), node.attr)
1065 raise AssertionError()
1066
1067 def _EvalAttribute(self, node):
1068 # type: (Attribute) -> value_t
1069
1070 val = self._EvalExpr(node.obj)
1071 with switch(node.op.id) as case:
1072 if case(Id.Expr_Dot): # d.key is like d['key']
1073 return self._EvalDot(node, val)
1074
1075 elif case(Id.Expr_RArrow): # e.g. mylist->append(42)
1076 return self._EvalRArrow(node, val)
1077
1078 elif case(Id.Expr_RDArrow): # chaining s => split()
1079 name = node.attr_name
1080
1081 # Look up builtin methods, e.g.
1082 # s => strip() is like s.strip()
1083 # Note:
1084 # m => group(1) is worse than m.group(1)
1085 # This is not a transformation, but more like an attribute
1086
1087 type_methods = self.methods.get(val.tag())
1088 vm_callable = (type_methods.get(name)
1089 if type_methods is not None else None)
1090 if vm_callable:
1091 func_val = value.BuiltinFunc(vm_callable)
1092 return value.BoundFunc(val, func_val)
1093
1094 # Operator is =>, so try function chaining.
1095
1096 # Instead of str(f()) => upper()
1097 # or str(f()).upper() as in Pythohn
1098 #
1099 # It's more natural to write
1100 # f() => str() => upper()
1101
1102 # Could improve error message: may give "Undefined variable"
1103 val2 = self._LookupVar(name, node.attr)
1104
1105 with tagswitch(val2) as case2:
1106 if case2(value_e.Func, value_e.BuiltinFunc):
1107 return value.BoundFunc(val, val2)
1108 else:
1109 raise error.TypeErr(
1110 val2, 'Fat arrow => expects method or function',
1111 node.attr)
1112
1113 else:
1114 raise AssertionError(node.op)
1115 raise AssertionError()
1116
1117 def _EvalExpr(self, node):
1118 # type: (expr_t) -> value_t
1119 """Turn an expression into a value."""
1120 if 0:
1121 print('_EvalExpr()')
1122 node.PrettyPrint()
1123 print('')
1124
1125 UP_node = node
1126 with tagswitch(node) as case:
1127 if case(expr_e.Const):
1128 node = cast(expr.Const, UP_node)
1129 return self._EvalConst(node)
1130
1131 elif case(expr_e.Var):
1132 node = cast(expr.Var, UP_node)
1133 return self._LookupVar(node.name, node.left)
1134
1135 elif case(expr_e.Place):
1136 node = cast(expr.Place, UP_node)
1137 frame = self.mem.TopNamespace()
1138 return value.Place(LeftName(node.var_name, node.blame_tok),
1139 frame)
1140
1141 elif case(expr_e.CommandSub):
1142 node = cast(CommandSub, UP_node)
1143
1144 id_ = node.left_token.id
1145 if id_ == Id.Left_CaretParen: # ^(echo block literal)
1146 # TODO: Propgate location info?
1147 return value.Command(node.child)
1148 else:
1149 stdout_str = self.shell_ex.RunCommandSub(node)
1150 if id_ == Id.Left_AtParen: # @(seq 3)
1151 # YSH splitting algorithm: does not depend on IFS
1152 try:
1153 strs = j8.SplitJ8Lines(stdout_str)
1154 except error.Decode as e:
1155 # status code 4 is special, for encode/decode errors.
1156 raise error.Structured(4, e.Message(),
1157 node.left_token)
1158
1159 #strs = self.splitter.SplitForWordEval(stdout_str)
1160
1161 items = [value.Str(s)
1162 for s in strs] # type: List[value_t]
1163 return value.List(items)
1164 else:
1165 return value.Str(stdout_str)
1166
1167 elif case(expr_e.ShArrayLiteral): # var x = :| foo *.py |
1168 node = cast(ShArrayLiteral, UP_node)
1169 words = braces.BraceExpandWords(node.words)
1170 strs = self.word_ev.EvalWordSequence(words)
1171 #log('ARRAY LITERAL EVALUATED TO -> %s', strs)
1172 #return value.BashArray(strs)
1173
1174 # It's equivalent to ['foo', 'bar']
1175 items = [value.Str(s) for s in strs]
1176 return value.List(items)
1177
1178 elif case(expr_e.DoubleQuoted):
1179 node = cast(DoubleQuoted, UP_node)
1180 # In an ideal world, YSH would *statically* disallow:
1181 #
1182 # - "$@" and "${array[@]}"
1183 # - backticks like `echo hi`
1184 # - $(( 1+2 )) and $[] -- although useful for refactoring
1185 # - not sure: ${x%%} -- could disallow this
1186 # - these enters the ArgDQ state: "${a:-foo bar}" ?
1187 #
1188 # But that would complicate the parser/evaluator. So just rely
1189 # on runtime strict_array to disallow the bad parts.
1190 return value.Str(self.word_ev.EvalDoubleQuotedToString(node))
1191
1192 elif case(expr_e.SingleQuoted):
1193 node = cast(SingleQuoted, UP_node)
1194 return value.Str(node.sval)
1195
1196 elif case(expr_e.BracedVarSub):
1197 node = cast(BracedVarSub, UP_node)
1198 return value.Str(self.word_ev.EvalBracedVarSubToString(node))
1199
1200 elif case(expr_e.SimpleVarSub):
1201 node = cast(SimpleVarSub, UP_node)
1202 return value.Str(self.word_ev.EvalSimpleVarSubToString(node))
1203
1204 elif case(expr_e.Unary):
1205 node = cast(expr.Unary, UP_node)
1206 return self._EvalUnary(node)
1207
1208 elif case(expr_e.Binary):
1209 node = cast(expr.Binary, UP_node)
1210 return self._EvalBinary(node)
1211
1212 elif case(expr_e.Slice): # a[:0]
1213 node = cast(expr.Slice, UP_node)
1214
1215 lower = None # type: Optional[IntBox]
1216 upper = None # type: Optional[IntBox]
1217
1218 if node.lower:
1219 msg = 'Slice begin should be Int'
1220 i = val_ops.ToInt(self._EvalExpr(node.lower), msg,
1221 loc.Missing)
1222 lower = IntBox(i)
1223
1224 if node.upper:
1225 msg = 'Slice end should be Int'
1226 i = val_ops.ToInt(self._EvalExpr(node.upper), msg,
1227 loc.Missing)
1228 upper = IntBox(i)
1229
1230 return value.Slice(lower, upper)
1231
1232 elif case(expr_e.Range):
1233 node = cast(expr.Range, UP_node)
1234
1235 assert node.lower is not None
1236 assert node.upper is not None
1237
1238 msg = 'Range begin should be Int'
1239 i = val_ops.ToInt(self._EvalExpr(node.lower), msg, loc.Missing)
1240
1241 msg = 'Range end should be Int'
1242 j = val_ops.ToInt(self._EvalExpr(node.upper), msg, loc.Missing)
1243
1244 return value.Range(i, j)
1245
1246 elif case(expr_e.Compare):
1247 node = cast(expr.Compare, UP_node)
1248 return self._EvalCompare(node)
1249
1250 elif case(expr_e.IfExp):
1251 node = cast(expr.IfExp, UP_node)
1252 b = val_ops.ToBool(self._EvalExpr(node.test))
1253 if b:
1254 return self._EvalExpr(node.body)
1255 else:
1256 return self._EvalExpr(node.orelse)
1257
1258 elif case(expr_e.List):
1259 node = cast(expr.List, UP_node)
1260 items = [self._EvalExpr(e) for e in node.elts]
1261 return value.List(items)
1262
1263 elif case(expr_e.Tuple):
1264 node = cast(expr.Tuple, UP_node)
1265 # YSH language: Tuple syntax evaluates to LIST !
1266 items = [self._EvalExpr(e) for e in node.elts]
1267 return value.List(items)
1268
1269 elif case(expr_e.Dict):
1270 node = cast(expr.Dict, UP_node)
1271
1272 kvals = [self._EvalExpr(e) for e in node.keys]
1273 values = [] # type: List[value_t]
1274
1275 for i, value_expr in enumerate(node.values):
1276 if value_expr.tag() == expr_e.Implicit: # {key}
1277 # Enforced by parser. Key is expr.Const
1278 assert kvals[i].tag() == value_e.Str, kvals[i]
1279 key = cast(value.Str, kvals[i])
1280 v = self._LookupVar(key.s, loc.Missing)
1281 else:
1282 v = self._EvalExpr(value_expr)
1283
1284 values.append(v)
1285
1286 d = NewDict() # type: Dict[str, value_t]
1287 for i, kval in enumerate(kvals):
1288 k = val_ops.ToStr(kval, 'Dict keys must be strings',
1289 loc.Missing)
1290 d[k] = values[i]
1291
1292 return value.Dict(d)
1293
1294 elif case(expr_e.ListComp):
1295 e_die_status(
1296 2, 'List comprehension reserved but not implemented')
1297
1298 elif case(expr_e.GeneratorExp):
1299 e_die_status(
1300 2, 'Generator expression reserved but not implemented')
1301
1302 elif case(expr_e.Literal): # ^[1 + 2]
1303 node = cast(expr.Literal, UP_node)
1304 return value.Expr(node.inner)
1305
1306 elif case(expr_e.Lambda): # |x| x+1 syntax is reserved
1307 # TODO: Location information for |, or func
1308 # Note: anonymous functions also evaluate to a Lambda, but they shouldn't
1309 e_die_status(2, 'Lambda reserved but not implemented')
1310
1311 elif case(expr_e.FuncCall):
1312 node = cast(expr.FuncCall, UP_node)
1313 return self._EvalFuncCall(node)
1314
1315 elif case(expr_e.Subscript):
1316 node = cast(Subscript, UP_node)
1317 obj = self._EvalExpr(node.obj)
1318 index = self._EvalExpr(node.index)
1319 return self._EvalSubscript(obj, index)
1320
1321 elif case(expr_e.Attribute): # obj->method or mydict.key
1322 node = cast(Attribute, UP_node)
1323 return self._EvalAttribute(node)
1324
1325 elif case(expr_e.Eggex):
1326 node = cast(Eggex, UP_node)
1327 return self.EvalEggex(node)
1328
1329 else:
1330 raise NotImplementedError(node.__class__.__name__)
1331
1332 def EvalEggex(self, node):
1333 # type: (Eggex) -> value.Eggex
1334
1335 # Splice, check flags consistency, and accumulate convert_funcs indexed
1336 # by capture group
1337 ev = EggexEvaluator(self.mem, node.canonical_flags)
1338 spliced = ev.EvalE(node.regex)
1339
1340 # as_ere and capture_names filled by ~ operator or Str method
1341 return value.Eggex(spliced, node.canonical_flags, ev.convert_funcs,
1342 ev.convert_toks, None, [])
1343
1344
1345class EggexEvaluator(object):
1346
1347 def __init__(self, mem, canonical_flags):
1348 # type: (state.Mem, str) -> None
1349 self.mem = mem
1350 self.canonical_flags = canonical_flags
1351 self.convert_funcs = [] # type: List[Optional[value_t]]
1352 self.convert_toks = [] # type: List[Optional[Token]]
1353
1354 def _LookupVar(self, name, var_loc):
1355 # type: (str, loc_t) -> value_t
1356 """
1357 Duplicated from ExprEvaluator
1358 """
1359 return LookupVar(self.mem, name, scope_e.LocalOrGlobal, var_loc)
1360
1361 def _EvalClassLiteralTerm(self, term, out):
1362 # type: (class_literal_term_t, List[char_class_term_t]) -> None
1363 UP_term = term
1364
1365 # These 2 vars will be initialized if we don't return early
1366 s = None # type: str
1367 char_code_tok = None # type: Token
1368
1369 with tagswitch(term) as case:
1370
1371 if case(class_literal_term_e.CharCode):
1372 term = cast(CharCode, UP_term)
1373
1374 # What about \0? At runtime, ERE should disallow it. But we
1375 # can also disallow it here.
1376 out.append(term)
1377 return
1378
1379 elif case(class_literal_term_e.CharRange):
1380 term = cast(CharRange, UP_term)
1381 out.append(term)
1382 return
1383
1384 elif case(class_literal_term_e.PosixClass):
1385 term = cast(PosixClass, UP_term)
1386 out.append(term)
1387 return
1388
1389 elif case(class_literal_term_e.PerlClass):
1390 term = cast(PerlClass, UP_term)
1391 out.append(term)
1392 return
1393
1394 elif case(class_literal_term_e.SingleQuoted):
1395 term = cast(SingleQuoted, UP_term)
1396
1397 s = term.sval
1398 char_code_tok = term.left
1399
1400 elif case(class_literal_term_e.Splice):
1401 term = cast(class_literal_term.Splice, UP_term)
1402
1403 val = self._LookupVar(term.var_name, term.name)
1404 s = val_ops.ToStr(val, 'Eggex char class splice expected Str',
1405 term.name)
1406 char_code_tok = term.name
1407
1408 assert s is not None, term
1409 for ch in s:
1410 char_int = ord(ch)
1411 if char_int >= 128:
1412 # / [ '\x7f\xff' ] / is better written as / [ \x7f \xff ] /
1413 e_die(
1414 "Use unquoted char literal for byte %d, which is >= 128"
1415 " (avoid confusing a set of bytes with a sequence)" %
1416 char_int, char_code_tok)
1417 out.append(CharCode(char_code_tok, char_int, False))
1418
1419 def EvalE(self, node):
1420 # type: (re_t) -> re_t
1421 """Resolve references and eval constants in an Eggex
1422
1423 Rules:
1424 Splice => re_t # like Hex and @const in / Hex '.' @const /
1425 Speck/Token (syntax) => Primitive (logical)
1426 Chars and Strings => LiteralChars
1427 """
1428 UP_node = node
1429
1430 with tagswitch(node) as case:
1431 if case(re_e.Seq):
1432 node = cast(re.Seq, UP_node)
1433 new_children = [self.EvalE(child) for child in node.children]
1434 return re.Seq(new_children)
1435
1436 elif case(re_e.Alt):
1437 node = cast(re.Alt, UP_node)
1438 new_children = [self.EvalE(child) for child in node.children]
1439 return re.Alt(new_children)
1440
1441 elif case(re_e.Repeat):
1442 node = cast(re.Repeat, UP_node)
1443 return re.Repeat(self.EvalE(node.child), node.op)
1444
1445 elif case(re_e.Group):
1446 node = cast(re.Group, UP_node)
1447
1448 # placeholder for non-capturing group
1449 self.convert_funcs.append(None)
1450 self.convert_toks.append(None)
1451 return re.Group(self.EvalE(node.child))
1452
1453 elif case(re_e.Capture): # Identical to Group
1454 node = cast(re.Capture, UP_node)
1455 convert_func = None # type: Optional[value_t]
1456 convert_tok = None # type: Optional[Token]
1457 if node.func_name:
1458 func_name = lexer.LazyStr(node.func_name)
1459 func_val = self.mem.GetValue(func_name)
1460 with tagswitch(func_val) as case:
1461 if case(value_e.Func, value_e.BuiltinFunc):
1462 convert_func = func_val
1463 convert_tok = node.func_name
1464 else:
1465 raise error.TypeErr(
1466 func_val,
1467 "Expected %r to be a func" % func_name,
1468 node.func_name)
1469
1470 self.convert_funcs.append(convert_func)
1471 self.convert_toks.append(convert_tok)
1472 return re.Capture(self.EvalE(node.child), node.name,
1473 node.func_name)
1474
1475 elif case(re_e.CharClassLiteral):
1476 node = cast(re.CharClassLiteral, UP_node)
1477
1478 new_terms = [] # type: List[char_class_term_t]
1479 for t in node.terms:
1480 # can get multiple char_class_term.CharCode for a
1481 # class_literal_term_t
1482 self._EvalClassLiteralTerm(t, new_terms)
1483 return re.CharClass(node.negated, new_terms)
1484
1485 elif case(re_e.SingleQuoted):
1486 node = cast(SingleQuoted, UP_node)
1487
1488 s = node.sval
1489 return re.LiteralChars(node.left, s)
1490
1491 elif case(re_e.Splice):
1492 node = cast(re.Splice, UP_node)
1493
1494 val = self._LookupVar(node.var_name, node.name)
1495 UP_val = val
1496 with tagswitch(val) as case:
1497 if case(value_e.Str):
1498 val = cast(value.Str, UP_val)
1499 to_splice = re.LiteralChars(node.name,
1500 val.s) # type: re_t
1501
1502 elif case(value_e.Eggex):
1503 val = cast(value.Eggex, UP_val)
1504
1505 # Splicing means we get the conversion funcs too.
1506 self.convert_funcs.extend(val.convert_funcs)
1507 self.convert_toks.extend(val.convert_toks)
1508
1509 # Splicing requires flags to match. This check is
1510 # transitive.
1511 to_splice = val.spliced
1512
1513 if val.canonical_flags != self.canonical_flags:
1514 e_die(
1515 "Expected eggex flags %r, but got %r" %
1516 (self.canonical_flags, val.canonical_flags),
1517 node.name)
1518
1519 else:
1520 raise error.TypeErr(
1521 val, 'Eggex splice expected Str or Eggex',
1522 node.name)
1523 return to_splice
1524
1525 else:
1526 # These are evaluated at translation time
1527
1528 # case(re_e.Primitive)
1529 # case(re_e.PosixClass)
1530 # case(re_e.PerlClass)
1531 return node
1532
1533
1534# vim: sw=4