7.7.2.1. Module axivion.analysis¶
Classes¶
|
Base class for rules that implement an analysis producing violations. |
|
Base class for rules in the analysis framework. |
AnalysisRule¶
- class axivion.analysis.AnalysisRule(rulename, *, rule_config=None, **kwargs)¶
Bases:
ConfigurableRule[AnalysisSchedulingContext],ABCBase class for rules that implement an analysis producing violations.
- Features:
automatically schedules an AnalysisRuleWorkItem
base class sets up ResultsCollection instance
Derived class is expected to have an execute() method
Note: derive from this class if your rule implementation produces violations and/or needs the exclude processing. Otherwise, consider directly deriving from ConfigurableRule.
- Parameters:
rulename (
str)rule_config (
typing.Optional[axivion.analysis.RuleConfiguration])kwargs (
typing.Any)
-
languages:
typing.Set[bauhaus.style.excludes.Language] = {Language.ASM, Language.C, Language.CPP, Language.CPP_CLI, Language.CSHARP}¶ Source languages the rule applies to.
Violations are excluded if they appear in a file of a language not in this set.
- provider = 'axivion'¶
Provider of this check, appears in the dashboard.
- severity = 'error'¶
Severity to classify violations, appears in the dashboard.
-
excludes:
typing.Set[typing.NewType(FileGlobPattern,str)] = {}¶ Filename patterns for files to exclude from the individual rule. <p> Note that excludes can also be specified via the option <a href=”#/Analysis//global_excludes”>/Analysis/global_excludes</a> or via the axivion_analysis –exclude command-line option. <p> If both <a href=”#./includes”>includes</a> and <code>excludes</code> are used, the rule applies to all files that match at least one include pattern, and do not match any exclude patterns.
-
includes:
typing.Set[typing.NewType(FileGlobPattern,str)] = {}¶ Filename patterns to restrict this individual rule to. May be combined with the <a href=”#/Analysis//global_includes”>/Analysis/global_includes</a> (the rule then is applied to more locations than just the global include patterns). <p> If both <code>includes</code> and <a href=”#./excludes”>excludes</a> are used, the rule applies to all files that match at least one include pattern, and do not match any exclude patterns.
-
exclude_messages_in_system_headers:
typing.Optional[bool] = None¶ Whether to exclude files marked as system headers. <p> If this option is not set, the option defaults to true, except when <code>axivion_analysis</code> is called with the <code>–system_headers</code> command-line argument. In <code>axivion_ci</code>, this option always defaults to true. <p> If this option is set, the <code>axivion_analysis –system_headers</code> command-line argument will have no effect. <p> System headers are the header files that are found in the system include path. <code>#pragma GCC system_header</code> also causes files to be classified as system header.
-
exclude_in_macros:
typing.Set[typing.NewType(GlobPattern,str)] = {}¶ Macro name patterns for macros where this rule should not be applied.
Violations will not be reported if they are from code generated by the expansion of a macro matching one of these glob patterns.
-
extend_exclude_to_macro_invocations:
bool= False¶ When true, messages associated with macro expansions will not be reported if the macro is defined in an excluded file. This applies even if the violation is depending on the context in which the macro is used. <p> Note: violations reported inside the macro definition itself (e.g. if <a href=”#./report_at”>report_at</a> is set to <code>automatic</code>) are always excluded, independently of this option.
- report_at = 'automatic'¶
Select where violations from macro expansions should be reported. <p> Note: Reporting violations at the macro definition will cause violations to be excluded if the macro is defined in an excluded file (e.g. system header).
-
user_data:
typing.Any= None¶ This attribute offers the possibility to add custom data to any rule (which would otherwise be detected as error by the configuration validation).
-
justification_checker:
typing.Optional[typing.Callable[[typing.Union[analysis_result_pb2.Architecture_Violation,analysis_result_pb2.Clone_Pair,analysis_result_pb2.Cycle_Finding,analysis_result_pb2.Dead_Entity,analysis_result_pb2.Metric,analysis_result_pb2.Style_Violation]],None]] = None¶ Can be set to a callable taking (and possibly modifying) a style violation instance. Will be called per issue and can be used to check a disabled issue’s justification, for example, against permitted ones. <p> Note: use the <a href=”#./post_processing”>post_processing</a> option for a more general method of filtering/modifying violations produced by this rule.
-
post_processing:
bauhaus.analysis.post_processing.PostProcessingSettings= <PostProcessingSettings(0 filters)>¶ This option allows registering custom post-processing steps that will be applied to violations produced by this rule. <p> See the documentation of module <code>axivion.analysis.post_processing</code> for more information.
- migrate_config(config, ctx)¶
Allows the rule to migrate a JSON config subtree that is about to be applied to itself. ‘ctx’ supplies background information, most notably the version for which the configuration was originally intended.
- Parameters:
config (
typing.MutableMapping[str,typing.Any])ctx (
axivion.analysis.MigrationContext)
- Return type:
None
- possible_messages()¶
Gets the possible messages produced by this rule.
For AnalysisRule, this method will return a copy of the ‘_message_descriptions’ dictionary (except that it creates MessageDescription instances where necessary)
- Return type:
typing.Mapping[str,axivion.analysis.MessageDescription]
- well_known_inputs()¶
Gets the well-known inputs used by this rule. This is used only when generating the stylecheck documentation.
- Return type:
typing.Iterable[axivion.analysis.WellKnownRuleInput]
- running_on_unit()¶
Called before execute() if the stylecheck is executed on a single compilation unit. A call to this function should usually change some settings to avoid false positives due to the rule not seeing the whole system, and then call super().running_on_unit().
- get_inputs(ctx, /)¶
Gets the inputs required by the execute() function.
If the implementation in the AnalysisRule base class is not overridden, execute will be called with the IR graph.
- Parameters:
ctx (
axivion.style.AnalysisSchedulingContext)- Return type:
typing.Iterable[typing.Union[axivion.style.WorkItem[typing.Any],axivion.style.InputHandleProtocol[axivion.style.WorkItem[typing.Any]]]]
- abstract execute(*inputs)¶
Core execution logic for the rule.
Derived classes must override this method to provide the implementation of the rule. Note that execute() is called with parameters according to the return value of get_inputs().
- get_inputs_full(ctx)¶
Gets the full list of inputs required by this rule, i.e. the inputs to the execute_full() function.
- Parameters:
ctx (
axivion.style.AnalysisSchedulingContext)- Return type:
typing.Iterable[typing.Union[axivion.style.WorkItem[typing.Any],axivion.style.InputHandleProtocol[axivion.style.WorkItem[typing.Any]]]]
- execute_full(ctx, inputs)¶
Executes this rule. This prepares the result collection, calls execute() and then sends the results.
- Parameters:
ctx (
axivion.style.ExecutionContext)inputs (
tuple[typing.Any,...])
- Return type:
object
- property analysis_kind: ar.Analysis_Execution.Analyses¶
Returns an enumerator describing the kind of analysis (like ar.Analysis_Execution.CYCLES_ANALYSIS)
- property results: AnalysisResultsCollection¶
Gets the results collection that accumulates the violations produced by this rule. This property can only be used during execute().
- property exclude_settings: ExcludeSettings¶
Gets the exclude settings that currently apply to this rule. This property can only be used during execute().
- add_message(primary_sloc, msg_key, *, message=None, message_arguments=None, severity=None, provider=None, error_number=None, entity=None, secondary_slocs=(), suppressed=False, justification=None, extra_info=(), old_primary_sloc=None, connecting_flags=None, macro_sloc_detection=None, irrelevant_violation=False)¶
Adds a style violation to the result collection.
Note: multiple identical violations (e.g. from different template instances) will be combined into a single violation.
The violation may be discarded if the msg_key is marked as disabled or if the primary_sloc is excluded by the rule’s exclude settings.
- Parameters:
primary_sloc (
typing.Union[analysis_result_pb2.SLoc,_dg.Node,_dg.Edge,axivion.ir.Node,axivion.ir.SLoc,scanner.Token,axivion.analysis_results.analysis_results_collection.SLoc_Input_Protocol,typing.Iterable[axivion.ir.Node],None]) – The primary position where the message should be reported.msg_key (
str) – The key into _message_descriptions; identifying this message.message (
typing.Optional[str]) – If message is specified, use that instead of the message for the msg_key.message_arguments (
typing.Union[typing.Tuple[typing.Any,...],typing.Dict[str,typing.Any],object,None]) – If specified, provides formatting arguments that are applied to the message via str.format().severity (
typing.Optional[str]) – If severity is specified, use that instead of the severity for the msg_key.provider (
typing.Optional[str]) – If provider is specified, use that instead of self.provider.error_number (
typing.Optional[str]) – If error_number specified, use that instead of self.rulename.entity (
typing.Optional[str]) – Text for the “entity” column in the dashboard.secondary_slocs (
typing.Iterable[typing.Union[analysis_result_pb2.SLoc,_dg.Node,_dg.Edge,axivion.ir.Node,axivion.ir.SLoc,scanner.Token,axivion.analysis_results.analysis_results_collection.SLoc_Input_Protocol]]) – Additional source locations that will be displayed in the issue details.justification (
typing.Optional[str]) – Can specify a justification for the violation.extra_info (
typing.Union[typing.Mapping[str,typing.Iterable[typing.Union[str,axivion.ir.Node,axivion.ir.SLoc,analysis_result_pb2.SLoc]]],typing.Iterable[typing.Union[analysis_result_pb2.Extra_Info_Entry,typing.Tuple[str,typing.Iterable[typing.Union[str,axivion.ir.Node,axivion.ir.SLoc,analysis_result_pb2.SLoc]]]]]]) – iterable of ar.Extra_Info_Entry, or of (key, values)-pairs, where values is an iterable, and each value is an ar.SLoc. This will be displayed in the issue details in the dashboard.old_primary_sloc (
typing.Union[analysis_result_pb2.SLoc,_dg.Node,_dg.Edge,axivion.ir.Node,axivion.ir.SLoc,scanner.Token,axivion.analysis_results.analysis_results_collection.SLoc_Input_Protocol,None]) – If specified, the database importer will use this SLoc to look for existing violations (to connect to). This should be used only on the first analysis run after a migration, when the computation of the SLoc changed between versions.connecting_flags (
typing.Optional[int]) – Flags for Style_Violation.Connecting_Flags.suppressed (
bool) – If set, the issue starts out in the suppressed status. It won’t be imported into the dashboard unless import_suppressed_issues is enabled. It may still be un-suppressed by a post_processing filter (e.g. justification_checker).macro_sloc_detection (
typing.Optional[typing.Literal['at_invocation','at_invocation_6x','at_definition','subtree','parent']]) –- Determines how SLoc marshalling in macros behaves for this violation:
at_invocation: (default) Never report in a macro definition
at_definition: Report at the original SLoc that contains the token on which the primary_sloc is based, even if that is inside a macro definition.
subtree: Consider the macro invocations involved in the subtree rooted at primary_sloc, and put the violation only in a macro definition if the whole subtree is from that macro definition and does not involve macro arguments.
parent: Like subtree, but also consider the parent node of the primary_sloc. Use this option in rules that report violations at the operand of an implicit conversion; or in rules that report violations for essential type conversions.
Alternatively, you can get more control over macro SLocs by using the return value of
detect_macro_sloc()for the primary_sloc argument.Note that in order to use macro_sloc_detection, the ‘report_at’ option must be set to automatic.
irrelevant_violation – Only use for violations in template instances for messages with violations_in_templates_must_affect_all_instances=True. If set, the violation itself will be dropped during issue deduplication but when deciding if a violation affects all instances, the containing instance is counted as affecting instance.
- detect_macro_sloc(primary_node, *, additional_nodes=(), subtrees=(), exprs_for_types=())¶
Run automatic SLoc detection. This function will return primary_node.SLoc or primary_node.Original_SLoc (or for nested macro invocations, possibly a partially-expanded SLoc), depending on which macro context is most suitable to display the violation at. To be displayed at a macro definition, all “considered nodes” must be from the macro definition (and not from its macro arguments).
- Parameters:
additional_nodes (
typing.Iterable[typing.Union[Physical_IR_Root,axivion.ir.NoNode[Physical_IR_Root]]]) – additional nodes to consider.subtrees (
typing.Iterable[typing.Union[Physical_IR_Root,axivion.ir.NoNode[Physical_IR_Root]]]) – root nodes of full subtrees to consider.exprs_for_types (
typing.Iterable[typing.Union[Physical_IR_Root,axivion.ir.NoNode[Physical_IR_Root]]]) – expressions to consider for their type. Similar to ‘subtrees’, but special-cases certain expressions such as casts to avoid looking at their operands, when the type of the expression does not depend on that operand.
- Return type:
axivion.ir.SLoc
- Note: if automatic SLoc detection is disabled via the ‘report_at’ option,
this function will always return the SLoc according to the ‘report_at’ option.
- Note: In the common case where primary_sloc is not from a macro definition
at all, this function will avoid iterating through the other parameters. It’s recommended to use generators as arguments so that the arguments do not have to be fully calculated in the common case.
- Parameters:
primary_node (
Physical_IR_Root)
- relevant_pir_nodes(ir_graph, types)¶
Gets physical IR nodes of the specified type(s). This function automatically excludes nodes from excluded files (e.g. system headers, exclude glob patterns, or due to language filter).
This function only uses the fast file-based exclude checks.
This can be used as a performance optimization to avoid computing whether a violation is present if add_message() is going to exclude the violation anyway.
- Parameters:
ir_graph (
axivion.ir.Graph)types (
typing.Union[typing.TypeForm[typing.TypeVar(TPhysical, bound=Physical_IR_Root)],tuple[typing.TypeForm[typing.TypeVar(TPhysical, bound=Physical_IR_Root)],...],typing.NewType(PIR_Class_Name,str),typing.Collection[typing.NewType(PIR_Class_Name,str)]])
- Return type:
typing.Iterable[typing.TypeVar(TPhysical, bound=Physical_IR_Root)]
Rule¶
- class axivion.analysis.Rule¶
Bases:
Generic[SchedulingContextTypeVar],ABCBase class for rules in the analysis framework.
- abstract property rulename: str¶
Full name of this rule, e.g. “MisraC2012-10.1”.
- property rulegroup: str | None¶
Full name of the parent analysis group; or None if this is a top-level item.
- property pseudo_hierarchy: str | None¶
additional hierarchy levels shown in the UI in the palette section of the parent group, separated by dots, e.g., ‘Analyses.Architecture’. None for top-level entries.
- Type:
For children of an ordered rulegroup only
- property rulesortkey: int¶
Rules are sorted by (rulesortkey, rulename), so overriding this property allows control over the sort order.
- property is_rule_group: bool¶
Gets whether this rule is a rule group. Rule groups do not have an explicit “active” state. Instead, trying to (de)activate them will (de)activate all their child rules; and the schedule() function on the rule group will be called if at least one of the descendant rules is active (or if the rule group is implicit).
- property is_ordered_rule_group: bool¶
Gets whether this rule is a rule group that cares about the order in which its children are scheduled. If this property is True, the GUI will allow re-ordering the rules within this group; and the schedule() function for those rules will be called in the configured order.
- property is_implicit_rule: bool¶
Gets whether this is an implicit rule. Implicit rules cannot be selected in the ACTIVE set, and are always implicitly active. Implicit rules can be used to apply global configuration. Implicit rule groups can be used to prevent the user from activating the whole group where this does not make sense (e.g. activating all “Analysis Control” items at once)
- property is_active_by_default: bool¶
Gets whether this is a rule that is active by default. Such a rule is activated by default for convenience (e.g. external function summaries for the standard library), but it can be manually deactivated. These rules are not automatically active when using axivion_analysis –rule, but they can be manually listed with the –rule parameter like other rules.
- property expose_to_toolconfig: Iterable[str]¶
Gets whether this rule should be exposed to the toolconfig C++ library.
- property title: str¶
The title of the rule.
A short (usually single-line) description of the rule in plain text used for documentation generation; also displayed during stylecheck execution in the “Executing …” status message when using the default RuleWorkItem.
Example: ‘Operands shall not be of an inappropriate essential type.’
- property supports_multiple_instances: bool¶
Whether the rule can be instantiated at all.
- property is_dev_rule: bool¶
Whether the rule should be hidden from end users and documentation and only shown in the UI to developers on demand (see OptionVisibility.DEV).
- property include_in_public_documentation: bool¶
Whether the rule is part of the public documentation.
- abstract property aspect: str¶
The config aspect this rule(group) belongs to.
- property is_deprecated: bool¶
Gets whether this rule is deprecated. This currently has no effect.
- well_known_inputs()¶
Gets the well-known inputs used by this rule. This is used only when generating the stylecheck documentation.
- Return type:
typing.Iterable[axivion.analysis.WellKnownRuleInput]
- get_rulehtml(config=None)¶
Retrieves the complete HTML documentation for the rule.
- Parameters:
config (
typing.Optional[axivion.analysis.RuleConfiguration])- Return type:
str
- get_rulehtml_header(config=None)¶
Gets the HTML header for this rule. This is typically only called from get_rulehtml().
- Parameters:
config (
typing.Optional[axivion.analysis.RuleConfiguration])- Return type:
str
- get_rulehtml_description(config=None, /)¶
Retrieves the HTML documentation for the rule, without header or configuration section. This is used when generating the stylecheck documentation and shown in the axivion_config GUI.
- Parameters:
config (
typing.Optional[axivion.analysis.RuleConfiguration])- Return type:
str
Gets the HTML footer for this rule. This is typically only called from get_rulehtml().
- Parameters:
config (
typing.Optional[axivion.analysis.RuleConfiguration])- Return type:
str
- get_rulehtml_config(config=None, /)¶
Gets HTML describing the rule’s configuration.
This function is deprecated since version 7.3: it is no longer called by the default get_rulehtml() implementation, as we no longer show the available configuration options in the dashboard. axivion_config and our HTML documentation are not using this method either; they directly document the individual options.
- Parameters:
config (
typing.Optional[axivion.analysis.RuleConfiguration])- Return type:
str
- get_rule_description(config, /, migrate_from=None)¶
Gets the rule description object that can be stored in the database. ‘migrate_from’ is the Bauhaus version used for the previous analysis.
- Parameters:
config (
axivion.analysis.RuleConfiguration)migrate_from (
typing.Optional[typing.Tuple[int,int,int,int]])
- Return type:
typing.Optional[analysis_result_pb2.Style_Rule]
- abstract configuration(include_description=True)¶
Gets the configuration options for this rule.
- Return type:
typing.Mapping[str,axivion.analysis.ConfigOption]
- migrate_config(config, ctx)¶
Allows the rule to migrate a JSON config subtree that is about to be applied to itself. ‘ctx’ supplies background information, most notably the version for which the configuration was originally intended.
- Parameters:
config (
typing.MutableMapping[str,typing.Any])ctx (
axivion.analysis.MigrationContext)
- Return type:
None
- get_older_names()¶
Returns older names of the rule together with the last version in which the name was valid, sorted from higher versions to lower versions. So, if a rule named ‘Pear’ returns [((7, 3), ‘Orange’), ((7, 1), [‘Apple’, ‘Kiwi’])], it was called ‘Apple’ or ‘Kiwi’ in versions up to and including 7.1, ‘Orange’ in 7.2 and 7.3, and ‘Pear’ starting from 7.4.
- Return type:
typing.Sequence[typing.Tuple[axivion.analysis.NumericVersion,typing.Union[str,typing.List[str]]]]
- abstract possible_messages()¶
Gets the possible messages produced by this rule.
- Return type:
typing.Mapping[str,axivion.analysis.MessageDescription]
- count_parts()¶
Counts the total number of parts that this rule consists of. Returns 1 for most rules; but can be overridden (e.g. by CompositeRule).
- Return type:
int
- part_types()¶
Gets a list of types that identify the implementation behind this rule. This is used in axivion_analysis –list_identical_rules.
- Return type:
typing.Iterable[type[axivion.analysis.Rule[typing.TypeVar(SchedulingContextTypeVar, bound=axivion.style.SchedulingContext)]]]
- abstract schedule(rule_config, ctx)¶
Schedules execution of this rule. A rule can be scheduled multiple times with different configuration options by calling this method multiple times.
- Parameters:
rule_config (
axivion.analysis.RuleConfiguration)ctx (
typing.TypeVar(SchedulingContextTypeVar, bound=axivion.style.SchedulingContext))
- Return type:
None
Functions¶
|
Registers the decorated class/function as a rule. |
rule¶
- analysis.rule(**kwargs)¶
Registers the decorated class/function as a rule.
@rule("MisraC2012-10.1") class MyRule(AnalysisRule): pass
Note
the arguments passed to the rule annotation will be passed to the Rule’s constructor. They have no other special meaning to the decorator – the rule name is only specified in the example because the AnalysisRule base class constructor expects to be passed the rule name.
Additionally, the
InstantiationContextwill be passed in a named argument calledctx.It is possible to register multiple instances of a rule class by applying the decorator multiple times, specifying different arguments each time.
- Parameters:
args (
typing.Any)kwargs (
typing.Any)
- Return type:
typing.Callable[[typing.TypeVar(T, bound=type)],typing.TypeVar(T, bound=type)]