Moved register state to scopes

This commit is contained in:
2024-07-16 15:30:28 +02:00
parent d1ccd60139
commit d6d018c5c5
22 changed files with 230 additions and 129 deletions

View File

@ -32,6 +32,21 @@ func (expr *Expression) AddChild(child *Expression) {
child.Parent = expr
}
// Count counts how often the given token appears in the expression.
func (expr *Expression) Count(kind token.Kind, name string) int {
count := 0
expr.EachLeaf(func(leaf *Expression) error {
if leaf.Token.Kind == kind && leaf.Token.Text() == name {
count++
}
return nil
})
return count
}
// Reset resets all values to the default.
func (expr *Expression) Reset() {
for _, child := range expr.Children {

View File

@ -9,7 +9,7 @@ import (
"git.akyoto.dev/go/assert"
)
func TestExpressionParse(t *testing.T) {
func TestParse(t *testing.T) {
tests := []struct {
Name string
Expression string
@ -96,6 +96,17 @@ func TestExpressionParse(t *testing.T) {
}
}
func TestCount(t *testing.T) {
src := []byte("(a+b-c*d)+(a*b-c+d)")
tokens := token.Tokenize(src)
expr := expression.Parse(tokens)
assert.Equal(t, expr.Count(token.Identifier, "a"), 2)
assert.Equal(t, expr.Count(token.Identifier, "b"), 2)
assert.Equal(t, expr.Count(token.Identifier, "c"), 2)
assert.Equal(t, expr.Count(token.Identifier, "d"), 2)
assert.Equal(t, expr.Count(token.Identifier, "e"), 0)
}
func TestEachLeaf(t *testing.T) {
src := []byte("(1+2-3*4)+(5*6-7+8)")
tokens := token.Tokenize(src)