سؤال

لدي القواعد التالية :

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 محددات الكمية).أي فكرة كيف يمكنني تحقيق ذلك?

هل كانت مفيدة؟

المحلول

كل عنصر من عناصر formulaMatches سوف يكون ParseTreeMatch الكائن الذي يمكنك استخدامه للحصول على ParseTree المقابلة ل <formula> العنصر النائب في النمط الخاص بك.أن شجرة تحليل سيكون FormulaContext.يمكنك استخدام quantifier() طريقة FormulaContext للحصول على عدد من QuantifierContext الأطفال لديها:

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

ملاحظة:إذا كنت تقوم بالتحليل باستخدام ParserInterpreter, ، ستكون كائنات السياق الخاصة بك InterpreterRuleContext بدلا من FormulaContext.في هذه الحالة ، ستحتاج إلى الاتصال بما يلي:

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...
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top