1 | #!/usr/bin/env python2
|
2 | """
|
3 | meta_oils.py - Builtins that call back into the interpreter, or reflect on it.
|
4 |
|
5 | OSH builtins:
|
6 | builtin command type
|
7 | source eval
|
8 |
|
9 | YSH builtins:
|
10 | invoke extern
|
11 | use
|
12 | """
|
13 | from __future__ import print_function
|
14 |
|
15 | from _devbuild.gen import arg_types
|
16 | from _devbuild.gen.runtime_asdl import cmd_value, CommandStatus
|
17 | from _devbuild.gen.syntax_asdl import source, loc, loc_t, CompoundWord
|
18 | from _devbuild.gen.value_asdl import Obj, value, value_t
|
19 | from core import alloc
|
20 | from core import dev
|
21 | from core import error
|
22 | from core.error import e_usage
|
23 | from core import executor
|
24 | from core import main_loop
|
25 | from core import process
|
26 | from core import pyutil # strerror
|
27 | from core import state
|
28 | from core import vm
|
29 | from data_lang import j8_lite
|
30 | from frontend import consts
|
31 | from frontend import flag_util
|
32 | from frontend import reader
|
33 | from mycpp.mylib import log, print_stderr, NewDict
|
34 | from pylib import os_path
|
35 | from osh import cmd_eval
|
36 |
|
37 | import posix_ as posix
|
38 | from posix_ import X_OK # translated directly to C macro
|
39 |
|
40 | import libc
|
41 |
|
42 | _ = log
|
43 |
|
44 | from typing import Dict, List, Tuple, Optional, TYPE_CHECKING
|
45 | if TYPE_CHECKING:
|
46 | from frontend import args
|
47 | from frontend.parse_lib import ParseContext
|
48 | from core import optview
|
49 | from display import ui
|
50 | from mycpp import mylib
|
51 | from osh.cmd_eval import CommandEvaluator
|
52 | from osh import cmd_parse
|
53 |
|
54 |
|
55 | class Eval(vm._Builtin):
|
56 |
|
57 | def __init__(
|
58 | self,
|
59 | parse_ctx, # type: ParseContext
|
60 | exec_opts, # type: optview.Exec
|
61 | cmd_ev, # type: CommandEvaluator
|
62 | tracer, # type: dev.Tracer
|
63 | errfmt, # type: ui.ErrorFormatter
|
64 | mem, # type: state.Mem
|
65 | ):
|
66 | # type: (...) -> None
|
67 | self.parse_ctx = parse_ctx
|
68 | self.arena = parse_ctx.arena
|
69 | self.exec_opts = exec_opts
|
70 | self.cmd_ev = cmd_ev
|
71 | self.tracer = tracer
|
72 | self.errfmt = errfmt
|
73 | self.mem = mem
|
74 |
|
75 | def Run(self, cmd_val):
|
76 | # type: (cmd_value.Argv) -> int
|
77 |
|
78 | # There are no flags, but we need it to respect --
|
79 | _, arg_r = flag_util.ParseCmdVal('eval', cmd_val)
|
80 |
|
81 | if self.exec_opts.simple_eval_builtin():
|
82 | code_str, eval_loc = arg_r.ReadRequired2('requires code string')
|
83 | if not arg_r.AtEnd():
|
84 | e_usage('requires exactly 1 argument', loc.Missing)
|
85 | else:
|
86 | code_str = ' '.join(arg_r.Rest())
|
87 | # code_str could be EMPTY, so just use the first one
|
88 | eval_loc = cmd_val.arg_locs[0]
|
89 |
|
90 | line_reader = reader.StringLineReader(code_str, self.arena)
|
91 | c_parser = self.parse_ctx.MakeOshParser(line_reader)
|
92 |
|
93 | src = source.Dynamic('eval arg', eval_loc)
|
94 | with dev.ctx_Tracer(self.tracer, 'eval', None):
|
95 | with alloc.ctx_SourceCode(self.arena, src):
|
96 | return main_loop.Batch(self.cmd_ev,
|
97 | c_parser,
|
98 | self.errfmt,
|
99 | cmd_flags=cmd_eval.RaiseControlFlow)
|
100 |
|
101 |
|
102 | def _VarName(module_path):
|
103 | # type: (str) -> str
|
104 | """Convert ///path/foo-bar.ysh -> foo_bar
|
105 |
|
106 | Design issue: proc vs. func naming conventinos imply treating hyphens
|
107 | differently.
|
108 |
|
109 | foo-bar myproc
|
110 | var x = `foo-bar`.myproc
|
111 |
|
112 | I guess use this for now:
|
113 |
|
114 | foo_bar myproc
|
115 | var x = foo_bar.myproc
|
116 |
|
117 | The user can also choose this:
|
118 |
|
119 | fooBar myproc
|
120 | var x = fooBar.myproc
|
121 | """
|
122 | basename = os_path.basename(module_path)
|
123 | i = basename.rfind('.')
|
124 | if i != -1:
|
125 | basename = basename[:i]
|
126 | #return basename.replace('-', '_')
|
127 | return basename
|
128 |
|
129 |
|
130 | class ShellFile(vm._Builtin):
|
131 | """
|
132 | These share code:
|
133 | - 'source' builtin for OSH
|
134 | - 'use' builtin for YSH
|
135 | """
|
136 |
|
137 | def __init__(
|
138 | self,
|
139 | parse_ctx, # type: ParseContext
|
140 | search_path, # type: state.SearchPath
|
141 | cmd_ev, # type: CommandEvaluator
|
142 | fd_state, # type: process.FdState
|
143 | tracer, # type: dev.Tracer
|
144 | errfmt, # type: ui.ErrorFormatter
|
145 | loader, # type: pyutil._ResourceLoader
|
146 | module_invoke=None, # type: vm._Builtin
|
147 | ):
|
148 | # type: (...) -> None
|
149 | """
|
150 | If module_invoke is passed, this class behaves like 'use'. Otherwise
|
151 | it behaves like 'source'.
|
152 | """
|
153 | self.parse_ctx = parse_ctx
|
154 | self.arena = parse_ctx.arena
|
155 | self.search_path = search_path
|
156 | self.cmd_ev = cmd_ev
|
157 | self.fd_state = fd_state
|
158 | self.tracer = tracer
|
159 | self.errfmt = errfmt
|
160 | self.loader = loader
|
161 | self.module_invoke = module_invoke
|
162 |
|
163 | self.builtin_name = 'use' if module_invoke else 'source'
|
164 | self.mem = cmd_ev.mem
|
165 |
|
166 | # Don't load modules more than once
|
167 | # keyed by libc.realpath(arg)
|
168 | self._disk_cache = {} # type: Dict[str, Obj]
|
169 |
|
170 | # keyed by ///
|
171 | self._embed_cache = {} # type: Dict[str, Obj]
|
172 |
|
173 | def Run(self, cmd_val):
|
174 | # type: (cmd_value.Argv) -> int
|
175 | if self.module_invoke:
|
176 | return self._Use(cmd_val)
|
177 | else:
|
178 | return self._Source(cmd_val)
|
179 |
|
180 | def LoadEmbeddedFile(self, embed_path, blame_loc):
|
181 | # type: (str, loc_t) -> Tuple[str, cmd_parse.CommandParser]
|
182 | try:
|
183 | load_path = os_path.join("stdlib", embed_path)
|
184 | contents = self.loader.Get(load_path)
|
185 | except (IOError, OSError):
|
186 | self.errfmt.Print_('%r failed: No builtin file %r' %
|
187 | (self.builtin_name, load_path),
|
188 | blame_loc=blame_loc)
|
189 | return None, None # error
|
190 |
|
191 | line_reader = reader.StringLineReader(contents, self.arena)
|
192 | c_parser = self.parse_ctx.MakeOshParser(line_reader)
|
193 | return load_path, c_parser
|
194 |
|
195 | def _LoadDiskFile(self, fs_path, blame_loc):
|
196 | # type: (str, loc_t) -> Tuple[mylib.LineReader, cmd_parse.CommandParser]
|
197 | try:
|
198 | # Shell can't use descriptors 3-9
|
199 | f = self.fd_state.Open(fs_path)
|
200 | except (IOError, OSError) as e:
|
201 | self.errfmt.Print_(
|
202 | '%s %r failed: %s' %
|
203 | (self.builtin_name, fs_path, pyutil.strerror(e)),
|
204 | blame_loc=blame_loc)
|
205 | return None, None
|
206 |
|
207 | line_reader = reader.FileLineReader(f, self.arena)
|
208 | c_parser = self.parse_ctx.MakeOshParser(line_reader)
|
209 | return f, c_parser
|
210 |
|
211 | def _SourceExec(self, cmd_val, arg_r, path, c_parser):
|
212 | # type: (cmd_value.Argv, args.Reader, str, cmd_parse.CommandParser) -> int
|
213 | call_loc = cmd_val.arg_locs[0]
|
214 |
|
215 | # A sourced module CAN have a new arguments array, but it always shares
|
216 | # the same variable scope as the caller. The caller could be at either a
|
217 | # global or a local scope.
|
218 |
|
219 | # TODO: I wonder if we compose the enter/exit methods more easily.
|
220 |
|
221 | with dev.ctx_Tracer(self.tracer, 'source', cmd_val.argv):
|
222 | source_argv = arg_r.Rest()
|
223 | with state.ctx_Source(self.mem, path, source_argv):
|
224 | with state.ctx_ThisDir(self.mem, path):
|
225 | src = source.OtherFile(path, call_loc)
|
226 | with alloc.ctx_SourceCode(self.arena, src):
|
227 | try:
|
228 | status = main_loop.Batch(
|
229 | self.cmd_ev,
|
230 | c_parser,
|
231 | self.errfmt,
|
232 | cmd_flags=cmd_eval.RaiseControlFlow)
|
233 | except vm.IntControlFlow as e:
|
234 | if e.IsReturn():
|
235 | status = e.StatusCode()
|
236 | else:
|
237 | raise
|
238 |
|
239 | return status
|
240 |
|
241 | def _NewModule(self):
|
242 | # type: () -> Obj
|
243 | # Builtin proc that serves as __invoke__ - it looks up procs in 'self'
|
244 | methods = Obj(None,
|
245 | {'__invoke__': value.BuiltinProc(self.module_invoke)})
|
246 | props = NewDict() # type: Dict[str, value_t]
|
247 | module_obj = Obj(methods, props)
|
248 | return module_obj
|
249 |
|
250 | def _UseExec(self, cmd_val, path, path_loc, c_parser, props):
|
251 | # type: (cmd_value.Argv, str, loc_t, cmd_parse.CommandParser, Dict[str, value_t]) -> int
|
252 | """
|
253 | Args:
|
254 | props: is mutated, and will contain module properties
|
255 | """
|
256 | error_strs = [] # type: List[str]
|
257 |
|
258 | with dev.ctx_Tracer(self.tracer, 'use', cmd_val.argv):
|
259 | with state.ctx_ModuleEval(self.mem, props, error_strs):
|
260 | with state.ctx_ThisDir(self.mem, path):
|
261 | src = source.OtherFile(path, path_loc)
|
262 | with alloc.ctx_SourceCode(self.arena, src):
|
263 | try:
|
264 | status = main_loop.Batch(
|
265 | self.cmd_ev,
|
266 | c_parser,
|
267 | self.errfmt,
|
268 | cmd_flags=cmd_eval.RaiseControlFlow)
|
269 | except vm.IntControlFlow as e:
|
270 | if e.IsReturn():
|
271 | status = e.StatusCode()
|
272 | else:
|
273 | raise
|
274 | if status != 0:
|
275 | return status
|
276 | #e_die("'use' failed 2", path_loc)
|
277 |
|
278 | if len(error_strs):
|
279 | for s in error_strs:
|
280 | self.errfmt.PrintMessage('Error: %s' % s, path_loc)
|
281 | return 1
|
282 |
|
283 | return 0
|
284 |
|
285 | def _Source(self, cmd_val):
|
286 | # type: (cmd_value.Argv) -> int
|
287 | attrs, arg_r = flag_util.ParseCmdVal('source', cmd_val)
|
288 | arg = arg_types.source(attrs.attrs)
|
289 |
|
290 | path_arg, path_loc = arg_r.ReadRequired2('requires a file path')
|
291 |
|
292 | # Old:
|
293 | # source --builtin two.sh # looks up stdlib/two.sh
|
294 | # New:
|
295 | # source $LIB_OSH/two.sh # looks up stdlib/osh/two.sh
|
296 | # source ///osh/two.sh # looks up stdlib/osh/two.sh
|
297 | embed_path = None # type: Optional[str]
|
298 | if arg.builtin:
|
299 | embed_path = path_arg
|
300 | elif path_arg.startswith('///'):
|
301 | embed_path = path_arg[3:]
|
302 |
|
303 | if embed_path is not None:
|
304 | load_path, c_parser = self.LoadEmbeddedFile(embed_path, path_loc)
|
305 | if c_parser is None:
|
306 | return 1 # error was already shown
|
307 |
|
308 | return self._SourceExec(cmd_val, arg_r, load_path, c_parser)
|
309 |
|
310 | else:
|
311 | # 'source' respects $PATH
|
312 | resolved = self.search_path.LookupOne(path_arg,
|
313 | exec_required=False)
|
314 | if resolved is None:
|
315 | resolved = path_arg
|
316 |
|
317 | f, c_parser = self._LoadDiskFile(resolved, path_loc)
|
318 | if c_parser is None:
|
319 | return 1 # error was already shown
|
320 |
|
321 | with process.ctx_FileCloser(f):
|
322 | return self._SourceExec(cmd_val, arg_r, path_arg, c_parser)
|
323 |
|
324 | raise AssertionError()
|
325 |
|
326 | def _BindNames(self, module_obj, module_name, pick_names, pick_locs):
|
327 | # type: (Obj, str, Optional[List[str]], Optional[List[CompoundWord]]) -> int
|
328 | state.SetGlobalValue(self.mem, module_name, module_obj)
|
329 |
|
330 | if pick_names is None:
|
331 | return 0
|
332 |
|
333 | for i, name in enumerate(pick_names):
|
334 | val = module_obj.d.get(name)
|
335 | # ctx_ModuleEval ensures this
|
336 | if val is None:
|
337 | # note: could be more precise
|
338 | self.errfmt.Print_("use: module doesn't provide name %r" %
|
339 | name,
|
340 | blame_loc=pick_locs[i])
|
341 | return 1
|
342 | state.SetGlobalValue(self.mem, name, val)
|
343 | return 0
|
344 |
|
345 | def _Use(self, cmd_val):
|
346 | # type: (cmd_value.Argv) -> int
|
347 | """
|
348 | Module system with all the power of Python, but still a proc
|
349 |
|
350 | use util.ysh # util is a value.Obj
|
351 |
|
352 | # Importing a bunch of words
|
353 | use dialect-ninja.ysh --all-provided
|
354 | use dialect-github.ysh --all-provided
|
355 |
|
356 | # This declares some names
|
357 | use --extern grep sed
|
358 |
|
359 | # Renaming
|
360 | use util.ysh (&myutil)
|
361 |
|
362 | # Ignore
|
363 | use util.ysh (&_)
|
364 |
|
365 | # Picking specifics
|
366 | use util.ysh --names log die
|
367 |
|
368 | # Rename
|
369 | var mylog = log
|
370 | """
|
371 | attrs, arg_r = flag_util.ParseCmdVal('use', cmd_val)
|
372 | arg = arg_types.use(attrs.attrs)
|
373 |
|
374 | # Accepts any args
|
375 | if arg.extern_: # use --extern grep # no-op for static analysis
|
376 | return 0
|
377 |
|
378 | path_arg, path_loc = arg_r.ReadRequired2('requires a module path')
|
379 |
|
380 | pick_names = None # type: Optional[List[str]]
|
381 | pick_locs = None # type: Optional[List[CompoundWord]]
|
382 |
|
383 | # There is only one flag
|
384 | flag, flag_loc = arg_r.Peek2()
|
385 | if flag is not None:
|
386 | if flag == '--pick':
|
387 | arg_r.Next()
|
388 | p = arg_r.Peek()
|
389 | if p is None:
|
390 | raise error.Usage('with --pick expects one or more names',
|
391 | flag_loc)
|
392 | pick_names, pick_locs = arg_r.Rest2()
|
393 |
|
394 | elif flag == '--all-provided':
|
395 | arg_r.Next()
|
396 | arg_r.Done()
|
397 | print('TODO: --all-provided not implemented')
|
398 |
|
399 | elif flag == '--all-for-testing':
|
400 | arg_r.Next()
|
401 | arg_r.Done()
|
402 | print('TODO: --all-for testing not implemented')
|
403 |
|
404 | else:
|
405 | raise error.Usage(
|
406 | 'expected flag like --pick after module path', flag_loc)
|
407 |
|
408 | # Similar logic as 'source'
|
409 | if path_arg.startswith('///'):
|
410 | embed_path = path_arg[3:]
|
411 | else:
|
412 | embed_path = None
|
413 |
|
414 | if self.mem.InsideFunction():
|
415 | raise error.Usage("may only be used at the top level", path_loc)
|
416 |
|
417 | # Important, consider:
|
418 | # use symlink.ysh # where symlink.ysh -> realfile.ysh
|
419 | #
|
420 | # Then the cache key would be '/some/path/realfile.ysh'
|
421 | # But the variable name bound is 'symlink'
|
422 | var_name = _VarName(path_arg)
|
423 | #log('var %s', var_name)
|
424 |
|
425 | if embed_path is not None:
|
426 | # Embedded modules are cached using /// path as cache key
|
427 | cached_obj = self._embed_cache.get(embed_path)
|
428 | if cached_obj:
|
429 | return self._BindNames(cached_obj, var_name, pick_names,
|
430 | pick_locs)
|
431 |
|
432 | load_path, c_parser = self.LoadEmbeddedFile(embed_path, path_loc)
|
433 | if c_parser is None:
|
434 | return 1 # error was already shown
|
435 |
|
436 | module_obj = self._NewModule()
|
437 |
|
438 | # Cache BEFORE executing, to prevent circular import
|
439 | self._embed_cache[embed_path] = module_obj
|
440 |
|
441 | status = self._UseExec(cmd_val, load_path, path_loc, c_parser,
|
442 | module_obj.d)
|
443 | if status != 0:
|
444 | return status
|
445 |
|
446 | return self._BindNames(module_obj, var_name, pick_names, pick_locs)
|
447 |
|
448 | else:
|
449 | normalized = libc.realpath(path_arg)
|
450 | if normalized is None:
|
451 | self.errfmt.Print_("use: couldn't find %r" % path_arg,
|
452 | blame_loc=path_loc)
|
453 | return 1
|
454 |
|
455 | # Disk modules are cached using normalized path as cache key
|
456 | cached_obj = self._disk_cache.get(normalized)
|
457 | if cached_obj:
|
458 | return self._BindNames(cached_obj, var_name, pick_names,
|
459 | pick_locs)
|
460 |
|
461 | f, c_parser = self._LoadDiskFile(normalized, path_loc)
|
462 | if c_parser is None:
|
463 | return 1 # error was already shown
|
464 |
|
465 | module_obj = self._NewModule()
|
466 |
|
467 | # Cache BEFORE executing, to prevent circular import
|
468 | self._disk_cache[normalized] = module_obj
|
469 |
|
470 | with process.ctx_FileCloser(f):
|
471 | status = self._UseExec(cmd_val, path_arg, path_loc, c_parser,
|
472 | module_obj.d)
|
473 | if status != 0:
|
474 | return status
|
475 |
|
476 | return self._BindNames(module_obj, var_name, pick_names, pick_locs)
|
477 |
|
478 | return 0
|
479 |
|
480 |
|
481 | def _PrintFreeForm(row):
|
482 | # type: (Tuple[str, str, Optional[str]]) -> None
|
483 | name, kind, resolved = row
|
484 |
|
485 | if kind == 'file':
|
486 | what = resolved
|
487 | elif kind == 'alias':
|
488 | what = ('an alias for %s' %
|
489 | j8_lite.EncodeString(resolved, unquoted_ok=True))
|
490 | elif kind in ('proc', 'invokable'):
|
491 | # Note: haynode should be an invokable
|
492 | what = 'a YSH %s' % kind
|
493 | else: # builtin, function, keyword
|
494 | what = 'a shell %s' % kind
|
495 |
|
496 | print('%s is %s' % (name, what))
|
497 |
|
498 | # if kind == 'function':
|
499 | # bash is the only shell that prints the function
|
500 |
|
501 |
|
502 | def _PrintEntry(arg, row):
|
503 | # type: (arg_types.type, Tuple[str, str, Optional[str]]) -> None
|
504 |
|
505 | _, kind, resolved = row
|
506 | assert kind is not None
|
507 |
|
508 | if arg.t: # short string
|
509 | print(kind)
|
510 |
|
511 | elif arg.p:
|
512 | #log('%s %s %s', name, kind, resolved)
|
513 | if kind == 'file':
|
514 | print(resolved)
|
515 |
|
516 | else: # free-form text
|
517 | _PrintFreeForm(row)
|
518 |
|
519 |
|
520 | class Command(vm._Builtin):
|
521 | """'command ls' suppresses function lookup."""
|
522 |
|
523 | def __init__(
|
524 | self,
|
525 | shell_ex, # type: vm._Executor
|
526 | funcs, # type: state.Procs
|
527 | aliases, # type: Dict[str, str]
|
528 | search_path, # type: state.SearchPath
|
529 | ):
|
530 | # type: (...) -> None
|
531 | self.shell_ex = shell_ex
|
532 | self.funcs = funcs
|
533 | self.aliases = aliases
|
534 | self.search_path = search_path
|
535 |
|
536 | def Run(self, cmd_val):
|
537 | # type: (cmd_value.Argv) -> int
|
538 |
|
539 | # accept_typed_args=True because we invoke other builtins
|
540 | attrs, arg_r = flag_util.ParseCmdVal('command',
|
541 | cmd_val,
|
542 | accept_typed_args=True)
|
543 | arg = arg_types.command(attrs.attrs)
|
544 |
|
545 | argv, locs = arg_r.Rest2()
|
546 |
|
547 | if arg.v or arg.V:
|
548 | status = 0
|
549 | for argument in argv:
|
550 | r = _ResolveName(argument, self.funcs, self.aliases,
|
551 | self.search_path, False)
|
552 | if len(r):
|
553 | # Print only the first occurrence
|
554 | row = r[0]
|
555 | if arg.v:
|
556 | name, _, path = row
|
557 | if path is not None:
|
558 | print(path) # /usr/bin/awk
|
559 | else:
|
560 | print(name) # myfunc
|
561 | else:
|
562 | _PrintFreeForm(row)
|
563 | else:
|
564 | # match bash behavior by printing to stderr
|
565 | print_stderr('%s: not found' % argument)
|
566 | status = 1 # nothing printed, but we fail
|
567 |
|
568 | return status
|
569 |
|
570 | cmd_val2 = cmd_value.Argv(argv, locs, cmd_val.is_last_cmd,
|
571 | cmd_val.self_obj, cmd_val.proc_args)
|
572 |
|
573 | cmd_st = CommandStatus.CreateNull(alloc_lists=True)
|
574 |
|
575 | # If we respected do_fork here instead of passing DO_FORK
|
576 | # unconditionally, the case 'command date | wc -l' would take 2
|
577 | # processes instead of 3. See test/syscall
|
578 | run_flags = executor.NO_CALL_PROCS
|
579 | if cmd_val.is_last_cmd:
|
580 | run_flags |= executor.IS_LAST_CMD
|
581 | if arg.p:
|
582 | run_flags |= executor.USE_DEFAULT_PATH
|
583 |
|
584 | return self.shell_ex.RunSimpleCommand(cmd_val2, cmd_st, run_flags)
|
585 |
|
586 |
|
587 | def _ShiftArgv(cmd_val):
|
588 | # type: (cmd_value.Argv) -> cmd_value.Argv
|
589 | return cmd_value.Argv(cmd_val.argv[1:], cmd_val.arg_locs[1:],
|
590 | cmd_val.is_last_cmd, cmd_val.self_obj,
|
591 | cmd_val.proc_args)
|
592 |
|
593 |
|
594 | class Builtin(vm._Builtin):
|
595 |
|
596 | def __init__(self, shell_ex, errfmt):
|
597 | # type: (vm._Executor, ui.ErrorFormatter) -> None
|
598 | self.shell_ex = shell_ex
|
599 | self.errfmt = errfmt
|
600 |
|
601 | def Run(self, cmd_val):
|
602 | # type: (cmd_value.Argv) -> int
|
603 |
|
604 | if len(cmd_val.argv) == 1:
|
605 | return 0 # this could be an error in strict mode?
|
606 |
|
607 | name = cmd_val.argv[1]
|
608 |
|
609 | # Run regular builtin or special builtin
|
610 | to_run = consts.LookupNormalBuiltin(name)
|
611 | if to_run == consts.NO_INDEX:
|
612 | to_run = consts.LookupSpecialBuiltin(name)
|
613 | if to_run == consts.NO_INDEX:
|
614 | location = cmd_val.arg_locs[1]
|
615 | if consts.LookupAssignBuiltin(name) != consts.NO_INDEX:
|
616 | # NOTE: There's a similar restriction for 'command'
|
617 | self.errfmt.Print_("Can't run assignment builtin recursively",
|
618 | blame_loc=location)
|
619 | else:
|
620 | self.errfmt.Print_("%r isn't a shell builtin" % name,
|
621 | blame_loc=location)
|
622 | return 1
|
623 |
|
624 | cmd_val2 = _ShiftArgv(cmd_val)
|
625 | return self.shell_ex.RunBuiltin(to_run, cmd_val2)
|
626 |
|
627 |
|
628 | class RunProc(vm._Builtin):
|
629 |
|
630 | def __init__(self, shell_ex, procs, errfmt):
|
631 | # type: (vm._Executor, state.Procs, ui.ErrorFormatter) -> None
|
632 | self.shell_ex = shell_ex
|
633 | self.procs = procs
|
634 | self.errfmt = errfmt
|
635 |
|
636 | def Run(self, cmd_val):
|
637 | # type: (cmd_value.Argv) -> int
|
638 | _, arg_r = flag_util.ParseCmdVal('runproc',
|
639 | cmd_val,
|
640 | accept_typed_args=True)
|
641 | argv, locs = arg_r.Rest2()
|
642 |
|
643 | if len(argv) == 0:
|
644 | raise error.Usage('requires arguments', loc.Missing)
|
645 |
|
646 | name = argv[0]
|
647 | proc, _ = self.procs.GetInvokable(name)
|
648 | if not proc:
|
649 | # note: should runproc be invoke?
|
650 | self.errfmt.PrintMessage('runproc: no invokable named %r' % name)
|
651 | return 1
|
652 |
|
653 | cmd_val2 = cmd_value.Argv(argv, locs, cmd_val.is_last_cmd,
|
654 | cmd_val.self_obj, cmd_val.proc_args)
|
655 |
|
656 | cmd_st = CommandStatus.CreateNull(alloc_lists=True)
|
657 | run_flags = executor.IS_LAST_CMD if cmd_val.is_last_cmd else 0
|
658 | return self.shell_ex.RunSimpleCommand(cmd_val2, cmd_st, run_flags)
|
659 |
|
660 |
|
661 | class Invoke(vm._Builtin):
|
662 | """
|
663 | Introspection:
|
664 |
|
665 | invoke - YSH introspection on first word
|
666 | type --all - introspection on variables too?
|
667 | - different than = type(x)
|
668 |
|
669 | 3 Coarsed-grained categories
|
670 | - invoke --builtin aka builtin
|
671 | - including special builtins
|
672 | - invoke --proc-like aka runproc
|
673 | - myproc (42)
|
674 | - sh-func
|
675 | - invokable-obj
|
676 | - invoke --extern aka extern
|
677 |
|
678 | Note: If you don't distinguish between proc, sh-func, and invokable-obj,
|
679 | then 'runproc' suffices.
|
680 |
|
681 | invoke --proc-like reads more nicely though, and it also combines.
|
682 |
|
683 | invoke --builtin --extern # this is like 'command'
|
684 |
|
685 | You can also negate:
|
686 |
|
687 | invoke --no-proc-like --no-builtin --no-extern
|
688 |
|
689 | - type -t also has 'keyword' and 'assign builtin'
|
690 |
|
691 | With no args, print a table of what's available
|
692 |
|
693 | invoke --builtin
|
694 | invoke --builtin true
|
695 | """
|
696 |
|
697 | def __init__(self, shell_ex, procs, errfmt):
|
698 | # type: (vm._Executor, state.Procs, ui.ErrorFormatter) -> None
|
699 | self.shell_ex = shell_ex
|
700 | self.procs = procs
|
701 | self.errfmt = errfmt
|
702 |
|
703 | def Run(self, cmd_val):
|
704 | # type: (cmd_value.Argv) -> int
|
705 | _, arg_r = flag_util.ParseCmdVal('invoke',
|
706 | cmd_val,
|
707 | accept_typed_args=True)
|
708 | #argv, locs = arg_r.Rest2()
|
709 |
|
710 | print('TODO: invoke')
|
711 | # TODO
|
712 | return 0
|
713 |
|
714 |
|
715 | class Extern(vm._Builtin):
|
716 |
|
717 | def __init__(self, shell_ex, procs, errfmt):
|
718 | # type: (vm._Executor, state.Procs, ui.ErrorFormatter) -> None
|
719 | self.shell_ex = shell_ex
|
720 | self.procs = procs
|
721 | self.errfmt = errfmt
|
722 |
|
723 | def Run(self, cmd_val):
|
724 | # type: (cmd_value.Argv) -> int
|
725 | _, arg_r = flag_util.ParseCmdVal('extern',
|
726 | cmd_val,
|
727 | accept_typed_args=True)
|
728 | #argv, locs = arg_r.Rest2()
|
729 |
|
730 | print('TODO: extern')
|
731 |
|
732 | return 0
|
733 |
|
734 |
|
735 | def _ResolveName(
|
736 | name, # type: str
|
737 | procs, # type: state.Procs
|
738 | aliases, # type: Dict[str, str]
|
739 | search_path, # type: state.SearchPath
|
740 | do_all, # type: bool
|
741 | ):
|
742 | # type: (...) -> List[Tuple[str, str, Optional[str]]]
|
743 | """
|
744 | Returns:
|
745 | A list of (name, type, optional file system path)
|
746 |
|
747 | TODO: All of these could be in YSH:
|
748 |
|
749 | type, type -t, type -a
|
750 | pp proc
|
751 |
|
752 | We could builtin functions like isShellFunc() and isInvokableObj()
|
753 | """
|
754 | # MyPy tuple type
|
755 | no_str = None # type: Optional[str]
|
756 |
|
757 | results = [] # type: List[Tuple[str, str, Optional[str]]]
|
758 |
|
759 | if procs:
|
760 | if procs.IsShellFunc(name):
|
761 | results.append((name, 'function', no_str))
|
762 |
|
763 | if procs.IsProc(name):
|
764 | results.append((name, 'proc', no_str))
|
765 | elif procs.IsInvokableObj(name): # can't be both proc and obj
|
766 | results.append((name, 'invokable', no_str))
|
767 |
|
768 | if name in aliases:
|
769 | results.append((name, 'alias', aliases[name]))
|
770 |
|
771 | # See if it's a builtin
|
772 | if consts.LookupNormalBuiltin(name) != 0:
|
773 | results.append((name, 'builtin', no_str))
|
774 | elif consts.LookupSpecialBuiltin(name) != 0:
|
775 | results.append((name, 'builtin', no_str))
|
776 | elif consts.LookupAssignBuiltin(name) != 0:
|
777 | results.append((name, 'builtin', no_str))
|
778 |
|
779 | # See if it's a keyword
|
780 | if consts.IsControlFlow(name): # continue, etc.
|
781 | results.append((name, 'keyword', no_str))
|
782 | elif consts.IsKeyword(name):
|
783 | results.append((name, 'keyword', no_str))
|
784 |
|
785 | # See if it's external
|
786 | for path in search_path.LookupReflect(name, do_all):
|
787 | if posix.access(path, X_OK):
|
788 | results.append((name, 'file', path))
|
789 |
|
790 | return results
|
791 |
|
792 |
|
793 | class Type(vm._Builtin):
|
794 |
|
795 | def __init__(
|
796 | self,
|
797 | funcs, # type: state.Procs
|
798 | aliases, # type: Dict[str, str]
|
799 | search_path, # type: state.SearchPath
|
800 | errfmt, # type: ui.ErrorFormatter
|
801 | ):
|
802 | # type: (...) -> None
|
803 | self.funcs = funcs
|
804 | self.aliases = aliases
|
805 | self.search_path = search_path
|
806 | self.errfmt = errfmt
|
807 |
|
808 | def Run(self, cmd_val):
|
809 | # type: (cmd_value.Argv) -> int
|
810 | attrs, arg_r = flag_util.ParseCmdVal('type', cmd_val)
|
811 | arg = arg_types.type(attrs.attrs)
|
812 |
|
813 | if arg.f: # suppress function lookup
|
814 | funcs = None # type: state.Procs
|
815 | else:
|
816 | funcs = self.funcs
|
817 |
|
818 | status = 0
|
819 | names = arg_r.Rest()
|
820 |
|
821 | if arg.P: # -P should forces PATH search, regardless of builtin/alias/function/etc.
|
822 | for name in names:
|
823 | paths = self.search_path.LookupReflect(name, arg.a)
|
824 | if len(paths):
|
825 | for path in paths:
|
826 | print(path)
|
827 | else:
|
828 | status = 1
|
829 | return status
|
830 |
|
831 | for argument in names:
|
832 | r = _ResolveName(argument, funcs, self.aliases, self.search_path,
|
833 | arg.a)
|
834 | if arg.a:
|
835 | for row in r:
|
836 | _PrintEntry(arg, row)
|
837 | else:
|
838 | if len(r): # Just print the first one
|
839 | _PrintEntry(arg, r[0])
|
840 |
|
841 | # Error case
|
842 | if len(r) == 0:
|
843 | if not arg.t: # 'type -t' is silent in this case
|
844 | # match bash behavior by printing to stderr
|
845 | print_stderr('%s: not found' % argument)
|
846 | status = 1 # nothing printed, but we fail
|
847 |
|
848 | return status
|