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

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