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