forked from oils-for-unix/oils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcmd_eval.py
executable file
·1760 lines (1484 loc) · 59.9 KB
/
cmd_eval.py
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
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python2
# Copyright 2016 Andy Chu. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
"""
cmd_eval.py -- Interpreter for the command language.
Problems:
$ < Makefile cat | < NOTES.txt head
This just does head? Last one wins.
"""
from __future__ import print_function
import sys
from _devbuild.gen.id_kind_asdl import Id, Id_str
from _devbuild.gen.syntax_asdl import (
compound_word,
command_e, command_t,
command__AndOr,
command__Case,
command__CommandList,
command__ControlFlow,
command__DBracket,
command__DoGroup,
command__DParen,
command__ExpandedAlias,
command__Expr,
command__ForEach,
command__ForExpr,
command__Func,
command__If,
command__NoOp,
command__OilCondition,
command__OilForIn,
command__Pipeline,
command__PlaceMutation,
command__Proc,
command__Return,
command__Sentence,
command__ShAssignment,
command__ShFunction,
command__Simple,
command__Subshell,
command__TimeBlock,
command__VarDecl,
command__WhileUntil,
BraceGroup,
assign_op_e,
place_expr__Var,
proc_sig_e, proc_sig__Closed,
redir_param_e, redir_param__MultiLine,
)
from _devbuild.gen.runtime_asdl import (
quote_e,
lvalue, lvalue_e, lvalue__ObjIndex, lvalue__ObjAttr,
value, value_e, value_t, value__Int, value__Str, value__MaybeStrArray,
redirect, redirect_arg, scope_e,
cmd_value_e, cmd_value__Argv, cmd_value__Assign,
)
from _devbuild.gen.types_asdl import redir_arg_type_e
from asdl import runtime
from core import error
from core.error import _ControlFlow
from core import pyos # Time(). TODO: rename
from core import state
from core import ui
from core import util
from core.pyerror import log, e_die
from frontend import consts
from oil_lang import objects
from osh import braces
from osh import sh_expr_eval
from osh import word_
from mycpp import mylib
from mycpp.mylib import switch, tagswitch
import posix_ as posix
import libc # for fnmatch
from typing import List, Dict, Tuple, Any, cast, TYPE_CHECKING
if TYPE_CHECKING:
from _devbuild.gen.id_kind_asdl import Id_t
from _devbuild.gen.option_asdl import builtin_t
from _devbuild.gen.runtime_asdl import (
cmd_value_t, cell, lvalue_t,
)
from _devbuild.gen.syntax_asdl import (
redir, expr__Lambda, env_pair, proc_sig__Closed,
)
from core.alloc import Arena
from core import dev
from core import optview
from core.vm import _Executor, _AssignBuiltin
from oil_lang import expr_eval
from osh import word_eval
from osh import builtin_process
# flags for main_loop.Batch, ExecuteAndCatch. TODO: Should probably in
# ExecuteAndCatch, along with SetVar() flags.
IsMainProgram = 1 << 0 # the main shell program, not eval/source/subshell
IsEvalSource = 1 << 1 # eval/source builtins
Optimize = 1 << 2
# Python type name -> Oil type name
OIL_TYPE_NAMES = {
'bool': 'Bool',
'int': 'Int',
'float': 'Float',
'str': 'Str',
'tuple': 'Tuple',
'list': 'List',
'dict': 'Dict',
}
# These are nodes that execute more than one COMMAND. DParen doesn't
# count because there are no commands.
# - AndOr has multiple commands, but uses exit code in boolean way
_DISALLOWED = [
command_e.DoGroup, # covers ForEach and ForExpr, but not WhileUntil/If
command_e.BraceGroup, command_e.Subshell,
command_e.WhileUntil, command_e.If, command_e.Case,
command_e.TimeBlock,
# BUG: This happens in 'if echo $(echo hi; false)'
# but not in 'if echo $(false)'
# Because the CommandSub has no CommandList!
# This also doesn't work bceause the CommandList is inside the
# SubProgramThunk, and doesn't abort the rest of the program!
command_e.CommandList,
]
def _DisallowErrExit(node):
# type: (command_t) -> bool
tag = node.tag_()
if tag in _DISALLOWED:
return True
UP_node = node # type: command_t
# '! foo' is a pipeline according to the POSIX shell grammar, but it's NOT
# disallowed! It's not more than one command.
if tag == command_e.Pipeline:
node = cast(command__Pipeline, UP_node)
return len(node.children) > 1
return False
class Deps(object):
def __init__(self):
# type: () -> None
self.mutable_opts = None # type: state.MutableOpts
self.dumper = None # type: dev.CrashDumper
self.debug_f = None # type: util._DebugFile
# signal/hook name -> handler
self.traps = None # type: Dict[str, builtin_process._TrapHandler]
# appended to by signal handlers
self.trap_nodes = None # type: List[command_t]
if mylib.PYTHON:
def _PyObjectToVal(py_val):
# type: (Any) -> Any
"""
Maintain the 'value' invariant in osh/runtime.asdl.
TODO: Move this to Mem and combine with LookupVar in oil_lang/expr_eval.py.
They are opposites.
"""
if isinstance(py_val, str): # var s = "hello $name"
val = value.Str(py_val) # type: Any
elif isinstance(py_val, objects.StrArray): # var a = @(a b)
# It's safe to convert StrArray to MaybeStrArray.
val = value.MaybeStrArray(py_val)
elif isinstance(py_val, dict): # var d = {name: "bob"}
# TODO: Is this necessary? Shell assoc arrays aren't nested and don't have
# arbitrary values.
val = value.AssocArray(py_val)
else:
val = value.Obj(py_val)
return val
def _PackFlags(keyword_id, flags=0):
# type: (Id_t, int) -> int
# Set/Clear are lower 8 bits, and keyword is the rest
return (keyword_id << 8) | flags
class CommandEvaluator(object):
"""Executes the program by tree-walking.
It also does some double-dispatch by passing itself into Eval() for
Compound/WordPart.
"""
def __init__(self,
mem, # type: state.Mem
exec_opts, # type: optview.Exec
errfmt, # type: ui.ErrorFormatter
procs, # type: Dict[str, command__ShFunction]
assign_builtins, # type: Dict[builtin_t, _AssignBuiltin]
arena, # type: Arena
cmd_deps, # type: Deps
):
# type: (...) -> None
"""
Args:
mem: Mem instance for storing variables
procs: dict of SHELL functions or 'procs'
builtins: dict of builtin callables
TODO: This should only be for assignment builtins?
cmd_deps: A bundle of stateless code
"""
self.shell_ex = None # type: _Executor
self.arith_ev = None # type: sh_expr_eval.ArithEvaluator
self.bool_ev = None # type: sh_expr_eval.BoolEvaluator
self.expr_ev = None # type: expr_eval.OilEvaluator
self.word_ev = None # type: word_eval.AbstractWordEvaluator
self.tracer = None # type: dev.Tracer
self.mem = mem
# This is for shopt and set -o. They are initialized by flags.
self.exec_opts = exec_opts
self.errfmt = errfmt
self.procs = procs
self.assign_builtins = assign_builtins
self.arena = arena
self.mutable_opts = cmd_deps.mutable_opts
self.dumper = cmd_deps.dumper
self.debug_f = cmd_deps.debug_f # Used by ShellFuncAction too
self.traps = cmd_deps.traps
self.trap_nodes = cmd_deps.trap_nodes
self.loop_level = 0 # for detecting bad top-level break/continue
self.check_command_sub_status = False # a hack. Modified by ShellExecutor
def CheckCircularDeps(self):
# type: () -> None
assert self.arith_ev is not None
assert self.bool_ev is not None
# Disabled for push OSH
#assert self.expr_ev is not None
assert self.word_ev is not None
def _RunAssignBuiltin(self, cmd_val):
# type: (cmd_value__Assign) -> int
"""Run an assignment builtin. Except blocks copied from RunBuiltin."""
self.errfmt.PushLocation(cmd_val.arg_spids[0]) # default
builtin_func = self.assign_builtins.get(cmd_val.builtin_id)
if builtin_func is None:
# This only happens with alternative Oil interpreters.
e_die("Assignment builtin %r not configured",
cmd_val.argv[0], span_id=cmd_val.arg_spids[0])
try:
status = builtin_func.Run(cmd_val)
except error.Usage as e: # Copied from RunBuiltin
arg0 = cmd_val.argv[0]
if e.span_id == runtime.NO_SPID: # fill in default location.
e.span_id = self.errfmt.CurrentLocation()
self.errfmt.PrefixPrint(e.msg, prefix='%r ' % arg0, span_id=e.span_id)
status = 2 # consistent error code for usage error
except KeyboardInterrupt:
if self.exec_opts.interactive():
print('') # newline after ^C
status = 130 # 128 + 2 for SIGINT
else:
raise
finally:
try:
sys.stdout.flush()
except IOError as e:
pass
self.errfmt.PopLocation()
return status
# TODO: Also change to BareAssign (set global or mutate local) and
# KeywordAssign. The latter may have flags too.
def _SpanIdForShAssignment(self, node):
# type: (command__ShAssignment) -> int
# TODO: Share with tracing (SetCurrentSpanId) and _CheckStatus
return node.spids[0]
def _CheckStatus(self, status, node):
# type: (int, command_t) -> None
"""Raises ErrExitFailure, maybe with location info attached."""
if self.exec_opts.errexit() and status != 0:
# NOTE: Sometimes location info is duplicated, like on UsageError, or a
# bad redirect. Also, pipelines can fail twice.
UP_node = node
with tagswitch(node) as case:
if case(command_e.Simple):
node = cast(command__Simple, UP_node)
reason = 'command in '
span_id = word_.LeftMostSpanForWord(node.words[0])
elif case(command_e.ShAssignment):
node = cast(command__ShAssignment, UP_node)
reason = 'assignment in '
span_id = self._SpanIdForShAssignment(node)
elif case(command_e.Subshell):
node = cast(command__Subshell, UP_node)
reason = 'subshell invoked from '
span_id = node.spids[0]
elif case(command_e.Pipeline):
node = cast(command__Pipeline, UP_node)
# The whole pipeline can fail separately
reason = 'pipeline invoked from '
span_id = node.spids[0] # only one spid
else:
# NOTE: The fallback of CurrentSpanId() fills this in.
reason = ''
span_id = runtime.NO_SPID
raise error.ErrExit(
'Exiting with status %d (%sPID %d)' % (status, reason, posix.getpid()),
span_id=span_id, status=status)
def _EvalRedirect(self, r):
# type: (redir) -> redirect
result = redirect(r.op.id, r.op.span_id, r.loc, None)
arg = r.arg
UP_arg = arg
with tagswitch(arg) as case:
if case(redir_param_e.Word):
arg_word = cast(compound_word, UP_arg)
# note: needed for redirect like 'echo foo > x$LINENO'
self.mem.SetCurrentSpanId(r.op.span_id)
redir_type = consts.RedirArgType(r.op.id) # could be static in the LST?
if redir_type == redir_arg_type_e.Path:
# NOTES
# - no globbing. You can write to a file called '*.py'.
# - set -o strict-array prevents joining by spaces
val = self.word_ev.EvalWordToString(arg_word)
filename = val.s
if len(filename) == 0:
# Whether this is fatal depends on errexit.
raise error.RedirectEval(
"Redirect filename can't be empty", word=arg_word)
result.arg = redirect_arg.Path(filename)
return result
elif redir_type == redir_arg_type_e.Desc: # e.g. 1>&2, 1>&-, 1>&2-
val = self.word_ev.EvalWordToString(arg_word)
t = val.s
if len(t) == 0:
raise error.RedirectEval(
"Redirect descriptor can't be empty", word=arg_word)
return None
try:
if t == '-':
result.arg = redirect_arg.CloseFd()
elif t[-1] == '-':
target_fd = int(t[:-1])
result.arg = redirect_arg.MoveFd(target_fd)
else:
result.arg = redirect_arg.CopyFd(int(t))
except ValueError:
raise error.RedirectEval(
'Invalid descriptor %r. Expected D, -, or D- where D is an '
'integer' % t, word=arg_word)
return None
return result
elif redir_type == redir_arg_type_e.Here: # here word
val = self.word_ev.EvalWordToString(arg_word)
assert val.tag_() == value_e.Str, val
# NOTE: bash and mksh both add \n
result.arg = redirect_arg.HereDoc(val.s + '\n')
return result
else:
raise AssertionError('Unknown redirect op')
elif case(redir_param_e.MultiLine):
arg = cast(redir_param__MultiLine, UP_arg)
w = compound_word(arg.stdin_parts) # HACK: Wrap it in a word to eval
val = self.word_ev.EvalWordToString(w)
assert val.tag_() == value_e.Str, val
result.arg = redirect_arg.HereDoc(val.s)
return result
else:
raise AssertionError('Unknown redirect type')
def _EvalRedirects(self, node):
# type: (command_t) -> List[redirect]
"""Evaluate redirect nodes to concrete objects.
We have to do this every time, because you could have something like:
for i in a b c; do
echo foo >$i
done
Does it makes sense to just have RedirectNode.Eval? Nah I think the
Redirect() abstraction in process.py is useful. It has a lot of methods.
Raises:
error.RedirectEval
"""
# This is kind of lame because we have two switches over command_e: one for
# redirects, and to evaluate the node. But it's what you would do in C++ I
# suppose. We could also inline them. Or maybe use RAII.
UP_node = node
with tagswitch(node) as case:
if case(command_e.Simple):
node = cast(command__Simple, UP_node)
redirects = node.redirects
elif case(command_e.ExpandedAlias):
node = cast(command__ExpandedAlias, UP_node)
redirects = node.redirects
elif case(command_e.ShAssignment):
node = cast(command__ShAssignment, UP_node)
redirects = node.redirects
elif case(command_e.BraceGroup):
node = cast(BraceGroup, UP_node)
redirects = node.redirects
elif case(command_e.Subshell):
node = cast(command__Subshell, UP_node)
redirects = node.redirects
elif case(command_e.DParen):
node = cast(command__DParen, UP_node)
redirects = node.redirects
elif case(command_e.DBracket):
node = cast(command__DBracket, UP_node)
redirects = node.redirects
elif case(command_e.ForEach):
node = cast(command__ForEach, UP_node)
redirects = node.redirects
elif case(command_e.ForExpr):
node = cast(command__ForExpr, UP_node)
redirects = node.redirects
elif case(command_e.WhileUntil):
node = cast(command__WhileUntil, UP_node)
redirects = node.redirects
elif case(command_e.If):
node = cast(command__If, UP_node)
redirects = node.redirects
elif case(command_e.Case):
node = cast(command__Case, UP_node)
redirects = node.redirects
else:
raise AssertionError()
result = [] # type: List[redirect]
for redir in redirects:
result.append(self._EvalRedirect(redir))
return result
def _RunSimpleCommand(self, cmd_val, do_fork):
# type: (cmd_value_t, bool) -> int
"""Private interface to run a simple command (including assignment)."""
UP_cmd_val = cmd_val
with tagswitch(UP_cmd_val) as case:
if case(cmd_value_e.Argv):
cmd_val = cast(cmd_value__Argv, UP_cmd_val)
return self.shell_ex.RunSimpleCommand(cmd_val, do_fork)
elif case(cmd_value_e.Assign):
cmd_val = cast(cmd_value__Assign, UP_cmd_val)
return self._RunAssignBuiltin(cmd_val)
else:
raise AssertionError()
def _EvalTempEnv(self, more_env, flags):
# type: (List[env_pair], int) -> None
"""For FOO=1 cmd."""
for e_pair in more_env:
val = self.word_ev.EvalWordToString(e_pair.val)
# Set each var so the next one can reference it. Example:
# FOO=1 BAR=$FOO ls /
self.mem.SetVar(lvalue.Named(e_pair.name), val, scope_e.LocalOnly,
flags=flags)
def _Dispatch(self, node):
# type: (command_t) -> Tuple[int, bool]
# If we call RunCommandSub in a recursive call to the executor, this will
# be set true (if strict-errexit is false). But it only lasts for one
# command.
self.check_command_sub_status = False
#argv0 = None # for error message
check_errexit = False # for errexit
UP_node = node
with tagswitch(node) as case:
if case(command_e.Simple):
node = cast(command__Simple, UP_node)
check_errexit = True
# Find span_id for a basic implementation of $LINENO, e.g.
# PS4='+$SOURCE_NAME:$LINENO:'
# Note that for '> $LINENO' the span_id is set in _EvalRedirect.
# TODO: Can we avoid setting this so many times? See issue #567.
if len(node.words):
span_id = word_.LeftMostSpanForWord(node.words[0])
# Special case for __cat < file: leave it at the redirect.
if span_id != runtime.NO_SPID:
self.mem.SetCurrentSpanId(span_id)
# PROBLEM: We want to log argv in 'xtrace' mode, but we may have already
# redirected here, which screws up logging. For example, 'echo hi
# >/dev/null 2>&1'. We want to evaluate argv and log it BEFORE applying
# redirects.
# Another problem:
# - tracing can be called concurrently from multiple processes, leading
# to overlap. Maybe have a mode that creates a file per process.
# xtrace-proc
# - line numbers for every command would be very nice. But then you have
# to print the filename too.
words = braces.BraceExpandWords(node.words)
# note: we could catch the 'failglob' exception here and return 1.
cmd_val = self.word_ev.EvalWordSequence2(words, allow_assign=True)
UP_cmd_val = cmd_val
if UP_cmd_val.tag_() == cmd_value_e.Argv:
cmd_val = cast(cmd_value__Argv, UP_cmd_val)
argv = cmd_val.argv
cmd_val.block = node.block # may be None
else:
argv = ['TODO: trace string for assignment']
if node.block:
e_die("ShAssignment builtins don't accept blocks",
span_id=node.block.spids[0])
# This comes before evaluating env, in case there are problems evaluating
# it. We could trace the env separately? Also trace unevaluated code
# with set-o verbose?
self.tracer.OnSimpleCommand(argv)
# NOTE: RunSimpleCommand never returns when do_fork=False!
if len(node.more_env): # I think this guard is necessary?
is_other_special = False # TODO: There are other special builtins too!
if cmd_val.tag_() == cmd_value_e.Assign or is_other_special:
# Special builtins have their temp env persisted.
self._EvalTempEnv(node.more_env, 0)
status = self._RunSimpleCommand(cmd_val, node.do_fork)
else:
with state.ctx_Temp(self.mem):
self._EvalTempEnv(node.more_env, state.SetExport)
status = self._RunSimpleCommand(cmd_val, node.do_fork)
else:
status = self._RunSimpleCommand(cmd_val, node.do_fork)
elif case(command_e.ExpandedAlias):
node = cast(command__ExpandedAlias, UP_node)
# Expanded aliases need redirects and env bindings from the calling
# context, as well as redirects in the expansion!
# TODO: SetCurrentSpanId to OUTSIDE? Don't bother with stuff inside
# expansion, since aliases are discouarged.
if len(node.more_env):
with state.ctx_Temp(self.mem):
self._EvalTempEnv(node.more_env, state.SetExport)
status = self._Execute(node.child)
else:
status = self._Execute(node.child)
elif case(command_e.Sentence):
node = cast(command__Sentence, UP_node)
# Don't check_errexit since this isn't a real node!
if node.terminator.id == Id.Op_Semi:
status = self._Execute(node.child)
else:
status = self.shell_ex.RunBackgroundJob(node.child)
elif case(command_e.Pipeline):
node = cast(command__Pipeline, UP_node)
check_errexit = True
if len(node.stderr_indices):
e_die("|& isn't supported", span_id=node.spids[0])
if node.negated:
with state.ctx_ErrExit(self.mutable_opts, node.spids[0]): # ! spid
status2 = self.shell_ex.RunPipeline(node)
# errexit is disabled for !.
check_errexit = False
status = 1 if status2 == 0 else 0
else:
status = self.shell_ex.RunPipeline(node)
elif case(command_e.Subshell):
node = cast(command__Subshell, UP_node)
check_errexit = True
status = self.shell_ex.RunSubshell(node)
elif case(command_e.DBracket):
node = cast(command__DBracket, UP_node)
span_id = node.spids[0]
self.mem.SetCurrentSpanId(span_id)
check_errexit = True
result = self.bool_ev.EvalB(node.expr)
status = 0 if result else 1
elif case(command_e.DParen):
node = cast(command__DParen, UP_node)
span_id = node.spids[0]
self.mem.SetCurrentSpanId(span_id)
check_errexit = True
i = self.arith_ev.EvalToInt(node.child)
status = 1 if i == 0 else 0
elif case(command_e.OilCondition):
node = cast(command__OilCondition, UP_node)
# TODO: Do we need location information? Yes, probably for execptions in
# Oil expressions.
#span_id = node.spids[0]
#self.mem.SetCurrentSpanId(span_id)
obj = self.expr_ev.EvalExpr(node.e)
status = 0 if obj else 1
# TODO: Change x = 1 + 2*3 into its own Decl node.
elif case(command_e.VarDecl):
node = cast(command__VarDecl, UP_node)
if mylib.PYTHON:
# x = 'foo' is a shortcut for const x = 'foo'
if node.keyword is None or node.keyword.id == Id.KW_Const:
self.mem.SetCurrentSpanId(node.lhs[0].name.span_id) # point to var name
# Note: there's only one LHS
vd_lval = lvalue.Named(node.lhs[0].name.val) # type: lvalue_t
py_val = self.expr_ev.EvalExpr(node.rhs)
val = _PyObjectToVal(py_val) # type: value_t
self.mem.SetVar(vd_lval, val, scope_e.LocalOnly,
flags=_PackFlags(Id.KW_Const, state.SetReadOnly))
status = 0
else:
self.mem.SetCurrentSpanId(node.keyword.span_id) # point to var
py_val = self.expr_ev.EvalExpr(node.rhs)
vd_lvals = [] # type: List[lvalue_t]
vals = [] # type: List[value_t]
if len(node.lhs) == 1: # TODO: optimize this common case (but measure)
vd_lval = lvalue.Named(node.lhs[0].name.val)
val = _PyObjectToVal(py_val)
vd_lvals.append(vd_lval)
vals.append(val)
else:
it = py_val.__iter__()
for vd_lhs in node.lhs:
vd_lval = lvalue.Named(vd_lhs.name.val)
val = _PyObjectToVal(it.next())
vd_lvals.append(vd_lval)
vals.append(val)
for vd_lval, val in zip(vd_lvals, vals):
self.mem.SetVar(vd_lval, val, scope_e.LocalOnly,
flags=_PackFlags(node.keyword.id))
status = 0
elif case(command_e.PlaceMutation):
if mylib.PYTHON: # DISABLED because it relies on CPytho now
node = cast(command__PlaceMutation, UP_node)
self.mem.SetCurrentSpanId(node.keyword.span_id) # point to setvar/set
with switch(node.keyword.id) as case2:
if case2(Id.KW_SetVar):
lookup_mode = scope_e.LocalOrGlobal
elif case2(Id.KW_Set, Id.KW_SetLocal):
lookup_mode = scope_e.LocalOnly
elif case2(Id.KW_SetGlobal):
lookup_mode = scope_e.GlobalOnly
elif case2(Id.KW_SetRef):
# So this can modify two levels up?
lookup_mode = scope_e.Dynamic
# TODO: setref upvalue = 'returned'
e_die("setref isn't implemented")
else:
raise AssertionError(node.keyword.id)
if node.op.id == Id.Arith_Equal:
py_val = self.expr_ev.EvalExpr(node.rhs)
lvals_ = [] # type: List[lvalue_t]
py_vals = []
if len(node.lhs) == 1: # TODO: Optimize this common case (but measure)
# See ShAssignment
lval_ = self.expr_ev.EvalPlaceExpr(node.lhs[0]) # type: lvalue_t
lvals_.append(lval_)
py_vals.append(py_val)
else:
it = py_val.__iter__()
for pm_lhs in node.lhs:
lval_ = self.expr_ev.EvalPlaceExpr(pm_lhs)
py_val = it.next()
lvals_.append(lval_)
py_vals.append(py_val)
# TODO: Resolve the asymmetry betwen Named vs ObjIndex,ObjAttr.
for UP_lval_, py_val in zip(lvals_, py_vals):
tag = UP_lval_.tag_()
if tag == lvalue_e.ObjIndex:
lval_ = cast(lvalue__ObjIndex, UP_lval_)
lval_.obj[lval_.index] = py_val
elif tag == lvalue_e.ObjAttr:
lval_ = cast(lvalue__ObjAttr, UP_lval_)
setattr(lval_.obj, lval_.attr, py_val)
else:
val = _PyObjectToVal(py_val)
# top level variable
self.mem.SetVar(UP_lval_, val, lookup_mode,
flags=_PackFlags(node.keyword.id))
# TODO: Other augmented assignments
elif node.op.id == Id.Arith_PlusEqual:
# NOTE: x, y += 1 in Python is a SYNTAX error, but it's checked in the
# transformer and not the grammar. We should do that too.
place_expr = cast(place_expr__Var, node.lhs[0])
pe_lval = lvalue.Named(place_expr.name.val)
py_val = self.expr_ev.EvalExpr(node.rhs)
new_py_val = self.expr_ev.EvalPlusEquals(pe_lval, py_val)
# This should only be an int or float, so we don't need the logic above
val = value.Obj(new_py_val)
self.mem.SetVar(pe_lval, val, lookup_mode,
flags=_PackFlags(node.keyword.id))
else:
raise NotImplementedError(Id_str(node.op.id))
status = 0 # TODO: what should status be?
elif case(command_e.ShAssignment): # Only unqualified assignment
node = cast(command__ShAssignment, UP_node)
lookup_mode = scope_e.Dynamic
for pair in node.pairs:
spid = pair.spids[0] # Source location for tracing
# Use the spid of each pair.
self.mem.SetCurrentSpanId(spid)
if pair.op == assign_op_e.PlusEqual:
assert pair.rhs, pair.rhs # I don't think a+= is valid?
val = self.word_ev.EvalRhsWord(pair.rhs)
lval = self.arith_ev.EvalShellLhs(pair.lhs, spid, lookup_mode)
old_val = sh_expr_eval.OldValue(lval, self.mem, self.exec_opts)
UP_old_val = old_val
UP_val = val
old_tag = old_val.tag_()
tag = val.tag_()
if old_tag == value_e.Undef and tag == value_e.Str:
pass # val is RHS
elif old_tag == value_e.Undef and tag == value_e.MaybeStrArray:
pass # val is RHS
elif old_tag == value_e.Str and tag == value_e.Str:
old_val = cast(value__Str, UP_old_val)
str_to_append = cast(value__Str, UP_val)
val = value.Str(old_val.s + str_to_append.s)
elif old_tag == value_e.Str and tag == value_e.MaybeStrArray:
e_die("Can't append array to string")
elif old_tag == value_e.MaybeStrArray and tag == value_e.Str:
e_die("Can't append string to array")
elif (old_tag == value_e.MaybeStrArray and
tag == value_e.MaybeStrArray):
old_val = cast(value__MaybeStrArray, UP_old_val)
to_append = cast(value__MaybeStrArray, UP_val)
# TODO: MUTATE the existing value for efficiency?
strs = [] # type: List[str]
strs.extend(old_val.strs)
strs.extend(to_append.strs)
val = value.MaybeStrArray(strs)
else: # plain assignment
lval = self.arith_ev.EvalShellLhs(pair.lhs, spid, lookup_mode)
# RHS can be a string or array.
if pair.rhs:
val = self.word_ev.EvalRhsWord(pair.rhs)
assert isinstance(val, value_t), val
else: # e.g. 'readonly x' or 'local x'
val = None
# NOTE: In bash and mksh, declare -a myarray makes an empty cell with
# Undef value, but the 'array' attribute.
#log('setting %s to %s with flags %s', lval, val, flags)
flags = 0
self.mem.SetVar(lval, val, lookup_mode, flags=flags)
self.tracer.OnShAssignment(lval, pair.op, val, flags, lookup_mode)
# PATCH to be compatible with existing shells: If the assignment had a
# command sub like:
#
# s=$(echo one; false)
#
# then its status will be in mem.last_status, and we can check it here.
# If there was NOT a command sub in the assignment, then we don't want to
# check it.
# Only do this if there was a command sub? How? Look at node?
# Set a flag in mem? self.mem.last_status or
if self.check_command_sub_status:
last_status = self.mem.LastStatus()
self._CheckStatus(last_status, node)
status = last_status # A global assignment shouldn't clear $?.
else:
status = 0
elif case(command_e.Return):
node = cast(command__Return, UP_node)
# TODO: This should always return value_t, which is coerced to an
# integer?
# BUT: we don't have 'func' yet. Alternative: in 'proc' mode,
# return remains a builtin. This node should be called ReturnExpr.
# Can change ParseOilProc to make it inactive. Might be a good
# idea.
obj = self.expr_ev.EvalExpr(node.e)
if 0:
val = _PyObjectToVal(obj)
status_code = -1
UP_val = val
with tagswitch(val) as case:
if case(value_e.Int):
val = cast(value__Int, UP_val)
status_code = val.i
elif case(value_e.Str):
val = cast(value__Str, UP_val)
try:
status_code = int(val.s)
except ValueError:
e_die('Invalid return value %r', val.s, token=node.keyword)
else:
e_die('Expected integer return value, got %r', val,
token=node.keyword)
if mylib.PYTHON:
raise _ControlFlow(node.keyword, obj)
elif case(command_e.Expr):
node = cast(command__Expr, UP_node)
if mylib.PYTHON:
self.mem.SetCurrentSpanId(node.keyword.span_id)
obj = self.expr_ev.EvalExpr(node.e)
if node.keyword.id == Id.Lit_Equals:
# NOTE: It would be nice to unify this with 'repr', but there isn't a
# good way to do it with the value/PyObject split.
class_name = obj.__class__.__name__
oil_name = OIL_TYPE_NAMES.get(class_name, class_name)
print('(%s) %s' % (oil_name, repr(obj)))
# TODO: What about exceptions? They just throw?
status = 0
elif case(command_e.ControlFlow):
node = cast(command__ControlFlow, UP_node)
tok = node.token
if node.arg_word: # Evaluate the argument
str_val = self.word_ev.EvalWordToString(node.arg_word)
try:
# They all take integers. NOTE: dash is the only shell that
# disallows -1! Others wrap to 255.
arg = int(str_val.s)
except ValueError:
e_die('%r expected a number, got %r',
node.token.val, str_val.s, word=node.arg_word)
else:
if tok.id in (Id.ControlFlow_Exit, Id.ControlFlow_Return):
arg = self.mem.LastStatus()
else:
arg = 0 # break 0 levels, nothing for continue
# NOTE: A top-level 'return' is OK, unlike in bash. If you can return
# from a sourced script, it makes sense to return from a main script.
ok = True
if (tok.id in (Id.ControlFlow_Break, Id.ControlFlow_Continue) and
self.loop_level == 0):
ok = False
if ok:
if tok.id == Id.ControlFlow_Exit:
raise util.UserExit(arg) # handled differently than other control flow
else:
raise _ControlFlow(tok, arg)
else:
msg = 'Invalid control flow at top level'
if self.exec_opts.strict_control_flow():
e_die(msg, token=tok)
else:
# Only print warnings, never fatal.
# Bash oddly only exits 1 for 'return', but no other shell does.
self.errfmt.PrefixPrint(msg, prefix='warning: ', span_id=tok.span_id)
status = 0
# The only difference between these next two is that CommandList
# has no redirects. We already took care of that above. But we
# need to split them up for mycpp.
elif case(command_e.CommandList):
node = cast(command__CommandList, UP_node)
status = self._ExecuteList(node.children)
check_errexit = False
elif case(command_e.BraceGroup):
node = cast(BraceGroup, UP_node)
status = self._ExecuteList(node.children)
check_errexit = False
elif case(command_e.AndOr):
node = cast(command__AndOr, UP_node)
# NOTE: && and || have EQUAL precedence in command mode. See case #13
# in dbracket.test.sh.
left = node.children[0]
# Suppress failure for every child except the last one.
with state.ctx_ErrExit(self.mutable_opts, node.spids[0]):
status = self._Execute(left)
i = 1
n = len(node.children)
while i < n:
#log('i %d status %d', i, status)
child = node.children[i]
op_id = node.ops[i-1]
#log('child %s op_id %s', child, op_id)
if op_id == Id.Op_DPipe and status == 0:
i += 1
continue # short circuit
elif op_id == Id.Op_DAmp and status != 0:
i += 1
continue # short circuit
if i == n - 1: # errexit handled differently for last child
status = self._Execute(child)
check_errexit = True
else:
# blame the right && or ||
with state.ctx_ErrExit(self.mutable_opts, node.spids[i]):
status = self._Execute(child)
i += 1
elif case(command_e.WhileUntil):
node = cast(command__WhileUntil, UP_node)
status = 0
self.loop_level += 1
try: