/[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 3573 - (show annotations) (download)
Tue Aug 27 21:36:53 2019 UTC (4 years, 7 months ago) by schoenebeck
File size: 20705 byte(s)
NKSP: Introducing floating point support.

* NKSP language: Added support for NKSP real number literals and
  arithmetic operations on them (e.g. "(3.9 + 2.9) / 12.3 - 42.0").

* NKSP language: Added support for NKSP real number (floating point)
  script variables (declare ~foo := 3.4).

* NKSP language: Added support for NKSP real number (floating point)
  array script variables (declare ?foo[3] := ( 1.1, 2.7, 49.0 )).

* NKSP built-in script function "message()" accepts now real number
  argument as well.

* Added built-in NKSP script function "real_to_int()" and its short
  hand form "int()" for casting from real number to integer in NKSP
  scripts.

* Added built-in NKSP script function "int_to_real()" and its short
  hand form "real()" for casting from integer to real number in NKSP
  scripts.

* Bumped version (2.1.1.svn6).

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

  ViewVC Help
Powered by ViewVC