7.6. Scanner Scripting

7.6.1. Introduction

With Scanner Scripting, you can access a token stream of any source code file or even a specific token at a certain position in the file. This is useful for inspecting comments or looking for code that has been removed via preprocessor macros (e.g. #ifdef etc.) because this information is not present in the IR.

To get code completion and type checking for the Scanner in your IDE, see Section Code Completion and Type Checking in an IDE.

7.6.1.1. Accessing the Scanner

Import the bauhaus.scanner module to use the Scanner (see Listing Importing the scanner part of bauhaus).

Importing the scanner part of bauhaus
from bauhaus import scanner

7.6.1.2. Global functions of the Scanner

tokens(filename[, line[, basepath[, language]]])

The tokens function returns a tuple of all the tokens in filename. If line is also specified, it returns a generator that yields only the tokens starting on that line. If the file cannot be opened, the result is empty.

If filename is a relative path that does not exist relative to the current working directory, it is looked up relative to basepath. File names from #line directives are made relative to basepath in the Logical_Pathname field. The language parameter selects the tokenizer using one of the lang_ constants from the bauhaus.shared module, e.g., shared.lang_c. By default, the language is detected from the filename.

token(filename, line, column[, basepath[, language]])

The token function returns the token starting at the specified position or None if the position does not point to the start of a token or the file cannot be opened. The parameters basepath and language have the same meaning as for tokens.

nearest_token(filename, line, column[, basepath[, language]])

The nearest_token function returns the token that covers the specified position. If no token covers it, the next token is returned. The result is None if there is no such token or the file cannot be opened. The parameters basepath and language have the same meaning as for tokens.

clear_tokencache()

The tokens, token, and nearest_token functions cache the tokens of the files they read. The clear_tokencache function empties this cache to free memory.

is_keyword(token_type)
is_operator_symbol(token_type)
is_preprocessing_directive(token_type)

These functions determine whether the token type token_type (the value of a token’s Type field) is a keyword, an operator symbol, or a preprocessing directive.

7.6.1.3. Tokenizer

An object of class Tokenizer reads tokens from a file or from a bytes object. Unlike the tokens, token, and nearest_token functions, it does not cache tokens.

Tokenizer([filename[, content[, language[, pathname]]]])
read_tokens([basepath])
encoding

The constructor reads the file filename, or content if provided. The language parameter selects the tokenizer in the same way as the tokens function. Without filename, both content and language are required. pathname sets the Pathname field of the tokens and defaults to filename. If the file cannot be opened, the constructor raises scanner.FileOpenException.

The read_tokens method reads tokens up to the end of the input and returns them as a tuple. A second call returns an empty tuple. The basepath parameter has the same meaning as for tokens.

The encoding property contains the name of the character encoding detected by the tokenizer, e.g., utf-8.

from bauhaus import scanner, shared

tokenizer = scanner.Tokenizer(content=b'int x = 1;\n', language=shared.lang_c)
for token in tokenizer.read_tokens():
    print(token.Name, token.Value)

7.6.1.4. Token

Objects of class Token represent source code tokens. They represent source code verbatim but are classified into categories such as identifiers, literals, or keywords for the respective programming languages.

Accessing fields

fields()
field(fieldname)
next([until])
prev([until])
__str__()

The fields instance method returns a frozenset containing the names Pathname, Line, Column, End_Line, End_Column, Type, Name, and Value. The names of the logical location fields described below are not included.

The field instance method accesses a specific field of a Token and returns the field’s content.

Tokens provide the following fields: Pathname, Line, Column, End_Line, End_Column, Logical_Pathname, Logical_Line, Logical_Column, Logical_End_Line, Logical_End_Column, Type, Name, and Value.

The field name is provided as fieldname, and the method’s return type depends on the field type. For Line, Column, End_Line, and End_Column, integer values are returned that indicate the location in the source code file. Similarly, the fields Logical_Line, Logical_Column, Logical_End_Line, and Logical_End_Column are represented as integer values and, together with the string field Logical_Pathname, indicate the token’s logical source location. This is the location where the token is logically positioned after any #line directives have been processed. The Type field is also an integer value. The fields Pathname, Name, and Value return string values.

The prev and next instance methods return the previous and next tokens in the token stream, respectively. If until is specified, they skip tokens until they reach a token whose Name matches until (or one of the names if until is a tuple, list, or set). If the end of a file’s token stream is reached during forward or backward iteration, a StopIteration exception is raised.

The __str__ method returns the token value.

A token can be passed as a source location to the add_message method of an analysis rule.

Token Types

The value stored in the Type field is a constant designating the token type, such as an identifier or an integer literal. The list of token types is subject to change, as new input languages may be added to the Axivion Suite. You can inspect the current list using Python’s online help:

from bauhaus import scanner
help(scanner)

All token type constants are listed in the data section; their names are prefixed with “Sym_”.

Example Usage

The following example searches for tokens of type Sym_Identifier with the value “x” and prints the corresponding lines.

from bauhaus import scanner

for token in scanner.tokens("file.c"):
    if token.Type == scanner.Sym_Identifier and token.Value == "x":
        print("identifier \"x\" at line %d" % token.Line)