OILS / core / shell.py View on Github | oils.pub

1231 lines, 790 significant
1"""
2core/shell.py -- Entry point for the shell interpreter.
3"""
4from __future__ import print_function
5
6from errno import ENOENT
7import time as time_
8
9from _devbuild.gen import arg_types
10from _devbuild.gen.option_asdl import option_i, builtin_i
11from _devbuild.gen.syntax_asdl import (loc, source, source_t, IntParamBox,
12 debug_frame, debug_frame_t)
13from _devbuild.gen.value_asdl import (value, value_e, value_t, value_str, Obj)
14from core import alloc
15from core import comp_ui
16from core import dev
17from core import error
18from core import executor
19from core import completion
20from core import main_loop
21from core import optview
22from core import process
23from core import pyutil
24from core import sh_init
25from core import state
26from display import ui
27from core import util
28from core import vm
29
30from frontend import args
31from frontend import flag_def # side effect: flags are defined!
32
33unused1 = flag_def
34from frontend import flag_util
35from frontend import reader
36from frontend import parse_lib
37
38from builtin import assign_osh
39from builtin import bracket_osh
40from builtin import completion_osh
41from builtin import completion_ysh
42from builtin import dirs_osh
43from builtin import error_ysh
44from builtin import hay_ysh
45from builtin import io_osh
46from builtin import io_ysh
47from builtin import json_ysh
48from builtin import meta_oils
49from builtin import misc_osh
50from builtin import module_ysh
51from builtin import printf_osh
52from builtin import process_osh
53from builtin import pure_osh
54from builtin import pure_ysh
55from builtin import readline_osh
56from builtin import read_osh
57from builtin import trap_osh
58
59from builtin import func_eggex
60from builtin import func_hay
61from builtin import func_misc
62from builtin import func_reflect
63
64from builtin import method_dict
65from builtin import method_io
66from builtin import method_list
67from builtin import method_other
68from builtin import method_str
69from builtin import method_type
70
71from osh import cmd_eval
72from osh import glob_
73from osh import history
74from osh import prompt
75from osh import sh_expr_eval
76from osh import split
77from osh import word_eval
78
79from mycpp import iolib
80from mycpp import mops
81from mycpp import mylib
82from mycpp.mylib import NewDict, print_stderr, log
83from pylib import os_path
84from tools import deps
85from tools import fmt
86from tools import ysh_ify
87from ysh import expr_eval
88
89unused2 = log
90
91import libc
92import posix_ as posix
93
94from typing import List, Dict, Optional, TYPE_CHECKING
95if TYPE_CHECKING:
96 from frontend.py_readline import Readline
97
98if mylib.PYTHON:
99 try:
100 from _devbuild.gen import help_meta # type: ignore
101 except ImportError:
102 help_meta = None
103
104DEFAULT_TERM_WIDTH = 80
105
106
107def _InitDefaultCompletions(cmd_ev, complete_builtin, comp_lookup):
108 # type: (cmd_eval.CommandEvaluator, completion_osh.Complete, completion.Lookup) -> None
109
110 # register builtins and words
111 complete_builtin.Run(cmd_eval.MakeBuiltinArgv(['-E', '-A', 'command']))
112 # register path completion
113 # Add -o filenames? Or should that be automatic?
114 complete_builtin.Run(cmd_eval.MakeBuiltinArgv(['-D', '-A', 'file']))
115
116
117def _CompletionDemo(comp_lookup):
118 # type: (completion.Lookup) -> None
119
120 # Something for fun, to show off. Also: test that you don't repeatedly hit
121 # the file system / network / coprocess.
122 A1 = completion.TestAction(['foo.py', 'foo', 'bar.py'], 0.0)
123 l = [] # type: List[str]
124 for i in xrange(0, 5):
125 l.append('m%d' % i)
126
127 A2 = completion.TestAction(l, 0.1)
128 C1 = completion.UserSpec([A1, A2], [], [], completion.DefaultPredicate(),
129 '', '')
130 comp_lookup.RegisterName('slowc', {}, C1)
131
132
133def SourceStartupFile(
134 fd_state, # type: process.FdState
135 rc_path, # type: str
136 lang, # type: str
137 parse_ctx, # type: parse_lib.ParseContext
138 cmd_ev, # type: cmd_eval.CommandEvaluator
139 errfmt, # type: ui.ErrorFormatter
140):
141 # type: (...) -> None
142
143 # Right now this is called when the shell is interactive. (Maybe it should
144 # be called on login_shel too.)
145 #
146 # Terms:
147 # - interactive shell: Roughly speaking, no args or -c, and isatty() is true
148 # for stdin and stdout.
149 # - login shell: Started from the top level, e.g. from init or ssh.
150 #
151 # We're not going to copy everything bash does because it's too complex, but
152 # for reference:
153 # https://www.gnu.org/software/bash/manual/bash.html#Bash-Startup-Files
154 # Bash also has --login.
155
156 try:
157 f = fd_state.Open(rc_path)
158 except (IOError, OSError) as e:
159 # TODO: Could warn about nonexistent explicit --rcfile?
160 if e.errno != ENOENT:
161 raise # Goes to top level. Handle this better?
162 return
163
164 arena = parse_ctx.arena
165 rc_line_reader = reader.FileLineReader(f, arena)
166 rc_c_parser = parse_ctx.MakeOshParser(rc_line_reader)
167
168 with alloc.ctx_SourceCode(arena, source.MainFile(rc_path)):
169 # TODO: handle status, e.g. 2 for ParseError
170 unused = main_loop.Batch(cmd_ev, rc_c_parser, errfmt)
171
172 f.close()
173
174
175class ShellOptHook(state.OptHook):
176
177 def __init__(self, readline):
178 # type: (Optional[Readline]) -> None
179 self.readline = readline
180
181 def OnChange(self, opt0_array, opt_name, b):
182 # type: (List[bool], str, bool) -> bool
183 """This method is called whenever an option is changed.
184
185 Returns success or failure.
186 """
187 if opt_name == 'vi' or opt_name == 'emacs':
188 # TODO: Replace with a hook? Just like setting LANG= can have a hook.
189 if self.readline:
190 self.readline.parse_and_bind("set editing-mode " + opt_name)
191 else:
192 print_stderr(
193 "Warning: Can't set option %r because shell wasn't compiled with GNU readline"
194 % opt_name)
195 return False
196
197 # Invert: they are mutually exclusive!
198 if opt_name == 'vi':
199 opt0_array[option_i.emacs] = not b
200 elif opt_name == 'emacs':
201 opt0_array[option_i.vi] = not b
202
203 return True
204
205
206def _AddBuiltinFunc(mem, name, func):
207 # type: (state.Mem, str, vm._Callable) -> None
208 assert isinstance(func, vm._Callable), func
209 mem.AddBuiltin(name, value.BuiltinFunc(func))
210
211
212def InitAssignmentBuiltins(
213 mem, # type: state.Mem
214 procs, # type: state.Procs
215 exec_opts, # type: optview.Exec
216 errfmt, # type: ui.ErrorFormatter
217):
218 # type: (...) -> Dict[int, vm._AssignBuiltin]
219
220 assign_b = {} # type: Dict[int, vm._AssignBuiltin]
221
222 new_var = assign_osh.NewVar(mem, procs, exec_opts, errfmt)
223 assign_b[builtin_i.declare] = new_var
224 assign_b[builtin_i.typeset] = new_var
225 assign_b[builtin_i.local] = new_var
226
227 assign_b[builtin_i.export_] = assign_osh.Export(mem, errfmt)
228 assign_b[builtin_i.readonly] = assign_osh.Readonly(mem, errfmt)
229
230 return assign_b
231
232
233def Main(
234 lang, # type: str
235 arg_r, # type: args.Reader
236 environ, # type: Dict[str, str]
237 login_shell, # type: bool
238 loader, # type: pyutil._ResourceLoader
239 readline, # type: Optional[Readline]
240):
241 # type: (...) -> int
242 """The full shell lifecycle. Used by bin/osh and bin/ysh.
243
244 Args:
245 lang: 'osh' or 'ysh'
246 login_shell: Was - on argv[0]?
247 loader: to get help, version, grammar, etc.
248 readline: optional GNU readline
249 """
250 # Differences between osh and ysh:
251 # - oshrc vs yshrc
252 # - shopt -s ysh:all
253 # - Prompt
254 # - --help
255
256 argv0 = arg_r.Peek()
257 assert argv0 is not None
258 arg_r.Next()
259
260 assert lang in ('osh', 'ysh'), lang
261
262 try:
263 attrs = flag_util.ParseMore('main', arg_r)
264 except error.Usage as e:
265 print_stderr('%s usage error: %s' % (lang, e.msg))
266 return 2
267 flag = arg_types.main(attrs.attrs)
268
269 arena = alloc.Arena()
270 errfmt = ui.ErrorFormatter()
271
272 if flag.help:
273 util.HelpFlag(loader, '%s-usage' % lang, mylib.Stdout())
274 return 0
275 if flag.version:
276 util.VersionFlag(loader, mylib.Stdout())
277 return 0
278
279 if flag.tool == 'cat-em':
280 paths = arg_r.Rest()
281
282 status = 0
283 for p in paths:
284 try:
285 contents = loader.Get(p)
286 print(contents)
287 except (OSError, IOError):
288 print_stderr("cat-em: %r not found" % p)
289 status = 1
290 return status
291
292 debug_stack = [] # type: List[debug_frame_t]
293 if arg_r.AtEnd():
294 dollar0 = argv0
295 else:
296 dollar0 = arg_r.Peek() # the script name, or the arg after -c
297
298 frame0 = debug_frame.Main(dollar0)
299 debug_stack.append(frame0)
300
301 script_name = arg_r.Peek() # type: Optional[str]
302 arg_r.Next()
303
304 env_dict = NewDict() # type: Dict[str, value_t]
305 defaults = NewDict() # type: Dict[str, value_t]
306 mem = state.Mem(dollar0,
307 arg_r.Rest(),
308 arena,
309 debug_stack,
310 env_dict,
311 defaults=defaults)
312
313 opt_hook = ShellOptHook(readline)
314 # Note: only MutableOpts needs mem, so it's not a true circular dep.
315 parse_opts, exec_opts, mutable_opts = state.MakeOpts(
316 mem, environ, opt_hook)
317 mem.exec_opts = exec_opts # circular dep
318 mutable_opts.Init()
319
320 # Set these BEFORE processing flags, so they can be overridden.
321 if lang == 'ysh':
322 mutable_opts.SetAnyOption('ysh:all', True)
323
324 pure_osh.SetOptionsFromFlags(mutable_opts, attrs.opt_changes,
325 attrs.shopt_changes)
326
327 version_str = pyutil.GetVersion(loader)
328 sh_init.InitBuiltins(mem, version_str, defaults)
329 sh_init.InitDefaultVars(mem)
330
331 sh_init.CopyVarsFromEnv(exec_opts, environ, mem)
332
333 # PATH PWD SHELLOPTS, etc. must be set after CopyVarsFromEnv()
334 sh_init.InitVarsAfterEnv(mem)
335
336 if attrs.show_options: # special case: sh -o
337 pure_osh.ShowOptions(mutable_opts, [])
338 return 0
339
340 # feedback between runtime and parser
341 aliases = NewDict() # type: Dict[str, str]
342
343 ysh_grammar = pyutil.LoadYshGrammar(loader)
344
345 if flag.do_lossless and not exec_opts.noexec():
346 raise error.Usage('--one-pass-parse requires noexec (-n)', loc.Missing)
347
348 # Tools always use one pass parse
349 # Note: osh --tool syntax-tree is like osh -n --one-pass-parse
350 do_lossless = True if len(flag.tool) else flag.do_lossless
351
352 parse_ctx = parse_lib.ParseContext(arena,
353 parse_opts,
354 aliases,
355 ysh_grammar,
356 do_lossless=do_lossless)
357
358 # Three ParseContext instances SHARE aliases.
359 comp_arena = alloc.Arena()
360 comp_arena.PushSource(source.Unused('completion'))
361 trail1 = parse_lib.Trail()
362 # do_lossless needs to be turned on to complete inside backticks. TODO:
363 # fix the issue where ` gets erased because it's not part of
364 # set_completer_delims().
365 comp_ctx = parse_lib.ParseContext(comp_arena,
366 parse_opts,
367 aliases,
368 ysh_grammar,
369 do_lossless=True)
370 comp_ctx.Init_Trail(trail1)
371
372 hist_arena = alloc.Arena()
373 hist_arena.PushSource(source.Unused('history'))
374 trail2 = parse_lib.Trail()
375 hist_ctx = parse_lib.ParseContext(hist_arena, parse_opts, aliases,
376 ysh_grammar)
377 hist_ctx.Init_Trail(trail2)
378
379 # Deps helps manages dependencies. These dependencies are circular:
380 # - cmd_ev and word_ev, arith_ev -- for command sub, arith sub
381 # - arith_ev and word_ev -- for $(( ${a} )) and $x$(( 1 ))
382 # - cmd_ev and builtins (which execute code, like eval)
383 # - prompt_ev needs word_ev for $PS1, which needs prompt_ev for @P
384 cmd_deps = cmd_eval.Deps()
385 cmd_deps.mutable_opts = mutable_opts
386
387 job_control = process.JobControl()
388 job_list = process.JobList()
389 fd_state = process.FdState(errfmt, job_control, job_list, mem, None, None,
390 exec_opts)
391
392 my_pid = posix.getpid()
393
394 debug_path = ''
395 debug_dir = environ.get('OILS_DEBUG_DIR')
396 if flag.debug_file is not None:
397 # --debug-file takes precedence over OSH_DEBUG_DIR
398 debug_path = flag.debug_file
399 elif debug_dir is not None:
400 debug_path = os_path.join(debug_dir, '%d-osh.log' % my_pid)
401
402 if len(debug_path):
403 # This will be created as an empty file if it doesn't exist, or it could be
404 # a pipe.
405 try:
406 debug_f = util.DebugFile(
407 fd_state.OpenForWrite(debug_path)) # type: util._DebugFile
408 except (IOError, OSError) as e:
409 print_stderr("%s: Couldn't open %r: %s" %
410 (lang, debug_path, posix.strerror(e.errno)))
411 return 2
412 else:
413 debug_f = util.NullDebugFile()
414
415 if flag.xtrace_to_debug_file:
416 trace_f = debug_f
417 else:
418 trace_f = util.DebugFile(mylib.Stderr())
419
420 trace_dir = environ.get('OILS_TRACE_DIR', '')
421 dumps = environ.get('OILS_TRACE_DUMPS', '')
422 streams = environ.get('OILS_TRACE_STREAMS', '')
423 multi_trace = dev.MultiTracer(my_pid, trace_dir, dumps, streams, fd_state)
424
425 tracer = dev.Tracer(parse_ctx, exec_opts, mutable_opts, mem, trace_f,
426 multi_trace)
427 fd_state.tracer = tracer # circular dep
428
429 signal_safe = iolib.InitSignalSafe()
430 trap_state = trap_osh.TrapState(signal_safe)
431
432 waiter = process.Waiter(job_list, exec_opts, signal_safe, tracer)
433 fd_state.waiter = waiter
434
435 cmd_deps.debug_f = debug_f
436
437 now = time_.time()
438 iso_stamp = time_.strftime("%Y-%m-%d %H:%M:%S", time_.localtime(now))
439
440 argv_buf = mylib.BufWriter()
441 dev.PrintShellArgv(arg_r.argv, argv_buf)
442
443 debug_f.writeln('%s [%d] Oils started with argv %s' %
444 (iso_stamp, my_pid, argv_buf.getvalue()))
445 if len(debug_path):
446 debug_f.writeln('Writing logs to %r' % debug_path)
447
448 interp = environ.get('OILS_HIJACK_SHEBANG', '')
449 search_path = executor.SearchPath(mem, exec_opts)
450 ext_prog = process.ExternalProgram(interp, fd_state, errfmt, debug_f)
451
452 splitter = split.SplitContext(mem)
453 # TODO: This is instantiation is duplicated in osh/word_eval.py
454 globber = glob_.Globber(exec_opts)
455
456 # This could just be OILS_TRACE_DUMPS='crash:argv0'
457 crash_dump_dir = environ.get('OILS_CRASH_DUMP_DIR', '')
458 cmd_deps.dumper = dev.CrashDumper(crash_dump_dir, fd_state)
459
460 comp_lookup = completion.Lookup()
461
462 # Various Global State objects to work around readline interfaces
463 compopt_state = completion.OptionState()
464
465 comp_ui_state = comp_ui.State()
466 prompt_state = comp_ui.PromptState()
467
468 # The login program is supposed to set $HOME
469 # https://superuser.com/questions/271925/where-is-the-home-environment-variable-set
470 # state.InitMem(mem) must happen first
471 tilde_ev = word_eval.TildeEvaluator(mem, exec_opts)
472 home_dir = tilde_ev.GetMyHomeDir()
473 if home_dir is None:
474 # TODO: print errno from getpwuid()
475 print_stderr("%s: Failed to get home dir from $HOME or getpwuid()" %
476 lang)
477 return 1
478
479 sh_files = sh_init.ShellFiles(lang, home_dir, mem, flag)
480
481 #
482 # Executor and Evaluators (are circularly dependent)
483 #
484
485 # Global proc namespace. Funcs are defined in the common variable
486 # namespace.
487 procs = state.Procs(mem) # type: state.Procs
488
489 builtins = {} # type: Dict[int, vm._Builtin]
490
491 # e.g. s.startswith()
492 methods = {} # type: Dict[int, Dict[str, vm._Callable]]
493
494 hay_state = hay_ysh.HayState()
495
496 shell_ex = executor.ShellExecutor(mem, exec_opts, mutable_opts, procs,
497 hay_state, builtins, search_path,
498 ext_prog, waiter, tracer, job_control,
499 job_list, fd_state, trap_state, errfmt)
500
501 arith_ev = sh_expr_eval.ArithEvaluator(mem, exec_opts, mutable_opts,
502 parse_ctx, errfmt)
503 bool_ev = sh_expr_eval.BoolEvaluator(mem, exec_opts, mutable_opts,
504 parse_ctx, errfmt)
505 expr_ev = expr_eval.ExprEvaluator(mem, mutable_opts, methods, splitter,
506 errfmt)
507 word_ev = word_eval.NormalWordEvaluator(mem, exec_opts, mutable_opts,
508 tilde_ev, splitter, errfmt)
509
510 assign_b = InitAssignmentBuiltins(mem, procs, exec_opts, errfmt)
511 cmd_ev = cmd_eval.CommandEvaluator(mem, exec_opts, errfmt, procs, assign_b,
512 arena, cmd_deps, trap_state,
513 signal_safe)
514
515 # PromptEvaluator rendering is needed in non-interactive shells for @P.
516 prompt_ev = prompt.Evaluator(lang, version_str, parse_ctx, mem)
517
518 io_methods = NewDict() # type: Dict[str, value_t]
519 io_methods['promptVal'] = value.BuiltinFunc(method_io.PromptVal(prompt_ev))
520
521 # The M/ prefix means it's io->eval()
522 io_methods['M/eval'] = value.BuiltinFunc(
523 method_io.Eval(mem, cmd_ev, method_io.EVAL_NULL))
524 io_methods['M/evalToDict'] = value.BuiltinFunc(
525 method_io.Eval(mem, cmd_ev, method_io.EVAL_DICT))
526 io_methods['M/evalInFrame'] = value.BuiltinFunc(
527 method_io.EvalInFrame(mem, cmd_ev))
528 io_methods['M/evalExpr'] = value.BuiltinFunc(method_io.EvalExpr(expr_ev))
529
530 # Identical to command sub
531 io_methods['captureStdout'] = value.BuiltinFunc(
532 method_io.CaptureStdout(mem, shell_ex))
533
534 # TODO:
535 io_methods['time'] = value.BuiltinFunc(method_io.Time())
536 io_methods['strftime'] = value.BuiltinFunc(method_io.Strftime())
537 io_methods['glob'] = value.BuiltinFunc(method_io.Glob())
538
539 io_props = {'stdin': value.Stdin} # type: Dict[str, value_t]
540 io_obj = Obj(Obj(None, io_methods), io_props)
541
542 vm_methods = NewDict() # type: Dict[str, value_t]
543 # These are methods, not free functions, because they reflect VM state
544 vm_methods['getFrame'] = value.BuiltinFunc(func_reflect.GetFrame(mem))
545 vm_methods['id'] = value.BuiltinFunc(func_reflect.Id())
546
547 vm_props = NewDict() # type: Dict[str, value_t]
548 vm_obj = Obj(Obj(None, vm_methods), vm_props)
549
550 # Add basic type objects for flag parser
551 # flag -v --verbose (Bool, help='foo')
552 #
553 # TODO:
554 # - Add other types like Dict, CommandFlag
555 # - Obj(first, rest)
556 # - List() Dict() Obj() can do shallow copy with __call__
557
558 # - type(x) should return these Obj, or perhaps typeObj(x)
559 # - __str__ method for echo $[type(x)] ?
560
561 # TODO: List and Dict could be the only ones with __index__?
562 i_func = method_type.Index__()
563 type_m = NewDict() # type: Dict[str, value_t]
564 type_m['__index__'] = value.BuiltinFunc(i_func)
565 type_obj_methods = Obj(None, type_m)
566
567 # Note: Func[Int -> Int] is something we should do?
568 for tag in [
569 value_e.Bool,
570 value_e.Int,
571 value_e.Float,
572 value_e.Str,
573 value_e.List,
574 value_e.Dict,
575 ]:
576 type_name = value_str(tag, dot=False)
577 #log('%s %s' , type_name, tag)
578 type_obj = Obj(type_obj_methods, {'name': value.Str(type_name)})
579 mem.AddBuiltin(type_name, type_obj)
580
581 # Initialize Obj
582 tag = value_e.Obj
583 type_name = value_str(tag, dot=False)
584
585 # TODO: change Obj.new to __call__
586 type_props = NewDict() # type: Dict[str, value_t]
587 type_props['name'] = value.Str(type_name)
588 type_props['new'] = value.BuiltinFunc(func_misc.Obj_call())
589 type_obj = Obj(type_obj_methods, type_props)
590
591 mem.AddBuiltin(type_name, type_obj)
592
593 # Wire up circular dependencies.
594 vm.InitCircularDeps(arith_ev, bool_ev, expr_ev, word_ev, cmd_ev, shell_ex,
595 prompt_ev, io_obj, tracer)
596
597 unsafe_arith = sh_expr_eval.UnsafeArith(mem, exec_opts, mutable_opts,
598 parse_ctx, arith_ev, errfmt)
599 vm.InitUnsafeArith(mem, word_ev, unsafe_arith)
600
601 #
602 # Initialize Built-in Procs
603 #
604
605 b = builtins # short alias for initialization
606
607 if mylib.PYTHON:
608 if help_meta:
609 help_data = help_meta.TopicMetadata()
610 else:
611 help_data = NewDict() # minimal build
612 else:
613 help_data = help_meta.TopicMetadata()
614 b[builtin_i.help] = misc_osh.Help(lang, loader, help_data, errfmt)
615
616 # Interpreter state
617 b[builtin_i.set] = pure_osh.Set(mutable_opts, mem)
618 b[builtin_i.shopt] = pure_osh.Shopt(exec_opts, mutable_opts, cmd_ev, mem,
619 environ)
620
621 b[builtin_i.hash] = pure_osh.Hash(search_path) # not really pure
622 b[builtin_i.trap] = trap_osh.Trap(trap_state, parse_ctx, tracer, errfmt)
623
624 b[builtin_i.shvar] = pure_ysh.Shvar(mem, search_path, cmd_ev)
625 b[builtin_i.ctx] = pure_ysh.Ctx(mem, cmd_ev)
626 b[builtin_i.push_registers] = pure_ysh.PushRegisters(mem, cmd_ev)
627
628 # Hay
629 b[builtin_i.hay] = hay_ysh.Hay(hay_state, mutable_opts, mem, cmd_ev)
630 b[builtin_i.haynode] = hay_ysh.HayNode_(hay_state, mem, cmd_ev)
631
632 # Interpreter introspection
633 b[builtin_i.type] = meta_oils.Type(procs, aliases, search_path, errfmt)
634 b[builtin_i.builtin] = meta_oils.Builtin(shell_ex, errfmt)
635 b[builtin_i.command] = meta_oils.Command(shell_ex, procs, aliases,
636 search_path)
637 # Part of YSH, but similar to builtin/command
638 b[builtin_i.runproc] = meta_oils.RunProc(shell_ex, procs, errfmt)
639 b[builtin_i.invoke] = meta_oils.Invoke(shell_ex, procs, errfmt)
640 b[builtin_i.extern_] = meta_oils.Extern(shell_ex, procs, errfmt)
641
642 # Meta builtins
643 module_invoke = module_ysh.ModuleInvoke(cmd_ev, tracer, errfmt)
644 b[builtin_i.use] = meta_oils.ShellFile(parse_ctx,
645 search_path,
646 cmd_ev,
647 fd_state,
648 tracer,
649 errfmt,
650 loader,
651 module_invoke=module_invoke)
652 source_builtin = meta_oils.ShellFile(parse_ctx, search_path, cmd_ev,
653 fd_state, tracer, errfmt, loader)
654 b[builtin_i.source] = source_builtin
655 b[builtin_i.dot] = source_builtin
656 b[builtin_i.eval] = meta_oils.Eval(parse_ctx, exec_opts, cmd_ev, tracer,
657 errfmt, mem)
658
659 # Module builtins
660 guards = NewDict() # type: Dict[str, bool]
661 b[builtin_i.source_guard] = module_ysh.SourceGuard(guards, exec_opts,
662 errfmt)
663 b[builtin_i.is_main] = module_ysh.IsMain(mem)
664
665 # Errors
666 b[builtin_i.error] = error_ysh.Error()
667 b[builtin_i.failed] = error_ysh.Failed(mem)
668 b[builtin_i.boolstatus] = error_ysh.BoolStatus(shell_ex, errfmt)
669 b[builtin_i.try_] = error_ysh.Try(mutable_opts, mem, cmd_ev, shell_ex,
670 errfmt)
671 b[builtin_i.assert_] = error_ysh.Assert(expr_ev, errfmt)
672
673 # Pure builtins
674 true_ = pure_osh.Boolean(0)
675 b[builtin_i.colon] = true_ # a "special" builtin
676 b[builtin_i.true_] = true_
677 b[builtin_i.false_] = pure_osh.Boolean(1)
678
679 b[builtin_i.alias] = pure_osh.Alias(aliases, errfmt)
680 b[builtin_i.unalias] = pure_osh.UnAlias(aliases, errfmt)
681
682 b[builtin_i.getopts] = pure_osh.GetOpts(mem, errfmt)
683
684 b[builtin_i.shift] = assign_osh.Shift(mem)
685 b[builtin_i.unset] = assign_osh.Unset(mem, procs, unsafe_arith, errfmt)
686
687 b[builtin_i.append] = pure_ysh.Append(mem, errfmt)
688
689 # test / [ differ by need_right_bracket
690 b[builtin_i.test] = bracket_osh.Test(False, exec_opts, mem, errfmt)
691 b[builtin_i.bracket] = bracket_osh.Test(True, exec_opts, mem, errfmt)
692
693 # Output
694 b[builtin_i.echo] = io_osh.Echo(exec_opts)
695 b[builtin_i.printf] = printf_osh.Printf(mem, parse_ctx, unsafe_arith,
696 errfmt)
697 b[builtin_i.write] = io_ysh.Write(mem, errfmt)
698 redir_builtin = io_ysh.RunBlock(mem, cmd_ev) # used only for redirects
699 b[builtin_i.redir] = redir_builtin
700 b[builtin_i.fopen] = redir_builtin # alias for backward compatibility
701
702 # (pp output format isn't stable)
703 b[builtin_i.pp] = io_ysh.Pp(expr_ev, mem, errfmt, procs, arena)
704
705 # Input
706 b[builtin_i.cat] = io_osh.Cat() # for $(<file)
707 b[builtin_i.read] = read_osh.Read(splitter, mem, parse_ctx, cmd_ev, errfmt)
708
709 mapfile = io_osh.MapFile(mem, errfmt, cmd_ev)
710 b[builtin_i.mapfile] = mapfile
711 b[builtin_i.readarray] = mapfile
712
713 # Dirs
714 dir_stack = dirs_osh.DirStack()
715 b[builtin_i.cd] = dirs_osh.Cd(mem, dir_stack, cmd_ev, errfmt)
716 b[builtin_i.pushd] = dirs_osh.Pushd(mem, dir_stack, errfmt)
717 b[builtin_i.popd] = dirs_osh.Popd(mem, dir_stack, errfmt)
718 b[builtin_i.dirs] = dirs_osh.Dirs(mem, dir_stack, errfmt)
719 b[builtin_i.pwd] = dirs_osh.Pwd(mem, errfmt)
720
721 b[builtin_i.times] = misc_osh.Times()
722
723 b[builtin_i.json] = json_ysh.Json(mem, errfmt, False)
724 b[builtin_i.json8] = json_ysh.Json(mem, errfmt, True)
725
726 ### Process builtins
727 b[builtin_i.exec_] = process_osh.Exec(mem, ext_prog, fd_state, search_path,
728 errfmt)
729 b[builtin_i.umask] = process_osh.Umask()
730 b[builtin_i.ulimit] = process_osh.Ulimit()
731 b[builtin_i.wait] = process_osh.Wait(waiter, job_list, mem, tracer, errfmt)
732
733 b[builtin_i.jobs] = process_osh.Jobs(job_list)
734 b[builtin_i.fg] = process_osh.Fg(job_control, job_list, waiter)
735 b[builtin_i.bg] = process_osh.Bg(job_list)
736
737 # Could be in process_ysh
738 b[builtin_i.fork] = process_osh.Fork(shell_ex)
739 b[builtin_i.forkwait] = process_osh.ForkWait(shell_ex)
740
741 # Interactive builtins depend on readline
742 b[builtin_i.bind] = readline_osh.Bind(readline, errfmt)
743 b[builtin_i.history] = readline_osh.History(readline, sh_files, errfmt,
744 mylib.Stdout())
745
746 # Completion
747 spec_builder = completion_osh.SpecBuilder(cmd_ev, parse_ctx, word_ev,
748 splitter, comp_lookup, help_data,
749 errfmt)
750 complete_builtin = completion_osh.Complete(spec_builder, comp_lookup)
751 b[builtin_i.complete] = complete_builtin
752 b[builtin_i.compgen] = completion_osh.CompGen(spec_builder)
753 b[builtin_i.compopt] = completion_osh.CompOpt(compopt_state, errfmt)
754 b[builtin_i.compadjust] = completion_osh.CompAdjust(mem)
755
756 comp_ev = word_eval.CompletionWordEvaluator(mem, exec_opts, mutable_opts,
757 tilde_ev, splitter, errfmt)
758
759 comp_ev.arith_ev = arith_ev
760 comp_ev.expr_ev = expr_ev
761 comp_ev.prompt_ev = prompt_ev
762 comp_ev.CheckCircularDeps()
763
764 root_comp = completion.RootCompleter(comp_ev, mem, comp_lookup,
765 compopt_state, comp_ui_state,
766 comp_ctx, debug_f)
767 b[builtin_i.compexport] = completion_ysh.CompExport(root_comp)
768
769 #
770 # Initialize Builtin-in Methods
771 #
772
773 methods[value_e.Str] = {
774 'startsWith': method_str.HasAffix(method_str.START),
775 'endsWith': method_str.HasAffix(method_str.END),
776 'trim': method_str.Trim(method_str.START | method_str.END),
777 'trimStart': method_str.Trim(method_str.START),
778 'trimEnd': method_str.Trim(method_str.END),
779 'upper': method_str.Upper(),
780 'lower': method_str.Lower(),
781 'split': method_str.Split(),
782
783 # finds a substring, optional position to start at
784 'find': None,
785
786 # replace substring, OR an eggex
787 # takes count=3, the max number of replacements to do.
788 'replace': method_str.Replace(mem, expr_ev),
789
790 # Like Python's re.search, except we put it on the string object
791 # It's more consistent with Str->find(substring, pos=0)
792 # It returns value.Match() rather than an integer
793 'search': method_str.SearchMatch(method_str.SEARCH),
794
795 # like Python's re.match()
796 'leftMatch': method_str.SearchMatch(method_str.LEFT_MATCH),
797
798 # like Python's re.fullmatch(), not sure if we really need it
799 'fullMatch': None,
800 }
801 methods[value_e.Dict] = {
802 # keys() values() get() are FREE functions, not methods
803 # I think items() isn't as necessary because dicts are ordered? YSH
804 # code shouldn't use the List of Lists representation.
805 'M/erase': method_dict.Erase(),
806 # could be d->tally() or d->increment(), but inc() is short
807 #
808 # call d->inc('mycounter')
809 # call d->inc('mycounter', 3)
810 'M/inc': None,
811
812 # call d->accum('mygroup', 'value')
813 'M/accum': None,
814
815 # DEPRECATED - use free functions
816 'get': method_dict.Get(),
817 'keys': method_dict.Keys(),
818 'values': method_dict.Values(),
819 }
820 methods[value_e.List] = {
821 'M/reverse': method_list.Reverse(),
822 'M/append': method_list.Append(),
823 'M/clear': method_list.Clear(),
824 'M/extend': method_list.Extend(),
825 'M/pop': method_list.Pop(),
826 'M/insert': None, # insert object before index
827 'M/remove': None, # insert object before index
828 'indexOf': method_list.IndexOf(), # return first index of value, or -1
829 # Python list() has index(), which raises ValueError
830 # But this is consistent with Str->find(), and doesn't
831 # use exceptions
832 'lastIndexOf': method_list.LastIndexOf(),
833 'join': func_misc.Join(), # both a method and a func
834 }
835
836 methods[value_e.Match] = {
837 'group': func_eggex.MatchMethod(func_eggex.G, expr_ev),
838 'start': func_eggex.MatchMethod(func_eggex.S, None),
839 'end': func_eggex.MatchMethod(func_eggex.E, None),
840 }
841
842 methods[value_e.Place] = {
843 # __mut_setValue()
844
845 # instead of setplace keyword
846 'M/setValue': method_other.SetValue(mem),
847 }
848
849 methods[value_e.CommandFrag] = {
850 # var x = ^(echo hi)
851 # Export source code and line number
852 # Useful for test frameworks and so forth
853 'export': None,
854 }
855
856 #
857 # Initialize Built-in Funcs
858 #
859
860 parse_hay = func_hay.ParseHay(fd_state, parse_ctx, mem, errfmt)
861 eval_hay = func_hay.EvalHay(hay_state, mutable_opts, mem, cmd_ev)
862 hay_func = func_hay.HayFunc(hay_state)
863
864 _AddBuiltinFunc(mem, 'parseHay', parse_hay)
865 _AddBuiltinFunc(mem, 'evalHay', eval_hay)
866 _AddBuiltinFunc(mem, '_hay', hay_func)
867
868 _AddBuiltinFunc(mem, 'len', func_misc.Len())
869 _AddBuiltinFunc(mem, 'type', func_misc.Type())
870
871 g = func_eggex.MatchFunc(func_eggex.G, expr_ev, mem)
872 _AddBuiltinFunc(mem, '_group', g)
873 _AddBuiltinFunc(mem, '_match',
874 g) # TODO: remove this backward compat alias
875 _AddBuiltinFunc(mem, '_start',
876 func_eggex.MatchFunc(func_eggex.S, None, mem))
877 _AddBuiltinFunc(mem, '_end', func_eggex.MatchFunc(func_eggex.E, None, mem))
878
879 # TODO: should this be parseCommandStr() vs. parseFile() for Hay?
880 _AddBuiltinFunc(mem, 'parseCommand',
881 func_reflect.ParseCommand(parse_ctx, mem, errfmt))
882 _AddBuiltinFunc(mem, 'parseExpr',
883 func_reflect.ParseExpr(parse_ctx, errfmt))
884
885 _AddBuiltinFunc(mem, 'shvarGet', func_reflect.Shvar_get(mem))
886 _AddBuiltinFunc(mem, 'getVar', func_reflect.GetVar(mem))
887 _AddBuiltinFunc(mem, 'setVar', func_reflect.SetVar(mem))
888
889 # TODO: implement bindFrame() to turn CommandFrag -> Command
890 # Then parseCommand() and parseHay() will not depend on mem; they will not
891 # bind a frame yet
892 #
893 # what about newFrame() and globalFrame()?
894 _AddBuiltinFunc(mem, 'bindFrame', func_reflect.BindFrame())
895
896 _AddBuiltinFunc(mem, 'Object', func_misc.Object())
897
898 _AddBuiltinFunc(mem, 'rest', func_misc.Prototype())
899 _AddBuiltinFunc(mem, 'first', func_misc.PropView())
900
901 # TODO: remove these aliases
902 _AddBuiltinFunc(mem, 'prototype', func_misc.Prototype())
903 _AddBuiltinFunc(mem, 'propView', func_misc.PropView())
904
905 # type conversions
906 _AddBuiltinFunc(mem, 'bool', func_misc.Bool())
907 _AddBuiltinFunc(mem, 'int', func_misc.Int())
908 _AddBuiltinFunc(mem, 'float', func_misc.Float())
909 _AddBuiltinFunc(mem, 'str', func_misc.Str_())
910 _AddBuiltinFunc(mem, 'list', func_misc.List_())
911 _AddBuiltinFunc(mem, 'dict', func_misc.DictFunc())
912
913 # Dict functions
914 _AddBuiltinFunc(mem, 'get', method_dict.Get())
915 _AddBuiltinFunc(mem, 'keys', method_dict.Keys())
916 _AddBuiltinFunc(mem, 'values', method_dict.Values())
917
918 _AddBuiltinFunc(mem, 'runes', func_misc.Runes())
919 _AddBuiltinFunc(mem, 'encodeRunes', func_misc.EncodeRunes())
920 _AddBuiltinFunc(mem, 'bytes', func_misc.Bytes())
921 _AddBuiltinFunc(mem, 'encodeBytes', func_misc.EncodeBytes())
922
923 # Str
924 #_AddBuiltinFunc(mem, 'strcmp', None)
925 # TODO: This should be Python style splitting
926 _AddBuiltinFunc(mem, 'split', func_misc.Split(splitter))
927 _AddBuiltinFunc(mem, 'shSplit', func_misc.Split(splitter))
928
929 # Float
930 _AddBuiltinFunc(mem, 'floatsEqual', func_misc.FloatsEqual())
931
932 # List
933 _AddBuiltinFunc(mem, 'join', func_misc.Join())
934 _AddBuiltinFunc(mem, 'maybe', func_misc.Maybe())
935 _AddBuiltinFunc(mem, 'glob', func_misc.Glob(globber))
936
937 # Serialize
938 _AddBuiltinFunc(mem, 'toJson8', func_misc.ToJson8(True))
939 _AddBuiltinFunc(mem, 'toJson', func_misc.ToJson8(False))
940
941 _AddBuiltinFunc(mem, 'fromJson8', func_misc.FromJson8(True))
942 _AddBuiltinFunc(mem, 'fromJson', func_misc.FromJson8(False))
943
944 # Demos
945 _AddBuiltinFunc(mem, '_a2sp', func_misc.BashArrayToSparse())
946 _AddBuiltinFunc(mem, '_opsp', func_misc.SparseOp())
947
948 mem.AddBuiltin('io', io_obj)
949 mem.AddBuiltin('vm', vm_obj)
950
951 # Special case for testing
952 mem.AddBuiltin('module-invoke', value.BuiltinProc(module_invoke))
953
954 #
955 # Is the shell interactive?
956 #
957
958 # History evaluation is a no-op if readline is None.
959 hist_ev = history.Evaluator(readline, hist_ctx, debug_f)
960
961 if flag.c is not None:
962 src = source.CFlag # type: source_t
963 line_reader = reader.StringLineReader(flag.c,
964 arena) # type: reader._Reader
965 if flag.i: # -c and -i can be combined
966 mutable_opts.set_interactive()
967
968 elif flag.i: # force interactive
969 src = source.Stdin(' -i')
970 line_reader = reader.InteractiveLineReader(arena, prompt_ev, hist_ev,
971 readline, prompt_state)
972 mutable_opts.set_interactive()
973
974 else:
975 if script_name is None:
976 if flag.headless:
977 src = source.Headless
978 line_reader = None # unused!
979 # Not setting '-i' flag for now. Some people's bashrc may want it?
980 else:
981 stdin_ = mylib.Stdin()
982 # --tool never starts a prompt
983 if len(flag.tool) == 0 and stdin_.isatty():
984 src = source.Interactive
985 line_reader = reader.InteractiveLineReader(
986 arena, prompt_ev, hist_ev, readline, prompt_state)
987 mutable_opts.set_interactive()
988 else:
989 src = source.Stdin('')
990 line_reader = reader.FileLineReader(stdin_, arena)
991 else:
992 src = source.MainFile(script_name)
993 try:
994 f = fd_state.Open(script_name)
995 except (IOError, OSError) as e:
996 print_stderr("%s: Couldn't open %r: %s" %
997 (lang, script_name, posix.strerror(e.errno)))
998 return 1
999 line_reader = reader.FileLineReader(f, arena)
1000
1001 # Pretend it came from somewhere else
1002 if flag.location_str is not None:
1003 src = source.Synthetic(flag.location_str)
1004 assert line_reader is not None
1005 location_start_line = mops.BigTruncate(flag.location_start_line)
1006 if location_start_line != -1:
1007 line_reader.SetLineOffset(location_start_line)
1008
1009 arena.PushSource(src)
1010
1011 # Calculate ~/.config/oils/oshrc or yshrc. Used for both -i and --headless
1012 # We avoid cluttering the user's home directory. Some users may want to ln
1013 # -s ~/.config/oils/oshrc ~/oshrc or ~/.oshrc.
1014
1015 # https://unix.stackexchange.com/questions/24347/why-do-some-applications-use-config-appname-for-their-config-data-while-other
1016
1017 config_dir = '.config/oils'
1018 rc_paths = [] # type: List[str]
1019 if flag.headless or exec_opts.interactive():
1020 if flag.norc:
1021 # bash doesn't have this warning, but it's useful
1022 if flag.rcfile is not None:
1023 print_stderr('%s warning: --rcfile ignored with --norc' % lang)
1024 if flag.rcdir is not None:
1025 print_stderr('%s warning: --rcdir ignored with --norc' % lang)
1026 else:
1027 # User's rcfile comes FIRST. Later we can add an 'after-rcdir' hook
1028 rc_path = flag.rcfile
1029 if rc_path is None:
1030 rc_paths.append(
1031 os_path.join(home_dir, '%s/%src' % (config_dir, lang)))
1032 else:
1033 rc_paths.append(rc_path)
1034
1035 # Load all files in ~/.config/oils/oshrc.d or oilrc.d
1036 # This way "installers" can avoid mutating oshrc directly
1037
1038 rc_dir = flag.rcdir
1039 if rc_dir is None:
1040 rc_dir = os_path.join(home_dir,
1041 '%s/%src.d' % (config_dir, lang))
1042
1043 rc_paths.extend(libc.glob(os_path.join(rc_dir, '*'), 0))
1044
1045 # Initialize even in non-interactive shell, for 'compexport'
1046 _InitDefaultCompletions(cmd_ev, complete_builtin, comp_lookup)
1047
1048 if flag.headless:
1049 sh_init.InitInteractive(mem, sh_files, lang)
1050 mutable_opts.set_redefine_const()
1051 mutable_opts.set_redefine_source()
1052
1053 # NOTE: rc files loaded AFTER _InitDefaultCompletions.
1054 for rc_path in rc_paths:
1055 with state.ctx_ThisDir(mem, rc_path):
1056 try:
1057 SourceStartupFile(fd_state, rc_path, lang, parse_ctx,
1058 cmd_ev, errfmt)
1059 except util.UserExit as e:
1060 return e.status
1061
1062 loop = main_loop.Headless(cmd_ev, parse_ctx, errfmt)
1063 try:
1064 # TODO: What other exceptions happen here?
1065 status = loop.Loop()
1066 except util.UserExit as e:
1067 status = e.status
1068
1069 # Same logic as interactive shell
1070 mut_status = IntParamBox(status)
1071 cmd_ev.RunTrapsOnExit(mut_status)
1072 status = mut_status.i
1073
1074 return status
1075
1076 # Note: headless mode above doesn't use c_parser
1077 assert line_reader is not None
1078 c_parser = parse_ctx.MakeOshParser(line_reader)
1079
1080 if exec_opts.interactive():
1081 sh_init.InitInteractive(mem, sh_files, lang)
1082 # bash: 'set -o emacs' is the default only in the interactive shell
1083 mutable_opts.set_emacs()
1084 mutable_opts.set_redefine_const()
1085 mutable_opts.set_redefine_source()
1086
1087 if readline:
1088 term_width = 0
1089 try:
1090 term_width = libc.get_terminal_width()
1091 except (IOError, OSError): # stdin not a terminal
1092 pass
1093
1094 if flag.completion_display == 'nice' and term_width != 0:
1095 display = comp_ui.NiceDisplay(
1096 term_width, comp_ui_state, prompt_state, debug_f, readline,
1097 signal_safe) # type: comp_ui._IDisplay
1098 else:
1099 if term_width == 0:
1100 term_width = DEFAULT_TERM_WIDTH
1101
1102 display = comp_ui.MinimalDisplay(comp_ui_state, prompt_state,
1103 debug_f, term_width,
1104 signal_safe)
1105
1106 comp_ui.InitReadline(readline, sh_files.HistoryFile(), root_comp,
1107 display, debug_f)
1108
1109 if flag.completion_demo:
1110 _CompletionDemo(comp_lookup)
1111
1112 else: # Without readline module
1113 display = comp_ui.MinimalDisplay(comp_ui_state, prompt_state,
1114 debug_f, DEFAULT_TERM_WIDTH,
1115 signal_safe)
1116
1117 process.InitInteractiveShell(signal_safe) # Set signal handlers
1118
1119 # The interactive shell leads a process group which controls the terminal.
1120 # It MUST give up the terminal afterward, otherwise we get SIGTTIN /
1121 # SIGTTOU bugs.
1122 with process.ctx_TerminalControl(job_control, errfmt):
1123
1124 # NOTE: rc files loaded AFTER _InitDefaultCompletions.
1125 for rc_path in rc_paths:
1126 with state.ctx_ThisDir(mem, rc_path):
1127 try:
1128 SourceStartupFile(fd_state, rc_path, lang, parse_ctx,
1129 cmd_ev, errfmt)
1130 except util.UserExit as e:
1131 return e.status
1132
1133 assert line_reader is not None
1134 line_reader.Reset() # After sourcing startup file, render $PS1
1135
1136 prompt_plugin = prompt.UserPlugin(mem, parse_ctx, cmd_ev, errfmt)
1137 try:
1138 status = main_loop.Interactive(flag, cmd_ev, c_parser, display,
1139 prompt_plugin, waiter, errfmt)
1140 except util.UserExit as e:
1141 status = e.status
1142
1143 mut_status = IntParamBox(status)
1144 cmd_ev.RunTrapsOnExit(mut_status)
1145 status = mut_status.i
1146
1147 if readline:
1148 hist_file = sh_files.HistoryFile()
1149 if hist_file is not None:
1150 try:
1151 readline.write_history_file(hist_file)
1152 except (IOError, OSError):
1153 pass
1154
1155 return status
1156
1157 if flag.rcfile is not None: # bash doesn't have this warning, but it's useful
1158 print_stderr('%s warning: --rcfile ignored in non-interactive shell' %
1159 lang)
1160 if flag.rcdir is not None:
1161 print_stderr('%s warning: --rcdir ignored in non-interactive shell' %
1162 lang)
1163
1164 #
1165 # Tools that use the OSH/YSH parsing mode, etc.
1166 #
1167
1168 # flag.tool is '' if nothing is passed
1169 # osh --tool syntax-tree is equivalent to osh -n --one-pass-parse
1170 tool_name = 'syntax-tree' if exec_opts.noexec() else flag.tool
1171
1172 if len(tool_name):
1173 # Don't save tokens becaues it's slow
1174 if tool_name != 'syntax-tree':
1175 arena.SaveTokens()
1176
1177 try:
1178 node = main_loop.ParseWholeFile(c_parser)
1179 except error.Parse as e:
1180 errfmt.PrettyPrintError(e)
1181 return 2
1182
1183 if tool_name == 'syntax-tree':
1184 ui.PrintAst(node, flag)
1185
1186 elif tool_name == 'tokens':
1187 ysh_ify.PrintTokens(arena)
1188
1189 elif tool_name == 'lossless-cat': # for test/lossless.sh
1190 ysh_ify.LosslessCat(arena)
1191
1192 elif tool_name == 'fmt':
1193 fmt.Format(arena, node)
1194
1195 elif tool_name == 'test':
1196 raise AssertionError('TODO')
1197
1198 elif tool_name == 'ysh-ify':
1199 ysh_ify.Ysh_ify(arena, node)
1200
1201 elif tool_name == 'deps':
1202 if mylib.PYTHON:
1203 deps.Deps(node)
1204
1205 else:
1206 raise AssertionError(tool_name) # flag parser validated it
1207
1208 return 0
1209
1210 #
1211 # Run a shell script
1212 #
1213
1214 with state.ctx_ThisDir(mem, script_name):
1215 try:
1216 status = main_loop.Batch(cmd_ev,
1217 c_parser,
1218 errfmt,
1219 cmd_flags=cmd_eval.IsMainProgram)
1220 except util.UserExit as e:
1221 status = e.status
1222 except KeyboardInterrupt:
1223 # The interactive shell handles this in main_loop.Interactive
1224 status = 130 # 128 + 2
1225 mut_status = IntParamBox(status)
1226 cmd_ev.RunTrapsOnExit(mut_status)
1227
1228 multi_trace.WriteDumps()
1229
1230 # NOTE: We haven't closed the file opened with fd_state.Open
1231 return mut_status.i