Home

Awesome

CMake AST

Status

Travis CI (Ubuntu)AppVeyor (Windows)CoveragePyPILicence
TravisAppVeyorCoverallsPyPIVersionPyPIPythonsLicense

cmake-ast has been tested against every single CMake module that ships with recent versions of CMake. These tests also run in the continuous integration environment on each build. It supports multi-line strings and other corner cases.

Usage

Import cmakeast and ASTify the contents of a cmake file with cmakeast.ast.parse(contents). You can also pass it a list of tokens obtained by tokenization with the tokens keyword argument. The return will be a toplevel node, with node descriptions as follows:

Word

Body

FunctionCall

FunctionDefinition

MacroDefinition

IfStatement

ElseIfStatement

ElseStatement

IfBlock

ForeachStatement

WhileStatement

Each node also has a line and col member to indicate where it can be found in the source file.

Word type aliases are stored in WordType inside ast.

Traversing the AST

CMake-AST provides a helper module ast_visitor to make traversing the AST less verbose. It will traverse every single node by default. Listeners matching the signature def handler (name, node, depth) can be passed as the following keyword arguments to recurse (body, **kwargs):

KeywordHandles Node Type
toplevelToplevelBody
while_stmntWhileStatement
foreachForeachStatement
function_defFunctionDefinition
macro_defMacroDefinition
if_blockIfBlock
if_stmntIfStatement
elseif_stmntElseIfStatement
else_stmntElseStatement
function_callFunctionCall
wordWord

Dumping the AST of a CMake file

If you wish to dump the AST of a cmake file, the cmake-print-ast tool is also provided. Pass a single filename to dump the AST of to it on the command line

Tokenization

To get an even lower level representation, use cmakeast.ast.tokenize(contents) which divides the file only into tokens. Aliases are stored in the TokenType class in ast. Tokens correspond as follows:

Token TypeDescription
QuotedLiteralSomething in quotes
LeftParen(
RightParen)
WordAlphanumeric Sequence
NumberNumeric-Only Sequence
DerefAlphanumeric Sequence inside ${}
RSTDocumentation Comment
CommentComment
UnquotedLiteralAny character sequence, punctuation included