Debian Codegraph @

src/transition/script.c

raw symbols SCIP
1 // SPDX-License-Identifier: MPL-2.0
2 // Copyright (c) Yuxuan Shui <[email protected]>
3
4 #include <stdbool.h>
5 #include <stddef.h>
6
7 #include <libconfig.h>
8 #include <uthash.h>
9
10 #include "utils/dynarr.h"
11 #include "utils/list.h"
12 #include "utils/str.h"
13 #include "utils/uthash_extra.h"
14
15 #include "curve.h"
16 #include "script.h"
17 #include "script_internal.h"
18
19 #define X(x) [x] = #x,
20 static const char *op_names[] = {OPERATORS};
21 #undef X
22
23 struct fragment {
24 struct list_node siblings;
25 /// If `once` is true, this is the succeeding fragment if
26 /// this fragment is executed.
27 struct fragment *once_next;
28 /// The succeeding fragment of this fragment. If `once` is true, this is the
29 /// succeeding fragment if this fragment is NOT executed.
30 struct fragment *next;
31 /// Number of instructions
32 unsigned ninstrs;
33 /// The address of the first instruction of this fragment in compiled script.
34 /// For `once` fragments, this is the address of the branch instruction.
35 unsigned addr;
36 /// Whether code is generated for this fragment. 0 = not emitted, 1 = emitted, 2 =
37 /// in queue
38 bool emitted;
39 struct instruction instrs[];
40 };
41
42 /// Represent a variable during compilation. Contains a sequence of fragments, and
43 /// dependency of this variable.
44 struct compilation_stack {
45 struct fragment *entry_point;
46 struct fragment **exit;
47 unsigned index;
48 /// Number of dependencies
49 unsigned ndeps;
50 /// Whether the fragments loads from execution context
51 bool need_context;
52 /// Dependencies
53 unsigned deps[];
54 };
55
56 struct script_compile_context {
57 struct script_context_info_internal *context_info;
58 struct variable_allocation *vars;
59 struct overridable_slot *overrides;
60 /// The memory slot for storing the elapsed time.
61 /// The next slot after this is used for storing the total duration of the script.
62 unsigned elapsed_slot;
63 unsigned allocated_slots;
64 unsigned max_stack;
65 const char *current_variable_name;
66 int *compiled;
67 struct list_node all_fragments;
68 struct fragment **tail, *head;
69 /// Fragments that can be executed once at the beginning of the execution.
70 /// For example, storing imms into memory slots.
71 struct fragment **once_tail;
72 /// Fragments that should be executed once at the end of the first execution.
73 struct fragment **once_end_tail, *once_end_head;
74 };
75
76 static const char operators[] = "+-*/^";
77 static const enum op operator_types[] = {OP_ADD, OP_SUB, OP_MUL, OP_DIV, OP_EXP};
78 static const int operator_pre[] = {0, 0, 1, 1, 2};
79
80 static void log_instruction_(enum log_level level, const char *func, unsigned index,
81 const struct instruction *inst) {
82 if (log_get_level_tls() > level) {
83 return;
84 }
85 #define logv(fmt, ...) log_printf(tls_logger, level, func, "%u: " fmt, index, __VA_ARGS__)
86 switch (inst->type) {
87 case INST_IMM: logv("imm %f", inst->imm); break;
88 case INST_BRANCH: logv("br %d", inst->rel); break;
89 case INST_BRANCH_ONCE: logv("br_once %d", inst->rel); break;
90 case INST_HALT: log_printf(tls_logger, level, func, "%u: halt", index); break;
91 case INST_CURVE: log_printf(tls_logger, level, func, "%u: curve", index); break;
92 case INST_OP: logv("op %s", op_names[inst->op]); break;
93 case INST_LOAD: logv("load %u", inst->slot); break;
94 case INST_STORE: logv("store %u", inst->slot); break;
95 case INST_STORE_OVER_NAN: logv("store/nan %u", inst->slot); break;
96 case INST_LOAD_CTX: logv("load_ctx *(%td)", inst->ctx); break;
97 }
98 #undef logv
99 }
100 #define log_instruction(level, i, inst) \
101 log_instruction_(LOG_LEVEL_##level, __func__, i, &(inst))
102
103 char *instruction_to_c(struct instruction i) {
104 char *buf = NULL;
105 switch (i.type) {
106 case INST_IMM: casprintf(&buf, "{.type = INST_IMM, .imm = %a},", i.imm); break;
107 case INST_BRANCH:
108 casprintf(&buf, "{.type = INST_BRANCH, .rel = %d},", i.rel);
109 break;
110 case INST_BRANCH_ONCE:
111 casprintf(&buf, "{.type = INST_BRANCH_ONCE, .rel = %d},", i.rel);
112 break;
113 case INST_HALT: casprintf(&buf, "{.type = INST_HALT},"); break;
114 case INST_CURVE:;
115 char *curve = curve_to_c(&i.curve);
116 casprintf(&buf, "{.type = INST_CURVE, .curve = %s},", curve);
117 free(curve);
118 break;
119 case INST_OP:
120 casprintf(&buf, "{.type = INST_OP, .op = %s},", op_names[i.op]);
121 break;
122 case INST_LOAD:
123 casprintf(&buf, "{.type = INST_LOAD, .slot = %u},", i.slot);
124 break;
125 case INST_STORE:
126 casprintf(&buf, "{.type = INST_STORE, .slot = %u},", i.slot);
127 break;
128 case INST_STORE_OVER_NAN:
129 casprintf(&buf, "{.type = INST_STORE_OVER_NAN, .slot = %u},", i.slot);
130 break;
131 case INST_LOAD_CTX:
132 casprintf(&buf, "{.type = INST_LOAD_CTX, .ctx = %td},", i.ctx);
133 break;
134 }
135 return buf;
136 }
137
138 static char parse_op(const char *input_str, const char **end, char **err) {
139 char *op = strchr(operators, input_str[0]);
140 *err = NULL;
141 if (op != NULL) {
142 *end = input_str + 1;
143 return input_str[0];
144 }
145
146 casprintf(err, "Expected one of \"%s\", got '%c'.", operators, input_str[0]);
147 *end = input_str;
148 return 0;
149 }
150
151 static enum op char_to_op(char ch) {
152 char *op = strchr(operators, ch);
153 BUG_ON(op == NULL);
154 return operator_types[op - operators];
155 }
156
157 struct script_context_info_internal {
158 UT_hash_handle hh;
159 struct script_context_info info;
160 };
161
162 struct expression_parser_context {
163 char *op_stack;
164 struct compilation_stack *entry;
165 size_t len;
166
167 unsigned op_top, operand_top;
168 bool need_context;
169 };
170
171 /// Parse a number or a variable. Variable can optionally be prefixed with a minus sign.
172 static void
173 parse_raw_operand(struct expression_parser_context *ctx, const char *str, const char **end,
174 struct script_compile_context *script_ctx, char **err) {
175 double number = strtod_simple(str, end);
176 auto expr = ctx->entry->entry_point;
177 *err = NULL;
178 if (*end != str) {
179 expr->instrs[expr->ninstrs++] = (struct instruction){
180 .type = INST_IMM,
181 .imm = number,
182 };
183 return;
184 }
185 bool neg = false;
186 bool succeeded = false;
187 if (**end == '-') {
188 neg = true;
189 str = skip_space(str + 1);
190 *end = str;
191 }
192 while (**end) {
193 if (isalnum(**end) || **end == '-' || **end == '_') {
194 succeeded = true;
195 (*end)++;
196 } else {
197 break;
198 }
199 }
200 if (!succeeded) {
201 casprintf(err, "Expected a number or a variable name, got \"%s\".", str);
202 *end = str;
203 return;
204 }
205 struct variable_allocation *var = NULL;
206 struct script_context_info_internal *exe_ctx = NULL;
207 HASH_FIND(hh, script_ctx->vars, str, (unsigned long)(*end - str), var);
208 HASH_FIND(hh, script_ctx->context_info, str, (unsigned long)(*end - str), exe_ctx);
209 if (var != NULL) {
210 expr->instrs[expr->ninstrs++] = (struct instruction){
211 .type = INST_LOAD,
212 .slot = var->slot,
213 };
214 ctx->entry->deps[ctx->entry->ndeps++] = var->index;
215 } else if (exe_ctx != NULL) {
216 expr->instrs[expr->ninstrs++] = (struct instruction){
217 .type = INST_LOAD_CTX,
218 .ctx = exe_ctx->info.offset,
219 };
220 ctx->need_context = true;
221 } else {
222 casprintf(err, "variable name \"%.*s\" is not defined", (int)(*end - str), str);
223 *end = str;
224 return;
225 }
226
227 if (neg) {
228 expr->instrs[expr->ninstrs++] = (struct instruction){
229 .type = INST_OP,
230 .op = OP_NEG,
231 };
232 }
233 }
234 static inline double op_eval(double l, enum op op, double r) {
235 switch (op) {
236 case OP_ADD: return l + r;
237 case OP_SUB: return l - r;
238 case OP_DIV: return l / r;
239 case OP_MUL: return l * r;
240 case OP_EXP: return pow(l, r);
241 case OP_NEG: return -l;
242 case OP_MAX: return max2(l, r);
243 }
244 unreachable();
245 }
246 static bool pop_op(const char *input_str, struct expression_parser_context *ctx, char **err) {
247 if (ctx->operand_top < 2) {
248 casprintf(err, "Missing operand for operator %c, in expression %s",
249 ctx->op_stack[ctx->op_top - 1], input_str);
250 return false;
251 }
252 auto f = ctx->entry->entry_point;
253 // Both operands are immediates, do constant propagation.
254 if (f->instrs[f->ninstrs - 1].type == INST_IMM &&
255 f->instrs[f->ninstrs - 2].type == INST_IMM) {
256 double imm = op_eval(f->instrs[f->ninstrs - 1].imm,
257 char_to_op(ctx->op_stack[ctx->op_top]),
258 f->instrs[f->ninstrs - 2].imm);
259 ctx->operand_top -= 1;
260 f->instrs[f->ninstrs - 2].imm = imm;
261 f->ninstrs -= 1;
262 ctx->op_top -= 1;
263 return true;
264 }
265 f->instrs[f->ninstrs].type = INST_OP;
266 f->instrs[f->ninstrs].op = char_to_op(ctx->op_stack[ctx->op_top - 1]);
267 f->ninstrs += 1;
268 ctx->op_top -= 1;
269 ctx->operand_top -= 1;
270 return true;
271 }
272
273 /// Parse an operand surrounded by some parenthesis:
274 /// `(((((var))` or `(((var` or `var)))`
275 static bool parse_operand_or_paren(struct expression_parser_context *ctx,
276 const char *input_str, const char **end,
277 struct script_compile_context *script_ctx, char **err) {
278 const char *str = input_str;
279 while (*str == '(') {
280 str = skip_space(str + 1);
281 ctx->op_stack[ctx->op_top++] = '(';
282 }
283
284 parse_raw_operand(ctx, str, end, script_ctx, err);
285 if (str == *end) {
286 return false;
287 }
288 str = skip_space(*end);
289 ctx->operand_top += 1;
290 if (ctx->operand_top > script_ctx->max_stack) {
291 script_ctx->max_stack = ctx->operand_top;
292 }
293
294 while (*str == ')') {
295 while (ctx->op_top > 0 && ctx->op_stack[ctx->op_top - 1] != '(') {
296 if (!pop_op(str, ctx, err)) {
297 return false;
298 }
299 }
300 if (ctx->op_top == 0) {
301 casprintf(err, "Unmatched ')' in expression \"%s\"", input_str);
302 return false;
303 }
304 ctx->op_top -= 1;
305 str = skip_space(str + 1);
306 }
307 *end = str;
308 return true;
309 }
310
311 static struct fragment *fragment_new(struct script_compile_context *ctx, unsigned ninstrs) {
312 struct fragment *fragment = calloc(
313 1, sizeof(struct fragment) + sizeof(struct instruction[max2(1, ninstrs)]));
314 allocchk(fragment);
315 list_insert_after(&ctx->all_fragments, &fragment->siblings);
316 return fragment;
317 }
318
319 /// Precedence based expression parser. Prepend fragments to `stack_entry`, or allocate a
320 /// new one if `stack_entry` is NULL.
321 static bool expression_compile(struct compilation_stack **stack_entry, const char *input_str,
322 struct script_compile_context *script_ctx, unsigned slot,
323 bool allow_override, char **err) {
324 const char *str = skip_space(input_str);
325 const size_t len = strlen(str);
326 BUG_ON(len > UINT_MAX);
327 if (len == 0) {
328 return false;
329 }
330 // At most each character in `input_str` could map to an individual instruction
331 auto fragment = fragment_new(script_ctx, (unsigned)len + 1);
332 if (!*stack_entry) {
333 *stack_entry =
334 calloc(1, sizeof(struct compilation_stack) + sizeof(unsigned[len]));
335 (*stack_entry)->exit = &fragment->next;
336 } else {
337 fragment->next = (*stack_entry)->entry_point;
338 }
339 (*stack_entry)->entry_point = fragment;
340
341 struct expression_parser_context ctx = {
342 .op_stack = ccalloc(len, char),
343 .entry = *stack_entry,
344 .op_top = 0,
345 .operand_top = 0,
346 };
347 const char *end = NULL;
348 bool succeeded = false;
349 if (!parse_operand_or_paren(&ctx, str, &end, script_ctx, err)) {
350 goto end;
351 }
352
353 str = end;
354 while (*str) {
355 str = skip_space(str);
356
357 char new_op = parse_op(str, &end, err);
358 if (str == end) {
359 goto end;
360 }
361 str = skip_space(end);
362
363 int pre = operator_pre[char_to_op(new_op)];
364 while (ctx.op_top > 0 && ctx.op_stack[ctx.op_top - 1] != '(' &&
365 pre <= operator_pre[char_to_op(ctx.op_stack[ctx.op_top - 1])]) {
366 if (!pop_op(input_str, &ctx, err)) {
367 goto end;
368 }
369 }
370 ctx.op_stack[ctx.op_top++] = new_op;
371 if (!parse_operand_or_paren(&ctx, str, &end, script_ctx, err)) {
372 goto end;
373 }
374 str = end;
375 }
376 while (ctx.op_top != 0) {
377 if (!pop_op(input_str, &ctx, err)) {
378 goto end;
379 }
380 }
381 if (ctx.operand_top != 1) {
382 casprintf(err, "excessive operand on stack %s", input_str);
383 goto end;
384 }
385 succeeded = true;
386 // Save the value of the expression
387 // For overridable variables, we use store/nan, so caller can "pre-fill" the
388 // variable to override it.
389 fragment->instrs[fragment->ninstrs].type =
390 allow_override ? INST_STORE_OVER_NAN : INST_STORE;
391 fragment->instrs[fragment->ninstrs++].slot = slot;
392 (*stack_entry)->need_context = ctx.need_context;
393
394 end:
395 free(ctx.op_stack);
396 if (!succeeded) {
397 free(*stack_entry);
398 *stack_entry = NULL;
399 }
400 return succeeded;
401 }
402
403 static struct compilation_stack *
404 make_imm_stack_entry(struct script_compile_context *ctx, double imm, unsigned slot,
405 bool allow_override) {
406 auto fragment = fragment_new(ctx, 2);
407 fragment->ninstrs = 2;
408 fragment->instrs[0].type = INST_IMM;
409 fragment->instrs[0].imm = imm;
410 fragment->instrs[1].type = allow_override ? INST_STORE_OVER_NAN : INST_STORE;
411 fragment->instrs[1].slot = slot;
412 *ctx->once_tail = fragment;
413 ctx->once_tail = &fragment->next;
414
415 // Insert an empty fragment for the stack entry
416 fragment = fragment_new(ctx, 0);
417
418 struct compilation_stack *entry = ccalloc(1, struct compilation_stack);
419 allocchk(entry);
420 entry->entry_point = fragment;
421 entry->exit = &fragment->next;
422 return entry;
423 }
424
425 static void compilation_stack_cleanup(struct compilation_stack **stack_entry) {
426 free(*stack_entry);
427 *stack_entry = NULL;
428 }
429
430 static bool
431 transition_compile(struct compilation_stack **stack_entry, config_setting_t *setting,
432 struct script_compile_context *ctx, unsigned slot, char **out_err) {
433 int boolean = 0;
434 double number = 0;
435 struct curve curve;
436 bool reset = false;
437 char *err = NULL;
438 const char *str = NULL;
439 if (config_setting_lookup_string(setting, "curve", &str)) {
440 curve = curve_parse(str, &str, &err);
441 if (curve.type == CURVE_INVALID) {
442 casprintf(out_err, "Cannot parse curve at line %d: %s",
443 config_setting_source_line(setting), err);
444 free(err);
445 return false;
446 }
447 } else if (config_setting_lookup(setting, "curve") != NULL) {
448 casprintf(out_err, "Invalid curve definition at line %d. `curve` must be a string.",
449 config_setting_source_line(setting));
450 return false;
451 } else {
452 curve = CURVE_LINEAR_INIT;
453 }
454
455 if (config_setting_lookup_bool(setting, "reset", &boolean)) {
456 reset = boolean;
457 }
458
459 BUG_ON(ctx->allocated_slots > UINT_MAX - 1);
460
461 // The start value must take a slot, because it's overridable.
462 auto start_slot = ctx->allocated_slots;
463 ctx->allocated_slots += 1;
464 if (!reset) {
465 auto override = ccalloc(1, struct overridable_slot);
466 override->name = strdup(ctx->current_variable_name);
467 override->slot = start_slot;
468 HASH_ADD_STR(ctx->overrides, name, override);
469 }
470 cleanup(compilation_stack_cleanup) struct compilation_stack *start = NULL, *end = NULL;
471 if (config_setting_lookup_float(setting, "start", &number)) {
472 start = make_imm_stack_entry(ctx, number, start_slot, true);
473 } else if (!config_setting_lookup_string(setting, "start", &str)) {
474 casprintf(out_err,
475 "Transition definition does not contain a start value or "
476 "expression. Line %d.",
477 config_setting_source_line(setting));
478 return false;
479 } else if (!expression_compile(&start, str, ctx, start_slot, !reset, &err)) {
480 casprintf(out_err, "transition has an invalid start expression: %s Line %d.",
481 err, config_setting_source_line(setting));
482 free(err);
483 return false;
484 }
485
486 // 0 = end, 1 = duration, 2 = delay
487 struct instruction load_parameters[3];
488 if (config_setting_lookup_float(setting, "end", &number)) {
489 load_parameters[0] = (struct instruction){
490 .type = INST_IMM,
491 .imm = number,
492 };
493 } else if (!config_setting_lookup_string(setting, "end", &str)) {
494 casprintf(out_err,
495 "Transition definition does not contain a end value or "
496 "expression. Line %d.",
497 config_setting_source_line(setting));
498 return false;
499 } else {
500 BUG_ON(ctx->allocated_slots > UINT_MAX - 1);
501 auto end_slot = ctx->allocated_slots++;
502 if (!expression_compile(&end, str, ctx, end_slot, false, &err)) {
503 casprintf(out_err,
504 "Transition has an invalid end expression: %s. Line %d",
505 err, config_setting_source_line(setting));
506 free(err);
507 return false;
508 }
509 load_parameters[0] = (struct instruction){
510 .type = INST_LOAD,
511 .slot = end_slot,
512 };
513 }
514
515 if (config_setting_lookup_float(setting, "duration", &number)) {
516 if (number == 0) {
517 casprintf(out_err, "Duration must be greater than 0. Line %d.",
518 config_setting_source_line(setting));
519 return false;
520 }
521 load_parameters[1] = (struct instruction){
522 .type = INST_IMM,
523 .imm = number,
524 };
525 } else if (!config_setting_lookup_string(setting, "duration", &str)) {
526 casprintf(out_err,
527 "Transition definition does not contain a duration value or "
528 "expression. Line %d.",
529 config_setting_source_line(setting));
530 return false;
531 } else {
532 BUG_ON(ctx->allocated_slots > UINT_MAX - 1);
533 auto duration_slot = ctx->allocated_slots++;
534 if (!expression_compile(&end, str, ctx, duration_slot, false, &err)) {
535 casprintf(out_err,
536 "Transition has an invalid duration expression: %s. "
537 "Line %d",
538 err, config_setting_source_line(setting));
539 free(err);
540 return false;
541 }
542 load_parameters[1] = (struct instruction){
543 .type = INST_LOAD,
544 .slot = duration_slot,
545 };
546 }
547
548 if (config_setting_lookup_float(setting, "delay", &number)) {
549 load_parameters[2] = (struct instruction){
550 .type = INST_IMM,
551 .imm = number,
552 };
553 } else if (!config_setting_lookup_string(setting, "delay", &str)) {
554 load_parameters[2] = (struct instruction){
555 .type = INST_IMM,
556 .imm = 0,
557 };
558 } else {
559 BUG_ON(ctx->allocated_slots > UINT_MAX - 1);
560 auto delay_slot = ctx->allocated_slots++;
561 if (!expression_compile(&end, str, ctx, delay_slot, false, &err)) {
562 casprintf(out_err, "Transition has an invalid delay expression: %s. Line %d",
563 err, config_setting_source_line(setting));
564 free(err);
565 return false;
566 }
567 load_parameters[2] = (struct instruction){
568 .type = INST_LOAD,
569 .slot = delay_slot,
570 };
571 }
572
573 // clang-format off
574 struct instruction instrs[] = {
575 load_parameters[0],
576 {.type = INST_LOAD, .slot = start_slot},
577 {.type = INST_OP, .op = OP_SUB}, // v0 = end - start
578 {.type = INST_LOAD, .slot = ctx->elapsed_slot},
579 load_parameters[2],
580 {.type = INST_OP, .op = OP_SUB}, // v1 = elapsed - delay
581 load_parameters[1],
582 {.type = INST_OP, .op = OP_DIV}, // v2 = v1 / duration
583 {.type = INST_CURVE, .curve = curve}, // v3 = curve(v2)
584 {.type = INST_OP, .op = OP_MUL}, // v4 = v0 * v3
585 {.type = INST_LOAD, .slot = start_slot},
586 {.type = INST_OP, .op = OP_ADD}, // v5 = v4 + start
587 {.type = INST_STORE, .slot = slot}, // memory[slot] = v5
588 };
589
590 // Instructs for calculating the total duration of the transition
591 struct instruction total_duration_instrs[] = {
592 load_parameters[1],
593 load_parameters[2],
594 {.type = INST_OP, .op = OP_ADD}, // v0 = duration + delay
595 {.type = INST_LOAD, .slot = ctx->elapsed_slot + 1},
596 {.type = INST_OP, .op = OP_MAX}, // v1 = max(v0, total_duration)
597 {.type = INST_STORE, .slot = ctx->elapsed_slot + 1},
598 };
599 // clang-format on
600
601 if (ctx->max_stack < 3) {
602 // The list of instructions above needs 3 stack slots
603 ctx->max_stack = 3;
604 }
605
606 struct fragment *fragment = fragment_new(ctx, ARR_SIZE(instrs));
607 memcpy(fragment->instrs, instrs, sizeof(instrs));
608 fragment->ninstrs = ARR_SIZE(instrs);
609
610 *stack_entry = calloc(
611 1, sizeof(struct compilation_stack) + sizeof(unsigned[max2(1, start->ndeps)]));
612 allocchk(*stack_entry);
613 struct fragment **next = &(*stack_entry)->entry_point;
614
615 // Dependencies of the start value is the real dependencies of this transition
616 // variable.
617 (*stack_entry)->ndeps = start->ndeps;
618 // If start value has dependencies, we calculate it like this:
619 // if (first_evaluation) mem[start_slot] = <start expression>;
620 // Otherwise, it's put into the "evaluation once" block.
621 if (start->ndeps > 0) {
622 memcpy((*stack_entry)->deps, start->deps, sizeof(unsigned[start->ndeps]));
623
624 auto branch = fragment_new(ctx, 0);
625 *next = branch;
626 branch->once_next = start->entry_point;
627
628 auto phi = fragment_new(ctx, 0);
629 *start->exit = phi;
630 branch->next = phi;
631 next = &phi->next;
632 } else {
633 *ctx->once_tail = start->entry_point;
634 ctx->once_tail = start->exit;
635 }
636
637 // The `end` block includes `end`, `duration`, and `delay` values.
638 if (end != NULL && end->ndeps > 0) {
639 // If we get here, the end/duration/delay values are not static, luckily
640 // we can still just calculate it at the end of the first evaluation,
641 // since at that point nothing can depends on a transition's end value.
642 // However, for the calculation of this transition curve, we don't yet
643 // have the these values, so we do this: `mem[output_slot] =
644 // mem[start_slot]`, instead of compute it normally.
645 *ctx->once_end_tail = end->entry_point;
646 ctx->once_end_tail = end->exit;
647
648 const struct instruction load_store_instrs[] = {
649 {.type = INST_LOAD, .slot = start_slot},
650 {.type = INST_STORE, .slot = slot},
651 };
652 auto load_store = fragment_new(ctx, ARR_SIZE(load_store_instrs));
653 load_store->ninstrs = ARR_SIZE(load_store_instrs);
654 memcpy(load_store->instrs, load_store_instrs, sizeof(load_store_instrs));
655
656 auto branch = fragment_new(ctx, 0);
657 *next = branch;
658 branch->once_next = load_store;
659 branch->next = fragment;
660
661 auto phi = fragment_new(ctx, 0);
662 load_store->next = phi;
663 fragment->next = phi;
664 (*stack_entry)->exit = &phi->next;
665 } else {
666 if (end != NULL) {
667 // The end value has no dependencies, so it only needs to be
668 // evaluated once at the start of the first evaluation. And
669 // therefore we can evaluate the curve like normal even for the
670 // first evaluation.
671 *ctx->once_tail = end->entry_point;
672 ctx->once_tail = end->exit;
673 }
674
675 *next = fragment;
676 (*stack_entry)->exit = &fragment->next;
677 }
678
679 // This must happen _after_ the `end` block.
680 struct fragment *total_duration_fragment = fragment_new(ctx, ARR_SIZE(instrs));
681 memcpy(total_duration_fragment->instrs, total_duration_instrs,
682 sizeof(total_duration_instrs));
683 total_duration_fragment->ninstrs = ARR_SIZE(total_duration_instrs);
684 *ctx->once_end_tail = total_duration_fragment;
685 ctx->once_end_tail = &total_duration_fragment->next;
686
687 return true;
688 }
689
690 static void instruction_deinit(struct instruction * /*instr*/) {
691 }
692
693 static void fragment_free(struct fragment *frag) {
694 list_remove(&frag->siblings);
695 for (unsigned i = 0; i < frag->ninstrs; i++) {
696 instruction_deinit(&frag->instrs[i]);
697 }
698 free(frag);
699 }
700
701 #define free_hash_table(head) \
702 do { \
703 typeof(head) i, ni; \
704 HASH_ITER(hh, head, i, ni) { \
705 HASH_DEL(head, i); \
706 free(i->name); \
707 free(i); \
708 } \
709 } while (0)
710
711 void script_free(struct script *script) {
712 for (unsigned i = 0; i < script->len; i++) {
713 instruction_deinit(&script->instrs[i]);
714 }
715 free_hash_table(script->vars);
716 free_hash_table(script->overrides);
717 free(script);
718 }
719
720 static bool script_compile_one(struct compilation_stack **stack_entry, config_setting_t *var,
721 struct script_compile_context *ctx, char **err) {
722 ctx->current_variable_name = config_setting_name(var);
723
724 struct variable_allocation *alloc = NULL;
725 HASH_FIND_STR(ctx->vars, ctx->current_variable_name, alloc);
726 BUG_ON(!alloc);
727
728 if (config_setting_is_number(var)) {
729 *stack_entry = make_imm_stack_entry(ctx, config_setting_get_float(var),
730 alloc->slot, false);
731 return true;
732 }
733 const char *str = config_setting_get_string(var);
734 if (str != NULL) {
735 char *tmp_err = NULL;
736 bool succeeded =
737 expression_compile(stack_entry, str, ctx, alloc->slot, false, &tmp_err);
738 if (!succeeded) {
739 casprintf(err, "Failed to parse expression at line %d. %s",
740 config_setting_source_line(var), tmp_err);
741 free(tmp_err);
742 }
743 return succeeded;
744 }
745
746 if (!config_setting_is_group(var)) {
747 casprintf(err,
748 "Invalid variable \"%s\", it must be either a number, a "
749 "string, "
750 "or a config group defining a transition.",
751 config_setting_name(var));
752 return false;
753 }
754 return transition_compile(stack_entry, var, ctx, alloc->slot, err);
755 }
756
757 static void report_cycle(struct compilation_stack **stack, unsigned top, unsigned index,
758 config_setting_t *setting, char **err) {
759 unsigned start = top - 1;
760 while (stack[start]->index != index) {
761 start -= 1;
762 }
763 auto last_var = config_setting_get_elem(setting, index);
764 auto last_name = config_setting_name(last_var);
765 auto len = (size_t)(top - start) * 4 /* " -> " */ + strlen(last_name);
766 for (unsigned i = start; i < top; i++) {
767 auto var = config_setting_get_elem(setting, stack[i]->index);
768 len += strlen(config_setting_name(var));
769 }
770 auto buf = ccalloc(len + 1, char);
771 auto pos = buf;
772 for (unsigned i = start; i < top; i++) {
773 auto var = config_setting_get_elem(setting, stack[i]->index);
774 auto name = config_setting_name(var);
775 strcpy(pos, name);
776 pos += strlen(name);
777 strcpy(pos, " -> ");
778 pos += 4;
779 }
780 strcpy(pos, last_name);
781
782 casprintf(err, "Cyclic references detected in animation script defined at line %d: %s",
783 config_setting_source_line(setting), buf);
784 free(buf);
785 }
786
787 static bool script_compile_one_recursive(struct compilation_stack **stack,
788 config_setting_t *setting, unsigned index,
789 struct script_compile_context *ctx, char **err) {
790 unsigned stack_top = 1;
791 if (!script_compile_one(&stack[0], config_setting_get_elem(setting, index), ctx, err)) {
792 return false;
793 }
794 stack[0]->index = index;
795 ctx->compiled[index] = 2;
796 while (stack_top) {
797 auto stack_entry = stack[stack_top - 1];
798 while (stack_entry->ndeps) {
799 auto dep = stack_entry->deps[--stack_entry->ndeps];
800 if (ctx->compiled[dep] == 1) {
801 continue;
802 }
803 if (ctx->compiled[dep] == 2) {
804 report_cycle(stack, stack_top, dep, setting, err);
805 goto out;
806 }
807
808 auto dep_setting = config_setting_get_elem(setting, dep);
809 if (!script_compile_one(&stack[stack_top], dep_setting, ctx, err)) {
810 goto out;
811 }
812 stack[stack_top]->index = dep;
813 ctx->compiled[dep] = 2;
814 stack_top += 1;
815 goto next;
816 }
817 // Top of the stack has all of its dependencies resolved, we can emit
818 // its fragment.
819 *ctx->tail = stack_entry->entry_point;
820 ctx->tail = stack_entry->exit;
821 ctx->compiled[stack_entry->index] = 1;
822 stack[--stack_top] = NULL;
823 free(stack_entry);
824 next:;
825 }
826 out:
827 for (unsigned i = 0; i < stack_top; i++) {
828 free(stack[i]);
829 }
830 return stack_top == 0;
831 }
832
833 static void prune_fragments(struct list_node *head) {
834 bool changed = true;
835 while (changed) {
836 changed = false;
837 list_foreach(struct fragment, i, head, siblings) {
838 if (i->once_next == i->next && i->next != NULL) {
839 i->once_next = NULL;
840 changed = true;
841 }
842 }
843 list_foreach(struct fragment, i, head, siblings) {
844 struct fragment *non_empty = i->next;
845 while (non_empty && non_empty->ninstrs == 0 &&
846 non_empty->once_next == NULL) {
847 non_empty = non_empty->next;
848 }
849 changed |= (non_empty != i->next);
850 i->next = non_empty;
851 non_empty = i->once_next;
852 while (non_empty && non_empty->ninstrs == 0 &&
853 non_empty->once_next == NULL) {
854 non_empty = non_empty->next;
855 }
856 changed |= (non_empty != i->once_next);
857 i->once_next = non_empty;
858 }
859 }
860 }
861
862 static struct script *script_codegen(struct list_node *all_fragments, struct fragment *head) {
863 unsigned nfragments = 0;
864 list_foreach(struct fragment, i, all_fragments, siblings) {
865 nfragments += 1;
866 }
867 auto queue = ccalloc(nfragments, struct fragment *);
868 unsigned pos = 0, h = 0, t = 1;
869 queue[0] = head;
870 head->emitted = true;
871 // First, layout the fragments in the output
872 while (h != t) {
873 auto curr = queue[h];
874 while (curr) {
875 curr->addr = pos;
876 curr->emitted = true;
877 pos += curr->ninstrs;
878 if (curr->once_next) {
879 pos += 1; // For branch_once
880 if (!curr->once_next->emitted) {
881 queue[t++] = curr->once_next;
882 curr->once_next->emitted = true;
883 }
884 }
885 if ((curr->next && curr->next->emitted) || !curr->next) {
886 pos += 1; // For branch or halt
887 break;
888 }
889 curr = curr->next;
890 }
891 h += 1;
892 }
893 struct script *script =
894 calloc(1, sizeof(struct script) + sizeof(struct instruction[pos]));
895 script->len = pos;
896 free(queue);
897
898 list_foreach(const struct fragment, i, all_fragments, siblings) {
899 if (i->ninstrs) {
900 memcpy(&script->instrs[i->addr], i->instrs,
901 sizeof(struct instruction[i->ninstrs]));
902 }
903
904 auto ninstrs = i->ninstrs;
905 if (i->once_next) {
906 script->instrs[i->addr + ninstrs].type = INST_BRANCH_ONCE;
907 script->instrs[i->addr + ninstrs].rel =
908 (int)i->once_next->addr - (int)(i->addr + ninstrs);
909 ninstrs += 1;
910 }
911 if (i->next && i->next->addr != i->addr + ninstrs) {
912 script->instrs[i->addr + ninstrs].type = INST_BRANCH;
913 script->instrs[i->addr + ninstrs].rel =
914 (int)i->next->addr - (int)(i->addr + ninstrs);
915 } else if (!i->next) {
916 script->instrs[i->addr + ninstrs].type = INST_HALT;
917 }
918 }
919 return script;
920 }
921
922 static void
923 script_compile_context_init(struct script_compile_context *ctx, config_setting_t *setting) {
924 list_init_head(&ctx->all_fragments);
925 const uint32_t n = to_u32_checked(config_setting_length(setting));
926 ctx->compiled = ccalloc(n, int);
927 for (uint32_t i = 0; i < n; i++) {
928 auto var = config_setting_get_elem(setting, i);
929 const char *var_name = config_setting_name(var);
930 auto alloc = ccalloc(1, struct variable_allocation);
931 alloc->name = strdup(var_name);
932 alloc->index = i;
933 alloc->slot = i;
934 HASH_ADD_STR(ctx->vars, name, alloc);
935 }
936
937 ctx->allocated_slots = n + 2;
938 ctx->elapsed_slot = n;
939
940 auto head = fragment_new(ctx, 0);
941 ctx->head = head;
942 ctx->once_tail = &head->once_next;
943 ctx->tail = &head->next;
944
945 ctx->once_end_head = fragment_new(ctx, 2);
946 ctx->once_end_head->instrs[0] = (struct instruction){
947 .type = INST_IMM,
948 .imm = 0,
949 };
950 ctx->once_end_head->instrs[1] = (struct instruction){
951 .type = INST_STORE,
952 .slot = ctx->elapsed_slot + 1,
953 };
954 ctx->once_end_head->ninstrs = 2;
955 ctx->once_end_tail = &ctx->once_end_head->next;
956 ctx->max_stack = 1;
957 }
958
959 unsigned script_elapsed_slot(const struct script *script) {
960 return script->elapsed_slot;
961 }
962
963 unsigned script_total_duration_slot(const struct script *script) {
964 return script->elapsed_slot + 1;
965 }
966
967 struct script *
968 script_compile(config_setting_t *setting, struct script_parse_config cfg, char **out_err) {
969 if (!config_setting_is_group(setting)) {
970 casprintf(out_err, "Script setting must be a group");
971 return NULL;
972 }
973 struct script_context_info_internal *context_table = NULL;
974 if (cfg.context_info) {
975 for (unsigned i = 0; cfg.context_info[i].name; i++) {
976 struct script_context_info_internal *new_ctx =
977 ccalloc(1, struct script_context_info_internal);
978 new_ctx->info = cfg.context_info[i];
979 HASH_ADD_STR(context_table, info.name, new_ctx);
980 }
981 }
982
983 struct script_compile_context ctx = {};
984 script_compile_context_init(&ctx, setting);
985 ctx.context_info = context_table;
986 const uint32_t n = to_u32_checked(config_setting_length(setting));
987 auto stack = ccalloc(n, struct compilation_stack *);
988 for (uint32_t i = 0; i < n; i++) {
989 if (ctx.compiled[i]) {
990 continue;
991 }
992 if (!script_compile_one_recursive(stack, setting, i, &ctx, out_err)) {
993 break;
994 }
995 }
996
997 {
998 struct script_context_info_internal *info, *next_info;
999 HASH_ITER(hh, context_table, info, next_info) {
1000 HASH_DEL(context_table, info);
1001 free(info);
1002 }
1003 }
1004 for (int i = 0; cfg.output_info && cfg.output_info[i].name; i++) {
1005 struct variable_allocation *alloc = NULL;
1006 HASH_FIND_STR(ctx.vars, cfg.output_info[i].name, alloc);
1007 if (alloc) {
1008 cfg.output_info[i].slot = to_int_checked(alloc->slot);
1009 } else {
1010 cfg.output_info[i].slot = -1;
1011 }
1012 }
1013
1014 bool succeeded = true;
1015 for (unsigned i = 0; i < n; i++) {
1016 if (ctx.compiled[i] != 1) {
1017 succeeded = false;
1018 break;
1019 }
1020 }
1021 free(stack);
1022 free(ctx.compiled);
1023 if (!succeeded) {
1024 free_hash_table(ctx.vars);
1025 free_hash_table(ctx.overrides);
1026 list_foreach_safe(struct fragment, i, &ctx.all_fragments, siblings) {
1027 fragment_free(i);
1028 }
1029 return NULL;
1030 }
1031
1032 // Connect everything together
1033 if (ctx.once_end_head) {
1034 auto once_end = fragment_new(&ctx, 0);
1035 *ctx.tail = once_end;
1036 once_end->once_next = ctx.once_end_head;
1037 }
1038 *ctx.once_tail = ctx.head->next;
1039
1040 prune_fragments(&ctx.all_fragments);
1041
1042 auto script = script_codegen(&ctx.all_fragments, ctx.head);
1043 script->vars = ctx.vars;
1044 script->overrides = ctx.overrides;
1045 script->elapsed_slot = ctx.elapsed_slot;
1046 script->n_slots = ctx.allocated_slots;
1047 script->stack_size = ctx.max_stack;
1048 log_debug("Compiled script at line %d, total instructions: %d, "
1049 "slots: %d, stack size: %d, memory[%u] = total duration, memory[%u] = "
1050 "elapsed",
1051 config_setting_source_line(setting), script->len, script->n_slots,
1052 script->stack_size, script->elapsed_slot + 1, script->elapsed_slot);
1053 if (log_get_level_tls() <= LOG_LEVEL_DEBUG) {
1054 log_debug("Output mapping:");
1055 HASH_ITER2(ctx.vars, var) {
1056 log_debug(" %s -> %d", var->name, var->slot);
1057 }
1058 }
1059 if (log_get_level_tls() <= LOG_LEVEL_TRACE) {
1060 for (unsigned i = 0; i < script->len; i++) {
1061 log_instruction(TRACE, i, script->instrs[i]);
1062 }
1063 }
1064 list_foreach_safe(struct fragment, i, &ctx.all_fragments, siblings) {
1065 free(i);
1066 }
1067 return script;
1068 }
1069
1070 char *script_to_c(const struct script *script, const struct script_output_info *outputs) {
1071 char **buf = dynarr_new(char *, (size_t)script->len * 40);
1072 char *tmp = NULL;
1073 casprintf(&tmp, "{\n"
1074 " static const struct instruction instrs[] = {\n");
1075 dynarr_push(buf, tmp);
1076 for (unsigned i = 0; i < script->len; i++) {
1077 dynarr_push(buf, instruction_to_c(script->instrs[i]));
1078 }
1079 casprintf(&tmp,
1080 " };\n struct script *ret = \n"
1081 " malloc(offsetof(struct script, instrs) + sizeof(instrs));\n"
1082 " ret->len = ARR_SIZE(instrs); ret->elapsed_slot = %u;"
1083 " ret->n_slots = %u; ret->stack_size = %u;\n"
1084 " ret->vars = NULL; ret->overrides = NULL;\n"
1085 " memcpy(ret->instrs, instrs, sizeof(instrs));\n",
1086 script->elapsed_slot, script->n_slots, script->stack_size);
1087 dynarr_push(buf, tmp);
1088
1089 struct variable_allocation *var, *next_var;
1090 HASH_ITER(hh, script->vars, var, next_var) {
1091 char *var_str = NULL;
1092 casprintf(&var_str,
1093 " {\n"
1094 " struct variable_allocation *var = \n"
1095 " malloc(sizeof(*var));\n"
1096 " *var = (struct variable_allocation){\n"
1097 " .name = strdup(\"%s\"), .slot = %u, .index = %u\n"
1098 " };\n"
1099 " HASH_ADD_STR(ret->vars, name, var);\n"
1100 " }\n",
1101 var->name, var->slot, var->index);
1102 dynarr_push(buf, var_str);
1103 }
1104
1105 struct overridable_slot *override, *next_override;
1106 HASH_ITER(hh, script->overrides, override, next_override) {
1107 char *override_str = NULL;
1108 casprintf(&override_str,
1109 " {\n"
1110 " struct overridable_slot *override = \n"
1111 " malloc(sizeof(*override));\n"
1112 " *override = (struct overridable_slot){\n"
1113 " .name = strdup(\"%s\"), .slot = %u\n"
1114 " };\n"
1115 " HASH_ADD_STR(ret->overrides, name, override);\n"
1116 " }\n",
1117 override->name, override->slot);
1118 dynarr_push(buf, override_str);
1119 }
1120
1121 for (size_t i = 0; outputs && outputs[i].name; i++) {
1122 struct variable_allocation *alloc = NULL;
1123 HASH_FIND_STR(script->vars, outputs[i].name, alloc);
1124 if (alloc) {
1125 casprintf(&tmp, " output_slots[%zu] = %u;\n", i, alloc->slot);
1126 } else {
1127 casprintf(&tmp, " output_slots[%zu] = -1;\n", i);
1128 }
1129 dynarr_push(buf, tmp);
1130 }
1131
1132 casprintf(&tmp, " return ret;\n}\n");
1133 dynarr_push(buf, tmp);
1134 return dynarr_join(buf, "");
1135 }
1136
1137 void script_specialize(struct script *script,
1138 const struct script_specialization_context *context,
1139 unsigned n_context) {
1140 for (unsigned i = 0; i < script->len; i++) {
1141 if (script->instrs[i].type != INST_LOAD_CTX) {
1142 continue;
1143 }
1144 for (unsigned j = 0; j < n_context; j++) {
1145 if (script->instrs[i].ctx == context[j].offset) {
1146 script->instrs[i].type = INST_IMM;
1147 script->instrs[i].imm = context[j].value;
1148 break;
1149 }
1150 }
1151 }
1152 }
1153
1154 struct script_instance *script_instance_new(const struct script *script) {
1155 // allocate no space for the variable length array is UB.
1156 unsigned memory_size = max2(1, script->n_slots + script->stack_size);
1157 struct script_instance *instance =
1158 calloc(1, sizeof(struct script_instance) + sizeof(double[memory_size]));
1159 allocchk(instance);
1160 instance->script = script;
1161 for (unsigned i = 0; i < script->n_slots; i++) {
1162 instance->memory[i] = NAN;
1163 }
1164 instance->memory[script->elapsed_slot] = 0;
1165 return instance;
1166 }
1167
1168 void script_instance_resume_from(struct script_instance *old, struct script_instance *new_) {
1169 // todo: proper steer logic
1170 struct overridable_slot *i, *next;
1171 HASH_ITER(hh, new_->script->overrides, i, next) {
1172 struct variable_allocation *src_alloc = NULL;
1173 HASH_FIND_STR(old->script->vars, i->name, src_alloc);
1174 if (!src_alloc) {
1175 continue;
1176 }
1177 new_->memory[i->slot] = old->memory[src_alloc->slot];
1178 }
1179 }
1180
1181 enum script_evaluation_result script_instance_evaluate(struct script_instance *instance,
1182 void *context, bool do_branch_once) {
1183 auto script = instance->script;
1184 auto stack = &instance->memory[script->n_slots];
1185 unsigned top = 0;
1186 double l, r;
1187 for (auto i = script->instrs;; i++) {
1188 switch (i->type) {
1189 case INST_IMM: stack[top++] = i->imm; break;
1190 case INST_LOAD: stack[top++] = instance->memory[i->slot]; break;
1191 case INST_LOAD_CTX: stack[top++] = *(double *)(context + i->ctx); break;
1192 case INST_STORE:
1193 BUG_ON(top < 1);
1194 instance->memory[i->slot] = stack[--top];
1195 break;
1196 case INST_STORE_OVER_NAN:
1197 BUG_ON(top < 1);
1198 top -= 1;
1199 if (safe_isnan(instance->memory[i->slot])) {
1200 instance->memory[i->slot] = stack[top];
1201 }
1202 break;
1203 case INST_BRANCH: i += i->rel - 1; break;
1204 case INST_BRANCH_ONCE:
1205 if (do_branch_once) {
1206 i += i->rel - 1;
1207 }
1208 break;
1209 case INST_HALT: return SCRIPT_EVAL_OK;
1210 case INST_OP:
1211 if (i->op == OP_NEG) {
1212 BUG_ON(top < 1);
1213 l = stack[top - 1];
1214 stack[top - 1] = -l;
1215 } else {
1216 BUG_ON(top < 2);
1217 l = stack[top - 2];
1218 r = stack[top - 1];
1219 stack[top - 2] = op_eval(l, i->op, r);
1220 top -= 1;
1221 }
1222 break;
1223 case INST_CURVE:
1224 BUG_ON(top < 1);
1225 l = stack[top - 1];
1226 l = min2(max2(0, l), 1);
1227 stack[top - 1] = curve_sample(&i->curve, l);
1228 break;
1229 }
1230 if (top && safe_isnan(stack[top - 1])) {
1231 return SCRIPT_EVAL_ERROR_NAN;
1232 }
1233 if (top && safe_isinf(stack[top - 1])) {
1234 return SCRIPT_EVAL_ERROR_INF;
1235 }
1236 }
1237 unreachable();
1238 }
1239
1240 #ifdef UNIT_TEST
1241 static inline void
1242 script_compile_str(struct test_case_metadata *metadata, const char *str,
1243 struct script_output_info *outputs, char **err, struct script **out) {
1244 config_t cfg;
1245 config_init(&cfg);
1246 config_set_auto_convert(&cfg, 1);
1247 int ret = config_read_string(&cfg, str);
1248 TEST_EQUAL(ret, CONFIG_TRUE);
1249
1250 config_setting_t *setting = config_root_setting(&cfg);
1251 TEST_NOTEQUAL(setting, NULL);
1252 *out = script_compile(setting,
1253 (struct script_parse_config){.output_info = outputs}, err);
1254 config_destroy(&cfg);
1255 }
1256
1257 TEST_CASE(scripts_1) {
1258 static const char *str = "\
1259 a = 10; \
1260 b = \"a * 2\";\
1261 c = \"(b - 1) * (a+1)\";\
1262 d = \"- e - 1\"; \
1263 e : { \
1264 curve = \"cubic-bezier(0.5,0.5, 0.5, 0.5)\"; \
1265 duration = \"a\"; \
1266 delay = 0.5; \
1267 start = 10; \
1268 end = \"2 * c\"; \
1269 }; \
1270 f : { \
1271 curve = \"cubic-bezier(0.1,0.2, 0.3, 0.4)\"; \
1272 duration = 10; \
1273 delay = 0.5; \
1274 start = \"e + 1\"; \
1275 end = \"f - 1\"; \
1276 }; \
1277 neg = \"-a\"; \
1278 timing1 : { \
1279 duration = 10; \
1280 start = 1; \
1281 end = 0; \
1282 };\
1283 timing2 : { \
1284 curve = \"steps(1, jump-start)\"; \
1285 duration = 10; \
1286 start = 1; \
1287 end = 0; \
1288 };";
1289 struct script_output_info outputs[] = {{"a"}, {"b"}, {"c"}, {"d"}, {"e"}, {NULL}};
1290 char *err = NULL;
1291 struct script *script = NULL;
1292 script_compile_str(metadata, str, outputs, &err, &script);
1293 if (err) {
1294 log_error("err: %s\n", err);
1295 free(err);
1296 }
1297 TEST_NOTEQUAL(script, NULL);
1298 TEST_EQUAL(err, NULL);
1299 if (script) {
1300 struct variable_allocation *c;
1301 HASH_FIND_STR(script->vars, "c", c);
1302 TEST_NOTEQUAL(c, NULL);
1303
1304 struct script_instance *instance = script_instance_new(script);
1305 auto result = script_instance_evaluate(instance, NULL, true);
1306 TEST_EQUAL(result, SCRIPT_EVAL_OK);
1307 TEST_EQUAL(instance->memory[script->elapsed_slot + 1], 10.5);
1308 TEST_EQUAL(instance->memory[outputs[0].slot], 10);
1309 TEST_EQUAL(instance->memory[outputs[1].slot], 20);
1310 TEST_EQUAL(instance->memory[outputs[2].slot], 209);
1311 TEST_EQUAL(instance->memory[outputs[3].slot], -11);
1312 TEST_EQUAL(instance->memory[outputs[4].slot], 10);
1313 TEST_TRUE(!script_instance_is_finished(instance));
1314
1315 instance->memory[instance->script->elapsed_slot] += 5.5;
1316 result = script_instance_evaluate(instance, NULL, false);
1317 TEST_EQUAL(result, SCRIPT_EVAL_OK);
1318 TEST_EQUAL(instance->memory[outputs[4].slot], 214);
1319
1320 instance->memory[instance->script->elapsed_slot] += 5.5;
1321 result = script_instance_evaluate(instance, NULL, false);
1322 TEST_EQUAL(result, SCRIPT_EVAL_OK);
1323 TEST_EQUAL(instance->memory[outputs[0].slot], 10);
1324 TEST_EQUAL(instance->memory[outputs[1].slot], 20);
1325 TEST_EQUAL(instance->memory[outputs[2].slot], 209);
1326 TEST_EQUAL(instance->memory[outputs[3].slot], -419);
1327 TEST_EQUAL(instance->memory[outputs[4].slot], 418);
1328 TEST_TRUE(script_instance_is_finished(instance));
1329 free(instance);
1330 script_free(script);
1331 }
1332 }
1333 TEST_CASE(scripts_report_cycle) {
1334 static const char *str = "\
1335 a = \"c\"; \
1336 b = \"a * 2\";\
1337 c = \"b + 1\";";
1338 char *err = NULL;
1339 struct script *script = NULL;
1340 script_compile_str(metadata, str, NULL, &err, &script);
1341 TEST_EQUAL(script, NULL);
1342 TEST_NOTEQUAL(err, NULL);
1343 TEST_STREQUAL(err, "Cyclic references detected in animation script defined at "
1344 "line 0: a -> c -> b -> a");
1345 free(err);
1346 }
1347 TEST_CASE(script_errors) {
1348 static const char *cases[][2] = {
1349 {"a = \"1 @ 2 \";", "Failed to parse expression at line 1. Expected one of "
1350 "\"+-*/^\", got '@'."},
1351 {"a = { curve = \"asdf\";};", "Cannot parse curve at line 1: Unknown curve "
1352 "type \"asdf\"."},
1353 {"a = { curve = \"steps(a)\";};", "Cannot parse curve at line 1: Invalid "
1354 "step count at \"a)\"."},
1355 {"a = { curve = \"steps(1)\";};", "Cannot parse curve at line 1: Invalid "
1356 "steps argument list \"(1)\"."},
1357 {"a = \"1 + +\";", "Failed to parse expression at line 1. Expected a number "
1358 "or a variable name, got \"+\"."},
1359 {"a = \"1)\";", "Failed to parse expression at line 1. Unmatched ')' in "
1360 "expression \"1)\""},
1361 {"a = {};", "Transition definition does not contain a start value or "
1362 "expression. Line 1."},
1363 {"a = { duration = 0; start = 0; end = 0; };", "Duration must be greater "
1364 "than 0. Line 1."},
1365 };
1366 char *err = NULL;
1367 struct script *script = NULL;
1368 for (size_t i = 0; i < ARR_SIZE(cases); i++) {
1369 script_compile_str(metadata, cases[i][0], NULL, &err, &script);
1370 TEST_EQUAL(script, NULL);
1371 TEST_NOTEQUAL(err, NULL);
1372 TEST_STREQUAL(err, cases[i][1]);
1373 free(err);
1374 err = NULL;
1375 }
1376 }
1377 #endif