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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3551 - (show annotations) (download)
Thu Aug 1 10:22:56 2019 UTC (4 years, 8 months ago) by schoenebeck
File size: 19549 byte(s)
* Added test cases for NKSP core language aspects and core built-in
  functions.
* NKSP: Added method ScriptVM::setExitResultEnabled() which allows
  to explicitly enable the built-in exit() function to optionally
  accept one function argument; the value of the passed exit()
  function argument will then become available by calling
  VMExecContext::exitResult() after script execution.
* Bumped version (2.1.1.svn2).

1 /*
2 * Copyright (c) 2014 - 2019 Christian Schoenebeck
3 *
4 * http://www.linuxsampler.org
5 *
6 * This file is part of LinuxSampler and released under the same terms.
7 * See README file for details.
8 */
9
10 #include "ScriptVM.h"
11
12 #include <string.h>
13 #include <assert.h>
14 #include "../common/global_private.h"
15 #include "tree.h"
16 #include "CoreVMFunctions.h"
17 #include "CoreVMDynVars.h"
18 #include "editor/NkspScanner.h"
19
20 #define DEBUG_SCRIPTVM_CORE 0
21
22 /**
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 int InstrScript_parse(LinuxSampler::ParserContext*);
60
61 namespace LinuxSampler {
62
63 #if DEBUG_SCRIPTVM_CORE
64 static void _printIndents(int n) {
65 for (int i = 0; i < n; ++i) printf(" ");
66 fflush(stdout);
67 }
68 #endif
69
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 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 }
133
134 return 1; // actually just to avoid compiler warning
135 }
136
137 static int _requiredMaxStackSizeFor(EventHandlers* handlers) {
138 int max = 1;
139 for (int i = 0; i < handlers->size(); ++i) {
140 int size = _requiredMaxStackSizeFor(handlers->eventHandler(i));
141 if (max < size) max = size;
142 }
143 return max;
144 }
145
146 ScriptVM::ScriptVM() :
147 m_eventHandler(NULL), m_parserContext(NULL), m_autoSuspend(true),
148 m_acceptExitRes(false)
149 {
150 m_fnMessage = new CoreVMFunction_message;
151 m_fnExit = new CoreVMFunction_exit(this);
152 m_fnWait = new CoreVMFunction_wait(this);
153 m_fnAbs = new CoreVMFunction_abs;
154 m_fnRandom = new CoreVMFunction_random;
155 m_fnNumElements = new CoreVMFunction_num_elements;
156 m_fnInc = new CoreVMFunction_inc;
157 m_fnDec = new CoreVMFunction_dec;
158 m_fnInRange = new CoreVMFunction_in_range;
159 m_varRealTimer = new CoreVMDynVar_NKSP_REAL_TIMER;
160 m_varPerfTimer = new CoreVMDynVar_NKSP_PERF_TIMER;
161 m_fnShLeft = new CoreVMFunction_sh_left;
162 m_fnShRight = new CoreVMFunction_sh_right;
163 m_fnMin = new CoreVMFunction_min;
164 m_fnMax = new CoreVMFunction_max;
165 m_fnArrayEqual = new CoreVMFunction_array_equal;
166 m_fnSearch = new CoreVMFunction_search;
167 m_fnSort = new CoreVMFunction_sort;
168 }
169
170 ScriptVM::~ScriptVM() {
171 delete m_fnMessage;
172 delete m_fnExit;
173 delete m_fnWait;
174 delete m_fnAbs;
175 delete m_fnRandom;
176 delete m_fnNumElements;
177 delete m_fnInc;
178 delete m_fnDec;
179 delete m_fnInRange;
180 delete m_fnShLeft;
181 delete m_fnShRight;
182 delete m_fnMin;
183 delete m_fnMax;
184 delete m_fnArrayEqual;
185 delete m_fnSearch;
186 delete m_fnSort;
187 delete m_varRealTimer;
188 delete m_varPerfTimer;
189 }
190
191 VMParserContext* ScriptVM::loadScript(const String& s) {
192 std::istringstream iss(s);
193 return loadScript(&iss);
194 }
195
196 VMParserContext* ScriptVM::loadScript(std::istream* is) {
197 ParserContext* context = new ParserContext(this);
198 //printf("parserCtx=0x%lx\n", (uint64_t)context);
199
200 context->registerBuiltInConstIntVariables( builtInConstIntVariables() );
201 context->registerBuiltInIntVariables( builtInIntVariables() );
202 context->registerBuiltInIntArrayVariables( builtInIntArrayVariables() );
203 context->registerBuiltInDynVariables( builtInDynamicVariables() );
204
205 context->createScanner(is);
206
207 InstrScript_parse(context);
208 dmsg(2,("Allocating %ld bytes of global int VM memory.\n", long(context->globalIntVarCount * sizeof(int))));
209 dmsg(2,("Allocating %d of global VM string variables.\n", context->globalStrVarCount));
210 if (!context->globalIntMemory)
211 context->globalIntMemory = new ArrayList<int>();
212 if (!context->globalStrMemory)
213 context->globalStrMemory = new ArrayList<String>();
214 context->globalIntMemory->resize(context->globalIntVarCount);
215 memset(&((*context->globalIntMemory)[0]), 0, context->globalIntVarCount * sizeof(int));
216
217 context->globalStrMemory->resize(context->globalStrVarCount);
218
219 context->destroyScanner();
220
221 return context;
222 }
223
224 void ScriptVM::dumpParsedScript(VMParserContext* context) {
225 ParserContext* ctx = dynamic_cast<ParserContext*>(context);
226 if (!ctx) {
227 std::cerr << "No VM context. So nothing to dump.\n";
228 return;
229 }
230 if (!ctx->handlers) {
231 std::cerr << "No event handlers defined in script. So nothing to dump.\n";
232 return;
233 }
234 if (!ctx->globalIntMemory) {
235 std::cerr << "Internal error: no global memory assigend to script VM.\n";
236 return;
237 }
238 ctx->handlers->dump();
239 }
240
241 VMExecContext* ScriptVM::createExecContext(VMParserContext* parserContext) {
242 ParserContext* parserCtx = dynamic_cast<ParserContext*>(parserContext);
243 ExecContext* execCtx = new ExecContext();
244
245 if (parserCtx->requiredMaxStackSize < 0) {
246 parserCtx->requiredMaxStackSize =
247 _requiredMaxStackSizeFor(&*parserCtx->handlers);
248 }
249 execCtx->stack.resize(parserCtx->requiredMaxStackSize);
250 dmsg(2,("Created VM exec context with %ld bytes VM stack size.\n",
251 long(parserCtx->requiredMaxStackSize * sizeof(ExecContext::StackFrame))));
252 //printf("execCtx=0x%lx\n", (uint64_t)execCtx);
253 const int polySize = parserCtx->polyphonicIntVarCount;
254 execCtx->polyphonicIntMemory.resize(polySize);
255 memset(&execCtx->polyphonicIntMemory[0], 0, polySize * sizeof(int));
256
257 dmsg(2,("Allocated %ld bytes polyphonic memory.\n", long(polySize * sizeof(int))));
258 return execCtx;
259 }
260
261 std::vector<VMSourceToken> ScriptVM::syntaxHighlighting(const String& s) {
262 std::istringstream iss(s);
263 return syntaxHighlighting(&iss);
264 }
265
266 std::vector<VMSourceToken> ScriptVM::syntaxHighlighting(std::istream* is) {
267 try {
268 NkspScanner scanner(is);
269 std::vector<SourceToken> tokens = scanner.tokens();
270 std::vector<VMSourceToken> result;
271 result.resize(tokens.size());
272 for (int i = 0; i < tokens.size(); ++i) {
273 SourceToken* st = new SourceToken;
274 *st = tokens[i];
275 result[i] = VMSourceToken(st);
276 }
277 return result;
278 } catch (...) {
279 return std::vector<VMSourceToken>();
280 }
281 }
282
283 VMFunction* ScriptVM::functionByName(const String& name) {
284 if (name == "message") return m_fnMessage;
285 else if (name == "exit") return m_fnExit;
286 else if (name == "wait") return m_fnWait;
287 else if (name == "abs") return m_fnAbs;
288 else if (name == "random") return m_fnRandom;
289 else if (name == "num_elements") return m_fnNumElements;
290 else if (name == "inc") return m_fnInc;
291 else if (name == "dec") return m_fnDec;
292 else if (name == "in_range") return m_fnInRange;
293 else if (name == "sh_left") return m_fnShLeft;
294 else if (name == "sh_right") return m_fnShRight;
295 else if (name == "min") return m_fnMin;
296 else if (name == "max") return m_fnMax;
297 else if (name == "array_equal") return m_fnArrayEqual;
298 else if (name == "search") return m_fnSearch;
299 else if (name == "sort") return m_fnSort;
300 return NULL;
301 }
302
303 bool ScriptVM::isFunctionDisabled(VMFunction* fn, VMParserContext* ctx) {
304 ParserContext* parserCtx = dynamic_cast<ParserContext*>(ctx);
305 if (!parserCtx) return false;
306
307 if (fn == m_fnMessage && parserCtx->userPreprocessorConditions.count("NKSP_NO_MESSAGE"))
308 return true;
309
310 return false;
311 }
312
313 std::map<String,VMIntRelPtr*> ScriptVM::builtInIntVariables() {
314 return std::map<String,VMIntRelPtr*>();
315 }
316
317 std::map<String,VMInt8Array*> ScriptVM::builtInIntArrayVariables() {
318 return std::map<String,VMInt8Array*>();
319 }
320
321 std::map<String,VMDynVar*> ScriptVM::builtInDynamicVariables() {
322 std::map<String,VMDynVar*> m;
323
324 m["$NKSP_PERF_TIMER"] = m_varPerfTimer;
325 m["$NKSP_REAL_TIMER"] = m_varRealTimer;
326 m["$KSP_TIMER"] = m_varRealTimer;
327
328 return m;
329 }
330
331 std::map<String,int> ScriptVM::builtInConstIntVariables() {
332 std::map<String,int> m;
333
334 m["$NI_CB_TYPE_INIT"] = VM_EVENT_HANDLER_INIT;
335 m["$NI_CB_TYPE_NOTE"] = VM_EVENT_HANDLER_NOTE;
336 m["$NI_CB_TYPE_RELEASE"] = VM_EVENT_HANDLER_RELEASE;
337 m["$NI_CB_TYPE_CONTROLLER"] = VM_EVENT_HANDLER_CONTROLLER;
338
339 return m;
340 }
341
342 VMEventHandler* ScriptVM::currentVMEventHandler() {
343 return m_eventHandler;
344 }
345
346 VMParserContext* ScriptVM::currentVMParserContext() {
347 return m_parserContext;
348 }
349
350 VMExecContext* ScriptVM::currentVMExecContext() {
351 if (!m_parserContext) return NULL;
352 return m_parserContext->execContext;
353 }
354
355 void ScriptVM::setAutoSuspendEnabled(bool b) {
356 m_autoSuspend = b;
357 }
358
359 bool ScriptVM::isAutoSuspendEnabled() const {
360 return m_autoSuspend;
361 }
362
363 void ScriptVM::setExitResultEnabled(bool b) {
364 m_acceptExitRes = b;
365 }
366
367 bool ScriptVM::isExitResultEnabled() const {
368 return m_acceptExitRes;
369 }
370
371 VMExecStatus_t ScriptVM::exec(VMParserContext* parserContext, VMExecContext* execContex, VMEventHandler* handler) {
372 m_parserContext = dynamic_cast<ParserContext*>(parserContext);
373 if (!m_parserContext) {
374 std::cerr << "No VM parser context provided. Did you load a script?.\n";
375 return VMExecStatus_t(VM_EXEC_NOT_RUNNING | VM_EXEC_ERROR);
376 }
377
378 // a ParserContext object is always tied to exactly one ScriptVM object
379 assert(m_parserContext->functionProvider == this);
380
381 ExecContext* ctx = dynamic_cast<ExecContext*>(execContex);
382 if (!ctx) {
383 std::cerr << "Invalid VM exec context.\n";
384 return VMExecStatus_t(VM_EXEC_NOT_RUNNING | VM_EXEC_ERROR);
385 }
386 EventHandler* h = dynamic_cast<EventHandler*>(handler);
387 if (!h) return VM_EXEC_NOT_RUNNING;
388 m_eventHandler = handler;
389
390 m_parserContext->execContext = ctx;
391
392 ctx->status = VM_EXEC_RUNNING;
393 ctx->instructionsCount = 0;
394 ctx->clearExitRes();
395 StmtFlags_t& flags = ctx->flags;
396 int instructionsCounter = 0;
397 int synced = m_autoSuspend ? 0 : 1;
398
399 int& frameIdx = ctx->stackFrame;
400 if (frameIdx < 0) { // start condition ...
401 frameIdx = -1;
402 ctx->pushStack(h);
403 }
404
405 while (flags == STMT_SUCCESS && frameIdx >= 0) {
406 if (frameIdx >= ctx->stack.size()) { // should never happen, otherwise it's a bug ...
407 std::cerr << "CRITICAL: VM stack overflow! (" << frameIdx << ")\n";
408 flags = StmtFlags_t(STMT_ABORT_SIGNALLED | STMT_ERROR_OCCURRED);
409 break;
410 }
411
412 ExecContext::StackFrame& frame = ctx->stack[frameIdx];
413 switch (frame.statement->statementType()) {
414 case STMT_LEAF: {
415 #if DEBUG_SCRIPTVM_CORE
416 _printIndents(frameIdx);
417 printf("-> STMT_LEAF\n");
418 #endif
419 LeafStatement* leaf = (LeafStatement*) frame.statement;
420 flags = leaf->exec();
421 ctx->popStack();
422 break;
423 }
424
425 case STMT_LIST: {
426 #if DEBUG_SCRIPTVM_CORE
427 _printIndents(frameIdx);
428 printf("-> STMT_LIST subidx=%d\n", frame.subindex);
429 #endif
430 Statements* stmts = (Statements*) frame.statement;
431 if (stmts->statement(frame.subindex)) {
432 ctx->pushStack(
433 stmts->statement(frame.subindex++)
434 );
435 } else {
436 #if DEBUG_SCRIPTVM_CORE
437 _printIndents(frameIdx);
438 printf("[END OF LIST] subidx=%d\n", frame.subindex);
439 #endif
440 ctx->popStack();
441 }
442 break;
443 }
444
445 case STMT_BRANCH: {
446 #if DEBUG_SCRIPTVM_CORE
447 _printIndents(frameIdx);
448 printf("-> STMT_BRANCH\n");
449 #endif
450 if (frame.subindex < 0) ctx->popStack();
451 else {
452 BranchStatement* branchStmt = (BranchStatement*) frame.statement;
453 frame.subindex = branchStmt->evalBranch();
454 if (frame.subindex >= 0) {
455 ctx->pushStack(
456 branchStmt->branch(frame.subindex)
457 );
458 frame.subindex = -1;
459 } else ctx->popStack();
460 }
461 break;
462 }
463
464 case STMT_LOOP: {
465 #if DEBUG_SCRIPTVM_CORE
466 _printIndents(frameIdx);
467 printf("-> STMT_LOOP\n");
468 #endif
469 While* whileStmt = (While*) frame.statement;
470 if (whileStmt->evalLoopStartCondition() && whileStmt->statements()) {
471 ctx->pushStack(
472 whileStmt->statements()
473 );
474 if (flags == STMT_SUCCESS && !synced &&
475 instructionsCounter > SCRIPTVM_MAX_INSTR_PER_CYCLE_SOFT)
476 {
477 flags = StmtFlags_t(STMT_SUSPEND_SIGNALLED);
478 ctx->suspendMicroseconds = SCRIPT_VM_FORCE_SUSPENSION_MICROSECONDS;
479 }
480 } else ctx->popStack();
481 break;
482 }
483
484 case STMT_SYNC: {
485 #if DEBUG_SCRIPTVM_CORE
486 _printIndents(frameIdx);
487 printf("-> STMT_SYNC\n");
488 #endif
489 SyncBlock* syncStmt = (SyncBlock*) frame.statement;
490 if (!frame.subindex++ && syncStmt->statements()) {
491 ++synced;
492 ctx->pushStack(
493 syncStmt->statements()
494 );
495 } else {
496 ctx->popStack();
497 --synced;
498 }
499 break;
500 }
501 }
502
503 if (flags == STMT_SUCCESS && !synced &&
504 instructionsCounter > SCRIPTVM_MAX_INSTR_PER_CYCLE_HARD)
505 {
506 flags = StmtFlags_t(STMT_SUSPEND_SIGNALLED);
507 ctx->suspendMicroseconds = SCRIPT_VM_FORCE_SUSPENSION_MICROSECONDS;
508 }
509
510 ++instructionsCounter;
511 }
512
513 if ((flags & STMT_SUSPEND_SIGNALLED) && !(flags & STMT_ABORT_SIGNALLED)) {
514 ctx->status = VM_EXEC_SUSPENDED;
515 ctx->flags = STMT_SUCCESS;
516 } else {
517 ctx->status = VM_EXEC_NOT_RUNNING;
518 if (flags & STMT_ERROR_OCCURRED)
519 ctx->status = VM_EXEC_ERROR;
520 ctx->reset();
521 }
522
523 ctx->instructionsCount = instructionsCounter;
524
525 m_eventHandler = NULL;
526 m_parserContext->execContext = NULL;
527 m_parserContext = NULL;
528 return ctx->status;
529 }
530
531 } // namespace LinuxSampler

  ViewVC Help
Powered by ViewVC