ptolemy.codegen.kernel
Class CodeGenerator

java.lang.Object
  extended by ptolemy.kernel.util.NamedObj
      extended by ptolemy.kernel.util.Attribute
          extended by ptolemy.codegen.kernel.CodeGenerator
All Implemented Interfaces:
java.io.Serializable, java.lang.Cloneable, ComponentCodeGenerator, Changeable, Debuggable, DebugListener, Derivable, ModelErrorHandler, MoMLExportable, Moveable, Nameable
Direct Known Subclasses:
CCodeGenerator, JavaCodeGenerator, RTMaudeCodeGenerator

public class CodeGenerator
extends Attribute
implements ComponentCodeGenerator

Base class for code generator.

Since:
Ptolemy II 6.0
Version:
$Id: CodeGenerator.java 57046 2010-01-27 23:35:53Z cxh $
Author:
Edward A. Lee, Gang Zhou, Ye Zhou, Contributors: Christopher Brooks
See Also:
Serialized Form
Accepted Rating:
Yellow (eal)
Proposed Rating:
Yellow (eal)

Nested Class Summary
private static class CodeGenerator.TargetFilter
          A FilenameFilter that looks for directories other than CVS.
 
Nested classes/interfaces inherited from class ptolemy.kernel.util.NamedObj
NamedObj.ContainedObjectsIterator
 
Field Summary
protected  java.lang.String _codeFileName
          The name of the file that was written.
protected static java.lang.String[] _commandFlags
          The command-line options that are either present or not.
protected static java.lang.String[][] _commandOptions
          The command-line options that take arguments.
protected static java.lang.String _commandTemplate
          The form of the command line.
protected static java.lang.String _DEFAULT_TARGET
          The default target name.
protected static java.lang.String _eol
          End of line character.
protected  ExecuteCommands _executeCommands
          Execute commands to run the generated code.
private  java.util.Map _helperStore
          A map giving the code generator helpers for each actor.
protected  java.util.Set<java.lang.String> _includes
          Set of include command line arguments where each element is a string, for example "-I/usr/local/include".
private  int _indent
          The current indent level when pretty printing code.
protected static java.lang.String _INDENT1
          Indent string for indent level 1.
protected static java.lang.String _INDENT2
          Indent string for indent level 2.
protected static java.lang.String _INDENT3
          Indent string for indent level 3.
protected  java.util.List<java.lang.String> _libraries
          List of library command line arguments where each element is a string, for example "-L/usr/local/lib".
private static int _LINES_PER_METHOD
          Maximum number of lines in initialize(), postfire() and wrapup() methodS.
protected  java.util.List<java.lang.String> _macros
          A static list of all macros supported by the code generator.
protected  CompositeEntity _model
          The model we for which we are generating code.
protected  java.util.Set _modifiedVariables
          A set that contains all variables in the model whose values can be changed during execution.
protected  java.util.HashSet<java.lang.String> _newTypesUsed
          A HashSet that contains all codegen types referenced in the model.
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 _postfireCode
          The postfire code.
protected static java.util.List _primitiveTypes
          A list of the primitive types supported by the code generator.
protected  java.lang.String _sanitizedModelName
          The sanitized model name.
protected  java.util.Set<java.lang.String> _tokenFuncUsed
          A set that contains all token functions referenced in the model.
protected  java.util.Set<java.lang.String> _typeFuncUsed
          A set that contains all type-specific functions referenced in the model.
 Parameter allowDynamicMultiportReference
          If true, then channels in multiports can be dynamically referenced using the $ref macro.
 FileParameter codeDirectory
          The directory in which to put the generated code.
 Parameter compile
          If true, then compile the generated code.
 StringParameter compileTarget
          The name of compile target to be run if the compile parameter is true.
 Parameter generateComment
          If true, generate comments in the output code; otherwise, no comments is generated.
 Parameter generateCpp
          If true, the generated code will be C++ instead of C.
 Parameter generateEmbeddedCode
          If true, then generate code for that uses the reflection for Java and JNI for C and is embedded within the model The default value is false and this parameter is not usually editable by the user.
 StringParameter generatorPackage
          The name of the package in which to look for helper class code generators.
 Parameter inline
          If true, generate file with no functions.
 Parameter measureTime
          If true, generate code to meausre the execution time.
 Parameter overwriteFiles
          If true, overwrite preexisting files.
 Parameter padBuffers
          If true, then buffers are padded to powers of two.
 Parameter run
          If true, then run the generated code.
 Parameter sourceLineBinding
          If true, then the generated source is bound to the line number and file of the (helper) templates.
 StringParameter target
          The hardware target for code generation.
 
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
CodeGenerator(NamedObj container, java.lang.String name)
          Create a new instance of the code generator.
 
Method Summary
protected  void _addActorIncludeDirectories()
          Add include directories specified by the actors in this model.
protected  void _addActorLibraries()
          Add libraries specified by the actors in this model.
protected  void _analyzeTypeConversions()
          Analyze the model to find out what connections need to be type converted.
protected  java.io.File _codeDirectoryAsFile()
          Return the value of the codeDirectory parameter.
protected  int _executeCommands()
          Execute the compile and run commands in the codeDirectory directory.
protected  java.lang.StringBuffer _finalPassOverCode(java.lang.StringBuffer code)
          Make a final pass over the generated code.
protected  java.lang.String _generateBodyCode()
          Generate the body code that lies between variable declaration and wrapup.
private  int _generateCode(java.lang.StringBuffer code)
          Generate code and append it to the given string buffer.
protected  java.lang.String _generateIncludeFiles()
          Generate include files.
protected  java.lang.String _generatePreinitializeCode()
          Generate preinitialize code (if there is any).
protected  java.lang.String _generateSharedCode()
          Generate code shared by actors, including globally defined data struct types and static methods or variables shared by multiple instances of the same actor type.
private static java.lang.Class _getCodeGeneratorClass(java.lang.String generatorPackageValue)
          Get the code generator associated with the generatePackage parameter.
protected  ActorCodeGenerator _getHelper(NamedObj component)
          Get the code generator helper associated with the given component.
protected  java.lang.Object _getHelper(java.lang.Object object)
          Get the code generator helper associated with the given object.
private  ActorCodeGenerator _getTargetHelper(NamedObj component)
          Get the code generator helper associated with target, if any.
private  ActorCodeGenerator _instantiateHelper(java.lang.Object component, java.lang.Class componentClass, java.lang.String helperClassName)
          Instantiate the given code generator helper.
private  ActorCodeGenerator _instantiateHelper(java.lang.Object component, java.lang.String helperClassName)
           
private  java.lang.String _prettyPrint(java.lang.String line, java.lang.String blockBegin, java.lang.String blockEnd)
          Pretty print the given line by indenting the line with the current indent level.
protected  java.lang.String _printExecutionTime()
          Generate the code for printing the execution time since the code generated by _recordStartTime() was called.
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  java.lang.String _recordStartTime()
          Generate the code for recording the current time.
private  void _sandboxVariableCheck(IllegalActionException ex)
           
private  java.lang.String[] _splitBody(java.lang.String prefix, java.lang.String code)
          Split the code.
private  void _updateParameters(NamedObj model)
          Set the parameters in the model stored in _parameterNames to the values given by _parameterValues.
private  void _updateTarget()
          Update the target parameter choices from the directory named by the generatorPackage parameter.
protected 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  void _writeMakefile()
          Create a make file to compile the generated code file(s).
 void addInclude(java.lang.String includeCommand)
          Add an include command line argument the compile command.
 void addLibrary(java.lang.String libraryCommand)
          Add a library command line argument the compile command.
 void addLibraryIfNecessary(java.lang.String libraryCommand)
          If the compile command does not yet containe a library, add a library command line argument the compile command.
 void attributeChanged(Attribute attribute)
          If the attribute is the codeDirectory parameter, then set the base directory of the codeDirectory parameter.
 java.lang.String codeGenType(Type ptType)
          Get the corresponding type in code generation from the given Ptolemy type.
 java.lang.String comment(int indentLevel, java.lang.String comment)
          Return a formatted comment containing the specified string with a specified indent level.
 java.lang.String comment(java.lang.String comment)
          Return a formatted comment containing the specified string.
static boolean containsCode(java.lang.String code)
          Return true if the input contains code.
 java.lang.String formatComment(java.lang.String comment)
          Return a formatted comment containing the specified string.
 java.lang.String generateClosingEntryCode()
          Return the closing entry code, if any.
 java.lang.String generateClosingExitCode()
          Return the closing exit code, if any.
 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.String generateFireFunctionCode()
          Generate The fire function code.
 java.lang.Object generateFunctionTable(java.lang.Object[] types, java.lang.Object[] functions)
          Generate the function table.
 java.lang.String generateInitializeCode()
          Return the code associated with initialization of the containing composite actor.
 java.lang.String generateInitializeEntryCode()
          Generate the initialization procedure entry point.
 java.lang.String generateInitializeExitCode()
          Generate the initialization procedure exit point.
 java.lang.String generateInitializeProcedureName()
          Generate the initialization procedure name.
 java.lang.String generateLineInfo(int lineNumber, java.lang.String filename)
          Generate line number and file name information.
 java.lang.String generateMainEntryCode()
          Generate the main entry point.
 java.lang.String generateMainExitCode()
          Generate the main exit point.
 java.lang.String generatePostfireCode()
          Generate into the specified code stream the code associated with postfiring up the container composite actor.
 java.lang.String generatePostfireEntryCode()
          Generate the postfire procedure entry point.
 java.lang.String generatePostfireExitCode()
          Generate the postfire procedure exit point.
 java.lang.String generatePostfireProcedureName()
          Generate the postfire procedure name.
 java.lang.String generateTypeConvertCode()
          Generate type conversion code.
 java.lang.String generateVariableDeclaration()
          Generate variable declarations for inputs and outputs and parameters.
 java.lang.String generateVariableInitialization()
          Generate variable initialization for the referenced parameters.
 java.lang.String generateVariableName(NamedObj attribute)
          Generate variable name for the given attribute.
 java.lang.String generateWrapupCode()
          Generate into the specified code stream the code associated with wrapping up the container composite actor.
 java.lang.String generateWrapupEntryCode()
          Generate the wrapup procedure entry point.
 java.lang.String generateWrapupExitCode()
          Generate the wrapup procedure exit point.
 java.lang.String generateWrapupProcedureName()
          Generate the wrapup procedure name.
 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.util.List getMacros()
          Return a list of macros this code generator supports.
 java.util.Set getModifiedVariables()
          Return the set of modified variables.
 java.lang.String getOutputFilename()
          Return the name of the output file.
 boolean isPrimitive(java.lang.String cgType)
          Determine if the given type is primitive.
 boolean isPrimitive(Type ptType)
          Determine if the given type is primitive.
 boolean isTopLevel()
          Test if the containing actor is in the top level.
static void main(java.lang.String[] args)
          Generate code for a model.
static boolean parseArg(java.lang.String arg)
          Parse a command-line argument.
static Type ptolemyType(java.lang.String cgType)
          Return the Ptolemy type that corresponds to the type named by the argument.
 void reset()
          Reset the code generator.
 void setCodeGenerator(CodeGenerator codeGenerator)
          This method is used to set the code generator for a helper 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.
 java.lang.String[] splitLongBody(int linesPerMethod, java.lang.String prefix, java.lang.String code)
          Split a long function body into multiple functions.
 java.lang.String targetType(Type ptType)
          Get the corresponding type in C from the given Ptolemy type.
 
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
 

Field Detail

allowDynamicMultiportReference

public Parameter allowDynamicMultiportReference
If true, then channels in multiports can be dynamically referenced using the $ref macro. TODO: This parameter is SDF specific.


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


compile

public Parameter compile
If true, then compile the generated code. The default value is a parameter with the value true.


compileTarget

public StringParameter compileTarget
The name of compile target to be run if the compile parameter is true. This is a string with a default value of the empty string, which means the first target in the makefile would be run.


generateComment

public Parameter generateComment
If true, generate comments in the output code; otherwise, no comments is generated. The default value is a parameter with the value true.


generateCpp

public Parameter generateCpp
If true, the generated code will be C++ instead of C. FIXME: This is a temporary fix. In the long run, C++ should be its own target language for code generation. In the short run, this parameter will allow experimentation with C++ code generation, and should identify changes needed for correctly implemented C++ code generation.


generatorPackage

public StringParameter generatorPackage
The name of the package in which to look for helper class code generators. This is a string that defaults to "ptolemy.codegen.c".


generateEmbeddedCode

public Parameter generateEmbeddedCode
If true, then generate code for that uses the reflection for Java and JNI for C and is embedded within the model The default value is false and this parameter is not usually editable by the user. This parameter is set to true when CompiledCompositeActor is run in an interpreted Ptolemy model. This parameter is set to false when a model contains one or more CompiledCompositeActors and C or Java code is being generated for the model.


inline

public Parameter inline
If true, generate file with no functions. If false, generate file with functions. The default value is a parameter with the value false.


measureTime

public Parameter measureTime
If true, generate code to meausre the execution time. The default value is a parameter with the value false.


overwriteFiles

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


padBuffers

public Parameter padBuffers
If true, then buffers are padded to powers of two. TODO: This parameter is SDF specific.


run

public Parameter run
If true, then run the generated code. The default value is a parameter with the value true.


sourceLineBinding

public Parameter sourceLineBinding
If true, then the generated source is bound to the line number and file of the (helper) templates. Otherwise, the source is bound only to the output file. This is a boolean parameter with default value false.


target

public StringParameter target
The hardware target for code generation. The list of possible choices is generated from the list of directories in the targets subdirectory of the directory named by the generatorPackage parameter. For example, if generatorPackage is ptolemy.codegen.c, and if $PTII/ptolemy/codegen/c/targets/ exists and contains an iRobot/ directory, and this parameter is set to iRobot, then files from $PTII/ptolemy/codegen/c/targets/iRobot will be used to generate code. The default value is the string "default" which means that the default target for the language is used.


_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

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


_commandOptions

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


_commandTemplate

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

See Also:
Constant Field Values

_DEFAULT_TARGET

protected static final java.lang.String _DEFAULT_TARGET
The default target name.

See Also:
Constant Field Values

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


_libraries

protected java.util.List<java.lang.String> _libraries
List of library command line arguments where each element is a string, for example "-L/usr/local/lib". This variable is a list so as to preserve the order that the library commands were added to the list of libraries matters, see the manual page for the -L option of the ld command.


_INDENT1

protected static final java.lang.String _INDENT1
Indent string for indent level 1.

See Also:
StringUtilities.getIndentPrefix(int)

_INDENT2

protected static final java.lang.String _INDENT2
Indent string for indent level 2.

See Also:
StringUtilities.getIndentPrefix(int)

_INDENT3

protected static final java.lang.String _INDENT3
Indent string for indent level 3.

See Also:
StringUtilities.getIndentPrefix(int)

_includes

protected java.util.Set<java.lang.String> _includes
Set of include command line arguments where each element is a string, for example "-I/usr/local/include".


_model

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


_modifiedVariables

protected java.util.Set _modifiedVariables
A set that contains all variables in the model whose values can be changed during execution.


_newTypesUsed

protected java.util.HashSet<java.lang.String> _newTypesUsed
A HashSet that contains all codegen types referenced in the model. When the codegen kernel processes a $new() macro, it would add the codegen type to this set. Codegen types are supported by the code generator package. (e.g. Int, Double, Array, and etc.)


_macros

protected java.util.List<java.lang.String> _macros
A static list of all macros supported by the code generator.


_primitiveTypes

protected static java.util.List _primitiveTypes
A list of the primitive types supported by the code generator.


_postfireCode

protected java.lang.String _postfireCode
The postfire code.


_sanitizedModelName

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


_tokenFuncUsed

protected java.util.Set<java.lang.String> _tokenFuncUsed
A set that contains all token functions referenced in the model. When the codegen kernel processes a $tokenFunc() macro, it must add the token function to this set.


_typeFuncUsed

protected java.util.Set<java.lang.String> _typeFuncUsed
A set that contains all type-specific functions referenced in the model. When the codegen kernel processes a $typeFunc() macro, it must add the type function to this set. Only those functions that are added to this set will be included in the generated code.


_helperStore

private java.util.Map _helperStore
A map giving the code generator helpers for each actor.


_indent

private int _indent
The current indent level when pretty printing code.


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


_LINES_PER_METHOD

private static int _LINES_PER_METHOD
Maximum number of lines in initialize(), postfire() and wrapup() methodS. This variable is used to make smaller methods so that compilers take less time.

Constructor Detail

CodeGenerator

public CodeGenerator(NamedObj container,
                     java.lang.String name)
              throws IllegalActionException,
                     NameDuplicationException
Create a new instance of the code generator.

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.
Method Detail

_generateCode

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

addInclude

public void addInclude(java.lang.String includeCommand)
Add an include command line argument the compile command.

Parameters:
includeCommand - The include command, for example "-I/usr/local/include".

addLibrary

public void addLibrary(java.lang.String libraryCommand)
Add a library command line argument the compile command.

Parameters:
libraryCommand - The library command, for example "-L/usr/local/lib".
See Also:
addLibraryIfNecessary(String)

addLibraryIfNecessary

public void addLibraryIfNecessary(java.lang.String libraryCommand)
If the compile command does not yet containe a library, add a library command line argument the compile command.

Parameters:
libraryCommand - The library command, for example "-L/usr/local/lib".
See Also:
addLibrary(String)

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.

codeGenType

public java.lang.String codeGenType(Type ptType)
Get the corresponding type in code generation from the given Ptolemy type.

Parameters:
ptType - The given Ptolemy type.
Returns:
The code generation type.
Throws:
IllegalActionException - Thrown if the given ptolemy cannot be resolved.

comment

public java.lang.String comment(int indentLevel,
                                java.lang.String comment)
Return a formatted comment containing the specified string with a specified indent level.

Parameters:
comment - The string to put in the comment.
indentLevel - The indentation level.
Returns:
A formatted comment.

comment

public java.lang.String comment(java.lang.String comment)
Return a formatted comment containing the specified string. In this base class, the comments is a C-style comment, which begins with "\/*" and ends with "*\/".

Parameters:
comment - The string to put in the comment.
Returns:
A formatted comment.

formatComment

public java.lang.String formatComment(java.lang.String comment)
Return a formatted comment containing the specified string. In this base class, the comments is a C-style comment, which begins with "\/*" and ends with "*\/" followed by the platform dependent end of line character(s): under Unix: "\n", under Windows: "\n\r". Subclasses may override this produce comments that match the code generation language.

Parameters:
comment - The string to put in the comment.
Returns:
A formatted comment.

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.

generateClosingEntryCode

public java.lang.String generateClosingEntryCode()
Return the closing entry code, if any.

Returns:
the closing entry code.

generateClosingExitCode

public java.lang.String generateClosingExitCode()
Return the closing exit code, if any.

Returns:
the closing exit code.

generateCopyright

public java.lang.String generateCopyright()
Return the copyright for this code.

Returns:
The copyright.

generateFireFunctionCode

public java.lang.String generateFireFunctionCode()
                                          throws IllegalActionException
Generate The fire function code. This method is called when the firing code of each actor is not inlined. Each actor's firing code is in a function with the same name as that of the actor.

Returns:
The fire function code of the containing composite actor.
Throws:
IllegalActionException - If thrown while generating fire code.

generateFunctionTable

public java.lang.Object generateFunctionTable(java.lang.Object[] types,
                                              java.lang.Object[] functions)
Generate the function table. In this base class return the empty string.

Parameters:
types - An array of types.
functions - An array of functions.
Returns:
The code that declares functions.

generateInitializeCode

public java.lang.String generateInitializeCode()
                                        throws IllegalActionException
Return the code associated with initialization of the containing composite actor. This method calls the generateInitializeCode() method of the code generator helper associated with the model director.

Specified by:
generateInitializeCode in interface ComponentCodeGenerator
Returns:
The initialize code of the containing composite actor.
Throws:
IllegalActionException - If the helper class for the model director cannot be found or if an error occurs when the director helper generates initialize code.

generateInitializeEntryCode

public java.lang.String generateInitializeEntryCode()
                                             throws IllegalActionException
Generate the initialization procedure entry point.

Returns:
a string for the initialization procedure entry point.
Throws:
IllegalActionException - Not thrown in this base class.

generateInitializeExitCode

public java.lang.String generateInitializeExitCode()
                                            throws IllegalActionException
Generate the initialization procedure exit point.

Returns:
a string for the initialization procedure exit point.
Throws:
IllegalActionException - Not thrown in this base class.

generateInitializeProcedureName

public java.lang.String generateInitializeProcedureName()
                                                 throws IllegalActionException
Generate the initialization procedure name.

Returns:
a string for the initialization procedure name.
Throws:
IllegalActionException - Not thrown in this base class.

generateLineInfo

public java.lang.String generateLineInfo(int lineNumber,
                                         java.lang.String filename)
Generate line number and file name information.

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:
In this base class, return the empty string.

generateMainEntryCode

public java.lang.String generateMainEntryCode()
                                       throws IllegalActionException
Generate the main entry point.

Returns:
Return the definition of the main entry point for a program.
Throws:
IllegalActionException - Not thrown in this base class.

generateMainExitCode

public java.lang.String generateMainExitCode()
                                      throws IllegalActionException
Generate the main exit point.

Returns:
Return a string that declares the end of the main() function.
Throws:
IllegalActionException - Not thrown in this base class.

generatePostfireCode

public java.lang.String generatePostfireCode()
                                      throws IllegalActionException
Generate into the specified code stream the code associated with postfiring up the container composite actor. This method calls the generatePostfireCode() method of the code generator helper associated with the director of this container.

Returns:
The postfire code of the containing composite actor.
Throws:
IllegalActionException - If the helper class for the model director cannot be found.

generatePostfireEntryCode

public java.lang.String generatePostfireEntryCode()
                                           throws IllegalActionException
Generate the postfire procedure entry point.

Returns:
a string for the postfire procedure entry point.
Throws:
IllegalActionException - Not thrown in this base class.

generatePostfireExitCode

public java.lang.String generatePostfireExitCode()
                                          throws IllegalActionException
Generate the postfire procedure exit point.

Returns:
a string for the postfire procedure exit point.
Throws:
IllegalActionException - Not thrown in this base class.

generatePostfireProcedureName

public java.lang.String generatePostfireProcedureName()
                                               throws IllegalActionException
Generate the postfire procedure name.

Returns:
a string for the postfire procedure name.
Throws:
IllegalActionException - Not thrown in this base class.

generateTypeConvertCode

public java.lang.String generateTypeConvertCode()
                                         throws IllegalActionException
Generate type conversion code.

Returns:
The type conversion code.
Throws:
IllegalActionException - If an error occurrs when generating the type conversion code, or if the helper class for the model director cannot be found, or if an error occurs when the helper actor generates the type conversion code.

generateVariableDeclaration

public java.lang.String generateVariableDeclaration()
                                             throws IllegalActionException
Generate variable declarations for inputs and outputs and parameters. Append the declarations to the given string buffer.

Returns:
code The generated code.
Throws:
IllegalActionException - If the helper class for the model director cannot be found.

generateVariableInitialization

public java.lang.String generateVariableInitialization()
                                                throws IllegalActionException
Generate variable initialization for the referenced parameters.

Returns:
code The generated code.
Throws:
IllegalActionException - If the helper class for the model director cannot be found.

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.

Parameters:
attribute - The attribute to generate variable name for.
Returns:
The generated variable name.

generateWrapupCode

public java.lang.String generateWrapupCode()
                                    throws IllegalActionException
Generate into the specified code stream the code associated with wrapping up the container composite actor. This method calls the generateWrapupCode() method of the code generator helper associated with the director of this container.

Specified by:
generateWrapupCode in interface ComponentCodeGenerator
Returns:
The wrapup code of the containing composite actor.
Throws:
IllegalActionException - If the helper class for the model director cannot be found.

generateWrapupEntryCode

public java.lang.String generateWrapupEntryCode()
                                         throws IllegalActionException
Generate the wrapup procedure entry point.

Returns:
a string for the wrapup procedure entry point.
Throws:
IllegalActionException - Not thrown in this base class.

generateWrapupExitCode

public java.lang.String generateWrapupExitCode()
                                        throws IllegalActionException
Generate the wrapup procedure exit point.

Returns:
a string for the wrapup procedure exit point.
Throws:
IllegalActionException - Not thrown in this base class.

generateWrapupProcedureName

public java.lang.String generateWrapupProcedureName()
                                             throws IllegalActionException
Generate the wrapup procedure name.

Returns:
a string for the wrapup procedure name.
Throws:
IllegalActionException - Not thrown in this base class.

getCodeFileName

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

Specified by:
getComponent in interface ComponentCodeGenerator
Returns:
The helper to generate code.

getExecuteCommands

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

getMacros

public java.util.List getMacros()
Return a list of macros this code generator supports.

Returns:
Returns the _macros.

getModifiedVariables

public java.util.Set getModifiedVariables()
                                   throws IllegalActionException
Return the set of modified variables.

Returns:
The set of modified variables.
Throws:
IllegalActionException - Not thrown in this base class.

getOutputFilename

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

isPrimitive

public boolean isPrimitive(java.lang.String cgType)
Determine if the given type is primitive.

Parameters:
cgType - The given codegen type.
Returns:
true if the given type is primitive, otherwise false.

isPrimitive

public boolean isPrimitive(Type ptType)
Determine if the given type is primitive.

Parameters:
ptType - The given ptolemy type.
Returns:
true if the given type is primitive, otherwise false.

isTopLevel

public boolean isTopLevel()
Test if the containing actor is in the top level.

Returns:
true if the containing actor is in the top level.

ptolemyType

public static Type ptolemyType(java.lang.String cgType)
Return the Ptolemy type that corresponds to the type named by the argument.

Parameters:
cgType - A String naming a type.
Returns:
null if there is not corresponding Ptolemy type.

reset

public void reset()
Reset the code generator.


setCodeGenerator

public void setCodeGenerator(CodeGenerator codeGenerator)
This method is used to set the code generator for a helper class. Since this is not a helper class for a component, this method does nothing.

Specified by:
setCodeGenerator in interface ComponentCodeGenerator
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()

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

In this base class, since we don't know what the target language will be, the first element is the empty string, the second element is the code argument.

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 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. In this base class, the first element is always the empty string and the second element is the value of the code parameter.
Throws:
java.io.IOException - If thrown will reading the code.

targetType

public java.lang.String targetType(Type ptType)
Get the corresponding type in C from the given Ptolemy type.

Parameters:
ptType - The given Ptolemy type.
Returns:
The C data type.

_addActorIncludeDirectories

protected void _addActorIncludeDirectories()
                                    throws IllegalActionException
Add include directories specified by the actors in this model.

Throws:
IllegalActionException - Never in this base class.

_addActorLibraries

protected void _addActorLibraries()
                           throws IllegalActionException
Add libraries specified by the actors in this model.

Throws:
IllegalActionException - Never in this base class.

_analyzeTypeConversions

protected void _analyzeTypeConversions()
                                throws IllegalActionException
Analyze the model to find out what connections need to be type converted. This should be called before all the generate methods.

Throws:
IllegalActionException - If the helper of the top composite actor is unavailable.

_codeDirectoryAsFile

protected java.io.File _codeDirectoryAsFile()
                                     throws java.io.IOException,
                                            IllegalActionException
Return the value of the codeDirectory parameter.

Returns:
The value of the codeDirectory parameter.
Throws:
java.io.IOException - If the codeDirectory parameter names a file or a directory cannot be created.
IllegalActionException - If thrown while reading the codeDirectory parameter.

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

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

Parameters:
code - The given code to be processed.
Returns:
The processed code.
Throws:
IllegalActionException - If #getOutputFilename() throws it.

_generateBodyCode

protected java.lang.String _generateBodyCode()
                                      throws IllegalActionException
Generate the body code that lies between variable declaration and wrapup. This method delegates to the director helper to generate a main loop.

Returns:
The generated body code.
Throws:
IllegalActionException - If there is no director.

_generateIncludeFiles

protected java.lang.String _generateIncludeFiles()
                                          throws IllegalActionException
Generate include files. This base class just returns an empty string.

Returns:
The include files.
Throws:
IllegalActionException - If the helper class for some actor cannot be found.

_generatePreinitializeCode

protected java.lang.String _generatePreinitializeCode()
                                               throws IllegalActionException
Generate preinitialize code (if there is any). This method calls the generatePreinitializeCode() method of the code generator helper associated with the enclosing composite actor.

Returns:
The preinitialize code of the containing composite actor.
Throws:
IllegalActionException - If the helper class for the model director cannot be found, or if an error occurs when the director helper generates preinitialize code.

_generateSharedCode

protected java.lang.String _generateSharedCode()
                                        throws IllegalActionException
Generate code shared by actors, including globally defined data struct types and static methods or variables shared by multiple instances of the same actor type.

Returns:
The shared code of the containing composite actor.
Throws:
IllegalActionException - If an error occurrs when generating the globally shared code, or if the helper class for the model director cannot be found, or if an error occurs when the helper actor generates the shared code.

_getHelper

protected ActorCodeGenerator _getHelper(NamedObj component)
                                 throws IllegalActionException
Get the code generator helper associated with the given component.

Parameters:
component - The given component.
Returns:
The code generator helper.
Throws:
IllegalActionException - If the helper class cannot be found.

_getHelper

protected java.lang.Object _getHelper(java.lang.Object object)
                               throws IllegalActionException
Get the code generator helper associated with the given object.

Parameters:
object - The given object.
Returns:
The code generator helper.
Throws:
IllegalActionException - If the helper class cannot be found.

_printExecutionTime

protected java.lang.String _printExecutionTime()
Generate the code for printing the execution time since the code generated by _recordStartTime() was called. This base class only generates a comment.

Returns:
Return the code for printing the total execution time.

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

_recordStartTime

protected java.lang.String _recordStartTime()
Generate the code for recording the current time. This base class only generates a comment.

Returns:
Return the code for recording 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.

_writeMakefile

protected void _writeMakefile()
                       throws IllegalActionException
Create a make file to compile the generated code file(s). In this base class, it does nothing.

Throws:
IllegalActionException - Not thrown in this base class.

_getTargetHelper

private ActorCodeGenerator _getTargetHelper(NamedObj component)
                                     throws IllegalActionException
Get the code generator helper associated with target, if any.

Parameters:
component - The given component.
Returns:
The code generator helper.
Throws:
IllegalActionException - If the helper class cannot be found.

_instantiateHelper

private ActorCodeGenerator _instantiateHelper(java.lang.Object component,
                                              java.lang.String helperClassName)
                                       throws IllegalActionException
Throws:
IllegalActionException

_instantiateHelper

private ActorCodeGenerator _instantiateHelper(java.lang.Object component,
                                              java.lang.Class componentClass,
                                              java.lang.String helperClassName)
                                       throws IllegalActionException
Instantiate the given code generator helper.

Parameters:
component - The given component.
helperClassName - The dot separated name of the helper.
Returns:
The code generator helper.
Throws:
IllegalActionException - If the helper class cannot be found.

_prettyPrint

private java.lang.String _prettyPrint(java.lang.String line,
                                      java.lang.String blockBegin,
                                      java.lang.String blockEnd)
Pretty print the given line by indenting the line with the current indent level. If a block begin symbol is found, the indent level is incremented. Similarly, the indent level is decremented if a block end symbol is found.

Parameters:
line - The given line of code.
blockBegin - The given block begin symbol to match.
blockEnd - The given block end symbol to match.
Returns:
The pretty-printed version of the given code line.

_splitBody

private java.lang.String[] _splitBody(java.lang.String prefix,
                                      java.lang.String code)
Split the code.


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

_updateTarget

private void _updateTarget()
                    throws IllegalActionException
Update the target parameter choices from the directory named by the generatorPackage parameter. All the choices are removed the choice "default" is added and then the names of all directories in the directory named by generatorPackage/targets (except the CVS directory are added as choices.

Throws:
IllegalActionException - If the generatorPackage attribute cannot be read.

containsCode

public static boolean containsCode(java.lang.String code)
Return true if the input contains code. In this context, code is considered to be anything other than comments and whitespace.

Parameters:
code - The string to check for code.
Returns:
True if the string contains anything other than white space or comments

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.

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.

parseArg

public 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

protected 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 helper class cannot be found.

_sandboxVariableCheck

private void _sandboxVariableCheck(IllegalActionException ex)
                            throws IllegalActionException
Throws:
IllegalActionException