Code generation functions

A module called cogeno 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(sOut=’‘, dedent=False, trimblanklines=False)

cogeno.output.OutputMixin.out(self self, sOut sOut = '', dedent dedent = False, trimblanklines trimblanklines = False)

Write text to the output.

dedent and trimblanklines make it easier to use multi-line strings, and they are only are useful for multi-line strings:

Parameters
  • sOut: The string to write to the output.

  • dedent: If dedent is True, then common initial white space is removed from the lines in sOut before adding them to the output.

  • trimblanklines: If trimblanklines is True, then an initial and trailing blank line are removed from sOut before adding them to the output.

cogeno.out("""
   These are lines I
   want to write into my source file.
""", dedent=True, trimblanklines=True)

cogeno.outl(sOut=’‘, dedent=False, trimblanklines=False)

cogeno.output.OutputMixin.outl(self self, sOut sOut = '', dedent dedent = False, trimblanklines trimblanklines = False)

Write text to the output with newline appended.

See

OutputMixin::out(self, sOut=’‘, dedent=False, trimblanklines=False)

Parameters
  • sOut: The string to write to the output.

  • dedent: If dedent is True, then common initial white space is removed from the lines in sOut before adding them to the output.

  • trimblanklines: If trimblanklines is True, then an initial and trailing blank line are removed from sOut before adding them to the output.

The cogeno module also provides a set of convenience functions:

Code generator

cogeno.cogeno_state()

cogeno.generator.CodeGenerator.cogeno_state(self self)

numeric cogeno state id

Code generation module import

cogeno.import_module(name)

cogeno.importmodule.ImportMixin.import_module(self self, name name)

Import a Cogeno module.

Import a module from the cogeno/modules package.

Parameters
  • name: Module to import. Specified without any path.

See Code generation modules for the available modules.

Template file inclusion

cogeno.out_include(include_file)

cogeno.include.IncludeMixin.out_include(self self, include_file include_file)

Write the text from include_file to the output.

The include_file is processed by cogeno. Inline code generation in include_file can access the globals defined in the including source file before inclusion. The including source file can access the globals defined in the include_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 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 self, msg msg = ' Error raised by cogeno generator.', frame_index frame_index = 0, lineno 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 message

  • frame_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 self, message message, message_type message_type = None)

Print message and write to log file.

Parameters
  • message: Message

  • message_type: If given will be prepended to the message

  • end: 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 self, message message)

Print message to stdout and log with a “message: ” prefix.

See

LogMixin::log()

Parameters
  • message: Message

cogeno.warning(message)

cogeno.log.LogMixin.warning(self self, message message)

Print message to stdout and log with a “warning: ” prefix.

See

LogMixin::log()

Parameters
  • message: Message

cogeno.prout(message, end=”n”)

cogeno.log.LogMixin.prout(self self, message message)

Print message to stdout and log.

See

LogMixin::log()

Parameters
  • message: Message

  • end: Character to put at the end of the message. ‘\n’ by default.

cogeno.prerr(message, end=”n”)

cogeno.log.LogMixin.prerr(self self, message message)

Print message to stderr and log with a “error: ” prefix.

See

LogMixin::log()

Parameters
  • message: Message

  • end: 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 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 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 self, timeout timeout = None, poll_intervall 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 self, force 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 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 self, name 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 self, args args, kwargs 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.options_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.find_template_files(top, marker, suffix=’.c’)

cogeno.paths.PathsMixin.find_template_files(top top, marker marker, suffix 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 self, stdout stdout = None, stderr 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 self, variable_name variable_name, default 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.txt file 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 variable

  • default: Default value

cogeno.cmake_cache_variable(variable_name [, default=”<unset>”])

cogeno.stdmodules.StdModulesMixin.cmake_cache_variable(self self, variable_name variable_name, default default = "<unset>")

Get the value of a CMake variable from CMakeCache.txt.

If variable_name is not given in CMakeCache.txt the default value is returned.

Return

value

Parameters
  • variable_name: Name of the CMake variable

  • default: Default value

See Invoking cogeno and Integration into the build process for how to provide CMake variables to cogeno.

Standard Modules - config

cogeno.config_properties()

cogeno.stdmodules.StdModulesMixin.config_properties(self 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 self, property_name property_name, default 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 property

  • default: Property value to return per default.

See Invoking cogeno and Integration into the build process for how to provide config variables to cogeno.

Standard Modules - Extended Device Tree Database

cogeno.edts()

cogeno.stdmodules.StdModulesMixin.edts(self self)

Get the extended device tree database.

Return

Extended device tree database.

See Invoking cogeno and Integration into the build process for how to provide all files to enable cogeno to build the extended device tree database.