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

789 lines, 463 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
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 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
102def _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
130class 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 _UseExec(self, cmd_val, path, path_loc, c_parser):
242 # type: (cmd_value.Argv, str, loc_t, cmd_parse.CommandParser) -> Tuple[int, Optional[Obj]]
243
244 attrs = NewDict() # type: Dict[str, value_t]
245 error_strs = [] # type: List[str]
246
247 with dev.ctx_Tracer(self.tracer, 'use', cmd_val.argv):
248 with state.ctx_ModuleEval(self.mem, attrs, error_strs):
249 with state.ctx_ThisDir(self.mem, path):
250 src = source.OtherFile(path, path_loc)
251 with alloc.ctx_SourceCode(self.arena, src):
252 try:
253 status = main_loop.Batch(
254 self.cmd_ev,
255 c_parser,
256 self.errfmt,
257 cmd_flags=cmd_eval.RaiseControlFlow)
258 except vm.IntControlFlow as e:
259 if e.IsReturn():
260 status = e.StatusCode()
261 else:
262 raise
263 if status != 0:
264 return status, None
265 #e_die("'use' failed 2", path_loc)
266
267 if len(error_strs):
268 for s in error_strs:
269 self.errfmt.PrintMessage('Error: %s' % s, path_loc)
270 return 1, None
271
272 # Builtin proc that serves as __invoke__ - it looks up procs in 'self'
273 methods = Obj(None,
274 {'__invoke__': value.BuiltinProc(self.module_invoke)})
275 module_obj = Obj(methods, attrs)
276 return 0, module_obj
277
278 def _Source(self, cmd_val):
279 # type: (cmd_value.Argv) -> int
280 attrs, arg_r = flag_util.ParseCmdVal('source', cmd_val)
281 arg = arg_types.source(attrs.attrs)
282
283 path_arg, path_loc = arg_r.ReadRequired2('requires a file path')
284
285 # Old:
286 # source --builtin two.sh # looks up stdlib/two.sh
287 # New:
288 # source $LIB_OSH/two.sh # looks up stdlib/osh/two.sh
289 # source ///osh/two.sh # looks up stdlib/osh/two.sh
290 embed_path = None # type: Optional[str]
291 if arg.builtin:
292 embed_path = path_arg
293 elif path_arg.startswith('///'):
294 embed_path = path_arg[3:]
295
296 if embed_path is not None:
297 load_path, c_parser = self.LoadEmbeddedFile(embed_path, path_loc)
298 if c_parser is None:
299 return 1 # error was already shown
300
301 return self._SourceExec(cmd_val, arg_r, load_path, c_parser)
302
303 else:
304 # 'source' respects $PATH
305 resolved = self.search_path.LookupOne(path_arg,
306 exec_required=False)
307 if resolved is None:
308 resolved = path_arg
309
310 f, c_parser = self._LoadDiskFile(resolved, path_loc)
311 if c_parser is None:
312 return 1 # error was already shown
313
314 with process.ctx_FileCloser(f):
315 return self._SourceExec(cmd_val, arg_r, path_arg, c_parser)
316
317 raise AssertionError()
318
319 def _Use(self, cmd_val):
320 # type: (cmd_value.Argv) -> int
321 """
322 Module system with all the power of Python, but still a proc
323
324 use util.ysh # util is a value.Obj
325
326 # Importing a bunch of words
327 use dialect-ninja.ysh --all-provided
328 use dialect-github.ysh --all-provided
329
330 # This declares some names
331 use --extern grep sed
332
333 # Renaming
334 use util.ysh (&myutil)
335
336 # Ignore
337 use util.ysh (&_)
338
339 # Picking specifics
340 use util.ysh --names log die
341
342 # Rename
343 var mylog = log
344 """
345 attrs, arg_r = flag_util.ParseCmdVal('use', cmd_val)
346 arg = arg_types.use(attrs.attrs)
347
348 # Accepts any args
349 if arg.extern_: # use --extern grep # no-op for static analysis
350 return 0
351
352 path_arg, path_loc = arg_r.ReadRequired2('requires a module path')
353 # TODO on usage:
354 # - typed arg is value.Place
355 # - block arg binds 'pick' and 'all'
356 # Although ALL these 3 mechanisms can be done with 'const' assignments.
357 # Hm.
358 arg_r.Done()
359
360 # I wonder if modules should be FROZEN value.Obj, not mutable?
361
362 # Similar logic as 'source'
363 if path_arg.startswith('///'):
364 embed_path = path_arg[3:]
365 else:
366 embed_path = None
367
368 if self.mem.InsideFunction():
369 raise error.Usage("may only be used at the top level", path_loc)
370
371 # Important, consider:
372 # use symlink.ysh # where symlink.ysh -> realfile.ysh
373 #
374 # Then the cache key would be '/some/path/realfile.ysh'
375 # But the variable name bound is 'symlink'
376 var_name = _VarName(path_arg)
377 #log('var %s', var_name)
378
379 if embed_path is not None:
380 # Embedded modules are cached using /// path as cache key
381 cached_obj = self._embed_cache.get(embed_path)
382 if cached_obj:
383 state.SetGlobalValue(self.mem, var_name, cached_obj)
384 return 0
385
386 load_path, c_parser = self.LoadEmbeddedFile(embed_path, path_loc)
387 if c_parser is None:
388 return 1 # error was already shown
389
390 status, obj = self._UseExec(cmd_val, load_path, path_loc, c_parser)
391 if status != 0:
392 return status
393 state.SetGlobalValue(self.mem, var_name, obj)
394 self._embed_cache[embed_path] = obj
395
396 else:
397 normalized = libc.realpath(path_arg)
398 if normalized is None:
399 self.errfmt.Print_("use: couldn't find %r" % path_arg,
400 blame_loc=path_loc)
401 return 1
402
403 # Disk modules are cached using normalized path as cache key
404 cached_obj = self._disk_cache.get(normalized)
405 if cached_obj:
406 state.SetGlobalValue(self.mem, var_name, cached_obj)
407 return 0
408
409 f, c_parser = self._LoadDiskFile(normalized, path_loc)
410 if c_parser is None:
411 return 1 # error was already shown
412
413 with process.ctx_FileCloser(f):
414 status, obj = self._UseExec(cmd_val, path_arg, path_loc,
415 c_parser)
416 if status != 0:
417 return status
418 state.SetGlobalValue(self.mem, var_name, obj)
419 self._disk_cache[normalized] = obj
420
421 return 0
422
423
424def _PrintFreeForm(row):
425 # type: (Tuple[str, str, Optional[str]]) -> None
426 name, kind, resolved = row
427
428 if kind == 'file':
429 what = resolved
430 elif kind == 'alias':
431 what = ('an alias for %s' %
432 j8_lite.EncodeString(resolved, unquoted_ok=True))
433 elif kind in ('proc', 'invokable'):
434 # Note: haynode should be an invokable
435 what = 'a YSH %s' % kind
436 else: # builtin, function, keyword
437 what = 'a shell %s' % kind
438
439 print('%s is %s' % (name, what))
440
441 # if kind == 'function':
442 # bash is the only shell that prints the function
443
444
445def _PrintEntry(arg, row):
446 # type: (arg_types.type, Tuple[str, str, Optional[str]]) -> None
447
448 _, kind, resolved = row
449 assert kind is not None
450
451 if arg.t: # short string
452 print(kind)
453
454 elif arg.p:
455 #log('%s %s %s', name, kind, resolved)
456 if kind == 'file':
457 print(resolved)
458
459 else: # free-form text
460 _PrintFreeForm(row)
461
462
463class Command(vm._Builtin):
464 """'command ls' suppresses function lookup."""
465
466 def __init__(
467 self,
468 shell_ex, # type: vm._Executor
469 funcs, # type: state.Procs
470 aliases, # type: Dict[str, str]
471 search_path, # type: state.SearchPath
472 ):
473 # type: (...) -> None
474 self.shell_ex = shell_ex
475 self.funcs = funcs
476 self.aliases = aliases
477 self.search_path = search_path
478
479 def Run(self, cmd_val):
480 # type: (cmd_value.Argv) -> int
481
482 # accept_typed_args=True because we invoke other builtins
483 attrs, arg_r = flag_util.ParseCmdVal('command',
484 cmd_val,
485 accept_typed_args=True)
486 arg = arg_types.command(attrs.attrs)
487
488 argv, locs = arg_r.Rest2()
489
490 if arg.v or arg.V:
491 status = 0
492 for argument in argv:
493 r = _ResolveName(argument, self.funcs, self.aliases,
494 self.search_path, False)
495 if len(r):
496 # command -v prints the name (-V is more detailed)
497 # Print it only once.
498 row = r[0]
499 name, _, _ = row
500 if arg.v:
501 print(name)
502 else:
503 _PrintFreeForm(row)
504 else:
505 # match bash behavior by printing to stderr
506 print_stderr('%s: not found' % argument)
507 status = 1 # nothing printed, but we fail
508
509 return status
510
511 cmd_val2 = cmd_value.Argv(argv, locs, cmd_val.is_last_cmd,
512 cmd_val.self_obj, cmd_val.proc_args)
513
514 cmd_st = CommandStatus.CreateNull(alloc_lists=True)
515
516 # If we respected do_fork here instead of passing DO_FORK
517 # unconditionally, the case 'command date | wc -l' would take 2
518 # processes instead of 3. See test/syscall
519 run_flags = executor.NO_CALL_PROCS
520 if cmd_val.is_last_cmd:
521 run_flags |= executor.IS_LAST_CMD
522 if arg.p:
523 run_flags |= executor.USE_DEFAULT_PATH
524
525 return self.shell_ex.RunSimpleCommand(cmd_val2, cmd_st, run_flags)
526
527
528def _ShiftArgv(cmd_val):
529 # type: (cmd_value.Argv) -> cmd_value.Argv
530 return cmd_value.Argv(cmd_val.argv[1:], cmd_val.arg_locs[1:],
531 cmd_val.is_last_cmd, cmd_val.self_obj,
532 cmd_val.proc_args)
533
534
535class Builtin(vm._Builtin):
536
537 def __init__(self, shell_ex, errfmt):
538 # type: (vm._Executor, ui.ErrorFormatter) -> None
539 self.shell_ex = shell_ex
540 self.errfmt = errfmt
541
542 def Run(self, cmd_val):
543 # type: (cmd_value.Argv) -> int
544
545 if len(cmd_val.argv) == 1:
546 return 0 # this could be an error in strict mode?
547
548 name = cmd_val.argv[1]
549
550 # Run regular builtin or special builtin
551 to_run = consts.LookupNormalBuiltin(name)
552 if to_run == consts.NO_INDEX:
553 to_run = consts.LookupSpecialBuiltin(name)
554 if to_run == consts.NO_INDEX:
555 location = cmd_val.arg_locs[1]
556 if consts.LookupAssignBuiltin(name) != consts.NO_INDEX:
557 # NOTE: There's a similar restriction for 'command'
558 self.errfmt.Print_("Can't run assignment builtin recursively",
559 blame_loc=location)
560 else:
561 self.errfmt.Print_("%r isn't a shell builtin" % name,
562 blame_loc=location)
563 return 1
564
565 cmd_val2 = _ShiftArgv(cmd_val)
566 return self.shell_ex.RunBuiltin(to_run, cmd_val2)
567
568
569class RunProc(vm._Builtin):
570
571 def __init__(self, shell_ex, procs, errfmt):
572 # type: (vm._Executor, state.Procs, ui.ErrorFormatter) -> None
573 self.shell_ex = shell_ex
574 self.procs = procs
575 self.errfmt = errfmt
576
577 def Run(self, cmd_val):
578 # type: (cmd_value.Argv) -> int
579 _, arg_r = flag_util.ParseCmdVal('runproc',
580 cmd_val,
581 accept_typed_args=True)
582 argv, locs = arg_r.Rest2()
583
584 if len(argv) == 0:
585 raise error.Usage('requires arguments', loc.Missing)
586
587 name = argv[0]
588 proc, _ = self.procs.GetInvokable(name)
589 if not proc:
590 # note: should runproc be invoke?
591 self.errfmt.PrintMessage('runproc: no invokable named %r' % name)
592 return 1
593
594 cmd_val2 = cmd_value.Argv(argv, locs, cmd_val.is_last_cmd,
595 cmd_val.self_obj, cmd_val.proc_args)
596
597 cmd_st = CommandStatus.CreateNull(alloc_lists=True)
598 run_flags = executor.IS_LAST_CMD if cmd_val.is_last_cmd else 0
599 return self.shell_ex.RunSimpleCommand(cmd_val2, cmd_st, run_flags)
600
601
602class Invoke(vm._Builtin):
603 """
604 Introspection:
605
606 invoke - YSH introspection on first word
607 type --all - introspection on variables too?
608 - different than = type(x)
609
610 3 Coarsed-grained categories
611 - invoke --builtin aka builtin
612 - including special builtins
613 - invoke --proc-like aka runproc
614 - myproc (42)
615 - sh-func
616 - invokable-obj
617 - invoke --extern aka extern
618
619 Note: If you don't distinguish between proc, sh-func, and invokable-obj,
620 then 'runproc' suffices.
621
622 invoke --proc-like reads more nicely though, and it also combines.
623
624 invoke --builtin --extern # this is like 'command'
625
626 You can also negate:
627
628 invoke --no-proc-like --no-builtin --no-extern
629
630 - type -t also has 'keyword' and 'assign builtin'
631
632 With no args, print a table of what's available
633
634 invoke --builtin
635 invoke --builtin true
636 """
637
638 def __init__(self, shell_ex, procs, errfmt):
639 # type: (vm._Executor, state.Procs, ui.ErrorFormatter) -> None
640 self.shell_ex = shell_ex
641 self.procs = procs
642 self.errfmt = errfmt
643
644 def Run(self, cmd_val):
645 # type: (cmd_value.Argv) -> int
646 _, arg_r = flag_util.ParseCmdVal('invoke',
647 cmd_val,
648 accept_typed_args=True)
649 #argv, locs = arg_r.Rest2()
650
651 print('TODO: invoke')
652 # TODO
653 return 0
654
655
656class Extern(vm._Builtin):
657
658 def __init__(self, shell_ex, procs, errfmt):
659 # type: (vm._Executor, state.Procs, ui.ErrorFormatter) -> None
660 self.shell_ex = shell_ex
661 self.procs = procs
662 self.errfmt = errfmt
663
664 def Run(self, cmd_val):
665 # type: (cmd_value.Argv) -> int
666 _, arg_r = flag_util.ParseCmdVal('extern',
667 cmd_val,
668 accept_typed_args=True)
669 #argv, locs = arg_r.Rest2()
670
671 print('TODO: extern')
672
673 return 0
674
675
676def _ResolveName(
677 name, # type: str
678 procs, # type: state.Procs
679 aliases, # type: Dict[str, str]
680 search_path, # type: state.SearchPath
681 do_all, # type: bool
682):
683 # type: (...) -> List[Tuple[str, str, Optional[str]]]
684 """
685 TODO: Can this be moved to pure YSH?
686
687 All of these could be in YSH:
688
689 type, type -t, type -a
690 pp proc
691
692 We would have primitive isShellFunc() and isInvokableObj() functions
693 """
694
695 # MyPy tuple type
696 no_str = None # type: Optional[str]
697
698 results = [] # type: List[Tuple[str, str, Optional[str]]]
699
700 if procs:
701 if procs.IsShellFunc(name):
702 results.append((name, 'function', no_str))
703
704 if procs.IsProc(name):
705 results.append((name, 'proc', no_str))
706 elif procs.IsInvokableObj(name): # can't be both proc and obj
707 results.append((name, 'invokable', no_str))
708
709 if name in aliases:
710 results.append((name, 'alias', aliases[name]))
711
712 # See if it's a builtin
713 if consts.LookupNormalBuiltin(name) != 0:
714 results.append((name, 'builtin', no_str))
715 elif consts.LookupSpecialBuiltin(name) != 0:
716 results.append((name, 'builtin', no_str))
717 elif consts.LookupAssignBuiltin(name) != 0:
718 results.append((name, 'builtin', no_str))
719
720 # See if it's a keyword
721 if consts.IsControlFlow(name): # continue, etc.
722 results.append((name, 'keyword', no_str))
723 elif consts.IsKeyword(name):
724 results.append((name, 'keyword', no_str))
725
726 # See if it's external
727 for path in search_path.LookupReflect(name, do_all):
728 if posix.access(path, X_OK):
729 results.append((name, 'file', path))
730
731 return results
732
733
734class Type(vm._Builtin):
735
736 def __init__(
737 self,
738 funcs, # type: state.Procs
739 aliases, # type: Dict[str, str]
740 search_path, # type: state.SearchPath
741 errfmt, # type: ui.ErrorFormatter
742 ):
743 # type: (...) -> None
744 self.funcs = funcs
745 self.aliases = aliases
746 self.search_path = search_path
747 self.errfmt = errfmt
748
749 def Run(self, cmd_val):
750 # type: (cmd_value.Argv) -> int
751 attrs, arg_r = flag_util.ParseCmdVal('type', cmd_val)
752 arg = arg_types.type(attrs.attrs)
753
754 if arg.f: # suppress function lookup
755 funcs = None # type: state.Procs
756 else:
757 funcs = self.funcs
758
759 status = 0
760 names = arg_r.Rest()
761
762 if arg.P: # -P should forces PATH search, regardless of builtin/alias/function/etc.
763 for name in names:
764 paths = self.search_path.LookupReflect(name, arg.a)
765 if len(paths):
766 for path in paths:
767 print(path)
768 else:
769 status = 1
770 return status
771
772 for argument in names:
773 r = _ResolveName(argument, funcs, self.aliases, self.search_path,
774 arg.a)
775 if arg.a:
776 for row in r:
777 _PrintEntry(arg, row)
778 else:
779 if len(r): # Just print the first one
780 _PrintEntry(arg, r[0])
781
782 # Error case
783 if len(r) == 0:
784 if not arg.t: # 'type -t' is silent in this case
785 # match bash behavior by printing to stderr
786 print_stderr('%s: not found' % argument)
787 status = 1 # nothing printed, but we fail
788
789 return status