Merge pull request #380 from parrt/master

get last not first when get() finds multiple matching nodes.
This commit is contained in:
Terence Parr 2013-12-20 12:48:23 -08:00
commit 6f48625618
2 changed files with 28 additions and 6 deletions

View File

@ -97,11 +97,11 @@ public class ParseTreeMatch {
}
/**
* Get the first node associated with a specific {@code label}.
* Get the last node associated with a specific {@code label}.
* <p/>
* For example, for pattern {@code <id:ID>}, {@code get("id")} returns the
* node matched for that {@code ID}. If more than one node
* matched the specified label, only the first is returned. If there is
* matched the specified label, only the last is returned. If there is
* no node associated with the label, this returns {@code null}.
* <p/>
* Pattern tags like {@code <ID>} and {@code <expr>} without labels are
@ -109,7 +109,7 @@ public class ParseTreeMatch {
*
* @param label The label to check.
*
* @return The first {@link ParseTree} to match a tag with the specified
* @return The last {@link ParseTree} to match a tag with the specified
* label, or {@code null} if no parse tree matched a tag with the label.
*/
@Nullable
@ -119,7 +119,7 @@ public class ParseTreeMatch {
return null;
}
return parseTrees.get(0); // return first if multiple
return parseTrees.get( parseTrees.size()-1 ); // return last if multiple
}
/**

View File

@ -193,6 +193,28 @@ public class TestParseTreeMatcher extends BaseTest {
assertEquals("[]", m.getAll("undefined").toString());
}
@Test public void testLabelGetsLastIDNode() throws Exception {
String grammar =
"grammar X9;\n" +
"s : ID ID ';' ;\n" +
"ID : [a-z]+ ;\n" +
"WS : [ \\r\\n\\t]+ -> skip ;\n";
String input = "x y;";
String pattern = "<id:ID> <id:ID>;";
ParseTreeMatch m = checkPatternMatch(grammar, "s", input, pattern, "X9");
assertEquals("{ID=[x, y], id=[x, y]}", m.getLabels().toString());
assertNotNull(m.get("id"));
assertNotNull(m.get("ID"));
assertEquals("y", m.get("id").getText());
assertEquals("y", m.get("ID").getText());
assertEquals("[x, y]", m.getAll("id").toString());
assertEquals("[x, y]", m.getAll("ID").toString());
assertNull(m.get("undefined"));
assertEquals("[]", m.getAll("undefined").toString());
}
@Test public void testIDNodeWithMultipleLabelMatches() throws Exception {
String grammar =
"grammar X7;\n" +
@ -207,9 +229,9 @@ public class TestParseTreeMatcher extends BaseTest {
assertNotNull(m.get("a")); // get first
assertNotNull(m.get("b"));
assertNotNull(m.get("ID"));
assertEquals("x", m.get("a").getText());
assertEquals("z", m.get("a").getText());
assertEquals("y", m.get("b").getText());
assertEquals("x", m.get("ID").getText()); // get first
assertEquals("z", m.get("ID").getText()); // get last
assertEquals("[x, z]", m.getAll("a").toString());
assertEquals("[y]", m.getAll("b").toString());
assertEquals("[x, y, z]", m.getAll("ID").toString()); // ordered