Added separate cc/ci emitters, modified driver, added antlr3.1 option
authorAaron Becker <abecker3@illinois.edu>
Tue, 3 Jun 2008 23:34:49 +0000 (23:34 +0000)
committerAaron Becker <abecker3@illinois.edu>
Tue, 3 Jun 2008 23:34:49 +0000 (23:34 +0000)
src/langs/charj/build.xml
src/langs/charj/src/charj/Main.java
src/langs/charj/src/charj/translator/CharjCC.stg [new file with mode: 0644]
src/langs/charj/src/charj/translator/CharjCCEmitter.g [new file with mode: 0644]
src/langs/charj/src/charj/translator/CharjCI.stg [new file with mode: 0644]
src/langs/charj/src/charj/translator/CharjCIEmitter.g [new file with mode: 0644]
src/langs/charj/src/charj/translator/CharjEmitter.g
src/langs/charj/src/charj/translator/Translator.java

index b9f7a35b8f44a3375f9b9bde0ff5d4c6990d984d..b230b87113e9c24f90a6b9cfabb0406e758d32c9 100644 (file)
     <property name="token.lib" location="${buildsrc}/${package}" />\r
 \r
     <!-- Define path used for classpath later -->\r
-    <path id="project.class.path">\r
+    <path id="project.class.path.3.0">\r
         <pathelement location="lib/antlr-2.7.7.jar"/>\r
         <pathelement location="lib/antlr-3.0.1.jar"/>\r
         <pathelement location="lib/antlr-runtime-3.0.1.jar"/>\r
         <pathelement location="lib/stringtemplate-3.1b1.jar"/>\r
     </path>\r
+    <path id="project.class.path.3.1">\r
+        <pathelement location="lib/antlr-2.7.7.jar"/>\r
+        <pathelement location="lib/antlr-3.1b1.jar"/>\r
+        <pathelement location="lib/antlr-runtime-3.1b1.jar"/>\r
+        <pathelement location="lib/stringtemplate-3.1.jar"/>\r
+        <pathelement location="lib/gunit-1.0.2.jar"/>\r
+    </path>\r
+    <property name="classpath" value="project.class.path.3.1"/>\r
 \r
     <!-- antlr options -->\r
     <property name="profile" value="false" />\r
@@ -59,7 +67,7 @@
                 report="${report}"\r
                 depend="${depend}"\r
                 profile="${profile}">\r
-                <classpath refid="project.class.path"/>\r
+                <classpath refid="${classpath}"/>\r
             </antlr:antlr3>\r
         </sequential>\r
     </macrodef>\r
     </target>\r
 \r
     <target name="CharjEmitter" depends="Charj">\r
-        <antlr3 grammar.name="CharjEmitter.g" \r
+        <antlr3 grammar.name="CharjCCEmitter.g" \r
+            grammar.path="${buildsrc}/charj/translator"/>\r
+        <antlr3 grammar.name="CharjCIEmitter.g" \r
             grammar.path="${buildsrc}/charj/translator"/>\r
     </target>\r
-    \r
+\r
     <target name="compile" depends="Charj, CharjEmitter" description="compile">\r
         <javac debug="true" srcdir="${buildsrc}" destdir="${classes}"\r
                target="1.5" listfiles="Yes" deprecation="Yes">\r
-            <classpath refid="project.class.path"/>\r
+               <classpath refid="${classpath}"/>\r
         </javac>\r
     </target>\r
 \r
index 0d9279cf789ba475e01a5d2ecf395d9de5aca936..efba5ccb68f28658eb3a450942c2bf12af47d9ee 100644 (file)
@@ -7,6 +7,8 @@ public class Main
 {
     public static void main(String[] args) throws Exception
     {
-        System.out.println(Translator.translate(new FileInputStream(args[0])));
+        for (String filename : args) { 
+            System.out.println(Translator.translate(filename));
+        }
     }
 }
diff --git a/src/langs/charj/src/charj/translator/CharjCC.stg b/src/langs/charj/src/charj/translator/CharjCC.stg
new file mode 100644 (file)
index 0000000..ea7e18d
--- /dev/null
@@ -0,0 +1,12 @@
+group CharjCC;
+
+classExtends(type) ::= ": public CBase_<type>"
+
+
+interfaceExtends(ts) ::=
+<<
+: public CBase_<ts; separator=", public CBase_">
+>>
+
+
+classTopLevelScope(classScopeDeclarations) ::= "!!<classScopeDeclarations>!!"
diff --git a/src/langs/charj/src/charj/translator/CharjCCEmitter.g b/src/langs/charj/src/charj/translator/CharjCCEmitter.g
new file mode 100644 (file)
index 0000000..73502b1
--- /dev/null
@@ -0,0 +1,475 @@
+/**
+ * ANTLR (v3) Tree Parser for the Charj Language
+ */
+
+tree grammar CharjCCEmitter;
+
+options {
+    backtrack = true; 
+    memoize = true;
+    tokenVocab = Charj;
+    ASTLabelType = CommonTree;
+    output = template;
+    rewrite = true;
+}
+
+
+@treeparser::header {
+package charj.translator;
+}
+
+@treeparser::members {
+    
+    boolean mMessageCollectionEnabled = false;
+    private boolean mHasErrors = false;
+    List<String> mMessages;
+
+    /**
+     *  Switches error message collection on or off.
+     *
+     *  The standard destination for parser error messages is <code>System.err</code>.
+     *  However, if <code>true</code> gets passed to this method this default
+     *  behaviour will be switched off and all error messages will be collected
+     *  instead of written to anywhere.
+     *
+     *  The default value is <code>false</code>.
+     *
+     *  @param pNewState  <code>true</code> if error messages should be collected.
+     */
+    public void enableErrorMessageCollection(boolean pNewState) {
+        mMessageCollectionEnabled = pNewState;
+        if (mMessages == null && mMessageCollectionEnabled) {
+            mMessages = new ArrayList<String>();
+        }
+    }
+    
+    /**
+     *  Collects an error message or passes the error message to <code>
+     *  super.emitErrorMessage(...)</code>.
+     *
+     *  The actual behaviour depends on whether collecting error messages
+     *  has been enabled or not.
+     *
+     *  @param pMessage  The error message.
+     */
+     @Override
+    public void emitErrorMessage(String pMessage) {
+        if (mMessageCollectionEnabled) {
+            mMessages.add(pMessage);
+        } else {
+            super.emitErrorMessage(pMessage);
+        }
+    }
+    
+    /**
+     *  Returns collected error messages.
+     *
+     *  @return  A list holding collected error messages or <code>null</code> if
+     *           collecting error messages hasn't been enabled. Of course, this
+     *           list may be empty if no error message has been emited.
+     */
+    public List<String> getMessages() {
+        return mMessages;
+    }
+    
+    /**
+     *  Tells if parsing a Charj source has caused any error messages.
+     *
+     *  @return  <code>true</code> if parsing a Charj source has caused at 
+     *           least one error message.
+     */
+    public boolean hasErrors() {
+        return mHasErrors;
+    }
+}
+
+// Starting point for parsing a Charj file.
+charjSource
+    :   ^(CHARJ_SOURCE packageDeclaration? importDeclaration* (ts+=typeDeclaration)*)
+        -> template(allText={$text}, types={$ts}) <<
+        <allText>
+        >>
+    ;
+
+packageDeclaration
+    :   ^(PACKAGE qualifiedIdentifier)  
+    ;
+    
+importDeclaration
+    :   ^(IMPORT STATIC? qualifiedIdentifier DOTSTAR?)
+    ;
+    
+typeDeclaration
+    :   ^(CLASS modifierList IDENT genericTypeParameterList? classExtendsClause? implementsClause? classTopLevelScope) -> template(t={$text}) "<t>"
+    |   ^(INTERFACE modifierList IDENT genericTypeParameterList? interfaceExtendsClause? interfaceTopLevelScope)
+    |   ^(ENUM modifierList IDENT implementsClause? enumTopLevelScope)
+    ;
+
+
+classExtendsClause
+    :   ^(EXTENDS_CLAUSE t=type) 
+        -> classExtends(type={$t.st})
+    ;   
+
+interfaceExtendsClause 
+    :   ^(EXTENDS_CLAUSE (typeList+=type)+) 
+        -> interfaceExtends(ts={$typeList})
+    ;   
+    
+implementsClause
+    :   ^(IMPLEMENTS_CLAUSE type+)
+    ;
+        
+genericTypeParameterList
+    :   ^(GENERIC_TYPE_PARAM_LIST genericTypeParameter+)
+    ;
+
+genericTypeParameter
+    :   ^(IDENT bound?)
+    ;
+        
+bound
+    :   ^(EXTENDS_BOUND_LIST type+)
+    ;
+
+enumTopLevelScope
+    :   ^(ENUM_TOP_LEVEL_SCOPE enumConstant+ classTopLevelScope?)
+    ;
+    
+enumConstant
+    :   ^(IDENT arguments? classTopLevelScope?)
+    ;
+    
+    
+classTopLevelScope
+    :   ^(CLASS_TOP_LEVEL_SCOPE (csd+=classScopeDeclarations)*) 
+        -> classTopLevelScope(classScopeDeclarations={$csd})
+    ;
+    
+classScopeDeclarations
+    :   ^(CLASS_INSTANCE_INITIALIZER block)
+    |   ^(CLASS_STATIC_INITIALIZER block)
+    |   ^(FUNCTION_METHOD_DECL modifierList genericTypeParameterList? type IDENT formalParameterList arrayDeclaratorList? throwsClause? block?)
+    |   ^(VOID_METHOD_DECL modifierList genericTypeParameterList? IDENT formalParameterList throwsClause? block?)
+    |   ^(VAR_DECLARATION modifierList type variableDeclaratorList)
+    |   ^(CONSTRUCTOR_DECL modifierList genericTypeParameterList? formalParameterList throwsClause? block)
+    |   typeDeclaration
+    ;
+    
+interfaceTopLevelScope
+    :   ^(INTERFACE_TOP_LEVEL_SCOPE interfaceScopeDeclarations*)
+    ;
+    
+interfaceScopeDeclarations
+    :   ^(FUNCTION_METHOD_DECL modifierList genericTypeParameterList? type IDENT formalParameterList arrayDeclaratorList? throwsClause?)
+    |   ^(VOID_METHOD_DECL modifierList genericTypeParameterList? IDENT formalParameterList throwsClause?)
+        // Interface constant declarations have been switched to variable
+        // declarations by Charj.g; the parser has already checked that
+        // there's an obligatory initializer.
+    |   ^(VAR_DECLARATION modifierList type variableDeclaratorList)
+    |   typeDeclaration
+    ;
+
+variableDeclaratorList
+    :   ^(VAR_DECLARATOR_LIST variableDeclarator+)
+    ;
+
+variableDeclarator
+    :   ^(VAR_DECLARATOR variableDeclaratorId variableInitializer?)
+    ;
+    
+variableDeclaratorId
+    :   ^(IDENT arrayDeclaratorList?)
+    ;
+
+variableInitializer
+    :   arrayInitializer
+    |   expression
+    ;
+
+arrayDeclarator
+    :   LBRACK RBRACK
+    ;
+
+arrayDeclaratorList
+    :   ^(ARRAY_DECLARATOR_LIST ARRAY_DECLARATOR*)  
+    ;
+    
+arrayInitializer
+    :   ^(ARRAY_INITIALIZER variableInitializer*)
+    ;
+
+throwsClause
+    :   ^(THROWS_CLAUSE qualifiedIdentifier+)
+    ;
+
+modifierList
+    :   ^(MODIFIER_LIST modifier*)
+    ;
+
+modifier
+    :   PUBLIC
+    |   PROTECTED
+    |   PRIVATE
+    |   STATIC
+    |   ABSTRACT
+    |   NATIVE
+    |   SYNCHRONIZED
+    |   TRANSIENT
+    |   VOLATILE
+    |   localModifier
+    ;
+
+localModifierList
+    :   ^(LOCAL_MODIFIER_LIST localModifier*)
+    ;
+
+localModifier
+    :   FINAL
+    ;
+
+type
+    :   ^(TYPE (primitiveType | qualifiedTypeIdent) arrayDeclaratorList?) 
+        -> template(t={$text}) "<t>"
+    ;
+
+qualifiedTypeIdent
+    :   ^(QUALIFIED_TYPE_IDENT typeIdent+) 
+    ;
+
+typeIdent
+    :   ^(IDENT genericTypeArgumentList?)
+    ;
+
+primitiveType
+    :   BOOLEAN
+    |   CHAR
+    |   BYTE
+    |   SHORT
+    |   INT
+    |   LONG
+    |   FLOAT
+    |   DOUBLE
+    ;
+
+genericTypeArgumentList
+    :   ^(GENERIC_TYPE_ARG_LIST genericTypeArgument+)
+    ;
+    
+genericTypeArgument
+    :   type
+    |   ^(QUESTION genericWildcardBoundType?)
+    ;
+
+genericWildcardBoundType                                                                                                                      
+    :   ^(EXTENDS type)
+    |   ^(SUPER type)
+    ;
+
+formalParameterList
+    :   ^(FORMAL_PARAM_LIST formalParameterStandardDecl* formalParameterVarargDecl?) 
+    ;
+    
+formalParameterStandardDecl
+    :   ^(FORMAL_PARAM_STD_DECL localModifierList type variableDeclaratorId)
+    ;
+    
+formalParameterVarargDecl
+    :   ^(FORMAL_PARAM_VARARG_DECL localModifierList type variableDeclaratorId)
+    ;
+    
+qualifiedIdentifier
+    :   IDENT
+    |   ^(DOT qualifiedIdentifier IDENT)
+    ;
+    
+block
+    :   ^(BLOCK_SCOPE blockStatement*)
+    ;
+    
+blockStatement
+    :   localVariableDeclaration
+    |   typeDeclaration
+    |   statement
+    ;
+    
+localVariableDeclaration
+    :   ^(VAR_DECLARATION localModifierList type variableDeclaratorList)
+    ;
+    
+        
+statement
+    :   block
+    |   ^(ASSERT expression expression?)
+    |   ^(IF parenthesizedExpression statement statement?)
+    |   ^(FOR forInit forCondition forUpdater statement)
+    |   ^(FOR_EACH localModifierList type IDENT expression statement) 
+    |   ^(WHILE parenthesizedExpression statement)
+    |   ^(DO statement parenthesizedExpression)
+    |   ^(TRY block catches? block?)  // The second optional block is the optional finally block.
+    |   ^(SWITCH parenthesizedExpression switchBlockLabels)
+    |   ^(SYNCHRONIZED parenthesizedExpression block)
+    |   ^(RETURN expression?)
+    |   ^(THROW expression)
+    |   ^(BREAK IDENT?)
+    |   ^(CONTINUE IDENT?)
+    |   ^(LABELED_STATEMENT IDENT statement)
+    |   expression
+    |   SEMI // Empty statement.
+    ;
+        
+catches
+    :   ^(CATCH_CLAUSE_LIST catchClause+)
+    ;
+    
+catchClause
+    :   ^(CATCH formalParameterStandardDecl block)
+    ;
+
+switchBlockLabels
+    :   ^(SWITCH_BLOCK_LABEL_LIST switchCaseLabel* switchDefaultLabel? switchCaseLabel*)
+    ;
+        
+switchCaseLabel
+    :   ^(CASE expression blockStatement*)
+    ;
+    
+switchDefaultLabel
+    :   ^(DEFAULT blockStatement*)
+    ;
+    
+forInit
+    :   ^(FOR_INIT (localVariableDeclaration | expression*)?)
+    ;
+    
+forCondition
+    :   ^(FOR_CONDITION expression?)
+    ;
+    
+forUpdater
+    :   ^(FOR_UPDATE expression*)
+    ;
+    
+// EXPRESSIONS
+
+parenthesizedExpression
+    :   ^(PARENTESIZED_EXPR expression)
+    ;
+    
+expression
+    :   ^(EXPR expr)
+    ;
+
+expr
+    :   ^(ASSIGN expr expr)
+    |   ^(PLUS_ASSIGN expr expr)
+    |   ^(MINUS_ASSIGN expr expr)
+    |   ^(STAR_ASSIGN expr expr)
+    |   ^(DIV_ASSIGN expr expr)
+    |   ^(AND_ASSIGN expr expr)
+    |   ^(OR_ASSIGN expr expr)
+    |   ^(XOR_ASSIGN expr expr)
+    |   ^(MOD_ASSIGN expr expr)
+    |   ^(BIT_SHIFT_RIGHT_ASSIGN expr expr)
+    |   ^(SHIFT_RIGHT_ASSIGN expr expr)
+    |   ^(SHIFT_LEFT_ASSIGN expr expr)
+    |   ^(QUESTION expr expr expr)
+    |   ^(LOGICAL_OR expr expr)
+    |   ^(LOGICAL_AND expr expr)
+    |   ^(OR expr expr)
+    |   ^(XOR expr expr)
+    |   ^(AND expr expr)
+    |   ^(EQUAL expr expr)
+    |   ^(NOT_EQUAL expr expr)
+    |   ^(INSTANCEOF expr type)
+    |   ^(LESS_OR_EQUAL expr expr)
+    |   ^(GREATER_OR_EQUAL expr expr)
+    |   ^(BIT_SHIFT_RIGHT expr expr)
+    |   ^(SHIFT_RIGHT expr expr)
+    |   ^(GREATER_THAN expr expr)
+    |   ^(SHIFT_LEFT expr expr)
+    |   ^(LESS_THAN expr expr)
+    |   ^(PLUS expr expr)
+    |   ^(MINUS expr expr)
+    |   ^(STAR expr expr)
+    |   ^(DIV expr expr)
+    |   ^(MOD expr expr)
+    |   ^(UNARY_PLUS expr)
+    |   ^(UNARY_MINUS expr)
+    |   ^(PRE_INC expr)
+    |   ^(PRE_DEC expr)
+    |   ^(POST_INC expr)
+    |   ^(POST_DEC expr)
+    |   ^(NOT expr)
+    |   ^(LOGICAL_NOT expr)
+    |   ^(CAST_EXPR type expr)
+    |   primaryExpression
+    ;
+    
+primaryExpression
+    :   ^(  DOT
+            (   primaryExpression
+                (   IDENT
+                |   THIS
+                |   SUPER
+                |   innerNewExpression
+                |   CLASS
+                )
+            |   primitiveType CLASS
+            |   VOID CLASS
+            )
+        )
+    |   parenthesizedExpression
+    |   IDENT
+    |   ^(METHOD_CALL primaryExpression genericTypeArgumentList? arguments)
+    |   explicitConstructorCall
+    |   ^(ARRAY_ELEMENT_ACCESS primaryExpression expression)
+    |   literal
+    |   newExpression
+    |   THIS
+    |   arrayTypeDeclarator
+    |   SUPER
+    ;
+    
+explicitConstructorCall
+    :   ^(THIS_CONSTRUCTOR_CALL genericTypeArgumentList? arguments)
+    |   ^(SUPER_CONSTRUCTOR_CALL primaryExpression? genericTypeArgumentList? arguments)
+    ;
+
+arrayTypeDeclarator
+    :   ^(ARRAY_DECLARATOR (arrayTypeDeclarator | qualifiedIdentifier | primitiveType))
+    ;
+
+newExpression
+    :   ^(  STATIC_ARRAY_CREATOR
+            (   primitiveType newArrayConstruction
+            |   genericTypeArgumentList? qualifiedTypeIdent newArrayConstruction
+            )
+        )
+    |   ^(CLASS_CONSTRUCTOR_CALL genericTypeArgumentList? qualifiedTypeIdent arguments classTopLevelScope?)
+    ;
+
+innerNewExpression // something like 'InnerType innerType = outer.new InnerType();'
+    :   ^(CLASS_CONSTRUCTOR_CALL genericTypeArgumentList? IDENT arguments classTopLevelScope?)
+    ;
+    
+newArrayConstruction
+    :   arrayDeclaratorList arrayInitializer
+    |   expression+ arrayDeclaratorList?
+    ;
+
+arguments
+    :   ^(ARGUMENT_LIST expression*)
+    ;
+
+literal 
+    :   HEX_LITERAL
+    |   OCTAL_LITERAL
+    |   DECIMAL_LITERAL
+    |   FLOATING_POINT_LITERAL
+    |   CHARACTER_LITERAL
+    |   STRING_LITERAL
+    |   TRUE
+    |   FALSE
+    |   NULL
+    ;
diff --git a/src/langs/charj/src/charj/translator/CharjCI.stg b/src/langs/charj/src/charj/translator/CharjCI.stg
new file mode 100644 (file)
index 0000000..b38d81a
--- /dev/null
@@ -0,0 +1,10 @@
+group CharjCI;
+
+classExtends(type) ::= ": <type>"
+
+
+interfaceExtends(ts) ::=
+<<
+: <ts; separator=", ">
+>>
+
diff --git a/src/langs/charj/src/charj/translator/CharjCIEmitter.g b/src/langs/charj/src/charj/translator/CharjCIEmitter.g
new file mode 100644 (file)
index 0000000..fddbf4c
--- /dev/null
@@ -0,0 +1,471 @@
+/**
+ * ANTLR (v3) Tree Parser for the Charj Language
+ */
+
+tree grammar CharjCIEmitter;
+
+options {
+    backtrack = true; 
+    memoize = true;
+    tokenVocab = Charj;
+    ASTLabelType = CommonTree;
+    output = template;
+    rewrite = true;
+}
+
+
+@treeparser::header {
+package charj.translator;
+}
+
+@treeparser::members {
+    
+    boolean mMessageCollectionEnabled = false;
+    private boolean mHasErrors = false;
+    List<String> mMessages;
+
+    /**
+     *  Switches error message collection on or off.
+     *
+     *  The standard destination for parser error messages is <code>System.err</code>.
+     *  However, if <code>true</code> gets passed to this method this default
+     *  behaviour will be switched off and all error messages will be collected
+     *  instead of written to anywhere.
+     *
+     *  The default value is <code>false</code>.
+     *
+     *  @param pNewState  <code>true</code> if error messages should be collected.
+     */
+    public void enableErrorMessageCollection(boolean pNewState) {
+        mMessageCollectionEnabled = pNewState;
+        if (mMessages == null && mMessageCollectionEnabled) {
+            mMessages = new ArrayList<String>();
+        }
+    }
+    
+    /**
+     *  Collects an error message or passes the error message to <code>
+     *  super.emitErrorMessage(...)</code>.
+     *
+     *  The actual behaviour depends on whether collecting error messages
+     *  has been enabled or not.
+     *
+     *  @param pMessage  The error message.
+     */
+     @Override
+    public void emitErrorMessage(String pMessage) {
+        if (mMessageCollectionEnabled) {
+            mMessages.add(pMessage);
+        } else {
+            super.emitErrorMessage(pMessage);
+        }
+    }
+    
+    /**
+     *  Returns collected error messages.
+     *
+     *  @return  A list holding collected error messages or <code>null</code> if
+     *           collecting error messages hasn't been enabled. Of course, this
+     *           list may be empty if no error message has been emited.
+     */
+    public List<String> getMessages() {
+        return mMessages;
+    }
+    
+    /**
+     *  Tells if parsing a Charj source has caused any error messages.
+     *
+     *  @return  <code>true</code> if parsing a Charj source has caused at 
+     *           least one error message.
+     */
+    public boolean hasErrors() {
+        return mHasErrors;
+    }
+}
+
+// Starting point for parsing a Charj file.
+charjSource
+    :   ^(CHARJ_SOURCE packageDeclaration? importDeclaration* (ts+=typeDeclaration)*)
+        -> template(allText={$text}, types={$ts}) <<
+        <allText>
+        >>
+    ;
+
+packageDeclaration
+    :   ^(PACKAGE qualifiedIdentifier)  
+    ;
+    
+importDeclaration
+    :   ^(IMPORT STATIC? qualifiedIdentifier DOTSTAR?)
+    ;
+    
+typeDeclaration
+    :   ^(CLASS modifierList IDENT genericTypeParameterList? classExtendsClause? implementsClause? classTopLevelScope) -> template(t={$text}) "<t>"
+    |   ^(INTERFACE modifierList IDENT genericTypeParameterList? interfaceExtendsClause? interfaceTopLevelScope)
+    |   ^(ENUM modifierList IDENT implementsClause? enumTopLevelScope)
+    ;
+
+
+classExtendsClause
+    :   ^(EXTENDS_CLAUSE t=type) -> classExtends(type={$t.st})
+    ;   
+
+interfaceExtendsClause 
+    :   ^(EXTENDS_CLAUSE (typeList+=type)+) -> interfaceExtends(ts={$typeList})
+    ;   
+    
+implementsClause
+    :   ^(IMPLEMENTS_CLAUSE type+)
+    ;
+        
+genericTypeParameterList
+    :   ^(GENERIC_TYPE_PARAM_LIST genericTypeParameter+)
+    ;
+
+genericTypeParameter
+    :   ^(IDENT bound?)
+    ;
+        
+bound
+    :   ^(EXTENDS_BOUND_LIST type+)
+    ;
+
+enumTopLevelScope
+    :   ^(ENUM_TOP_LEVEL_SCOPE enumConstant+ classTopLevelScope?)
+    ;
+    
+enumConstant
+    :   ^(IDENT arguments? classTopLevelScope?)
+    ;
+    
+    
+classTopLevelScope
+    :   ^(CLASS_TOP_LEVEL_SCOPE classScopeDeclarations*)
+    ;
+    
+classScopeDeclarations
+    :   ^(CLASS_INSTANCE_INITIALIZER block)
+    |   ^(CLASS_STATIC_INITIALIZER block)
+    |   ^(FUNCTION_METHOD_DECL modifierList genericTypeParameterList? type IDENT formalParameterList arrayDeclaratorList? throwsClause? block?)
+    |   ^(VOID_METHOD_DECL modifierList genericTypeParameterList? IDENT formalParameterList throwsClause? block?)
+    |   ^(VAR_DECLARATION modifierList type variableDeclaratorList)
+    |   ^(CONSTRUCTOR_DECL modifierList genericTypeParameterList? formalParameterList throwsClause? block)
+    |   typeDeclaration
+    ;
+    
+interfaceTopLevelScope
+    :   ^(INTERFACE_TOP_LEVEL_SCOPE interfaceScopeDeclarations*)
+    ;
+    
+interfaceScopeDeclarations
+    :   ^(FUNCTION_METHOD_DECL modifierList genericTypeParameterList? type IDENT formalParameterList arrayDeclaratorList? throwsClause?)
+    |   ^(VOID_METHOD_DECL modifierList genericTypeParameterList? IDENT formalParameterList throwsClause?)
+        // Interface constant declarations have been switched to variable
+        // declarations by Charj.g; the parser has already checked that
+        // there's an obligatory initializer.
+    |   ^(VAR_DECLARATION modifierList type variableDeclaratorList)
+    |   typeDeclaration
+    ;
+
+variableDeclaratorList
+    :   ^(VAR_DECLARATOR_LIST variableDeclarator+)
+    ;
+
+variableDeclarator
+    :   ^(VAR_DECLARATOR variableDeclaratorId variableInitializer?)
+    ;
+    
+variableDeclaratorId
+    :   ^(IDENT arrayDeclaratorList?)
+    ;
+
+variableInitializer
+    :   arrayInitializer
+    |   expression
+    ;
+
+arrayDeclarator
+    :   LBRACK RBRACK
+    ;
+
+arrayDeclaratorList
+    :   ^(ARRAY_DECLARATOR_LIST ARRAY_DECLARATOR*)  
+    ;
+    
+arrayInitializer
+    :   ^(ARRAY_INITIALIZER variableInitializer*)
+    ;
+
+throwsClause
+    :   ^(THROWS_CLAUSE qualifiedIdentifier+)
+    ;
+
+modifierList
+    :   ^(MODIFIER_LIST modifier*)
+    ;
+
+modifier
+    :   PUBLIC
+    |   PROTECTED
+    |   PRIVATE
+    |   STATIC
+    |   ABSTRACT
+    |   NATIVE
+    |   SYNCHRONIZED
+    |   TRANSIENT
+    |   VOLATILE
+    |   localModifier
+    ;
+
+localModifierList
+    :   ^(LOCAL_MODIFIER_LIST localModifier*)
+    ;
+
+localModifier
+    :   FINAL
+    ;
+
+type
+    :   ^(TYPE (primitiveType | qualifiedTypeIdent) arrayDeclaratorList?) -> template(t={$text}) "<t>"
+    ;
+
+qualifiedTypeIdent
+    :   ^(QUALIFIED_TYPE_IDENT typeIdent+) 
+    ;
+
+typeIdent
+    :   ^(IDENT genericTypeArgumentList?)
+    ;
+
+primitiveType
+    :   BOOLEAN
+    |   CHAR
+    |   BYTE
+    |   SHORT
+    |   INT
+    |   LONG
+    |   FLOAT
+    |   DOUBLE
+    ;
+
+genericTypeArgumentList
+    :   ^(GENERIC_TYPE_ARG_LIST genericTypeArgument+)
+    ;
+    
+genericTypeArgument
+    :   type
+    |   ^(QUESTION genericWildcardBoundType?)
+    ;
+
+genericWildcardBoundType                                                                                                                      
+    :   ^(EXTENDS type)
+    |   ^(SUPER type)
+    ;
+
+formalParameterList
+    :   ^(FORMAL_PARAM_LIST formalParameterStandardDecl* formalParameterVarargDecl?) 
+    ;
+    
+formalParameterStandardDecl
+    :   ^(FORMAL_PARAM_STD_DECL localModifierList type variableDeclaratorId)
+    ;
+    
+formalParameterVarargDecl
+    :   ^(FORMAL_PARAM_VARARG_DECL localModifierList type variableDeclaratorId)
+    ;
+    
+qualifiedIdentifier
+    :   IDENT
+    |   ^(DOT qualifiedIdentifier IDENT)
+    ;
+    
+block
+    :   ^(BLOCK_SCOPE blockStatement*)
+    ;
+    
+blockStatement
+    :   localVariableDeclaration
+    |   typeDeclaration
+    |   statement
+    ;
+    
+localVariableDeclaration
+    :   ^(VAR_DECLARATION localModifierList type variableDeclaratorList)
+    ;
+    
+        
+statement
+    :   block
+    |   ^(ASSERT expression expression?)
+    |   ^(IF parenthesizedExpression statement statement?)
+    |   ^(FOR forInit forCondition forUpdater statement)
+    |   ^(FOR_EACH localModifierList type IDENT expression statement) 
+    |   ^(WHILE parenthesizedExpression statement)
+    |   ^(DO statement parenthesizedExpression)
+    |   ^(TRY block catches? block?)  // The second optional block is the optional finally block.
+    |   ^(SWITCH parenthesizedExpression switchBlockLabels)
+    |   ^(SYNCHRONIZED parenthesizedExpression block)
+    |   ^(RETURN expression?)
+    |   ^(THROW expression)
+    |   ^(BREAK IDENT?)
+    |   ^(CONTINUE IDENT?)
+    |   ^(LABELED_STATEMENT IDENT statement)
+    |   expression
+    |   SEMI // Empty statement.
+    ;
+        
+catches
+    :   ^(CATCH_CLAUSE_LIST catchClause+)
+    ;
+    
+catchClause
+    :   ^(CATCH formalParameterStandardDecl block)
+    ;
+
+switchBlockLabels
+    :   ^(SWITCH_BLOCK_LABEL_LIST switchCaseLabel* switchDefaultLabel? switchCaseLabel*)
+    ;
+        
+switchCaseLabel
+    :   ^(CASE expression blockStatement*)
+    ;
+    
+switchDefaultLabel
+    :   ^(DEFAULT blockStatement*)
+    ;
+    
+forInit
+    :   ^(FOR_INIT (localVariableDeclaration | expression*)?)
+    ;
+    
+forCondition
+    :   ^(FOR_CONDITION expression?)
+    ;
+    
+forUpdater
+    :   ^(FOR_UPDATE expression*)
+    ;
+    
+// EXPRESSIONS
+
+parenthesizedExpression
+    :   ^(PARENTESIZED_EXPR expression)
+    ;
+    
+expression
+    :   ^(EXPR expr)
+    ;
+
+expr
+    :   ^(ASSIGN expr expr)
+    |   ^(PLUS_ASSIGN expr expr)
+    |   ^(MINUS_ASSIGN expr expr)
+    |   ^(STAR_ASSIGN expr expr)
+    |   ^(DIV_ASSIGN expr expr)
+    |   ^(AND_ASSIGN expr expr)
+    |   ^(OR_ASSIGN expr expr)
+    |   ^(XOR_ASSIGN expr expr)
+    |   ^(MOD_ASSIGN expr expr)
+    |   ^(BIT_SHIFT_RIGHT_ASSIGN expr expr)
+    |   ^(SHIFT_RIGHT_ASSIGN expr expr)
+    |   ^(SHIFT_LEFT_ASSIGN expr expr)
+    |   ^(QUESTION expr expr expr)
+    |   ^(LOGICAL_OR expr expr)
+    |   ^(LOGICAL_AND expr expr)
+    |   ^(OR expr expr)
+    |   ^(XOR expr expr)
+    |   ^(AND expr expr)
+    |   ^(EQUAL expr expr)
+    |   ^(NOT_EQUAL expr expr)
+    |   ^(INSTANCEOF expr type)
+    |   ^(LESS_OR_EQUAL expr expr)
+    |   ^(GREATER_OR_EQUAL expr expr)
+    |   ^(BIT_SHIFT_RIGHT expr expr)
+    |   ^(SHIFT_RIGHT expr expr)
+    |   ^(GREATER_THAN expr expr)
+    |   ^(SHIFT_LEFT expr expr)
+    |   ^(LESS_THAN expr expr)
+    |   ^(PLUS expr expr)
+    |   ^(MINUS expr expr)
+    |   ^(STAR expr expr)
+    |   ^(DIV expr expr)
+    |   ^(MOD expr expr)
+    |   ^(UNARY_PLUS expr)
+    |   ^(UNARY_MINUS expr)
+    |   ^(PRE_INC expr)
+    |   ^(PRE_DEC expr)
+    |   ^(POST_INC expr)
+    |   ^(POST_DEC expr)
+    |   ^(NOT expr)
+    |   ^(LOGICAL_NOT expr)
+    |   ^(CAST_EXPR type expr)
+    |   primaryExpression
+    ;
+    
+primaryExpression
+    :   ^(  DOT
+            (   primaryExpression
+                (   IDENT
+                |   THIS
+                |   SUPER
+                |   innerNewExpression
+                |   CLASS
+                )
+            |   primitiveType CLASS
+            |   VOID CLASS
+            )
+        )
+    |   parenthesizedExpression
+    |   IDENT
+    |   ^(METHOD_CALL primaryExpression genericTypeArgumentList? arguments)
+    |   explicitConstructorCall
+    |   ^(ARRAY_ELEMENT_ACCESS primaryExpression expression)
+    |   literal
+    |   newExpression
+    |   THIS
+    |   arrayTypeDeclarator
+    |   SUPER
+    ;
+    
+explicitConstructorCall
+    :   ^(THIS_CONSTRUCTOR_CALL genericTypeArgumentList? arguments)
+    |   ^(SUPER_CONSTRUCTOR_CALL primaryExpression? genericTypeArgumentList? arguments)
+    ;
+
+arrayTypeDeclarator
+    :   ^(ARRAY_DECLARATOR (arrayTypeDeclarator | qualifiedIdentifier | primitiveType))
+    ;
+
+newExpression
+    :   ^(  STATIC_ARRAY_CREATOR
+            (   primitiveType newArrayConstruction
+            |   genericTypeArgumentList? qualifiedTypeIdent newArrayConstruction
+            )
+        )
+    |   ^(CLASS_CONSTRUCTOR_CALL genericTypeArgumentList? qualifiedTypeIdent arguments classTopLevelScope?)
+    ;
+
+innerNewExpression // something like 'InnerType innerType = outer.new InnerType();'
+    :   ^(CLASS_CONSTRUCTOR_CALL genericTypeArgumentList? IDENT arguments classTopLevelScope?)
+    ;
+    
+newArrayConstruction
+    :   arrayDeclaratorList arrayInitializer
+    |   expression+ arrayDeclaratorList?
+    ;
+
+arguments
+    :   ^(ARGUMENT_LIST expression*)
+    ;
+
+literal 
+    :   HEX_LITERAL
+    |   OCTAL_LITERAL
+    |   DECIMAL_LITERAL
+    |   FLOATING_POINT_LITERAL
+    |   CHARACTER_LITERAL
+    |   STRING_LITERAL
+    |   TRUE
+    |   FALSE
+    |   NULL
+    ;
index 6f2d70b46f8a5c07b62887d4bafc559907325dfb..b354217b89aad4f98724d338ae5216ebf7987636 100644 (file)
@@ -87,7 +87,7 @@ package charj.translator;
 charjSource
     :   ^(CHARJ_SOURCE packageDeclaration? importDeclaration* (ts+=typeDeclaration)*)
         -> template(allText={$text}, types={$ts}) <<
-        ::: <allText> ::: <types> :::
+        <allText>
         >>
     ;
 
index bea22bf95e249fa915d551d0d9b6bab04729964c..62685f57dacde1ad5c7b4da2b6f86f751718c0f5 100644 (file)
@@ -8,45 +8,86 @@ import org.antlr.runtime.tree.*;
 import org.antlr.stringtemplate.*;
 import java.io.*;
 
+enum OutputMode {
+    cc, ci
+}
+
 public class Translator {
 
-    public static final String templateFile = "src/charj/translator/Charj.stg";
+    public static final String ccTemplateFile = "src/charj/translator/CharjCC.stg";
+    public static final String ciTemplateFile = "src/charj/translator/CharjCI.stg";
     public static boolean debug = true;
     public static boolean errorCondition = false;
 
-    public static String translate(InputStream io) throws Exception {
-        StringTemplateGroup templates = null;
-        try {
-            ClassLoader loader = Thread.currentThread().getContextClassLoader();
-            InputStream istream = loader.getResourceAsStream(templateFile);
-            BufferedReader reader = new BufferedReader(new InputStreamReader(istream));
-            templates = new StringTemplateGroup(reader);
-            reader.close();
-        } catch(IOException ex) {
-            error("Failed to load template file", ex); 
-        }
+    public static String translate(String filename) throws Exception {
 
-        // Parse input, creating an AST
-        ANTLRInputStream input = new ANTLRInputStream(io);
+        ANTLRFileStream input = new ANTLRFileStream(filename);
+            
         CharjLexer lexer = new CharjLexer(input);
+        String output = translationPass(lexer, OutputMode.cc);
+        input.seek(0);
+        output += translationPass(lexer, OutputMode.ci);
         
+        return output;
+    }
+
+    public static String translationPass(CharjLexer lexer, OutputMode m) throws
+        RecognitionException, IOException, InterruptedException
+    {
         // Use lexer tokens to feed tree parser. Note that the parser is a
         // rewriter, so a TokenRewriteStream is needed
         TokenRewriteStream tokens = new TokenRewriteStream(lexer);
         CharjParser parser = new CharjParser(tokens);
         CharjParser.charjSource_return r = parser.charjSource();
 
-        // Walk tree, modifying input buffer
+        // Create node stream for emitters
         CommonTree t = (CommonTree)r.getTree();
         CommonTreeNodeStream nodes = new CommonTreeNodeStream(t);
         nodes.setTokenStream(tokens);
-        CharjEmitter emitter = new CharjEmitter(nodes);
+
+        String output = null;
+        if (m == OutputMode.cc) {
+            output = "\nCC File\n-----------------------\n" + generateCC(nodes);
+        } else if (OutputMode.ci == m) {
+            output = "\nCI File\n-----------------------\n" + generateCI(nodes);
+        }
+        return output;
+    }
+
+    public static String generateCC(CommonTreeNodeStream nodes) throws
+        RecognitionException, IOException, InterruptedException
+    {
+        CharjCCEmitter emitter = new CharjCCEmitter(nodes);
+        StringTemplateGroup templates = getTemplates(ccTemplateFile);
         emitter.setTemplateLib(templates);
-        emitter.charjSource();
+        StringTemplate st = (StringTemplate)emitter.charjSource().getTemplate();
+        return st.toString();
+    }
 
-        return tokens.toString();
+    public static String generateCI(CommonTreeNodeStream nodes) throws
+        RecognitionException, IOException, InterruptedException
+    {
+        CharjCIEmitter emitter = new CharjCIEmitter(nodes);
+        StringTemplateGroup templates = getTemplates(ciTemplateFile);
+        emitter.setTemplateLib(templates);
+        StringTemplate st = (StringTemplate)emitter.charjSource().getTemplate();
+        return st.toString();
     }
 
+    public static StringTemplateGroup getTemplates(String templateFile)
+    {
+        StringTemplateGroup templates = null;
+        try {
+            ClassLoader loader = Thread.currentThread().getContextClassLoader();
+            InputStream istream = loader.getResourceAsStream(templateFile);
+            BufferedReader reader = new BufferedReader(new InputStreamReader(istream));
+            templates = new StringTemplateGroup(reader);
+            reader.close();
+        } catch(IOException ex) {
+            error("Failed to load template file", ex); 
+        }
+        return templates;
+    }
     
     public static void error(String sourceName, String msg, CommonTree node) 
     {