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

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