OILS / builtin / meta_osh.py View on Github | oilshell.org

478 lines, 331 significant
1#!/usr/bin/env python2
2"""
3meta_osh.py - Builtins that call back into the interpreter.
4"""
5from __future__ import print_function
6
7from _devbuild.gen import arg_types
8from _devbuild.gen.runtime_asdl import cmd_value, CommandStatus
9from _devbuild.gen.syntax_asdl import source, loc
10from core import alloc
11from core import dev
12from core import error
13from core import executor
14from core import main_loop
15from core import process
16from core.error import e_usage
17from core import pyutil # strerror
18from core import state
19from core import vm
20from data_lang import j8_lite
21from frontend import flag_util
22from frontend import consts
23from frontend import reader
24from frontend import typed_args
25from mycpp.mylib import log, print_stderr
26from pylib import os_path
27from osh import cmd_eval
28
29import posix_ as posix
30from posix_ import X_OK # translated directly to C macro
31
32_ = log
33
34from typing import Dict, List, Tuple, Optional, TYPE_CHECKING
35if TYPE_CHECKING:
36 from frontend import args
37 from frontend.parse_lib import ParseContext
38 from core import optview
39 from display import ui
40 from osh.cmd_eval import CommandEvaluator
41 from osh.cmd_parse import CommandParser
42
43
44class Eval(vm._Builtin):
45
46 def __init__(
47 self,
48 parse_ctx, # type: ParseContext
49 exec_opts, # type: optview.Exec
50 cmd_ev, # type: CommandEvaluator
51 tracer, # type: dev.Tracer
52 errfmt, # type: ui.ErrorFormatter
53 ):
54 # type: (...) -> None
55 self.parse_ctx = parse_ctx
56 self.arena = parse_ctx.arena
57 self.exec_opts = exec_opts
58 self.cmd_ev = cmd_ev
59 self.tracer = tracer
60 self.errfmt = errfmt
61
62 def Run(self, cmd_val):
63 # type: (cmd_value.Argv) -> int
64
65 if cmd_val.proc_args: # eval (mycmd)
66 rd = typed_args.ReaderForProc(cmd_val)
67 cmd = rd.PosCommand()
68 rd.Done()
69 return self.cmd_ev.EvalCommand(cmd)
70
71 # There are no flags, but we need it to respect --
72 _, arg_r = flag_util.ParseCmdVal('eval', cmd_val)
73
74 if self.exec_opts.simple_eval_builtin():
75 code_str, eval_loc = arg_r.ReadRequired2('requires code string')
76 if not arg_r.AtEnd():
77 e_usage('requires exactly 1 argument', loc.Missing)
78 else:
79 code_str = ' '.join(arg_r.Rest())
80 # code_str could be EMPTY, so just use the first one
81 eval_loc = cmd_val.arg_locs[0]
82
83 line_reader = reader.StringLineReader(code_str, self.arena)
84 c_parser = self.parse_ctx.MakeOshParser(line_reader)
85
86 src = source.ArgvWord('eval', eval_loc)
87 with dev.ctx_Tracer(self.tracer, 'eval', None):
88 with alloc.ctx_SourceCode(self.arena, src):
89 return main_loop.Batch(self.cmd_ev,
90 c_parser,
91 self.errfmt,
92 cmd_flags=cmd_eval.RaiseControlFlow)
93
94
95class Source(vm._Builtin):
96
97 def __init__(
98 self,
99 parse_ctx, # type: ParseContext
100 search_path, # type: state.SearchPath
101 cmd_ev, # type: CommandEvaluator
102 fd_state, # type: process.FdState
103 tracer, # type: dev.Tracer
104 errfmt, # type: ui.ErrorFormatter
105 loader, # type: pyutil._ResourceLoader
106 ):
107 # type: (...) -> None
108 self.parse_ctx = parse_ctx
109 self.arena = parse_ctx.arena
110 self.search_path = search_path
111 self.cmd_ev = cmd_ev
112 self.fd_state = fd_state
113 self.tracer = tracer
114 self.errfmt = errfmt
115 self.loader = loader
116
117 self.mem = cmd_ev.mem
118
119 def Run(self, cmd_val):
120 # type: (cmd_value.Argv) -> int
121 attrs, arg_r = flag_util.ParseCmdVal('source', cmd_val)
122 arg = arg_types.source(attrs.attrs)
123
124 path_arg = arg_r.Peek()
125 if path_arg is None:
126 e_usage('missing required argument', loc.Missing)
127 arg_r.Next()
128
129 # Old:
130 # source --builtin two.sh # looks up stdlib/two.sh
131 # New:
132 # source $LIB_OSH/two.sh # looks up stdlib/osh/two.sh
133 # source ///osh/two.sh # looks up stdlib/osh/two.sh
134 builtin_path = None # type: Optional[str]
135 if arg.builtin:
136 builtin_path = path_arg
137 elif path_arg.startswith('///'):
138 builtin_path = path_arg[3:]
139
140 if builtin_path is not None:
141 try:
142 load_path = os_path.join("stdlib", builtin_path)
143 contents = self.loader.Get(load_path)
144 except (IOError, OSError):
145 self.errfmt.Print_('source failed: No builtin file %r' %
146 load_path,
147 blame_loc=cmd_val.arg_locs[2])
148 return 2
149
150 line_reader = reader.StringLineReader(contents, self.arena)
151 c_parser = self.parse_ctx.MakeOshParser(line_reader)
152 return self._Exec(cmd_val, arg_r, load_path, c_parser)
153
154 else:
155 # 'source' respects $PATH
156 resolved = self.search_path.LookupOne(path_arg,
157 exec_required=False)
158 if resolved is None:
159 resolved = path_arg
160
161 try:
162 # Shell can't use descriptors 3-9
163 f = self.fd_state.Open(resolved)
164 except (IOError, OSError) as e:
165 self.errfmt.Print_('source %r failed: %s' %
166 (path_arg, pyutil.strerror(e)),
167 blame_loc=cmd_val.arg_locs[1])
168 return 1
169
170 line_reader = reader.FileLineReader(f, self.arena)
171 c_parser = self.parse_ctx.MakeOshParser(line_reader)
172
173 with process.ctx_FileCloser(f):
174 return self._Exec(cmd_val, arg_r, path_arg, c_parser)
175
176 def _Exec(self, cmd_val, arg_r, path, c_parser):
177 # type: (cmd_value.Argv, args.Reader, str, CommandParser) -> int
178 call_loc = cmd_val.arg_locs[0]
179
180 # A sourced module CAN have a new arguments array, but it always shares
181 # the same variable scope as the caller. The caller could be at either a
182 # global or a local scope.
183
184 # TODO: I wonder if we compose the enter/exit methods more easily.
185
186 with dev.ctx_Tracer(self.tracer, 'source', cmd_val.argv):
187 source_argv = arg_r.Rest()
188 with state.ctx_Source(self.mem, path, source_argv):
189 with state.ctx_ThisDir(self.mem, path):
190 src = source.SourcedFile(path, call_loc)
191 with alloc.ctx_SourceCode(self.arena, src):
192 try:
193 status = main_loop.Batch(
194 self.cmd_ev,
195 c_parser,
196 self.errfmt,
197 cmd_flags=cmd_eval.RaiseControlFlow)
198 except vm.IntControlFlow as e:
199 if e.IsReturn():
200 status = e.StatusCode()
201 else:
202 raise
203
204 return status
205
206
207def _PrintFreeForm(row):
208 # type: (Tuple[str, str, Optional[str]]) -> None
209 name, kind, resolved = row
210
211 if kind == 'file':
212 what = resolved
213 elif kind == 'alias':
214 what = ('an alias for %s' %
215 j8_lite.EncodeString(resolved, unquoted_ok=True))
216 else: # builtin, function, keyword
217 what = 'a shell %s' % kind
218
219 # TODO: Should also print haynode
220
221 print('%s is %s' % (name, what))
222
223 # if kind == 'function':
224 # bash is the only shell that prints the function
225
226
227def _PrintEntry(arg, row):
228 # type: (arg_types.type, Tuple[str, str, Optional[str]]) -> None
229
230 _, kind, resolved = row
231 assert kind is not None
232
233 if arg.t: # short string
234 print(kind)
235
236 elif arg.p:
237 #log('%s %s %s', name, kind, resolved)
238 if kind == 'file':
239 print(resolved)
240
241 else: # free-form text
242 _PrintFreeForm(row)
243
244
245class Command(vm._Builtin):
246 """'command ls' suppresses function lookup."""
247
248 def __init__(
249 self,
250 shell_ex, # type: vm._Executor
251 funcs, # type: state.Procs
252 aliases, # type: Dict[str, str]
253 search_path, # type: state.SearchPath
254 ):
255 # type: (...) -> None
256 self.shell_ex = shell_ex
257 self.funcs = funcs
258 self.aliases = aliases
259 self.search_path = search_path
260
261 def Run(self, cmd_val):
262 # type: (cmd_value.Argv) -> int
263
264 # accept_typed_args=True because we invoke other builtins
265 attrs, arg_r = flag_util.ParseCmdVal('command',
266 cmd_val,
267 accept_typed_args=True)
268 arg = arg_types.command(attrs.attrs)
269
270 argv, locs = arg_r.Rest2()
271
272 if arg.v or arg.V:
273 status = 0
274 for argument in argv:
275 r = _ResolveName(argument, self.funcs, self.aliases,
276 self.search_path, False)
277 if len(r):
278 # command -v prints the name (-V is more detailed)
279 # Print it only once.
280 row = r[0]
281 name, _, _ = row
282 if arg.v:
283 print(name)
284 else:
285 _PrintFreeForm(row)
286 else:
287 # match bash behavior by printing to stderr
288 print_stderr('%s: not found' % argument)
289 status = 1 # nothing printed, but we fail
290
291 return status
292
293 cmd_val2 = cmd_value.Argv(argv, locs, cmd_val.is_last_cmd,
294 cmd_val.proc_args)
295
296 cmd_st = CommandStatus.CreateNull(alloc_lists=True)
297
298 # If we respected do_fork here instead of passing DO_FORK
299 # unconditionally, the case 'command date | wc -l' would take 2
300 # processes instead of 3. See test/syscall
301 run_flags = executor.NO_CALL_PROCS
302 if cmd_val.is_last_cmd:
303 run_flags |= executor.IS_LAST_CMD
304 if arg.p:
305 run_flags |= executor.USE_DEFAULT_PATH
306
307 return self.shell_ex.RunSimpleCommand(cmd_val2, cmd_st, run_flags)
308
309
310def _ShiftArgv(cmd_val):
311 # type: (cmd_value.Argv) -> cmd_value.Argv
312 return cmd_value.Argv(cmd_val.argv[1:], cmd_val.arg_locs[1:],
313 cmd_val.is_last_cmd, cmd_val.proc_args)
314
315
316class Builtin(vm._Builtin):
317
318 def __init__(self, shell_ex, errfmt):
319 # type: (vm._Executor, ui.ErrorFormatter) -> None
320 self.shell_ex = shell_ex
321 self.errfmt = errfmt
322
323 def Run(self, cmd_val):
324 # type: (cmd_value.Argv) -> int
325
326 if len(cmd_val.argv) == 1:
327 return 0 # this could be an error in strict mode?
328
329 name = cmd_val.argv[1]
330
331 # Run regular builtin or special builtin
332 to_run = consts.LookupNormalBuiltin(name)
333 if to_run == consts.NO_INDEX:
334 to_run = consts.LookupSpecialBuiltin(name)
335 if to_run == consts.NO_INDEX:
336 location = cmd_val.arg_locs[1]
337 if consts.LookupAssignBuiltin(name) != consts.NO_INDEX:
338 # NOTE: There's a similar restriction for 'command'
339 self.errfmt.Print_("Can't run assignment builtin recursively",
340 blame_loc=location)
341 else:
342 self.errfmt.Print_("%r isn't a shell builtin" % name,
343 blame_loc=location)
344 return 1
345
346 cmd_val2 = _ShiftArgv(cmd_val)
347 return self.shell_ex.RunBuiltin(to_run, cmd_val2)
348
349
350class RunProc(vm._Builtin):
351
352 def __init__(self, shell_ex, procs, errfmt):
353 # type: (vm._Executor, state.Procs, ui.ErrorFormatter) -> None
354 self.shell_ex = shell_ex
355 self.procs = procs
356 self.errfmt = errfmt
357
358 def Run(self, cmd_val):
359 # type: (cmd_value.Argv) -> int
360 _, arg_r = flag_util.ParseCmdVal('runproc',
361 cmd_val,
362 accept_typed_args=True)
363 argv, locs = arg_r.Rest2()
364
365 if len(argv) == 0:
366 raise error.Usage('requires arguments', loc.Missing)
367
368 name = argv[0]
369 if not self.procs.Get(name):
370 self.errfmt.PrintMessage('runproc: no proc named %r' % name)
371 return 1
372
373 cmd_val2 = cmd_value.Argv(argv, locs, cmd_val.is_last_cmd,
374 cmd_val.proc_args)
375
376 cmd_st = CommandStatus.CreateNull(alloc_lists=True)
377 run_flags = executor.IS_LAST_CMD if cmd_val.is_last_cmd else 0
378 return self.shell_ex.RunSimpleCommand(cmd_val2, cmd_st, run_flags)
379
380
381def _ResolveName(
382 name, # type: str
383 funcs, # type: state.Procs
384 aliases, # type: Dict[str, str]
385 search_path, # type: state.SearchPath
386 do_all, # type: bool
387):
388 # type: (...) -> List[Tuple[str, str, Optional[str]]]
389
390 # MyPy tuple type
391 no_str = None # type: Optional[str]
392
393 results = [] # type: List[Tuple[str, str, Optional[str]]]
394
395 if funcs and funcs.Get(name):
396 results.append((name, 'function', no_str))
397
398 if name in aliases:
399 results.append((name, 'alias', aliases[name]))
400
401 # See if it's a builtin
402 if consts.LookupNormalBuiltin(name) != 0:
403 results.append((name, 'builtin', no_str))
404 elif consts.LookupSpecialBuiltin(name) != 0:
405 results.append((name, 'builtin', no_str))
406 elif consts.LookupAssignBuiltin(name) != 0:
407 results.append((name, 'builtin', no_str))
408
409 # See if it's a keyword
410 if consts.IsControlFlow(name): # continue, etc.
411 results.append((name, 'keyword', no_str))
412 elif consts.IsKeyword(name):
413 results.append((name, 'keyword', no_str))
414
415 # See if it's external
416 for path in search_path.LookupReflect(name, do_all):
417 if posix.access(path, X_OK):
418 results.append((name, 'file', path))
419
420 return results
421
422
423class Type(vm._Builtin):
424
425 def __init__(
426 self,
427 funcs, # type: state.Procs
428 aliases, # type: Dict[str, str]
429 search_path, # type: state.SearchPath
430 errfmt, # type: ui.ErrorFormatter
431 ):
432 # type: (...) -> None
433 self.funcs = funcs
434 self.aliases = aliases
435 self.search_path = search_path
436 self.errfmt = errfmt
437
438 def Run(self, cmd_val):
439 # type: (cmd_value.Argv) -> int
440 attrs, arg_r = flag_util.ParseCmdVal('type', cmd_val)
441 arg = arg_types.type(attrs.attrs)
442
443 if arg.f: # suppress function lookup
444 funcs = None # type: state.Procs
445 else:
446 funcs = self.funcs
447
448 status = 0
449 names = arg_r.Rest()
450
451 if arg.P: # -P should forces PATH search, regardless of builtin/alias/function/etc.
452 for name in names:
453 paths = self.search_path.LookupReflect(name, arg.a)
454 if len(paths):
455 for path in paths:
456 print(path)
457 else:
458 status = 1
459 return status
460
461 for argument in names:
462 r = _ResolveName(argument, funcs, self.aliases, self.search_path,
463 arg.a)
464 if arg.a:
465 for row in r:
466 _PrintEntry(arg, row)
467 else:
468 if len(r): # Just print the first one
469 _PrintEntry(arg, r[0])
470
471 # Error case
472 if len(r) == 0:
473 if not arg.t: # 'type -t' is silent in this case
474 # match bash behavior by printing to stderr
475 print_stderr('%s: not found' % argument)
476 status = 1 # nothing printed, but we fail
477
478 return status