| |
| |
| |
|
|
| package unify |
|
|
| import ( |
| "errors" |
| "fmt" |
| "io" |
| "io/fs" |
| "os" |
| "path/filepath" |
| "regexp" |
| "strings" |
|
|
| "gopkg.in/yaml.v3" |
| ) |
|
|
| |
| |
| type ReadOpts struct { |
| |
| |
| FS fs.FS |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| func Read(r io.Reader, path string, opts ReadOpts) (Closure, error) { |
| dec := yamlDecoder{opts: opts, path: path, env: topEnv} |
| v, err := dec.read(r) |
| if err != nil { |
| return Closure{}, err |
| } |
| return dec.close(v), nil |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| func ReadFile(path string, opts ReadOpts) (Closure, error) { |
| f, err := os.Open(path) |
| if err != nil { |
| return Closure{}, err |
| } |
| defer f.Close() |
|
|
| if opts.FS == nil { |
| opts.FS = os.DirFS(filepath.Dir(path)) |
| } |
|
|
| return Read(f, path, opts) |
| } |
|
|
| |
| |
| |
| |
| func (c *Closure) UnmarshalYAML(node *yaml.Node) error { |
| dec := yamlDecoder{path: "<yaml.Node>", env: topEnv} |
| v, err := dec.root(node) |
| if err != nil { |
| return err |
| } |
| *c = dec.close(v) |
| return nil |
| } |
|
|
| type yamlDecoder struct { |
| opts ReadOpts |
| path string |
|
|
| vars map[string]*ident |
| nSums int |
|
|
| env envSet |
| } |
|
|
| func (dec *yamlDecoder) read(r io.Reader) (*Value, error) { |
| n, err := readOneNode(r) |
| if err != nil { |
| return nil, fmt.Errorf("%s: %w", dec.path, err) |
| } |
|
|
| |
| v, err := dec.root(n) |
| if err != nil { |
| return nil, fmt.Errorf("%s: %w", dec.path, err) |
| } |
|
|
| return v, nil |
| } |
|
|
| |
| |
| func readOneNode(r io.Reader) (*yaml.Node, error) { |
| yd := yaml.NewDecoder(r) |
|
|
| |
| var node yaml.Node |
| if err := yd.Decode(&node); err != nil { |
| return nil, err |
| } |
| np := &node |
| if np.Kind == yaml.DocumentNode { |
| np = node.Content[0] |
| } |
|
|
| |
| if err := yd.Decode(nil); err == nil { |
| return nil, fmt.Errorf("must not contain multiple documents") |
| } else if err != io.EOF { |
| return nil, err |
| } |
|
|
| return np, nil |
| } |
|
|
| |
| func (dec *yamlDecoder) root(node *yaml.Node) (*Value, error) { |
| |
| |
| oldVars, oldNSums := dec.vars, dec.nSums |
| defer func() { |
| dec.vars, dec.nSums = oldVars, oldNSums |
| }() |
| dec.vars = make(map[string]*ident, 0) |
| dec.nSums = 0 |
|
|
| return dec.value(node) |
| } |
|
|
| |
| func (dec *yamlDecoder) close(v *Value) Closure { |
| return Closure{v, dec.env} |
| } |
|
|
| func (dec *yamlDecoder) value(node *yaml.Node) (vOut *Value, errOut error) { |
| pos := &Pos{Path: dec.path, Line: node.Line} |
|
|
| |
| if node.Kind == yaml.AliasNode { |
| node = node.Alias |
| } |
|
|
| mk := func(d Domain) (*Value, error) { |
| v := &Value{Domain: d, pos: pos} |
| return v, nil |
| } |
| mk2 := func(d Domain, err error) (*Value, error) { |
| if err != nil { |
| return nil, err |
| } |
| return mk(d) |
| } |
|
|
| |
| is := func(kind yaml.Kind, tag string) bool { |
| return node.Kind == kind && node.LongTag() == tag |
| } |
| isExact := func() bool { |
| if node.Kind != yaml.ScalarNode { |
| return false |
| } |
| |
| switch node.LongTag() { |
| case "!string", "tag:yaml.org,2002:int", "tag:yaml.org,2002:float", "tag:yaml.org,2002:bool", "tag:yaml.org,2002:binary": |
| return true |
| } |
| return false |
| } |
|
|
| |
| |
| |
| strVal := "" |
| isStr := is(yaml.ScalarNode, "tag:yaml.org,2002:str") |
| if isStr { |
| strVal = node.Value |
| } |
|
|
| switch { |
| case is(yaml.ScalarNode, "!var"): |
| strVal = "$" + node.Value |
| fallthrough |
| case strings.HasPrefix(strVal, "$"): |
| id, ok := dec.vars[strVal] |
| if !ok { |
| |
| |
| |
| name, _, _ := strings.Cut(strVal, "#") |
| id = &ident{name: name} |
| dec.vars[strVal] = id |
| dec.env = dec.env.bind(id, topValue) |
| } |
| return mk(Var{id: id}) |
|
|
| case strVal == "_" || is(yaml.ScalarNode, "!top"): |
| return mk(Top{}) |
|
|
| case strVal == "_|_" || is(yaml.ScalarNode, "!bottom"): |
| return nil, errors.New("found bottom") |
|
|
| case isExact(): |
| val := node.Value |
| return mk(NewStringExact(val)) |
|
|
| case isStr || is(yaml.ScalarNode, "!regex"): |
| |
| |
| val := node.Value |
| return mk2(NewStringRegex(val)) |
|
|
| case is(yaml.SequenceNode, "!regex"): |
| var vals []string |
| if err := node.Decode(&vals); err != nil { |
| return nil, err |
| } |
| return mk2(NewStringRegex(vals...)) |
|
|
| case is(yaml.MappingNode, "tag:yaml.org,2002:map"): |
| var db DefBuilder |
| for i := 0; i < len(node.Content); i += 2 { |
| key := node.Content[i] |
| if key.Kind != yaml.ScalarNode { |
| return nil, fmt.Errorf("non-scalar key %q", key.Value) |
| } |
| val, err := dec.value(node.Content[i+1]) |
| if err != nil { |
| return nil, err |
| } |
| db.Add(key.Value, val) |
| } |
| return mk(db.Build()) |
|
|
| case is(yaml.SequenceNode, "tag:yaml.org,2002:seq"): |
| elts := node.Content |
| vs := make([]*Value, 0, len(elts)) |
| for _, elt := range elts { |
| v, err := dec.value(elt) |
| if err != nil { |
| return nil, err |
| } |
| vs = append(vs, v) |
| } |
| return mk(NewTuple(vs...)) |
|
|
| case is(yaml.SequenceNode, "!repeat") || is(yaml.SequenceNode, "!repeat-unify"): |
| |
| |
| |
| if node.LongTag() == "!repeat" && len(node.Content) != 1 { |
| return nil, fmt.Errorf("!repeat must have exactly one child") |
| } |
|
|
| |
| |
| |
| var gen []func(e envSet) (*Value, envSet) |
| origEnv := dec.env |
| elts := node.Content |
| for i, elt := range elts { |
| _, err := dec.value(elt) |
| if err != nil { |
| return nil, err |
| } |
| |
| |
| |
| |
| |
| |
| dec.env = origEnv |
| |
| gen = append(gen, func(e envSet) (*Value, envSet) { |
| dec.env = e |
| |
| |
| |
| |
| v, err := dec.value(elts[i]) |
| if err != nil { |
| |
| panic("decoding repeat element failed") |
| } |
| return v, dec.env |
| }) |
| } |
| return mk(NewRepeat(gen...)) |
|
|
| case is(yaml.SequenceNode, "!sum"): |
| vs := make([]*Value, 0, len(node.Content)) |
| for _, elt := range node.Content { |
| v, err := dec.value(elt) |
| if err != nil { |
| return nil, err |
| } |
| vs = append(vs, v) |
| } |
| if len(vs) == 1 { |
| return vs[0], nil |
| } |
|
|
| |
| |
| id := &ident{name: fmt.Sprintf("sum%d", dec.nSums)} |
| dec.nSums++ |
| dec.env = dec.env.bind(id, vs...) |
| return mk(Var{id: id}) |
|
|
| case is(yaml.ScalarNode, "!import"): |
| if dec.opts.FS == nil { |
| return nil, fmt.Errorf("!import not allowed (ReadOpts.FS not set)") |
| } |
| pat := node.Value |
|
|
| if !fs.ValidPath(pat) { |
| |
| |
| return nil, fmt.Errorf("!import path must not contain '.' or '..'") |
| } |
|
|
| ms, err := fs.Glob(dec.opts.FS, pat) |
| if err != nil { |
| return nil, fmt.Errorf("resolving !import: %w", err) |
| } |
| if len(ms) == 0 { |
| return nil, fmt.Errorf("!import did not match any files") |
| } |
|
|
| |
| vs := make([]*Value, 0, len(ms)) |
| for _, m := range ms { |
| v, err := dec.import1(m) |
| if err != nil { |
| return nil, err |
| } |
| vs = append(vs, v) |
| } |
|
|
| |
| if len(vs) == 1 { |
| return vs[0], nil |
| } |
| id := &ident{name: "import"} |
| dec.env = dec.env.bind(id, vs...) |
| return mk(Var{id: id}) |
| } |
|
|
| return nil, fmt.Errorf("unknown node kind %d %v", node.Kind, node.Tag) |
| } |
|
|
| func (dec *yamlDecoder) import1(path string) (*Value, error) { |
| |
| f, err := dec.opts.FS.Open(path) |
| if err != nil { |
| return nil, fmt.Errorf("!import failed: %w", err) |
| } |
| defer f.Close() |
|
|
| |
| oldFS, oldPath := dec.opts.FS, dec.path |
| defer func() { |
| dec.opts.FS, dec.path = oldFS, oldPath |
| }() |
|
|
| |
| newPath := filepath.Join(filepath.Dir(dec.path), path) |
| subFS, err := fs.Sub(dec.opts.FS, filepath.Dir(path)) |
| if err != nil { |
| return nil, err |
| } |
| dec.opts.FS, dec.path = subFS, newPath |
|
|
| |
| return dec.read(f) |
| } |
|
|
| type yamlEncoder struct { |
| idp identPrinter |
| e envSet |
| } |
|
|
| |
|
|
| func (c Closure) MarshalYAML() (any, error) { |
| |
| enc := &yamlEncoder{} |
| return enc.closure(c), nil |
| } |
|
|
| func (c Closure) String() string { |
| b, err := yaml.Marshal(c) |
| if err != nil { |
| return fmt.Sprintf("marshal failed: %s", err) |
| } |
| return string(b) |
| } |
|
|
| func (v *Value) MarshalYAML() (any, error) { |
| enc := &yamlEncoder{e: topEnv} |
| return enc.value(v), nil |
| } |
|
|
| func (v *Value) String() string { |
| b, err := yaml.Marshal(v) |
| if err != nil { |
| return fmt.Sprintf("marshal failed: %s", err) |
| } |
| return string(b) |
| } |
|
|
| func (enc *yamlEncoder) closure(c Closure) *yaml.Node { |
| enc.e = c.env |
| var n yaml.Node |
| n.Kind = yaml.MappingNode |
| n.Tag = "!closure" |
| n.Content = make([]*yaml.Node, 4) |
| n.Content[0] = new(yaml.Node) |
| n.Content[0].SetString("env") |
| n.Content[2] = new(yaml.Node) |
| n.Content[2].SetString("in") |
| n.Content[3] = enc.value(c.val) |
| |
| |
| n.Content[1] = enc.env(enc.e) |
| enc.e = envSet{} |
| return &n |
| } |
|
|
| func (enc *yamlEncoder) env(e envSet) *yaml.Node { |
| var encode func(e *envExpr) *yaml.Node |
| encode = func(e *envExpr) *yaml.Node { |
| var n yaml.Node |
| switch e.kind { |
| default: |
| panic("bad kind") |
| case envZero: |
| n.SetString("0") |
| case envUnit: |
| n.SetString("1") |
| case envBinding: |
| var id yaml.Node |
| id.SetString(enc.idp.unique(e.id)) |
| n.Kind = yaml.MappingNode |
| n.Content = []*yaml.Node{&id, enc.value(e.val)} |
| case envProduct, envSum: |
| n.Kind = yaml.SequenceNode |
| if e.kind == envProduct { |
| n.Tag = "!product" |
| } else { |
| n.Tag = "!sum" |
| } |
| for _, e2 := range e.operands { |
| n.Content = append(n.Content, encode(e2)) |
| } |
| } |
| return &n |
| } |
| return encode(e.root) |
| } |
|
|
| var yamlIntRe = regexp.MustCompile(`^-?[0-9]+$`) |
|
|
| func (enc *yamlEncoder) value(v *Value) *yaml.Node { |
| var n yaml.Node |
| switch d := v.Domain.(type) { |
| case nil: |
| |
| |
| |
| |
| |
| n.SetString("_|_") |
| return &n |
|
|
| case Top: |
| n.SetString("_") |
| return &n |
|
|
| case Def: |
| n.Kind = yaml.MappingNode |
| for k, elt := range d.All() { |
| var kn yaml.Node |
| kn.SetString(k) |
| n.Content = append(n.Content, &kn, enc.value(elt)) |
| } |
| n.HeadComment = v.PosString() |
| return &n |
|
|
| case Tuple: |
| n.Kind = yaml.SequenceNode |
| if d.repeat == nil { |
| for _, elt := range d.vs { |
| n.Content = append(n.Content, enc.value(elt)) |
| } |
| } else { |
| if len(d.repeat) == 1 { |
| n.Tag = "!repeat" |
| } else { |
| n.Tag = "!repeat-unify" |
| } |
| |
| for _, gen := range d.repeat { |
| v, e := gen(enc.e) |
| enc.e = e |
| n.Content = append(n.Content, enc.value(v)) |
| } |
| } |
| return &n |
|
|
| case String: |
| switch d.kind { |
| case stringExact: |
| n.SetString(d.exact) |
| switch { |
| |
| case yamlIntRe.MatchString(d.exact): |
| n.Tag = "tag:yaml.org,2002:int" |
|
|
| |
| case d.exact == "false" || d.exact == "true": |
| n.Tag = "tag:yaml.org,2002:bool" |
|
|
| |
| |
| |
| |
| case d.exact != regexp.QuoteMeta(d.exact): |
| n.Tag = "!string" |
| } |
| return &n |
| case stringRegex: |
| o := make([]string, 0, 1) |
| for _, re := range d.re { |
| s := re.String() |
| s = strings.TrimSuffix(strings.TrimPrefix(s, `\A(?:`), `)\z`) |
| o = append(o, s) |
| } |
| if len(o) == 1 { |
| n.SetString(o[0]) |
| return &n |
| } |
| n.Encode(o) |
| n.Tag = "!regex" |
| return &n |
| } |
| panic("bad String kind") |
|
|
| case Var: |
| |
| |
| |
| if false { |
| var vs []*Value |
| if len(vs) == 1 { |
| return enc.value(vs[0]) |
| } |
| n.Kind = yaml.SequenceNode |
| n.Tag = "!sum" |
| for _, elt := range vs { |
| n.Content = append(n.Content, enc.value(elt)) |
| } |
| return &n |
| } |
| n.SetString(enc.idp.unique(d.id)) |
| if !strings.HasPrefix(d.id.name, "$") { |
| n.Tag = "!var" |
| } |
| return &n |
| } |
| panic(fmt.Sprintf("unknown domain type %T", v.Domain)) |
| } |
|
|