EmbASP-Python
clingo_parser_visitor_implementation.py
1 from .ClingoLexer import ClingoLexer
2 from .ClingoParser import ClingoParser
3 from .ClingoParserVisitor import ClingoParserVisitor
4 from antlr4 import PredictionMode
5 from antlr4.CommonTokenStream import CommonTokenStream
6 from antlr4.error.ErrorListener import ConsoleErrorListener
7 from antlr4.error.Errors import RecognitionException
8 from antlr4.error.ErrorStrategy import BailErrorStrategy, DefaultErrorStrategy
9 from antlr4.InputStream import InputStream
10 
11 
13  def __init__(self, answerSets):
14  self._answerSets = answerSets
15 
16  def visitAnswer_set(self, ctx):
17  self._answerSets.add_answer_set()
18 
19  return self.visitChildren(ctx)
20 
21  def visitModel(self, ctx):
22  cost = ctx.NEW_LINE().getText().strip()
23 
24  if len(cost) > 1:
25  tokens = cost.split(' ')
26  levels = len(tokens) - 1
27 
28  for index in range(1, len(tokens)):
29  self._answerSets.store_cost(levels, tokens[index])
30  levels -= 1
31 
32  return self.visitChildren(ctx)
33 
34  def visitPredicate_atom(self, ctx):
35  self._answerSets.store_atom(ctx.getText())
36 
37  @staticmethod
38  def parse(answerSets, clingoOutput, two_stageParsing):
39  tokens = CommonTokenStream(ClingoLexer(InputStream(clingoOutput)))
40  parser = ClingoParser(tokens)
41  visitor = ClingoParserVisitorImplementation(answerSets)
42 
43  if not two_stageParsing:
44  visitor.visit(parser.output())
45 
46  return
47 
48  parser._interp.predictionMode = PredictionMode.SLL
49  parser.removeErrorListeners()
50  parser._errHandler = BailErrorStrategy()
51 
52  try:
53  visitor.visit(parser.output())
54  except RuntimeError as exception:
55  if isinstance(exception, RecognitionException):
56  tokens.seek(0)
57  parser.addErrorListener(ConsoleErrorListener.INSTANCE)
58  parser._errHandler = DefaultErrorStrategy()
59  parser._interp.predictionMode = PredictionMode.LL
60  visitor.visit(parser.output())
parsers.asp.clingo.ClingoParser.ClingoParser
Definition: ClingoParser.py:31
parsers.asp.clingo.ClingoParserVisitor.ClingoParserVisitor
Definition: ClingoParserVisitor.py:6
parsers.asp.clingo.clingo_parser_visitor_implementation.ClingoParserVisitorImplementation
Definition: clingo_parser_visitor_implementation.py:12
parsers.asp.clingo.clingo_parser_visitor_implementation.ClingoParserVisitorImplementation._answerSets
_answerSets
Definition: clingo_parser_visitor_implementation.py:14
parsers.asp.clingo.ClingoLexer.ClingoLexer
Definition: ClingoLexer.py:56