-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathenvironment.go
More file actions
890 lines (731 loc) · 23.7 KB
/
environment.go
File metadata and controls
890 lines (731 loc) · 23.7 KB
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
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
package friendscript
import (
"fmt"
"io"
"io/ioutil"
"maps"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/ghetzel/friendscript/utils"
prompt "github.com/c-bata/go-prompt"
"github.com/fatih/color"
cmdassert "github.com/ghetzel/friendscript/commands/assert"
"github.com/ghetzel/friendscript/commands/core"
cmdencode "github.com/ghetzel/friendscript/commands/encode"
cmdfile "github.com/ghetzel/friendscript/commands/file"
cmdfmt "github.com/ghetzel/friendscript/commands/fmt"
cmdhttp "github.com/ghetzel/friendscript/commands/http"
cmdparse "github.com/ghetzel/friendscript/commands/parse"
cmdurl "github.com/ghetzel/friendscript/commands/url"
cmdutils "github.com/ghetzel/friendscript/commands/utils"
cmdvars "github.com/ghetzel/friendscript/commands/vars"
"github.com/ghetzel/friendscript/scripting"
"github.com/ghetzel/go-stockutil/fileutil"
"github.com/ghetzel/go-stockutil/log"
"github.com/ghetzel/go-stockutil/maputil"
"github.com/ghetzel/go-stockutil/sliceutil"
"github.com/ghetzel/go-stockutil/stringutil"
"github.com/ghetzel/go-stockutil/typeutil"
)
var MaxReaderWait = time.Duration(5) * time.Second
const DefaultEnvironmentName = `friendscript`
type InteractiveContext struct {
Command string
Line string
}
type InteractiveHandlerFunc func(ctx *InteractiveContext, environment *Environment) ([]string, error)
type ContextHandlerFunc func(ctx *scripting.Context, isCompleted bool)
type Environment struct {
Name string
modules map[string]Module
script *scripting.Friendscript
stack []*scripting.Scope
replHandlers map[string]InteractiveHandlerFunc
contextHandlers []ContextHandlerFunc
chlock sync.Mutex
filterCommands map[string]bool
pathWriters []utils.PathWriterFunc
pathReaders []utils.PathReaderFunc
}
// Create a new scripting environment.
func NewEnvironment(data ...map[string]any) *Environment {
environment := &Environment{
Name: DefaultEnvironmentName,
modules: make(map[string]Module),
replHandlers: make(map[string]InteractiveHandlerFunc),
filterCommands: make(map[string]bool),
pathWriters: make([]utils.PathWriterFunc, 0),
pathReaders: make([]utils.PathReaderFunc, 0),
}
environment.pushScope(scripting.NewScope(nil))
for _, d := range data {
environment.SetData(d)
}
environment.RegisterModule(scripting.UnqualifiedModuleName, core.New(environment))
environment.RegisterModule(`assert`, cmdassert.New(environment))
environment.RegisterModule(`encode`, cmdencode.New(environment))
environment.RegisterModule(`file`, cmdfile.New(environment))
environment.RegisterModule(`fmt`, cmdfmt.New(environment))
environment.RegisterModule(`http`, cmdhttp.New(environment))
environment.RegisterModule(`parse`, cmdparse.New(environment))
environment.RegisterModule(`url`, cmdurl.New(environment))
environment.RegisterModule(`utils`, cmdutils.New(environment))
environment.RegisterModule(`vars`, cmdvars.New(environment))
// use the "http" module (and its 🔔bells🔔 & whistles) to retrieve HTTP(S) links
environment.RegisterPathReader(func(path string) (io.ReadCloser, error) {
var scheme, _ = stringutil.SplitPair(strings.ToLower(path), `:`)
switch scheme {
case `http`, `https`:
if mod, ok := environment.modules[`http`]; ok {
if chttp, ok := mod.(*cmdhttp.Commands); ok {
if res, err := chttp.Get(path, &cmdhttp.RequestArgs{
RawBody: true,
}); err == nil {
if rc, ok := res.Body.(io.ReadCloser); ok {
return rc, nil
} else {
return nil, fmt.Errorf("invalid response type (%T)", res.Body)
}
} else {
return nil, err
}
}
}
}
return nil, nil
})
return environment
}
// Registers a command module to the given prefix. If a module with the same prefix already exists,
// it will be replaced with the given module. Prefixes will be stripped of spaces and converted to
// snake_case. If an empty prefix is given, the default UnqualifiedModuleName ("core") will be used.
func (self *Environment) RegisterModule(prefix string, module Module) {
prefix = strings.TrimSpace(prefix)
prefix = stringutil.Underscore(prefix)
if prefix == `` {
prefix = scripting.UnqualifiedModuleName
}
self.modules[prefix] = module
}
// Removes a registered module at the given prefix.
func (self *Environment) UnregisterModule(prefix string) {
delete(self.modules, prefix)
}
// Specify a command that should not be permitted to execute.
func (self *Environment) DisableCommand(module string, cmdname string) {
if module == `` {
module = scripting.UnqualifiedModuleName
}
self.filterCommands[module+scripting.CommandSeparator+cmdname] = true
}
// Specify a command that should be permitted to execute.
func (self *Environment) EnableCommand(module string, cmdname string) {
if module == `` {
module = scripting.UnqualifiedModuleName
}
delete(self.filterCommands, module+scripting.CommandSeparator+cmdname)
}
// List all commands supported by all registered modules.
func (self *Environment) Commands() []string {
commands := make([]string, 0)
for name, module := range self.Modules() {
for _, cmdname := range utils.ListModuleCommands(module) {
fullname := name + scripting.CommandSeparator + cmdname
if _, ok := self.filterCommands[fullname]; !ok {
commands = append(commands, fullname)
}
}
}
sort.Strings(commands)
return commands
}
// Retrieve a copy of the currently registered modules.
func (self *Environment) Modules() map[string]Module {
modules := make(map[string]Module)
maps.Copy(modules, self.modules)
return modules
}
// Retrieve the named module.
func (self *Environment) Module(name string) (Module, bool) {
module, ok := self.modules[name]
return module, ok
}
// Retrieve the named module, or panic if it is not registered.
func (self *Environment) MustModule(name string) Module {
if module, ok := self.modules[name]; ok {
return module
} else {
panic(fmt.Sprintf("Module '%v' is not registered to this Friendscript environment", name))
}
}
// Registers a function to handle a specific REPL command. If command is an empty string, the function will be called
// for each command entered into the REPL.
func (self *Environment) RegisterCommandHandler(command string, handler InteractiveHandlerFunc) error {
if _, ok := self.replHandlers[command]; ok {
return fmt.Errorf("A handler is already registered for the interactive command '%s'", command)
} else {
self.replHandlers[command] = handler
return nil
}
}
// Registers a handler that will receive updates on execution context and state as the script is running.
// Will return an integer that can be used to remove the handler at a later point.
func (self *Environment) RegisterContextHandler(handler ContextHandlerFunc) int {
self.chlock.Lock()
defer self.chlock.Unlock()
self.contextHandlers = append(self.contextHandlers, handler)
return len(self.contextHandlers)
}
// Remove the context handler with the given ID.
func (self *Environment) UnregisterContextHandler(id int) {
self.chlock.Lock()
defer self.chlock.Unlock()
self.contextHandlers = append(self.contextHandlers[:id], self.contextHandlers[id+1:]...)
}
func (self *Environment) EvaluateFile(path string, scope ...*scripting.Scope) (*scripting.Scope, error) {
if script, err := scripting.LoadFromFile(path); err == nil {
return self.Evaluate(script, scope...)
} else {
return nil, err
}
}
func (self *Environment) EvaluateReader(reader io.Reader, scope ...*scripting.Scope) (*scripting.Scope, error) {
var data []byte
var errchan = make(chan error)
go func() {
if d, err := ioutil.ReadAll(reader); err == nil {
data = d
errchan <- nil
} else {
errchan <- err
}
}()
select {
case err := <-errchan:
if err == nil {
return self.EvaluateString(string(data), scope...)
} else {
return nil, err
}
case <-time.After(MaxReaderWait):
return nil, fmt.Errorf("Failed to read Friendscript after %v", MaxReaderWait)
}
}
func (self *Environment) EvaluateString(data string, scope ...*scripting.Scope) (*scripting.Scope, error) {
if script, err := scripting.Parse(data); err == nil {
return self.Evaluate(script, scope...)
} else {
return nil, err
}
}
func (self *Environment) Evaluate(script *scripting.Friendscript, scope ...*scripting.Scope) (*scripting.Scope, error) {
var rootScope *scripting.Scope
if len(scope) > 0 && scope[0] != nil {
rootScope = scope[0]
} else {
rootScope = self.Scope()
}
rootScope.Environment = self
self.script = script
self.pushScope(rootScope)
for _, block := range script.Blocks() {
if err := self.evaluateBlock(block); err != nil {
return self.Scope(), err
}
}
return self.Scope(), nil
}
func (self *Environment) Run(scriptName string, options *utils.RunOptions) (any, error) {
var fsp = os.Getenv(`FRIENDSCRIPT_PATH`)
var searchPaths = sliceutil.CompactString(strings.Split(fsp, `:`))
scriptName = strings.TrimSuffix(scriptName, `.fs`)
if options == nil {
options = &utils.RunOptions{
Isolated: true,
BasePath: `.`,
}
}
// if the script is an absolute path, then we won't be searching for anything
if filepath.IsAbs(scriptName) {
searchPaths = []string{scriptName}
} else {
// prepend the dirname of the calling script to the searchPaths
searchPaths = append([]string{options.BasePath}, searchPaths...)
// join all the search paths with the candidate script name
for i, sp := range searchPaths {
searchPaths[i] = filepath.Join(sp, scriptName+`.fs`)
}
}
// find the file
for _, candidate := range searchPaths {
if !fileutil.IsNonemptyFile(candidate) {
continue
}
var scope *scripting.Scope
if options.Isolated {
scope = scripting.NewEphemeralScope(self.Scope())
} else {
scope = scripting.NewScope(self.Scope())
}
if len(options.Data) > 0 {
for k, v := range options.Data {
scope.Set(k, v)
}
}
if res, err := self.EvaluateFile(candidate, scope); err == nil {
if options.ResultKey == `` {
return res.MostRecentValue(), err
} else {
return res.Get(options.ResultKey), nil
}
} else {
return nil, err
}
}
return nil, fmt.Errorf("could not locate script %q", scriptName)
}
func (self *Environment) replCompleter(d prompt.Document) []prompt.Suggest {
suggestions := []prompt.Suggest{}
// {Text: "users", Description: "Store the username and age"},
// {Text: "articles", Description: "Store the article text posted by user"},
// {Text: "comments", Description: "Store the text commented to articles"},
return prompt.FilterHasPrefix(suggestions, d.GetWordBeforeCursor(), true)
}
func (self *Environment) REPL() (*scripting.Scope, error) {
var replScope = scripting.NewScope(nil)
var replErr error
var options = []prompt.Option{
prompt.OptionPrefix(self.Name + `> `),
}
var exec = func(line string) {
if handled, err := self.evaluateReplBuiltin(line); handled {
if err != nil {
fmt.Println(err.Error())
}
} else {
_, replErr = self.EvaluateString(line, replScope)
if replErr != nil {
fmt.Println(replErr.Error())
}
}
}
var repl = prompt.New(exec, self.replCompleter, options...)
repl.Run()
return replScope, replErr
}
func (self *Environment) evaluateReplBuiltin(line string) (bool, error) {
var handler InteractiveHandlerFunc
cmd, _ := stringutil.SplitPair(strings.TrimSpace(line), ` `)
ctx := &InteractiveContext{
Command: cmd,
Line: line,
}
if h, ok := self.replHandlers[cmd]; ok {
handler = h
} else if h, ok := self.replHandlers[``]; ok {
handler = h
}
if handler != nil {
if output, err := handler(ctx, self); err == nil {
for _, line := range output {
fmt.Println(line)
}
} else {
fmt.Println(color.New(color.FgRed).Sprint(`error:`) + ` ` + err.Error())
}
return true, nil
} else {
return false, nil
}
}
func (self *Environment) pushScope(scope *scripting.Scope) {
// if len(self.stack) > 0 {
// log.Debugf("PUSH scope(%d) is masked", self.Scope().Level())
// } else {
// log.Debugf("PUSH scope(%d) is ROOT", scope.Level())
// }
if len(self.stack) == 0 || scope != self.Scope() {
self.stack = append(self.stack, scope)
}
if self.script != nil {
self.script.SetScope(self.Scope())
}
// log.Debugf("PUSH scope(%d) is active", self.Scope().Level())
}
func (self *Environment) Scope() *scripting.Scope {
if len(self.stack) > 0 {
return self.stack[len(self.stack)-1]
} else {
panic("Scope not available yet")
}
}
func (self *Environment) Set(key string, value any) {
self.Scope().Set(key, value)
}
func (self *Environment) Get(key string, fallback ...any) any {
return self.Scope().Get(key, fallback...)
}
func (self *Environment) SetData(data map[string]any) {
for k, v := range data {
self.Set(k, v)
}
}
func (self *Environment) popScope() *scripting.Scope {
if len(self.stack) > 1 {
top := self.stack[len(self.stack)-1]
self.stack = self.stack[0 : len(self.stack)-1]
if self.script != nil {
self.script.SetScope(self.Scope())
}
// log.Debugf("POP scope(%d) is active", self.Scope().Level())
return top
} else if len(self.stack) == 1 {
return self.stack[0]
} else {
log.Fatal("attempted pop on an empty scope stack")
return nil
}
}
func (self *Environment) evaluateBlock(block *scripting.Block) error {
switch block.Type() {
case scripting.EventHandlerBlock:
return fmt.Errorf("Not Implemented")
case scripting.FlowControlWord:
if levels := block.FlowBreak(); levels > 0 {
return scripting.NewFlowControl(scripting.FlowBreak, levels)
} else if levels := block.FlowContinue(); levels > 0 {
return scripting.NewFlowControl(scripting.FlowContinue, levels)
} else {
return fmt.Errorf("invalid flow control statement")
}
case scripting.StatementBlock:
for _, statement := range block.Statements() {
if err := self.evaluateStatement(statement); err != nil {
return err
}
}
}
return nil
}
func (self *Environment) evaluateStatement(statement *scripting.Statement) error {
switch statement.Type() {
case scripting.AssignmentStatement:
return self.evaluateAssignment(statement.Assignment(), false)
case scripting.DirectiveStatement:
return self.evaluateDirective(statement.Directive())
case scripting.ConditionalStatement:
_, err := self.evaluateConditional(statement.Conditional())
return err
case scripting.LoopStatement:
return self.evaluateLoop(statement.Loop())
case scripting.CommandStatement:
_, _, err := self.evaluateCommand(statement.Command(), false)
return err
case scripting.NoOpStatement:
return nil
default:
return fmt.Errorf("Unrecognized statement: %v", statement.Type())
}
}
func (self *Environment) evaluateAssignment(assignment *scripting.Assignment, forceDeclare bool) error {
log.Debugf("ASSN %v", assignment)
// clear out all the left-hand side variables (if there isn't already one in this scope)
if assignment.Operator.ShouldPreclear() {
for _, lhs := range assignment.LeftHandSide {
if scope := self.Scope(); !scope.IsLocal(lhs) {
if forceDeclare {
scope.Declare(lhs)
} else if !scope.SkipPreclear { // this line is erasing variables in a loop before performing the RHS eval
scope.Set(lhs, nil)
}
}
}
}
// unpack
if len(assignment.RightHandSide) == 1 {
if rhs, err := assignment.RightHandSide[0].Value(); err == nil {
totalLhsCount := len(assignment.LeftHandSide)
if totalLhsCount > 1 && typeutil.IsArray(rhs) {
for i, rhs := range sliceutil.Sliceify(rhs) {
if i < totalLhsCount {
if result, err := assignment.Operator.Evaluate(
self.Scope().Get(assignment.LeftHandSide[i]),
rhs,
); err == nil {
self.Scope().Set(assignment.LeftHandSide[i], result)
} else {
return err
}
}
}
return nil
}
}
}
for i, lhs := range assignment.LeftHandSide {
if i < len(assignment.RightHandSide) {
if result, err := assignment.Operator.Evaluate(
self.Scope().Get(lhs),
assignment.RightHandSide[i],
); err == nil {
self.Scope().Set(lhs, result)
} else {
return err
}
}
}
return nil
}
func (self *Environment) evaluateDirective(directive *scripting.Directive) error {
switch directive.Type() {
case scripting.UnsetDirective:
return fmt.Errorf("'unset' not implemented yet")
case scripting.IncludeDirective:
return fmt.Errorf("'include' not implemented yet")
case scripting.DeclareDirective:
for _, varname := range directive.VariableNames() {
self.Scope().Declare(varname)
}
}
return nil
}
// make this an interface scripting.Commandable{}, use it to let scripting statements call commands
func (self *Environment) ExecuteCommand(command *scripting.Command) (string, any, error) {
return self.evaluateCommand(command, true)
}
func (self *Environment) evaluateCommand(command *scripting.Command, forceDeclare bool) (string, any, error) {
var modname, name = command.Name()
// prevent the execution of disabled commands
if reject, _ := self.filterCommands[modname+scripting.CommandSeparator+name]; reject {
return ``, nil, fmt.Errorf("Execution of the %s::%s command has been disabled", modname, name)
}
if a, _, _ := command.Args(); a != nil {
log.Debugf("CMD %v::%v %v", modname, name, typeutil.JSON(a))
} else {
log.Debugf("CMD %v::%v", modname, name)
}
var ctx = command.SourceContext()
self.sendContextUpdate(ctx, false)
if first, rest, err := command.Args(); err == nil {
// locate the module this command belongs to
if module, ok := self.modules[modname]; ok {
// log.Debugf("CMND called %T(%v), %T(%v)", first, first, rest, rest)
// tell that module to execute the command, giving it the name and arguments
var evalscope = self.Scope()
evalscope.LockContext(ctx)
result, err := module.ExecuteCommand(name, first, rest)
evalscope.Unlock()
if err == nil {
self.sendContextUpdate(ctx, true)
// log.Debugf("CMND returned %T(%v)", result, result)
// if there is an output variable destination, set that in the current scope
if resultVar := command.OutputName(); resultVar != `` {
if forceDeclare {
evalscope.Declare(resultVar)
}
evalscope.Set(resultVar, result)
return resultVar, result, nil
}
return ``, result, nil
} else {
ctx.Error = err
}
} else {
ctx.Error = fmt.Errorf("Cannot locate module %q", modname)
}
} else {
ctx.Error = fmt.Errorf("invalid arguments: %v", err)
}
self.sendContextUpdate(ctx, true)
return ``, nil, ctx.Error
}
func (self *Environment) evaluateConditional(conditional *scripting.Conditional) (bool, error) {
var blocks = make([]*scripting.Block, 0)
var takeTrueBranch bool
var conditionScope = scripting.NewScope(self.Scope())
conditionScope.SkipPreclear = true
self.pushScope(conditionScope)
defer self.popScope()
switch conditional.Type() {
case scripting.ConditionWithAssignment:
assignment, condition := conditional.WithAssignment()
if err := self.evaluateAssignment(assignment, true); err == nil {
result := condition.IsTrue()
blocks, takeTrueBranch = self.evaluateConditionalGetBranch(conditional, result)
} else {
return takeTrueBranch, err
}
case scripting.ConditionWithCommand:
command, condition := conditional.WithCommand()
if _, _, err := self.evaluateCommand(command, true); err == nil {
result := condition.IsTrue()
blocks, takeTrueBranch = self.evaluateConditionalGetBranch(conditional, result)
} else {
return takeTrueBranch, err
}
case scripting.ConditionWithRegex:
expression, matchOp, rx := conditional.WithRegex()
result := matchOp.Evaluate(rx, expression)
blocks, takeTrueBranch = self.evaluateConditionalGetBranch(conditional, result)
case scripting.ConditionWithComparator:
lhs, cmp, rhs := conditional.WithComparator()
result := cmp.Evaluate(lhs, rhs)
blocks, takeTrueBranch = self.evaluateConditionalGetBranch(conditional, result)
default:
return takeTrueBranch, fmt.Errorf("Unrecognized Conditional type")
}
for _, block := range blocks {
if err := self.evaluateBlock(block); err != nil {
return takeTrueBranch, err
}
}
return takeTrueBranch, nil
}
func (self *Environment) evaluateConditionalGetBranch(conditional *scripting.Conditional, result bool) ([]*scripting.Block, bool) {
var blocks = make([]*scripting.Block, 0)
var takeTrueBranch bool
if conditional.IsNegated() {
result = !result
}
if result {
blocks = conditional.IfBlocks()
takeTrueBranch = true
} else {
var tookElifBranch bool
for _, elif := range conditional.ElseIfConditions() {
if t, err := self.evaluateConditional(elif); err == nil {
if t {
tookElifBranch = true
blocks = elif.IfBlocks()
break
}
} else {
log.Fatal(err)
return nil, false
}
}
if !tookElifBranch {
blocks = conditional.ElseBlocks()
}
}
return blocks, takeTrueBranch
}
func (self *Environment) evaluateLoop(loop *scripting.Loop) error {
var sourceVar string
var destVars []string
var loopScope = scripting.NewScope(self.Scope())
loopScope.Declare(`index`)
loopScope.Declare(`index0`)
loopScope.SkipPreclear = true
self.pushScope(loopScope)
defer self.popScope()
// if we have an iterator we have to retrieve the values
if loop.Type() == scripting.IteratorLoop {
if s, d, err := self.evaluateLoopIterationStart(loop, loopScope); err == nil {
sourceVar = s
destVars = d
} else {
return err
}
}
LoopEval:
for {
if i, proceed := loop.Iterate(); proceed {
if loop.Type() == scripting.IteratorLoop {
var iterVector = loopScope.Get(sourceVar)
if typeutil.IsMap(iterVector) {
var remap = make([][]any, 0)
var keys = maputil.StringKeys(iterVector)
sort.Strings(keys)
for _, key := range keys {
remap = append(remap, []any{
key,
maputil.Get(iterVector, key),
})
}
iterVector = remap
}
if iterLen := sliceutil.Len(iterVector); i < iterLen {
if iterItem, ok := sliceutil.At(iterVector, i); ok {
var didSet bool
if totalLhsCount := len(destVars); totalLhsCount > 1 {
if typeutil.IsArray(iterItem) {
for j, rhs := range sliceutil.Sliceify(iterItem) {
if j < totalLhsCount {
loopScope.Set(destVars[j], rhs)
didSet = true
}
}
}
}
if !didSet {
loopScope.Set(destVars[0], iterItem)
}
} else {
return fmt.Errorf("Failed to retrieve iterator item %d", i)
}
} else {
break
}
}
loopScope.Set(`index`, i)
loopScope.Set(`index0`, i-1)
for _, block := range loop.Blocks() {
if err := self.evaluateBlock(block); err != nil {
if fc, ok := err.(*scripting.FlowControlErr); ok {
if fc.Level <= 0 {
return fc
} else if fc.Level == 1 {
if fc.Type == scripting.FlowContinue {
continue LoopEval
} else {
break LoopEval
}
} else {
fc.Level = fc.Level - 1
return fc
}
} else {
return err
}
}
}
} else {
break
}
}
return nil
}
func (self *Environment) evaluateLoopIterationStart(loop *scripting.Loop, scope *scripting.Scope) (string, []string, error) {
var destVars, source = loop.IteratableParts()
var sourceVar string
if cmd, ok := source.(*scripting.Command); ok {
// since we totally need the results of the command to iterate on them, if the command
// didn't specify a result variable, we're going to force it to have one
if outputName := cmd.OutputName(); outputName == `` {
cmd.SetOutputNameOverride(scripting.DefaultIteratorCommandResultVariableName)
}
if resultVar, _, err := self.evaluateCommand(cmd, true); err == nil {
sourceVar = resultVar
} else {
return ``, nil, err
}
} else if srcvar, ok := source.(string); ok {
sourceVar = srcvar
}
for _, v := range destVars {
scope.Declare(v)
}
return sourceVar, destVars, nil
}
func (self *Environment) sendContextUpdate(ctx *scripting.Context, isDone bool) {
self.chlock.Lock()
defer self.chlock.Unlock()
for _, handler := range self.contextHandlers {
handler(ctx, isDone)
}
}