OILS / builtin / meta_oils.py View on Github | oils.pub

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