/[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 3564 - (show annotations) (download) (as text)
Sat Aug 24 09:18:57 2019 UTC (4 years, 7 months ago) by schoenebeck
File MIME type: text/x-c++hdr
File size: 69052 byte(s)
NKSP: Bug fixes regarding new measurement units feature:

* Fix: Engine internal Fade of script synthesis parameters volume, pitch
  and pan were not rendered at all.

* Fix: Backward compatibility of built-in function arguments without a
  metric unit prefix was broken (resulted in incorrect value
  transformation).

* Fix: built-in script function change_play_pos() resolved wrong arguments.

* Bumped version (2.1.1.svn5).

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

  ViewVC Help
Powered by ViewVC