Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
  • anders.blomdell
  • compiler-refactoring
  • labcomm2006
  • labcomm2013
  • labcomm2014
  • master
  • pragma
  • python_sig_hash
  • typedefs
  • typeref
  • v2006.0
  • v2013.0
  • v2014.0
  • v2014.1
  • v2014.2
  • v2014.3
  • v2014.4
  • v2014.5
  • v2014.6
  • v2015.0
20 results

Target

Select target project
  • anders_blomdell/labcomm
  • klaren/labcomm
  • tommyo/labcomm
  • erikj/labcomm
  • sven/labcomm
5 results
Select Git revision
  • anders.blomdell
  • compiler-refactoring
  • labcomm2006
  • labcomm2013
  • master
  • pragma
  • typedefs
  • typeref
  • v2006.0
  • v2013.0
  • v2014.0
  • v2014.1
  • v2014.2
  • v2014.3
  • v2014.4
15 results
Show changes
Showing
with 3408 additions and 54 deletions
Specification ::= Decl*;
abstract Decl ::= TypeInstance /Signature/;
TypeInstance ::= DataType Annotations;
Annotations ::= Annotation*;
Annotation ::= <Key:String> <Value:byte[]>;
Intention : Annotation;
DocString : Annotation;
TypeDecl : Decl;
SampleDecl : Decl;
//Signatures are in the abstract grammar, so that
//they can be extended and refined by aspects.
Signature ::= SignatureList FlatSignatureList:SignatureList;
SignatureList ::= SignatureLine*;
abstract SignatureLine ::= <Indent:int> <Comment:String>;
abstract DataSignatureLine : SignatureLine;
ByteArraySignatureLine : DataSignatureLine ::= <Data:byte[]>;
IntSignatureLine : DataSignatureLine ::= <Data:int>;
StringSignatureLine : DataSignatureLine ::= <Data:String>;
IntentionSignatureLine : DataSignatureLine ::= Intention* ;
TypeRefSignatureLine : SignatureLine ::= Decl;
Field : TypeInstance;
abstract DataType;
VoidType : DataType;
//SampleRefType : DataType;
PrimType : DataType ::= <Name:String> <Token:int>;
UserType : DataType ::= <Name:String>;
StructType : DataType ::= Field*;
ParseArrayType : DataType ::= DataType Dim*;
abstract ArrayType : DataType ::= DataType Dim;
VariableArrayType : ArrayType;
FixedArrayType : ArrayType;
Dim ::= Exp*;
abstract Exp;
IntegerLiteral : Exp ::= <Value:String>;
VariableSize : Exp;
package se.lth.control.labcomm2014.compiler;
import java.io.*;
import java.util.*;
public class LabComm {
private static void println(String s) {
System.out.println(s);
}
private static void print_help() {
println("\n Usage: java -jar labcom.jar [options*] FILE");
println("");
println(" --help Shows this help text");
println(" -v Be verbose");
println(" --ver=VERSION Generate code for labcomm VERSION (=2006 or 2014)");
println("[ C options ]");
println(" -C Generates C/H code in FILE.[ch]");
println(" --cprefix=PREFIX Prefixes C types with PREFIX");
println(" --cinclude=FILE Include FILE in generated .c");
println(" --c=CFILE Generates C code in CFILE");
println(" --h=HFILE Generates H code in HFILE");
println("[ C# options]");
println(" --cs Generates C# code in FILE.cs");
println(" --cs=CSFILE Generates C# code in CSFILE");
println(" --csnamespace=NAMESPACE Place C# classes in NAMESPACE");
println("[ Java options ]");
println(" --java=JDIR Generates Java files in JDIR");
println(" --javapackage=PACKAGE Place Java classes in PACKAGE");
println("[ Python options ]");
println(" -P Generates Python code in FILE.py");
println(" --python=PFILE Generates Python code in PFILE");
println("[ RAPID options ]");
println(" --rapid Generates RAPID code in FILE.sys");
println("[ Misc options ]");
println(" --pretty=PFILE Pretty prints to PFILE");
println(" --typeinfo=TIFILE Generates typeinfo in TIFILE");
println(" --typedefs=TIFILE Generates typedefs in TIFILE");
}
/** To be cleaned up.
*/
private static void checkVersion(int v) {
if(! (v == 2006 || v == 2014) ) {
System.err.println(" Unknown version: " + v);
System.err.println(" Supported versions: 2006, 2014 ");
System.exit(2);
}
}
private static void genH(Specification p, String hName,
Vector cIncludes, String coreName, String prefix, int ver) {
try {
FileOutputStream f;
PrintStream out;
f = new FileOutputStream(hName);
out = new PrintStream(f);
p.C_genH(out, cIncludes, coreName, prefix, ver);
out.close();
} catch (IOException e) {
System.err.println("IOException: " + hName + " " + e);
}
}
private static void genC(Specification p, String cName,
Vector cIncludes, String coreName, String prefix, int ver) {
try {
FileOutputStream f;
PrintStream out;
f = new FileOutputStream(cName);
out = new PrintStream(f);
p.C_genC(out, cIncludes, coreName, prefix, ver);
out.close();
} catch (IOException e) {
System.err.println("IOException: " + cName + " " + e);
}
}
private static void genCS(Specification p, String csName, String csNamespace, int ver) {
// throw new Error("C# generation currently disabled");
try {
p.CS_gen(csName, csNamespace, ver);
} catch (IOException e) {
System.err.println("IOException: " + csName + " " +
csNamespace + " " + e);
}
}
private static void genJava(Specification p, String dirName, String packageName, int ver) {
try {
p.J_gen(dirName, packageName, ver);
} catch (IOException e) {
System.err.println("IOException: " + dirName + " " +
packageName + " " + e);
}
}
private static void genPython(Specification p, String filename, String prefix, int ver) {
try {
FileOutputStream f;
PrintStream out;
f = new FileOutputStream(filename);
out = new PrintStream(f);
p.Python_gen(out, prefix, ver);
out.close();
} catch (IOException e) {
System.err.println("IOException: " + filename + " " + e);
}
}
private static void genRAPID(Specification p, String filename, String prefix, int ver) {
try {
p.RAPID_gen(filename, prefix, ver);
} catch (IOException e) {
System.err.println("IOException: " + filename + " " + e);
}
}
/** Helper class to contain command line options
and their associated behaviour
**/
private static class Opts {
final String[] args;
String coreName = null;
String prefix = null;
boolean verbose = false;
int ver = 2014; //Version 2014 as default
String cFile = null;
String hFile = null;
Vector cIncludes = new Vector();
String cPrefix; // gets default value (prefix) in processFilename
String csFile = null;
String csNamespace = null;
String javaDir = null;
String javaPackage = "";
String pythonFile = null;
String prettyFile = null;
String typeinfoFile = null;
String typedefsFile = null;
String rapidFile = null;
String fileName = null;
Opts(String[] args) {
this.args = args;
}
private static String getCoreName(String s) {
int i = s.lastIndexOf('.');
return s.substring(0, i > 0 ? i : s.length());
}
private static String getFileName(String s) {
return s.substring(s.lastIndexOf('/') + 1, s.length());
}
private static String getBaseName(String s) {
s = getFileName(s);
int i = s.lastIndexOf('.');
return s.substring(0, i > 0 ? i : s.length());
}
private static String getPrefix(String s) {
return s.substring(s.lastIndexOf('/') + 1, s.length());
}
boolean processFilename(){
// Scan for first non-option
for (int i = 0 ; i < args.length ; i++) {
if (! args[i].startsWith("-")) {
fileName = args[i];
break;
}
}
if (fileName != null) {
coreName = getBaseName(fileName);
prefix = getPrefix(coreName);
cPrefix = prefix;
}
return fileName != null;
}
void processArgs(){
for (int i = 0 ; i < args.length ; i++) {
if (fileName == null ||
args[i].equals("-help") ||
args[i].equals("-h") ||
args[i].equals("--help")) {
print_help();
System.exit(0);
} else if (args[i].equals("-v")) {
verbose=true;
} else if (args[i].startsWith("--ver=")) {
ver = Integer.parseInt(args[i].substring(6));
checkVersion(ver);
} else if (args[i].equals("-C")) {
cFile = coreName + ".c";
hFile = coreName + ".h";
} else if (args[i].startsWith("--cinclude=")) {
cIncludes.add(args[i].substring(11));
} else if (args[i].startsWith("--cprefix=")) {
cPrefix = args[i].substring(10);
} else if (args[i].startsWith("--c=")) {
cFile = args[i].substring(4);
} else if (args[i].startsWith("--h=")) {
hFile = args[i].substring(4);
} else if (args[i].equals("--cs")) {
csFile = coreName + ".cs";
} else if (args[i].startsWith("--cs=")) {
csFile = args[i].substring(5);
} else if (args[i].startsWith("--csnamespace=")) {
csNamespace = args[i].substring(14);
} else if (args[i].startsWith("--java=")) {
javaDir = args[i].substring(7);
} else if (args[i].startsWith("--javapackage=")) {
javaPackage = args[i].substring(14);
} else if (args[i].equals("-P")) {
pythonFile = coreName + ".py";
} else if (args[i].startsWith("--python=")) {
pythonFile = args[i].substring(9);
} else if (args[i].startsWith("--pretty=")) {
prettyFile = args[i].substring(9);
} else if (args[i].startsWith("--typeinfo=")) {
typeinfoFile = args[i].substring(11);
} else if (args[i].startsWith("--typedefs=")) {
typedefsFile = args[i].substring(11);
} else if (args[i].equals("--rapid")) {
rapidFile = coreName + ".sys";
} else if (i == args.length - 1) {
fileName = args[i];
} else {
System.err.println(" Unknown argument " + args[i]);
print_help();
System.exit(2);
}
}
if(prefix==null){
System.err.println(" WARNING! prefix==null");
prefix="";
}
}
Specification parseFile(){
Specification ast = null;
try {
// Check for errors
LabCommScanner scanner = new LabCommScanner(
new FileReader(fileName));
LabCommParser parser = new LabCommParser();
Specification p = (Specification)parser.parse(scanner);
Collection errors = new LinkedList();
p.errorCheck(errors);
if (errors.isEmpty()) {
ast = p;
} else {
for (Iterator iter = errors.iterator(); iter.hasNext(); ) {
String s = (String)iter.next();
System.out.println(s);
}
}
} catch (FileNotFoundException e) {
System.err.println("Could not find file: " + fileName);
} catch (IOException e) {
System.err.println("IOException: " + fileName + " " + e);
} catch (beaver.Parser.Exception e) {
System.err.println(e.getMessage());
}
return ast;
}
boolean generateC(Specification ast) {
boolean wroteFile = false;
Vector hIncludes = new Vector(cIncludes);
if (hFile != null) {
cIncludes.add(hFile);
}
if (cFile != null) {
printStatus("C: " , cFile);
genC(ast, cFile, cIncludes, coreName, cPrefix, ver);
wroteFile = true;
}
if (hFile != null) {
printStatus("H: " , hFile);
genH(ast, hFile, hIncludes, coreName, cPrefix, ver);
wroteFile = true;
}
return wroteFile;
}
boolean generateCS(Specification ast) {
boolean wroteFile = false;
if (csFile != null) {
printStatus("C#: " , csFile);
genCS(ast, csFile, csNamespace, ver);
wroteFile = true;
}
return wroteFile;
}
boolean generateJava(Specification ast) {
boolean wroteFile = false;
if (javaDir != null) {
printStatus("Java: " , javaDir);
genJava(ast, javaDir, javaPackage, ver);
wroteFile = true;
}
return wroteFile;
}
boolean generatePython(Specification ast) {
boolean wroteFile = false;
if (pythonFile != null) {
printStatus("Python: " , pythonFile);
genPython(ast, pythonFile, prefix, ver);
wroteFile = true;
}
return wroteFile;
}
boolean generateRAPID(Specification ast) {
boolean wroteFile = false;
if (rapidFile != null) {
printStatus("RAPID: " , rapidFile);
genRAPID(ast, rapidFile, coreName, ver);
wroteFile = true;
}
return wroteFile;
}
boolean generatePrettyPrint(Specification ast) {
boolean wroteFile = false;
if (prettyFile != null) {
printStatus("Pretty: " , prettyFile);
try {
FileOutputStream f = new FileOutputStream(prettyFile);
PrintStream out = new PrintStream(f);
ast.pp(out);
out.close();
wroteFile = true;
} catch (IOException e) {
System.err.println("IOException: " + prettyFile + " " + e);
}
}
return wroteFile;
}
boolean generateTypeinfo(Specification ast) {
boolean wroteFile = false;
if (typeinfoFile != null) {
printStatus("TypeInfo: " , typeinfoFile);
try {
FileOutputStream f = new FileOutputStream(typeinfoFile);
PrintStream out = new PrintStream(f);
ast.C_info(out, cPrefix, ver);
ast.Java_info(out, ver);
ast.CS_info(out, csNamespace, ver);
wroteFile = true;
} catch (IOException e) {
System.err.println("IOException: " + typeinfoFile + " " + e);
}
}
return wroteFile;
}
boolean generateTypedefs(Specification ast) {
boolean wroteFile = false;
if (typedefsFile != null) {
printStatus("Typedefs: " , typedefsFile);
try {
FileOutputStream f = new FileOutputStream(typedefsFile);
PrintStream out = new PrintStream(f);
ast.generateTypedefs(out, ver);
wroteFile = true;
} catch (IOException e) {
System.err.println("IOException: " + typedefsFile + " " + e);
}
}
return wroteFile;
}
private void printStatus(String kind, String filename){
if (verbose) {
System.err.println("Generating "+kind+": " + filename);
}
}
}
public static void main(String[] args) {
Opts opts = new Opts(args);
if(!opts.processFilename()) {
print_help();
System.exit(1);
} else {
opts.processArgs();
Specification ast = opts.parseFile();
if (ast != null) {
boolean fileWritten = false;
fileWritten |= opts.generateC(ast);
fileWritten |= opts.generateCS(ast);
fileWritten |= opts.generateJava(ast);
fileWritten |= opts.generatePython(ast);
fileWritten |= opts.generateRAPID(ast);
fileWritten |= opts.generatePrettyPrint(ast);
fileWritten |= opts.generateTypeinfo(ast);
fileWritten |= opts.generateTypedefs(ast);
// if no output to files, prettyprint on stdout
if (!fileWritten) {
ast.pp(System.out);
}
} else {
// Catch-all for compilation errors
System.err.println("Error in specification");
System.exit(3);
}
}
}
}
%header {: %header {:
package AST; package se.lth.control.labcomm2014.compiler;
import se.lth.control.labcomm2014.compiler.*;
:}; :};
%embed {: %embed {:
public static class SourceError extends Error { public static class SourceError extends Error {
...@@ -33,9 +34,9 @@ ...@@ -33,9 +34,9 @@
} }
:}; :};
Program goal = Specification goal =
/* Empty program */ {: return new Program(); :} /* Empty program */ {: return new Specification(); :}
| decl_list.l {: return new Program(l); :} | decl_list.l {: return new Specification(l); :}
; ;
List decl_list = List decl_list =
...@@ -53,31 +54,44 @@ List var_decl_list = ...@@ -53,31 +54,44 @@ List var_decl_list =
| var_decl_list.l var_decl.v {: return l.add(v); :} | var_decl_list.l var_decl.v {: return l.add(v); :}
; ;
Annotations annotations =
/* empty list */ {: return new Annotations(); :}
| annotation_list.l {: return new Annotations(l); :}
;
List annotation_list =
annotation.i {: return new List().add(i); :}
| annotation_list.l annotation.i {: return l.add(i); :}
;
String key = IDENTIFIER;
String stringliteral = IDENTIFIER | QUOTEDSTRING;
Annotation annotation = intention.i | docstring.d;
Annotation intention = LPAREN key.k COLON stringliteral.v RPAREN {: return new Intention(k,v.getBytes()); :};
Annotation docstring = QUOTEDSTRING.s {: return new DocString(s.substring(1,s.length()-1).getBytes()); :};
TypeInstance type_instance =
annotations.a type.t IDENTIFIER {: return new TypeInstance(t, IDENTIFIER, a); :}
| annotations.a type.t IDENTIFIER dim_list.d
{: return new TypeInstance(new ParseArrayType(t, d), IDENTIFIER, a); :}
;
Field var_decl = Field var_decl =
type.t IDENTIFIER SEMICOLON {: return new Field(t, IDENTIFIER); :} type_instance.t SEMICOLON {: return new Field(t); :}
| type.t IDENTIFIER dim_list.d SEMICOLON
{: return new Field(new ParseArrayType(t, d), IDENTIFIER); :}
; ;
TypeDecl type_decl = TypeDecl type_decl =
TYPEDEF type.t IDENTIFIER SEMICOLON {: return new TypeDecl(t, IDENTIFIER); :} TYPEDEF type_instance.t SEMICOLON {: return new TypeDecl(t); :} ;
| TYPEDEF type.t IDENTIFIER dim_list.d SEMICOLON
{: return new TypeDecl(new ParseArrayType(t, d), IDENTIFIER); :}
;
SampleDecl sample_decl = SampleDecl sample_decl =
SAMPLE type.t IDENTIFIER SEMICOLON SAMPLE type_instance.t SEMICOLON {: return new SampleDecl(t); :} ;
{: return new SampleDecl(t, IDENTIFIER); :}
| SAMPLE type.t IDENTIFIER dim_list.d SEMICOLON
{: return new SampleDecl(new ParseArrayType(t, d), IDENTIFIER); :}
| SAMPLE VOID IDENTIFIER SEMICOLON
{: return new SampleDecl(new VoidType(), IDENTIFIER); :}
;
Type type = DataType type =
prim_type.p {: return p; :} prim_type.p {: return p; :}
| user_type.u {: return u; :} | user_type.u {: return u; :}
| struct_type.s {: return s; :} | struct_type.s {: return s; :}
| void_type.v {: return v; :}
; ;
PrimType prim_type = PrimType prim_type =
...@@ -97,6 +111,8 @@ PrimType prim_type = ...@@ -97,6 +111,8 @@ PrimType prim_type =
{: return new PrimType(DOUBLE, ASTNode.LABCOMM_DOUBLE); :} {: return new PrimType(DOUBLE, ASTNode.LABCOMM_DOUBLE); :}
| STRING | STRING
{: return new PrimType(STRING, ASTNode.LABCOMM_STRING); :} {: return new PrimType(STRING, ASTNode.LABCOMM_STRING); :}
| SAMPLE
{: return new PrimType(SAMPLE, ASTNode.LABCOMM_SAMPLE); :}
; ;
UserType user_type = UserType user_type =
...@@ -107,6 +123,10 @@ StructType struct_type = ...@@ -107,6 +123,10 @@ StructType struct_type =
STRUCT LBRACE var_decl_list.l RBRACE {: return new StructType(l); :} STRUCT LBRACE var_decl_list.l RBRACE {: return new StructType(l); :}
; ;
VoidType void_type =
VOID {: return new VoidType(); :}
;
List dim_list = List dim_list =
dim.d {: return new List().add(d); :} dim.d {: return new List().add(d); :}
| dim_list.l dim.d {: return l.add(d); :} | dim_list.l dim.d {: return l.add(d); :}
......
package AST; package se.lth.control.labcomm2014.compiler;
import beaver.Symbol; import beaver.Symbol;
import beaver.Scanner; import beaver.Scanner;
import AST.LabCommParser.Terminals; import se.lth.control.labcomm2014.compiler.LabCommParser.Terminals;
%% %%
...@@ -44,13 +44,16 @@ Comment = {TraditionalComment} ...@@ -44,13 +44,16 @@ Comment = {TraditionalComment}
TraditionalComment = "/*" [^*] ~"*/" | "/*" "*"+ "/" | "/*" "*"+ [^/*] ~"*/" TraditionalComment = "/*" [^*] ~"*/" | "/*" "*"+ "/" | "/*" "*"+ [^/*] ~"*/"
EndOfLineComment = "//" {InputCharacter}* {LineTerminator}? EndOfLineComment = "//" {InputCharacter}* {LineTerminator}?
Identifier = [:jletter:][:jletterdigit:]* Identifier = [[:letter:]_]([[:letter:]_[:digit:]])*
StringLiteral = [:jletterdigit:]*
DecimalNumeral = 0 | {NonZeroDigit} {Digits}? DecimalNumeral = 0 | {NonZeroDigit} {Digits}?
Digits = {Digit}+ Digits = {Digit}+
Digit = 0 | {NonZeroDigit} Digit = 0 | {NonZeroDigit}
NonZeroDigit = [1-9] NonZeroDigit = [1-9]
QuotedString = "\""~"\""
%% %%
<YYINITIAL> { <YYINITIAL> {
...@@ -76,10 +79,14 @@ NonZeroDigit = [1-9] ...@@ -76,10 +79,14 @@ NonZeroDigit = [1-9]
"}" { return sym(Terminals.RBRACE); } "}" { return sym(Terminals.RBRACE); }
"[" { return sym(Terminals.LBRACK); } "[" { return sym(Terminals.LBRACK); }
"]" { return sym(Terminals.RBRACK); } "]" { return sym(Terminals.RBRACK); }
"(" { return sym(Terminals.LPAREN); }
")" { return sym(Terminals.RPAREN); }
";" { return sym(Terminals.SEMICOLON); } ";" { return sym(Terminals.SEMICOLON); }
":" { return sym(Terminals.COLON); }
"," { return sym(Terminals.COMMA); } "," { return sym(Terminals.COMMA); }
{Identifier} { return sym(Terminals.IDENTIFIER); } {Identifier} { return sym(Terminals.IDENTIFIER); }
{QuotedString} { return sym(Terminals.QUOTEDSTRING); }
} }
// fall through errors // fall through errors
......
aspect LabCommTokens {
public static final int ASTNode.LABCOMM_VERSION = 0x01;
public static final int ASTNode.LABCOMM_SAMPLE_DEF = 0x02; // The flat signature
public static final int ASTNode.LABCOMM_SAMPLE_REF = 0x03;
public static final int ASTNode.LABCOMM_TYPE_DEF = 0x03; // and type declarations, hierarchically
public static final int ASTNode.LABCOMM_TYPE_BINDING=0x05;
public static final int ASTNode.LABCOMM_ARRAY = 0x10;
public static final int ASTNode.LABCOMM_STRUCT = 0x11;
public static final int ASTNode.LABCOMM_BOOLEAN = 0x20;
public static final int ASTNode.LABCOMM_BYTE = 0x21;
public static final int ASTNode.LABCOMM_SHORT = 0x22;
public static final int ASTNode.LABCOMM_INT = 0x23;
public static final int ASTNode.LABCOMM_LONG = 0x24;
public static final int ASTNode.LABCOMM_FLOAT = 0x25;
public static final int ASTNode.LABCOMM_DOUBLE = 0x26;
public static final int ASTNode.LABCOMM_STRING = 0x27;
public static final int ASTNode.LABCOMM_SAMPLE = 0x28;
}
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
aspect NameAnalysis { aspect NameAnalysis {
inh String Decl.lookupName(String name); inh String Decl.lookupName(String name);
eq Program.getDecl(int index).lookupName(String name) { eq Specification.getDecl(int index).lookupName(String name) {
for (int i = 0; i < index; i++) { for (int i = 0; i < index; i++) {
String s = getDecl(i).getName(); String s = getDecl(i).getName();
if (s.equals(name)) { if (s.equals(name)) {
...@@ -24,7 +24,7 @@ aspect NameAnalysis { ...@@ -24,7 +24,7 @@ aspect NameAnalysis {
inh TypeDecl Decl.lookupType(String name); inh TypeDecl Decl.lookupType(String name);
inh TypeDecl UserType.lookupType(String name); inh TypeDecl UserType.lookupType(String name);
eq Program.getDecl(int index).lookupType(String name) { eq Specification.getDecl(int index).lookupType(String name) {
for(int i = 0; i < index; i++) { for(int i = 0; i < index; i++) {
Decl d = getDecl(i); Decl d = getDecl(i);
if(d instanceof TypeDecl && d.getName().equals(name)) { if(d instanceof TypeDecl && d.getName().equals(name)) {
...@@ -34,7 +34,10 @@ aspect NameAnalysis { ...@@ -34,7 +34,10 @@ aspect NameAnalysis {
return null; return null;
} }
syn TypeDecl UserType.decl() = lookupType(getName()); syn TypeDecl DataType.decl();
eq DataType.decl() = null;
eq UserType.decl() = lookupType(getName());
eq PrimType.decl() = null; //HERE BE DRAGONS XXX
public void ASTNode.nameCheck() { public void ASTNode.nameCheck() {
......
...@@ -6,7 +6,7 @@ aspect PPIndentation { ...@@ -6,7 +6,7 @@ aspect PPIndentation {
inh String Field.pp_indent(); inh String Field.pp_indent();
inh String StructType.pp_indent(); inh String StructType.pp_indent();
eq StructType.getField(int index).pp_indent() = pp_indent() + " "; eq StructType.getField(int index).pp_indent() = pp_indent() + " ";
eq Program.getDecl(int index).pp_indent() = ""; eq Specification.getDecl(int index).pp_indent() = "";
} }
...@@ -18,7 +18,7 @@ aspect PrettyPrint { ...@@ -18,7 +18,7 @@ aspect PrettyPrint {
" not declared"); " not declared");
} }
public void Program.pp(PrintStream out) { public void Specification.pp(PrintStream out) {
for(int i = 0; i < getNumDecl(); i++) { for(int i = 0; i < getNumDecl(); i++) {
getDecl(i).pp(out); getDecl(i).pp(out);
} }
...@@ -27,24 +27,24 @@ aspect PrettyPrint { ...@@ -27,24 +27,24 @@ aspect PrettyPrint {
// Pretty print declarations // Pretty print declarations
public void TypeDecl.pp(PrintStream out) { public void TypeDecl.pp(PrintStream out) {
out.print("typedef "); out.print("typedef ");
getType().ppIdentifier(out, getName()); getDataType().ppIdentifier(out, getName());
out.println(";"); out.println(";");
} }
public void SampleDecl.pp(PrintStream out) { public void SampleDecl.pp(PrintStream out) {
out.print("sample "); out.print("sample ");
getType().ppIdentifier(out, getName()); getDataType().ppIdentifier(out, getName());
out.println(";"); out.println(";");
} }
public void Field.pp(PrintStream out) { public void Field.pp(PrintStream out) {
out.print(pp_indent()); out.print(pp_indent());
getType().ppIdentifier(out, getName()); getDataType().ppIdentifier(out, getName());
out.println(";"); out.println(";");
} }
// Pretty print variable of a given type // Pretty print variable of a given type
public void Type.ppIdentifier(PrintStream out, String id) { public void DataType.ppIdentifier(PrintStream out, String id) {
ppPrefix(out); ppPrefix(out);
out.print(" "); out.print(" ");
out.print(id); out.print(id);
...@@ -58,7 +58,7 @@ aspect PrettyPrint { ...@@ -58,7 +58,7 @@ aspect PrettyPrint {
} }
// PrettyPrint prefix type info // PrettyPrint prefix type info
public void Type.ppPrefix(PrintStream out) { public void DataType.ppPrefix(PrintStream out) {
throw new Error(this.getClass().getName() + throw new Error(this.getClass().getName() +
".ppPrefix(PrintStream out)" + ".ppPrefix(PrintStream out)" +
" not declared"); " not declared");
...@@ -68,6 +68,10 @@ aspect PrettyPrint { ...@@ -68,6 +68,10 @@ aspect PrettyPrint {
out.print("void"); out.print("void");
} }
// public void SampleRefType.ppPrefix(PrintStream out) {
// out.print("sample");
// }
public void PrimType.ppPrefix(PrintStream out) { public void PrimType.ppPrefix(PrintStream out) {
out.print(getName()); out.print(getName());
} }
...@@ -77,7 +81,7 @@ aspect PrettyPrint { ...@@ -77,7 +81,7 @@ aspect PrettyPrint {
} }
public void ArrayType.ppPrefix(PrintStream out) { public void ArrayType.ppPrefix(PrintStream out) {
getType().ppPrefix(out); getDataType().ppPrefix(out);
} }
public void StructType.ppPrefix(PrintStream out) { public void StructType.ppPrefix(PrintStream out) {
...@@ -90,7 +94,7 @@ aspect PrettyPrint { ...@@ -90,7 +94,7 @@ aspect PrettyPrint {
} }
// PrettyPrint suffix type info (array dimensions) // PrettyPrint suffix type info (array dimensions)
public void Type.ppSuffix(PrintStream out) { } public void DataType.ppSuffix(PrintStream out) { }
public void ArrayType.ppSuffix(PrintStream out) { public void ArrayType.ppSuffix(PrintStream out) {
out.print("["); out.print("[");
...@@ -99,7 +103,7 @@ aspect PrettyPrint { ...@@ -99,7 +103,7 @@ aspect PrettyPrint {
getExp(i).pp(out); getExp(i).pp(out);
} }
out.print("]"); out.print("]");
getType().ppSuffix(out); getDataType().ppSuffix(out);
} }
public void IntegerLiteral.pp(PrintStream out) { public void IntegerLiteral.pp(PrintStream out) {
......
aspect Python_CodeGenEnv {
// Environment wrapper for Python code generation
// handles qualid nesting, indentation, file writing and
// prefix propagation
public class Python_env extends PrintEnv {
final private class Python_printer extends PrintEnv.Printer {
// public C_printer(PrintStream out) {
// super(out, " ");
// }
}
public Python_env(PrintStream out) {
super(out);
}
}
}
aspect Python_CodeGen {
public void Specification.Python_gen(PrintStream out, String baseName, int version) {
Python_env env = new Python_env(out);
env.println("#!/usr/bin/python");
env.println("# Auto generated " + baseName);
env.println();
env.println("import labcomm2014");
env.println();
Python_genTypes(env);
env.println("typedef = tuple([");
env.indent();
for (int i = 0 ; i < getNumDecl() ; i++) {
getDecl(i).Python_genTypedefListEntry(env);
}
env.unindent();
env.println("])");
env.println("sample = tuple([");
env.indent();
for (int i = 0 ; i < getNumDecl() ; i++) {
getDecl(i).Python_genSampleListEntry(env);
}
env.unindent();
env.println("])");
}
}
aspect PythonTypes {
public void Specification.Python_genTypes(Python_env env) {
for (int i = 0 ; i < getNumDecl() ; i++) {
getDecl(i).Python_genSignatureAndTypedef(env);
}
}
public void Decl.Python_genSignatureAndTypedef(Python_env env) {
throw new Error(this.getClass().getName() +
".Python_genSignatureAndTypedef(Python_env env)" +
" not declared");
}
public void TypeDecl.Python_genSignatureAndTypedef(Python_env env) {
env.println("class " + getName() + "(object):");
env.indent();
env.print("typedef = labcomm2014.typedef(");
Python_genIntentions(env);
env.println(",");
env.indent();
getTypeInstance().Python_genTypedef(env);
env.unindent();
env.println(")");
env.unindent();
env.println();
}
public void SampleDecl.Python_genSignatureAndTypedef(Python_env env) {
env.println("class " + getName() + "(object):");
env.indent();
env.print("signature = labcomm2014.sample(");
Python_genIntentions(env);
env.println(",");
env.indent();
getDataType().Python_genSignature(env);
env.unindent();
env.println(")");
env.print("typedef = labcomm2014.sample(");
Python_genIntentions(env);
env.println(",");
env.indent();
getTypeInstance().Python_genTypedef(env);
env.unindent();
env.println(")");
env.unindent();
env.println();
}
public void Decl.Python_genIntentions(Python_env env) {
getTypeInstance().Python_genIntentions(env);
}
public void TypeInstance.Python_genIntentions(Python_env env) {
// env.print("{");
// for(Intention i : sortedIntentions()) {
// env.print("'"+i.getKey()+"':'"+new String(i.getValue())+"', ");
// }
// env.print("}");
env.print("tuple((");
for(Intention i : sortedIntentions()) {
env.print("('"+i.getKey()+"','"+new String(i.getValue())+"'), ");
}
env.print("))");
}
public void TypeInstance.Python_genTypedef(Python_env env) {
getDataType().Python_genTypedef(env);
}
public void UserType.Python_genSignature(Python_env env) {
lookupType(getName()).getDataType().Python_genSignature(env);
}
public void DataType.Python_genSignature(Python_env env) {
throw new Error(this.getClass().getName() +
".Python_genSignature(Python_env env)" +
" not declared");
}
public void PrimType.Python_genSignature(Python_env env) {
switch (getToken()) {
case LABCOMM_BOOLEAN: { env.print("labcomm2014.BOOLEAN()"); } break;
case LABCOMM_BYTE: { env.print("labcomm2014.BYTE()"); } break;
case LABCOMM_SHORT: { env.print("labcomm2014.SHORT()"); } break;
case LABCOMM_INT: { env.print("labcomm2014.INTEGER()"); } break;
case LABCOMM_LONG: { env.print("labcomm2014.LONG()"); } break;
case LABCOMM_FLOAT: { env.print("labcomm2014.FLOAT()"); } break;
case LABCOMM_DOUBLE: { env.print("labcomm2014.DOUBLE()"); } break;
case LABCOMM_STRING: { env.print("labcomm2014.STRING()"); } break;
case LABCOMM_SAMPLE: { env.print("labcomm2014.SAMPLE()"); } break;
}
}
public void ArrayType.Python_genSignature(Python_env env) {
env.print("labcomm2014.array([");
for (int i = 0 ; i < getNumExp() ; i++) {
if (i > 0) { env.print(", "); }
env.print(getExp(i).Python_getValue());
}
env.println("],");
env.indent();
getDataType().Python_genSignature(env);
env.print(")");
env.unindent();
}
public void StructType.Python_genSignature(Python_env env) {
env.println("labcomm2014.struct([");
env.indent();
for (int i = 0 ; i < getNumField() ; i++) {
if (i > 0) { env.println(","); }
getField(i).Python_genSignature(env);
}
env.print("])");
env.unindent();
}
public void VoidType.Python_genSignature(Python_env env) {
env.println("labcomm2014.struct([])");
}
public void Field.Python_genSignature(Python_env env) {
env.print("(");
Python_genIntentions(env);
env.print(", ");
getDataType().Python_genSignature(env);
env.print(")");
}
public void UserType.Python_genTypedef(Python_env env) {
env.println(getName() + ".typedef");
}
public void DataType.Python_genTypedef(Python_env env) {
throw new Error(this.getClass().getName() +
".Python_genTypedef(Python_env env)" +
" not declared");
}
public void PrimType.Python_genTypedef(Python_env env) {
switch (getToken()) {
case LABCOMM_BOOLEAN: { env.print("labcomm2014.BOOLEAN()"); } break;
case LABCOMM_BYTE: { env.print("labcomm2014.BYTE()"); } break;
case LABCOMM_SHORT: { env.print("labcomm2014.SHORT()"); } break;
case LABCOMM_INT: { env.print("labcomm2014.INTEGER()"); } break;
case LABCOMM_LONG: { env.print("labcomm2014.LONG()"); } break;
case LABCOMM_FLOAT: { env.print("labcomm2014.FLOAT()"); } break;
case LABCOMM_DOUBLE: { env.print("labcomm2014.DOUBLE()"); } break;
case LABCOMM_STRING: { env.print("labcomm2014.STRING()"); } break;
case LABCOMM_SAMPLE: { env.print("labcomm2014.SAMPLE()"); } break;
}
}
public void ArrayType.Python_genTypedef(Python_env env) {
env.print("labcomm2014.array([");
for (int i = 0 ; i < getNumExp() ; i++) {
if (i > 0) { env.print(", "); }
env.print(getExp(i).Python_getValue());
}
env.println("],");
env.indent();
getDataType().Python_genTypedef(env);
env.print(")");
env.unindent();
}
public void StructType.Python_genTypedef(Python_env env) {
env.println("labcomm2014.struct([");
env.indent();
for (int i = 0 ; i < getNumField() ; i++) {
if (i > 0) { env.println(","); }
getField(i).Python_genTypedef(env);
}
env.print("])");
env.unindent();
}
public void VoidType.Python_genTypedef(Python_env env) {
env.println("labcomm2014.struct([])");
}
public void Field.Python_genTypedef(Python_env env) {
env.print("(");
Python_genIntentions(env);
env.print(", ");
getDataType().Python_genTypedef(env);
env.print(")");
}
public void Decl.Python_genTypedefListEntry(Python_env env) {
}
public void TypeDecl.Python_genTypedefListEntry(Python_env env) {
env.println(getName() + ",");
}
public void Decl.Python_genSampleListEntry(Python_env env) {
}
public void SampleDecl.Python_genSampleListEntry(Python_env env) {
env.println(getName()+ ",");
}
public String Exp.Python_getValue() {
throw new Error(this.getClass().getName() +
".Python_getValue()" +
" not declared");
}
public String IntegerLiteral.Python_getValue() {
return getValue();
}
public String VariableSize.Python_getValue() {
return "0";
}
}
This diff is collapsed.
/* Temporary aspect with forwarding methods */
aspect Refactoring {
syn int ArrayType.getNumExp() = getDim().getNumExp();
syn Exp ArrayType.getExp(int i) = getDim().getExp(i);
syn String Decl.getName() = getTypeInstance().getName();
syn DataType Decl.getDataType() = getTypeInstance().getDataType();
syn String TypeInstance.getName() = getAnnotations().getName();
public Annotations Annotations.addName(String n) {
//XXX TODO: check if name already exists
addAnnotation(new Intention("",n.getBytes()));
return this;
}
public Field.Field(TypeInstance t) {
this(t.getDataType(), t.getAnnotations());
}
public TypeInstance.TypeInstance(DataType t, String n, Annotations a) {
this(t, a.addName(n));
}
public TypeInstance.TypeInstance(DataType t, String n) {
this(t, new Annotations().addName(n));
System.out.println("WARNING! TypeInstance(DataType, String) ignoring intention list");
}
syn Annotation TypeInstance.getAnnotation(int i) = getAnnotations().getAnnotation(i);
}
This diff is collapsed.
aspect TypeCheck {
public void ASTNode.typeCheck() {
// calls to the different type checks to be performed
nullTypeCheck();
}
// void is not allowed as a field in a struct or an array element
syn boolean DataType.isNull();
eq DataType.isNull() = false;
eq VoidType.isNull() = true;
eq UserType.isNull() = decl().isNull();
syn boolean TypeDecl.isNull();
eq TypeDecl.isNull() = getDataType().isNull();
public void ASTNode.nullTypeCheck() {}
public void Field.nullTypeCheck() {
if(getDataType().isNull()) {
error("field " + getName() + " of struct "+ declName()+ " may not be of type void");
}
}
public void ParseArrayType.nullTypeCheck() {
if(getDataType().isNull()) {
error("elements of array "+declName()+" may not be of type void");
}
}
public void ArrayType.nullTypeCheck() {
if(getDataType().isNull()) {
error("elements of array "+declName()+" may not be of type void");
}
}
}
aspect AnnotationCheck {
refine TypeCheck void ASTNode.typeCheck() {
refined(); // similar to call to super
annotationCheck();
}
public void ASTNode.annotationCheck() {}
public void TypeDecl.annotationCheck() {
Iterator<Intention> it = getTypeInstance().intentions().iterator();;
while(it.hasNext()) {
if(!it.next().getKey().equals("")) {
error("TypeDecl " + getName() + " has intentions. (Not allowed for typedefs)");
}
}
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
#!/bin/sh
java -jar /lib/labcomm2014_compiler.jar "$@"
File moved