cmake_format package

Module contents

Parse cmake listfiles and format them nicely

Submodules

cmake_format.configuration module

class cmake_format.configuration.Configuration(**kwargs)[source]

Bases: cmake_format.config_util.ConfigObject

Various configuration options and parameters

encode

Implements the descriptor interface for nested configuration objects.

format

Implements the descriptor interface for nested configuration objects.

lint

Implements the descriptor interface for nested configuration objects.

markup

Implements the descriptor interface for nested configuration objects.

misc

Implements the descriptor interface for nested configuration objects.

parse

Implements the descriptor interface for nested configuration objects.

resolve_for_command(command_name, config_key, default_value=None)[source]

Check for a per-command value or override of the given configuration key and return it if it exists. Otherwise return the global configuration value for that key.

class cmake_format.configuration.EncodingConfig(**kwargs)[source]

Bases: cmake_format.config_util.ConfigObject

Options affecting file encoding

emit_byteorder_mark = False
input_encoding = 'utf-8'
output_encoding = 'utf-8'
class cmake_format.configuration.FormattingConfig(**kwargs)[source]

Bases: cmake_format.config_util.ConfigObject

Options affecting formatting.

always_wrap = []
autosort = False
command_case = 'canonical'
dangle_align = 'prefix'
dangle_parens = False
enable_sort = True
keyword_case = 'unchanged'
layout_passes = {}
line_ending = 'unix'
line_width = 80
linewidth
max_lines_hwrap = 2
max_pargs_hwrap = 6
max_prefix_chars = 10
max_rows_cmdline = 2
max_subgroups_hwrap = 2
min_prefix_chars = 4
require_valid_layout = False
separate_ctrl_name_with_space = False
separate_fn_name_with_space = False
set_line_ending(detected)[source]
tab_size = 2
class cmake_format.configuration.LinterConfig(**kwargs)[source]

Bases: cmake_format.config_util.ConfigObject

Options affecting the linter

disabled_codes = []
function_pattern = '[0-9a-z_]+'
global_var_pattern = '[0-9A-Z][0-9A-Z_]+'
internal_var_pattern = '_[0-9A-Z][0-9A-Z_]+'
keyword_pattern = '[0-9A-Z_]+'
local_var_pattern = '[0-9a-z_]+'
macro_pattern = '[0-9A-Z_]+'
max_arguments = 5
max_branches = 12
max_conditionals_custom_parser = 2
max_localvars = 15
max_returns = 6
max_statement_spacing = 1
max_statements = 50
min_statement_spacing = 1
private_var_pattern = '_[0-9a-z_]+'
public_var_pattern = '[0-9A-Z][0-9A-Z_]+'
class cmake_format.configuration.MarkupConfig(**kwargs)[source]

Bases: cmake_format.config_util.ConfigObject

Options affecting comment reflow and formatting.

bullet_char = '*'
canonicalize_hashrulers = True
enable_markup = True
enum_char = '.'
explicit_trailing_pattern = '#<'
fence_pattern = '^\\s*([`~]{3}[`~]*)(.*)$'
first_comment_is_literal = False
hashruler_min_length = 10
literal_comment_pattern = None
ruler_pattern = '^\\s*[^\\w\\s]{3}.*[^\\w\\s]{3}$'
class cmake_format.configuration.MiscConfig(**kwargs)[source]

Bases: cmake_format.config_util.ConfigObject

Miscellaneous configurations options.

per_command = {}
class cmake_format.configuration.ParseConfig(**kwargs)[source]

Bases: cmake_format.config_util.ConfigObject

Options affecting listfile parsing

additional_commands = {'foo': {'flags': ['BAR', 'BAZ'], 'kwargs': {'DEPENDS': '*', 'HEADERS': '*', 'SOURCES': '*'}}}
proptags = []
vartags = []

cmake_format.commands module

Command specifications for cmake built-in commands.

class cmake_format.commands.CommandSpec(name, pargs=None, flags=None, kwargs=None)[source]

Bases: object

A command specification is primarily a dictionary mapping keyword arguments to command specifications. It also includes a command name and number of positional arguments

add(name, pargs=None, flags=None, kwargs=None)[source]
add_conditional(name)[source]
is_flag(key)[source]
is_kwarg(key)[source]
cmake_format.commands.add_standard_nonbuiltins(fn_spec)[source]

Add commands provided by “standard” listfiles

cmake_format.commands.get_default_config()[source]

Return the default per-command configuration database

cmake_format.commands.get_fn_spec()[source]

Return a dictionary mapping cmake function names to a dictionary containing kwarg specifications.

cmake_format.commands.make_conditional_spec(name=None)[source]
cmake_format.commands.parse_pspec(pargs, flags)[source]

Parse a positional argument specification.

cmake_format.common module

class cmake_format.common.EnumObject(value)[source]

Bases: object

Simple enumeration base. Design inspired by clang python bindings BaseEnumeration. Subclasses must provide class member _id_map.

as_dict()[source]
classmethod assign_names()[source]
classmethod from_id(qid)[source]
classmethod from_name(name)[source]
classmethod get(name, default=None)[source]
name

Get the enumeration name of this value.

classmethod register_value(value, obj)[source]
exception cmake_format.common.InternalError(msg=None)[source]

Bases: Exception

Raised when we encounter something we do not expect, indicating a problem with the code itself.

exception cmake_format.common.UserError(msg=None)[source]

Bases: Exception

Raised when we encounter a fatal problem with usage: e.g. parse error, config error, input error, etc.

cmake_format.common.stable_wrap(wrapper, paragraph_text)[source]

textwrap doesn’t appear to be stable. We run it multiple times until it converges

cmake_format.formatter module

class cmake_format.formatter.ArgGroupNode(pnode)[source]

Bases: cmake_format.formatter.LayoutNode

A group of arguments. This is the single child node of either a StatementNode or KwargGroupNode which then contains any further group nodes.

has_terminal_comment()[source]

An ArgGroup is a container for one or more PARGGROUP, FLAGGROUP, or KWARGGROUP subtrees. Any terminal comment will belong to one of it’s children.

write(config, ctx)[source]

Output text content given the currently configured layout.

class cmake_format.formatter.AssertTypeDescriptor(assert_type, hidden_name)[source]

Bases: object

class cmake_format.formatter.BodyNode(pnode)[source]

Bases: cmake_format.formatter.LayoutNode

Top-level node for a given “scope” depth. This node is the root of a document, or the root of any nested statement scopes.

class cmake_format.formatter.CommentNode(pnode)[source]

Bases: cmake_format.formatter.LayoutNode

A line comment or bracket comment. If parented by a group node then this comment acts as an argument. If parented by a scalar node, then this comment acts like an argument comment.

is_tag()[source]
write(config, ctx)[source]

Output text content given the currently configured layout.

class cmake_format.formatter.Cursor(x, y)[source]

Bases: object

Lightweight class to encode integer positions in a 2d grid.

  • x = row
  • y = cols
clone()[source]

Return a new Cursor object with the same value as this one.

class cmake_format.formatter.CursorFile(config)[source]

Bases: object

assert_at(cursor)[source]
assert_lt(cursor)[source]
cursor
forge_cursor(cursor)[source]
getvalue()[source]
write(copy_text)[source]
write_at(cursor, text)[source]
class cmake_format.formatter.FlowControlNode(pnode)[source]

Bases: cmake_format.formatter.LayoutNode

Top-Level node composed of a flow-control statement and it’s associated BodyNodes.

class cmake_format.formatter.KwargGroupNode(pnode)[source]

Bases: cmake_format.formatter.LayoutNode

A keyword argument group. Contains a keyword, followed by an argument group.

has_terminal_comment()[source]

Return true if this node has a terminal line comment. In particular, this implies that no other node may be packed at the output cursor of this node’s layout, and a line-wrap is required.

name

The class name of the derived node type.

class cmake_format.formatter.LayoutNode(pnode)[source]

Bases: object

An element in the format/layout tree. The structure of the layout tree mirrors that of the parse tree. We could store this info the nodes of the parse tree itself but it’s a little cleaner to keep the functionality separate I think.

children

A list of children layout nodes

colextent

The column index of the right-most character in the layout of the subtree rooted at this node. In other words, the width of the bounding box for the subtree rooted at this node.

static create(pnode)[source]

Create a new layout node associated with then given parser node.

get_depth()[source]

Compute and return the depth of the subtree rooted at this node. The depth of the tree is the depth of the deepest (leaf) descendant.

has_terminal_comment()[source]

Return true if this node has a terminal line comment. In particular, this implies that no other node may be packed at the output cursor of this node’s layout, and a line-wrap is required.

lock(config, stmt_depth=0)[source]

Lock the tree structure (topology) and prevent further updates. This is mostly for sanity checking. It also computes topological statistics such as stmt_depth and subtree_depth, and replaces the mutable list of children with an immuatable tuple.

name

The class name of the derived node type.

next_sibling()[source]
node_type

Return the NodeType of the corresponding parser node that generated this layout node.

passno

The active pass-number which contributed the current layout of the subtree rooted at this node.

position

A cursor with the (row,col) of the first (i.e. top,left) character in the subtree rooted at this node.

reflow(stack_context, cursor, parent_passno=0)[source]

(re-)compute the layout of this node under the assumption that it should be placed at the given cursor on the current parent_passno.

reflow_valid

A boolean flag indicating whether or not the current layout is accepted. If False, then further layout passes are required.

rowextent
write(config, ctx)[source]

Output text content given the currently configured layout.

class cmake_format.formatter.OnOffSwitchNode(pnode)[source]

Bases: cmake_format.formatter.LayoutNode

Holds a special-case line comment token such as # cmake-format: off or # cmake-format: on

has_terminal_comment()[source]

Return true if this node has a terminal line comment. In particular, this implies that no other node may be packed at the output cursor of this node’s layout, and a line-wrap is required.

name

The class name of the derived node type.

write(config, ctx)[source]

Output text content given the currently configured layout.

class cmake_format.formatter.ParenGroupNode(pnode)[source]

Bases: cmake_format.formatter.LayoutNode

A parenthetical group. According to cmake syntax rules, this necessarily implies a boolean logical expression.

has_terminal_comment()[source]

Return true if this node has a terminal line comment. In particular, this implies that no other node may be packed at the output cursor of this node’s layout, and a line-wrap is required.

write(config, ctx)[source]

Output text content given the currently configured layout.

class cmake_format.formatter.ParenNode(pnode)[source]

Bases: cmake_format.formatter.LayoutNode

Holds parenthesis ‘(‘ or ‘)’ for statements or boolean groups.

name

The class name of the derived node type.

write(config, ctx)[source]

Output text content given the currently configured layout.

class cmake_format.formatter.PargGroupNode(pnode)[source]

Bases: cmake_format.formatter.LayoutNode

A group of positional arguments.

has_terminal_comment()[source]

Return true if this node has a terminal line comment. In particular, this implies that no other node may be packed at the output cursor of this node’s layout, and a line-wrap is required.

lock(config, stmt_depth=0)[source]

Lock the tree structure (topology) and prevent further updates. This is mostly for sanity checking. It also computes topological statistics such as stmt_depth and subtree_depth, and replaces the mutable list of children with an immuatable tuple.

class cmake_format.formatter.ScalarNode(pnode)[source]

Bases: cmake_format.formatter.LayoutNode

Holds scalar tokens such as statement names, parentheses, or keyword or positional arguments.

has_terminal_comment()[source]

Return true if this node has a terminal line comment. In particular, this implies that no other node may be packed at the output cursor of this node’s layout, and a line-wrap is required.

write(config, ctx)[source]

Output text content given the currently configured layout.

class cmake_format.formatter.StackContext(config, first_token=None)[source]

Bases: object

Aggregate information about the current stack. This object is passed down through all of the nested reflow() function calls.

push_node(node)[source]

Push node onto the node_path and yield a context manager. Pop node off of node_path when the context manager __exit__()s

class cmake_format.formatter.StatementNode(pnode)[source]

Bases: cmake_format.formatter.LayoutNode

Top-level node for a statement.

get_prefix_width(config)[source]
name

The class name of the derived node type.

reflow(stack_context, cursor, _=0)[source]

(re-)compute the layout of this node under the assumption that it should be placed at the given cursor on the current parent_passno.

write(config, ctx)[source]

Output text content given the currently configured layout.

class cmake_format.formatter.WhitespaceNode(pnode)[source]

Bases: cmake_format.formatter.LayoutNode

A series of newlines

write(config, ctx)[source]

Output text content given the currently configured layout.

class cmake_format.formatter.WriteContext(config, infile_content)[source]

Bases: object

Global state for the writing functions

is_active()[source]
cmake_format.formatter.clamp(value, min_value, max_value)[source]

Simple double-ended saturation function.

cmake_format.formatter.count_arguments(children)[source]

Count the number of positional arguments (excluding line comments and whitespace) within a parg group.

cmake_format.formatter.count_subgroups(children)[source]

Count the number of positional or kwarg sub groups in an argument group. Ignore comments, and assert that no other types of children are found.

cmake_format.formatter.create_box_tree(pnode)[source]

Recursively construct a layout tree from the given parse tree

cmake_format.formatter.dump_tree(nodes, outfile=None, indent=None)[source]

Print a tree of node objects for debugging purposes

cmake_format.formatter.dump_tree_for_test(nodes, outfile=None, indent=None, increment=None)[source]

Print a tree of node objects for debugging purposes

cmake_format.formatter.dump_tree_upto(nodes, history, outfile=None, indent=None)[source]

Print a tree of node objects for debugging purposes

cmake_format.formatter.filename_node_key(layout_node)[source]

Return the sort key for sortable arguments nodes. This is the case-insensitive spelling of the first token in the node.

cmake_format.formatter.format_comment_lines(node, stack_context, line_width)[source]

Reflow comment lines into the given line width, parsing markup as necessary.

cmake_format.formatter.get_comment_lines(config, node)[source]

Given a comment node, iterate through it’s tokens and generate a list of textual lines.

cmake_format.formatter.get_scalar_sequence_len(box_children)[source]
cmake_format.formatter.is_line_comment(node)[source]

Return true if the node is a pure parser node holding a line comment (i.e. not a bracket comment)

cmake_format.formatter.layout_tree(parsetree_root, config, linewidth=None, first_token=None)[source]

Top-level function to construct a layout tree from a parse tree, and then iterate through layout passes until the entire tree is satisfactory. Returns the root of the layout tree.

cmake_format.formatter.need_paren_space(spelling, config)[source]

Return whether or not we need a space between the statement name and the starting parenthesis. This aggregates the logic of the two configuration options separate_ctrl_name_with_space and separate_fn_name_with_space.

cmake_format.formatter.normalize_line_endings(instr)[source]

Remove trailing whitespace and replace line endings with unix line endings. They will be replaced with config.endl during output

cmake_format.formatter.sort_arguments(children)[source]
cmake_format.formatter.test_string(nodes, indent=None, increment=None)[source]
cmake_format.formatter.tree_string(nodes, history=None)[source]
cmake_format.formatter.write_tree(root_box, config, infile_content)[source]

Format the tree for size only, then print all of the boxes to outfile

cmake_format.lexer module

class cmake_format.lexer.SourceLocation[source]

Bases: tuple

Named tuple of (line, col, offset)

col
line
offset
class cmake_format.lexer.Token(tok_type, spelling, index, begin, end)[source]

Bases: object

Lexical unit of a listfile.

content
count_newlines()[source]
get_location()[source]
location()[source]
class cmake_format.lexer.TokenType(value)[source]

Bases: cmake_format.common.EnumObject

ATWORD = TokenType.ATWORD
BRACKET_ARGUMENT = TokenType.BRACKET_ARGUMENT
BRACKET_COMMENT = TokenType.BRACKET_COMMENT
BYTEORDER_MARK = TokenType.BYTEORDER_MARK
COMMENT = TokenType.COMMENT
DEREF = TokenType.DEREF
FORMAT_OFF = TokenType.FORMAT_OFF
FORMAT_ON = TokenType.FORMAT_ON
LEFT_PAREN = TokenType.LEFT_PAREN
NEWLINE = TokenType.NEWLINE
NUMBER = TokenType.NUMBER
QUOTED_LITERAL = TokenType.QUOTED_LITERAL
RIGHT_PAREN = TokenType.RIGHT_PAREN
UNQUOTED_LITERAL = TokenType.UNQUOTED_LITERAL
WHITESPACE = TokenType.WHITESPACE
WORD = TokenType.WORD
cmake_format.lexer.get_first_non_whitespace_token(tokens)[source]

Return the first token in the list that is not whitespace, or None

cmake_format.lexer.main()[source]

Dump tokenized listfile to stdout for debugging.

cmake_format.lexer.parse_bracket_argument(text)[source]
cmake_format.lexer.parse_bracket_comment(text)[source]
cmake_format.lexer.tokenize(contents)[source]

Scan a string and return a list of Token objects representing the contents of the cmake listfile.

cmake_format.markup module

Functions for parsing comments in markup

class cmake_format.markup.CommentItem(kind)[source]

Bases: object

class cmake_format.markup.CommentType(value)[source]

Bases: cmake_format.common.EnumObject

BULLET_LIST = CommentType.BULLET_LIST
ENUM_LIST = CommentType.ENUM_LIST
FENCE = CommentType.FENCE
NOTE = CommentType.NOTE
PARAGRAPH = CommentType.PARAGRAPH
RULER = CommentType.RULER
SEPARATOR = CommentType.SEPARATOR
VERBATIM = CommentType.VERBATIM
cmake_format.markup.format_item(config, line_width, item)[source]

Return lines of formatted text based on the typeof markup

cmake_format.markup.format_items(config, line_width, items)[source]

Return lines of formatted text for the sequence of items within a comment block

cmake_format.markup.is_hashruler(item)[source]

Return true if the markup item is a hash ruler, i.e.:

###########################
# Like this ^^^ or this vvv
###########################
cmake_format.markup.parse(lines, config=None)[source]

Parse comment lines. Returns objects of different formatable entities

cmake_format.parse_funs module

Statement parser functions

cmake_format.parse_funs.get_legacy_parse(cmdspec)[source]

Construct a parse tree from a legacy command specification

cmake_format.parse_funs.get_parse_db()[source]

Returns a dictionary mapping statement name to parse functor for that statement.

cmake_format.parse_funs.split_legacy_spec(cmdspec)[source]

Split a legacy specification object into pargs, kwargs, and flags

cmake_format.parse module

class cmake_format.parse.MockEverything[source]

Bases: object

Dummy object which implements any interface by mocking all functions with an empty implementation that returns None

class cmake_format.parse.ParseContext(parse_db=None, lint_ctx=None, config=None)[source]

Bases: object

Global context passed through every function in the parse stack.

pusharg(node)[source]
cmake_format.parse.parse(tokens, ctx=None)[source]

digest tokens, then layout the digested blocks.

cmake_format.render module

Parse cmake listfiles and emit an html file containing semantic and syntactic annotations.

cmake_format.render.dump_html(node, outfile)[source]

Write to outfile an html annoted version of the listfile which has been parsed into the parse tree rooted at node

cmake_format.render.get_html(node, fullpage=False)[source]

Return a string containing html markup of the annoted listfile which has been parsed into the parse tree rooted at node.