~andyc/oil

ref: 61e07695461bbe7b6989a3331fca16f8b87d1e2b oil/oil_lang/expr_eval.py -rw-r--r-- 22.9 KiB
61e07695 — Andy Chu [oil-language] Implement "pound" char literals like #'a' 2 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
#!/usr/bin/env python2
"""
expr_eval.py
"""
from __future__ import print_function

from _devbuild.gen.id_kind_asdl import Id, Kind
from _devbuild.gen.syntax_asdl import (
    expr_e, expr_t, re, re_e, re_t, class_literal_term, class_literal_term_e,
    place_expr_e, place_expr_t,
)
from _devbuild.gen.runtime_asdl import (
    lvalue, value, value_e, scope_e,
)
from asdl import runtime
from core.pyerror import e_die, log
from frontend import consts
from oil_lang import objects
from osh import braces
from osh import word_compile

import libc

from typing import Any, Dict, Optional, List, Union, Tuple, TYPE_CHECKING

if TYPE_CHECKING:
  from _devbuild.gen.runtime_asdl import (
      lvalue_t, lvalue__Named, lvalue__ObjIndex, lvalue__ObjAttr,
  )
  from _devbuild.gen.syntax_asdl import arg_list
  from core.vm import _Executor
  from core.ui import ErrorFormatter
  from core.state import Mem
  from osh.word_eval import StringWordEvaluator
  from osh import split

_ = log


def LookupVar(mem, var_name, which_scopes, span_id=runtime.NO_SPID):
  """Convert to a Python object so we can calculate on it natively."""

  # Lookup WITHOUT dynamic scope.
  val = mem.GetValue(var_name, which_scopes=which_scopes)
  if val.tag == value_e.Undef:
    # TODO: Location info
    e_die('Undefined variable %r', var_name, span_id=span_id)

  if val.tag == value_e.Str:
    return val.s
  if val.tag == value_e.MaybeStrArray:
    return val.strs  # node: has None
  if val.tag == value_e.AssocArray:
    return val.d
  if val.tag == value_e.Obj:
    return val.obj


class OilEvaluator(object):
  """Shared between arith and bool evaluators.

  They both:

  1. Convert strings to integers, respecting shopt -s strict_arith.
  2. Look up variables and evaluate words.
  """

  def __init__(self,
               mem,  # type: Mem
               funcs,  # type: Dict
               splitter,  # type: split.SplitContext
               errfmt,  # type: ErrorFormatter
               ):
    # type: (...) -> None
    self.shell_ex = None  # type: _Executor
    self.word_ev = None  # type: StringWordEvaluator

    self.mem = mem
    self.splitter = splitter
    self.funcs = funcs
    self.errfmt = errfmt

  def CheckCircularDeps(self):
    # type: () -> None
    assert self.shell_ex is not None
    assert self.word_ev is not None

  def LookupVar(self, name, span_id=runtime.NO_SPID):
    # type: (str, int) -> Any
    return LookupVar(self.mem, name, scope_e.LocalOrGlobal, span_id=span_id)

  def EvalPlusEquals(self, lval, rhs_py):
    # type: (lvalue_t, Union[int, float]) -> Union[int, float]
    lhs_py = self.LookupVar(lval.name)
    if not isinstance(lhs_py, (int, float)):
      # TODO: Could point at the variable name
      e_die("Object of type %r doesn't support +=", lhs_py.__class__.__name__)

    return lhs_py + rhs_py

  def EvalLHS(self, node):
    if 0:
      print('EvalLHS()')
      node.PrettyPrint()
      print('')

    if node.tag == expr_e.Var:
      return lvalue.Named(node.name.val)
    else:
      # TODO:
      # subscripts, tuple unpacking, starred expressions, etc.

      raise NotImplementedError(node.__class__.__name__)

  # Copied from BoolEvaluator
  def _EvalMatch(self, left, right, set_match_result):
    """
    Args:
      set_match_result: Whether to assign
    """
    # TODO: Rename EggEx?
    if isinstance(right, str):
      pass
    elif isinstance(right, objects.Regex):
      right = right.AsPosixEre()
    else:
      raise RuntimeError(
          "RHS of ~ should be string or Regex (got %s)" % right.__class__.__name__)
    
    # TODO: We need an API that can populate _start() and _end() too
    matches = libc.regex_match(right, left)
    if matches:
      if set_match_result:
        self.mem.SetMatches(matches)
      return True
    else:
      if set_match_result:
        self.mem.ClearMatches()
      return False

  def EvalArgList(self, args):
    # type: (arg_list) -> Tuple[List[Any], Dict[str, Any]]
    """ Used by do f(x) and echo $f(x). """
    pos_args = []
    for arg in args.positional:
      if arg.tag == expr_e.Spread:
        # assume it returns a list
        pos_args.extend(self.EvalExpr(arg.child))
      else:
        pos_args.append(self.EvalExpr(arg))

    kwargs = {}
    for arg in args.named:
      if arg.name:
        kwargs[arg.name.val] = self.EvalExpr(arg.value)
      else:
        # ...named
        kwargs.update(self.EvalExpr(arg.value))
    return pos_args, kwargs

  def _EvalIndices(self, indices):
    if len(indices) == 1:
      return self.EvalExpr(indices[0])
    else:
      # e.g. mydict[a,b]
      return tuple(self.EvalExpr(ind) for ind in indices)

  def EvalPlaceExpr(self, place):
    # type: (place_expr_t) -> Union[lvalue__Named, lvalue__ObjIndex, lvalue__ObjAttr]
    if place.tag == place_expr_e.Var:
      return lvalue.Named(place.name.val)

    if place.tag == place_expr_e.Subscript:
      obj = self.EvalExpr(place.obj)
      index = self._EvalIndices(place.indices)
      return lvalue.ObjIndex(obj, index)

    if place.tag == place_expr_e.Attribute:
      obj = self.EvalExpr(place.obj)
      if place.op.id == Id.Expr_RArrow:
        index = place.attr.val
        return lvalue.ObjIndex(obj, index)
      else:
        return lvalue.ObjAttr(obj, place.attr.val)

    raise NotImplementedError(place)

  def EvalExpr(self, node):
    # type: (expr_t) -> Any
    """
    This is a naive PyObject evaluator!  It uses the type dispatch of the host
    Python interpreter.

    Returns:
      A Python object of ANY type.  Should be wrapped in value.Obj() for
      storing in Mem.
    """
    if 0:
      print('EvalExpr()')
      node.PrettyPrint()
      print('')

    if node.tag == expr_e.Const:
      # NOTE: This could all be done at PARSE TIME / COMPILE TIME.

      # Remove underscores from 1_000_000.  The lexer is responsible for
      # validation.
      c = node.c.val.replace('_', '')

      id_ = node.c.id
      if id_ == Id.Expr_DecInt:
        return int(c)
      if id_ == Id.Expr_BinInt:
        return int(c, 2)
      if id_ == Id.Expr_OctInt:
        return int(c, 8)
      if id_ == Id.Expr_HexInt:
        return int(c, 16)

      if id_ == Id.Expr_Float:
        return float(c)

      if id_ == Id.Expr_Null:
        return None
      if id_ == Id.Expr_True:
        return True
      if id_ == Id.Expr_False:
        return False

      if id_ == Id.Expr_Name:
        # for {name: 'bob'}
        # Maybe also :Symbol?
        return node.c.val

      # These two could be done at COMPILE TIME
      if id_ == Id.Char_OneChar:
        return consts.LookupCharInt(node.c.val[1])  # It's an integer
      if id_ == Id.Char_Pound:
        # TODO: accept UTF-8 code point instead of single byte
        byte = node.c.val[2]  # the a in #'a'
        return ord(byte)  # It's an integer

      # NOTE: We could allow Ellipsis for a[:, ...] here, but we're not using
      # it yet.
      raise AssertionError(id_)

    if node.tag == expr_e.Var:
      return self.LookupVar(node.name.val, span_id=node.name.span_id)

    if node.tag == expr_e.CommandSub:
      id_ = node.left_token.id
      # &(echo block literal)
      if id_ == Id.Left_AmpParen:
        return 'TODO: value.Block'
      else:
        stdout = self.shell_ex.RunCommandSub(node)
        if id_ == Id.Left_AtParen:  # @(seq 3)
          strs = self.splitter.SplitForWordEval(stdout)
          return strs
        else:
          return stdout

    if node.tag == expr_e.ShArrayLiteral:
      words = braces.BraceExpandWords(node.words)
      strs = self.word_ev.EvalWordSequence(words)
      #log('ARRAY LITERAL EVALUATED TO -> %s', strs)
      return objects.StrArray(strs)

    if node.tag == expr_e.DoubleQuoted:
      # In an ideal world, I would *statically* disallow:
      # - "$@" and "${array[@]}"
      # - backticks like `echo hi`  
      # - $(( 1+2 )) and $[] -- although useful for refactoring
      #   - not sure: ${x%%} -- could disallow this
      #     - these enters the ArgDQ state: "${a:-foo bar}" ?
      # But that would complicate the parser/evaluator.  So just rely on
      # strict_array to disallow the bad parts.
      return self.word_ev.EvalDoubleQuotedToString(node)

    if node.tag == expr_e.SingleQuoted:
      return word_compile.EvalSingleQuoted(node)

    if node.tag == expr_e.BracedVarSub:
      return self.word_ev.EvalBracedVarSubToString(node)

    if node.tag == expr_e.SimpleVarSub:
      return self.word_ev.EvalSimpleVarSubToString(node.token)

    if node.tag == expr_e.Unary:
      child = self.EvalExpr(node.child)
      if node.op.id == Id.Arith_Minus:
        return -child
      if node.op.id == Id.Arith_Tilde:
        return ~child
      if node.op.id == Id.Expr_Not:
        return not child

      raise NotImplementedError(node.op.id)

    if node.tag == expr_e.Binary:
      left = self.EvalExpr(node.left)
      right = self.EvalExpr(node.right)

      if node.op.id == Id.Arith_Plus:
        return left + right
      if node.op.id == Id.Arith_Minus:
        return left - right
      if node.op.id == Id.Arith_Star:
        return left * right
      if node.op.id == Id.Arith_Slash:
        # NOTE: from __future__ import division changes 5/2!
        # But just make it explicit.
        return float(left) / right  # floating point division

      if node.op.id == Id.Expr_DSlash:
        return left // right  # integer divison
      if node.op.id == Id.Arith_Percent:
        return left % right

      if node.op.id == Id.Arith_DStar:  # Exponentiation
        return left ** right

      if node.op.id == Id.Arith_DPlus:
        # list or string concatenation
        return left + right

      # Bitwise
      if node.op.id == Id.Arith_Amp:
        return left & right
      if node.op.id == Id.Arith_Pipe:
        return left | right
      if node.op.id == Id.Arith_Caret:
        return left ^ right
      if node.op.id == Id.Arith_DGreat:
        return left >> right
      if node.op.id == Id.Arith_DLess:
        return left << right

      # Logical
      if node.op.id == Id.Expr_And:
        return left and right
      if node.op.id == Id.Expr_Or:
        return left or right

      raise NotImplementedError(node.op.id)

    if node.tag == expr_e.Range:  # 1:10  or  1:10:2
      lower = self.EvalExpr(node.lower)
      upper = self.EvalExpr(node.upper)
      return xrange(lower, upper)

    if node.tag == expr_e.Slice:  # a[:0]
      lower = self.EvalExpr(node.lower) if node.lower else None
      upper = self.EvalExpr(node.upper) if node.upper else None
      return slice(lower, upper)

    if node.tag == expr_e.Compare:
      left = self.EvalExpr(node.left)
      result = True  # Implicit and
      for op, right_expr in zip(node.ops, node.comparators):

        right = self.EvalExpr(right_expr)

        if op.id == Id.Arith_Less:
          result = left < right
        elif op.id == Id.Arith_Great:
          result = left > right
        elif op.id == Id.Arith_GreatEqual:
          result = left >= right
        elif op.id == Id.Arith_LessEqual:
          result = left <= right

        elif op.id == Id.Arith_DEqual:
          result = left == right
        elif op.id == Id.Arith_NEqual:
          result = left != right

        elif op.id == Id.Expr_In:
          result = left in right
        elif op.id == Id.Node_NotIn:
          result = left not in right

        elif op.id == Id.Expr_Is:
          result = left is right
        elif op.id == Id.Node_IsNot:
          result = left is not right

        elif op.id == Id.Expr_DTilde:
          # no extglob in Oil language; use eggex
          return libc.fnmatch(right, left, False)
        elif op.id == Id.Expr_NotDTilde:
          return not libc.fnmatch(right, left, False)

        elif op.id == Id.Expr_TildeDEqual:
          # Approximate equality
          e_die('~== not implemented')

        else:
          try:
            if op.id == Id.Arith_Tilde:
              result = self._EvalMatch(left, right, True)

            elif op.id == Id.Expr_NotTilde:
              result = not self._EvalMatch(left, right, False)

            else:
              raise AssertionError(op.id)
          except RuntimeError as e:
            # Status 2 indicates a regex parse error.  This is fatal in OSH but
            # not in bash, which treats [[ like a command with an exit code.
            e_die("Invalid regex %r", right, span_id=op.span_id, status=2)

        if not result:
          return result

        left = right
      return result
 
    if node.tag == expr_e.IfExp:
      b = self.EvalExpr(node.test)
      if b:
        return self.EvalExpr(node.body)
      else:
        return self.EvalExpr(node.orelse)

    if node.tag == expr_e.List:
      return [self.EvalExpr(e) for e in node.elts]

    if node.tag == expr_e.Tuple:
      return tuple(self.EvalExpr(e) for e in node.elts)

    if node.tag == expr_e.Dict:
      # NOTE: some keys are expr.Const
      keys = [self.EvalExpr(e) for e in node.keys]

      values = []
      for i, e in enumerate(node.values):
        if e.tag == expr_e.Implicit:
          v = self.LookupVar(keys[i])  # {name}
        else:
          v = self.EvalExpr(e)
        values.append(v)

      return dict(zip(keys, values))

    if node.tag == expr_e.ListComp:

      # TODO:
      # - Consolidate with command_e.OilForIn in osh/cmd_eval.py?
      # - Do I have to push a temp frame here?
      #   Hm... lexical or dynamic scope is an issue.
      result = []
      comp = node.generators[0]
      obj = self.EvalExpr(comp.iter)

      # TODO: Handle x,y etc.
      iter_name = comp.lhs[0].name.val

      if isinstance(obj, str):
        e_die("Strings aren't iterable")
      else:
        it = obj.__iter__()

      while True:
        try:
          loop_val = it.next()  # e.g. x
        except StopIteration:
          break
        self.mem.SetValue(
            lvalue.Named(iter_name), value.Obj(loop_val), scope_e.LocalOnly)

        if comp.cond:
          b = self.EvalExpr(comp.cond)
        else:
          b = True

        if b:
          item = self.EvalExpr(node.elt)  # e.g. x*2
          result.append(item)

      return result

    if node.tag == expr_e.GeneratorExp:
      comp = node.generators[0]
      obj = self.EvalExpr(comp.iter)

      # TODO: Support (x for x, y in ...)
      iter_name = comp.lhs[0].name.val

      it = obj.__iter__()

      # TODO: There is probably a much better way to do this!
      #       The scope of the loop variable is wrong, etc.

      def _gen():
        while True:
          try:
            loop_val = it.next()  # e.g. x
          except StopIteration:
            break
          self.mem.SetValue(
              lvalue.Named(iter_name), value.Obj(loop_val), scope_e.LocalOnly)

          if comp.cond:
            b = self.EvalExpr(comp.cond)
          else:
            b = True

          if b:
            item = self.EvalExpr(node.elt)  # e.g. x*2
            yield item

      return _gen()

    if node.tag == expr_e.Lambda:
      raise NotImplementedError()
      # This used to depend on cmd_ev, but we no longer have it.
      #return objects.Lambda(node, None)

    if node.tag == expr_e.FuncCall:
      func = self.EvalExpr(node.func)
      pos_args, named_args = self.EvalArgList(node.args)
      ret = func(*pos_args, **named_args)
      return ret

    if node.tag == expr_e.Subscript:
      obj = self.EvalExpr(node.obj)
      index = self._EvalIndices(node.indices)
      return obj[index]

    # Note: This is only for the obj.method() case.  We will probably change
    # the AST and get rid of getattr().
    if node.tag == expr_e.Attribute:  # obj.attr 
      o = self.EvalExpr(node.obj)
      id_ = node.op.id
      if id_ == Id.Expr_Dot:
        # Used for .startswith()
        name = node.attr.val
        return getattr(o, name)

      if id_ == Id.Expr_RArrow:  # d->key is like d['key']
        name = node.attr.val
        return o[name]

      if id_ == Id.Expr_DColon:  # StaticName::member
        raise NotImplementedError(id_)

        # TODO: We should prevent virtual lookup here?  This is a pure static
        # namespace lookup?
        # But Python doesn't any hook for this.
        # Maybe we can just check that it's a module?  And modules don't lookup
        # in a supertype or __class__, etc.

      raise AssertionError(id_)

    if node.tag == expr_e.RegexLiteral:  # obj.attr 
      # TODO: Should this just be an object that ~ calls?
      return objects.Regex(self.EvalRegex(node.regex))

    if node.tag == expr_e.ArrayLiteral:  # obj.attr 
      items = [self.EvalExpr(item) for item in node.items]
      if items:
        # Determine type at runtime?  If we have something like @[(i) (j)]
        # then we don't know its type until runtime.

        first = items[0]
        if isinstance(first, bool):
          return objects.BoolArray(bool(x) for x in items)
        elif isinstance(first, int):
          return objects.IntArray(int(x) for x in items)
        elif isinstance(first, float):
          return objects.FloatArray(float(x) for x in items)
        elif isinstance(first, str):
          return objects.StrArray(str(x) for x in items)
        else:
          raise AssertionError(first)
      else:
        # TODO: Should this have an unknown type?
        # What happens when you mutate or extend it?  You have to make sure
        # that the type tags match?
        return objects.BoolArray(items)

    raise NotImplementedError(node.__class__.__name__)

  def _EvalClassLiteralPart(self, part):
    # TODO: You can RESOLVE strings -> literal
    # Technically you can also @ if it contains exactly ONE CharClassLiteral?
    # But leave it out for now.

    return part

    raise NotImplementedError(part.__class__.__name__)

  def _MaybeReplaceLeaf(self, node):
    # type: (re_t) -> Tuple[Optional[re_t], bool]
    """
    If a leaf node needs to be evaluated, do it and return the replacement.
    Otherwise return None.
    """
    new_leaf = None
    recurse = True

    if node.tag == re_e.Speck:
      id_ = node.id
      if id_ == Id.Expr_Dot:
        new_leaf = re.Primitive(Id.Re_Dot)
      elif id_ == Id.Arith_Caret:  # ^
        new_leaf = re.Primitive(Id.Re_Start)
      elif id_ == Id.Expr_Dollar:  # $
        new_leaf = re.Primitive(Id.Re_End)
      else:
        raise NotImplementedError(id_)

    elif node.tag == re_e.Token:
      id_ = node.id
      val = node.val

      if id_ == Id.Expr_Name:
        if val == 'dot':
          new_leaf = re.Primitive(Id.Re_Dot)
        else:
          raise NotImplementedError(val)

      elif id_ == Id.Expr_Symbol:
        if val == '%start':
          new_leaf = re.Primitive(Id.Re_Start)
        elif val == '%end':
          new_leaf = re.Primitive(Id.Re_End)
        else:
          raise NotImplementedError(val)

      else:  # Must be Id.Char_{OneChar,Hex,Unicode4,Unicode8}
        kind = consts.GetKind(id_)
        assert kind == Kind.Char, id_
        s = word_compile.EvalCStringToken(node)
        new_leaf = re.LiteralChars(s, node.span_id)

    elif node.tag == re_e.SingleQuoted:
      s = word_compile.EvalSingleQuoted(node)
      new_leaf = re.LiteralChars(s, node.left.span_id)

    elif node.tag == re_e.DoubleQuoted:
      s = self.word_ev.EvalDoubleQuotedToString(node)
      new_leaf = re.LiteralChars(s, node.left.span_id)

    elif node.tag == re_e.BracedVarSub:
      s = self.word_ev.EvalBracedVarSubToString(node)
      new_leaf = re.LiteralChars(s, node.spids[0])

    elif node.tag == re_e.SimpleVarSub:
      s = self.word_ev.EvalSimpleVarSubToString(node.token)
      new_leaf = re.LiteralChars(s, node.token.span_id)

    elif node.tag == re_e.Splice:
      obj = self.LookupVar(node.name.val, span_id=node.name.span_id)
      if not isinstance(obj, objects.Regex):
        e_die("Can't splice object of type %r into regex", obj.__class__,
              token=node.name)
      # Note: we only splice the regex, and ignore flags.
      # Should we warn about this?
      new_leaf = obj.regex

    # These are leaves we don't need to do anything with.
    elif node.tag == re_e.PosixClass:
      recurse = False
    elif node.tag == re_e.PerlClass:
      recurse = False

    return new_leaf, recurse

  def _MutateChildren(self, children):
    # type: (List[re_t]) -> None
    """
    """
    for i, c in enumerate(children):
      new_leaf, recurse = self._MaybeReplaceLeaf(c)
      if new_leaf:
        children[i] = new_leaf
      elif recurse:
        self._MutateSubtree(c)

  def _MutateClassLiteral(self, node):
    # type: (re_t) -> None
    for i, term in enumerate(node.terms):
      s = None
      if term.tag == class_literal_term_e.SingleQuoted:
        s = word_compile.EvalSingleQuoted(term)
        spid = term.left.span_id

      elif term.tag == class_literal_term_e.DoubleQuoted:
        s = self.word_ev.EvalDoubleQuotedToString(term)
        spid = term.left.span_id

      elif term.tag == class_literal_term_e.BracedVarSub:
        s = self.word_ev.EvalBracedVarSubToString(term)
        spid = term.spids[0]

      elif term.tag == class_literal_term_e.SimpleVarSub:
        s = self.word_ev.EvalSimpleVarSubToString(term.token)
        spid = term.token.span_id

      elif term.tag == class_literal_term_e.CharLiteral:
        # What about \0?
        # At runtime, ERE should disallow it.  But we can also disallow it here.
        new_leaf = word_compile.EvalCharLiteralForRegex(term.tok)
        if new_leaf:
          node.terms[i] = new_leaf

      if s is not None:
        # A string like '\x7f\xff' should be presented like
        if len(s) > 1:
          for c in s:
            if ord(c) > 128:
              e_die("Express these bytes as character literals to avoid "
                    "confusing them with encoded characters", span_id=spid)

        node.terms[i] = class_literal_term.ByteSet(s, spid)

  def _MutateSubtree(self, node):
    if node.tag == re_e.Seq:
      self._MutateChildren(node.children)
      return

    if node.tag == re_e.Alt:
      self._MutateChildren(node.children)
      return

    if node.tag == re_e.Repeat:
      new_leaf, recurse = self._MaybeReplaceLeaf(node.child)
      if new_leaf:
        node.child = new_leaf
      elif recurse:
        self._MutateSubtree(node.child)
      return

    # TODO: How to consolidate this code with the above?
    if node.tag in (re_e.Group, re_e.Capture):
      new_leaf, recurse = self._MaybeReplaceLeaf(node.child)
      if new_leaf:
        node.child = new_leaf
      elif recurse:
        self._MutateSubtree(node.child)
      return

    elif node.tag == re_e.ClassLiteral:
      self._MutateClassLiteral(node)
      return

    elif node.tag == re_e.LiteralChars:
      # No children
      return

    raise NotImplementedError(node.__class__.__name__)

  def EvalRegex(self, node):
    # type: (re_t) -> re_t
    """
    Resolve the references in an eggex, e.g. Hex and $const in
    
    / Hex '.' $const "--$const" /
    """
    # Regex Evaluation Shares the Same Structure, but uses slightly different 
    # nodes.
    # * Speck/Token (syntactic concepts) -> Primitive (logical)
    # * Splice -> Resolved
    # * All Strings -> Literal

    new_leaf, recurse = self._MaybeReplaceLeaf(node)
    if new_leaf:
      return new_leaf
    elif recurse:
      self._MutateSubtree(node)

    # View it after evaluation
    if 0:
      log('After evaluation:')
      node.PrettyPrint(); print()
    return node