Commit c6eed6ee authored by Administrator's avatar Administrator
Browse files

added examples and grammars

parent 7bb4a150
// Example 1
Sum = Number ("+" Number)* !_ ;
Number = [0-9]+ ;
import mouse.runtime.SourceFile;
class FileCalc
{
public static void main(String argv[])
{
myParser parser = new myParser(); // Instantiate Parser+Semantics
SourceFile src = new SourceFile(argv[0]); // Wrap the file
if (!src.created()) return; // Return if no file
boolean ok = parser.parse(src); // Apply parser to it
System.out.println(ok? "ok":"failed"); // Tell if succeeded
}
}
n = 0
f = 1
e = 1
e
n = n + 1
f = f * n
e = e + 1/f
e
n = n + 1
f = f * n
e = e + 1/f
e
n = n + 1
f = f * n
e = e + 1/f
e
n = n + 1
f = f * n
e = e + 1/f
e
n = n + 1
f = f * n
e = e + 1/f
e
n = n + 1
f = f * n
e = e + 1/f
e
n = n + 1
f = f * n
e = e + 1/f
e
n = n + 1
f = f * n
e = e + 1/f
e
n = n + 1
f = f * n
e = e + 1/f
e
n = n + 1
f = f * n
e = e + 1/f
e
// Example 10
Input = [\n\r]* Line++ EOF ;
Line = Space (Store / Print) ~{badLine}
/ BadLine ;
Store = Name Space Equ Sum EOL {store} ; // store result
Print = Sum EOL {print} ; // print result
BadLine = _++ EOL ; // skip bad line
Sum = Sign Product (AddOp Product)* {sum} ;
Product = Factor (OptMult Factor)* {product} ;
Factor = Digits? "." Digits Space {fraction}
/ Digits Space {integer}
/ Lparen Sum Rparen {unwrap}
/ Name Space {retrieve} ;
OptMult = MultOp? ;
Sign = ("-" Space)? ;
AddOp = [-+] Space <+ or -> ;
MultOp = [*/] Space <* or /> ;
Lparen = "(" Space <(> ;
Rparen = ")" Space <)> ;
Equ = "=" Space <=> ;
Digits = [0-9]+ ;
Name = [a-z]+ ;
Space = " "* {space} ;
EOL = [\n\r]+ / EOF <end of line> ;
EOF = !_ <end of file> ;
// Example 10
import java.util.Hashtable;
class mySemantics extends mouse.runtime.SemanticsBase
{
//-------------------------------------------------------------------
// Dictionary
//-------------------------------------------------------------------
private Hashtable<String,Double> dictionary = new Hashtable<String,Double>();
//-------------------------------------------------------------------
// Store = Name Space Equ Sum
// 0 1 2 3
//-------------------------------------------------------------------
void store()
{
lhs().actExec();
dictionary.put(rhs(0).text(),(Double)rhs(3).get());
}
//-------------------------------------------------------------------
// Print = Sum
// 0
//-------------------------------------------------------------------
void print()
{
lhs().actExec();
System.out.println((Double)rhs(0).get());
}
//-------------------------------------------------------------------
// Line = Store / Print (failed)
//-------------------------------------------------------------------
void badLine()
{
System.out.println(lhs().errMsg());
lhs().errClear();
}
//-------------------------------------------------------------------
// Sum = Sign Product AddOp Product ... AddOp Product
// 0 1 2 3 n-2 n-1
//-------------------------------------------------------------------
void sum()
{
int n = rhsSize();
double s = (Double)rhs(1).get();
if (!rhs(0).isEmpty()) s = -s;
for (int i=3;i<n;i+=2)
{
if (rhs(i-1).charAt(0)=='+')
s += (Double)rhs(i).get();
else
s -= (Double)rhs(i).get();
}
lhs().put(new Double(s));
}
//-------------------------------------------------------------------
// Product = Factor OptMult Factor ... OptMult Factor
// 0 1 2 n-2 n-1
//-------------------------------------------------------------------
void product()
{
int n = rhsSize();
double s = (Double)rhs(0).get();
for (int i=2;i<n;i+=2)
{
if (!rhs(i-1).isEmpty() && rhs(i-1).charAt(0)=='/')
s /= (Double)rhs(i).get();
else
s *= (Double)rhs(i).get();
}
lhs().put(new Double(s));
}
//-------------------------------------------------------------------
// Factor = Digits? "." Digits Space
// 0 1(0) 2(1) 3(2)
//-------------------------------------------------------------------
void fraction()
{ lhs().put(Double.valueOf(rhsText(0,rhsSize()-1))); }
//-------------------------------------------------------------------
// Factor = Digits Space
// 0 1
//-------------------------------------------------------------------
void integer()
{ lhs().put(Double.valueOf(rhs(0).text())); }
//-------------------------------------------------------------------
// Factor = Lparen Sum Rparen
// 0 1 2
//-------------------------------------------------------------------
void unwrap()
{ lhs().put(rhs(1).get()); }
//-------------------------------------------------------------------
// Factor = Name Space
// 0 1
//-------------------------------------------------------------------
void retrieve()
{
String name = rhs(0).text();
Double d = dictionary.get(name);
if (d==null)
{
d = (Double)Double.NaN;
String msg = rhs(0).where(0) + ": '" + name + "' is not defined";
lhs().actAdd(()->{System.out.println(msg);});
}
lhs().put(d);
}
//-------------------------------------------------------------------
// Space = " "*
//-------------------------------------------------------------------
void space()
{ lhs().errClear(); }
}
import mouse.runtime.SourceString;
import java.io.*;
import java.nio.file.*;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java_cup.runtime.XMLElement;
import java_cup.runtime.SyntaxTreeTranform;
public class Compiler {
public static void main(String args[]) throws Exception {
StringBuffer lines=new StringBuffer();
for (String line: Files.readAllLines(FileSystems.getDefault().getPath(args[0]))){
lines.append(line);
lines.append("\n");
}
SourceString src = new SourceString(lines.toString());
JavaParser parser=new JavaParser();
boolean ok = parser.parse(src);
if (ok) {
JavaSemantics sem = parser.semantics();
System.out.println(" -> Compilation succeeded");
XMLElement elem = (XMLElement)sem.rule.rhs(0).get();
// Remove unwanted unary branch chains from the syntax tree
elem = SyntaxTreeTranform.removeUnaryChains(elem);
// Dump DoM into XML-String via output stream
XMLOutputFactory outFactory = XMLOutputFactory.newInstance();
ByteArrayOutputStream out = new ByteArrayOutputStream();
XMLStreamWriter sw = outFactory.createXMLStreamWriter(out);
XMLElement.dump(null, sw, elem);
//PrintWriter pw = new PrintWriter("debug.xml");
//String s = new String(out.toByteArray());
//pw.print(s);
//pw.flush();
//pw.close();
// Transform XML-Tree via XSL to carry symbolname as tagname
Transformer transformer;
transformer = TransformerFactory.newInstance().newTransformer(new StreamSource("tree.xsl"));
Source text = new StreamSource(new ByteArrayInputStream(out.toByteArray()));
out = new ByteArrayOutputStream();
transformer.transform(text, new StreamResult(out));
// Transform XML-Tree via XSL into an HTML-Based Syntaxtree
transformer= TransformerFactory.newInstance().newTransformer(new StreamSource("tree-view.xsl"));
text=new StreamSource(new ByteArrayInputStream(out.toByteArray()));
transformer.transform(text,new StreamResult(new File(args[1]+".ast.html")));
System.out.println(" -> Transformation succeeded"); }
}
}
\ No newline at end of file
This diff is collapsed.
import java_cup.runtime.ComplexSymbolFactory.Location;
import java_cup.runtime.XMLElement;
import mouse.runtime.Phrase;
public interface JavaSemanticsUsercode {
Phrase lhs();
Phrase rhs(int i);
//-------------------------------------------------------------------
// Identifier = !Keyword Letter LetterOrDigit* Spacing
//-------------------------------------------------------------------
default void Identifier()
{
XMLElement x = (XMLElement)lhs().get();
lhs().put(new XMLElement.Terminal(new Location(lhs().getStartLine(),lhs().getStartColumn(),lhs().getStartPos()),"Identifier",lhs().text().trim(),new Location(lhs().getEndLine(),lhs().getEndColumn(),lhs().getEndPos())));
}
//-------------------------------------------------------------------
// CLASS = "class" !LetterOrDigit Spacing
// INTERFACE = "interface" !LetterOrDigit Spacing
// LPAR = "(" Spacing
// RPAR = ")" Spacing
// LWING = "{" Spacing
// RWING = "}" Spacing
// SEMI = ";" Spacing
// Spacing = ([ \t\r\n\f]+ / "/*" _*+ "*/" / "//" _*+ [\r\n])*
//-------------------------------------------------------------------
default void Suppress()
{
lhs().put(null);
}
}
// Example 2
Sum = Number ("+" Number)* !_ {sum} ;
Number = [0-9]+ {number} ;
// Example 2
class mySemantics extends mouse.runtime.SemanticsBase
{
//-------------------------------------------------------------------
// Sum = Number "+" Number ... "+" Number !_
// 0 1 2 n-2 n-1
//-------------------------------------------------------------------
void sum()
{
int s = 0;
for (int i=0;i<rhsSize();i+=2)
s += (Integer)rhs(i).get();
System.out.println(s);
}
//-------------------------------------------------------------------
// Number = [0-9] ... [0-9]
// 0 n-1
//-------------------------------------------------------------------
void number()
{ lhs().put(Integer.valueOf(lhs().text())); }
}
// Example 3
Sum = Space Sign Number (AddOp Number)* !_ {sum} ;
Number = Digits Space {number} ;
Sign = ("-" Space)? ;
AddOp = [-+] Space ;
Digits = [0-9]+ ;
Space = " "* ;
// Example 3
class mySemantics extends mouse.runtime.SemanticsBase
{
//-------------------------------------------------------------------
// Sum = Space Sign Number AddOp Number ... AddOp Number
// 0 1 2 3 4 n-2 n-1
//-------------------------------------------------------------------
void sum()
{
int n = rhsSize();
int s = (Integer)rhs(2).get();
if (!rhs(1).isEmpty()) s = -s;
for (int i=4;i<n;i+=2)
{
if (rhs(i-1).charAt(0)=='+')
s += (Integer)rhs(i).get();
else
s -= (Integer)rhs(i).get();
}
System.out.println(s);
}
//-------------------------------------------------------------------
// Number = Digits Space
// 0 1
//-------------------------------------------------------------------
void number()
{ lhs().put(Integer.valueOf(rhs(0).text())); }
}
// Example 4
Sum = Space Sign Number (AddOp Number)* !_ {sum} ;
Number = Digits? "." Digits Space {fraction}
/ Digits Space {integer} ;
Sign = ("-" Space)? ;
AddOp = [-+] Space ;
Digits = [0-9]+ ;
Space = " "* ;
// Example 4
class mySemantics extends mouse.runtime.SemanticsBase
{
//-------------------------------------------------------------------
// Sum = Space Sign Number AddOp Number ... AddOp Number
// 0 1 2 3 4 n-2 n-1
//-------------------------------------------------------------------
void sum()
{
int n = rhsSize();
double s = (Double)rhs(2).get();
if (!rhs(1).isEmpty()) s = -s;
for (int i=4;i<n;i+=2)
{
if (rhs(i-1).charAt(0)=='+')
s += (Double)rhs(i).get();
else
s -= (Double)rhs(i).get();
}
System.out.println(s);
}
//-------------------------------------------------------------------
// Number = Digits? "." Digits Space
// 0 1(0) 2(1) 3(2)
//-------------------------------------------------------------------
void fraction()
{ lhs().put(Double.valueOf(rhsText(0,rhsSize()-1))); }
//-------------------------------------------------------------------
// Number = Digits Space
// 0 1
//-------------------------------------------------------------------
void integer()
{ lhs().put(Double.valueOf(rhs(0).text())); }
}
// Example 5
Input = Space Sum !_ {result} ;
Sum = Sign Product (AddOp Product)* {sum} ;
Product = Factor (OptMult Factor)* {product} ;
Factor = Digits? "." Digits Space {fraction}
/ Digits Space {integer}
/ Lparen Sum Rparen {unwrap} ;
OptMult = MultOp? ;
Sign = ("-" Space)? ;
AddOp = [-+] Space ;
MultOp = [*/] Space ;
Lparen = "(" Space ;
Rparen = ")" Space ;
Digits = [0-9]+ ;
Space = " "* ;
// Example 5
class mySemantics extends mouse.runtime.SemanticsBase
{
//-------------------------------------------------------------------
// Input = Space Sum !_
// 0 1
//-------------------------------------------------------------------
void result()
{ System.out.println((Double)rhs(1).get()); }
//-------------------------------------------------------------------
// Sum = Sign Product AddOp Product ... AddOp Product
// 0 1 2 3 n-2 n-1
//-------------------------------------------------------------------
void sum()
{
int n = rhsSize();
double s = (Double)rhs(1).get();
if (!rhs(0).isEmpty()) s = -s;
for (int i=3;i<n;i+=2)
{
if (rhs(i-1).charAt(0)=='+')
s += (Double)rhs(i).get();
else
s -= (Double)rhs(i).get();
}
lhs().put(new Double(s));
}
//-------------------------------------------------------------------
// Product = Factor OptMult Factor ... OptMult Factor
// 0 1 2 n-2 n-1
//-------------------------------------------------------------------
void product()
{
int n = rhsSize();
double s = (Double)rhs(0).get();
for (int i=2;i<n;i+=2)
{
if (!rhs(i-1).isEmpty() && rhs(i-1).charAt(0)=='/')
s /= (Double)rhs(i).get();
else
s *= (Double)rhs(i).get();
}
lhs().put(new Double(s));
}
//-------------------------------------------------------------------
// Factor = Digits? "." Digits Space
// 0 1(0) 2(1) 3(2)
//-------------------------------------------------------------------
void fraction()
{ lhs().put(Double.valueOf(rhsText(0,rhsSize()-1))); }
//-------------------------------------------------------------------
// Factor = Digits Space
// 0 1
//-------------------------------------------------------------------
void integer()
{ lhs().put(Double.valueOf(rhs(0).text())); }
//-------------------------------------------------------------------
// Factor = Lparen Sum Rparen
// 0 1 2
//-------------------------------------------------------------------
void unwrap()
{ lhs().put(rhs(1).get()); }
}
abstract class Node
{
abstract String show();
static class Num extends Node
{
final String number;
Num(final String v)
{ number = v; }
String show()
{ return number; }
}
static class Op extends Node
{
final Node leftArg;
final char operator;
final Node rightArg;
Op(final Node left, char op, final Node right)
{
leftArg = left;
operator = op;
rightArg = right;
}
String show()
{ return "[" + leftArg.show() + operator + rightArg.show() + "]" ; }
}
}
\ No newline at end of file
import mouse.runtime.SourceString;
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Try
{
public static void main(String argv[])
throws Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
myParser parser = new myParser(); // Instantiate Parser+Semantics
while (true)
{
System.out.print("> "); // Print prompt
String line = in.readLine(); // Read line
if (line.length()==0) return; // Quit on empty line
SourceString src = new SourceString(line); // Wrap up the line
boolean ok = parser.parse(src); // Apply Parser to it
if (ok) // If succeeded:
{
mySemantics sem = parser.semantics(); // Access Semantics
System.out.println(sem.tree.show()); // Get the tree and show it
}
}
}
}
// Example 6
Input = Space Sum !_ {result} ;
Sum = Sign Product (AddOp Product)* {sum} ;
Product = Factor (OptMult Factor)* {product} ;
Factor = Digits? "." Digits Space {fraction}