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

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

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

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

Legend:
Removed from v.2619  
changed lines
  Added in v.3221

  ViewVC Help
Powered by ViewVC