Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: optimize ast with constant folding #76

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

dugenkui03
Copy link
Contributor

常量折叠优化 提议

对表达式编译生成的 ast 中的常量进行预计算优化、以提高表达式执行性能

实现思路

  1. 表达式结点添加 Optimize() (bool, ExprNode) 判断当前结点是否可以常量折叠优化、以及优化后的结点
type ExprNode interface {
        ......
	Optimize() (bool, ExprNode)
}
  1. 判断叶子结点是否可以优化
    比如数字结点总是可以优化
func (de *digitalExprNode) Optimize() (bool, ExprNode) {
	return true, de
}
  1. 非叶子结点根据子节点判断当前阶段是否可以优化
    比如乘法叶子结点都是可折叠的结点,则乘法结点也可以优化
func (ae *multiplicationExprNode) Optimize() (bool, ExprNode) {
	lsucc, newLeft := ae.leftOperand.Optimize()
	if lsucc {
		ae.leftOperand = newLeft
	}

	rSucc, newRight := ae.rightOperand.Optimize()
	if rSucc {
		ae.rightOperand = newRight
	}

	if lsucc && rSucc {
		v1, _ := toFloat64(ae.rightOperand.Run(context.Background(), "", nil), true)
		if v1 == 0 {
			return true, &digitalExprNode{val: math.NaN()}
		}
		v0, _ := toFloat64(ae.leftOperand.Run(context.Background(), "", nil), true)
		return true, &digitalExprNode{val: v0 * v1}
	}

	return false, ae
}

@dugenkui03 dugenkui03 changed the title optimize ast with constant folding WIP: optimize ast with constant folding Nov 30, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant