ptolemy.codegen.c.kernel
Class CCodeGenerator

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

public class CCodeGenerator
extends CodeGenerator

Base class for C code generator.

Since:
Ptolemy II 6.0
Version:
$Id: CCodeGenerator.java 59247 2010-09-24 18:49:42Z cxh $
Author:
Gang Zhou
See Also:
Serialized Form
Accepted Rating:
red (zgang)
Proposed Rating:
red (zgang)

Nested Class Summary
 
Nested classes/interfaces inherited from class ptolemy.kernel.util.NamedObj
NamedObj.ContainedObjectsIterator
 
Field Summary
private  CodeStream _overloadedFunctions
           
(package private)  java.util.LinkedHashSet<java.lang.String> _overloadedFunctionSet
          An ordered set of function code
private static java.util.Set _scalarDeleteTypes
          Types that share the scalarDelete() method, which does nothing.
private static java.util.Set _unsupportedTypeFunctions
          Set of type/function combinations that are not supported.
 
Fields inherited from class ptolemy.codegen.kernel.CodeGenerator
_codeFileName, _commandFlags, _commandOptions, _commandTemplate, _DEFAULT_TARGET, _eol, _executeCommands, _includes, _INDENT1, _INDENT2, _INDENT3, _libraries, _macros, _model, _modifiedVariables, _newTypesUsed, _postfireCode, _primitiveTypes, _sanitizedModelName, _tokenFuncUsed, _typeFuncUsed, allowDynamicMultiportReference, codeDirectory, compile, compileTarget, generateComment, generateCpp, generateEmbeddedCode, generatorPackage, inline, measureTime, overwriteFiles, padBuffers, run, sourceLineBinding, target
 
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
CCodeGenerator(NamedObj container, java.lang.String name)
          Create a new instance of the C 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.
private static java.lang.String _concatenateElements(java.util.Collection collection)
          Given a Collection of Strings, return a string where each element of the Set is separated by a space.
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 _generateIncludeFiles()
          Generate include files.
private  java.util.HashSet _getNewTypesUsed(java.util.HashSet functions)
          Return the new types used by the given set of functions.
private  java.util.HashSet _getReferencedFunctions()
          Return the set of referenced functions.
private  java.util.HashSet<java.lang.String> _getTypeIDToUsed(java.util.HashSet<java.lang.String> types)
           
 boolean _hasPlaceable()
          Return true if the model contains a Placeable.
protected  java.lang.String _printExecutionTime()
          Generate the code for printing the execution time since the code generated by _recordStartTime() was called.
protected  java.lang.String _recordStartTime()
          Generate the code for recording the current time.
protected  void _writeMakefile()
          Read in a template makefile, substitute variables and write the resulting makefile.
 java.lang.Object generateFunctionTable(java.lang.Object[] types, java.lang.Object[] functions)
          Generate the function table.
 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 information.
 java.lang.String generateMainEntryCode()
          Generate the main entry point.
 java.lang.String generateMainExitCode()
          Generate the main exit point.
 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 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.
 void markFunctionCalled(java.lang.String name, CCodeGeneratorHelper helper)
          Add called functions to the set of overloaded functions for later use.
 java.lang.String processCode(java.lang.String code)
          Process the specified code for the helper associated with the container.
 java.lang.String[] splitLongBody(int linesPerMethod, java.lang.String prefix, java.lang.String code)
          Split a long function body into multiple functions.
 
Methods inherited from class ptolemy.codegen.kernel.CodeGenerator
_codeDirectoryAsFile, _generateBodyCode, _generatePreinitializeCode, _generateSharedCode, _getHelper, _getHelper, _printTimeAndMemory, _usage, _writeCode, addInclude, addLibrary, addLibraryIfNecessary, attributeChanged, codeGenType, comment, comment, containsCode, formatComment, generateClosingEntryCode, generateClosingExitCode, generateCode, generateCode, generateCode, generateCopyright, generateFireFunctionCode, generateInitializeCode, generatePostfireCode, generateVariableName, generateWrapupCode, getCodeFileName, getComponent, getExecuteCommands, getMacros, getModifiedVariables, getOutputFilename, isPrimitive, isPrimitive, isTopLevel, main, parseArg, ptolemyType, reset, setCodeGenerator, setContainer, setExecuteCommands, targetType
 
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

_overloadedFunctions

private CodeStream _overloadedFunctions

_overloadedFunctionSet

java.util.LinkedHashSet<java.lang.String> _overloadedFunctionSet
An ordered set of function code


_unsupportedTypeFunctions

private static java.util.Set _unsupportedTypeFunctions
Set of type/function combinations that are not supported. We use one method so as to reduce code size.


_scalarDeleteTypes

private static java.util.Set _scalarDeleteTypes
Types that share the scalarDelete() method, which does nothing. We use one method so as to reduce code size.

Constructor Detail

CCodeGenerator

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

Parameters:
container - The container.
name - The name of the C 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

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.

Overrides:
generateFunctionTable in class CodeGenerator
Parameters:
types - An array of types.
functions - An array of functions.
Returns:
The code that declares functions.

generateInitializeEntryCode

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

Overrides:
generateInitializeEntryCode in class CodeGenerator
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.

Overrides:
generateInitializeExitCode in class CodeGenerator
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.

Overrides:
generateInitializeProcedureName in class CodeGenerator
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 information. In this class, lines of the format
  #line lineNumber "filename"
  
are generated for use by the C preprocessor.

Overrides:
generateLineInfo in class CodeGenerator
Parameters:
lineNumber - The line number of the source file or file containing code blocks.
filename - The name of the source file or file containing code blocks.
Returns:
text that is suitable for the C preprocessor.

generateMainEntryCode

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

Overrides:
generateMainEntryCode in class CodeGenerator
Returns:
Return the definition of the main entry point for a program. In C, this would be defining main().
Throws:
IllegalActionException - Not thrown in this base class.

generateMainExitCode

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

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

generatePostfireEntryCode

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

Overrides:
generatePostfireEntryCode in class CodeGenerator
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.

Overrides:
generatePostfireExitCode in class CodeGenerator
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.

Overrides:
generatePostfireProcedureName in class CodeGenerator
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. Determine the proper code put into the source to support dynamic type resolution. First, find out the different types used in the model. Second, find out the different polymorphic functions used. (note: types and functions are independent of each other). Third, append code blocks according to the functions used, and read from files according to the types referenced. Fourth, generate type resolution code, which consists of constants (MAX_NUM_TYPE, MAX_NUM_FUNC), the type map, the function map, function definitions read from the files, and function table.

Overrides:
generateTypeConvertCode in class CodeGenerator
Returns:
The type resolution code.
Throws:
IllegalActionException - If an error occurrs when generating the type resolution 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 resolution code.

_getTypeIDToUsed

private java.util.HashSet<java.lang.String> _getTypeIDToUsed(java.util.HashSet<java.lang.String> types)

processCode

public java.lang.String processCode(java.lang.String code)
                             throws IllegalActionException
Process the specified code for the helper associated with the container. Replace macros with their values.

Parameters:
code - The code to process.
Returns:
The processed code.
Throws:
IllegalActionException - If illegal macro names are found.

_getReferencedFunctions

private java.util.HashSet _getReferencedFunctions()
Return the set of referenced functions.

Returns:
The set of referenced functions.

_getNewTypesUsed

private java.util.HashSet _getNewTypesUsed(java.util.HashSet functions)
Return the new types used by the given set of functions.

Parameters:
functions - The set of functions used, such as "equals", "isCloseTo", and "toString".
Returns:
The new types used.

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.

Overrides:
generateVariableDeclaration in class CodeGenerator
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.

Overrides:
generateVariableInitialization in class CodeGenerator
Returns:
code The generated code.
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.

Overrides:
generateWrapupEntryCode in class CodeGenerator
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.

Overrides:
generateWrapupExitCode in class CodeGenerator
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.

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

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.

Overrides:
splitLongBody in class CodeGenerator
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.
Throws:
java.io.IOException - If thrown will reading the code.

_addActorIncludeDirectories

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

Overrides:
_addActorIncludeDirectories in class CodeGenerator
Throws:
IllegalActionException - If thrown when getting an actor's include directories.

_addActorLibraries

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

Overrides:
_addActorLibraries in class CodeGenerator
Throws:
IllegalActionException - If thrown when getting an actor's libraries.

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

Overrides:
_analyzeTypeConversions in class CodeGenerator
Throws:
IllegalActionException - If the helper of the top composite actor is unavailable.

_executeCommands

protected int _executeCommands()
                        throws IllegalActionException
Execute the compile and run commands in the codeDirectory directory.

Overrides:
_executeCommands in class CodeGenerator
Returns:
The return value of the last subprocess that was executed or -1 if no commands were executed.
Throws:
IllegalActionException - If there are problems reading parameters or executing the commands.

_finalPassOverCode

protected java.lang.StringBuffer _finalPassOverCode(java.lang.StringBuffer code)
                                             throws IllegalActionException
Make a final pass over the generated code. Subclass may extend this method to do extra processing to format the output code. If sourceLineBinding is set to true, it will check and insert the appropriate #line macro for each line in the given code. Blank lines are discarded if #line macros are inserted.

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

_generateIncludeFiles

protected java.lang.String _generateIncludeFiles()
                                          throws IllegalActionException
Generate include files. FIXME: State what is included.

Overrides:
_generateIncludeFiles in class CodeGenerator
Returns:
The #include statements, surrounded by #ifndef to ensure that the files are included only once.
Throws:
IllegalActionException - If the helper class for some actor 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.

Overrides:
_printExecutionTime in class CodeGenerator
Returns:
Return the code for printing the total execution time.

_recordStartTime

protected java.lang.String _recordStartTime()
Generate the code for recording the current time. This writes current time into a timespec struct called "start".

Overrides:
_recordStartTime in class CodeGenerator
Returns:
Return the code for recording the current time.

_writeMakefile

protected void _writeMakefile()
                       throws IllegalActionException
Read in a template makefile, substitute variables and write the resulting makefile.

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

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

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

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

The following variables are substituted

@modelName@
The sanitized model name, created by invoking StringUtilities.sanitizeName(String) on the model name.
@PTCGIncludes@
The elements of the set of include command arguments that were added by calling CodeGenerator.addInclude(String), where each element is separated by a space.
@PTCGLibraries@
The elements of the set of library command arguments that were added by calling CodeGenerator.addLibrary(String), where each element is separated by a space.

Overrides:
_writeMakefile in class CodeGenerator
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.

_concatenateElements

private static java.lang.String _concatenateElements(java.util.Collection collection)
Given a Collection of Strings, return a string where each element of the Set is separated by a space.

Parameters:
collection - The collection of elements.
Returns:
A String that contains each element of the Set separated by a space.

_hasPlaceable

public boolean _hasPlaceable()
Return true if the model contains a Placeable.

Returns:
true if the model contains a Placeable;

markFunctionCalled

public void markFunctionCalled(java.lang.String name,
                               CCodeGeneratorHelper helper)
                        throws IllegalActionException
Add called functions to the set of overloaded functions for later use. If the function starts with "Array_", add everything after the "Array_" is added to the set of token functions used.

Parameters:
name - The name of the function, for example "Double_equals"
helper - The corresponding helper that contains the codeBlock.
Throws:
IllegalActionException - If there is a problem adding a function to the set of overloaded functions.