Better over- and underflow handling in the optimizer

This commit is contained in:
nocturn9x 2021-09-27 19:33:37 +02:00
parent 89f57b4c07
commit 3fcdb3ec0a
1 changed files with 28 additions and 24 deletions

View File

@ -138,30 +138,34 @@ proc optimizeBinary(self: Optimizer, node: BinaryExpr): ASTNode =
var x, y, z: int var x, y, z: int
discard parseInt(IntExpr(a).literal.lexeme, x) discard parseInt(IntExpr(a).literal.lexeme, x)
discard parseInt(IntExpr(b).literal.lexeme, y) discard parseInt(IntExpr(b).literal.lexeme, y)
case node.operator.kind: try:
of Plus: case node.operator.kind:
z = x + y of Plus:
of Minus: z = x + y
z = x - y of Minus:
of Asterisk: z = x - y
z = x * y of Asterisk:
of FloorDiv: z = x * y
z = int(x / y) of FloorDiv:
of DoubleAsterisk: z = int(x / y)
z = x ^ y of DoubleAsterisk:
of Percentage: z = x ^ y
z = x mod y of Percentage:
of Caret: z = x mod y
z = x xor y of Caret:
of Ampersand: z = x xor y
z = x and y of Ampersand:
of Pipe: z = x and y
z = x or y of Pipe:
of Slash: z = x or y
# Special case, yields a float of Slash:
return ASTNode(FloatExpr(kind: intExpr, literal: Token(kind: Float, lexeme: $(x / y), line: IntExpr(a).literal.line, pos: (start: -1, stop: -1)))) # Special case, yields a float
else: return ASTNode(FloatExpr(kind: intExpr, literal: Token(kind: Float, lexeme: $(x / y), line: IntExpr(a).literal.line, pos: (start: -1, stop: -1))))
discard else:
discard # Unreachable
except OverflowDefect:
self.newWarning(valueOverflow, node)
return ASTNode(BinaryExpr(kind: binaryExpr, a: a, b: b, operator: node.operator))
result = ASTNode(IntExpr(kind: intExpr, literal: Token(kind: Integer, lexeme: $z, line: IntExpr(a).literal.line, pos: (start: -1, stop: -1)))) result = ASTNode(IntExpr(kind: intExpr, literal: Token(kind: Integer, lexeme: $z, line: IntExpr(a).literal.line, pos: (start: -1, stop: -1))))
elif a.kind == floatExpr or b.kind == floatExpr: elif a.kind == floatExpr or b.kind == floatExpr:
# Optimizes float operations # Optimizes float operations