Skip to main content
Sign in
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
  • labcomm2014
  • labcomm2006
  • master
  • python_sig_hash
  • typedefs
  • anders.blomdell
  • typeref
  • pragma
  • compiler-refactoring
  • labcomm2013
  • 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
  • Anton Klarén / LabComm
  • Tommy Olofsson / LabComm
  • Erik Jansson / LabComm
  • Sven Gestegård Robertz / LabComm
5 results
Select Git revision
  • master
  • anders.blomdell
  • typeref
  • pragma
  • compiler-refactoring
  • labcomm2013
  • v2013.0
  • v2014.0
  • v2014.1
9 results
Show changes

Commits on Source 610

510 additional commits have been omitted to prevent performance issues.
396 files
+ 30963
9521
Compare changes
  • Side-by-side
  • Inline

Files

.bzrignore

deleted100644 → 0
+0 −19
Original line number Diff line number Diff line
AST
AST/*
LabComm.class
labComm.jar
lib/java/se/lth/control/labcomm/LabComm.class
lib/java/se/lth/control/labcomm/LabCommDecoderChannel.class
lib/java/se/lth/control/labcomm/LabCommDecoder.class
lib/java/se/lth/control/labcomm/LabCommDecoderRegistry.class
lib/java/se/lth/control/labcomm/LabCommDecoderRegistry$Entry.class
lib/java/se/lth/control/labcomm/LabCommDispatcher.class
lib/java/se/lth/control/labcomm/LabCommEncoderChannel.class
lib/java/se/lth/control/labcomm/LabCommEncoder.class
lib/java/se/lth/control/labcomm/LabCommEncoderRegistry.class
lib/java/se/lth/control/labcomm/LabCommEncoderRegistry$Entry.class
lib/java/se/lth/control/labcomm/LabCommHandler.class
lib/java/se/lth/control/labcomm/LabCommReader.class
lib/java/se/lth/control/labcomm/LabCommSample.class
lib/java/se/lth/control/labcomm/LabCommType.class
lib/java/se/lth/control/labcomm/LabCommWriter.class

.gitignore

0 → 100644
+5 −0
Original line number Diff line number Diff line
*~
*.class
*.o
*.pyc
examples/dynamic/gen

ErrorCheck.jrag

deleted100644 → 0
+0 −30
Original line number Diff line number Diff line
import java.util.Collection;

aspect ErrorCheck {

	syn int ASTNode.lineNumber() = getLine(getStart());

	protected String ASTNode.errors = null;
	
	protected void ASTNode.error(String s) {
	    s = "Error at " + lineNumber() + ": " + s;
	    if(errors == null) {
	      errors = s;
	    } else {
	      errors = errors + "\n" + s;
	    }
	}

	protected boolean ASTNode.hasErrors() {
		return errors != null;
	}
	public void ASTNode.errorCheck(Collection collection) {
	    nameCheck();
	    if(hasErrors())
		collection.add(errors);
	    for(int i = 0; i < getNumChild(); i++) {
		getChild(i).errorCheck(collection);
	    }
	}

}

LICENSE.rationale

0 → 100644
+73 −0
Original line number Diff line number Diff line
Rationale for the licensing choosen for LabComm
===============================================

Primary goal:   the owners of systems with LabComm communication in it, 
                should have the liberty to replace the LabComm parts with 
                any software they see fit.

Secondary goal: it should be possible to release propreitary software
                with LabComm.


Wanted software architecture
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

+------------------------------------------------------------+
| Propreitary software (any license)                         |
+------------------------------------------------------------+
| Labcomm glue (LGPL)                                        |
+--------------+-----+--------------+                        |
|  Generated   |     |  Generated   |                        |
|   encoder/   |     |   encoder/   |                        |
|   decoder    | * * |   decoder    |                        |
| (  GPLv3 +   |     | (  GPLv3 +   |        +---------------+
|  permission) |     |  permission) |        |  Non-system   |
+--------------+-----+--------------+--+     |    library    |
| LabComm library (GPLv3 + permission) |     | (any license) | 
+--------------------------------------+-----+----------+----+
| System library (any license)                          |    |
+-------------------------------------------------------+    |
| OS (any license)                                           |
+------------------------------------------------------------+

License considerations
^^^^^^^^^^^^^^^^^^^^^^

We need to allow linking to the LabComm library from the LGPL glue
(see http://www.gnu.org/licenses/gpl-faq.html#GPLIncompatibleLibs).

We can not set a license on generated code
(http://www.gnu.org/licenses/gpl-faq.html#GPLOutput), 
but when used with the LabComm library we can force it 
to be licensed under GPLv3.


Suggested license for all library files
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Copyright 2013 Anders Blomdell <anders.blomdell@control.lth.se>

This file is part of LabComm.

LabComm is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

LabComm is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

Additional permission under GNU GPL version 3 section 7

If you modify this Program, or any covered work, by directly linking 
any functionality of it, with the the exception of calls denoting the 
boundary of encoded samples and calls encoding primitive datatypes,
with any software licensed under the GNU Lesser General Public License, 
the licensors of this Program grant you additional permission to convey 
the resulting work. 

LabComm.ast

deleted100644 → 0
+0 −23
Original line number Diff line number Diff line
Program ::= Decl*;

abstract Decl ::= Type <Name:String>;
TypeDecl : Decl;
SampleDecl : Decl;

Field ::= Type <Name:String>;

abstract Type;
VoidType          : Type;
PrimType          : Type ::= <Name:String> <Token:int>;
UserType          : Type ::= <Name:String>;
StructType        : Type ::= Field*;
ParseArrayType    : Type ::= Type Dim*;
abstract ArrayType : Type ::= Type Exp*;
VariableArrayType : ArrayType;
FixedArrayType    : ArrayType;

Dim ::= Exp*;

abstract Exp;
IntegerLiteral : Exp ::= <Value:String>;
VariableSize : Exp;

LabComm.java

deleted100644 → 0
+0 −295
Original line number Diff line number Diff line
import AST.*;
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("[ 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("[ Misc options ]");
    println(" --pretty                Pretty prints on standard output");
    println(" --typeinfo=TIFILE       Generates typeinfo in TIFILE");
  }
    
  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());
  }

  public static void main(String[] args) {
    String fileName = null;
    // Scan for first non-option
    for (int i = 0 ; i < args.length ; i++) {
      if (! args[i].startsWith("-")) {
	fileName = args[i];
	break;
      }
    }
    String coreName = null;
    String prefix = null;
    if (fileName != null) {
      coreName = getBaseName(fileName);
      prefix = getPrefix(coreName);
    }
    boolean verbose = false;
    String cFile = null;
    String hFile = null;
    Vector cIncludes = new Vector();
    String cPrefix = prefix;
    String csFile = null;
    String csNamespace = null;
    String javaDir = null;
    String javaPackage = "";
    String pythonFile = null;
    String prettyFile = null;
    String typeinfoFile = null;

    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].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 (i == args.length - 1) {
	fileName = args[i];
      } else {
	System.err.println(" Unknown argument " + args[i]);
	print_help();
	System.exit(2);
      }
    }
    if (fileName == null) {
      print_help();
      System.exit(1);
    } else {

      Program ast = null;

      try {
	// Check for errors
	LabCommScanner scanner = new LabCommScanner(new FileReader(fileName));
	LabCommParser parser = new LabCommParser();
	Program p = (Program)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());
      }
      if (ast != null) {
	
	Vector hIncludes = new Vector(cIncludes);
	if (hFile != null) {
	  cIncludes.add(hFile);
	}
	  
	boolean prettyOnStdout = true;
	if (cFile != null) {
	  if (verbose) { System.err.println("Generating C: " + cFile); }
	  genC(ast, cFile, cIncludes, coreName, cPrefix);
	  prettyOnStdout = false;
	}
	if (hFile != null) {
	  if (verbose) { System.err.println("Generating H: " + hFile); }
	  genH(ast, hFile, hIncludes, coreName, cPrefix);
	  prettyOnStdout = false;
	}
	if (csFile != null) {
	  if (verbose) { System.err.println("Generating C#: " + csFile); }
	  genCS(ast, csFile, csNamespace);
	  prettyOnStdout = false;
	}
	if (javaDir != null) {
	  if (verbose) { System.err.println("Generating Java: " + javaDir); }
	  genJava(ast, javaDir, javaPackage);
	  prettyOnStdout = false;
	}
	if (pythonFile != null) {
	  if (verbose) { 
	    System.err.println("Generating Python: " + pythonFile); 
	  }
	  genPython(ast, pythonFile, prefix);
	  prettyOnStdout = false;
	}
	if (prettyFile != null) {
	  if (verbose) { 
	    System.err.println("Generating Pretty: " + prettyFile); 
	  }
	  try {
	    FileOutputStream f = new FileOutputStream(prettyFile);
	    PrintStream out = new PrintStream(f);
	    ast.pp(out);
	    out.close();
	    prettyOnStdout = false;
	  } catch (IOException e) {
	    System.err.println("IOException: " + prettyFile + " " + e);
	  } 
	}
	if (typeinfoFile != null) {
	  if (verbose) { 
	    System.err.println("Generating TypeInfo: " + typeinfoFile); 
	  }
	  try {
	    FileOutputStream f = new FileOutputStream(typeinfoFile);
	    PrintStream out = new PrintStream(f);
	    ast.C_info(out, cPrefix);
	    ast.Java_info(out);
	    ast.CS_info(out, csNamespace);
	    prettyOnStdout = false;
	  } catch (IOException e) {
	    System.err.println("IOException: " + typeinfoFile + " " + e);
	  }
	}
	if (prettyOnStdout) {
	  ast.pp(System.out);
	}
      }
    }
  } 

  private static void genH(Program p, String hName, 
			   Vector cIncludes, String coreName, String prefix) {
    try {
      FileOutputStream f;
      PrintStream out;
      
      f = new FileOutputStream(hName);
      out = new PrintStream(f);
      p.C_genH(out, cIncludes, coreName, prefix);
      out.close();
    } catch (IOException e) {
      System.err.println("IOException: " + hName + " " + e);
    }
  }

  private static void genC(Program p, String cName, 
			   Vector cIncludes, String coreName, String prefix) {
    try {
      FileOutputStream f;
      PrintStream out;

      f = new FileOutputStream(cName);
      out = new PrintStream(f);
      p.C_genC(out, cIncludes, coreName, prefix);
      out.close();
    } catch (IOException e) {
      System.err.println("IOException: " + cName + " " + e);
    }
  }

  private static void genCS(Program p, String csName, String csNamespace) {
    try {
      p.CS_gen(csName, csNamespace);
    } catch (IOException e) {
      System.err.println("IOException: " + csName + " " + 
			 csNamespace + " " + e);
    }
  }

  private static void genJava(Program p,  String dirName, String packageName) {
    try {
      p.J_gen(dirName, packageName);
    } catch (IOException e) {
      System.err.println("IOException: " + dirName + " " + 
			 packageName + " " + e);
    }
  }

  private static void genPython(Program p, String filename, String prefix) {
    try {
      FileOutputStream f;
      PrintStream out;

      f = new FileOutputStream(filename);
      out = new PrintStream(f);
      p.Python_gen(out, prefix);
      out.close();
    } catch (IOException e) {
      System.err.println("IOException: " + filename + " " + e);
    }
  }



}

LabCommmTokens.jrag

deleted100644 → 0
+0 −18
Original line number Diff line number Diff line
aspect LabCommTokens {

  public static final int ASTNode.LABCOMM_TYPEDEF = 0x01;
  public static final int ASTNode.LABCOMM_SAMPLE =  0x02;

  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;

}
 No newline at end of file

Makefile

0 → 100644
+46 −0
Original line number Diff line number Diff line
SUBDIRS=compiler lib test examples packaging
export LABCOMM_JAR=$(shell pwd)/compiler/labcomm2014_compiler.jar
export LABCOMM=java -jar $(LABCOMM_JAR) 
export VALGRIND=valgrind --leak-check=full --error-exitcode=1

UNAME_S=$(shell uname -s)

.PHONY: all
all: $(SUBDIRS:%=all-%)

.PHONY: all-%
all-%:
ifeq ($(UNAME_S),Darwin)
	DYLD_LIBRARY_PATH=`pwd`/lib/c $(MAKE) -C $*
else
	LD_LIBRARY_PATH=`pwd`/lib/c $(MAKE) -C $*
endif

.PHONY: test
test: $(SUBDIRS:%=test-%)

.PHONY: test-%
test-%:
ifeq ($(UNAME_S),Darwin)
	DYLD_LIBRARY_PATH=`pwd`/lib/c $(MAKE) -C $* test
else
	LD_LIBRARY_PATH=`pwd`/lib/c $(MAKE) -C $* test
endif

.PHONY: clean
clean: $(SUBDIRS:%=clean-%)

.PHONY: clean-%
clean-%:
	$(MAKE) -C $* clean

.PHONY: distclean
distclean: clean $(SUBDIRS:%=distclean-%)

.PHONY: distclean-%
distclean-%:
	$(MAKE) -C $* distclean

.PHONY: srpm
srpm:
	make -C packaging $@

Python_CodeGen.jrag

deleted100644 → 0
+0 −193
Original line number Diff line number Diff line
aspect Python_CodeGenEnv {

  // Environment wrapper for Python code generation
  // handles qualid nesting, indentation, file writing and
  // prefix propagation

  public class Python_env {

    final private class Python_printer {
      
      private boolean newline = true;
      private PrintStream out;

      public Python_printer(PrintStream out) {
        this.out = out;
      }

      public void print(Python_env env, String s) {
        if (newline) {
          newline = false;
          for (int i = 0 ; i < env.indent ; i++) {
            out.print("    ");
          }
        }
        out.print(s);
      }

      public void println(Python_env env, String s) {
        print(env, s);
        out.println();
        newline = true;
      }

      public void println(Python_env env) {
        out.println();
        newline = true;
      }

    }

    private int indent;
    private Python_printer printer;

    public Python_env(PrintStream out) {
      this.indent = 0;
      this.printer = new Python_printer(out);
    }

    public void indent() {
      indent++;
    }

    public void unindent() {
      indent--;
    }

    public void print(String s) {
      printer.print(this, s);
    }

    public void println(String s) {
      printer.println(this, s);
    }

    public void println() {
      printer.println(this);
    }

  }

}

aspect Python_CodeGen {

  public void Program.Python_gen(PrintStream out, String baseName) {
    Python_env env = new Python_env(out);
    env.println("#!/usr/bin/python");
    env.println("# Auto generated " + baseName);
    env.println();
    env.println("import labcomm");
    env.println();
    Python_genTypes(env);
  }

}

aspect PythonTypes {
  
  public void Program.Python_genTypes(Python_env env) {
    for (int i = 0 ; i < getNumDecl() ; i++) {
      env.println("class " + getDecl(i).getName() + "(object):");
      env.indent();
      getDecl(i).Python_genSignature(env);
      env.unindent();
      env.println();
    }
  }

  public void Decl.Python_genSignature(Python_env env) {
    throw new Error(this.getClass().getName() + 
                    ".Python_genSignature(Python_env env)" + 
                    " not declared");
  }

  public void TypeDecl.Python_genSignature(Python_env env) {
    env.println("no_signature = labcomm.typedef('" + getName() + "',");
    env.indent();
    getType().Python_genSignature(env);
    env.unindent();
    env.println(")");
  }

  public void SampleDecl.Python_genSignature(Python_env env) {
    env.println("signature = labcomm.sample('" + getName() + "', ");
    env.indent();
    getType().Python_genSignature(env);
    env.unindent();
    env.println(")");
  }

  public void UserType.Python_genSignature(Python_env env) {
    lookupType(getName()).getType().Python_genSignature(env);
  }

  public void Type.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("labcomm.BOOLEAN()"); } break;
      case LABCOMM_BYTE: { env.print("labcomm.BYTE()"); } break;
      case LABCOMM_SHORT: { env.print("labcomm.SHORT()"); } break;
      case LABCOMM_INT: { env.print("labcomm.INTEGER()"); } break;
      case LABCOMM_LONG: { env.print("labcomm.LONG()"); } break;
      case LABCOMM_FLOAT: { env.print("labcomm.FLOAT()"); } break;
      case LABCOMM_DOUBLE: { env.print("labcomm.DOUBLE()"); } break;
      case LABCOMM_STRING: { env.print("labcomm.STRING()"); } break;
    }
  }

  public void ArrayType.Python_genSignature(Python_env env) {
    env.print("labcomm.array([");
    for (int i = 0 ; i < getNumExp() ; i++) {
      if (i > 0) { env.print(", "); }
      env.print(getExp(i).Python_getValue());
    }
    env.println("],");
    env.indent();
    getType().Python_genSignature(env);
    env.print(")");
    env.unindent();
  }

  public void StructType.Python_genSignature(Python_env env) {
    env.println("labcomm.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("labcomm.struct([])");
    env.unindent();
  }

  public void Field.Python_genSignature(Python_env env) {
    env.print("('" + getName() + "', ");
    getType().Python_genSignature(env);
    env.print(")");
  }

  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";
  }

}
 No newline at end of file

README

0 → 100644
+60 −0
Original line number Diff line number Diff line
Embryo of documentation. More details on http://wiki.cs.lth.se/moin/LabComm

*** The LabComm data description language: ***

Primitive types

  sample boolean a_boolean;
  sample byte a_byte;
  sample short a_short;
  sample int an_int;
  sample long a_long;
  sample float a_float;
  sample double a_double;
  sample string a_string;


Arrays

  sample int fixed_array[3];
  sample int variable_array[_];                // Note 1
  sample int fixed_array_of_array[3][4];       // Note 2
  sample int fixed_rectangular_array[3, 4];    // Note 2
  sample int variable_array_of_array[_][_];    // Notes 1 & 2
  sample int variable_rectangular_array[_, _]; // Notes 1 & 2

1 In contrast to C, LabComm supports both fixed and variable (denoted by '_') sized arrays.
2 In contrast to Java, LabComm supports multidimensional arrays and not only arrays of arrays. 


Structures

  sample struct {
    int an_int_field;
    double a_double_field;
  } a_struct;


User defined types

  typedef struct {
    int field_1;
    byte field_2;
  } user_type[_];
  sample user_type a_user_type_instance;
  sample user_type another_user_type_instance;


Example sample declaration (e.g. example.lc)

  sample struct {
    int sequence;
    struct {
      boolean last;
      string data;
    } line[_];
  } log_message;

From an .lc file, the labcomm compiler can generate marshalling and demarshalling code
for C, Java, Python, and C#.

build.xml

deleted100644 → 0
+0 −104
Original line number Diff line number Diff line
<!--
 Targets for working from terminal window:
       build (default) - generates java files and compiles them
       clean           - removes all generated files and class files
 Targets for working from Eclipse:
       gen             - generates java files
       genClean        - removes all generated files and their class files
-->
<project name="LabComm" default="build" basedir=".">

<!-- "package" is the directory where generated files will be stored -->
<property name="package" value="AST"/>

<!-- "tools" is the directory where generators and libraries are located. -->
<property name="tools" value="tools"/>
	
<!-- "test" is the directory where tests are located. -->
<property name="test" value="test"/>
	
<!-- "jflex" is an ant task class for the scanner generator in JFlex.jar -->
<taskdef name="jflex" classname="JFlex.anttask.JFlexTask" classpath="tools/JFlex.jar"/>
<!-- "beaver" is an ant task class for the parser generator in beaver.jar -->
<taskdef name="beaver" classname="beaver.comp.run.AntTask" classpath="tools/beaver.jar"/>
<!-- "jastadd" is an ant task class in jastadd2.jar -->
<taskdef name="jastadd" classname="jastadd.JastAddTask"
classpath="tools/jastadd2.jar"/>


<!-- compile sources -->
<target name="build" depends="gen">
	<javac debug="true" nowarn="true" srcdir="." includes="**/*.java" excludes="test/**" classpath=".:${tools}/beaver-rt.jar:${tools}/junit.jar"
   fork="true" memoryMaximumSize="128M"/>
</target>
	

<!-- generate compiler source files -->
<target name="gen">
	<!-- create AST node types and weave aspect modules -->
		<echo message = "Running JastAdd"/>
		<jastadd package="${package}" rewrite="true" beaver="true" novisitcheck="true" lazyMaps="true" outdir="${basedir}">
			<fileset dir=".">
				<include name="**/*.ast"/>
				<include name="**/*.jrag"/>
				<include name="**/*.jadd"/>
			</fileset>
		</jastadd>
	<!-- generate the scanner -->
		<echo message = "Running jflex"/>
		<jflex file="LabCommScanner.flex" outdir="AST" nobak="yes"/>
	<!-- generate the parser phase 1, create a full .lalr specification from fragments-->
		<echo message = "Running parser phase 1"/>
		<concat destfile="AST/LabCommParser.all" binary="true">
	    <fileset dir=".">
	      <include name="*.parser"/>
	    </fileset>
	</concat>
	<!-- generate the parser phase 2, translating .lalr to .beaver -->
		<java fork="true" dir="${basedir}" classpath="${tools}/proj.jar:${tools}/beaver-rt.jar" classname="Main">
			<arg line="AST/LabCommParser.all AST/LabCommParser.beaver"/>
		</java>
	<!-- generate the parser phase 3, translating .beaver to .java -->
	<beaver file="AST/LabCommParser.beaver" terminalNames="yes" compress="yes" useSwitch="yes"/>
</target>


<!-- compile sources -->
<target name="test" depends="jar">
  <echo message = "Running tests"/>
  <exec executable="./run" dir="test"> 
    <env key="PYTHONPATH" value="../lib/python"/>
    <!--arg value="hej"/-->
  </exec>
</target>
	
<!-- remove generated source files and .class files -->
<target name="clean" depends="cleanGen">
     <!-- delete all .class files recursively -->
    <delete>
      <fileset dir="." includes="**/*.class"/>
    </delete>
</target>


<!-- remove generated source files and their .class files -->
<target name="cleanGen">
	 <delete dir="${package}"/>
</target>


<target name="jar" depends="build">
  <jar destfile="labComm.jar">
    <fileset dir="." includes="LabComm*.class"/>
    <fileset dir="." includes="AST/*.class"/>
    <zipfileset src="tools/beaver-rt.jar" includes="beaver/*.class"/>
    <manifest>
      <attribute name="Main-Class" value="LabComm"/>
    </manifest>
  </jar>
</target>
		  

</project>

compiler/.gitignore

0 → 100644
+4 −0
Original line number Diff line number Diff line
gen
labcomm2006_compiler.jar
labcomm2014_compiler.jar
labcomm2014_compiler.jar
+130 −0
Original line number Diff line number Diff line
aspect Annotations {
    syn boolean TypeInstance.hasAnnotations() = getAnnotations().getNumAnnotation()>0;
    syn boolean TypeInstance.hasIntentions() = ! intentionSet().isEmpty();

    syn String Annotations.getName() = new String(lookup(""));

    syn byte[] Annotations.lookup(String key) {
        for(Annotation a: getAnnotations()) {
            byte[] res = a.lookup(key);
            if(res != null) return res;
        }
        return null;
    }

    syn byte[] Annotation.lookup(String key) = (getKey().equals(key) ? getValue() : null);

    syn boolean Annotation.isIntention() = false;
    eq Intention.isIntention() = true;

    inh TypeInstance Annotation.parentInstance();
    eq TypeInstance.getAnnotations().parentInstance() = this;

    coll Set<Intention> TypeInstance.intentionSet() [new HashSet<Intention>()] with add;
    Intention contributes this
        to TypeInstance.intentionSet()
        for parentInstance();

}

aspect SigAnnotations {

   inh Decl TypeInstance.parentDecl();

   coll Set Decl.allAnnotations() [new HashSet()] with add;
   TypeInstance contributes getAnnotationString()
           to Decl.allAnnotations()
           for parentDecl();

   // Helper attribute to get the "outermost" intentions for Decls

   syn byte[] TypeInstance.intentionBytes() = getIntentionBytes(sortedIntentions());
   syn byte[] Decl.getIntentionBytes() = getTypeInstance().intentionBytes();

    static Comparator TypeInstance.intentionComp =
        new Comparator<Intention>() {
            public int compare(Intention i1, Intention i2) {
                    return i1.getKey().compareTo(i2.getKey());
            }
    };

    syn int Decl.getNumIntentions() = getTypeInstance().sortedIntentions().getNumChild();

   syn List<Intention> TypeInstance.sortedIntentions() {
       List<Intention> res = new List<Intention>();

       //TODO: refactor out creation of sorted list of intentions

       java.util.ArrayList<Intention> sorted = new ArrayList(intentionSet());
       java.util.Collections.sort(sorted, intentionComp);
       for(Intention i : sorted) {
           res.add(i);
       }
       return res;
   }


   public DocString.DocString(byte[] bs) {
           super("DOCSTRING", bs);
   }

   public DocString.DocString(String s) {
           super("DOCSTRING", s.getBytes());
   }

   public String Intention.toString() {
       return "("+getKey() + ":"+new String(getValue())+")";
   }
   public String  DocString.toString() {
           return "\""+new String(getValue())+"\"";
   }

    /// TESTING
    syn String Decl.getAnnotationString()  {
            StringBuilder sb = new StringBuilder();
            Iterator<String> iti = allAnnotations().iterator();
            while(iti.hasNext()) {
                    //Annotation i = iti.next();
                    //sb.append("("+i.getKey()+" : "+i.getValue()+") ");
                    String i = iti.next();
                    sb.append(i);
            }
            return sb.toString();
    }


    syn int TypeInstance.fooHash() {
            List<Annotation> ints = getAnnotations().getAnnotationList();
            int result=0;
            for(Annotation i : ints) {
                    if(i.isIntention()) {
                        result += i.toString().hashCode();
                    }
            }
            return result;
    }

    syn String TypeInstance.getAnnotationString() {
            StringBuilder sb = new StringBuilder();
            List<Annotation> ints = getAnnotations().getAnnotationList();
            for(Annotation i : ints) {
                    sb.append(i.toString());
            }
            return sb.toString();
    }

    public void Decl.debugAnnotations() {
            getTypeInstance().debugAnnotations(getName());
    }

    public void TypeInstance.debugAnnotations(String context) {
            if(hasAnnotations()){
                System.out.println(context+".annotations: " + fooHash() + " : " + getAnnotationString());
            } else {
                //System.out.println(context + " : " + fooHash() + " : " + ": NO ANNOTATIONS ");
            }
    }
    //  TESTING END

}
+8 −8
Original line number Diff line number Diff line
@@ -13,29 +13,29 @@ aspect ArrayRewrite {
    when (! getDim(0).isVariable()) 
    to FixedArrayType  { 
      if (getNumDim() == 1) {
        return new FixedArrayType(getType(), 
				  getDim(0).getExpList());
        return new FixedArrayType(getDataType(), 
				  getDim(0));
      } else {
        List l = new List();
        for (int i = 1 ; i < getNumDim() ; i++) {
	  l.add(getDim(i));
        }
        return new FixedArrayType(new ParseArrayType(getType(), l), 
				  getDim(0).getExpList());
        return new FixedArrayType(new ParseArrayType(getDataType(), l), 
				  getDim(0));
      }
    }
    when (getDim(0).isVariable()) 
    to VariableArrayType  { 
      if (getNumDim() == 1) {
        return new VariableArrayType(getType(), 
				     getDim(0).getExpList());
        return new VariableArrayType(getDataType(), 
				     getDim(0));
      } else {
        List l = new List();
        for (int i = 1 ; i < getNumDim() ; i++) {
	  l.add(getDim(i));
        }
        return new VariableArrayType(new ParseArrayType(getType(), l), 
				     getDim(0).getExpList());
        return new VariableArrayType(new ParseArrayType(getDataType(), l), 
				     getDim(0));
      }
    }
  }
+343 −293

File changed and moved.

Preview size limit exceeded, changes collapsed.

+1701 −0

File changed and moved.

Preview size limit exceeded, changes collapsed.

+14 −0
Original line number Diff line number Diff line
aspect DeclNames {
	inh String DataType.declName();
	eq Decl.getTypeInstance().declName() = getName();

	inh String Field.declName();
	eq StructType.getField(int i).declName() = declName();

    //TODO: aspect should be renamed to parent-something

    inh Decl DataType.parentDecl();
    inh Decl Field.parentDecl();
    eq Decl.getTypeInstance().parentDecl() = this;
    eq StructType.getField(int i).parentDecl() = parentDecl();
}
+30 −0
Original line number Diff line number Diff line
import java.util.Collection;

aspect ErrorCheck {

    syn int ASTNode.lineNumber() = getLine(getStart());

    protected String ASTNode.errors = null;

    protected void ASTNode.error(String s) {
        s = "Error at " + lineNumber() + ": " + s;
        if(errors == null) {
          errors = s;
        } else {
          errors = errors + "\n" + s;
        }
    }

    protected boolean ASTNode.hasErrors() {
        return errors != null;
    }
    public void ASTNode.errorCheck(Collection collection) {
        nameCheck();
        typeCheck();
        if(hasErrors())
        collection.add(errors);
        for(int i = 0; i < getNumChild(); i++) {
        getChild(i).errorCheck(collection);
        }
    }
}
+139 −0
Original line number Diff line number Diff line
import java.util.*;

aspect Signature {  

  public class SignatureLine {
  
    private int indent;
    private byte[] data;
    private String comment;

    public SignatureLine(int indent, byte[] data, String comment) {
      this.indent = indent;
      this.data = data;
      this.comment = comment;
    }

    public int getIndent() {
      return indent;
    }

    public byte[] getData() {
      return data;
    }

    public String getComment() {
      return comment;
    }

aspect NoIntentionForTypeOrSampledefs {
    inh boolean TypeInstance.addIntentions();
    eq Decl.getTypeInstance().addIntentions() = false;
    eq StructType.getField(int i).addIntentions() = true;
}

  public class SignatureList {
aspect FlatSignature {

    private int indent;
    private ArrayList list = new ArrayList();
    
    public void add(byte[] data, String comment) {
      list.add(new SignatureLine(indent, data, comment));
    }

    public void addInt(int value, String comment) {
      byte[] data = new byte[4];
      for (int i = 0 ; i < 4 ; i++) {
        data[3 - i] = (byte)((value >> (8 * i)) & 0xff);
      }
      add(data, comment);
    }

    public void addString(String value, String comment) {
      addInt(value.length(), comment);
      byte[] data = new byte[value.length()];
      for (int i = 0 ; i < value.length() ; i++) {
        data[i] = (byte)(value.charAt(i) & 0xff);
      }
      add(data, null);
    }

    public int size() {
      return list.size();
    }

    public String getIndent(int i) {
      StringBuffer result = new StringBuffer();
      int indent = ((SignatureLine)list.get(i)).getIndent();
      for (i = 0 ; i < indent ; i++) {
        result.append("  ");
      }
      return result.toString();
    }

    public byte[] getData(int i) {
      return ((SignatureLine)list.get(i)).getData();
    }

    public String getComment(int i) {
      return ((SignatureLine)list.get(i)).getComment();
    }

    public void indent() {
      indent++;
    }

    public void unindent() {
      indent--;
    }

  }

  public SignatureList Decl.signature() {
    SignatureList result = new SignatureList();
    flatSignature(result);
  public SignatureList Decl.flatSignature(int version) {
    SignatureList result = getSignature().getFlatSignatureList();
    return result;
  }

@@ -98,11 +20,23 @@ aspect Signature {
  }

  public void TypeDecl.flatSignature(SignatureList list) {
    getType().flatSignature(list);
    getTypeInstance().flatSignature(list);
  }

  public void SampleDecl.flatSignature(SignatureList list) {
    getType().flatSignature(list);
    getTypeInstance().flatSignature(list);
  }

//  public void SampleRefType.flatSignature(SignatureList list) {
//    list.addInt(LABCOMM_SAMPLE_REF, "sample");
//  }

  public void TypeInstance.flatSignature(SignatureList list) {
    if(addIntentions()) {
      debugAnnotations(this.getName()+".TypeInstance.flatSignature");
      list.addIntentions(intentions(), "intentions: "+getIntentionString());
    }
    getDataType().flatSignature(list);
  }

  public void VoidType.flatSignature(SignatureList list) {
@@ -125,7 +59,7 @@ aspect Signature {
    for (int i = 0 ; i < getNumExp() ; i++) {
      getExp(i).flatSignature(list);
    }
    getType().flatSignature(list);
    getDataType().flatSignature(list);
    list.unindent();
    list.add(null, "}");
  }
@@ -142,8 +76,10 @@ aspect Signature {
  }

  public void Field.flatSignature(SignatureList list) {
    list.addString(getName(), signatureComment());
    getType().flatSignature(list);
    debugAnnotations(this.getName()+".Field.flatSignature");
    list.addIntentions(intentions(), "Field: "+getIntentionString());
//    list.addString(getName(), signatureComment());
    getDataType().flatSignature(list);
  }

  public void IntegerLiteral.flatSignature(SignatureList list) {
@@ -173,9 +109,13 @@ aspect Signature {
  }

  public String Field.signatureComment() {
    return getType().signatureComment() + " '" + getName() +"'";
    return getDataType().signatureComment() + " '" + getName() +"'";
  }

//  public String SampleRefType.signatureComment() {
//    return "sample";
//  }

  public String PrimType.signatureComment() {
    return getName();
  }
+36 −0
Original line number Diff line number Diff line
aspect TypeDefGen {

    public void Specification.generateTypedefs(PrintStream out, int ver) {
        for(Decl d : getDecls()) {
            d.generateTypedefs(out);
        }
    }

    public void Decl.generateTypedefs(PrintStream out) {
    }


    public void Decl.generateDepTypedefs(PrintStream out){
        Iterator<Decl> it = type_dependencies().iterator();
        while(it.hasNext()) {
            Decl d = it.next();
            d.generateDepTypedefs(out);
        }
        pp(out);
    }

    public void SampleDecl.generateTypedefs(PrintStream out){

        if(hasDependencies()) {
            out.println("sample "+getName()+"_def {");
            out.println("    sample sample;");
            out.println("    string typedef = <<EOL");
            for(Decl d : type_dependencies()) {
                d.generateDepTypedefs(out);
            }
            pp(out);
            out.println("EOL;");
        }
    }

}
+1188 −0

File changed and moved.

Preview size limit exceeded, changes collapsed.

+46 −0
Original line number Diff line number Diff line
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;
+425 −0
Original line number Diff line number Diff line
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);
      }
    }
  }
}
+52 −32
Original line number Diff line number Diff line
%header {:
 package AST;
  package se.lth.control.labcomm2014.compiler;
  import se.lth.control.labcomm2014.compiler.*;
:};
%embed {:
  public static class SourceError extends Error {
@@ -33,9 +34,9 @@
        }
:};

Program goal =
     /* Empty program */               {: return new Program(); :}
  |  decl_list.l                       {: return new Program(l); :}
Specification goal =
     /* Empty program */               {: return new Specification(); :}
  |  decl_list.l                       {: return new Specification(l); :}
  ;

List decl_list =
@@ -53,31 +54,44 @@ List var_decl_list =
  | 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 =
    type.t IDENTIFIER SEMICOLON     {: return new Field(t, IDENTIFIER); :}
  | type.t IDENTIFIER dim_list.d SEMICOLON 
    {: return new Field(new ParseArrayType(t, d), IDENTIFIER); :}
    type_instance.t SEMICOLON     {: return new Field(t); :}
  ;

TypeDecl type_decl =
    TYPEDEF type.t IDENTIFIER SEMICOLON {: return new TypeDecl(t, IDENTIFIER); :}
  | TYPEDEF type.t IDENTIFIER dim_list.d SEMICOLON 
    {: return new TypeDecl(new ParseArrayType(t, d), IDENTIFIER); :}
  ;
    TYPEDEF type_instance.t  SEMICOLON {: return new TypeDecl(t); :} ;

SampleDecl sample_decl =
    SAMPLE type.t IDENTIFIER SEMICOLON 
      {: 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); :}
  ;
    SAMPLE type_instance.t SEMICOLON {: return new SampleDecl(t); :} ;

Type type =
DataType type =
    prim_type.p                     {: return p; :}
  | user_type.u                     {: return u; :}
  | struct_type.s                   {: return s; :}
  | void_type.v                     {: return v; :}
  ;

PrimType prim_type =
@@ -97,6 +111,8 @@ PrimType prim_type =
      {: return new PrimType(DOUBLE, ASTNode.LABCOMM_DOUBLE); :}
  | STRING
      {: return new PrimType(STRING, ASTNode.LABCOMM_STRING); :}
  | SAMPLE
      {: return new PrimType(SAMPLE, ASTNode.LABCOMM_SAMPLE); :}
  ;

UserType user_type =
@@ -107,6 +123,10 @@ StructType struct_type =
    STRUCT LBRACE var_decl_list.l RBRACE {: return new StructType(l); :}
  ;

VoidType void_type =
    VOID {: return new VoidType(); :}
;

List dim_list =
    dim.d                           {: return new List().add(d); :}
  | dim_list.l  dim.d               {: return l.add(d); :}
+16 −9
Original line number Diff line number Diff line
package AST;
package se.lth.control.labcomm2014.compiler;

import beaver.Symbol;
import beaver.Scanner;
import AST.LabCommParser.Terminals;
import se.lth.control.labcomm2014.compiler.LabCommParser.Terminals;

%%

@@ -44,13 +44,16 @@ Comment = {TraditionalComment}
TraditionalComment = "/*" [^*] ~"*/" | "/*" "*"+ "/" | "/*" "*"+ [^/*] ~"*/"
EndOfLineComment = "//" {InputCharacter}* {LineTerminator}?

Identifier = [:jletter:][:jletterdigit:]*
Identifier = [[:letter:]_]([[:letter:]_[:digit:]])*
StringLiteral = [:jletterdigit:]*

DecimalNumeral = 0 | {NonZeroDigit} {Digits}?
Digits = {Digit}+
Digit = 0 | {NonZeroDigit}
NonZeroDigit = [1-9]

QuotedString = "\""~"\""

%%

<YYINITIAL> {
@@ -76,10 +79,14 @@ NonZeroDigit = [1-9]
  "}"                            { return sym(Terminals.RBRACE); }
  "["                            { return sym(Terminals.LBRACK); }
  "]"                            { return sym(Terminals.RBRACK); }
  "("                            { return sym(Terminals.LPAREN); }
  ")"                            { return sym(Terminals.RPAREN); }
  ";"                            { return sym(Terminals.SEMICOLON); }
  ":"                            { return sym(Terminals.COLON); }
  ","                            { return sym(Terminals.COMMA); }

  {Identifier}                   { return sym(Terminals.IDENTIFIER); }
  {QuotedString}                 { return sym(Terminals.QUOTEDSTRING); }
}

// fall through errors
+22 −0
Original line number Diff line number Diff line
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;

}
+6 −3
Original line number Diff line number Diff line
@@ -2,7 +2,7 @@
aspect NameAnalysis {

  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++) {
      String s = getDecl(i).getName();
      if (s.equals(name)) {
@@ -24,7 +24,7 @@ aspect NameAnalysis {

  inh TypeDecl Decl.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++) {
      Decl d = getDecl(i);  
      if(d instanceof TypeDecl && d.getName().equals(name)) {
@@ -34,7 +34,10 @@ aspect NameAnalysis {
    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() {
+14 −10
Original line number Diff line number Diff line
@@ -6,7 +6,7 @@ aspect PPIndentation {
  inh String Field.pp_indent();
  inh String StructType.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 {
		    " not declared");
  }

  public void Program.pp(PrintStream out) {
  public void Specification.pp(PrintStream out) {
    for(int i = 0; i < getNumDecl(); i++) {
    	getDecl(i).pp(out);
    }
@@ -27,24 +27,24 @@ aspect PrettyPrint {
   // Pretty print declarations
  public void TypeDecl.pp(PrintStream out) {
    out.print("typedef ");
    getType().ppIdentifier(out, getName());
    getDataType().ppIdentifier(out, getName());
    out.println(";");
  }

  public void SampleDecl.pp(PrintStream out) {
    out.print("sample ");
    getType().ppIdentifier(out, getName());
    getDataType().ppIdentifier(out, getName());
    out.println(";");
  }

  public void Field.pp(PrintStream out) {
    out.print(pp_indent());
    getType().ppIdentifier(out, getName());
    getDataType().ppIdentifier(out, getName());
    out.println(";");
  }

  // 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);
    out.print(" ");
    out.print(id);
@@ -58,7 +58,7 @@ aspect PrettyPrint {
  }

  // PrettyPrint prefix type info
  public void Type.ppPrefix(PrintStream out) {
  public void DataType.ppPrefix(PrintStream out) {
    throw new Error(this.getClass().getName() + 
		    ".ppPrefix(PrintStream out)" + 
		    " not declared");
@@ -68,6 +68,10 @@ aspect PrettyPrint {
    out.print("void");
  }

//  public void SampleRefType.ppPrefix(PrintStream out) { 
//    out.print("sample");
//  }

  public void PrimType.ppPrefix(PrintStream out) { 
    out.print(getName());
  }
@@ -77,7 +81,7 @@ aspect PrettyPrint {
  }

  public void ArrayType.ppPrefix(PrintStream out) {
    getType().ppPrefix(out);
    getDataType().ppPrefix(out);
  }

  public void StructType.ppPrefix(PrintStream out) {
@@ -90,7 +94,7 @@ aspect PrettyPrint {
  }

  // PrettyPrint suffix type info (array dimensions)
  public void Type.ppSuffix(PrintStream out) { }
  public void DataType.ppSuffix(PrintStream out) { }

  public void ArrayType.ppSuffix(PrintStream out) { 
    out.print("[");
@@ -99,7 +103,7 @@ aspect PrettyPrint {
      getExp(i).pp(out);
    }
    out.print("]");
    getType().ppSuffix(out);
    getDataType().ppSuffix(out);
  }

  public void IntegerLiteral.pp(PrintStream out) {
+267 −0
Original line number Diff line number Diff line
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";
  }

}
+369 −0

File added.

Preview size limit exceeded, changes collapsed.

+30 −0
Original line number Diff line number Diff line
/* 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);
}
+372 −0

File added.

Preview size limit exceeded, changes collapsed.

+54 −0
Original line number Diff line number Diff line
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)");
     }
    }
  }
}
+46 −0

File added.

Preview size limit exceeded, changes collapsed.

+233 −0

File added.

Preview size limit exceeded, changes collapsed.

+22 −0

File added.

Preview size limit exceeded, changes collapsed.

compiler/Makefile

0 → 100644
+16 −0

File added.

Preview size limit exceeded, changes collapsed.

compiler/build.xml

0 → 100644
+228 −0

File added.

Preview size limit exceeded, changes collapsed.

compiler/labcomm2014

0 → 100755
+2 −0
Original line number Diff line number Diff line
#!/bin/sh
java -jar /lib/labcomm2014_compiler.jar "$@"
(166 KiB)

File moved.

+123 KiB

File added.

No diff preview for this file type.

+119 KiB

File added.

No diff preview for this file type.

+14.8 KiB

File added.

No diff preview for this file type.

+592 KiB

File added.

No diff preview for this file type.

(61.3 KiB)

File moved.

cs_codegen.patch

deleted100644 → 0
+0 −34

File deleted.

Preview size limit exceeded, changes collapsed.

doc/.gitignore

0 → 100644
+7 −0

File added.

Preview size limit exceeded, changes collapsed.

doc/refs.bib

0 → 100644
+39 −0

File added.

Preview size limit exceeded, changes collapsed.

doc/tech_report.tex

0 → 100644
+911 −0

File added.

Preview size limit exceeded, changes collapsed.

examples/Makefile

0 → 100644
+33 −0

File added.

Preview size limit exceeded, changes collapsed.

+1 −0
Original line number Diff line number Diff line
gen
Loading