/[svn]/linuxsampler/trunk/src/scriptvm/ScriptVM.cpp
ViewVC logotype

Annotation of /linuxsampler/trunk/src/scriptvm/ScriptVM.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3581 - (hide annotations) (download)
Fri Aug 30 11:40:25 2019 UTC (4 years, 7 months ago) by schoenebeck
File size: 21967 byte(s)
NKSP: Allow more wider support of standard measuring units & 'final'ness.

* Raised compiler requirement to be C++14 compliant (due to severe
  restrictions regarding C-style aggregate initializer lists in C++11
  which are now massively used throughout the code base).

* NKSP VM API: Allow units and 'final'ness to be returned as result from
  built-in functions (added methods VMFunction::returnUnitType() and
  VMFunction::returnsFinal() for that purpose which must be implemented by
  built-in function implementations).

* NKSP language: Allow metric unit prefixes of numeric scalar and array
  variables to be changed freely at runtime (unlike unit types like Hz etc.
  which are still sticky parse-time features of variables which cannot be
  changed at runtime for the intentional sake of determinism).

* NKSP language: 'final' values are prohibited for array variables for now
  (attempt causes a parsers error).

* NKSP language: expressions with unit types (e.g. Hz) are prohibited for
  conditions of runtime control structures like if(), while(), select()
  (attempt causes a parser error).

* NKSP VM API: Allow built-in functions to perform their own, individual
  parse time checks of arguments going to be passed to the function at
  runtime (added method VMFunction::checkArgs() for that purpose).

* NKSP language: raise parser warning if only one operand of binary
  operators (like logical 'or' comparison) contain a 'final' value (because
  it would always yield in a 'final' result in such cases).

* NKSP language: Allow comparison (=, #, <, >, <=, >=) of values with
  different metric unit prefixes, which will behave as expected (e.g.
  result of expression '1000us < 2ms' is true).

* NKSP language: Allow adding values with different metric unit prefixes
  (e.g. result of expression '100Hz + 5kHz' is '5100Hz').

* NKSP language: Allow subtracting values with different metric unit
  prefixes (e.g. result of expression '1ms - 20us' is '980us').

* NKSP language: Allow multiplying with any metric unit prefixes
  (e.g. result of expression '2k * 3ms' is '6s'), however multiplications
  with unit types on both sides (e.g. '2s * 2s') is still prohibited since
  we don't have any considerable practical use for a term like '4s^2'
  (hence any attempt multiplying two unit types still causes parser error).

* NKSP language: Allow dividing by any metric unit prefixes and allow
  division of same unit type on both sides (e.g. expression '8kHz / 1000Hz'
  yields in unit free result '8'). So this is now a way to cast units away
  e.g. for passing the result to other expressions, certain function calls
  or variables which are not accepting any units (or that specific unit).

* NKSP language: integer arrays and real number arrays can now be converted
  to strings (e.g. for dumping their content with message() calls for
  script debugging purposes).

* NKSP language: expressions and variables with units are now correctly
  casted to strings (e.g. with message() calls).

* NKSP language: comparing real numbers for equalness (e.g. '~foo = 3.1') or
  unequalness (e.g. '~foo # 3.1') is now less strict and takes the expected
  floating point tolerances into account.

* NKSP VM API: Added methods VMScalarNumberExpr::evalCastInt() and
  VMScalarNumberExpr::evalCastReal().

* NKSP VM API: Added base class 'VMNumberArrayExpr' for classes
  'VMIntArrayExpr' and 'VMRealArrayExpr'.

* NKSP VM API: replaced all unitPrefix() (parse time) methods by
  unitFactor() (runtime) methods.

* Built-in function "exit()" supports now returning units and 'final'ness
  exclusively for test cases.

* The following built-in functions support now units as well: "abs()",
  "random()", "inc()", "dec()", "in_range()", "min()", "max()",
  "real_to_int()", "int()", "int_to_real()" and "real()".

* Built-in functions "array_equal()", "search()" and "sort()" support now
  real number arrays (correctly) as well.

* Added individual parse time checks of arguments to be passed to built-in
  functions "random()", "inc()", "dec()", "in_range()", "min()", "max()",
  "array_equal()" and "search()" specific for their individual purposes.

* Test cases: Added massive amount of NKSP test cases for standard
  measuring units and 'final' operator usage cases.

* Test cases: Added NKSP test cases for (floating point tolerance aware)
  real number equalness / unequalness comparison.

* Bumped version (2.1.1.svn8).

1 schoenebeck 2581 /*
2 schoenebeck 3551 * Copyright (c) 2014 - 2019 Christian Schoenebeck
3 schoenebeck 2581 *
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     #include "ScriptVM.h"
11    
12 schoenebeck 2588 #include <string.h>
13 schoenebeck 2619 #include <assert.h>
14 schoenebeck 2581 #include "../common/global_private.h"
15     #include "tree.h"
16 schoenebeck 2885 #include "CoreVMFunctions.h"
17 schoenebeck 2942 #include "CoreVMDynVars.h"
18 schoenebeck 2885 #include "editor/NkspScanner.h"
19 schoenebeck 2581
20     #define DEBUG_SCRIPTVM_CORE 0
21    
22 schoenebeck 2974 /**
23     * Maximum amount of VM instructions to be executed per ScriptVM::exec() call
24     * in case loops are involved, before the script got automatically suspended
25     * for a certain amount of time to avoid any RT instability issues.
26     *
27     * The following value takes a max. execution time of 300 microseconds as aimed
28     * target, assuming an execution time of approximately 5 microseconds per
29     * instruction this leads to the very approximate value set below.
30     */
31     #define SCRIPTVM_MAX_INSTR_PER_CYCLE_SOFT 70
32    
33     /**
34     * Absolute maximum amount of VM instructions to be executed per
35     * ScriptVM::exec() call (even if no loops are involved), before the script got
36     * automatically suspended for a certain amount of time to avoid any RT
37     * instability issues.
38     *
39     * A distinction between "soft" and "hard" limit is done here ATM because a
40     * script author typically expects that his script might be interrupted
41     * automatically if he is using while() loops, however he might not be
42     * prepared that his script might also be interrupted if no loop is involved
43     * (i.e. on very large scripts).
44     *
45     * The following value takes a max. execution time of 1000 microseconds as
46     * aimed target, assuming an execution time of approximately 5 microseconds per
47     * instruction this leads to the very approximate value set below.
48     */
49     #define SCRIPTVM_MAX_INSTR_PER_CYCLE_HARD 210
50    
51     /**
52     * In case either SCRIPTVM_MAX_INSTR_PER_CYCLE_SOFT or
53     * SCRIPTVM_MAX_INSTR_PER_CYCLE_HARD was exceeded when calling
54     * ScriptVM::exec() : the amount of microseconds the respective script
55     * execution instance should be automatically suspended by the VM.
56     */
57     #define SCRIPT_VM_FORCE_SUSPENSION_MICROSECONDS 1000
58    
59 schoenebeck 2581 int InstrScript_parse(LinuxSampler::ParserContext*);
60    
61     namespace LinuxSampler {
62    
63 schoenebeck 3034 #if DEBUG_SCRIPTVM_CORE
64 schoenebeck 2581 static void _printIndents(int n) {
65     for (int i = 0; i < n; ++i) printf(" ");
66     fflush(stdout);
67     }
68 schoenebeck 3034 #endif
69 schoenebeck 2581
70 schoenebeck 3557 static vmint _requiredMaxStackSizeFor(Statement* statement, vmint depth = 0) {
71 schoenebeck 2581 if (!statement) return 1;
72    
73     switch (statement->statementType()) {
74     case STMT_LEAF:
75     #if DEBUG_SCRIPTVM_CORE
76     _printIndents(depth);
77     printf("-> STMT_LEAF\n");
78     #endif
79     return 1;
80    
81     case STMT_LIST: {
82     #if DEBUG_SCRIPTVM_CORE
83     _printIndents(depth);
84     printf("-> STMT_LIST\n");
85     #endif
86     Statements* stmts = (Statements*) statement;
87 schoenebeck 3557 vmint max = 0;
88 schoenebeck 2581 for (int i = 0; stmts->statement(i); ++i) {
89 schoenebeck 3557 vmint size = _requiredMaxStackSizeFor( stmts->statement(i), depth+1 );
90 schoenebeck 2581 if (max < size) max = size;
91     }
92     return max + 1;
93     }
94    
95     case STMT_BRANCH: {
96     #if DEBUG_SCRIPTVM_CORE
97     _printIndents(depth);
98     printf("-> STMT_BRANCH\n");
99     #endif
100     BranchStatement* branchStmt = (BranchStatement*) statement;
101 schoenebeck 3557 vmint max = 0;
102 schoenebeck 2581 for (int i = 0; branchStmt->branch(i); ++i) {
103 schoenebeck 3557 vmint size = _requiredMaxStackSizeFor( branchStmt->branch(i), depth+1 );
104 schoenebeck 2581 if (max < size) max = size;
105     }
106     return max + 1;
107     }
108    
109     case STMT_LOOP: {
110     #if DEBUG_SCRIPTVM_CORE
111     _printIndents(depth);
112     printf("-> STMT_LOOP\n");
113     #endif
114     While* whileStmt = (While*) statement;
115     if (whileStmt->statements())
116     return _requiredMaxStackSizeFor( whileStmt->statements() ) + 1;
117     else
118     return 1;
119     }
120 schoenebeck 3260
121     case STMT_SYNC: {
122     #if DEBUG_SCRIPTVM_CORE
123     _printIndents(depth);
124     printf("-> STMT_SYNC\n");
125     #endif
126     SyncBlock* syncStmt = (SyncBlock*) statement;
127     if (syncStmt->statements())
128     return _requiredMaxStackSizeFor( syncStmt->statements() ) + 1;
129     else
130     return 1;
131     }
132 schoenebeck 3557
133     case STMT_NOOP:
134     break; // no operation like the name suggests
135 schoenebeck 2581 }
136    
137     return 1; // actually just to avoid compiler warning
138     }
139    
140 schoenebeck 3557 static vmint _requiredMaxStackSizeFor(EventHandlers* handlers) {
141     vmint max = 1;
142 schoenebeck 2581 for (int i = 0; i < handlers->size(); ++i) {
143 schoenebeck 3557 vmint size = _requiredMaxStackSizeFor(handlers->eventHandler(i));
144 schoenebeck 2581 if (max < size) max = size;
145     }
146     return max;
147     }
148    
149 schoenebeck 3551 ScriptVM::ScriptVM() :
150     m_eventHandler(NULL), m_parserContext(NULL), m_autoSuspend(true),
151     m_acceptExitRes(false)
152     {
153 schoenebeck 2885 m_fnMessage = new CoreVMFunction_message;
154 schoenebeck 3551 m_fnExit = new CoreVMFunction_exit(this);
155 schoenebeck 2885 m_fnWait = new CoreVMFunction_wait(this);
156     m_fnAbs = new CoreVMFunction_abs;
157     m_fnRandom = new CoreVMFunction_random;
158     m_fnNumElements = new CoreVMFunction_num_elements;
159 schoenebeck 2945 m_fnInc = new CoreVMFunction_inc;
160     m_fnDec = new CoreVMFunction_dec;
161 schoenebeck 3076 m_fnInRange = new CoreVMFunction_in_range;
162 schoenebeck 2942 m_varRealTimer = new CoreVMDynVar_NKSP_REAL_TIMER;
163     m_varPerfTimer = new CoreVMDynVar_NKSP_PERF_TIMER;
164 schoenebeck 2965 m_fnShLeft = new CoreVMFunction_sh_left;
165     m_fnShRight = new CoreVMFunction_sh_right;
166 schoenebeck 2970 m_fnMin = new CoreVMFunction_min;
167     m_fnMax = new CoreVMFunction_max;
168 schoenebeck 3221 m_fnArrayEqual = new CoreVMFunction_array_equal;
169     m_fnSearch = new CoreVMFunction_search;
170     m_fnSort = new CoreVMFunction_sort;
171 schoenebeck 3573 m_fnIntToReal = new CoreVMFunction_int_to_real;
172     m_fnRealToInt = new CoreVMFunction_real_to_int;
173 schoenebeck 2581 }
174    
175     ScriptVM::~ScriptVM() {
176 schoenebeck 2885 delete m_fnMessage;
177     delete m_fnExit;
178     delete m_fnWait;
179     delete m_fnAbs;
180     delete m_fnRandom;
181     delete m_fnNumElements;
182 schoenebeck 2945 delete m_fnInc;
183     delete m_fnDec;
184 schoenebeck 3076 delete m_fnInRange;
185 schoenebeck 2965 delete m_fnShLeft;
186     delete m_fnShRight;
187 schoenebeck 2970 delete m_fnMin;
188     delete m_fnMax;
189 schoenebeck 3221 delete m_fnArrayEqual;
190     delete m_fnSearch;
191     delete m_fnSort;
192 schoenebeck 3573 delete m_fnIntToReal;
193     delete m_fnRealToInt;
194 schoenebeck 2942 delete m_varRealTimer;
195     delete m_varPerfTimer;
196 schoenebeck 2581 }
197    
198 schoenebeck 2588 VMParserContext* ScriptVM::loadScript(const String& s) {
199 schoenebeck 2581 std::istringstream iss(s);
200 schoenebeck 2588 return loadScript(&iss);
201 schoenebeck 2581 }
202    
203 schoenebeck 2588 VMParserContext* ScriptVM::loadScript(std::istream* is) {
204     ParserContext* context = new ParserContext(this);
205     //printf("parserCtx=0x%lx\n", (uint64_t)context);
206 schoenebeck 2594
207     context->registerBuiltInConstIntVariables( builtInConstIntVariables() );
208     context->registerBuiltInIntVariables( builtInIntVariables() );
209     context->registerBuiltInIntArrayVariables( builtInIntArrayVariables() );
210 schoenebeck 2942 context->registerBuiltInDynVariables( builtInDynamicVariables() );
211 schoenebeck 2594
212 schoenebeck 2588 context->createScanner(is);
213 schoenebeck 2581
214 schoenebeck 2588 InstrScript_parse(context);
215 schoenebeck 3557 dmsg(2,("Allocating %lld bytes of global int VM memory.\n", context->globalIntVarCount * sizeof(vmint)));
216 schoenebeck 3581 dmsg(2,("Allocating %lld bytes of global real VM memory.\n", context->globalRealVarCount * sizeof(vmfloat)));
217     dmsg(2,("Allocating %lld bytes of global unit factor VM memory.\n", context->globalUnitFactorCount * sizeof(vmfloat)));
218 schoenebeck 3557 dmsg(2,("Allocating %lld of global VM string variables.\n", context->globalStrVarCount));
219 schoenebeck 2588 if (!context->globalIntMemory)
220 schoenebeck 3557 context->globalIntMemory = new ArrayList<vmint>();
221 schoenebeck 3573 if (!context->globalRealMemory)
222     context->globalRealMemory = new ArrayList<vmfloat>();
223 schoenebeck 3581 if (!context->globalUnitFactorMemory)
224     context->globalUnitFactorMemory = new ArrayList<vmfloat>();
225 schoenebeck 2588 if (!context->globalStrMemory)
226     context->globalStrMemory = new ArrayList<String>();
227     context->globalIntMemory->resize(context->globalIntVarCount);
228 schoenebeck 3573 context->globalRealMemory->resize(context->globalRealVarCount);
229 schoenebeck 3581 context->globalUnitFactorMemory->resize(context->globalUnitFactorCount);
230 schoenebeck 3557 memset(&((*context->globalIntMemory)[0]), 0, context->globalIntVarCount * sizeof(vmint));
231 schoenebeck 3573 memset(&((*context->globalRealMemory)[0]), 0, context->globalRealVarCount * sizeof(vmfloat));
232 schoenebeck 3581 for (vmint i = 0; i < context->globalUnitFactorCount; ++i)
233     (*context->globalUnitFactorMemory)[i] = VM_NO_FACTOR;
234 schoenebeck 2588 context->globalStrMemory->resize(context->globalStrVarCount);
235 schoenebeck 2581
236 schoenebeck 2588 context->destroyScanner();
237 schoenebeck 2581
238 schoenebeck 2588 return context;
239 schoenebeck 2581 }
240    
241 schoenebeck 2588 void ScriptVM::dumpParsedScript(VMParserContext* context) {
242     ParserContext* ctx = dynamic_cast<ParserContext*>(context);
243     if (!ctx) {
244 schoenebeck 2581 std::cerr << "No VM context. So nothing to dump.\n";
245     return;
246     }
247 schoenebeck 2588 if (!ctx->handlers) {
248 schoenebeck 2581 std::cerr << "No event handlers defined in script. So nothing to dump.\n";
249     return;
250     }
251 schoenebeck 2588 if (!ctx->globalIntMemory) {
252 schoenebeck 3573 std::cerr << "Internal error: no global integer memory assigend to script VM.\n";
253 schoenebeck 2581 return;
254     }
255 schoenebeck 3573 if (!ctx->globalRealMemory) {
256     std::cerr << "Internal error: no global real number memory assigend to script VM.\n";
257     return;
258     }
259 schoenebeck 2588 ctx->handlers->dump();
260 schoenebeck 2581 }
261    
262 schoenebeck 2588 VMExecContext* ScriptVM::createExecContext(VMParserContext* parserContext) {
263     ParserContext* parserCtx = dynamic_cast<ParserContext*>(parserContext);
264     ExecContext* execCtx = new ExecContext();
265    
266     if (parserCtx->requiredMaxStackSize < 0) {
267     parserCtx->requiredMaxStackSize =
268     _requiredMaxStackSizeFor(&*parserCtx->handlers);
269     }
270     execCtx->stack.resize(parserCtx->requiredMaxStackSize);
271 schoenebeck 3557 dmsg(2,("Created VM exec context with %lld bytes VM stack size.\n",
272     parserCtx->requiredMaxStackSize * sizeof(ExecContext::StackFrame)));
273 schoenebeck 2588 //printf("execCtx=0x%lx\n", (uint64_t)execCtx);
274 schoenebeck 3581 const vmint polyIntSize = parserCtx->polyphonicIntVarCount;
275     execCtx->polyphonicIntMemory.resize(polyIntSize);
276     memset(&execCtx->polyphonicIntMemory[0], 0, polyIntSize * sizeof(vmint));
277 schoenebeck 2588
278 schoenebeck 3581 const vmint polyRealSize = parserCtx->polyphonicRealVarCount;
279     execCtx->polyphonicRealMemory.resize(polyRealSize);
280     memset(&execCtx->polyphonicRealMemory[0], 0, polyRealSize * sizeof(vmfloat));
281    
282     const vmint polyFactorSize = parserCtx->polyphonicUnitFactorCount;
283     execCtx->polyphonicUnitFactorMemory.resize(polyFactorSize);
284     for (vmint i = 0; i < polyFactorSize; ++i)
285     execCtx->polyphonicUnitFactorMemory[i] = VM_NO_FACTOR;
286    
287     dmsg(2,("Allocated %lld bytes polyphonic int memory.\n", polyIntSize * sizeof(vmint)));
288     dmsg(2,("Allocated %lld bytes polyphonic real memory.\n", polyRealSize * sizeof(vmfloat)));
289     dmsg(2,("Allocated %lld bytes unit factor memory.\n", polyFactorSize * sizeof(vmfloat)));
290 schoenebeck 2588 return execCtx;
291 schoenebeck 2581 }
292    
293 schoenebeck 2885 std::vector<VMSourceToken> ScriptVM::syntaxHighlighting(const String& s) {
294     std::istringstream iss(s);
295     return syntaxHighlighting(&iss);
296     }
297    
298     std::vector<VMSourceToken> ScriptVM::syntaxHighlighting(std::istream* is) {
299 schoenebeck 3332 try {
300     NkspScanner scanner(is);
301     std::vector<SourceToken> tokens = scanner.tokens();
302     std::vector<VMSourceToken> result;
303     result.resize(tokens.size());
304 schoenebeck 3557 for (vmint i = 0; i < tokens.size(); ++i) {
305 schoenebeck 3332 SourceToken* st = new SourceToken;
306     *st = tokens[i];
307     result[i] = VMSourceToken(st);
308     }
309     return result;
310     } catch (...) {
311     return std::vector<VMSourceToken>();
312 schoenebeck 2885 }
313     }
314    
315 schoenebeck 2581 VMFunction* ScriptVM::functionByName(const String& name) {
316 schoenebeck 2885 if (name == "message") return m_fnMessage;
317     else if (name == "exit") return m_fnExit;
318     else if (name == "wait") return m_fnWait;
319     else if (name == "abs") return m_fnAbs;
320     else if (name == "random") return m_fnRandom;
321     else if (name == "num_elements") return m_fnNumElements;
322 schoenebeck 2945 else if (name == "inc") return m_fnInc;
323     else if (name == "dec") return m_fnDec;
324 schoenebeck 3076 else if (name == "in_range") return m_fnInRange;
325 schoenebeck 2965 else if (name == "sh_left") return m_fnShLeft;
326     else if (name == "sh_right") return m_fnShRight;
327 schoenebeck 2970 else if (name == "min") return m_fnMin;
328     else if (name == "max") return m_fnMax;
329 schoenebeck 3221 else if (name == "array_equal") return m_fnArrayEqual;
330     else if (name == "search") return m_fnSearch;
331     else if (name == "sort") return m_fnSort;
332 schoenebeck 3573 else if (name == "int_to_real") return m_fnIntToReal;
333     else if (name == "real") return m_fnIntToReal;
334     else if (name == "real_to_int") return m_fnRealToInt;
335     else if (name == "int") return m_fnRealToInt;
336 schoenebeck 2581 return NULL;
337     }
338 schoenebeck 2588
339 schoenebeck 3311 bool ScriptVM::isFunctionDisabled(VMFunction* fn, VMParserContext* ctx) {
340     ParserContext* parserCtx = dynamic_cast<ParserContext*>(ctx);
341     if (!parserCtx) return false;
342    
343     if (fn == m_fnMessage && parserCtx->userPreprocessorConditions.count("NKSP_NO_MESSAGE"))
344     return true;
345    
346     return false;
347     }
348    
349 schoenebeck 3557 std::map<String,VMIntPtr*> ScriptVM::builtInIntVariables() {
350     return std::map<String,VMIntPtr*>();
351 schoenebeck 2594 }
352    
353     std::map<String,VMInt8Array*> ScriptVM::builtInIntArrayVariables() {
354     return std::map<String,VMInt8Array*>();
355     }
356    
357 schoenebeck 2942 std::map<String,VMDynVar*> ScriptVM::builtInDynamicVariables() {
358     std::map<String,VMDynVar*> m;
359    
360     m["$NKSP_PERF_TIMER"] = m_varPerfTimer;
361     m["$NKSP_REAL_TIMER"] = m_varRealTimer;
362     m["$KSP_TIMER"] = m_varRealTimer;
363    
364     return m;
365     }
366    
367 schoenebeck 3557 std::map<String,vmint> ScriptVM::builtInConstIntVariables() {
368     std::map<String,vmint> m;
369 schoenebeck 2948
370     m["$NI_CB_TYPE_INIT"] = VM_EVENT_HANDLER_INIT;
371     m["$NI_CB_TYPE_NOTE"] = VM_EVENT_HANDLER_NOTE;
372     m["$NI_CB_TYPE_RELEASE"] = VM_EVENT_HANDLER_RELEASE;
373     m["$NI_CB_TYPE_CONTROLLER"] = VM_EVENT_HANDLER_CONTROLLER;
374    
375     return m;
376 schoenebeck 2594 }
377    
378 schoenebeck 2879 VMEventHandler* ScriptVM::currentVMEventHandler() {
379     return m_eventHandler;
380     }
381    
382 schoenebeck 2588 VMParserContext* ScriptVM::currentVMParserContext() {
383     return m_parserContext;
384     }
385    
386 schoenebeck 2581 VMExecContext* ScriptVM::currentVMExecContext() {
387 schoenebeck 2588 if (!m_parserContext) return NULL;
388     return m_parserContext->execContext;
389 schoenebeck 2581 }
390    
391 schoenebeck 2974 void ScriptVM::setAutoSuspendEnabled(bool b) {
392     m_autoSuspend = b;
393     }
394    
395     bool ScriptVM::isAutoSuspendEnabled() const {
396     return m_autoSuspend;
397     }
398    
399 schoenebeck 3551 void ScriptVM::setExitResultEnabled(bool b) {
400     m_acceptExitRes = b;
401     }
402    
403     bool ScriptVM::isExitResultEnabled() const {
404     return m_acceptExitRes;
405     }
406    
407 schoenebeck 2588 VMExecStatus_t ScriptVM::exec(VMParserContext* parserContext, VMExecContext* execContex, VMEventHandler* handler) {
408     m_parserContext = dynamic_cast<ParserContext*>(parserContext);
409     if (!m_parserContext) {
410 schoenebeck 3557 std::cerr << "No VM parser context provided. Did you load a script?\n";
411 schoenebeck 2581 return VMExecStatus_t(VM_EXEC_NOT_RUNNING | VM_EXEC_ERROR);
412     }
413    
414 schoenebeck 2611 // a ParserContext object is always tied to exactly one ScriptVM object
415     assert(m_parserContext->functionProvider == this);
416    
417 schoenebeck 2581 ExecContext* ctx = dynamic_cast<ExecContext*>(execContex);
418     if (!ctx) {
419     std::cerr << "Invalid VM exec context.\n";
420     return VMExecStatus_t(VM_EXEC_NOT_RUNNING | VM_EXEC_ERROR);
421     }
422     EventHandler* h = dynamic_cast<EventHandler*>(handler);
423     if (!h) return VM_EXEC_NOT_RUNNING;
424 schoenebeck 2879 m_eventHandler = handler;
425 schoenebeck 2581
426 schoenebeck 2588 m_parserContext->execContext = ctx;
427 schoenebeck 2581
428     ctx->status = VM_EXEC_RUNNING;
429 schoenebeck 3221 ctx->instructionsCount = 0;
430 schoenebeck 3551 ctx->clearExitRes();
431 schoenebeck 3277 StmtFlags_t& flags = ctx->flags;
432 schoenebeck 3557 vmint instructionsCounter = 0;
433     vmint synced = m_autoSuspend ? 0 : 1;
434 schoenebeck 2581
435     int& frameIdx = ctx->stackFrame;
436     if (frameIdx < 0) { // start condition ...
437     frameIdx = -1;
438     ctx->pushStack(h);
439     }
440    
441     while (flags == STMT_SUCCESS && frameIdx >= 0) {
442     if (frameIdx >= ctx->stack.size()) { // should never happen, otherwise it's a bug ...
443     std::cerr << "CRITICAL: VM stack overflow! (" << frameIdx << ")\n";
444     flags = StmtFlags_t(STMT_ABORT_SIGNALLED | STMT_ERROR_OCCURRED);
445     break;
446     }
447    
448     ExecContext::StackFrame& frame = ctx->stack[frameIdx];
449     switch (frame.statement->statementType()) {
450     case STMT_LEAF: {
451     #if DEBUG_SCRIPTVM_CORE
452     _printIndents(frameIdx);
453     printf("-> STMT_LEAF\n");
454     #endif
455     LeafStatement* leaf = (LeafStatement*) frame.statement;
456     flags = leaf->exec();
457     ctx->popStack();
458     break;
459     }
460    
461     case STMT_LIST: {
462     #if DEBUG_SCRIPTVM_CORE
463     _printIndents(frameIdx);
464     printf("-> STMT_LIST subidx=%d\n", frame.subindex);
465     #endif
466     Statements* stmts = (Statements*) frame.statement;
467     if (stmts->statement(frame.subindex)) {
468     ctx->pushStack(
469     stmts->statement(frame.subindex++)
470     );
471     } else {
472     #if DEBUG_SCRIPTVM_CORE
473     _printIndents(frameIdx);
474     printf("[END OF LIST] subidx=%d\n", frame.subindex);
475     #endif
476     ctx->popStack();
477     }
478     break;
479     }
480    
481     case STMT_BRANCH: {
482     #if DEBUG_SCRIPTVM_CORE
483     _printIndents(frameIdx);
484     printf("-> STMT_BRANCH\n");
485     #endif
486     if (frame.subindex < 0) ctx->popStack();
487     else {
488     BranchStatement* branchStmt = (BranchStatement*) frame.statement;
489 schoenebeck 3557 frame.subindex =
490     (decltype(frame.subindex))
491     branchStmt->evalBranch();
492 schoenebeck 2581 if (frame.subindex >= 0) {
493     ctx->pushStack(
494     branchStmt->branch(frame.subindex)
495     );
496     frame.subindex = -1;
497     } else ctx->popStack();
498     }
499     break;
500     }
501    
502     case STMT_LOOP: {
503     #if DEBUG_SCRIPTVM_CORE
504     _printIndents(frameIdx);
505     printf("-> STMT_LOOP\n");
506     #endif
507     While* whileStmt = (While*) frame.statement;
508     if (whileStmt->evalLoopStartCondition() && whileStmt->statements()) {
509     ctx->pushStack(
510     whileStmt->statements()
511     );
512 schoenebeck 3260 if (flags == STMT_SUCCESS && !synced &&
513 schoenebeck 2974 instructionsCounter > SCRIPTVM_MAX_INSTR_PER_CYCLE_SOFT)
514     {
515     flags = StmtFlags_t(STMT_SUSPEND_SIGNALLED);
516     ctx->suspendMicroseconds = SCRIPT_VM_FORCE_SUSPENSION_MICROSECONDS;
517     }
518 schoenebeck 2581 } else ctx->popStack();
519 schoenebeck 2974 break;
520 schoenebeck 2581 }
521 schoenebeck 3260
522     case STMT_SYNC: {
523     #if DEBUG_SCRIPTVM_CORE
524     _printIndents(frameIdx);
525     printf("-> STMT_SYNC\n");
526     #endif
527     SyncBlock* syncStmt = (SyncBlock*) frame.statement;
528     if (!frame.subindex++ && syncStmt->statements()) {
529     ++synced;
530     ctx->pushStack(
531     syncStmt->statements()
532     );
533     } else {
534     ctx->popStack();
535     --synced;
536     }
537     break;
538     }
539 schoenebeck 3557
540     case STMT_NOOP:
541     break; // no operation like the name suggests
542 schoenebeck 2581 }
543 schoenebeck 2974
544 schoenebeck 3260 if (flags == STMT_SUCCESS && !synced &&
545 schoenebeck 2974 instructionsCounter > SCRIPTVM_MAX_INSTR_PER_CYCLE_HARD)
546     {
547     flags = StmtFlags_t(STMT_SUSPEND_SIGNALLED);
548     ctx->suspendMicroseconds = SCRIPT_VM_FORCE_SUSPENSION_MICROSECONDS;
549     }
550    
551     ++instructionsCounter;
552 schoenebeck 2581 }
553    
554 schoenebeck 3277 if ((flags & STMT_SUSPEND_SIGNALLED) && !(flags & STMT_ABORT_SIGNALLED)) {
555 schoenebeck 2581 ctx->status = VM_EXEC_SUSPENDED;
556 schoenebeck 3277 ctx->flags = STMT_SUCCESS;
557 schoenebeck 2581 } else {
558     ctx->status = VM_EXEC_NOT_RUNNING;
559     if (flags & STMT_ERROR_OCCURRED)
560     ctx->status = VM_EXEC_ERROR;
561     ctx->reset();
562     }
563    
564 schoenebeck 3221 ctx->instructionsCount = instructionsCounter;
565    
566 schoenebeck 2879 m_eventHandler = NULL;
567 schoenebeck 2588 m_parserContext->execContext = NULL;
568     m_parserContext = NULL;
569 schoenebeck 2581 return ctx->status;
570     }
571    
572     } // namespace LinuxSampler

  ViewVC Help
Powered by ViewVC