Simplified ast package

This commit is contained in:
Eduard Urbach 2025-02-20 14:12:25 +01:00
parent d26bf9d1a9
commit 35ee40988d
Signed by: eduard
GPG key ID: 49226B848C78F6C8
19 changed files with 151 additions and 168 deletions

View file

@ -0,0 +1,62 @@
package ast
import "git.akyoto.dev/cli/q/src/token"
// eachInstruction calls the function on each AST node.
func eachInstruction(tokens token.List, call func(token.List) error) error {
start := 0
groupLevel := 0
blockLevel := 0
for i, t := range tokens {
if start == i && t.Kind == token.NewLine {
start = i + 1
continue
}
switch t.Kind {
case token.NewLine:
if groupLevel > 0 || blockLevel > 0 {
continue
}
err := call(tokens[start:i])
if err != nil {
return err
}
start = i + 1
case token.GroupStart:
groupLevel++
case token.GroupEnd:
groupLevel--
case token.BlockStart:
blockLevel++
case token.BlockEnd:
blockLevel--
if groupLevel > 0 || blockLevel > 0 {
continue
}
err := call(tokens[start : i+1])
if err != nil {
return err
}
start = i + 1
}
}
if start != len(tokens) {
return call(tokens[start:])
}
return nil
}