From d68976b55e2710b071d90ca59ceaf60cc0907c6a Mon Sep 17 00:00:00 2001 From: weckyy702 Date: Wed, 30 Dec 2020 14:45:54 +0100 Subject: [PATCH] interpreter improvements and error handling in NSD image saving --- .vscode/launch.json | 2 +- interpreter/NassiShneidermann.py | 19 ++- interpreter/interpret_source.py | 25 ++-- res/input/input.java | 2 - res/input/input_parsed.java | 249 +++++++++++++++++++++++++++++++ 5 files changed, 277 insertions(+), 20 deletions(-) create mode 100644 res/input/input_parsed.java diff --git a/.vscode/launch.json b/.vscode/launch.json index 1ded7e8..e80f071 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -8,7 +8,7 @@ "name": "Python: Aktuelle Datei", "type": "python", "request": "launch", - "program": "run.py", + "program": "debug.py", "console": "integratedTerminal" } ] diff --git a/interpreter/NassiShneidermann.py b/interpreter/NassiShneidermann.py index 8aa7085..22a6db9 100644 --- a/interpreter/NassiShneidermann.py +++ b/interpreter/NassiShneidermann.py @@ -66,15 +66,20 @@ class NassiShneidermanDiagram: filepath = self.check_conflicts(filepath, on_conflict) if filepath is not None: logging.info(f"Saving NSD to {filepath}...") - print(f"Saving... to {filepath}") image_y_sz = self._get_image_height(i) - with NSD_writer(filepath, x_size, image_y_sz): - scope = self.function_scopes[i].contents - x, y = 0, 0 - for instruction in scope: - x, y = instruction.to_image(x, y, x_size) - logging.info("Done!") + try: + with NSD_writer(filepath, x_size, image_y_sz): + scope = self.function_scopes[i].contents + x, y = 0, 0 + for instruction in scope: + x, y = instruction.to_image(x, y, x_size) + logging.info("Done!") + except Exception as e: + logging.error(f"Failed to save image {filepath} with error '{e}'") + except: + logging.error(f"Failed to save image {filepath}. Unknown error") + raise def load_from_file(self, filepath:str): self.function_scopes = itp.load_scoped_instructions(filepath) \ No newline at end of file diff --git a/interpreter/interpret_source.py b/interpreter/interpret_source.py index 05573d6..2b8a997 100644 --- a/interpreter/interpret_source.py +++ b/interpreter/interpret_source.py @@ -7,7 +7,7 @@ from typing import List, Match, Tuple from errors.custom import InterpreterException, JavaSyntaxError, ScopeNotFoundException from draw.Iinstruction import * -logging.warning("""As the Interpreter is still WIP, some Java language features are not supported. These include: +logging.warning("""Because the Interpreter is still WIP, some Java language features are not supported. These include: *else if statements *for loops Please remove these features from the source code as they will result in incorrect behaviour""") @@ -23,7 +23,7 @@ class Function_scope(Iterable): return self.contents.__iter__() COMMENT_PATTERN = re.compile(r"""^//|^/\*\*|^\*|^--""") -REMOVE_KEYWORDS = [' ', "public", "private", "final"] +REMOVE_KEYWORDS = [' ', ';', "public", "private", "final", "protected"] VARIABLE_TAGS = ["byte", "short", "int", "long", "float", "double", "boolean", "char", "String"] FUNCTION_IDENTIFIERS = ["void"] FUNCTION_IDENTIFIERS.extend(VARIABLE_TAGS) @@ -34,14 +34,15 @@ REPLACE = dict((re.escape(k), '') for k in REMOVE_KEYWORDS) remove_pattern = re.compile("|".join(REPLACE.keys())) variable_regex = "^(" -for kw in FUNCTION_IDENTIFIERS: +for kw in VARIABLE_TAGS: variable_regex += fr"""{kw}|""" -variable_pattern = re.compile(variable_regex[0:-1]+")(.*)") +variable_pattern = re.compile(variable_regex[0:-1]+")(.*=|.*;)(.*)") +print(variable_pattern) function_regex = "^(" for kw in FUNCTION_IDENTIFIERS: function_regex += fr"""{kw}|""" -function_regex = function_regex[0:-1]+ r""").*([(].*[)].*)""" +function_regex = function_regex[0:-1]+ ").*([(].*[)].*)" function_pattern = re.compile(function_regex) @@ -150,8 +151,12 @@ def handle_do_while(line: str, src: List[str], i: int) -> Tuple[Iinstruction, in def handle_variable(line:str, src: List[str], i: int) -> Tuple[Iinstruction, int]: groups = variable_pattern.match(line).groups() var_type = groups[0] - var_name = groups[1] - return generic_instruction(f"{var_type} {var_name}"), i + var_name = groups[1][:-1] + var_value = groups[2] + if var_value == "": + return generic_instruction(f"declare variable '{var_name}' of type {var_type}"), i + return generic_instruction(f"declare variable '{var_name}' of type {var_type} with value {var_value}"), i + def handle_instruction(line: str, src: List[str], i: int) -> Tuple[Iinstruction, int]: if line.startswith("while("): @@ -166,9 +171,9 @@ def handle_instruction(line: str, src: List[str], i: int) -> Tuple[Iinstruction, logging.debug("Found do-while construct in line: %i", i+1) return handle_do_while(line, src, i) - # elif variable_pattern.match(line): - # logging.debug("Found variable in line %i", i+1) - # return handle_variable(line, src, i) + elif variable_pattern.match(line): + logging.debug("Found variable in line %i", i+1) + return handle_variable(line, src, i) else: logging.debug("found generic instruction in line %i", i+1) diff --git a/res/input/input.java b/res/input/input.java index 108ef23..b4e9624 100644 --- a/res/input/input.java +++ b/res/input/input.java @@ -274,7 +274,6 @@ public class Rover extends Actor protected void addedToWorld(World world) { - setImage("images/rover.png"); world = getWorld(); anzeige = new Display(); @@ -285,7 +284,6 @@ public class Rover extends Actor setLocation(getX(),1); } anzeige.anzeigen("Ich bin bereit"); - } class Display extends Actor diff --git a/res/input/input_parsed.java b/res/input/input_parsed.java new file mode 100644 index 0000000..bc0b4da --- /dev/null +++ b/res/input/input_parsed.java @@ -0,0 +1,249 @@ +//except for this line, this is what interpret_source.load_src returns +importgreenfoot.*;//(World,Actor,GreenfootImage,GreenfootandMouseInfo) +classRoverextendsActor +{ +Displayanzeige; +voidact() +{ +S66Nr3(7); +} +voidfahreUmHuegel(Stringrichtung) +{ +Stringpri; +Stringsec; +if(richtung.equals("Hoch")){ +pri="links"; +sec="rechts"; +}else{ +if(richtung.equals("Runter")){ +pri="rechts"; +sec="links"; +}else{ +nachricht("JUNGEDUSPAST!"); +return; +} +} +drehe(pri); +fahre(); +drehe(sec); +fahre(); +fahre(); +drehe(sec); +fahre(); +drehe(pri); +} +voidfahreBisHuegel() +{ +while(!huegelVorhanden("vorne")) +{ +fahre(); +} +} +voidfahreZeileDreheHoch() +{ +fahreBisHuegel(); +fahreUmHuegel("Hoch"); +fahreBisHuegel(); +drehe("um"); +fahreBisHuegel(); +fahreUmHuegel("Runter"); +fahreBisHuegel(); +drehe("rechts"); +fahre(); +drehe("rechts"); +} +voidfahreZeileDreheRunter(booleangeheInNächsteZeile) +{ +fahreBisHuegel(); +fahreUmHuegel("Runter"); +fahreBisHuegel(); +drehe("um"); +fahreBisHuegel(); +fahreUmHuegel("Hoch"); +fahreBisHuegel(); +if(geheInNächsteZeile){ +drehe("rechts"); +fahre(); +drehe("rechts"); +}else{ +drehe("um"); +} +} +voidS66Nr3(intanzahlZeilen) +{ +if(anzahlZeilen<3){ +nachricht("IchmussmindestensdreiZeilenfahren!:("); +return; +} +fahreZeileDreheHoch(); +for(inti=1;i30) +{ +returntrue; +} +} +if(richtung=="vorne"&&rot==180||richtung=="rechts"&&rot==90||richtung=="links"&&rot==270) +{ +if(getOneObjectAtOffset(-1,0,Huegel.class)!=null&&((Huegel)getOneObjectAtOffset(-1,0,Huegel.class)).getSteigung()>30) +{ +returntrue; +} +} +if(richtung=="vorne"&&rot==90||richtung=="rechts"&&rot==0||richtung=="links"&&rot==180) +{ +if(getOneObjectAtOffset(0,1,Huegel.class)!=null&&((Huegel)getOneObjectAtOffset(0,1,Huegel.class)).getSteigung()>30) +{ +returntrue; +} +} +if(richtung=="vorne"&&rot==270||richtung=="rechts"&&rot==180||richtung=="links"&&rot==0) +{ +if(getOneObjectAtOffset(0,-1,Huegel.class)!=null&&((Huegel)getOneObjectAtOffset(0,-1,Huegel.class)).getSteigung()>30) +{ +returntrue; +} +} +if(richtung!="vorne"&&richtung!="links"&&richtung!="rechts") +{ +nachricht("Befehlnichtkorrekt!"); +} +returnfalse; +} +voidanalysiereGestein() +{ +if(gesteinVorhanden()) +{ +nachricht("Gesteinuntersucht!Wassergehaltist"+((Gestein)getOneIntersectingObject(Gestein.class)).getWassergehalt()+"%."); +Greenfoot.delay(1); +removeTouching(Gestein.class); +} +else +{ +nachricht("HieristkeinGestein"); +} +} +voidsetzeMarke() +{ +getWorld().addObject(newMarke(),getX(),getY()); +} +booleanmarkeVorhanden() +{ +if(getOneIntersectingObject(Marke.class)!=null) +{ +returntrue; +} +returnfalse; +} +voidentferneMarke() +{ +if(markeVorhanden()) +{ +removeTouching(Marke.class); +} +} +voidnachricht(StringpText) +{ +if(anzeige!=null) +{ +anzeige.anzeigen(pText); +Greenfoot.delay(1); +anzeige.loeschen(); +} +} +voiddisplayAusschalten() +{ +getWorld().removeObject(anzeige); +} +protectedvoidaddedToWorld(Worldworld) +{ +setImage("images/rover.png"); +world=getWorld(); +anzeige=newDisplay(); +anzeige.setImage("images/nachricht.png"); +world.addObject(anzeige,7,0); +if(getY()==0) +{ +setLocation(getX(),1); +} +anzeige.anzeigen("Ichbinbereit"); +} +classDisplayextendsActor +{ +GreenfootImagebild; +Display() +{ +bild=getImage(); +} +voidact() +{ +} +voidanzeigen(StringpText) +{ +loeschen(); +getImage().drawImage(newGreenfootImage(pText,25,Color.BLACK,newColor(0,0,0,0)),10,10); +} +voidloeschen() +{ +getImage().clear(); +setImage("images/nachricht.png"); +} +} +classDirection{ +Direction(intval){ +this.value=val; +} +intvalue; +}; +}