/[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 3804 - (hide annotations) (download)
Thu Aug 6 12:15:02 2020 UTC (3 years, 8 months ago) by schoenebeck
File size: 27496 byte(s)
NKSP: Fixed built-in exit() function to behave as return statement.

* VM API: Introduced new signal STMT_RETURN_SIGNALLED.

* NKSP exit() function: signal STMT_RETURN_SIGNALLED instead of
  STMT_ABORT_SIGNALLED.

* NKSP AST: Introduced common base class 'Subroutine' for 'EventHandler'
  and for new 'UserFunction' class.

* NKSP parser: Use 'UserFunction' class instead of 'Statements' class
  for user declared NKSP functions.

* ScriptVM: Handle new STMT_RETURN_SIGNALLED signal by unwinding the
  stack to previous, calling subroutine.

* NKSP tests: Added test cases for exit() acting as return statement.

* Bumped version (2.1.1.svn62).

1 schoenebeck 2581 /*
2 schoenebeck 3690 * Copyright (c) 2014 - 2020 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 3678 m_fnMsb = new CoreVMFunction_msb;
167     m_fnLsb = new CoreVMFunction_lsb;
168 schoenebeck 2970 m_fnMin = new CoreVMFunction_min;
169     m_fnMax = new CoreVMFunction_max;
170 schoenebeck 3221 m_fnArrayEqual = new CoreVMFunction_array_equal;
171     m_fnSearch = new CoreVMFunction_search;
172     m_fnSort = new CoreVMFunction_sort;
173 schoenebeck 3573 m_fnIntToReal = new CoreVMFunction_int_to_real;
174     m_fnRealToInt = new CoreVMFunction_real_to_int;
175 schoenebeck 3590 m_fnRound = new CoreVMFunction_round;
176     m_fnCeil = new CoreVMFunction_ceil;
177     m_fnFloor = new CoreVMFunction_floor;
178     m_fnSqrt = new CoreVMFunction_sqrt;
179     m_fnLog = new CoreVMFunction_log;
180     m_fnLog2 = new CoreVMFunction_log2;
181     m_fnLog10 = new CoreVMFunction_log10;
182     m_fnExp = new CoreVMFunction_exp;
183     m_fnPow = new CoreVMFunction_pow;
184     m_fnSin = new CoreVMFunction_sin;
185     m_fnCos = new CoreVMFunction_cos;
186     m_fnTan = new CoreVMFunction_tan;
187     m_fnAsin = new CoreVMFunction_asin;
188     m_fnAcos = new CoreVMFunction_acos;
189     m_fnAtan = new CoreVMFunction_atan;
190 schoenebeck 2581 }
191    
192     ScriptVM::~ScriptVM() {
193 schoenebeck 2885 delete m_fnMessage;
194     delete m_fnExit;
195     delete m_fnWait;
196     delete m_fnAbs;
197     delete m_fnRandom;
198     delete m_fnNumElements;
199 schoenebeck 2945 delete m_fnInc;
200     delete m_fnDec;
201 schoenebeck 3076 delete m_fnInRange;
202 schoenebeck 2965 delete m_fnShLeft;
203     delete m_fnShRight;
204 schoenebeck 3678 delete m_fnMsb;
205     delete m_fnLsb;
206 schoenebeck 2970 delete m_fnMin;
207     delete m_fnMax;
208 schoenebeck 3221 delete m_fnArrayEqual;
209     delete m_fnSearch;
210     delete m_fnSort;
211 schoenebeck 3573 delete m_fnIntToReal;
212     delete m_fnRealToInt;
213 schoenebeck 3590 delete m_fnRound;
214     delete m_fnCeil;
215     delete m_fnFloor;
216     delete m_fnSqrt;
217     delete m_fnLog;
218     delete m_fnLog2;
219     delete m_fnLog10;
220     delete m_fnExp;
221     delete m_fnPow;
222     delete m_fnSin;
223     delete m_fnCos;
224     delete m_fnTan;
225     delete m_fnAsin;
226     delete m_fnAcos;
227     delete m_fnAtan;
228 schoenebeck 2942 delete m_varRealTimer;
229     delete m_varPerfTimer;
230 schoenebeck 2581 }
231    
232 schoenebeck 3733 VMParserContext* ScriptVM::loadScript(std::istream* is,
233     const std::map<String,String>& patchVars,
234     std::map<String,String>* patchVarsDef)
235     {
236     std::string s(std::istreambuf_iterator<char>(*is),{});
237     return loadScript(s, patchVars, patchVarsDef);
238 schoenebeck 2581 }
239 schoenebeck 3733
240     VMParserContext* ScriptVM::loadScript(const String& s,
241     const std::map<String,String>& patchVars,
242     std::map<String,String>* patchVarsDef)
243     {
244     ParserContext* context = (ParserContext*) loadScriptOnePass(s);
245     if (!context->vErrors.empty())
246     return context;
247    
248     if (!context->patchVars.empty() && (!patchVars.empty() || patchVarsDef)) {
249     String s2 = s;
250    
251     typedef std::pair<String,PatchVarBlock> Var;
252     std::map<int,Var> varsByPos;
253     for (const Var& var : context->patchVars) {
254     const String& name = var.first;
255     const PatchVarBlock& block = var.second;
256     const int pos =
257     (block.exprBlock) ?
258     block.exprBlock->firstByte :
259     block.nameBlock.firstByte + block.nameBlock.lengthBytes;
260     varsByPos[pos] = var;
261     if (patchVarsDef) {
262     (*patchVarsDef)[name] =
263     (block.exprBlock) ?
264     s.substr(pos, block.exprBlock->lengthBytes) : "";
265     }
266     }
267    
268     if (patchVars.empty())
269     return context;
270    
271     for (std::map<int,Var>::reverse_iterator it = varsByPos.rbegin();
272     it != varsByPos.rend(); ++it)
273     {
274     const String name = it->second.first;
275     if (patchVars.find(name) != patchVars.end()) {
276     const int pos = it->first;
277     const PatchVarBlock& block = it->second.second;
278     const int length =
279     (block.exprBlock) ? block.exprBlock->lengthBytes : 0;
280     String value;
281     if (!length)
282     value += " := ";
283     value += patchVars.find(name)->second;
284     s2.replace(pos, length, value);
285     }
286     }
287    
288     if (s2 != s) {
289     delete context;
290     context = (ParserContext*) loadScriptOnePass(s2);
291     }
292     }
293    
294     return context;
295     }
296    
297     VMParserContext* ScriptVM::loadScriptOnePass(const String& s) {
298 schoenebeck 2588 ParserContext* context = new ParserContext(this);
299     //printf("parserCtx=0x%lx\n", (uint64_t)context);
300 schoenebeck 3733 std::istringstream iss(s);
301 schoenebeck 2594
302     context->registerBuiltInConstIntVariables( builtInConstIntVariables() );
303 schoenebeck 3590 context->registerBuiltInConstRealVariables( builtInConstRealVariables() );
304 schoenebeck 2594 context->registerBuiltInIntVariables( builtInIntVariables() );
305     context->registerBuiltInIntArrayVariables( builtInIntArrayVariables() );
306 schoenebeck 2942 context->registerBuiltInDynVariables( builtInDynamicVariables() );
307 schoenebeck 2594
308 schoenebeck 3733 context->createScanner(&iss);
309 schoenebeck 2581
310 schoenebeck 2588 InstrScript_parse(context);
311 schoenebeck 3707 dmsg(2,("Allocating %" PRId64 " bytes of global int VM memory.\n", int64_t(context->globalIntVarCount * sizeof(vmint))));
312     dmsg(2,("Allocating %" PRId64 " bytes of global real VM memory.\n", int64_t(context->globalRealVarCount * sizeof(vmfloat))));
313     dmsg(2,("Allocating %" PRId64 " bytes of global unit factor VM memory.\n", int64_t(context->globalUnitFactorCount * sizeof(vmfloat))));
314     dmsg(2,("Allocating %" PRId64 " of global VM string variables.\n", (int64_t)context->globalStrVarCount));
315 schoenebeck 2588 if (!context->globalIntMemory)
316 schoenebeck 3557 context->globalIntMemory = new ArrayList<vmint>();
317 schoenebeck 3573 if (!context->globalRealMemory)
318     context->globalRealMemory = new ArrayList<vmfloat>();
319 schoenebeck 3581 if (!context->globalUnitFactorMemory)
320     context->globalUnitFactorMemory = new ArrayList<vmfloat>();
321 schoenebeck 2588 if (!context->globalStrMemory)
322     context->globalStrMemory = new ArrayList<String>();
323     context->globalIntMemory->resize(context->globalIntVarCount);
324 schoenebeck 3573 context->globalRealMemory->resize(context->globalRealVarCount);
325 schoenebeck 3581 context->globalUnitFactorMemory->resize(context->globalUnitFactorCount);
326 schoenebeck 3557 memset(&((*context->globalIntMemory)[0]), 0, context->globalIntVarCount * sizeof(vmint));
327 schoenebeck 3573 memset(&((*context->globalRealMemory)[0]), 0, context->globalRealVarCount * sizeof(vmfloat));
328 schoenebeck 3581 for (vmint i = 0; i < context->globalUnitFactorCount; ++i)
329     (*context->globalUnitFactorMemory)[i] = VM_NO_FACTOR;
330 schoenebeck 2588 context->globalStrMemory->resize(context->globalStrVarCount);
331 schoenebeck 2581
332 schoenebeck 2588 context->destroyScanner();
333 schoenebeck 2581
334 schoenebeck 2588 return context;
335 schoenebeck 2581 }
336    
337 schoenebeck 2588 void ScriptVM::dumpParsedScript(VMParserContext* context) {
338     ParserContext* ctx = dynamic_cast<ParserContext*>(context);
339     if (!ctx) {
340 schoenebeck 2581 std::cerr << "No VM context. So nothing to dump.\n";
341     return;
342     }
343 schoenebeck 2588 if (!ctx->handlers) {
344 schoenebeck 2581 std::cerr << "No event handlers defined in script. So nothing to dump.\n";
345     return;
346     }
347 schoenebeck 2588 if (!ctx->globalIntMemory) {
348 schoenebeck 3573 std::cerr << "Internal error: no global integer memory assigend to script VM.\n";
349 schoenebeck 2581 return;
350     }
351 schoenebeck 3573 if (!ctx->globalRealMemory) {
352     std::cerr << "Internal error: no global real number memory assigend to script VM.\n";
353     return;
354     }
355 schoenebeck 2588 ctx->handlers->dump();
356 schoenebeck 2581 }
357    
358 schoenebeck 2588 VMExecContext* ScriptVM::createExecContext(VMParserContext* parserContext) {
359     ParserContext* parserCtx = dynamic_cast<ParserContext*>(parserContext);
360     ExecContext* execCtx = new ExecContext();
361    
362     if (parserCtx->requiredMaxStackSize < 0) {
363     parserCtx->requiredMaxStackSize =
364     _requiredMaxStackSizeFor(&*parserCtx->handlers);
365     }
366     execCtx->stack.resize(parserCtx->requiredMaxStackSize);
367 schoenebeck 3707 dmsg(2,("Created VM exec context with %" PRId64 " bytes VM stack size.\n",
368     int64_t(parserCtx->requiredMaxStackSize * sizeof(ExecContext::StackFrame))));
369 schoenebeck 2588 //printf("execCtx=0x%lx\n", (uint64_t)execCtx);
370 schoenebeck 3581 const vmint polyIntSize = parserCtx->polyphonicIntVarCount;
371     execCtx->polyphonicIntMemory.resize(polyIntSize);
372     memset(&execCtx->polyphonicIntMemory[0], 0, polyIntSize * sizeof(vmint));
373 schoenebeck 2588
374 schoenebeck 3581 const vmint polyRealSize = parserCtx->polyphonicRealVarCount;
375     execCtx->polyphonicRealMemory.resize(polyRealSize);
376     memset(&execCtx->polyphonicRealMemory[0], 0, polyRealSize * sizeof(vmfloat));
377    
378     const vmint polyFactorSize = parserCtx->polyphonicUnitFactorCount;
379     execCtx->polyphonicUnitFactorMemory.resize(polyFactorSize);
380     for (vmint i = 0; i < polyFactorSize; ++i)
381     execCtx->polyphonicUnitFactorMemory[i] = VM_NO_FACTOR;
382    
383 schoenebeck 3707 dmsg(2,("Allocated %" PRId64 " bytes polyphonic int memory.\n", int64_t(polyIntSize * sizeof(vmint))));
384     dmsg(2,("Allocated %" PRId64 " bytes polyphonic real memory.\n", int64_t(polyRealSize * sizeof(vmfloat))));
385     dmsg(2,("Allocated %" PRId64 " bytes unit factor memory.\n", int64_t(polyFactorSize * sizeof(vmfloat))));
386 schoenebeck 2588 return execCtx;
387 schoenebeck 2581 }
388    
389 schoenebeck 2885 std::vector<VMSourceToken> ScriptVM::syntaxHighlighting(const String& s) {
390     std::istringstream iss(s);
391     return syntaxHighlighting(&iss);
392     }
393    
394     std::vector<VMSourceToken> ScriptVM::syntaxHighlighting(std::istream* is) {
395 schoenebeck 3332 try {
396     NkspScanner scanner(is);
397     std::vector<SourceToken> tokens = scanner.tokens();
398     std::vector<VMSourceToken> result;
399     result.resize(tokens.size());
400 schoenebeck 3557 for (vmint i = 0; i < tokens.size(); ++i) {
401 schoenebeck 3332 SourceToken* st = new SourceToken;
402     *st = tokens[i];
403     result[i] = VMSourceToken(st);
404     }
405     return result;
406     } catch (...) {
407     return std::vector<VMSourceToken>();
408 schoenebeck 2885 }
409     }
410    
411 schoenebeck 2581 VMFunction* ScriptVM::functionByName(const String& name) {
412 schoenebeck 2885 if (name == "message") return m_fnMessage;
413     else if (name == "exit") return m_fnExit;
414     else if (name == "wait") return m_fnWait;
415     else if (name == "abs") return m_fnAbs;
416     else if (name == "random") return m_fnRandom;
417     else if (name == "num_elements") return m_fnNumElements;
418 schoenebeck 2945 else if (name == "inc") return m_fnInc;
419     else if (name == "dec") return m_fnDec;
420 schoenebeck 3076 else if (name == "in_range") return m_fnInRange;
421 schoenebeck 2965 else if (name == "sh_left") return m_fnShLeft;
422     else if (name == "sh_right") return m_fnShRight;
423 schoenebeck 3678 else if (name == "msb") return m_fnMsb;
424     else if (name == "lsb") return m_fnLsb;
425 schoenebeck 2970 else if (name == "min") return m_fnMin;
426     else if (name == "max") return m_fnMax;
427 schoenebeck 3221 else if (name == "array_equal") return m_fnArrayEqual;
428     else if (name == "search") return m_fnSearch;
429     else if (name == "sort") return m_fnSort;
430 schoenebeck 3573 else if (name == "int_to_real") return m_fnIntToReal;
431     else if (name == "real") return m_fnIntToReal;
432     else if (name == "real_to_int") return m_fnRealToInt;
433     else if (name == "int") return m_fnRealToInt;
434 schoenebeck 3590 else if (name == "round") return m_fnRound;
435     else if (name == "ceil") return m_fnCeil;
436     else if (name == "floor") return m_fnFloor;
437     else if (name == "sqrt") return m_fnSqrt;
438     else if (name == "log") return m_fnLog;
439     else if (name == "log2") return m_fnLog2;
440     else if (name == "log10") return m_fnLog10;
441     else if (name == "exp") return m_fnExp;
442     else if (name == "pow") return m_fnPow;
443     else if (name == "sin") return m_fnSin;
444     else if (name == "cos") return m_fnCos;
445     else if (name == "tan") return m_fnTan;
446     else if (name == "asin") return m_fnAsin;
447     else if (name == "acos") return m_fnAcos;
448     else if (name == "atan") return m_fnAtan;
449 schoenebeck 2581 return NULL;
450     }
451 schoenebeck 2588
452 schoenebeck 3311 bool ScriptVM::isFunctionDisabled(VMFunction* fn, VMParserContext* ctx) {
453     ParserContext* parserCtx = dynamic_cast<ParserContext*>(ctx);
454     if (!parserCtx) return false;
455    
456     if (fn == m_fnMessage && parserCtx->userPreprocessorConditions.count("NKSP_NO_MESSAGE"))
457     return true;
458    
459     return false;
460     }
461    
462 schoenebeck 3557 std::map<String,VMIntPtr*> ScriptVM::builtInIntVariables() {
463     return std::map<String,VMIntPtr*>();
464 schoenebeck 2594 }
465    
466     std::map<String,VMInt8Array*> ScriptVM::builtInIntArrayVariables() {
467     return std::map<String,VMInt8Array*>();
468     }
469    
470 schoenebeck 2942 std::map<String,VMDynVar*> ScriptVM::builtInDynamicVariables() {
471     std::map<String,VMDynVar*> m;
472    
473     m["$NKSP_PERF_TIMER"] = m_varPerfTimer;
474     m["$NKSP_REAL_TIMER"] = m_varRealTimer;
475     m["$KSP_TIMER"] = m_varRealTimer;
476    
477     return m;
478     }
479    
480 schoenebeck 3557 std::map<String,vmint> ScriptVM::builtInConstIntVariables() {
481     std::map<String,vmint> m;
482 schoenebeck 2948
483     m["$NI_CB_TYPE_INIT"] = VM_EVENT_HANDLER_INIT;
484     m["$NI_CB_TYPE_NOTE"] = VM_EVENT_HANDLER_NOTE;
485     m["$NI_CB_TYPE_RELEASE"] = VM_EVENT_HANDLER_RELEASE;
486     m["$NI_CB_TYPE_CONTROLLER"] = VM_EVENT_HANDLER_CONTROLLER;
487 schoenebeck 3690 m["$NI_CB_TYPE_RPN"] = VM_EVENT_HANDLER_RPN;
488     m["$NI_CB_TYPE_NRPN"] = VM_EVENT_HANDLER_NRPN;
489 schoenebeck 2948
490     return m;
491 schoenebeck 2594 }
492    
493 schoenebeck 3590 std::map<String,vmfloat> ScriptVM::builtInConstRealVariables() {
494     std::map<String,vmfloat> m;
495    
496     m["~NI_MATH_PI"] = M_PI;
497     m["~NI_MATH_E"] = M_E;
498    
499     return m;
500     }
501    
502 schoenebeck 2879 VMEventHandler* ScriptVM::currentVMEventHandler() {
503     return m_eventHandler;
504     }
505    
506 schoenebeck 2588 VMParserContext* ScriptVM::currentVMParserContext() {
507     return m_parserContext;
508     }
509    
510 schoenebeck 2581 VMExecContext* ScriptVM::currentVMExecContext() {
511 schoenebeck 2588 if (!m_parserContext) return NULL;
512     return m_parserContext->execContext;
513 schoenebeck 2581 }
514    
515 schoenebeck 2974 void ScriptVM::setAutoSuspendEnabled(bool b) {
516     m_autoSuspend = b;
517     }
518    
519     bool ScriptVM::isAutoSuspendEnabled() const {
520     return m_autoSuspend;
521     }
522    
523 schoenebeck 3551 void ScriptVM::setExitResultEnabled(bool b) {
524     m_acceptExitRes = b;
525     }
526    
527     bool ScriptVM::isExitResultEnabled() const {
528     return m_acceptExitRes;
529     }
530    
531 schoenebeck 2588 VMExecStatus_t ScriptVM::exec(VMParserContext* parserContext, VMExecContext* execContex, VMEventHandler* handler) {
532     m_parserContext = dynamic_cast<ParserContext*>(parserContext);
533     if (!m_parserContext) {
534 schoenebeck 3557 std::cerr << "No VM parser context provided. Did you load a script?\n";
535 schoenebeck 2581 return VMExecStatus_t(VM_EXEC_NOT_RUNNING | VM_EXEC_ERROR);
536     }
537    
538 schoenebeck 2611 // a ParserContext object is always tied to exactly one ScriptVM object
539     assert(m_parserContext->functionProvider == this);
540    
541 schoenebeck 2581 ExecContext* ctx = dynamic_cast<ExecContext*>(execContex);
542     if (!ctx) {
543     std::cerr << "Invalid VM exec context.\n";
544     return VMExecStatus_t(VM_EXEC_NOT_RUNNING | VM_EXEC_ERROR);
545     }
546     EventHandler* h = dynamic_cast<EventHandler*>(handler);
547     if (!h) return VM_EXEC_NOT_RUNNING;
548 schoenebeck 2879 m_eventHandler = handler;
549 schoenebeck 2581
550 schoenebeck 2588 m_parserContext->execContext = ctx;
551 schoenebeck 2581
552     ctx->status = VM_EXEC_RUNNING;
553 schoenebeck 3221 ctx->instructionsCount = 0;
554 schoenebeck 3551 ctx->clearExitRes();
555 schoenebeck 3277 StmtFlags_t& flags = ctx->flags;
556 schoenebeck 3557 vmint instructionsCounter = 0;
557     vmint synced = m_autoSuspend ? 0 : 1;
558 schoenebeck 2581
559     int& frameIdx = ctx->stackFrame;
560     if (frameIdx < 0) { // start condition ...
561     frameIdx = -1;
562     ctx->pushStack(h);
563     }
564    
565     while (flags == STMT_SUCCESS && frameIdx >= 0) {
566     if (frameIdx >= ctx->stack.size()) { // should never happen, otherwise it's a bug ...
567     std::cerr << "CRITICAL: VM stack overflow! (" << frameIdx << ")\n";
568     flags = StmtFlags_t(STMT_ABORT_SIGNALLED | STMT_ERROR_OCCURRED);
569     break;
570     }
571    
572     ExecContext::StackFrame& frame = ctx->stack[frameIdx];
573     switch (frame.statement->statementType()) {
574     case STMT_LEAF: {
575     #if DEBUG_SCRIPTVM_CORE
576     _printIndents(frameIdx);
577     printf("-> STMT_LEAF\n");
578     #endif
579     LeafStatement* leaf = (LeafStatement*) frame.statement;
580     flags = leaf->exec();
581     ctx->popStack();
582     break;
583     }
584    
585     case STMT_LIST: {
586     #if DEBUG_SCRIPTVM_CORE
587     _printIndents(frameIdx);
588     printf("-> STMT_LIST subidx=%d\n", frame.subindex);
589     #endif
590     Statements* stmts = (Statements*) frame.statement;
591     if (stmts->statement(frame.subindex)) {
592     ctx->pushStack(
593     stmts->statement(frame.subindex++)
594     );
595     } else {
596     #if DEBUG_SCRIPTVM_CORE
597     _printIndents(frameIdx);
598     printf("[END OF LIST] subidx=%d\n", frame.subindex);
599     #endif
600     ctx->popStack();
601     }
602     break;
603     }
604    
605     case STMT_BRANCH: {
606     #if DEBUG_SCRIPTVM_CORE
607     _printIndents(frameIdx);
608     printf("-> STMT_BRANCH\n");
609     #endif
610     if (frame.subindex < 0) ctx->popStack();
611     else {
612     BranchStatement* branchStmt = (BranchStatement*) frame.statement;
613 schoenebeck 3557 frame.subindex =
614     (decltype(frame.subindex))
615     branchStmt->evalBranch();
616 schoenebeck 2581 if (frame.subindex >= 0) {
617     ctx->pushStack(
618     branchStmt->branch(frame.subindex)
619     );
620     frame.subindex = -1;
621     } else ctx->popStack();
622     }
623     break;
624     }
625    
626     case STMT_LOOP: {
627     #if DEBUG_SCRIPTVM_CORE
628     _printIndents(frameIdx);
629     printf("-> STMT_LOOP\n");
630     #endif
631     While* whileStmt = (While*) frame.statement;
632     if (whileStmt->evalLoopStartCondition() && whileStmt->statements()) {
633     ctx->pushStack(
634     whileStmt->statements()
635     );
636 schoenebeck 3260 if (flags == STMT_SUCCESS && !synced &&
637 schoenebeck 2974 instructionsCounter > SCRIPTVM_MAX_INSTR_PER_CYCLE_SOFT)
638     {
639     flags = StmtFlags_t(STMT_SUSPEND_SIGNALLED);
640     ctx->suspendMicroseconds = SCRIPT_VM_FORCE_SUSPENSION_MICROSECONDS;
641     }
642 schoenebeck 2581 } else ctx->popStack();
643 schoenebeck 2974 break;
644 schoenebeck 2581 }
645 schoenebeck 3260
646     case STMT_SYNC: {
647     #if DEBUG_SCRIPTVM_CORE
648     _printIndents(frameIdx);
649     printf("-> STMT_SYNC\n");
650     #endif
651     SyncBlock* syncStmt = (SyncBlock*) frame.statement;
652     if (!frame.subindex++ && syncStmt->statements()) {
653     ++synced;
654     ctx->pushStack(
655     syncStmt->statements()
656     );
657     } else {
658     ctx->popStack();
659     --synced;
660     }
661     break;
662     }
663 schoenebeck 3557
664     case STMT_NOOP:
665     break; // no operation like the name suggests
666 schoenebeck 2581 }
667 schoenebeck 2974
668 schoenebeck 3804 if (flags & STMT_RETURN_SIGNALLED) {
669     flags = StmtFlags_t(flags & ~STMT_RETURN_SIGNALLED);
670     for (; frameIdx >= 0; ctx->popStack()) {
671     frame = ctx->stack[frameIdx];
672     if (frame.statement->statementType() == STMT_SYNC) {
673     --synced;
674     } else if (dynamic_cast<Subroutine*>(frame.statement)) {
675     ctx->popStack();
676     break; // stop here
677     }
678     }
679     }
680    
681 schoenebeck 3260 if (flags == STMT_SUCCESS && !synced &&
682 schoenebeck 2974 instructionsCounter > SCRIPTVM_MAX_INSTR_PER_CYCLE_HARD)
683     {
684     flags = StmtFlags_t(STMT_SUSPEND_SIGNALLED);
685     ctx->suspendMicroseconds = SCRIPT_VM_FORCE_SUSPENSION_MICROSECONDS;
686     }
687    
688     ++instructionsCounter;
689 schoenebeck 2581 }
690    
691 schoenebeck 3277 if ((flags & STMT_SUSPEND_SIGNALLED) && !(flags & STMT_ABORT_SIGNALLED)) {
692 schoenebeck 2581 ctx->status = VM_EXEC_SUSPENDED;
693 schoenebeck 3277 ctx->flags = STMT_SUCCESS;
694 schoenebeck 2581 } else {
695     ctx->status = VM_EXEC_NOT_RUNNING;
696     if (flags & STMT_ERROR_OCCURRED)
697     ctx->status = VM_EXEC_ERROR;
698     ctx->reset();
699     }
700    
701 schoenebeck 3221 ctx->instructionsCount = instructionsCounter;
702    
703 schoenebeck 2879 m_eventHandler = NULL;
704 schoenebeck 2588 m_parserContext->execContext = NULL;
705     m_parserContext = NULL;
706 schoenebeck 2581 return ctx->status;
707     }
708    
709     } // namespace LinuxSampler

  ViewVC Help
Powered by ViewVC