From acaa37b3b1c5ef6425114ae2330e48b53c15391b Mon Sep 17 00:00:00 2001 From: nitrix Date: Mon, 9 Mar 2020 15:55:23 +0100 Subject: [PATCH] implement detection of tail calls --- .../java/de/hsrm/compiler/Klang/ContextAnalysis.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/main/java/de/hsrm/compiler/Klang/ContextAnalysis.java b/src/main/java/de/hsrm/compiler/Klang/ContextAnalysis.java index 61275a6..33e8b6a 100644 --- a/src/main/java/de/hsrm/compiler/Klang/ContextAnalysis.java +++ b/src/main/java/de/hsrm/compiler/Klang/ContextAnalysis.java @@ -18,6 +18,7 @@ public class ContextAnalysis extends KlangBaseVisitor { Map funcs; Map structs; Type currentDeclaredReturnType; + String currentFunctionDefinitionName; private void checkNumeric(Node lhs, Node rhs, int line, int col) { if (!lhs.type.isNumericType() || !rhs.type.isNumericType()) { @@ -246,6 +247,16 @@ public class ContextAnalysis extends KlangBaseVisitor { public Node visitReturn_statement(KlangParser.Return_statementContext ctx) { Expression expression = (Expression) this.visit(ctx.expression()); ReturnStatement result = new ReturnStatement(expression); + + // Check if this expression is a tail recursion + if (expression instanceof FunctionCall) { + var funCall = (FunctionCall) expression; + if (funCall.name.equals(this.currentFunctionDefinitionName)) { + // Flag this function call + funCall.isTailRecursive = true; + } + } + result.type = expression.type; result.line = ctx.start.getLine(); result.col = ctx.start.getCharPositionInLine(); @@ -720,6 +731,7 @@ public class ContextAnalysis extends KlangBaseVisitor { int col = ctx.start.getCharPositionInLine(); Type returnType = Type.getByName(ctx.returnType.type().getText()); this.currentDeclaredReturnType = returnType; + this.currentFunctionDefinitionName = name; if (!returnType.isPrimitiveType() && this.structs.get(returnType.getName()) == null) { String error = "Type " + returnType.getName() + " not defined.";