Skip to content

@Tomcat88 /gist:4565047
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
package grammar;
import java.util.ArrayList;
import java.util.List;
public class Grammar {
private List<String> rules;
public Grammar(String...strings){
rules=new ArrayList<>();
for(String rule :strings)
rules.add(rule);
}
public List<String> getRules(){
return rules;
}
public static void main(String[] args){
Grammar a=new Grammar("S = ()","S = (S)","S = SS");
System.out.println(a.check("(()(()))"));
Grammar b=new Grammar("S = x | y | z","S = S + S","S = S - S","S = S * S","S = S / S","S = (S)");
System.out.println(b.check("(x + y) * x - z * y / (x + x)"));
System.out.println(b.check("(xx - zz + x / z)"));
System.out.println(b.check("x + y * x - z * y / x + x"));
}
}
package grammarAspect;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import grammar.*;
public aspect GrammarAspect {
public Map<String, String> Grammar.simplifiedRules;
public void simplify(Grammar t, String rule) {
String[] split = rule.split("=");
if (split.length < 2)
throw new IllegalArgumentException("Rule malformed: " + rule);
String[] splitPipe = split[1].split("\\|");
for (String part : splitPipe) {
System.out.println(part.trim() + "->" + split[0].trim());
t.simplifiedRules.put(part.trim(), split[0].trim());
}
}
public boolean Grammar.check(String toCheck) throws InterruptedException {
if (toCheck.length() == 1)
return true;
else {
boolean atLeastOne = false;
Iterator<String> values = simplifiedRules.keySet().iterator();
while (values.hasNext()) {
String value = values.next();
if (toCheck.contains(value)) {
toCheck = toCheck.replace(value,
simplifiedRules.get(value));
atLeastOne = true;
System.out.println(toCheck);
}
}
if (atLeastOne)
return check(toCheck);
else
return false;
}
}
after(Grammar t): execution(Grammar.new(..)) && this(t){
t.simplifiedRules = new HashMap<>();
Iterator<String> i = t.getRules().iterator();
while (i.hasNext()) {
simplify(t, i.next());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.