/
state.py
1786 lines (1429 loc) · 53.7 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 cStringIO
from _devbuild.gen.id_kind_asdl import Id, Id_t
from _devbuild.gen.option_asdl import option_i
from _devbuild.gen.runtime_asdl import (
value, value_e, value_t, value__Str, value__MaybeStrArray, value__AssocArray,
lvalue, lvalue_e, lvalue_t, lvalue__Named, lvalue__Indexed, lvalue__Keyed,
scope_e, scope_t,
)
from _devbuild.gen import runtime_asdl # for cell
from asdl import runtime
from core import error
from core import pyos
from core import pyutil
from core.pyerror import e_usage
from core.pyutil import stderr_line
from core import ui
from core.pyerror import log, e_die
from core import optview
from frontend import consts
from frontend import match
from mycpp import mylib
from mycpp.mylib import tagswitch, iteritems
from osh import split
from pylib import os_path
from pylib import path_stat
import libc
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 _devbuild.gen.runtime_asdl import cell
from core.alloc import Arena
# This was derived from bash --norc -c 'argv "$COMP_WORDBREAKS".
# Python overwrites this to something Python-specific in Modules/readline.c, so
# we have to set it back!
# Used in both core/competion.py and osh/state.py
_READLINE_DELIMS = ' \t\n"\'><=;|&(:'
LINE_ZERO = -2 # special value that's not runtime.NO_SPID
# flags for SetVar
SetReadOnly = 1 << 0
ClearReadOnly = 1 << 1
SetExport = 1 << 2
ClearExport = 1 << 3
SetNameref = 1 << 4
ClearNameref = 1 << 5
class SearchPath(object):
"""For looking up files in $PATH."""
def __init__(self, mem):
# type: (Mem) -> None
self.mem = mem
self.cache = {} # type: Dict[str, str]
def Lookup(self, name, exec_required=True):
# type: (str, bool) -> Optional[str]
"""
Returns the path itself (for relative path), the resolve path, or None.
"""
if '/' in name:
if path_stat.exists(name):
return name
else:
return None
# TODO: Could cache this computation to avoid allocating every time for all
# the splitting.
val = self.mem.GetVar('PATH')
UP_val = val
if val.tag_() == value_e.Str:
val = cast(value__Str, UP_val)
path_list = val.s.split(':')
else:
path_list = [] # treat as empty path
for path_dir in path_list:
full_path = os_path.join(path_dir, name)
# NOTE: dash and bash only check for EXISTENCE in 'command -v' (and 'type
# -t'). OSH follows mksh and zsh. Note that we can still get EPERM if
# the permissions are changed between check and use.
if exec_required:
found = posix.access(full_path, posix.X_OK_)
else:
found = path_stat.exists(full_path) # for 'source'
if found:
return full_path
return None
def CachedLookup(self, name):
# type: (str) -> Optional[str]
if name in self.cache:
return self.cache[name]
full_path = self.Lookup(name)
if full_path is not None:
self.cache[name] = full_path
return full_path
def MaybeRemoveEntry(self, name):
# type: (str) -> None
"""When the file system changes."""
mylib.dict_remove(self.cache, name)
def ClearCache(self):
# type: () -> None
"""For hash -r."""
self.cache.clear()
def CachedCommands(self):
# type: () -> List[str]
return self.cache.values()
class ctx_ErrExit(object):
def __init__(self, mutable_opts, span_id):
# type: (MutableOpts, int) -> None
mutable_opts.errexit.Push(span_id)
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.Pop()
class _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)
- && ||
An _ErrExit object prevents these two mechanisms from clobbering each other.
"""
def __init__(self):
# type: () -> None
self._value = False # the setting
# SUBTLE INVARIANT: There's only ONE valid integer in the stack that's not
# runtime.NO_SPID, and it's either a valid span_id or 0. Push() and Set()
# enforce this.
self.stack = [] # type: List[int]
def Push(self, span_id):
# type: (int) -> None
"""Temporarily disable errexit."""
assert span_id != runtime.NO_SPID
if self._value:
self._value = False
self.stack.append(span_id) # value to restore
else:
self.stack.append(runtime.NO_SPID) # INVALID span ID / "False"
def Pop(self):
# type: () -> None
"""Restore the previous value."""
self._value = (self.stack.pop() != runtime.NO_SPID)
def SpidIfDisabled(self):
# type: () -> int
for n in self.stack:
if n != runtime.NO_SPID: # set -e will be restored later
return n
return runtime.NO_SPID
def Set(self, b):
# type: (bool) -> None
"""Set the errexit flag.
Callers: set -o errexit, shopt -s oil:all, strict:all.
"""
for i, n in enumerate(self.stack):
if n != runtime.NO_SPID: # set -e will be restored later
# Ignore set -e or set +e now, but its effect becomes visible LATER.
# This is confusing behavior that all shells implement! strict_errexit
# makes it a non-issue.
# SUBTLE: 0 isn't a valid span_id, but we will never use it for the
# strict_errexit message.
self.stack[i] = 0 if b else runtime.NO_SPID
return
self._value = b # Otherwise just set it
def Disable(self):
# type: () -> None
"""For bash compatibility in command sub."""
self._value = False
def value(self):
# type: () -> bool
return self._value
def __repr__(self): # not translated
# type: () -> str
return '<ErrExit %s %s>' % (self._value, self.stack)
class _Getter(object):
def __init__(self, opt_array, opt_name):
# type: (List[bool], str) -> None
self.opt_array = opt_array
self.num = match.MatchOption(opt_name)
assert self.num != 0, opt_name
def __call__(self):
# type: () -> bool
return self.opt_array[self.num]
class OptHook(object):
"""Interface for option hooks."""
def OnChange(self, opt_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 MakeOpts(mem, opt_hook):
# type: (Mem, OptHook) -> Tuple[optview.Parse, optview.Exec, MutableOpts]
# 38 options
#log('opts = %d', option_def.ArraySize())
opt_array = [False] * option_i.ARRAY_SIZE
errexit = _ErrExit()
parse_opts = optview.Parse(opt_array)
exec_opts = optview.Exec(opt_array, errexit)
mutable_opts = MutableOpts(mem, opt_array, errexit, opt_hook)
return parse_opts, exec_opts, mutable_opts
def _ShoptOptionNum(opt_name):
# type: (str) -> option_t
opt_num = match.MatchOption(opt_name)
if opt_num == 0:
e_usage('got invalid option %r' % opt_name)
# TODO: relax this rule
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 = match.MatchOption(opt_name)
if opt_num == 0:
e_usage('got invalid option %r' % opt_name)
# BUG: shopt -p -o simple_word_eval says 'shopt' doesn't own, try 'shopt'
if opt_num not in consts.SET_OPTION_NUMS:
e_usage("doesn't own option %r (try 'shopt')" % opt_name)
return opt_num
class MutableOpts(object):
def __init__(self, mem, opt_array, errexit, opt_hook):
# type: (Mem, List[bool], _ErrExit, OptHook) -> None
self.mem = mem
self.opt_array = opt_array
self.errexit = errexit
# On by default
for opt_num in consts.DEFAULT_TRUE:
self.opt_array[opt_num] = True
# Used for 'set -o vi/emacs'
self.opt_hook = opt_hook
# This comes after all the 'set' options.
UP_shellopts = self.mem.GetVar('SHELLOPTS')
if UP_shellopts.tag_() == value_e.Str: # Always true in Oil, see Init above
shellopts = cast(value__Str, UP_shellopts)
self._InitOptionsFromEnv(shellopts.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._SetOption(name, True)
def set_interactive(self):
# type: () -> None
self.opt_array[option_i.interactive] = True
def set_emacs(self):
# type: () -> None
self.opt_array[option_i.emacs] = True
def set_xtrace(self, b):
# type: (bool) -> None
self.opt_array[option_i.xtrace] = b
def _SetArrayByNum(self, opt_num, b):
# type: (int, bool) -> None
if (opt_num in consts.PARSE_OPTION_NUMS and
not self.mem.InGlobalNamespace()):
e_die('Syntax options must be set at the top level '
'(outside any function)')
self.opt_array[opt_num] = b
def _SetOption(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 = match.MatchOption(opt_name)
assert opt_num != 0, opt_name
if opt_num == option_i.errexit:
self.errexit.Set(b)
else:
if opt_num == option_i.verbose and b:
stderr_line('Warning: set -o verbose not implemented')
self._SetArrayByNum(opt_num, b)
# note: may FAIL before we get here.
success = self.opt_hook.OnChange(self.opt_array, opt_name, b)
def SetOption(self, opt_name, b):
# type: (str, bool) -> None
""" For set -o, set +o, or shopt -s/-u -o. """
_ = _SetOptionNum(opt_name)
self._SetOption(opt_name, b)
UP_val = self.mem.GetVar('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 _SetGroup(self, opt_nums, b):
# type: (List[int], bool) -> None
for opt_num in opt_nums:
b2 = not b if opt_num in consts.DEFAULT_TRUE else b
self.opt_array[opt_num] = b2
self.errexit.Set(b) # Special case for all option groups
def SetShoptOption(self, opt_name, b):
# type: (str, bool) -> None
""" For shopt -s/-u. """
# shopt -s all:oil turns on all Oil options, which includes all strict #
# options
if opt_name == 'oil:basic':
self._SetGroup(consts.OIL_BASIC, b)
return
if opt_name == 'oil:all':
self._SetGroup(consts.OIL_ALL, b)
return
if opt_name == 'strict:all':
self._SetGroup(consts.STRICT_ALL, b)
return
opt_num = _ShoptOptionNum(opt_name)
self._SetArrayByNum(opt_num, b)
def ShowOptions(self, opt_names):
# type: (List[str]) -> None
""" For 'set -o' and 'shopt -p -o' """
# TODO: Maybe sort them differently?
if len(opt_names) == 0: # if none, supplied, show all
opt_names = [consts.OptionName(i) for i in consts.SET_OPTION_NUMS]
for opt_name in opt_names:
opt_num = _SetOptionNum(opt_name)
if opt_name == 'errexit':
b = self.errexit.value()
else:
b = self.opt_array[opt_num]
print('set %so %s' % ('-' if b else '+', opt_name))
def ShowShoptOptions(self, opt_names):
# type: (List[str]) -> None
""" For 'shopt -p' """
if len(opt_names) == 0:
opt_names = consts.VISIBLE_SHOPT_NAMES # if none supplied, show all
for opt_name in opt_names:
index = match.MatchOption(opt_name)
if index == 0:
e_usage('got invalid option %r' % opt_name)
b = self.opt_array[index]
print('shopt -%s %s' % ('s' if b else 'u', opt_name))
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, Any]
return {
'argv': self.argv,
'num_shifted': self.num_shifted,
}
def GetArgNum(self, arg_num):
# type: (int) -> value_t
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
if mylib.PYTHON:
def _DumpVarFrame(frame):
# type: (Dict[str, cell]) -> Any
"""Dump the stack frame as reasonably compact and readable JSON."""
vars_json = {}
for name, cell in frame.iteritems():
cell_json = {} # type: Dict[str, Any]
buf = mylib.BufWriter()
if cell.exported:
buf.write('x')
if cell.readonly:
buf.write('r')
flags = buf.getvalue()
if len(flags):
cell_json['flags'] = flags
# For compactness, just put the value right in the cell.
val = None # type: value_t
with tagswitch(cell.val) as case:
if case(value_e.Undef):
cell_json['type'] = 'Undef'
elif case(value_e.Str):
val = cast(value__Str, cell.val)
cell_json['type'] = 'Str'
cell_json['value'] = val.s
elif case(value_e.MaybeStrArray):
val = cast(value__MaybeStrArray, cell.val)
cell_json['type'] = 'MaybeStrArray'
cell_json['value'] = val.strs
elif case(value_e.AssocArray):
val = cast(value__AssocArray, cell.val)
cell_json['type'] = 'AssocArray'
cell_json['value'] = val.d
vars_json[name] = cell_json
return vars_json
class DirStack(object):
"""For pushd/popd/dirs."""
def __init__(self):
# type: () -> None
self.stack = [] # type: List[str]
self.Reset() # Invariant: it always has at least ONE entry.
def Reset(self):
# type: () -> None
del self.stack[:]
self.stack.append(posix.getcwd())
def Push(self, entry):
# type: (str) -> None
self.stack.append(entry)
def Pop(self):
# type: () -> Optional[str]
if len(self.stack) <= 1:
return None
self.stack.pop() # remove last
return self.stack[-1] # return second to last
def Iter(self):
# type: () -> List[str]
"""Iterate in reverse order."""
# mycpp REWRITE:
#return reversed(self.stack)
ret = [] # type: List[str]
ret.extend(self.stack)
ret.reverse()
return ret
# NOTE: not used!
if mylib.PYTHON:
def _FormatStack(var_stack):
# type: (List[Any]) -> str
"""Temporary debugging.
TODO: Turn this into a real JSON dump or something.
"""
f = cStringIO.StringIO()
for i, entry in enumerate(var_stack):
f.write('[%d] %s' % (i, entry))
f.write('\n')
return f.getvalue()
def _GetWorkingDir():
# type: () -> str
"""Fallback for pwd and $PWD when there's no 'cd' and no inherited $PWD."""
try:
return posix.getcwd()
except OSError as e:
e_die("Can't determine working directory: %s", pyutil.strerror_OS(e))
class DebugFrame(object):
def __init__(self, bash_source, func_name, source_name, call_spid, argv_i,
var_i):
# type: (Optional[str], Optional[str], Optional[str], int, int, int) -> None
self.bash_source = bash_source
# ONE of these is set. func_name for 'myproc a b', and source_name for
# 'source lib.sh'
self.func_name = func_name
self.source_name = source_name
self.call_spid = call_spid
self.argv_i = argv_i
self.var_i = var_i
def _InitDefaults(mem):
# type: (Mem) -> None
# Default value; user may unset it.
# $ echo -n "$IFS" | python -c 'import sys;print repr(sys.stdin.read())'
# ' \t\n'
SetGlobalString(mem, 'IFS', split.DEFAULT_IFS)
# NOTE: Should we put these in a name_map for Oil?
SetGlobalString(mem, 'UID', str(posix.getuid()))
SetGlobalString(mem, 'EUID', str(posix.geteuid()))
SetGlobalString(mem, 'PPID', str(posix.getppid()))
SetGlobalString(mem, 'HOSTNAME', libc.gethostname())
# In bash, this looks like 'linux-gnu', 'linux-musl', etc. Scripts test
# for 'darwin' and 'freebsd' too. They generally don't like at 'gnu' or
# 'musl'. We don't have that info, so just make it 'linux'.
SetGlobalString(mem, 'OSTYPE', pyos.OsType())
# For getopts builtin
SetGlobalString(mem, 'OPTIND', '1')
# For xtrace
SetGlobalString(mem, 'PS4', '+ ')
# bash-completion uses this. Value copied from bash. It doesn't integrate
# with 'readline' yet.
SetGlobalString(mem, 'COMP_WORDBREAKS', _READLINE_DELIMS)
# TODO on $HOME: bash sets it if it's a login shell and not in POSIX mode!
# if (login_shell == 1 && posixly_correct == 0)
# set_home_var ();
def _InitVarsFromEnv(mem, environ):
# type: (Mem, Dict[str, str]) -> None
# This is the way dash and bash work -- at startup, they turn everything in
# 'environ' variable into shell variables. Bash has an export_env
# variable. Dash has a loop through environ in init.c
for n, v in iteritems(environ):
mem.SetVar(lvalue.Named(n), value.Str(v), scope_e.GlobalOnly,
flags=SetExport)
# If it's not in the environment, initialize it. This makes it easier to
# update later in MutableOpts.
# TODO: IFS, etc. should follow this pattern. Maybe need a SysCall
# interface? self.syscall.getcwd() etc.
val = mem.GetVar('SHELLOPTS')
if val.tag_() == value_e.Undef:
SetGlobalString(mem, 'SHELLOPTS', '')
# Now make it readonly
mem.SetVar(
lvalue.Named('SHELLOPTS'), None, scope_e.GlobalOnly, flags=SetReadOnly)
# Usually we inherit PWD from the parent shell. When it's not set, we may
# compute it.
val = mem.GetVar('PWD')
if val.tag_() == value_e.Undef:
SetGlobalString(mem, 'PWD', _GetWorkingDir())
# Now mark it exported, no matter what. This is one of few variables
# EXPORTED. bash and dash both do it. (e.g. env -i -- dash -c env)
mem.SetVar(
lvalue.Named('PWD'), None, scope_e.GlobalOnly, flags=SetExport)
def InitMem(mem, environ, version_str):
# type: (Mem, Dict[str, str], str) -> None
"""
Initialize memory with shell defaults. Other interpreters could have
different builtin variables.
"""
SetGlobalString(mem, 'OIL_VERSION', version_str)
_InitDefaults(mem)
_InitVarsFromEnv(mem, environ)
# MUTABLE GLOBAL that's SEPARATE from $PWD. Used by the 'pwd' builtin, but
# it can't be modified by users.
val = mem.GetVar('PWD')
# should be true since it's exported
assert val.tag_() == value_e.Str, val
pwd = cast(value__Str, val).s
mem.SetPwd(pwd)
class ctx_Call(object):
def __init__(self, mem, func_name, def_spid, argv):
# type: (Mem, str, int, List[str]) -> None
mem.PushCall(func_name, def_spid, argv)
self.mem = mem
def __enter__(self):
# type: () -> None
pass
def __exit__(self, type, value, traceback):
# type: (Any, Any, Any) -> None
self.mem.PopCall()
class ctx_Temp(object):
def __init__(self, mem):
# type: (Mem) -> None
mem.PushTemp()
self.mem = mem
def __enter__(self):
# type: () -> None
pass
def __exit__(self, type, value, traceback):
# type: (Any, Any, Any) -> None
self.mem.PopTemp()
class Mem(object):
"""For storing variables.
Mem is better than "Env" -- Env implies OS stuff.
Callers:
User code: assigning and evaluating variables, in command context or
arithmetic context.
Completion engine: for COMP_WORDS, etc.
Builtins call it implicitly: read, cd for $PWD, $OLDPWD, etc.
Modules: cmd_eval, word_eval, expr_eval, completion
"""
def __init__(self, dollar0, argv, arena, debug_stack):
# type: (str, List[str], Arena, List[DebugFrame]) -> None
"""
Args:
arena: for computing BASH_SOURCE, etc. Could be factored out
"""
# circular dep initialized out of line
self.exec_opts = None # type: optview.Exec
self.dollar0 = dollar0
self.argv_stack = [_ArgFrame(argv)]
self.var_stack = [{}] # type: List[Dict[str, cell]]
self.arena = arena
# The debug_stack isn't strictly necessary for execution. We use it for
# crash dumps and for 4 parallel arrays: BASH_SOURCE, FUNCNAME,
# CALL_SOURCE, and BASH_LINENO.
self.debug_stack = debug_stack
self.current_spid = runtime.NO_SPID
self.line_num = value.Str('')
self.last_status = [0] # type: List[int] # a stack
self.pipe_status = [[]] # type: List[List[int]] # stack
self.last_bg_pid = -1 # Uninitialized value mutable public variable
# Done ONCE on initialization
self.root_pid = posix.getpid()
def __repr__(self):
# type: () -> str
parts = [] # type: List[str]
parts.append('<Mem')
for i, frame in enumerate(self.var_stack):
parts.append(' -- %d --' % i)
for n, v in frame.iteritems():
parts.append(' %s %s' % (n, v))
parts.append('>')
return '\n'.join(parts) + '\n'
def SetPwd(self, pwd):
# type: (str) -> None
"""Used by builtins."""
self.pwd = pwd
def InGlobalNamespace(self):
# type: () -> bool
"""For checking that syntax options are only used at the top level."""
return len(self.argv_stack) == 1
def Dump(self):
# type: () -> Tuple[Any, Any, Any]
"""Copy state before unwinding the stack."""
if mylib.PYTHON:
var_stack = [_DumpVarFrame(frame) for frame in self.var_stack]
argv_stack = [frame.Dump() for frame in self.argv_stack]
debug_stack = [] # type: List[Dict[str, Any]]
for frame in self.debug_stack:
d = {} # type: Dict[str, Any]
if frame.func_name:
d['func_called'] = frame.func_name
elif frame.source_name:
d['file_sourced'] = frame.source_name
else:
pass # It's a frame for FOO=bar? Or the top one?
d['call_spid'] = frame.call_spid
if frame.call_spid != runtime.NO_SPID: # first frame has this issue
span = self.arena.GetLineSpan(frame.call_spid)
line_id = span.line_id
d['call_source'] = self.arena.GetLineSourceString(line_id)
d['call_line_num'] = self.arena.GetLineNumber(line_id)
d['call_line'] = self.arena.GetLine(line_id)
d['argv_frame'] = frame.argv_i
d['var_frame'] = frame.var_i
debug_stack.append(d)
return var_stack, argv_stack, debug_stack
raise AssertionError()
def SetCurrentSpanId(self, span_id):
# type: (int) -> None
"""Set the current source location, for BASH_SOURCE, BASH_LINENO, LINENO,
etc.
It's also set on SimpleCommand, ShAssignment, ((, [[, etc. and used as
a fallback when e_die() didn't set any location information.
"""
if span_id == runtime.NO_SPID:
# NOTE: This happened in the osh-runtime benchmark for yash.
log('Warning: span_id undefined in SetCurrentSpanId')
#import traceback
#traceback.print_stack()
return
self.current_spid = span_id
def CurrentSpanId(self):
# type: () -> int
return self.current_spid
#
# Status Variable Stack (for isolating $PS1 and $PS4)
#
def PushStatusFrame(self):
# type: () -> None
self.last_status.append(0)
self.pipe_status.append([])
def PopStatusFrame(self):
# type: () -> None
self.last_status.pop()
self.pipe_status.pop()
def LastStatus(self):
# type: () -> int
return self.last_status[-1]
def PipeStatus(self):
# type: () -> List[int]
return self.pipe_status[-1]
def SetLastStatus(self, x):
# type: (int) -> None
self.last_status[-1] = x
def SetPipeStatus(self, x):
# type: (List[int]) -> None
self.pipe_status[-1] = x
#
# Call Stack
#
def PushCall(self, func_name, def_spid, argv):
# type: (str, int, List[str]) -> None
"""For function calls."""
self.argv_stack.append(_ArgFrame(argv))
self.var_stack.append({})
span = self.arena.GetLineSpan(def_spid)
source_str = self.arena.GetLineSourceString(span.line_id)
# bash uses this order: top of stack first.
self._PushDebugStack(source_str, func_name, None)
def PopCall(self):
# type: () -> None
self._PopDebugStack()
self.var_stack.pop()
self.argv_stack.pop()
def PushSource(self, source_name, argv):
# type: (str, List[str]) -> None
"""For 'source foo.sh 1 2 3."""
if len(argv):
self.argv_stack.append(_ArgFrame(argv))
# Match bash's behavior for ${FUNCNAME[@]}. But it would be nicer to add
# the name of the script here?
self._PushDebugStack(source_name, None, source_name)
def PopSource(self, argv):
# type: (List[str]) -> None
self._PopDebugStack()
if len(argv):
self.argv_stack.pop()
def PushTemp(self):
# type: () -> None
"""For the temporary scope in 'FOO=bar BAR=baz echo'."""
# We don't want the 'read' builtin to write to this frame!
self.var_stack.append({})
self._PushDebugStack(None, None, None)
def PopTemp(self):
# type: () -> None
self._PopDebugStack()
self.var_stack.pop()
def TopNamespace(self):
# type: () -> Dict[str, runtime_asdl.cell]
"""For evalblock()."""
return self.var_stack[-1]
def _PushDebugStack(self, bash_source, func_name, source_name):
# type: (Optional[str], Optional[str], Optional[str]) -> None
# self.current_spid is set before every SimpleCommand, ShAssignment, [[, ((,
# etc. Function calls and 'source' are both SimpleCommand.
# These integers are handles/pointers, for use in CrashDumper.
argv_i = len(self.argv_stack) - 1
var_i = len(self.var_stack) - 1
# The stack is a 5-tuple, where func_name and source_name are optional. If
# both are unset, then it's a "temp frame".
self.debug_stack.append(
DebugFrame(bash_source, func_name, source_name, self.current_spid, argv_i, var_i)
)
def _PopDebugStack(self):
# type: () -> None
self.debug_stack.pop()
#
# Argv
#
def Shift(self, n):
# type: (int) -> int
frame = self.argv_stack[-1]
num_args = len(frame.argv)
if (frame.num_shifted + n) <= num_args:
frame.num_shifted += n
return 0 # success
else:
return 1 # silent error
def GetArg0(self):
# type: () -> value__Str
"""Like GetArgNum(0) but with a more specific type."""
return value.Str(self.dollar0)
def GetArgNum(self, arg_num):
# type: (int) -> value_t
if arg_num == 0:
return value.Str(self.dollar0)
return self.argv_stack[-1].GetArgNum(arg_num)
def GetArgv(self):
# type: () -> List[str]
"""For $* and $@."""
return self.argv_stack[-1].GetArgv()
def SetArgv(self, argv):
# type: (List[str]) -> None
"""For set -- 1 2 3."""
# from set -- 1 2 3
self.argv_stack[-1].SetArgv(argv)
#
# Special Vars
#
def GetSpecialVar(self, op_id):
# type: (int) -> value_t
if op_id == Id.VSub_Bang: # $!