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

321 lines, 180 significant
1#!/usr/bin/env python2
2"""
3func_reflect.py - Functions for reflecting on Oils code - OSH or YSH.
4"""
5from __future__ import print_function
6
7from _devbuild.gen.runtime_asdl import scope_e
8from _devbuild.gen.syntax_asdl import (Token, source, debug_frame,
9 debug_frame_e)
10from _devbuild.gen.value_asdl import (value, value_e, value_t, cmd_frag)
11
12from core import alloc
13from core import error
14from core import main_loop
15from core import state
16from core import vm
17from data_lang import j8
18from display import ui
19from frontend import location
20from frontend import reader
21from frontend import typed_args
22from mycpp import mops
23from mycpp import mylib
24from mycpp.mylib import log, tagswitch
25
26from typing import List, cast, TYPE_CHECKING
27if TYPE_CHECKING:
28 from frontend import parse_lib
29
30_ = log
31
32
33class Id(vm._Callable):
34 """Return an integer object ID, like Python's id().
35
36 Long shot: pointer tagging, boxless value_t, and small string optimization
37 could mean that value.Str is no longer heap-allocated, and thus doesn't
38 have a GC ID?
39
40 What about value.{Bool,Int,Float}?
41
42 I guess only mutable objects can have IDs then
43 """
44
45 def __init__(self):
46 # type: () -> None
47 vm._Callable.__init__(self)
48
49 def Call(self, rd):
50 # type: (typed_args.Reader) -> value_t
51 unused_vm = rd.PosValue() # vm.id()
52 val = rd.PosValue()
53 rd.Done()
54
55 # Select mutable values for now
56 with tagswitch(val) as case:
57 if case(value_e.List, value_e.Dict, value_e.Obj):
58 id_ = j8.HeapValueId(val)
59 return value.Int(mops.IntWiden(id_))
60 else:
61 raise error.TypeErr(val, 'id() expected List, Dict, or Obj',
62 rd.BlamePos())
63 raise AssertionError()
64
65
66class GetFrame(vm._Callable):
67
68 def __init__(self, mem):
69 # type: (state.Mem) -> None
70 vm._Callable.__init__(self)
71 self.mem = mem
72
73 def Call(self, rd):
74 # type: (typed_args.Reader) -> value_t
75 unused_self = rd.PosObj()
76 index = mops.BigTruncate(rd.PosInt())
77 rd.Done()
78
79 length = len(self.mem.var_stack)
80 if index < 0:
81 index += length
82 if 0 <= index and index < length:
83 return value.Frame(self.mem.var_stack[index])
84 else:
85 raise error.Structured(3, "Invalid frame %d" % index,
86 rd.LeftParenToken())
87
88
89class BindFrame(vm._Callable):
90
91 def __init__(self):
92 # type: () -> None
93 vm._Callable.__init__(self)
94
95 def Call(self, rd):
96 # type: (typed_args.Reader) -> value_t
97
98 # TODO: also take an ExprFrag -> Expr
99
100 frag = rd.PosCommandFrag()
101 frame = rd.PosFrame()
102 rd.Done()
103 return value.Null
104 # TODO: I guess you have to bind 2 frames?
105 #return Command(cmd_frag.Expr(frag), frame, None)
106
107
108class GetDebugStack(vm._Callable):
109
110 def __init__(self, mem):
111 # type: (state.Mem) -> None
112 vm._Callable.__init__(self)
113 self.mem = mem
114
115 def Call(self, rd):
116 # type: (typed_args.Reader) -> value_t
117 unused_self = rd.PosObj()
118 rd.Done()
119
120 debug_frames = [] # type: List[value_t]
121 for fr in self.mem.debug_stack:
122 if fr.tag() in (debug_frame_e.ProcLike, debug_frame_e.Func,
123 debug_frame_e.Source, debug_frame_e.Use,
124 debug_frame_e.EvalBuiltin,
125 debug_frame_e.BeforeErrTrap):
126 debug_frames.append(value.DebugFrame(fr))
127 # Don't report stuff inside the err trap
128 if fr.tag() == debug_frame_e.BeforeErrTrap:
129 break
130
131 if 0:
132 for fr in debug_frames:
133 log('%s', fr.frame)
134 return value.List(debug_frames)
135
136
137def _FormatDebugFrame(buf, token):
138 # type: (mylib.Writer, Token) -> None
139 """
140 Based on _AddCallToken in core/state.py
141 Should probably move that into core/dev.py or something, and unify them
142
143 We also want the column number so we can print ^==
144 """
145 # note: absolute path can be lon,g, but Python prints it too
146 call_source = ui.GetLineSourceString(token.line)
147 line_num = token.line.line_num
148 call_line = token.line.content
149
150 func_str = ''
151 # This gives the wrong token? If we are calling p, it gives the definition
152 # of p. It doesn't give the func/proc that contains the call to p.
153
154 #if def_tok is not None:
155 # #log('DEF_TOK %s', def_tok)
156 # func_str = ' in %s' % lexer.TokenVal(def_tok)
157
158 # should be exactly 1 line
159 buf.write('%s:%d\n' % (call_source, line_num))
160
161 maybe_newline = '' if call_line.endswith('\n') else '\n'
162 buf.write(' %s%s' % (call_line, maybe_newline))
163
164 buf.write(' ') # prefix
165 ui.PrintCaretLine(call_line, token.col, token.length, buf)
166
167
168class DebugFrameToString(vm._Callable):
169
170 def __init__(self):
171 # type: () -> None
172 vm._Callable.__init__(self)
173
174 def Call(self, rd):
175 # type: (typed_args.Reader) -> value_t
176 frame = rd.PosDebugFrame()
177
178 rd.Done()
179
180 UP_frame = frame
181 buf = mylib.BufWriter()
182 with tagswitch(frame) as case:
183 if case(debug_frame_e.ProcLike):
184 frame = cast(debug_frame.ProcLike, UP_frame)
185 invoke_token = location.LeftTokenForCompoundWord(
186 frame.invoke_loc)
187 assert invoke_token is not None, frame.invoke_loc
188 _FormatDebugFrame(buf, invoke_token)
189 elif case(debug_frame_e.Func):
190 frame = cast(debug_frame.Func, UP_frame)
191 _FormatDebugFrame(buf, frame.call_tok)
192 elif case(debug_frame_e.Source):
193 frame = cast(debug_frame.Source, UP_frame)
194 _FormatDebugFrame(buf, frame.call_tok)
195 elif case(debug_frame_e.Use):
196 frame = cast(debug_frame.Use, UP_frame)
197 _FormatDebugFrame(buf, frame.invoke_tok)
198 elif case(debug_frame_e.EvalBuiltin):
199 frame = cast(debug_frame.EvalBuiltin, UP_frame)
200 _FormatDebugFrame(buf, frame.invoke_tok)
201 elif case(debug_frame_e.BeforeErrTrap):
202 frame = cast(debug_frame.BeforeErrTrap, UP_frame)
203 _FormatDebugFrame(buf, frame.tok)
204 else:
205 raise AssertionError()
206 return value.Str(buf.getvalue())
207
208
209class Shvar_get(vm._Callable):
210 """Look up with dynamic scope."""
211
212 def __init__(self, mem):
213 # type: (state.Mem) -> None
214 vm._Callable.__init__(self)
215 self.mem = mem
216
217 def Call(self, rd):
218 # type: (typed_args.Reader) -> value_t
219 name = rd.PosStr()
220 rd.Done()
221 return state.DynamicGetVar(self.mem, name, scope_e.Dynamic)
222
223
224class GetVar(vm._Callable):
225 """Look up a variable, with normal scoping rules."""
226
227 def __init__(self, mem):
228 # type: (state.Mem) -> None
229 vm._Callable.__init__(self)
230 self.mem = mem
231
232 def Call(self, rd):
233 # type: (typed_args.Reader) -> value_t
234 name = rd.PosStr()
235 rd.Done()
236 return state.DynamicGetVar(self.mem, name, scope_e.LocalOrGlobal)
237
238
239class SetVar(vm._Callable):
240 """Set a variable in the local scope.
241
242 We could have a separae setGlobal() too.
243 """
244
245 def __init__(self, mem):
246 # type: (state.Mem) -> None
247 vm._Callable.__init__(self)
248 self.mem = mem
249
250 def Call(self, rd):
251 # type: (typed_args.Reader) -> value_t
252 var_name = rd.PosStr()
253 val = rd.PosValue()
254 set_global = rd.NamedBool('global', False)
255 rd.Done()
256 scope = scope_e.GlobalOnly if set_global else scope_e.LocalOnly
257 self.mem.SetNamed(location.LName(var_name), val, scope)
258 return value.Null
259
260
261class ParseCommand(vm._Callable):
262
263 def __init__(self, parse_ctx, mem, errfmt):
264 # type: (parse_lib.ParseContext, state.Mem, ui.ErrorFormatter) -> None
265 self.parse_ctx = parse_ctx
266 self.mem = mem
267 self.errfmt = errfmt
268
269 def Call(self, rd):
270 # type: (typed_args.Reader) -> value_t
271 code_str = rd.PosStr()
272 rd.Done()
273
274 line_reader = reader.StringLineReader(code_str, self.parse_ctx.arena)
275 c_parser = self.parse_ctx.MakeOshParser(line_reader)
276
277 # TODO: it would be nice to point to the location of the expression
278 # argument
279 src = source.Dynamic('parseCommand()', rd.LeftParenToken())
280 with alloc.ctx_SourceCode(self.parse_ctx.arena, src):
281 try:
282 cmd = main_loop.ParseWholeFile(c_parser)
283 except error.Parse as e:
284 # This prints the location
285 self.errfmt.PrettyPrintError(e)
286
287 # TODO: add inner location info to this structured error
288 raise error.Structured(3, "Syntax error in parseCommand()",
289 rd.LeftParenToken())
290
291 # TODO: It's a little weird that this captures?
292 # We should have scoping like 'eval $mystr'
293 # Or we should have
294 #
295 # var c = parseCommand('echo hi') # raw AST
296 # var block = Block(c) # attachs the current frame
297 #
298 # Yeah we might need this for value.Expr too, to control evaluation of
299 # names
300 #
301 # value.Expr vs. value.BoundExpr - it's bound to the frame it's defined
302 # in
303 # value.Command vs. value.Block - BoundCommand?
304
305 return value.Command(cmd_frag.Expr(cmd), self.mem.CurrentFrame(),
306 self.mem.GlobalFrame())
307
308
309class ParseExpr(vm._Callable):
310
311 def __init__(self, parse_ctx, errfmt):
312 # type: (parse_lib.ParseContext, ui.ErrorFormatter) -> None
313 self.parse_ctx = parse_ctx
314 self.errfmt = errfmt
315
316 def Call(self, rd):
317 # type: (typed_args.Reader) -> value_t
318 code_str = rd.PosStr()
319 rd.Done()
320
321 return value.Null