Implemented simple expressions

This commit is contained in:
2024-06-25 20:50:06 +02:00
parent 2569c1bf63
commit e6462266ef
12 changed files with 232 additions and 52 deletions

View File

@ -120,27 +120,61 @@ func (f *Function) CompileInstruction(line token.List) error {
return errors.New(&errors.InvalidInstruction{Instruction: expr.Token.Text()}, f.File, expr.Token.Position)
}
// isAssignment returns true if the expression is an assignment.
func isAssignment(expr *expression.Expression) bool {
return expr.Token.Kind == token.Operator && expr.Token.Bytes[len(expr.Token.Bytes)-1] == '='
}
// isFunctionCall returns true if the expression is a function call.
func isFunctionCall(expr *expression.Expression) bool {
return expr.Token.Kind == token.Operator && expr.Token.Text() == "λ"
}
// isVariableDefinition returns true if the expression is a variable definition.
func isVariableDefinition(expr *expression.Expression) bool {
return expr.Token.Kind == token.Operator && expr.Token.Text() == ":="
}
// ExpressionToRegister moves the result of an expression into the given register.
func (f *Function) ExpressionToRegister(root *expression.Expression, register cpu.Register) error {
if root.IsLeaf() {
return f.TokenToRegister(root.Token, register)
}
left := root.Children[0]
right := root.Children[1]
f.ExpressionToRegister(left, register)
if right.IsLeaf() {
value := right.Token.Text()
n, err := strconv.Atoi(value)
if err != nil {
return err
}
switch root.Token.Text() {
case "+":
f.Assembler.RegisterNumber(asm.ADD, register, n)
case "-":
f.Assembler.RegisterNumber(asm.SUB, register, n)
case "*":
f.Assembler.RegisterNumber(asm.MUL, register, n)
case "/":
f.Assembler.RegisterNumber(asm.DIV, register, n)
}
return nil
} else {
temporary, _ := f.CPU.FindFree()
f.CPU.Use(temporary)
f.ExpressionToRegister(right, temporary)
f.CPU.Free(temporary)
switch root.Token.Text() {
case "+":
f.Assembler.RegisterRegister(asm.ADD, register, temporary)
case "-":
f.Assembler.RegisterRegister(asm.SUB, register, temporary)
case "*":
f.Assembler.RegisterRegister(asm.MUL, register, temporary)
case "/":
f.Assembler.RegisterRegister(asm.DIV, register, temporary)
}
}
return errors.New(errors.NotImplemented, f.File, root.Token.Position)
}
@ -207,3 +241,18 @@ func (f *Function) identifierExists(name string) bool {
_, exists := f.Variables[name]
return exists
}
// isAssignment returns true if the expression is an assignment.
func isAssignment(expr *expression.Expression) bool {
return expr.Token.Kind == token.Operator && expr.Token.Bytes[len(expr.Token.Bytes)-1] == '='
}
// isFunctionCall returns true if the expression is a function call.
func isFunctionCall(expr *expression.Expression) bool {
return expr.Token.Kind == token.Operator && expr.Token.Text() == "λ"
}
// isVariableDefinition returns true if the expression is a variable definition.
func isVariableDefinition(expr *expression.Expression) bool {
return expr.Token.Kind == token.Operator && expr.Token.Text() == ":="
}