/[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 3076 - (hide annotations) (download)
Thu Jan 5 18:00:52 2017 UTC (7 years, 3 months ago) by schoenebeck
File size: 17131 byte(s)
* NKSP: Implemented built-in script function "in_range()".
* Bumped version (2.0.0.svn36).

1 schoenebeck 2581 /*
2 schoenebeck 3076 * Copyright (c) 2014 - 2017 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     static int _requiredMaxStackSizeFor(Statement* statement, int depth = 0) {
71     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     int max = 0;
88     for (int i = 0; stmts->statement(i); ++i) {
89     int size = _requiredMaxStackSizeFor( stmts->statement(i), depth+1 );
90     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     int max = 0;
102     for (int i = 0; branchStmt->branch(i); ++i) {
103     int size = _requiredMaxStackSizeFor( branchStmt->branch(i), depth+1 );
104     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     }
121    
122     return 1; // actually just to avoid compiler warning
123     }
124    
125     static int _requiredMaxStackSizeFor(EventHandlers* handlers) {
126     int max = 1;
127     for (int i = 0; i < handlers->size(); ++i) {
128     int size = _requiredMaxStackSizeFor(handlers->eventHandler(i));
129     if (max < size) max = size;
130     }
131     return max;
132     }
133    
134 schoenebeck 2974 ScriptVM::ScriptVM() : m_eventHandler(NULL), m_parserContext(NULL), m_autoSuspend(true) {
135 schoenebeck 2885 m_fnMessage = new CoreVMFunction_message;
136     m_fnExit = new CoreVMFunction_exit;
137     m_fnWait = new CoreVMFunction_wait(this);
138     m_fnAbs = new CoreVMFunction_abs;
139     m_fnRandom = new CoreVMFunction_random;
140     m_fnNumElements = new CoreVMFunction_num_elements;
141 schoenebeck 2945 m_fnInc = new CoreVMFunction_inc;
142     m_fnDec = new CoreVMFunction_dec;
143 schoenebeck 3076 m_fnInRange = new CoreVMFunction_in_range;
144 schoenebeck 2942 m_varRealTimer = new CoreVMDynVar_NKSP_REAL_TIMER;
145     m_varPerfTimer = new CoreVMDynVar_NKSP_PERF_TIMER;
146 schoenebeck 2965 m_fnShLeft = new CoreVMFunction_sh_left;
147     m_fnShRight = new CoreVMFunction_sh_right;
148 schoenebeck 2970 m_fnMin = new CoreVMFunction_min;
149     m_fnMax = new CoreVMFunction_max;
150 schoenebeck 2581 }
151    
152     ScriptVM::~ScriptVM() {
153 schoenebeck 2885 delete m_fnMessage;
154     delete m_fnExit;
155     delete m_fnWait;
156     delete m_fnAbs;
157     delete m_fnRandom;
158     delete m_fnNumElements;
159 schoenebeck 2945 delete m_fnInc;
160     delete m_fnDec;
161 schoenebeck 3076 delete m_fnInRange;
162 schoenebeck 2965 delete m_fnShLeft;
163     delete m_fnShRight;
164 schoenebeck 2970 delete m_fnMin;
165     delete m_fnMax;
166 schoenebeck 2942 delete m_varRealTimer;
167     delete m_varPerfTimer;
168 schoenebeck 2581 }
169    
170 schoenebeck 2588 VMParserContext* ScriptVM::loadScript(const String& s) {
171 schoenebeck 2581 std::istringstream iss(s);
172 schoenebeck 2588 return loadScript(&iss);
173 schoenebeck 2581 }
174    
175 schoenebeck 2588 VMParserContext* ScriptVM::loadScript(std::istream* is) {
176     ParserContext* context = new ParserContext(this);
177     //printf("parserCtx=0x%lx\n", (uint64_t)context);
178 schoenebeck 2594
179     context->registerBuiltInConstIntVariables( builtInConstIntVariables() );
180     context->registerBuiltInIntVariables( builtInIntVariables() );
181     context->registerBuiltInIntArrayVariables( builtInIntArrayVariables() );
182 schoenebeck 2942 context->registerBuiltInDynVariables( builtInDynamicVariables() );
183 schoenebeck 2594
184 schoenebeck 2588 context->createScanner(is);
185 schoenebeck 2581
186 schoenebeck 2588 InstrScript_parse(context);
187 persson 2837 dmsg(2,("Allocating %ld bytes of global int VM memory.\n", long(context->globalIntVarCount * sizeof(int))));
188 schoenebeck 2611 dmsg(2,("Allocating %d of global VM string variables.\n", context->globalStrVarCount));
189 schoenebeck 2588 if (!context->globalIntMemory)
190     context->globalIntMemory = new ArrayList<int>();
191     if (!context->globalStrMemory)
192     context->globalStrMemory = new ArrayList<String>();
193     context->globalIntMemory->resize(context->globalIntVarCount);
194     memset(&((*context->globalIntMemory)[0]), 0, context->globalIntVarCount * sizeof(int));
195    
196     context->globalStrMemory->resize(context->globalStrVarCount);
197 schoenebeck 2581
198 schoenebeck 2588 context->destroyScanner();
199 schoenebeck 2581
200 schoenebeck 2588 return context;
201 schoenebeck 2581 }
202    
203 schoenebeck 2588 void ScriptVM::dumpParsedScript(VMParserContext* context) {
204     ParserContext* ctx = dynamic_cast<ParserContext*>(context);
205     if (!ctx) {
206 schoenebeck 2581 std::cerr << "No VM context. So nothing to dump.\n";
207     return;
208     }
209 schoenebeck 2588 if (!ctx->handlers) {
210 schoenebeck 2581 std::cerr << "No event handlers defined in script. So nothing to dump.\n";
211     return;
212     }
213 schoenebeck 2588 if (!ctx->globalIntMemory) {
214 schoenebeck 2581 std::cerr << "Internal error: no global memory assigend to script VM.\n";
215     return;
216     }
217 schoenebeck 2588 ctx->handlers->dump();
218 schoenebeck 2581 }
219    
220 schoenebeck 2588 VMExecContext* ScriptVM::createExecContext(VMParserContext* parserContext) {
221     ParserContext* parserCtx = dynamic_cast<ParserContext*>(parserContext);
222     ExecContext* execCtx = new ExecContext();
223    
224     if (parserCtx->requiredMaxStackSize < 0) {
225     parserCtx->requiredMaxStackSize =
226     _requiredMaxStackSizeFor(&*parserCtx->handlers);
227     }
228     execCtx->stack.resize(parserCtx->requiredMaxStackSize);
229 persson 2837 dmsg(2,("Created VM exec context with %ld bytes VM stack size.\n",
230     long(parserCtx->requiredMaxStackSize * sizeof(ExecContext::StackFrame))));
231 schoenebeck 2588 //printf("execCtx=0x%lx\n", (uint64_t)execCtx);
232     const int polySize = parserCtx->polyphonicIntVarCount;
233     execCtx->polyphonicIntMemory.resize(polySize);
234     memset(&execCtx->polyphonicIntMemory[0], 0, polySize * sizeof(int));
235    
236 persson 2837 dmsg(2,("Allocated %ld bytes polyphonic memory.\n", long(polySize * sizeof(int))));
237 schoenebeck 2588 return execCtx;
238 schoenebeck 2581 }
239    
240 schoenebeck 2885 std::vector<VMSourceToken> ScriptVM::syntaxHighlighting(const String& s) {
241     std::istringstream iss(s);
242     return syntaxHighlighting(&iss);
243     }
244    
245     std::vector<VMSourceToken> ScriptVM::syntaxHighlighting(std::istream* is) {
246     NkspScanner scanner(is);
247     std::vector<SourceToken> tokens = scanner.tokens();
248     std::vector<VMSourceToken> result;
249     result.resize(tokens.size());
250     for (int i = 0; i < tokens.size(); ++i) {
251     SourceToken* st = new SourceToken;
252     *st = tokens[i];
253     result[i] = VMSourceToken(st);
254     }
255     return result;
256     }
257    
258 schoenebeck 2581 VMFunction* ScriptVM::functionByName(const String& name) {
259 schoenebeck 2885 if (name == "message") return m_fnMessage;
260     else if (name == "exit") return m_fnExit;
261     else if (name == "wait") return m_fnWait;
262     else if (name == "abs") return m_fnAbs;
263     else if (name == "random") return m_fnRandom;
264     else if (name == "num_elements") return m_fnNumElements;
265 schoenebeck 2945 else if (name == "inc") return m_fnInc;
266     else if (name == "dec") return m_fnDec;
267 schoenebeck 3076 else if (name == "in_range") return m_fnInRange;
268 schoenebeck 2965 else if (name == "sh_left") return m_fnShLeft;
269     else if (name == "sh_right") return m_fnShRight;
270 schoenebeck 2970 else if (name == "min") return m_fnMin;
271     else if (name == "max") return m_fnMax;
272 schoenebeck 2581 return NULL;
273     }
274 schoenebeck 2588
275 schoenebeck 2594 std::map<String,VMIntRelPtr*> ScriptVM::builtInIntVariables() {
276     return std::map<String,VMIntRelPtr*>();
277     }
278    
279     std::map<String,VMInt8Array*> ScriptVM::builtInIntArrayVariables() {
280     return std::map<String,VMInt8Array*>();
281     }
282    
283 schoenebeck 2942 std::map<String,VMDynVar*> ScriptVM::builtInDynamicVariables() {
284     std::map<String,VMDynVar*> m;
285    
286     m["$NKSP_PERF_TIMER"] = m_varPerfTimer;
287     m["$NKSP_REAL_TIMER"] = m_varRealTimer;
288     m["$KSP_TIMER"] = m_varRealTimer;
289    
290     return m;
291     }
292    
293 schoenebeck 2594 std::map<String,int> ScriptVM::builtInConstIntVariables() {
294 schoenebeck 2948 std::map<String,int> m;
295    
296     m["$NI_CB_TYPE_INIT"] = VM_EVENT_HANDLER_INIT;
297     m["$NI_CB_TYPE_NOTE"] = VM_EVENT_HANDLER_NOTE;
298     m["$NI_CB_TYPE_RELEASE"] = VM_EVENT_HANDLER_RELEASE;
299     m["$NI_CB_TYPE_CONTROLLER"] = VM_EVENT_HANDLER_CONTROLLER;
300    
301     return m;
302 schoenebeck 2594 }
303    
304 schoenebeck 2879 VMEventHandler* ScriptVM::currentVMEventHandler() {
305     return m_eventHandler;
306     }
307    
308 schoenebeck 2588 VMParserContext* ScriptVM::currentVMParserContext() {
309     return m_parserContext;
310     }
311    
312 schoenebeck 2581 VMExecContext* ScriptVM::currentVMExecContext() {
313 schoenebeck 2588 if (!m_parserContext) return NULL;
314     return m_parserContext->execContext;
315 schoenebeck 2581 }
316    
317 schoenebeck 2974 void ScriptVM::setAutoSuspendEnabled(bool b) {
318     m_autoSuspend = b;
319     }
320    
321     bool ScriptVM::isAutoSuspendEnabled() const {
322     return m_autoSuspend;
323     }
324    
325 schoenebeck 2588 VMExecStatus_t ScriptVM::exec(VMParserContext* parserContext, VMExecContext* execContex, VMEventHandler* handler) {
326     m_parserContext = dynamic_cast<ParserContext*>(parserContext);
327     if (!m_parserContext) {
328     std::cerr << "No VM parser context provided. Did you load a script?.\n";
329 schoenebeck 2581 return VMExecStatus_t(VM_EXEC_NOT_RUNNING | VM_EXEC_ERROR);
330     }
331    
332 schoenebeck 2611 // a ParserContext object is always tied to exactly one ScriptVM object
333     assert(m_parserContext->functionProvider == this);
334    
335 schoenebeck 2581 ExecContext* ctx = dynamic_cast<ExecContext*>(execContex);
336     if (!ctx) {
337     std::cerr << "Invalid VM exec context.\n";
338     return VMExecStatus_t(VM_EXEC_NOT_RUNNING | VM_EXEC_ERROR);
339     }
340     EventHandler* h = dynamic_cast<EventHandler*>(handler);
341     if (!h) return VM_EXEC_NOT_RUNNING;
342 schoenebeck 2879 m_eventHandler = handler;
343 schoenebeck 2581
344 schoenebeck 2588 m_parserContext->execContext = ctx;
345 schoenebeck 2581
346     ctx->status = VM_EXEC_RUNNING;
347     StmtFlags_t flags = STMT_SUCCESS;
348 schoenebeck 2974 int instructionsCounter = 0;
349 schoenebeck 2581
350     int& frameIdx = ctx->stackFrame;
351     if (frameIdx < 0) { // start condition ...
352     frameIdx = -1;
353     ctx->pushStack(h);
354     }
355    
356     while (flags == STMT_SUCCESS && frameIdx >= 0) {
357     if (frameIdx >= ctx->stack.size()) { // should never happen, otherwise it's a bug ...
358     std::cerr << "CRITICAL: VM stack overflow! (" << frameIdx << ")\n";
359     flags = StmtFlags_t(STMT_ABORT_SIGNALLED | STMT_ERROR_OCCURRED);
360     break;
361     }
362    
363     ExecContext::StackFrame& frame = ctx->stack[frameIdx];
364     switch (frame.statement->statementType()) {
365     case STMT_LEAF: {
366     #if DEBUG_SCRIPTVM_CORE
367     _printIndents(frameIdx);
368     printf("-> STMT_LEAF\n");
369     #endif
370     LeafStatement* leaf = (LeafStatement*) frame.statement;
371     flags = leaf->exec();
372     ctx->popStack();
373     break;
374     }
375    
376     case STMT_LIST: {
377     #if DEBUG_SCRIPTVM_CORE
378     _printIndents(frameIdx);
379     printf("-> STMT_LIST subidx=%d\n", frame.subindex);
380     #endif
381     Statements* stmts = (Statements*) frame.statement;
382     if (stmts->statement(frame.subindex)) {
383     ctx->pushStack(
384     stmts->statement(frame.subindex++)
385     );
386     } else {
387     #if DEBUG_SCRIPTVM_CORE
388     _printIndents(frameIdx);
389     printf("[END OF LIST] subidx=%d\n", frame.subindex);
390     #endif
391     ctx->popStack();
392     }
393     break;
394     }
395    
396     case STMT_BRANCH: {
397     #if DEBUG_SCRIPTVM_CORE
398     _printIndents(frameIdx);
399     printf("-> STMT_BRANCH\n");
400     #endif
401     if (frame.subindex < 0) ctx->popStack();
402     else {
403     BranchStatement* branchStmt = (BranchStatement*) frame.statement;
404     frame.subindex = branchStmt->evalBranch();
405     if (frame.subindex >= 0) {
406     ctx->pushStack(
407     branchStmt->branch(frame.subindex)
408     );
409     frame.subindex = -1;
410     } else ctx->popStack();
411     }
412     break;
413     }
414    
415     case STMT_LOOP: {
416     #if DEBUG_SCRIPTVM_CORE
417     _printIndents(frameIdx);
418     printf("-> STMT_LOOP\n");
419     #endif
420     While* whileStmt = (While*) frame.statement;
421     if (whileStmt->evalLoopStartCondition() && whileStmt->statements()) {
422     ctx->pushStack(
423     whileStmt->statements()
424     );
425 schoenebeck 2974 if (flags == STMT_SUCCESS && m_autoSuspend &&
426     instructionsCounter > SCRIPTVM_MAX_INSTR_PER_CYCLE_SOFT)
427     {
428     flags = StmtFlags_t(STMT_SUSPEND_SIGNALLED);
429     ctx->suspendMicroseconds = SCRIPT_VM_FORCE_SUSPENSION_MICROSECONDS;
430     }
431 schoenebeck 2581 } else ctx->popStack();
432 schoenebeck 2974 break;
433 schoenebeck 2581 }
434     }
435 schoenebeck 2974
436     if (flags == STMT_SUCCESS && m_autoSuspend &&
437     instructionsCounter > SCRIPTVM_MAX_INSTR_PER_CYCLE_HARD)
438     {
439     flags = StmtFlags_t(STMT_SUSPEND_SIGNALLED);
440     ctx->suspendMicroseconds = SCRIPT_VM_FORCE_SUSPENSION_MICROSECONDS;
441     }
442    
443     ++instructionsCounter;
444 schoenebeck 2581 }
445    
446     if (flags & STMT_SUSPEND_SIGNALLED) {
447     ctx->status = VM_EXEC_SUSPENDED;
448     } else {
449     ctx->status = VM_EXEC_NOT_RUNNING;
450     if (flags & STMT_ERROR_OCCURRED)
451     ctx->status = VM_EXEC_ERROR;
452     ctx->reset();
453     }
454    
455 schoenebeck 2879 m_eventHandler = NULL;
456 schoenebeck 2588 m_parserContext->execContext = NULL;
457     m_parserContext = NULL;
458 schoenebeck 2581 return ctx->status;
459     }
460    
461     } // namespace LinuxSampler

  ViewVC Help
Powered by ViewVC