forked from madlambda/nash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshell.go
2499 lines (2026 loc) · 54.1 KB
/
shell.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
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
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package sh
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"os/signal"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"syscall"
"github.com/madlambda/nash/ast"
"github.com/madlambda/nash/errors"
"github.com/madlambda/nash/internal/sh/builtin"
"github.com/madlambda/nash/parser"
"github.com/madlambda/nash/sh"
"github.com/madlambda/nash/token"
)
const (
logNS = "nashell.Shell"
defPrompt = "\033[31mλ>\033[0m "
)
type (
// Env is the environment map of lists
Env map[string]sh.Obj
Var Env
Fns map[string]sh.FnDef
StatusCode uint8
// Shell is the core data structure.
Shell struct {
name string
debug bool
interactive bool
abortOnErr bool
logf LogFn
nashdPath string
isFn bool
filename string // current file being executed or imported
sigs chan os.Signal
interrupted bool
looping bool
stdin io.Reader
stdout io.Writer
stderr io.Writer
env Env
vars Var
binds Fns
root *ast.Tree
parent *Shell
repr string // string representation
nashpath string
nashroot string
*sync.Mutex
}
errIgnore struct {
*errors.NashError
}
errInterrupted struct {
*errors.NashError
}
errStopWalking struct {
*errors.NashError
}
)
const (
ESuccess StatusCode = 0
ENotFound = 127
ENotStarted = 255
)
func newErrIgnore(format string, arg ...interface{}) error {
e := &errIgnore{
NashError: errors.NewError(format, arg...),
}
return e
}
func (e *errIgnore) Ignore() bool { return true }
func newErrInterrupted(format string, arg ...interface{}) error {
return &errInterrupted{
NashError: errors.NewError(format, arg...),
}
}
func (e *errInterrupted) Interrupted() bool { return true }
func newErrStopWalking() *errStopWalking {
return &errStopWalking{
NashError: errors.NewError("return"),
}
}
func (e *errStopWalking) StopWalking() bool { return true }
func NewAbortShell(nashpath string, nashroot string) (*Shell, error) {
return newShell(nashpath, nashroot, true)
}
// NewShell creates a new shell object
// nashpath will be used to search libraries and nashroot will be used to
// search for the standard library shipped with the language.
func NewShell(nashpath string, nashroot string) (*Shell, error) {
return newShell(nashpath, nashroot, false)
}
func newShell(nashpath string, nashroot string, abort bool) (*Shell, error) {
shell := &Shell{
name: "parent scope",
interactive: false,
abortOnErr: abort,
isFn: false,
logf: NewLog(logNS, false),
nashdPath: nashdAutoDiscover(),
stdout: os.Stdout,
stderr: os.Stderr,
stdin: os.Stdin,
env: make(Env),
vars: make(Var),
binds: make(Fns),
Mutex: &sync.Mutex{},
sigs: make(chan os.Signal, 1),
filename: "<interactive>",
nashpath: nashpath,
nashroot: nashroot,
}
err := shell.setup()
if err != nil {
return nil, err
}
shell.setupSignals()
err = validateDirs(nashpath, nashroot)
if err != nil {
if shell.abortOnErr {
return nil, err
}
printerr := func(msg string) {
shell.Stderr().Write([]byte(msg + "\n"))
}
printerr(err.Error())
printerr("please check your NASHPATH and NASHROOT so they point to valid locations")
}
return shell, nil
}
// NewSubShell creates a nashell.Shell that inherits the parent shell stdin,
// stdout, stderr and mutex lock.
// Every variable and function lookup is done first in the subshell and then, if
// not found, in the parent shell recursively.
func NewSubShell(name string, parent *Shell) *Shell {
return &Shell{
name: name,
isFn: true,
parent: parent,
logf: NewLog(logNS, false),
nashdPath: nashdAutoDiscover(),
stdout: parent.Stdout(),
stderr: parent.Stderr(),
stdin: parent.Stdin(),
env: make(Env),
vars: make(Var),
binds: make(Fns),
Mutex: parent.Mutex,
filename: parent.filename,
}
}
func (shell *Shell) NashPath() string {
return shell.nashpath
}
// initEnv creates a new environment from old one
func (shell *Shell) initEnv(processEnv []string) error {
largs := make([]sh.Obj, len(os.Args))
for i := 0; i < len(os.Args); i++ {
largs[i] = sh.NewStrObj(os.Args[i])
}
argv := sh.NewListObj(largs)
shell.Setenv("argv", argv)
shell.Newvar("argv", argv)
for _, penv := range processEnv {
var value sh.Obj
p := strings.Split(penv, "=")
if len(p) >= 2 {
// TODO(i4k): handle lists correctly in the future
// argv is not special, every list must be handled correctly
if p[0] == "argv" {
continue
}
value = sh.NewStrObj(strings.Join(p[1:], "="))
shell.Setenv(p[0], value)
shell.Newvar(p[0], value)
}
}
pidVal := sh.NewStrObj(strconv.Itoa(os.Getpid()))
shell.Setenv("PID", pidVal)
shell.Newvar("PID", pidVal)
if _, ok := shell.Getenv("SHELL"); !ok {
shellVal := sh.NewStrObj(nashdAutoDiscover())
shell.Setenv("SHELL", shellVal)
shell.Newvar("SHELL", shellVal)
}
cwd, err := os.Getwd()
if err != nil {
return err
}
cwdObj := sh.NewStrObj(cwd)
shell.Setenv("PWD", cwdObj)
shell.Newvar("PWD", cwdObj)
return nil
}
// Reset internal state
func (shell *Shell) Reset() {
shell.vars = make(Var)
shell.env = make(Env)
shell.binds = make(Fns)
}
// SetDebug enable/disable debug in the shell
func (shell *Shell) SetDebug(d bool) {
shell.debug = d
shell.logf = NewLog(logNS, d)
}
// SetInteractive enable/disable shell interactive mode
func (shell *Shell) SetInteractive(i bool) {
shell.interactive = i
if i {
_ = shell.setupDefaultBindings()
}
}
func (shell *Shell) Interactive() bool {
if shell.parent != nil {
return shell.parent.Interactive()
}
return shell.interactive
}
func (shell *Shell) SetName(a string) {
shell.name = a
}
func (shell *Shell) Name() string { return shell.name }
func (shell *Shell) SetParent(a *Shell) {
shell.parent = a
}
func (shell *Shell) Environ() Env {
if shell.parent != nil {
return shell.parent.Environ()
}
return shell.env
}
func (shell *Shell) Getenv(name string) (sh.Obj, bool) {
if shell.parent != nil {
return shell.parent.Getenv(name)
}
value, ok := shell.env[name]
return value, ok
}
func (shell *Shell) Setenv(name string, value sh.Obj) {
if shell.parent != nil {
shell.parent.Setenv(name, value)
return
}
shell.Newvar(name, value)
shell.env[name] = value
os.Setenv(name, value.String())
}
func (shell *Shell) SetEnviron(processEnv []string) {
shell.env = make(Env)
for _, penv := range processEnv {
var value sh.Obj
p := strings.Split(penv, "=")
if len(p) == 2 {
value = sh.NewStrObj(p[1])
shell.Setenv(p[0], value)
shell.Newvar(p[0], value)
}
}
}
// GetLocalvar returns a local scoped variable.
func (shell *Shell) GetLocalvar(name string) (sh.Obj, bool) {
v, ok := shell.vars[name]
return v, ok
}
// Getvar returns the value of the variable name. It could look in their
// parent scopes if not found locally.
func (shell *Shell) Getvar(name string) (sh.Obj, bool) {
if value, ok := shell.vars[name]; ok {
return value, ok
}
if shell.parent != nil {
return shell.parent.Getvar(name)
}
return nil, false
}
// GetFn returns the function name or error if not found.
func (shell *Shell) GetFn(name string) (*sh.FnObj, error) {
shell.logf("Looking for function '%s' on shell '%s'\n", name, shell.name)
if obj, ok := shell.vars[name]; ok {
if obj.Type() == sh.FnType {
fnObj := obj.(*sh.FnObj)
return fnObj, nil
}
return nil, errors.NewError("Identifier '%s' is not a function", name)
}
if shell.parent != nil {
return shell.parent.GetFn(name)
}
return nil, fmt.Errorf("function '%s' not found", name)
}
func (shell *Shell) Setbindfn(name string, value sh.FnDef) {
shell.binds[name] = value
}
func (shell *Shell) Getbindfn(cmdName string) (sh.FnDef, bool) {
if fn, ok := shell.binds[cmdName]; ok {
return fn, true
}
if shell.parent != nil {
return shell.parent.Getbindfn(cmdName)
}
return nil, false
}
// Newvar creates a new variable in the scope.
func (shell *Shell) Newvar(name string, value sh.Obj) {
shell.vars[name] = value
}
// Setvar updates the value of an existing variable. If the variable
// doesn't exist in current scope it looks up in their parent scopes.
// It returns true if the variable was found and updated.
func (shell *Shell) Setvar(name string, value sh.Obj) bool {
_, ok := shell.vars[name]
if ok {
shell.vars[name] = value
return true
}
if shell.parent != nil {
return shell.parent.Setvar(name, value)
}
return false
}
func (shell *Shell) IsFn() bool { return shell.isFn }
func (shell *Shell) SetIsFn(b bool) { shell.isFn = b }
// SetNashdPath sets an alternativa path to nashd
func (shell *Shell) SetNashdPath(path string) {
shell.nashdPath = path
}
// SetStdin sets the stdin for commands
func (shell *Shell) SetStdin(in io.Reader) {
shell.stdin = in
}
// SetStdout sets stdout for commands
func (shell *Shell) SetStdout(out io.Writer) {
shell.stdout = out
}
// SetStderr sets stderr for commands
func (shell *Shell) SetStderr(err io.Writer) {
shell.stderr = err
}
func (shell *Shell) Stdout() io.Writer { return shell.stdout }
func (shell *Shell) Stderr() io.Writer { return shell.stderr }
func (shell *Shell) Stdin() io.Reader { return shell.stdin }
// SetTree sets the internal tree of the interpreter. It's used for
// sub-shells like `fn`.
func (shell *Shell) SetTree(t *ast.Tree) {
shell.root = t
}
// Tree returns the internal tree of the subshell.
func (shell *Shell) Tree() *ast.Tree { return shell.root }
// SetRepr set the string representation of the shell
func (shell *Shell) SetRepr(a string) {
shell.repr = a
}
func (shell *Shell) setupBuiltin() {
for name, constructor := range builtin.Constructors() {
fnDef := newBuiltinFnDef(name, shell, constructor)
shell.Newvar(name, sh.NewFnObj(fnDef))
}
}
func (shell *Shell) setupDefaultBindings() error {
// only one builtin fn... no need for advanced machinery yet
homeEnvVar := "HOME"
if runtime.GOOS == "windows" {
homeEnvVar = "HOMEPATH"
}
err := shell.Exec(shell.name, fmt.Sprintf(`fn nash_builtin_cd(args...) {
var path = ""
var l <= len($args)
if $l == "0" {
path = $%s
} else {
path = $args[0]
}
chdir($path)
}
bindfn nash_builtin_cd cd`, homeEnvVar))
return err
}
func (shell *Shell) setup() error {
err := shell.initEnv(os.Environ())
if err != nil {
return err
}
if shell.env["PROMPT"] == nil {
pobj := sh.NewStrObj(defPrompt)
shell.Setenv("PROMPT", pobj)
shell.Newvar("PROMPT", pobj)
}
_, ok := shell.Getvar("_")
if !ok {
shell.Newvar("_", sh.NewStrObj(""))
}
shell.setupBuiltin()
return err
}
func (shell *Shell) setupSignals() {
signal.Notify(shell.sigs, syscall.SIGINT)
go func() {
for {
sig := <-shell.sigs
switch sig {
case syscall.SIGINT:
shell.Lock()
// TODO(i4k): Review implementation when interrupted inside
// function loops
if shell.looping {
shell.setIntr(true)
}
shell.Unlock()
default:
fmt.Printf("%s\n", sig)
}
}
}()
}
// TriggerCTRLC mock the user pressing CTRL-C in the terminal
func (shell *Shell) TriggerCTRLC() error {
p, err := os.FindProcess(os.Getpid())
if err != nil {
return err
}
return p.Signal(syscall.SIGINT)
}
// setIntr *do not lock*. You must do it yourself!
func (shell *Shell) setIntr(b bool) {
if shell.parent != nil {
shell.parent.setIntr(b)
return
}
shell.interrupted = b
}
// getIntr returns true if nash was interrupted by CTRL-C
func (shell *Shell) getIntr() bool {
if shell.parent != nil {
return shell.parent.getIntr()
}
return shell.interrupted
}
// Exec executes the commands specified by string content
func (shell *Shell) Exec(path, content string) error {
p := parser.NewParser(path, content)
tr, err := p.Parse()
if err != nil {
return err
}
_, err = shell.ExecuteTree(tr)
return err
}
// Execute the nash file at given path
func (shell *Shell) ExecFile(path string) error {
bkCurFile := shell.filename
content, err := ioutil.ReadFile(path)
if err != nil {
return err
}
shell.filename = path
defer func() {
shell.filename = bkCurFile
}()
return shell.Exec(path, string(content))
}
func (shell *Shell) newvar(name *ast.NameNode, value sh.Obj) error {
if name.Index == nil {
shell.Newvar(name.Ident, value)
return nil
}
// handles ident[x] = v
obj, ok := shell.Getvar(name.Ident)
if !ok {
return errors.NewEvalError(shell.filename,
name, "Variable %s not found", name.Ident)
}
index, err := shell.evalIndex(name.Index)
if err != nil {
return err
}
col, err := sh.NewWriteableCollection(obj)
if err != nil {
return errors.NewEvalError(shell.filename, name, err.Error())
}
err = col.Set(index, value)
if err != nil {
return errors.NewEvalError(
shell.filename,
name,
"error[%s] setting var",
err,
)
}
shell.Newvar(name.Ident, obj)
return nil
}
func (shell *Shell) setvar(name *ast.NameNode, value sh.Obj) error {
if name.Index == nil {
if !shell.Setvar(name.Ident, value) {
return errors.NewEvalError(shell.filename,
name, "Variable '%s' is not initialized. Use 'var %s = <value>'",
name, name)
}
return nil
}
obj, ok := shell.Getvar(name.Ident)
if !ok {
return errors.NewEvalError(shell.filename,
name, "Variable %s not found", name.Ident)
}
index, err := shell.evalIndex(name.Index)
if err != nil {
return err
}
col, err := sh.NewWriteableCollection(obj)
if err != nil {
return errors.NewEvalError(shell.filename, name, err.Error())
}
err = col.Set(index, value)
if err != nil {
return errors.NewEvalError(
shell.filename,
name,
"error[%s] setting var",
err,
)
}
if !shell.Setvar(name.Ident, obj) {
return errors.NewEvalError(shell.filename,
name, "Variable '%s' is not initialized. Use 'var %s = <value>'",
name, name)
}
return nil
}
func (shell *Shell) setvars(names []*ast.NameNode, values []sh.Obj) error {
for i := 0; i < len(names); i++ {
err := shell.setvar(names[i], values[i])
if err != nil {
return err
}
}
return nil
}
func (shell *Shell) newvars(names []*ast.NameNode, values []sh.Obj) {
for i := 0; i < len(names); i++ {
shell.newvar(names[i], values[i])
}
}
func (shell *Shell) setcmdvars(names []*ast.NameNode, stdout, stderr, status sh.Obj) error {
if len(names) == 3 {
err := shell.setvar(names[0], stdout)
if err != nil {
return err
}
err = shell.setvar(names[1], stderr)
if err != nil {
return err
}
return shell.setvar(names[2], status)
} else if len(names) == 2 {
err := shell.setvar(names[0], stdout)
if err != nil {
return err
}
return shell.setvar(names[1], status)
} else if len(names) == 1 {
return shell.setvar(names[0], stdout)
}
panic(fmt.Sprintf("internal error: expects 1 <= len(names) <= 3,"+
" but got %d",
len(names)))
return nil
}
func (shell *Shell) newcmdvars(names []*ast.NameNode, stdout, stderr, status sh.Obj) {
if len(names) == 3 {
shell.newvar(names[0], stdout)
shell.newvar(names[1], stderr)
shell.newvar(names[2], status)
} else if len(names) == 2 {
shell.newvar(names[0], stdout)
shell.newvar(names[1], status)
} else if len(names) == 1 {
shell.newvar(names[0], stdout)
} else {
panic(fmt.Sprintf("internal error: expects 1 <= len(names) <= 3,"+
" but got %d",
len(names)))
}
}
// evalConcat reveives the AST representation of a concatenation of objects and
// returns the string representation, or error.
func (shell *Shell) evalConcat(path ast.Expr) (string, error) {
var pathStr string
if path.Type() != ast.NodeConcatExpr {
return "", fmt.Errorf("Invalid node %+v", path)
}
concatExpr := path.(*ast.ConcatExpr)
concat := concatExpr.List()
for i := 0; i < len(concat); i++ {
part := concat[i]
switch part.Type() {
case ast.NodeConcatExpr:
return "", errors.NewEvalError(shell.filename, part,
"Nested concat is not allowed: %s", part)
case ast.NodeVarExpr, ast.NodeIndexExpr:
partValue, err := shell.evalVariable(part)
if err != nil {
return "", err
}
if partValue.Type() == sh.ListType {
return "", errors.NewEvalError(shell.filename,
part, "Concat of list variables is not allowed: %v = %v",
part, partValue)
} else if partValue.Type() != sh.StringType {
return "", errors.NewEvalError(shell.filename, part,
"Invalid concat element: %v", partValue)
}
strval := partValue.(*sh.StrObj)
pathStr += strval.Str()
case ast.NodeStringExpr:
str, ok := part.(*ast.StringExpr)
if !ok {
return "", errors.NewEvalError(shell.filename, part,
"Failed to eval string: %s", part)
}
pathStr += str.Value()
case ast.NodeFnInv:
fnNode := part.(*ast.FnInvNode)
result, err := shell.executeFnInv(fnNode)
if err != nil {
return "", err
}
if len(result) == 0 || len(result) > 1 {
return "", errors.NewEvalError(shell.filename, part,
"Function '%s' used in string concat but returns %d values.",
fnNode.Name)
}
obj := result[0]
if obj.Type() != sh.StringType {
return "", errors.NewEvalError(shell.filename, part,
"Function '%s' used in concat but returns a '%s'", obj.Type())
}
str := obj.(*sh.StrObj)
pathStr += str.Str()
case ast.NodeListExpr:
return "", errors.NewEvalError(shell.filename, part,
"Concat of lists is not allowed: %+v", part.String())
default:
return "", errors.NewEvalError(shell.filename, part,
"Invalid argument: %+v", part)
}
}
return pathStr, nil
}
func (shell *Shell) executeNode(node ast.Node) ([]sh.Obj, error) {
var (
objs []sh.Obj
err error
)
shell.logf("Executing node: %v\n", node)
switch node.Type() {
case ast.NodeImport:
err = shell.executeImport(node.(*ast.ImportNode))
case ast.NodeComment:
// ignore
case ast.NodeSetenv:
err = shell.executeSetenv(node.(*ast.SetenvNode))
case ast.NodeVarAssignDecl:
err = shell.executeVarAssign(node.(*ast.VarAssignDeclNode))
case ast.NodeVarExecAssignDecl:
err = shell.executeVarExecAssign(node.(*ast.VarExecAssignDeclNode))
case ast.NodeAssign:
err = shell.executeAssignment(node.(*ast.AssignNode))
case ast.NodeExecAssign:
err = shell.executeExecAssign(node.(*ast.ExecAssignNode))
case ast.NodeCommand:
_, err = shell.executeCommand(node.(*ast.CommandNode))
case ast.NodePipe:
_, err = shell.executePipe(node.(*ast.PipeNode))
case ast.NodeRfork:
err = shell.executeRfork(node.(*ast.RforkNode))
case ast.NodeIf:
objs, err = shell.executeIf(node.(*ast.IfNode))
case ast.NodeFnDecl:
err = shell.executeFnDecl(node.(*ast.FnDeclNode))
case ast.NodeFnInv:
// invocation ignoring output
_, err = shell.executeFnInv(node.(*ast.FnInvNode))
case ast.NodeFor:
objs, err = shell.executeFor(node.(*ast.ForNode))
case ast.NodeBindFn:
err = shell.executeBindFn(node.(*ast.BindFnNode))
case ast.NodeReturn:
if shell.IsFn() {
objs, err = shell.executeReturn(node.(*ast.ReturnNode))
} else {
err = errors.NewEvalError(shell.filename,
node,
"Unexpected return outside of function declaration.")
}
default:
// should never get here
return nil, errors.NewEvalError(shell.filename, node,
"invalid node: %v.", node.Type())
}
return objs, err
}
func (shell *Shell) ExecuteTree(tr *ast.Tree) ([]sh.Obj, error) {
return shell.executeTree(tr, true)
}
// executeTree evaluates the given tree
func (shell *Shell) executeTree(tr *ast.Tree, stopable bool) ([]sh.Obj, error) {
if tr == nil || tr.Root == nil {
return nil, errors.NewError("empty abstract syntax tree to execute")
}
root := tr.Root
for _, node := range root.Nodes {
objs, err := shell.executeNode(node)
if err != nil {
type (
IgnoreError interface {
Ignore() bool
}
InterruptedError interface {
Interrupted() bool
}
StopWalkingError interface {
StopWalking() bool
}
)
if errIgnore, ok := err.(IgnoreError); ok && errIgnore.Ignore() {
continue
}
if errInterrupted, ok := err.(InterruptedError); ok && errInterrupted.Interrupted() {
return nil, err
}
if errStopWalking, ok := err.(StopWalkingError); stopable && ok && errStopWalking.StopWalking() {
return objs, nil
}
return objs, err
}
}
return nil, nil
}
func (shell *Shell) executeReturn(n *ast.ReturnNode) ([]sh.Obj, error) {
var returns []sh.Obj
returnExprs := n.Returns
for i := 0; i < len(returnExprs); i++ {
retExpr := returnExprs[i]
obj, err := shell.evalExpr(retExpr)
if err != nil {
return nil, err
}
returns = append(returns, obj)
}
return returns, newErrStopWalking()
}
func (shell *Shell) getNashRootFromGOPATH(preverr error) (string, error) {
g, hasgopath := shell.Getenv("GOPATH")
if !hasgopath {
return "", errors.NewError("%s\nno GOPATH env var setted", preverr)
}
gopath := g.String()
return filepath.Join(gopath, filepath.FromSlash("/src/github.com/madlambda/nash")), nil
}
func isValidNashRoot(nashroot string) bool {
_, err := os.Stat(filepath.Join(nashroot, "stdlib"))
return err == nil
}
func (shell *Shell) executeImport(node *ast.ImportNode) error {
obj, err := shell.evalExpr(node.Path)
if err != nil {
return errors.NewEvalError(shell.filename,
node, err.Error())
}
if obj.Type() != sh.StringType {
return errors.NewEvalError(shell.filename,
node.Path,
"Invalid type on import argument: %s", obj.Type())
}
objstr := obj.(*sh.StrObj)
fname := objstr.Str()
shell.logf("Importing '%s'", fname)
var (
tries []string
hasExt bool
)
hasExt = filepath.Ext(fname) != ""
if filepath.IsAbs(fname) {
tries = append(tries, fname)
if !hasExt {
tries = append(tries, fname+".sh")
}
}
if shell.filename != "" {
localFile := filepath.Join(filepath.Dir(shell.filename), fname)
tries = append(tries, localFile)
if !hasExt {
tries = append(tries, localFile+".sh")
}
}
tries = append(tries, filepath.Join(shell.nashpath, "lib", fname))
if !hasExt {
tries = append(tries, filepath.Join(shell.nashpath, "lib", fname+".sh"))
}
tries = append(tries, filepath.Join(shell.nashroot, "stdlib", fname+".sh"))
shell.logf("Trying %q\n", tries)
for _, path := range tries {