/[svn]/linuxsampler/trunk/src/scriptvm/common.h
ViewVC logotype

Contents of /linuxsampler/trunk/src/scriptvm/common.h

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3311 - (show annotations) (download) (as text)
Sat Jul 15 16:24:59 2017 UTC (6 years, 8 months ago) by schoenebeck
File MIME type: text/x-c++hdr
File size: 51865 byte(s)
* NKSP: Added built-in preprocessor condition NKSP_NO_MESSAGE,
  which can be set to disable all subsequent built-in "message()"
  function calls on preprocessor level.
* Bumped version (2.0.0.svn71).

1 /*
2 * Copyright (c) 2014-2017 Christian Schoenebeck
3 *
4 * http://www.linuxsampler.org
5 *
6 * This file is part of LinuxSampler and released under the same terms.
7 * See README file for details.
8 */
9
10 // This header defines data types shared between the VM core implementation
11 // (inside the current source directory) and other parts of the sampler
12 // (located at other source directories). It also acts as public API of the
13 // Real-Time script engine for other applications.
14
15 #ifndef LS_INSTR_SCRIPT_PARSER_COMMON_H
16 #define LS_INSTR_SCRIPT_PARSER_COMMON_H
17
18 #include "../common/global.h"
19 #include <vector>
20 #include <map>
21 #include <stddef.h> // offsetof()
22
23 namespace LinuxSampler {
24
25 /**
26 * Identifies the type of a noteworthy issue identified by the script
27 * parser. That's either a parser error or parser warning.
28 */
29 enum ParserIssueType_t {
30 PARSER_ERROR, ///< Script parser encountered an error, the script cannot be executed.
31 PARSER_WARNING ///< Script parser encountered a warning, the script may be executed if desired, but the script may not necessarily behave as originally intended by the script author.
32 };
33
34 /** @brief Expression's data type.
35 *
36 * Identifies to which data type an expression within a script evaluates to.
37 * This can for example reflect the data type of script function arguments,
38 * script function return values, but also the resulting data type of some
39 * mathematical formula within a script.
40 */
41 enum ExprType_t {
42 EMPTY_EXPR, ///< i.e. on invalid expressions or i.e. a function call that does not return a result value (the built-in wait() or message() functions for instance)
43 INT_EXPR, ///< integer (scalar) expression
44 INT_ARR_EXPR, ///< integer array expression
45 STRING_EXPR, ///< string expression
46 STRING_ARR_EXPR, ///< string array expression
47 };
48
49 /** @brief Result flags of a script statement or script function call.
50 *
51 * A set of bit flags which provide informations about the success or
52 * failure of a statement within a script. That's also especially used for
53 * providing informations about success / failure of a call to a built-in
54 * script function. The virtual machine evaluates these flags during runtime
55 * to decide whether it should i.e. stop or suspend execution of a script.
56 *
57 * Since these are bit flags, these constants are bitwise combined.
58 */
59 enum StmtFlags_t {
60 STMT_SUCCESS = 0, ///< Function / statement was executed successfully, no error occurred.
61 STMT_ABORT_SIGNALLED = 1, ///< VM should stop the current callback execution (usually because of an error, but might also be without an error reason, i.e. when the built-in script function exit() was called).
62 STMT_SUSPEND_SIGNALLED = (1<<1), ///< VM supended execution, either because the script called the built-in wait() script function or because the script consumed too much execution time and was forced by the VM to be suspended for some time
63 STMT_ERROR_OCCURRED = (1<<2), ///< VM stopped execution due to some script runtime error that occurred
64 };
65
66 /** @brief Virtual machine execution status.
67 *
68 * A set of bit flags which reflect the current overall execution status of
69 * the virtual machine concerning a certain script execution instance.
70 *
71 * Since these are bit flags, these constants are bitwise combined.
72 */
73 enum VMExecStatus_t {
74 VM_EXEC_NOT_RUNNING = 0, ///< Script is currently not executed by the VM.
75 VM_EXEC_RUNNING = 1, ///< The VM is currently executing the script.
76 VM_EXEC_SUSPENDED = (1<<1), ///< Script is currently suspended by the VM, either because the script called the built-in wait() script function or because the script consumed too much execution time and was forced by the VM to be suspended for some time.
77 VM_EXEC_ERROR = (1<<2), ///< A runtime error occurred while executing the script (i.e. a call to some built-in script function failed).
78 };
79
80 /** @brief Script event handler type.
81 *
82 * Identifies one of the possible event handler callback types defined by
83 * the NKSP script language.
84 */
85 enum VMEventHandlerType_t {
86 VM_EVENT_HANDLER_INIT, ///< Initilization event handler, that is script's "on init ... end on" code block.
87 VM_EVENT_HANDLER_NOTE, ///< Note event handler, that is script's "on note ... end on" code block.
88 VM_EVENT_HANDLER_RELEASE, ///< Release event handler, that is script's "on release ... end on" code block.
89 VM_EVENT_HANDLER_CONTROLLER, ///< Controller event handler, that is script's "on controller ... end on" code block.
90 };
91
92 // just symbol prototyping
93 class VMIntExpr;
94 class VMStringExpr;
95 class VMIntArrayExpr;
96 class VMStringArrayExpr;
97 class VMParserContext;
98
99 /** @brief Virtual machine expression
100 *
101 * This is the abstract base class for all expressions of scripts.
102 * Deriving classes must implement the abstract method exprType().
103 *
104 * An expression within a script is translated into one instance of this
105 * class. It allows a high level access for the virtual machine to evaluate
106 * and handle expressions appropriately during execution. Expressions are
107 * for example all kinds of formulas, function calls, statements or a
108 * combination of them. Most of them evaluate to some kind of value, which
109 * might be further processed as part of encompassing expressions to outer
110 * expression results and so forth.
111 */
112 class VMExpr {
113 public:
114 /**
115 * Identifies the data type to which the result of this expression
116 * evaluates to. This abstract method must be implemented by deriving
117 * classes.
118 */
119 virtual ExprType_t exprType() const = 0;
120
121 /**
122 * In case this expression is an integer expression, then this method
123 * returns a casted pointer to that VMIntExpr object. It returns NULL
124 * if this expression is not an integer expression.
125 *
126 * @b Note: type casting performed by this method is strict! That means
127 * if this expression is i.e. actually a string expression like "12",
128 * calling asInt() will @b not cast that numerical string expression to
129 * an integer expression 12 for you, instead this method will simply
130 * return NULL!
131 *
132 * @see exprType()
133 */
134 VMIntExpr* asInt() const;
135
136 /**
137 * In case this expression is a string expression, then this method
138 * returns a casted pointer to that VMStringExpr object. It returns NULL
139 * if this expression is not a string expression.
140 *
141 * @b Note: type casting performed by this method is strict! That means
142 * if this expression is i.e. actually an integer expression like 120,
143 * calling asString() will @b not cast that integer expression to a
144 * string expression "120" for you, instead this method will simply
145 * return NULL!
146 *
147 * @see exprType()
148 */
149 VMStringExpr* asString() const;
150
151 /**
152 * In case this expression is an integer array expression, then this
153 * method returns a casted pointer to that VMIntArrayExpr object. It
154 * returns NULL if this expression is not an integer array expression.
155 *
156 * @b Note: type casting performed by this method is strict! That means
157 * if this expression is i.e. an integer expression or a string
158 * expression, calling asIntArray() will @b not cast those scalar
159 * expressions to an array expression for you, instead this method will
160 * simply return NULL!
161 *
162 * @b Note: this method is currently, and in contrast to its other
163 * counter parts, declared as virtual method. Some deriving classes are
164 * currently using this to override this default implementation in order
165 * to implement an "evaluate now as integer array" behavior. This has
166 * efficiency reasons, however this also currently makes this part of
167 * the API less clean and should thus be addressed in future with
168 * appropriate changes to the API.
169 *
170 * @see exprType()
171 */
172 virtual VMIntArrayExpr* asIntArray() const;
173
174 /**
175 * Returns true in case this expression can be considered to be a
176 * constant expression. A constant expression will retain the same
177 * value throughout the entire life time of a script and the
178 * expression's constant value may be evaluated already at script
179 * parse time, which may result in performance benefits during script
180 * runtime.
181 *
182 * @b NOTE: A constant expression is per se always also non modifyable.
183 * But a non modifyable expression may not necessarily be a constant
184 * expression!
185 *
186 * @see isModifyable()
187 */
188 virtual bool isConstExpr() const = 0;
189
190 /**
191 * Returns true in case this expression is allowed to be modified.
192 * If this method returns @c false then this expression must be handled
193 * as read-only expression, which means that assigning a new value to it
194 * is either not possible or not allowed.
195 *
196 * @b NOTE: A constant expression is per se always also non modifyable.
197 * But a non modifyable expression may not necessarily be a constant
198 * expression!
199 *
200 * @see isConstExpr()
201 */
202 bool isModifyable() const;
203 };
204
205 /** @brief Virtual machine integer expression
206 *
207 * This is the abstract base class for all expressions inside scripts which
208 * evaluate to an integer (scalar) value. Deriving classes implement the
209 * abstract method evalInt() to return the actual integer result value of
210 * the expression.
211 */
212 class VMIntExpr : virtual public VMExpr {
213 public:
214 /**
215 * Returns the result of this expression as integer (scalar) value.
216 * This abstract method must be implemented by deriving classes.
217 */
218 virtual int evalInt() = 0;
219
220 /**
221 * Returns always INT_EXPR for instances of this class.
222 */
223 ExprType_t exprType() const OVERRIDE { return INT_EXPR; }
224 };
225
226 /** @brief Virtual machine string expression
227 *
228 * This is the abstract base class for all expressions inside scripts which
229 * evaluate to a string value. Deriving classes implement the abstract
230 * method evalStr() to return the actual string result value of the
231 * expression.
232 */
233 class VMStringExpr : virtual public VMExpr {
234 public:
235 /**
236 * Returns the result of this expression as string value. This abstract
237 * method must be implemented by deriving classes.
238 */
239 virtual String evalStr() = 0;
240
241 /**
242 * Returns always STRING_EXPR for instances of this class.
243 */
244 ExprType_t exprType() const OVERRIDE { return STRING_EXPR; }
245 };
246
247 /** @brief Virtual Machine Array Value Expression
248 *
249 * This is the abstract base class for all expressions inside scripts which
250 * evaluate to some kind of array value. Deriving classes implement the
251 * abstract method arraySize() to return the amount of elements within the
252 * array.
253 */
254 class VMArrayExpr : virtual public VMExpr {
255 public:
256 /**
257 * Returns amount of elements in this array. This abstract method must
258 * be implemented by deriving classes.
259 */
260 virtual int arraySize() const = 0;
261 };
262
263 /** @brief Virtual Machine Integer Array Expression
264 *
265 * This is the abstract base class for all expressions inside scripts which
266 * evaluate to an array of integer values. Deriving classes implement the
267 * abstract methods arraySize(), evalIntElement() and assignIntElement() to
268 * access the individual integer array values.
269 */
270 class VMIntArrayExpr : virtual public VMArrayExpr {
271 public:
272 /**
273 * Returns the (scalar) integer value of the array element given by
274 * element index @a i.
275 *
276 * @param i - array element index (must be between 0 .. arraySize() - 1)
277 */
278 virtual int evalIntElement(uint i) = 0;
279
280 /**
281 * Changes the current value of an element (given by array element
282 * index @a i) of this integer array.
283 *
284 * @param i - array element index (must be between 0 .. arraySize() - 1)
285 * @param value - new integer scalar value to be assigned to that array element
286 */
287 virtual void assignIntElement(uint i, int value) = 0;
288
289 /**
290 * Returns always INT_ARR_EXPR for instances of this class.
291 */
292 ExprType_t exprType() const OVERRIDE { return INT_ARR_EXPR; }
293 };
294
295 /** @brief Arguments (parameters) for being passed to a built-in script function.
296 *
297 * An argument or a set of arguments passed to a script function are
298 * translated by the parser to an instance of this class. This abstract
299 * interface class is used by implementations of built-in functions to
300 * obtain the individual function argument values being passed to them at
301 * runtime.
302 */
303 class VMFnArgs {
304 public:
305 /**
306 * Returns the amount of arguments going to be passed to the script
307 * function.
308 */
309 virtual int argsCount() const = 0;
310
311 /**
312 * Returns the respective argument (requested by argument index @a i) of
313 * this set of arguments. This method is called by implementations of
314 * built-in script functions to obtain the value of each function
315 * argument passed to the function at runtime.
316 *
317 * @param i - function argument index (indexed from left to right)
318 */
319 virtual VMExpr* arg(int i) = 0;
320 };
321
322 /** @brief Result value returned from a call to a built-in script function.
323 *
324 * Implementations of built-in script functions return an instance of this
325 * object to let the virtual machine obtain the result value of the function
326 * call, which might then be further processed by the virtual machine
327 * according to the script. It also provides informations about the success
328 * or failure of the function call.
329 */
330 class VMFnResult {
331 public:
332 /**
333 * Returns the result value of the function call, represented by a high
334 * level expression object.
335 */
336 virtual VMExpr* resultValue() = 0;
337
338 /**
339 * Provides detailed informations of the success / failure of the
340 * function call. The virtual machine is evaluating the flags returned
341 * here to decide whether it must abort or suspend execution of the
342 * script at this point.
343 */
344 virtual StmtFlags_t resultFlags() { return STMT_SUCCESS; }
345 };
346
347 /** @brief Virtual machine built-in function.
348 *
349 * Abstract base class for built-in script functions, defining the interface
350 * for all built-in script function implementations. All built-in script
351 * functions are deriving from this abstract interface class in order to
352 * provide their functionality to the virtual machine with this unified
353 * interface.
354 *
355 * The methods of this interface class provide two purposes:
356 *
357 * 1. When a script is loaded, the script parser uses the methods of this
358 * interface to check whether the script author was calling the
359 * respective built-in script function in a correct way. For example
360 * the parser checks whether the required amount of parameters were
361 * passed to the function and whether the data types passed match the
362 * data types expected by the function. If not, loading the script will
363 * be aborted with a parser error, describing to the user (i.e. script
364 * author) the precise misusage of the respective function.
365 * 2. After the script was loaded successfully and the script is executed,
366 * the virtual machine calls the exec() method of the respective built-in
367 * function to provide the actual functionality of the built-in function
368 * call.
369 */
370 class VMFunction {
371 public:
372 /**
373 * Script data type of the function's return value. If the function does
374 * not return any value (void), then it returns EMPTY_EXPR here.
375 */
376 virtual ExprType_t returnType() = 0;
377
378 /**
379 * Minimum amount of function arguments this function accepts. If a
380 * script is calling this function with less arguments, the script
381 * parser will throw a parser error.
382 */
383 virtual int minRequiredArgs() const = 0;
384
385 /**
386 * Maximum amount of function arguments this functions accepts. If a
387 * script is calling this function with more arguments, the script
388 * parser will throw a parser error.
389 */
390 virtual int maxAllowedArgs() const = 0;
391
392 /**
393 * Script data type of the function's @c iArg 'th function argument.
394 * The information provided here is less strong than acceptsArgType().
395 * The parser will compare argument data types provided in scripts by
396 * calling acceptsArgType(). The return value of argType() is used by the
397 * parser instead to show an appropriate parser error which data type
398 * this function usually expects as "default" data type. Reason: a
399 * function may accept multiple data types for a certain function
400 * argument and would automatically cast the passed argument value in
401 * that case to the type it actually needs.
402 *
403 * @param iArg - index of the function argument in question
404 * (must be between 0 .. maxAllowedArgs() - 1)
405 */
406 virtual ExprType_t argType(int iArg) const = 0;
407
408 /**
409 * This method is called by the parser to check whether arguments
410 * passed in scripts to this function are accepted by this function. If
411 * a script calls this function with an argument's data type not
412 * accepted by this function, the parser will throw a parser error. On
413 * such errors the data type returned by argType() will be used to
414 * assemble an appropriate error message regarding the precise misusage
415 * of the built-in function.
416 *
417 * @param iArg - index of the function argument in question
418 * (must be between 0 .. maxAllowedArgs() - 1)
419 * @param type - script data type used for this function argument by
420 * currently parsed script
421 * @return true if the given data type would be accepted for the
422 * respective function argument by the function
423 */
424 virtual bool acceptsArgType(int iArg, ExprType_t type) const = 0;
425
426 /**
427 * This method is called by the parser to check whether some arguments
428 * (and if yes which ones) passed to this script function will be
429 * modified by this script function. Most script functions simply use
430 * their arguments as inputs, that is they only read the argument's
431 * values. However some script function may also use passed
432 * argument(s) as output variables. In this case the function
433 * implementation must return @c true for the respective argument
434 * index here.
435 *
436 * @param iArg - index of the function argument in question
437 * (must be between 0 .. maxAllowedArgs() - 1)
438 */
439 virtual bool modifiesArg(int iArg) const = 0;
440
441 /**
442 * Implements the actual function execution. This exec() method is
443 * called by the VM whenever this function implementation shall be
444 * executed at script runtime. This method blocks until the function
445 * call completed.
446 *
447 * @param args - function arguments for executing this built-in function
448 * @returns function's return value (if any) and general status
449 * informations (i.e. whether the function call caused a
450 * runtime error)
451 */
452 virtual VMFnResult* exec(VMFnArgs* args) = 0;
453
454 /**
455 * Convenience method for function implementations to show warning
456 * messages during actual execution of the built-in function.
457 *
458 * @param txt - runtime warning text to be shown to user
459 */
460 void wrnMsg(const String& txt);
461
462 /**
463 * Convenience method for function implementations to show error
464 * messages during actual execution of the built-in function.
465 *
466 * @param txt - runtime error text to be shown to user
467 */
468 void errMsg(const String& txt);
469 };
470
471 /** @brief Virtual machine relative pointer.
472 *
473 * POD base of VMIntRelPtr and VMInt8RelPtr structures. Not intended to be
474 * used directly. Use VMIntRelPtr or VMInt8RelPtr instead.
475 *
476 * @see VMIntRelPtr, VMInt8RelPtr
477 */
478 struct VMRelPtr {
479 void** base; ///< Base pointer.
480 int offset; ///< Offset (in bytes) relative to base pointer.
481 bool readonly; ///< Whether the pointed data may be modified or just be read.
482 };
483
484 /** @brief Pointer to built-in VM integer variable (of C/C++ type int).
485 *
486 * Used for defining built-in 32 bit integer script variables.
487 *
488 * @b CAUTION: You may only use this class for pointing to C/C++ variables
489 * of type "int" (which on most systems is 32 bit in size). If the C/C++ int
490 * variable you want to reference is only 8 bit in size, then you @b must
491 * use VMInt8RelPtr instead!
492 *
493 * For efficiency reasons the actual native C/C++ int variable is referenced
494 * by two components here. The actual native int C/C++ variable in memory
495 * is dereferenced at VM run-time by taking the @c base pointer dereference
496 * and adding @c offset bytes. This has the advantage that for a large
497 * number of built-in int variables, only one (or few) base pointer need
498 * to be re-assigned before running a script, instead of updating each
499 * built-in variable each time before a script is executed.
500 *
501 * Refer to DECLARE_VMINT() for example code.
502 *
503 * @see VMInt8RelPtr, DECLARE_VMINT()
504 */
505 struct VMIntRelPtr : VMRelPtr {
506 VMIntRelPtr() {
507 base = NULL;
508 offset = 0;
509 readonly = false;
510 }
511 VMIntRelPtr(const VMRelPtr& data) {
512 base = data.base;
513 offset = data.offset;
514 readonly = false;
515 }
516 virtual int evalInt() { return *(int*)&(*(uint8_t**)base)[offset]; }
517 virtual void assign(int i) { *(int*)&(*(uint8_t**)base)[offset] = i; }
518 };
519
520 /** @brief Pointer to built-in VM integer variable (of C/C++ type int8_t).
521 *
522 * Used for defining built-in 8 bit integer script variables.
523 *
524 * @b CAUTION: You may only use this class for pointing to C/C++ variables
525 * of type "int8_t" (8 bit integer). If the C/C++ int variable you want to
526 * reference is an "int" type (which is 32 bit on most systems), then you
527 * @b must use VMIntRelPtr instead!
528 *
529 * For efficiency reasons the actual native C/C++ int variable is referenced
530 * by two components here. The actual native int C/C++ variable in memory
531 * is dereferenced at VM run-time by taking the @c base pointer dereference
532 * and adding @c offset bytes. This has the advantage that for a large
533 * number of built-in int variables, only one (or few) base pointer need
534 * to be re-assigned before running a script, instead of updating each
535 * built-in variable each time before a script is executed.
536 *
537 * Refer to DECLARE_VMINT() for example code.
538 *
539 * @see VMIntRelPtr, DECLARE_VMINT()
540 */
541 struct VMInt8RelPtr : VMIntRelPtr {
542 VMInt8RelPtr() : VMIntRelPtr() {}
543 VMInt8RelPtr(const VMRelPtr& data) : VMIntRelPtr(data) {}
544 virtual int evalInt() OVERRIDE {
545 return *(uint8_t*)&(*(uint8_t**)base)[offset];
546 }
547 virtual void assign(int i) OVERRIDE {
548 *(uint8_t*)&(*(uint8_t**)base)[offset] = i;
549 }
550 };
551
552 #if HAVE_CXX_EMBEDDED_PRAGMA_DIAGNOSTICS
553 # define COMPILER_DISABLE_OFFSETOF_WARNING \
554 _Pragma("GCC diagnostic push") \
555 _Pragma("GCC diagnostic ignored \"-Winvalid-offsetof\"")
556 # define COMPILER_RESTORE_OFFSETOF_WARNING \
557 _Pragma("GCC diagnostic pop")
558 #else
559 # define COMPILER_DISABLE_OFFSETOF_WARNING
560 # define COMPILER_RESTORE_OFFSETOF_WARNING
561 #endif
562
563 /**
564 * Convenience macro for initializing VMIntRelPtr and VMInt8RelPtr
565 * structures. Usage example:
566 * @code
567 * struct Foo {
568 * uint8_t a; // native representation of a built-in integer script variable
569 * int b; // native representation of another built-in integer script variable
570 * int c; // native representation of another built-in integer script variable
571 * uint8_t d; // native representation of another built-in integer script variable
572 * };
573 *
574 * // initializing the built-in script variables to some values
575 * Foo foo1 = (Foo) { 1, 2000, 3000, 4 };
576 * Foo foo2 = (Foo) { 5, 6000, 7000, 8 };
577 *
578 * Foo* pFoo;
579 *
580 * VMInt8RelPtr varA = DECLARE_VMINT(pFoo, class Foo, a);
581 * VMIntRelPtr varB = DECLARE_VMINT(pFoo, class Foo, b);
582 * VMIntRelPtr varC = DECLARE_VMINT(pFoo, class Foo, c);
583 * VMInt8RelPtr varD = DECLARE_VMINT(pFoo, class Foo, d);
584 *
585 * pFoo = &foo1;
586 * printf("%d\n", varA->evalInt()); // will print 1
587 * printf("%d\n", varB->evalInt()); // will print 2000
588 * printf("%d\n", varC->evalInt()); // will print 3000
589 * printf("%d\n", varD->evalInt()); // will print 4
590 *
591 * // same printf() code, just with pFoo pointer being changed ...
592 *
593 * pFoo = &foo2;
594 * printf("%d\n", varA->evalInt()); // will print 5
595 * printf("%d\n", varB->evalInt()); // will print 6000
596 * printf("%d\n", varC->evalInt()); // will print 7000
597 * printf("%d\n", varD->evalInt()); // will print 8
598 * @endcode
599 * As you can see above, by simply changing one single pointer, you can
600 * remap a huge bunch of built-in integer script variables to completely
601 * different native values/native variables. Which especially reduces code
602 * complexity inside the sampler engines which provide the actual script
603 * functionalities.
604 */
605 #define DECLARE_VMINT(basePtr, T_struct, T_member) ( \
606 /* Disable offsetof warning, trust us, we are cautios. */ \
607 COMPILER_DISABLE_OFFSETOF_WARNING \
608 (VMRelPtr) { \
609 (void**) &basePtr, \
610 offsetof(T_struct, T_member), \
611 false \
612 } \
613 COMPILER_RESTORE_OFFSETOF_WARNING \
614 ) \
615
616 /**
617 * Same as DECLARE_VMINT(), but this one defines the VMIntRelPtr and
618 * VMInt8RelPtr structures to be of read-only type. That means the script
619 * parser will abort any script at parser time if the script is trying to
620 * modify such a read-only built-in variable.
621 *
622 * @b NOTE: this is only intended for built-in read-only variables that
623 * may change during runtime! If your built-in variable's data is rather
624 * already available at parser time and won't change during runtime, then
625 * you should rather register a built-in constant in your VM class instead!
626 *
627 * @see ScriptVM::builtInConstIntVariables()
628 */
629 #define DECLARE_VMINT_READONLY(basePtr, T_struct, T_member) ( \
630 /* Disable offsetof warning, trust us, we are cautios. */ \
631 COMPILER_DISABLE_OFFSETOF_WARNING \
632 (VMRelPtr) { \
633 (void**) &basePtr, \
634 offsetof(T_struct, T_member), \
635 true \
636 } \
637 COMPILER_RESTORE_OFFSETOF_WARNING \
638 ) \
639
640 /** @brief Built-in VM 8 bit integer array variable.
641 *
642 * Used for defining built-in integer array script variables (8 bit per
643 * array element). Currently there is no support for any other kind of array
644 * type. So all integer arrays of scripts use 8 bit data types.
645 */
646 struct VMInt8Array {
647 int8_t* data;
648 int size;
649 bool readonly; ///< Whether the array data may be modified or just be read.
650
651 VMInt8Array() : data(NULL), size(0), readonly(false) {}
652 };
653
654 /** @brief Virtual machine script variable.
655 *
656 * Common interface for all variables accessed in scripts.
657 */
658 class VMVariable : virtual public VMExpr {
659 public:
660 /**
661 * Whether a script may modify the content of this variable by
662 * assigning a new value to it.
663 *
664 * @see isConstExpr(), assign()
665 */
666 virtual bool isAssignable() const = 0;
667
668 /**
669 * In case this variable is assignable, this method will be called to
670 * perform the value assignment to this variable with @a expr
671 * reflecting the new value to be assigned.
672 *
673 * @param expr - new value to be assigned to this variable
674 */
675 virtual void assignExpr(VMExpr* expr) = 0;
676 };
677
678 /** @brief Dynamically executed variable (abstract base class).
679 *
680 * Interface for the implementation of a dynamically generated content of
681 * a built-in script variable. Most built-in variables are simply pointers
682 * to some native location in memory. So when a script reads them, the
683 * memory location is simply read to get the value of the variable. A
684 * dynamic variable however is not simply a memory location. For each access
685 * to a dynamic variable some native code is executed to actually generate
686 * and provide the content (value) of this type of variable.
687 */
688 class VMDynVar : public VMVariable {
689 public:
690 /**
691 * Returns true in case this dynamic variable can be considered to be a
692 * constant expression. A constant expression will retain the same value
693 * throughout the entire life time of a script and the expression's
694 * constant value may be evaluated already at script parse time, which
695 * may result in performance benefits during script runtime.
696 *
697 * However due to the "dynamic" behavior of dynamic variables, almost
698 * all dynamic variables are probably not constant expressions. That's
699 * why this method returns @c false by default. If you are really sure
700 * that your dynamic variable implementation can be considered a
701 * constant expression then you may override this method and return
702 * @c true instead. Note that when you return @c true here, your
703 * dynamic variable will really just be executed once; and exectly
704 * already when the script is loaded!
705 *
706 * As an example you may implement a "constant" built-in dynamic
707 * variable that checks for a certain operating system feature and
708 * returns the result of that OS feature check as content (value) of
709 * this dynamic variable. Since the respective OS feature might become
710 * available/unavailable after OS updates, software migration, etc. the
711 * OS feature check should at least be performed once each time the
712 * application is launched. And since the OS feature check might take a
713 * certain amount of execution time, it might make sense to only
714 * perform the check if the respective variable name is actually
715 * referenced at all in the script to be loaded. Note that the dynamic
716 * variable will still be evaluated again though if the script is
717 * loaded again. So it is up to you to probably cache the result in the
718 * implementation of your dynamic variable.
719 *
720 * On doubt, please rather consider to use a constant built-in script
721 * variable instead of implementing a "constant" dynamic variable, due
722 * to the runtime overhead a dynamic variable may cause.
723 *
724 * @see isAssignable()
725 */
726 bool isConstExpr() const OVERRIDE { return false; }
727
728 /**
729 * In case this dynamic variable is assignable, the new value (content)
730 * to be assigned to this dynamic variable.
731 *
732 * By default this method does nothing. Override and implement this
733 * method in your subclass in case your dynamic variable allows to
734 * assign a new value by script.
735 *
736 * @param expr - new value to be assigned to this variable
737 */
738 void assignExpr(VMExpr* expr) OVERRIDE {}
739
740 virtual ~VMDynVar() {}
741 };
742
743 /** @brief Dynamically executed variable (of integer data type).
744 *
745 * This is the base class for all built-in integer script variables whose
746 * variable content needs to be provided dynamically by executable native
747 * code on each script variable access.
748 */
749 class VMDynIntVar : virtual public VMDynVar, virtual public VMIntExpr {
750 public:
751 };
752
753 /** @brief Dynamically executed variable (of string data type).
754 *
755 * This is the base class for all built-in string script variables whose
756 * variable content needs to be provided dynamically by executable native
757 * code on each script variable access.
758 */
759 class VMDynStringVar : virtual public VMDynVar, virtual public VMStringExpr {
760 public:
761 };
762
763 /** @brief Dynamically executed variable (of integer array data type).
764 *
765 * This is the base class for all built-in integer array script variables
766 * whose variable content needs to be provided dynamically by executable
767 * native code on each script variable access.
768 */
769 class VMDynIntArrayVar : virtual public VMDynVar, virtual public VMIntArrayExpr {
770 public:
771 };
772
773 /** @brief Provider for built-in script functions and variables.
774 *
775 * Abstract base class defining the high-level interface for all classes
776 * which add and implement built-in script functions and built-in script
777 * variables.
778 */
779 class VMFunctionProvider {
780 public:
781 /**
782 * Returns pointer to the built-in function with the given function
783 * @a name, or NULL if there is no built-in function with that function
784 * name.
785 *
786 * @param name - function name (i.e. "wait" or "message" or "exit", etc.)
787 */
788 virtual VMFunction* functionByName(const String& name) = 0;
789
790 /**
791 * Returns @c true if the passed built-in function is disabled and
792 * should be ignored by the parser. This method is called by the
793 * parser on preprocessor level for each built-in function call within
794 * a script. Accordingly if this method returns @c true, then the
795 * respective function call is completely filtered out on preprocessor
796 * level, so that built-in function won't make into the result virtual
797 * machine representation, nor would expressions of arguments passed to
798 * that built-in function call be evaluated, nor would any check
799 * regarding correct usage of the built-in function be performed.
800 * In other words: a disabled function call ends up as a comment block.
801 *
802 * @param fn - built-in function to be checked
803 * @param ctx - parser context at the position where the built-in
804 * function call is located within the script
805 */
806 virtual bool isFunctionDisabled(VMFunction* fn, VMParserContext* ctx) = 0;
807
808 /**
809 * Returns a variable name indexed map of all built-in script variables
810 * which point to native "int" scalar (usually 32 bit) variables.
811 */
812 virtual std::map<String,VMIntRelPtr*> builtInIntVariables() = 0;
813
814 /**
815 * Returns a variable name indexed map of all built-in script integer
816 * array variables with array element type "int8_t" (8 bit).
817 */
818 virtual std::map<String,VMInt8Array*> builtInIntArrayVariables() = 0;
819
820 /**
821 * Returns a variable name indexed map of all built-in constant script
822 * variables, which never change their value at runtime.
823 */
824 virtual std::map<String,int> builtInConstIntVariables() = 0;
825
826 /**
827 * Returns a variable name indexed map of all built-in dynamic variables,
828 * which are not simply data stores, rather each one of them executes
829 * natively to provide or alter the respective script variable data.
830 */
831 virtual std::map<String,VMDynVar*> builtInDynamicVariables() = 0;
832 };
833
834 /** @brief Execution state of a virtual machine.
835 *
836 * An instance of this abstract base class represents exactly one execution
837 * state of a virtual machine. This encompasses most notably the VM
838 * execution stack, and VM polyphonic variables. It does not contain global
839 * variables. Global variables are contained in the VMParserContext object.
840 * You might see a VMExecContext object as one virtual thread of the virtual
841 * machine.
842 *
843 * In contrast to a VMParserContext, a VMExecContext is not tied to a
844 * ScriptVM instance. Thus you can use a VMExecContext with different
845 * ScriptVM instances, however not concurrently at the same time.
846 *
847 * @see VMParserContext
848 */
849 class VMExecContext {
850 public:
851 virtual ~VMExecContext() {}
852
853 /**
854 * In case the script was suspended for some reason, this method returns
855 * the amount of microseconds before the script shall continue its
856 * execution. Note that the virtual machine itself does never put its
857 * own execution thread(s) to sleep. So the respective class (i.e. sampler
858 * engine) which is using the virtual machine classes here, must take
859 * care by itself about taking time stamps, determining the script
860 * handlers that shall be put aside for the requested amount of
861 * microseconds, indicated by this method by comparing the time stamps in
862 * real-time, and to continue passing the respective handler to
863 * ScriptVM::exec() as soon as its suspension exceeded, etc. Or in other
864 * words: all classes in this directory never have an idea what time it
865 * is.
866 *
867 * You should check the return value of ScriptVM::exec() to determine
868 * whether the script was actually suspended before calling this method
869 * here.
870 *
871 * @see ScriptVM::exec()
872 */
873 virtual int suspensionTimeMicroseconds() const = 0;
874
875 /**
876 * Causes all polyphonic variables to be reset to zero values. A
877 * polyphonic variable is expected to be zero when entering a new event
878 * handler instance. As an exception the values of polyphonic variables
879 * shall only be preserved from an note event handler instance to its
880 * correspending specific release handler instance. So in the latter
881 * case the script author may pass custom data from the note handler to
882 * the release handler, but only for the same specific note!
883 */
884 virtual void resetPolyphonicData() = 0;
885
886 /**
887 * Returns amount of virtual machine instructions which have been
888 * performed the last time when this execution context was executing a
889 * script. So in case you need the overall amount of instructions
890 * instead, then you need to add them by yourself after each
891 * ScriptVM::exec() call.
892 */
893 virtual size_t instructionsPerformed() const = 0;
894
895 /**
896 * Sends a signal to this script execution instance to abort its script
897 * execution as soon as possible. This method is called i.e. when one
898 * script execution instance intends to stop another script execution
899 * instance.
900 */
901 virtual void signalAbort() = 0;
902
903 /**
904 * Copies the current entire execution state from this object to the
905 * given object. So this can be used to "fork" a new script thread which
906 * then may run independently with its own polyphonic data for instance.
907 */
908 virtual void forkTo(VMExecContext* ectx) const = 0;
909 };
910
911 /** @brief Script callback for a certain event.
912 *
913 * Represents a script callback for a certain event, i.e.
914 * "on note ... end on" code block.
915 */
916 class VMEventHandler {
917 public:
918 /**
919 * Type of this event handler, which identifies its purpose. For example
920 * for a "on note ... end on" script callback block,
921 * @c VM_EVENT_HANDLER_NOTE would be returned here.
922 */
923 virtual VMEventHandlerType_t eventHandlerType() const = 0;
924
925 /**
926 * Name of the event handler which identifies its purpose. For example
927 * for a "on note ... end on" script callback block, the name "note"
928 * would be returned here.
929 */
930 virtual String eventHandlerName() const = 0;
931
932 /**
933 * Whether or not the event handler makes any use of so called
934 * "polyphonic" variables.
935 */
936 virtual bool isPolyphonic() const = 0;
937 };
938
939 /**
940 * Reflects the precise position and span of a specific code block within
941 * a script. This is currently only used for the locations of commented
942 * code blocks due to preprocessor statements, and for parser errors and
943 * parser warnings.
944 *
945 * @see ParserIssue for code locations of parser errors and parser warnings
946 *
947 * @see VMParserContext::preprocessorComments() for locations of code which
948 * have been filtered out by preprocessor statements
949 */
950 struct CodeBlock {
951 int firstLine; ///< The first line number of this code block within the script (indexed with 1 being the very first line).
952 int lastLine; ///< The last line number of this code block within the script.
953 int firstColumn; ///< The first column of this code block within the script (indexed with 1 being the very first column).
954 int lastColumn; ///< The last column of this code block within the script.
955 };
956
957 /**
958 * Encapsulates a noteworty parser issue. This encompasses the type of the
959 * issue (either a parser error or parser warning), a human readable
960 * explanation text of the error or warning and the location of the
961 * encountered parser issue within the script.
962 *
963 * @see VMSourceToken for processing syntax highlighting instead.
964 */
965 struct ParserIssue : CodeBlock {
966 String txt; ///< Human readable explanation text of the parser issue.
967 ParserIssueType_t type; ///< Whether this issue is either a parser error or just a parser warning.
968
969 /**
970 * Print this issue out to the console (stdio).
971 */
972 inline void dump() {
973 switch (type) {
974 case PARSER_ERROR:
975 printf("[ERROR] line %d, column %d: %s\n", firstLine, firstColumn, txt.c_str());
976 break;
977 case PARSER_WARNING:
978 printf("[Warning] line %d, column %d: %s\n", firstLine, firstColumn, txt.c_str());
979 break;
980 }
981 }
982
983 /**
984 * Returns true if this issue is a parser error. In this case the parsed
985 * script may not be executed!
986 */
987 inline bool isErr() const { return type == PARSER_ERROR; }
988
989 /**
990 * Returns true if this issue is just a parser warning. A parsed script
991 * that only raises warnings may be executed if desired, however the
992 * script may not behave exactly as intended by the script author.
993 */
994 inline bool isWrn() const { return type == PARSER_WARNING; }
995 };
996
997 /**
998 * Convenience function used for converting an ExprType_t constant to a
999 * string, i.e. for generating error message by the parser.
1000 */
1001 inline String typeStr(const ExprType_t& type) {
1002 switch (type) {
1003 case EMPTY_EXPR: return "empty";
1004 case INT_EXPR: return "integer";
1005 case INT_ARR_EXPR: return "integer array";
1006 case STRING_EXPR: return "string";
1007 case STRING_ARR_EXPR: return "string array";
1008 }
1009 return "invalid";
1010 }
1011
1012 /** @brief Virtual machine representation of a script.
1013 *
1014 * An instance of this abstract base class represents a parsed script,
1015 * translated into a virtual machine tree. You should first check if there
1016 * were any parser errors. If there were any parser errors, you should
1017 * refrain from executing the virtual machine. Otherwise if there were no
1018 * parser errors (i.e. only warnings), then you might access one of the
1019 * script's event handlers by i.e. calling eventHandlerByName() and pass the
1020 * respective event handler to the ScriptVM class (or to one of the ScriptVM
1021 * descendants) for execution.
1022 *
1023 * @see VMExecContext, ScriptVM
1024 */
1025 class VMParserContext {
1026 public:
1027 virtual ~VMParserContext() {}
1028
1029 /**
1030 * Returns all noteworthy issues encountered when the script was parsed.
1031 * These are parser errors and parser warnings.
1032 */
1033 virtual std::vector<ParserIssue> issues() const = 0;
1034
1035 /**
1036 * Same as issues(), but this method only returns parser errors.
1037 */
1038 virtual std::vector<ParserIssue> errors() const = 0;
1039
1040 /**
1041 * Same as issues(), but this method only returns parser warnings.
1042 */
1043 virtual std::vector<ParserIssue> warnings() const = 0;
1044
1045 /**
1046 * Returns all code blocks of the script which were filtered out by the
1047 * preprocessor.
1048 */
1049 virtual std::vector<CodeBlock> preprocessorComments() const = 0;
1050
1051 /**
1052 * Returns the translated virtual machine representation of an event
1053 * handler block (i.e. "on note ... end on" code block) within the
1054 * parsed script. This translated representation of the event handler
1055 * can be executed by the virtual machine.
1056 *
1057 * @param index - index of the event handler within the script
1058 */
1059 virtual VMEventHandler* eventHandler(uint index) = 0;
1060
1061 /**
1062 * Same as eventHandler(), but this method returns the event handler by
1063 * its name. So for a "on note ... end on" code block of the parsed
1064 * script you would pass "note" for argument @a name here.
1065 *
1066 * @param name - name of the event handler (i.e. "init", "note",
1067 * "controller", "release")
1068 */
1069 virtual VMEventHandler* eventHandlerByName(const String& name) = 0;
1070 };
1071
1072 class SourceToken;
1073
1074 /** @brief Recognized token of a script's source code.
1075 *
1076 * Represents one recognized token of a script's source code, for example
1077 * a keyword, variable name, etc. and it provides further informations about
1078 * that particular token, i.e. the precise location (line and column) of the
1079 * token within the original script's source code.
1080 *
1081 * This class is not actually used by the sampler itself. It is rather
1082 * provided for external script editor applications. Primary purpose of
1083 * this class is syntax highlighting for external script editors.
1084 *
1085 * @see ParserIssue for processing compile errors and warnings instead.
1086 */
1087 class VMSourceToken {
1088 public:
1089 VMSourceToken();
1090 VMSourceToken(SourceToken* ct);
1091 VMSourceToken(const VMSourceToken& other);
1092 virtual ~VMSourceToken();
1093
1094 // original text of this token as it is in the script's source code
1095 String text() const;
1096
1097 // position of token in script
1098 int firstLine() const; ///< First line this source token is located at in script source code (indexed with 0 being the very first line). Most source code tokens are not spanning over multiple lines, the only current exception are comments, in the latter case you need to process text() to get the last line and last column for the comment.
1099 int firstColumn() const; ///< First column on the first line this source token is located at in script source code (indexed with 0 being the very first column). To get the length of this token use text().length().
1100
1101 // base types
1102 bool isEOF() const; ///< Returns true in case this source token represents the end of the source code file.
1103 bool isNewLine() const; ///< Returns true in case this source token represents a line feed character (i.e. "\n" on Unix systems).
1104 bool isKeyword() const; ///< Returns true in case this source token represents a language keyword (i.e. "while", "function", "declare", "on", etc.).
1105 bool isVariableName() const; ///< Returns true in case this source token represents a variable name (i.e. "$someIntVariable", "%someArrayVariable", "\@someStringVariable"). @see isIntegerVariable(), isStringVariable(), isArrayVariable() for the precise variable type.
1106 bool isIdentifier() const; ///< Returns true in case this source token represents an identifier, which currently always means a function name.
1107 bool isNumberLiteral() const; ///< Returns true in case this source token represents a number literal (i.e. 123).
1108 bool isStringLiteral() const; ///< Returns true in case this source token represents a string literal (i.e. "Some text").
1109 bool isComment() const; ///< Returns true in case this source token represents a source code comment.
1110 bool isPreprocessor() const; ///< Returns true in case this source token represents a preprocessor statement.
1111 bool isOther() const; ///< Returns true in case this source token represents anything else not covered by the token types mentioned above.
1112
1113 // extended types
1114 bool isIntegerVariable() const; ///< Returns true in case this source token represents an integer variable name (i.e. "$someIntVariable").
1115 bool isStringVariable() const; ///< Returns true in case this source token represents an string variable name (i.e. "\@someStringVariable").
1116 bool isArrayVariable() const; ///< Returns true in case this source token represents an array variable name (i.e. "%someArryVariable").
1117 bool isEventHandlerName() const; ///< Returns true in case this source token represents an event handler name (i.e. "note", "release", "controller").
1118
1119 VMSourceToken& operator=(const VMSourceToken& other);
1120
1121 private:
1122 SourceToken* m_token;
1123 };
1124
1125 } // namespace LinuxSampler
1126
1127 #endif // LS_INSTR_SCRIPT_PARSER_COMMON_H

  ViewVC Help
Powered by ViewVC