Skip to content

Commit

Permalink
Merge pull request #6 from Faterou/master
Browse files Browse the repository at this point in the history
Added getAlternatives to BnfParser, a test to test the function and c…
  • Loading branch information
sylvainhalle authored May 15, 2017
2 parents 9affc41 + 6550a75 commit f047128
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
24 changes: 24 additions & 0 deletions Source/Parsing/src/ca/uqac/lif/bullwinkle/BnfParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
Expand Down Expand Up @@ -295,6 +296,29 @@ public static List<BnfRule> getRules(String grammar) throws InvalidGrammarExcept
}
return rules;
}

/**
* Returns the list of alternative rules
* @param rule_name The rule you need the alternatives
* @return a list of strings representing the alternatives
*/
public List<String> getAlternatives(String rule_name)
{
for (BnfRule rule : m_rules)
{
String lhs = rule.getLeftHandSide().getName();
if (rule_name.compareTo(lhs) == 0)
{
List<String> alternatives = new ArrayList<String>();
for(TokenString alt : rule.getAlternatives())
{
alternatives.add(alt.toString());
}
return alternatives;
}
}
return null;
}

/**
* Adds a rule to the parser at a specific position.
Expand Down
2 changes: 1 addition & 1 deletion Source/Parsing/src/ca/uqac/lif/bullwinkle/BnfRule.java
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ public List<TokenString> getAlternatives()
* Retrieves the left-hand side symbol of the rule
* @return The left-hand side symbol
*/
NonTerminalToken getLeftHandSide()
public NonTerminalToken getLeftHandSide()
{
return m_leftHandSide;
}
Expand Down
26 changes: 26 additions & 0 deletions Source/ParsingTest/src/ca/uqac/lif/bullwinkle/ParserTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
package ca.uqac.lif.bullwinkle;
import static org.junit.Assert.*;

import java.util.List;

import org.junit.Before;
import org.junit.Test;

Expand Down Expand Up @@ -92,5 +94,29 @@ public void simpleValidGrammarFromFile()
fail("Valid grammar has thrown an exception when parsed.");
}
}

@Test
public void getAlternativesTest()
{
boolean has_error = false;
BnfParser parser = new BnfParser();
try
{
parser.setGrammar("<S> := <a> | b;\n<a> := c;");
}
catch (BnfParser.InvalidGrammarException e)
{
has_error = true;
}
if (has_error)
{
fail("Valid grammar has thrown an exception when parsed.");
}

List<String> alternatives = parser.getAlternatives("<S>");

assertTrue(alternatives.get(0).compareTo("<a>") == 0);
assertTrue(alternatives.get(1).compareTo("b") == 0);
}

}

0 comments on commit f047128

Please sign in to comment.