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/ExprNode.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'src/ast/nodes/ExprNode.java') 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(); } -- cgit v1.2.3-71-g8e6c 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/Main.java | 2 +- src/ast/nodes/AtomNode.java | 31 +++++---- src/ast/nodes/ExprNode.java | 121 ++++++++++++++++++++++++++++------ src/ast/nodes/RootNode.java | 8 +-- src/ast/types/VoidType.java | 6 ++ src/semanticanalysis/SymbolTable.java | 17 +++-- 6 files changed, 140 insertions(+), 45 deletions(-) (limited to 'src/ast/nodes/ExprNode.java') diff --git a/src/Main.java b/src/Main.java index 3987bad..bfc21e3 100644 --- a/src/Main.java +++ b/src/Main.java @@ -60,7 +60,7 @@ public class Main { Node ast = visitor.visit(tree); ArrayList errors = ast.checkSemantics(ST, 0); if (errors.size() > 0) { - System.out.println("You had: " + errors.size() + " errors:"); + System.out.println("You had " + errors.size() + " errors:"); for (SemanticError e : errors) { System.out.println("\t" + e); } 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"; + } } diff --git a/src/semanticanalysis/SymbolTable.java b/src/semanticanalysis/SymbolTable.java index 8193d5e..617b48a 100644 --- a/src/semanticanalysis/SymbolTable.java +++ b/src/semanticanalysis/SymbolTable.java @@ -126,15 +126,18 @@ public class SymbolTable { // We always increment the offset by 1 otherwise we need ad-hoc bytecode // operations // FIXME: wtf is that? - if (type.getClass().equals((new BoolType()).getClass())) { - offs = offs + 1; - } else if (type.getClass().equals((new IntType()).getClass())) { - offs = offs + 1; - } else { - offs = offs + 1; - } + // if (type.getClass().equals((new BoolType()).getClass())) { + // offs = offs + 1; + // } else if (type.getClass().equals((new IntType()).getClass())) { + // offs = offs + 1; + // } else { + // offs = offs + 1; + // } + offs = offs + 1; this.offset.add(offs); + + // System.out.println("Insert " + id + " of type " + type.toString() + " with nesting " + String.valueOf(_nesting)); } /** -- cgit v1.2.3-71-g8e6c From fc712f94a7ed8554d8d44f4965be367354a7e670 Mon Sep 17 00:00:00 2001 From: L0P0P Date: Wed, 26 Jun 2024 10:06:12 +0200 Subject: Using child --- progs/test.py | 8 ++++---- 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 +++++++++++---------------- 7 files changed, 46 insertions(+), 47 deletions(-) (limited to 'src/ast/nodes/ExprNode.java') diff --git a/progs/test.py b/progs/test.py index ab0901a..72729e1 100644 --- a/progs/test.py +++ b/progs/test.py @@ -1,4 +1,4 @@ -x = 1 - -if x == 1: - print("a") +def unibo(a): + print("u") + +unibo(a) 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-71-g8e6c 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 --- progs/test.py | 4 +++- 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 +- src/semanticanalysis/STentry.java | 6 ++++++ src/semanticanalysis/SymbolTable.java | 15 +++++++++++++++ 8 files changed, 59 insertions(+), 27 deletions(-) (limited to 'src/ast/nodes/ExprNode.java') diff --git a/progs/test.py b/progs/test.py index 72729e1..97e316f 100644 --- a/progs/test.py +++ b/progs/test.py @@ -1,4 +1,6 @@ def unibo(a): - print("u") + if a == 3: + print("UNIBO") +a = 3 unibo(a) 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; diff --git a/src/semanticanalysis/STentry.java b/src/semanticanalysis/STentry.java index 0e4b00e..07b62c8 100644 --- a/src/semanticanalysis/STentry.java +++ b/src/semanticanalysis/STentry.java @@ -52,4 +52,10 @@ public class STentry { return label; } + @Override + public String toString() { + // Print all the fields of the STentry + return "Type: " + type + ", Offset: " + offset + ", Nesting: " + nesting + ", Label: " + label; + } + } diff --git a/src/semanticanalysis/SymbolTable.java b/src/semanticanalysis/SymbolTable.java index 617b48a..6756ec4 100644 --- a/src/semanticanalysis/SymbolTable.java +++ b/src/semanticanalysis/SymbolTable.java @@ -153,4 +153,19 @@ public class SymbolTable { this.offset.add(offs); } + @Override + public String toString() { + // Print the symbol table + String str = ""; + for (int i = 0; i < this.symbolTable.size(); i++) { + str += "Level " + i + "\n"; + HashMap H = this.symbolTable.get(i); + for (String key : H.keySet()) { + STentry T = H.get(key); + str += key + " -> " + T.toString() + "\n"; + } + } + return str; + } + } -- cgit v1.2.3-71-g8e6c 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" --- progs/test2.py | 9 +++++--- src/Main.java | 2 +- 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 +++++++++++++++++++++++ 16 files changed, 116 insertions(+), 42 deletions(-) create mode 100644 src/ast/types/FunctionType.java (limited to 'src/ast/nodes/ExprNode.java') diff --git a/progs/test2.py b/progs/test2.py index c62d44a..9c1318d 100644 --- a/progs/test2.py +++ b/progs/test2.py @@ -1,3 +1,6 @@ -x = 1 -if y == 1: - print("a") +x = 2 ; y = 3 + +def f(x, y): + return x+y + +print(f(5,3,1)+ x + y) diff --git a/src/Main.java b/src/Main.java index bfc21e3..121d3d1 100644 --- a/src/Main.java +++ b/src/Main.java @@ -20,7 +20,7 @@ public class Main { try { // String fileStr = file.getPath(); // FIXME: use the fileStr above - String fileStr = "./progs/test.py"; + String fileStr = "./progs/test2.py"; System.out.println(fileStr); System.out.println(readFile(fileStr)); CharStream cs = CharStreams.fromFileName(fileStr); 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-71-g8e6c 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) --- progs/test.py | 2 -- progs/test2.py | 6 ------ src/Main.java | 2 +- src/ast/nodes/ExprNode.java | 2 ++ test/1a.py | 8 ++++++++ test/1b.py | 6 ++++++ test/1c.py | 5 +++++ 7 files changed, 22 insertions(+), 9 deletions(-) delete mode 100644 progs/test.py delete mode 100644 progs/test2.py create mode 100644 test/1a.py create mode 100644 test/1b.py create mode 100644 test/1c.py (limited to 'src/ast/nodes/ExprNode.java') diff --git a/progs/test.py b/progs/test.py deleted file mode 100644 index f9140c6..0000000 --- a/progs/test.py +++ /dev/null @@ -1,2 +0,0 @@ -def unibo(a): - unibo(a) diff --git a/progs/test2.py b/progs/test2.py deleted file mode 100644 index 9c1318d..0000000 --- a/progs/test2.py +++ /dev/null @@ -1,6 +0,0 @@ -x = 2 ; y = 3 - -def f(x, y): - return x+y - -print(f(5,3,1)+ x + y) diff --git a/src/Main.java b/src/Main.java index 121d3d1..21645db 100644 --- a/src/Main.java +++ b/src/Main.java @@ -20,7 +20,7 @@ public class Main { try { // String fileStr = file.getPath(); // FIXME: use the fileStr above - String fileStr = "./progs/test2.py"; + String fileStr = "./test/1a.py"; System.out.println(fileStr); System.out.println(readFile(fileStr)); CharStream cs = CharStreams.fromFileName(fileStr); 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) { diff --git a/test/1a.py b/test/1a.py new file mode 100644 index 0000000..69b3dc5 --- /dev/null +++ b/test/1a.py @@ -0,0 +1,8 @@ + +x = 2 +y = z + +def f(x, y): + return x + y + +print(f(5, 3) + x + y) diff --git a/test/1b.py b/test/1b.py new file mode 100644 index 0000000..a8324a0 --- /dev/null +++ b/test/1b.py @@ -0,0 +1,6 @@ +x = 2 ; y = 3 + +def f(x, x): + return x+y + +print(f(5,3)+ x + y) diff --git a/test/1c.py b/test/1c.py new file mode 100644 index 0000000..59e51e5 --- /dev/null +++ b/test/1c.py @@ -0,0 +1,5 @@ + +def mult(a, b): + return a * b + +print(mult(3, 2, 4)) -- cgit v1.2.3-71-g8e6c 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 --- progs/a284.py | 24 +++---- progs/a339.py | 51 ++++++++------- progs/a394.py | 46 +++++++------- progs/a403.py | 2 +- progs/a52.py | 14 +++-- progs/a641.py | 12 ++-- progs/a745.py | 32 +++++----- src/Main.java | 4 +- src/ParseAll.java | 75 ++++++---------------- 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 ++++ src/semanticanalysis/SymbolTable.java | 1 - 23 files changed, 336 insertions(+), 250 deletions(-) create mode 100644 src/ast/types/ContinueBreakType.java create mode 100644 src/ast/types/ImportType.java (limited to 'src/ast/nodes/ExprNode.java') diff --git a/progs/a284.py b/progs/a284.py index b69395b..cfd429d 100644 --- a/progs/a284.py +++ b/progs/a284.py @@ -1,11 +1,13 @@ -def is_Isomorphic(str1,str2): - dict_str1 = {} - dict_str2 = {} - for i, value in enumerate(str1): - dict_str1[value] = dict_str1.get(value,[]) + [i] - for j, value in enumerate(str2): - dict_str2[value] = dict_str2.get(value,[]) + [j] - if sorted(dict_str1.values()) == sorted(dict_str2.values()): - return True - else: - return False \ No newline at end of file +# FIXME: multiple variable assignment in for loop +# +# def is_Isomorphic(str1,str2): +# dict_str1 = {} +# dict_str2 = {} +# for i, value in enumerate(str1): +# dict_str1[value] = dict_str1.get(value,[]) + [i] +# for j, value in enumerate(str2): +# dict_str2[value] = dict_str2.get(value,[]) + [j] +# if sorted(dict_str1.values()) == sorted(dict_str2.values()): +# return True +# else: +# return False \ No newline at end of file diff --git a/progs/a339.py b/progs/a339.py index 9a57403..95724d2 100644 --- a/progs/a339.py +++ b/progs/a339.py @@ -1,25 +1,28 @@ -def heap_sort(arr): - heapify(arr) - end = len(arr) - 1 - while end > 0: - arr[end], arr[0] = arr[0], arr[end] - shift_down(arr, 0, end - 1) - end -= 1 - return arr +# FIXME: chiamata a funzione definita dopo +# +# def heap_sort(arr): +# heapify(arr) +# end = len(arr) - 1 +# while end > 0: +# arr[end], arr[0] = arr[0], arr[end] +# shift_down(arr, 0, end - 1) +# end -= 1 +# return arr -def heapify(arr): - start = len(arr) // 2 - while start >= 0: - shift_down(arr, start, len(arr) - 1) - start -= 1 -def shift_down(arr, start, end): - root = start - while root * 2 + 1 <= end: - child = root * 2 + 1 - if child + 1 <= end and arr[child] < arr[child + 1]: - child += 1 - if child <= end and arr[root] < arr[child]: - arr[root], arr[child] = arr[child], arr[root] - root = child - else: - return +# def heapify(arr): +# start = len(arr) // 2 +# while start >= 0: +# shift_down(arr, start, len(arr) - 1) +# start -= 1 + +# def shift_down(arr, start, end): +# root = start +# while root * 2 + 1 <= end: +# child = root * 2 + 1 +# if child + 1 <= end and arr[child] < arr[child + 1]: +# child += 1 +# if child <= end and arr[root] < arr[child]: +# arr[root], arr[child] = arr[child], arr[root] +# root = child +# else: +# return diff --git a/progs/a394.py b/progs/a394.py index 4fe6e47..25f8f3e 100644 --- a/progs/a394.py +++ b/progs/a394.py @@ -1,22 +1,24 @@ -def func(nums, k): - import collections - d = collections.defaultdict(int) - for row in nums: - for i in row: - d[i] += 1 - temp = [] - import heapq - for key, v in d.items(): - if len(temp) < k: - temp.append((v, key)) - if len(temp) == k: - heapq.heapify(temp) - else: - if v > temp[0][0]: - heapq.heappop(temp) - heapq.heappush(temp, (v, key)) - result = [] - while temp: - v, key = heapq.heappop(temp) - result.append(key) - return result \ No newline at end of file +# FIXME: multiple variable assignment in for loop +# +# def func(nums, k): +# import collections +# d = collections.defaultdict(int) +# for row in nums: +# for i in row: +# d[i] += 1 +# temp = [] +# import heapq +# for key, v in d.items(): +# if len(temp) < k: +# temp.append((v, key)) +# if len(temp) == k: +# heapq.heapify(temp) +# else: +# if v > temp[0][0]: +# heapq.heappop(temp) +# heapq.heappush(temp, (v, key)) +# result = [] +# while temp: +# v, key = heapq.heappop(temp) +# result.append(key) +# return result \ No newline at end of file diff --git a/progs/a403.py b/progs/a403.py index 18c84b2..ee1bdd7 100644 --- a/progs/a403.py +++ b/progs/a403.py @@ -2,4 +2,4 @@ from collections import Counter from itertools import chain def freq_element(nums): result = Counter(chain.from_iterable(nums)) - return result \ No newline at end of file + return result diff --git a/progs/a52.py b/progs/a52.py index 4a0b33a..1d116bc 100644 --- a/progs/a52.py +++ b/progs/a52.py @@ -1,6 +1,8 @@ -from collections import defaultdict -def grouping_dictionary(l): - d = defaultdict(list) - for k, v in l: - d[k].append(v) - return d \ No newline at end of file +# FIXME: multiple variable assignment in for loop +# +# from collections import defaultdict +# def grouping_dictionary(l): +# d = defaultdict(list) +# for k, v in l: +# d[k].append(v) +# return d \ No newline at end of file diff --git a/progs/a641.py b/progs/a641.py index 51393cd..52b0f6a 100644 --- a/progs/a641.py +++ b/progs/a641.py @@ -1,5 +1,7 @@ -def count_first_elements(test_tup): - for count, ele in enumerate(test_tup): - if isinstance(ele, tuple): - break - return (count) \ No newline at end of file +# FIXME: multiple variable assignment in for loop +# +# def count_first_elements(test_tup): +# for count, ele in enumerate(test_tup): +# if isinstance(ele, tuple): +# break +# return (count) \ No newline at end of file diff --git a/progs/a745.py b/progs/a745.py index 9a21dfa..e8ad671 100644 --- a/progs/a745.py +++ b/progs/a745.py @@ -1,15 +1,17 @@ -def find_rotation_count(A): - (left, right) = (0, len(A) - 1) - while left <= right: - if A[left] <= A[right]: - return left - mid = (left + right) // 2 - next = (mid + 1) % len(A) - prev = (mid - 1 + len(A)) % len(A) - if A[mid] <= A[next] and A[mid] <= A[prev]: - return mid - elif A[mid] <= A[right]: - right = mid - 1 - elif A[mid] >= A[left]: - left = mid + 1 - return -1 \ No newline at end of file +# FIXME: unpacking assignment +# +# def find_rotation_count(A): +# (left, right) = (0, len(A) - 1) +# while left <= right: +# if A[left] <= A[right]: +# return left +# mid = (left + right) // 2 +# next = (mid + 1) % len(A) +# prev = (mid - 1 + len(A)) % len(A) +# if A[mid] <= A[next] and A[mid] <= A[prev]: +# return mid +# elif A[mid] <= A[right]: +# right = mid - 1 +# elif A[mid] >= A[left]: +# left = mid + 1 +# return -1 \ No newline at end of file diff --git a/src/Main.java b/src/Main.java index 21645db..c3c1cdd 100644 --- a/src/Main.java +++ b/src/Main.java @@ -20,7 +20,7 @@ public class Main { try { // String fileStr = file.getPath(); // FIXME: use the fileStr above - String fileStr = "./test/1a.py"; + String fileStr = "./progs/a600.py"; System.out.println(fileStr); System.out.println(readFile(fileStr)); CharStream cs = CharStreams.fromFileName(fileStr); @@ -41,7 +41,7 @@ public class Main { JPanel panel = new JPanel(); TreeViewer viewer = new TreeViewer(Arrays.asList(parser.getRuleNames()), tree); - viewer.setScale(1.5); // Zoom factor + viewer.setScale(1); // Zoom factor panel.add(viewer); frame.add(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); diff --git a/src/ParseAll.java b/src/ParseAll.java index 3e5d868..87b4ca3 100644 --- a/src/ParseAll.java +++ b/src/ParseAll.java @@ -1,14 +1,14 @@ -import java.io.BufferedReader; import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.Arrays; +import java.util.ArrayList; import java.util.Objects; -import javax.swing.*; -import org.antlr.v4.gui.TreeViewer; import org.antlr.v4.runtime.*; -import parser.*; +import ast.Python3VisitorImpl; +import ast.nodes.*; +import parser.Python3Lexer; +import parser.Python3Parser; +import semanticanalysis.SemanticError; +import semanticanalysis.SymbolTable; public class ParseAll { @SuppressWarnings("unused") @@ -22,12 +22,8 @@ public class ParseAll { if (!file.isFile() || !getExtension(file.getName()).equals("py")) { System.err.println("Wont parse: " + fileStr); continue; - } else { - System.out.println(fileStr); } - // System.out.println(readFile(fileStr)); - CharStream cs = CharStreams.fromFileName(fileStr); Python3Lexer lexer = new Python3Lexer(cs); CommonTokenStream tokenStream = new CommonTokenStream(lexer); @@ -37,11 +33,17 @@ public class ParseAll { String treeStr = tree.toStringTree(); // System.out.println(treeStr); - TreeViewer viewer = new TreeViewer(Arrays.asList(parser.getRuleNames()), tree); - viewer.setScale(1.5); - saveTree(viewer, "./trees/" + removeExtension(file.getName()) + ".png"); - if (parser.getNumberOfSyntaxErrors() != 0) { - System.err.println("Parse errors: " + fileStr); + Python3VisitorImpl visitor = new Python3VisitorImpl(); + SymbolTable ST = new SymbolTable(); + Node ast = visitor.visit(tree); + ArrayList errors = ast.checkSemantics(ST, 0); + if (errors.size() > 0) { + System.out.println(); + System.out.println(fileStr); + System.out.println("You had " + errors.size() + " errors:"); + for (SemanticError e : errors) { + System.out.println("\t" + e); + } } } catch (Exception e) { @@ -51,47 +53,6 @@ public class ParseAll { } } - @SuppressWarnings("unused") - private static String readFile(String filePath) throws IOException { - StringBuilder content = new StringBuilder(); - try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { - String line; - while ((line = reader.readLine()) != null) { - content.append(line).append("\n"); - } - } - return content.toString(); - } - - @SuppressWarnings("unused") - private static void showTree(TreeViewer viewer) { - JFrame frame = new JFrame("Parse Tree"); - JPanel panel = new JPanel(); - panel.add(viewer); - frame.add(panel); - frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - frame.setSize(800, 600); - frame.setVisible(true); - } - - private static void saveTree(TreeViewer viewer, String name) { - try { - viewer.save(name); - } catch (Exception e) { - System.err.println(name); - e.printStackTrace(); - } - } - - public static String removeExtension(String fileName) { - int extensionIndex = fileName.lastIndexOf('.'); - if (extensionIndex == -1) { - return fileName; - } else { - return fileName.substring(0, extensionIndex); - } - } - public static String getExtension(String fileName) { int extensionIndex = fileName.lastIndexOf('.'); if (extensionIndex == -1) { 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"; + } +} + diff --git a/src/semanticanalysis/SymbolTable.java b/src/semanticanalysis/SymbolTable.java index 6756ec4..db9649c 100644 --- a/src/semanticanalysis/SymbolTable.java +++ b/src/semanticanalysis/SymbolTable.java @@ -137,7 +137,6 @@ public class SymbolTable { this.offset.add(offs); - // System.out.println("Insert " + id + " of type " + type.toString() + " with nesting " + String.valueOf(_nesting)); } /** -- cgit v1.2.3-71-g8e6c 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/nodes/ExprNode.java') 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-71-g8e6c 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/nodes/ExprNode.java') 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-71-g8e6c 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/nodes/ExprNode.java') 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-71-g8e6c 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/Main.java | 15 +-------------- src/ParseAll.java | 11 +---------- 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 +++++---- src/semanticanalysis/Share.java | 33 +++++++++++++++++++++++++++------ 10 files changed, 98 insertions(+), 47 deletions(-) (limited to 'src/ast/nodes/ExprNode.java') diff --git a/src/Main.java b/src/Main.java index 04f7183..4f5d45f 100644 --- a/src/Main.java +++ b/src/Main.java @@ -1,7 +1,4 @@ -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import javax.swing.*; @@ -27,7 +24,7 @@ public class Main { try { String fileStr = args[0]; System.out.println(fileStr); - System.out.println(readFile(fileStr)); + System.out.println(Share.readFile(fileStr)); CharStream cs = CharStreams.fromFileName(fileStr); Python3Lexer lexer = new Python3Lexer(cs); CommonTokenStream tokens = new CommonTokenStream(lexer); @@ -71,14 +68,4 @@ public class Main { } } - private static String readFile(String filePath) throws IOException { - StringBuilder content = new StringBuilder(); - try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { - String line; - while ((line = reader.readLine()) != null) { - content.append(line).append("\n"); - } - } - return content.toString(); - } } diff --git a/src/ParseAll.java b/src/ParseAll.java index 2662a85..568c89c 100644 --- a/src/ParseAll.java +++ b/src/ParseAll.java @@ -22,7 +22,7 @@ public class ParseAll { // fileStr = "./progs/wrong.py"; try { - if (!file.isFile() || !getExtension(file.getName()).equals("py")) { + if (!file.isFile() || !Share.getExtension(file.getName()).equals("py")) { System.err.println("Wont parse: " + fileStr); continue; } @@ -56,13 +56,4 @@ public class ParseAll { } } } - - public static String getExtension(String fileName) { - int extensionIndex = fileName.lastIndexOf('.'); - if (extensionIndex == -1) { - return fileName; - } else { - return fileName.substring(extensionIndex + 1); - } - } } 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"; } } diff --git a/src/semanticanalysis/Share.java b/src/semanticanalysis/Share.java index c1f03c2..c98fc53 100644 --- a/src/semanticanalysis/Share.java +++ b/src/semanticanalysis/Share.java @@ -1,13 +1,18 @@ package semanticanalysis; -import java.util.ArrayList; +import java.util.*; +import java.io.*; public class Share { - public static ArrayList removeDuplicates(ArrayList list) { - ArrayList newList = new ArrayList(); + /** + * Removes the duplicate elements in a list of Semantic Errors. It's not + * generic because it's used a custom contains function. + */ + public static ArrayList removeDuplicates(ArrayList list) { + ArrayList newList = new ArrayList(); - for (T element : list) { + for (SemanticError element : list) { if (!customContains(newList, element)) { newList.add(element); } @@ -15,9 +20,14 @@ public class Share { return newList; } - public static boolean customContains(ArrayList list, T e) { + /** + * Normal contains did not work, so we made a custom contains function. + * Returns `true` if the String rappresentation of an object in the list is + * equal to the element given in input. + */ + private static boolean customContains(ArrayList list, SemanticError e) { String e1 = e.toString(); - for (T element : list) { + for (SemanticError element : list) { String e2 = element.toString(); if (e2.equals(e1)) { return true; @@ -34,4 +44,15 @@ public class Share { return fileName.substring(extensionIndex + 1); } } + + public static String readFile(String filePath) throws IOException { + StringBuilder content = new StringBuilder(); + try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { + String line; + while ((line = reader.readLine()) != null) { + content.append(line).append("\n"); + } + } + return content.toString(); + } } -- cgit v1.2.3-71-g8e6c 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/Main.java | 2 +- src/ParseAll.java | 2 +- 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 + src/semanticanalysis/STentry.java | 7 ++++--- src/semanticanalysis/SemanticError.java | 4 +++- src/semanticanalysis/Share.java | 4 ++-- src/semanticanalysis/SymbolTable.java | 20 ++++++-------------- 41 files changed, 136 insertions(+), 129 deletions(-) (limited to 'src/ast/nodes/ExprNode.java') diff --git a/src/Main.java b/src/Main.java index 4f5d45f..f53b410 100644 --- a/src/Main.java +++ b/src/Main.java @@ -54,7 +54,7 @@ public class Main { Node ast = visitor.visit(tree); ArrayList errorsWithDup = ast.checkSemantics(ST, 0); ArrayList errors = Share.removeDuplicates(errorsWithDup); - if (errors.size() > 0) { + if (!errors.isEmpty()) { System.out.println("You had " + errors.size() + " errors:"); for (SemanticError e : errors) { System.out.println("\t" + e); diff --git a/src/ParseAll.java b/src/ParseAll.java index 568c89c..7def6f4 100644 --- a/src/ParseAll.java +++ b/src/ParseAll.java @@ -41,7 +41,7 @@ public class ParseAll { Node ast = visitor.visit(tree); ArrayList errorsWithDup = ast.checkSemantics(ST, 0); ArrayList errors = Share.removeDuplicates(errorsWithDup); - if (errors.size() > 0) { + if (!errors.isEmpty()) { System.out.println(); System.out.println(fileStr); System.out.println("You had " + errors.size() + " errors:"); 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"; } diff --git a/src/semanticanalysis/STentry.java b/src/semanticanalysis/STentry.java index 07b62c8..51fb109 100644 --- a/src/semanticanalysis/STentry.java +++ b/src/semanticanalysis/STentry.java @@ -6,9 +6,10 @@ import ast.types.Type; * Entry class for the symbol table. */ public class STentry { - private Type type; - private int offset; - private int nesting; + + private final Type type; + private final int offset; + private final int nesting; private String label; public STentry(Type type, int offset, int nesting) { diff --git a/src/semanticanalysis/SemanticError.java b/src/semanticanalysis/SemanticError.java index 745e3fb..ac2dc4c 100644 --- a/src/semanticanalysis/SemanticError.java +++ b/src/semanticanalysis/SemanticError.java @@ -4,12 +4,14 @@ package semanticanalysis; * Class respresents a semantic error. */ public class SemanticError { - private String msg; + + private final String msg; public SemanticError(String msg) { this.msg = msg; } + @Override public String toString() { return msg; } diff --git a/src/semanticanalysis/Share.java b/src/semanticanalysis/Share.java index c98fc53..7542cf7 100644 --- a/src/semanticanalysis/Share.java +++ b/src/semanticanalysis/Share.java @@ -1,7 +1,7 @@ package semanticanalysis; -import java.util.*; import java.io.*; +import java.util.*; public class Share { @@ -10,7 +10,7 @@ public class Share { * generic because it's used a custom contains function. */ public static ArrayList removeDuplicates(ArrayList list) { - ArrayList newList = new ArrayList(); + ArrayList newList = new ArrayList(); for (SemanticError element : list) { if (!customContains(newList, element)) { diff --git a/src/semanticanalysis/SymbolTable.java b/src/semanticanalysis/SymbolTable.java index db9649c..b620af7 100644 --- a/src/semanticanalysis/SymbolTable.java +++ b/src/semanticanalysis/SymbolTable.java @@ -1,8 +1,8 @@ package semanticanalysis; +import ast.types.*; import java.util.ArrayList; import java.util.HashMap; -import ast.types.*; /** * Class representing a symbol table. It's a list of hash table symbol table. We @@ -11,12 +11,12 @@ import ast.types.*; */ public class SymbolTable { - private ArrayList> symbolTable; - private ArrayList offset; + private final ArrayList> symbolTable; + private final ArrayList offset; public SymbolTable() { - this.symbolTable = new ArrayList>(); - this.offset = new ArrayList(); + this.symbolTable = new ArrayList(); + this.offset = new ArrayList(); } /** @@ -96,7 +96,7 @@ public class SymbolTable { */ public boolean top_lookup(String id) { int n = symbolTable.size() - 1; - STentry T = null; + STentry T; HashMap H = symbolTable.get(n); T = H.get(id); return (T != null); @@ -125,14 +125,6 @@ public class SymbolTable { // We always increment the offset by 1 otherwise we need ad-hoc bytecode // operations - // FIXME: wtf is that? - // if (type.getClass().equals((new BoolType()).getClass())) { - // offs = offs + 1; - // } else if (type.getClass().equals((new IntType()).getClass())) { - // offs = offs + 1; - // } else { - // offs = offs + 1; - // } offs = offs + 1; this.offset.add(offs); -- cgit v1.2.3-71-g8e6c