+ new structure

This commit is contained in:
oleting
2020-12-24 00:17:54 +01:00
parent dca758b597
commit 5c6cf88991
13 changed files with 142 additions and 135 deletions

View File

@@ -0,0 +1,51 @@
from typing import List
import logging
from draw.Iinstruction import Iinstruction
from interpreter import interpret_source as itp
from draw import code_to_image as cti
class NassiShneidermanDiagram:
def __init__(self, debug: bool=False) -> None:
self.instructions: dict[str, Iinstruction] = {}
self.init_logging(debug)
def init_logging(self, debug: bool):
logLevel = logging.INFO
if debug:
logLevel = logging.DEBUG
logging.basicConfig(level=logLevel)
def add_instruction(self, instruction: Iinstruction):
instruction_key = "instruction#" + str(len(self.instructions))
self.instructions[instruction_key] = instruction
logging.debug("added instruction %s : %s", instruction_key, instruction.instruction_text)
def convert_to_image(self, filename: str, x_size=200):
logging.info(f"Saving NSD to {filename}.png")
cti.NSD_init(x_size, 5000)
x, y, x_sz = 0, 0, x_size
for _k, instruction in self.instructions.items():
x, y = instruction.to_image(x, y, x_sz, 800)
cti.NSD_save(filename)
def load_from_file(self, filepath:str):
src_code = itp.load_src(filepath)
global_scope = itp.get_instructions_in_scope(src_code)[0]
self.add_instructions_from_scope(global_scope)
def add_instructions_from_scope(self, scope: List[Iinstruction]):
for inst in scope:
self.add_instruction(inst)
if __name__ == "__main__":
NSD = NassiShneidermanDiagram(True)
NSD.load_from_file("res/input/input.java")
NSD.convert_to_image("Nina", 500)

0
interpreter/__init__.py Normal file
View File

View File

@@ -0,0 +1,87 @@
import logging
import re
from typing import List, Tuple
from draw.Iinstruction import *
class Scope():
def __init__(self, enclosing_scope) -> None:
self.enclosing_scope = enclosing_scope
self.contents: List = []
def add_instruction(self, instruction: Iinstruction) -> None:
self.contents.append(instruction)
def load_src(filepath: str) -> List[str]:
lines: List[str] = []
brace_open_count, brace_closed_count = 0,0
try:
with open(filepath) as file:
for _line in file:
line = _line.strip().replace(' ', '')
if line and not re.match(r"""^//|^#|^COMMENT|^--""", line):
lines.append(line)
if line.__contains__('{'):
brace_open_count += 1
if line.__contains__('}'):
brace_closed_count += 1
except:
logging.error(f"Failed to open input file {filepath}!")
if brace_open_count != brace_closed_count:
raise Exception("Number of opened braces does not match number of closed ones. Program is illformed!")
return lines
def get_instructions_in_scope(src: List[str], start_idx: int = 0) -> Tuple[List[Iinstruction], int]:
outer_scope = Scope(None)
i = start_idx
while i < len(src):
line = src[i]
try:
if line.__contains__('}'): #We exited this scope, return it
return outer_scope.contents, i
if line.startswith("while("):
logging.debug("Found while instruction in line: %i", i+1)
bracket_idx = line.rindex(')') # throws if the while is illformed
instruction_txt = line[6:bracket_idx]
child_instructions, i = get_instructions_in_scope(src, i+1)
outer_scope.add_instruction(while_instruction_front(instruction_txt, child_instructions))
elif line.startswith("if("):
logging.debug("Found if instruction in line: %i", i+1)
bracket_idx = line.rindex(')') # throws if the contruct is illformed
instruction_txt = line[3:bracket_idx]
true_instructions, i = get_instructions_in_scope(src, i+2)
false_instructions = None
if src[i].__contains__("else"): #if there is an else statement, check it
false_instructions, i = get_instructions_in_scope(src, i+2)
outer_scope.add_instruction(if_instruction(instruction_txt, true_instructions, false_instructions))
elif line.startswith("do{"):
logging.debug("Found start of do-while instruction in line: %i", i)
child_instructions, i = get_instructions_in_scope(src, i+1)
end_line = src[i]
#line: }while(...);
bracket_idx = end_line.rindex(");")
instruction_txt = end_line[7: bracket_idx]
outer_scope.add_instruction(while_instruction_back(instruction_txt, child_instructions))
else:
logging.debug("Found generic instruction in line: %i", i+1)
outer_scope.add_instruction(generic_instruction(line))
except:
logging.error("Encountered error in line: %i", i)
raise # rethrow
i += 1
return outer_scope.contents, 0
if __name__ == "__main__":
"""debuging"""
logging.basicConfig(level=logging.DEBUG)
#inst = get_scoped_instructions("res/input/input.java")
lines = load_src("res/input/input.java")
global_scope = get_instructions_in_scope(lines)
print(global_scope)