/[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 3577 - (show annotations) (download) (as text)
Wed Aug 28 15:23:23 2019 UTC (4 years, 7 months ago) by schoenebeck
File MIME type: text/x-c++hdr
File size: 78649 byte(s)
NKSP: Introducing variable return type for built-in functions.

* Changed method signature VMFunction::returnType() ->
  VMFunction::returnType(VMFnArgs* args) to allow built-in
  functions to proclaim a different result value type depending
  on the arguments to be passed to the function.

* Built-in script function abs() optionally accepts and returns
  real number.

* Built-in script functions min() and max() optionally accept
  real number arguments and return real number as result in that
  case.

* Added real number test cases for the built-in abs(), min() and
  max() functions.

* Bumped version (2.1.1.svn7).

1 /*
2 * Copyright (c) 2014-2019 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 * Native data type used by the script engine both internally, as well as
27 * for all integer data types used by scripts (i.e. for all $foo variables
28 * in NKSP scripts). Note that this is different from the original KSP which
29 * is limited to 32 bit for integer variables in KSP scripts.
30 */
31 typedef int64_t vmint;
32
33 /**
34 * Native data type used internally by the script engine for all unsigned
35 * integer types. This type is currently not exposed to scripts.
36 */
37 typedef uint64_t vmuint;
38
39 /**
40 * Native data type used by the script engine both internally for floating
41 * point data, as well as for all @c real data types used by scripts (i.e.
42 * for all ~foo variables in NKSP scripts).
43 */
44 typedef float vmfloat;
45
46 /**
47 * Identifies the type of a noteworthy issue identified by the script
48 * parser. That's either a parser error or parser warning.
49 */
50 enum ParserIssueType_t {
51 PARSER_ERROR, ///< Script parser encountered an error, the script cannot be executed.
52 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.
53 };
54
55 /** @brief Expression's data type.
56 *
57 * Identifies to which data type an expression within a script evaluates to.
58 * This can for example reflect the data type of script function arguments,
59 * script function return values, but also the resulting data type of some
60 * mathematical formula within a script.
61 */
62 enum ExprType_t {
63 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)
64 INT_EXPR, ///< integer (scalar) expression
65 INT_ARR_EXPR, ///< integer array expression
66 STRING_EXPR, ///< string expression
67 STRING_ARR_EXPR, ///< string array expression
68 REAL_EXPR, ///< floating point (scalar) expression
69 REAL_ARR_EXPR, ///< floating point array expression
70 };
71
72 /** @brief Result flags of a script statement or script function call.
73 *
74 * A set of bit flags which provide informations about the success or
75 * failure of a statement within a script. That's also especially used for
76 * providing informations about success / failure of a call to a built-in
77 * script function. The virtual machine evaluates these flags during runtime
78 * to decide whether it should i.e. stop or suspend execution of a script.
79 *
80 * Since these are bit flags, these constants are bitwise combined.
81 */
82 enum StmtFlags_t {
83 STMT_SUCCESS = 0, ///< Function / statement was executed successfully, no error occurred.
84 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).
85 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
86 STMT_ERROR_OCCURRED = (1<<2), ///< VM stopped execution due to some script runtime error that occurred
87 };
88
89 /** @brief Virtual machine execution status.
90 *
91 * A set of bit flags which reflect the current overall execution status of
92 * the virtual machine concerning a certain script execution instance.
93 *
94 * Since these are bit flags, these constants are bitwise combined.
95 */
96 enum VMExecStatus_t {
97 VM_EXEC_NOT_RUNNING = 0, ///< Script is currently not executed by the VM.
98 VM_EXEC_RUNNING = 1, ///< The VM is currently executing the script.
99 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.
100 VM_EXEC_ERROR = (1<<2), ///< A runtime error occurred while executing the script (i.e. a call to some built-in script function failed).
101 };
102
103 /** @brief Script event handler type.
104 *
105 * Identifies one of the possible event handler callback types defined by
106 * the NKSP script language.
107 *
108 * IMPORTANT: this type is forced to be emitted as int32_t type ATM, because
109 * that's the native size expected by the built-in instrument script
110 * variable bindings (see occurrences of VMInt32RelPtr and DECLARE_VMINT
111 * respectively. A native type mismatch between the two could lead to
112 * undefined behavior! Background: By definition the C/C++ compiler is free
113 * to choose a bit size for individual enums which it might find
114 * appropriate, which is usually decided by the compiler according to the
115 * biggest enum constant value defined (in practice it is usually 32 bit).
116 */
117 enum VMEventHandlerType_t : int32_t {
118 VM_EVENT_HANDLER_INIT, ///< Initilization event handler, that is script's "on init ... end on" code block.
119 VM_EVENT_HANDLER_NOTE, ///< Note event handler, that is script's "on note ... end on" code block.
120 VM_EVENT_HANDLER_RELEASE, ///< Release event handler, that is script's "on release ... end on" code block.
121 VM_EVENT_HANDLER_CONTROLLER, ///< Controller event handler, that is script's "on controller ... end on" code block.
122 };
123
124 /**
125 * All metric unit prefixes (actually just scale factors) supported by this
126 * script engine.
127 */
128 enum MetricPrefix_t {
129 VM_NO_PREFIX = 0, ///< = 1
130 VM_KILO, ///< = 10^3, short 'k'
131 VM_HECTO, ///< = 10^2, short 'h'
132 VM_DECA, ///< = 10, short 'da'
133 VM_DECI, ///< = 10^-1, short 'd'
134 VM_CENTI, ///< = 10^-2, short 'c' (this is also used for tuning "cents")
135 VM_MILLI, ///< = 10^-3, short 'm'
136 VM_MICRO, ///< = 10^-6, short 'u'
137 };
138
139 /**
140 * All measurement unit types supported by this script engine.
141 *
142 * @e Note: there is no standard unit "cents" here (for pitch/tuning), use
143 * @c VM_CENTI for the latter instad. That's because the commonly cited
144 * "cents" unit is actually no measurement unit type but rather a metric
145 * unit prefix.
146 *
147 * @see MetricPrefix_t
148 */
149 enum StdUnit_t {
150 VM_NO_UNIT = 0, ///< No unit used, the number is just an abstract number.
151 VM_SECOND, ///< Measuring time.
152 VM_HERTZ, ///< Measuring frequency.
153 VM_BEL, ///< Measuring relation between two energy levels (in logarithmic scale). Since we are using it for accoustics, we are always referring to A-weighted Bels (i.e. dBA).
154 };
155
156 // just symbol prototyping
157 class VMIntExpr;
158 class VMRealExpr;
159 class VMStringExpr;
160 class VMScalarNumberExpr;
161 class VMIntArrayExpr;
162 class VMRealArrayExpr;
163 class VMStringArrayExpr;
164 class VMParserContext;
165
166 /** @brief Virtual machine measuring unit.
167 *
168 * Abstract base class representing standard measurement units throughout
169 * the script engine. These might be i.e. "dB" (deci Bel) for loudness,
170 * "Hz" (Hertz) for frequencies or "s" for "seconds".
171 *
172 * Originally the script engine only supported abstract integer values for
173 * controlling any synthesis parameter or built-in function argument or
174 * variable. Under certain situations it makes sense though for an
175 * instrument script author to provide values in real, standard measurement
176 * units, for example setting the frequency of some LFO directly to "20Hz".
177 * Hence support for standard units in scripts was added as an extension to
178 * the NKSP script engine.
179 */
180 class VMUnit {
181 public:
182 /**
183 * Returns the metric prefix of this unit. A metric prefix essentially
184 * is just a mathematical scale factor that should be applied to the
185 * number associated with the measurement unit. Usually a unit either
186 * has exactly none or one prefix, but note that there might also be
187 * units with more than one prefix, for example mdB (mili deci bel)
188 * is used sometimes which has two prefixes. This is an exception though
189 * and more than two prefixes is currently not supported by the script
190 * engine.
191 *
192 * Start iterating over the prefixes of this unit by passing @c 0 as
193 * argument to this method. The prefixes are terminated with return
194 * value VM_NO_PREFIX being always the last element.
195 *
196 * @param i - index of prefix
197 * @returns prefix of requested index or VM_NO_PREFIX otherwise
198 * @see unitFactor()
199 */
200 virtual MetricPrefix_t unitPrefix(vmuint i) const = 0;
201
202 /**
203 * Conveniently returns the final mathematical factor that should be
204 * multiplied against the number associated with this unit. This factor
205 * results from the sequence of metric prefixes of this unit.
206 *
207 * @see unitPrefix()
208 */
209 vmfloat unitFactor() const;
210
211 /**
212 * This is the actual fundamental measuring unit base type of this unit,
213 * which might be either Hertz, second or Bel.
214 *
215 * @returns standard unit type identifier or VM_NO_UNIT if no unit used
216 */
217 virtual StdUnit_t unitType() const = 0;
218
219 /**
220 * Returns the actual mathematical factor represented by the passed
221 * @a prefix argument.
222 */
223 static vmfloat unitFactor(MetricPrefix_t prefix);
224
225 /**
226 * Returns the actual mathematical factor represented by the passed
227 * two @a prefix1 and @a prefix2 arguments.
228 */
229 static vmfloat unitFactor(MetricPrefix_t prefix1, MetricPrefix_t prefix2);
230 };
231
232 /** @brief Virtual machine expression
233 *
234 * This is the abstract base class for all expressions of scripts.
235 * Deriving classes must implement the abstract method exprType().
236 *
237 * An expression within a script is translated into one instance of this
238 * class. It allows a high level access for the virtual machine to evaluate
239 * and handle expressions appropriately during execution. Expressions are
240 * for example all kinds of formulas, function calls, statements or a
241 * combination of them. Most of them evaluate to some kind of value, which
242 * might be further processed as part of encompassing expressions to outer
243 * expression results and so forth.
244 */
245 class VMExpr {
246 public:
247 /**
248 * Identifies the data type to which the result of this expression
249 * evaluates to. This abstract method must be implemented by deriving
250 * classes.
251 */
252 virtual ExprType_t exprType() const = 0;
253
254 /**
255 * In case this expression is an integer expression, then this method
256 * returns a casted pointer to that VMIntExpr object. It returns NULL
257 * if this expression is not an integer expression.
258 *
259 * @b Note: type casting performed by this method is strict! That means
260 * if this expression is i.e. actually a string expression like "12",
261 * calling asInt() will @b not cast that numerical string expression to
262 * an integer expression 12 for you, instead this method will simply
263 * return NULL! Same applies if this expression is actually a real
264 * number expression: asInt() would return NULL in that case as well.
265 *
266 * @see exprType(), asReal(), asScalarNumberExpr()
267 */
268 VMIntExpr* asInt() const;
269
270 /**
271 * In case this expression is a real number (floating point) expression,
272 * then this method returns a casted pointer to that VMRealExpr object.
273 * It returns NULL if this expression is not a real number expression.
274 *
275 * @b Note: type casting performed by this method is strict! That means
276 * if this expression is i.e. actually a string expression like "12",
277 * calling asReal() will @b not cast that numerical string expression to
278 * a real number expression 12.0 for you, instead this method will
279 * simply return NULL! Same applies if this expression is actually an
280 * integer expression: asReal() would return NULL in that case as well.
281 *
282 * @see exprType(), asInt(), asScalarNumberExpr()
283 */
284 VMRealExpr* asReal() const;
285
286 /**
287 * In case this expression is a scalar number expression, that is either
288 * an integer (scalar) expression or a real number (floating point
289 * scalar) expression, then this method returns a casted pointer to that
290 * VMScalarNumberExpr base class object. It returns NULL if this
291 * expression is neither an integer (scalar), nor a real number (scalar)
292 * expression.
293 *
294 * Since the methods asInt() and asReal() are very strict, this method
295 * is provided as convenience access in case only very general
296 * information (e.g. which standard measurement unit is being used or
297 * whether final operator being effective to this expression) is
298 * intended to be retrieved of this scalar number expression independent
299 * from whether this expression is actually an integer or a real number
300 * expression.
301 *
302 * @see exprType(), asInt(), asReal()
303 */
304 VMScalarNumberExpr* asScalarNumberExpr() const;
305
306 /**
307 * In case this expression is a string expression, then this method
308 * returns a casted pointer to that VMStringExpr object. It returns NULL
309 * if this expression is not a string expression.
310 *
311 * @b Note: type casting performed by this method is strict! That means
312 * if this expression is i.e. actually an integer expression like 120,
313 * calling asString() will @b not cast that integer expression to a
314 * string expression "120" for you, instead this method will simply
315 * return NULL!
316 *
317 * @see exprType()
318 */
319 VMStringExpr* asString() const;
320
321 /**
322 * In case this expression is an integer array expression, then this
323 * method returns a casted pointer to that VMIntArrayExpr object. It
324 * returns NULL if this expression is not an integer array expression.
325 *
326 * @b Note: type casting performed by this method is strict! That means
327 * if this expression is i.e. an integer scalar expression, a real
328 * number expression or a string expression, calling asIntArray() will
329 * @b not cast those expressions to an integer array expression for you,
330 * instead this method will simply return NULL!
331 *
332 * @b Note: this method is currently, and in contrast to its other
333 * counter parts, declared as virtual method. Some deriving classes are
334 * currently using this to override this default implementation in order
335 * to implement an "evaluate now as integer array" behavior. This has
336 * efficiency reasons, however this also currently makes this part of
337 * the API less clean and should thus be addressed in future with
338 * appropriate changes to the API.
339 *
340 * @see exprType()
341 */
342 virtual VMIntArrayExpr* asIntArray() const;
343
344 /**
345 * In case this expression is a real number (floating point) array
346 * expression, then this method returns a casted pointer to that
347 * VMRealArrayExpr object. It returns NULL if this expression is not a
348 * real number array expression.
349 *
350 * @b Note: type casting performed by this method is strict! That means
351 * if this expression is i.e. a real number scalar expression, an
352 * integer expression or a string expression, calling asRealArray() will
353 * @b not cast those scalar expressions to a real number array
354 * expression for you, instead this method will simply return NULL!
355 *
356 * @b Note: this method is currently, and in contrast to its other
357 * counter parts, declared as virtual method. Some deriving classes are
358 * currently using this to override this default implementation in order
359 * to implement an "evaluate now as real number array" behavior. This
360 * has efficiency reasons, however this also currently makes this part
361 * of the API less clean and should thus be addressed in future with
362 * appropriate changes to the API.
363 *
364 * @see exprType()
365 */
366 virtual VMRealArrayExpr* asRealArray() const;
367
368 /**
369 * Returns true in case this expression can be considered to be a
370 * constant expression. A constant expression will retain the same
371 * value throughout the entire life time of a script and the
372 * expression's constant value may be evaluated already at script
373 * parse time, which may result in performance benefits during script
374 * runtime.
375 *
376 * @b NOTE: A constant expression is per se always also non modifyable.
377 * But a non modifyable expression may not necessarily be a constant
378 * expression!
379 *
380 * @see isModifyable()
381 */
382 virtual bool isConstExpr() const = 0;
383
384 /**
385 * Returns true in case this expression is allowed to be modified.
386 * If this method returns @c false then this expression must be handled
387 * as read-only expression, which means that assigning a new value to it
388 * is either not possible or not allowed.
389 *
390 * @b NOTE: A constant expression is per se always also non modifyable.
391 * But a non modifyable expression may not necessarily be a constant
392 * expression!
393 *
394 * @see isConstExpr()
395 */
396 bool isModifyable() const;
397 };
398
399 /** @brief Virtual machine scalar number expression
400 *
401 * This is the abstract base class for integer (scalar) expressions and
402 * real number (floating point scalar) expressions of scripts.
403 */
404 class VMScalarNumberExpr : virtual public VMExpr, virtual public VMUnit {
405 public:
406 /**
407 * Returns @c true if the value of this expression should be applied
408 * as final value to the respective destination synthesis chain
409 * parameter.
410 *
411 * This property is somewhat special and dedicated for the purpose of
412 * this expression's (integer or real number) value to be applied as
413 * parameter to the synthesis chain of the sampler (i.e. for altering a
414 * filter cutoff frequency). Now historically and by default all values
415 * of scripts are applied relatively to the sampler's synthesis chain,
416 * that is the synthesis parameter value of a script is multiplied
417 * against other sources for the same synthesis parameter (i.e. an LFO
418 * or a dedicated MIDI controller either hard wired in the engine or
419 * defined by the instrument patch). So by default the resulting actual
420 * final synthesis parameter is a combination of all these sources. This
421 * has the advantage that it creates a very living and dynamic overall
422 * sound.
423 *
424 * However sometimes there are requirements by script authors where this
425 * is not what you want. Therefore the NKSP script engine added a
426 * language extension by prefixing a value in scripts with a @c !
427 * character the value will be defined as being the "final" value of the
428 * destination synthesis parameter, so that causes this value to be
429 * applied exclusively, and the values of all other sources are thus
430 * entirely ignored by the sampler's synthesis core as long as this
431 * value is assigned by the script engine as "final" value for the
432 * requested synthesis parameter.
433 */
434 virtual bool isFinal() const = 0;
435 };
436
437 /** @brief Virtual machine integer expression
438 *
439 * This is the abstract base class for all expressions inside scripts which
440 * evaluate to an integer (scalar) value. Deriving classes implement the
441 * abstract method evalInt() to return the actual integer result value of
442 * the expression.
443 */
444 class VMIntExpr : virtual public VMScalarNumberExpr {
445 public:
446 /**
447 * Returns the result of this expression as integer (scalar) value.
448 * This abstract method must be implemented by deriving classes.
449 */
450 virtual vmint evalInt() = 0;
451
452 /**
453 * Returns the result of this expression as integer (scalar) value and
454 * thus behaves similar to the previous method, however this overridden
455 * method automatically takes unit prefixes into account and returns a
456 * value corresponding to the expected given unit @a prefix.
457 *
458 * @param prefix - default measurement unit prefix expected by caller
459 */
460 vmint evalInt(MetricPrefix_t prefix);
461
462 /**
463 * This method behaves like the previous method, just that it takes
464 * a default measurement prefix with two elements (i.e. "milli cents"
465 * for tuning).
466 */
467 vmint evalInt(MetricPrefix_t prefix1, MetricPrefix_t prefix2);
468
469 /**
470 * Returns always INT_EXPR for instances of this class.
471 */
472 ExprType_t exprType() const OVERRIDE { return INT_EXPR; }
473 };
474
475 /** @brief Virtual machine real number (floating point scalar) expression
476 *
477 * This is the abstract base class for all expressions inside scripts which
478 * evaluate to a real number (floating point scalar) value. Deriving classes
479 * implement the abstract method evalReal() to return the actual floating
480 * point result value of the expression.
481 */
482 class VMRealExpr : virtual public VMScalarNumberExpr {
483 public:
484 /**
485 * Returns the result of this expression as real number (floating point
486 * scalar) value. This abstract method must be implemented by deriving
487 * classes.
488 */
489 virtual vmfloat evalReal() = 0;
490
491 /**
492 * Returns the result of this expression as real number (floating point
493 * scalar) value and thus behaves similar to the previous method,
494 * however this overridden method automatically takes unit prefixes into
495 * account and returns a value corresponding to the expected given unit
496 * @a prefix.
497 *
498 * @param prefix - default measurement unit prefix expected by caller
499 */
500 vmfloat evalReal(MetricPrefix_t prefix);
501
502 /**
503 * This method behaves like the previous method, just that it takes
504 * a default measurement prefix with two elements (i.e. "milli cents"
505 * for tuning).
506 */
507 vmfloat evalReal(MetricPrefix_t prefix1, MetricPrefix_t prefix2);
508
509 /**
510 * Returns always REAL_EXPR for instances of this class.
511 */
512 ExprType_t exprType() const OVERRIDE { return REAL_EXPR; }
513 };
514
515 /** @brief Virtual machine string expression
516 *
517 * This is the abstract base class for all expressions inside scripts which
518 * evaluate to a string value. Deriving classes implement the abstract
519 * method evalStr() to return the actual string result value of the
520 * expression.
521 */
522 class VMStringExpr : virtual public VMExpr {
523 public:
524 /**
525 * Returns the result of this expression as string value. This abstract
526 * method must be implemented by deriving classes.
527 */
528 virtual String evalStr() = 0;
529
530 /**
531 * Returns always STRING_EXPR for instances of this class.
532 */
533 ExprType_t exprType() const OVERRIDE { return STRING_EXPR; }
534 };
535
536 /** @brief Virtual Machine Array Value Expression
537 *
538 * This is the abstract base class for all expressions inside scripts which
539 * evaluate to some kind of array value. Deriving classes implement the
540 * abstract method arraySize() to return the amount of elements within the
541 * array.
542 */
543 class VMArrayExpr : virtual public VMExpr {
544 public:
545 /**
546 * Returns amount of elements in this array. This abstract method must
547 * be implemented by deriving classes.
548 */
549 virtual vmint arraySize() const = 0;
550 };
551
552 /** @brief Virtual Machine Integer Array Expression
553 *
554 * This is the abstract base class for all expressions inside scripts which
555 * evaluate to an array of integer values. Deriving classes implement the
556 * abstract methods arraySize(), evalIntElement() and assignIntElement() to
557 * access the individual integer array values.
558 */
559 class VMIntArrayExpr : virtual public VMArrayExpr {
560 public:
561 /**
562 * Returns the (scalar) integer value of the array element given by
563 * element index @a i.
564 *
565 * @param i - array element index (must be between 0 .. arraySize() - 1)
566 */
567 virtual vmint evalIntElement(vmuint i) = 0;
568
569 /**
570 * Changes the current value of an element (given by array element
571 * index @a i) of this integer array.
572 *
573 * @param i - array element index (must be between 0 .. arraySize() - 1)
574 * @param value - new integer scalar value to be assigned to that array element
575 */
576 virtual void assignIntElement(vmuint i, vmint value) = 0;
577
578 /**
579 * Returns always INT_ARR_EXPR for instances of this class.
580 */
581 ExprType_t exprType() const OVERRIDE { return INT_ARR_EXPR; }
582 };
583
584 /** @brief Virtual Machine Real Number Array Expression
585 *
586 * This is the abstract base class for all expressions inside scripts which
587 * evaluate to an array of real numbers (floating point values). Deriving
588 * classes implement the abstract methods arraySize(), evalRealElement() and
589 * assignRealElement() to access the array's individual real numbers.
590 */
591 class VMRealArrayExpr : virtual public VMArrayExpr {
592 public:
593 /**
594 * Returns the (scalar) real mumber (floating point value) of the array
595 * element given by element index @a i.
596 *
597 * @param i - array element index (must be between 0 .. arraySize() - 1)
598 */
599 virtual vmfloat evalRealElement(vmuint i) = 0;
600
601 /**
602 * Changes the current value of an element (given by array element
603 * index @a i) of this real number array.
604 *
605 * @param i - array element index (must be between 0 .. arraySize() - 1)
606 * @param value - new real number value to be assigned to that array element
607 */
608 virtual void assignRealElement(vmuint i, vmfloat value) = 0;
609
610 /**
611 * Returns always REAL_ARR_EXPR for instances of this class.
612 */
613 ExprType_t exprType() const OVERRIDE { return REAL_ARR_EXPR; }
614 };
615
616 /** @brief Arguments (parameters) for being passed to a built-in script function.
617 *
618 * An argument or a set of arguments passed to a script function are
619 * translated by the parser to an instance of this class. This abstract
620 * interface class is used by implementations of built-in functions to
621 * obtain the individual function argument values being passed to them at
622 * runtime.
623 */
624 class VMFnArgs {
625 public:
626 /**
627 * Returns the amount of arguments going to be passed to the script
628 * function.
629 */
630 virtual vmint argsCount() const = 0;
631
632 /**
633 * Returns the respective argument (requested by argument index @a i) of
634 * this set of arguments. This method is called by implementations of
635 * built-in script functions to obtain the value of each function
636 * argument passed to the function at runtime.
637 *
638 * @param i - function argument index (indexed from left to right)
639 */
640 virtual VMExpr* arg(vmint i) = 0;
641 };
642
643 /** @brief Result value returned from a call to a built-in script function.
644 *
645 * Implementations of built-in script functions return an instance of this
646 * object to let the virtual machine obtain the result value of the function
647 * call, which might then be further processed by the virtual machine
648 * according to the script. It also provides informations about the success
649 * or failure of the function call.
650 */
651 class VMFnResult {
652 public:
653 /**
654 * Returns the result value of the function call, represented by a high
655 * level expression object.
656 */
657 virtual VMExpr* resultValue() = 0;
658
659 /**
660 * Provides detailed informations of the success / failure of the
661 * function call. The virtual machine is evaluating the flags returned
662 * here to decide whether it must abort or suspend execution of the
663 * script at this point.
664 */
665 virtual StmtFlags_t resultFlags() { return STMT_SUCCESS; }
666 };
667
668 /** @brief Virtual machine built-in function.
669 *
670 * Abstract base class for built-in script functions, defining the interface
671 * for all built-in script function implementations. All built-in script
672 * functions are deriving from this abstract interface class in order to
673 * provide their functionality to the virtual machine with this unified
674 * interface.
675 *
676 * The methods of this interface class provide two purposes:
677 *
678 * 1. When a script is loaded, the script parser uses the methods of this
679 * interface to check whether the script author was calling the
680 * respective built-in script function in a correct way. For example
681 * the parser checks whether the required amount of parameters were
682 * passed to the function and whether the data types passed match the
683 * data types expected by the function. If not, loading the script will
684 * be aborted with a parser error, describing to the user (i.e. script
685 * author) the precise misusage of the respective function.
686 * 2. After the script was loaded successfully and the script is executed,
687 * the virtual machine calls the exec() method of the respective built-in
688 * function to provide the actual functionality of the built-in function
689 * call.
690 */
691 class VMFunction {
692 public:
693 /**
694 * Script data type of the function's return value. If the function does
695 * not return any value (void), then it returns EMPTY_EXPR here.
696 *
697 * Some functions may have a different return type depending on the
698 * arguments to be passed to this function. That's what the @a args
699 * parameter is for, so that the method implementation can look ahead
700 * of what kind of parameters are going to be passed to the built-in
701 * function later on in order to decide which return value type would
702 * be used and returned by the function accordingly in that case.
703 *
704 * @param args - function arguments going to be passed for executing
705 * this built-in function later on
706 */
707 virtual ExprType_t returnType(VMFnArgs* args) = 0;
708
709 /**
710 * Minimum amount of function arguments this function accepts. If a
711 * script is calling this function with less arguments, the script
712 * parser will throw a parser error.
713 */
714 virtual vmint minRequiredArgs() const = 0;
715
716 /**
717 * Maximum amount of function arguments this functions accepts. If a
718 * script is calling this function with more arguments, the script
719 * parser will throw a parser error.
720 */
721 virtual vmint maxAllowedArgs() const = 0;
722
723 /**
724 * Script data type of the function's @c iArg 'th function argument.
725 * The information provided here is less strong than acceptsArgType().
726 * The parser will compare argument data types provided in scripts by
727 * calling acceptsArgType(). The return value of argType() is used by the
728 * parser instead to show an appropriate parser error which data type
729 * this function usually expects as "default" data type. Reason: a
730 * function may accept multiple data types for a certain function
731 * argument and would automatically cast the passed argument value in
732 * that case to the type it actually needs.
733 *
734 * @param iArg - index of the function argument in question
735 * (must be between 0 .. maxAllowedArgs() - 1)
736 */
737 virtual ExprType_t argType(vmint iArg) const = 0;
738
739 /**
740 * This method is called by the parser to check whether arguments
741 * passed in scripts to this function are accepted by this function. If
742 * a script calls this function with an argument's data type not
743 * accepted by this function, the parser will throw a parser error. On
744 * such errors the data type returned by argType() will be used to
745 * assemble an appropriate error message regarding the precise misusage
746 * of the built-in function.
747 *
748 * @param iArg - index of the function argument in question
749 * (must be between 0 .. maxAllowedArgs() - 1)
750 * @param type - script data type used for this function argument by
751 * currently parsed script
752 * @return true if the given data type would be accepted for the
753 * respective function argument by the function
754 */
755 virtual bool acceptsArgType(vmint iArg, ExprType_t type) const = 0;
756
757 /**
758 * This method is called by the parser to check whether arguments
759 * passed in scripts to this function are accepted by this function. If
760 * a script calls this function with an argument's measuremnt unit type
761 * not accepted by this function, the parser will throw a parser error.
762 *
763 * This default implementation of this method does not accept any
764 * measurement unit. Deriving subclasses would override this method
765 * implementation in case they do accept any measurement unit for its
766 * function arguments.
767 *
768 * @param iArg - index of the function argument in question
769 * (must be between 0 .. maxAllowedArgs() - 1)
770 * @param type - standard measurement unit data type used for this
771 * function argument by currently parsed script
772 * @return true if the given standard measurement unit type would be
773 * accepted for the respective function argument by the function
774 */
775 virtual bool acceptsArgUnitType(vmint iArg, StdUnit_t type) const;
776
777 /**
778 * This method is called by the parser to check whether arguments
779 * passed in scripts to this function are accepted by this function. If
780 * a script calls this function with a metric unit prefix and metric
781 * prefixes are not accepted for that argument by this function, then
782 * the parser will throw a parser error.
783 *
784 * This default implementation of this method does not accept any
785 * metric prefix. Deriving subclasses would override this method
786 * implementation in case they do accept any metric prefix for its
787 * function arguments.
788 *
789 * @param iArg - index of the function argument in question
790 * (must be between 0 .. maxAllowedArgs() - 1)
791 * @param type - standard measurement unit data type used for that
792 * function argument by currently parsed script
793 *
794 * @return true if a metric prefix would be accepted for the respective
795 * function argument by this function
796 *
797 * @see MetricPrefix_t
798 */
799 virtual bool acceptsArgUnitPrefix(vmint iArg, StdUnit_t type) const;
800
801 /**
802 * This method is called by the parser to check whether arguments
803 * passed in scripts to this function are accepted by this function. If
804 * a script calls this function with an argument that is declared to be
805 * a "final" value and this is not accepted by this function, the parser
806 * will throw a parser error.
807 *
808 * This default implementation of this method does not accept a "final"
809 * value. Deriving subclasses would override this method implementation
810 * in case they do accept a "final" value for its function arguments.
811 *
812 * @param iArg - index of the function argument in question
813 * (must be between 0 .. maxAllowedArgs() - 1)
814 * @return true if a "final" value would be accepted for the respective
815 * function argument by the function
816 *
817 * @see VMIntExpr::isFinal()
818 */
819 virtual bool acceptsArgFinal(vmint iArg) const;
820
821 /**
822 * This method is called by the parser to check whether some arguments
823 * (and if yes which ones) passed to this script function will be
824 * modified by this script function. Most script functions simply use
825 * their arguments as inputs, that is they only read the argument's
826 * values. However some script function may also use passed
827 * argument(s) as output variables. In this case the function
828 * implementation must return @c true for the respective argument
829 * index here.
830 *
831 * @param iArg - index of the function argument in question
832 * (must be between 0 .. maxAllowedArgs() - 1)
833 */
834 virtual bool modifiesArg(vmint iArg) const = 0;
835
836 /**
837 * Implements the actual function execution. This exec() method is
838 * called by the VM whenever this function implementation shall be
839 * executed at script runtime. This method blocks until the function
840 * call completed.
841 *
842 * @param args - function arguments for executing this built-in function
843 * @returns function's return value (if any) and general status
844 * informations (i.e. whether the function call caused a
845 * runtime error)
846 */
847 virtual VMFnResult* exec(VMFnArgs* args) = 0;
848
849 /**
850 * Convenience method for function implementations to show warning
851 * messages during actual execution of the built-in function.
852 *
853 * @param txt - runtime warning text to be shown to user
854 */
855 void wrnMsg(const String& txt);
856
857 /**
858 * Convenience method for function implementations to show error
859 * messages during actual execution of the built-in function.
860 *
861 * @param txt - runtime error text to be shown to user
862 */
863 void errMsg(const String& txt);
864 };
865
866 /** @brief Virtual machine relative pointer.
867 *
868 * POD base of VMInt64RelPtr, VMInt32RelPtr and VMInt8RelPtr structures. Not
869 * intended to be used directly. Use VMInt64RelPtr, VMInt32RelPtr,
870 * VMInt8RelPtr instead.
871 *
872 * @see VMInt64RelPtr, VMInt32RelPtr, VMInt8RelPtr
873 */
874 struct VMRelPtr {
875 void** base; ///< Base pointer.
876 vmint offset; ///< Offset (in bytes) relative to base pointer.
877 bool readonly; ///< Whether the pointed data may be modified or just be read.
878 };
879
880 /** @brief Pointer to built-in VM integer variable (interface class).
881 *
882 * This class acts as an abstract interface to all built-in integer script
883 * variables, independent of their actual native size (i.e. some built-in
884 * script variables are internally using a native int size of 64 bit or 32
885 * bit or 8 bit). The virtual machine is using this interface class instead
886 * of its implementing descendants (VMInt64RelPtr, VMInt32RelPtr,
887 * VMInt8RelPtr) in order for the virtual machine for not being required to
888 * handle each of them differently.
889 */
890 struct VMIntPtr {
891 virtual vmint evalInt() = 0;
892 virtual void assign(vmint i) = 0;
893 virtual bool isAssignable() const = 0;
894 };
895
896 /** @brief Pointer to built-in VM integer variable (of C/C++ type int64_t).
897 *
898 * Used for defining built-in 64 bit integer script variables.
899 *
900 * @b CAUTION: You may only use this class for pointing to C/C++ variables
901 * of type "int64_t" (thus being exactly 64 bit in size). If the C/C++ int
902 * variable you want to reference is only 32 bit in size then you @b must
903 * use VMInt32RelPtr instead! Respectively for a referenced native variable
904 * with only 8 bit in size you @b must use VMInt8RelPtr instead!
905 *
906 * For efficiency reasons the actual native C/C++ int variable is referenced
907 * by two components here. The actual native int C/C++ variable in memory
908 * is dereferenced at VM run-time by taking the @c base pointer dereference
909 * and adding @c offset bytes. This has the advantage that for a large
910 * number of built-in int variables, only one (or few) base pointer need
911 * to be re-assigned before running a script, instead of updating each
912 * built-in variable each time before a script is executed.
913 *
914 * Refer to DECLARE_VMINT() for example code.
915 *
916 * @see VMInt32RelPtr, VMInt8RelPtr, DECLARE_VMINT()
917 */
918 struct VMInt64RelPtr : VMRelPtr, VMIntPtr {
919 VMInt64RelPtr() {
920 base = NULL;
921 offset = 0;
922 readonly = false;
923 }
924 VMInt64RelPtr(const VMRelPtr& data) {
925 base = data.base;
926 offset = data.offset;
927 readonly = false;
928 }
929 vmint evalInt() OVERRIDE {
930 return (vmint)*(int64_t*)&(*(uint8_t**)base)[offset];
931 }
932 void assign(vmint i) OVERRIDE {
933 *(int64_t*)&(*(uint8_t**)base)[offset] = (int64_t)i;
934 }
935 bool isAssignable() const OVERRIDE { return !readonly; }
936 };
937
938 /** @brief Pointer to built-in VM integer variable (of C/C++ type int32_t).
939 *
940 * Used for defining built-in 32 bit integer script variables.
941 *
942 * @b CAUTION: You may only use this class for pointing to C/C++ variables
943 * of type "int32_t" (thus being exactly 32 bit in size). If the C/C++ int
944 * variable you want to reference is 64 bit in size then you @b must use
945 * VMInt64RelPtr instead! Respectively for a referenced native variable with
946 * only 8 bit in size you @b must use VMInt8RelPtr instead!
947 *
948 * For efficiency reasons the actual native C/C++ int variable is referenced
949 * by two components here. The actual native int C/C++ variable in memory
950 * is dereferenced at VM run-time by taking the @c base pointer dereference
951 * and adding @c offset bytes. This has the advantage that for a large
952 * number of built-in int variables, only one (or few) base pointer need
953 * to be re-assigned before running a script, instead of updating each
954 * built-in variable each time before a script is executed.
955 *
956 * Refer to DECLARE_VMINT() for example code.
957 *
958 * @see VMInt64RelPtr, VMInt8RelPtr, DECLARE_VMINT()
959 */
960 struct VMInt32RelPtr : VMRelPtr, VMIntPtr {
961 VMInt32RelPtr() {
962 base = NULL;
963 offset = 0;
964 readonly = false;
965 }
966 VMInt32RelPtr(const VMRelPtr& data) {
967 base = data.base;
968 offset = data.offset;
969 readonly = false;
970 }
971 vmint evalInt() OVERRIDE {
972 return (vmint)*(int32_t*)&(*(uint8_t**)base)[offset];
973 }
974 void assign(vmint i) OVERRIDE {
975 *(int32_t*)&(*(uint8_t**)base)[offset] = (int32_t)i;
976 }
977 bool isAssignable() const OVERRIDE { return !readonly; }
978 };
979
980 /** @brief Pointer to built-in VM integer variable (of C/C++ type int8_t).
981 *
982 * Used for defining built-in 8 bit integer script variables.
983 *
984 * @b CAUTION: You may only use this class for pointing to C/C++ variables
985 * of type "int8_t" (8 bit integer). If the C/C++ int variable you want to
986 * reference is not exactly 8 bit in size then you @b must respectively use
987 * either VMInt32RelPtr for native 32 bit variables or VMInt64RelPtrl for
988 * native 64 bit variables instead!
989 *
990 * For efficiency reasons the actual native C/C++ int variable is referenced
991 * by two components here. The actual native int C/C++ variable in memory
992 * is dereferenced at VM run-time by taking the @c base pointer dereference
993 * and adding @c offset bytes. This has the advantage that for a large
994 * number of built-in int variables, only one (or few) base pointer need
995 * to be re-assigned before running a script, instead of updating each
996 * built-in variable each time before a script is executed.
997 *
998 * Refer to DECLARE_VMINT() for example code.
999 *
1000 * @see VMIntRel32Ptr, VMIntRel64Ptr, DECLARE_VMINT()
1001 */
1002 struct VMInt8RelPtr : VMRelPtr, VMIntPtr {
1003 VMInt8RelPtr() {
1004 base = NULL;
1005 offset = 0;
1006 readonly = false;
1007 }
1008 VMInt8RelPtr(const VMRelPtr& data) {
1009 base = data.base;
1010 offset = data.offset;
1011 readonly = false;
1012 }
1013 vmint evalInt() OVERRIDE {
1014 return (vmint)*(uint8_t*)&(*(uint8_t**)base)[offset];
1015 }
1016 void assign(vmint i) OVERRIDE {
1017 *(uint8_t*)&(*(uint8_t**)base)[offset] = (uint8_t)i;
1018 }
1019 bool isAssignable() const OVERRIDE { return !readonly; }
1020 };
1021
1022 /** @brief Pointer to built-in VM integer variable (of C/C++ type vmint).
1023 *
1024 * Use this typedef if the native variable to be pointed to is using the
1025 * typedef vmint. If the native C/C++ variable to be pointed to is using
1026 * another C/C++ type then better use one of VMInt64RelPtr or VMInt32RelPtr
1027 * instead.
1028 */
1029 typedef VMInt64RelPtr VMIntRelPtr;
1030
1031 #if HAVE_CXX_EMBEDDED_PRAGMA_DIAGNOSTICS
1032 # define COMPILER_DISABLE_OFFSETOF_WARNING \
1033 _Pragma("GCC diagnostic push") \
1034 _Pragma("GCC diagnostic ignored \"-Winvalid-offsetof\"")
1035 # define COMPILER_RESTORE_OFFSETOF_WARNING \
1036 _Pragma("GCC diagnostic pop")
1037 #else
1038 # define COMPILER_DISABLE_OFFSETOF_WARNING
1039 # define COMPILER_RESTORE_OFFSETOF_WARNING
1040 #endif
1041
1042 /**
1043 * Convenience macro for initializing VMInt64RelPtr, VMInt32RelPtr and
1044 * VMInt8RelPtr structures. Usage example:
1045 * @code
1046 * struct Foo {
1047 * uint8_t a; // native representation of a built-in integer script variable
1048 * int64_t b; // native representation of another built-in integer script variable
1049 * int64_t c; // native representation of another built-in integer script variable
1050 * uint8_t d; // native representation of another built-in integer script variable
1051 * };
1052 *
1053 * // initializing the built-in script variables to some values
1054 * Foo foo1 = (Foo) { 1, 2000, 3000, 4 };
1055 * Foo foo2 = (Foo) { 5, 6000, 7000, 8 };
1056 *
1057 * Foo* pFoo;
1058 *
1059 * VMInt8RelPtr varA = DECLARE_VMINT(pFoo, class Foo, a);
1060 * VMInt64RelPtr varB = DECLARE_VMINT(pFoo, class Foo, b);
1061 * VMInt64RelPtr varC = DECLARE_VMINT(pFoo, class Foo, c);
1062 * VMInt8RelPtr varD = DECLARE_VMINT(pFoo, class Foo, d);
1063 *
1064 * pFoo = &foo1;
1065 * printf("%d\n", varA->evalInt()); // will print 1
1066 * printf("%d\n", varB->evalInt()); // will print 2000
1067 * printf("%d\n", varC->evalInt()); // will print 3000
1068 * printf("%d\n", varD->evalInt()); // will print 4
1069 *
1070 * // same printf() code, just with pFoo pointer being changed ...
1071 *
1072 * pFoo = &foo2;
1073 * printf("%d\n", varA->evalInt()); // will print 5
1074 * printf("%d\n", varB->evalInt()); // will print 6000
1075 * printf("%d\n", varC->evalInt()); // will print 7000
1076 * printf("%d\n", varD->evalInt()); // will print 8
1077 * @endcode
1078 * As you can see above, by simply changing one single pointer, you can
1079 * remap a huge bunch of built-in integer script variables to completely
1080 * different native values/native variables. Which especially reduces code
1081 * complexity inside the sampler engines which provide the actual script
1082 * functionalities.
1083 */
1084 #define DECLARE_VMINT(basePtr, T_struct, T_member) ( \
1085 /* Disable offsetof warning, trust us, we are cautios. */ \
1086 COMPILER_DISABLE_OFFSETOF_WARNING \
1087 (VMRelPtr) { \
1088 (void**) &basePtr, \
1089 offsetof(T_struct, T_member), \
1090 false \
1091 } \
1092 COMPILER_RESTORE_OFFSETOF_WARNING \
1093 ) \
1094
1095 /**
1096 * Same as DECLARE_VMINT(), but this one defines the VMInt64RelPtr,
1097 * VMInt32RelPtr and VMInt8RelPtr structures to be of read-only type.
1098 * That means the script parser will abort any script at parser time if the
1099 * script is trying to modify such a read-only built-in variable.
1100 *
1101 * @b NOTE: this is only intended for built-in read-only variables that
1102 * may change during runtime! If your built-in variable's data is rather
1103 * already available at parser time and won't change during runtime, then
1104 * you should rather register a built-in constant in your VM class instead!
1105 *
1106 * @see ScriptVM::builtInConstIntVariables()
1107 */
1108 #define DECLARE_VMINT_READONLY(basePtr, T_struct, T_member) ( \
1109 /* Disable offsetof warning, trust us, we are cautios. */ \
1110 COMPILER_DISABLE_OFFSETOF_WARNING \
1111 (VMRelPtr) { \
1112 (void**) &basePtr, \
1113 offsetof(T_struct, T_member), \
1114 true \
1115 } \
1116 COMPILER_RESTORE_OFFSETOF_WARNING \
1117 ) \
1118
1119 /** @brief Built-in VM 8 bit integer array variable.
1120 *
1121 * Used for defining built-in integer array script variables (8 bit per
1122 * array element). Currently there is no support for any other kind of
1123 * built-in array type. So all built-in integer arrays accessed by scripts
1124 * use 8 bit data types.
1125 */
1126 struct VMInt8Array {
1127 int8_t* data;
1128 vmint size;
1129 bool readonly; ///< Whether the array data may be modified or just be read.
1130
1131 VMInt8Array() : data(NULL), size(0), readonly(false) {}
1132 };
1133
1134 /** @brief Virtual machine script variable.
1135 *
1136 * Common interface for all variables accessed in scripts, independent of
1137 * their precise data type.
1138 */
1139 class VMVariable : virtual public VMExpr {
1140 public:
1141 /**
1142 * Whether a script may modify the content of this variable by
1143 * assigning a new value to it.
1144 *
1145 * @see isConstExpr(), assign()
1146 */
1147 virtual bool isAssignable() const = 0;
1148
1149 /**
1150 * In case this variable is assignable, this method will be called to
1151 * perform the value assignment to this variable with @a expr
1152 * reflecting the new value to be assigned.
1153 *
1154 * @param expr - new value to be assigned to this variable
1155 */
1156 virtual void assignExpr(VMExpr* expr) = 0;
1157 };
1158
1159 /** @brief Dynamically executed variable (abstract base class).
1160 *
1161 * Interface for the implementation of a dynamically generated content of
1162 * a built-in script variable. Most built-in variables are simply pointers
1163 * to some native location in memory. So when a script reads them, the
1164 * memory location is simply read to get the value of the variable. A
1165 * dynamic variable however is not simply a memory location. For each access
1166 * to a dynamic variable some native code is executed to actually generate
1167 * and provide the content (value) of this type of variable.
1168 */
1169 class VMDynVar : public VMVariable {
1170 public:
1171 /**
1172 * Returns true in case this dynamic variable can be considered to be a
1173 * constant expression. A constant expression will retain the same value
1174 * throughout the entire life time of a script and the expression's
1175 * constant value may be evaluated already at script parse time, which
1176 * may result in performance benefits during script runtime.
1177 *
1178 * However due to the "dynamic" behavior of dynamic variables, almost
1179 * all dynamic variables are probably not constant expressions. That's
1180 * why this method returns @c false by default. If you are really sure
1181 * that your dynamic variable implementation can be considered a
1182 * constant expression then you may override this method and return
1183 * @c true instead. Note that when you return @c true here, your
1184 * dynamic variable will really just be executed once; and exectly
1185 * already when the script is loaded!
1186 *
1187 * As an example you may implement a "constant" built-in dynamic
1188 * variable that checks for a certain operating system feature and
1189 * returns the result of that OS feature check as content (value) of
1190 * this dynamic variable. Since the respective OS feature might become
1191 * available/unavailable after OS updates, software migration, etc. the
1192 * OS feature check should at least be performed once each time the
1193 * application is launched. And since the OS feature check might take a
1194 * certain amount of execution time, it might make sense to only
1195 * perform the check if the respective variable name is actually
1196 * referenced at all in the script to be loaded. Note that the dynamic
1197 * variable will still be evaluated again though if the script is
1198 * loaded again. So it is up to you to probably cache the result in the
1199 * implementation of your dynamic variable.
1200 *
1201 * On doubt, please rather consider to use a constant built-in script
1202 * variable instead of implementing a "constant" dynamic variable, due
1203 * to the runtime overhead a dynamic variable may cause.
1204 *
1205 * @see isAssignable()
1206 */
1207 bool isConstExpr() const OVERRIDE { return false; }
1208
1209 /**
1210 * In case this dynamic variable is assignable, the new value (content)
1211 * to be assigned to this dynamic variable.
1212 *
1213 * By default this method does nothing. Override and implement this
1214 * method in your subclass in case your dynamic variable allows to
1215 * assign a new value by script.
1216 *
1217 * @param expr - new value to be assigned to this variable
1218 */
1219 void assignExpr(VMExpr* expr) OVERRIDE {}
1220
1221 virtual ~VMDynVar() {}
1222 };
1223
1224 /** @brief Dynamically executed variable (of integer data type).
1225 *
1226 * This is the base class for all built-in integer script variables whose
1227 * variable content needs to be provided dynamically by executable native
1228 * code on each script variable access.
1229 */
1230 class VMDynIntVar : virtual public VMDynVar, virtual public VMIntExpr {
1231 public:
1232 MetricPrefix_t unitPrefix(vmuint i) const OVERRIDE { return VM_NO_PREFIX; }
1233 StdUnit_t unitType() const OVERRIDE { return VM_NO_UNIT; }
1234 bool isFinal() const OVERRIDE { return false; }
1235 };
1236
1237 /** @brief Dynamically executed variable (of string data type).
1238 *
1239 * This is the base class for all built-in string script variables whose
1240 * variable content needs to be provided dynamically by executable native
1241 * code on each script variable access.
1242 */
1243 class VMDynStringVar : virtual public VMDynVar, virtual public VMStringExpr {
1244 public:
1245 };
1246
1247 /** @brief Dynamically executed variable (of integer array data type).
1248 *
1249 * This is the base class for all built-in integer array script variables
1250 * whose variable content needs to be provided dynamically by executable
1251 * native code on each script variable access.
1252 */
1253 class VMDynIntArrayVar : virtual public VMDynVar, virtual public VMIntArrayExpr {
1254 public:
1255 };
1256
1257 /** @brief Provider for built-in script functions and variables.
1258 *
1259 * Abstract base class defining the high-level interface for all classes
1260 * which add and implement built-in script functions and built-in script
1261 * variables.
1262 */
1263 class VMFunctionProvider {
1264 public:
1265 /**
1266 * Returns pointer to the built-in function with the given function
1267 * @a name, or NULL if there is no built-in function with that function
1268 * name.
1269 *
1270 * @param name - function name (i.e. "wait" or "message" or "exit", etc.)
1271 */
1272 virtual VMFunction* functionByName(const String& name) = 0;
1273
1274 /**
1275 * Returns @c true if the passed built-in function is disabled and
1276 * should be ignored by the parser. This method is called by the
1277 * parser on preprocessor level for each built-in function call within
1278 * a script. Accordingly if this method returns @c true, then the
1279 * respective function call is completely filtered out on preprocessor
1280 * level, so that built-in function won't make into the result virtual
1281 * machine representation, nor would expressions of arguments passed to
1282 * that built-in function call be evaluated, nor would any check
1283 * regarding correct usage of the built-in function be performed.
1284 * In other words: a disabled function call ends up as a comment block.
1285 *
1286 * @param fn - built-in function to be checked
1287 * @param ctx - parser context at the position where the built-in
1288 * function call is located within the script
1289 */
1290 virtual bool isFunctionDisabled(VMFunction* fn, VMParserContext* ctx) = 0;
1291
1292 /**
1293 * Returns a variable name indexed map of all built-in script variables
1294 * which point to native "int" scalar (usually 32 bit) variables.
1295 */
1296 virtual std::map<String,VMIntPtr*> builtInIntVariables() = 0;
1297
1298 /**
1299 * Returns a variable name indexed map of all built-in script integer
1300 * array variables with array element type "int8_t" (8 bit).
1301 */
1302 virtual std::map<String,VMInt8Array*> builtInIntArrayVariables() = 0;
1303
1304 /**
1305 * Returns a variable name indexed map of all built-in constant script
1306 * variables, which never change their value at runtime.
1307 */
1308 virtual std::map<String,vmint> builtInConstIntVariables() = 0;
1309
1310 /**
1311 * Returns a variable name indexed map of all built-in dynamic variables,
1312 * which are not simply data stores, rather each one of them executes
1313 * natively to provide or alter the respective script variable data.
1314 */
1315 virtual std::map<String,VMDynVar*> builtInDynamicVariables() = 0;
1316 };
1317
1318 /** @brief Execution state of a virtual machine.
1319 *
1320 * An instance of this abstract base class represents exactly one execution
1321 * state of a virtual machine. This encompasses most notably the VM
1322 * execution stack, and VM polyphonic variables. It does not contain global
1323 * variables. Global variables are contained in the VMParserContext object.
1324 * You might see a VMExecContext object as one virtual thread of the virtual
1325 * machine.
1326 *
1327 * In contrast to a VMParserContext, a VMExecContext is not tied to a
1328 * ScriptVM instance. Thus you can use a VMExecContext with different
1329 * ScriptVM instances, however not concurrently at the same time.
1330 *
1331 * @see VMParserContext
1332 */
1333 class VMExecContext {
1334 public:
1335 virtual ~VMExecContext() {}
1336
1337 /**
1338 * In case the script was suspended for some reason, this method returns
1339 * the amount of microseconds before the script shall continue its
1340 * execution. Note that the virtual machine itself does never put its
1341 * own execution thread(s) to sleep. So the respective class (i.e. sampler
1342 * engine) which is using the virtual machine classes here, must take
1343 * care by itself about taking time stamps, determining the script
1344 * handlers that shall be put aside for the requested amount of
1345 * microseconds, indicated by this method by comparing the time stamps in
1346 * real-time, and to continue passing the respective handler to
1347 * ScriptVM::exec() as soon as its suspension exceeded, etc. Or in other
1348 * words: all classes in this directory never have an idea what time it
1349 * is.
1350 *
1351 * You should check the return value of ScriptVM::exec() to determine
1352 * whether the script was actually suspended before calling this method
1353 * here.
1354 *
1355 * @see ScriptVM::exec()
1356 */
1357 virtual vmint suspensionTimeMicroseconds() const = 0;
1358
1359 /**
1360 * Causes all polyphonic variables to be reset to zero values. A
1361 * polyphonic variable is expected to be zero when entering a new event
1362 * handler instance. As an exception the values of polyphonic variables
1363 * shall only be preserved from an note event handler instance to its
1364 * correspending specific release handler instance. So in the latter
1365 * case the script author may pass custom data from the note handler to
1366 * the release handler, but only for the same specific note!
1367 */
1368 virtual void resetPolyphonicData() = 0;
1369
1370 /**
1371 * Returns amount of virtual machine instructions which have been
1372 * performed the last time when this execution context was executing a
1373 * script. So in case you need the overall amount of instructions
1374 * instead, then you need to add them by yourself after each
1375 * ScriptVM::exec() call.
1376 */
1377 virtual size_t instructionsPerformed() const = 0;
1378
1379 /**
1380 * Sends a signal to this script execution instance to abort its script
1381 * execution as soon as possible. This method is called i.e. when one
1382 * script execution instance intends to stop another script execution
1383 * instance.
1384 */
1385 virtual void signalAbort() = 0;
1386
1387 /**
1388 * Copies the current entire execution state from this object to the
1389 * given object. So this can be used to "fork" a new script thread which
1390 * then may run independently with its own polyphonic data for instance.
1391 */
1392 virtual void forkTo(VMExecContext* ectx) const = 0;
1393
1394 /**
1395 * In case the script called the built-in exit() function and passed a
1396 * value as argument to the exit() function, then this method returns
1397 * the value that had been passed as argument to the exit() function.
1398 * Otherwise if the exit() function has not been called by the script
1399 * or no argument had been passed to the exit() function, then this
1400 * method returns NULL instead.
1401 *
1402 * Currently this is only used for automated test cases against the
1403 * script engine, which return some kind of value in the individual
1404 * test case scripts to check their behaviour in automated way. There
1405 * is no purpose for this mechanism in production use. Accordingly this
1406 * exit result value is @b always completely ignored by the sampler
1407 * engines.
1408 *
1409 * Officially the built-in exit() function does not expect any arguments
1410 * to be passed to its function call, and by default this feature is
1411 * hence disabled and will yield in a parser error unless
1412 * ScriptVM::setExitResultEnabled() was explicitly set.
1413 *
1414 * @see ScriptVM::setExitResultEnabled()
1415 */
1416 virtual VMExpr* exitResult() = 0;
1417 };
1418
1419 /** @brief Script callback for a certain event.
1420 *
1421 * Represents a script callback for a certain event, i.e.
1422 * "on note ... end on" code block.
1423 */
1424 class VMEventHandler {
1425 public:
1426 /**
1427 * Type of this event handler, which identifies its purpose. For example
1428 * for a "on note ... end on" script callback block,
1429 * @c VM_EVENT_HANDLER_NOTE would be returned here.
1430 */
1431 virtual VMEventHandlerType_t eventHandlerType() const = 0;
1432
1433 /**
1434 * Name of the event handler which identifies its purpose. For example
1435 * for a "on note ... end on" script callback block, the name "note"
1436 * would be returned here.
1437 */
1438 virtual String eventHandlerName() const = 0;
1439
1440 /**
1441 * Whether or not the event handler makes any use of so called
1442 * "polyphonic" variables.
1443 */
1444 virtual bool isPolyphonic() const = 0;
1445 };
1446
1447 /**
1448 * Reflects the precise position and span of a specific code block within
1449 * a script. This is currently only used for the locations of commented
1450 * code blocks due to preprocessor statements, and for parser errors and
1451 * parser warnings.
1452 *
1453 * @see ParserIssue for code locations of parser errors and parser warnings
1454 *
1455 * @see VMParserContext::preprocessorComments() for locations of code which
1456 * have been filtered out by preprocessor statements
1457 */
1458 struct CodeBlock {
1459 int firstLine; ///< The first line number of this code block within the script (indexed with 1 being the very first line).
1460 int lastLine; ///< The last line number of this code block within the script.
1461 int firstColumn; ///< The first column of this code block within the script (indexed with 1 being the very first column).
1462 int lastColumn; ///< The last column of this code block within the script.
1463 };
1464
1465 /**
1466 * Encapsulates a noteworty parser issue. This encompasses the type of the
1467 * issue (either a parser error or parser warning), a human readable
1468 * explanation text of the error or warning and the location of the
1469 * encountered parser issue within the script.
1470 *
1471 * @see VMSourceToken for processing syntax highlighting instead.
1472 */
1473 struct ParserIssue : CodeBlock {
1474 String txt; ///< Human readable explanation text of the parser issue.
1475 ParserIssueType_t type; ///< Whether this issue is either a parser error or just a parser warning.
1476
1477 /**
1478 * Print this issue out to the console (stdio).
1479 */
1480 inline void dump() {
1481 switch (type) {
1482 case PARSER_ERROR:
1483 printf("[ERROR] line %d, column %d: %s\n", firstLine, firstColumn, txt.c_str());
1484 break;
1485 case PARSER_WARNING:
1486 printf("[Warning] line %d, column %d: %s\n", firstLine, firstColumn, txt.c_str());
1487 break;
1488 }
1489 }
1490
1491 /**
1492 * Returns true if this issue is a parser error. In this case the parsed
1493 * script may not be executed!
1494 */
1495 inline bool isErr() const { return type == PARSER_ERROR; }
1496
1497 /**
1498 * Returns true if this issue is just a parser warning. A parsed script
1499 * that only raises warnings may be executed if desired, however the
1500 * script may not behave exactly as intended by the script author.
1501 */
1502 inline bool isWrn() const { return type == PARSER_WARNING; }
1503 };
1504
1505 /**
1506 * Convenience function used for converting an ExprType_t constant to a
1507 * string, i.e. for generating error message by the parser.
1508 */
1509 inline String typeStr(const ExprType_t& type) {
1510 switch (type) {
1511 case EMPTY_EXPR: return "empty";
1512 case INT_EXPR: return "integer";
1513 case INT_ARR_EXPR: return "integer array";
1514 case REAL_EXPR: return "real number";
1515 case REAL_ARR_EXPR: return "real number array";
1516 case STRING_EXPR: return "string";
1517 case STRING_ARR_EXPR: return "string array";
1518 }
1519 return "invalid";
1520 }
1521
1522 /**
1523 * Convenience function used for retrieving the data type of a script
1524 * variable name being passed to this function.
1525 *
1526 * @param name - some script variable name (e.g. "$foo")
1527 * @return variable's data type (e.g. INT_EXPR for example above)
1528 */
1529 inline ExprType_t exprTypeOfVarName(const String& name) {
1530 if (name.empty()) return (ExprType_t) -1;
1531 const char prefix = name[0];
1532 switch (prefix) {
1533 case '$': return INT_EXPR;
1534 case '%': return INT_ARR_EXPR;
1535 case '~': return REAL_EXPR;
1536 case '?': return REAL_ARR_EXPR;
1537 case '@': return STRING_EXPR;
1538 case '!': return STRING_ARR_EXPR;
1539 }
1540 return (ExprType_t) -1;
1541 }
1542
1543 /**
1544 * Returns @c true in case the passed data type is some array data type.
1545 */
1546 inline bool isArray(const ExprType_t& type) {
1547 return type == INT_ARR_EXPR || type == REAL_ARR_EXPR ||
1548 type == STRING_ARR_EXPR;
1549 }
1550
1551 /**
1552 * Returns @c true in case the passed data type is some scalar number type
1553 * (i.e. not an array and not a string).
1554 */
1555 inline bool isScalarNumber(const ExprType_t& type) {
1556 return type == INT_EXPR || type == REAL_EXPR;
1557 }
1558
1559 /**
1560 * Convenience function used for converting an StdUnit_t constant to a
1561 * string, i.e. for generating error message by the parser.
1562 */
1563 inline String unitTypeStr(const StdUnit_t& type) {
1564 switch (type) {
1565 case VM_NO_UNIT: return "none";
1566 case VM_SECOND: return "seconds";
1567 case VM_HERTZ: return "Hz";
1568 case VM_BEL: return "Bel";
1569 }
1570 return "invalid";
1571 }
1572
1573 /** @brief Virtual machine representation of a script.
1574 *
1575 * An instance of this abstract base class represents a parsed script,
1576 * translated into a virtual machine tree. You should first check if there
1577 * were any parser errors. If there were any parser errors, you should
1578 * refrain from executing the virtual machine. Otherwise if there were no
1579 * parser errors (i.e. only warnings), then you might access one of the
1580 * script's event handlers by i.e. calling eventHandlerByName() and pass the
1581 * respective event handler to the ScriptVM class (or to one of the ScriptVM
1582 * descendants) for execution.
1583 *
1584 * @see VMExecContext, ScriptVM
1585 */
1586 class VMParserContext {
1587 public:
1588 virtual ~VMParserContext() {}
1589
1590 /**
1591 * Returns all noteworthy issues encountered when the script was parsed.
1592 * These are parser errors and parser warnings.
1593 */
1594 virtual std::vector<ParserIssue> issues() const = 0;
1595
1596 /**
1597 * Same as issues(), but this method only returns parser errors.
1598 */
1599 virtual std::vector<ParserIssue> errors() const = 0;
1600
1601 /**
1602 * Same as issues(), but this method only returns parser warnings.
1603 */
1604 virtual std::vector<ParserIssue> warnings() const = 0;
1605
1606 /**
1607 * Returns all code blocks of the script which were filtered out by the
1608 * preprocessor.
1609 */
1610 virtual std::vector<CodeBlock> preprocessorComments() const = 0;
1611
1612 /**
1613 * Returns the translated virtual machine representation of an event
1614 * handler block (i.e. "on note ... end on" code block) within the
1615 * parsed script. This translated representation of the event handler
1616 * can be executed by the virtual machine.
1617 *
1618 * @param index - index of the event handler within the script
1619 */
1620 virtual VMEventHandler* eventHandler(uint index) = 0;
1621
1622 /**
1623 * Same as eventHandler(), but this method returns the event handler by
1624 * its name. So for a "on note ... end on" code block of the parsed
1625 * script you would pass "note" for argument @a name here.
1626 *
1627 * @param name - name of the event handler (i.e. "init", "note",
1628 * "controller", "release")
1629 */
1630 virtual VMEventHandler* eventHandlerByName(const String& name) = 0;
1631 };
1632
1633 class SourceToken;
1634
1635 /** @brief Recognized token of a script's source code.
1636 *
1637 * Represents one recognized token of a script's source code, for example
1638 * a keyword, variable name, etc. and it provides further informations about
1639 * that particular token, i.e. the precise location (line and column) of the
1640 * token within the original script's source code.
1641 *
1642 * This class is not actually used by the sampler itself. It is rather
1643 * provided for external script editor applications. Primary purpose of
1644 * this class is syntax highlighting for external script editors.
1645 *
1646 * @see ParserIssue for processing compile errors and warnings instead.
1647 */
1648 class VMSourceToken {
1649 public:
1650 VMSourceToken();
1651 VMSourceToken(SourceToken* ct);
1652 VMSourceToken(const VMSourceToken& other);
1653 virtual ~VMSourceToken();
1654
1655 // original text of this token as it is in the script's source code
1656 String text() const;
1657
1658 // position of token in script
1659 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.
1660 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().
1661
1662 // base types
1663 bool isEOF() const; ///< Returns true in case this source token represents the end of the source code file.
1664 bool isNewLine() const; ///< Returns true in case this source token represents a line feed character (i.e. "\n" on Unix systems).
1665 bool isKeyword() const; ///< Returns true in case this source token represents a language keyword (i.e. "while", "function", "declare", "on", etc.).
1666 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.
1667 bool isIdentifier() const; ///< Returns true in case this source token represents an identifier, which currently always means a function name.
1668 bool isNumberLiteral() const; ///< Returns true in case this source token represents a number literal (i.e. 123).
1669 bool isStringLiteral() const; ///< Returns true in case this source token represents a string literal (i.e. "Some text").
1670 bool isComment() const; ///< Returns true in case this source token represents a source code comment.
1671 bool isPreprocessor() const; ///< Returns true in case this source token represents a preprocessor statement.
1672 bool isMetricPrefix() const;
1673 bool isStdUnit() const;
1674 bool isOther() const; ///< Returns true in case this source token represents anything else not covered by the token types mentioned above.
1675
1676 // extended types
1677 bool isIntegerVariable() const; ///< Returns true in case this source token represents an integer variable name (i.e. "$someIntVariable").
1678 bool isRealVariable() const; ///< Returns true in case this source token represents a floating point variable name (i.e. "~someRealVariable").
1679 bool isStringVariable() const; ///< Returns true in case this source token represents an string variable name (i.e. "\@someStringVariable").
1680 bool isIntArrayVariable() const; ///< Returns true in case this source token represents an integer array variable name (i.e. "%someArrayVariable").
1681 bool isRealArrayVariable() const; ///< Returns true in case this source token represents a real number array variable name (i.e. "?someArrayVariable").
1682 bool isArrayVariable() const DEPRECATED_API; ///< Returns true in case this source token represents an @b integer array variable name (i.e. "%someArrayVariable"). @deprecated This method will be removed, use isIntArrayVariable() instead.
1683 bool isEventHandlerName() const; ///< Returns true in case this source token represents an event handler name (i.e. "note", "release", "controller").
1684
1685 VMSourceToken& operator=(const VMSourceToken& other);
1686
1687 private:
1688 SourceToken* m_token;
1689 };
1690
1691 } // namespace LinuxSampler
1692
1693 #endif // LS_INSTR_SCRIPT_PARSER_COMMON_H

  ViewVC Help
Powered by ViewVC