Simplified constant folding

This commit is contained in:
Eduard Urbach 2025-02-26 20:02:53 +01:00
parent ebe53b3b50
commit bbf2970c4e
Signed by: akyoto
GPG Key ID: C874F672B1AF20C0
5 changed files with 51 additions and 25 deletions

View File

@ -17,31 +17,11 @@ func (f *Function) Fold(expr *expression.Expression) error {
}
if expr.IsLeaf() {
if expr.Token.IsNumeric() {
value, err := f.ToNumber(expr.Token)
expr.Value = value
expr.IsFolded = true
return err
}
return nil
return f.FoldLeaf(expr)
}
if expr.Token.Kind == token.Period {
left := expr.Children[0]
leftText := left.Token.Text(f.File.Bytes)
right := expr.Children[1]
rightText := right.Token.Text(f.File.Bytes)
constant, isConst := f.All.Constants[f.Package+"."+leftText+"."+rightText]
if !isConst {
return nil
}
value, err := ToNumber(constant.Token, constant.File)
expr.Value = value
expr.IsFolded = true
return err
return f.FoldConstant(expr)
}
canFold := true

23
src/core/FoldConstant.go Normal file
View File

@ -0,0 +1,23 @@
package core
import (
"git.urbach.dev/cli/q/src/expression"
)
// FoldConstant tries to find a constant that can be folded.
func (f *Function) FoldConstant(expr *expression.Expression) error {
left := expr.Children[0]
right := expr.Children[1]
leftText := left.Token.Text(f.File.Bytes)
rightText := right.Token.Text(f.File.Bytes)
constant, exists := f.All.Constants[f.Package+"."+leftText+"."+rightText]
if !exists {
return nil
}
value, err := ToNumber(constant.Token, constant.File)
expr.Value = value
expr.IsFolded = true
return err
}

17
src/core/FoldLeaf.go Normal file
View File

@ -0,0 +1,17 @@
package core
import (
"git.urbach.dev/cli/q/src/expression"
)
// FoldLeaf tries to fold a leaf expression.
func (f *Function) FoldLeaf(expr *expression.Expression) error {
if !expr.Token.IsNumeric() {
return nil
}
value, err := f.ToNumber(expr.Token)
expr.Value = value
expr.IsFolded = true
return err
}

View File

@ -11,9 +11,8 @@ type Expression struct {
Parent *Expression
Children []*Expression
Token token.Token
Value int
Precedence int8
IsFolded bool
Foldable
}
// New creates a new expression.
@ -62,8 +61,8 @@ func (expr *Expression) Reset() {
}
expr.Token.Reset()
expr.Value = 0
expr.Precedence = 0
expr.Value = 0
expr.IsFolded = false
}

View File

@ -0,0 +1,7 @@
package expression
// Foldable has optional fields that are used for constant folding later.
type Foldable struct {
Value int
IsFolded bool
}