Class GenericCodeGenerator

    • Field Detail

      • codeDirectory

        public FileParameter codeDirectory
        The directory in which to put the generated code. This is a file parameter that must specify a directory. The default is "$HOME/cg/".
      • generateInSubdirectory

        public Parameter generateInSubdirectory
        If true, then generate code in a subdirectory of codeDirectory. The default value is false, indicating that code should be generated in the directory named by codeDirectory. If the value is true, then code is generated in a subdirectory of the directory named by the codeDirectory parameter. This is useful for languages such as Java, which means that the code will be generated in a package named by the sanitized version of the model name. The default value is a Boolean with the value "false".
      • generatorPackage

        public StringParameter generatorPackage
        The name of the package in which to look for adapter class code generators. The default value of this parameter is the empty string. Derived classes may set this parameter to values like ptolemy.cg.kernel.generic.program.procedural.c. ptolemy.cg.kernel.generic.html, or ptolemy.cg.kernel.generic.program.procedural.java.
      • generatorPackageList

        public StringParameter generatorPackageList
        The name of the package(s) in which to look for adapter classes. The string can either be just one package, such as "generic.program.procedural.java" or a list of semicolon ';' , colon ':', space ' ' or asterix '*' separated list of Java packages, such as generic.program.procedural.java.target1:generic.program.procedural.java.target2. The adapter is first searched in the first package. Adapters are looked up by class name, where the class name consists of "ptolemy.cg.adapter" + the package name from this list + "adapters.". Thus, if generatorPackageList is set to generic.program.procedural.java, then the ptolemy.cg.adapter.generic.program.procedural.java.adapters. package will be searched.
      • overwriteFiles

        public Parameter overwriteFiles
        If true, overwrite preexisting files. The default value is a parameter with the value true.
      • _eol

        protected static final java.lang.String _eol
        End of line character. Under Unix: "\n", under Windows: "\n\r". We use a end of line character so that the files we generate have the proper end of line character for use by other native tools.
      • _executeCommands

        protected ExecuteCommands _executeCommands
        Execute commands to run the generated code.
      • _generateInSubdirectory

        protected boolean _generateInSubdirectory
        The value of the generateInSubdirectory parameter.
      • _model

        protected CompositeEntity _model
        The model we for which we are generating code.
      • _sanitizedModelName

        protected java.lang.String _sanitizedModelName
        The sanitized model name.
      • _codeFileName

        protected java.lang.String _codeFileName
        The name of the file that was written. If no file was written, then the value is null.
    • Constructor Detail

      • GenericCodeGenerator

        public GenericCodeGenerator​(NamedObj container,
                                    java.lang.String name)
                             throws IllegalActionException,
                                    NameDuplicationException
        Create a new instance of the code generator. The file extension is set to the last package of the generatePackage parameter.
        Parameters:
        container - The container.
        name - The name of the 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.
      • GenericCodeGenerator

        public GenericCodeGenerator​(NamedObj container,
                                    java.lang.String name,
                                    java.lang.String outputFileExtension)
                             throws IllegalActionException,
                                    NameDuplicationException
        Create a new instance of the code generator.
        Parameters:
        container - The container.
        name - The name of the code generator.
        outputFileExtension - The extension of the output file. (for example c in case of C and java in case of Java)
        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

      • attributeChanged

        public void attributeChanged​(Attribute attribute)
                              throws IllegalActionException
        If the attribute is the codeDirectory parameter, then set the base directory of the codeDirectory parameter.
        Overrides:
        attributeChanged in class NamedObj
        Parameters:
        attribute - The attribute that changed.
        Throws:
        IllegalActionException - If the change is not acceptable to this container.
      • comment

        public java.lang.String comment​(java.lang.String comment)
        Return a formatted comment containing the specified string. In this base class, the empty string is returned.
        Parameters:
        comment - The string to put in the comment.
        Returns:
        A formatted comment.
      • createDecoratorAttributes

        public DecoratorAttributes createDecoratorAttributes​(NamedObj target)
        Return the decorated attributes for the target NamedObj.
        Specified by:
        createDecoratorAttributes in interface Decorator
        Parameters:
        target - The NamedObj that will be decorated.
        Returns:
        A list of decorated attributes for the target NamedObj, or null if there is no adapter for this object.
      • decoratedObjects

        public java.util.List<NamedObj> decoratedObjects()
        Return a list of the entities deeply contained by the container of this resource scheduler.
        Specified by:
        decoratedObjects in interface Decorator
        Returns:
        A list of the objects decorated by this decorator.
      • generateCode

        public int generateCode()
                         throws KernelException
        Generate code and write it to the file specified by the codeDirectory parameter.
        Returns:
        The return value of the last subprocess that was executed. or -1 if no commands were executed.
        Throws:
        KernelException - If the target file cannot be overwritten or write-to-file throw any exception.
      • generateCode

        public int generateCode​(java.lang.StringBuffer code)
                         throws KernelException
        Generate code. This is the main entry point.
        Parameters:
        code - The code buffer into which to generate the code.
        Returns:
        The return value of the last subprocess that was executed. or -1 if no commands were executed.
        Throws:
        KernelException - If a type conflict occurs or the model is running.
      • generateCode

        public static int generateCode​(java.lang.String[] args)
                                throws java.lang.Exception
        Generate code for a model.
        Parameters:
        args - An array of Strings, each element names a MoML file containing a model.
        Returns:
        The return value of the last subprocess that was run to compile or run the model. Return -1 if called with no arguments. Return -2 if no CodeGenerator was created.
        Throws:
        java.lang.Exception - If any error occurs.
      • generateCopyright

        public java.lang.String generateCopyright()
        Return the copyright for this code. In this base class, the empty string is returned. In derived classes, the standard Ptolemy copyright is returned within a comment.
        Returns:
        The copyright.
      • getAdapter

        public final java.lang.Object getAdapter​(java.lang.Object component)
                                          throws IllegalActionException
        Get the code generator adapter associated with the given component.
        Parameters:
        component - The given component.
        Returns:
        The code generator adapter.
        Throws:
        IllegalActionException - If the adapter class cannot be found.
      • getCodeFileName

        public final java.lang.String getCodeFileName()
        Return the name of the code file that was written, if any. If no file was written, then return null.
        Returns:
        The name of the file that was written.
      • getComponent

        public NamedObj getComponent()
        Return the associated component, which is always the container.
        Returns:
        The adapter to generate code.
      • getExecuteCommands

        public final ExecuteCommands getExecuteCommands()
        Get the command executor, which can be either non-graphical or graphical. The initial default is non-graphical, which means that stderr and stdout from subcommands is written to the console.
        Returns:
        executeCommands The subprocess command executor.
        See Also:
        setExecuteCommands(ExecuteCommands)
      • getMethodVisibilityString

        public java.lang.String getMethodVisibilityString()
        Return the visibility signature for run() and execute() (for Java).
        Returns:
        The visibility signature, empty string for C.
      • getMethodExceptionString

        public java.lang.String getMethodExceptionString()
        Return the exception signature (for Java).
        Returns:
        The exception signature, empty string for C.
      • isGlobalDecorator

        public boolean isGlobalDecorator()
        Return false to indicate that this decorator should not decorate objects across opaque hierarchy boundaries.
        Specified by:
        isGlobalDecorator in interface Decorator
        Returns:
        True if decorator is global.
      • main

        public static void main​(java.lang.String[] args)
                         throws java.lang.Exception
        Generate code for a model.

        For example:

          java -classpath $PTII ptolemy.cg.kernel.generic.GenericCodeGenerator $PTII/ptolemy/cg/adapter/generic/program/procedural/c/adapters/ptolemy/actor/lib/test/auto/Ramp.xml
          
        or
          $PTII/bin/ptinvoke ptolemy.cg.kernel.generic.GenericCodeGenerator $PTII/ptolemy/cg/adapter/generic/program/procedural/c/adapters/ptolemy/actor/lib/test/auto/Ramp.xml
          

        The HandSimDroid work in $PTII/ptserver uses dependency injection to determine which implementation actors such as Const and Display to use. This method reads the ptolemy/actor/ActorModule.properties file.

        Parameters:
        args - An array of Strings, each element names a MoML file containing a model.
        Throws:
        java.lang.Exception - If any error occurs.
      • setCodeGenerator

        public void setCodeGenerator​(GenericCodeGenerator codeGenerator)
        This method is used to set the code generator for a adapter class. Since this is not a adapter class for a component, this method does nothing.
        Parameters:
        codeGenerator - The given code generator.
      • setExecuteCommands

        public void setExecuteCommands​(ExecuteCommands executeCommands)
        Set the command executor, which can be either non-graphical or graphical. The initial default is non-graphical, which means that stderr and stdout from subcommands is written to the console.
        Parameters:
        executeCommands - The subprocess command executor.
        See Also:
        getExecuteCommands()
      • updateCommandOptions

        public java.lang.String[][] updateCommandOptions()
        Return an updated array of command line options.
        Returns:
        An array of updated command line options.
      • _copyCFileTosrc

        protected void _copyCFileTosrc​(java.lang.String path,
                                       java.lang.String directoryToCopy,
                                       java.lang.String codeFileName)
                                throws IllegalActionException
        Copy a C (or h) file into the directory /src of the project. This is useful to copy the files pre-written in C.
        Parameters:
        path - The path to the source to be copied. A relative path has $PTII prepended to it.
        directoryToCopy - The destination directory, typically an absolute path determined by the value of the codeDirectory parameter.
        codeFileName - the name of the file to copy.
        Throws:
        IllegalActionException - If thrown while copying a file.
      • _copyCFilesTosrc

        protected void _copyCFilesTosrc​(java.lang.String path,
                                        java.lang.String directoryToCopy,
                                        java.lang.String[] codeFileNames)
                                 throws IllegalActionException
        Copy files into the directory of the project. This is useful to copy the files pre-written in C.
        Parameters:
        path - The path to the source to be copied. A relative path has $PTII prepended to it.
        directoryToCopy - The destination directory, typically an absolute path determined by the value of the codeDirectory parameter.
        codeFileNames - the name of the file to copy.
        Throws:
        IllegalActionException - If thrown while copying a file.
      • _executeCommands

        protected int _executeCommands()
                                throws IllegalActionException
        Execute the compile and run commands in the codeDirectory directory. In this base class, 0 is returned by default.
        Returns:
        The result of the execution.
        Throws:
        IllegalActionException - Not thrown in this base class.
      • _generateCode

        protected int _generateCode​(java.lang.StringBuffer code)
                             throws KernelException
        Generate code and append it to the given string buffer.

        Write the code to the directory specified by the codeDirectory parameter. The file name is a sanitized version of the model name with a suffix that is based on last package name of the generatorPackage parameter. Thus if the codeDirectory is $HOME, the name of the model is Foo and the generatorPackage is ptolemy.codegen.c, then the file that is written will be $HOME/Foo.c

        This method is the main entry point, derived classes will override this method with code that traverses the model and generates code.

        Parameters:
        code - The given string buffer.
        Returns:
        The return value of the last subprocess that was executed. or -1 if no commands were executed.
        Throws:
        KernelException - If the target file cannot be overwritten or write-to-file throw any exception.
      • _getAdapter

        protected final CodeGeneratorAdapter _getAdapter​(java.lang.Object object)
                                                  throws IllegalActionException
        Get the code generator adapter associated with the given object.
        Parameters:
        object - The given object.
        Returns:
        The code generator adapter.
        Throws:
        IllegalActionException - If the adapter class cannot be found.
      • _getAdapterClassFilter

        protected java.lang.Class<?> _getAdapterClassFilter()
        Return the filter class to find adapters. All adapters have to extend this class.
        Returns:
        The base class for the adapters.
      • _getAutoGeneratedAdapter

        protected CodeGeneratorAdapter _getAutoGeneratedAdapter​(GenericCodeGenerator codeGenerator,
                                                                java.lang.Object object)
        Attempt to automatically generate an adapter. In this base class, return null, indicating that an adapter cannot be generated. Derived classes could create an adapter
        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.
      • _getOutputFilename

        protected java.lang.String _getOutputFilename()
                                               throws IllegalActionException
        Return the name of the output file.
        Returns:
        The output file name.
        Throws:
        IllegalActionException - If there is problem resolving the string value of the generatorPackage parameter.
      • _instantiateAdapter

        protected CodeGeneratorAdapter _instantiateAdapter​(java.lang.Object component,
                                                           java.lang.Class<?> componentClass,
                                                           java.lang.String adapterClassName)
                                                    throws IllegalActionException
        Instantiate the given code generator adapter.
        Parameters:
        component - The given component.
        componentClass - The class of the component to be instantiated. The constructor for class named by the adapterClassName argument must take an argument of the class componentClass.
        adapterClassName - The dot separated name of the adapter.
        Returns:
        The code generator adapter.
        Throws:
        IllegalActionException - If the adapter class cannot be found.
      • _isTopLevel

        protected boolean _isTopLevel()
                               throws IllegalActionException
        Test if the containing actor is in the top level.
        Returns:
        true if the containing actor is in the top level.
        Throws:
        IllegalActionException - If thrown while getting the container.
      • _printTimeAndMemory

        protected long _printTimeAndMemory​(long startTime,
                                           java.lang.String message)
        Print the elapsed time since the specified startTime if the elapsed time is greater than 10 seconds. Otherwise, do nothing.
        Parameters:
        startTime - The start time. Usually set to the value of (new Date()).getTime().
        message - A prefix to the printed message.
        Returns:
        The current time.
      • _writeCode

        protected java.lang.String _writeCode​(java.lang.StringBuffer code)
                                       throws IllegalActionException
        Write the code to a directory named by the codeDirectory parameter, with a file name that is a sanitized version of the model name, and an extension that is the last package of the generatorPackage.
        Parameters:
        code - The StringBuffer containing the code.
        Returns:
        The name of the file that was 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.
      • _writeCodeFileName

        protected java.lang.String _writeCodeFileName​(java.lang.StringBuffer code,
                                                      java.lang.String codeFileName,
                                                      boolean overwriteFile,
                                                      boolean dontShowDialog)
                                               throws IllegalActionException
        Write the code to a directory named by the codeDirectory parameter, with a file name that is a sanitized version of the model name, and an extension that is the last package of the generatorPackage.
        Parameters:
        code - The StringBuffer containing the code.
        codeFileName - The name of the output file.
        overwriteFile - The overwrite flag.
        dontShowDialog - When true the confirmation dialog won't be shown.
        Returns:
        The name of the file that was 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.