1 | #!/usr/bin/env python2
|
2 | """
|
3 | meta_osh.py - Builtins that call back into the interpreter.
|
4 | """
|
5 | from __future__ import print_function
|
6 |
|
7 | from _devbuild.gen import arg_types
|
8 | from _devbuild.gen.runtime_asdl import cmd_value, CommandStatus
|
9 | from _devbuild.gen.syntax_asdl import source, loc
|
10 | from _devbuild.gen.value_asdl import value
|
11 | from core import alloc
|
12 | from core import dev
|
13 | from core import error
|
14 | from core import executor
|
15 | from core import main_loop
|
16 | from core import process
|
17 | from core.error import e_usage
|
18 | from core import pyutil # strerror
|
19 | from core import state
|
20 | from core import vm
|
21 | from data_lang import j8_lite
|
22 | from frontend import flag_util
|
23 | from frontend import consts
|
24 | from frontend import reader
|
25 | from frontend import typed_args
|
26 | from mycpp.mylib import log, print_stderr
|
27 | from pylib import os_path
|
28 | from osh import cmd_eval
|
29 |
|
30 | import posix_ as posix
|
31 | from posix_ import X_OK # translated directly to C macro
|
32 |
|
33 | _ = log
|
34 |
|
35 | from typing import Dict, List, Tuple, Optional, TYPE_CHECKING
|
36 | if TYPE_CHECKING:
|
37 | from frontend import args
|
38 | from frontend.parse_lib import ParseContext
|
39 | from core import optview
|
40 | from core import ui
|
41 | from osh.cmd_eval import CommandEvaluator
|
42 | from osh.cmd_parse import CommandParser
|
43 |
|
44 |
|
45 | class Eval(vm._Builtin):
|
46 |
|
47 | def __init__(
|
48 | self,
|
49 | parse_ctx, # type: ParseContext
|
50 | exec_opts, # type: optview.Exec
|
51 | cmd_ev, # type: CommandEvaluator
|
52 | tracer, # type: dev.Tracer
|
53 | errfmt, # type: ui.ErrorFormatter
|
54 | ):
|
55 | # type: (...) -> None
|
56 | self.parse_ctx = parse_ctx
|
57 | self.arena = parse_ctx.arena
|
58 | self.exec_opts = exec_opts
|
59 | self.cmd_ev = cmd_ev
|
60 | self.tracer = tracer
|
61 | self.errfmt = errfmt
|
62 |
|
63 | def Run(self, cmd_val):
|
64 | # type: (cmd_value.Argv) -> int
|
65 |
|
66 | if cmd_val.typed_args: # eval (mycmd)
|
67 | rd = typed_args.ReaderForProc(cmd_val)
|
68 | cmd = rd.PosCommand()
|
69 | rd.Done()
|
70 | return self.cmd_ev.EvalCommand(cmd)
|
71 |
|
72 | # There are no flags, but we need it to respect --
|
73 | _, arg_r = flag_util.ParseCmdVal('eval', cmd_val)
|
74 |
|
75 | if self.exec_opts.simple_eval_builtin():
|
76 | code_str, eval_loc = arg_r.ReadRequired2('requires code string')
|
77 | if not arg_r.AtEnd():
|
78 | e_usage('requires exactly 1 argument', loc.Missing)
|
79 | else:
|
80 | code_str = ' '.join(arg_r.Rest())
|
81 | # code_str could be EMPTY, so just use the first one
|
82 | eval_loc = cmd_val.arg_locs[0]
|
83 |
|
84 | line_reader = reader.StringLineReader(code_str, self.arena)
|
85 | c_parser = self.parse_ctx.MakeOshParser(line_reader)
|
86 |
|
87 | src = source.ArgvWord('eval', eval_loc)
|
88 | with dev.ctx_Tracer(self.tracer, 'eval', None):
|
89 | with alloc.ctx_SourceCode(self.arena, src):
|
90 | return main_loop.Batch(self.cmd_ev,
|
91 | c_parser,
|
92 | self.errfmt,
|
93 | cmd_flags=cmd_eval.RaiseControlFlow)
|
94 |
|
95 |
|
96 | class Source(vm._Builtin):
|
97 |
|
98 | def __init__(
|
99 | self,
|
100 | parse_ctx, # type: ParseContext
|
101 | search_path, # type: state.SearchPath
|
102 | cmd_ev, # type: CommandEvaluator
|
103 | fd_state, # type: process.FdState
|
104 | tracer, # type: dev.Tracer
|
105 | errfmt, # type: ui.ErrorFormatter
|
106 | loader, # type: pyutil._ResourceLoader
|
107 | ):
|
108 | # type: (...) -> None
|
109 | self.parse_ctx = parse_ctx
|
110 | self.arena = parse_ctx.arena
|
111 | self.search_path = search_path
|
112 | self.cmd_ev = cmd_ev
|
113 | self.fd_state = fd_state
|
114 | self.tracer = tracer
|
115 | self.errfmt = errfmt
|
116 | self.loader = loader
|
117 |
|
118 | self.mem = cmd_ev.mem
|
119 |
|
120 | def Run(self, cmd_val):
|
121 | # type: (cmd_value.Argv) -> int
|
122 | attrs, arg_r = flag_util.ParseCmdVal('source', cmd_val)
|
123 | arg = arg_types.source(attrs.attrs)
|
124 |
|
125 | path_arg = arg_r.Peek()
|
126 | if path_arg is None:
|
127 | e_usage('missing required argument', loc.Missing)
|
128 | arg_r.Next()
|
129 |
|
130 | # Old:
|
131 | # source --builtin two.sh # looks up stdlib/two.sh
|
132 | # New:
|
133 | # source $LIB_OSH/two.sh # looks up stdlib/osh/two.sh
|
134 | # source ///osh/two.sh # looks up stdlib/osh/two.sh
|
135 | builtin_path = None # type: Optional[str]
|
136 | if arg.builtin:
|
137 | builtin_path = path_arg
|
138 | elif path_arg.startswith('///'):
|
139 | builtin_path = path_arg[3:]
|
140 |
|
141 | if builtin_path is not None:
|
142 | try:
|
143 | load_path = os_path.join("stdlib", builtin_path)
|
144 | contents = self.loader.Get(load_path)
|
145 | except (IOError, OSError):
|
146 | self.errfmt.Print_(
|
147 | 'source failed: No builtin file %r' % load_path,
|
148 | blame_loc=cmd_val.arg_locs[2])
|
149 | return 2
|
150 |
|
151 | line_reader = reader.StringLineReader(contents, self.arena)
|
152 | c_parser = self.parse_ctx.MakeOshParser(line_reader)
|
153 | return self._Exec(cmd_val, arg_r, load_path, c_parser)
|
154 |
|
155 | else:
|
156 | # 'source' respects $PATH
|
157 | resolved = self.search_path.LookupOne(path_arg, 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 |
|
207 | def _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 |
|
227 | def _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 |
|
245 | class Command(vm._Builtin):
|
246 | """'command ls' suppresses function lookup."""
|
247 |
|
248 | def __init__(
|
249 | self,
|
250 | shell_ex, # type: vm._Executor
|
251 | funcs, # type: Dict[str, value.Proc]
|
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 |
|
310 | def _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 |
|
317 | class 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 |
|
351 | class RunProc(vm._Builtin):
|
352 |
|
353 | def __init__(self, shell_ex, procs, errfmt):
|
354 | # type: (vm._Executor, Dict[str, value.Proc], 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 name not in self.procs:
|
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 |
|
383 | def _ResolveName(
|
384 | name, # type: str
|
385 | funcs, # type: Dict[str, value.Proc]
|
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 name in funcs:
|
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 |
|
425 | class Type(vm._Builtin):
|
426 |
|
427 | def __init__(
|
428 | self,
|
429 | funcs, # type: Dict[str, value.Proc]
|
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 = {} # type: Dict[str, value.Proc]
|
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
|