-
Notifications
You must be signed in to change notification settings - Fork 3
/
gf_lang_exec.go
797 lines (589 loc) · 24.6 KB
/
gf_lang_exec.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
/*
GloFlow application and media management/publishing platform
Copyright (C) 2022 Ivan Trajkovic
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package gf_lang
import (
"fmt"
"errors"
"strings"
"github.com/gloflow/gloflow/go/gf_core"
// "github.com/davecgh/go-spew/spew"
)
//-------------------------------------------------
func executeTree(pExpressionASTlst []interface{},
pStateParent *GFstate,
pRulesDefsMap GFruleDefs,
pShaderDefsMap map[string]*GFshaderDef,
pStateFamilyStackLst []*GFstate,
pExternAPI GFexternAPI,
pDebug *GFprogramDebug) (*GFstate, interface{}, error) {
symbols := getSymbolsAndConstants()
//--------------------
// STATE_NEW
// IMPORTANT!! - on every tree descent a new independent state is constructed
state := stateCreateNew(pStateParent, pDebug)
//--------------------
// clone in case of mutations of expression
expressionLst := cloneExpr(pExpressionASTlst)
//-------------------------------------------------
handleSubExpressionFun := func(pSubExprLst GFexpr) (interface{}, error) {
// RECURSION
childState, subExprResult, err := executeTree(pSubExprLst,
state,
pRulesDefsMap,
pShaderDefsMap,
pStateFamilyStackLst,
pExternAPI,
pDebug)
if err != nil {
return nil, err
}
mergedState, err := stateMergeChild(state, childState)
if err != nil {
return nil, err
}
state = mergedState
return subExprResult, nil
}
//-------------------------------------------------
// iterate over each expression element
for i:=0; i < len(expressionLst); i++ {
element := expressionLst[i]
elementIsStrBool, elementStr := gf_core.CastToStr(element)
//------------------------------------
// PROPERTY_MODIFIER
if elementIsStrBool && gf_core.ListContainsStr(elementStr, symbols.PredefinedPropertiesLst) {
propertyNameStr := elementStr
modifier := expressionLst[i+1]
var modifierFinalValF float64
// modifier is a number
if modifierF, ok := modifier.(float64); ok {
modifierFinalValF = modifierF
} else if modifierLst, ok := modifier.([]interface{}); ok {
// modifier is a sub-expression - needs to be evaluated
subExprLst := modifierLst
//--------------------
// SYSTEM_FUNCTION
if isSysFunc(subExprLst) {
result, err := sysFuncEval(subExprLst, state, pExternAPI)
if err != nil {
return nil, nil, err
}
modifierFinalValF = result.(float64)
//--------------------
} else {
resultF, err := arithmeticEval(subExprLst, state, pExternAPI)
if err != nil {
return nil, nil, err
}
modifierFinalValF = *resultF
}
}
// IMPORTANT!! - incremental modification
statePropFloatIncrement(state, propertyNameStr, modifierFinalValF)
//-----------
// FIX!! - this should be i+=2, since we're jumping over "property_name, modifier" (2 elements, not just one)
i+=1 // fast-forward, modifiers can be listed sequentially in the same expression
//-----------
continue
} else if subExprLst, ok := element.(GFexpr); ok {
//------------------------------------
// SUB_EXPRESSION
subExprResult, err := handleSubExpressionFun(subExprLst)
if err != nil {
return nil, nil, err
}
// sub-expression evaluated to a value
if subExprResult != nil {
// RETURN - special handling if a subexpression is a return statement.
// in that case break out of the expression processing loop
// immediatelly and return to parent expression a result.
if checkIsReturnExpr(subExprLst) {
return state, subExprResult, nil
} else {
// REGULAR_CASE
// substitute sub-expression for its results
expressionLst[i] = subExprResult
// continue looping through the expression elements,
// without incrementing "i". because we evaluated the expression
// at position "i" and substituted results of that expression at that slot.
continue
}
}
//------------------------------------
} else if checkIsArithmeticOp(elementStr) && i==0 {
//------------------------------------
// ARITHMETIC
arithmeticResult, err := arithmeticEval(expressionLst, state, pExternAPI)
if err != nil {
return nil, nil, err
}
expressionResult := *arithmeticResult
return state, expressionResult, nil
//------------------------------------
} else if elementIsStrBool && elementStr == "if" {
//------------------------------------
// CONDITIONALS
if i != 0 {
return nil, nil, errors.New("'if' keyword can ony be the first element in the expression")
}
childState, err := exprConditional(expressionLst,
state,
pRulesDefsMap,
pShaderDefsMap,
pStateFamilyStackLst,
pExternAPI,
pDebug)
if err != nil {
return nil, nil, err
}
mergedState, err := stateMergeChild(state, childState)
if err != nil {
return nil, nil, err
}
state = mergedState
break
//------------------------------------
} else if elementIsStrBool && (elementStr == "set" || elementStr == "push" || elementStr == "pop") {
//------------------------------------
// STATE_SETTERS - global state setters
setterTypeStr := elementStr
propertyNameStr := expressionLst[1].(string)
vals := expressionLst[2]
if (setterTypeStr == "push" || setterTypeStr == "pop") && propertyNameStr == "coord_origin" {
// coord_origin state_setter is the only setter so far that returns
// a new state, all other state setters dont modify the gf_lang state.
newState, err := execStateSetterExpr(setterTypeStr,
propertyNameStr,
vals,
state,
pStateFamilyStackLst,
pExternAPI,
pDebug)
if err != nil {
return nil, nil, err
}
state = newState
} else {
// setterTypeStr == "set"
_, err := execStateSetterExpr(setterTypeStr,
propertyNameStr,
vals,
state,
pStateFamilyStackLst,
pExternAPI,
pDebug)
if err != nil {
return nil, nil, err
}
}
break
//------------------------------------
} else if elementIsStrBool && elementStr == "print" {
//------------------------------------
// PRINT
err := exprPrint(expressionLst, state)
if err != nil {
return nil, nil, err
}
break
//------------------------------------
} else if elementIsStrBool && elementStr == "animate" {
//------------------------------------
// ANIMATION
if i != 0 {
return nil, nil, errors.New("'animate' keyword can ony be the first element in the expression")
}
exprAnimation(expressionLst, state, pExternAPI)
break
//------------------------------------
} else if elementIsStrBool && isVar(elementStr) && i==0 && len(expressionLst) == 2 {
//------------------------------------
// VARIABLE_ASSIGNMENT
// as the first element is the expression.
// when assigning to a variable (["$some", 10])
// the name of the var is always expected to be the first.
err := execVarAssignExpr(expressionLst, state, pExternAPI)
if err != nil {
return nil, nil, err
}
// spew.Dump(state.VarsMap)
return state, nil, nil
//------------------------------------
} else if elementIsStrBool && elementStr == "return" && i==0 {
//------------------------------------
// RETURN
valUnevaluated := expressionLst[1]
// EVALUATE
returnVal, complexSubExprBool, err := exprEvalSimple(valUnevaluated, state, pExternAPI)
if err != nil {
return nil, nil, err
}
var expressionResult interface{}
// return statement contains a complex sub-expression, which cant be handled by exprEvalSimple(),
// and instead it has to be handled by a full executeTree() run.
if complexSubExprBool {
subExprLst := valUnevaluated.(GFexpr)
subExprResult, err := handleSubExpressionFun(subExprLst)
if err != nil {
return nil, nil, err
}
expressionResult = subExprResult
} else {
expressionResult = returnVal
}
return state, expressionResult, nil
//------------------------------------
} else {
//------------------------------------
// RULE_CALL
ruleNameStr := elementStr
if i != len(expressionLst)-1 {
return nil, nil, errors.New(fmt.Sprintf("rule call can only be the last element in expression; name %s, expression %s",
ruleNameStr,
expressionLst))
}
newState, err := exprRuleCall(ruleNameStr,
expressionLst,
state,
pRulesDefsMap,
pShaderDefsMap,
pStateFamilyStackLst,
pExternAPI,
pDebug)
if err != nil {
return nil, nil, err
}
state = newState
break
//------------------------------------
}
//------------------------------------
}
return state, nil, nil
}
//-------------------------------------------------
func exprRuleCall(pCalledRuleNameStr string,
pExpressionLst []interface{},
pStateParent *GFstate,
pRulesDefsMap GFruleDefs,
pShaderDefsMap map[string]*GFshaderDef,
pStateFamilyStackLst []*GFstate,
pExternAPI GFexternAPI,
pDebug *GFprogramDebug) (*GFstate, error) {
symbols := getSymbolsAndConstants()
if pDebug != nil {
if _, ok := pDebug.RulesCallsCounterMap[pCalledRuleNameStr]; !ok {
pDebug.RulesCallsCounterMap[pCalledRuleNameStr] = 0
}
pDebug.RulesCallsCounterMap[pCalledRuleNameStr] += 1
}
//------------------------------------
// SYSTEM_RULE
// rules predefined in the system
if gf_core.ListContainsStr(pCalledRuleNameStr, symbols.SystemRulesLst) {
newState := exprRuleSysCall(pCalledRuleNameStr,
pStateParent,
pExternAPI,
pDebug)
return newState, nil
//------------------------------------
} else if gf_core.MapHasKey(pRulesDefsMap, pCalledRuleNameStr) {
//------------------------------------
// USER_RULE
// rules defined by the user in their program
//--------------------
// STATE_NEW
// for each rule invocation a new state object is created, that inherits
// the values of its parent state, within the same state family.
newState := stateCreateNew(pStateParent, pDebug)
//--------------------
// get the name of the rule that is making this call to another rule
currentRuleNameStr, err := ruleGetName(pStateParent)
if err != nil {
return nil, err
}
// all user calls (even recursive) are stored in the call stack
newState.RulesNamesStackLst = append(newState.RulesNamesStackLst, pCalledRuleNameStr)
// console.log(`calling rule ${currentRuleNameStr}->${pCalledRuleNameStr}`, pStateParent *GFstate["rules_names_stack_lst"]);
// new rule getting executed
if currentRuleNameStr != pCalledRuleNameStr {
// start a new iterations counter since we're entering a new rule
// (not recursively iterating within the same rule)
addNewItersNumState(newState)
}
currentRuleItersNumInt := ruleGetItersNum(newState)
// pick a random definition for a rule, which can have many definitions.
ruleDef, ruleExpressionsLst := pickRuleRandomDef(pCalledRuleNameStr,
pRulesDefsMap)
//------------------------------------
// RECURSION_STOP
// - prevent infinite rules execution
// - if global iters_max limit is reached (global for all rules)
// - if local rule-specific (rule modifier) iters_max limit is reached (for current rule only)
// GLOBAL_LIMIT
if newState.ItersNumGlobalInt > newState.ItersMaxInt-1 {
fmt.Println("global iter limit reached")
return newState, nil
} else if gf_core.MapHasKey(ruleDef.ModifiersMap, "iters_max") {
// RULE_LIMIT
// check if rule has a iters_max rule modifier specified
ruleItersLimitInt := int(ruleDef.ModifiersMap["iters_max"].(float64))
if currentRuleItersNumInt > ruleItersLimitInt-1 {
// console.log(`local iter limit ${currentRuleItersNumInt} for rule ${pCalledRuleNameStr} reached`,
// pStateParent *GFstate["rules_names_stack_lst"]);
//-----------------
// RULE_EXIT
// rule naturally ended with iter_num limit, without entering
// a different rule. the state has to be reset to the callers
// state.
// pop
_, newRulesItersNumStackLst := gf_core.ListPop[int](newState.RulesItersNumStackLst)
newState.RulesItersNumStackLst = newRulesItersNumStackLst
// pop
_, newRulesNamesStackLst := gf_core.ListPop[string](newState.RulesNamesStackLst)
newState.RulesNamesStackLst = newRulesNamesStackLst
oldRuleItersNumInt := ruleGetItersNum(newState)
newState.VarsMap["$i"].Val = oldRuleItersNumInt
//-----------------
return newState, nil
}
//------------------------------------
}
// RECURSION
// IMPORTANT!! - rules are not yet treated as expressions, and cant return
// results of evaluating its expressions. so ignoring execution results.
childState, _, err := executeTree(ruleExpressionsLst,
newState,
pRulesDefsMap,
pShaderDefsMap,
pStateFamilyStackLst,
pExternAPI,
pDebug)
if err != nil {
return nil, err
}
// remove rule_name from the stack of rules that were executed
_, newRulesNamesStackLst := gf_core.ListPop[string](newState.RulesNamesStackLst)
newState.RulesNamesStackLst = newRulesNamesStackLst
if currentRuleNameStr != pCalledRuleNameStr {
// RULE_EXIT
// we returned from a new rule into the old rule context,
// so the iterations count for that new rule is no longer needed (and removed from stack).
restorePreviousRulesItersNum(newState)
return newState, nil
} else {
// we're still within the same rule, in one of its iterations, so just merge state
mergedState, err := stateMergeChild(newState, childState)
if err != nil {
return nil, err
}
return mergedState, nil
}
//------------------------------------
} else {
return nil, errors.New(fmt.Sprintf("rule call referencing an unexisting rule - %s", pCalledRuleNameStr))
}
//------------------------------------
}
//-------------------------------------------------
func exprRuleSysCall(pRuleNameStr string,
pState *GFstate,
pExternAPI GFexternAPI,
pDebug *GFprogramDebug) *GFstate {
//----------------------
pState.ItersNumGlobalInt += 1
// IMPORTANT!! - rule iterations are counted only for actual rule evaluations.
// important not to count "set" statements, expression tree
// descending, property modifiers execution, etc.
incrementItersNum(pState)
//----------------------
x := pState.Xf
y := pState.Yf
z := pState.Zf
rx := pState.RotationXf
ry := pState.RotationYf
rz := pState.RotationZf
sx := pState.ScaleXf
sy := pState.ScaleYf
sz := pState.ScaleZf
cr := pState.ColorRedF
cg := pState.ColorGreenF
cb := pState.ColorBlueF
props := &GFentityProps{
Xf: pState.Xf,
Yf: pState.Yf,
Zf: pState.Zf,
RotationXf: pState.RotationXf,
RotationYf: pState.RotationYf,
RotationZf: pState.RotationZf,
ScaleXf: pState.ScaleXf,
ScaleYf: pState.ScaleYf,
ScaleZf: pState.ScaleZf,
ColorRedF: pState.ColorRedF,
ColorGreenF: pState.ColorGreenF,
ColorBlueF: pState.ColorBlueF,
}
if pRuleNameStr == "cube" {
// CUBE
pExternAPI.CreateCubeFun(x, y, z, rx, ry, rz, sx, sy, sz, cr, cg, cb)
addEntityToOutput("cube", props, pDebug)
} else if pRuleNameStr == "sphere" {
// SPHERE
pExternAPI.CreateSphereFun(x, y, z, rx, ry, rz, sx, sy, sz, cr, cg, cb)
addEntityToOutput("sphere", props, pDebug)
} else if pRuleNameStr == "line" {
// LINE
pExternAPI.CreateLineFun(x, y, z, rx, ry, rz, sx, sy, sz, cr, cg, cb)
addEntityToOutput("line", props, pDebug)
}
return pState
}
//-------------------------------------------------
func exprAnimation(pExpressionLst []interface{},
pState *GFstate,
pExternAPI GFexternAPI) error {
symbols := getSymbolsAndConstants()
if len(pExpressionLst) != 3 && len(pExpressionLst) != 4 {
return errors.New("animation expression can only have 3|4 elements")
}
var propsLst []interface{}
var durationSecF float64
var repeatBool bool
if len(pExpressionLst) == 3 {
propsLst = pExpressionLst[1].([]interface{})
durationSecF = pExpressionLst[2].(float64)
} else if len(pExpressionLst) == 4 {
propsLst = pExpressionLst[1].([]interface{})
durationSecF = pExpressionLst[2].(float64)
repeatStr := pExpressionLst[3].(string)
if repeatStr == "repeat" {
repeatBool = true
} else {
return errors.New("animation can only be enabled with the 'repeat' keyword")
}
}
propsToAnimateLst := []map[string]interface{}{}
for _, prop := range propsLst {
propLst := prop.([]interface{})
propNameStr := propLst[0].(string)
changeDeltaF := propLst[1].(float64)
if !gf_core.ListContainsStr(propNameStr, symbols.PredefinedPropertiesLst) {
return errors.New(fmt.Sprintf("cant animate property that is not predefined - %s", propNameStr))
}
startValF := statePropGet(pState, propNameStr)
endValF := startValF + changeDeltaF
propsToAnimateLst = append(propsToAnimateLst, map[string]interface{}{
"name_str": propNameStr,
"start_val_f": startValF,
"end_val_f": endValF,
})
}
pExternAPI.AnimateFun(propsToAnimateLst, durationSecF, repeatBool)
return nil
}
//-------------------------------------------------
// EXPRESSION__CONDITIONAL
func exprConditional(pExpressionLst GFexpr,
pState *GFstate,
pRulesDefsMap GFruleDefs,
pShaderDefsMap map[string]*GFshaderDef,
pStateFamilyStackLst []*GFstate,
pExternAPI GFexternAPI,
pDebug *GFprogramDebug) (*GFstate, error) {
// [, conditionLst, subExpressionsLst] = pExpressionLst;
conditionLst := pExpressionLst[1].(GFexpr)
subExpressionsLst := pExpressionLst[2].(GFexpr)
if len(conditionLst) > 3 {
return nil, errors.New("'if' condition can only have 3 elements [logic_op, operand1, operand2]")
}
//-------------------------------------------------
evaluateLogicExprFun := func(pLogicExprLst GFexpr) (bool, error) {
symbols := getSymbolsAndConstants()
logicOpStr := conditionLst[0].(string)
operand1 := conditionLst[1]
operand2 := conditionLst[2]
if !gf_core.MapHasKey(symbols.LogicOperatorsMap, logicOpStr) {
return false, errors.New(fmt.Sprintf("specified logic operator %s is not valid", logicOpStr))
}
//-------------------------------------------------
op1val, _, err := exprEvalSimple(operand1, pState, pExternAPI)
if err != nil {
return false, err
}
op2val, _, err := exprEvalSimple(operand2, pState, pExternAPI)
if err != nil {
return false, err
}
if symbols.LogicOperatorsMap[logicOpStr](castToFloat(op1val), castToFloat(op2val)) {
return true, nil
} else {
return false, nil
}
return false, nil
}
//-------------------------------------------------
logicResultBool, err := evaluateLogicExprFun(conditionLst)
if err != nil {
return nil, err
}
// if condition evaluates to true, execute subexpressions
if logicResultBool {
// recursion
childState, _, err := executeTree(subExpressionsLst,
pState,
pRulesDefsMap,
pShaderDefsMap,
pStateFamilyStackLst,
pExternAPI,
pDebug)
if err != nil {
return nil, err
}
mergedState, err := stateMergeChild(pState, childState)
if err != nil {
return nil, err
}
return mergedState, nil
} else {
return pState, nil // else returned state unchanged
}
return nil, nil
}
//-------------------------------------------------
// EXPRESSION__PRINT
func exprPrint(pExpressionLst GFexpr,
pState *GFstate) error {
valsLst := pExpressionLst[1].(GFexpr)
valsStr := ""
for _, val := range valsLst {
valIsStringBool, valStr := gf_core.CastToStr(val)
if valIsStringBool {
if strings.HasPrefix(valStr, "$") {
varRefStr := valStr
varVal, err := varEval(varRefStr, pState)
if err != nil {
return err
}
valFmtStr := fmt.Sprintf("%s=%s ", varRefStr, varVal.Val)
valsStr += valFmtStr
} else {
valsStr += valStr+" "
}
}
}
fmt.Printf(`gf %s\n`, valsStr)
return nil
}