Write a Java program (using JFIex/Cup) to interpret WAE expressions. The CFG for
ID: 3784812 • Letter: W
Question
Write a Java program (using JFIex/Cup) to interpret WAE expressions. The CFG for WAE expressions is given below: SEMI ::= I {+ ) I (- } I {with { ) > I You will write a main program, called WAE.java, that prompts the user with wae>. The user can enter a WAE expression at the prompt or type exit to exit the WAE interpreter. If the user enters a WAE expression, your program should verify that it is a valid expression. If the expression is valid, it should be evaluated and the value of the expression should be printed; Otherwise and error message should be reported. $ java WAE WAE> (with {x 3} {with {y 4} {with (Z 5} {+ x (+ y z)}}}} The value is 12 WAE> (with (x 3) (with {y 4} {+ y z}} Syntax Error WAE> (with (x 3) (with (y 4) {+ y 2}}} Semantic ErrorExplanation / Answer
import java.util.regex.*;
class RegexDemo
{
public static void main (String [] args)
{
if (args.length != 2)
{
System.err.println ("java RegexDemo regex text");
return;
}
Pattern p;
try
{
p = Pattern.compile (args [0]);
}
catch (PatternSyntaxException e)
{
System.err.println ("Regex syntax error: " + e.getMessage ());
System.err.println ("Error description: " + e.getDescription ());
System.err.println ("Error index: " + e.getIndex ());
System.err.println ("Erroneous pattern: " + e.getPattern ());
return;
}
String s = cvtLineTerminators (args [1]);
Matcher m = p.matcher (s);
System.out.println ("Regex = " + args [0]);
System.out.println ("Text = " + s);
System.out.println ();
while (m.find ())
{
System.out.println ("Found " + m.group ());
System.out.println (" starting at index " + m.start () +
" and ending at index " + m.end ());
System.out.println ();
}
}
static String cvtLineTerminators (String s)
{
StringBuffer sb = new StringBuffer (80);
int oldindex = 0, newindex;
while ((newindex = s.indexOf (" ", oldindex)) != -1)
{
sb.append (s.substring (oldindex, newindex));
oldindex = newindex + 2;
sb.append (' ');
}
sb.append (s.substring (oldindex));
s = sb.toString ();
sb = new StringBuffer (80);
oldindex = 0;
while ((newindex = s.indexOf (" ", oldindex)) != -1)
{
sb.append (s.substring (oldindex, newindex));
oldindex = newindex + 2;
sb.append (' ');
}
sb.append (s.substring (oldindex));
return sb.toString ();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.