/
state.py
2124 lines (1706 loc) · 64.3 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
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 posix_ import X_OK # translated directly to C macro
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, Proc
from core import alloc
from osh import sh_expr_eval
# 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.GetValue('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, 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_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
def __enter__(self):
# type: () -> None
pass
def __exit__(self, type, value, traceback):
# type: (Any, Any, Any) -> None
self.mem.PopSource(self.argv)
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:
mutable_opts.errexit_disabled_spid.append(runtime.NO_SPID) # it wasn't disabled
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_spid.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.do_pop = False
if mutable_opts.Get(option_i.strict_errexit):
mutable_opts.Push(option_i.allow_command_sub, False)
self.do_pop = 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.do_pop:
self.mutable_opts.Pop(option_i.allow_command_sub)
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, span_id):
# type: (MutableOpts, bool, int) -> None
# If we're disabling it, we need a span ID. If not, then we should NOT
# have one.
assert b == (span_id == runtime.NO_SPID)
mutable_opts.Push(option_i.errexit, b)
mutable_opts.errexit_disabled_spid.append(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_disabled_spid.pop()
self.mutable_opts.Pop(option_i.errexit)
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, opt_hook):
# type: (Mem, OptHook) -> Tuple[optview.Parse, optview.Exec, MutableOpts]
# Unusual representation: opt0_array + opt_stacks. For two features:
#
# - POSIX errexit disable semantics
# - Oil's 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, opt0_array, opt_stacks, 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)
# Note: we relaxed this for Oil so we can do 'shopt --unset errexit' consistently
# 'set' is for assignment!
#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)
if opt_num not in consts.SET_OPTION_NUMS:
e_usage("invalid option %r (try -O or shopt)" % opt_name)
return opt_num
class MutableOpts(object):
def __init__(self, mem, opt0_array, opt_stacks, opt_hook):
# type: (Mem, List[bool], List[List[bool]], OptHook) -> None
self.mem = mem
self.opt0_array = opt0_array
self.opt_stacks = opt_stacks
self.errexit_disabled_spid = [] # type: List[int]
# Used for 'set -o vi/emacs'
self.opt_hook = opt_hook
def Init(self):
# type: () -> None
# This comes after all the 'set' options.
UP_shellopts = self.mem.GetValue('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 Push(self, opt_num, b):
# type: (int, bool) -> None
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."""
# 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_proc(self):
# type: () -> None
"""For interactive shells."""
self._Set(option_i.redefine_proc, True)
def set_redefine_module(self):
# type: () -> None
"""For interactive shells."""
self._Set(option_i.redefine_module, True)
def set_emacs(self):
# type: () -> None
self._Set(option_i.emacs, True)
def set_xtrace(self, b):
# type: (bool) -> None
self._Set(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._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 oil:all, oil:basic
"""
#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 ErrExitDisabledSpanId(self):
# type: () -> int
"""If errexit is disabled by POSIX rules, return span ID for construct.
e.g. the spid for 'if' or '&&' etc.
Otherwise return runtime.NO_SPID
"""
# 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 runtime.NO_SPID
overlay = self.opt_stacks[option_i.errexit]
if 0:
log('overlay %s', overlay)
log('errexit_disabled_spid %s', self.errexit_disabled_spid)
if overlay is None or len(overlay) == 0:
return runtime.NO_SPID
else:
was_on = self.opt0_array[option_i.errexit] or (True in overlay)
# top of stack == False means it's disabled
if was_on and not overlay[-1]:
return self.errexit_disabled_spid[-1]
else:
return runtime.NO_SPID
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.SetDeferredErrExit(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.opt0_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) # validate it
self._SetOption(opt_name, b)
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 _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.opt0_array[opt_num] = b2
def SetShoptOption(self, opt_name, b):
# type: (str, bool) -> None
""" For shopt -s/-u and sh -O/+O. """
# 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)
self.SetDeferredErrExit(b) # Special case
return
if opt_name == 'oil:all':
self._SetGroup(consts.OIL_ALL, b)
self.SetDeferredErrExit(b) # Special case
return
if opt_name == 'strict:all':
self._SetGroup(consts.STRICT_ALL, b)
return
opt_num = _ShoptOptionNum(opt_name)
if opt_num == option_i.errexit:
self.SetDeferredErrExit(b)
return
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)
b = self.Get(opt_num)
print('set %so %s' % ('-' if b else '+', opt_name))
def ShowShoptOptions(self, opt_names):
# type: (List[str]) -> None
""" For 'shopt -p' """
# Respect option gropus.
opt_nums = [] # type: List[int]
for opt_name in opt_names:
if opt_name == 'oil:basic':
opt_nums.extend(consts.OIL_BASIC)
elif opt_name == 'oil:all':
opt_nums.extend(consts.OIL_ALL)
elif opt_name == 'strict:all':
opt_nums.extend(consts.STRICT_ALL)
else:
index = match.MatchOption(opt_name)
# Minor incompatibility with bash: we validate everything before
# printing.
if index == 0:
e_usage('got invalid option %r' % opt_name)
opt_nums.append(index)
if len(opt_names) == 0:
# If none supplied, show all>
# TODO: Should this show 'set' options too?
opt_nums.extend(consts.VISIBLE_SHOPT_NUMS)
for opt_num in opt_nums:
b = self.opt0_array[opt_num]
print('shopt -%s %s' % ('s' if b else 'u', consts.OptionName(opt_num)))
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))
if mylib.PYTHON: # mycpp has problem with dict literal
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(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')
# When xtrace_rich is off, this is just like '+ ', the shell default
SetGlobalString(mem, 'PS4', '${SHX_indent}${SHX_punct}${SHX_pid_str} ')
# 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.SetValue(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.GetValue('SHELLOPTS')
if val.tag_() == value_e.Undef:
SetGlobalString(mem, 'SHELLOPTS', '')
# Now make it readonly
mem.SetValue(
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.GetValue('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.SetValue(
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.GetValue('PWD')
# should be true since it's exported
assert val.tag_() == value_e.Str, val
pwd = cast(value__Str, val).s
mem.SetPwd(pwd)
def InitInteractive(mem):
# type: (Mem) -> None
"""Initialization that's only done in the interactive/headless shell."""
# Same default PS1 as bash
if mem.GetValue('PS1').tag_() == value_e.Undef:
SetGlobalString(mem, 'PS1', r'\s-\v\$ ')
class ctx_Call(object):
"""For function calls."""
def __init__(self, mem, mutable_opts, proc, argv):
# type: (Mem, MutableOpts, Proc, List[str]) -> None
mem.PushCall(proc.name, proc.name_spid, argv)
mutable_opts.PushDynamicScope(proc.dynamic_scope)
# 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
def __enter__(self):
# type: () -> None
pass
def __exit__(self, type, value, traceback):
# type: (Any, Any, Any) -> None
self.mutable_opts.PopDynamicScope()
self.mem.PopCall()
class ctx_Temp(object):
"""For FOO=bar myfunc, etc."""
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 ctx_Shvar(object):
"""For shvar LANG=C _ESCAPER=posix-sh-word _DIALECT=ninja """
def __init__(self, mem, pairs):
# type: (Mem, List[Tuple[str, str]]) -> None
#log('pairs %s', pairs)
self.mem = mem
self.restore = [] # type: List[Tuple[lvalue_t, value_t]]
self._Push(pairs)
def __enter__(self):
# type: () -> None
pass
def __exit__(self, type, value, traceback):
# type: (Any, Any, Any) -> None
self._Pop()
# Note: _Push and _Pop are separate methods because the C++ translation
# doesn't like when they are inline in __init__ and __exit__.
def _Push(self, pairs):
# type: (List[Tuple[str, str]]) -> None
for name, s in pairs:
lval = lvalue.Named(name) # type: lvalue_t
# LocalOnly because we are only overwriting the current scope
old_val = self.mem.GetValue(name, scope_e.LocalOnly)
self.restore.append((lval, old_val))
self.mem.SetValue(lval, value.Str(s), scope_e.LocalOnly)
def _Pop(self):
# type: () -> None
for lval, old_val in self.restore:
if old_val.tag_() == value_e.Undef:
self.mem.Unset(lval, scope_e.LocalOnly)
else:
self.mem.SetValue(lval, old_val, scope_e.LocalOnly)
class ctx_Registers(object):
"""For $PS1, $PS4, $PROMPT_COMMAND, traps, and headless EVAL."""
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)
# 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_matches.append([])
self.mem = mem
def __enter__(self):
# type: () -> None
pass
def __exit__(self, type, value, traceback):
# type: (Any, Any, Any) -> None
self.mem.regex_matches.pop()
self.mem.process_sub_status.pop()
self.mem.pipe_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()
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], alloc.Arena, List[DebugFrame]) -> None
"""
Args:
arena: for computing BASH_SOURCE, etc. Could be factored out