1208 lines
38 KiB
Go
1208 lines
38 KiB
Go
package gentypes
|
|
|
|
import (
|
|
"bytes"
|
|
_ "embed"
|
|
"fmt"
|
|
"path"
|
|
"regexp"
|
|
"slices"
|
|
"strings"
|
|
)
|
|
|
|
// libFile is lib/<rel> of module mod.
|
|
type libFile struct{ mod, rel, src string }
|
|
|
|
// Resolver returns lib/<rel> of every module that has it in modulepath order, or of mod alone when mod is set.
|
|
type Resolver func(rel, mod string) ([]libFile, error)
|
|
|
|
// world is the Ruby state a type file shares with the providers and libraries puppet loads for it.
|
|
type world struct {
|
|
resolve Resolver
|
|
shadows func(mod string) (string, error)
|
|
defined map[string]bool
|
|
kind map[string]byte
|
|
sup map[string]string
|
|
user map[string]bool
|
|
mods map[string][]string
|
|
loaded map[string]bool
|
|
gems map[string]bool
|
|
classes map[string]*classCtx
|
|
// tclasses are the classes newtype defined, which already hold their providers when later code reopens them
|
|
tclasses map[string]bool
|
|
// typ is the type whose providers are loading; sdefs are user classes' singleton methods by class
|
|
typ *rtype
|
|
sdefs map[string]map[string]*sdef
|
|
steps, alloc int
|
|
// provFiles are the provider files by type; types are the types Puppet::Type.type returns, nil where none loads
|
|
provFiles map[string][]string
|
|
types map[string]*loadedType
|
|
// features are the libs of each Puppet.features.add a loaded file ran
|
|
features map[string][]string
|
|
}
|
|
|
|
// loadedType is a type newtype stored; provs is set once its providerloader.loadall finished.
|
|
type loadedType struct {
|
|
t *rtype
|
|
provs map[string]*provDecl
|
|
}
|
|
|
|
// Constant kinds: module, class, a Puppet::Provider subclass, a Puppet::Provider::ParsedFile subclass.
|
|
const (
|
|
kMod = 'm'
|
|
kClass = 'c'
|
|
kProv = 'p'
|
|
kParsed = 'f'
|
|
)
|
|
|
|
//go:embed startup.txt
|
|
var startupTxt string
|
|
|
|
// startup are the constants defined before openvox 9.3.0 `puppet generate types` loads any type.
|
|
var startup = func() map[string]byte {
|
|
m := map[string]byte{}
|
|
for _, l := range strings.Split(startupTxt, "\n") {
|
|
if name, k, ok := strings.Cut(l, " "); ok && !strings.HasPrefix(l, "#") {
|
|
m[name] = k[0]
|
|
}
|
|
}
|
|
m["Puppet::Provider"] = kProv
|
|
return m
|
|
}()
|
|
|
|
func newWorld(resolve Resolver) *world {
|
|
w := &world{resolve: resolve, defined: map[string]bool{}, kind: map[string]byte{}, sup: map[string]string{}, user: map[string]bool{}, mods: map[string][]string{}, loaded: map[string]bool{}, classes: map[string]*classCtx{}, tclasses: map[string]bool{}, types: map[string]*loadedType{}, features: map[string][]string{}}
|
|
for c, k := range startup {
|
|
w.define(c, k)
|
|
}
|
|
return w
|
|
}
|
|
|
|
func (w *world) define(c string, k byte) {
|
|
w.defined[c] = true
|
|
w.kind[c] = k
|
|
}
|
|
|
|
//go:embed corelibs.txt
|
|
var corelibsTxt string
|
|
|
|
// corelibs are the require paths openvox 9.3.0, its gems and Ruby 3.3's stdlib provide ahead of module lib dirs on
|
|
// $LOAD_PATH: full paths under puppet/, hiera/, facter/ and puppet_x, and first path segments elsewhere.
|
|
var corelibs = func() map[string]bool {
|
|
m := map[string]bool{}
|
|
for _, l := range strings.Split(corelibsTxt, "\n") {
|
|
if l = strings.TrimSpace(l); l != "" && !strings.HasPrefix(l, "#") {
|
|
m[l] = true
|
|
}
|
|
}
|
|
return m
|
|
}()
|
|
|
|
// gemModel is what requiring a gem's entry path does: its gem and dependencies put the require roots ahead of module
|
|
// lib dirs on $LOAD_PATH and define consts, under the top-level namespaces tops.
|
|
type gemModel struct {
|
|
entry string
|
|
roots, tops []string
|
|
consts []string
|
|
}
|
|
|
|
// knownGems are the gems w10k models when declared, as installed beside openvox 9.3.0 on Ruby 3.3.
|
|
var knownGems = map[string]gemModel{
|
|
// toml 0.3.0 with parslet 2.0.0; toml/monkey_patch loads only when TOML::Generator runs.
|
|
"toml": {entry: "toml", roots: []string{"toml", "parslet"}, tops: []string{"TOML", "Parslet"}, consts: strings.Split(`Parslet m
|
|
Parslet::Atoms m
|
|
Parslet::Atoms::Alternative c
|
|
Parslet::Atoms::Base c
|
|
Parslet::Atoms::CanFlatten m
|
|
Parslet::Atoms::Capture c
|
|
Parslet::Atoms::Context c
|
|
Parslet::Atoms::DSL m
|
|
Parslet::Atoms::Dynamic c
|
|
Parslet::Atoms::Entity c
|
|
Parslet::Atoms::Ignored c
|
|
Parslet::Atoms::Infix c
|
|
Parslet::Atoms::Lookahead c
|
|
Parslet::Atoms::Named c
|
|
Parslet::Atoms::Precedence m
|
|
Parslet::Atoms::Re c
|
|
Parslet::Atoms::Repetition c
|
|
Parslet::Atoms::Scope c
|
|
Parslet::Atoms::Sequence c
|
|
Parslet::Atoms::Str c
|
|
Parslet::Cause c
|
|
Parslet::ClassMethods m
|
|
Parslet::Context c
|
|
Parslet::DelayedMatchConstructor c
|
|
Parslet::ErrorReporter m
|
|
Parslet::ErrorReporter::Contextual c
|
|
Parslet::ErrorReporter::Deepest c
|
|
Parslet::ErrorReporter::Tree c
|
|
Parslet::ParseFailed c
|
|
Parslet::Parser c
|
|
Parslet::Pattern c
|
|
Parslet::Pattern::SequenceBind c
|
|
Parslet::Pattern::SimpleBind c
|
|
Parslet::Pattern::SubtreeBind c
|
|
Parslet::Position c
|
|
Parslet::Scope c
|
|
Parslet::Scope::Binding c
|
|
Parslet::Scope::NotFound c
|
|
Parslet::Slice c
|
|
Parslet::Source c
|
|
Parslet::Source::LineCache c
|
|
Parslet::Source::RangeSearch m
|
|
Parslet::Transform c
|
|
TOML m
|
|
TOML::Generator c
|
|
TOML::Key c
|
|
TOML::Parser c
|
|
TOML::Parslet c
|
|
TOML::Table c
|
|
TOML::TableArray c
|
|
TOML::Transformer c`, "\n")},
|
|
}
|
|
|
|
// KnownGem reports whether w10k models gem name.
|
|
func KnownGem(name string) bool {
|
|
_, ok := knownGems[name]
|
|
return ok
|
|
}
|
|
|
|
// gemFor returns the declared gem whose require roots contain lib.
|
|
func (w *world) gemFor(lib string) (string, gemModel, bool) {
|
|
first, _, _ := strings.Cut(lib, "/")
|
|
for name := range w.gems {
|
|
if g := knownGems[name]; slices.Contains(g.roots, first) {
|
|
return name, g, true
|
|
}
|
|
}
|
|
return "", gemModel{}, false
|
|
}
|
|
|
|
// gemTop returns the declared gem defining top-level constant c.
|
|
func (w *world) gemTop(c string) string {
|
|
for name := range w.gems {
|
|
if slices.Contains(knownGems[name].tops, c) {
|
|
return name
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func coreLib(lib string) bool {
|
|
first, _, _ := strings.Cut(lib, "/")
|
|
switch first {
|
|
case "puppet", "hiera", "puppet_x", "facter":
|
|
return corelibs[lib]
|
|
}
|
|
return corelibs[first]
|
|
}
|
|
|
|
// load evaluates a required module file once, as Ruby's require does.
|
|
func (p *parser) load(f libFile) error {
|
|
key := f.mod + "\x00" + f.rel
|
|
if p.w.loaded[key] {
|
|
return nil
|
|
}
|
|
p.w.loaded[key] = true
|
|
toks, err := lex(f.src)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
q := &parser{toks: toks, consts: map[string]rval{}, used: map[int]bool{}, w: p.w, defined: p.w.defined, mod: f.mod, dir: path.Dir(f.rel), file: path.Base(f.rel), depth: p.depth, src: f.src}
|
|
if err := q.body("", q.fileStmt(nil)); err != nil {
|
|
return fmt.Errorf("lib/%s: %w", f.rel, q.wrap(err))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// fileStmt allows the top level of a required file or provider file: requires, literal constants and module or class
|
|
// definitions; prov additionally takes the provider file's one provide call.
|
|
func (p *parser) fileStmt(prov func() (bool, error)) func() (bool, error) {
|
|
return func() (bool, error) {
|
|
t := p.cur()
|
|
switch {
|
|
case t.kind == tIdent && (t.text == "require" || t.text == "require_relative"):
|
|
return true, p.require()
|
|
case t.kind == tIdent && t.text == "begin":
|
|
return true, p.beginRequire()
|
|
case t.kind == tIdent && (t.text == "module" || t.text == "class") && p.at(1).kind == tConst:
|
|
return true, p.namespace()
|
|
case t.kind == tConst && (p.assigns() || p.at(1).text == "||=") && !coreConsts[t.text]:
|
|
return true, p.strictConstAssign()
|
|
case t.kind == tGVar && t.text == "$LOAD_PATH" && p.at(1).text == "." && p.at(2).text == "unshift":
|
|
return true, p.unshift()
|
|
case p.featuresCall("add"):
|
|
return true, p.featureAdd()
|
|
case t.kind == tIdent && (t.text == "raise" || t.text == "fail"):
|
|
return true, p.guardedRaise()
|
|
case prov != nil:
|
|
if ok, err := prov(); ok || err != nil {
|
|
return true, err
|
|
}
|
|
}
|
|
return true, fmt.Errorf("unsupported top-level %s", p.construct())
|
|
}
|
|
}
|
|
|
|
// guardedRaise runs raise ... if/unless cond, which raises when the condition holds; Ruby evaluates the raise
|
|
// arguments only then.
|
|
func (p *parser) guardedRaise() error {
|
|
start := p.i
|
|
depth := 0
|
|
for ; p.cur().kind != tEOF && (depth > 0 || p.cur().kind != tNL && !p.op(";")); p.i++ {
|
|
t := p.cur()
|
|
switch {
|
|
case t.kind == tOp && strings.Contains("([{", t.text):
|
|
depth++
|
|
case t.kind == tOp && strings.Contains(")]}", t.text):
|
|
depth--
|
|
case depth == 0 && t.kind == tIdent && (t.text == "if" || t.text == "unless") && p.i > start+1:
|
|
unless := p.take().text == "unless"
|
|
cond, err := p.eval()
|
|
if err == nil && truthy(cond) != unless {
|
|
err = fmt.Errorf("%s raises", p.toks[start].text)
|
|
}
|
|
return err
|
|
}
|
|
}
|
|
return fmt.Errorf("unsupported top-level %s", p.toks[start].text)
|
|
}
|
|
|
|
// lexical resolves constant path c as Ruby does from the current lexical scope, or returns "" when it is undefined.
|
|
func (p *parser) lexical(c string) string {
|
|
for i := len(p.cref) - 1; i >= 0; i-- {
|
|
if q := p.cref[i] + "::" + c; p.w.defined[q] {
|
|
return q
|
|
}
|
|
}
|
|
if p.w.defined[c] {
|
|
return c
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// namespace evaluates module/class Name [< Super] ... end in the current lexical scope.
|
|
func (p *parser) namespace() error {
|
|
isClass := p.take().text == "class"
|
|
name, err := p.constPath()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
outer := ""
|
|
if len(p.cref) > 0 {
|
|
outer = p.cref[len(p.cref)-1] + "::"
|
|
}
|
|
if i := strings.LastIndex(name, "::"); i >= 0 {
|
|
ns := p.lexical(name[:i])
|
|
if ns == "" {
|
|
return fmt.Errorf("uninitialized constant %s", name[:i])
|
|
}
|
|
name = ns + name[i:]
|
|
} else {
|
|
name = outer + name
|
|
}
|
|
if top, _, _ := strings.Cut(name, "::"); p.w.gemTop(top) != "" {
|
|
return fmt.Errorf("%s opens a namespace of gem %s", name, p.w.gemTop(top))
|
|
}
|
|
for t := range p.w.tclasses {
|
|
if strings.HasPrefix(name, t+"::") {
|
|
return fmt.Errorf("%s opens a namespace of type class %s", name, t)
|
|
}
|
|
}
|
|
k, had := p.w.kind[name]
|
|
switch {
|
|
case !isClass:
|
|
if had && k != kMod {
|
|
return fmt.Errorf("%s is not a module", name)
|
|
}
|
|
p.w.define(name, kMod)
|
|
p.w.mods[name] = append(p.w.mods[name], p.src)
|
|
case p.op("<"):
|
|
p.take()
|
|
sup, err := p.constPath()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
rs := p.lexical(sup)
|
|
sk := p.w.kind[rs]
|
|
if sk == kMod || sk == 0 {
|
|
return fmt.Errorf("superclass %s is not a defined class", sup)
|
|
}
|
|
if had && p.w.sup[name] != rs {
|
|
return fmt.Errorf("superclass mismatch for class %s", name)
|
|
}
|
|
p.w.define(name, sk)
|
|
p.w.sup[name] = rs
|
|
default:
|
|
if had && k == kMod {
|
|
return fmt.Errorf("%s is not a class", name)
|
|
}
|
|
if !had {
|
|
p.w.define(name, kClass)
|
|
}
|
|
}
|
|
p.cref = append(p.cref, name)
|
|
defer func() { p.cref = p.cref[:len(p.cref)-1] }()
|
|
if had && !p.w.user[name] {
|
|
return p.body("end", func() (bool, error) {
|
|
if (p.is(tIdent, "module") || p.is(tIdent, "class")) && p.at(1).kind == tConst {
|
|
return true, p.namespace()
|
|
}
|
|
return true, fmt.Errorf("reopened %s may only nest modules and classes, found %s", name, p.construct())
|
|
})
|
|
}
|
|
p.w.user[name] = true
|
|
c := p.w.classes[name]
|
|
if c == nil {
|
|
c = newClass(p.w.kind[name], false)
|
|
c.sdefs, c.parent = p.w.classSdefs(name), p.w.sup[name]
|
|
p.w.classes[name] = c
|
|
}
|
|
c.priv = false
|
|
stmt := p.classStmt(name, c)
|
|
return p.body("end", func() (bool, error) {
|
|
t := p.cur()
|
|
inert := t.kind == tIdent && (t.text == "def" && p.at(1).text != "self" || t.text == "private" || t.text == "protected" || t.text == "public" ||
|
|
(t.text == "module" || t.text == "class") && p.at(1).kind == tConst)
|
|
if !inert && c.parented {
|
|
return true, fmt.Errorf("%s runs class-level code after an attribute inherits from it", name)
|
|
}
|
|
c.active = c.active || !inert
|
|
return stmt()
|
|
})
|
|
}
|
|
|
|
// userParent resolves attribute parent c, a chain of user classes whose bodies define only instance methods, to the
|
|
// puppet class it inherits from: their genclass'd subclass then has that class's values, doc and class methods.
|
|
func (w *world) userParent(c string) (string, error) {
|
|
for w != nil && w.user[c] {
|
|
cc := w.classes[c]
|
|
if cc == nil || cc.kind != kClass || cc.active {
|
|
return "", fmt.Errorf("parent %s runs class-level code", c)
|
|
}
|
|
cc.parented = true
|
|
c = w.sup[c]
|
|
}
|
|
return c, nil
|
|
}
|
|
|
|
// addMethod records instance method n; Puppet::Property.method_added raises on safe_insync? in its subclasses.
|
|
func (c *classCtx) addMethod(n string, hidden bool) error {
|
|
if n == "safe_insync?" && c.kind == kClass && c.parent != "" {
|
|
return fmt.Errorf("Puppet::Property.method_added raises on safe_insync?")
|
|
}
|
|
c.methods[n], c.hidden[n] = true, hidden
|
|
return nil
|
|
}
|
|
|
|
func (p *parser) constPath() (string, error) {
|
|
if p.cur().kind != tConst {
|
|
return "", fmt.Errorf("expected a constant, found %s", describe(p.cur()))
|
|
}
|
|
name := p.take().text
|
|
for p.op("::") && p.at(1).kind == tConst {
|
|
p.take()
|
|
name += "::" + p.take().text
|
|
}
|
|
return name, nil
|
|
}
|
|
|
|
// classCtx is what a class body defines; for providers, gen marks a genclass'd class, which starts with initvars run,
|
|
// and doc, defaults, commands and declared are its own Puppet::Provider DSL state, never inherited.
|
|
type classCtx struct {
|
|
kind byte
|
|
methods map[string]bool
|
|
smethods map[string]bool
|
|
lines map[string]bool
|
|
hidden map[string]bool
|
|
priv bool
|
|
mixed []string
|
|
cmds map[string]bool
|
|
mkres bool
|
|
gen bool
|
|
inited bool
|
|
doc *string
|
|
defaults []rval
|
|
commands map[string]string
|
|
declared []string
|
|
// singleton methods so far, the user superclass searched next, and for a provide block its type and top-level cref
|
|
sdefs map[string]*sdef
|
|
parent string
|
|
parentUnknown bool
|
|
// active marks class-level code in a user class body; parented marks a class an attribute inherits from
|
|
active, parented bool
|
|
typ *rtype
|
|
block bool
|
|
// a module's instance method bodies and included hook; extended methods that stand in for the ones they shadow
|
|
idefs map[string]*sdef
|
|
included *sdef
|
|
supers map[string]bool
|
|
}
|
|
|
|
func newClass(kind byte, gen bool) *classCtx {
|
|
return &classCtx{kind: kind, gen: gen, methods: map[string]bool{}, smethods: map[string]bool{}, hidden: map[string]bool{}, cmds: map[string]bool{}, commands: map[string]string{}, idefs: map[string]*sdef{}, supers: map[string]bool{}}
|
|
}
|
|
|
|
// Hooks Ruby or Puppet::Provider call on a class or module while loading it; defining one runs code w10k cannot see.
|
|
var hooks = set("inherited method_added singleton_method_added included extended prepended append_features const_missing method_missing respond_to_missing? respond_to? postinit initvars name doc to_s inspect")
|
|
|
|
// providerIvars are the class-level ivars openvox 9.3.0's Puppet::Provider, Confiner, ProviderFeatures, Docs and
|
|
// ParsedFile read; plainGlobal excludes Ruby's special globals.
|
|
var (
|
|
providerIvars = set("abstract backup_stats commands confine_collection confiner declared_features default_target defaults doc executor failed_prefetch_targets feature_module features filetype line_separator name notdefaults property_hash raise_prefetch_errors record_order records record_types resource resource_type source stampwarnings target target_objects trailing_separator")
|
|
plainGlobal = regexp.MustCompile(`^\$[a-z][a-z0-9_]*$`)
|
|
)
|
|
|
|
// providerDSL are the Puppet::Provider class methods a provider body may call; each consumes literal arguments only.
|
|
var providerDSL = set("desc confine defaultfor notdefaultfor commands optional_commands has_feature has_features has_command mk_resource_methods initvars text_line record_line")
|
|
|
|
// classStmt allows a class or module body whose evaluation cannot raise: method and accessor definitions, literal
|
|
// constants and variables, includes of analysed modules, nested namespaces and, in providers, literal DSL calls.
|
|
func (p *parser) classStmt(name string, c *classCtx) func() (bool, error) {
|
|
return func() (bool, error) {
|
|
t := p.cur()
|
|
switch {
|
|
case t.kind == tIdent && (t.text == "require" || t.text == "require_relative"):
|
|
return true, p.require()
|
|
case t.kind == tIdent && t.text == "def" && c.kind == kMod && p.at(1).text == "self" && p.at(2).text == "." && p.at(3).text == "included":
|
|
return true, p.includedHook(c)
|
|
case t.kind == tIdent && t.text == "def":
|
|
return true, p.defMethod(c, false)
|
|
case t.kind == tIdent && t.text == "class" && p.at(1).text == "<<" && p.at(2).text == "self":
|
|
p.i += 3
|
|
return true, p.body("end", func() (bool, error) { return p.singletonBody(c) })
|
|
case t.kind == tIdent && (t.text == "module" || t.text == "class") && p.at(1).kind == tConst:
|
|
return true, p.namespace()
|
|
case t.kind == tIVar && t.text == "@doc" && p.assigns() && (c.kind == kProv || c.kind == kParsed):
|
|
p.i += 2
|
|
s, err := p.docExpr()
|
|
c.doc = &s
|
|
return true, err
|
|
case t.kind == tConst && p.assigns():
|
|
saved, savedCls := p.scope, p.cls
|
|
p.scope, p.cls = name, c
|
|
if c.block {
|
|
p.scope = ""
|
|
}
|
|
defer func() { p.scope, p.cls = saved, savedCls }()
|
|
if c.block && p.defined[t.text] {
|
|
return true, fmt.Errorf("%s = overwrites a constant puppet defines", t.text)
|
|
}
|
|
return true, p.strictConstAssign()
|
|
case p.assigns() && (t.kind == tIVar && !strings.HasPrefix(t.text, "@@") && (!providerIvars[t.text[1:]] || c.kind != kProv && c.kind != kParsed) ||
|
|
t.kind == tGVar && plainGlobal.MatchString(t.text) && t.text != "$stdout" && t.text != "$stderr" && t.text != "$stdin"):
|
|
p.i += 2
|
|
_, err := p.expr()
|
|
return true, err
|
|
case t.kind == tIdent && (t.text == "attr_accessor" || t.text == "attr_reader" || t.text == "attr_writer"):
|
|
return true, p.accessors(c)
|
|
case t.kind == tConst && t.text == "ENV" && p.at(1).text == "[":
|
|
return true, p.envAssign()
|
|
case t.kind == tIdent && (t.text == "private" || t.text == "protected" || t.text == "public"):
|
|
return true, p.visibility(c)
|
|
case t.kind == tIdent && (t.text == "alias_method" || t.text == "alias"):
|
|
return true, p.alias(c)
|
|
case t.kind == tIdent && t.text == "include" && p.at(1).kind == tConst:
|
|
p.take()
|
|
m, err := p.constPath()
|
|
if err != nil {
|
|
return true, err
|
|
}
|
|
names, err := p.mixin(m)
|
|
c.mixed = append(c.mixed, names...)
|
|
if err == nil {
|
|
err = p.runIncluded(c, p.lexical(m))
|
|
}
|
|
return true, err
|
|
case t.kind == tIdent && (c.kind == kProv || c.kind == kParsed) && providerDSL[t.text] && (!c.smethods[t.text] || c.supers[t.text]):
|
|
return true, p.providerCall(c)
|
|
}
|
|
if ok, err := p.evalStmt(c); ok {
|
|
return true, err
|
|
}
|
|
return true, fmt.Errorf("unsupported %s in %s", p.construct(), name)
|
|
}
|
|
}
|
|
|
|
func (p *parser) defMethod(c *classCtx, single bool) error {
|
|
n, off := p.at(1).text, 1
|
|
if p.at(1).text == "self" && p.at(2).text == "." {
|
|
single, n, off = true, p.at(3).text, 3
|
|
}
|
|
if !single {
|
|
if err := c.addMethod(n, c.priv); err != nil {
|
|
return err
|
|
}
|
|
if c.kind != kMod {
|
|
return p.skipStatement()
|
|
}
|
|
sd := p.newSdef(off)
|
|
c.idefs[n] = sd
|
|
err := p.skipStatement()
|
|
if sd != nil {
|
|
sd.end = p.i - 1
|
|
}
|
|
return err
|
|
}
|
|
if hooks[n] || providerDSL[n] || strings.HasPrefix(n, "dochook_") {
|
|
return fmt.Errorf("def self.%s runs while loading", n)
|
|
}
|
|
c.smethods[n] = true
|
|
sd := c.defSingleton(p, n, off)
|
|
err := p.skipStatement()
|
|
if sd != nil {
|
|
sd.end = p.i - 1
|
|
}
|
|
return err
|
|
}
|
|
|
|
func (p *parser) singletonBody(c *classCtx) (bool, error) {
|
|
t := p.cur()
|
|
switch {
|
|
case t.kind == tIdent && t.text == "def":
|
|
return true, p.defMethod(c, true)
|
|
case t.kind == tIdent && (t.text == "attr_accessor" || t.text == "attr_reader" || t.text == "attr_writer"):
|
|
args, err := p.symArgs()
|
|
for _, a := range args {
|
|
if hooks[a] || providerDSL[a] {
|
|
return true, fmt.Errorf("%s %s shadows a class method", t.text, a)
|
|
}
|
|
c.smethods[a] = true
|
|
c.opaque(a, a+"=")
|
|
}
|
|
return true, err
|
|
case t.kind == tIdent && (t.text == "private" || t.text == "protected" || t.text == "public") && (p.at(1).kind == tNL || p.at(1).text == ";"):
|
|
p.take()
|
|
return true, nil
|
|
}
|
|
return true, fmt.Errorf("unsupported %s in class << self", p.construct())
|
|
}
|
|
|
|
func (p *parser) symArgs() ([]string, error) {
|
|
p.take()
|
|
args, err := p.args()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var out []string
|
|
for _, a := range args {
|
|
if a.k != vSym && a.k != vStr {
|
|
return nil, fmt.Errorf("expected symbol arguments, found %s", a.kindName())
|
|
}
|
|
out = append(out, a.s)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (p *parser) accessors(c *classCtx) error {
|
|
kind := p.cur().text
|
|
names, err := p.symArgs()
|
|
for _, n := range names {
|
|
if kind != "attr_writer" {
|
|
if err := c.addMethod(n, c.priv); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if kind != "attr_reader" {
|
|
c.methods[n+"="], c.hidden[n+"="] = true, c.priv
|
|
}
|
|
}
|
|
return err
|
|
}
|
|
|
|
func (p *parser) visibility(c *classCtx) error {
|
|
kind := p.cur().text
|
|
if p.at(1).kind == tNL || p.at(1).text == ";" || p.at(1).kind == tEOF || p.closes("end") {
|
|
p.take()
|
|
c.priv = kind != "public"
|
|
return nil
|
|
}
|
|
names, err := p.symArgs()
|
|
for _, n := range names {
|
|
if !c.methods[n] {
|
|
return fmt.Errorf("%s: undefined method %s", kind, n)
|
|
}
|
|
c.hidden[n] = kind != "public"
|
|
}
|
|
return err
|
|
}
|
|
|
|
func (p *parser) alias(c *classCtx) error {
|
|
var from, to string
|
|
if p.take().text == "alias_method" {
|
|
args, err := p.args()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if len(args) != 2 || args[0].k != vSym && args[0].k != vStr || args[1].k != vSym && args[1].k != vStr {
|
|
return fmt.Errorf("unsupported alias_method arguments")
|
|
}
|
|
to, from = args[0].s, args[1].s
|
|
} else {
|
|
a, b := p.take(), p.take()
|
|
if a.kind != tIdent && a.kind != tOp || b.kind != tIdent && b.kind != tOp {
|
|
return fmt.Errorf("unsupported alias")
|
|
}
|
|
to, from = a.text, b.text
|
|
}
|
|
if !c.methods[from] {
|
|
return fmt.Errorf("alias of undefined method %s", from)
|
|
}
|
|
return c.addMethod(to, c.hidden[from])
|
|
}
|
|
|
|
// coreMixins are openvox 9.3.0 modules without include hooks, with their public instance methods.
|
|
var coreMixins = map[string][]string{"Puppet::Util": nil, "Puppet::Util::Diff": {"lcs_diff", "string_file_diff"}, "Puppet::Util::Package": nil}
|
|
|
|
func coreMixin(m string) bool {
|
|
_, ok := coreMixins[m]
|
|
return ok
|
|
}
|
|
|
|
// mixin returns the public instance methods of module m, which one loaded file must define without include hooks.
|
|
func (p *parser) mixin(m string) ([]string, error) {
|
|
r := p.lexical(m)
|
|
switch {
|
|
case r == "Enumerable" || r == "Comparable":
|
|
return nil, nil
|
|
case coreMixin(r) && p.w.defined[r]:
|
|
return coreMixins[r], nil
|
|
case r == "" || p.w.kind[r] != kMod:
|
|
return nil, fmt.Errorf("include %s: no require defines it as a module", m)
|
|
case len(p.w.mods[r]) == 0:
|
|
return nil, fmt.Errorf("include %s: no loaded module file defines it", m)
|
|
case len(p.w.mods[r]) > 1:
|
|
return nil, fmt.Errorf("include %s: more than one loaded file opens it", m)
|
|
}
|
|
names, err := mixinMethods(p.w.mods[r][0], r)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("include %s: %w", m, err)
|
|
}
|
|
return names, nil
|
|
}
|
|
|
|
// providerCall evaluates one literal Puppet::Provider DSL call, failing on any argument shape that raises while loading.
|
|
func (p *parser) providerCall(c *classCtx) error {
|
|
name := p.take().text
|
|
args, err := p.args()
|
|
if err != nil {
|
|
return fmt.Errorf("%s: %w", name, err)
|
|
}
|
|
hash := len(args) == 1 && args[0].k == vHash
|
|
switch name {
|
|
case "defaultfor", "notdefaultfor", "commands", "optional_commands", "has_command":
|
|
if !c.gen && !c.inited {
|
|
return fmt.Errorf("%s before initvars", name)
|
|
}
|
|
}
|
|
switch name {
|
|
case "confine":
|
|
if !hash || slices.ContainsFunc(args[0].keys, func(k rval) bool { return k.k != vSym && k.k != vStr }) {
|
|
return fmt.Errorf("confine takes one literal hash")
|
|
}
|
|
for _, k := range args[0].keys {
|
|
if err := p.confineTest(k.s); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
case "defaultfor", "notdefaultfor":
|
|
if len(args) != 1 || args[0].k != vHash && args[0].k != vArray {
|
|
return fmt.Errorf("%s takes one literal hash or array", name)
|
|
}
|
|
if name == "defaultfor" {
|
|
c.defaults = append(c.defaults, args[0])
|
|
}
|
|
case "commands", "optional_commands":
|
|
if !hash || slices.ContainsFunc(args[0].keys, func(k rval) bool { return k.k != vSym && k.k != vStr }) || slices.ContainsFunc(args[0].arr, func(v rval) bool { return v.k != vStr }) {
|
|
return fmt.Errorf("%s takes one hash of names to strings", name)
|
|
}
|
|
for i, k := range args[0].keys {
|
|
c.commands[k.s], c.cmds[k.s] = args[0].arr[i].s, true
|
|
c.opaque(k.s)
|
|
}
|
|
case "has_feature", "has_features":
|
|
if len(args) == 0 || slices.ContainsFunc(args, func(v rval) bool { return v.k != vSym && v.k != vStr }) {
|
|
return fmt.Errorf("%s takes feature names", name)
|
|
}
|
|
for _, a := range args {
|
|
c.declared = append(c.declared, a.s)
|
|
}
|
|
case "has_command":
|
|
if len(args) != 2 || args[0].k != vSym && args[0].k != vStr || args[1].k != vStr {
|
|
return fmt.Errorf("has_command takes a name and a string")
|
|
}
|
|
c.commands[args[0].s], c.cmds[args[0].s] = args[1].s, true
|
|
c.opaque(args[0].s)
|
|
if p.is(tIdent, "do") || p.op("{") {
|
|
closeTok, err := p.blockOpen()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return p.body(closeTok, p.commandStmt)
|
|
}
|
|
case "mk_resource_methods", "initvars":
|
|
if len(args) != 0 {
|
|
return fmt.Errorf("%s takes no arguments", name)
|
|
}
|
|
if name == "initvars" {
|
|
c.inited, c.defaults, c.commands = true, nil, map[string]string{}
|
|
} else {
|
|
c.mkres = true
|
|
}
|
|
case "desc":
|
|
if len(args) != 1 || args[0].k != vStr {
|
|
return fmt.Errorf("desc takes one string")
|
|
}
|
|
c.doc = &args[0].s
|
|
case "text_line", "record_line":
|
|
if c.kind != kParsed {
|
|
return fmt.Errorf("%s outside a ParsedFile provider", name)
|
|
}
|
|
return p.parsedLine(c, name, args)
|
|
}
|
|
if p.is(tIdent, "do") || p.op("{") {
|
|
return fmt.Errorf("%s with a block", name)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// confineTest checks the require "puppet/confine/<name>" Puppet::Confine.test makes for a confine key: it must load
|
|
// one of openvox's confines or, finding no file, fall back to a fact comparison.
|
|
func (p *parser) confineTest(name string) error {
|
|
if name == "for_binary" || coreConfines[name] {
|
|
return nil
|
|
}
|
|
lib := "puppet/confine/" + name
|
|
if !confineName.MatchString(name) || strings.Contains(name, "..") || coreLib(lib) {
|
|
return fmt.Errorf("unsupported confine %q", name)
|
|
}
|
|
if p.w.resolve == nil {
|
|
return fmt.Errorf("confine %q: module sources are not available", name)
|
|
}
|
|
srcs, err := p.w.resolve(lib+".rb", "")
|
|
if err == nil && len(srcs) > 0 {
|
|
err = fmt.Errorf("confine %q loads lib/%s.rb", name, lib)
|
|
}
|
|
return err
|
|
}
|
|
|
|
var (
|
|
coreConfines = set("any boolean exists false feature true variable")
|
|
confineName = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9_.]*$`)
|
|
)
|
|
|
|
// commandStmt allows Puppet::Provider::CommandDefiner's literal calls inside a has_command block.
|
|
func (p *parser) commandStmt() (bool, error) {
|
|
switch {
|
|
case p.is(tIdent, "is_optional"):
|
|
p.take()
|
|
return true, nil
|
|
case p.is(tIdent, "environment"):
|
|
p.take()
|
|
args, err := p.args()
|
|
if err == nil && (len(args) != 1 || args[0].k != vHash) {
|
|
err = fmt.Errorf("environment takes one literal hash")
|
|
}
|
|
return true, err
|
|
}
|
|
return true, fmt.Errorf("unsupported %s in has_command", p.construct())
|
|
}
|
|
|
|
// recordOpts are Puppet::Util::FileParsing::FileRecord#initialize's keywords; any other raises ArgumentError.
|
|
var recordOpts = set("absent block_eval fields joiner match optional post_parse pre_gen rollup rts separator to_line")
|
|
|
|
// parsedLine checks text_line/record_line as Puppet::Util::FileParsing does: a unique name, FileRecord keywords with
|
|
// :match for text lines and :fields for records, symbol lists for fields and optional, and procs for the hooks.
|
|
func (p *parser) parsedLine(c *classCtx, kind string, args []rval) error {
|
|
if len(args) != 2 || args[0].k != vSym && args[0].k != vStr || args[1].k != vHash || symHash(args[1], kind) != nil {
|
|
return fmt.Errorf("%s takes a name and literal options", kind)
|
|
}
|
|
if c.lines == nil {
|
|
c.lines = map[string]bool{}
|
|
}
|
|
if c.lines[args[0].s] {
|
|
return fmt.Errorf("line type %s is already defined", args[0].s)
|
|
}
|
|
c.lines[args[0].s] = true
|
|
opts := args[1]
|
|
need := map[string]string{"text_line": "match", "record_line": "fields"}[kind]
|
|
if _, ok := opts.get(need); !ok {
|
|
return fmt.Errorf("%s needs :%s", kind, need)
|
|
}
|
|
names := func(v rval) bool {
|
|
return v.k == vArray && !slices.ContainsFunc(v.arr, func(f rval) bool {
|
|
return f.k != vStr && f.k != vSym || f.s == "record_type" || f.s == "target" || f.s == "on_disk"
|
|
})
|
|
}
|
|
for i, k := range opts.keys {
|
|
v := opts.arr[i]
|
|
unset := v.k == vNil || v.k == vFalse
|
|
switch {
|
|
case !recordOpts[k.s]:
|
|
return fmt.Errorf("unknown %s keyword %s", kind, k.s)
|
|
case (k.s == "fields" || k.s == "optional") && !unset && !names(v):
|
|
return fmt.Errorf("%s %s must be a literal list of names", kind, k.s)
|
|
case (k.s == "post_parse" || k.s == "pre_gen" || k.s == "to_line") && !unset && v.k != vBlock:
|
|
return fmt.Errorf("%s %s must be a proc", kind, k.s)
|
|
}
|
|
}
|
|
if !p.is(tIdent, "do") && !p.op("{") {
|
|
return nil
|
|
}
|
|
be, _ := opts.get("block_eval")
|
|
switch {
|
|
case be.k == vSym && be.s == "instance":
|
|
case be.k == vSym || be.k == vStr || be.k == vNil || be.k == vFalse:
|
|
return p.skipBlock()
|
|
default:
|
|
return fmt.Errorf("unsupported block_eval %s", be.kindName())
|
|
}
|
|
closeTok, err := p.blockOpen()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
rc := newClass(kClass, false)
|
|
return p.body(closeTok, func() (bool, error) {
|
|
if !p.is(tIdent, "def") {
|
|
return true, fmt.Errorf("unsupported %s in record_line", p.construct())
|
|
}
|
|
return true, p.defMethod(rc, false)
|
|
})
|
|
}
|
|
|
|
// unshift allows $LOAD_PATH.unshift of the file's own lib dir when no file there shadows a library ahead of module
|
|
// lib dirs, so moving it first cannot change what any require loads.
|
|
func (p *parser) unshift() error {
|
|
p.i += 3
|
|
if err := p.expect("("); err != nil {
|
|
return err
|
|
}
|
|
dir, err := p.pathExpr(0)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := p.expect(")"); err != nil {
|
|
return err
|
|
}
|
|
if path.Clean(dir) != "/lib" {
|
|
return fmt.Errorf("$LOAD_PATH.unshift of %s", dir)
|
|
}
|
|
if p.w.shadows == nil {
|
|
return fmt.Errorf("$LOAD_PATH.unshift: module sources are not available")
|
|
}
|
|
shadow, err := p.w.shadows(p.mod)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if shadow != "" {
|
|
return fmt.Errorf("$LOAD_PATH.unshift puts lib/%s ahead of the library it shadows", shadow)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// requireTarget reads a require argument: a string for $LOAD_PATH, or a path built from __FILE__/__dir__ with
|
|
// File.join, File.expand_path and File.dirname, which loads that file of the requiring module by absolute path.
|
|
func (p *parser) requireTarget() (lib string, abs bool, err error) {
|
|
if p.cur().kind == tStr && p.cur().flags != "`" && !p.op("(") {
|
|
if t := p.at(1); t.kind == tNL || t.kind == tEOF || t.text == ";" {
|
|
s, err := p.interp(p.take().parts)
|
|
return s, false, err
|
|
}
|
|
}
|
|
paren := p.op("(") && !p.cur().space
|
|
if paren {
|
|
p.take()
|
|
}
|
|
v, err := p.pathExpr(0)
|
|
if err != nil {
|
|
return "", false, err
|
|
}
|
|
if paren {
|
|
if err := p.expect(")"); err != nil {
|
|
return "", false, err
|
|
}
|
|
}
|
|
if !strings.HasPrefix(v, "/") {
|
|
return v, false, nil
|
|
}
|
|
rel, ok := strings.CutPrefix(path.Clean(v), "/lib/")
|
|
if !ok {
|
|
return "", false, fmt.Errorf("require of %s outside the module's lib", v)
|
|
}
|
|
return rel, true, nil
|
|
}
|
|
|
|
// pathExpr evaluates a path expression with the requiring file at /lib/<dir>/<file>.
|
|
func (p *parser) pathExpr(depth int) (string, error) {
|
|
if depth > maxDepth {
|
|
return "", errLimit
|
|
}
|
|
t := p.cur()
|
|
switch {
|
|
case t.kind == tStr && t.flags != "`":
|
|
p.take()
|
|
return p.interp(t.parts)
|
|
case t.kind == tIdent && t.text == "__FILE__":
|
|
p.take()
|
|
return "/lib/" + p.dir + "/" + p.file, nil
|
|
case t.kind == tIdent && t.text == "__dir__" && (p.at(1).text != "(" || p.at(1).space):
|
|
p.take()
|
|
return "/lib/" + p.dir, nil
|
|
case t.kind == tConst && t.text == "File" && p.at(1).text == "." && p.at(3).text == "(":
|
|
fn := p.at(2).text
|
|
p.i += 4
|
|
var args []string
|
|
for !p.op(")") {
|
|
p.skipNL()
|
|
a, err := p.joinArg(fn, depth+1)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
args = append(args, a)
|
|
p.skipNL()
|
|
if !p.op(",") {
|
|
break
|
|
}
|
|
p.take()
|
|
}
|
|
p.skipNL()
|
|
if err := p.expect(")"); err != nil {
|
|
return "", err
|
|
}
|
|
switch {
|
|
case fn == "join":
|
|
return fileJoin(args), nil
|
|
case fn == "dirname" && len(args) == 1:
|
|
return path.Dir(args[0]), nil
|
|
case fn == "expand_path" && (len(args) == 1 || len(args) == 2):
|
|
base := args[len(args)-1]
|
|
if len(args) == 2 && !strings.HasPrefix(args[0], "/") {
|
|
return path.Clean(base + "/" + args[0]), nil
|
|
}
|
|
if strings.HasPrefix(args[0], "/") {
|
|
return path.Clean(args[0]), nil
|
|
}
|
|
}
|
|
return "", fmt.Errorf("unsupported File.%s", fn)
|
|
}
|
|
return "", fmt.Errorf("unsupported require path %s", describe(t))
|
|
}
|
|
|
|
// joinArg reads one File.<fn> argument; File.join takes %w and literal arrays, which it joins recursively.
|
|
func (p *parser) joinArg(fn string, depth int) (string, error) {
|
|
t := p.cur()
|
|
switch {
|
|
case fn == "join" && t.kind == tWords && t.flags == "w" && !slices.ContainsFunc(t.words, func(w string) bool { return strings.Contains(w, "\\") }):
|
|
p.take()
|
|
return fileJoin(t.words), nil
|
|
case fn == "join" && t.kind == tOp && t.text == "[":
|
|
if depth > maxDepth {
|
|
return "", errLimit
|
|
}
|
|
p.take()
|
|
var elems []string
|
|
for p.skipNL(); !p.op("]"); p.skipNL() {
|
|
e, err := p.joinArg(fn, depth+1)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
elems = append(elems, e)
|
|
if p.skipNL(); !p.op(",") {
|
|
break
|
|
}
|
|
p.take()
|
|
}
|
|
return fileJoin(elems), p.expect("]")
|
|
}
|
|
return p.pathExpr(depth)
|
|
}
|
|
|
|
// fileJoin is Ruby's File.join: one separator between parts, keeping a part's leading one and the doubled ones within.
|
|
func fileJoin(parts []string) string {
|
|
var b []byte
|
|
for i, s := range parts {
|
|
if n := len(bytes.TrimRight(b, "/")); i > 0 && strings.HasPrefix(s, "/") {
|
|
b = b[:n]
|
|
} else if i > 0 && n == len(b) {
|
|
b = append(b, '/')
|
|
}
|
|
b = append(b, s...)
|
|
}
|
|
return string(b)
|
|
}
|
|
|
|
// provDecl is a provide call: its name, its parent by provider name or class, and its class body.
|
|
type provDecl struct {
|
|
name, parent, sup string
|
|
c *classCtx
|
|
}
|
|
|
|
// providerFile analyses a provider file the way loading it inside Puppet::Type.newtype would run it, returning the
|
|
// provider its one provide call declares, or no name for a file without one.
|
|
func providerFile(f libFile, typ string, rsapi bool, w *world) (pr *provDecl, err error) {
|
|
defer guard(&err)
|
|
toks, err := lex(f.src)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var name, parent, sup string
|
|
var c *classCtx
|
|
p := &parser{toks: toks, consts: map[string]rval{}, used: map[int]bool{}, w: w, defined: w.defined, mod: f.mod, dir: path.Dir(f.rel), file: path.Base(f.rel), src: f.src}
|
|
w.loaded[f.mod+"\x00"+f.rel] = true
|
|
provide := func() (bool, error) {
|
|
if !p.is(tConst, "Puppet") || p.at(1).text != "::" || p.at(2).text != "Type" || p.at(3).text != "." || p.at(4).text != "type" {
|
|
return false, nil
|
|
}
|
|
if name != "" || rsapi {
|
|
return true, fmt.Errorf("unsupported second provide call")
|
|
}
|
|
p.i += 5
|
|
args, err := p.args()
|
|
if err != nil {
|
|
return true, err
|
|
}
|
|
if len(args) != 1 || args[0].k != vSym && args[0].k != vStr || args[0].s != typ {
|
|
return true, fmt.Errorf("provide must target Puppet::Type.type(:%s)", typ)
|
|
}
|
|
if !p.op(".") || p.at(1).text != "provide" {
|
|
return true, fmt.Errorf("unsupported %s", p.construct())
|
|
}
|
|
p.i += 2
|
|
if args, err = p.args(); err != nil {
|
|
return true, err
|
|
}
|
|
if len(args) == 0 || len(args) > 2 || args[0].k != vSym && args[0].k != vStr || len(args) == 2 && args[1].k != vHash {
|
|
return true, fmt.Errorf("unsupported provide arguments")
|
|
}
|
|
name = args[0].s
|
|
if !rubyName.MatchString(name) {
|
|
return true, fmt.Errorf("unsupported provider name %q", name)
|
|
}
|
|
kind := byte(kProv)
|
|
c = newClass(kind, true)
|
|
c.parent, c.block = "Puppet::Provider", true
|
|
if w.typ != nil && w.typ.name == typ {
|
|
c.typ = w.typ
|
|
}
|
|
if len(args) == 2 {
|
|
if err := symHash(args[1], "provide "+name); err != nil {
|
|
return true, err
|
|
}
|
|
if v, ok := args[1].get("parent"); ok {
|
|
switch v.k {
|
|
case vNil, vFalse:
|
|
case vSym, vStr:
|
|
parent = v.s
|
|
c.parentUnknown = true
|
|
case vConst:
|
|
if kind = w.kind[v.s]; kind != kProv && kind != kParsed {
|
|
return true, fmt.Errorf("parent %s is not a provider class", v.s)
|
|
}
|
|
c.parent, sup = v.s, v.s
|
|
default:
|
|
return true, fmt.Errorf("unsupported provider parent %s", v.kindName())
|
|
}
|
|
}
|
|
}
|
|
closeTok, err := p.blockOpen()
|
|
if err != nil || closeTok == "" {
|
|
return true, err
|
|
}
|
|
c.kind = kind
|
|
return true, p.body(closeTok, p.classStmt("Puppet::Type::"+typ, c))
|
|
}
|
|
if err := p.body("", p.fileStmt(provide)); err != nil {
|
|
return nil, p.wrap(err)
|
|
}
|
|
return &provDecl{name: name, parent: parent, sup: sup, c: c}, nil
|
|
}
|
|
|
|
// envAssign evaluates ENV[name] = value for a literal name and a value built only from literals and ENV reads,
|
|
// which cannot raise: names are non-empty without '=' or NUL and values have no NUL.
|
|
func (p *parser) envAssign() error {
|
|
p.i += 2
|
|
k, err := p.expr()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if k.k != vStr || k.s == "" || strings.ContainsAny(k.s, "=\x00") {
|
|
return fmt.Errorf("unsupported ENV name")
|
|
}
|
|
if err := p.expect("]"); err != nil {
|
|
return err
|
|
}
|
|
if err := p.expect("="); err != nil {
|
|
return err
|
|
}
|
|
switch t := p.cur(); {
|
|
case t.kind == tStr && t.flags != "`":
|
|
p.take()
|
|
for _, pt := range t.parts {
|
|
if !pt.code && strings.Contains(pt.text, "\x00") {
|
|
return fmt.Errorf("ENV value with a NUL byte")
|
|
}
|
|
if pt.code {
|
|
toks, err := lex(pt.text)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
q := &parser{toks: toks, depth: p.depth}
|
|
if !q.envRead() || q.cur().kind != tEOF {
|
|
return fmt.Errorf("unsupported interpolation #{%s} in ENV value", pt.text)
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
case p.op("["):
|
|
p.take()
|
|
for {
|
|
p.skipNL()
|
|
if p.op("]") {
|
|
break
|
|
}
|
|
if !p.envRead() {
|
|
e, err := p.expr()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if e.k != vStr || strings.Contains(e.s, "\x00") {
|
|
return fmt.Errorf("unsupported ENV value element %s", e.kindName())
|
|
}
|
|
}
|
|
p.skipNL()
|
|
if !p.op(",") {
|
|
break
|
|
}
|
|
p.take()
|
|
}
|
|
p.skipNL()
|
|
if err := p.expect("]"); err != nil {
|
|
return err
|
|
}
|
|
if !p.op(".") || p.at(1).text != "join" || p.at(2).text != "(" || p.at(3).kind != tStr || p.at(4).text != ")" {
|
|
return fmt.Errorf("unsupported ENV value")
|
|
}
|
|
p.i += 5
|
|
return nil
|
|
}
|
|
return fmt.Errorf("unsupported ENV value")
|
|
}
|
|
|
|
// envRead consumes ENV.fetch('NAME', nil) or ENV['NAME'].
|
|
func (p *parser) envRead() bool {
|
|
if !p.is(tConst, "ENV") {
|
|
return false
|
|
}
|
|
str := func(t token) bool { return t.kind == tStr && len(t.parts) == 1 && !t.parts[0].code }
|
|
switch {
|
|
case p.at(1).text == "." && p.at(2).text == "fetch" && p.at(3).text == "(" && str(p.at(4)) && p.at(5).text == "," && p.at(6).text == "nil" && p.at(7).text == ")":
|
|
p.i += 8
|
|
case p.at(1).text == "[" && str(p.at(2)) && p.at(3).text == "]":
|
|
p.i += 4
|
|
default:
|
|
return false
|
|
}
|
|
return true
|
|
}
|