2014-02-27 3 views
0

나는 다음과 같은 문법이에서를 getAll (...)를 사용하는 방법 : 간단한 첫 번째 순서 논리 수식을 구문 분석ParseTreeMatch ANTLR4

input 
: 
formula EOF 
; 

formula 
: 
TRUE       
| FALSE      
| formula AND formula  
| formula OR formula   
| (quantifier)+ ST condition   
; 


condition 
: 
atom EQUALS QUOTE? (assignment | atom) QUOTE? 
; 

quantifier 
: 
(FOREACH | EXISTS) variable IN domain 
; 
..... 

합니다. 따라서 다음 코드를 사용하십시오 :

String formulaPatternString = "<formula>"; 
ParseTreePattern formulaPattern = parser.compileParseTreePattern(formulaPatternString, GraphParser.RULE_formula); 
List<ParseTreeMatch> formulaMatches = formulaPattern.findAll(tree, "//formula"); 

입력 한 내용의 수를 찾고 있습니다. 예

를 들어
Exists node in GraphA -> node.color='red' 

반환 한 formulaMatch

Exists node in GraphA -> node.color='red' AND Foreach node in GraphA Exists node1 in GraphB -> node.color=node1.color 

반환이 formulaMatches. 지금은 수식의 수량 한정자로 끝나기 위해 formulaMatches을 사용하고 싶습니다 (하나 이상을 허용하는 것을 볼 수 있듯이). 나는 내가 필요로하는 방법이 formulaMatches.get(i).getAll("quantifier")이라고 생각했다. 그러나이 결과는 0으로 일치한다. (내 경우에는 첫 번째 수식의 한정자 부분은 Exists node in GraphA이고 두 번째 부분은 Foreach node in GraphA Exists node1 in GraphB이고 2 개의 한정 기호이다.) 어떻게 내가 이걸 이룰 수 있을지 아는가?

답변

1

formulaMatches의 각 요소는 <formula> 자리 표시 자에 해당하는 ParseTree을 얻는 데 사용할 수있는 ParseTreeMatch 개체입니다. 그 파스 트리는 FormulaContext이 될 것입니다.

for (ParseTreeMatch match : formulaMatches) { 
    int quantifierCount = ((FormulaContext)match.get("formula")).quantifier().size(); 
} 

참고 : 당신은이 QuantifierContext 아이의 수를 얻을 수 FormulaContextquantifier() 방법을 사용할 수 있습니다 당신은 ParserInterpreter를 사용하여 구문 분석하는 경우, 사용자의 컨텍스트 객체는 InterpreterRuleContext 대신 FormulaContext 될 것입니다. ParseTreeMatch 변환 할 수 없습니다 : 나도`FormulaContext` 또는`ParseRuleContext` 나는 호환되지 않는 유형 '으로 끝날 수있는`ParseTreeMatch`을 구분하려고 할 때

for (ParseTreeMatch match : formulaMatches) { 
    ParserRuleContext formulaContext = (FormulaContext)match.get("formula"); 
    int quantifierCount = 0; 
    for (int i = 0; i < formulaContext.getChildCount(); i++) { 
    if (formulaContext.getChild(i) instanceof RuleNode 
     && ((RuleNode)formulaContext.getChild(i)).getRuleContext().getRuleIndex() 
      == RULE_quantifier) 
    { 
     quantifierCount++; 
    } 
    } 

    // quantifierCount is accurate here... 
} 
+0

음 :이 경우, 다음 호출 할 수 있습니다 ~ ParserRuleContex'와'호환되지 않는 타입 : ParseTreeMatch는 FormulaContext'로 변환 될 수 없습니다. – Wosh

+0

그리고 또 하나의 질문 :'ParseInterpreter'로 파싱하는지 여부를 어떻게 알 수 있습니까? – Wosh

+0

'ParseTreeMatch'의 사용법을 수정하기 위해 내 게시물을 업데이트했습니다. 그러한 간단한 표현식의 경우, 패턴 대신에 XPath 표현식'// formula'를 사용해야하지만 어느 방법이든 작동합니다. 코드에서'ParserInterpreter'를 사용한다면'ParserInterpreter'를 사용하고 있습니다. –