Code generation functions¶
The cogeno module provides the core functions for inline
code generation. It encapsulates all the functions to retrieve information
(options, device tree properties, CMake variables, config properties) and
to output the generated code.
The cogeno module is automatically imported by all code snippets. No
explicit import is necessary.
Note
The cogeno module provides the public functions of the code generator
Mixin classes as cogeno functions. You can simply write:
cogeno.func(…)
The mixin class function cogeno.xxx.XxxMixin.func(self, …) is not directly available to code snippets.
Output¶
cogeno.out(*args)¶
-
cogeno::output::OutputMixin.out(self, args) Write text to the output.
The string arguments are concenated. The filters are then applied to the lines of the concenated string. The resulting string is written to the output.
OutputFilterDedentandOutputFilterTrimBlankLinesmake it easier to use multi-line strings, and they are only are useful for multi-line strings:cogeno.out(""" These are lines I want to write into my source file. """, cogeno.OutputFilterDedent(), cogeno.OutputFilterTrimBlankLines())
- Return
output string
- Parameters
*args: Variable length argument list of strings and output filters.
cogeno.outl(*args)¶
-
cogeno::output::OutputMixin.outl(self, args) Write text to the output with newline appended.
- See
OutputMixin::out(self, *args)
- Return
output string
- Parameters
*args: Variable length argument list of strings and output filters.
cogeno.out_insert(insert_file, *args)¶
-
cogeno::output::OutputMixin.out_insert(self, insert_file, args) Insert the text from the file into the output.
- See
OutputMixin::out(self, *args)
- Return
output string
- Parameters
insert_file: Path of file, either absolute path or relative to current directory or relative to templates directory.*args: Variable length argument list of strings and output filters.
Output filters¶
cogeno.OutputFilterTrimBlankLines()¶
-
cogeno.output.OutputMixin.OutputFilterTrimBlankLines : public cogeno.output.OutputMixin.OutputFilter Remove initial and trailing blank lines from the block of lines.
cogeno.OutputFilterTrimDedent()¶
-
cogeno.output.OutputMixin.OutputFilterDedent : public cogeno.output.OutputMixin.OutputFilter Remove common initial white space from the lines.
- Parameters
new_indent: Optional new indentation (after dedent)
cogeno.OutputFilterLineNumbers()¶
-
cogeno.output.OutputMixin.OutputFilterLineNumbers : public cogeno.output.OutputMixin.OutputFilter Filter lines by line numbers.
Filter lines that are given by line sumber specifications (such as “1,2,4-6”).
- Parameters
args: list of arguments denoting line number specifications
cogeno.OutputFilterStartAt()¶
-
cogeno.output.OutputMixin.OutputFilterStartAt : public cogeno.output.OutputMixin.OutputFilter Start output at pattern.
- Parameters
start_at: Start pattern
cogeno.OutputFilterStopAt()¶
-
cogeno.output.OutputMixin.OutputFilterStopAt : public cogeno.output.OutputMixin.OutputFilter Stop output at pattern.
- Parameters
stop_at: Stop pattern
cogeno.OutputFilterReplace()¶
-
cogeno.output.OutputMixin.OutputFilterReplace : public cogeno.output.OutputMixin.OutputFilter Replace substring.
- Parameters
old: old substring to replacenew: new substring which will replace the old substring. if new is None and the resulting line is empty it is deleted.count: (optional) the number of times to replace the old substring with the new substring
cogeno.OutputFilterReSub()¶
-
cogeno.output.OutputMixin.OutputFilterReSub : public cogeno.output.OutputMixin.OutputFilter Substitude regular expression pattern.
Replace the leftmost non-overlapping occurrences of pattern in each line by the replacement repl.
- Parameters
pattern: Pattern for replacement. Pattern is a string that will be compiled to a pattern object.repl: Replacement. Repl can be a string or a function. If repl is a function, it is called for every non-overlapping occurrence of pattern.count: (optional) maximum number of pattern occurrences to be replaced
cogeno.OutputFilterTemplateSubstitude()¶
-
cogeno.output.OutputMixin.OutputFilterTemplateSubstitude : public cogeno.output.OutputMixin.OutputFilter Substitude template placeholders.
Template placeholder substitution supports $-based substitutions, using the following rules:
$$ is an escape; it is replaced with a single $.
$identifier names a substitution placeholder matching a mapping key of “identifier”. By default, “identifier” is restricted to any case-insensitive ASCII alphanumeric string (including underscores) that starts with an underscore or ASCII letter. The first non-identifier character after the $ character terminates this placeholder specification.
${identifier} is equivalent to $identifier. It is required when valid identifier characters follow the placeholder but are not part of the placeholder, such as “${noun}ification”.
At least up to 4 nesting levels of placeholders are substituded, e.g.:
${placeholder_level1} : mapping = ‘placeholder_level1’ : ‘holder’
${place${placeholder_level1}_level2} : mapping = ‘placeholder_level2’ : ‘placeholder’
${${placeholder_level2}_level3} : mapping = ‘placeholder_level3’ : ‘placeholder_level’
${${placeholder_level3}4} : mapping = ‘placeholder_level4’ : ‘success’
If more than one placeholder patterns are provided the substitution is done for each pattern sequencing through the patterns list.
- Parameters
mapping: Mapping is any dictionary-like object with keys that match the template placeholders.patterns: (optional) Patterns is a list of regular expressions describing the pattern for non-braced placeholders.
The cogeno module also provides a set of convenience functions:
Code generator¶
cogeno.cogeno_state()¶
-
cogeno::generator::CodeGenerator.cogeno_state(self) numeric cogeno state id
Code generation module import¶
cogeno.import_module(name)¶
-
cogeno::importmodule::ImportMixin.import_module(self, name) Import a Cogeno module.
Import a module.
Module file is searched in current directory or modules directories.
- Parameters
name: Module to import. Specified without any path.
See Cogeno modules for the available modules.
Template file inclusion¶
cogeno.out_include(include_file)¶
-
cogeno::include::IncludeMixin.out_include(self, include_file) Write the text from include_file to the output.
The
include_fileis processed by cogeno. Inline code generation ininclude_filecan access the globals defined in theincluding source filebefore inclusion. Theincluding source filecan access the globals defined in theinclude_file(after inclusion).- Parameters
include_file: Path of include file, either absolute path or relative to current directory or relative to templates directory (e.g. ‘templates/drivers/simple_tmpl.c’)
cogeno.guard_include()¶
-
cogeno::include::IncludeMixin.guard_include(self) Prevent the current file to be included by
cogeno.out_include()when called the next time.
Error handling¶
cogeno.error(msg [, frame_index=0] [, snippet_lineno=0])¶
-
cogeno::error::ErrorMixin.error(self, msg='Error raised by cogeno generator.', frame_index=0, lineno=0) Raise Error exception.
Extra information is added that maps the python snippet line seen by the Python interpreter to the line of the file that inlines the python snippet.
- Parameters
msg: [optional] exception messageframe_index: [optional] Call frame index. The call frame offset of the function calling error(). Zero if directly called in a snippet. Add one for every level of function call.lineno: [optional] line number within template
Log output¶
cogeno.log(message, message_type=None, end=”n”, logonly=True)¶
-
cogeno::log::LogMixin.log(self, message, message_type=None, end="\, logonly=True) Print message and write to log file.
- Parameters
message: Messagemessage_type: If given will be prepended to the messageend: Character to put at the end of the message. ‘\n’ by default.logonly: Only write to logfile. True by default.
cogeno.msg(message)¶
-
cogeno::log::LogMixin.msg(self, message) Print message to stdout and log with a “message: ” prefix.
- See
- Parameters
message: Message
cogeno.warning(message)¶
-
cogeno::log::LogMixin.warning(self, message) Print message to stdout and log with a “warning: ” prefix.
- See
- Parameters
message: Message
cogeno.prout(message, end=”n”)¶
-
cogeno::log::LogMixin.prout(self, message, end="\) Print message to stdout and log.
- See
- Parameters
message: Messageend: Character to put at the end of the message. ‘\n’ by default.
cogeno.prerr(message, end=”n”)¶
-
cogeno::log::LogMixin.prerr(self, message, end="\) Print message to stderr and log with a “error: ” prefix.
- See
- Parameters
message: Messageend: Character to put at the end of the message. ‘\n’ by default.
See Invoking Cogeno for how to provide the path to the file used for logging.
Lock access¶
cogeno.lock()¶
-
cogeno::lock::LockMixin.lock(self) Get the global cogeno lock.
try: with cogeno.lock().acquire(timeout = 10): ... except cogeno.lock_timeout(): cogeno.error(...) except: raise
- Return
Lock object
cogeno.lock_timeout()¶
-
cogeno::lock::LockMixin.lock_timeout(self) Lock timeout.
- Return
Lock timeout object
See Invoking Cogeno for how to provide the path to the file used for locking.
Lock object¶
-
cogeno::filelock::BaseFileLock.acquire(self, timeout=None, poll_intervall=0.05) Acquires the file lock or fails with a :exc:`Timeout` error. .. code-block:: python # You can use this method in the context manager (recommended) with lock.acquire(): pass # Or use an equivalent try-finally construct: lock.acquire() try: pass finally: lock.release() :arg float timeout: The maximum time waited for the file lock. If ``timeout <= 0``, there is no timeout and this method will block until the lock could be acquired. If ``timeout`` is None, the default :attr:`~timeout` is used. :arg float poll_intervall: We check once in *poll_intervall* seconds if we can acquire the file lock. :raises Timeout: if the lock could not be acquired in *timeout* seconds. .. versionchanged:: 2.0.0 This method returns now a *proxy* object instead of *self*, so that it can be used in a with statement without side effects.
-
cogeno::filelock::BaseFileLock.release(self, force=False) Releases the file lock. Please note, that the lock is only completely released, if the lock counter is 0. Also note, that the lock file itself is not automatically deleted. :arg bool force: If true, the lock counter is ignored and the lock is released in every case.
-
cogeno::filelock::BaseFileLock.is_locked(self) True, if the object holds the file lock. .. versionchanged:: 2.0.0 This was previously a method and is now a property.
Options¶
cogeno.option()¶
-
cogeno::options::OptionsMixin.option(self, name) Get option of actual context.
- Return
option value
- Parameters
name: Name of option
cogeno.options_add_argument(*args, **kwargs)¶
-
cogeno::options::OptionsMixin.options_add_argument(self, args, kwargs) Add option arguments to option parser of actual context.
Cogeno modules may add arguments to the cogeno option parser. The argument variables given to cogeno are rescanned after new option arguments are provided.
def mymodule(cogeno): if not hasattr(cogeno, '_mymodule'): cogeno._mymodule = None cogeno.options_add_argument('-m', '--mymodule', metavar='FILE', dest='mymodule_file', action='store', type=lambda x: cogeno.option_is_valid_file(x), help='Load mymodule data from FILE.') if getattr(cogeno, '_mymodule') is not None: return cogeno._mymodule if cogeno.option('mymodule_file'): mymodule_file = cogeno.option('mymodule_file') else: cogeno.error(..., 2) ... cogeno._mymodule = ...
Path functions¶
cogeno.path_walk(top, topdown = False, followlinks = False)¶
-
cogeno::paths::PathsMixin.path_walk(top, topdown=False, followlinks=False) Walk directory tree.
For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames):
dirpath: the path to the directory.
dirnames: list of the paths of the subdirectories in dirpath
filenames: list of the paths of the non-directory files in dirpath
See Python docs for os.walk, exact same behavior but it yields Path() instances instead. From: http://ominian.com/2016/03/29/os-walk-for-pathlib-path/
- Return
yields a 3-tuple (dirpath, dirpathes, filepathes)
- Parameters
top: root of directory treetopdown: if topdown is True, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top-down). If topdown is False, the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom-up).followlinks:
cogeno.rmtree(top)¶
-
cogeno::paths::PathsMixin.rmtree(top) Delete an entire directory tree.
- Parameters
top: root of directory tree
cogeno.find_template_files(top, marker, suffix=’.c’)¶
-
cogeno::paths::PathsMixin.find_template_files(top, marker, suffix='.c') Find template files.
- Return
List of template file pathes
- Parameters
marker: Marker as b’my-marker’suffix:
Standard streams¶
cogeno.set_standard_streams(self, stdout=None, stderr=None)¶
-
cogeno::redirectable::RedirectableMixin.set_standard_streams(self, stdout=None, stderr=None) Redirect status and error reporting.
Assign new files for standard out and/or standard error.
- Parameters
stdout:stderr:
Standard Modules - CMake¶
cogeno.cmake_variable(variable_name [, default=”<unset>”])¶
-
cogeno::stdmodules::StdModulesMixin.cmake_variable(self, variable_name, default="<unset>") Get the value of a CMake variable.
If variable_name is not provided to cogeno by CMake the default value is returned.
A typical set of CMake variables that are not available in the
CMakeCache.txtfile and have to be provided as defines to cogeno if needed:“PROJECT_NAME”
”PROJECT_SOURCE_DIR”
”PROJECT_BINARY_DIR”
”CMAKE_SOURCE_DIR”
”CMAKE_BINARY_DIR”
”CMAKE_CURRENT_SOURCE_DIR”
”CMAKE_CURRENT_BINARY_DIR”
”CMAKE_CURRENT_LIST_DIR”
”CMAKE_FILES_DIRECTORY”
”CMAKE_PROJECT_NAME”
”CMAKE_SYSTEM”
”CMAKE_SYSTEM_NAME”
”CMAKE_SYSTEM_VERSION”
”CMAKE_SYSTEM_PROCESSOR”
”CMAKE_C_COMPILER”
”CMAKE_CXX_COMPILER”
”CMAKE_COMPILER_IS_GNUCC”
”CMAKE_COMPILER_IS_GNUCXX”
- Return
value
- Parameters
variable_name: Name of the CMake variabledefault: Default value
cogeno.cmake_cache_variable(variable_name [, default=”<unset>”])¶
-
cogeno::stdmodules::StdModulesMixin.cmake_cache_variable(self, variable_name, default="<unset>") Get the value of a CMake variable from CMakeCache.txt.
If variable_name is not given in
CMakeCache.txtthe default value is returned.- Return
value
- Parameters
variable_name: Name of the CMake variabledefault: Default value
See Invoking Cogeno and Build with Cogeno for how to provide CMake variables to cogeno.
Standard Modules - config¶
cogeno.config_properties()¶
-
cogeno::stdmodules::StdModulesMixin.config_properties(self) Get all config properties.
The property names are the ones config file.
- Return
A dictionary of config properties.
cogeno.config_property(property_name [, default=”<unset>”])¶
-
cogeno::stdmodules::StdModulesMixin.config_property(self, property_name, default="<unset>") Get the value of a configuration property fromthe config file.
If property_name is not given in .config the default value is returned.
- Return
property value
- Parameters
property_name: Name of the propertydefault: Property value to return per default.
See Invoking Cogeno and Build with Cogeno for how to provide config variables to cogeno.
Standard Modules - Extended Device Tree Database¶
cogeno.edts()¶
-
cogeno::stdmodules::StdModulesMixin.edts(self, force_extract=False) Get the extended device tree database.
- Return
Extended device tree database.
See Invoking Cogeno and Build with Cogeno for how to provide all files to enable cogeno to build the extended device tree database.