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

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