The Understand Python API gives scripts access to everything Understand knows about your code — entities, references, metrics, and dependencies — and powers custom checks, graphs, and reports.

CodeCheck#

CodeCheck inspects code against coding standards and reports violations. Understand comes with many checks, including the checks for published standards such as MISRA and AUTOSAR. Checks can also be defined through plugins. A configuration selects which checks to run and their options, and running a configuration over a set of files produces an inspection containing violations.

Discovery#

Use db.inspections() to retrieve the project’s current inspections. There is one for each background configuration and one for each synced inspection, matching the Inspections window in the Understand GUI. Use violations to get an inspection’s violations.

List the current inspections and their violations:

import understand

db = understand.open("/path/to/myproject.und")
for inspection in db.inspections():
    print(inspection.name(), "-", len(inspection.violations()), "violations")
    for v in inspection.violations():
        print(f"  {v.file()}({v.line()}): {v.check_id()} {v.text()}")

db.violations() and ent.violations() return the project’s violations: the violations from all of the inspections returned by db.inspections(), plus analysis errors and warnings (check ids UND_ERROR and UND_WARNING). Use ent.violations() on a file entity for the violations in that file.

Use config to see the configuration an inspection ran, and checks for the ids of the checks in it. Use lookup_check for a Check whose options are the configuration’s values.

List the checks each inspection ran:

import understand

db = understand.open("/path/to/myproject.und")
for inspection in db.inspections():
    config = inspection.config()
    print(inspection.name())
    for id in config.checks():
        check = config.lookup_check(id)
        print("  ", id, "-", check.name() if check else "")

Use Check.list to discover available checks. The Check objects returned can be used to query information about the check such as the id, name, and description. Use Check.lookup to find a check by id. Pass a Db so that checks the project defines, such as dependency checks, are included.

Checks support options. Use Check.options followed by Options.list to discover available options.

List checks available for the open project:

import understand

db = understand.open("/path/to/myproject.und")
for check in understand.Check.list(db):
    print(check.id(), "-", check.name())

Use Config.list to discover configurations. The configurations stored in the project are listed along with the standard configurations that apply to the project. Use Config.load to load a configuration file instead.

List each configuration and the number of checks it runs:

import understand

db = understand.open("/path/to/myproject.und")
for config in understand.Config.list(db):
    print(config.name(), "-", len(config.checks(db)), "checks")

Generation#

Call db.inspect() to run a configuration and return the finished Inspection. By default all the database’s files are inspected. Use targets to inspect only some entities and architectures. Inspections run from the API are not saved to the project, so they don’t appear in the Understand GUI.

The config can come from Config.list or Config.load, or be created from a list of checks with Config.create. Each check can be paired with options, given as an understand.Options object or an options string.

An inspection provides its violations, the files inspected, and any errors that occurred. Use save to write the inspection to a SARIF file. Use report and draw to generate the reports and graphs available for inspections, which are discovered by passing the inspection to Report.list and Graph.list.

db.load_inspection() loads an inspection from a SARIF file, such as one written by save or by und codecheck.

If an error occurs, an UnderstandError will be raised. Errors in individual files don’t stop the inspection; they are returned by errors.

Run a configuration with one check at High severity and print the violations:

import understand

db = understand.open("/path/to/myproject.und")
check = understand.Check.lookup("CPP_CT_MODERNIZE_USE_NULLPTR", db)
config = understand.Config.create([(check, "Severity=High")], name="Null Pointers")
inspection = db.inspect(config)
for v in inspection.violations():
    print(f"{v.file()}({v.line()}): {v.text()}")

Inspect a single file with a standard configuration and save the results:

import understand

db = understand.open("/path/to/myproject.und")
config = next(c for c in understand.Config.list(db) if c.name() == "MISRA C 2012")
file = db.lookup("main.c", "file")[0]
inspection = db.inspect(config, [file])
inspection.save("main.sarif")

Plugin writing#

The define_options and check functions have a CheckContext parameter. Use the CheckContext object to retrieve arguments such as the files to run on, the database or the id being run (a single script can contain multiple check ids).

Use the violation method to report a violation. The returned ViolationContext object can be used to add fix it hints (see add_fixit_hint).

Custom options can be defined and retrieved using the Options object stored in the check.

#
# These functions describe the check
#

def id():
    """
    Required, return a unique identifier for this check.
    """
    return 'TEST_01'

def name():
    """
    Required, return the short name of the check.

    This should be a phrase or word that reminds you what the check does.
    """
    return 'Python Options Test'

def detailed_description():
    """
    Required, return a detailed description of the check.

    This string appears in the 'checks selection' interface within CodeCheck.
    Here you can provide a more in-depth explanation of what your check does,
    any notes or exceptions to the check, and even simple code examples that
    show how the check should behave.
    """
    return """
    <p><b>Rationale</b></p>
    <p>
    This is a template check showing available options.
    </p>
    """

#
# These functions determine when the check will run
#

def test_entity(file):
    """
    Required, return True if the check should run on the file.

    This is only called for non-project level checks (checks whose
    test_global function was omitted or returned False).
    """
    return file.kind().check('code file')

def test_language(language):
    """
    Optional, return True if this check works for the given language.
    """
    return language == "C++"

def test_global():
    """
    Optional, return True if this check is a project level check.

    Project level checks are run on the entire project regardless of which
    files are selected. For example, a check that counted the total member
    function declarations.

    This function should only be set to True for project-level checks,
    otherwise it can be set to False or omitted from the script entirely.
    """
    return True

#
# This method is called when a check is created
#
def define_options(check):
    """
    Optional, initialize check options.

    Options defined here are configurable from Understand. The check
    function below has examples retrieving the options.
    """
    check.options().checkbox('checkbox', 'This is a checkbox')
    check.options().integer('integer', 'This is an integer', 2)
    check.options().text('text', 'This is text', 'Default Text')
    check.options().choice('choice', 'This is a choice', ['A', 'B', 'C'], 'B');

#
# The check method runs the actual check. Project level checks use the
# first signature. Other checks use the second signature. A codecheck
# is either project level or it is not. These check methods are shown
# together in this template only for demonstration.
#

def check(check):
    """
    The check overload for a project level check.
    """
    # Use the check object to get the database
    ent = check.db().ents('code file')[0]

    # The check also contains the values for the defined options
    checkbox = check.options().lookup('checkbox')
    integer = check.options().lookup('integer')
    text = check.options().lookup('text')
    choice = check.options().lookup('choice');

    # submit a violation by calling violation on the check object.
    check.violation(ent, ent, 0, 0,
                    'checkbox: %1, integer: %2, text: %3, choice: %4',
                    checkbox, integer, text, choice)

def check(check, file):
    """
    The check overload for a non-project level check.
    """
    for ref in file.filerefs('define', 'function'):
        # Use is_aborted to see if an abort was requested
        if check.is_aborted():
            return

        ent = ref.ent()
        if ent.name() == 'main':
            # Store the violation returned from check.violation to add
            # more details
            violation = check.violation(ent, file, ref.line(), ref.column(),
                                        'definition of %1 function', ent)
            # You can add fix it hints to violations
            violation.add_fixit_hint(ref.line(), ref.column(), ref.line(),
                                     ref.column() + len(ent.name()), 'foo')