Class JavaCodeGenerator

    • Constructor Detail

      • JavaCodeGenerator

        public JavaCodeGenerator​(NamedObj container,
                                 java.lang.String name)
                          throws IllegalActionException,
                                 NameDuplicationException
        Create a new instance of the Java code generator.
        Parameters:
        container - The container.
        name - The name of the Java code generator.
        Throws:
        IllegalActionException - If the super class throws the exception or error occurs when setting the file path.
        NameDuplicationException - If the super class throws the exception or an error occurs when setting the file path.
    • Method Detail

      • codeGenType2

        public static java.lang.String codeGenType2​(Type type)
        Get the corresponding type in code generation from the given Ptolemy type.
        Parameters:
        type - The given Ptolemy type.
        Returns:
        The code generation type in primitive Java types.
      • codeGenTypeValue

        public static java.lang.Short codeGenTypeValue​(java.lang.String type)
                                                throws IllegalActionException
        Return the index of the type in the typesArray in the generated code.
        Parameters:
        type - The given codegen type.
        Returns:
        The index of the type in the typesArray
        Throws:
        IllegalActionException - If the type is unsupported.
      • codeGenTypeToPtType

        public static Type codeGenTypeToPtType​(int codeGenType)
                                        throws IllegalActionException
        Return the type that corresponds with an index in the typesArray in in the generated type.
        Parameters:
        codeGenType - The index of the codegen type.
        Returns:
        The Ptolemy type that corresponds with the index.
        Throws:
        IllegalActionException - If the type is unsupported.
        See Also:
        ptTypeToCodegenType(Type)
      • ptTypeToCodegenType

        public static int ptTypeToCodegenType​(Type type)
                                       throws IllegalActionException
        Return the index of the type in the typesArray in the generated code.
        Parameters:
        type - The given Ptolemy type.
        Returns:
        The index of the type in the typesArray
        Throws:
        IllegalActionException - If the type is unsupported.
        See Also:
        codeGenTypeToPtType(int)
      • generateConstantDefinition

        public java.lang.String generateConstantDefinition​(java.lang.String constant,
                                                           java.lang.String type,
                                                           java.lang.String value)
        Generate code that defines a constant. In Java, generate a static final.
        Overrides:
        generateConstantDefinition in class ProgramCodeGenerator
        Parameters:
        constant - The name of the constant to be defined
        type - A string representing the type. In C, this parameter is ignored.
        value - The value of the constant.
        Returns:
        A static final that defines the constant.
      • generateFireFunctionCompositeEnd

        public java.lang.String generateFireFunctionCompositeEnd()
        Generate the closing code for a group of fire functions common to a Composite Actor. This method is called when the firing code of each actor is not inlined.
        Overrides:
        generateFireFunctionCompositeEnd in class ProgramCodeGenerator
        Returns:
        a curly bracket and _eol.
      • generateFireFunctionCompositeStart

        public java.lang.String generateFireFunctionCompositeStart​(java.lang.String className)
        Generate the initial code for a group of fire functions common to a Composite Actor. This method is called when the firing code of each actor is not inlined.
        Overrides:
        generateFireFunctionCompositeStart in class ProgramCodeGenerator
        Parameters:
        className - The name of the class to include in the initial code.
        Returns:
        A string that defines an inner class.
      • generateFireFunctionMethodInvocation

        public java.lang.String generateFireFunctionMethodInvocation​(NamedObj namedObj)
                                                              throws IllegalActionException
        Generate the fire function method invocation. This method is called when the firing code of each actor is not inlined.

        So as to reduce the size of classes to be compiled, this code generator generates the fire function methods for the top two levels of composites in separate inner classes. This method returns a String that contains variable that refers to an instance of the inner class followed by the name of the method to be invoked.

        Overrides:
        generateFireFunctionMethodInvocation in class ProgramCodeGenerator
        Parameters:
        namedObj - The named object for which the name is generated.
        Returns:
        The name of the fire function method to be invoked.
        Throws:
        IllegalActionException - If thrown while generating fire code.
      • generateFireFunctionMethodName

        public java.lang.String generateFireFunctionMethodName​(NamedObj namedObj)
                                                        throws IllegalActionException
        Generate the fire function method name. This method is called when the firing code of each actor is not inlined.

        So as to reduce the size of classes to be compiled, this code generator generates the fire function methods for the top two levels of composites in separate inner classes. This method returns a String that contains the name of the method to be invoked.

        Overrides:
        generateFireFunctionMethodName in class ProgramCodeGenerator
        Parameters:
        namedObj - The named object for which the name is generated.
        Returns:
        The name of the fire function method.
        Throws:
        IllegalActionException - If thrown while generating fire code.
      • generateFireFunctionVariableAndMethodName

        public java.lang.String[] generateFireFunctionVariableAndMethodName​(NamedObj namedObj)
                                                                     throws IllegalActionException
        Generate the fire function variable name and method name. This method is called when the firing code of each actor is not inlined.

        So as to reduce the size of classes to be compiled, this code generator generates the fire function methods for the top two levels of composites in separate inner classes.

        Overrides:
        generateFireFunctionVariableAndMethodName in class ProgramCodeGenerator
        Parameters:
        namedObj - The named object for which the name is generated.
        Returns:
        An array of two elements. The first element is a String that contains the variable name, the second is the name of the method.
        Throws:
        IllegalActionException - If thrown while generating fire code.
      • generateFireFunctionVariableDeclaration

        public java.lang.String generateFireFunctionVariableDeclaration​(NamedObj namedObj)
                                                                 throws IllegalActionException
        Generate the fire function variable declaration. This method is called when the firing code of each actor is not inlined.

        So as to reduce the size of classes the Java Code Generator, the fire function methods for the top two levels of composites are placed in a separate inner class.

        Overrides:
        generateFireFunctionVariableDeclaration in class ProgramCodeGenerator
        Parameters:
        namedObj - The named object for which the name is generated.
        Returns:
        If the namedObj is in a containment hierarchy that also contains a GenericCodeGenerator, then the declaration is returned. Otherwise, the empty string is returned.
        Throws:
        IllegalActionException - If there are problems accessing the name of the namedObj or generating the variable declaration.
      • generateFunctionTable

        public java.lang.Object generateFunctionTable​(java.lang.String[] types,
                                                      java.lang.String[] functions)
        Generate the function table.
        Parameters:
        types - An array of types.
        functions - An array of functions.
        Returns:
        The code that declares functions.
      • generateLineInfo

        public java.lang.String generateLineInfo​(int lineNumber,
                                                 java.lang.String filename)
        Generate line number information. In this class, lines of the format
          #line lineNumber "filename"
          
        are generated for use by the C preprocessor.
        Overrides:
        generateLineInfo in class ProgramCodeGenerator
        Parameters:
        lineNumber - The line number of the source file or file containing code blocks.
        filename - The name of the source file or file containing code blocks.
        Returns:
        text that is suitable for the C preprocessor.
      • generatePackageStatement

        public java.lang.String generatePackageStatement()
                                                  throws IllegalActionException
        Generate the package statement, if any.
        Overrides:
        generatePackageStatement in class ProgramCodeGenerator
        Returns:
        If the generateInSubdirectory parameter of the grandparent is true, then generate a package statement with the name of the package being the sanitized model name
        Throws:
        IllegalActionException - Thrown if generateInSubdirectory cannot be read.
      • generateTypeConvertCode

        public java.lang.String generateTypeConvertCode()
                                                 throws IllegalActionException
        Generate type conversion code. Determine the proper code put into the source to support dynamic type resolution. First, find out the different types used in the model. Second, find out the different polymorphic functions used. (note: types and functions are independent of each other). Third, append code blocks according to the functions used, and read from files according to the types referenced. Fourth, generate type resolution code, which consists of constants (MAX_NUM_TYPE, MAX_NUM_FUNC), the type map, the function map, function definitions read from the files, and function table.
        Overrides:
        generateTypeConvertCode in class ProgramCodeGenerator
        Returns:
        The type resolution code.
        Throws:
        IllegalActionException - If an error occurs when generating the type resolution code, or if the adapter class for the model director cannot be found, or if an error occurs when the adapter actor generates the type resolution code.
      • generateVariableName

        public java.lang.String generateVariableName​(NamedObj attribute)
        Generate variable name for the given attribute. The reason to append underscore is to avoid conflict with the names of other objects. For example, the paired PortParameter and ParameterPort have the same name.
        Overrides:
        generateVariableName in class ProgramCodeGenerator
        Parameters:
        attribute - The attribute to for which to generate a variable name.
        Returns:
        The generated variable name.
      • getMethodVisibilityString

        public java.lang.String getMethodVisibilityString()
        Return the return signature for run() and execute().
        Overrides:
        getMethodVisibilityString in class GenericCodeGenerator
        Returns:
        The visibility signature.
      • getMethodExceptionString

        public java.lang.String getMethodExceptionString()
        Return the exception signature (for Java).
        Overrides:
        getMethodExceptionString in class GenericCodeGenerator
        Returns:
        The exception signature.
      • markFunctionCalled

        public void markFunctionCalled​(java.lang.String name,
                                       JavaTemplateParser javaTemplateParser)
                                throws IllegalActionException
        Add called functions to the set of overloaded functions for later use. If the function starts with "Array_", add everything after the "Array_" is added to the set of token functions used.
        Parameters:
        name - The name of the function, for example "Double_equals"
        javaTemplateParser - The corresponding parser that contains the codeBlock.
        Throws:
        IllegalActionException - If there is a problem adding a function to the set of overloaded functions.
      • splitLongBody

        public java.lang.String[] splitLongBody​(int linesPerMethod,
                                                java.lang.String prefix,
                                                java.lang.String code)
                                         throws java.io.IOException
        Split a long function body into multiple inner classes.
        Overrides:
        splitLongBody in class ProgramCodeGenerator
        Parameters:
        linesPerMethod - The number of lines that should go into each method.
        prefix - The prefix to use when naming inner classes that are created.
        code - The method body to be split.
        Returns:
        An array of two Strings, where the first element is the new definitions (if any), and the second element is the new body. If the number of lines in the code parameter is less than linesPerMethod, then the first element will be the empty string and the second element will be the value of the code parameter.
        Throws:
        java.io.IOException - If thrown while reading the code.
      • splitVariableDeclaration

        public java.util.List<java.lang.String> splitVariableDeclaration​(int linesPerMethod,
                                                                         java.lang.String prefix,
                                                                         java.lang.String code)
                                                                  throws java.io.IOException
        Split a long variable declaration body into multiple blocks or files.

        For Java, if the code consists of linesPerMethod or fewer lines, then the the first element will be the empty string and the second element will consist of the value of the code argument. If the code consists of more than linesPerMethod then the first element will consist of one or more "import static" statements and the second and possibly successive element will consist of Java classes that should be written out by _writeVariableDeclarations(List).

        Overrides:
        splitVariableDeclaration in class ProgramCodeGenerator
        Parameters:
        linesPerMethod - The number of lines that should go into each method.
        prefix - The prefix to use when naming functions that are created
        code - The variable declarations to be split.
        Returns:
        A list of at least two elements. If the code has less than _LINES_PER_METHOD lines, then the first element is empty, the second element contains the contents of the code parameter. If the code has more lines than _LINES_PER_METHOD, then the first element contains the declarations necessary for the include files section and the second element and successive elements contain the declarations. Each declaration should be placed into a file that corresponds with the include or import listed in the first element.
        Throws:
        java.io.IOException - If thrown while reading the code.
      • targetType

        public java.lang.String targetType​(Type ptType)
        Get the corresponding type in Java from the given Ptolemy type.
        Overrides:
        targetType in class ProgramCodeGenerator
        Parameters:
        ptType - The given Ptolemy type.
        Returns:
        The Java data type.
      • _addClassPathLibraries

        protected void _addClassPathLibraries()
        Add the directories and files from the classpath to the list of libraries. This method is used to add the JavaScope.zip file used by code coverage so that we can use Ptolemy classes in the nightly build.
      • _concatenateClasspath

        protected java.lang.String _concatenateClasspath​(java.util.Collection<java.lang.String> collection)
        Given a Collection of Strings, return a string where each element of the Set is separated by $.
        Parameters:
        collection - The Collection of Strings.
        Returns:
        A String that contains each element of the Set separated by a space.
      • _finalPassOverCode

        protected java.lang.StringBuffer _finalPassOverCode​(java.lang.StringBuffer code)
                                                     throws IllegalActionException
        Make a final pass over the generated code. Subclass may extend this method to do extra processing to format the output code. If sourceLineBinding is set to true, it will check and insert the appropriate #line macro for each line in the given code. Blank lines are discarded if #line macros are inserted.
        Overrides:
        _finalPassOverCode in class ProgramCodeGenerator
        Parameters:
        code - The given code to be processed.
        Returns:
        The processed code.
        Throws:
        IllegalActionException - If #getOutputFilename() throws it.
      • _generatePreinitializeMethodBodyCode

        protected java.lang.String _generatePreinitializeMethodBodyCode()
                                                                 throws IllegalActionException
        Generate the preinitialization method body.

        Typically, the preinitialize code consists of variable declarations. However, AutoAdapter generates method calls that instantiate wrapper TypedCompositeActors, so we need to invoke those method calls.

        Overrides:
        _generatePreinitializeMethodBodyCode in class ProgramCodeGenerator
        Returns:
        a string for the preinitialization method body.
        Throws:
        IllegalActionException - Not thrown in this base class.
      • _getAutoGeneratedAdapter

        protected CodeGeneratorAdapter _getAutoGeneratedAdapter​(GenericCodeGenerator codeGenerator,
                                                                java.lang.Object object)
        Attempt to automatically generate an adapter.
        Overrides:
        _getAutoGeneratedAdapter in class GenericCodeGenerator
        Parameters:
        codeGenerator - The code generator with which to associate the adapter.
        object - The given object.
        Returns:
        The code generator adapter or null if no adapter can be automatically generated.
      • _getFireFunctionArguments

        protected java.lang.String _getFireFunctionArguments()
        Return the prototype for fire functions.
        Overrides:
        _getFireFunctionArguments in class ProgramCodeGenerator
        Returns:
        The string " throws Exception" is appended to the value returned by the superclass.
      • _printExecutionTime

        protected java.lang.String _printExecutionTime()
        Generate the code for printing the execution time since the code generated by _recordStartTime() was called.
        Overrides:
        _printExecutionTime in class ProgramCodeGenerator
        Returns:
        Return the code for printing the total execution time.
      • _processCode

        protected java.lang.String _processCode​(java.lang.String code)
                                         throws IllegalActionException
        Process the specified code for the adapter associated with the container. Replace macros with their values.
        Parameters:
        code - The code to process.
        Returns:
        The processed code.
        Throws:
        IllegalActionException - If illegal macro names are found.
      • _recordStartTime

        protected java.lang.String _recordStartTime()
        Generate the code for recording the current time. This writes current time into a timespec struct called "start".
        Overrides:
        _recordStartTime in class ProgramCodeGenerator
        Returns:
        Return the code for recording the current time.
      • _reset

        protected void _reset()
                       throws IllegalActionException
        Reset the code generator. After calling _reset(), you must call _analyzeTypeConversions() before calling the generate methods again.
        Overrides:
        _reset in class ProceduralCodeGenerator
        Throws:
        IllegalActionException - Not thrown in this base class, thrown by the parent if the container of the model cannot be set to null.
      • _templateParserClass

        protected java.lang.Class<? extends TemplateParser> _templateParserClass()
        Return the class of the templateParser class. In cse there isn't one return null.
        Overrides:
        _templateParserClass in class ProgramCodeGenerator
        Returns:
        The base class for templateParser.
      • _writeMakefile

        protected void _writeMakefile​(CompositeEntity container,
                                      java.lang.String currentDirectory)
                               throws IllegalActionException
        Read in a template makefile, substitute variables and write the resulting makefile.

        If a .mk.in file with the name of the sanitized model name, then that file is used as a template. For example, if the model name is Foo and the file Foo.mk.in exists, then the file Foo.mk.in is used as a makefile template.

        If no .mk.in file is found, then the makefile template can be found by looking up a resource name makefile.in in the package named by the generatorPackage parameter. Thus, if the generatorPackage has the value "ptolemy.codegen.c", then we look for the resource "ptolemy.codegen.c.makefile.in", which is usually found as $PTII/ptolemy/codegen/c/makefile.in.

        The makefile is written to a directory named by the codeDirectory parameter, with a file name that is a sanitized version of the model name, and a ".mk" extension. Thus, for a model named "Foo", we might generate a makefile in "$HOME/codegen/Foo.mk".

        Under Java under Windows, your $HOME variable is set to the value of the user.homeSystem property, which is usually something like C:\Documents and Settings\yourlogin, thus for user mrptolemy the makefile would be C:\Documents and Settings\mrptolemy\codegen\Foo.mk.

        The following variables are substituted

        @modelName@
        The sanitized model name, created by invoking StringUtilities.sanitizeName(String) on the model name.
        @PTCGIncludes@
        The elements of the set of include command arguments that were added by calling ProceduralCodeGenerator.addInclude(String), where each element is separated by a space.
        @PTCGLibraries@
        The elements of the set of library command arguments that were added by calling ProceduralCodeGenerator.addLibrary(String), where each element is separated by a space.
        Overrides:
        _writeMakefile in class ProceduralCodeGenerator
        Parameters:
        container - The composite actor for which we generate the makefile
        currentDirectory - The director in which the makefile is to be written.
        Throws:
        IllegalActionException - If there is a problem reading a parameter, if there is a problem creating the codeDirectory directory or if there is a problem writing the code to a file.
      • _writeVariableDeclarations

        protected java.lang.String _writeVariableDeclarations​(java.util.List<java.lang.String> variableDeclarations)
                                                       throws IllegalActionException
        Write the variable declaration code.

        If the first element is the empty String, then the second element contains all of the variable declarations and this method does not create files and the value of the second element is returned. If the first element is not the empty string, then the second and successive elements are written to a file whos name is created by parsing the first element. The first element must consist of strings like "import static variables.foo;", the file name will be "variables/foo.java".

        Overrides:
        _writeVariableDeclarations in class ProgramCodeGenerator
        Parameters:
        variableDeclarations - A List of two or more elements. first element is not empty, then it contains the language specific declarations for the variable declarations. In Java, the first element may consist of one or more "import" statements. The second and successive elements contain the code to be written to separate files or to be returned as one String.
        Returns:
        If the first element is empty, then return the value of the second element. If the first element is not empty, then files are created and the empty string is returned.
        Throws:
        IllegalActionException - Thrown if there is a problem writing the files.