126e7593b2
resource_api names title-pattern captures with `Regexp.new(pattern).names`, which counts only real named groups. w10k matched `(?<name>` anywhere in the source, so an escaped paren, a character class or a comment added names puppet never emits. - scan patterns as Onigmo does: escapes, nested character classes, `(?#...)` and extended-mode comments hold no groups; names stay unique in first-appearance order - skip a pattern whose names or back references fall outside what w10k models (Unicode or hyphenated names, `\g`, forward `\k`) - bump gentypes.Version to 14 Reviewed-on: #20 Co-authored-by: unkin-agent <unkin-agent@unkin.net> Co-committed-by: unkin-agent <unkin-agent@unkin.net>
1654 lines
47 KiB
Go
1654 lines
47 KiB
Go
package gentypes
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"maps"
|
|
"regexp"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"unicode"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
// Evaluator budgets: inlined singleton-method depth, and the tokens and bytes one world may spend.
|
|
const (
|
|
maxCalls = 8
|
|
maxWorldSteps = 1 << 24
|
|
maxWorldAlloc = 1 << 26
|
|
)
|
|
|
|
// sdef is a singleton method body without parameters, evaluated in the lexical scope of the file defining it.
|
|
type sdef struct {
|
|
toks []token
|
|
start, end int
|
|
consts map[string]rval
|
|
cref []string
|
|
mod, dir string
|
|
file, src string
|
|
param string
|
|
// optional parameters with their one-token literal defaults, and the &block parameter
|
|
opts []sparam
|
|
block string
|
|
}
|
|
|
|
type sparam struct {
|
|
name string
|
|
tok int
|
|
}
|
|
|
|
var errNext = errors.New("next")
|
|
|
|
func (w *world) classSdefs(name string) map[string]*sdef {
|
|
if w.sdefs == nil {
|
|
w.sdefs = map[string]map[string]*sdef{}
|
|
}
|
|
if w.sdefs[name] == nil {
|
|
w.sdefs[name] = map[string]*sdef{}
|
|
}
|
|
return w.sdefs[name]
|
|
}
|
|
|
|
// charge counts n bytes against the world's allocation budget.
|
|
func (p *parser) charge(n int) {
|
|
b := &p.alloc
|
|
if p.w != nil {
|
|
b = &p.w.alloc
|
|
}
|
|
if *b += n; *b > maxWorldAlloc {
|
|
panic(errBudget)
|
|
}
|
|
}
|
|
|
|
// defSingleton records the singleton method whose name is at p.i+off; a method taking parameters is opaque.
|
|
func (c *classCtx) defSingleton(p *parser, name string, off int) *sdef {
|
|
sd := p.newSdef(off)
|
|
if sd == nil {
|
|
c.opaque(name)
|
|
return nil
|
|
}
|
|
if c.sdefs == nil {
|
|
c.sdefs = map[string]*sdef{}
|
|
}
|
|
c.sdefs[name] = sd
|
|
return sd
|
|
}
|
|
|
|
// newSdef starts the body of the method whose name is at p.i+off, or returns nil when the method takes parameters.
|
|
// newSdef starts the body of the method whose name is at p.i+off, or returns nil when a call without arguments would
|
|
// not bind its parameters: only optional ones with literal defaults and a &block parameter are allowed.
|
|
func (p *parser) newSdef(off int) *sdef {
|
|
sd := &sdef{toks: p.toks, consts: p.consts, cref: slices.Clone(p.cref), mod: p.mod, dir: p.dir, file: p.file, src: p.src}
|
|
j := off + 1
|
|
if t := p.at(j); t.text == "(" && !t.space {
|
|
for j++; p.at(j).text != ")"; j++ {
|
|
t, eq, def := p.at(j), p.at(j+1), p.at(j+2)
|
|
switch {
|
|
case t.text == "&" && isLocal(eq) && sd.block == "":
|
|
sd.block = eq.text
|
|
j++
|
|
case isLocal(t) && eq.text == "=" && (def.kind == tStr && len(def.parts) <= 1 && (len(def.parts) == 0 || !def.parts[0].code) && def.flags != "`" || def.kind == tSym && def.parts == nil ||
|
|
def.kind == tNum || def.kind == tIdent && (def.text == "nil" || def.text == "true" || def.text == "false")):
|
|
sd.opts = append(sd.opts, sparam{t.text, p.i + j + 2})
|
|
j += 2
|
|
default:
|
|
return nil
|
|
}
|
|
if p.at(j+1).text == "," {
|
|
j++
|
|
} else if p.at(j+1).text != ")" {
|
|
return nil
|
|
}
|
|
}
|
|
j++
|
|
}
|
|
if t := p.at(j); t.kind != tNL && t.text != ";" {
|
|
return nil
|
|
}
|
|
sd.start = p.i + j
|
|
return sd
|
|
}
|
|
|
|
// opaque marks singleton methods w10k does not evaluate, such as accessors and command methods.
|
|
func (c *classCtx) opaque(names ...string) {
|
|
if c.sdefs == nil {
|
|
c.sdefs = map[string]*sdef{}
|
|
}
|
|
for _, n := range names {
|
|
c.sdefs[n] = nil
|
|
}
|
|
}
|
|
|
|
// singleton finds singleton method name on c's class, then up its user superclasses.
|
|
func (p *parser) singleton(c *classCtx, name string) (sd *sdef, found bool, err error) {
|
|
if sd, ok := c.sdefs[name]; ok {
|
|
return sd, true, nil
|
|
}
|
|
if c.parentUnknown {
|
|
return nil, false, fmt.Errorf("singleton method %s: the parent provider is not modelled", name)
|
|
}
|
|
for k := c.parent; k != "" && p.w.user[k]; k = p.w.sup[k] {
|
|
if sd, ok := p.w.sdefs[k][name]; ok {
|
|
return sd, true, nil
|
|
}
|
|
}
|
|
return nil, false, nil
|
|
}
|
|
|
|
// call evaluates a method call on self without arguments: a user singleton method, or resource_type in a provider.
|
|
func (p *parser) call(name string) (rval, error) {
|
|
c := p.cls
|
|
if c == nil {
|
|
return rval{}, fmt.Errorf("undefined local variable or method %s", name)
|
|
}
|
|
sd, found, err := p.singleton(c, name)
|
|
switch {
|
|
case err != nil:
|
|
return rval{}, err
|
|
case found && sd == nil:
|
|
return rval{}, fmt.Errorf("singleton method %s is not evaluable", name)
|
|
case found:
|
|
return p.inline(sd, name)
|
|
case name == "resource_type" && c.typ != nil:
|
|
return rval{k: vType, s: c.typ.name}, nil
|
|
}
|
|
return rval{}, fmt.Errorf("undefined local variable or method %s", name)
|
|
}
|
|
|
|
// inline evaluates a singleton method body of local assignments and expressions and returns its last value.
|
|
func (p *parser) inline(sd *sdef, name string) (rval, error) {
|
|
q, err := p.sub(sd, name)
|
|
if err != nil {
|
|
return rval{}, err
|
|
}
|
|
last := rval{k: vNil}
|
|
for {
|
|
q.skipNL()
|
|
if q.is(tIdent, "end") {
|
|
if q.i != sd.end {
|
|
return rval{}, fmt.Errorf("%s: unsupported end", name)
|
|
}
|
|
return last, nil
|
|
}
|
|
local := ""
|
|
if isLocal(q.cur()) && q.assigns() {
|
|
local = q.take().text
|
|
q.take()
|
|
}
|
|
v, err := q.eval()
|
|
if err != nil {
|
|
return rval{}, fmt.Errorf("%s: %w", name, err)
|
|
}
|
|
if local != "" {
|
|
q.locals[local] = v
|
|
}
|
|
last = v
|
|
if t := q.cur(); t.kind != tNL && t.text != ";" && !q.is(tIdent, "end") {
|
|
return rval{}, fmt.Errorf("%s: unsupported %s", name, describe(t))
|
|
}
|
|
}
|
|
}
|
|
|
|
// sub returns a parser at the start of method body sd, in the lexical scope of the file defining it.
|
|
func (p *parser) sub(sd *sdef, name string) (*parser, error) {
|
|
if p.calls >= maxCalls {
|
|
return nil, fmt.Errorf("method %s nested deeper than %d", name, maxCalls)
|
|
}
|
|
q := &parser{toks: sd.toks, i: sd.start, consts: sd.consts, used: map[int]bool{}, w: p.w, defined: p.w.defined, mod: sd.mod, dir: sd.dir,
|
|
file: sd.file, src: sd.src, cref: sd.cref, depth: p.depth, cls: p.cls, calls: p.calls + 1, locals: map[string]rval{}}
|
|
if len(sd.cref) > 0 {
|
|
q.scope = sd.cref[len(sd.cref)-1]
|
|
}
|
|
for _, o := range sd.opts {
|
|
q.i = o.tok
|
|
v, err := q.primary()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
q.locals[o.name] = v
|
|
}
|
|
if sd.block != "" {
|
|
q.locals[sd.block] = rval{k: vNil}
|
|
}
|
|
q.i = sd.start
|
|
return q, nil
|
|
}
|
|
|
|
func truthy(v rval) bool { return v.k != vNil && v.k != vFalse }
|
|
|
|
// eval evaluates an expression: literals, locals, constants, defined?, calls on self, allowlisted methods, String#+,
|
|
// ==/!=, ! and &&/||, whose right operand it always evaluates. It stops before .each, which only a statement takes.
|
|
func (p *parser) eval() (rval, error) {
|
|
defer func() { p.depth-- }()
|
|
if err := p.enter(); err != nil {
|
|
return rval{}, err
|
|
}
|
|
v, err := p.and()
|
|
for err == nil && p.op("||") {
|
|
p.take()
|
|
p.skipNL()
|
|
var w rval
|
|
if w, err = p.and(); err == nil && !truthy(v) {
|
|
v = w
|
|
}
|
|
}
|
|
return v, err
|
|
}
|
|
|
|
func (p *parser) and() (rval, error) {
|
|
v, err := p.equality()
|
|
for err == nil && p.op("&&") {
|
|
p.take()
|
|
p.skipNL()
|
|
var w rval
|
|
if w, err = p.equality(); err == nil && truthy(v) {
|
|
v = w
|
|
}
|
|
}
|
|
return v, err
|
|
}
|
|
|
|
func (p *parser) equality() (rval, error) {
|
|
v, err := p.sum()
|
|
if err != nil || !p.op("==") && !p.op("!=") {
|
|
return v, err
|
|
}
|
|
neg := p.take().text == "!="
|
|
p.skipNL()
|
|
w, err := p.sum()
|
|
if err != nil {
|
|
return v, err
|
|
}
|
|
eq, err := rubyEq(v, w)
|
|
if eq != neg {
|
|
return rval{k: vTrue}, err
|
|
}
|
|
return rval{k: vFalse}, err
|
|
}
|
|
|
|
func (p *parser) sum() (rval, error) {
|
|
v, err := p.postfix()
|
|
for err == nil && p.op("+") {
|
|
p.take()
|
|
p.skipNL()
|
|
var w rval
|
|
if w, err = p.postfix(); err != nil {
|
|
break
|
|
}
|
|
if v.k != vStr || w.k != vStr {
|
|
return v, fmt.Errorf("%s + %s", v.kindName(), w.kindName())
|
|
}
|
|
p.charge(len(v.s) + len(w.s))
|
|
v.s += w.s
|
|
}
|
|
return v, err
|
|
}
|
|
|
|
func (p *parser) postfix() (rval, error) {
|
|
v, err := p.atom()
|
|
for err == nil {
|
|
switch {
|
|
case v.k == vStr && p.cur().kind == tStr:
|
|
var w rval
|
|
if w, err = p.primary(); err == nil {
|
|
p.charge(len(v.s) + len(w.s))
|
|
v.s += w.s
|
|
}
|
|
case p.op(".") && p.at(1).kind == tIdent && p.at(1).text != "each":
|
|
p.take()
|
|
v, err = p.method(v, p.take().text)
|
|
default:
|
|
return v, nil
|
|
}
|
|
}
|
|
return v, err
|
|
}
|
|
|
|
// method applies allowlisted method m to v. Only reject takes a block; a do block after any other method belongs to
|
|
// the enclosing call.
|
|
func (p *parser) method(v rval, m string) (rval, error) {
|
|
if m == "reject" && v.k == vArray {
|
|
return p.reject(v)
|
|
}
|
|
if m == "respond_to?" || m == "is_a?" || m == "kind_of?" {
|
|
return p.typeQuery(v, m)
|
|
}
|
|
if m == "provider" && v.k == vType {
|
|
return p.typeProvider(v)
|
|
}
|
|
if p.op("(") && !p.cur().space || p.op("{") {
|
|
return v, fmt.Errorf("unsupported arguments or block for %s", m)
|
|
}
|
|
switch {
|
|
case m == "freeze" && v.k != vType:
|
|
return v, nil
|
|
case m == "nil?" && v.k != vUndet:
|
|
return rval{k: map[bool]vkind{true: vTrue, false: vFalse}[v.k == vNil]}, nil
|
|
case m == "to_s" && (v.k == vStr || v.k == vSym):
|
|
return rval{k: vStr, s: v.s}, nil
|
|
case (m == "to_sym" || m == "intern") && (v.k == vStr || v.k == vSym):
|
|
return rval{k: vSym, s: v.s}, nil
|
|
case m == "validproperties" && v.k == vType:
|
|
return p.validProperties(v.s)
|
|
}
|
|
return v, fmt.Errorf("unsupported %s#%s", v.kindName(), m)
|
|
}
|
|
|
|
// responds are methods every String and Symbol has; respond_to? of any other name is not decided.
|
|
var responds = set("to_s to_sym intern downcase upcase freeze")
|
|
|
|
// coreClasses are the classes is_a? decides, by the value kinds that are instances of each.
|
|
var coreClasses = map[string][]vkind{
|
|
"Symbol": {vSym}, "String": {vStr}, "Array": {vArray}, "Hash": {vHash}, "Regexp": {vRegex},
|
|
"NilClass": {vNil}, "TrueClass": {vTrue}, "FalseClass": {vFalse},
|
|
"Object": {vStr, vSym, vRegex, vNum, vTrue, vFalse, vNil, vArray, vHash, vConst, vBlock, vType},
|
|
}
|
|
|
|
// typeQuery evaluates v.respond_to?(:name) for a String or Symbol, and v.is_a?(Class) for a core class.
|
|
func (p *parser) typeQuery(v rval, m string) (rval, error) {
|
|
if !p.op("(") || p.cur().space {
|
|
return v, fmt.Errorf("unsupported %s without parentheses", m)
|
|
}
|
|
p.take()
|
|
ok := false
|
|
if m == "respond_to?" {
|
|
a, err := p.eval()
|
|
if err != nil {
|
|
return v, err
|
|
}
|
|
if a.k != vSym && a.k != vStr || v.k != vStr && v.k != vSym || !responds[a.s] {
|
|
return v, fmt.Errorf("respond_to? %s on a %s is not decided", a.s, v.kindName())
|
|
}
|
|
ok = true
|
|
} else {
|
|
name, err := p.constPath()
|
|
if err != nil {
|
|
return v, err
|
|
}
|
|
kinds, known := coreClasses[name]
|
|
if !known || !p.coreConst(name) || v.k == vUndet {
|
|
return v, fmt.Errorf("unsupported %s(%s)", m, name)
|
|
}
|
|
ok = slices.Contains(kinds, v.k)
|
|
}
|
|
if err := p.expect(")"); err != nil {
|
|
return v, err
|
|
}
|
|
if ok {
|
|
return rval{k: vTrue}, nil
|
|
}
|
|
return rval{k: vFalse}, nil
|
|
}
|
|
|
|
// coreConst reports whether constant name resolves to Ruby's top-level constant from here.
|
|
func (p *parser) coreConst(name string) bool {
|
|
_, own := p.consts[name]
|
|
_, scoped := p.consts[p.scope+"::"+name]
|
|
return p.w != nil && p.lexical(name) == name && !own && !scoped
|
|
}
|
|
|
|
// validProperties is Puppet::Type.validproperties of the type being loaded: property names in definition order.
|
|
func (p *parser) validProperties(typ string) (rval, error) {
|
|
out := rval{k: vArray}
|
|
for _, n := range p.w.types[typ].t.validprops {
|
|
if !rubyName.MatchString(n) {
|
|
return rval{}, fmt.Errorf("unsupported property name %q", n)
|
|
}
|
|
out.arr = append(out.arr, rval{k: vSym, s: n})
|
|
}
|
|
p.charge(16 * len(out.arr))
|
|
return out, nil
|
|
}
|
|
|
|
// reject keeps the elements for which its block, with the element bound to the block's parameter, is falsy.
|
|
func (p *parser) reject(v rval) (rval, error) {
|
|
if p.is(tIdent, "do") && p.noDo {
|
|
return v, fmt.Errorf("a do block here belongs to the enclosing call")
|
|
}
|
|
out := rval{k: vArray}
|
|
err := p.block(v.arr, func(e rval, closeTok string) error {
|
|
p.skipNL()
|
|
r, err := p.eval()
|
|
p.skipNL()
|
|
if err == nil && !p.closes(closeTok) {
|
|
err = fmt.Errorf("reject: unsupported %s", describe(p.cur()))
|
|
}
|
|
if r.k == vNil || r.k == vFalse {
|
|
out.arr = append(out.arr, e)
|
|
}
|
|
return err
|
|
})
|
|
p.charge(16 * len(out.arr))
|
|
return out, err
|
|
}
|
|
|
|
// block runs body once per element with the cursor at the start of the do or brace block at the cursor and the
|
|
// element bound to its one parameter, then leaves the cursor after the block. An empty list never runs the body.
|
|
func (p *parser) block(elems []rval, body func(e rval, closeTok string) error) error {
|
|
if !p.is(tIdent, "do") && !p.op("{") {
|
|
return fmt.Errorf("expected a block")
|
|
}
|
|
open := p.i
|
|
if err := p.skipBlock(); err != nil {
|
|
return err
|
|
}
|
|
end := p.i
|
|
p.i = open
|
|
closeTok := "end"
|
|
if p.take().text == "{" {
|
|
closeTok = "}"
|
|
}
|
|
if !p.op("|") || !isLocal(p.at(1)) || p.at(2).text != "|" {
|
|
return fmt.Errorf("unsupported block parameters")
|
|
}
|
|
param := p.at(1).text
|
|
start := p.i + 3
|
|
saved, savedParam := p.locals, p.bparam
|
|
p.bparam = param
|
|
defer func() { p.locals, p.bparam = saved, savedParam }()
|
|
for _, e := range elems {
|
|
p.locals = make(map[string]rval, len(saved)+1)
|
|
for k, x := range saved {
|
|
p.locals[k] = x
|
|
}
|
|
p.locals[param] = e
|
|
p.i = start
|
|
if err := body(e, closeTok); err != nil && err != errNext {
|
|
return err
|
|
}
|
|
}
|
|
p.i = end
|
|
return nil
|
|
}
|
|
|
|
func (p *parser) atom() (rval, error) {
|
|
t := p.cur()
|
|
switch {
|
|
case t.kind == tOp && t.text == "!":
|
|
p.take()
|
|
v, err := p.postfix()
|
|
if truthy(v) {
|
|
return rval{k: vFalse}, err
|
|
}
|
|
return rval{k: vTrue}, err
|
|
case t.kind == tConst && t.text == "Hash" && p.at(1).text == "." && p.at(2).text == "new" && p.coreConst("Hash"):
|
|
p.i += 3
|
|
if p.op("(") && !p.cur().space && p.at(1).text == ")" {
|
|
p.i += 2
|
|
}
|
|
if p.op("{") || p.is(tIdent, "do") && !p.noDo {
|
|
return rval{k: vHash}, p.skipBlock()
|
|
}
|
|
return rval{k: vHash}, nil
|
|
case t.kind == tConst && t.text == "Regexp" && p.at(1).text == "." && p.at(2).text == "new" && p.coreConst("Regexp"):
|
|
p.i += 3
|
|
return p.regexpNew()
|
|
case p.featuresCall(""):
|
|
p.i += 4
|
|
name, _ := strings.CutSuffix(p.take().text, "?")
|
|
if p.op("(") && !p.cur().space {
|
|
return rval{}, fmt.Errorf("unsupported arguments to Puppet.features.%s?", name)
|
|
}
|
|
ok, err := p.featureTest(name)
|
|
if ok {
|
|
return rval{k: vTrue}, err
|
|
}
|
|
return rval{k: vFalse}, err
|
|
case t.kind == tIdent && t.text == "defined?":
|
|
return p.definedExpr()
|
|
case isLocal(t) && (p.locals != nil || p.cls != nil):
|
|
if _, ok := p.locals[t.text]; ok {
|
|
return p.primary()
|
|
}
|
|
binary := p.at(1).text == "+" && (!p.at(1).space || p.at(2).space)
|
|
if n := p.at(1); n.kind != tNL && n.kind != tEOF && (n.kind != tOp || !callEnds[n.text] && !binary) && (n.kind != tIdent || !reserved[n.text]) {
|
|
return rval{}, fmt.Errorf("unsupported call %s with arguments", t.text)
|
|
}
|
|
p.take()
|
|
return p.call(t.text)
|
|
case p.typeAhead():
|
|
return p.typeCall()
|
|
}
|
|
return p.primary()
|
|
}
|
|
|
|
// callEnds are the tokens that may follow a method call without arguments.
|
|
var callEnds = set(". == != ) ] } , ;")
|
|
|
|
// definedExpr evaluates defined?(Const) or defined? Const. A constant w10k does not see may be defined by a file
|
|
// another input loaded first, so a false result is only allowed where conditional assignment accounts for it.
|
|
func (p *parser) definedExpr() (rval, error) {
|
|
p.take()
|
|
paren := p.op("(") && !p.cur().space
|
|
if paren {
|
|
p.take()
|
|
}
|
|
if p.cur().kind != tConst {
|
|
return rval{}, fmt.Errorf("unsupported defined? operand %s", describe(p.cur()))
|
|
}
|
|
path, err := p.constPath()
|
|
if err != nil {
|
|
return rval{}, err
|
|
}
|
|
if paren {
|
|
if err := p.expect(")"); err != nil {
|
|
return rval{}, err
|
|
}
|
|
}
|
|
if p.constDefined(path) {
|
|
return rval{k: vStr, s: "constant"}, nil
|
|
}
|
|
if !p.condAssign {
|
|
return rval{}, fmt.Errorf("defined?(%s) depends on what other inputs loaded", path)
|
|
}
|
|
p.undetermined = true
|
|
return rval{k: vNil}, nil
|
|
}
|
|
|
|
func (p *parser) constDefined(path string) bool {
|
|
if _, ok := p.consts[path]; ok {
|
|
return true
|
|
}
|
|
if _, ok := p.consts[p.scope+"::"+path]; ok && p.scope != "" {
|
|
return true
|
|
}
|
|
return p.defined[path] || p.w != nil && p.crefConst(path) != ""
|
|
}
|
|
|
|
// crefConst resolves path in the enclosing lexical scopes' own constants, innermost first, which Ruby searches
|
|
// before any ancestor.
|
|
func (p *parser) crefConst(path string) string {
|
|
for i := len(p.cref) - 1; i >= 0; i-- {
|
|
if q := p.cref[i] + "::" + path; p.w.defined[q] {
|
|
return q
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// rubyEq is == on two evaluated values; Float operands and values w10k cannot compare are an error.
|
|
func rubyEq(a, b rval) (bool, error) {
|
|
comparable := func(v rval) bool {
|
|
return v.k == vStr || v.k == vSym || v.k == vNil || v.k == vTrue || v.k == vFalse || v.k == vNum && !strings.ContainsAny(v.s, ".e")
|
|
}
|
|
if !comparable(a) || !comparable(b) {
|
|
return false, fmt.Errorf("unsupported %s == %s", a.kindName(), b.kindName())
|
|
}
|
|
return a.k == b.k && a.s == b.s, nil
|
|
}
|
|
|
|
// evalStmt evaluates a class-level define_method or <list>.each loop, declining any other statement.
|
|
func (p *parser) evalStmt(c *classCtx) (bool, error) {
|
|
if p.is(tIdent, "define_method") {
|
|
return true, p.defineMethod(c)
|
|
}
|
|
if isLocal(p.cur()) && (p.at(1).text == "{" || p.at(1).text == "do") && (c.kind == kProv || c.kind == kParsed) {
|
|
return true, p.blockCall(c)
|
|
}
|
|
if !p.eachAhead() {
|
|
return false, nil
|
|
}
|
|
saved, savedLocals := p.cls, p.locals
|
|
p.cls = c
|
|
if p.locals == nil {
|
|
p.locals = map[string]rval{}
|
|
}
|
|
defer func() { p.cls, p.locals = saved, savedLocals }()
|
|
v, err := p.eval()
|
|
if err != nil {
|
|
return true, err
|
|
}
|
|
if !p.op(".") || p.at(1).text != "each" {
|
|
return true, fmt.Errorf("unsupported %s", p.construct())
|
|
}
|
|
p.i += 2
|
|
if v.k != vArray {
|
|
return true, fmt.Errorf("%s#each", v.kindName())
|
|
}
|
|
return true, p.block(v.arr, func(_ rval, closeTok string) error {
|
|
return p.body(closeTok, func() (bool, error) { return p.loopStmt(c) })
|
|
})
|
|
}
|
|
|
|
// eachAhead reports whether the statement at the cursor calls .each with a block outside any brackets.
|
|
func (p *parser) eachAhead() bool {
|
|
depth := 0
|
|
for j := p.i; j+2 < len(p.toks); j++ {
|
|
t := p.toks[j]
|
|
switch {
|
|
case t.kind == tEOF || depth == 0 && (t.kind == tNL || t.text == ";"):
|
|
return false
|
|
case t.kind == tOp && strings.Contains("([{", t.text):
|
|
depth++
|
|
case t.kind == tOp && strings.Contains(")]}", t.text):
|
|
depth--
|
|
case depth == 0 && t.kind == tOp && t.text == "." && p.toks[j+1].text == "each" && (p.toks[j+2].text == "do" || p.toks[j+2].text == "{"):
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// loopStmt allows define_method, next and reassigning the block parameter, optionally under an if or unless modifier,
|
|
// in a define loop; the assigned value is evaluated even when the modifier skips it.
|
|
func (p *parser) loopStmt(c *classCtx) (bool, error) {
|
|
switch {
|
|
case p.is(tIdent, "define_method"):
|
|
return true, p.defineMethod(c)
|
|
case isLocal(p.cur()) && p.assigns() && p.cur().text == p.bparam:
|
|
name := p.take().text
|
|
p.take()
|
|
v, err := p.eval()
|
|
if err == nil && (p.is(tIdent, "if") || p.is(tIdent, "unless")) {
|
|
unless := p.take().text == "unless"
|
|
var cond rval
|
|
if cond, err = p.eval(); truthy(cond) == unless {
|
|
return true, err
|
|
}
|
|
}
|
|
p.locals[name] = v
|
|
return true, err
|
|
case p.is(tIdent, "next"):
|
|
p.take()
|
|
next := true
|
|
if p.is(tIdent, "if") || p.is(tIdent, "unless") {
|
|
unless := p.take().text == "unless"
|
|
v, err := p.eval()
|
|
if err != nil {
|
|
return true, err
|
|
}
|
|
next = (v.k != vNil && v.k != vFalse) != unless
|
|
}
|
|
if next {
|
|
return true, errNext
|
|
}
|
|
return true, nil
|
|
}
|
|
return true, fmt.Errorf("unsupported %s in a define loop", p.construct())
|
|
}
|
|
|
|
// defineMethod records define_method(name) do ... end as an instance method with the current default visibility;
|
|
// the block runs only when the method is called.
|
|
func (p *parser) defineMethod(c *classCtx) error {
|
|
p.take()
|
|
saved, savedNoDo := p.cls, p.noDo
|
|
p.cls = c
|
|
paren := p.op("(") && !p.cur().space
|
|
p.noDo = !paren
|
|
defer func() { p.cls, p.noDo = saved, savedNoDo }()
|
|
if paren {
|
|
p.take()
|
|
}
|
|
v, err := p.eval()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if paren {
|
|
if err := p.expect(")"); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if v.k != vSym && v.k != vStr {
|
|
return fmt.Errorf("define_method name is a %s", v.kindName())
|
|
}
|
|
if !p.is(tIdent, "do") && (!p.op("{") || !paren) {
|
|
return fmt.Errorf("define_method without a block")
|
|
}
|
|
if err := c.addMethod(v.s, c.priv); err != nil {
|
|
return err
|
|
}
|
|
return p.skipBlock()
|
|
}
|
|
|
|
// includedHook records a module's def self.included(klass); including the module runs it on the including class.
|
|
func (p *parser) includedHook(c *classCtx) error {
|
|
if t := p.at(4); t.text != "(" || t.space || !isLocal(p.at(5)) || p.at(6).text != ")" {
|
|
return fmt.Errorf("unsupported def self.included parameters")
|
|
}
|
|
sd := &sdef{toks: p.toks, start: p.i + 7, consts: p.consts, cref: slices.Clone(p.cref), mod: p.mod, dir: p.dir, file: p.file, src: p.src, param: p.at(5).text}
|
|
err := p.skipStatement()
|
|
sd.end = p.i - 1
|
|
c.included = sd
|
|
return err
|
|
}
|
|
|
|
// runIncluded runs module mod's included hook on class c: klass.extend Module and klass.method calls without arguments.
|
|
func (p *parser) runIncluded(c *classCtx, mod string) error {
|
|
mc := p.w.classes[mod]
|
|
if mc == nil || mc.included == nil {
|
|
return nil
|
|
}
|
|
sd := mc.included
|
|
q, err := p.sub(sd, "included")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
err = q.body("end", func() (bool, error) {
|
|
if !q.is(tIdent, sd.param) || q.at(1).text != "." || q.at(2).kind != tIdent {
|
|
return true, fmt.Errorf("unsupported %s", q.construct())
|
|
}
|
|
q.i += 2
|
|
name := q.take().text
|
|
if name == "extend" {
|
|
return true, q.extend(c)
|
|
}
|
|
if t := q.cur(); t.kind != tNL && t.text != ";" && !q.is(tIdent, "end") {
|
|
return true, fmt.Errorf("unsupported arguments to %s.%s", sd.param, name)
|
|
}
|
|
return true, q.callStmt(c, name)
|
|
})
|
|
if err == nil && q.i-1 != sd.end {
|
|
err = fmt.Errorf("unsupported end")
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("%s.included: %w", mod, q.wrap(err))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// extend adds the instance methods of one loaded module as singleton methods of c, behind c's own. A method that
|
|
// shadows a provider DSL method must be a super wrapper, which then stands in for it; one shadowing a hook, doc or
|
|
// dochook_ is an error.
|
|
func (p *parser) extend(c *classCtx) error {
|
|
path, err := p.constPath()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
r := p.lexical(path)
|
|
mc := p.w.classes[r]
|
|
switch {
|
|
case r == "" || p.w.kind[r] != kMod || mc == nil:
|
|
return fmt.Errorf("extend %s: no loaded file defines it as a module", path)
|
|
case len(p.w.mods[r]) != 1:
|
|
return fmt.Errorf("extend %s: more than one loaded file opens it", path)
|
|
case len(mc.mixed) > 0:
|
|
return fmt.Errorf("extend %s: it includes other modules", path)
|
|
}
|
|
if c.sdefs == nil {
|
|
c.sdefs = map[string]*sdef{}
|
|
}
|
|
for _, n := range slices.Sorted(maps.Keys(mc.methods)) {
|
|
sd := mc.idefs[n]
|
|
switch {
|
|
case mc.hidden[n]:
|
|
return fmt.Errorf("extend %s: non-public method %s", path, n)
|
|
case providerDSL[n]:
|
|
if err := p.superWrapper(c, sd); err != nil {
|
|
return fmt.Errorf("extend %s: %s shadows a provider method: %w", path, n, err)
|
|
}
|
|
case hooks[n] || n == "doc" || strings.HasPrefix(n, "dochook_"):
|
|
return fmt.Errorf("extend %s: %s shadows a class method puppet calls", path, n)
|
|
}
|
|
if _, own := c.sdefs[n]; own {
|
|
continue
|
|
}
|
|
c.sdefs[n], c.smethods[n], c.supers[n] = sd, true, providerDSL[n]
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// superWrapper checks that provider method body sd calls super first and then only sets ivars puppet never reads, so
|
|
// calling it does what the method it shadows does.
|
|
func (p *parser) superWrapper(c *classCtx, sd *sdef) error {
|
|
if sd == nil || len(sd.opts) > 0 || sd.block != "" || c.kind != kProv && c.kind != kParsed {
|
|
return fmt.Errorf("not a super wrapper")
|
|
}
|
|
q, err := p.sub(sd, "super wrapper")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
q.skipNL()
|
|
if !q.is(tIdent, "super") || q.at(1).kind != tNL && q.at(1).text != ";" {
|
|
return fmt.Errorf("it does not start with super")
|
|
}
|
|
q.take()
|
|
err = q.body("end", func() (bool, error) {
|
|
t := q.cur()
|
|
if t.kind != tIVar || strings.HasPrefix(t.text, "@@") || !q.assigns() || puppetReads(c.kind, t.text[1:]) {
|
|
return true, fmt.Errorf("unsupported %s after super", q.construct())
|
|
}
|
|
q.i += 2
|
|
_, err := q.eval()
|
|
return true, err
|
|
})
|
|
if err == nil && q.i-1 != sd.end {
|
|
err = fmt.Errorf("unsupported end")
|
|
}
|
|
return err
|
|
}
|
|
|
|
// parsedIvars are the providerIvars only Puppet::Provider::ParsedFile and Puppet::Util::FileParsing read.
|
|
var parsedIvars = set("backup_stats failed_prefetch_targets filetype line_separator raise_prefetch_errors record_order records record_types target target_objects trailing_separator")
|
|
|
|
func puppetReads(kind byte, ivar string) bool {
|
|
return providerIvars[ivar] && (kind != kProv || !parsedIvars[ivar])
|
|
}
|
|
|
|
// callStmt runs c.name with no arguments as a statement: a super wrapper or an unshadowed provider DSL method, or an
|
|
// inlined singleton method body.
|
|
func (p *parser) callStmt(c *classCtx, name string) error {
|
|
sd, found, err := p.singleton(c, name)
|
|
switch {
|
|
case err != nil:
|
|
return err
|
|
case found && c.supers[name], !found && (c.kind == kProv || c.kind == kParsed) && providerDSL[name]:
|
|
return c.dslNoArgs(name)
|
|
case found && sd == nil:
|
|
return fmt.Errorf("singleton method %s is not evaluable", name)
|
|
case found:
|
|
return p.inlineStmt(c, sd, name)
|
|
}
|
|
return fmt.Errorf("undefined method %s", name)
|
|
}
|
|
|
|
// dslNoArgs applies a provider DSL call without arguments.
|
|
func (c *classCtx) dslNoArgs(name string) error {
|
|
switch name {
|
|
case "initvars":
|
|
c.inited, c.defaults, c.commands = true, nil, map[string]string{}
|
|
case "mk_resource_methods":
|
|
c.mkres = true
|
|
default:
|
|
return fmt.Errorf("%s takes arguments", name)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// inlineStmt runs singleton method body sd on c as class-level define loops and define_method calls, which define
|
|
// public methods whatever visibility c's body has set.
|
|
func (p *parser) inlineStmt(c *classCtx, sd *sdef, name string) error {
|
|
q, err := p.sub(sd, name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
saved := c.priv
|
|
c.priv = false
|
|
defer func() { c.priv = saved }()
|
|
err = q.body("end", func() (bool, error) {
|
|
if ok, err := q.evalStmt(c); ok {
|
|
return true, err
|
|
}
|
|
return true, fmt.Errorf("unsupported %s", q.construct())
|
|
})
|
|
if err == nil && q.i-1 != sd.end {
|
|
err = fmt.Errorf("unsupported end")
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("%s: %w", name, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// regexInterp composes an interpolated regex literal as Ruby does, each value by its to_s, and compiles it only when
|
|
// onigCheck proves Onigmo accepts the result.
|
|
func (p *parser) regexInterp(t token) (rval, error) {
|
|
if strings.Trim(t.flags, "mi") != "" {
|
|
return rval{}, fmt.Errorf("unsupported interpolated regex flags %q", t.flags)
|
|
}
|
|
var parts []part
|
|
var b strings.Builder
|
|
flush := func() {
|
|
if b.Len() > 0 {
|
|
parts = append(parts, part{text: b.String()})
|
|
b.Reset()
|
|
}
|
|
}
|
|
s := t.text
|
|
for i := 0; i < len(s); i++ {
|
|
switch {
|
|
case s[i] == '\\' && i+1 < len(s):
|
|
b.WriteString(s[i : i+2])
|
|
i++
|
|
case s[i] == '#' && i+1 < len(s) && s[i+1] == '{':
|
|
depth, j := 0, i+1
|
|
for ; j < len(s); j++ {
|
|
if s[j] == '{' {
|
|
depth++
|
|
} else if s[j] == '}' {
|
|
if depth--; depth == 0 {
|
|
break
|
|
}
|
|
}
|
|
}
|
|
if j >= len(s) {
|
|
return rval{}, fmt.Errorf("unterminated interpolation in regex")
|
|
}
|
|
flush()
|
|
parts = append(parts, part{text: strings.TrimSpace(s[i+2 : j]), code: true})
|
|
i = j
|
|
case s[i] == '#' && i+1 < len(s) && (s[i+1] == '@' || s[i+1] == '$'):
|
|
return rval{}, fmt.Errorf("unsupported interpolation in regex")
|
|
default:
|
|
b.WriteByte(s[i])
|
|
}
|
|
}
|
|
flush()
|
|
src, err := p.interp(parts)
|
|
if err != nil {
|
|
return rval{}, err
|
|
}
|
|
if err := onigCheck(src, strings.Contains(t.flags, "i")); err != nil {
|
|
return rval{}, err
|
|
}
|
|
return rval{k: vRegex, re: regex{src, t.flags}}, nil
|
|
}
|
|
|
|
// onig checks a regex source against a subset of Onigmo's Ruby syntax that Ruby 3.3 compiles without error: literals,
|
|
// punctuation and class escapes, anchors, simple character classes, groups, lookarounds, alternation and
|
|
// quantifiers. A look-behind holds alternatives of fixed-length atoms only, with case folding off.
|
|
type onig struct {
|
|
s string
|
|
i int
|
|
depth int
|
|
}
|
|
|
|
func onigCheck(src string, icase bool) error {
|
|
o := &onig{s: src}
|
|
err := o.alt(icase, false)
|
|
if err == nil && o.i < len(o.s) {
|
|
err = fmt.Errorf("unmatched close parenthesis")
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("regex %q: %w", src, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (o *onig) peek(off int) byte {
|
|
if o.i+off < len(o.s) {
|
|
return o.s[o.i+off]
|
|
}
|
|
return 0
|
|
}
|
|
|
|
func (o *onig) alt(icase, behind bool) error {
|
|
for {
|
|
n, err := o.seq(icase, behind)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if behind && n <= 0 {
|
|
return fmt.Errorf("look-behind alternative without a fixed length")
|
|
}
|
|
if o.peek(0) != '|' {
|
|
return nil
|
|
}
|
|
o.i++
|
|
}
|
|
}
|
|
|
|
// seq parses one alternative and returns its length in characters.
|
|
func (o *onig) seq(icase, behind bool) (int, error) {
|
|
n := 0
|
|
for o.i < len(o.s) && o.s[o.i] != '|' && o.s[o.i] != ')' {
|
|
w, repeatable, err := o.atom(icase, behind)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if c := o.peek(0); c == '*' || c == '+' || c == '?' || c == '{' {
|
|
if !repeatable {
|
|
return 0, fmt.Errorf("invalid target of repeat operator")
|
|
}
|
|
exact, err := o.quantifier()
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if behind && exact < 0 {
|
|
return 0, fmt.Errorf("variable repeat in look-behind")
|
|
}
|
|
w *= exact
|
|
}
|
|
n += w
|
|
}
|
|
return n, nil
|
|
}
|
|
|
|
// quantifier consumes one quantifier with an optional lazy or possessive suffix, returning its exact count or -1.
|
|
func (o *onig) quantifier() (int, error) {
|
|
exact := -1
|
|
if c := o.s[o.i]; c != '{' {
|
|
o.i++
|
|
if s := o.peek(0); s == '?' || s == '+' {
|
|
o.i++
|
|
}
|
|
} else {
|
|
end := strings.IndexByte(o.s[o.i:], '}')
|
|
if end < 0 {
|
|
return 0, fmt.Errorf("unsupported literal {")
|
|
}
|
|
lo, hi, comma := strings.Cut(o.s[o.i+1:o.i+end], ",")
|
|
num := func(s string) (int, bool) {
|
|
n, err := strconv.Atoi(s)
|
|
return n, err == nil && s == strconv.Itoa(n) && n <= 100000
|
|
}
|
|
l, lok := num(lo)
|
|
h, hok := num(hi)
|
|
switch {
|
|
case !comma && lok:
|
|
exact = l
|
|
case comma && lok && hi == "", comma && lo == "" && hok:
|
|
case comma && lok && hok && l <= h:
|
|
default:
|
|
return 0, fmt.Errorf("unsupported interval {%s}", o.s[o.i+1:o.i+end])
|
|
}
|
|
o.i += end + 1
|
|
if o.peek(0) == '?' {
|
|
o.i++
|
|
}
|
|
}
|
|
if c := o.peek(0); c == '*' || c == '+' || c == '?' || c == '{' {
|
|
return 0, fmt.Errorf("nested repeat operator")
|
|
}
|
|
return exact, nil
|
|
}
|
|
|
|
// atom consumes one atom and returns its length in characters and whether a quantifier may follow it.
|
|
func (o *onig) atom(icase, behind bool) (int, bool, error) {
|
|
switch c := o.s[o.i]; c {
|
|
case '(':
|
|
if behind {
|
|
return 0, false, fmt.Errorf("group in look-behind")
|
|
}
|
|
if o.depth++; o.depth > 64 {
|
|
return 0, false, fmt.Errorf("groups nested too deep")
|
|
}
|
|
defer func() { o.depth-- }()
|
|
o.i++
|
|
repeatable, lookbehind := true, false
|
|
if o.peek(0) == '?' {
|
|
switch {
|
|
case o.peek(1) == ':':
|
|
o.i += 2
|
|
case o.peek(1) == '=' || o.peek(1) == '!':
|
|
o.i += 2
|
|
repeatable = false
|
|
case o.peek(1) == '<' && (o.peek(2) == '=' || o.peek(2) == '!'):
|
|
if icase {
|
|
return 0, false, fmt.Errorf("look-behind with case folding")
|
|
}
|
|
o.i += 3
|
|
repeatable, lookbehind = false, true
|
|
default:
|
|
o.i++
|
|
on := true
|
|
for ; o.peek(0) != ':'; o.i++ {
|
|
switch f := o.peek(0); {
|
|
case f == '-' && on:
|
|
on = false
|
|
case f == 'i':
|
|
icase = on
|
|
case f == 'm' || f == 'x' && !on:
|
|
default:
|
|
return 0, false, fmt.Errorf("unsupported group option")
|
|
}
|
|
}
|
|
o.i++
|
|
}
|
|
}
|
|
if err := o.alt(icase, lookbehind); err != nil {
|
|
return 0, false, err
|
|
}
|
|
if o.peek(0) != ')' {
|
|
return 0, false, fmt.Errorf("end pattern with unmatched parenthesis")
|
|
}
|
|
o.i++
|
|
return 0, repeatable, nil
|
|
case '[':
|
|
return 1, true, o.class()
|
|
case '\\':
|
|
w, err := o.escape(false)
|
|
if w == 0 && behind {
|
|
return 0, false, fmt.Errorf("anchor in look-behind")
|
|
}
|
|
return w, w > 0, err
|
|
case '.':
|
|
o.i++
|
|
return 1, true, nil
|
|
case '^', '$':
|
|
if behind {
|
|
return 0, false, fmt.Errorf("anchor in look-behind")
|
|
}
|
|
o.i++
|
|
return 0, false, nil
|
|
case '*', '+', '?', '{', ']':
|
|
return 0, false, fmt.Errorf("unsupported %q here", c)
|
|
}
|
|
r, n := utf8.DecodeRuneInString(o.s[o.i:])
|
|
if r == utf8.RuneError {
|
|
return 0, false, fmt.Errorf("invalid multibyte character")
|
|
}
|
|
o.i += n
|
|
return 1, true, nil
|
|
}
|
|
|
|
// escape consumes a backslash escape, returning 1 for a character or class and 0 for an anchor, which a character
|
|
// class does not allow.
|
|
func (o *onig) escape(inClass bool) (int, error) {
|
|
c := o.peek(1)
|
|
o.i += 2
|
|
switch {
|
|
case strings.IndexByte("dDwWsShHntrfvea", c) >= 0:
|
|
return 1, nil
|
|
case !inClass && strings.IndexByte("AzZbB", c) >= 0:
|
|
return 0, nil
|
|
case c > 0x20 && c < 0x7f && !unicode.IsLetter(rune(c)) && !unicode.IsDigit(rune(c)):
|
|
return 1, nil
|
|
}
|
|
return 0, fmt.Errorf("unsupported escape")
|
|
}
|
|
|
|
// class consumes a bracket expression of characters, ranges in order and class escapes.
|
|
func (o *onig) class() error {
|
|
o.i++
|
|
if o.peek(0) == '^' {
|
|
o.i++
|
|
}
|
|
n, prev := 0, -1
|
|
for {
|
|
c := o.peek(0)
|
|
switch {
|
|
case o.i >= len(o.s):
|
|
return fmt.Errorf("premature end of char-class")
|
|
case c == ']' && n > 0:
|
|
o.i++
|
|
return nil
|
|
case c == ']', c == '[', c == '&' && o.peek(1) == '&', c >= 0x80:
|
|
return fmt.Errorf("unsupported character class")
|
|
case c == '\\':
|
|
e := o.peek(1)
|
|
if _, err := o.escape(true); err != nil {
|
|
return err
|
|
}
|
|
prev = -1
|
|
if strings.IndexByte("dDwWsShHntrfvea", e) < 0 {
|
|
prev = int(e)
|
|
}
|
|
case c == '-' && n > 0 && o.peek(1) != ']':
|
|
o.i++
|
|
hi := int(o.peek(0))
|
|
if o.peek(0) == '\\' {
|
|
if e := o.peek(1); strings.IndexByte("dDwWsShHntrfvea", e) >= 0 {
|
|
return fmt.Errorf("unsupported range end")
|
|
}
|
|
hi = int(o.peek(1))
|
|
if _, err := o.escape(true); err != nil {
|
|
return err
|
|
}
|
|
} else {
|
|
if hi == '[' || hi == ']' || hi >= 0x80 || o.i >= len(o.s) {
|
|
return fmt.Errorf("unsupported range end")
|
|
}
|
|
o.i++
|
|
}
|
|
if prev < 0 || hi < prev {
|
|
return fmt.Errorf("bad range in char-class")
|
|
}
|
|
prev = -1
|
|
default:
|
|
prev = int(c)
|
|
o.i++
|
|
}
|
|
n++
|
|
}
|
|
}
|
|
|
|
// regexpNew evaluates Regexp.new(src): a copy of a Regexp, or a String compiled with no options.
|
|
func (p *parser) regexpNew() (rval, error) {
|
|
args, err := p.args()
|
|
if err != nil {
|
|
return rval{}, err
|
|
}
|
|
switch {
|
|
case len(args) != 1:
|
|
case args[0].k == vRegex:
|
|
return args[0], nil
|
|
case args[0].k == vStr:
|
|
if err := onigCheck(args[0].s, false); err != nil {
|
|
return rval{}, err
|
|
}
|
|
return rval{k: vRegex, re: regex{src: args[0].s}}, nil
|
|
}
|
|
return rval{}, fmt.Errorf("unsupported Regexp.new arguments")
|
|
}
|
|
|
|
// blockCall runs class method name with a block and no arguments: its body may only branch on its parameters and
|
|
// store values in ivars puppet never reads; the block itself runs only when called later.
|
|
func (p *parser) blockCall(c *classCtx) error {
|
|
name := p.take().text
|
|
sd, found, err := p.singleton(c, name)
|
|
switch {
|
|
case err != nil:
|
|
return err
|
|
case !found:
|
|
return fmt.Errorf("undefined method %s", name)
|
|
case sd == nil:
|
|
return fmt.Errorf("singleton method %s is not evaluable", name)
|
|
}
|
|
if err := p.skipBlock(); err != nil {
|
|
return err
|
|
}
|
|
q, err := p.sub(sd, name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if sd.block != "" {
|
|
q.locals[sd.block] = rval{k: vBlock}
|
|
}
|
|
if err := q.branches(c, true); err != nil {
|
|
return fmt.Errorf("%s: %w", name, err)
|
|
}
|
|
if !q.is(tIdent, "end") || q.i != sd.end {
|
|
return fmt.Errorf("%s: unsupported %s", name, q.construct())
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// branches runs, or with run false skips, the statements before the next end, elsif or else: if/unless statements
|
|
// and assignments to ivars puppet never reads.
|
|
func (p *parser) branches(c *classCtx, run bool) error {
|
|
for p.skipNL(); !p.is(tIdent, "end") && !p.is(tIdent, "elsif") && !p.is(tIdent, "else"); p.skipNL() {
|
|
t := p.cur()
|
|
switch {
|
|
case t.kind == tEOF:
|
|
return fmt.Errorf("unexpected end of file")
|
|
case !run:
|
|
if err := p.skipStatement(); err != nil {
|
|
return err
|
|
}
|
|
continue
|
|
case t.kind == tIdent && (t.text == "if" || t.text == "unless"):
|
|
if err := p.ifStmt(c); err != nil {
|
|
return err
|
|
}
|
|
case t.kind == tIVar && !strings.HasPrefix(t.text, "@@") && p.assigns() && !puppetReads(c.kind, t.text[1:]):
|
|
p.i += 2
|
|
if _, err := p.eval(); err != nil {
|
|
return err
|
|
}
|
|
default:
|
|
return fmt.Errorf("unsupported %s", p.construct())
|
|
}
|
|
if t := p.cur(); t.kind != tNL && t.text != ";" && !p.is(tIdent, "end") {
|
|
return fmt.Errorf("unsupported %s", describe(t))
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ifStmt runs the first branch of an if or unless statement whose condition holds; Ruby evaluates no condition
|
|
// after it and runs no other branch.
|
|
func (p *parser) ifStmt(c *classCtx) error {
|
|
defer func() { p.depth-- }()
|
|
if err := p.enter(); err != nil {
|
|
return err
|
|
}
|
|
unless, taken := p.take().text == "unless", false
|
|
for {
|
|
run := false
|
|
if taken {
|
|
if err := p.skipStatement(); err != nil {
|
|
return err
|
|
}
|
|
} else {
|
|
cond, err := p.eval()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
run = truthy(cond) != unless
|
|
taken = run
|
|
}
|
|
if p.is(tIdent, "then") {
|
|
p.take()
|
|
}
|
|
if err := p.branches(c, run); err != nil {
|
|
return err
|
|
}
|
|
switch {
|
|
case p.is(tIdent, "end"):
|
|
p.take()
|
|
return nil
|
|
case p.is(tIdent, "elsif") && !unless:
|
|
p.take()
|
|
case p.is(tIdent, "else"):
|
|
p.take()
|
|
if err := p.branches(c, !taken); err != nil {
|
|
return err
|
|
}
|
|
return p.expectEnd()
|
|
default:
|
|
return fmt.Errorf("unsupported %s", p.construct())
|
|
}
|
|
}
|
|
}
|
|
|
|
func (p *parser) expectEnd() error {
|
|
if !p.is(tIdent, "end") {
|
|
return fmt.Errorf("expected end, found %s", describe(p.cur()))
|
|
}
|
|
p.take()
|
|
return nil
|
|
}
|
|
|
|
func capitalize(s string) string { return strings.ToUpper(s[:1]) + s[1:] }
|
|
|
|
// loadType ports Puppet::Type.type(name): a loaded type, or the first puppet/type/<name>.rb the typeloader finds in
|
|
// module lib dirs, analysed with all its providers, whose classes it defines; nil when no file defines it.
|
|
func (w *world) loadType(name string) (*loadedType, error) {
|
|
if lt, ok := w.types[name]; ok {
|
|
return lt, nil
|
|
}
|
|
lib := "puppet/type/" + name
|
|
switch {
|
|
case !rubyName.MatchString(name):
|
|
return nil, fmt.Errorf("Puppet::Type.type(%q) is not modelled", name)
|
|
case coreLib(lib):
|
|
return nil, fmt.Errorf("Puppet::Type.type(:%s) loads a type of puppet that w10k does not model", name)
|
|
case w.resolve == nil:
|
|
return nil, fmt.Errorf("Puppet::Type.type(:%s): module sources are not available", name)
|
|
}
|
|
srcs, err := w.resolve(lib+".rb", "")
|
|
switch {
|
|
case err != nil:
|
|
return nil, err
|
|
case len(srcs) == 0:
|
|
w.types[name] = nil
|
|
return nil, nil
|
|
case len(srcs) > 1:
|
|
return nil, fmt.Errorf("Puppet::Type.type(:%s): more than one module provides it", name)
|
|
case w.loaded[srcs[0].mod+"\x00"+srcs[0].rel]:
|
|
return nil, fmt.Errorf("Puppet::Type.type(:%s): lib/%s.rb was already required", name, lib)
|
|
}
|
|
types, err := parseFile(srcs[0], w)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("Puppet::Type.type(:%s): %w", name, err)
|
|
}
|
|
i := slices.IndexFunc(types, func(t *rtype) bool { return t.name == name })
|
|
if i < 0 || len(types) > 1 {
|
|
return nil, fmt.Errorf("Puppet::Type.type(:%s): lib/%s.rb does not define exactly that type", name, lib)
|
|
}
|
|
lt := &loadedType{t: types[i]}
|
|
w.types[name] = lt
|
|
saved := w.typ
|
|
w.typ = lt.t
|
|
defer func() { w.typ = saved }()
|
|
provs, err := loadProviders(lt.t, w.provFiles[name], w)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("Puppet::Type.type(:%s): %w", name, err)
|
|
}
|
|
tc := "Puppet::Type::" + capitalize(name)
|
|
for n, pr := range provs {
|
|
cname := tc + "::Provider" + capitalize(n)
|
|
w.define(cname, pr.c.kind)
|
|
w.user[cname], w.classes[cname], w.sup[cname] = true, pr.c, pr.c.parent
|
|
if pr.parent != "" {
|
|
w.sup[cname] = tc + "::Provider" + capitalize(pr.parent)
|
|
}
|
|
w.classSdefs(cname)
|
|
w.sdefs[cname] = pr.c.sdefs
|
|
}
|
|
lt.provs = provs
|
|
return lt, nil
|
|
}
|
|
|
|
func (p *parser) typeAhead() bool {
|
|
return p.is(tConst, "Puppet") && p.at(1).text == "::" && p.at(2).text == "Type" && p.at(3).text == "." && p.at(4).text == "type" && p.w != nil
|
|
}
|
|
|
|
// typeCall evaluates Puppet::Type.type(:name) at the cursor to the type, or nil.
|
|
func (p *parser) typeCall() (rval, error) {
|
|
p.i += 5
|
|
args, err := p.args()
|
|
if err != nil {
|
|
return rval{}, err
|
|
}
|
|
if len(args) != 1 || args[0].k != vSym {
|
|
return rval{}, fmt.Errorf("unsupported Puppet::Type.type arguments")
|
|
}
|
|
lt, err := p.w.loadType(args[0].s)
|
|
if err != nil || lt == nil {
|
|
return rval{k: vNil}, err
|
|
}
|
|
return rval{k: vType, s: args[0].s}, nil
|
|
}
|
|
|
|
// typeProvider evaluates type.provider(:name) of a type whose providers have loaded: its class, or nil.
|
|
func (p *parser) typeProvider(v rval) (rval, error) {
|
|
args, err := p.args()
|
|
if err != nil {
|
|
return v, err
|
|
}
|
|
if len(args) != 1 || args[0].k != vSym && args[0].k != vStr || !rubyName.MatchString(args[0].s) {
|
|
return v, fmt.Errorf("unsupported provider arguments")
|
|
}
|
|
lt := p.w.types[v.s]
|
|
if lt == nil || lt.provs == nil {
|
|
return v, fmt.Errorf("Puppet::Type.type(:%s).provider: its providers are still loading", v.s)
|
|
}
|
|
if lt.provs[args[0].s] == nil {
|
|
return rval{k: vNil}, nil
|
|
}
|
|
return rval{k: vConst, s: "Puppet::Type::" + capitalize(v.s) + "::Provider" + capitalize(args[0].s)}, nil
|
|
}
|
|
|
|
// libName is a require path $LOAD_PATH resolves: no absolute, home or ./ path.
|
|
var libName = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9_.-]*(/[A-Za-z0-9_][A-Za-z0-9_.-]*)*$`)
|
|
|
|
// openvoxFeatures are the features openvox 9.3.0 adds, whose results depend on the host.
|
|
var openvoxFeatures = set("bolt cfpropertylist dbus eventlog hiera hiera_eyaml hocon ldap libshadow libuser manages_symlinks microsoft_windows minitar msgpack openssl pe_license posix pson puppetserver_ca root selinux sqlite ssh syslog telnet usage zlib")
|
|
|
|
// featuresCall matches Puppet.features.<m> at the cursor, or Puppet.features.<name>? for an empty m.
|
|
func (p *parser) featuresCall(m string) bool {
|
|
n := p.at(4)
|
|
return p.w != nil && p.is(tConst, "Puppet") && p.lexical("Puppet") == "Puppet" && p.at(1).text == "." && p.at(2).text == "features" && p.at(3).text == "." && n.kind == tIdent &&
|
|
(m == "" && strings.HasSuffix(n.text, "?") && n.text != "?" || n.text == m)
|
|
}
|
|
|
|
// featureAdd runs Puppet.features.add(:name, libs: lib or [libs]) without a block.
|
|
func (p *parser) featureAdd() error {
|
|
p.i += 5
|
|
args, err := p.args()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if len(args) != 2 || args[0].k != vSym || args[1].k != vHash || len(args[1].keys) != 1 || p.is(tIdent, "do") || p.op("{") {
|
|
return fmt.Errorf("unsupported Puppet.features.add arguments")
|
|
}
|
|
libs, ok := args[1].get("libs")
|
|
if libs.k == vStr {
|
|
libs = rval{k: vArray, arr: []rval{libs}}
|
|
}
|
|
if !ok || libs.k != vArray || slices.ContainsFunc(libs.arr, func(l rval) bool { return l.k != vStr }) {
|
|
return fmt.Errorf("unsupported Puppet.features.add libs")
|
|
}
|
|
p.w.features[args[0].s] = nil
|
|
for _, l := range libs.arr {
|
|
p.w.features[args[0].s] = append(p.w.features[args[0].s], l.s)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// featureTest ports Puppet.features.<name>?: a missing method autoloads puppet/feature/<name>.rb, and a feature with
|
|
// libs is true when requiring each loads, which for a gem holds only when it is declared.
|
|
func (p *parser) featureTest(name string) (bool, error) {
|
|
if openvoxFeatures[name] || coreLib("puppet/feature/"+name) {
|
|
return false, fmt.Errorf("feature %s? depends on the host", name)
|
|
}
|
|
if _, ok := p.w.features[name]; !ok {
|
|
if err := p.loadFeature(name); err != nil {
|
|
return false, err
|
|
}
|
|
}
|
|
libs, ok := p.w.features[name]
|
|
if !ok {
|
|
return false, nil
|
|
}
|
|
for _, lib := range libs {
|
|
if p.w.resolve == nil || !libName.MatchString(lib) || strings.Contains(lib, "..") {
|
|
return false, fmt.Errorf("feature %s?: require %q is not modelled", name, lib)
|
|
}
|
|
_, modelled := puppetLibs[lib]
|
|
_, gem, declared := p.w.gemFor(lib)
|
|
srcs, err := p.w.resolve(lib+".rb", "")
|
|
switch {
|
|
case err != nil:
|
|
return false, err
|
|
case len(srcs) > 0 || coreLib(lib) && !modelled && !rubyLibs[lib] || declared && gem.entry != lib:
|
|
return false, fmt.Errorf("feature %s?: require %q is not modelled", name, lib)
|
|
case !modelled && !rubyLibs[lib] && !declared:
|
|
return false, nil
|
|
}
|
|
if err := p.requireLib(lib, false); err != nil {
|
|
return false, err
|
|
}
|
|
}
|
|
return true, nil
|
|
}
|
|
|
|
// loadFeature loads the first puppet/feature/<name>.rb in module lib dirs, which every copy must match.
|
|
func (p *parser) loadFeature(name string) error {
|
|
if p.w.resolve == nil {
|
|
return fmt.Errorf("feature %s?: module sources are not available", name)
|
|
}
|
|
srcs, err := p.w.resolve("puppet/feature/"+name+".rb", "")
|
|
switch {
|
|
case err != nil:
|
|
return err
|
|
case len(srcs) == 0:
|
|
return nil
|
|
case slices.ContainsFunc(srcs, func(f libFile) bool { return f.src != srcs[0].src }):
|
|
return fmt.Errorf("feature %s?: module copies of its feature file differ", name)
|
|
case p.w.loaded[srcs[0].mod+"\x00"+srcs[0].rel]:
|
|
return fmt.Errorf("feature %s?: its feature file loads again", name)
|
|
}
|
|
return p.load(srcs[0])
|
|
}
|
|
|
|
// onigNames ports Onigmo's Regexp#names: named groups in first-appearance order, skipping escapes, character classes,
|
|
// (?#...) comments and, in extended mode, # comments. A name outside [A-Za-z_][A-Za-z0-9_]* or a reference w10k
|
|
// cannot resolve is an error.
|
|
func onigNames(re regex) ([]string, error) {
|
|
s := re.src
|
|
var names []string
|
|
ext := []bool{strings.Contains(re.flags, "x")}
|
|
name := func(i int, end byte) (string, int, error) {
|
|
j := strings.IndexByte(s[i:], end)
|
|
if j < 0 || !rubyIdent.MatchString(s[i:i+j]) {
|
|
return "", 0, fmt.Errorf("regex /%s/: unsupported group name", s)
|
|
}
|
|
return s[i : i+j], i + j + 1, nil
|
|
}
|
|
for i := 0; i < len(s); {
|
|
c := s[i]
|
|
switch {
|
|
case c == '\\' && i+1 < len(s) && s[i+1] == 'k':
|
|
if i+2 >= len(s) || s[i+2] != '<' {
|
|
return nil, fmt.Errorf("regex /%s/: unsupported \\k", s)
|
|
}
|
|
n, j, err := name(i+3, '>')
|
|
if err != nil || !slices.Contains(names, n) {
|
|
return nil, fmt.Errorf("regex /%s/: unsupported back reference", s)
|
|
}
|
|
i = j
|
|
case c == '\\' && i+1 < len(s) && s[i+1] == 'g':
|
|
return nil, fmt.Errorf("regex /%s/: unsupported subexpression call", s)
|
|
case c == '\\':
|
|
_, n := utf8.DecodeRuneInString(s[min(i+1, len(s)):])
|
|
i += 1 + n
|
|
case c == '[':
|
|
depth := 0
|
|
for i < len(s) {
|
|
switch s[i] {
|
|
case '\\':
|
|
i++
|
|
case '[':
|
|
depth++
|
|
if i++; i < len(s) && s[i] == '^' {
|
|
i++
|
|
}
|
|
if i < len(s) && s[i] == ']' {
|
|
i++
|
|
}
|
|
continue
|
|
case ']':
|
|
depth--
|
|
}
|
|
i++
|
|
if depth == 0 {
|
|
break
|
|
}
|
|
}
|
|
if depth != 0 {
|
|
return nil, fmt.Errorf("regex /%s/: premature end of char-class", s)
|
|
}
|
|
case ext[len(ext)-1] && c == '#':
|
|
for i < len(s) && s[i] != '\n' {
|
|
i++
|
|
}
|
|
case c == '(' && strings.HasPrefix(s[i:], "(?#"):
|
|
for i += 3; i < len(s) && s[i] != ')'; i++ {
|
|
if s[i] == '\\' {
|
|
i++
|
|
}
|
|
}
|
|
if i++; i > len(s) {
|
|
return nil, fmt.Errorf("regex /%s/: end pattern in group", s)
|
|
}
|
|
case c == '(' && (strings.HasPrefix(s[i:], "(?<") && !strings.HasPrefix(s[i:], "(?<=") && !strings.HasPrefix(s[i:], "(?<!") || strings.HasPrefix(s[i:], "(?'")):
|
|
end := byte('>')
|
|
if s[i+2] == '\'' {
|
|
end = '\''
|
|
}
|
|
n, j, err := name(i+3, end)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !slices.Contains(names, n) {
|
|
names = append(names, n)
|
|
}
|
|
ext = append(ext, ext[len(ext)-1])
|
|
i = j
|
|
case c == '(' && strings.HasPrefix(s[i:], "(?") && i+2 < len(s) && strings.IndexByte("imx-", s[i+2]) >= 0:
|
|
on, x := true, ext[len(ext)-1]
|
|
j := i + 2
|
|
for ; j < len(s) && s[j] != ':' && s[j] != ')'; j++ {
|
|
switch s[j] {
|
|
case '-':
|
|
on = false
|
|
case 'x':
|
|
x = on
|
|
case 'i', 'm':
|
|
default:
|
|
return nil, fmt.Errorf("regex /%s/: unsupported group option", s)
|
|
}
|
|
}
|
|
if j == len(s) {
|
|
return nil, fmt.Errorf("regex /%s/: end pattern in group", s)
|
|
}
|
|
if s[j] == ')' {
|
|
ext[len(ext)-1] = x
|
|
} else {
|
|
ext = append(ext, x)
|
|
}
|
|
i = j + 1
|
|
case c == '(':
|
|
ext = append(ext, ext[len(ext)-1])
|
|
i++
|
|
case c == ')':
|
|
if len(ext) == 1 {
|
|
return nil, fmt.Errorf("regex /%s/: unmatched close parenthesis", s)
|
|
}
|
|
ext = ext[:len(ext)-1]
|
|
i++
|
|
default:
|
|
i++
|
|
}
|
|
}
|
|
if len(ext) != 1 {
|
|
return nil, fmt.Errorf("regex /%s/: end pattern with unmatched parenthesis", s)
|
|
}
|
|
return names, nil
|
|
}
|
|
|
|
var rubyIdent = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
|