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

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