Class ProgramCodeGenerator
- 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
-
- All Implemented Interfaces:
java.lang.Cloneable,Changeable,Debuggable,DebugListener,Decorator,Derivable,ModelErrorHandler,MoMLExportable,Moveable,Nameable
- Direct Known Subclasses:
ProceduralCodeGenerator
public class ProgramCodeGenerator extends RunnableCodeGenerator
Generate a compiled programming language version of a model.This base class contains parameters and methods common to all compiled programming languages.
- Since:
- Ptolemy II 10.0
- Version:
- $Id$
- Author:
- Bert Rodiers
- Pt.AcceptedRating:
- red (rodiers)
- Pt.ProposedRating:
- red (rodiers)
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class ptolemy.kernel.util.NamedObj
NamedObj.ContainedObjectsIterator
-
-
Field Summary
Fields Modifier and Type Field Description protected java.util.Set<Parameter>_modifiedVariablesA set that contains all variables in the model whose values can be changed during execution.protected java.util.HashSet<java.lang.String>_newTypesUsedA HashSet that contains all codegen types referenced in the model.protected java.util.HashMap<java.lang.String,java.util.HashMap<java.lang.String,java.lang.Integer>>_portTypeMapA map from String type name to a HashMap of port name to an array index.protected java.util.HashMap<java.lang.String,java.util.HashMap<java.lang.String,java.lang.Integer>>_portTypeMap2A map from String type name to a HashMap of multiport or port to an array index.protected java.util.HashMap<java.lang.String,java.util.HashMap<java.lang.String,java.lang.Integer>>_portTypeMap3A map from String type name to a HashMap of multiports to an array index.protected java.util.HashMap<java.lang.String,java.lang.Integer>_portTypeMaxIndexA map from String type name to a HashMap of port name to Array Index.protected java.util.HashMap<java.lang.String,java.lang.Integer>_portTypeMaxIndex2A map from String type name to a HashMap of multiport or port to the maximum number in the corresponding array.protected java.util.HashMap<java.lang.String,java.lang.Integer>_portTypeMaxIndex3A map from String type name to a HashMap of multiports to an to the maximum number in the corresponding array.protected static java.util.List<java.lang.String>_primitiveTypesA list of the primitive types supported by the code generator.protected static java.lang.String_runCommandDefaultThe initial default value of the runCommand parameter.protected java.util.Set<java.lang.String>_tokenFuncUsedA set that contains all token functions referenced in the model.protected java.util.Set<java.lang.String>_typeFuncUsedA set that contains all type-specific functions referenced in the model.protected boolean_variablesAsArraysThe value of the variableAsArrays parameter.ParametergenerateCommentIf true, generate comments in the output code; otherwise, no comments is generated.ParameterinlineIf true, generate file with no functions.ParametermaximumLinesPerBlockThe maximum number of lines per block.ParametermeasureTimeIf true, generate code to measure the execution time.ParametersourceLineBindingIf true, then the generated source is bound to the line number and file of the (adapter) templates.ParameteruseMakeIf true, then use the 'make' command to compile and run the generated code.ParametervariablesAsArraysIf true, then generate code that puts variables into arrays; otherwise, use standalone variables.ParameterverbosityLevel of verbosity in comments and other output.-
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 ProgramCodeGenerator(NamedObj container, java.lang.String name, java.lang.String outputFileExtension, java.lang.String templateExtension)Create a new instance of the ProgramCodeGenerator.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description 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 java.lang.StringBuffer_finalPassOverCode(java.lang.StringBuffer code)Make a final pass over the generated code.protected java.lang.String_formatComment(java.lang.String comment)Return a formatted comment containing the specified string.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_generateIncludeFiles()Generate include files.protected java.lang.String_generatePreinitializeCode()Generate preinitialize code (if there is any).protected java.lang.String_generatePreinitializeMethodBodyCode()Generate the preinitialization method body.protected java.lang.String_generatePreinitializeMethodEntryCode()Generate the preinitialization procedure entry point.protected java.lang.String_generatePreinitializeMethodExitCode()Generate the preinitialization procedure exit point.protected java.lang.String_generatePreinitializeMethodProcedureName()Generate the preinitialization procedure name.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.protected java.lang.String_getFireFunctionArguments()Return the prototype for fire functions.protected CodeGeneratorAdapter_instantiateAdapter(java.lang.Object component, java.lang.Class<?> componentClass, java.lang.String adapterClassName)Instantiate the given code generator adapter.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_reset()Reset the code generator.protected void_setupAdapter()Perform any setup or initialization of the adapter.java.lang.String[]_splitBody(java.lang.String prefix, java.lang.String code)Split the code.protected java.util.List<java.lang.String>_splitVariableDeclaration(java.lang.String suffix, java.lang.String code)Split the variable declaration into possibly two sections.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.protected java.lang.String_writeVariableDeclarations(java.util.List<java.lang.String> variableDeclarations)Write the variable declaration code.voidaddModifiedVariables(Parameter variable)Add a modified variable.voidattributeChanged(Attribute attribute)If the attribute is the verbosity attribute, then if its value is 1, set a debug listener on the code generator.java.lang.StringcodeGenType(Type ptType)Get the corresponding type in code generation from the given Ptolemy type.java.lang.Stringcomment(int indentLevel, java.lang.String comment)Return a formatted comment containing the specified string with a specified indent level.java.lang.Stringcomment(java.lang.String comment)Return a formatted comment containing the specified string.static booleancontainsCode(java.lang.String code)Return true if the input contains code.java.lang.StringgenerateClosingEntryCode()Return the closing entry code, if any.java.lang.StringgenerateClosingExitCode()Return the closing exit code, if any.java.lang.StringgenerateConstantDefinition(java.lang.String constant, java.lang.String type, java.lang.String value)Generate code that defines a constant.java.lang.StringgenerateFireFunctionCode()Generate The fire function code.java.lang.StringgenerateFireFunctionCompositeEnd()Generate the closing code for a group of fire functions common to a Composite Actor.java.lang.StringgenerateFireFunctionCompositeStart(java.lang.String className)Generate the initial code for a group of fire functions common to a Composite Actor.java.lang.StringgenerateFireFunctionMethodInvocation(NamedObj namedObj)Generate the fire function method invocation.java.lang.StringgenerateFireFunctionMethodName(NamedObj namedObj)Generate the fire function method name.java.lang.String[]generateFireFunctionVariableAndMethodName(NamedObj namedObj)Generate the fire function variable name and method name.java.lang.StringgenerateFireFunctionVariableDeclaration(NamedObj namedObj)Generate the fire function variable declaration.java.lang.StringgenerateInitializeCode()Return the code associated with initialization of the containing composite actor.java.lang.StringgenerateInitializeEntryCode()Generate the initialization procedure entry point.java.lang.StringgenerateInitializeExitCode()Generate the initialization procedure exit point.java.lang.StringgenerateInitializeProcedureName()Generate the initialization procedure name.java.lang.StringgenerateLineInfo(int lineNumber, java.lang.String filename)Generate line number and file name information.java.lang.StringgenerateMainEntryCode()Generate the main entry point.java.lang.StringgenerateMainExitCode()Generate the main exit point.java.lang.StringgeneratePackageStatement()Generate the package statement, if any.java.lang.StringgeneratePortName(TypedIOPort port, java.lang.String portName, int bufferSize)Generate sanitized name for the given port.java.lang.StringgeneratePostfireCode()Generate into the specified code stream the code associated with postfiring up the container composite actor.java.lang.StringgeneratePostfireEntryCode()Generate the postfire procedure entry point.java.lang.StringgeneratePostfireExitCode()Generate the postfire procedure exit point.java.lang.StringgeneratePostfireProcedureName()Generate the postfire procedure name.java.lang.StringgeneratePtIOPortName(NamedObj container, java.lang.String portName)Generate sanitized name for the given Ptolemy IOPort.intgeneratePtIOPortSize()Return the size of the ioPortMap.java.lang.StringgeneratePtTypedCompositeActorName(NamedObj container, java.lang.String actorName)Generate sanitized name for the given TypedCompositeActor This method is used when thevariablesAsArraysparameter is true.intgeneratePtTypedCompositeActorSize()Return the size of the TypedCompositeActor Map.java.lang.StringgenerateTypeConvertCode()Generate type conversion code.java.lang.StringgenerateVariableDeclaration()Generate variable declarations for inputs and outputs and parameters.java.lang.StringgenerateVariableInitialization()Generate variable initialization for the referenced parameters.java.lang.StringgenerateVariableName(NamedObj attribute)Generate variable name for the given attribute.java.lang.StringgenerateWrapupCode()Generate into the specified code stream the code associated with wrapping up the container composite actor.java.lang.StringgenerateWrapupEntryCode()Generate the wrapup procedure entry point.java.lang.StringgenerateWrapupExitCode()Generate the wrapup procedure exit point.java.lang.StringgenerateWrapupProcedureName()Generate the wrapup procedure name.java.util.Set<Parameter>getModifiedVariables()Return the set of modified variables.java.lang.StringgetTemplateExtension()Return The extension of the template files.booleaninvokeGenerateUpdatePortOffsets()Return true if StaticSchedulingDirector should invoke _generateUpdatePortOffsets.booleanisPrimitive(java.lang.String cgType)Determine if the given type is primitive.booleanisPrimitive(Type ptType)Determine if the given type is primitive.static TypeptolemyType(java.lang.String cgType)Return the Ptolemy type that corresponds to the type named by the argument.voidsetModifiedVariables(java.util.Set<Parameter> modifiedVariables)Sets the set of modified variables.java.lang.String[]splitLongBody(int linesPerMethod, java.lang.String prefix, java.lang.String code)Split a long function body into multiple functions.java.util.List<java.lang.String>splitVariableDeclaration(int linesPerMethod, java.lang.String prefix, java.lang.String code)Split a long variable declaration body into multiple blocks or files.java.lang.StringtargetType(Type ptType)Get the corresponding type in C from the given Ptolemy type.java.lang.String[][]updateCommandOptions()Return an updated array of command line options.-
Methods inherited from class ptolemy.cg.kernel.generic.RunnableCodeGenerator
_executeCommands, _runCommand, _setupCommands, _updateSubstituteMap, clone
-
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
-
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.
-
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.
-
maximumLinesPerBlock
public Parameter maximumLinesPerBlock
The maximum number of lines per block. Maximum number of lines in initialize(), postfire() and wrapup() methods. This parameter is used to make smaller methods so that compilers take less time to compile. Most target languages have limits to the size of a block or method. If a block or method has more lines than this value, then some code generators may try to split of the code. Note that this is very experimental. The default value is an integer with value 2500.
-
measureTime
public Parameter measureTime
If true, generate code to measure the execution time. The default value is a parameter with the value false.
-
sourceLineBinding
public Parameter sourceLineBinding
If true, then the generated source is bound to the line number and file of the (adapter) templates. Otherwise, the source is bound only to the output file. This is a boolean parameter with default value false.
-
useMake
public Parameter useMake
If true, then use the 'make' command to compile and run the generated code. The default is true;
-
variablesAsArrays
public Parameter variablesAsArrays
If true, then generate code that puts variables into arrays; otherwise, use standalone variables. This parameter is used for very large models that would otherwise generate code that cannot be compiled by the Java compiler. If this is the case, then javac will produce an error message like "too many constants". The default value is a parameter with the value false.
-
verbosity
public Parameter verbosity
Level of verbosity in comments and other output. Levels greater than 0 will cause the code generator to generate more detailed information about the operation of the code generator. If the value of the verbosity parameter is greater than 9, then the comment is prepended with the name of the method that called the method that called this method. This is useful for debugging. The default is an integer with the value 0, which indicates that the lowest level of verbosity.
-
_modifiedVariables
protected java.util.Set<Parameter> _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.)
-
_portTypeMap
protected java.util.HashMap<java.lang.String,java.util.HashMap<java.lang.String,java.lang.Integer>> _portTypeMap
A map from String type name to a HashMap of port name to an array index. Ports with a buffer size of 1 end up in this array. ThevariablesAsArraysparameter enables use of this map to reduce the number of variables generated.
-
_portTypeMaxIndex
protected java.util.HashMap<java.lang.String,java.lang.Integer> _portTypeMaxIndex
A map from String type name to a HashMap of port name to Array Index. ThevariablesAsArraysparameter enables use of this map to reduce the number of variables generated.
-
_portTypeMap2
protected java.util.HashMap<java.lang.String,java.util.HashMap<java.lang.String,java.lang.Integer>> _portTypeMap2
A map from String type name to a HashMap of multiport or port to an array index. Multiports with a buffersize of 1 or ports with a buffer size greater than 1 end up in this array. ThevariablesAsArraysparameter enables use of this map to reduce the number of variables generated.
-
_portTypeMaxIndex2
protected java.util.HashMap<java.lang.String,java.lang.Integer> _portTypeMaxIndex2
A map from String type name to a HashMap of multiport or port to the maximum number in the corresponding array. Multiports with a buffersize of 1 or ports with a buffer size greater than 1 end up in this array. ThevariablesAsArraysparameter enables use of this map to reduce the number of variables generated.
-
_portTypeMap3
protected java.util.HashMap<java.lang.String,java.util.HashMap<java.lang.String,java.lang.Integer>> _portTypeMap3
A map from String type name to a HashMap of multiports to an array index. Multiports with a buffer size greater than 1 end up in this array. ThevariablesAsArraysparameter enables use of this map to reduce the number of variables generated.
-
_portTypeMaxIndex3
protected java.util.HashMap<java.lang.String,java.lang.Integer> _portTypeMaxIndex3
A map from String type name to a HashMap of multiports to an to the maximum number in the corresponding array. Multiports with a buffer size greater than 1 end up in this array. ThevariablesAsArraysparameter enables use of this map to reduce the number of variables generated.
-
_primitiveTypes
protected static java.util.List<java.lang.String> _primitiveTypes
A list of the primitive types supported by the code generator.
-
_runCommandDefault
protected static final java.lang.String _runCommandDefault
The initial default value of the runCommand parameter. The constructor of a derived class may compare the value of runCommand and this variable and decide to override the value of the runCommand parameter with a new value.- See Also:
- Constant Field Values
-
_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.
-
_variablesAsArrays
protected boolean _variablesAsArrays
The value of the variableAsArrays parameter.
-
-
Constructor Detail
-
ProgramCodeGenerator
public ProgramCodeGenerator(NamedObj container, java.lang.String name, java.lang.String outputFileExtension, java.lang.String templateExtension) throws IllegalActionException, NameDuplicationException
Create a new instance of the ProgramCodeGenerator.- Parameters:
container- The container.name- The name of the ProgramCodeGenerator.outputFileExtension- The extension of the output file. (for example c in case of C and java in case of Java)templateExtension- The extension of the template files. (for example c in case of C and j in case of Java).- Throws:
IllegalActionException- If the super class throws the exception or error occurs when setting the file path.NameDuplicationException- If the super class throws the exception or an error occurs when setting the file path.
-
-
Method Detail
-
addModifiedVariables
public final void addModifiedVariables(Parameter variable) throws IllegalActionException
Add a modified variable.- Parameters:
variable- The variable to add to the Set- Throws:
IllegalActionException- Not thrown in this base class.- See Also:
getModifiedVariables()
-
attributeChanged
public void attributeChanged(Attribute attribute) throws IllegalActionException
If the attribute is the verbosity attribute, then if its value is 1, set a debug listener on the code generator.- Overrides:
attributeChangedin classGenericCodeGenerator- 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.
- See Also:
ptolemyType(String)
-
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 "*\/".- Overrides:
commentin classGenericCodeGenerator- Parameters:
comment- The string to put in the comment.- Returns:
- A formatted comment.
-
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, in Java, generate a static final.- 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 string that defines a constant. In this base class, a comment with the values of the arguments is returned.
-
generateFireFunctionCode
public java.lang.String generateFireFunctionCode() throws IllegalActionExceptionGenerate The fire function code. This method is called when the firing code of each actor is not inlined. In the default, each actor's firing code is in a function with the name that is returned bygenerateFireFunctionMethodName(NamedObj). Derived classes such as JavaCodeGenerator may put the fire functions in inner classes so as to reduce the Java file size.- Returns:
- The fire function code of the containing composite actor.
- Throws:
IllegalActionException- If thrown while generating fire code.
-
generateFireFunctionCompositeEnd
public java.lang.String generateFireFunctionCompositeEnd()
Generate the closing code for a group of fire functions common to a Composite Actor. This method is called when the firing code of each actor is not inlined.- Returns:
- In this base class, return the empty string. Derived classes, such as the JavaCodeGenerator could return the end of an inner class.
-
generateFireFunctionCompositeStart
public java.lang.String generateFireFunctionCompositeStart(java.lang.String className)
Generate the initial code for a group of fire functions common to a Composite Actor. This method is called when the firing code of each actor is not inlined.- Parameters:
className- The name of the class to include in the initial code.- Returns:
- In this base class, return the empty string. Derived classes, such as the JavaCodeGenerator could return the start of an inner class.
-
generateFireFunctionMethodInvocation
public java.lang.String generateFireFunctionMethodInvocation(NamedObj namedObj) throws IllegalActionException
Generate the fire function method invocation. This method is called when the firing code of each actor is not inlined. In this base class, each actor's firing code is in a function with the same name as that of the actor.- Parameters:
namedObj- The named object for which the name is generated.- Returns:
- The name of the fire function invocation.
- 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.
-
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 base class, each actor's firing code is in a function with the same name as that of the actor.- 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.
-
generateFireFunctionVariableAndMethodName
public java.lang.String[] generateFireFunctionVariableAndMethodName(NamedObj namedObj) throws IllegalActionException
Generate the fire function variable name and method name. This method is called when the firing code of each actor is not inlined.- Parameters:
namedObj- The named object for which the name is generated.- Returns:
- An array of two elements. In this base class, the first element is the empty string, the second element is the method name. In derived classes, the first element is a String that contains the variable name, the second is the name of the method.
- Throws:
IllegalActionException- If thrown while generating fire code.
-
generateFireFunctionVariableDeclaration
public java.lang.String generateFireFunctionVariableDeclaration(NamedObj namedObj) throws IllegalActionException
Generate the fire function variable declaration. This method is called when the firing code of each actor is not inlined. In this base class, the empty string is returned. Derived classes, such as JavaCodeGenerator, could return a variable declaration that instantiates an inner class.The purpose of this method is to allow derived generators to generate code in inner classes and thus allow the compilation of large models.
- Parameters:
namedObj- The named object for which the name is generated.- Returns:
- In this baseclass, return the empty string.
- 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.
-
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
-
generateInitializeCode
public java.lang.String generateInitializeCode() throws IllegalActionExceptionReturn the code associated with initialization of the containing composite actor. This method calls the generateInitializeCode() method of the code generator adapter associated with the model director.- Returns:
- The initialize code of the containing composite actor.
- Throws:
IllegalActionException- If the adapter class for the model director cannot be found or if an error occurs when the director adapter generates initialize code.
-
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.
-
generateInitializeEntryCode
public java.lang.String generateInitializeEntryCode() throws IllegalActionExceptionGenerate 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 IllegalActionExceptionGenerate 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 IllegalActionExceptionGenerate 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 IllegalActionExceptionGenerate 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 IllegalActionExceptionGenerate the main exit point.- Returns:
- Return a string that declares the end of the main() function.
- Throws:
IllegalActionException- Not thrown in this base class.
-
generatePackageStatement
public java.lang.String generatePackageStatement() throws IllegalActionExceptionGenerate the package statement, if any. Derived classes, such as the Java code generator, might generate a package statement here.- Returns:
- In this base class, return the empty string.
- Throws:
IllegalActionException- Not thrown in this base class.
-
generatePortName
public java.lang.String generatePortName(TypedIOPort port, java.lang.String portName, int bufferSize)
Generate sanitized name for the given port. If thevariablesAsArraysparameter is true, then a reference into an array of the appropriate type (ports_int[], ports_double[] etc.) is returned. Otherwise, the name of the port with any underscores converted to periods is returned. SeeSDFDirector.generateInitializeCode()for where the arrays are initialized.- Parameters:
port- The port for which the name is generated.portName- The sanitized name of the port.bufferSize- The size of the port buffer.- Returns:
- The name of the port as an array element.
-
generatePtIOPortName
public java.lang.String generatePtIOPortName(NamedObj container, java.lang.String portName)
Generate sanitized name for the given Ptolemy IOPort. This method returns an array reference in to an array of Ptolemy ports. This method is used with AutoAdapter, most code uses generatePortName() above. This method is used when thevariablesAsArraysparameter is true.- Parameters:
container- The actor that contains the port, which may be null.portName- The sanitized name of the port- Returns:
- The name of the port as an array element.
-
generatePtIOPortSize
public int generatePtIOPortSize()
Return the size of the ioPortMap.- Returns:
- the size of the ioPortMap.
-
generatePtTypedCompositeActorName
public java.lang.String generatePtTypedCompositeActorName(NamedObj container, java.lang.String actorName) throws IllegalActionException
Generate sanitized name for the given TypedCompositeActor This method is used when thevariablesAsArraysparameter is true.- Parameters:
container- The container of the actor.actorName- The sanitized name of the actor.- Returns:
- The name of the actor as an array element.
- Throws:
IllegalActionException- If the variablesAsArrays parameter of the code generator cannot be read.
-
generatePtTypedCompositeActorSize
public int generatePtTypedCompositeActorSize()
Return the size of the TypedCompositeActor Map.- Returns:
- the size of the TypedCompositeActor Map.
-
generatePostfireCode
public java.lang.String generatePostfireCode() throws IllegalActionExceptionGenerate 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 adapter associated with the director of this container.- Returns:
- The postfire code of the containing composite actor.
- Throws:
IllegalActionException- If the adapter class for the model director cannot be found.
-
generatePostfireEntryCode
public java.lang.String generatePostfireEntryCode() throws IllegalActionExceptionGenerate 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 IllegalActionExceptionGenerate 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 IllegalActionExceptionGenerate 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 IllegalActionExceptionGenerate type conversion code.- Returns:
- The type conversion code.
- Throws:
IllegalActionException- If an error occurrs when generating the type conversion 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 conversion code.
-
generateVariableDeclaration
public java.lang.String generateVariableDeclaration() throws IllegalActionExceptionGenerate 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 adapter class for the model director cannot be found.
-
generateVariableInitialization
public java.lang.String generateVariableInitialization() throws IllegalActionExceptionGenerate variable initialization for the referenced parameters.- Returns:
- code The generated code.
- Throws:
IllegalActionException- If the adapter 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 for which to generate a variable name.- Returns:
- The generated variable name.
-
generateWrapupCode
public java.lang.String generateWrapupCode() throws IllegalActionExceptionGenerate 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 adapter associated with the director of this container.- Returns:
- The wrapup code of the containing composite actor.
- Throws:
IllegalActionException- If the adapter class for the model director cannot be found.
-
generateWrapupEntryCode
public java.lang.String generateWrapupEntryCode() throws IllegalActionExceptionGenerate 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 IllegalActionExceptionGenerate 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 IllegalActionExceptionGenerate the wrapup procedure name.- Returns:
- a string for the wrapup procedure name.
- Throws:
IllegalActionException- Not thrown in this base class.
-
getModifiedVariables
public final java.util.Set<Parameter> getModifiedVariables() throws IllegalActionException
Return the set of modified variables.- Returns:
- The set of modified variables.
- Throws:
IllegalActionException- Not thrown in this base class.- See Also:
setModifiedVariables(Set)
-
getTemplateExtension
public final java.lang.String getTemplateExtension()
Return The extension of the template files. (for example c in case of C and j in case of Java)- Returns:
- The extension of the template files..
-
isPrimitive
public final 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.
-
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.- Returns:
- true, indicating that StaticSchedulingDirector should invoke StaticSchedulingDirectory._invokeGenerateUpdatePortOffset().
-
isPrimitive
public final 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.
-
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.
- See Also:
codeGenType(Type)
-
setModifiedVariables
public final void setModifiedVariables(java.util.Set<Parameter> modifiedVariables) throws IllegalActionException
Sets the set of modified variables.- Parameters:
modifiedVariables- The set of modified variables to be saved- Throws:
IllegalActionException- Not thrown in this base class.- See Also:
getModifiedVariables()
-
splitLongBody
public java.lang.String[] splitLongBody(int linesPerMethod, java.lang.String prefix, java.lang.String code) throws java.io.IOExceptionSplit 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 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. 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 while reading the code.
-
splitVariableDeclaration
public java.util.List<java.lang.String> splitVariableDeclaration(int linesPerMethod, java.lang.String prefix, java.lang.String code) throws java.io.IOExceptionSplit a long variable declaration body into multiple blocks or files.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 createdcode- The variable declarations to be split.- Returns:
- A list of at least two elements. If the code has less than the value of the maximumNumberOfLinesPerBlock parameter lines, then the first element is empty, the second element contains the contents of the code parameter. If the code has more lines than maximumLinesPerBlock, then the first element contains the declarations necessary for the include files section and the second element and successive elements contain the declarations. Each declaration should be placed into a file that corresponds with the include or import listed in the first element.
- Throws:
java.io.IOException- If thrown while 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.
-
updateCommandOptions
public java.lang.String[][] updateCommandOptions()
Return an updated array of command line options.- Overrides:
updateCommandOptionsin classRunnableCodeGenerator- Returns:
- An array of updated command line options.
-
_addActorIncludeDirectories
protected void _addActorIncludeDirectories() throws IllegalActionExceptionAdd include directories specified by the actors in this model.- Throws:
IllegalActionException- Never in this base class.
-
_addActorLibraries
protected void _addActorLibraries() throws IllegalActionExceptionAdd libraries specified by the actors in this model.- Throws:
IllegalActionException- Never in this base class.
-
_analyzeTypeConversions
protected void _analyzeTypeConversions() throws IllegalActionExceptionAnalyze 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 adapter of the top composite actor is unavailable.
-
_codeDirectoryAsFile
protected java.io.File _codeDirectoryAsFile() throws java.io.IOException, IllegalActionExceptionReturn the value of the codeDirectory parameter.- Returns:
- The value of the
GenericCodeGenerator.codeDirectoryparameter. - 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.
-
_finalPassOverCode
protected java.lang.StringBuffer _finalPassOverCode(java.lang.StringBuffer code) throws IllegalActionExceptionMake 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.
-
_formatComment
protected 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. If the value of the verbosity parameter is greater than 9, then the comment is prepended with the name of the method that called the method that called this method. This is useful for debugging.- Parameters:
comment- The string to put in the comment.- Returns:
- A formatted comment.
-
_generateBodyCode
protected java.lang.String _generateBodyCode() throws IllegalActionExceptionGenerate the body code that lies between variable declaration and wrapup. This method delegates to the director adapter to generate a main loop.- Returns:
- The generated body code.
- Throws:
IllegalActionException- If there is no director.
-
_generateIncludeFiles
protected java.lang.String _generateIncludeFiles() throws IllegalActionExceptionGenerate include files. This base class just returns an empty string.- Returns:
- The include files.
- Throws:
IllegalActionException- If the adapter class for some actor cannot be found.
-
_generateSharedCode
protected java.lang.String _generateSharedCode() throws IllegalActionExceptionGenerate 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 adapter class for the model director cannot be found, or if an error occurs when the adapter actor generates the shared code.
-
_generateCode
protected int _generateCode(java.lang.StringBuffer code) throws KernelExceptionGenerate 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 isFooand the generatorPackage isptolemy.codegen.c, then the file that is written will be$HOME/Foo.cThis method is the main entry point.- Overrides:
_generateCodein classGenericCodeGenerator- 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.
-
_generatePreinitializeCode
protected java.lang.String _generatePreinitializeCode() throws IllegalActionExceptionGenerate preinitialize code (if there is any). This method calls the generatePreinitializeCode() method of the code generator adapter associated with the enclosing composite actor.- Returns:
- The preinitialize code of the containing composite actor.
- Throws:
IllegalActionException- If the adapter class for the model director cannot be found, or if an error occurs when the director adapter generates preinitialize code.
-
_generatePreinitializeMethodBodyCode
protected java.lang.String _generatePreinitializeMethodBodyCode() throws IllegalActionExceptionGenerate the preinitialization method body.Typically, the preinitialize code consists of variable declarations. However, AutoAdapter generates method calls that instantiate wrapper TypedCompositeActors, so we need to invoke those method calls.
- Returns:
- a string for the preinitialization method body.
- Throws:
IllegalActionException- Not thrown in this base class.
-
_generatePreinitializeMethodEntryCode
protected java.lang.String _generatePreinitializeMethodEntryCode() throws IllegalActionExceptionGenerate the preinitialization procedure entry point.- Returns:
- a string for the preinitialization procedure entry point.
- Throws:
IllegalActionException- Not thrown in this base class.
-
_generatePreinitializeMethodExitCode
protected java.lang.String _generatePreinitializeMethodExitCode() throws IllegalActionExceptionGenerate the preinitialization procedure exit point.- Returns:
- a string for the preinitialization procedure exit point.
- Throws:
IllegalActionException- Not thrown in this base class.
-
_generatePreinitializeMethodProcedureName
protected java.lang.String _generatePreinitializeMethodProcedureName() throws IllegalActionExceptionGenerate the preinitialization procedure name.- Returns:
- a string for the preinitialization procedure name.
- Throws:
IllegalActionException- Not thrown in this base class.
-
_instantiateAdapter
protected CodeGeneratorAdapter _instantiateAdapter(java.lang.Object component, java.lang.Class<?> componentClass, java.lang.String adapterClassName) throws IllegalActionException
Instantiate the given code generator adapter.- Overrides:
_instantiateAdapterin classGenericCodeGenerator- Parameters:
component- The given component.componentClass- The class of the component to be instantiated. The constructor for class named by the adapterClassName argument must take an argument of the class componentClass.adapterClassName- The dot separated name of the adapter.- Returns:
- The code generator adapter.
- Throws:
IllegalActionException- If the adapter class cannot be found.
-
_getFireFunctionArguments
protected java.lang.String _getFireFunctionArguments()
Return the prototype for fire functions.- Returns:
- In this base class, return "()". Derived classes, such as the C code generator adapter might return "(void)".
-
_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.
-
_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.
-
_reset
protected void _reset() throws IllegalActionExceptionReset the code generator.- Overrides:
_resetin classRunnableCodeGenerator- Throws:
IllegalActionException- Not thrown in this base class, thrown by the parent if the container of the model cannot be set to null.
-
_setupAdapter
protected void _setupAdapter() throws IllegalActionExceptionPerform any setup or initialization of the adapter. Note that this is not the Ptolemy initialize() method, this method merely sets up any codegen-time variables in the adapters.- Throws:
IllegalActionException- If an error occurrs while initializing an adapter.
-
_splitVariableDeclaration
protected java.util.List<java.lang.String> _splitVariableDeclaration(java.lang.String suffix, java.lang.String code)Split the variable declaration into possibly two sections.- Parameters:
suffix- The suffix to use when naming functions that are created.code- The variable declarations to be split.- Returns:
- A list of at least two elements. If the code has less than maximumLinesPerBlock lines, then the first element is empty, the second element contains the contents of the code parameter. If the code has more lines than maximumLinesPerBlock, then the first element contains the declarations necessary for the include files section and the second element and successive elements contain the declarations. Each declaration should be placed into a file that corresponds with the include or import listed in the first element.
-
_templateParserClass
protected java.lang.Class<? extends TemplateParser> _templateParserClass()
Return the class of the templateParser class. In cse there isn't one return null.- 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.infile with the name of the sanitized model name, then that file is used as a template. For example, if the model name isFooand the fileFoo.mk.inexists, then the fileFoo.mk.inis used as a makefile template.If no
.mk.infile 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
$HOMEvariable is set to the value of theuser.homeSystem property, which is usually something likeC:\Documents and Settings\yourlogin, thus for usermrptolemythe makefile would beC:\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. @CLASSPATHSEPARATOR@- The value of the path.separator property
@PTJNI_NO_CYGWIN@,@PTJNI_SHAREDLIBRARY_CFLAG@,@PTJNI_SHAREDLIBRARY_LDFLAG@,@PTJNI_SHAREDLIBRARY_PREFIX@@PTJNI_SHAREDLIBRARY_SUFFIX@- Platform dependent compiler variables
@PTJavaCompiler@javac
- 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.
-
_splitBody
public java.lang.String[] _splitBody(java.lang.String prefix, java.lang.String code)Split the code.- Parameters:
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. In this base class, the first element is always the empty string and the second element is the value of the code parameter.
-
_writeVariableDeclarations
protected java.lang.String _writeVariableDeclarations(java.util.List<java.lang.String> variableDeclarations) throws IllegalActionExceptionWrite the variable declaration code.- Parameters:
variableDeclarations- A List of two or more elements. If the first element is the empty String, then the second element contains all of the variable declarations. If the first element is not empty, then it contains the language specific declarations for the variable declarations. For example, in C, the first element would consist of one or more "#include" statements. In Java, the first element would consist of one or more "import" statements. The second and successive elements contain the code to be written to separate files or to be returned as one String.- Returns:
- The variable declarations or the empty string. In this base class, the variable declarations are returned. Derived classes may write each element to a separate file and return the empty string.
- Throws:
IllegalActionException- Not thrown in this base class. Derived classes should throw this if there is a problem writing the file(s).
-
-