Class CCodeGenerator
- java.lang.Object
-
- ptolemy.kernel.util.NamedObj
-
- ptolemy.kernel.util.Attribute
-
- ptolemy.cg.kernel.generic.GenericCodeGenerator
-
- ptolemy.cg.kernel.generic.RunnableCodeGenerator
-
- ptolemy.cg.kernel.generic.program.ProgramCodeGenerator
-
- ptolemy.cg.kernel.generic.program.procedural.ProceduralCodeGenerator
-
- ptolemy.cg.kernel.generic.program.procedural.c.CCodeGenerator
-
- All Implemented Interfaces:
java.lang.Cloneable
,Changeable
,Debuggable
,DebugListener
,Decorator
,Derivable
,ModelErrorHandler
,MoMLExportable
,Moveable
,Nameable
- Direct Known Subclasses:
PtidyOSCodeGenerator
public class CCodeGenerator extends ProceduralCodeGenerator
Base class for C code generator.- Since:
- Ptolemy II 10.0
- Version:
- $Id$
- Author:
- Gang Zhou, William Lucas
- Pt.AcceptedRating:
- red (wlc)
- Pt.ProposedRating:
- red (wlc)
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class ptolemy.kernel.util.NamedObj
NamedObj.ContainedObjectsIterator
-
-
Field Summary
Fields Modifier and Type Field Description Parameter
generateCpp
If true, the generated code will be C++ instead of C.-
Fields inherited from class ptolemy.cg.kernel.generic.program.procedural.ProceduralCodeGenerator
_compileCommandDefault, _includes, _libraries, compile, compileCommand, generateEmbeddedCode
-
Fields inherited from class ptolemy.cg.kernel.generic.program.ProgramCodeGenerator
_modifiedVariables, _newTypesUsed, _portTypeMap, _portTypeMap2, _portTypeMap3, _portTypeMaxIndex, _portTypeMaxIndex2, _portTypeMaxIndex3, _primitiveTypes, _runCommandDefault, _tokenFuncUsed, _typeFuncUsed, _variablesAsArrays, generateComment, inline, maximumLinesPerBlock, measureTime, sourceLineBinding, useMake, variablesAsArrays, verbosity
-
Fields inherited from class ptolemy.cg.kernel.generic.RunnableCodeGenerator
_substituteMap, run, runCommand
-
Fields inherited from class ptolemy.cg.kernel.generic.GenericCodeGenerator
_codeFileName, _eol, _executeCommands, _generateInSubdirectory, _model, _sanitizedModelName, codeDirectory, generateInSubdirectory, generatorPackage, generatorPackageList, INDENT1, INDENT2, INDENT3, overwriteFiles
-
Fields inherited from class ptolemy.kernel.util.NamedObj
_changeListeners, _changeLock, _changeRequests, _debugging, _debugListeners, _deferChangeRequests, _elementName, _isPersistent, _verbose, _workspace, ATTRIBUTES, CLASSNAME, COMPLETE, CONTENTS, DEEP, FULLNAME, LINKS
-
-
Constructor Summary
Constructors Constructor Description CCodeGenerator(NamedObj container, java.lang.String name)
Create a new instance of the C code generator.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description protected void
_addActorIncludeDirectories(NamedProgramCodeGeneratorAdapter adapter)
Add include directories specified by the actors in this model.protected void
_addActorLibraries(NamedProgramCodeGeneratorAdapter adapter)
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.lang.StringBuffer
_finalPassOverCode(java.lang.StringBuffer code)
Make a final pass over the generated code.protected void
_generateAndWriteActorCode(NamedObj actor, NamedProgramCodeGeneratorAdapter directorAdapter, CompositeEntity container, java.lang.String directory)
Generate and write the code for an actor.protected void
_generateAndWriteCompositeActorCode(CompositeEntity container, java.lang.String containerDirectory)
Generate and write the code for a composite actor.protected java.lang.String
_generateBodyCode()
Generate the body code that lies between variable declaration and wrapup.protected int
_generateCode(java.lang.StringBuffer code)
Generate code and append it to the given string buffer.protected java.lang.String
_generateConstructorCode(Actor actor)
Generate the code for a constructor.protected java.lang.String
_generateConstructorCode(CompositeActor actor)
Generate the code for a constructor.protected java.lang.String
_generateDeclareSharedCode()
Generate the declarations of the code shared by actors, including globally defined data struct types and static methods or variables shared by multiple instances of the same actor type.protected java.lang.String
_generateIncludeFiles(NamedProgramCodeGeneratorAdapter actorAdapter)
Generate include files.protected java.lang.String
_generatePortsAccessorsCode(Actor actor)
Generate the code to access ports for an actor.protected java.lang.String
_generatePortsAccessorsCode(CompositeActor actor)
Generate the code to access ports for a composite actor.protected java.lang.String
_generatePortsAccessorsDeclaration(Actor actor)
Generate the code to declare the accessors to ports.protected java.lang.String
_generatePortsAccessorsDeclaration(CompositeActor actor)
Generate the code to declare the accessors to ports.protected java.lang.String
_getFireFunctionArguments()
Return the prototype for fire functions.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 java.lang.Class<? extends TemplateParser>
_templateParserClass()
Return the class of the templateParser class.protected void
_writeMakefile(CompositeEntity container, java.lang.String currentDirectory)
Read in a template makefile, substitute variables and write the resulting makefile.java.lang.Object
clone(Workspace workspace)
Clone the actor into the specified workspace.java.lang.String
generateClosingEntryCode()
Return the closing entry code, if any.java.lang.String
generateClosingExitCode()
Return the closing exit code, if any.java.lang.String
generateConstantDefinition(java.lang.String constant, java.lang.String type, java.lang.String value)
Generate code that defines a constant.java.lang.String
generateFireFunctionMethodName(NamedObj namedObj)
Generate the fire function method name.java.lang.String
generateFunctionTable(java.lang.String[] types, java.lang.String[] 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[]
generateTypeConvertCodeCandH()
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.java.lang.String
getModelName()
Generate the model name.boolean
invokeGenerateUpdatePortOffsets()
Return true if StaticSchedulingDirector should invoke generateUpdatePortOffsets.void
markFunctionCalled(java.lang.String name, ProceduralTemplateParser templateParser)
Add called functions to the set of overloaded functions for later use.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.cg.kernel.generic.program.procedural.ProceduralCodeGenerator
_concatenateElements, _executeCommands, _reset, addInclude, addLibrary, addLibraryIfNecessary
-
Methods inherited from class ptolemy.cg.kernel.generic.program.ProgramCodeGenerator
_addActorIncludeDirectories, _addActorLibraries, _codeDirectoryAsFile, _formatComment, _generateIncludeFiles, _generatePreinitializeCode, _generatePreinitializeMethodBodyCode, _generatePreinitializeMethodEntryCode, _generatePreinitializeMethodExitCode, _generatePreinitializeMethodProcedureName, _generateSharedCode, _instantiateAdapter, _setupAdapter, _splitBody, _splitVariableDeclaration, _writeVariableDeclarations, addModifiedVariables, attributeChanged, codeGenType, comment, comment, containsCode, generateFireFunctionCode, generateFireFunctionCompositeEnd, generateFireFunctionCompositeStart, generateFireFunctionMethodInvocation, generateFireFunctionVariableAndMethodName, generateFireFunctionVariableDeclaration, generateInitializeCode, generatePackageStatement, generatePortName, generatePostfireCode, generatePtIOPortName, generatePtIOPortSize, generatePtTypedCompositeActorName, generatePtTypedCompositeActorSize, generateTypeConvertCode, generateVariableName, generateWrapupCode, getModifiedVariables, getTemplateExtension, isPrimitive, isPrimitive, ptolemyType, setModifiedVariables, splitVariableDeclaration, targetType, updateCommandOptions
-
Methods inherited from class ptolemy.cg.kernel.generic.RunnableCodeGenerator
_runCommand, _setupCommands, _updateSubstituteMap
-
Methods inherited from class ptolemy.cg.kernel.generic.GenericCodeGenerator
_copyCFilesTosrc, _copyCFileTosrc, _getAdapter, _getAdapterClassFilter, _getAutoGeneratedAdapter, _getOutputFilename, _isTopLevel, _printTimeAndMemory, _resetAll, _writeCode, _writeCodeFileName, createDecoratorAttributes, decoratedObjects, generateCode, generateCode, generateCode, generateCopyright, getAdapter, getCodeFileName, getComponent, getExecuteCommands, getMethodExceptionString, getMethodVisibilityString, isGlobalDecorator, main, setCodeGenerator, setContainer, setExecuteCommands
-
Methods inherited from class ptolemy.kernel.util.Attribute
_checkContainer, _getContainedObject, _propagateExistence, getContainer, moveDown, moveToFirst, moveToIndex, moveToLast, moveUp, setName, updateContent
-
Methods inherited from class ptolemy.kernel.util.NamedObj
_addAttribute, _adjustOverride, _attachText, _cloneFixAttributeFields, _containedDecorators, _copyChangeRequestList, _debug, _debug, _debug, _debug, _debug, _description, _executeChangeRequests, _exportMoMLContents, _getIndentPrefix, _isMoMLSuppressed, _markContentsDerived, _notifyHierarchyListenersAfterChange, _notifyHierarchyListenersBeforeChange, _propagateValue, _removeAttribute, _splitName, _stripNumericSuffix, _validateSettables, addChangeListener, addDebugListener, addHierarchyListener, attributeDeleted, attributeList, attributeList, attributeTypeChanged, clone, containedObjectsIterator, decorators, 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, notifyOfNameChange, propagateExistence, propagateValue, propagateValues, removeAttribute, removeChangeListener, removeDebugListener, removeHierarchyListener, 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
-
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.
-
-
Constructor Detail
-
CCodeGenerator
public CCodeGenerator(NamedObj container, java.lang.String name) throws IllegalActionException, NameDuplicationException
Create a new instance of the C code generator. This class is the core of the C Code generation For instance, the _generateCode method is key to the code generation.- 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
-
clone
public java.lang.Object clone(Workspace workspace) throws java.lang.CloneNotSupportedException
Clone the actor into the specified workspace.- Overrides:
clone
in classProceduralCodeGenerator
- Parameters:
workspace
- The workspace for the new object.- Returns:
- A new actor.
- Throws:
java.lang.CloneNotSupportedException
- If a derived class contains an attribute that cannot be cloned.- See Also:
NamedObj.exportMoML(Writer, int, String)
,NamedObj.setDeferringChangeRequests(boolean)
-
generateConstantDefinition
public java.lang.String generateConstantDefinition(java.lang.String constant, java.lang.String type, java.lang.String value)
Generate code that defines a constant. In C, generate a #define- Overrides:
generateConstantDefinition
in classProgramCodeGenerator
- Parameters:
constant
- The name of the constant to be definedtype
- A string representing the type. In C, this parameter is ignored.value
- The value of the constant.- Returns:
- A #define that defines the constant.
-
generateFireFunctionMethodName
public java.lang.String generateFireFunctionMethodName(NamedObj namedObj) throws IllegalActionException
Generate the fire function method name. This method is called when the firing code of each actor is not inlined. In this class, each actor's firing code is in a function with the same name as that of the actor, with the "fire" id- Overrides:
generateFireFunctionMethodName
in classProgramCodeGenerator
- Parameters:
namedObj
- The named object for which the name is generated.- Returns:
- The name of the fire function method.
- Throws:
IllegalActionException
- Not thrown in this base class. Derived classes should throw this exception if there are problems accessing the name or generating the name.
-
generateFunctionTable
public java.lang.String generateFunctionTable(java.lang.String[] types, java.lang.String[] 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.
-
generateInitializeEntryCode
public java.lang.String generateInitializeEntryCode() throws IllegalActionException
Generate the initialization procedure entry point.- Overrides:
generateInitializeEntryCode
in classProgramCodeGenerator
- Returns:
- a string for the initialization procedure entry point.
- Throws:
IllegalActionException
- Not thrown in this base class.
-
generateClosingEntryCode
public java.lang.String generateClosingEntryCode()
Return the closing entry code, if any.- Overrides:
generateClosingEntryCode
in classProgramCodeGenerator
- Returns:
- the closing entry code.
-
generateClosingExitCode
public java.lang.String generateClosingExitCode()
Return the closing exit code, if any.- Overrides:
generateClosingExitCode
in classProgramCodeGenerator
- Returns:
- the closing exit code.
-
generateInitializeExitCode
public java.lang.String generateInitializeExitCode() throws IllegalActionException
Generate the initialization procedure exit point.- Overrides:
generateInitializeExitCode
in classProgramCodeGenerator
- 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 classProgramCodeGenerator
- 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 classProgramCodeGenerator
- 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 classProgramCodeGenerator
- 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 classProgramCodeGenerator
- 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 classProgramCodeGenerator
- 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 classProgramCodeGenerator
- 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 classProgramCodeGenerator
- Returns:
- a string for the postfire procedure name.
- Throws:
IllegalActionException
- Not thrown in this base class.
-
generateTypeConvertCodeCandH
public java.lang.String[] generateTypeConvertCodeCandH() 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. Note that this method is really different from the super one because it splits the code in a .c part and a .h part.- Returns:
- The type resolution code.
- Throws:
IllegalActionException
- If an error occurs when generating the type resolution code, or if the adapter class for the model director cannot be found, or if an error occurs when the adapter actor generates the type resolution code.
-
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 classProgramCodeGenerator
- Returns:
- code The generated code.
- Throws:
IllegalActionException
- If the adapter 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 classProgramCodeGenerator
- Returns:
- code The generated code.
- Throws:
IllegalActionException
- If the adapter 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 classProgramCodeGenerator
- 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 classProgramCodeGenerator
- 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 classProgramCodeGenerator
- Returns:
- a string for the wrapup procedure name.
- Throws:
IllegalActionException
- Not thrown in this base class.
-
getModelName
public java.lang.String getModelName() throws IllegalActionException
Generate the model name.- Returns:
- a string for the model name.
- Throws:
IllegalActionException
- Not thrown in this base class.
-
invokeGenerateUpdatePortOffsets
public boolean invokeGenerateUpdatePortOffsets()
Return true if StaticSchedulingDirector should invoke generateUpdatePortOffsets. Most code generators do not override this method, CCodeGenerator overrides it to return false.- Overrides:
invokeGenerateUpdatePortOffsets
in classProgramCodeGenerator
- Returns:
- false, indicating that StaticSchedulingDirector should not invoke StaticSchedulingDirectory.invokeGenerateUpdatePortOffset().
-
markFunctionCalled
public void markFunctionCalled(java.lang.String name, ProceduralTemplateParser templateParser) 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.- Overrides:
markFunctionCalled
in classProceduralCodeGenerator
- Parameters:
name
- The name of the function, for example "Double_equals"templateParser
- The corresponding templateParser that contains the codeBlock.- Throws:
IllegalActionException
- If there is a problem adding a function to the set of overloaded functions.
-
splitLongBody
public java.lang.String[] splitLongBody(int linesPerMethod, java.lang.String prefix, java.lang.String code) throws java.io.IOException
Split a long function body into multiple functions.- Overrides:
splitLongBody
in classProgramCodeGenerator
- Parameters:
linesPerMethod
- The number of lines that should go into each method.prefix
- The prefix to use when naming functions that are createdcode
- 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(NamedProgramCodeGeneratorAdapter adapter) throws IllegalActionException
Add include directories specified by the actors in this model. Each element in the Set of include directories has "-I" prepended and thenProceduralCodeGenerator.addInclude(String)
is called.- Parameters:
adapter
- The adapter that has the include directories.- Throws:
IllegalActionException
- If thrown when getting an actor's include directories.- See Also:
NamedProgramCodeGeneratorAdapter.getIncludeDirectories()
-
_addActorLibraries
protected void _addActorLibraries(NamedProgramCodeGeneratorAdapter adapter) throws IllegalActionException
Add libraries specified by the actors in this model.- Parameters:
adapter
- The adapter that has library directories.- 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 classProgramCodeGenerator
- Throws:
IllegalActionException
- If the adapter of the top composite actor is unavailable.
-
_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 classProgramCodeGenerator
- Parameters:
code
- The given code to be processed.- Returns:
- The processed code.
- Throws:
IllegalActionException
- If #getOutputFilename() throws it.
-
_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 isFoo
and the generatorPackage isptolemy.codegen.c
, then the file that is written will be$HOME/Foo.c
This method is the main entry point. We do not call the super method because it is too different from it. For instance, there is not only one file generated, but a few. The code generation algorithm works as followed : We generate a file with the name of the model (+ .c) and its header file. In this file we have the implementation of a ptolemy manager in C (Manager
. Also for, each Composite Actor (including the top level container) We generate the files implementing the behavior of the director and of all the actors. (sources files are in the src directory and header files in includes directory) Moreover, for each folder a makefile is generated.- Overrides:
_generateCode
in classProgramCodeGenerator
- 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.
-
_generateConstructorCode
protected java.lang.String _generateConstructorCode(Actor actor) throws IllegalActionException
Generate the code for a constructor.- Parameters:
actor
- The actor for which constructor code shall be generated.- Returns:
- The constructor code.
- Throws:
IllegalActionException
- If there is a problem generating the code.
-
_generateConstructorCode
protected java.lang.String _generateConstructorCode(CompositeActor actor) throws IllegalActionException
Generate the code for a constructor.- Parameters:
actor
- The Composite actor for which constructor code shall be generated.- Returns:
- The constructor code.
- Throws:
IllegalActionException
- If there is a problem generating the code.
-
_generatePortsAccessorsCode
protected java.lang.String _generatePortsAccessorsCode(Actor actor)
Generate the code to access ports for an actor.- Parameters:
actor
- The actor for which code shall be generated.- Returns:
- The port accessor code.
-
_generatePortsAccessorsCode
protected java.lang.String _generatePortsAccessorsCode(CompositeActor actor)
Generate the code to access ports for a composite actor.- Parameters:
actor
- The actor for which code shall be generated.- Returns:
- The port accessor code.
-
_generatePortsAccessorsDeclaration
protected java.lang.String _generatePortsAccessorsDeclaration(Actor actor)
Generate the code to declare the accessors to ports.- Parameters:
actor
- The actor for which code shall be generated.- Returns:
- The port accessor declaration code.
-
_generatePortsAccessorsDeclaration
protected java.lang.String _generatePortsAccessorsDeclaration(CompositeActor actor)
Generate the code to declare the accessors to ports.- Parameters:
actor
- The composite actor for which code shall be generated.- Returns:
- The port accessor declaration code.
-
_generateAndWriteActorCode
protected void _generateAndWriteActorCode(NamedObj actor, NamedProgramCodeGeneratorAdapter directorAdapter, CompositeEntity container, java.lang.String directory) throws IllegalActionException
Generate and write the code for an actor. This method is called by the container actor There are 2 phases in this method : First we generate the code for the actor Then we write the code- Parameters:
actor
- The actor that needs to be generateddirectorAdapter
- The adapter of the director. This adapter is used to generate variable declarations for the director.container
- Not used by this method.directory
- The directory path of the sources files- Throws:
IllegalActionException
- If anything goes wrong during the generation.
-
_generateAndWriteCompositeActorCode
protected void _generateAndWriteCompositeActorCode(CompositeEntity container, java.lang.String containerDirectory) throws IllegalActionException
Generate and write the code for a composite actor. This method is called recursively, for any composite actor present in the model. There are 5 phases in this method : First we initialize the parameters for the container Then we generate and write the code for the container Then we call the generation for each contained actor Then we call the generation for the director Finally we generate the makefile corresponding- Parameters:
container
- The actor that needs to be generatedcontainerDirectory
- A string describing where to write the files- Throws:
IllegalActionException
- If anything goes wrong during the generation.
-
_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 adapter to generate a main loop. Note : We do not call the super method, because this one is too different- Overrides:
_generateBodyCode
in classProgramCodeGenerator
- Returns:
- The generated body code.
- Throws:
IllegalActionException
- If there is no director.
-
_generateDeclareSharedCode
protected java.lang.String _generateDeclareSharedCode() throws IllegalActionException
Generate the declarations of the 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 occurs when generating the globally shared code, or if the adapter class for the model director cannot be found, or if an error occurs when the adapter actor generates the shared code.
-
_generateIncludeFiles
protected java.lang.String _generateIncludeFiles(NamedProgramCodeGeneratorAdapter actorAdapter) throws IllegalActionException
Generate include files. FIXME: State what is included.- Parameters:
actorAdapter
- The adapter that has the header files.- Returns:
- The #include statements, surrounded by #ifndef to ensure that the files are included only once.
- Throws:
IllegalActionException
- If the adapter class for some actor cannot be found.
-
_getFireFunctionArguments
protected java.lang.String _getFireFunctionArguments()
Return the prototype for fire functions.- Overrides:
_getFireFunctionArguments
in classProgramCodeGenerator
- Returns:
- The string"(void)" so as to avoid the avr-gcc 3.4.6 warning: "function declaration isn't a prototype"
-
_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 classProgramCodeGenerator
- 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 classProgramCodeGenerator
- Returns:
- Return the code for recording the current time.
-
_templateParserClass
protected java.lang.Class<? extends TemplateParser> _templateParserClass()
Return the class of the templateParser class. In cse there isn't one return null.- Overrides:
_templateParserClass
in classProgramCodeGenerator
- Returns:
- The base class for templateParser.
-
_writeMakefile
protected void _writeMakefile(CompositeEntity container, java.lang.String currentDirectory) throws IllegalActionException
Read in a template makefile, substitute variables and write the resulting makefile.If a
.mk.in
file with the name of the sanitized model name, then that file is used as a template. For example, if the model name isFoo
and the fileFoo.mk.in
exists, then the fileFoo.mk.in
is used as a makefile template.If no
.mk.in
file is found, then the makefile template can be found by looking up a resource name makefile.in in the package named by the generatorPackage parameter. Thus, if the generatorPackage has the value "ptolemy.codegen.c", then we look for the resource "ptolemy.codegen.c.makefile.in", which is usually found as$PTII/ptolemy/codegen/c/makefile.in
.The makefile is written to a directory named by the codeDirectory parameter, with a file name that is a sanitized version of the model name, and a ".mk" extension. Thus, for a model named "Foo", we might generate a makefile in "$HOME/codegen/Foo.mk".
Under Java under Windows, your
$HOME
variable is set to the value of theuser.home
System property, which is usually something likeC:\Documents and Settings\yourlogin
, thus for usermrptolemy
the makefile would beC:\Documents and Settings\mrptolemy\codegen\Foo.mk
.See the parent class
ProceduralCodeGenerator._writeMakefile(CompositeEntity, String)
for variable that are substituted by the parent class.The following variables are substituted:
PTCG_CFILES
,PTCG_OFILES
,PTCGCompiler
.- Overrides:
_writeMakefile
in classProceduralCodeGenerator
- Parameters:
container
- The composite actor for which we generate the makefilecurrentDirectory
- The director in which the makefile is to be written.- Throws:
IllegalActionException
- If there is a problem reading a parameter, if there is a problem creating the codeDirectory directory or if there is a problem writing the code to a file.
-
-