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

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