2017-07-12 03:35:08 +08:00
|
|
|
// Package nodeutil provides utilities for inspecting the AST.
|
2017-05-30 06:39:40 +08:00
|
|
|
package nodeutil
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strings"
|
|
|
|
|
2017-07-20 18:45:00 +08:00
|
|
|
"github.com/elves/elvish/eval"
|
2017-05-30 06:39:40 +08:00
|
|
|
"github.com/elves/elvish/parse"
|
|
|
|
"github.com/elves/elvish/util"
|
|
|
|
)
|
|
|
|
|
2017-07-20 18:45:00 +08:00
|
|
|
var logger = util.GetLogger("[nodeutil] ")
|
|
|
|
|
|
|
|
func SimpleCompound(cn *parse.Compound, upto *parse.Indexing, ev *eval.Evaler) (bool, string, error) {
|
2017-05-30 06:39:40 +08:00
|
|
|
tilde := false
|
|
|
|
head := ""
|
|
|
|
for _, in := range cn.Indexings {
|
|
|
|
if len(in.Indicies) > 0 {
|
|
|
|
return false, "", nil
|
|
|
|
}
|
|
|
|
switch in.Head.Type {
|
|
|
|
case parse.Tilde:
|
|
|
|
tilde = true
|
|
|
|
case parse.Bareword, parse.SingleQuoted, parse.DoubleQuoted:
|
|
|
|
head += in.Head.Value
|
2017-07-20 18:45:00 +08:00
|
|
|
case parse.Variable:
|
|
|
|
if ev == nil {
|
|
|
|
return false, "", nil
|
|
|
|
}
|
|
|
|
v := PurelyEvalPrimary(in.Head, ev)
|
|
|
|
if s, ok := v.(eval.String); ok {
|
|
|
|
head += string(s)
|
|
|
|
} else {
|
|
|
|
return false, "", nil
|
|
|
|
}
|
2017-05-30 06:39:40 +08:00
|
|
|
default:
|
|
|
|
return false, "", nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if in == upto {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if tilde {
|
|
|
|
i := strings.Index(head, "/")
|
|
|
|
if i == -1 {
|
|
|
|
i = len(head)
|
|
|
|
}
|
|
|
|
uname := head[:i]
|
|
|
|
home, err := util.GetHome(uname)
|
|
|
|
if err != nil {
|
|
|
|
return false, "", err
|
|
|
|
}
|
|
|
|
head = home + head[i:]
|
|
|
|
}
|
|
|
|
return true, head, nil
|
|
|
|
}
|
2017-07-20 18:45:00 +08:00
|
|
|
|
|
|
|
// PurelyEvalPrimary evaluates a primary node without causing any side effects.
|
|
|
|
// If this cannot be done, it returns nil.
|
|
|
|
//
|
|
|
|
// Currently, only string literals and variables with no @ can be evaluated.
|
|
|
|
func PurelyEvalPrimary(pn *parse.Primary, ev *eval.Evaler) eval.Value {
|
|
|
|
switch pn.Type {
|
|
|
|
case parse.Bareword, parse.SingleQuoted, parse.DoubleQuoted:
|
|
|
|
return eval.String(pn.Value)
|
|
|
|
case parse.Variable:
|
|
|
|
explode, ns, name := eval.ParseVariable(pn.Value)
|
|
|
|
if explode {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
ec := eval.NewTopEvalCtx(ev, "[pure eval]", "", nil)
|
|
|
|
variable := ec.ResolveVar(ns, name)
|
2017-10-01 10:47:25 +08:00
|
|
|
if variable != nil {
|
|
|
|
return variable.Get()
|
|
|
|
}
|
2017-07-20 18:45:00 +08:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|