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

329 lines, 177 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, CompoundWord, source,
9 debug_frame, 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 # Don't show stack frames created when running the ERR trap - we
123 # want the main stuff
124 if fr.tag() == debug_frame_e.BeforeErrTrap:
125 break
126 if fr.tag() in (debug_frame_e.ProcLike, debug_frame_e.Source,
127 debug_frame_e.CompoundWord, debug_frame_e.Token):
128 debug_frames.append(value.DebugFrame(fr))
129
130 if 0:
131 for fr in debug_frames:
132 log('%s', fr.frame)
133 return value.List(debug_frames)
134
135
136def _FormatDebugFrame(buf, token):
137 # type: (mylib.Writer, Token) -> None
138 """
139 Based on _AddCallToken in core/state.py
140 Should probably move that into core/dev.py or something, and unify them
141
142 We also want the column number so we can print ^==
143 """
144 # note: absolute path can be lon,g, but Python prints it too
145 call_source = ui.GetLineSourceString(token.line)
146 line_num = token.line.line_num
147 call_line = token.line.content
148
149 func_str = ''
150 # This gives the wrong token? If we are calling p, it gives the definition
151 # of p. It doesn't give the func/proc that contains the call to p.
152
153 #if def_tok is not None:
154 # #log('DEF_TOK %s', def_tok)
155 # func_str = ' in %s' % lexer.TokenVal(def_tok)
156
157 # should be exactly 1 line
158 buf.write('%s:%d\n' % (call_source, line_num))
159
160 maybe_newline = '' if call_line.endswith('\n') else '\n'
161 buf.write(' %s%s' % (call_line, maybe_newline))
162
163 buf.write(' ') # prefix
164 ui.PrintCaretLine(call_line, token.col, token.length, buf)
165
166
167class DebugFrameToString(vm._Callable):
168
169 def __init__(self):
170 # type: () -> None
171 vm._Callable.__init__(self)
172
173 def Call(self, rd):
174 # type: (typed_args.Reader) -> value_t
175 frame = rd.PosDebugFrame()
176
177 rd.Done()
178
179 UP_frame = frame
180 buf = mylib.BufWriter()
181 with tagswitch(frame) as case:
182 if case(debug_frame_e.ProcLike):
183 frame = cast(debug_frame.ProcLike, UP_frame)
184 invoke_token = location.LeftTokenForCompoundWord(
185 frame.invoke_loc)
186 assert invoke_token is not None, frame.invoke_loc
187 _FormatDebugFrame(buf, invoke_token)
188
189 elif case(debug_frame_e.Source):
190 frame = cast(debug_frame.Source, UP_frame)
191 invoke_token = location.LeftTokenForCompoundWord(
192 frame.source_loc)
193 assert invoke_token is not None, frame.source_loc
194 _FormatDebugFrame(buf, invoke_token)
195
196 elif case(debug_frame_e.CompoundWord):
197 frame = cast(CompoundWord, UP_frame)
198 invoke_token = location.LeftTokenForCompoundWord(frame)
199 assert invoke_token is not None, frame
200 _FormatDebugFrame(buf, invoke_token)
201
202 elif case(debug_frame_e.Token):
203 frame = cast(Token, UP_frame)
204 _FormatDebugFrame(buf, frame)
205
206 # The location is unused; it is a sentinel
207 #elif case(debug_frame_e.BeforeErrTrap):
208 # frame = cast(debug_frame.BeforeErrTrap, UP_frame)
209 # _FormatDebugFrame(buf, frame.tok)
210
211 else:
212 raise AssertionError()
213
214 return value.Str(buf.getvalue())
215
216
217class Shvar_get(vm._Callable):
218 """Look up with dynamic scope."""
219
220 def __init__(self, mem):
221 # type: (state.Mem) -> None
222 vm._Callable.__init__(self)
223 self.mem = mem
224
225 def Call(self, rd):
226 # type: (typed_args.Reader) -> value_t
227 name = rd.PosStr()
228 rd.Done()
229 return state.DynamicGetVar(self.mem, name, scope_e.Dynamic)
230
231
232class GetVar(vm._Callable):
233 """Look up a variable, with normal scoping rules."""
234
235 def __init__(self, mem):
236 # type: (state.Mem) -> None
237 vm._Callable.__init__(self)
238 self.mem = mem
239
240 def Call(self, rd):
241 # type: (typed_args.Reader) -> value_t
242 name = rd.PosStr()
243 rd.Done()
244 return state.DynamicGetVar(self.mem, name, scope_e.LocalOrGlobal)
245
246
247class SetVar(vm._Callable):
248 """Set a variable in the local scope.
249
250 We could have a separae setGlobal() too.
251 """
252
253 def __init__(self, mem):
254 # type: (state.Mem) -> None
255 vm._Callable.__init__(self)
256 self.mem = mem
257
258 def Call(self, rd):
259 # type: (typed_args.Reader) -> value_t
260 var_name = rd.PosStr()
261 val = rd.PosValue()
262 set_global = rd.NamedBool('global', False)
263 rd.Done()
264 scope = scope_e.GlobalOnly if set_global else scope_e.LocalOnly
265 self.mem.SetNamed(location.LName(var_name), val, scope)
266 return value.Null
267
268
269class ParseCommand(vm._Callable):
270
271 def __init__(self, parse_ctx, mem, errfmt):
272 # type: (parse_lib.ParseContext, state.Mem, ui.ErrorFormatter) -> None
273 self.parse_ctx = parse_ctx
274 self.mem = mem
275 self.errfmt = errfmt
276
277 def Call(self, rd):
278 # type: (typed_args.Reader) -> value_t
279 code_str = rd.PosStr()
280 rd.Done()
281
282 line_reader = reader.StringLineReader(code_str, self.parse_ctx.arena)
283 c_parser = self.parse_ctx.MakeOshParser(line_reader)
284
285 # TODO: it would be nice to point to the location of the expression
286 # argument
287 src = source.Dynamic('parseCommand()', rd.LeftParenToken())
288 with alloc.ctx_SourceCode(self.parse_ctx.arena, src):
289 try:
290 cmd = main_loop.ParseWholeFile(c_parser)
291 except error.Parse as e:
292 # This prints the location
293 self.errfmt.PrettyPrintError(e)
294
295 # TODO: add inner location info to this structured error
296 raise error.Structured(3, "Syntax error in parseCommand()",
297 rd.LeftParenToken())
298
299 # TODO: It's a little weird that this captures?
300 # We should have scoping like 'eval $mystr'
301 # Or we should have
302 #
303 # var c = parseCommand('echo hi') # raw AST
304 # var block = Block(c) # attachs the current frame
305 #
306 # Yeah we might need this for value.Expr too, to control evaluation of
307 # names
308 #
309 # value.Expr vs. value.BoundExpr - it's bound to the frame it's defined
310 # in
311 # value.Command vs. value.Block - BoundCommand?
312
313 return value.Command(cmd_frag.Expr(cmd), self.mem.CurrentFrame(),
314 self.mem.GlobalFrame())
315
316
317class ParseExpr(vm._Callable):
318
319 def __init__(self, parse_ctx, errfmt):
320 # type: (parse_lib.ParseContext, ui.ErrorFormatter) -> None
321 self.parse_ctx = parse_ctx
322 self.errfmt = errfmt
323
324 def Call(self, rd):
325 # type: (typed_args.Reader) -> value_t
326 code_str = rd.PosStr()
327 rd.Done()
328
329 return value.Null