salix/macro_tag.go

61 lines
1.4 KiB
Go
Raw Normal View History

2023-10-31 03:07:57 +00:00
package salix
2023-12-18 00:55:13 +00:00
import "go.elara.ws/salix/ast"
2023-10-31 03:07:57 +00:00
// macroTag represents an #macro tag within a Salix template
type macroTag struct{}
func (mt macroTag) Run(tc *TagContext, block, args []ast.Node) error {
2023-10-31 20:45:00 +00:00
if len(args) < 1 {
2023-12-18 00:55:13 +00:00
return tc.PosError(tc.Tag, "expected at least one argument, got %d", len(args))
2023-10-31 03:07:57 +00:00
}
nameVal, err := tc.GetValue(args[0], nil)
if err != nil {
return err
}
name, ok := nameVal.(string)
if !ok {
2023-12-18 00:55:13 +00:00
return tc.PosError(args[0], "invalid first argument type: %T (expected string)", nameVal)
2023-10-31 03:07:57 +00:00
}
ignoreMissing := false
if name[0] == '?' {
name = name[1:]
ignoreMissing = true
}
2023-10-31 03:07:57 +00:00
if len(block) == 0 {
2023-10-31 20:45:00 +00:00
local := map[string]any{}
// Use the variable assignments after the first argument
// to set the local variables of the execution
for _, arg := range args[1:] {
if a, ok := arg.(ast.Assignment); ok {
val, err := tc.GetValue(a.Value, local)
if err != nil {
return err
}
local[a.Name.Value] = val
} else {
// If the argument isn't an assigment, return invalid args
2023-12-18 00:55:13 +00:00
return tc.PosError(arg, "%s: invalid argument type: %T (expected ast.Assignment)", tc.NodeToString(arg), arg)
2023-10-31 20:45:00 +00:00
}
}
2023-10-31 04:06:17 +00:00
macro, ok := tc.t.macros[name]
2023-10-31 03:07:57 +00:00
if !ok {
if ignoreMissing {
return nil
}
2023-12-18 00:55:13 +00:00
return tc.PosError(tc.Tag, "no such macro: %q", name)
2023-10-31 03:07:57 +00:00
}
2023-10-31 20:45:00 +00:00
return tc.Execute(macro, local)
2023-10-31 03:07:57 +00:00
} else {
2023-10-31 04:06:17 +00:00
tc.t.macros[name] = block
2023-10-31 03:07:57 +00:00
}
return nil
}