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

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