add error handling: parser now throws exceptions

This commit is contained in:
Trolli Schmittlauch 2017-06-28 00:03:14 +02:00
parent c3953449ff
commit 58047569f8
2 changed files with 9 additions and 4 deletions

View file

@ -80,7 +80,7 @@ class JobShopVisitor(arpeggio.PTNodeVisitor):
if len(job_numbers) % 2 ==1: if len(job_numbers) % 2 ==1:
raise ParseError("Odd number of numbers in job data") raise ParseError("Odd number of numbers in job data")
# returns list of (duration, machine) tuples # returns list of (duration, machine) tuples
return list(zip(job_numbers[1::2], job_numbers[0::2])) # [::2] returns only every second element of the list return list(zip(job_numbers[1::2], job_numbers[0::2])) # [::2] returns only every second element of the list
def visit_problem_data(self, node: arpeggio.ParseTreeNode, children: arpeggio.SemanticActionResults) -> JobShopProblem: def visit_problem_data(self, node: arpeggio.ParseTreeNode, children: arpeggio.SemanticActionResults) -> JobShopProblem:
if self.debug: if self.debug:

View file

@ -16,13 +16,18 @@ class JobShop2Visitor(JobShopVisitor):
def parse_jobshop2_string(inputdata: str) -> JobShopProblem: def parse_jobshop2_string(inputdata: str) -> JobShopProblem:
"""parse string of jobshop2-formatted data (single problem instance, no name & description) """parse string of jobshop2-formatted data (single problem instance, no name & description)
and return JobShopProblem""" and return JobShopProblem
parse_tree = parser.parse(inputdata) Raises a ParseError exception on errors"""
try:
parse_tree = parser.parse(inputdata)
except arpeggio.NoMatch as e:
raise ParseError("Error while parsing problem input data at line {}, col {}:\n Rules {} did not match.".format(e.line, e.col, e.rules))
return arpeggio.visit_parse_tree(parse_tree, JobShop2Visitor()) return arpeggio.visit_parse_tree(parse_tree, JobShop2Visitor())
def parse_jobshop2_file(filename: Union[str, bytes]) -> JobShopProblem: def parse_jobshop2_file(filename: Union[str, bytes]) -> JobShopProblem:
"""Open file with jobshop2-formatted data (single problem instance, no name & description), """Open file with jobshop2-formatted data (single problem instance, no name & description),
parse it and return JobShopProblem""" parse it and return JobShopProblem
Raises a ParseError exception on errors"""
with open(filename) as datafile: with open(filename) as datafile:
inputdata: str = datafile.read() inputdata: str = datafile.read()