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