From 6bdf1fc6c1b7afe18ffcae05f8fb11eca0f51258 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Tue, 25 Jun 2024 11:33:41 +0200 Subject: wip --- src/ast/nodes/AssignmentNode.java | 12 +++++++----- src/ast/nodes/AtomNode.java | 22 ++++++++++++++++++++-- src/ast/nodes/ExprNode.java | 9 ++++++++- src/ast/nodes/FuncdefNode.java | 12 +++++++++++- src/ast/nodes/ParamdefNode.java | 7 +++++++ src/ast/nodes/ParamlistNode.java | 2 +- src/ast/nodes/RootNode.java | 12 ++++++++++-- 7 files changed, 64 insertions(+), 12 deletions(-) (limited to 'src/ast') diff --git a/src/ast/nodes/AssignmentNode.java b/src/ast/nodes/AssignmentNode.java index 627e842..b0310b5 100644 --- a/src/ast/nodes/AssignmentNode.java +++ b/src/ast/nodes/AssignmentNode.java @@ -10,24 +10,26 @@ import ast.types.*; * Node for the `assignment` statement of the grammar. */ public class AssignmentNode implements Node { - private Node lhr; + private ExprNode lhr; private Node assign; - private Node rhr; + private ExprNode rhr; public AssignmentNode(Node lhr, Node assign, Node rhr) { - this.lhr = lhr; + this.lhr = (ExprNode) lhr; this.assign = assign; - this.rhr = rhr; + this.rhr = (ExprNode) rhr; } @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { ArrayList errors = new ArrayList(); - errors.addAll(lhr.checkSemantics(ST, _nesting)); + // errors.addAll(lhr.checkSemantics(ST, _nesting)); errors.addAll(assign.checkSemantics(ST, _nesting)); errors.addAll(rhr.checkSemantics(ST, _nesting)); + ST.insert(lhr.getId(), rhr.typeCheck(), _nesting, ""); + return errors; } diff --git a/src/ast/nodes/AtomNode.java b/src/ast/nodes/AtomNode.java index 4dcb926..7dc38fb 100644 --- a/src/ast/nodes/AtomNode.java +++ b/src/ast/nodes/AtomNode.java @@ -16,15 +16,33 @@ public class AtomNode implements Node { this.val = val; } + public String getId() { + return this.val; + } + @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - return new ArrayList(); + var errors = new ArrayList(); + System.out.println(getId() + " " + _nesting + " " + ST.nslookup(getId())); + if (!(this.typeCheck() instanceof IntType) && !ST.top_lookup(this.getId())) { + System.out.println(!(this.typeCheck() instanceof IntType) + " " + !ST.top_lookup(this.getId())); + errors.add(new SemanticError("Undefined name `" + this.getId() + "`")); + } + + return errors; } // FIXME: this type for atom @Override public Type typeCheck() { - return new AtomType(); + try { + Integer.parseInt(this.val); + System.out.println(this.val + " is int"); + return new IntType(); + } catch (NumberFormatException e) { + System.out.println(this.val + " is atom"); + return new AtomType(); + } } // TODO: add code generation for atom node diff --git a/src/ast/nodes/ExprNode.java b/src/ast/nodes/ExprNode.java index 25c2016..39f397e 100644 --- a/src/ast/nodes/ExprNode.java +++ b/src/ast/nodes/ExprNode.java @@ -24,10 +24,13 @@ public class ExprNode implements Node { this.trailers = trailers; } + public String getId() { + return ((AtomNode) this.atom).getId(); + } + @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { ArrayList errors = new ArrayList(); - if (atom != null) { errors.addAll(atom.checkSemantics(ST, _nesting)); } @@ -50,6 +53,10 @@ public class ExprNode implements Node { // FIXME: type for the expr @Override public Type typeCheck() { + if (this.atom != null) { + return this.atom.typeCheck(); + } + return new VoidType(); } diff --git a/src/ast/nodes/FuncdefNode.java b/src/ast/nodes/FuncdefNode.java index 67bc772..e50e35c 100644 --- a/src/ast/nodes/FuncdefNode.java +++ b/src/ast/nodes/FuncdefNode.java @@ -1,6 +1,7 @@ package ast.nodes; import java.util.ArrayList; +import java.util.HashMap; import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; @@ -24,11 +25,20 @@ public class FuncdefNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { ArrayList errors = new ArrayList(); + ST.insert(this.name.toString(), this.block.typeCheck(), _nesting, ""); + + HashMap HM = new HashMap(); + ArrayList partypes = new ArrayList(); + + ST.add(HM); if (paramlist != null) { - errors.addAll(paramlist.checkSemantics(ST, _nesting)); + errors.addAll(paramlist.checkSemantics(ST, _nesting + 1)); } + // Offset is increased for the possible return value + ST.increaseoffset(); + errors.addAll(block.checkSemantics(ST, _nesting)); return errors; diff --git a/src/ast/nodes/ParamdefNode.java b/src/ast/nodes/ParamdefNode.java index 481282e..3ad82dd 100644 --- a/src/ast/nodes/ParamdefNode.java +++ b/src/ast/nodes/ParamdefNode.java @@ -11,6 +11,13 @@ public class ParamdefNode extends AtomNode { super(val); } + @Override + public ArrayList checkSemantics(SymbolTable ST, int _nesting) { + ST.insert(this.getId(), this.typeCheck(), _nesting, ""); + + return new ArrayList(); + } + // FIXME: it should returns the param' type @Override public Type typeCheck() { diff --git a/src/ast/nodes/ParamlistNode.java b/src/ast/nodes/ParamlistNode.java index 144eb13..a097c19 100644 --- a/src/ast/nodes/ParamlistNode.java +++ b/src/ast/nodes/ParamlistNode.java @@ -21,7 +21,7 @@ public class ParamlistNode implements Node { ArrayList errors = new ArrayList(); for (var param : params) { - errors.addAll(param.checkSemantics(ST, _nesting)); + errors.addAll(param.checkSemantics(ST, _nesting + 1)); } return errors; diff --git a/src/ast/nodes/RootNode.java b/src/ast/nodes/RootNode.java index e0989e8..fd33e30 100644 --- a/src/ast/nodes/RootNode.java +++ b/src/ast/nodes/RootNode.java @@ -1,6 +1,7 @@ package ast.nodes; import java.util.ArrayList; +import java.util.HashMap; import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; @@ -24,13 +25,20 @@ public class RootNode implements Node { public ArrayList checkSemantics(SymbolTable ST, int _nesting) { ArrayList errors = new ArrayList(); - for (Node stmt : stmts) { + HashMap HM = new HashMap(); + + ST.add(HM); + + for (Node stmt : compoundStmts) { errors.addAll(stmt.checkSemantics(ST, _nesting)); } - for (Node stmt : compoundStmts) { + + for (Node stmt : stmts) { errors.addAll(stmt.checkSemantics(ST, _nesting)); } + ST.remove(); + return errors; } -- cgit v1.2.3-18-g5258 From da554f4281da45a22f7101f26cfdf274149c7966 Mon Sep 17 00:00:00 2001 From: L0P0P Date: Tue, 25 Jun 2024 11:41:32 +0200 Subject: Fixed import problems --- src/ast/nodes/FuncdefNode.java | 2 +- src/ast/nodes/ParamdefNode.java | 3 +++ src/ast/nodes/RootNode.java | 3 +-- 3 files changed, 5 insertions(+), 3 deletions(-) (limited to 'src/ast') diff --git a/src/ast/nodes/FuncdefNode.java b/src/ast/nodes/FuncdefNode.java index e50e35c..341a28d 100644 --- a/src/ast/nodes/FuncdefNode.java +++ b/src/ast/nodes/FuncdefNode.java @@ -3,6 +3,7 @@ package ast.nodes; import java.util.ArrayList; import java.util.HashMap; +import semanticanalysis.STentry; import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; import ast.types.*; @@ -28,7 +29,6 @@ public class FuncdefNode implements Node { ST.insert(this.name.toString(), this.block.typeCheck(), _nesting, ""); HashMap HM = new HashMap(); - ArrayList partypes = new ArrayList(); ST.add(HM); diff --git a/src/ast/nodes/ParamdefNode.java b/src/ast/nodes/ParamdefNode.java index 3ad82dd..265b6b6 100644 --- a/src/ast/nodes/ParamdefNode.java +++ b/src/ast/nodes/ParamdefNode.java @@ -1,6 +1,9 @@ package ast.nodes; +import java.util.ArrayList; + import ast.types.*; +import semanticanalysis.*; /** * Node for the `paramdef` statement of the grammar. Extends the `AtomNode` diff --git a/src/ast/nodes/RootNode.java b/src/ast/nodes/RootNode.java index fd33e30..4b7e579 100644 --- a/src/ast/nodes/RootNode.java +++ b/src/ast/nodes/RootNode.java @@ -3,8 +3,7 @@ package ast.nodes; import java.util.ArrayList; import java.util.HashMap; -import semanticanalysis.SemanticError; -import semanticanalysis.SymbolTable; +import semanticanalysis.*; import ast.types.*; /** -- cgit v1.2.3-18-g5258 From b12c01732860f9727626829e0b25a273de5fe5c7 Mon Sep 17 00:00:00 2001 From: geno Date: Tue, 25 Jun 2024 16:04:07 +0200 Subject: check semantic of defined and undefined variables implemented do not check for built-in function works on the example --- src/ast/nodes/AtomNode.java | 31 +++++++----- src/ast/nodes/ExprNode.java | 121 ++++++++++++++++++++++++++++++++++++-------- src/ast/nodes/RootNode.java | 8 +-- src/ast/types/VoidType.java | 6 +++ 4 files changed, 129 insertions(+), 37 deletions(-) (limited to 'src/ast') diff --git a/src/ast/nodes/AtomNode.java b/src/ast/nodes/AtomNode.java index 7dc38fb..4c9a807 100644 --- a/src/ast/nodes/AtomNode.java +++ b/src/ast/nodes/AtomNode.java @@ -1,15 +1,17 @@ package ast.nodes; +import ast.types.*; import java.util.ArrayList; - +import java.util.regex.Matcher; +import java.util.regex.Pattern; import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; -import ast.types.*; /** * Node for the `atom` statement of the grammar. */ public class AtomNode implements Node { + protected String val; public AtomNode(String val) { @@ -23,25 +25,28 @@ public class AtomNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { var errors = new ArrayList(); - System.out.println(getId() + " " + _nesting + " " + ST.nslookup(getId())); - if (!(this.typeCheck() instanceof IntType) && !ST.top_lookup(this.getId())) { - System.out.println(!(this.typeCheck() instanceof IntType) + " " + !ST.top_lookup(this.getId())); + // System.out.println("[ATOM] id: " + getId() + " ns: " + _nesting + " top_lookup" + ST.top_lookup(this.getId())); + if ((this.typeCheck() instanceof AtomType) && !ST.top_lookup(this.getId())) { + // System.out.println(!(this.typeCheck() instanceof IntType) + " " + !ST.top_lookup(this.getId())); errors.add(new SemanticError("Undefined name `" + this.getId() + "`")); } return errors; } - // FIXME: this type for atom + // ENHANCE: return more specific types @Override public Type typeCheck() { - try { - Integer.parseInt(this.val); - System.out.println(this.val + " is int"); - return new IntType(); - } catch (NumberFormatException e) { - System.out.println(this.val + " is atom"); - return new AtomType(); + // this regex should match every possible atom name written in this format: CHAR (CHAR | DIGIT)* + Pattern pattern = Pattern.compile("^[a-zA-Z][a-zA-Z0-9]*$", Pattern.CASE_INSENSITIVE); + Matcher matcher = pattern.matcher(this.val); + boolean matchFound = matcher.find(); + if (matchFound) { + // System.out.println("Match found for " + this.val); + return new AtomType(); // could be a variable or a fuction + } else { + // System.out.println("Match not found for " + this.val); + return new VoidType(); // could be any type of data } } diff --git a/src/ast/nodes/ExprNode.java b/src/ast/nodes/ExprNode.java index 39f397e..13b6619 100644 --- a/src/ast/nodes/ExprNode.java +++ b/src/ast/nodes/ExprNode.java @@ -1,23 +1,96 @@ package ast.nodes; +import ast.types.*; import java.util.ArrayList; - +import java.util.Arrays; import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; -import ast.types.*; /** * Node for the `expr` statement of the grammar. */ public class ExprNode implements Node { - private Node atom; + + private AtomNode atom; private Node compOp; private String op; private ArrayList exprs; private ArrayList trailers; + private static final String[] bif = {"abs", + "aiter", + "all", + "anext", + "any", + "ascii", + "bin", + "bool", + "breakpoint", + "bytearray", + "bytes", + "callable", + "chr", + "classmethod", + "compile", + "complex", + "delattr", + "dict", + "dir", + "divmod", + "enumerate", + "eval", + "exec", + "filter", + "float", + "format", + "frozenset", + "getattr", + "globals", + "hasattr", + "hash", + "help", + "hex", + "id", + "input", + "int", + "isinstance", + "issubclass", + "iter", + "len", + "list", + "locals", + "map", + "max", + "memoryview", + "min", + "next", + "object", + "oct", + "open", + "ord", + "pow", + "print", + "property", + "range", + "repr", + "reversed", + "round", + "set", + "setattr", + "slice", + "sorted", + "staticmethod", + "str", + "sum", + "super", + "tuple", + "type", + "vars", + "zip", + "__import__"}; + public ExprNode(Node atom, Node compOp, ArrayList exprs, String op, ArrayList trailers) { - this.atom = atom; + this.atom = (AtomNode) atom; this.compOp = compOp; this.exprs = exprs; this.op = op; @@ -31,20 +104,28 @@ public class ExprNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { ArrayList errors = new ArrayList(); - if (atom != null) { - errors.addAll(atom.checkSemantics(ST, _nesting)); - } - - if (compOp != null) { - errors.addAll(compOp.checkSemantics(ST, _nesting)); - } - - for (var expr : exprs) { - errors.addAll(expr.checkSemantics(ST, _nesting)); - } - - for (var trailer : trailers) { - errors.addAll(trailer.checkSemantics(ST, _nesting)); + if (atom != null && !trailers.isEmpty()) { + // function call + if (!Arrays.asList(bif).contains(atom.getId())) { + errors.addAll(atom.checkSemantics(ST, _nesting)); + } + } else { + // butto tutto quello che c'era prima nell'else così non rischio di perdere niente di utile + if (atom != null) { + errors.addAll(atom.checkSemantics(ST, _nesting)); + } + + if (compOp != null) { + errors.addAll(compOp.checkSemantics(ST, _nesting)); + } + + for (var expr : exprs) { + errors.addAll(expr.checkSemantics(ST, _nesting)); + } + + for (var trailer : trailers) { + errors.addAll(trailer.checkSemantics(ST, _nesting)); + } } return errors; @@ -81,11 +162,11 @@ public class ExprNode implements Node { for (var expr : exprs) { str += expr.toPrint(prefix); - } + } for (var trailer : trailers) { str += trailer.toPrint(prefix); - } + } if (op != null) { str += prefix + "Op(" + op + ")\n"; diff --git a/src/ast/nodes/RootNode.java b/src/ast/nodes/RootNode.java index 4b7e579..45d20db 100644 --- a/src/ast/nodes/RootNode.java +++ b/src/ast/nodes/RootNode.java @@ -1,15 +1,15 @@ package ast.nodes; +import ast.types.*; import java.util.ArrayList; import java.util.HashMap; - import semanticanalysis.*; -import ast.types.*; /** * Node for the `root` statement of the grammar. */ public class RootNode implements Node { + // stms and compundStmts are protected because they are reused for a // BlockNode protected ArrayList stmts; @@ -28,11 +28,11 @@ public class RootNode implements Node { ST.add(HM); - for (Node stmt : compoundStmts) { + for (Node stmt : stmts) { errors.addAll(stmt.checkSemantics(ST, _nesting)); } - for (Node stmt : stmts) { + for (Node stmt : compoundStmts) { errors.addAll(stmt.checkSemantics(ST, _nesting)); } diff --git a/src/ast/types/VoidType.java b/src/ast/types/VoidType.java index d15933f..8e3f9b2 100644 --- a/src/ast/types/VoidType.java +++ b/src/ast/types/VoidType.java @@ -4,7 +4,13 @@ package ast.types; * A void type. Voids return nothing. */ public class VoidType extends Type { + public String toPrint(String prefix) { return prefix + "Void\n"; } + + @Override + public String toString() { + return "Void"; + } } -- cgit v1.2.3-18-g5258 From fc712f94a7ed8554d8d44f4965be367354a7e670 Mon Sep 17 00:00:00 2001 From: L0P0P Date: Wed, 26 Jun 2024 10:06:12 +0200 Subject: Using child --- src/ast/Python3VisitorImpl.java | 40 ++++++++++++++++++++++------------------ src/ast/nodes/AtomNode.java | 2 +- src/ast/nodes/BlockNode.java | 11 ++++------- src/ast/nodes/ExprNode.java | 4 +++- src/ast/nodes/FuncdefNode.java | 1 + src/ast/nodes/RootNode.java | 27 +++++++++++---------------- 6 files changed, 42 insertions(+), 43 deletions(-) (limited to 'src/ast') diff --git a/src/ast/Python3VisitorImpl.java b/src/ast/Python3VisitorImpl.java index 604c8d2..f5b369d 100644 --- a/src/ast/Python3VisitorImpl.java +++ b/src/ast/Python3VisitorImpl.java @@ -21,17 +21,19 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { * ``` */ public Node visitRoot(RootContext ctx) { - ArrayList stmts = new ArrayList(); - ArrayList compStmts = new ArrayList(); - - for (Simple_stmtsContext stm : ctx.simple_stmts()) { - stmts.add(visit(stm)); - } - for (Compound_stmtContext stm : ctx.compound_stmt()) { - compStmts.add(visit(stm)); + ArrayList childs = new ArrayList(); + + for (int i = 0; i < ctx.getChildCount(); i++){ + var child = ctx.getChild(i); + + if (child instanceof Simple_stmtsContext) { + childs.add(visit((Simple_stmtsContext) child)); + } else if (child instanceof Compound_stmtContext) { + childs.add(visit((Compound_stmtContext) child)); + } } - return new RootNode(stmts, compStmts); + return new RootNode(childs); } /** @@ -331,17 +333,19 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { * ``` */ public Node visitBlock(BlockContext ctx) { - ArrayList stmts = new ArrayList(); - ArrayList compStmts = new ArrayList(); - - for (Simple_stmtsContext s : ctx.simple_stmts()) { - stmts.add(visit(s)); - } - for (Compound_stmtContext s : ctx.compound_stmt()) { - compStmts.add(visit(s)); + ArrayList childs = new ArrayList(); + + for (int i = 0; i < ctx.getChildCount(); i++){ + var child = ctx.getChild(i); + + if (child instanceof Simple_stmtsContext) { + childs.add(visit((Simple_stmtsContext) child)); + } else if (child instanceof Compound_stmtContext) { + childs.add(visit((Compound_stmtContext) child)); + } } - return new BlockNode(stmts, compStmts); + return new BlockNode(childs); } /** diff --git a/src/ast/nodes/AtomNode.java b/src/ast/nodes/AtomNode.java index 4c9a807..0a3c765 100644 --- a/src/ast/nodes/AtomNode.java +++ b/src/ast/nodes/AtomNode.java @@ -26,7 +26,7 @@ public class AtomNode implements Node { public ArrayList checkSemantics(SymbolTable ST, int _nesting) { var errors = new ArrayList(); // System.out.println("[ATOM] id: " + getId() + " ns: " + _nesting + " top_lookup" + ST.top_lookup(this.getId())); - if ((this.typeCheck() instanceof AtomType) && !ST.top_lookup(this.getId())) { + if ((this.typeCheck() instanceof AtomType) && ST.nslookup(this.getId()) < 0) { // System.out.println(!(this.typeCheck() instanceof IntType) + " " + !ST.top_lookup(this.getId())); errors.add(new SemanticError("Undefined name `" + this.getId() + "`")); } diff --git a/src/ast/nodes/BlockNode.java b/src/ast/nodes/BlockNode.java index 6b07f49..2c85025 100644 --- a/src/ast/nodes/BlockNode.java +++ b/src/ast/nodes/BlockNode.java @@ -9,8 +9,8 @@ import ast.types.*; * It extends the `RootNode`. */ public class BlockNode extends RootNode { - public BlockNode(ArrayList stmts, ArrayList compoundStmts) { - super(stmts, compoundStmts); + public BlockNode(ArrayList childs) { + super(childs); } @Override @@ -23,11 +23,8 @@ public class BlockNode extends RootNode { String str = prefix + "Block\n"; prefix += " "; - for (Node stmt : stmts) { - str += stmt.toPrint(prefix); - } - for (Node stmt : compoundStmts) { - str += stmt.toPrint(prefix); + for (Node child : childs) { + str += child.toPrint(prefix); } return str; diff --git a/src/ast/nodes/ExprNode.java b/src/ast/nodes/ExprNode.java index 13b6619..344f3c0 100644 --- a/src/ast/nodes/ExprNode.java +++ b/src/ast/nodes/ExprNode.java @@ -17,7 +17,9 @@ public class ExprNode implements Node { private ArrayList exprs; private ArrayList trailers; - private static final String[] bif = {"abs", + // built-in functions + private static final String[] bif = { + "abs", "aiter", "all", "anext", diff --git a/src/ast/nodes/FuncdefNode.java b/src/ast/nodes/FuncdefNode.java index 341a28d..742f670 100644 --- a/src/ast/nodes/FuncdefNode.java +++ b/src/ast/nodes/FuncdefNode.java @@ -26,6 +26,7 @@ public class FuncdefNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { ArrayList errors = new ArrayList(); + ST.insert(this.name.toString(), this.block.typeCheck(), _nesting, ""); HashMap HM = new HashMap(); diff --git a/src/ast/nodes/RootNode.java b/src/ast/nodes/RootNode.java index 45d20db..4b29e8d 100644 --- a/src/ast/nodes/RootNode.java +++ b/src/ast/nodes/RootNode.java @@ -12,30 +12,28 @@ public class RootNode implements Node { // stms and compundStmts are protected because they are reused for a // BlockNode - protected ArrayList stmts; - protected ArrayList compoundStmts; + protected ArrayList childs; - public RootNode(ArrayList stmts, ArrayList compoundStmts) { - this.stmts = stmts; - this.compoundStmts = compoundStmts; + public RootNode(ArrayList childs) { + this.childs = childs; } @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { ArrayList errors = new ArrayList(); + // Create a new HashMap for the current scope HashMap HM = new HashMap(); + // Add the HashMap to the SymbolTable ST.add(HM); - for (Node stmt : stmts) { - errors.addAll(stmt.checkSemantics(ST, _nesting)); - } - - for (Node stmt : compoundStmts) { - errors.addAll(stmt.checkSemantics(ST, _nesting)); + // Check semantics for each child + for (Node child : childs) { + errors.addAll(child.checkSemantics(ST, _nesting)); } + // Remove the HashMap from the SymbolTable ST.remove(); return errors; @@ -58,11 +56,8 @@ public class RootNode implements Node { prefix += " "; - for (Node stmt : stmts) { - str += stmt.toPrint(prefix); - } - for (Node stmt : compoundStmts) { - str += stmt.toPrint(prefix); + for (Node child : childs) { + str += child.toPrint(prefix); } return str; -- cgit v1.2.3-18-g5258 From 9e6c17cb44bc165e315ec039a0e09183716d2037 Mon Sep 17 00:00:00 2001 From: L0P0P Date: Wed, 26 Jun 2024 11:44:58 +0200 Subject: Semantic check for function declaration and function invocation --- src/ast/nodes/ArglistNode.java | 14 ++++++++++++-- src/ast/nodes/AtomNode.java | 9 ++++++--- src/ast/nodes/ExprNode.java | 31 ++++++++++++------------------- src/ast/nodes/FuncdefNode.java | 5 ++++- src/ast/nodes/ParamlistNode.java | 2 +- 5 files changed, 35 insertions(+), 26 deletions(-) (limited to 'src/ast') diff --git a/src/ast/nodes/ArglistNode.java b/src/ast/nodes/ArglistNode.java index f0c33e1..71bcdce 100644 --- a/src/ast/nodes/ArglistNode.java +++ b/src/ast/nodes/ArglistNode.java @@ -19,9 +19,19 @@ public class ArglistNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { ArrayList errors = new ArrayList(); - + for (var arg : arguments) { - errors.addAll(arg.checkSemantics(ST, _nesting)); + ExprNode argExpr = (ExprNode) arg; + String argName = argExpr.getId(); + + // TODO: check fucking IntType for params + // TODO: remove fucking comments + if (!ST.top_lookup(argName) && argExpr.typeCheck() instanceof AtomType){ + // System.out.println(!(this.typeCheck() instanceof IntType) + " " + !ST.top_lookup(this.getId())); + errors.add(new SemanticError("'" + argName + "' is not defined.")); + } else { + errors.addAll(arg.checkSemantics(ST, _nesting)); + } } return errors; diff --git a/src/ast/nodes/AtomNode.java b/src/ast/nodes/AtomNode.java index 0a3c765..0704bc4 100644 --- a/src/ast/nodes/AtomNode.java +++ b/src/ast/nodes/AtomNode.java @@ -25,10 +25,13 @@ public class AtomNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { var errors = new ArrayList(); - // System.out.println("[ATOM] id: " + getId() + " ns: " + _nesting + " top_lookup" + ST.top_lookup(this.getId())); - if ((this.typeCheck() instanceof AtomType) && ST.nslookup(this.getId()) < 0) { + + // Print the symbol table + System.out.println(ST); + + if ((this.typeCheck() instanceof AtomType) && !ST.top_lookup(this.getId())/*ST.nslookup(this.getId()) < 0*/) { // System.out.println(!(this.typeCheck() instanceof IntType) + " " + !ST.top_lookup(this.getId())); - errors.add(new SemanticError("Undefined name `" + this.getId() + "`")); + errors.add(new SemanticError("'" + this.getId() + "' is not defined.")); } return errors; diff --git a/src/ast/nodes/ExprNode.java b/src/ast/nodes/ExprNode.java index 344f3c0..4bb67f7 100644 --- a/src/ast/nodes/ExprNode.java +++ b/src/ast/nodes/ExprNode.java @@ -106,30 +106,23 @@ public class ExprNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { ArrayList errors = new ArrayList(); - if (atom != null && !trailers.isEmpty()) { - // function call - if (!Arrays.asList(bif).contains(atom.getId())) { - errors.addAll(atom.checkSemantics(ST, _nesting)); - } - } else { - // butto tutto quello che c'era prima nell'else così non rischio di perdere niente di utile - if (atom != null) { - errors.addAll(atom.checkSemantics(ST, _nesting)); - } - - if (compOp != null) { - errors.addAll(compOp.checkSemantics(ST, _nesting)); - } - - for (var expr : exprs) { - errors.addAll(expr.checkSemantics(ST, _nesting)); - } - + + if (atom != null && !Arrays.asList(bif).contains(atom.getId())) { + errors.addAll(atom.checkSemantics(ST, _nesting)); + for (var trailer : trailers) { errors.addAll(trailer.checkSemantics(ST, _nesting)); } } + + if (compOp != null) { + errors.addAll(compOp.checkSemantics(ST, _nesting)); + } + for (var expr : exprs) { + errors.addAll(expr.checkSemantics(ST, _nesting)); + } + return errors; } diff --git a/src/ast/nodes/FuncdefNode.java b/src/ast/nodes/FuncdefNode.java index 742f670..f3be1d9 100644 --- a/src/ast/nodes/FuncdefNode.java +++ b/src/ast/nodes/FuncdefNode.java @@ -37,10 +37,13 @@ public class FuncdefNode implements Node { errors.addAll(paramlist.checkSemantics(ST, _nesting + 1)); } + // TODO: think to the fucking offset // Offset is increased for the possible return value ST.increaseoffset(); - errors.addAll(block.checkSemantics(ST, _nesting)); + errors.addAll(block.checkSemantics(ST, _nesting + 1)); + + ST.remove(); return errors; } diff --git a/src/ast/nodes/ParamlistNode.java b/src/ast/nodes/ParamlistNode.java index a097c19..144eb13 100644 --- a/src/ast/nodes/ParamlistNode.java +++ b/src/ast/nodes/ParamlistNode.java @@ -21,7 +21,7 @@ public class ParamlistNode implements Node { ArrayList errors = new ArrayList(); for (var param : params) { - errors.addAll(param.checkSemantics(ST, _nesting + 1)); + errors.addAll(param.checkSemantics(ST, _nesting)); } return errors; -- cgit v1.2.3-18-g5258 From e09358f3648445bbf9747f40497af6221d933a99 Mon Sep 17 00:00:00 2001 From: L0P0P Date: Wed, 26 Jun 2024 11:54:57 +0200 Subject: Introduction to recursive function --- src/ast/nodes/BlockNode.java | 15 +++++++++++++++ src/ast/nodes/FuncdefNode.java | 2 ++ 2 files changed, 17 insertions(+) (limited to 'src/ast') diff --git a/src/ast/nodes/BlockNode.java b/src/ast/nodes/BlockNode.java index 2c85025..a38b4ea 100644 --- a/src/ast/nodes/BlockNode.java +++ b/src/ast/nodes/BlockNode.java @@ -3,6 +3,8 @@ package ast.nodes; import java.util.ArrayList; import ast.types.*; +import semanticanalysis.SemanticError; +import semanticanalysis.SymbolTable; /** * Node for `block` statement of the grammar. @@ -13,6 +15,19 @@ public class BlockNode extends RootNode { super(childs); } + @Override + public ArrayList checkSemantics(SymbolTable ST, int _nesting) { + ArrayList errors = new ArrayList(); + + // Check semantics for each child + for (Node child : childs) { + errors.addAll(child.checkSemantics(ST, _nesting)); + } + + return errors; + } + + @Override public Type typeCheck() { return new VoidType(); diff --git a/src/ast/nodes/FuncdefNode.java b/src/ast/nodes/FuncdefNode.java index f3be1d9..4c8f92f 100644 --- a/src/ast/nodes/FuncdefNode.java +++ b/src/ast/nodes/FuncdefNode.java @@ -33,6 +33,8 @@ public class FuncdefNode implements Node { ST.add(HM); + ST.insert(this.name.toString(), this.block.typeCheck(), _nesting + 1, ""); + if (paramlist != null) { errors.addAll(paramlist.checkSemantics(ST, _nesting + 1)); } -- cgit v1.2.3-18-g5258 From 06671f5aed68753435a762bc3be43e83094156d1 Mon Sep 17 00:00:00 2001 From: geno Date: Wed, 26 Jun 2024 14:53:05 +0200 Subject: exercise 1 completed 1.b now works 1.c implened error for "function takes N positional arguments but M were given" --- src/ast/nodes/ArglistNode.java | 12 ++++++---- src/ast/nodes/AssignmentNode.java | 4 ++-- src/ast/nodes/AtomNode.java | 6 ++--- src/ast/nodes/CompNode.java | 2 ++ src/ast/nodes/CompoundNode.java | 4 ++-- src/ast/nodes/ExprNode.java | 45 +++++++++++++++++++++++++++----------- src/ast/nodes/FuncdefNode.java | 10 ++++++--- src/ast/nodes/IfNode.java | 3 +-- src/ast/nodes/ParamdefNode.java | 18 ++++++++++----- src/ast/nodes/ParamlistNode.java | 5 +++++ src/ast/nodes/SimpleStmtNode.java | 3 +-- src/ast/nodes/SimpleStmtsNode.java | 3 +-- src/ast/nodes/TrailerNode.java | 5 +++++ src/ast/types/FunctionType.java | 27 +++++++++++++++++++++++ 14 files changed, 109 insertions(+), 38 deletions(-) create mode 100644 src/ast/types/FunctionType.java (limited to 'src/ast') diff --git a/src/ast/nodes/ArglistNode.java b/src/ast/nodes/ArglistNode.java index 71bcdce..cd1a403 100644 --- a/src/ast/nodes/ArglistNode.java +++ b/src/ast/nodes/ArglistNode.java @@ -1,15 +1,15 @@ package ast.nodes; +import ast.types.*; import java.util.ArrayList; - import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; -import ast.types.*; /** * Node for the `arglist` statement of the grammar. */ public class ArglistNode implements Node { + protected ArrayList arguments; public ArglistNode(ArrayList arguments) { @@ -19,14 +19,14 @@ public class ArglistNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { ArrayList errors = new ArrayList(); - + for (var arg : arguments) { ExprNode argExpr = (ExprNode) arg; String argName = argExpr.getId(); // TODO: check fucking IntType for params // TODO: remove fucking comments - if (!ST.top_lookup(argName) && argExpr.typeCheck() instanceof AtomType){ + if (argName != null && !ST.top_lookup(argName) && argExpr.typeCheck() instanceof AtomType) { // System.out.println(!(this.typeCheck() instanceof IntType) + " " + !ST.top_lookup(this.getId())); errors.add(new SemanticError("'" + argName + "' is not defined.")); } else { @@ -37,6 +37,10 @@ public class ArglistNode implements Node { return errors; } + public int getArgumentNumber() { + return arguments.size(); + } + @Override public Type typeCheck() { return new VoidType(); diff --git a/src/ast/nodes/AssignmentNode.java b/src/ast/nodes/AssignmentNode.java index b0310b5..3d597ef 100644 --- a/src/ast/nodes/AssignmentNode.java +++ b/src/ast/nodes/AssignmentNode.java @@ -1,15 +1,15 @@ package ast.nodes; +import ast.types.*; import java.util.ArrayList; - import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; -import ast.types.*; /** * Node for the `assignment` statement of the grammar. */ public class AssignmentNode implements Node { + private ExprNode lhr; private Node assign; private ExprNode rhr; diff --git a/src/ast/nodes/AtomNode.java b/src/ast/nodes/AtomNode.java index 0704bc4..96132d8 100644 --- a/src/ast/nodes/AtomNode.java +++ b/src/ast/nodes/AtomNode.java @@ -25,11 +25,11 @@ public class AtomNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { var errors = new ArrayList(); - + // Print the symbol table - System.out.println(ST); + // System.out.println(ST); - if ((this.typeCheck() instanceof AtomType) && !ST.top_lookup(this.getId())/*ST.nslookup(this.getId()) < 0*/) { + if ((this.typeCheck() instanceof AtomType) && ST.nslookup(this.getId()) < 0) { // System.out.println(!(this.typeCheck() instanceof IntType) + " " + !ST.top_lookup(this.getId())); errors.add(new SemanticError("'" + this.getId() + "' is not defined.")); } diff --git a/src/ast/nodes/CompNode.java b/src/ast/nodes/CompNode.java index 33976bf..f167bf9 100644 --- a/src/ast/nodes/CompNode.java +++ b/src/ast/nodes/CompNode.java @@ -11,6 +11,7 @@ import org.antlr.v4.runtime.tree.TerminalNode; * Node for the `comp_op` statement of the grammar. */ public class CompNode implements Node { + private TerminalNode op; public CompNode(TerminalNode op) { @@ -19,6 +20,7 @@ public class CompNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { + System.out.println("Comp node"); return new ArrayList(); } diff --git a/src/ast/nodes/CompoundNode.java b/src/ast/nodes/CompoundNode.java index e64be9e..d21c2c7 100644 --- a/src/ast/nodes/CompoundNode.java +++ b/src/ast/nodes/CompoundNode.java @@ -1,15 +1,15 @@ package ast.nodes; +import ast.types.*; import java.util.ArrayList; - import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; -import ast.types.*; /** * Node for the `compound_node` statement of the grammar. */ public class CompoundNode implements Node { + private Node ifNode; private Node funcDef; private Node forStmt; diff --git a/src/ast/nodes/ExprNode.java b/src/ast/nodes/ExprNode.java index 4bb67f7..eea69f8 100644 --- a/src/ast/nodes/ExprNode.java +++ b/src/ast/nodes/ExprNode.java @@ -3,6 +3,7 @@ package ast.nodes; import ast.types.*; import java.util.ArrayList; import java.util.Arrays; +import semanticanalysis.STentry; import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; @@ -100,29 +101,47 @@ public class ExprNode implements Node { } public String getId() { - return ((AtomNode) this.atom).getId(); + if (atom != null) { + return ((AtomNode) this.atom).getId(); + } else { + return null; + } } @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { ArrayList errors = new ArrayList(); - - if (atom != null && !Arrays.asList(bif).contains(atom.getId())) { - errors.addAll(atom.checkSemantics(ST, _nesting)); - - for (var trailer : trailers) { - errors.addAll(trailer.checkSemantics(ST, _nesting)); - } + + if (atom != null && !trailers.isEmpty()) { + // function call + if (!Arrays.asList(bif).contains(atom.getId())) { + errors.addAll(atom.checkSemantics(ST, _nesting)); + Node trailer = trailers.get(0); + String funName = atom.getId(); + STentry s = ST.lookup(funName); + if (s != null) { + FunctionType ft = (FunctionType) s.getType(); + int paramNumber = ft.getParamNumber(); + int argNumber = ((TrailerNode) trailer).getArgumentNumber(); + if (paramNumber != argNumber) { + errors.add(new SemanticError(funName + "() takes " + String.valueOf(paramNumber) + " positional arguments but " + String.valueOf(argNumber) + " were given")); + } + } + } else { + for (var trailer : trailers) { + errors.addAll(trailer.checkSemantics(ST, _nesting)); + } + } } - + if (compOp != null) { errors.addAll(compOp.checkSemantics(ST, _nesting)); } for (var expr : exprs) { errors.addAll(expr.checkSemantics(ST, _nesting)); - } - + } + return errors; } @@ -157,11 +176,11 @@ public class ExprNode implements Node { for (var expr : exprs) { str += expr.toPrint(prefix); - } + } for (var trailer : trailers) { str += trailer.toPrint(prefix); - } + } if (op != null) { str += prefix + "Op(" + op + ")\n"; diff --git a/src/ast/nodes/FuncdefNode.java b/src/ast/nodes/FuncdefNode.java index 4c8f92f..8985e08 100644 --- a/src/ast/nodes/FuncdefNode.java +++ b/src/ast/nodes/FuncdefNode.java @@ -13,6 +13,7 @@ import org.antlr.v4.runtime.tree.TerminalNode; * Node for the `funcdef` statement of the grammar. */ public class FuncdefNode implements Node { + private TerminalNode name; private Node paramlist; private Node block; @@ -26,14 +27,17 @@ public class FuncdefNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { ArrayList errors = new ArrayList(); - - ST.insert(this.name.toString(), this.block.typeCheck(), _nesting, ""); + int paramNumber = ((ParamlistNode) paramlist).getParamNumber(); + Type returnType = this.block.typeCheck(); + FunctionType ft = new FunctionType(paramNumber, returnType); + + ST.insert(this.name.toString(), ft, _nesting, ""); HashMap HM = new HashMap(); ST.add(HM); - ST.insert(this.name.toString(), this.block.typeCheck(), _nesting + 1, ""); + ST.insert(this.name.toString(), ft, _nesting + 1, ""); if (paramlist != null) { errors.addAll(paramlist.checkSemantics(ST, _nesting + 1)); diff --git a/src/ast/nodes/IfNode.java b/src/ast/nodes/IfNode.java index 50dde4a..772041b 100644 --- a/src/ast/nodes/IfNode.java +++ b/src/ast/nodes/IfNode.java @@ -1,10 +1,9 @@ package ast.nodes; +import ast.types.*; import java.util.ArrayList; - import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; -import ast.types.*; /** * Node for the `if` statement of the grammar. diff --git a/src/ast/nodes/ParamdefNode.java b/src/ast/nodes/ParamdefNode.java index 265b6b6..5164537 100644 --- a/src/ast/nodes/ParamdefNode.java +++ b/src/ast/nodes/ParamdefNode.java @@ -1,24 +1,32 @@ package ast.nodes; -import java.util.ArrayList; - import ast.types.*; -import semanticanalysis.*; +import java.util.ArrayList; +import semanticanalysis.SemanticError; +import semanticanalysis.SymbolTable; /** * Node for the `paramdef` statement of the grammar. Extends the `AtomNode` * class. */ public class ParamdefNode extends AtomNode { + public ParamdefNode(String val) { super(val); } @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - ST.insert(this.getId(), this.typeCheck(), _nesting, ""); + var errors = new ArrayList(); + String paramName = this.getId(); + + if (!ST.top_lookup(paramName)) { + ST.insert(paramName, this.typeCheck(), _nesting, ""); + } else { + errors.add(new SemanticError("Duplicate argument '" + paramName + "' in function definition.")); + } - return new ArrayList(); + return errors; } // FIXME: it should returns the param' type diff --git a/src/ast/nodes/ParamlistNode.java b/src/ast/nodes/ParamlistNode.java index 144eb13..0a9696f 100644 --- a/src/ast/nodes/ParamlistNode.java +++ b/src/ast/nodes/ParamlistNode.java @@ -10,6 +10,7 @@ import ast.types.*; * Node for the `param_list` statement of the grammar. */ public class ParamlistNode implements Node { + private ArrayList params; public ParamlistNode(ArrayList _params) { @@ -27,6 +28,10 @@ public class ParamlistNode implements Node { return errors; } + public int getParamNumber() { + return params.size(); + } + @Override public Type typeCheck() { return new VoidType(); diff --git a/src/ast/nodes/SimpleStmtNode.java b/src/ast/nodes/SimpleStmtNode.java index 5f844cb..b7e5455 100644 --- a/src/ast/nodes/SimpleStmtNode.java +++ b/src/ast/nodes/SimpleStmtNode.java @@ -1,10 +1,9 @@ package ast.nodes; +import ast.types.*; import java.util.ArrayList; - import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; -import ast.types.*; /** * Node for the `simple_stmt` statement of the grammar. diff --git a/src/ast/nodes/SimpleStmtsNode.java b/src/ast/nodes/SimpleStmtsNode.java index 66c8e2c..97bffff 100644 --- a/src/ast/nodes/SimpleStmtsNode.java +++ b/src/ast/nodes/SimpleStmtsNode.java @@ -1,10 +1,9 @@ package ast.nodes; +import ast.types.*; import java.util.ArrayList; - import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; -import ast.types.*; /** * Node for the `simple_stmts` statement of the grammar. diff --git a/src/ast/nodes/TrailerNode.java b/src/ast/nodes/TrailerNode.java index b0a0ee7..850b8e8 100644 --- a/src/ast/nodes/TrailerNode.java +++ b/src/ast/nodes/TrailerNode.java @@ -11,6 +11,7 @@ import org.antlr.v4.runtime.tree.TerminalNode; * Node for the `trailer` statement of the grammar. */ public class TrailerNode implements Node { + private Node arglist; private ArrayList exprs; private TerminalNode methodCall; @@ -39,6 +40,10 @@ public class TrailerNode implements Node { return errors; } + public int getArgumentNumber() { + return ((ArglistNode) arglist).getArgumentNumber(); + } + @Override public Type typeCheck() { return new VoidType(); diff --git a/src/ast/types/FunctionType.java b/src/ast/types/FunctionType.java new file mode 100644 index 0000000..464bb9c --- /dev/null +++ b/src/ast/types/FunctionType.java @@ -0,0 +1,27 @@ +package ast.types; + +/** + * An tom type. TODO: do I need to use this one? + */ +public class FunctionType extends Type { + + private final int paramNumber; + private final Type returnType; + + public FunctionType(int paramNumber, Type returnType) { + this.paramNumber = paramNumber; + this.returnType = returnType; + } + + public int getParamNumber() { + return paramNumber; + } + + public Type getReturnType() { + return returnType; + } + + public String toPrint(String prefix) { + return prefix + "Atom\n"; + } +} -- cgit v1.2.3-18-g5258 From fb89b8c0885ee4e289cfb577bbabf0ee66b05024 Mon Sep 17 00:00:00 2001 From: geno Date: Wed, 26 Jun 2024 18:23:05 +0200 Subject: test dir added, fix bug in ExprNode (added by myself obv) --- src/ast/nodes/ExprNode.java | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src/ast') diff --git a/src/ast/nodes/ExprNode.java b/src/ast/nodes/ExprNode.java index eea69f8..4fbe166 100644 --- a/src/ast/nodes/ExprNode.java +++ b/src/ast/nodes/ExprNode.java @@ -132,6 +132,8 @@ public class ExprNode implements Node { errors.addAll(trailer.checkSemantics(ST, _nesting)); } } + } else if (atom != null) { + errors.addAll(atom.checkSemantics(ST, _nesting)); } if (compOp != null) { -- cgit v1.2.3-18-g5258 From 3c4229fc9e0ec6da9a7f60b57b9e93c49d1b6b6c Mon Sep 17 00:00:00 2001 From: L0P0P Date: Thu, 27 Jun 2024 12:02:35 +0200 Subject: Fixed a lot of problems from all the progs we need to parse --- src/ast/Python3VisitorImpl.java | 30 ++++++++- src/ast/nodes/ArglistNode.java | 17 +++++- src/ast/nodes/AtomNode.java | 27 ++++++--- src/ast/nodes/CompNode.java | 1 - src/ast/nodes/DottedNameNode.java | 6 +- src/ast/nodes/ExprNode.java | 114 +++++++++-------------------------- src/ast/nodes/ForStmtNode.java | 4 ++ src/ast/nodes/IfNode.java | 4 +- src/ast/nodes/ImportNode.java | 14 ++++- src/ast/nodes/Node.java | 75 +++++++++++++++++++++++ src/ast/nodes/TrailerNode.java | 12 +++- src/ast/types/ContinueBreakType.java | 10 +++ src/ast/types/ImportType.java | 11 ++++ 13 files changed, 219 insertions(+), 106 deletions(-) create mode 100644 src/ast/types/ContinueBreakType.java create mode 100644 src/ast/types/ImportType.java (limited to 'src/ast') diff --git a/src/ast/Python3VisitorImpl.java b/src/ast/Python3VisitorImpl.java index f5b369d..d4b4fbf 100644 --- a/src/ast/Python3VisitorImpl.java +++ b/src/ast/Python3VisitorImpl.java @@ -264,10 +264,28 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { x = new AugassignNode(ctx.SUB_ASSIGN()); } else if (ctx.MULT_ASSIGN() != null) { x = new AugassignNode(ctx.MULT_ASSIGN()); + } else if (ctx.AT_ASSIGN() != null) { + x = new AugassignNode(ctx.AT_ASSIGN()); } else if (ctx.DIV_ASSIGN() != null) { x = new AugassignNode(ctx.DIV_ASSIGN()); + } else if (ctx.MOD_ASSIGN() != null) { + x = new AugassignNode(ctx.MOD_ASSIGN()); + } else if (ctx.AND_ASSIGN() != null) { + x = new AugassignNode(ctx.AND_ASSIGN()); + } else if (ctx.OR_ASSIGN() != null) { + x = new AugassignNode(ctx.OR_ASSIGN()); + } else if (ctx.XOR_ASSIGN() != null) { + x = new AugassignNode(ctx.XOR_ASSIGN()); + } else if (ctx.LEFT_SHIFT_ASSIGN() != null) { + x = new AugassignNode(ctx.LEFT_SHIFT_ASSIGN()); + } else if (ctx.RIGHT_SHIFT_ASSIGN() != null) { + x = new AugassignNode(ctx.RIGHT_SHIFT_ASSIGN()); + } else if (ctx.POWER_ASSIGN() != null) { + x = new AugassignNode(ctx.POWER_ASSIGN()); + } else if (ctx.IDIV_ASSIGN() != null) { + x = new AugassignNode(ctx.IDIV_ASSIGN()); } - + return x; } @@ -495,7 +513,7 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { methodCall = ctx.NAME(); } - return new TrailerNode(arglist, exprs, methodCall); + return new TrailerNode(arglist, exprs, methodCall, ctx.OPEN_PAREN() != null); } /** @@ -507,7 +525,13 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { * ``` */ public Node visitExprlist(ExprlistContext ctx) { - Node exp = visit(ctx.expr(0)); + Node exp; + + if (ctx.expr(0).expr(0) != null){ + exp = visit(ctx.expr(0).expr(0)); + } else { + exp = visit(ctx.expr(0)); + } return exp; } diff --git a/src/ast/nodes/ArglistNode.java b/src/ast/nodes/ArglistNode.java index cd1a403..78b4ca7 100644 --- a/src/ast/nodes/ArglistNode.java +++ b/src/ast/nodes/ArglistNode.java @@ -2,6 +2,8 @@ package ast.nodes; import ast.types.*; import java.util.ArrayList; +import java.util.Arrays; + import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; @@ -26,9 +28,18 @@ public class ArglistNode implements Node { // TODO: check fucking IntType for params // TODO: remove fucking comments - if (argName != null && !ST.top_lookup(argName) && argExpr.typeCheck() instanceof AtomType) { - // System.out.println(!(this.typeCheck() instanceof IntType) + " " + !ST.top_lookup(this.getId())); - errors.add(new SemanticError("'" + argName + "' is not defined.")); + if (argName != null) { + if (Arrays.asList(bif).contains(argName)) { + continue; + } + + if (ST.lookup(argName) != null && ST.lookup(argName).getType() instanceof ImportType) { + continue; + } + + if (!ST.top_lookup(argName) && argExpr.typeCheck() instanceof AtomType) { + errors.add(new SemanticError("'" + argName + "' is not defined.")); + } } else { errors.addAll(arg.checkSemantics(ST, _nesting)); } diff --git a/src/ast/nodes/AtomNode.java b/src/ast/nodes/AtomNode.java index 96132d8..ceafc07 100644 --- a/src/ast/nodes/AtomNode.java +++ b/src/ast/nodes/AtomNode.java @@ -26,11 +26,7 @@ public class AtomNode implements Node { public ArrayList checkSemantics(SymbolTable ST, int _nesting) { var errors = new ArrayList(); - // Print the symbol table - // System.out.println(ST); - if ((this.typeCheck() instanceof AtomType) && ST.nslookup(this.getId()) < 0) { - // System.out.println(!(this.typeCheck() instanceof IntType) + " " + !ST.top_lookup(this.getId())); errors.add(new SemanticError("'" + this.getId() + "' is not defined.")); } @@ -40,15 +36,26 @@ public class AtomNode implements Node { // ENHANCE: return more specific types @Override public Type typeCheck() { + Pattern booleanVariable = Pattern.compile("^(True|False)$"); + Pattern continueBreakVariable = Pattern.compile("^(continue|break)$"); // this regex should match every possible atom name written in this format: CHAR (CHAR | DIGIT)* - Pattern pattern = Pattern.compile("^[a-zA-Z][a-zA-Z0-9]*$", Pattern.CASE_INSENSITIVE); - Matcher matcher = pattern.matcher(this.val); - boolean matchFound = matcher.find(); - if (matchFound) { - // System.out.println("Match found for " + this.val); + Pattern simpleVariable = Pattern.compile("^[a-zA-Z][a-zA-Z0-9]*$", Pattern.CASE_INSENSITIVE); + + Matcher booleanVariableMatcher = booleanVariable.matcher(this.val); + Matcher continueBreakVariableMatcher = continueBreakVariable.matcher(this.val); + Matcher simpleVariableMatcher = simpleVariable.matcher(this.val); + + boolean matchFoundBoolean = booleanVariableMatcher.find(); + boolean matchFoundContinueBreak = continueBreakVariableMatcher.find(); + boolean matchFoundSimpleVariable = simpleVariableMatcher.find(); + + if (matchFoundBoolean) { + return new BoolType(); + } else if (matchFoundContinueBreak) { + return new ContinueBreakType(); + } else if (matchFoundSimpleVariable) { return new AtomType(); // could be a variable or a fuction } else { - // System.out.println("Match not found for " + this.val); return new VoidType(); // could be any type of data } } diff --git a/src/ast/nodes/CompNode.java b/src/ast/nodes/CompNode.java index f167bf9..8be6ea1 100644 --- a/src/ast/nodes/CompNode.java +++ b/src/ast/nodes/CompNode.java @@ -20,7 +20,6 @@ public class CompNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - System.out.println("Comp node"); return new ArrayList(); } diff --git a/src/ast/nodes/DottedNameNode.java b/src/ast/nodes/DottedNameNode.java index 46d1b61..df86c99 100644 --- a/src/ast/nodes/DottedNameNode.java +++ b/src/ast/nodes/DottedNameNode.java @@ -21,12 +21,16 @@ public class DottedNameNode implements Node { public ArrayList checkSemantics(SymbolTable ST, int _nesting) { ArrayList errors = new ArrayList(); + for (int i = 0; i < names.size(); ++i) { + ST.insert(names.get(i).toString(), this.typeCheck(), _nesting, null); + } + return errors; } @Override public Type typeCheck() { - return new VoidType(); + return new ImportType(); } // NOTE: we do not provide code generation for this node in the same way diff --git a/src/ast/nodes/ExprNode.java b/src/ast/nodes/ExprNode.java index 4fbe166..1b20e2e 100644 --- a/src/ast/nodes/ExprNode.java +++ b/src/ast/nodes/ExprNode.java @@ -3,6 +3,7 @@ package ast.nodes; import ast.types.*; import java.util.ArrayList; import java.util.Arrays; + import semanticanalysis.STentry; import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; @@ -18,80 +19,6 @@ public class ExprNode implements Node { private ArrayList exprs; private ArrayList trailers; - // built-in functions - private static final String[] bif = { - "abs", - "aiter", - "all", - "anext", - "any", - "ascii", - "bin", - "bool", - "breakpoint", - "bytearray", - "bytes", - "callable", - "chr", - "classmethod", - "compile", - "complex", - "delattr", - "dict", - "dir", - "divmod", - "enumerate", - "eval", - "exec", - "filter", - "float", - "format", - "frozenset", - "getattr", - "globals", - "hasattr", - "hash", - "help", - "hex", - "id", - "input", - "int", - "isinstance", - "issubclass", - "iter", - "len", - "list", - "locals", - "map", - "max", - "memoryview", - "min", - "next", - "object", - "oct", - "open", - "ord", - "pow", - "print", - "property", - "range", - "repr", - "reversed", - "round", - "set", - "setattr", - "slice", - "sorted", - "staticmethod", - "str", - "sum", - "super", - "tuple", - "type", - "vars", - "zip", - "__import__"}; - public ExprNode(Node atom, Node compOp, ArrayList exprs, String op, ArrayList trailers) { this.atom = (AtomNode) atom; this.compOp = compOp; @@ -112,19 +39,38 @@ public class ExprNode implements Node { public ArrayList checkSemantics(SymbolTable ST, int _nesting) { ArrayList errors = new ArrayList(); + // check if the atom is a built-in function if (atom != null && !trailers.isEmpty()) { - // function call + if (!Arrays.asList(bif).contains(atom.getId())) { + errors.addAll(atom.checkSemantics(ST, _nesting)); - Node trailer = trailers.get(0); + + TrailerNode trailer = (TrailerNode) trailers.get(0); String funName = atom.getId(); - STentry s = ST.lookup(funName); - if (s != null) { - FunctionType ft = (FunctionType) s.getType(); - int paramNumber = ft.getParamNumber(); - int argNumber = ((TrailerNode) trailer).getArgumentNumber(); - if (paramNumber != argNumber) { - errors.add(new SemanticError(funName + "() takes " + String.valueOf(paramNumber) + " positional arguments but " + String.valueOf(argNumber) + " were given")); + + // TODO: it isnt a function, it could be a variable + STentry fun = ST.lookup(funName); + + + + if (fun != null && !(fun.getType() instanceof ImportType)) { + if (!(fun.getType() instanceof FunctionType)) { + if (trailer.isParenthesis()) { + errors.add(new SemanticError("'" + funName + "' is not a function.")); + } else { + for (var t : trailers) { + errors.addAll(t.checkSemantics(ST, _nesting)); + } + } + } else { + FunctionType ft = (FunctionType) fun.getType(); + int paramNumber = ft.getParamNumber(); + int argNumber = trailer.getArgumentNumber(); + + if (paramNumber != argNumber) { + errors.add(new SemanticError(funName + "() takes " + String.valueOf(paramNumber) + " positional arguments but " + String.valueOf(argNumber) + " were given.")); + } } } } else { @@ -150,7 +96,7 @@ public class ExprNode implements Node { // FIXME: type for the expr @Override public Type typeCheck() { - if (this.atom != null) { + if (this.atom != null ) { return this.atom.typeCheck(); } diff --git a/src/ast/nodes/ForStmtNode.java b/src/ast/nodes/ForStmtNode.java index 6d94bb2..28fe783 100644 --- a/src/ast/nodes/ForStmtNode.java +++ b/src/ast/nodes/ForStmtNode.java @@ -22,6 +22,10 @@ public class ForStmtNode implements Node { public ArrayList checkSemantics(SymbolTable ST, int _nesting) { ArrayList errors = new ArrayList(); + ExprNode expr = (ExprNode) exprList; + + ST.insert(expr.getId(), expr.typeCheck(), _nesting, ""); + errors.addAll(exprList.checkSemantics(ST, _nesting)); errors.addAll(block.checkSemantics(ST, _nesting)); diff --git a/src/ast/nodes/IfNode.java b/src/ast/nodes/IfNode.java index 772041b..f51d486 100644 --- a/src/ast/nodes/IfNode.java +++ b/src/ast/nodes/IfNode.java @@ -41,11 +41,11 @@ public class IfNode implements Node { if (thenexp.getClass().equals(elseexp.getClass())) return thenexp; else { - System.out.println("Type Error: incompatible types in then and else branches"); + System.out.println("Type Error: incompatible types in then and else branches."); return new ErrorType(); } } else { - System.out.println("Type Error: non boolean condition in if"); + System.out.println("Type Error: non boolean condition in if."); return new ErrorType(); } } diff --git a/src/ast/nodes/ImportNode.java b/src/ast/nodes/ImportNode.java index e264c99..900a909 100644 --- a/src/ast/nodes/ImportNode.java +++ b/src/ast/nodes/ImportNode.java @@ -29,12 +29,24 @@ public class ImportNode implements Node { public ArrayList checkSemantics(SymbolTable ST, int _nesting) { ArrayList errors = new ArrayList(); + if (isFrom) { + for (int i = 0; i < names.size(); ++i) { + ST.insert(names.get(i), this.typeCheck(), _nesting, null); + } + } else { + errors.addAll(dottedName.checkSemantics(ST, _nesting)); + } + + if (importAs) { + ST.insert(names.get(names.size() - 1), this.typeCheck(), _nesting, null); + } + return errors; } @Override public Type typeCheck() { - return new VoidType(); + return new ImportType(); } // NOTE: we do not want to provide a code generation for this statement diff --git a/src/ast/nodes/Node.java b/src/ast/nodes/Node.java index 949531e..77ba669 100644 --- a/src/ast/nodes/Node.java +++ b/src/ast/nodes/Node.java @@ -10,6 +10,81 @@ import ast.types.*; * Base interface for a Node. */ public interface Node { + + static final String[] bif = { + "abs", + "aiter", + "all", + "anext", + "any", + "ascii", + "bin", + "bool", + "breakpoint", + "bytearray", + "bytes", + "callable", + "chr", + "classmethod", + "compile", + "complex", + "delattr", + "dict", + "dir", + "divmod", + "enumerate", + "eval", + "exec", + "exit", + "filter", + "float", + "format", + "frozenset", + "getattr", + "globals", + "hasattr", + "hash", + "help", + "hex", + "id", + "input", + "int", + "isinstance", + "issubclass", + "iter", + "len", + "list", + "locals", + "map", + "max", + "memoryview", + "min", + "next", + "object", + "oct", + "open", + "ord", + "pow", + "print", + "property", + "range", + "repr", + "reversed", + "round", + "set", + "setattr", + "slice", + "sorted", + "staticmethod", + "str", + "sum", + "super", + "tuple", + "type", + "vars", + "zip", + "__import__"}; + /** * Checks semantics for a given node for a SymbolTable ST and a level of * nesting. diff --git a/src/ast/nodes/TrailerNode.java b/src/ast/nodes/TrailerNode.java index 850b8e8..22e43a0 100644 --- a/src/ast/nodes/TrailerNode.java +++ b/src/ast/nodes/TrailerNode.java @@ -15,12 +15,14 @@ public class TrailerNode implements Node { private Node arglist; private ArrayList exprs; private TerminalNode methodCall; + private boolean isParenthesis; private boolean isEmpty; - public TrailerNode(Node arglist, ArrayList exprs, TerminalNode methodCall) { + public TrailerNode(Node arglist, ArrayList exprs, TerminalNode methodCall, boolean isParenthesis) { this.arglist = arglist; this.exprs = exprs; this.methodCall = methodCall; + this.isParenthesis = isParenthesis; this.isEmpty = (this.arglist == null && this.exprs.size() == 0 && this.methodCall == null); } @@ -41,9 +43,17 @@ public class TrailerNode implements Node { } public int getArgumentNumber() { + if (arglist == null) { + return 0; + } + return ((ArglistNode) arglist).getArgumentNumber(); } + public boolean isParenthesis() { + return this.isParenthesis; + } + @Override public Type typeCheck() { return new VoidType(); diff --git a/src/ast/types/ContinueBreakType.java b/src/ast/types/ContinueBreakType.java new file mode 100644 index 0000000..dfcf1f2 --- /dev/null +++ b/src/ast/types/ContinueBreakType.java @@ -0,0 +1,10 @@ +package ast.types; + +/** + * A type for the continue and break statements. + */ +public class ContinueBreakType extends Type { + public String toPrint(String prefix) { + return prefix + "ContinueBreak\n"; + } +} diff --git a/src/ast/types/ImportType.java b/src/ast/types/ImportType.java new file mode 100644 index 0000000..6852bfa --- /dev/null +++ b/src/ast/types/ImportType.java @@ -0,0 +1,11 @@ +package ast.types; + +/** + * A type for the imported names. + */ +public class ImportType extends Type { + public String toPrint(String prefix) { + return prefix + "Import\n"; + } +} + -- cgit v1.2.3-18-g5258 From 673117132daa9c4fdd103189b5cd9a32a3731f5a Mon Sep 17 00:00:00 2001 From: geno Date: Thu, 27 Jun 2024 13:08:54 +0200 Subject: remove duplicates --- src/ast/nodes/AtomNode.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/ast') diff --git a/src/ast/nodes/AtomNode.java b/src/ast/nodes/AtomNode.java index ceafc07..58cd7f9 100644 --- a/src/ast/nodes/AtomNode.java +++ b/src/ast/nodes/AtomNode.java @@ -27,7 +27,7 @@ public class AtomNode implements Node { var errors = new ArrayList(); if ((this.typeCheck() instanceof AtomType) && ST.nslookup(this.getId()) < 0) { - errors.add(new SemanticError("'" + this.getId() + "' is not defined.")); + errors.add(new SemanticError("name '" + this.getId() + "' is not defined.")); } return errors; -- cgit v1.2.3-18-g5258 From 095a2cb4e9abb88805aac3271874bc512108ff96 Mon Sep 17 00:00:00 2001 From: geno Date: Thu, 27 Jun 2024 18:19:27 +0200 Subject: minor changes --- src/ast/nodes/ArglistNode.java | 5 ++--- src/ast/nodes/AtomNode.java | 6 ++++-- src/ast/nodes/ExprNode.java | 12 +++++------- 3 files changed, 11 insertions(+), 12 deletions(-) (limited to 'src/ast') diff --git a/src/ast/nodes/ArglistNode.java b/src/ast/nodes/ArglistNode.java index 78b4ca7..983d150 100644 --- a/src/ast/nodes/ArglistNode.java +++ b/src/ast/nodes/ArglistNode.java @@ -3,7 +3,6 @@ package ast.nodes; import ast.types.*; import java.util.ArrayList; import java.util.Arrays; - import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; @@ -37,8 +36,8 @@ public class ArglistNode implements Node { continue; } - if (!ST.top_lookup(argName) && argExpr.typeCheck() instanceof AtomType) { - errors.add(new SemanticError("'" + argName + "' is not defined.")); + if (ST.nslookup(argName) < 0 && argExpr.typeCheck() instanceof AtomType) { + errors.add(new SemanticError("name '" + argName + "' is not defined.")); } } else { errors.addAll(arg.checkSemantics(ST, _nesting)); diff --git a/src/ast/nodes/AtomNode.java b/src/ast/nodes/AtomNode.java index 58cd7f9..3c2b1eb 100644 --- a/src/ast/nodes/AtomNode.java +++ b/src/ast/nodes/AtomNode.java @@ -28,6 +28,8 @@ public class AtomNode implements Node { if ((this.typeCheck() instanceof AtomType) && ST.nslookup(this.getId()) < 0) { errors.add(new SemanticError("name '" + this.getId() + "' is not defined.")); + } else { + // System.out.println("exist " + this.getId()); } return errors; @@ -40,11 +42,11 @@ public class AtomNode implements Node { Pattern continueBreakVariable = Pattern.compile("^(continue|break)$"); // this regex should match every possible atom name written in this format: CHAR (CHAR | DIGIT)* Pattern simpleVariable = Pattern.compile("^[a-zA-Z][a-zA-Z0-9]*$", Pattern.CASE_INSENSITIVE); - + Matcher booleanVariableMatcher = booleanVariable.matcher(this.val); Matcher continueBreakVariableMatcher = continueBreakVariable.matcher(this.val); Matcher simpleVariableMatcher = simpleVariable.matcher(this.val); - + boolean matchFoundBoolean = booleanVariableMatcher.find(); boolean matchFoundContinueBreak = continueBreakVariableMatcher.find(); boolean matchFoundSimpleVariable = simpleVariableMatcher.find(); diff --git a/src/ast/nodes/ExprNode.java b/src/ast/nodes/ExprNode.java index 1b20e2e..62b3a94 100644 --- a/src/ast/nodes/ExprNode.java +++ b/src/ast/nodes/ExprNode.java @@ -3,7 +3,6 @@ package ast.nodes; import ast.types.*; import java.util.ArrayList; import java.util.Arrays; - import semanticanalysis.STentry; import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; @@ -39,21 +38,20 @@ public class ExprNode implements Node { public ArrayList checkSemantics(SymbolTable ST, int _nesting) { ArrayList errors = new ArrayList(); - // check if the atom is a built-in function + // check if the atom is a function if (atom != null && !trailers.isEmpty()) { + // check if the atom is not a built-in function if (!Arrays.asList(bif).contains(atom.getId())) { - + errors.addAll(atom.checkSemantics(ST, _nesting)); - + TrailerNode trailer = (TrailerNode) trailers.get(0); String funName = atom.getId(); // TODO: it isnt a function, it could be a variable STentry fun = ST.lookup(funName); - - if (fun != null && !(fun.getType() instanceof ImportType)) { if (!(fun.getType() instanceof FunctionType)) { if (trailer.isParenthesis()) { @@ -96,7 +94,7 @@ public class ExprNode implements Node { // FIXME: type for the expr @Override public Type typeCheck() { - if (this.atom != null ) { + if (this.atom != null) { return this.atom.typeCheck(); } -- cgit v1.2.3-18-g5258 From eb7fb04d2dfadd004fa86f28da42681e0038df06 Mon Sep 17 00:00:00 2001 From: geno Date: Thu, 27 Jun 2024 18:20:34 +0200 Subject: left, right = 1, 2 assignment covered sfaccimm ho fatto refactoring dell exprlist --- src/ast/Python3VisitorImpl.java | 192 +++++++++++++++++------------------- src/ast/nodes/AssignmentNode.java | 21 +++- src/ast/nodes/AtomNode.java | 22 ++++- src/ast/nodes/ExprListNode.java | 61 ++++++++++++ src/ast/nodes/ForStmtNode.java | 12 +-- src/ast/nodes/ParamdefNode.java | 2 +- src/ast/nodes/TestlistCompNode.java | 61 ++++++++++++ 7 files changed, 249 insertions(+), 122 deletions(-) create mode 100644 src/ast/nodes/ExprListNode.java create mode 100644 src/ast/nodes/TestlistCompNode.java (limited to 'src/ast') diff --git a/src/ast/Python3VisitorImpl.java b/src/ast/Python3VisitorImpl.java index d4b4fbf..5b812ea 100644 --- a/src/ast/Python3VisitorImpl.java +++ b/src/ast/Python3VisitorImpl.java @@ -12,20 +12,19 @@ import org.antlr.v4.runtime.tree.TerminalNode; * Overrides each `visitNODE` method from the base class. */ public class Python3VisitorImpl extends Python3ParserBaseVisitor { + /** * Since a root can be a simple_stmts or a compound_stmt, this method * returns a new `RootNode` with a list of them. * - * ``` - * root : NEWLINE* (simple_stmts | compound_stmt)* EOF; - * ``` + * ``` root : NEWLINE* (simple_stmts | compound_stmt)* EOF; ``` */ public Node visitRoot(RootContext ctx) { ArrayList childs = new ArrayList(); - - for (int i = 0; i < ctx.getChildCount(); i++){ + + for (int i = 0; i < ctx.getChildCount(); i++) { var child = ctx.getChild(i); - + if (child instanceof Simple_stmtsContext) { childs.add(visit((Simple_stmtsContext) child)); } else if (child instanceof Compound_stmtContext) { @@ -39,9 +38,7 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { /** * Returns a `SimpleStmtsNode`, made by an array of SimpleStmtNode * - * ``` - * simple_stmts : simple_stmt (';' simple_stmt)* ';'? NEWLINE ; - * ``` + * ``` simple_stmts : simple_stmt (';' simple_stmt)* ';'? NEWLINE ; ``` */ public Node visitSimple_stmts(Simple_stmtsContext ctx) { ArrayList stmts = new ArrayList(); @@ -57,9 +54,7 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { * Returns a `CompoundNode`. It can be built by a different kind of * statements, so only one of theme won't be null. * - * ``` - * compound_stmt : if_stmt | while_stmt | for_stmt | funcdef ; - * ``` + * ``` compound_stmt : if_stmt | while_stmt | for_stmt | funcdef ; ``` */ public Node visitCompound_stmt(Compound_stmtContext ctx) { Node ifStmt = null; @@ -90,9 +85,7 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { * Returns a `SimpleStmtNode`. It can be built by a different kind of * statements, so only one of theme won't be null. * - * ``` - * simple_stmt : assignment | expr | return_stmt | import_stm ; - * ``` + * ``` simple_stmt : assignment | expr | return_stmt | import_stm ; ``` */ public Node visitSimple_stmt(Simple_stmtContext ctx) { Node assignment = null; @@ -122,10 +115,8 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { /** * Returns an `AssignmentNode`. It's made by left side, an assignment and a * right side. - * - * ``` - * assignment : exprlist augassign exprlist ; - * ``` + * + * ``` assignment : exprlist augassign exprlist ; ``` */ public Node visitAssignment(AssignmentContext ctx) { Node lhr = visit(ctx.exprlist(0)); @@ -138,9 +129,7 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { /** * Returns a `ReturnStmtNode`. The returned exprlist can be null. * - * ``` - * return_stmt : 'return' exprlist? ; - * ``` + * ``` return_stmt : 'return' exprlist? ; ``` */ public Node visitReturn_stmt(Return_stmtContext ctx) { Node exprList = null; @@ -155,10 +144,8 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { * Returns a `ImportNode`. An import can be made in different ways so we * check the way in a module is imported (by from, by alias or by star). * - * ``` - * import_stm : 'import' dotted_name ('as' NAME)? - * | 'from' dotted_name 'import' (NAME (',' NAME)* | '*') ; - * ``` + * ``` import_stm : 'import' dotted_name ('as' NAME)? | 'from' dotted_name + * 'import' (NAME (',' NAME)* | '*') ; ``` */ public Node visitImport_stm(Import_stmContext ctx) { boolean isFrom = ctx.FROM() != null; @@ -179,9 +166,7 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { /** * Returns a `DottedNameNode` used in `import_stm`. * - * ``` - * dotted_name : NAME ('.' NAME)* ; - * ``` + * ``` dotted_name : NAME ('.' NAME)* ; ``` */ public Node visitDotted_name(Dotted_nameContext ctx) { ArrayList names = new ArrayList(); @@ -196,9 +181,7 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { /** * Returns a `FuncdefNode`. A paramlist can be null. * - * ``` - * funcdef : 'def' NAME '(' paramlist? ')' ':' block ; - * ``` + * ``` funcdef : 'def' NAME '(' paramlist? ')' ':' block ; ``` */ public Node visitFuncdef(FuncdefContext ctx) { Node paramlist = null; @@ -216,9 +199,8 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { * Returns a `ParamlistNode`. We ignore the paramdef with default values * (eg: is_used=False) because there is no test which uses this feature. * - * ``` - * paramlist : paramdef ('=' expr)? (',' paramdef ('=' expr)?)* ; - * + * ``` paramlist : paramdef ('=' expr)? (',' paramdef ('=' expr)?)* ; + * * ``` */ public Node visitParamlist(ParamlistContext ctx) { @@ -235,9 +217,7 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { * Returns a `ParamdefNode`. We ignore the paramdef with type annotation * (eg: x : int) because there is no test which uses this feature. * - * ``` - * paramdef : NAME (':' expr)? ; - * ``` + * ``` paramdef : NAME (':' expr)? ; ``` */ public Node visitParamdef(ParamdefContext ctx) { return new ParamdefNode(ctx.NAME().toString()); @@ -247,11 +227,8 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { * Returns an `AugassignNode`. We don't provide all kinds of assignment * below. * - * ``` - * augassign : '=' | '+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | - * '^=' | '<<=' | '>>=' | '**=' | '//=' - * ; - * ``` + * ``` augassign : '=' | '+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | + * '|=' | '^=' | '<<=' | '>>=' | '**=' | '//=' ; ``` */ public Node visitAugassign(AugassignContext ctx) { Node x = null; @@ -285,17 +262,15 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { } else if (ctx.IDIV_ASSIGN() != null) { x = new AugassignNode(ctx.IDIV_ASSIGN()); } - + return x; } /** - * Returns a `IfNode`. - * FIXME: add support for elif statement. + * Returns a `IfNode`. FIXME: add support for elif statement. * - * ``` - * if_stmt : 'if' expr ':' block ('elif' expr ':' block)* ('else' ':' block)? ; - * ``` + * ``` if_stmt : 'if' expr ':' block ('elif' expr ':' block)* ('else' ':' + * block)? ; ``` */ public Node visitIf_stmt(If_stmtContext ctx) { var blocks = ctx.block(); @@ -312,9 +287,7 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { /** * Returns a `WhileStmtNode`. We do not provide 'else' branch. * - * ``` - * while_stmt : 'while' expr ':' block ('else' ':' block)? ; - * ``` + * ``` while_stmt : 'while' expr ':' block ('else' ':' block)? ; ``` */ public Node visitWhile_stmt(While_stmtContext ctx) { Node expr = visit(ctx.expr()); @@ -328,9 +301,7 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { /** * Returns a `ForSmtNode`. We do not provide 'else' branch. * - * ``` - * for_stmt : 'for' exprlist ':' block ('else' ':' block)? ; - * ``` + * ``` for_stmt : 'for' exprlist ':' block ('else' ':' block)? ; ``` */ public Node visitFor_stmt(For_stmtContext ctx) { Node exprList = visit(ctx.exprlist()); @@ -345,17 +316,15 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { * Returns a `BlockNode`. A block can be be a simple_stmts or a list of * simple_stms and/or compound_stmt, so we just use a list for each kind. * - * ``` - * block : simple_stmts - * | NEWLINE INDENT (simple_stmts | compound_stmt)+ DEDENT ; - * ``` + * ``` block : simple_stmts | NEWLINE INDENT (simple_stmts | compound_stmt)+ + * DEDENT ; ``` */ public Node visitBlock(BlockContext ctx) { ArrayList childs = new ArrayList(); - for (int i = 0; i < ctx.getChildCount(); i++){ + for (int i = 0; i < ctx.getChildCount(); i++) { var child = ctx.getChild(i); - + if (child instanceof Simple_stmtsContext) { childs.add(visit((Simple_stmtsContext) child)); } else if (child instanceof Compound_stmtContext) { @@ -369,10 +338,8 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { /** * Returns a `CompNode`. It should never be null. * - * ``` - * comp_op : '<' | '>' | '==' | '>=' | '<=' | '<>' | '!=' | 'in' | 'not' 'in' | - * 'is' | 'is' 'not' ; - * ``` + * ``` comp_op : '<' | '>' | '==' | '>=' | '<=' | '<>' | '!=' | 'in' | 'not' + * 'in' | 'is' | 'is' 'not' ; ``` */ public Node visitComp_op(Comp_opContext ctx) { Node comp = null; @@ -404,13 +371,11 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { * Returns an `ExprNode`. An expession can be a different kind of * sub-expression. We do not provide all kinds of expr(s). * - * ``` - * expr : atom trailer* | expr '**' expr | ('+' | '-' | '~')+ expr | expr ('*' | - * '@' | '/' | '%' | '//') expr | expr ('+' | '-') expr | expr ('<<' | '>>') - * expr | expr '&' expr | expr '^' expr | expr '|' expr | 'not' expr | expr - * comp_op expr | expr 'and' expr | expr 'or' expr | expr 'if' expr 'else' expr - * ; - * ``` + * ``` expr : atom trailer* | expr '**' expr | ('+' | '-' | '~')+ expr | + * expr ('*' | '@' | '/' | '%' | '//') expr | expr ('+' | '-') expr | expr + * ('<<' | '>>') expr | expr '&' expr | expr '^' expr | expr '|' expr | + * 'not' expr | expr comp_op expr | expr 'and' expr | expr 'or' expr | expr + * 'if' expr 'else' expr ; ``` */ public Node visitExpr(ExprContext ctx) { Node atom = null; @@ -459,42 +424,52 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { } /** - * Returns an `AtomNode`. - * FIXME: add support for testlist_comp + * Returns an `AtomNode`. FIXME: add support for testlist_comp * - * ``` - * atom : '(' testlist_comp? ')' | '[' testlist_comp? ']' | '{' testlist_comp? - * '}' | NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False' ; - * ``` + * ``` atom : '(' testlist_comp? ')' | '[' testlist_comp? ']' | '{' + * testlist_comp? '}' | NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | + * 'False' ; ``` */ public Node visitAtom(AtomContext ctx) { + Testlist_compContext tlc = ctx.testlist_comp(); if (ctx.NUMBER() != null) { - return new AtomNode(ctx.NUMBER().toString()); + return new AtomNode(ctx.NUMBER().toString(), null); } else if (ctx.TRUE() != null) { - return new AtomNode(ctx.TRUE().toString()); + return new AtomNode(ctx.TRUE().toString(), null); } else if (ctx.FALSE() != null) { - return new AtomNode(ctx.FALSE().toString()); + return new AtomNode(ctx.FALSE().toString(), null); } else if (ctx.NAME() != null) { - return new AtomNode(ctx.NAME().toString()); - } else if (ctx.STRING() != null) { - + return new AtomNode(ctx.NAME().toString(), null); + } else if (!ctx.STRING().isEmpty()) { var varName = ""; for (var x : ctx.STRING()) { varName += x; } + return new AtomNode(varName, null); + } else if (ctx.OPEN_BRACE() != null && ctx.CLOSE_BRACE() != null) { + return manageTlc(tlc); + } else if (ctx.OPEN_BRACK() != null && ctx.CLOSE_BRACK() != null) { + return manageTlc(tlc); + } else if (ctx.OPEN_PAREN() != null && ctx.CLOSE_PAREN() != null) { + return manageTlc(tlc); + } + return new AtomNode(ctx.NONE().toString(), null); + } - return new AtomNode(varName); + public AtomNode manageTlc(Testlist_compContext tlc) { + if (tlc != null) { + Node testlist_comp = visit(tlc); + return new AtomNode(null, testlist_comp); + } else { + return new AtomNode(null, null); } - return new AtomNode(ctx.NONE().toString()); } /** * Returns an `TrailerNode`. * - * ``` - * trailer : '(' arglist? ')' | '[' expr (',' expr)* ','? ']' | '.' NAME | '[' - * expr? ':' expr? (':' expr? )? ']' ; - * ``` + * ``` trailer : '(' arglist? ')' | '[' expr (',' expr)* ','? ']' | '.' NAME + * | '[' expr? ':' expr? (':' expr? )? ']' ; ``` */ public Node visitTrailer(TrailerContext ctx) { Node arglist = null; @@ -517,31 +492,24 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { } /** - * Returns a `Node`. - * FIXME: what to do in case of list?? + * Returns a `Node`. FIXME: what to do in case of list?? * - * ``` - * exprlist : expr (',' expr )* ','? ; - * ``` + * ``` exprlist : expr (',' expr )* ','? ; ``` */ public Node visitExprlist(ExprlistContext ctx) { - Node exp; + ArrayList exprlist = new ArrayList(); - if (ctx.expr(0).expr(0) != null){ - exp = visit(ctx.expr(0).expr(0)); - } else { - exp = visit(ctx.expr(0)); + for (ExprContext c : ctx.expr()) { + exprlist.add(visit(c)); } - return exp; + return new ExprListNode(exprlist); } /** * Returns a `ArglistNode`. * - * ``` - * arglist : argument (',' argument)* ','? ; - * ``` + * ``` arglist : argument (',' argument)* ','? ; ``` */ public Node visitArglist(ArglistContext ctx) { ArrayList arguments = new ArrayList(); @@ -552,4 +520,20 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { return new ArglistNode(arguments); } + + /** + * Returns a `TestlistCompNode`. + * + * ``` testlist_comp : expr (comp_for | (',' expr)* ','?) ; ``` + */ + public Node visitTestlist_comp(Testlist_compContext ctx) { + // TODO: implement comp_for + ArrayList exprlist = new ArrayList(); + + for (ExprContext c : ctx.expr()) { + exprlist.add(visit(c)); + } + + return new TestlistCompNode(exprlist); + } } diff --git a/src/ast/nodes/AssignmentNode.java b/src/ast/nodes/AssignmentNode.java index 3d597ef..07966c3 100644 --- a/src/ast/nodes/AssignmentNode.java +++ b/src/ast/nodes/AssignmentNode.java @@ -10,14 +10,14 @@ import semanticanalysis.SymbolTable; */ public class AssignmentNode implements Node { - private ExprNode lhr; + private ExprListNode lhr; private Node assign; - private ExprNode rhr; + private ExprListNode rhr; public AssignmentNode(Node lhr, Node assign, Node rhr) { - this.lhr = (ExprNode) lhr; + this.lhr = (ExprListNode) lhr; this.assign = assign; - this.rhr = (ExprNode) rhr; + this.rhr = (ExprListNode) rhr; } @Override @@ -28,7 +28,18 @@ public class AssignmentNode implements Node { errors.addAll(assign.checkSemantics(ST, _nesting)); errors.addAll(rhr.checkSemantics(ST, _nesting)); - ST.insert(lhr.getId(), rhr.typeCheck(), _nesting, ""); + int lsize = lhr.getSize(); + int rsize = rhr.getSize(); + + if (lsize == rsize) { + for (int i = 0; i < lsize; i++) { + ExprNode latom = (ExprNode) lhr.getElem(i); + ExprNode ratom = (ExprNode) rhr.getElem(i); + ST.insert(latom.getId(), ratom.typeCheck(), _nesting, ""); + } + } else { + errors.add(new SemanticError("ValueError: different size of left or right side assignment")); + } return errors; } diff --git a/src/ast/nodes/AtomNode.java b/src/ast/nodes/AtomNode.java index 3c2b1eb..592aac4 100644 --- a/src/ast/nodes/AtomNode.java +++ b/src/ast/nodes/AtomNode.java @@ -13,9 +13,11 @@ import semanticanalysis.SymbolTable; public class AtomNode implements Node { protected String val; + protected TestlistCompNode exprlist; - public AtomNode(String val) { + public AtomNode(String val, Node exprlist) { this.val = val; + this.exprlist = (TestlistCompNode) exprlist; } public String getId() { @@ -26,10 +28,16 @@ public class AtomNode implements Node { public ArrayList checkSemantics(SymbolTable ST, int _nesting) { var errors = new ArrayList(); - if ((this.typeCheck() instanceof AtomType) && ST.nslookup(this.getId()) < 0) { - errors.add(new SemanticError("name '" + this.getId() + "' is not defined.")); - } else { - // System.out.println("exist " + this.getId()); + if (val != null) { + if ((this.typeCheck() instanceof AtomType) && ST.nslookup(this.getId()) < 0) { + errors.add(new SemanticError("name '" + this.getId() + "' is not defined.")); + } else { + // System.out.println("exist " + this.typeCheck()); + } + } + + if (exprlist != null) { + errors.addAll(exprlist.checkSemantics(ST, _nesting)); } return errors; @@ -38,6 +46,10 @@ public class AtomNode implements Node { // ENHANCE: return more specific types @Override public Type typeCheck() { + if (this.val == null) { + return new VoidType(); + } + Pattern booleanVariable = Pattern.compile("^(True|False)$"); Pattern continueBreakVariable = Pattern.compile("^(continue|break)$"); // this regex should match every possible atom name written in this format: CHAR (CHAR | DIGIT)* diff --git a/src/ast/nodes/ExprListNode.java b/src/ast/nodes/ExprListNode.java new file mode 100644 index 0000000..c1a2ebc --- /dev/null +++ b/src/ast/nodes/ExprListNode.java @@ -0,0 +1,61 @@ +package ast.nodes; + +import ast.types.*; +import java.util.ArrayList; +import semanticanalysis.SemanticError; +import semanticanalysis.SymbolTable; + +/** + * Node for the `expr_list` statement of the grammar. + */ +public class ExprListNode implements Node { + + private final ArrayList exprs; + + public ExprListNode(ArrayList _exprs) { + this.exprs = _exprs; + } + + @Override + public ArrayList checkSemantics(SymbolTable ST, int _nesting) { + ArrayList errors = new ArrayList(); + + for (var param : exprs) { + errors.addAll(param.checkSemantics(ST, _nesting)); + } + + return errors; + } + + public int getSize() { + return exprs.size(); + } + + public Node getElem(int i) { + return exprs.get(i); + } + + @Override + public Type typeCheck() { + return new VoidType(); + } + + // TODO: code generation for expr list + @Override + public String codeGeneration() { + return ""; + } + + @Override + public String toPrint(String prefix) { + String str = prefix + "Paramlist\n"; + + prefix += " "; + for (var param : exprs) { + str += param.toPrint(prefix); + } + + return str; + } + +} diff --git a/src/ast/nodes/ForStmtNode.java b/src/ast/nodes/ForStmtNode.java index 28fe783..610d0a0 100644 --- a/src/ast/nodes/ForStmtNode.java +++ b/src/ast/nodes/ForStmtNode.java @@ -1,20 +1,20 @@ package ast.nodes; +import ast.types.*; import java.util.ArrayList; - import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; -import ast.types.*; /** * Node for the `for_stmt` statement of the grammar. */ public class ForStmtNode implements Node { - private Node exprList; + + private ExprListNode exprList; private Node block; public ForStmtNode(Node exprList, Node block) { - this.exprList = exprList; + this.exprList = (ExprListNode) exprList; this.block = block; } @@ -22,9 +22,7 @@ public class ForStmtNode implements Node { public ArrayList checkSemantics(SymbolTable ST, int _nesting) { ArrayList errors = new ArrayList(); - ExprNode expr = (ExprNode) exprList; - - ST.insert(expr.getId(), expr.typeCheck(), _nesting, ""); + // ST.insert(expr.getId(), expr.typeCheck(s), _nesting, ""); errors.addAll(exprList.checkSemantics(ST, _nesting)); errors.addAll(block.checkSemantics(ST, _nesting)); diff --git a/src/ast/nodes/ParamdefNode.java b/src/ast/nodes/ParamdefNode.java index 5164537..adadf72 100644 --- a/src/ast/nodes/ParamdefNode.java +++ b/src/ast/nodes/ParamdefNode.java @@ -12,7 +12,7 @@ import semanticanalysis.SymbolTable; public class ParamdefNode extends AtomNode { public ParamdefNode(String val) { - super(val); + super(val, null); } @Override diff --git a/src/ast/nodes/TestlistCompNode.java b/src/ast/nodes/TestlistCompNode.java new file mode 100644 index 0000000..070b1a1 --- /dev/null +++ b/src/ast/nodes/TestlistCompNode.java @@ -0,0 +1,61 @@ +package ast.nodes; + +import ast.types.*; +import java.util.ArrayList; +import semanticanalysis.SemanticError; +import semanticanalysis.SymbolTable; + +/** + * Node for the `testlist_comp` statement of the grammar. + */ +public class TestlistCompNode implements Node { + + private final ArrayList exprs; + + public TestlistCompNode(ArrayList _exprs) { + this.exprs = _exprs; + } + + @Override + public ArrayList checkSemantics(SymbolTable ST, int _nesting) { + ArrayList errors = new ArrayList(); + + for (var param : exprs) { + errors.addAll(param.checkSemantics(ST, _nesting)); + } + + return errors; + } + + public int getSize() { + return exprs.size(); + } + + public Node getElem(int i) { + return exprs.get(i); + } + + @Override + public Type typeCheck() { + return new VoidType(); + } + + // TODO: code generation for expr list + @Override + public String codeGeneration() { + return ""; + } + + @Override + public String toPrint(String prefix) { + String str = prefix + "Testlist_comp\n"; + + prefix += " "; + for (var param : exprs) { + str += param.toPrint(prefix); + } + + return str; + } + +} -- cgit v1.2.3-18-g5258 From 4898724edf343650ffb80792caf9e242e5843059 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Thu, 27 Jun 2024 19:47:05 +0200 Subject: Fix `for` loop for 1+ params --- src/ast/nodes/ExprListNode.java | 8 ++++---- src/ast/nodes/ExprNode.java | 11 ++++++++++- src/ast/nodes/ForStmtNode.java | 14 +++++++++++--- 3 files changed, 25 insertions(+), 8 deletions(-) (limited to 'src/ast') diff --git a/src/ast/nodes/ExprListNode.java b/src/ast/nodes/ExprListNode.java index c1a2ebc..acdf679 100644 --- a/src/ast/nodes/ExprListNode.java +++ b/src/ast/nodes/ExprListNode.java @@ -12,16 +12,16 @@ public class ExprListNode implements Node { private final ArrayList exprs; - public ExprListNode(ArrayList _exprs) { - this.exprs = _exprs; + public ExprListNode(ArrayList exprs) { + this.exprs = exprs; } @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { ArrayList errors = new ArrayList(); - for (var param : exprs) { - errors.addAll(param.checkSemantics(ST, _nesting)); + for (var expr : exprs) { + errors.addAll(expr.checkSemantics(ST, _nesting)); } return errors; diff --git a/src/ast/nodes/ExprNode.java b/src/ast/nodes/ExprNode.java index 62b3a94..781cc76 100644 --- a/src/ast/nodes/ExprNode.java +++ b/src/ast/nodes/ExprNode.java @@ -26,6 +26,14 @@ public class ExprNode implements Node { this.trailers = trailers; } + public Node getExpr(int i) { + if (i >= this.exprs.size()) { + return null; + } + + return this.exprs.get(i); + } + public String getId() { if (atom != null) { return ((AtomNode) this.atom).getId(); @@ -67,7 +75,8 @@ public class ExprNode implements Node { int argNumber = trailer.getArgumentNumber(); if (paramNumber != argNumber) { - errors.add(new SemanticError(funName + "() takes " + String.valueOf(paramNumber) + " positional arguments but " + String.valueOf(argNumber) + " were given.")); + errors.add(new SemanticError(funName + "() takes " + String.valueOf(paramNumber) + + " positional arguments but " + String.valueOf(argNumber) + " were given.")); } } } diff --git a/src/ast/nodes/ForStmtNode.java b/src/ast/nodes/ForStmtNode.java index 610d0a0..c5301ee 100644 --- a/src/ast/nodes/ForStmtNode.java +++ b/src/ast/nodes/ForStmtNode.java @@ -10,11 +10,11 @@ import semanticanalysis.SymbolTable; */ public class ForStmtNode implements Node { - private ExprListNode exprList; + private Node exprList; private Node block; public ForStmtNode(Node exprList, Node block) { - this.exprList = (ExprListNode) exprList; + this.exprList = exprList; this.block = block; } @@ -22,7 +22,15 @@ public class ForStmtNode implements Node { public ArrayList checkSemantics(SymbolTable ST, int _nesting) { ArrayList errors = new ArrayList(); - // ST.insert(expr.getId(), expr.typeCheck(s), _nesting, ""); + var l = (ExprListNode) exprList; + for (int i = 0; i < l.getSize() - 1; ++i) { + var e = (ExprNode) l.getElem(i); + ST.insert(e.getId(), e.typeCheck(), _nesting, ""); + } + + var left = (ExprNode) l.getElem(l.getSize() - 1); + var atomLeft = (ExprNode) left.getExpr(0); + ST.insert(atomLeft.getId(), atomLeft.typeCheck(), _nesting, ""); errors.addAll(exprList.checkSemantics(ST, _nesting)); errors.addAll(block.checkSemantics(ST, _nesting)); -- cgit v1.2.3-18-g5258 From fd85e9980c0305c6dfb91aaeb199430a89163c3e Mon Sep 17 00:00:00 2001 From: geno Date: Thu, 27 Jun 2024 20:49:56 +0200 Subject: fixed comp_for and added reseved word type --- src/ast/Python3VisitorImpl.java | 44 +++++++++++++++++++++++++-- src/ast/nodes/ArglistNode.java | 38 ++++++++++++----------- src/ast/nodes/AtomNode.java | 13 +++++--- src/ast/nodes/CompForNode.java | 59 ++++++++++++++++++++++++++++++++++++ src/ast/nodes/CompIterNode.java | 50 ++++++++++++++++++++++++++++++ src/ast/nodes/TestlistCompNode.java | 19 +++++++++--- src/ast/types/ContinueBreakType.java | 10 ------ src/ast/types/NoneType.java | 16 ++++++++++ src/ast/types/ReservedWordsType.java | 10 ++++++ 9 files changed, 221 insertions(+), 38 deletions(-) create mode 100644 src/ast/nodes/CompForNode.java create mode 100644 src/ast/nodes/CompIterNode.java delete mode 100644 src/ast/types/ContinueBreakType.java create mode 100644 src/ast/types/NoneType.java create mode 100644 src/ast/types/ReservedWordsType.java (limited to 'src/ast') diff --git a/src/ast/Python3VisitorImpl.java b/src/ast/Python3VisitorImpl.java index 5b812ea..c5f1bfa 100644 --- a/src/ast/Python3VisitorImpl.java +++ b/src/ast/Python3VisitorImpl.java @@ -434,6 +434,8 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { Testlist_compContext tlc = ctx.testlist_comp(); if (ctx.NUMBER() != null) { return new AtomNode(ctx.NUMBER().toString(), null); + } else if (ctx.NONE() != null) { + return new AtomNode(ctx.NONE().toString(), null); } else if (ctx.TRUE() != null) { return new AtomNode(ctx.TRUE().toString(), null); } else if (ctx.FALSE() != null) { @@ -453,7 +455,7 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { } else if (ctx.OPEN_PAREN() != null && ctx.CLOSE_PAREN() != null) { return manageTlc(tlc); } - return new AtomNode(ctx.NONE().toString(), null); + return new AtomNode(null, null); } public AtomNode manageTlc(Testlist_compContext tlc) { @@ -533,7 +535,45 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { for (ExprContext c : ctx.expr()) { exprlist.add(visit(c)); } + Comp_forContext cfc = ctx.comp_for(); + if (cfc != null) { + Node comp = visit(ctx.comp_for()); + return new TestlistCompNode(exprlist, comp); + } + return new TestlistCompNode(exprlist, null); + } + + /** + * Returns a `CompForNode`. + * + * ``` comp_for : 'for' exprlist 'in' expr comp_iter? ;``` + */ + public Node visitComp_for(Comp_forContext ctx) { + Node exprlist = visit(ctx.exprlist()); + Node expr = visit(ctx.expr()); + Comp_iterContext cic = ctx.comp_iter(); - return new TestlistCompNode(exprlist); + if (cic != null) { + Node comp = visit(ctx.comp_iter()); + return new CompForNode(exprlist, expr, comp); + } + return new CompForNode(exprlist, expr, null); + } + + /** + * Returns a `CompIterNode`. + * + * ``` comp_iter : comp_for | comp_if ; ;``` + */ + public Node visitComp_iter(Comp_iterContext ctx) { + // TODO: Implement comp_if + // Node iter = visit(ctx.comp_if()); + Comp_forContext cfc = ctx.comp_for(); + if (cfc != null) { + Node forNode = visit(ctx.comp_for()); + return new CompIterNode(forNode); + + } + return new CompIterNode(null); } } diff --git a/src/ast/nodes/ArglistNode.java b/src/ast/nodes/ArglistNode.java index 983d150..c29a4e0 100644 --- a/src/ast/nodes/ArglistNode.java +++ b/src/ast/nodes/ArglistNode.java @@ -22,25 +22,27 @@ public class ArglistNode implements Node { ArrayList errors = new ArrayList(); for (var arg : arguments) { - ExprNode argExpr = (ExprNode) arg; - String argName = argExpr.getId(); - - // TODO: check fucking IntType for params - // TODO: remove fucking comments - if (argName != null) { - if (Arrays.asList(bif).contains(argName)) { - continue; + if (arg instanceof ExprNode) { + ExprNode argExpr = (ExprNode) arg; + String argName = argExpr.getId(); + + // TODO: check fucking IntType for params + // TODO: remove fucking comments + if (argName != null) { + if (Arrays.asList(bif).contains(argName)) { + continue; + } + + if (ST.lookup(argName) != null && ST.lookup(argName).getType() instanceof ImportType) { + continue; + } + + if (ST.nslookup(argName) < 0 && argExpr.typeCheck() instanceof AtomType) { + errors.add(new SemanticError("name '" + argName + "' is not defined.")); + } + } else { + errors.addAll(arg.checkSemantics(ST, _nesting)); } - - if (ST.lookup(argName) != null && ST.lookup(argName).getType() instanceof ImportType) { - continue; - } - - if (ST.nslookup(argName) < 0 && argExpr.typeCheck() instanceof AtomType) { - errors.add(new SemanticError("name '" + argName + "' is not defined.")); - } - } else { - errors.addAll(arg.checkSemantics(ST, _nesting)); } } diff --git a/src/ast/nodes/AtomNode.java b/src/ast/nodes/AtomNode.java index 592aac4..16281d6 100644 --- a/src/ast/nodes/AtomNode.java +++ b/src/ast/nodes/AtomNode.java @@ -50,23 +50,28 @@ public class AtomNode implements Node { return new VoidType(); } + Pattern noneVariable = Pattern.compile("^(None)$"); Pattern booleanVariable = Pattern.compile("^(True|False)$"); - Pattern continueBreakVariable = Pattern.compile("^(continue|break)$"); + Pattern reservedWords = Pattern.compile("^(continue|break|int|float)$"); // this regex should match every possible atom name written in this format: CHAR (CHAR | DIGIT)* Pattern simpleVariable = Pattern.compile("^[a-zA-Z][a-zA-Z0-9]*$", Pattern.CASE_INSENSITIVE); + Matcher noneVariableMatcher = noneVariable.matcher(this.val); Matcher booleanVariableMatcher = booleanVariable.matcher(this.val); - Matcher continueBreakVariableMatcher = continueBreakVariable.matcher(this.val); + Matcher reservedWordsMatcher = reservedWords.matcher(this.val); Matcher simpleVariableMatcher = simpleVariable.matcher(this.val); + boolean matchFoundNone = noneVariableMatcher.find(); boolean matchFoundBoolean = booleanVariableMatcher.find(); - boolean matchFoundContinueBreak = continueBreakVariableMatcher.find(); + boolean matchFoundContinueBreak = reservedWordsMatcher.find(); boolean matchFoundSimpleVariable = simpleVariableMatcher.find(); if (matchFoundBoolean) { return new BoolType(); } else if (matchFoundContinueBreak) { - return new ContinueBreakType(); + return new ReservedWordsType(); + } else if (matchFoundNone) { + return new NoneType(); } else if (matchFoundSimpleVariable) { return new AtomType(); // could be a variable or a fuction } else { diff --git a/src/ast/nodes/CompForNode.java b/src/ast/nodes/CompForNode.java new file mode 100644 index 0000000..d5c50d6 --- /dev/null +++ b/src/ast/nodes/CompForNode.java @@ -0,0 +1,59 @@ +package ast.nodes; + +import ast.types.*; +import java.util.ArrayList; +import java.util.Arrays; +import semanticanalysis.SemanticError; +import semanticanalysis.SymbolTable; + +/** + * Node for the `comp_for` statement of the grammar. 'for' exprlist 'in' expr + * comp_iter? + */ +public class CompForNode implements Node { + + protected ExprListNode exprlist; + protected ExprNode single_expr; + protected CompIterNode comp_iter; + + public CompForNode(Node exprlist, Node single_expr, Node comp_iter) { + this.exprlist = (ExprListNode) exprlist; + this.single_expr = (ExprNode) single_expr; + this.comp_iter = (CompIterNode) comp_iter; + } + + @Override + public ArrayList checkSemantics(SymbolTable ST, int _nesting) { + ArrayList errors = new ArrayList(); + + errors.addAll(exprlist.checkSemantics(ST, _nesting)); + errors.addAll(single_expr.checkSemantics(ST, _nesting)); + if (comp_iter != null) { + errors.addAll(comp_iter.checkSemantics(ST, _nesting)); + } + return errors; + } + + @Override + public Type typeCheck() { + return new VoidType(); + } + + // TODO: add code generation for arglist node + @Override + public String codeGeneration() { + return ""; + } + + @Override + public String toPrint(String prefix) { + String str = prefix + "CompForNode\n"; + + prefix += " "; + str += exprlist.toPrint(prefix); + str += single_expr.toPrint(prefix); + str += comp_iter.toPrint(prefix); + return str; + } + +} diff --git a/src/ast/nodes/CompIterNode.java b/src/ast/nodes/CompIterNode.java new file mode 100644 index 0000000..6704bd7 --- /dev/null +++ b/src/ast/nodes/CompIterNode.java @@ -0,0 +1,50 @@ +package ast.nodes; + +import ast.types.*; +import java.util.ArrayList; +import semanticanalysis.SemanticError; +import semanticanalysis.SymbolTable; + +/** + * Node for the `comp_iter` statement of the grammar. + */ +public class CompIterNode implements Node { + + protected CompForNode comp_for; + // protected CompIfNode compIfNode; + + public CompIterNode(Node comp_for) { + this.comp_for = (CompForNode) comp_for; + } + + @Override + public ArrayList checkSemantics(SymbolTable ST, int _nesting) { + ArrayList errors = new ArrayList(); + + if (comp_for != null) { + errors.addAll(comp_for.checkSemantics(ST, _nesting)); + } + return errors; + } + + @Override + public Type typeCheck() { + return new VoidType(); + } + + // TODO: add code generation for arglist node + @Override + public String codeGeneration() { + return ""; + } + + @Override + public String toPrint(String prefix) { + String str = prefix + "CompIterNode\n"; + + prefix += " "; + str += comp_for.toPrint(prefix); + return str; + } + +} diff --git a/src/ast/nodes/TestlistCompNode.java b/src/ast/nodes/TestlistCompNode.java index 070b1a1..bcaca83 100644 --- a/src/ast/nodes/TestlistCompNode.java +++ b/src/ast/nodes/TestlistCompNode.java @@ -11,17 +11,28 @@ import semanticanalysis.SymbolTable; public class TestlistCompNode implements Node { private final ArrayList exprs; + private final CompForNode comp; - public TestlistCompNode(ArrayList _exprs) { - this.exprs = _exprs; + public TestlistCompNode(ArrayList exprs, Node comp) { + this.exprs = exprs; + this.comp = (CompForNode) comp; } @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { ArrayList errors = new ArrayList(); - for (var param : exprs) { - errors.addAll(param.checkSemantics(ST, _nesting)); + if (comp != null) { + // if comp is set, then we save the atom in the ST (we assume the first expr is an atom) + String id = ((ExprNode) exprs.get(0)).getId(); + Type t = ((ExprNode) exprs.get(0)).typeCheck(); + ST.insert(id, t, _nesting, ""); + // errors.addAll(comp.checkSemantics(ST, _nesting)); + } else { + // if comp is not set, then exprs is a list of 1 or more element + for (var param : exprs) { + errors.addAll(param.checkSemantics(ST, _nesting)); + } } return errors; diff --git a/src/ast/types/ContinueBreakType.java b/src/ast/types/ContinueBreakType.java deleted file mode 100644 index dfcf1f2..0000000 --- a/src/ast/types/ContinueBreakType.java +++ /dev/null @@ -1,10 +0,0 @@ -package ast.types; - -/** - * A type for the continue and break statements. - */ -public class ContinueBreakType extends Type { - public String toPrint(String prefix) { - return prefix + "ContinueBreak\n"; - } -} diff --git a/src/ast/types/NoneType.java b/src/ast/types/NoneType.java new file mode 100644 index 0000000..42f7fd7 --- /dev/null +++ b/src/ast/types/NoneType.java @@ -0,0 +1,16 @@ +package ast.types; + +/** + * A none type. None return unit. + */ +public class NoneType extends Type { + + public String toPrint(String prefix) { + return prefix + "None\n"; + } + + @Override + public String toString() { + return "None"; + } +} diff --git a/src/ast/types/ReservedWordsType.java b/src/ast/types/ReservedWordsType.java new file mode 100644 index 0000000..f5f7ac5 --- /dev/null +++ b/src/ast/types/ReservedWordsType.java @@ -0,0 +1,10 @@ +package ast.types; + +/** + * A type for the continue and break statements. + */ +public class ReservedWordsType extends Type { + public String toPrint(String prefix) { + return prefix + "ReservedWords\n"; + } +} -- cgit v1.2.3-18-g5258 From 4516c901ccbabfba9115c87237996dc9acdc7590 Mon Sep 17 00:00:00 2001 From: geno Date: Thu, 27 Jun 2024 20:58:29 +0200 Subject: fix additional useless errors --- src/ast/nodes/AssignmentNode.java | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) (limited to 'src/ast') diff --git a/src/ast/nodes/AssignmentNode.java b/src/ast/nodes/AssignmentNode.java index 07966c3..35c47b3 100644 --- a/src/ast/nodes/AssignmentNode.java +++ b/src/ast/nodes/AssignmentNode.java @@ -31,15 +31,16 @@ public class AssignmentNode implements Node { int lsize = lhr.getSize(); int rsize = rhr.getSize(); - if (lsize == rsize) { - for (int i = 0; i < lsize; i++) { - ExprNode latom = (ExprNode) lhr.getElem(i); - ExprNode ratom = (ExprNode) rhr.getElem(i); - ST.insert(latom.getId(), ratom.typeCheck(), _nesting, ""); - } - } else { - errors.add(new SemanticError("ValueError: different size of left or right side assignment")); + // if (lsize == rsize) { + for (int i = 0; i < lsize; i++) { + ExprNode latom = (ExprNode) lhr.getElem(i); + ST.insert(latom.getId(), new AtomType(), _nesting, ""); + // ExprNode ratom = (ExprNode) rhr.getElem(i); } + // } else { + // FIX: sgravata da più problemi che altro + // errors.add(new SemanticError("ValueError: different size of left or right side assignment")); + // } return errors; } -- cgit v1.2.3-18-g5258 From 3f29e5101d9c6e670dd05715297f2060707dc6c7 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Thu, 27 Jun 2024 22:18:55 +0200 Subject: Fix trailer with parentheeses `for (key, val) in ...` Resolves test `a228.py` --- src/ast/nodes/TestlistCompNode.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'src/ast') diff --git a/src/ast/nodes/TestlistCompNode.java b/src/ast/nodes/TestlistCompNode.java index bcaca83..4ae77c9 100644 --- a/src/ast/nodes/TestlistCompNode.java +++ b/src/ast/nodes/TestlistCompNode.java @@ -23,7 +23,8 @@ public class TestlistCompNode implements Node { ArrayList errors = new ArrayList(); if (comp != null) { - // if comp is set, then we save the atom in the ST (we assume the first expr is an atom) + // if comp is set, then we save the atom in the ST (we assume the first expr is + // an atom) String id = ((ExprNode) exprs.get(0)).getId(); Type t = ((ExprNode) exprs.get(0)).typeCheck(); ST.insert(id, t, _nesting, ""); @@ -31,6 +32,8 @@ public class TestlistCompNode implements Node { } else { // if comp is not set, then exprs is a list of 1 or more element for (var param : exprs) { + var exp = (ExprNode) param; + ST.insert(exp.getId(), exp.typeCheck(), _nesting, ""); errors.addAll(param.checkSemantics(ST, _nesting)); } } -- cgit v1.2.3-18-g5258 From 259580d38338ef53e6f98b2b279d1d4aa8ecff04 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Thu, 27 Jun 2024 22:24:43 +0200 Subject: Remove semantic error for `'x' is not a function` It's useless --- src/ast/nodes/ExprNode.java | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) (limited to 'src/ast') diff --git a/src/ast/nodes/ExprNode.java b/src/ast/nodes/ExprNode.java index 781cc76..591ee37 100644 --- a/src/ast/nodes/ExprNode.java +++ b/src/ast/nodes/ExprNode.java @@ -62,12 +62,8 @@ public class ExprNode implements Node { if (fun != null && !(fun.getType() instanceof ImportType)) { if (!(fun.getType() instanceof FunctionType)) { - if (trailer.isParenthesis()) { - errors.add(new SemanticError("'" + funName + "' is not a function.")); - } else { - for (var t : trailers) { - errors.addAll(t.checkSemantics(ST, _nesting)); - } + for (var t : trailers) { + errors.addAll(t.checkSemantics(ST, _nesting)); } } else { FunctionType ft = (FunctionType) fun.getType(); -- cgit v1.2.3-18-g5258 From d653d3598d71fea30d45d118e3d046a3aed53ac1 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Thu, 27 Jun 2024 22:39:22 +0200 Subject: Uncommented test files --- src/ast/nodes/AtomNode.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src/ast') diff --git a/src/ast/nodes/AtomNode.java b/src/ast/nodes/AtomNode.java index 16281d6..cea617f 100644 --- a/src/ast/nodes/AtomNode.java +++ b/src/ast/nodes/AtomNode.java @@ -53,7 +53,8 @@ public class AtomNode implements Node { Pattern noneVariable = Pattern.compile("^(None)$"); Pattern booleanVariable = Pattern.compile("^(True|False)$"); Pattern reservedWords = Pattern.compile("^(continue|break|int|float)$"); - // this regex should match every possible atom name written in this format: CHAR (CHAR | DIGIT)* + // this regex should match every possible atom name written in this format: CHAR + // (CHAR | DIGIT)* Pattern simpleVariable = Pattern.compile("^[a-zA-Z][a-zA-Z0-9]*$", Pattern.CASE_INSENSITIVE); Matcher noneVariableMatcher = noneVariable.matcher(this.val); @@ -87,6 +88,7 @@ public class AtomNode implements Node { @Override public String toPrint(String prefix) { + // FIXME: can be a testlist_comp with two expr and two atoms if (val != null) { return prefix + "Atom(" + val + ")\n"; } -- cgit v1.2.3-18-g5258 From 089787db950056a35eb1a5930b5b919c45523863 Mon Sep 17 00:00:00 2001 From: Geno <48206120+gabrielegenovese@users.noreply.github.com> Date: Fri, 28 Jun 2024 11:20:17 +0200 Subject: Update src/ast/Python3VisitorImpl.java suggested by santo Co-authored-by: Santo Cariotti --- src/ast/Python3VisitorImpl.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src/ast') diff --git a/src/ast/Python3VisitorImpl.java b/src/ast/Python3VisitorImpl.java index c5f1bfa..bef75cf 100644 --- a/src/ast/Python3VisitorImpl.java +++ b/src/ast/Python3VisitorImpl.java @@ -536,11 +536,11 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { exprlist.add(visit(c)); } Comp_forContext cfc = ctx.comp_for(); + Node comp = null; if (cfc != null) { - Node comp = visit(ctx.comp_for()); - return new TestlistCompNode(exprlist, comp); + comp = visit(ctx.comp_for()); } - return new TestlistCompNode(exprlist, null); + return new TestlistCompNode(exprlist, comp); } /** -- cgit v1.2.3-18-g5258 From 1d5c4862e136419ab1ed3fcf8d8edaa0ee5fda10 Mon Sep 17 00:00:00 2001 From: Geno <48206120+gabrielegenovese@users.noreply.github.com> Date: Fri, 28 Jun 2024 11:21:12 +0200 Subject: Update src/ast/Python3VisitorImpl.java suggested by santo Co-authored-by: Santo Cariotti --- src/ast/Python3VisitorImpl.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) (limited to 'src/ast') diff --git a/src/ast/Python3VisitorImpl.java b/src/ast/Python3VisitorImpl.java index bef75cf..42e2537 100644 --- a/src/ast/Python3VisitorImpl.java +++ b/src/ast/Python3VisitorImpl.java @@ -569,11 +569,10 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { // TODO: Implement comp_if // Node iter = visit(ctx.comp_if()); Comp_forContext cfc = ctx.comp_for(); + Node forNode = null; if (cfc != null) { - Node forNode = visit(ctx.comp_for()); - return new CompIterNode(forNode); - + forNode = visit(ctx.comp_for()); } - return new CompIterNode(null); + return new CompIterNode(forNode); } } -- cgit v1.2.3-18-g5258 From 37665fb6d0bc1eb29396ae949354cf7d6f9d54ca Mon Sep 17 00:00:00 2001 From: geno Date: Fri, 28 Jun 2024 12:23:28 +0200 Subject: resolving all the comments santo made --- src/ast/Python3VisitorImpl.java | 19 +++++++++++-------- src/ast/nodes/AtomNode.java | 4 ++++ src/ast/nodes/ExprListNode.java | 9 ++++++++- src/ast/nodes/ExprNode.java | 14 ++++++++++++-- src/ast/nodes/ForStmtNode.java | 20 ++++++++++++++++++++ src/ast/nodes/TestlistCompNode.java | 11 +++++++++-- src/ast/types/FunctionType.java | 9 +++++---- 7 files changed, 69 insertions(+), 17 deletions(-) (limited to 'src/ast') diff --git a/src/ast/Python3VisitorImpl.java b/src/ast/Python3VisitorImpl.java index 42e2537..1cf15b7 100644 --- a/src/ast/Python3VisitorImpl.java +++ b/src/ast/Python3VisitorImpl.java @@ -424,7 +424,7 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { } /** - * Returns an `AtomNode`. FIXME: add support for testlist_comp + * Returns an `AtomNode`. * * ``` atom : '(' testlist_comp? ')' | '[' testlist_comp? ']' | '{' * testlist_comp? '}' | NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | @@ -449,22 +449,26 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { } return new AtomNode(varName, null); } else if (ctx.OPEN_BRACE() != null && ctx.CLOSE_BRACE() != null) { - return manageTlc(tlc); + return manageCompListContext(tlc); } else if (ctx.OPEN_BRACK() != null && ctx.CLOSE_BRACK() != null) { - return manageTlc(tlc); + return manageCompListContext(tlc); } else if (ctx.OPEN_PAREN() != null && ctx.CLOSE_PAREN() != null) { - return manageTlc(tlc); + return manageCompListContext(tlc); } return new AtomNode(null, null); } - public AtomNode manageTlc(Testlist_compContext tlc) { + /** + * Supporting function for `visitAtom`. Returns an `AtomNode` with + * `testlist_comp` set if the context is not null. Otherwise, returns an + * `AtomNode` with nulls. + */ + public AtomNode manageCompListContext(Testlist_compContext tlc) { if (tlc != null) { Node testlist_comp = visit(tlc); return new AtomNode(null, testlist_comp); - } else { - return new AtomNode(null, null); } + return new AtomNode(null, null); } /** @@ -529,7 +533,6 @@ public class Python3VisitorImpl extends Python3ParserBaseVisitor { * ``` testlist_comp : expr (comp_for | (',' expr)* ','?) ; ``` */ public Node visitTestlist_comp(Testlist_compContext ctx) { - // TODO: implement comp_for ArrayList exprlist = new ArrayList(); for (ExprContext c : ctx.expr()) { diff --git a/src/ast/nodes/AtomNode.java b/src/ast/nodes/AtomNode.java index cea617f..fef72ec 100644 --- a/src/ast/nodes/AtomNode.java +++ b/src/ast/nodes/AtomNode.java @@ -20,6 +20,10 @@ public class AtomNode implements Node { this.exprlist = (TestlistCompNode) exprlist; } + /** + * Returns the identifier of the `AtomNode` if it's not `null`, otherwise + * returns `null`. + */ public String getId() { return this.val; } diff --git a/src/ast/nodes/ExprListNode.java b/src/ast/nodes/ExprListNode.java index acdf679..800f4be 100644 --- a/src/ast/nodes/ExprListNode.java +++ b/src/ast/nodes/ExprListNode.java @@ -31,7 +31,14 @@ public class ExprListNode implements Node { return exprs.size(); } + /** + * Returns the i-th expressions of `exprs` field. If the index is greater or + * equals than the size return `null`. + */ public Node getElem(int i) { + if (i >= this.exprs.size()) { + return null; + } return exprs.get(i); } @@ -48,7 +55,7 @@ public class ExprListNode implements Node { @Override public String toPrint(String prefix) { - String str = prefix + "Paramlist\n"; + String str = prefix + "ExprList\n"; prefix += " "; for (var param : exprs) { diff --git a/src/ast/nodes/ExprNode.java b/src/ast/nodes/ExprNode.java index 591ee37..8e3b896 100644 --- a/src/ast/nodes/ExprNode.java +++ b/src/ast/nodes/ExprNode.java @@ -26,6 +26,10 @@ public class ExprNode implements Node { this.trailers = trailers; } + /** + * Returns the i-th expressions of `exprs` field. If the index is greater or + * equals than the size return `null`. + */ public Node getExpr(int i) { if (i >= this.exprs.size()) { return null; @@ -34,6 +38,10 @@ public class ExprNode implements Node { return this.exprs.get(i); } + /** + * Returns the identifier of the `AtomNode` if it's not `null`, otherwise + * returns `null`. + */ public String getId() { if (atom != null) { return ((AtomNode) this.atom).getId(); @@ -65,6 +73,7 @@ public class ExprNode implements Node { for (var t : trailers) { errors.addAll(t.checkSemantics(ST, _nesting)); } + } else { FunctionType ft = (FunctionType) fun.getType(); int paramNumber = ft.getParamNumber(); @@ -80,6 +89,7 @@ public class ExprNode implements Node { for (var trailer : trailers) { errors.addAll(trailer.checkSemantics(ST, _nesting)); } + } } else if (atom != null) { errors.addAll(atom.checkSemantics(ST, _nesting)); @@ -126,11 +136,11 @@ public class ExprNode implements Node { } for (var expr : exprs) { - str += expr.toPrint(prefix); + str = expr.toPrint(prefix); } for (var trailer : trailers) { - str += trailer.toPrint(prefix); + str = trailer.toPrint(prefix); } if (op != null) { diff --git a/src/ast/nodes/ForStmtNode.java b/src/ast/nodes/ForStmtNode.java index c5301ee..d4c5e56 100644 --- a/src/ast/nodes/ForStmtNode.java +++ b/src/ast/nodes/ForStmtNode.java @@ -18,18 +18,38 @@ public class ForStmtNode implements Node { this.block = block; } + /** + * This methods check the semantics of the operation `for i in list: block`. + * + * After the `for` keyword, it's parsed as a list of expression. We verified + * that the last expression is always gonna be `expr comp_op expr`. We + * comp_op must be the `in` keyword. `i` could be of any lenght (e.g. `a, b, + * c`). + * + * In this function we define the following approch: we save in the + * SymbolTable every atom until the last expression in the expression's + * list. For the last element, we know that is in the `expr comp_op expr` + * format, so we take the left element and save it in the SymbolicTable as + * an atom. + */ @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { ArrayList errors = new ArrayList(); + // Save every atom in the expression's list, except the last one var l = (ExprListNode) exprList; for (int i = 0; i < l.getSize() - 1; ++i) { var e = (ExprNode) l.getElem(i); ST.insert(e.getId(), e.typeCheck(), _nesting, ""); } + // Manage the last expression of expression's list + // Get the ExprNode var left = (ExprNode) l.getElem(l.getSize() - 1); + // Get the left side expression of the operation, that + // corresponds to the first element of the expression list. var atomLeft = (ExprNode) left.getExpr(0); + // ENHANCE: check that the comp_op is the `in` keyword ST.insert(atomLeft.getId(), atomLeft.typeCheck(), _nesting, ""); errors.addAll(exprList.checkSemantics(ST, _nesting)); diff --git a/src/ast/nodes/TestlistCompNode.java b/src/ast/nodes/TestlistCompNode.java index 4ae77c9..244f4ef 100644 --- a/src/ast/nodes/TestlistCompNode.java +++ b/src/ast/nodes/TestlistCompNode.java @@ -10,8 +10,8 @@ import semanticanalysis.SymbolTable; */ public class TestlistCompNode implements Node { - private final ArrayList exprs; - private final CompForNode comp; + private ArrayList exprs; + private CompForNode comp; public TestlistCompNode(ArrayList exprs, Node comp) { this.exprs = exprs; @@ -45,7 +45,14 @@ public class TestlistCompNode implements Node { return exprs.size(); } + /** + * Returns the i-th expressions of `exprs` field. If the index is greater or + * equals than the size return `null`. + */ public Node getElem(int i) { + if (i >= this.exprs.size()) { + return null; + } return exprs.get(i); } diff --git a/src/ast/types/FunctionType.java b/src/ast/types/FunctionType.java index 464bb9c..ef50641 100644 --- a/src/ast/types/FunctionType.java +++ b/src/ast/types/FunctionType.java @@ -1,18 +1,19 @@ package ast.types; /** - * An tom type. TODO: do I need to use this one? + * A Function type. */ public class FunctionType extends Type { - private final int paramNumber; - private final Type returnType; + private int paramNumber; + private Type returnType; public FunctionType(int paramNumber, Type returnType) { this.paramNumber = paramNumber; this.returnType = returnType; } + // Return the length of the parameters public int getParamNumber() { return paramNumber; } @@ -22,6 +23,6 @@ public class FunctionType extends Type { } public String toPrint(String prefix) { - return prefix + "Atom\n"; + return prefix + "Function\n"; } } -- cgit v1.2.3-18-g5258 From aaa97e2e41c0aa17a6f99099dd39bb73a935fe02 Mon Sep 17 00:00:00 2001 From: L0P0P Date: Sat, 29 Jun 2024 09:54:08 +0200 Subject: Fixed some warnings --- src/ast/nodes/AssignmentNode.java | 4 +++- src/ast/nodes/CompForNode.java | 1 - src/ast/nodes/ExprListNode.java | 2 +- src/ast/nodes/TestlistCompNode.java | 2 +- 4 files changed, 5 insertions(+), 4 deletions(-) (limited to 'src/ast') diff --git a/src/ast/nodes/AssignmentNode.java b/src/ast/nodes/AssignmentNode.java index 35c47b3..74d7283 100644 --- a/src/ast/nodes/AssignmentNode.java +++ b/src/ast/nodes/AssignmentNode.java @@ -29,7 +29,9 @@ public class AssignmentNode implements Node { errors.addAll(rhr.checkSemantics(ST, _nesting)); int lsize = lhr.getSize(); - int rsize = rhr.getSize(); + + // FIXME: unused variable + // int rsize = rhr.getSize(); // if (lsize == rsize) { for (int i = 0; i < lsize; i++) { diff --git a/src/ast/nodes/CompForNode.java b/src/ast/nodes/CompForNode.java index d5c50d6..06c7aee 100644 --- a/src/ast/nodes/CompForNode.java +++ b/src/ast/nodes/CompForNode.java @@ -2,7 +2,6 @@ package ast.nodes; import ast.types.*; import java.util.ArrayList; -import java.util.Arrays; import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; diff --git a/src/ast/nodes/ExprListNode.java b/src/ast/nodes/ExprListNode.java index 800f4be..4760db8 100644 --- a/src/ast/nodes/ExprListNode.java +++ b/src/ast/nodes/ExprListNode.java @@ -18,7 +18,7 @@ public class ExprListNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - ArrayList errors = new ArrayList(); + ArrayList errors = new ArrayList<>(); for (var expr : exprs) { errors.addAll(expr.checkSemantics(ST, _nesting)); diff --git a/src/ast/nodes/TestlistCompNode.java b/src/ast/nodes/TestlistCompNode.java index 244f4ef..cba056c 100644 --- a/src/ast/nodes/TestlistCompNode.java +++ b/src/ast/nodes/TestlistCompNode.java @@ -20,7 +20,7 @@ public class TestlistCompNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - ArrayList errors = new ArrayList(); + ArrayList errors = new ArrayList<>(); if (comp != null) { // if comp is set, then we save the atom in the ST (we assume the first expr is -- cgit v1.2.3-18-g5258 From afff6a80cd58f7787efa1398f7c8cbdce8989323 Mon Sep 17 00:00:00 2001 From: geno Date: Sun, 30 Jun 2024 13:36:37 +0200 Subject: fixed warnings, better formatting, final added where possible --- src/ast/nodes/ArglistNode.java | 5 ++--- src/ast/nodes/AssignmentNode.java | 13 ++++++------- src/ast/nodes/AtomNode.java | 2 +- src/ast/nodes/AugassignNode.java | 5 +++-- src/ast/nodes/BlockNode.java | 10 ++++------ src/ast/nodes/CompForNode.java | 2 +- src/ast/nodes/CompIterNode.java | 2 +- src/ast/nodes/CompNode.java | 4 ++-- src/ast/nodes/CompoundNode.java | 10 +++++----- src/ast/nodes/DottedNameNode.java | 3 ++- src/ast/nodes/ExprNode.java | 12 ++++++------ src/ast/nodes/ForStmtNode.java | 6 +++--- src/ast/nodes/FuncdefNode.java | 11 ++++++----- src/ast/nodes/IfNode.java | 15 ++++++++------- src/ast/nodes/ImportNode.java | 19 ++++++++++--------- src/ast/nodes/Node.java | 10 ++++------ src/ast/nodes/ParamdefNode.java | 2 +- src/ast/nodes/ParamlistNode.java | 7 +++---- src/ast/nodes/ReturnStmtNode.java | 8 ++++---- src/ast/nodes/RootNode.java | 4 ++-- src/ast/nodes/SimpleStmtNode.java | 11 ++++++----- src/ast/nodes/SimpleStmtsNode.java | 5 +++-- src/ast/nodes/TestlistCompNode.java | 4 ++-- src/ast/nodes/TrailerNode.java | 14 +++++++------- src/ast/nodes/WhileStmtNode.java | 10 +++++----- src/ast/types/AtomType.java | 3 ++- src/ast/types/BoolType.java | 2 ++ src/ast/types/ErrorType.java | 2 ++ src/ast/types/FunctionType.java | 5 +++-- src/ast/types/ImportType.java | 3 ++- src/ast/types/IntType.java | 2 ++ src/ast/types/NoneType.java | 1 + src/ast/types/ReservedWordsType.java | 2 ++ src/ast/types/Type.java | 11 +++++------ src/ast/types/VoidType.java | 1 + 35 files changed, 119 insertions(+), 107 deletions(-) (limited to 'src/ast') diff --git a/src/ast/nodes/ArglistNode.java b/src/ast/nodes/ArglistNode.java index c29a4e0..55a568d 100644 --- a/src/ast/nodes/ArglistNode.java +++ b/src/ast/nodes/ArglistNode.java @@ -19,11 +19,10 @@ public class ArglistNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - ArrayList errors = new ArrayList(); + ArrayList errors = new ArrayList(); for (var arg : arguments) { - if (arg instanceof ExprNode) { - ExprNode argExpr = (ExprNode) arg; + if (arg instanceof ExprNode argExpr) { String argName = argExpr.getId(); // TODO: check fucking IntType for params diff --git a/src/ast/nodes/AssignmentNode.java b/src/ast/nodes/AssignmentNode.java index 74d7283..558e392 100644 --- a/src/ast/nodes/AssignmentNode.java +++ b/src/ast/nodes/AssignmentNode.java @@ -10,9 +10,9 @@ import semanticanalysis.SymbolTable; */ public class AssignmentNode implements Node { - private ExprListNode lhr; - private Node assign; - private ExprListNode rhr; + private final ExprListNode lhr; + private final Node assign; + private final ExprListNode rhr; public AssignmentNode(Node lhr, Node assign, Node rhr) { this.lhr = (ExprListNode) lhr; @@ -22,7 +22,7 @@ public class AssignmentNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - ArrayList errors = new ArrayList(); + ArrayList errors = new ArrayList(); // errors.addAll(lhr.checkSemantics(ST, _nesting)); errors.addAll(assign.checkSemantics(ST, _nesting)); @@ -32,7 +32,6 @@ public class AssignmentNode implements Node { // FIXME: unused variable // int rsize = rhr.getSize(); - // if (lsize == rsize) { for (int i = 0; i < lsize; i++) { ExprNode latom = (ExprNode) lhr.getElem(i); @@ -40,8 +39,8 @@ public class AssignmentNode implements Node { // ExprNode ratom = (ExprNode) rhr.getElem(i); } // } else { - // FIX: sgravata da più problemi che altro - // errors.add(new SemanticError("ValueError: different size of left or right side assignment")); + // FIX: sgravata da più problemi che altro + // errors.add(new SemanticError("ValueError: different size of left or right side assignment")); // } return errors; diff --git a/src/ast/nodes/AtomNode.java b/src/ast/nodes/AtomNode.java index fef72ec..47a15d7 100644 --- a/src/ast/nodes/AtomNode.java +++ b/src/ast/nodes/AtomNode.java @@ -30,7 +30,7 @@ public class AtomNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - var errors = new ArrayList(); + var errors = new ArrayList(); if (val != null) { if ((this.typeCheck() instanceof AtomType) && ST.nslookup(this.getId()) < 0) { diff --git a/src/ast/nodes/AugassignNode.java b/src/ast/nodes/AugassignNode.java index 629fbcd..7ced63e 100644 --- a/src/ast/nodes/AugassignNode.java +++ b/src/ast/nodes/AugassignNode.java @@ -12,7 +12,8 @@ import org.antlr.v4.runtime.tree.TerminalNode; * Node for the `augassign` statement of the grammar. */ public class AugassignNode implements Node { - private TerminalNode val; + + private final TerminalNode val; public AugassignNode(TerminalNode val) { this.val = val; @@ -20,7 +21,7 @@ public class AugassignNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - return new ArrayList(); + return new ArrayList(); } // FIXME: use the right type diff --git a/src/ast/nodes/BlockNode.java b/src/ast/nodes/BlockNode.java index a38b4ea..d9a151d 100644 --- a/src/ast/nodes/BlockNode.java +++ b/src/ast/nodes/BlockNode.java @@ -1,23 +1,22 @@ package ast.nodes; -import java.util.ArrayList; - import ast.types.*; +import java.util.ArrayList; import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; /** - * Node for `block` statement of the grammar. - * It extends the `RootNode`. + * Node for `block` statement of the grammar. It extends the `RootNode`. */ public class BlockNode extends RootNode { + public BlockNode(ArrayList childs) { super(childs); } @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - ArrayList errors = new ArrayList(); + ArrayList errors = new ArrayList(); // Check semantics for each child for (Node child : childs) { @@ -27,7 +26,6 @@ public class BlockNode extends RootNode { return errors; } - @Override public Type typeCheck() { return new VoidType(); diff --git a/src/ast/nodes/CompForNode.java b/src/ast/nodes/CompForNode.java index 06c7aee..b7c6924 100644 --- a/src/ast/nodes/CompForNode.java +++ b/src/ast/nodes/CompForNode.java @@ -23,7 +23,7 @@ public class CompForNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - ArrayList errors = new ArrayList(); + ArrayList errors = new ArrayList(); errors.addAll(exprlist.checkSemantics(ST, _nesting)); errors.addAll(single_expr.checkSemantics(ST, _nesting)); diff --git a/src/ast/nodes/CompIterNode.java b/src/ast/nodes/CompIterNode.java index 6704bd7..8de9f2f 100644 --- a/src/ast/nodes/CompIterNode.java +++ b/src/ast/nodes/CompIterNode.java @@ -19,7 +19,7 @@ public class CompIterNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - ArrayList errors = new ArrayList(); + ArrayList errors = new ArrayList(); if (comp_for != null) { errors.addAll(comp_for.checkSemantics(ST, _nesting)); diff --git a/src/ast/nodes/CompNode.java b/src/ast/nodes/CompNode.java index 8be6ea1..22906df 100644 --- a/src/ast/nodes/CompNode.java +++ b/src/ast/nodes/CompNode.java @@ -12,7 +12,7 @@ import org.antlr.v4.runtime.tree.TerminalNode; */ public class CompNode implements Node { - private TerminalNode op; + private final TerminalNode op; public CompNode(TerminalNode op) { this.op = op; @@ -20,7 +20,7 @@ public class CompNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - return new ArrayList(); + return new ArrayList(); } // TODO: it should be boolean, right? diff --git a/src/ast/nodes/CompoundNode.java b/src/ast/nodes/CompoundNode.java index d21c2c7..845f05e 100644 --- a/src/ast/nodes/CompoundNode.java +++ b/src/ast/nodes/CompoundNode.java @@ -10,10 +10,10 @@ import semanticanalysis.SymbolTable; */ public class CompoundNode implements Node { - private Node ifNode; - private Node funcDef; - private Node forStmt; - private Node whileStmt; + private final Node ifNode; + private final Node funcDef; + private final Node forStmt; + private final Node whileStmt; public CompoundNode(Node ifNode, Node funcDef, Node forStmt, Node whileStmt) { this.ifNode = ifNode; @@ -24,7 +24,7 @@ public class CompoundNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - ArrayList errors = new ArrayList(); + ArrayList errors = new ArrayList(); if (ifNode != null) { errors.addAll(ifNode.checkSemantics(ST, _nesting)); diff --git a/src/ast/nodes/DottedNameNode.java b/src/ast/nodes/DottedNameNode.java index df86c99..23f14c1 100644 --- a/src/ast/nodes/DottedNameNode.java +++ b/src/ast/nodes/DottedNameNode.java @@ -11,6 +11,7 @@ import org.antlr.v4.runtime.tree.TerminalNode; * Node for the `dooted_name` statement of the grammar. */ public class DottedNameNode implements Node { + protected ArrayList names; public DottedNameNode(ArrayList names) { @@ -19,7 +20,7 @@ public class DottedNameNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - ArrayList errors = new ArrayList(); + ArrayList errors = new ArrayList(); for (int i = 0; i < names.size(); ++i) { ST.insert(names.get(i).toString(), this.typeCheck(), _nesting, null); diff --git a/src/ast/nodes/ExprNode.java b/src/ast/nodes/ExprNode.java index 8e3b896..873d537 100644 --- a/src/ast/nodes/ExprNode.java +++ b/src/ast/nodes/ExprNode.java @@ -12,11 +12,11 @@ import semanticanalysis.SymbolTable; */ public class ExprNode implements Node { - private AtomNode atom; - private Node compOp; - private String op; - private ArrayList exprs; - private ArrayList trailers; + private final AtomNode atom; + private final Node compOp; + private final String op; + private final ArrayList exprs; + private final ArrayList trailers; public ExprNode(Node atom, Node compOp, ArrayList exprs, String op, ArrayList trailers) { this.atom = (AtomNode) atom; @@ -52,7 +52,7 @@ public class ExprNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - ArrayList errors = new ArrayList(); + ArrayList errors = new ArrayList(); // check if the atom is a function if (atom != null && !trailers.isEmpty()) { diff --git a/src/ast/nodes/ForStmtNode.java b/src/ast/nodes/ForStmtNode.java index d4c5e56..74c6ffc 100644 --- a/src/ast/nodes/ForStmtNode.java +++ b/src/ast/nodes/ForStmtNode.java @@ -10,8 +10,8 @@ import semanticanalysis.SymbolTable; */ public class ForStmtNode implements Node { - private Node exprList; - private Node block; + private final Node exprList; + private final Node block; public ForStmtNode(Node exprList, Node block) { this.exprList = exprList; @@ -34,7 +34,7 @@ public class ForStmtNode implements Node { */ @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - ArrayList errors = new ArrayList(); + ArrayList errors = new ArrayList(); // Save every atom in the expression's list, except the last one var l = (ExprListNode) exprList; diff --git a/src/ast/nodes/FuncdefNode.java b/src/ast/nodes/FuncdefNode.java index 8985e08..c4f5846 100644 --- a/src/ast/nodes/FuncdefNode.java +++ b/src/ast/nodes/FuncdefNode.java @@ -14,9 +14,9 @@ import org.antlr.v4.runtime.tree.TerminalNode; */ public class FuncdefNode implements Node { - private TerminalNode name; - private Node paramlist; - private Node block; + private final TerminalNode name; + private final Node paramlist; + private final Node block; public FuncdefNode(TerminalNode name, Node paramlist, Node block) { this.name = name; @@ -26,14 +26,14 @@ public class FuncdefNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - ArrayList errors = new ArrayList(); + ArrayList errors = new ArrayList(); int paramNumber = ((ParamlistNode) paramlist).getParamNumber(); Type returnType = this.block.typeCheck(); FunctionType ft = new FunctionType(paramNumber, returnType); ST.insert(this.name.toString(), ft, _nesting, ""); - HashMap HM = new HashMap(); + HashMap HM = new HashMap(); ST.add(HM); @@ -66,6 +66,7 @@ public class FuncdefNode implements Node { return ""; } + @Override public String toPrint(String prefix) { String str = prefix + "Funcdef(" + name + ")\n"; diff --git a/src/ast/nodes/IfNode.java b/src/ast/nodes/IfNode.java index f51d486..b0e1ddb 100644 --- a/src/ast/nodes/IfNode.java +++ b/src/ast/nodes/IfNode.java @@ -9,9 +9,10 @@ import semanticanalysis.SymbolTable; * Node for the `if` statement of the grammar. */ public class IfNode implements Node { - private Node guard; - private Node thenbranch; - private Node elsebranch; + + private final Node guard; + private final Node thenbranch; + private final Node elsebranch; public IfNode(Node guard, Node thenbranch, Node elsebranch) { this.guard = guard; @@ -21,7 +22,7 @@ public class IfNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - ArrayList errors = new ArrayList(); + ArrayList errors = new ArrayList(); errors.addAll(guard.checkSemantics(ST, _nesting)); errors.addAll(thenbranch.checkSemantics(ST, _nesting)); @@ -38,9 +39,9 @@ public class IfNode implements Node { if (guard.typeCheck() instanceof BoolType) { Type thenexp = thenbranch.typeCheck(); Type elseexp = elsebranch.typeCheck(); - if (thenexp.getClass().equals(elseexp.getClass())) - return thenexp; - else { + if (thenexp.getClass().equals(elseexp.getClass())) { + return thenexp; + }else { System.out.println("Type Error: incompatible types in then and else branches."); return new ErrorType(); } diff --git a/src/ast/nodes/ImportNode.java b/src/ast/nodes/ImportNode.java index 900a909..7e95ee3 100644 --- a/src/ast/nodes/ImportNode.java +++ b/src/ast/nodes/ImportNode.java @@ -1,20 +1,20 @@ package ast.nodes; +import ast.types.*; import java.util.ArrayList; - import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; -import ast.types.*; /** * Node for the `import_stmt` statement of the grammar. */ public class ImportNode implements Node { - private Node dottedName; - private boolean isFrom; - private boolean importAs; - private boolean importAll; - private ArrayList names; + + private final Node dottedName; + private final boolean isFrom; + private final boolean importAs; + private final boolean importAll; + private final ArrayList names; public ImportNode(Node dottedName, boolean isFrom, boolean importAs, boolean importAll, ArrayList names) { @@ -27,7 +27,7 @@ public class ImportNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - ArrayList errors = new ArrayList(); + ArrayList errors = new ArrayList(); if (isFrom) { for (int i = 0; i < names.size(); ++i) { @@ -75,8 +75,9 @@ public class ImportNode implements Node { } for (int i = 0; i < names.size(); ++i) { - if (i == 0 && importAs) + if (i == 0 && importAs) { continue; + } str += prefix + names.get(i) + "\n"; } diff --git a/src/ast/nodes/Node.java b/src/ast/nodes/Node.java index 77ba669..9fb58b8 100644 --- a/src/ast/nodes/Node.java +++ b/src/ast/nodes/Node.java @@ -1,10 +1,9 @@ package ast.nodes; +import ast.types.*; import java.util.ArrayList; - import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; -import ast.types.*; /** * Base interface for a Node. @@ -87,8 +86,7 @@ public interface Node { /** * Checks semantics for a given node for a SymbolTable ST and a level of - * nesting. - * Returns a list of `SemanticError`. + * nesting. Returns a list of `SemanticError`. */ ArrayList checkSemantics(SymbolTable ST, int _nesting); @@ -104,8 +102,8 @@ public interface Node { String codeGeneration(); /** - * Returns a string for a given node with a prefix. - * It used when an AST wants to be visualized on screen. + * Returns a string for a given node with a prefix. It used when an AST + * wants to be visualized on screen. */ String toPrint(String prefix); } diff --git a/src/ast/nodes/ParamdefNode.java b/src/ast/nodes/ParamdefNode.java index adadf72..6cdb2d0 100644 --- a/src/ast/nodes/ParamdefNode.java +++ b/src/ast/nodes/ParamdefNode.java @@ -17,7 +17,7 @@ public class ParamdefNode extends AtomNode { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - var errors = new ArrayList(); + var errors = new ArrayList(); String paramName = this.getId(); if (!ST.top_lookup(paramName)) { diff --git a/src/ast/nodes/ParamlistNode.java b/src/ast/nodes/ParamlistNode.java index 0a9696f..cf75d08 100644 --- a/src/ast/nodes/ParamlistNode.java +++ b/src/ast/nodes/ParamlistNode.java @@ -1,17 +1,16 @@ package ast.nodes; +import ast.types.*; import java.util.ArrayList; - import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; -import ast.types.*; /** * Node for the `param_list` statement of the grammar. */ public class ParamlistNode implements Node { - private ArrayList params; + private final ArrayList params; public ParamlistNode(ArrayList _params) { params = _params; @@ -19,7 +18,7 @@ public class ParamlistNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - ArrayList errors = new ArrayList(); + ArrayList errors = new ArrayList(); for (var param : params) { errors.addAll(param.checkSemantics(ST, _nesting)); diff --git a/src/ast/nodes/ReturnStmtNode.java b/src/ast/nodes/ReturnStmtNode.java index 0f2dd74..8e34813 100644 --- a/src/ast/nodes/ReturnStmtNode.java +++ b/src/ast/nodes/ReturnStmtNode.java @@ -1,16 +1,16 @@ package ast.nodes; +import ast.types.*; import java.util.ArrayList; - import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; -import ast.types.*; /** * Node for the `return_stmt` statement of the grammar. */ public class ReturnStmtNode implements Node { - private Node exprList; + + private final Node exprList; public ReturnStmtNode(Node exprList) { this.exprList = exprList; @@ -18,7 +18,7 @@ public class ReturnStmtNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - ArrayList errors = new ArrayList(); + ArrayList errors = new ArrayList(); if (this.exprList != null) { errors.addAll(this.exprList.checkSemantics(ST, _nesting)); diff --git a/src/ast/nodes/RootNode.java b/src/ast/nodes/RootNode.java index 4b29e8d..5bbce8c 100644 --- a/src/ast/nodes/RootNode.java +++ b/src/ast/nodes/RootNode.java @@ -20,10 +20,10 @@ public class RootNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - ArrayList errors = new ArrayList(); + ArrayList errors = new ArrayList(); // Create a new HashMap for the current scope - HashMap HM = new HashMap(); + HashMap HM = new HashMap(); // Add the HashMap to the SymbolTable ST.add(HM); diff --git a/src/ast/nodes/SimpleStmtNode.java b/src/ast/nodes/SimpleStmtNode.java index b7e5455..b2bc880 100644 --- a/src/ast/nodes/SimpleStmtNode.java +++ b/src/ast/nodes/SimpleStmtNode.java @@ -9,10 +9,11 @@ import semanticanalysis.SymbolTable; * Node for the `simple_stmt` statement of the grammar. */ public class SimpleStmtNode implements Node { - private Node assignment; - private Node expr; - private Node returnStmt; - private Node importStmt; + + private final Node assignment; + private final Node expr; + private final Node returnStmt; + private final Node importStmt; public SimpleStmtNode(Node assignment, Node expr, Node returnStmt, Node importStmt) { this.assignment = assignment; @@ -23,7 +24,7 @@ public class SimpleStmtNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - ArrayList errors = new ArrayList(); + ArrayList errors = new ArrayList(); if (assignment != null) { errors.addAll(assignment.checkSemantics(ST, _nesting)); diff --git a/src/ast/nodes/SimpleStmtsNode.java b/src/ast/nodes/SimpleStmtsNode.java index 97bffff..ae1044b 100644 --- a/src/ast/nodes/SimpleStmtsNode.java +++ b/src/ast/nodes/SimpleStmtsNode.java @@ -9,7 +9,8 @@ import semanticanalysis.SymbolTable; * Node for the `simple_stmts` statement of the grammar. */ public class SimpleStmtsNode implements Node { - private ArrayList stmts; + + private final ArrayList stmts; public SimpleStmtsNode(ArrayList stmts) { this.stmts = stmts; @@ -17,7 +18,7 @@ public class SimpleStmtsNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - ArrayList errors = new ArrayList(); + ArrayList errors = new ArrayList(); for (Node stmt : stmts) { errors.addAll(stmt.checkSemantics(ST, _nesting)); diff --git a/src/ast/nodes/TestlistCompNode.java b/src/ast/nodes/TestlistCompNode.java index cba056c..32049f5 100644 --- a/src/ast/nodes/TestlistCompNode.java +++ b/src/ast/nodes/TestlistCompNode.java @@ -10,8 +10,8 @@ import semanticanalysis.SymbolTable; */ public class TestlistCompNode implements Node { - private ArrayList exprs; - private CompForNode comp; + private final ArrayList exprs; + private final CompForNode comp; public TestlistCompNode(ArrayList exprs, Node comp) { this.exprs = exprs; diff --git a/src/ast/nodes/TrailerNode.java b/src/ast/nodes/TrailerNode.java index 22e43a0..aaa72f3 100644 --- a/src/ast/nodes/TrailerNode.java +++ b/src/ast/nodes/TrailerNode.java @@ -12,11 +12,11 @@ import org.antlr.v4.runtime.tree.TerminalNode; */ public class TrailerNode implements Node { - private Node arglist; - private ArrayList exprs; - private TerminalNode methodCall; - private boolean isParenthesis; - private boolean isEmpty; + private final Node arglist; + private final ArrayList exprs; + private final TerminalNode methodCall; + private final boolean isParenthesis; + private final boolean isEmpty; public TrailerNode(Node arglist, ArrayList exprs, TerminalNode methodCall, boolean isParenthesis) { this.arglist = arglist; @@ -24,12 +24,12 @@ public class TrailerNode implements Node { this.methodCall = methodCall; this.isParenthesis = isParenthesis; - this.isEmpty = (this.arglist == null && this.exprs.size() == 0 && this.methodCall == null); + this.isEmpty = (this.arglist == null && this.exprs.isEmpty() && this.methodCall == null); } @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - ArrayList errors = new ArrayList(); + ArrayList errors = new ArrayList(); if (arglist != null) { errors.addAll(arglist.checkSemantics(ST, _nesting)); diff --git a/src/ast/nodes/WhileStmtNode.java b/src/ast/nodes/WhileStmtNode.java index 6353ec1..1db01ea 100644 --- a/src/ast/nodes/WhileStmtNode.java +++ b/src/ast/nodes/WhileStmtNode.java @@ -1,17 +1,17 @@ package ast.nodes; +import ast.types.*; import java.util.ArrayList; - import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; -import ast.types.*; /** * Node for the `while_stmt` statement of the grammar. */ public class WhileStmtNode implements Node { - private Node expr; - private Node block; + + private final Node expr; + private final Node block; public WhileStmtNode(Node expr, Node block) { this.expr = expr; @@ -20,7 +20,7 @@ public class WhileStmtNode implements Node { @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { - ArrayList errors = new ArrayList(); + ArrayList errors = new ArrayList(); errors.addAll(expr.checkSemantics(ST, _nesting)); errors.addAll(block.checkSemantics(ST, _nesting)); diff --git a/src/ast/types/AtomType.java b/src/ast/types/AtomType.java index 0387ec1..fc1c69e 100644 --- a/src/ast/types/AtomType.java +++ b/src/ast/types/AtomType.java @@ -2,9 +2,10 @@ package ast.types; /** * An tom type. - * TODO: do I need to use this one? */ public class AtomType extends Type { + + @Override public String toPrint(String prefix) { return prefix + "Atom\n"; } diff --git a/src/ast/types/BoolType.java b/src/ast/types/BoolType.java index 20c2750..01e2cd5 100644 --- a/src/ast/types/BoolType.java +++ b/src/ast/types/BoolType.java @@ -4,6 +4,8 @@ package ast.types; * A boolean type. A bool is True or False. */ public class BoolType extends Type { + + @Override public String toPrint(String prefix) { return prefix + "Bool\n"; } diff --git a/src/ast/types/ErrorType.java b/src/ast/types/ErrorType.java index 4a7a0cf..71176d1 100644 --- a/src/ast/types/ErrorType.java +++ b/src/ast/types/ErrorType.java @@ -4,6 +4,8 @@ package ast.types; * Error type. */ public class ErrorType extends Type { + + @Override public String toPrint(String prefix) { return prefix + "Error\n"; } diff --git a/src/ast/types/FunctionType.java b/src/ast/types/FunctionType.java index ef50641..5e6adaa 100644 --- a/src/ast/types/FunctionType.java +++ b/src/ast/types/FunctionType.java @@ -5,8 +5,8 @@ package ast.types; */ public class FunctionType extends Type { - private int paramNumber; - private Type returnType; + private final int paramNumber; + private final Type returnType; public FunctionType(int paramNumber, Type returnType) { this.paramNumber = paramNumber; @@ -22,6 +22,7 @@ public class FunctionType extends Type { return returnType; } + @Override public String toPrint(String prefix) { return prefix + "Function\n"; } diff --git a/src/ast/types/ImportType.java b/src/ast/types/ImportType.java index 6852bfa..892de10 100644 --- a/src/ast/types/ImportType.java +++ b/src/ast/types/ImportType.java @@ -4,8 +4,9 @@ package ast.types; * A type for the imported names. */ public class ImportType extends Type { + + @Override public String toPrint(String prefix) { return prefix + "Import\n"; } } - diff --git a/src/ast/types/IntType.java b/src/ast/types/IntType.java index a29518b..6483d93 100644 --- a/src/ast/types/IntType.java +++ b/src/ast/types/IntType.java @@ -4,6 +4,8 @@ package ast.types; * An integer type. */ public class IntType extends Type { + + @Override public String toPrint(String prefix) { return prefix + "Int\n"; } diff --git a/src/ast/types/NoneType.java b/src/ast/types/NoneType.java index 42f7fd7..730add9 100644 --- a/src/ast/types/NoneType.java +++ b/src/ast/types/NoneType.java @@ -5,6 +5,7 @@ package ast.types; */ public class NoneType extends Type { + @Override public String toPrint(String prefix) { return prefix + "None\n"; } diff --git a/src/ast/types/ReservedWordsType.java b/src/ast/types/ReservedWordsType.java index f5f7ac5..da72890 100644 --- a/src/ast/types/ReservedWordsType.java +++ b/src/ast/types/ReservedWordsType.java @@ -4,6 +4,8 @@ package ast.types; * A type for the continue and break statements. */ public class ReservedWordsType extends Type { + + @Override public String toPrint(String prefix) { return prefix + "ReservedWords\n"; } diff --git a/src/ast/types/Type.java b/src/ast/types/Type.java index 6bff8b9..6190106 100644 --- a/src/ast/types/Type.java +++ b/src/ast/types/Type.java @@ -1,26 +1,25 @@ package ast.types; +import ast.nodes.*; import java.util.ArrayList; - import semanticanalysis.SemanticError; import semanticanalysis.SymbolTable; -import ast.nodes.*; /** * A node which represents a type class. */ public class Type implements Node { + public boolean isEqual(Type A, Type B) { - if (A.getClass().equals(B.getClass())) - return true; - else - return false; + return A.getClass().equals(B.getClass()); } + @Override public String toPrint(String s) { return s; } + @Override public ArrayList checkSemantics(SymbolTable ST, int _nesting) { // It is never invoked return null; diff --git a/src/ast/types/VoidType.java b/src/ast/types/VoidType.java index 8e3f9b2..2d21da6 100644 --- a/src/ast/types/VoidType.java +++ b/src/ast/types/VoidType.java @@ -5,6 +5,7 @@ package ast.types; */ public class VoidType extends Type { + @Override public String toPrint(String prefix) { return prefix + "Void\n"; } -- cgit v1.2.3-18-g5258 From 06d7c8dee25c065b1a569337f34d3cd5e892a31d Mon Sep 17 00:00:00 2001 From: geno Date: Sun, 30 Jun 2024 13:43:46 +0200 Subject: fix build error in CI --- src/ast/nodes/ArglistNode.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src/ast') diff --git a/src/ast/nodes/ArglistNode.java b/src/ast/nodes/ArglistNode.java index 55a568d..425e4c6 100644 --- a/src/ast/nodes/ArglistNode.java +++ b/src/ast/nodes/ArglistNode.java @@ -22,7 +22,8 @@ public class ArglistNode implements Node { ArrayList errors = new ArrayList(); for (var arg : arguments) { - if (arg instanceof ExprNode argExpr) { + if (arg instanceof ExprNode) { + ExprNode argExpr = (ExprNode) arg; String argName = argExpr.getId(); // TODO: check fucking IntType for params -- cgit v1.2.3-18-g5258