Debian Codegraph @

terps/tads/tads3/vmdynfunc.h

raw symbols SCIP
1 /* $Header$ */
2
3 /*
4 * Copyright (c) 2010 Michael J. Roberts. All Rights Reserved.
5 *
6 * Please see the accompanying license file, LICENSE.TXT, for information
7 * on using and copying this software.
8 */
9 /*
10 Name
11 vmdynfunc.h - Code Object
12 Function
13 A Code Object is an intrinsic class object that contains a block of byte
14 code. This can be used for things like debugger expressions and run-time
15 evaluation and code creation.
16
17 A Code Object is immutable, like a String or List. It contains the
18 original source code text, as a UTF-8 string, and the corresponding
19 compiled byte code.
20 Notes
21
22 Modified
23 12/13/09 MJRoberts - Creation
24 */
25
26 #ifndef VMDYNFUNC_H
27 #define VMDYNFUNC_H
28
29 #include "t3std.h"
30 #include "vmtype.h"
31 #include "tcprstyp.h"
32 #include "vmglob.h"
33 #include "vmobj.h"
34 #include "vmundo.h"
35
36
37 /* ------------------------------------------------------------------------ */
38 /*
39 * The image file data block is arranged as follows:
40 *
41 *. UINT2 code_length
42 *. UINT2 obj_ref_cnt
43 *. DATAHOLDER src_string
44 *. BYTE[code_length] bytecode
45 *. UINT2[ref_cnt] obj_refs
46 *
47 * code_length is the size of the bytecode stream, in bytes.
48 *
49 * obj_ref_cnt is the number of object references. These are stored
50 * immediately after the bytecode stream. Each reference array entry is a
51 * UINT2 giving the byte offset in the bytecode array of the reference,
52 * which is a UINT4 stored in portable format giving the object ID.
53 */
54
55
56 /* ------------------------------------------------------------------------ */
57 /*
58 * Our in-memory extension data structure, which mimics the image file
59 * structure but uses native types.
60 */
61
62 /* prefix header size */
63 const size_t VMCO_PREFIX_LENGTH = VMB_OBJECT_ID;
64
65 /* extension structure */
66 struct vm_dynfunc_ext
67 {
68 /* allocate the structure */
69 static vm_dynfunc_ext *alloc_ext(VMG_ class CVmDynamicFunc *self,
70 size_t bytecode_len, int obj_ref_cnt);
71
72 /* the source string object */
73 vm_val_t src;
74
75 /*
76 * Method context object. For a function that's compiled with a local
77 * stack frame context, this is the 'self' object or the complete
78 * method context object (suitable for the LOADCTX opcode), as
79 * applicable, for the enclosing method. This allows the function to
80 * establish the dynamic enclosing method context at entry.
81 */
82 vm_val_t method_ctx;
83
84 /* the size in bytes of the byte code data */
85 size_t bytecode_len;
86
87 /* number of object references in the fixup list */
88 int obj_ref_cnt;
89
90 /*
91 * Object references. The structure is allocated with enough memory
92 * for 'obj_ref_cnt' entries in this array.
93 */
94 uint obj_refs[1];
95
96 /*
97 * The structure is allocated with memory following the 'obj_refs'
98 * array for the following dynamic elements:
99 *
100 *. char dynamic_code_header[VMB_OBJECT_ID]
101 *. char bytecode[bytecode_len]
102 *
103 * Explanation of the dynamic object header:
104 *
105 * The VM internally refers to executing code by a pointer directly
106 * into the code's physical memory. It always keeps an Entry Pointer
107 * value giving a pointer to the first byte of the method; this makes
108 * it easy to get metadata about any active code block by serving as an
109 * identifier for the code.
110 *
111 * Regular code is stored at compile-time in the Code Pool, which is a
112 * special block of read-only memory especially for code. The FUNCPTR
113 * and CODEPTR primitive datatypes contain offsets into the Code Pool.
114 * A function generated by the compiler is represented by a FUNCPTR
115 * value. To get a FUNCPTR value given an Entry Pointer, we simply
116 * translate the physical memory pointer back into a Code Pool offset,
117 * and wrap the result in a FUNCPTR value.
118 *
119 * Dynamic code objects are not in the Code Pool, however, since that's
120 * read-only memory that we can't add to at run-time. Dynamic code
121 * objects are instead allocated in the garbage-collected heap like
122 * other objects. So we need some way to translate from an Entry
123 * Pointer that points into a dynamic object back into a vm_val_t. The
124 * vm_val_t representation of a dynamic object is a reference to the
125 * object - i.e., an OBJ value containing the code object's ID.
126 * There's no generic way to look up an object ID given the extension
127 * pointer, which is what the Entry Pointer for a dynamic code object
128 * basically is. (The Entry Pointer doesn't actually point to the
129 * extension - it points to the start of the 'buf' element of the
130 * extension, because that's where our method header starts.) So, we
131 * need our own way of working from the Entry Point back to our object
132 * ID. To do this, we simply add our object ID just ahead of the
133 * method header. To generate a vm_val_t from an Entry Pointer value,
134 * then, we first look to see if the pointer is a Code Pool element; if
135 * so, we use a FUNCPTR value; if not, it must be a dynamic code
136 * object, so we retrieve the OBJECT_ID value at (Entry Pointer -
137 * VMB_OBJECT_ID) as an object ID, and create an OBJ value with that
138 * ID.
139 */
140
141 /* get a pointer to the dynamic code object method header prefix */
142 char *get_prefix_ptr()
143 {
144 /* the prefix starts after the obj_ref array */
145 return (char *)&obj_refs[obj_ref_cnt];
146 }
147
148 /* get a pointer to the start of the byte code */
149 char *get_bytecode_ptr()
150 {
151 /* the byte code starts after the dynamic code prefix */
152 return get_prefix_ptr() + VMCO_PREFIX_LENGTH;
153 }
154 };
155
156
157 /* ------------------------------------------------------------------------ */
158 /*
159 * DynamicFunc metaclass
160 */
161
162 class CVmDynamicFunc: public CVmObject
163 {
164 friend class CVmMetaclassDynamicFunc;
165 friend class CVmDynamicCompiler;
166
167 public:
168 /* metaclass registration object */
169 static class CVmMetaclass *metaclass_reg_;
170 class CVmMetaclass *get_metaclass_reg() const { return metaclass_reg_; }
171
172 /* am I of the given metaclass? */
173 virtual int is_of_metaclass(class CVmMetaclass *meta) const
174 {
175 /* try my own metaclass and my base class */
176 return (meta == metaclass_reg_
177 || CVmObject::is_of_metaclass(meta));
178 }
179
180 /* is this a DynamicFunc object? */
181 static int is_dynfunc_obj(VMG_ vm_obj_id_t obj)
182 { return vm_objp(vmg_ obj)->is_of_metaclass(metaclass_reg_); }
183
184 /*
185 * Given a pointer to a method header, retrieve the object ID of the
186 * DynamicFunc that owns the bytecode. Returns VM_INVALID_OBJ if we
187 * can't find a valid owner.
188 */
189 static vm_obj_id_t get_obj_from_prefix(VMG_ const uchar *p);
190
191 /* create from a string, without saving the source text */
192 static vm_obj_id_t create(VMG_ int in_root_set,
193 vm_obj_id_t globals, vm_obj_id_t locals,
194 vm_obj_id_t macros,
195 const char *src, size_t src_len)
196 {
197 vm_val_t v;
198 v.set_nil();
199 return create(vmg_ in_root_set, globals, locals, macros,
200 &v, src, src_len);
201 }
202
203 /* create from a string value */
204 static vm_obj_id_t create(VMG_ int in_root_set,
205 vm_obj_id_t globals, vm_obj_id_t locals,
206 vm_obj_id_t macros,
207 const vm_val_t *src);
208
209 /* create from a string, optionally saving the string value */
210 static vm_obj_id_t create(VMG_ int in_root_set,
211 vm_obj_id_t symtab, vm_obj_id_t locals,
212 vm_obj_id_t macros,
213 const vm_val_t *src_val,
214 const char *src, size_t src_len);
215
216 /* create dynamically using stack arguments */
217 static vm_obj_id_t create_from_stack(VMG_ const uchar **pc_ptr,
218 uint argc);
219
220 /* notify of deletion */
221 void notify_delete(VMG_ int in_root_set);
222
223 /*
224 * call a static property - we don't have any of our own, so simply
225 * "inherit" the base class handling
226 */
227 static int call_stat_prop(VMG_ vm_val_t *result,
228 const uchar **pc_ptr, uint *argc,
229 vm_prop_id_t prop)
230 {
231 return CVmObject::
232 call_stat_prop(vmg_ result, pc_ptr, argc, prop);
233 }
234
235 /* reserve constant data */
236 virtual void reserve_const_data(VMG_ class CVmConstMapper *mapper,
237 vm_obj_id_t self)
238 {
239 /* we cannot be converted to constant data */
240 }
241
242 /* convert to constant data */
243 virtual void convert_to_const_data(VMG_ class CVmConstMapper *,
244 vm_obj_id_t)
245 {
246 /* we don't reference anything */
247 }
248
249 /* index the object */
250 virtual int index_val_q(VMG_ vm_val_t *result,
251 vm_obj_id_t self,
252 const vm_val_t *index_val);
253
254 /* set a property */
255 void set_prop(VMG_ class CVmUndo *,
256 vm_obj_id_t, vm_prop_id_t, const vm_val_t *)
257 {
258 /* we have no settable properties */
259 err_throw(VMERR_INVALID_SETPROP);
260 }
261
262 /* get a property */
263 int get_prop(VMG_ vm_prop_id_t prop, vm_val_t *val,
264 vm_obj_id_t self, vm_obj_id_t *source_obj, uint *argc);
265
266 /* invoke */
267 int get_invoker(VMG_ vm_val_t *val);
268
269 /* undo operations - we're immutable, so we can ignore these */
270 void notify_new_savept() { }
271 void apply_undo(VMG_ struct CVmUndoRecord *) { }
272 void discard_undo(VMG_ struct CVmUndoRecord *) { }
273 void mark_undo_ref(VMG_ struct CVmUndoRecord *) { }
274
275 /* mark our references (we reference our source string) */
276 void mark_refs(VMG_ uint);
277
278 /* we don't keep any weak references */
279 void remove_stale_weak_refs(VMG0_) { }
280 void remove_stale_undo_weak_ref(VMG_ struct CVmUndoRecord *) { }
281
282 /* load from an image file */
283 void load_from_image(VMG_ vm_obj_id_t self, const char *ptr, size_t siz);
284
285 /* reload from an image file */
286 void reload_from_image(VMG_ vm_obj_id_t self,
287 const char *ptr, size_t siz);
288
289 /* rebuild for image file */
290 virtual ulong rebuild_image(VMG_ char *buf, ulong buflen);
291
292 /* save to a file */
293 void save_to_file(VMG_ class CVmFile *fp);
294
295 /* restore from a file */
296 void restore_from_file(VMG_ vm_obj_id_t self,
297 class CVmFile *fp, class CVmObjFixup *fixups);
298
299 /* we're immutable, so we're definitely not changed since loading */
300 int is_changed_since_load() const { return FALSE; }
301
302 protected:
303 /* get my extension data */
304 vm_dynfunc_ext *get_ext() const { return (vm_dynfunc_ext *)ext_; }
305
306 /* load or reload image data */
307 void load_image_data(VMG_ vm_obj_id_t self, const char *ptr, size_t siz);
308
309 /* set the method context object */
310 void set_method_ctx(const vm_val_t *val) { get_ext()->method_ctx = *val; }
311
312 /* create a with no initial contents */
313 CVmDynamicFunc() { ext_ = 0; }
314
315 /* create with the given byte code array length */
316 CVmDynamicFunc(VMG_ vm_obj_id_t self, const vm_val_t *src,
317 size_t bytecode_len, int obj_ref_cnt);
318
319 /* property evaluator - undefined function */
320 int getp_undef(VMG_ vm_obj_id_t, vm_val_t *, uint *) { return FALSE; }
321
322 /* property evaluator - get my source text */
323 int getp_get_source(VMG_ vm_obj_id_t, vm_val_t *, uint *);
324
325 /* property evaluation function table */
326 static int (CVmDynamicFunc::*func_table_[])(
327 VMG_ vm_obj_id_t self, vm_val_t *retval, uint *argc);
328 };
329
330
331 /* ------------------------------------------------------------------------ */
332 /*
333 * DynamicFunc registration table object
334 */
335 class CVmMetaclassDynamicFunc: public CVmMetaclass
336 {
337 public:
338 /* get the global name */
339 const char *get_meta_name() const { return "dynamic-func/030000"; }
340
341 /* create from image file */
342 void create_for_image_load(VMG_ vm_obj_id_t id)
343 {
344 new (vmg_ id) CVmDynamicFunc();
345 G_obj_table->set_obj_gc_characteristics(id, TRUE, FALSE);
346 }
347
348 /* create from restoring from saved state */
349 void create_for_restore(VMG_ vm_obj_id_t id)
350 {
351 new (vmg_ id) CVmDynamicFunc();
352 G_obj_table->set_obj_gc_characteristics(id, TRUE, FALSE);
353 }
354
355 /* create dynamically using stack arguments */
356 vm_obj_id_t create_from_stack(VMG_ const uchar **pc_ptr, uint argc)
357 { return CVmDynamicFunc::create_from_stack(vmg_ pc_ptr, argc); }
358
359 /* call a static property */
360 int call_stat_prop(VMG_ vm_val_t *result,
361 const uchar **pc_ptr, uint *argc,
362 vm_prop_id_t prop)
363 {
364 return CVmDynamicFunc::call_stat_prop(vmg_ result, pc_ptr, argc, prop);
365 }
366 };
367
368 /* ------------------------------------------------------------------------ */
369 /*
370 * Dynamic compiler interface
371 */
372
373
374 /* compilation modes */
375 enum CVmDynCompMode
376 {
377 /* compile an expression */
378 DCModeExpression,
379
380 /* auto-sensing: 'function' syntax, 'method' syntax, or an expression */
381 DCModeAuto,
382
383 /* compile a grammar production rule (alternative) list */
384 DCModeGramAlt
385 };
386
387 /* debugger expression context */
388 struct CVmDynCompDebug
389 {
390 CVmDynCompDebug(class CTcPrsDbgSymtab *symtab,
391 tcpn_dyncomp_info &di, int self_valid)
392 {
393 this->symtab = symtab;
394 this->di = di;
395 this->self_valid = self_valid;
396 }
397
398 /* IN: local symbol table for debugger expression evaluation */
399 class CTcPrsDbgSymtab *symtab;
400
401 /* IN: debugger evaluation context settings */
402 tcpn_dyncomp_info di;
403
404 /* IN: is there a valid 'self' for this expression? */
405 int self_valid;
406
407 /* OUT: the parsed expression is an lvalue */
408 int is_lval;
409 };
410
411 /* results structure */
412 struct CVmDynCompResults
413 {
414 CVmDynCompResults()
415 {
416 /* clear the error code */
417 err = 0;
418
419 /* no error message */
420 msgbuf = 0;
421 }
422
423 virtual ~CVmDynCompResults()
424 {
425 free_msgbuf();
426 }
427
428 /* Explicitly free the message buffer */
429 void free_msgbuf()
430 {
431 if (msgbuf != 0)
432 {
433 t3free(msgbuf);
434 msgbuf = 0;
435 }
436 }
437
438 /* throw a dynamic compilation error based on the results */
439 void throw_error(VMG0_);
440
441 /*
442 * In grammar mode (DCModeGramAlt), the compiler passes back the parsed
443 * alt list to the caller by calling this method. Callers that don't
444 * parse grammar rules can leave this as a no-op. 'alts' is the head
445 * of the alternative list for the parsed grammar rule.
446 */
447 virtual void save_grammar(VMG_ class CTcGramProdAlt * /*alts*/,
448 struct CTcGramPropArrows * /*arrows*/) { }
449
450 /* compiler error code */
451 int err;
452
453 /*
454 * Message buffer. The compiler allocates this via t3malloc() if an
455 * error occurs.
456 */
457 char *msgbuf;
458 };
459
460 /*
461 * dynamic compiler
462 */
463 class CVmDynamicCompiler
464 {
465 public:
466 /* create */
467 CVmDynamicCompiler(VMG0_);
468
469 /* destroy */
470 ~CVmDynamicCompiler();
471
472 /*
473 * Get or create the global singleton instance. This creates an
474 * instance if it doesn't already exist, so that we don't instantiate
475 * the compiler structures until they're actually needed. Once we
476 * create the object, we keep it around in a global.
477 */
478 static CVmDynamicCompiler *get(VMG0_);
479
480 /*
481 * Compile source code into byte code, returning a new DynamicFunc
482 * instance containing the compiled function. The return value is the
483 * ID of the new object if the compilation was successful, or
484 * VM_INVALID_OBJ if the compilation failed.
485 *
486 * The source code is the string given by 'src' and 'srclen'. If
487 * 'srcval' is non-null, it should be a VM_SSTR or VM_OBJ value with
488 * the VM representation of the source code string; we'll store this
489 * with the DynamicFunc for retrieval with getSource(). If 'srcval' is
490 * null, the DynamicFunc won't store the source, so getSource() will
491 * return nil.
492 *
493 * 'mode' gives the compilation mode, which controls how the source
494 * string is parsed.
495 *
496 * If 'dbg' is non-null, we compile for the debugger, with the options
497 * in 'dbg'. Debugger evaluation is slightly different from regular
498 * evaluation because it can access local variables from an enclosing
499 * scope.
500 *
501 * If 'errp' is non-null, we'll fill it in with the TCERR_xxx number
502 * for the first compiler error, if any.
503 *
504 * If 'msgbuf' is non-null, we'll fill it in with an allocated string
505 * buffer containing the compiler error message(s). Multiple messages
506 * are separated by newline '\n' characters. The caller must free this
507 * buffer with t3free() when done with it.
508 */
509 vm_obj_id_t compile(VMG_ int in_root_set,
510 vm_obj_id_t globals, vm_obj_id_t locals,
511 vm_obj_id_t macros,
512 const vm_val_t *srcval,
513 const char *src, size_t srclen,
514 CVmDynCompMode mode, CVmDynCompDebug *dbg,
515 CVmDynCompResults *results);
516
517 protected:
518 /* generate code for a code body */
519 int gen_code_body(
520 VMG_ class CTPNStmTop *node, const vm_val_t *srcval,
521 CVmDynCompDebug *dbg);
522
523 /* parser */
524 class CTcParser *prs_;
525
526 /* compiler host interface */
527 class CTcHostIfcDynComp *hostifc_;
528 };
529
530
531
532 #endif /* VMDYNFUNC_H */
533
534 /*
535 * Register the class
536 */
537 VM_REGISTER_METACLASS(CVmDynamicFunc)