5.2.1. API reference documentation

5.2.1.1. bkl.model – project model

class bkl.model.Configuration(name, base, is_debug, source_pos=None)

Bases: object

Class representing a configuration.

Each model has two special configurations, Debug and Release, predefined.

name

Name of the configuration

base

Base configuration this one is derived from, as a Configuration instance, or None for “Debug” and “Release” configurations.

is_debug

Is this a debug configuration?

source_pos

Source code position of object’s definition, or None.

create_derived(new_name, source_pos=None)

Returns a new copy of this configuration with a new name.

derived_from(cfg)

Returns true if self derives, directly or indirectly, from configuration cfg.

Returns 0 if not derived. Returns degree of inheritance if derived: 1 if cfg is a direct base, 2 if it is a base of self’s base etc.

class bkl.model.ConfigurationProxy(model, config)

Bases: object

Proxy for accessing model part’s variables as configuration-specific. All expressions obtained using operator[] are processed to remove conditionals depending on the value of “config”, by substituting appropriate value according to the configuration name passed to proxy’s constructor.

See bkl.model.ModelPartWithConfigurations.configurations() for more information.

apply_subst(value)

Applies the proxy’s magic on given value. This is useful for when the proxy cannot be simply used in place of a real target. For example, NativeLinkedType.get_ldlibs() inspects other targets too and so the proxy is only partially effective.

class bkl.model.ConfigurationsPropertyMixin

Mixin class for implementation configurations property.

configurations

Returns all configurations for this model part (e.g. a target), as ConfigurationProxy objects that can be used similarly to the way the model part object itself is. In particular, it’s [] operator works the same.

The proxies are intended to be used in place of targets in code that needs to get per-configuration values of properties.

>>> for cfg in target.configurations:
...     outdir = cfg["outdir"]
class bkl.model.ModelPart(parent, source_pos=None)

Bases: object

Base class for model “parts”, i.e. projects, modules or targets. Basically, anything that can have variables on it.

name

Name of the part – e.g. target name, filename of source file etc.

variables

Dictionary of all variables defined in global scope in this module

parent

Parent model part of this one, i.e. the part one step higher in object model hierarchy (e.g. module for a target). May only be None for toplevel part (the project). Dictionary of all variables defined in global scope in this module

source_pos

Source code position of object’s definition, or None.

add_variable(var)

Adds a new variable object.

all_variables()

Returns iterator over all variables in the target. Works recursively, i.e. scans all modules and targets under this object too.

child_parts()

Yields model parts that are (direct) children of this.

enum_props()

Enumerates properties defined on this object.

Like get_prop(), this method doesn’t work recursively upwards, but lists only properties that are defined for this scope.

See also

get_prop()

get_child_part_by_name(name)

Returns child of this part of the model with given name (e.g. target with that name). Throws if not found.

get_matching_prop_with_inheritance(name)

Like get_prop(), but looks for inheritable properties defined for child scopes too (e.g. returns per-target property ‘outputdir’ even in module scope).

(This is used for assigning into variables and validating them against properties. Don’t use unless you know what you’re doing.)

get_prop(name)

Try to get a property name. Called by get_variable_value() if no variable with such name could be found.

Note that unlike get_variable(), this one doesn’t work recursively upwards, but finds only properties that are defined for this scope.

See also

enum_props()

get_variable(name)

Returns variable object for given variable or None if it is not defined at this scope.

This method does not do any recursive resolution or account for properties and their default values; it merely gets the variable object if it is defined at this scope.

get_variable_value(name)

Similar to get_variable(), but returns the expression with variable’s value. Throws and exception if the variable isn’t defined, neither in this scope or in any of its parent scopes.

If variable name is not explicitly defined, but a property with the same name exists in this scope, then its default value is used.

If the variable is not defined in this scope at all, looks in the parent – but only if name doesn’t correspond to non-inheritable property. In other words, fails only if the variable isn’t defined for use in this scope.

Throws if the value cannot be found.

As a shorthand syntax for this function, key indices may be used: >>> target[“includedirs”]

is_variable_explicitly_set(name)

Returns true if the variable was set in the bakefiles explicitly.

is_variable_null(name)

Returns true if the variable is unset or null (which amounts to not being set in this toolset / under current condition).

make_variables_for_missing_props(toolset)

Creates variables for properties that don’t have variables set yet.

Parameters:toolset – Name of the toolset to generate for. Properties specific to other toolsets are ignored for efficiency.
resolve_variable(name)

Returns variable object for given variable or None if it is not defined.

Unlike get_variable(), this method does perform recursive resolution and finds the variable (if it exists) according to the same rules that apply to $(…) expressions and to get_variable_value().

Note

Unlike get_variable_value(), this method doesn’t look for properties’ default values.

set_property_value(prop, value)

Adds variable with a value for property prop.

The property must exist on this model part. This is just a convenience wrapper around add_variable() and get_prop().

should_build()

Evaluates the condition property on this part and returns True if it should be built or False otherwise. Throws NonConstError if it cannot be determined.

condition

Condition expression (bkl.expr.Expr) that describes when should this part of the model be included. If it evaluates to true, the part is build, otherwise it is not. Typical use is enabling some targets or source files only for some toolsets, but it may be more complicated. Depending on the context and the toolset, the expression may even be undeterminable until make-time, if it references some user options (but not all toolsets can handle this). Is None if no condition is associated.

module

The bkl.model.Module that this part belongs to.

project

The bkl.model.Project project this part belongs to.

class bkl.model.Module(parent, source_pos)

Bases: bkl.model.ModelPart

Representation of single compilation unit. Corresponds to one Bakefile input file (either specified on command line or imported using import command; files included using include from other files are not represented by Module object) and typically to one generated output file.

targets

Dictionary of all targets defined in this module

source_file

Path to the input .bkl source file this module was created from.

srcdir

@srcdir path effective for this module.

imports

Set of filenames of sources imported using the ‘import’ keyword at this level.

child_parts()

Yields model parts that are (direct) children of this.

enum_props()

Enumerates properties defined on this object.

Like get_prop(), this method doesn’t work recursively upwards, but lists only properties that are defined for this scope.

See also

get_prop()

is_submodule_of(module)

Returns True if this module is (grand-)*child of module.

submodules

Submodules of this module.

class bkl.model.Project

Bases: bkl.model.ModelPart

Abstract model that completely describes state of loaded and processed Bakefile file(s) within the project.

modules

List of all modules included in the project.

configurations

All configurations defined in the project.

settings

List of all settings included in the project.

templates

Dictionary of all templates defined in the project.

add_configuration(config)

Adds a new configuration to the project.

add_template(templ)

Adds a new template to the project.

all_targets()

Returns iterator over all targets in the project.

child_parts()

Yields model parts that are (direct) children of this.

clone()

Makes an independent copy of the model.

Unlike deepcopy(), this does not copy everything, but uses an appropriate mix of deep and shallow copies. For example, expressions, which are read-only, are copied shallowly, but variables or model parts, both of which can be modified in further toolset-specific optimizations, are copied deeply.

enum_props()

Enumerates properties defined on this object.

Like get_prop(), this method doesn’t work recursively upwards, but lists only properties that are defined for this scope.

See also

get_prop()

get_target(id)

Returns Target object identified by its string ID.

has_target(id)

Returns true if target with given name exists.

top_module

The toplevel module of this project.

class bkl.model.ProxyIfResolver(config)

Bases: bkl.expr.RewritingVisitor

Replaces references to $(config) with value, allowing the expressions to be evaluated.

if_(e)

Called on IfExpr expressions.

placeholder(e)

Called on PlaceholderExpr expressions.

reference(e)

Called on ReferenceExpr expressions.

class bkl.model.Setting(parent, name, source_pos)

Bases: bkl.model.ModelPart

User-settable make-time configuration value.

child_parts()

Yields model parts that are (direct) children of this.

enum_props()

Enumerates properties defined on this object.

Like get_prop(), this method doesn’t work recursively upwards, but lists only properties that are defined for this scope.

See also

get_prop()

class bkl.model.SourceFile(parent, filename, source_pos)

Bases: bkl.model.ModelPart, bkl.model.ConfigurationsPropertyMixin

Source file object.

child_parts()

Yields model parts that are (direct) children of this.

enum_props()

Enumerates properties defined on this object.

Like get_prop(), this method doesn’t work recursively upwards, but lists only properties that are defined for this scope.

See also

get_prop()

class bkl.model.Target(parent, name, target_type, source_pos)

Bases: bkl.model.ModelPart, bkl.model.ConfigurationsPropertyMixin

A Bakefile target.

Variables are typed.

name

Name (ID) of the target. This must be unique in the entire project.

type

Type of the target, as bkl.api.TargetType instance.

sources

List of source files, as SourceFile instances.

headers

List of header files, as SourceFile instances. The difference from sources is that headers are installable and usable for compilation of other targets, while sources are not.

child_parts()

Yields model parts that are (direct) children of this.

enum_props()

Enumerates properties defined on this object.

Like get_prop(), this method doesn’t work recursively upwards, but lists only properties that are defined for this scope.

See also

get_prop()

class bkl.model.Template(name, bases, source_pos=None)

Bases: object

A template.

name

Name of the template.

bases

List of base templates (as bkl.model.Template objects).

source_pos

Source code position of template’s definition, or None.

class bkl.model.Variable(name, value, type=None, readonly=False, source_pos=None)

Bases: object

A Bakefile variable.

Variables can be either global or target-specific. Value held by a variable is stored as expression tree, it isn’t evaluated into string form until the final stage of processing, when output is generated.

Variables are typed.

name

Name of the variable.

type

Type of the property, as bkl.vartypes.Type instance.

value

Value of the variable, as bkl.expr.Expr object.

readonly

Indicates if the variable is read-only. Read-only variables can only be assigned once and cannot be modified afterwards.

is_property

Indicates if the variable corresponds to a property.

is_explicitly_set

Indicates if the value was set explicitly by the user. Normally true, only false for properties’ default values.

static from_property(prop, value=None)

Creates a variable from property prop. In particular, takes the type and readonly attribute from the property. Properties’ default value is not assigned; value is used instead.

set_value(value)

Sets new value on the variable. The new value must have same type as current value. Read-only variable cannot be set.

Parameters:value – New value as bkl.expr.Expr object.

5.2.1.2. bkl.expr – representation of expressions

The Expr class that represents a Bakefile expression (be it a condition or variable value) is defined in this module, together with useful functions for evaluating and manipulating expressions.

class bkl.expr.BoolExpr(operator, left, right=None, pos=None)

Bases: bkl.expr.Expr

Boolean expression.

operator

Boolean operator of the node. The value is one of BoolExpr constants, e.g. BoolExpr.AND.

left

Left (or in the case of NOT operator, only) operand.

right

Right operand. Not set for the NOT operator.

as_py()

Returns the expression as Python value (e.g. a list of strings) if it evaluates to a constant literal. Throws an exception if the expression cannot be evaluated at bake-time (such expressions cannot be used in some situations, e.g. to specify output files). Paths are returned as native paths.

Use bkl.expr.Formatter if you need to format expressions into strings.

See also

is_const()

has_bool_operands()

Returns true if the operator is such that it requires boolean operands (i.e. NOT, AND, OR).

AND = '&&'

And operator

EQUAL = '=='

Equality operator

NOT = '!'

Not operator; unlike others, this one is unary and has no right operand.

NOT_EQUAL = '!='

Inequality operator

OR = '||'

Or operator

class bkl.expr.BoolValueExpr(value, pos=None)

Bases: bkl.expr.Expr

Constant boolean value, i.e. true or false.

value

Value of the literal, as (Python) boolean.

as_py()

Returns the expression as Python value (e.g. a list of strings) if it evaluates to a constant literal. Throws an exception if the expression cannot be evaluated at bake-time (such expressions cannot be used in some situations, e.g. to specify output files). Paths are returned as native paths.

Use bkl.expr.Formatter if you need to format expressions into strings.

See also

is_const()

class bkl.expr.ConcatExpr(items, pos=None)

Bases: bkl.expr.Expr

Concatenation of several expression. Typically, used with LiteralExpr and ReferenceExpr to express values such as “$(foo).cpp”.

as_py()

Returns the expression as Python value (e.g. a list of strings) if it evaluates to a constant literal. Throws an exception if the expression cannot be evaluated at bake-time (such expressions cannot be used in some situations, e.g. to specify output files). Paths are returned as native paths.

Use bkl.expr.Formatter if you need to format expressions into strings.

See also

is_const()

class bkl.expr.CondTrackingMixin

Helper mixin class for tracking currently active condition. Useful for handling e.g. nested if statements.

active_if_cond

Currently active condition, if any.

class bkl.expr.Expr(pos=None)

Bases: object

Value expression.

Represents a value (typically assigned to a variable, but also expressions used somewhere else, e.g. as conditions) as tree of expression objects. In Bakefile, the expressions are kept in tree representation until the last possible moment, and are manipulated in this form.

Note that expression objects are immutable: if you need to modify an expression, replace it with a new object.

pos

Location of the expression in source tree.

as_py()

Returns the expression as Python value (e.g. a list of strings) if it evaluates to a constant literal. Throws an exception if the expression cannot be evaluated at bake-time (such expressions cannot be used in some situations, e.g. to specify output files). Paths are returned as native paths.

Use bkl.expr.Formatter if you need to format expressions into strings.

See also

is_const()

as_symbolic()

Returns the value as a symbolic representation, see SymbolicFormatter.

is_const()

Returns true if the expression is constant, i.e. can be evaluated at this time (bake-time), as opposed to expressions that depend on a setting that can only be determined at make-time.

See also

as_py()

is_null()

Returns true if the expression evaluates to null, i.e. empty value.

class bkl.expr.Formatter(paths_info)

Bases: bkl.expr.Visitor

Base class for expression formatters. A formatter is a class that formats the expression into a string in the way that is needed on the output. For example, it handles things such as path separators on different platforms, variable references, quoting of literals with whitespace in them and so on.

The base class implements commonly used formatting, such as using whitespace for delimiting list items etc.

Use the format() method to format an expression.

list_sep

Separator for list items (by default, single space).

paths_info

PathAnchorsInfo information object to use for formatting of paths.

bool(e)

Called on BoolExpr expressions.

bool_value(e)

Called on BoolValueExpr expressions.

concat(e)

Called on ConcatExpr expressions.

format(e)

Formats expression e into a string.

if_(e)

Called on IfExpr expressions.

list(e)

Called on ListExpr expressions.

literal(e)

Called on LiteralExpr expressions.

null(e)

Called on NullExpr expressions.

path(e)

Called on PathExpr expressions.

reference(e)

Called on ReferenceExpr expressions.

class bkl.expr.IfExpr(cond, yes, no, pos=None)

Bases: bkl.expr.Expr

Conditional expression.

cond

The condition expression.

value_yes

Value of the expression if the condition evaluates to True.

value_no

Value of the expression if the condition evaluates to False.

as_py()

Returns the expression as Python value (e.g. a list of strings) if it evaluates to a constant literal. Throws an exception if the expression cannot be evaluated at bake-time (such expressions cannot be used in some situations, e.g. to specify output files). Paths are returned as native paths.

Use bkl.expr.Formatter if you need to format expressions into strings.

See also

is_const()

get_value()

Returns value of the conditional expression, i.e. either value_yes or value_no, depending on what the condition evaluates to. Throws if the condition cannot be evaluated.

class bkl.expr.ListExpr(items, pos=None)

Bases: bkl.expr.Expr

List expression – list of several values of the same type.

as_py()

Returns the expression as Python value (e.g. a list of strings) if it evaluates to a constant literal. Throws an exception if the expression cannot be evaluated at bake-time (such expressions cannot be used in some situations, e.g. to specify output files). Paths are returned as native paths.

Use bkl.expr.Formatter if you need to format expressions into strings.

See also

is_const()

class bkl.expr.LiteralExpr(value, pos=None)

Bases: bkl.expr.Expr

Constant expression – holds a literal.

value

Value of the literal.

pos

Location of the expression in source tree.

as_py()

Returns the expression as Python value (e.g. a list of strings) if it evaluates to a constant literal. Throws an exception if the expression cannot be evaluated at bake-time (such expressions cannot be used in some situations, e.g. to specify output files). Paths are returned as native paths.

Use bkl.expr.Formatter if you need to format expressions into strings.

See also

is_const()

class bkl.expr.NullExpr(pos=None)

Bases: bkl.expr.Expr

Empty/unset value.

as_py()

Returns the expression as Python value (e.g. a list of strings) if it evaluates to a constant literal. Throws an exception if the expression cannot be evaluated at bake-time (such expressions cannot be used in some situations, e.g. to specify output files). Paths are returned as native paths.

Use bkl.expr.Formatter if you need to format expressions into strings.

See also

is_const()

class bkl.expr.PathAnchorsInfo(dirsep, outfile, builddir, model)

Bases: object

Struct with information about real values for symbolic anchors of PathExpr paths. These are needed in order to format path expression (using bkl.expr.Formatter or otherwise).

dirsep

Separator to separate path components (“/” on Unix and “” on Windows).

top_srcdir

Path to the top source directory, as a list of components, relative to the output directory. Will be empty list if the paths are the same.

builddir

Path to the build directory – the directory where object files and other generated files are put – as a list of components, relative to the output directory. Will be empty list if the paths are the same.

top_srcdir_abs

Absolute native path to the top source directory.

outdir_abs

Absolute native path to the output directory – the directory where the project or makefile currently being generated is written to.

builddir_abs

Absolute native path to the build directory.

The constructor creates anchors information from native paths passed to it:

Parameters:
  • dirsep – Path components separator, same as the dirsep attribute.
  • outfile – (Native) path to the output file (project, makefile). Paths in the output will be typically formatted relatively to this path. The outdir_abs attribute is computed from this parameter.
  • builddir – (Native) path to the build directory. May be None if builddir-relative paths make no sense in this context (e.g. for VS2010 solution files).
  • model – Part of the model (bkl.model.Module or bkl.model.Target) that outfile corresponds to.
class bkl.expr.PathExpr(components, anchor='@srcdir', anchor_file=None, pos=None)

Bases: bkl.expr.Expr

Expression that holds a file or directory name, or part of it.

components

List of path’s components (as expressions). For example, components of path foo/bar/file.cpp are ["foo", "bar", "file.cpp"].

anchor

The point to which the path is relative to. This can be one of the following:

  • expr.ANCHOR_SRCDIR – Path is relative to the directory where the input bakefile is (unless overridden in it).
  • expr.ANCHOR_TOP_SRCDIR – Path is relative to the top source directory (where the toplevel .bkl file is, unless overridden in it).
  • expr.ANCHOR_BUILDDIR – Path is relative to the build directory. Either this anchor or expr.ANCHOR_TOP_BUILDDIR should be used for all transient files (object files or other generated files).
  • expr.ANCHOR_TOP_BUILDDIR – Path is relative to the top build directory. This is currently only used by makefile backends where the build directory for a sub-makefile is different from the top one.
anchor_file

Name of the file the anchor was written in. This is important for @srcdir, which is relative to this place.

pos

Location of the expression in source tree.

as_native_path(paths_info)

Returns the path expressed as absolute native path. Requires complete bkl.expr.PathAnchorsInfo information as its argument.

Throws NonConstError if it cannot be done because of conditional subexpression.

as_native_path_for_output(model)

Specialized version of as_native_path() that only works with srcdir-based paths. It’s useful for code that needs to obtain output file name (which happens before PathAnchorsInfo can be constructed).

Parameters:model – Any part of the model.
as_py()

Returns the expression as Python value (e.g. a list of strings) if it evaluates to a constant literal. Throws an exception if the expression cannot be evaluated at bake-time (such expressions cannot be used in some situations, e.g. to specify output files). Paths are returned as native paths.

Use bkl.expr.Formatter if you need to format expressions into strings.

See also

is_const()

change_extension(newext)

Changes extension of the filename to newext and returns bkl.expr.PathExpr with the new path.

get_basename()

Returns basename of the filename path (i.e. the name without directory or extension). Throws if it cannot be determined.

get_directory_path()

Returns PathExpr with the directory component.

get_extension()

Returns extension of the filename path. Throws if it cannot be determined.

is_external_absolute()

Returns true if the path is to be treated as an absolute path provided externally (i.e. via an user setting) when the makefile was invoked.

TODO: add a @absdir anchor instead?

class bkl.expr.PlaceholderExpr(var, pos=None)

Bases: bkl.expr.Expr

This is a hack. It is used as placeholder for expressions with not yet known value. In particular, it is used for the “toolset” property before the model is split into toolset-specific copies, to allow partial evaluation common to all of them.

var

Name of referenced setting (e.g. “config” or “toolset”).

as_py()

Returns the expression as Python value (e.g. a list of strings) if it evaluates to a constant literal. Throws an exception if the expression cannot be evaluated at bake-time (such expressions cannot be used in some situations, e.g. to specify output files). Paths are returned as native paths.

Use bkl.expr.Formatter if you need to format expressions into strings.

See also

is_const()

class bkl.expr.ReferenceExpr(var, context, pos=None)

Bases: bkl.expr.Expr

Reference to a variable.

var

Name of referenced variable.

context

Context of the reference, i.e. the scope in which it was used. This is the appropriate bkl.model.ModelPart instance (e.g. a target or a module).

as_py()

Returns the expression as Python value (e.g. a list of strings) if it evaluates to a constant literal. Throws an exception if the expression cannot be evaluated at bake-time (such expressions cannot be used in some situations, e.g. to specify output files). Paths are returned as native paths.

Use bkl.expr.Formatter if you need to format expressions into strings.

See also

is_const()

get_value()

Returns value of the referenced variable. Throws an exception if the reference couldn’t be resolved.

get_variable()

Return the variable object this reference points to.

Use this method only if necessary; whenever possible, get_value() should be used instead.

Note that the returned value may be None, either if the referenced variable doesn’t exist or when the reference is to a property that wasn’t explicitly set and uses the default value.

class bkl.expr.RewritingVisitor

Bases: bkl.expr.Visitor

Base class for visitors that perform some changes to the expression.

RewritingVisitor is smart about the rewrites and if nothing changes, returns the same instance, instead of creating an identical copy.

It also implements all Visitor methods to do the right thing by default, so you only need to override the ones that are of interest. Default implementations of the others will do the right thing: for example, if an item in the list is rewritten, the list() method will detect it and return a new list.

bool(e)

Called on BoolExpr expressions.

concat(e)

Called on ConcatExpr expressions.

if_(e)

Called on IfExpr expressions.

list(e)

Called on ListExpr expressions.

path(e)

Called on PathExpr expressions.

class bkl.expr.SymbolicFormatter

Bases: bkl.expr.Formatter

Formats into unambiguous symbolic representation of the expression.

bool(e)

Called on BoolExpr expressions.

bool_value(e)

Called on BoolValueExpr expressions.

concat(e)

Called on ConcatExpr expressions.

if_(e)

Called on IfExpr expressions.

list(e)

Called on ListExpr expressions.

literal(e)

Called on LiteralExpr expressions.

null(e)

Called on NullExpr expressions.

path(e)

Called on PathExpr expressions.

placeholder(e)

Called on PlaceholderExpr expressions.

class bkl.expr.Visitor

Bases: object

Implements visitor pattern for Expr expressions. This is abstract base class, derived classes must implement all of its methods except visit(). The way visitors are used is that the caller calls visit() on the expression.

bool(e)

Called on BoolExpr expressions.

bool_value(e)

Called on BoolValueExpr expressions.

concat(e)

Called on ConcatExpr expressions.

if_(e)

Called on IfExpr expressions.

list(e)

Called on ListExpr expressions.

literal(e)

Called on LiteralExpr expressions.

noop(e)

Helper to quickly implement handler functions that do nothing.

null(e)

Called on NullExpr expressions.

path(e)

Called on PathExpr expressions.

placeholder(e)

Called on PlaceholderExpr expressions.

reference(e)

Called on ReferenceExpr expressions.

visit(e)

Call this method to visit expression e. One of object’s “callback” methods will be called, depending on e’s type.

Return value is the value returned by the appropriate callback and is typically None.

visit_children(e)

Helper to implement visitor methods that just need to recursively work on all children. Ignores return value for the children.

bkl.expr.add_prefix(prefix, e)

Adds a prefix in front of the expression e or, if e is a list, in front of each of its elements.

Parameters:
  • prefix – The prefix to add; either an bkl.expr.Expr object or a string.
  • e – The expression to add the prefix in front of.
bkl.expr.are_equal(a, b, _inside_cond=False)

Compares two expressions for equality.

Throws the CannotDetermineError exception if it cannot reliably determine equality.

bkl.expr.concat(*parts)

Concatenates all arguments and returns bkl.expr.ConcatExpr. The arguments may be expressions or string literals.

bkl.expr.enum_possible_values(e, global_cond=None)

Returns all values that are possible, together with their respective conditions, as an iteratable of (condition, value) tuples. The condition may be None if the value is always there, otherwise it is a boolean bkl.expr.Expr.

Note that this function returns possible elements for lists. It skips null expressions as well.

Parameters:
  • e – Expression to extract possible values from.
  • global_cond – Optional condition expression (bkl.expr.Expr) to apply to all items. If specified, then every tuple in returned list will have the condition set to either global_cond (for unconditional items) or its combination with per-item condition.
bkl.expr.format_string(format, values)

Substitutes occurrences of “%(varname)” in the format string with values from the dictionary values, similarly to the ‘%’ operator. Values in the dictionary may be either Expr objects or strings.

Note that there’s currently no way to escape “%” in such expressions.

bkl.expr.get_model_name_from_path(e)

Give an expression representing filename, return name suitable for model.SourceFile.name.

bkl.expr.keep_possible_values_unexpanded(e)

Determines if the given reference value should be expanded or not.

This is a helper of enum_possible_values() and is used to decide whether a value returned by that function is fully expanded or kept in its original form, with variable references in it. The latter is useful when dealing with the source files containing variables as it prevents them from being expanded too early, before the variable value for the current target is really known.

However anything not representing a simple single value should still be expanded and this function task is to check whether the argument is a reference to such simple single value or not.

bkl.expr.split(e, sep)

Splits expression e into a list of expressions, using sep as the delimiter character. Works with conditional expressions and variable references too.

bkl.expr.split_into_path(e)

Splits expression e into a list of expressions, using ‘/’ as the delimiter character. Returns a PathExpr. Works with conditional expressions and variable references too.

5.2.1.3. bkl.vartypes – variables types

This module defines types interface as well as basic types. The types – i.e. objects derived from bkl.vartypes.Type – are used to verify validity of variable values and other expressions.

class bkl.vartypes.AnyType

Bases: bkl.vartypes.Type

A fallback type that allows any value at all.

validate(e)

Validates if the expression e is of this type. If it isn’t, throws bkl.error.TypeError with description of the error.

Note that this method transparently handles references and conditional expressions.

class bkl.vartypes.BoolType

Bases: bkl.vartypes.Type

Boolean value type. May be product of a boolean expression or one of the following literals with obvious meanings: “true” or “false”.

class bkl.vartypes.EnumType(name, allowed_values)

Bases: bkl.vartypes.Type

Enum type. The value must be one of allowed values passed to the constructor.

allowed_values

List of allowed values (strings).

class bkl.vartypes.IdType

Bases: bkl.vartypes.Type

Type for target IDs.

class bkl.vartypes.ListType(item_type)

Bases: bkl.vartypes.Type

Type for a list of items of homogeneous type.

item_type

Type of items stored in the list (bkl.vartypes.Type instance).

class bkl.vartypes.PathType

Bases: bkl.vartypes.Type

A file or directory name.

class bkl.vartypes.StringType

Bases: bkl.vartypes.Type

Any string value.

class bkl.vartypes.Type

Bases: object

Base class for all Bakefile types.

name

Human-readable name of the type, e.g. “path” or “bool”.

normalize(e)

Normalizes the expression e to be of this type, if it can be done. If it cannot be, does nothing.

Returns e if no normalization was done or a new expression with normalized form of e.

validate(e)

Validates if the expression e is of this type. If it isn’t, throws bkl.error.TypeError with description of the error.

Note that this method transparently handles references and conditional expressions.

bkl.vartypes.guess_expr_type(e)

Attempts to guess type of the expression if it’s possible. Returns AnyType type if unsure.

bkl.vartypes.normalize_and_validate_bool_subexpressions(e)

Performs type normalization and validation steps for typed subexpressions, namely for IfExpr conditions and boolean expressions.

bkl.vartypes.TheAnyType = <bkl.vartypes.AnyType object>

For efficiency, singleton instance of AnyType

5.2.1.4. bkl.api – public extensions API

class bkl.api.BuildNode(commands, inputs=[], outputs=[], name=None, source_pos=None)

Bases: object

BuildNode represents a single node in traditional make-style build graph. Bakefile’s model is higher-level than that, its targets may represent entities that will be mapped into several makefile targets. But BuildNode is the simplest element of build process: a list of commands to run together with dependencies that describe when to run it and a list of outputs the commands create.

Node’s commands are executed if either a) some of its outputs doesn’t exist or b) any of the inputs was modified since the last time the outputs were modified.

name

Name of build node. May be empty. If not empty and the node has no output files (i.e. is phony), then this name is used in the generated makefiles. It is ignored in all other cases.

inputs

List of all inputs for this node. Its items are filenames (as bkl.expr.PathExpr expressions) or (phony) target names.

outputs

List of all outputs this node generates. Its items are filenames (as bkl.expr.PathExpr expressions).

A node with no outputs is called phony.

commands:

List of commands to execute when the rebuild condition is met, as bkl.expr.Expr.

source_pos

Source code position of whatever code was the cause for the creation of this BuildNode (e.g. associated source file), or None.

class bkl.api.BuildSubgraph(main, secondary=[])

Bases: object

BuildSubgraph is a collection of bkl.api.BuildNode nodes.

main

Primary build node of a target (e.g. its executable file).

secondary

A list of any secondary nodes needed to build the main nodes (e.g. object files for target’s source files). May be empty.

all_nodes()

Yield all nodes included in the subgraph.

class bkl.api.CustomStep

Bases: bkl.api.Extension

Custom processing step that is applied to the loaded model.

Plugins of this kind can be used to perform any custom operations with the model. For example, they may enforce coding style, they may add or modify some properties or even generate auxiliary output files.

CustomStep class has several hook methods called at different phases of processing. All of them do nothing by default and reimplementing them is optional.

finalize(model)

Called after loading the model from file(s) and before doing any optimizations or error checking on it.

Do not create any output files here, leave that to generate().

generate(model)

Called right before generating the output. It is called on the common model, before optimizing it for individual toolsets.

It is permitted to create output files in this method.

class bkl.api.Extension

Bases: object

Base class for all Bakefile extensions.

Extensions are singletons, there’s always only one instance of given extension at runtime. Use the get() method called on appropriate extension type to obtain it. For example:

program = TargetType.get(“program”) # …do something with it…
name

Use-visible name of the extension. For example, the name for targets extensions is what is used in target declarations; likewise for property names.

classmethod all()

Returns iterator over instances of all implementations of this extension type.

classmethod all_names()

Returns names of all implementations of this extension type.

classmethod all_properties(kind='properties')

For derived extension types that have properties e.g. TargetType), returns iterator over all properties.

The class must have class member variable var:properties with a list of bkl.api.Property instances. Base class’ properties are automagically scanned too.

Parameters:kind – Kind (i.e. attribute name) of the properties to list. By default, “properties”, but may be more specific, e.g. “properties_module” or “properties_vs2010”.

See also

bkl.api.Property

classmethod all_properties_kinds()

Returns a set of names of all properties attributes in this class. These are attributes named “properties” or “properties_<something>”, e.g. “properties_module” for properties with module scope.

classmethod get(name=None)

This class method is used to get an instance of an extension. In can be used in one of two ways:

  1. When called on an extension type class with name argument, it returns instance of extension with given name and of the extension type on which this classmethod was called:

    >>> bkl.api.Toolset.get("gnu")
        <bkl.plugins.gnu.GnuToolset object at 0x2232950>
    
  2. When called without the name argument, it must be called on particular extension class and returns its (singleton) instance:

    >>> GnuToolset.get()
        <bkl.plugins.gnu.GnuToolset object at 0x2232950>
    
Parameters:name – Name of the extension to read; this corresponds to class’ “name” attribute. If not specified, then get() must be called on a extension, not extension base class.
class bkl.api.FileCompiler

Bases: bkl.api.Extension

In Bakefile API, FileCompiler is used to define all compilation steps.

Traditionally, the term compiler is used for a tool that compiles source code into object files. In Bakefile, a file compiler is generalization of this term: it’s a tool that compiles file or files of one object type into one or more files of another type. In this meaning, a C/C++ compiler is a file compiler, but so is a linker (it “compiles” object files into executables) or e.g. Lex/Yacc compiler or Qt’s MOC preprocessor.

commands(toolset, target, input, output)

Returns list of commands (as bkl.expr.Expr) to invoke the compiler.

Parameters:
  • toolset – Toolset used.
  • target – The target object for which the invocation is done.
  • input – Input file (bkl.expr.PathExpr) or files (bkl.expr.ListExpr), depending on cardinality.
  • outputbkl.expr.Expr expression with the name of output file.
is_supported(toolset)

Returns whether given toolset is supported by this compiler.

Default implementation returns True for all toolsets.

cardinality = '1'

Cardinality of the compiler. That is, whether it compiles one file into one file (FileCompiler.ONE_TO_ONE, e.g. C compilers) or whether it compiles many files of the same type into one output file (FileCompiler.MANY_TO_ONE, e.g. the linker or Java compiler).

in_type = None

bkl.api.FileType for compiler’s input file.

out_type = None

bkl.api.FileType for compiler’s output file.

class bkl.api.FileRecognizer

Bases: object

Mixin base class for extensions that handle certain file types and need to be associated with a file automatically. The class provides easy to use get_for_file() mechanism.

To use this class, derive from both bkl.api.Extension and this one.

detect(filename)

Returns True if the file filename is supported by the class. Note that it is only called if the file has one of the extensions listed in extensions. By default, returns True.

Parameters:filename – Name of the file to check. Note that this is native filename (as a string) and points to existing file.
classmethod get_for_file(filename)

Returns appropriate implementation of the class for given file.

Throws bkl.error.UnsupportedError if no implementation could be found.

Parameters:filename – Name of the file, as a native path.
extensions = []

List of file extensions recognized by this extension, without dots (e.g. ["vcproj", "vcxproj"]).

class bkl.api.FileType(extensions=[])

Bases: bkl.api.Extension, bkl.api.FileRecognizer

Description of a file type. File types are used by bkl.api.FileCompiler to define both input and output files.

extensions

List of extensions for this file type, e.g. ["cpp", "cxx", "cc"].

class bkl.api.Property(name, type, default=None, readonly=False, inheritable=False, doc=None)

Bases: object

Properties describe variables on targets etc. that are part of the API – that is, they have special meaning for the toolset and. Unlike free-form variables, properties have a type associated with them and any values assigned to them are checked for type correctness. They can optionally have a default value, too.

name

Name of the property/variable.

type

Type of the property, as bkl.vartypes.Type instance.

default

Default value of the property (as bkl.expr.Expr or a function that returns an expression) or None. If not specified (i.e. None), then this property is required and must always be set to a value in the bakefile.

readonly

Indicates if the property is read-only. Read-only properties can only have the default value and cannot be modified. They are typically derived from some other value and exist as a convenience. An example of read-only property is the id property on targets.

scopes

Optional scope of the property, as list of strings. Each item may be one of Property.SCOPE_PROJECT, Property.SCOPE_MODULE, Property.SCOPE_TARGET for any target or target type name (e.g. program) for scoping on specific target name.

Finally, may be None for default (depending from where the property was obtained from).

inheritable

A property is inheritable if its value can be specified in the (grand-)parent scope. For example, an inheritable property on a target may be specified at the module level or even in the parent module; an inheritable property on a source file (e.g. “defines”) may be specified on the target, the module and so on.

toolsets

List of toolset names for toolsets this property applies to. This is mostly for documentation purposes, it doesn’t affect their processing. Is None for toolset-agnostic properties.

doc

Optional documentation for the property.

Example usage:

class FooTarget(bkl.api.TargetType):
    name = "foo"
    properties = [
        Property("deps",
              type=ListType(IdType()),
              default=[],
              doc="Target's dependencies (list of IDs).")
    ]
    ...
default_expr(for_obj, throw_if_required)

Returns the value of default expression. Always returns an bkl.expr.Expr instance, even if the default is of a different type.

Parameters:
  • for_obj – The class:bkl.model.ModelPart object to return the default for. If the default value is defined, its expression is evaluated in the context of for_obj.
  • throw_if_required – If False, returns NullExpr if the property is a required one (doesn’t have a default value). If True, throws in that case.
internal

True if the property is for internal purposes and shouldn’t be used by users, False otherwise.

class bkl.api.TargetType

Bases: bkl.api.Extension

Base class for implementation of a new target type.

get_build_subgraph(toolset, target)

Returns a bkl.api.BuildSubgraph object with description of this target’s local part of build graph – that is, its part needed to produce output files associated with this target.

Usually, a BuildSubgraph with just one main BuildNode will be returned, but it’s possible to have TargetTypes that correspond to more than one makefile target (e.g. libtool-style libraries or gettext catalogs).

Parameters:
vs_project(toolset, target)

Returns Visual Studio project file object (derived from bkl.plugins.vsbase.VSProjectBase) if the target type can be implemented as a Visual Studio project.

Implementing this method is strictly optional.

properties = []

List of all properties supported on this target type, as Property instances. Note that properties list is automagically inherited from base classes, if any.

class bkl.api.Toolset

Bases: bkl.api.Extension

This class encapsulates generating of the project files or makefiles.

The term “toolset” refers to collection of tools (compiler, linker, make, IDE, …) used to compile programs. For example, “Visual C++ 2008”, “Visual C++ 2005”, “Xcode” or “Borland C++” are toolsets.

In Bakefile API, this class is responsible for creation of the output. It puts all the components (platform-specific commands, make syntax, compiler invocation, …) together and writes out the makefiles or projects.

generate(project)

Generates all output files for this toolset.

Parameters:project – model.Project instance with complete description of the output. It was already preprocessed to remove content not relevant for this toolset (e.g. targets or sub-modules built conditionally only for other toolsets, conditionals that are always true or false within the toolset and so on).
get_builddir_for(target)

Returns build directory used for target.

Returned value must be a bkl.expr.PathExpr expression object, but it doesn’t have to be a constant (for example, it may reference configuration name, as e.g. Visual Studio does).

The function is called after the model is fully loaded and partially simplified, on a model already specialized for this toolset only. It is used to replace path expression with the relative @builddir anchor with absolute paths.

properties = []

List of all properties supported on this target type, as Property instances. Note that properties list is automagically inherited from base classes, if any.

5.2.1.5. bkl.error – exceptions and errors handling

This module contains helper classes for simple handling of errors. In particular, the Error class keeps track of the position in source code where the error occurred or to which it relates to.

exception bkl.error.CannotDetermineError(msg=None, pos=None)

Bases: bkl.error.NonConstError

Exception thrown when something (e.g. equality) cannot be determined. This usually signifies a weakness in Bakefile implementation that should be improved.

exception bkl.error.Error(msg, pos=None)

Bases: exceptions.Exception

Base class for all Bakefile errors.

When converted to string, the message is formatted in the usual way of compilers, as file:line: error.

msg

Error message to show to the user.

pos

bkl.parser.ast.Position object with location of the error. May be None.

exception bkl.error.NonConstError(msg, pos=None)

Bases: bkl.error.Error

Exception thrown when attempting to convert an expression into bake-time constant.

exception bkl.error.NotFoundError(msg, pos=None)

Bases: bkl.error.Error

Exception thrown when a property or variable wasn’t found at all.

exception bkl.error.ParserError(msg, pos=None)

Bases: bkl.error.Error

Exception class for errors encountered by the Bakefile parser.

exception bkl.error.TypeError(type, expr, msg=None, pos=None)

Bases: bkl.error.Error

Exception class for variable type errors.

detail

Any extra details about the error or (usually) None.

Convenience constructor creates error message appropriate for the type and expression test, in the form of expression expr is not type or expression expr is not type: msg if additional message is supplied.

Parameters:
  • typebkl.vartypes.Type instance the error is related to.
  • exprbkl.expr.Expr expression that caused the error.
  • msg – Optional error message detailing reasons for the error. This will be stored as detail if provided.
exception bkl.error.UndefinedError(msg, pos=None)

Bases: bkl.error.Error

Exception thrown when a property or variable is undefined, i.e. doesn’t have a value.

exception bkl.error.UnsupportedError(msg, pos=None)

Bases: bkl.error.Error

Exception class for errors when something is unsupported, e.g. unrecognized file extension.

exception bkl.error.VersionError(msg, pos=None)

Bases: bkl.error.Error

Exception raised when Bakefile version is too old for the input.

class bkl.error.error_context(context)

Error context for adding positional information to exceptions thrown without one. This can happen in some situations when the particular expression causing the error isn’t available. In such situations, it’s much better to provide coarse position information (e.g. a target) instead of not providing any at all.

Usage:

with error_context(target):
   ...do something that may throw...
pos

bkl.parser.ast.Position object with location of the error. May be None.

bkl.error.warning(msg, *args, **kwargs)

Logs a warning.

The function takes position arguments similarly to logging module’s functions. It also accepts options pos argument with position information as bkl.parser.ast.Position.

Uses active error_context instances to decorate the warning with position information if not provided.

Usage:

bkl.error.warning("target %s not supported", t.name, pos=t.source_pos)

5.2.1.6. bkl.io – I/O helpers

Helper classes for Bakefile I/O. Manages atomic writing of output, detecting changes, line endings conversions etc.

class bkl.io.OutputFile(filename, eol, charset='utf-8', creator=None, create_for=None)

Bases: object

File to be written by Bakefile.

Example usage:

f = io.OutputFile("Makefile")
f.write(body)
f.commit()

Notice the need to explicitly call commit().

Creates output file.

Parameters:
  • filename – Name of the output file. Should be either relative to CWD or absolute; the latter is recommended.
  • eol – Line endings to use. One of EOL_WINDOWS and EOL_UNIX.
  • charset – Charset to use if Unicode string is passed to write().
  • creator – Who is creating the file; typically toolset object.
  • create_for – Object the file is created for, e.g. a module or a target.
replace(placeholder, value)

Replaces the value of the given placeholder with its real value. This is useful for parts of the output which are not known at the time they are written because they depend on other parts coming after them.

Notice that only the first occurrency of the placeholder is replaced.

write(text)

Writes text to the output, performing line endings conversion as needed. Note that the changes don’t take effect until you call commit().

5.2.1.7. bkl.makefile – support for implementing makefiles toolsets

Foundation code for makefile-based toolsets.

All makefile-based toolsets should derive from MakefileToolset defined in this module.

class bkl.makefile.MakefileExprFormatter(toolset, paths_info)

Bases: bkl.expr.Formatter

literal(e)

Called on LiteralExpr expressions.

path(e)

Called on PathExpr expressions.

placeholder(e)

Called on PlaceholderExpr expressions.

class bkl.makefile.MakefileFormatter

Bases: bkl.api.Extension

MakefileFormatter extensions are used to format makefiles content (i.e. targets and their commands) in the particular makefiles format.

This includes things such as expressing conditional content, referencing variables and so on.

Note that formatters do not handle platform- or compiler-specific things, e.g. path separators or compiler invocation. There are done by bkl.expr.Formatter and bkl.api.FileCompiler classes.

This base class implements methods that are common for most make variants; derived classes can override them and they must implement the rest.

comment(text)

Returns given (possibly multi-line) string formatted as a comment.

Parameters:text – text of the comment
multifile_target(outputs, outfiles, deps, commands)

Returns string with target definition for targets that produce multiple files. A typical example is Bison parser generator, which produces both .c and .h files.

Parameters:
  • outputs – List of output files of the rule, as objects.
  • outfiles – List of output files of the rule, as strings.
  • deps – See target()
  • commands – See target()
submake_command(directory, filename, target)

Returns string with command to invoke make in subdirectory directory on makefile filename, running target.

target(name, deps, commands)

Returns string with target definition.

Parameters:
  • name – Name of the target.
  • deps – List of its dependencies. Items are strings corresponding to some target’s name (may be expressions that reference a variable, in that case the string must already be formatted with appropriate bkl.expr.Formatter). May be empty.
  • commands – List of commands to execute to build the target; they are already formatted to be in make’s syntax and each command in the list is single-line shell command. May be None.
var_definition(var, value)

Returns string with definition of a variable value, typically var = value.

Parameters:
  • var – variable being defined
  • value – value of the variable; this string is already formatted to be in make’s syntax and may be multi-line
class bkl.makefile.MakefileToolset

Bases: bkl.api.Toolset

Base class for makefile-based toolsets.

ExprFormatter

expr.Formatter-derived class for this toolset.

alias of MakefileExprFormatter

generate(project)

Generates all output files for this toolset.

Parameters:project – model.Project instance with complete description of the output. It was already preprocessed to remove content not relevant for this toolset (e.g. targets or sub-modules built conditionally only for other toolsets, conditionals that are always true or false within the toolset and so on).
get_builddir_for(target)

Returns build directory used for target.

Returned value must be a bkl.expr.PathExpr expression object, but it doesn’t have to be a constant (for example, it may reference configuration name, as e.g. Visual Studio does).

The function is called after the model is fully loaded and partially simplified, on a model already specialized for this toolset only. It is used to replace path expression with the relative @builddir anchor with absolute paths.

Called at the end of generating the output to add any ending text, for example unconditional inclusion of dependencies tracking code.

on_header(file, module)

Called before starting generating the output to add any header text, typically used to pre-define any make variables.

Call the base class version first to insert a warning about the file being auto-generated.

on_phony_targets(file, targets)

Called with a list of all phony (i.e. not producing actual files) targets (as their names as strings) when generating given file.

Formatter = None

MakefileFormatter-derived class for this toolset.

autoclean_extensions = []

Files with extensions from this list will be automatically deleted by “make clean”.

default_makefile = None

Default filename from output makefile.

del_command = None

Command used to delete files

5.2.1.8. bkl.compilers – FileCompiler helpers

Helpers for working with bkl.api.FileType and bkl.api.FileCompiler extensions.

class bkl.compilers.CFileType

Bases: bkl.api.FileType

class bkl.compilers.CxxFileType

Bases: bkl.api.FileType

class bkl.compilers.NativeLibFileType(extensions=[])

Bases: bkl.api.FileType

class bkl.compilers.NativeLoadableModuleFileType(extensions=[])

Bases: bkl.api.FileType

class bkl.compilers.NativeProgramFileType(extensions=[])

Bases: bkl.api.FileType

class bkl.compilers.NativeSharedLibraryFileType(extensions=[])

Bases: bkl.api.FileType

bkl.compilers.disambiguate_intermediate_file_names(files)

Given a list of SourceFile objects, finds files that would have conflicting object file names (e.g. foo/x.cpp and bar/x.cpp would use the same x.obj filename).

Returns dictionary with SourceFile objects as keys and unambiguous basenames (e.g. ‘x_foo’ and ‘x_bar’ for the above example). Only files with conflicts are included in the dictionary (consequently, it will be empty or near-empty most of the time).

bkl.compilers.get_compilation_subgraph(toolset, target, ft_to, outfile)

Given list of source files (as bkl.expr.ListExpr), produces build subgraph (bkl.api.BuildSubgraph) with appropriate bkl.api.BuildNode nodes.

Parameters:
  • toolset – The toolset used (as bkl.api.Toolset).
  • target – The target object for which the invocation is done.
  • ft_to – Type of the output file to compile to.
  • outfile – Name of the output file (as bkl.expr.PathExpr).
bkl.compilers.get_compiler(toolset, ft_from, ft_to)

Finds the compiler that compiles files of type ft_from into ft_to. Both arguments are bkl.api.FileType instances.

The returned object is a singleton. If such compiler cannot be found, returns None.

bkl.compilers.get_file_type(extension)

Returns file type instance based on extension.

The returned object is a singleton.

>>> a = get_file_type("cpp")
>>> b = get_file_type("cpp")
>>> assert a is b
bkl.compilers.get_file_types_compilable_into(toolset, ft)

Returns file types that can be compiled into ft.