OILS / ysh / expr_eval.py View on Github | oils.pub

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