public
Created

  • Download Gist
gistfile1.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
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());
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.