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

482 lines, 335 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.typed_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.typed_args, cmd_val.pos_args,
295 cmd_val.named_args, cmd_val.block_arg)
296
297 cmd_st = CommandStatus.CreateNull(alloc_lists=True)
298
299 # If we respected do_fork here instead of passing DO_FORK
300 # unconditionally, the case 'command date | wc -l' would take 2
301 # processes instead of 3. See test/syscall
302 run_flags = executor.NO_CALL_PROCS
303 if cmd_val.is_last_cmd:
304 run_flags |= executor.IS_LAST_CMD
305 if arg.p:
306 run_flags |= executor.USE_DEFAULT_PATH
307
308 return self.shell_ex.RunSimpleCommand(cmd_val2, cmd_st, run_flags)
309
310
311def _ShiftArgv(cmd_val):
312 # type: (cmd_value.Argv) -> cmd_value.Argv
313 return cmd_value.Argv(cmd_val.argv[1:], cmd_val.arg_locs[1:],
314 cmd_val.is_last_cmd, cmd_val.typed_args,
315 cmd_val.pos_args, cmd_val.named_args,
316 cmd_val.block_arg)
317
318
319class Builtin(vm._Builtin):
320
321 def __init__(self, shell_ex, errfmt):
322 # type: (vm._Executor, ui.ErrorFormatter) -> None
323 self.shell_ex = shell_ex
324 self.errfmt = errfmt
325
326 def Run(self, cmd_val):
327 # type: (cmd_value.Argv) -> int
328
329 if len(cmd_val.argv) == 1:
330 return 0 # this could be an error in strict mode?
331
332 name = cmd_val.argv[1]
333
334 # Run regular builtin or special builtin
335 to_run = consts.LookupNormalBuiltin(name)
336 if to_run == consts.NO_INDEX:
337 to_run = consts.LookupSpecialBuiltin(name)
338 if to_run == consts.NO_INDEX:
339 location = cmd_val.arg_locs[1]
340 if consts.LookupAssignBuiltin(name) != consts.NO_INDEX:
341 # NOTE: There's a similar restriction for 'command'
342 self.errfmt.Print_("Can't run assignment builtin recursively",
343 blame_loc=location)
344 else:
345 self.errfmt.Print_("%r isn't a shell builtin" % name,
346 blame_loc=location)
347 return 1
348
349 cmd_val2 = _ShiftArgv(cmd_val)
350 return self.shell_ex.RunBuiltin(to_run, cmd_val2)
351
352
353class RunProc(vm._Builtin):
354
355 def __init__(self, shell_ex, procs, errfmt):
356 # type: (vm._Executor, state.Procs, ui.ErrorFormatter) -> None
357 self.shell_ex = shell_ex
358 self.procs = procs
359 self.errfmt = errfmt
360
361 def Run(self, cmd_val):
362 # type: (cmd_value.Argv) -> int
363 _, arg_r = flag_util.ParseCmdVal('runproc',
364 cmd_val,
365 accept_typed_args=True)
366 argv, locs = arg_r.Rest2()
367
368 if len(argv) == 0:
369 raise error.Usage('requires arguments', loc.Missing)
370
371 name = argv[0]
372 if not self.procs.Get(name):
373 self.errfmt.PrintMessage('runproc: no proc named %r' % name)
374 return 1
375
376 cmd_val2 = cmd_value.Argv(argv, locs, cmd_val.is_last_cmd,
377 cmd_val.typed_args, cmd_val.pos_args,
378 cmd_val.named_args, cmd_val.block_arg)
379
380 cmd_st = CommandStatus.CreateNull(alloc_lists=True)
381 run_flags = executor.IS_LAST_CMD if cmd_val.is_last_cmd else 0
382 return self.shell_ex.RunSimpleCommand(cmd_val2, cmd_st, run_flags)
383
384
385def _ResolveName(
386 name, # type: str
387 funcs, # type: state.Procs
388 aliases, # type: Dict[str, str]
389 search_path, # type: state.SearchPath
390 do_all, # type: bool
391):
392 # type: (...) -> List[Tuple[str, str, Optional[str]]]
393
394 # MyPy tuple type
395 no_str = None # type: Optional[str]
396
397 results = [] # type: List[Tuple[str, str, Optional[str]]]
398
399 if funcs and funcs.Get(name):
400 results.append((name, 'function', no_str))
401
402 if name in aliases:
403 results.append((name, 'alias', aliases[name]))
404
405 # See if it's a builtin
406 if consts.LookupNormalBuiltin(name) != 0:
407 results.append((name, 'builtin', no_str))
408 elif consts.LookupSpecialBuiltin(name) != 0:
409 results.append((name, 'builtin', no_str))
410 elif consts.LookupAssignBuiltin(name) != 0:
411 results.append((name, 'builtin', no_str))
412
413 # See if it's a keyword
414 if consts.IsControlFlow(name): # continue, etc.
415 results.append((name, 'keyword', no_str))
416 elif consts.IsKeyword(name):
417 results.append((name, 'keyword', no_str))
418
419 # See if it's external
420 for path in search_path.LookupReflect(name, do_all):
421 if posix.access(path, X_OK):
422 results.append((name, 'file', path))
423
424 return results
425
426
427class Type(vm._Builtin):
428
429 def __init__(
430 self,
431 funcs, # type: state.Procs
432 aliases, # type: Dict[str, str]
433 search_path, # type: state.SearchPath
434 errfmt, # type: ui.ErrorFormatter
435 ):
436 # type: (...) -> None
437 self.funcs = funcs
438 self.aliases = aliases
439 self.search_path = search_path
440 self.errfmt = errfmt
441
442 def Run(self, cmd_val):
443 # type: (cmd_value.Argv) -> int
444 attrs, arg_r = flag_util.ParseCmdVal('type', cmd_val)
445 arg = arg_types.type(attrs.attrs)
446
447 if arg.f: # suppress function lookup
448 funcs = None # type: state.Procs
449 else:
450 funcs = self.funcs
451
452 status = 0
453 names = arg_r.Rest()
454
455 if arg.P: # -P should forces PATH search, regardless of builtin/alias/function/etc.
456 for name in names:
457 paths = self.search_path.LookupReflect(name, arg.a)
458 if len(paths):
459 for path in paths:
460 print(path)
461 else:
462 status = 1
463 return status
464
465 for argument in names:
466 r = _ResolveName(argument, funcs, self.aliases, self.search_path,
467 arg.a)
468 if arg.a:
469 for row in r:
470 _PrintEntry(arg, row)
471 else:
472 if len(r): # Just print the first one
473 _PrintEntry(arg, r[0])
474
475 # Error case
476 if len(r) == 0:
477 if not arg.t: # 'type -t' is silent in this case
478 # match bash behavior by printing to stderr
479 print_stderr('%s: not found' % argument)
480 status = 1 # nothing printed, but we fail
481
482 return status