-
-
Notifications
You must be signed in to change notification settings - Fork 164
/
Copy pathstate.py
2827 lines (2210 loc) · 91.4 KB
/
state.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
# 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
"""
state.py - Interpreter state
"""
from __future__ import print_function
import time as time_ # avoid name conflict
from _devbuild.gen.id_kind_asdl import Id
from _devbuild.gen.option_asdl import option_i
from _devbuild.gen.runtime_asdl import (error_code_e, scope_e, scope_t, Cell)
from _devbuild.gen.syntax_asdl import (loc, loc_t, Token, debug_frame,
debug_frame_e, debug_frame_t)
from _devbuild.gen.types_asdl import opt_group_i
from _devbuild.gen.value_asdl import (value, value_e, value_t, Obj, sh_lvalue,
sh_lvalue_e, sh_lvalue_t, LeftName,
y_lvalue_e, regex_match, regex_match_e,
regex_match_t, RegexMatch)
from core import bash_impl
from core import error
from core.error import e_usage, e_die
from core import num
from core import optview
from display import ui
from core import util
from frontend import consts
from frontend import location
from frontend import match
from mycpp import mops
from mycpp import mylib
from mycpp.mylib import (log, print_stderr, str_switch, tagswitch, iteritems,
NewDict)
from pylib import os_path
from libc import HAVE_GLOB_PERIOD
import posix_ as posix
from typing import Tuple, List, Dict, Optional, Any, cast, TYPE_CHECKING
if TYPE_CHECKING:
from _devbuild.gen.option_asdl import option_t
from core import alloc
from osh import sh_expr_eval
_ = log
# flags for mem.SetValue()
SetReadOnly = 1 << 0
ClearReadOnly = 1 << 1
SetExport = 1 << 2
ClearExport = 1 << 3
SetNameref = 1 << 4
ClearNameref = 1 << 5
class ctx_Source(object):
"""For source builtin."""
def __init__(self, mem, source_name, argv):
# type: (Mem, str, List[str]) -> None
mem.PushSource(source_name, argv)
self.mem = mem
self.argv = argv
# Whenever we're sourcing, the 'is-main' builtin will return 1 (false)
self.to_restore = self.mem.is_main
self.mem.is_main = False
def __enter__(self):
# type: () -> None
pass
def __exit__(self, type, value, traceback):
# type: (Any, Any, Any) -> None
self.mem.PopSource(self.argv)
self.mem.is_main = self.to_restore
class ctx_DebugTrap(object):
"""For trap DEBUG."""
def __init__(self, mem):
# type: (Mem) -> None
mem.running_debug_trap = True
self.mem = mem
def __enter__(self):
# type: () -> None
pass
def __exit__(self, type, value, traceback):
# type: (Any, Any, Any) -> None
self.mem.running_debug_trap = False
class ctx_ErrTrap(object):
"""For trap ERR."""
def __init__(self, mem):
# type: (Mem) -> None
mem.running_err_trap = True
self.mem = mem
def __enter__(self):
# type: () -> None
pass
def __exit__(self, type, value, traceback):
# type: (Any, Any, Any) -> None
self.mem.running_err_trap = False
class ctx_Option(object):
"""Shopt --unset errexit { false }"""
def __init__(self, mutable_opts, opt_nums, b):
# type: (MutableOpts, List[int], bool) -> None
for opt_num in opt_nums:
mutable_opts.Push(opt_num, b)
if opt_num == option_i.errexit:
# it wasn't disabled
mutable_opts.errexit_disabled_tok.append(None)
self.mutable_opts = mutable_opts
self.opt_nums = opt_nums
def __enter__(self):
# type: () -> None
pass
def __exit__(self, type, value, traceback):
# type: (Any, Any, Any) -> None
for opt_num in self.opt_nums: # don't bother to do it in reverse order
if opt_num == option_i.errexit:
self.mutable_opts.errexit_disabled_tok.pop()
self.mutable_opts.Pop(opt_num)
class ctx_AssignBuiltin(object):
"""Local x=$(false) is disallowed."""
def __init__(self, mutable_opts):
# type: (MutableOpts) -> None
self.strict = False
if mutable_opts.Get(option_i.strict_errexit):
mutable_opts.Push(option_i._allow_command_sub, False)
mutable_opts.Push(option_i._allow_process_sub, False)
self.strict = True
self.mutable_opts = mutable_opts
def __enter__(self):
# type: () -> None
pass
def __exit__(self, type, value, traceback):
# type: (Any, Any, Any) -> None
if self.strict:
self.mutable_opts.Pop(option_i._allow_command_sub)
self.mutable_opts.Pop(option_i._allow_process_sub)
class ctx_YshExpr(object):
"""Command sub must fail in 'mystring' ++ $(false)"""
def __init__(self, mutable_opts):
# type: (MutableOpts) -> None
# Similar to $LIB_OSH/bash-strict.sh
# TODO: consider errexit:all group, or even ysh:all
# It would be nice if this were more efficient
mutable_opts.Push(option_i.command_sub_errexit, True)
mutable_opts.Push(option_i.errexit, True)
mutable_opts.Push(option_i.pipefail, True)
mutable_opts.Push(option_i.inherit_errexit, True)
mutable_opts.Push(option_i.strict_errexit, True)
# What about nounset? This has a similar pitfall -- it's not running
# like YSH.
# e.g. var x = $(echo $zz)
self.mutable_opts = mutable_opts
def __enter__(self):
# type: () -> None
pass
def __exit__(self, type, value, traceback):
# type: (Any, Any, Any) -> None
self.mutable_opts.Pop(option_i.command_sub_errexit)
self.mutable_opts.Pop(option_i.errexit)
self.mutable_opts.Pop(option_i.pipefail)
self.mutable_opts.Pop(option_i.inherit_errexit)
self.mutable_opts.Pop(option_i.strict_errexit)
class ctx_ErrExit(object):
"""Manages the errexit setting.
- The user can change it with builtin 'set' at any point in the code.
- These constructs implicitly disable 'errexit':
- if / while / until conditions
- ! (part of pipeline)
- && ||
"""
def __init__(self, mutable_opts, b, disabled_tok):
# type: (MutableOpts, bool, Optional[Token]) -> None
# If we're disabling it, we need a span ID. If not, then we should NOT
# have one.
assert b == (disabled_tok is None)
mutable_opts.Push(option_i.errexit, b)
mutable_opts.errexit_disabled_tok.append(disabled_tok)
self.strict = False
if mutable_opts.Get(option_i.strict_errexit):
mutable_opts.Push(option_i._allow_command_sub, False)
mutable_opts.Push(option_i._allow_process_sub, False)
self.strict = True
self.mutable_opts = mutable_opts
def __enter__(self):
# type: () -> None
pass
def __exit__(self, type, value, traceback):
# type: (Any, Any, Any) -> None
self.mutable_opts.errexit_disabled_tok.pop()
self.mutable_opts.Pop(option_i.errexit)
if self.strict:
self.mutable_opts.Pop(option_i._allow_command_sub)
self.mutable_opts.Pop(option_i._allow_process_sub)
class OptHook(object):
"""Interface for option hooks."""
def __init__(self):
# type: () -> None
"""Empty constructor for mycpp."""
pass
def OnChange(self, opt0_array, opt_name, b):
# type: (List[bool], str, bool) -> bool
"""This method is called whenever an option is changed.
Returns success or failure.
"""
return True
def InitOpts():
# type: () -> List[bool]
opt0_array = [False] * option_i.ARRAY_SIZE
for opt_num in consts.DEFAULT_TRUE:
opt0_array[opt_num] = True
return opt0_array
def MakeOpts(
mem, # type: Mem
environ, # type: Dict[str, str]
opt_hook, # type: OptHook
):
# type: (...) -> Tuple[optview.Parse, optview.Exec, MutableOpts]
# Unusual representation: opt0_array + opt_stacks. For two features:
#
# - POSIX errexit disable semantics
# - YSH shopt --set nullglob { ... }
#
# We could do it with a single List of stacks. But because shopt --set
# random_option { ... } is very uncommon, we optimize and store the ZERO
# element of the stack in a flat array opt0_array (default False), and then
# the rest in opt_stacks, where the value could be None. By allowing the
# None value, we save ~50 or so list objects in the common case.
opt0_array = InitOpts()
# Overrides, including errexit
no_stack = None # type: List[bool] # for mycpp
opt_stacks = [no_stack] * option_i.ARRAY_SIZE # type: List[List[bool]]
parse_opts = optview.Parse(opt0_array, opt_stacks)
exec_opts = optview.Exec(opt0_array, opt_stacks)
mutable_opts = MutableOpts(mem, environ, opt0_array, opt_stacks, opt_hook)
return parse_opts, exec_opts, mutable_opts
def _SetGroup(opt0_array, opt_nums, b):
# type: (List[bool], List[int], bool) -> None
for opt_num in opt_nums:
b2 = not b if opt_num in consts.DEFAULT_TRUE else b
opt0_array[opt_num] = b2
def MakeYshParseOpts():
# type: () -> optview.Parse
opt0_array = InitOpts()
_SetGroup(opt0_array, consts.YSH_ALL, True)
no_stack = None # type: List[bool]
opt_stacks = [no_stack] * option_i.ARRAY_SIZE # type: List[List[bool]]
parse_opts = optview.Parse(opt0_array, opt_stacks)
return parse_opts
def _AnyOptionNum(opt_name, ignore_shopt_not_impl):
# type: (str, bool) -> option_t
opt_num = consts.OptionNum(opt_name)
if opt_num == 0:
if ignore_shopt_not_impl:
opt_num = consts.UnimplOptionNum(opt_name)
if opt_num == 0:
e_usage('got invalid option %r' % opt_name, loc.Missing)
# Note: we relaxed this for YSH so we can do 'shopt --unset errexit' consistently
#if opt_num not in consts.SHOPT_OPTION_NUMS:
# e_usage("doesn't own option %r (try 'set')" % opt_name)
return opt_num
def _SetOptionNum(opt_name):
# type: (str) -> option_t
opt_num = consts.OptionNum(opt_name)
if opt_num == 0:
e_usage('got invalid option %r' % opt_name, loc.Missing)
if opt_num not in consts.SET_OPTION_NUMS:
e_usage("invalid option %r (try shopt)" % opt_name, loc.Missing)
return opt_num
def _MaybeWarnDotglob():
# type: () -> None
if HAVE_GLOB_PERIOD == 0:
# GNU libc and musl libc have GLOB_PERIOD, but Android doesn't
print_stderr(
"osh warning: GLOB_PERIOD wasn't found in libc, so 'shopt -s dotglob' won't work"
)
class MutableOpts(object):
def __init__(self, mem, environ, opt0_array, opt_stacks, opt_hook):
# type: (Mem, Dict[str, str], List[bool], List[List[bool]], OptHook) -> None
self.mem = mem
self.environ = environ
self.opt0_array = opt0_array
self.opt_stacks = opt_stacks
self.errexit_disabled_tok = [] # type: List[Token]
# Used for 'set -o vi/emacs'
self.opt_hook = opt_hook
def Init(self):
# type: () -> None
# This comes after all the 'set' options.
shellopts = self.mem.GetValue('SHELLOPTS')
# True in OSH, but not in YSH (no_init_globals)
if shellopts.tag() == value_e.Str:
s = cast(value.Str, shellopts).s
self._InitOptionsFromEnv(s)
def _InitOptionsFromEnv(self, shellopts):
# type: (str) -> None
# e.g. errexit:nounset:pipefail
lookup = shellopts.split(':')
for opt_num in consts.SET_OPTION_NUMS:
name = consts.OptionName(opt_num)
if name in lookup:
self._SetOldOption(name, True)
def Push(self, opt_num, b):
# type: (int, bool) -> None
if opt_num == option_i.dotglob:
_MaybeWarnDotglob()
overlay = self.opt_stacks[opt_num]
if overlay is None or len(overlay) == 0:
self.opt_stacks[opt_num] = [b] # Allocate a new list
else:
overlay.append(b)
def Pop(self, opt_num):
# type: (int) -> bool
overlay = self.opt_stacks[opt_num]
assert overlay is not None
return overlay.pop()
def PushDynamicScope(self, b):
# type: (bool) -> None
"""B: False if it's a proc, and True if it's a shell function."""
# If it's already disabled, keep it disabled
if not self.Get(option_i.dynamic_scope):
b = False
self.Push(option_i.dynamic_scope, b)
def PopDynamicScope(self):
# type: () -> None
self.Pop(option_i.dynamic_scope)
def Get(self, opt_num):
# type: (int) -> bool
# Like _Getter in core/optview.py
overlay = self.opt_stacks[opt_num]
if overlay is None or len(overlay) == 0:
return self.opt0_array[opt_num]
else:
return overlay[-1] # the top value
def _Set(self, opt_num, b):
# type: (int, bool) -> None
"""Used to disable errexit.
For bash compatibility in command sub.
"""
if opt_num == option_i.dotglob:
_MaybeWarnDotglob()
# Like _Getter in core/optview.py
overlay = self.opt_stacks[opt_num]
if overlay is None or len(overlay) == 0:
self.opt0_array[opt_num] = b
else:
overlay[-1] = b # The top value
def set_interactive(self):
# type: () -> None
self._Set(option_i.interactive, True)
def set_redefine_const(self):
# type: () -> None
"""For interactive shells."""
self._Set(option_i.redefine_const, True)
def set_redefine_source(self):
# type: () -> None
"""For interactive shells. For source-guard"""
self._Set(option_i.redefine_source, True)
def set_emacs(self):
# type: () -> None
self._Set(option_i.emacs, True)
def _SetArrayByNum(self, opt_num, b):
# type: (int, bool) -> None
if (opt_num in consts.PARSE_OPTION_NUMS and
not self.mem.ParsingChangesAllowed()):
e_die('Syntax options must be set at the top level '
'(outside any function)')
self._Set(opt_num, b)
def SetDeferredErrExit(self, b):
# type: (bool) -> None
"""Set the errexit flag, possibly deferring it.
Implements the unusual POSIX "defer" behavior. Callers: set -o
errexit, shopt -s ysh:all, ysh:upgrade
"""
#log('Set %s', b)
# Defer it until we pop by setting the BOTTOM OF THE STACK.
self.opt0_array[option_i.errexit] = b
def DisableErrExit(self):
# type: () -> None
"""Called by core/process.py to implement bash quirks."""
self._Set(option_i.errexit, False)
def ErrExitDisabledToken(self):
# type: () -> Optional[Token]
"""If errexit is disabled by POSIX rules, return Token for construct.
e.g. the Token for 'if' or '&&' etc.
"""
# Bug fix: The errexit disabling inherently follows a STACK DISCIPLINE.
# But we run trap handlers in the MAIN LOOP, which break this. So just
# declare that it's never disabled in a trap.
if self.Get(option_i._running_trap):
return None
if len(self.errexit_disabled_tok) == 0:
return None
return self.errexit_disabled_tok[-1]
def ErrExitIsDisabled(self):
# type: () -> bool
"""
Similar to ErrExitDisabledToken, for ERR trap
"""
if len(self.errexit_disabled_tok) == 0:
return False
return self.errexit_disabled_tok[-1] is not None
def _SetOldOption(self, opt_name, b):
# type: (str, bool) -> None
"""Private version for synchronizing from SHELLOPTS."""
assert '_' not in opt_name
assert opt_name in consts.SET_OPTION_NAMES
opt_num = consts.OptionNum(opt_name)
assert opt_num != 0, opt_name
if opt_num == option_i.errexit:
self.SetDeferredErrExit(b)
else:
if opt_num == option_i.verbose and b:
print_stderr('osh warning: set -o verbose not implemented')
self._SetArrayByNum(opt_num, b)
# note: may FAIL before we get here.
success = self.opt_hook.OnChange(self.opt0_array, opt_name, b)
def SetOldOption(self, opt_name, b):
# type: (str, bool) -> None
"""For set -o, set +o, or shopt -s/-u -o."""
unused = _SetOptionNum(opt_name) # validate it
self._SetOldOption(opt_name, b)
if not self.Get(option_i.no_init_globals):
UP_val = self.mem.GetValue('SHELLOPTS')
assert UP_val.tag() == value_e.Str, UP_val
val = cast(value.Str, UP_val)
shellopts = val.s
# Now check if SHELLOPTS needs to be updated. It may be exported.
#
# NOTE: It might be better to skip rewriting SEHLLOPTS in the common case
# where it is not used. We could do it lazily upon GET.
# Also, it would be slightly more efficient to update SHELLOPTS if
# settings were batched, Examples:
# - set -eu
# - shopt -s foo bar
if b:
if opt_name not in shellopts:
new_val = value.Str('%s:%s' % (shellopts, opt_name))
self.mem.InternalSetGlobal('SHELLOPTS', new_val)
else:
if opt_name in shellopts:
names = [n for n in shellopts.split(':') if n != opt_name]
new_val = value.Str(':'.join(names))
self.mem.InternalSetGlobal('SHELLOPTS', new_val)
def SetAnyOption(self, opt_name, b, ignore_shopt_not_impl=False):
# type: (str, bool, bool) -> None
"""For shopt -s/-u and sh -O/+O."""
# shopt -s ysh:all turns on all YSH options, which includes all strict
# options
opt_group = consts.OptionGroupNum(opt_name)
if opt_group == opt_group_i.YshUpgrade:
_SetGroup(self.opt0_array, consts.YSH_UPGRADE, b)
self.SetDeferredErrExit(b) # Special case
if b: # ENV dict
self.mem.MaybeInitEnvDict(self.environ)
return
if opt_group == opt_group_i.YshAll:
_SetGroup(self.opt0_array, consts.YSH_ALL, b)
self.SetDeferredErrExit(b) # Special case
if b: # ENV dict
self.mem.MaybeInitEnvDict(self.environ)
return
if opt_group == opt_group_i.StrictAll:
_SetGroup(self.opt0_array, consts.STRICT_ALL, b)
return
opt_num = _AnyOptionNum(opt_name, ignore_shopt_not_impl)
if opt_num == option_i.errexit:
self.SetDeferredErrExit(b)
return
self._SetArrayByNum(opt_num, b)
class _ArgFrame(object):
"""Stack frame for arguments array."""
def __init__(self, argv):
# type: (List[str]) -> None
self.argv = argv
self.num_shifted = 0
def __repr__(self):
# type: () -> str
return '<_ArgFrame %s %d at %x>' % (self.argv, self.num_shifted,
id(self))
def Dump(self):
# type: () -> Dict[str, value_t]
items = [value.Str(s) for s in self.argv] # type: List[value_t]
argv = value.List(items)
return {
'argv': argv,
'num_shifted': num.ToBig(self.num_shifted),
}
def GetArgNum(self, arg_num):
# type: (int) -> value_t
# $0 is handled elsewhere
assert 1 <= arg_num, arg_num
index = self.num_shifted + arg_num - 1
if index >= len(self.argv):
return value.Undef
return value.Str(self.argv[index])
def GetArgv(self):
# type: () -> List[str]
return self.argv[self.num_shifted:]
def GetNumArgs(self):
# type: () -> int
return len(self.argv) - self.num_shifted
def SetArgv(self, argv):
# type: (List[str]) -> None
self.argv = argv
self.num_shifted = 0
def _DumpVarFrame(frame):
# type: (Dict[str, Cell]) -> Dict[str, value_t]
"""Dump the stack frame as reasonably compact and readable JSON."""
vars_json = {} # type: Dict[str, value_t]
for name, cell in iteritems(frame):
cell_json = {} # type: Dict[str, value_t]
buf = mylib.BufWriter()
if cell.exported:
buf.write('x')
if cell.readonly:
buf.write('r')
flags = buf.getvalue()
if len(flags):
cell_json['flags'] = value.Str(flags)
# TODO:
# - Use packle for crash dumps! Then we can represent object cycles
# - Right now the JSON serializer will probably crash
# - although BashArray and BashAssoc may need 'type' tags
# - they don't round trip correctly
# - maybe add value.Tombstone here or something?
# - value.{Func,Eggex,...} may have value.Tombstone and
# vm.ValueIdString()?
with tagswitch(cell.val) as case:
if case(value_e.Undef):
cell_json['val'] = value.Null
elif case(value_e.Str, value_e.BashArray, value_e.BashAssoc,
value_e.SparseArray):
cell_json['val'] = cell.val
else:
# TODO: should we show the object ID here?
pass
vars_json[name] = value.Dict(cell_json)
return vars_json
def _LineNumber(tok):
# type: (Optional[Token]) -> str
""" For $BASH_LINENO """
if tok is None:
return '-1'
return str(tok.line.line_num)
def _AddCallToken(d, token):
# type: (Dict[str, value_t], Optional[Token]) -> None
if token is None:
return
d['call_source'] = value.Str(ui.GetLineSourceString(token.line))
d['call_line_num'] = num.ToBig(token.line.line_num)
d['call_line'] = value.Str(token.line.content)
class ctx_FuncCall(object):
"""For func calls."""
def __init__(self, mem, func):
# type: (Mem, value.Func) -> None
self.saved_globals = mem.var_stack[0]
assert func.module_frame is not None
mem.var_stack[0] = func.module_frame
frame = NewDict() # type: Dict[str, Cell]
mem.var_stack.append(frame)
mem.PushCall(func.name, func.parsed.name)
self.mem = mem
def __enter__(self):
# type: () -> None
pass
def __exit__(self, type, value, traceback):
# type: (Any, Any, Any) -> None
self.mem.PopCall()
self.mem.var_stack.pop()
self.mem.var_stack[0] = self.saved_globals
class ctx_ProcCall(object):
"""For proc calls, including shell functions."""
def __init__(self, mem, mutable_opts, proc, argv):
# type: (Mem, MutableOpts, value.Proc, List[str]) -> None
# TODO:
# should we separate procs and shell functions?
# - dynamic scope is one difference
# - '$@" shift etc. are another difference
self.saved_globals = mem.var_stack[0]
assert proc.module_frame is not None
mem.var_stack[0] = proc.module_frame
frame = NewDict() # type: Dict[str, Cell]
assert argv is not None
if proc.sh_compat:
# shell function
mem.argv_stack.append(_ArgFrame(argv))
else:
# procs
# - open: is equivalent to ...ARGV
# - closed: ARGV is empty list
frame['ARGV'] = _MakeArgvCell(argv)
mem.var_stack.append(frame)
mem.PushCall(proc.name, proc.name_tok)
# Dynamic scope is only for shell functions
mutable_opts.PushDynamicScope(proc.sh_compat)
# It may have been disabled with ctx_ErrExit for 'if echo $(false)', but
# 'if p' should be allowed.
self.mem = mem
self.mutable_opts = mutable_opts
self.sh_compat = proc.sh_compat
def __enter__(self):
# type: () -> None
pass
def __exit__(self, type, value, traceback):
# type: (Any, Any, Any) -> None
self.mutable_opts.PopDynamicScope()
self.mem.PopCall()
self.mem.var_stack.pop()
if self.sh_compat:
self.mem.argv_stack.pop()
self.mem.var_stack[0] = self.saved_globals
class ctx_Temp(object):
""" POSIX shell FOO=bar mycommand """
def __init__(self, mem):
# type: (Mem) -> None
self.mem = mem
mem.PushTemp()
def __enter__(self):
# type: () -> None
pass
def __exit__(self, type, value, traceback):
# type: (Any, Any, Any) -> None
self.mem.PopTemp()
class ctx_EnvObj(object):
"""YSH FOO=bar my-command"""
def __init__(self, mem, bindings):
# type: (Mem, Dict[str, value_t]) -> None
self.mem = mem
mem.PushEnvObj(bindings)
def __enter__(self):
# type: () -> None
pass
def __exit__(self, type, value, traceback):
# type: (Any, Any, Any) -> None
self.mem.PopEnvObj()
class ctx_Registers(object):
"""For $PS1, $PS4, $PROMPT_COMMAND, traps, and headless EVAL.
This is tightly coupled to state.Mem, so it's not in builtin/pure_ysh.
"""
def __init__(self, mem):
# type: (Mem) -> None
# Because some prompts rely on the status leaking. See issue #853.
# PS1 also does.
last = mem.last_status[-1]
mem.last_status.append(last)
mem.try_status.append(0)
mem.try_error.append(value.Dict({}))
# TODO: We should also copy these values! Turn the whole thing into a
# frame.
mem.pipe_status.append([])
mem.process_sub_status.append([])
mem.regex_match.append(regex_match.No)
self.mem = mem
def __enter__(self):
# type: () -> None
pass
def __exit__(self, type, value, traceback):
# type: (Any, Any, Any) -> None
self.mem.regex_match.pop()
self.mem.process_sub_status.pop()
self.mem.pipe_status.pop()
self.mem.try_error.pop()
self.mem.try_status.pop()
self.mem.last_status.pop()
class ctx_ThisDir(object):
"""For $_this_dir."""
def __init__(self, mem, filename):
# type: (Mem, Optional[str]) -> None
self.do_pop = False
if filename is not None: # script_name in main() may be -c, etc.
d = os_path.dirname(os_path.abspath(filename))
mem.this_dir.append(d)
self.do_pop = True
self.mem = mem
def __enter__(self):
# type: () -> None
pass
def __exit__(self, type, value, traceback):
# type: (Any, Any, Any) -> None
if self.do_pop:
self.mem.this_dir.pop()
def _MakeArgvCell(argv):
# type: (List[str]) -> Cell
items = [value.Str(a) for a in argv] # type: List[value_t]
return Cell(False, False, False, value.List(items))
class ctx_LoopFrame(object):
def __init__(self, mem, name1):
# type: (Mem, str) -> None
self.mem = mem
self.name1 = name1
self.do_new_frame = name1 == '__hack__'
if self.do_new_frame:
to_enclose = self.mem.var_stack[-1]
self.new_frame = NewDict() # type: Dict[str, Cell]
self.new_frame['__E__'] = Cell(False, False, False,
value.Frame(to_enclose))
mem.var_stack.append(self.new_frame)
def __enter__(self):
# type: () -> None
pass
def __exit__(self, type, value, traceback):
# type: (Any, Any, Any) -> None
if self.do_new_frame:
self.mem.var_stack.pop()
class ctx_EnclosedFrame(object):
"""
Usages:
- io->evalToDict(), which is a primitive used for Hay and the Dict proc
- lexical scope aka static scope for block args to user-defined procs
- Including the "closures in a loop" problem, which will be used for Hay
var mutated = 'm'
var shadowed = 's'
Dict (&d) {
shadowed = 42
mutated = 'new' # this is equivalent to var mutated
setvar mutated = 'new'
}
echo $shadowed # restored to 's'
echo $mutated # new
Or maybe we disallow the setvar lookup?
"""
def __init__(
self,
mem, # type: Mem
to_enclose, # type: Dict[str, Cell]
module_frame, # type: Dict[str, Cell]
out_dict, # type: Optional[Dict[str, value_t]]
):
# type: (...) -> None
self.mem = mem
self.to_enclose = to_enclose
self.module_frame = module_frame
self.out_dict = out_dict
if module_frame is not None:
self.saved_globals = self.mem.var_stack[0]
self.mem.var_stack[0] = module_frame
# __E__ gets a lookup rule
self.new_frame = NewDict() # type: Dict[str, Cell]
self.new_frame['__E__'] = Cell(False, False, False,
value.Frame(to_enclose))
mem.var_stack.append(self.new_frame)
def __enter__(self):
# type: () -> None
pass
def __exit__(self, type, value, traceback):
# type: (Any, Any, Any) -> None
if self.out_dict is not None:
for name, cell in iteritems(self.new_frame):
#log('name %r', name)
#log('cell %r', cell)
# User can hide variables with _ suffix
# e.g. for i_ in foo bar { echo $i_ }
if name.endswith('_'):
continue
self.out_dict[name] = cell.val
# Restore
self.mem.var_stack.pop()
if self.module_frame is not None:
self.mem.var_stack[0] = self.saved_globals
class ctx_ModuleEval(object):
"""Evaluate a module with a new global stack frame.
e.g. setglobal in the new module doesn't leak