From ad6935723ece180fb7636db8ad77914726988e13 Mon Sep 17 00:00:00 2001 From: mudabbir-ahmad Date: Mon, 27 Apr 2026 18:11:49 +0100 Subject: [PATCH] Add TreesUser class for improved tree representation and update grammar rules --- Q1/Artefacts/RobotLang.g4 | 4 ++-- Q1/Artefacts/TreesUser.py | 27 +++++++++++++++++++++++++++ Q1/Artefacts/main.py | 10 ++++------ 3 files changed, 33 insertions(+), 8 deletions(-) create mode 100644 Q1/Artefacts/TreesUser.py diff --git a/Q1/Artefacts/RobotLang.g4 b/Q1/Artefacts/RobotLang.g4 index 104c9e1..be57e12 100644 --- a/Q1/Artefacts/RobotLang.g4 +++ b/Q1/Artefacts/RobotLang.g4 @@ -18,6 +18,6 @@ logStat: 'LOG' STRING ';' ; repeatStat: 'REPEAT' NUMBER '{' stat+ '}' ; ID_PREFIX: '// STUDENT ID:' ; -NUMBER: [0-9]+ ; -STRING: '"' .*? '"' {self.text = self.text[1:-1]} ; +NUMBER: [1-9]+ ; +STRING: '"' .*? '"' ; WS: [ \t\r\n]+ -> skip ; \ No newline at end of file diff --git a/Q1/Artefacts/TreesUser.py b/Q1/Artefacts/TreesUser.py new file mode 100644 index 0000000..20b0c79 --- /dev/null +++ b/Q1/Artefacts/TreesUser.py @@ -0,0 +1,27 @@ +from antlr4.Utils import escapeWhitespace +from antlr4.tree.Tree import Tree +from antlr4.tree.Trees import Trees + +# need forward declaration +Parser = None + +class TreesUser(Trees): + + # Print out a whole tree in prettier form + # Based on Trees.toStringTree() + # indent is the number of indents to use in the display + @classmethod + def PrettyPrint(cls, t:Tree, ruleNames:list=None, recog:Parser=None, indent:int=0): + # indentation is the indent to actually display + indentation = '' + for n in range(indent): + indentation += ' ' + if recog is not None: + ruleNames = recog.ruleNames + s = escapeWhitespace(cls.getNodeText(t, ruleNames), False) + retval = indentation + s + "\n" + if t.getChildCount()>0: + # we have children to deal with + for i in range(0, t.getChildCount()): + retval += cls.PrettyPrint(t.getChild(i), ruleNames, indent=indent+1) + return retval diff --git a/Q1/Artefacts/main.py b/Q1/Artefacts/main.py index 4333379..8ccf574 100644 --- a/Q1/Artefacts/main.py +++ b/Q1/Artefacts/main.py @@ -5,21 +5,19 @@ from RobotLangParser import RobotLangParser from RobotLangVisitorUser import RobotLangVisitorUser def main(argv): - # Determine if reading from a file or standard input if len(argv) == 1: inpstream = StdinStream() else: inpname = argv[1] inpstream = FileStream(inpname) - # Lexer analyses the characters lexer = RobotLangLexer(inpstream) - # Create a stream of tokens + #Create a stream of tokens tokstream = CommonTokenStream(lexer) - # Parser produces the abstract syntax tree + #Parser produces the abstract syntax tree parser = RobotLangParser(tokstream) - # Start parsing from the top rule + #Start parsing from the top rule tree = parser.prog() - + #execute script visitor = RobotLangVisitorUser() visitor.visit(tree)