ptolemy.cg.kernel.generic
Class GenericCodeGenerator

java.lang.Object
  extended by ptolemy.kernel.util.NamedObj
      extended by ptolemy.kernel.util.Attribute
          extended by ptolemy.cg.kernel.generic.GenericCodeGenerator
All Implemented Interfaces:
java.io.Serializable, java.lang.Cloneable, Changeable, Debuggable, DebugListener, Decorator, Derivable, ModelErrorHandler, MoMLExportable, Moveable, Nameable
Direct Known Subclasses:
HTMLCodeGenerator, ProgramCodeGenerator

public abstract class GenericCodeGenerator
extends Attribute
implements Decorator

Base class for code generator.

Since:
Ptolemy II 7.1
Version:
$Id: GenericCodeGenerator.java 56135 2009-11-10 19:54:19Z mschoebe $
Author:
Edward A. Lee, Gang Zhou, Ye Zhou, Contributors: Christopher Brooks, Bert Rodiers
See Also:
Serialized Form
Accepted Rating:
Yellow (eal)
Proposed Rating:
Yellow (eal)

Nested Class Summary
(package private)  class GenericCodeGenerator.GeneratorPackageListParser
          Parse the generatorPackageList parameter.
 
Nested classes/interfaces inherited from class ptolemy.kernel.util.NamedObj
NamedObj.ContainedObjectsIterator
 
Field Summary
private  java.util.Map<java.lang.Object,CodeGeneratorAdapter> _adapterStore
          A map giving the code generator adapters for each actor.
protected  java.lang.String _codeFileName
          The name of the file that was written.
private static java.lang.String[] _commandFlags
          The command-line options that are either present or not.
private static java.lang.String[][] _commandOptions
          The command-line options that take arguments.
private static java.lang.String _commandTemplate
          The form of the command line.
protected static java.lang.String _eol
          End of line character.
protected  ExecuteCommands _executeCommands
          Execute commands to run the generated code.
private  GenericCodeGenerator.GeneratorPackageListParser _generatorPackageListParser
           
protected  CompositeEntity _model
          The model we for which we are generating code.
private  java.lang.String _outputFileExtension
          The extension of the output file.
private static java.util.List<java.lang.String> _parameterNames
          List of parameter names seen on the command line.
private static java.util.List<java.lang.String> _parameterValues
          List of parameter values seen on the command line.
protected  java.lang.String _sanitizedModelName
          The sanitized model name.
 FileParameter codeDirectory
          The directory in which to put the generated code.
 StringParameter generatorPackage
          The name of the package in which to look for helper class code generators.
 StringParameter generatorPackageList
          The name of the package(s) in which to look for adapter classes.
static java.lang.String INDENT1
          Indent string for indent level 1.
static java.lang.String INDENT2
          Indent string for indent level 2.
static java.lang.String INDENT3
          Indent string for indent level 3.
 Parameter overwriteFiles
          If true, overwrite preexisting files.
 
Fields inherited from class ptolemy.kernel.util.NamedObj
_changeListeners, _changeLock, _changeRequests, _debugging, _debugListeners, _elementName, _isPersistent, _verbose, _workspace, ATTRIBUTES, CLASSNAME, COMPLETE, CONTENTS, DEEP, FULLNAME, LINKS
 
Constructor Summary
GenericCodeGenerator(NamedObj container, java.lang.String name)
          Create a new instance of the code generator.
GenericCodeGenerator(NamedObj container, java.lang.String name, java.lang.String outputFileExtension)
          Deprecated. Set generatorPackage and use @{link #GenericCodeGenerator(container, name) instead.
 
Method Summary
protected  int _executeCommands()
          Execute the compile and run commands in the codeDirectory directory.
protected  int _generateCode(java.lang.StringBuffer code)
          Generate code and append it to the given string buffer.
protected  CodeGeneratorAdapter _getAdapter(java.lang.Object object)
          Get the code generator adapter associated with the given object.
protected  java.lang.Class<?> _getAdapterClassFilter()
          Return the filter class to find adapters.
private static java.lang.Class<?> _getCodeGeneratorClass(java.lang.String generatorPackageValue)
          Get the code generator associated with the generatePackage parameter.
private  java.lang.String _getOutputFileExtension()
          Return the file extension for generated files.
protected  java.lang.String _getOutputFilename()
          Return the name of the output file.
protected  CodeGeneratorAdapter _instantiateAdapter(java.lang.Object component, java.lang.Class<?> componentClass, java.lang.String adapterClassName)
          Instantiate the given code generator adapter.
protected  boolean _isTopLevel()
          Test if the containing actor is in the top level.
protected  long _printTimeAndMemory(long startTime, java.lang.String message)
          Print the elapsed time since the specified startTime if the elpsed time is greater than 10 seconds.
protected  void _reset()
          Reset the code generator.
private  void _updateParameters(NamedObj model)
          Set the parameters in the model stored in _parameterNames to the values given by _parameterValues.
private static java.lang.String _usage()
          Return a string summarizing the command-line arguments.
protected  java.lang.String _writeCode(java.lang.StringBuffer code)
          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.
protected  java.lang.String _writeCodeFileName(java.lang.StringBuffer code, java.lang.String codeFileName, boolean overwriteFile, boolean dontShowDialog)
          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.
 void attributeChanged(Attribute attribute)
          If the attribute is the codeDirectory parameter, then set the base directory of the codeDirectory parameter.
 java.lang.String comment(java.lang.String comment)
          Return a formatted comment containing the specified string.
 DecoratedAttributes createDecoratedAttributes(NamedObj target)
          Return the decorated attributes for the target NamedObj.
 int generateCode()
          Generate code and write it to the file specified by the codeDirectory parameter.
static int generateCode(java.lang.String[] args)
          Generate code for a model.
 int generateCode(java.lang.StringBuffer code)
          Generate code.
 java.lang.String generateCopyright()
          Return the copyright for this code.
 java.lang.Object getAdapter(java.lang.Object component)
          Get the code generator adapter associated with the given component.
 java.lang.String getCodeFileName()
          Return the name of the code file that was written, if any.
 NamedObj getComponent()
          Return the associated component, which is always the container.
 ExecuteCommands getExecuteCommands()
          Get the command executor, which can be either non-graphical or graphical.
 java.lang.String getMethodExceptionString()
          Return the exception signature (for Java).
 java.lang.String getMethodVisibiliyString()
          Return the visibility signature for run() and execute() (for Java).
static void main(java.lang.String[] args)
          Generate code for a model.
private static boolean parseArg(java.lang.String arg)
          Parse a command-line argument.
 void setCodeGenerator(GenericCodeGenerator codeGenerator)
          This method is used to set the code generator for a adapter class.
 void setContainer(NamedObj container)
          Set the container of this object to be the given container.
 void setExecuteCommands(ExecuteCommands executeCommands)
          Set the command executor, which can be either non-graphical or graphical.
 void setTypesOfDecoratedVariables(DecoratedAttributes decoratedAttributes)
          Set the current type of the decorated attributes.
 
Methods inherited from class ptolemy.kernel.util.Attribute
_checkContainer, _getContainedObject, _propagateExistence, clone, getContainer, moveDown, moveToFirst, moveToIndex, moveToLast, moveUp, setName, updateContent
 
Methods inherited from class ptolemy.kernel.util.NamedObj
_addAttribute, _adjustOverride, _attachText, _cloneFixAttributeFields, _debug, _debug, _debug, _debug, _debug, _description, _exportMoMLContents, _getIndentPrefix, _isMoMLSuppressed, _markContentsDerived, _propagateValue, _recordDecoratedAttributes, _removeAttribute, _splitName, _stripNumericSuffix, _validateSettables, addChangeListener, addDebugListener, attributeList, attributeList, attributeTypeChanged, clone, containedObjectsIterator, deepContains, depthInHierarchy, description, description, event, executeChangeRequests, exportMoML, exportMoML, exportMoML, exportMoML, exportMoML, exportMoMLPlain, getAttribute, getAttribute, getAttributes, getChangeListeners, getClassName, getDecoratorAttribute, getDecoratorAttributes, getDerivedLevel, getDerivedList, getDisplayName, getElementName, getFullName, getModelErrorHandler, getName, getName, getPrototypeList, getSource, handleModelError, isDeferringChangeRequests, isOverridden, isPersistent, lazyContainedObjectsIterator, message, propagateExistence, propagateValue, propagateValues, removeChangeListener, removeDebugListener, requestChange, setClassName, setDeferringChangeRequests, setDerivedLevel, setDisplayName, setModelErrorHandler, setPersistent, setSource, sortContainedObjects, toplevel, toString, uniqueName, validateSettables, workspace
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface ptolemy.kernel.util.Nameable
description, getContainer, getDisplayName, getFullName, getName, getName, setName
 

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/".


generatorPackage

public StringParameter generatorPackage
The name of the package in which to look for helper 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.


INDENT1

public static final java.lang.String INDENT1
Indent string for indent level 1.

See Also:
StringUtilities.getIndentPrefix(int)

INDENT2

public static final java.lang.String INDENT2
Indent string for indent level 2.

See Also:
StringUtilities.getIndentPrefix(int)

INDENT3

public static final java.lang.String INDENT3
Indent string for indent level 3.

See Also:
StringUtilities.getIndentPrefix(int)

_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 charactor 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.


_model

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


_sanitizedModelName

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


_adapterStore

private java.util.Map<java.lang.Object,CodeGeneratorAdapter> _adapterStore
A map giving the code generator adapters for each actor.


_codeFileName

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


_commandFlags

private static java.lang.String[] _commandFlags
The command-line options that are either present or not.


_commandOptions

private static java.lang.String[][] _commandOptions
The command-line options that take arguments.


_commandTemplate

private static final java.lang.String _commandTemplate
The form of the command line.

See Also:
Constant Field Values

_generatorPackageListParser

private GenericCodeGenerator.GeneratorPackageListParser _generatorPackageListParser

_parameterNames

private static java.util.List<java.lang.String> _parameterNames
List of parameter names seen on the command line.


_parameterValues

private static java.util.List<java.lang.String> _parameterValues
List of parameter values seen on the command line.


_outputFileExtension

private java.lang.String _outputFileExtension
The extension of the output file. (for example c in case of C and java in case of Java). The file extension is set to the last package of the generatePackage parameter. For example, if generatePackage is set to ptolemy.cg.kernel.generic.html", then the extension will be ".html".

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
Deprecated. Set generatorPackage and use @{link #GenericCodeGenerator(container, name) instead.

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.

createDecoratedAttributes

public DecoratedAttributes createDecoratedAttributes(NamedObj target)
                                              throws IllegalActionException,
                                                     NameDuplicationException
Return the decorated attributes for the target NamedObj.

Specified by:
createDecoratedAttributes in interface Decorator
Parameters:
target - The NamedObj that will be decorated.
Returns:
A list of decorated attributes for the target NamedObj.
Throws:
IllegalActionException - If the attribute is not of an acceptable class for the container, or if the name contains a period.
NameDuplicationException - If the name coincides with an attribute already in the container.

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)

getMethodVisibiliyString

public java.lang.String getMethodVisibiliyString()
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.

main

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

For example:

  java -classpath $PTII ptolemy.codegen.kernel.CodeGenerator $PTII/ptolemy/codegen/c/actor/lib/test/auto/Ramp.xml
  
or
  $PTII/bin/ptinvoke ptolemy.codegen.kernel.CodeGenerator $PTII/ptolemy/codegen/c/actor/lib/test/auto/Ramp.xml
  

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.

setContainer

public void setContainer(NamedObj container)
                  throws IllegalActionException,
                         NameDuplicationException
Set the container of this object to be the given container.

Overrides:
setContainer in class Attribute
Parameters:
container - The given container.
Throws:
IllegalActionException - If the given container is not null and not an instance of CompositeEntity.
NameDuplicationException - If there already exists a container with the same name.
See Also:
Attribute.getContainer()

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()

setTypesOfDecoratedVariables

public void setTypesOfDecoratedVariables(DecoratedAttributes decoratedAttributes)
                                  throws IllegalActionException
Set the current type of the decorated attributes. The type information of the parameters are not saved in the model hand hence this has to be reset when reading the model again.

Specified by:
setTypesOfDecoratedVariables in interface Decorator
Parameters:
decoratedAttributes - The decorated attributes
Throws:
IllegalActionException - If the attribute is not of an acceptable class for the container, or if the name contains a period.

_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.

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.

_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.
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

_printTimeAndMemory

protected long _printTimeAndMemory(long startTime,
                                   java.lang.String message)
Print the elapsed time since the specified startTime if the elpsed 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.

_reset

protected void _reset()
Reset the code generator.


_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.

_getOutputFileExtension

private java.lang.String _getOutputFileExtension()
                                          throws IllegalActionException
Return the file extension for generated files. The file extension is set to the last package of the generatePackage parameter. For example, if generatePackage is set to ptolemy.cg.kernel.generic.html", then the extension will be ".html". In this base class, the output file extension

Returns:
The file extension.
Throws:
IllegalActionException - If getting the value of the generatorPackage parameter throws it.

_updateParameters

private void _updateParameters(NamedObj model)
Set the parameters in the model stored in _parameterNames to the values given by _parameterValues. Those lists are populated by command line arguments.

Parameters:
model - The model in which to update parameters.

parseArg

private static boolean parseArg(java.lang.String arg)
                         throws java.lang.Exception
Parse a command-line argument. This method recognized -help and -version command-line arguments, and prints usage or version information. No other command-line arguments are recognized.

Parameters:
arg - The command-line argument to be parsed.
Returns:
True if the argument is understood, false otherwise.
Throws:
java.lang.Exception - If something goes wrong.

_usage

private static java.lang.String _usage()
Return a string summarizing the command-line arguments.

Returns:
A usage string.

_getCodeGeneratorClass

private static java.lang.Class<?> _getCodeGeneratorClass(java.lang.String generatorPackageValue)
                                                  throws IllegalActionException
Get the code generator associated with the generatePackage parameter.

Parameters:
generatorPackageValue - The value of the generatorPackage parameter.
Returns:
The CodeGenerator class that corresponds with the generatorPackage parameter. For example, if generatorPackage is "ptolemy.codegen.c", then the class "ptolemy.codegen.c.kernel.CCodeGenerator" is searched for.
Throws:
IllegalActionException - If the adapter class cannot be found.