diff options
| author | Elias Haugsbakk <[email protected]> | 2026-09-19 00:11:45 +0200 |
|---|---|---|
| committer | Elias Haugsbakk <[email protected]> | 2026-09-19 01:59:23 +0200 |
| commit | ebdcb13d3a55e898a38b92e103b82fa44d822ddc (patch) | |
| tree | e7be2f943ae3fc557d352567de1b75c9a7c3820b /src/main/java/no/eliashaugsbakk/kompilator/semanticAnalysis/Analyzer.java | |
| parent | 1ef6f0e6b9083748e5b91743f15f10f09c6b8432 (diff) | |
Implement semantics analyzer
Diffstat (limited to 'src/main/java/no/eliashaugsbakk/kompilator/semanticAnalysis/Analyzer.java')
| -rw-r--r-- | src/main/java/no/eliashaugsbakk/kompilator/semanticAnalysis/Analyzer.java | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/src/main/java/no/eliashaugsbakk/kompilator/semanticAnalysis/Analyzer.java b/src/main/java/no/eliashaugsbakk/kompilator/semanticAnalysis/Analyzer.java index 891018c..0b01b14 100644 --- a/src/main/java/no/eliashaugsbakk/kompilator/semanticAnalysis/Analyzer.java +++ b/src/main/java/no/eliashaugsbakk/kompilator/semanticAnalysis/Analyzer.java @@ -1,4 +1,56 @@ package no.eliashaugsbakk.kompilator.semanticAnalysis; +import no.eliashaugsbakk.kompilator.parsing.AST; +import no.eliashaugsbakk.kompilator.parsing.node.Program; +import no.eliashaugsbakk.kompilator.parsing.node.expression.Expression; +import no.eliashaugsbakk.kompilator.parsing.node.expression.FunctionCall; +import no.eliashaugsbakk.kompilator.parsing.node.expression.StringLiteral; +import no.eliashaugsbakk.kompilator.parsing.node.statement.ExpressionStatement; +import no.eliashaugsbakk.kompilator.parsing.node.statement.Statement; + public class Analyzer { + private final AST ast; + + public Analyzer(AST ast) { + this.ast = ast; + } + + public void analyze() throws SemanticException { + Program program = (Program) ast.getRoot(); + + for (Statement stmt : program.statements) { + analyzeStatement(stmt); + } + } + + private void analyzeStatement(Statement stmt) throws SemanticException { + if (stmt instanceof ExpressionStatement exprStmt) { + analyzeExpression(exprStmt.expression); + } else { + // Analyze the statement + // NO other statements implemented + } + } + + private void analyzeExpression(Expression expr) throws SemanticException { + if (expr instanceof FunctionCall call) { + checkFunctionCall(call); + } else { + // analyze the expression + } + } + + private void checkFunctionCall(FunctionCall call) throws SemanticException { + if (!call.functionName.equals("print")) { + throw new SemanticException("unknown function: " + call.functionName); + } + + if (call.arguments.size() != 1) { + throw new SemanticException("print expects 1 argument, got " + call.arguments.size()); + } + + if (!(call.arguments.getFirst() instanceof StringLiteral)) { + throw new SemanticException("print expects String argument only"); + } + } } |
