A Python tool to analyze C/AUTOSAR codebases and generate function call trees with Mermaid and XMI output
Project description
AUTOSAR Call Tree Analyzer
A powerful Python package to analyze C/AUTOSAR codebases and generate function call trees with multiple output formats.
Features
- โจ AUTOSAR Support: Full parsing of AUTOSAR macros (
FUNC,FUNC_P2VAR,FUNC_P2CONST,VAR,P2VAR, etc.) - ๐ Static Analysis: Analyzes C source code without compilation
- ๐ Multiple Output Formats:
- Mermaid sequence diagrams (Markdown)
- XMI/UML 2.5 (importable to Enterprise Architect, Visual Paradigm, etc.)
- Rhapsody XMI 2.5 (importable to IBM Rhapsody 8.0+)
- JSON (for custom processing) - planned
- ๐๏ธ SW Module Support: Map C files to SW modules via YAML configuration for architecture-level diagrams
- ๐ Module-Aware Diagrams: Generate diagrams with SW module names as participants
- ๐ฏ Parameter Display: Function parameters shown in sequence diagram calls for better visibility
- ๐ Automatic Conditional Detection: Automatically detects
if/elsestatements and generatesoptblocks with actual conditions (Mermaid and XMI) - ๐ Performance: Intelligent caching for fast repeated analysis with file-by-file progress reporting
- ๐ฏ Depth Control: Configurable call tree depth
- ๐ Circular Dependency Detection: Identifies recursive calls and cycles
- ๐ Statistics: Detailed analysis statistics including module distribution
- ๐ Clean Diagrams: Return statements omitted by default for cleaner sequence diagrams (configurable)
What's New
Version 0.8.0 (2026-03-01)
๐ Major Feature: Full Rhapsody XMI 2.1 Compatibility
This release adds complete Rhapsody XMI 2.1 compatibility, matching Rhapsody's native export format for seamless import into IBM Rhapsody 8.0+.
New Features:
- ๐ฏ Rhapsody XMI 2.1 Export: Full XMI 2.1 compliant output with OMG UML namespace
- ๐ GUID+ ID Format: Uses
GUID+<UUID>format for maximum Rhapsody compatibility - ๐ MessageOccurrenceSpecification: Explicit send/receive occurrence fragments
- ๐๏ธ Role Definitions: Proper lifeline role definitions via ownedAttribute
- ๐ Element Imports: Profile metaclass imports for complete model structure
- ๐ CoveredBy Attributes: Lifeline coverage tracking for message occurrences
- ๐ฆ Complex Profile Structure: Nested eAnnotations with EPackage references
CLI Usage:
# Generate Rhapsody-compatible XMI
calltree --start-function Demo_MainFunction \
--source-dir demo/src \
--format rhapsody \
--output demo/rhapsody_output.xmi
Implementation:
- Independent
RhapsodyXmiGeneratorimplementation (does not extend XmiGenerator) - Uses lxml for proper namespace control
- Full structural match with Rhapsody's native XMI export format
- All 8 critical structural differences addressed
Benefits:
- โ Direct import into IBM Rhapsody 8.0+ without conversion
- โ Full Rhapsody XMI 2.1 compatibility (not just UML 2.5)
- โ Proper MessageOccurrenceSpecification for timing/sequencing info
- โ Role definitions matching Rhapsody's internal structure
- โ Complex profile structure with EPackage references
Demo Files:
- Enhanced demo code showcasing loops, multi-line conditions, nested conditionals
- Reorganized structure:
demo/src/for source code - Updated documentation in
demo/README.md
Breaking Changes:
- Rhapsody XMI output structure completely changed (old format not compatible)
- Source directory changed from
demo/todemo/src/ - All existing Rhapsody XMI files need regeneration
Version 0.6.0 (2026-02-10)
๐ Major Feature: Loop Detection and Multi-line If Condition Support
This release adds parsing of function calls inside for/while loops and improves multi-line if condition extraction for complex AUTOSAR code.
New Features:
- ๐ Loop Detection: Automatically detects function calls inside
forandwhileloops with condition extraction - ๐ Multi-line If Condition Extraction: Handles complex multi-line if statements with nested parentheses and logical operators
- โ Production Ready: Verified on real AUTOSAR codebases with complex formatting
Example Multi-line If:
// Complex multi-line condition with nested parentheses
if ((((uint32)config_ptr->settings->mode &
((uint32)0x1U << SLEEP_MODE)) > 0x0U) &&
(sensor_status == SENSOR_READY))
{
InitPeripheral();
EnableClockControl();
}
Parsed Condition: (((uint32)config_ptr->settings->mode & ((uint32)0x1U << SLEEP_MODE)) > 0x0U) && (sensor_status == SENSOR_READY)
Example Loop Detection:
while (retry_counter > 0x0U)
{
if (InitOscillator() != E_OK)
{
ReportError(ERR_INIT_FAILED);
}
retry_counter--;
}
Detected: Loop condition retry_counter > 0x0U with nested conditional call ReportError
Benefits:
- โ Handles production AUTOSAR code with complex formatting
- โ Accurate condition extraction across line breaks
- โ Better visualization of loop-based call patterns
- โ Verified on real-world embedded codebases with zero parse errors
Version 0.5.0 (2026-02-04)
๐ Major Feature: Automatic Conditional Call Detection with Opt/Alt/Else Blocks
This release adds intelligent parsing of conditional function calls, automatically detecting if/else blocks in your C code and representing them as opt/alt/else blocks in both Mermaid and XMI output formats.
Mermaid Example:
Source Code:
FUNC(void, RTE_CODE) Demo_Update(VAR(uint32, AUTOMATIC) update_mode)
{
SW_UpdateState(update_mode);
if (update_mode == 0x05) {
COM_SendLINMessage(0x456, (uint8*)0x20003000);
}
}
Generated Mermaid Diagram:
sequenceDiagram
participant Demo_Update
participant COM_SendLINMessage
participant SW_UpdateState
Demo_Update->>SW_UpdateState: call(new_state)
opt update_mode == 0x05
Demo_Update->>COM_SendLINMessage: call(msg_id, data)
end
XMI Example:
<uml:fragment name="opt" interactionOperator="opt">
<uml:operand name="update_mode == 0x05">
<uml:message name="COM_SendLINMessage" signature="COM_SendLINMessage(msg_id, data)">
<!-- message events -->
</uml:message>
</uml:operand>
</uml:fragment>
Benefits:
- โ No manual configuration required - automatic detection
- โ Shows actual condition text for better understanding
- โ Supports nested conditionals
- โ
Handles
if,else if, andelsestatements - โ Works with both Mermaid and XMI output formats
- โ XMI uses UML combined fragments (standard UML 2.5 representation)
Technical Changes:
FunctionCallmodel extended withis_conditionalandconditionfieldsCallTreeNodeextended withis_optionalandconditionfieldsCParserenhanced with line-by-line conditional context trackingMermaidGeneratorsupportsopt,alt, andelseblocksXMIGeneratorsupports UML combined fragments- 298 tests passing with 89% code coverage
Changelog
[Version 0.8.0] - 2026-03-01
Added
- Rhapsody XMI 2.1 full compatibility: Complete structural match with Rhapsody's native XMI export format
- GUID+ ID format: Uses
GUID+<UUID>format for all XMI elements - MessageOccurrenceSpecification: Explicit send/receive occurrence fragments for each message
- Lifeline role definitions: Proper ownedAttribute elements for lifeline roles
- Element imports: Profile metaclass imports for complete model structure
- CoveredBy attributes: Lifeline coverage tracking linking lifelines to message occurrences
- Complex profile structure: Nested eAnnotations with EPackage references
- lxml-based generator: Uses lxml for proper namespace control and XMI 2.1 compliance
- Independent RhapsodyXmiGenerator: Complete rewrite (does not extend XmiGenerator) for full structural control
- Enhanced demo files: Showcases loops, multi-line conditions, nested conditionals
- Reorganized demo structure: Source code moved to
demo/src/ - Comprehensive demo documentation: Usage guide in
demo/README.md
Breaking Changes
- Rhapsody XMI output format: Complete structural change from XMI 4.0 to XMI 2.1
- Old Rhapsody files incompatible: All existing Rhapsody XMI files must be regenerated
- Source directory changed: Default source directory changed from
./demoto./demo/src - Namespace format: Changed from Eclipse UML2 to OMG UML namespace
- ID format: Changed from
rhapsody_<UUID>toGUID+<UUID>
Improved
- Direct import into IBM Rhapsody 8.0+ without conversion
- Proper MessageOccurrenceSpecification for timing/sequencing information
- Role definitions matching Rhapsody's internal structure
- Full structural compatibility with Rhapsody's native export format
Technical
- All 8 critical structural differences between XMI 4.0 and Rhapsody XMI 2.1 addressed
- lxml used for proper namespace control and XMI generation
- RhapsodyXmiGenerator implemented independently for full structural control
- Demo files enhanced to showcase all parsing features
[Version 0.7.0] - 2026-02-14
Added
- IBM Rhapsody XMI export: Complete support for IBM Rhapsody 8.0+ XMI format with AUTOSAR profile
- RhapsodyGenerator: New generator class (221 lines) with IBM-specific XMI schema
- Rhapsody documentation: Comprehensive guides (1,075 lines total)
docs/rhapsody_export.md: Complete export guidedocs/rhapsody_troubleshooting.md: Troubleshooting guidedocs/requirements/requirements_rhapsody.md: Requirements documentation
- Rhapsody import helper: Script to assist with XMI imports
- Rhapsody demo files: 3 example XMI files (init, modules, update)
- Rhapsody CLI option:
--format rhapsodyfor Rhapsody XMI output
Fixed
- Invalid PyPI license classifier: Corrected license classifier in pyproject.toml for proper PyPI publishing
- Temporary file cleanup: Automatic cleanup of test output files
- Type safety: Code simplification and type safety improvements
- Code quality issues: Formatting, imports, and linting corrections
Improved
- Test structure: Reorganized unit tests to match source code package layout
- Documentation: Removed deprecated setup.py references, updated build docs
- Code quality: Resolved all ruff linting errors
- Test hygiene: Added automatic cleanup for temporary test files
Technical
- 17 new requirements (SWR_RHAPSODY_00001 through SWR_RHAPSODY_00017)
- 759 lines of comprehensive Rhapsody-specific tests
- All 397 tests passing (100%)
- Overall test coverage: 89%
- Rhapsody-specific AUTOSAR profile support
- Cross-platform compatibility with Rhapsody 8.0+
CLI Usage
# Generate Rhapsody XMI
calltree --start-function Demo_Init --format rhapsody
# Generate both Mermaid and Rhapsody XMI
calltree --start-function Demo_Init --format both
[Version 0.6.0] - 2026-02-10
Added
- Loop detection: Automatic detection of
forandwhileloops with condition text extraction - Multi-line if condition extraction: Handles complex multi-line if statements with nested parentheses
- FunctionCall model: Extended with
is_loopandloop_conditionfields - CallTreeNode model: Extended with
is_loopandloop_conditionfields - CParser enhancements: Multi-line parenthesis tracking for complete condition extraction
- Production AUTOSAR codebase verification (tested on large-scale embedded codebases)
- Requirements documentation for loop detection (SWR_PARSER_C_00021)
Improved
- Multi-line if condition extraction now captures complete conditions across line breaks
- Parenthesis depth tracking for complex nested conditions (4+ levels)
- Condition extraction for bitwise operations (
&,|,<<,>>) - Production code validation with zero parse errors
Technical
- Verified parsing of real-world AUTOSAR codebase with complex formatting
- Functions with loop calls correctly identified and tracked
- Multi-line conditions with 100+ character length properly extracted
- All existing tests passing (298 tests, 89% coverage)
[Version 0.5.0] - 2026-02-04
Added
- Conditional function call tracking: Automatic detection of
if/elseblocks with condition text extraction - Mermaid opt/alt/else blocks: Generate
opt,alt, andelseblocks for conditional calls - XMI combined fragments: UML 2.5 compliant
opt/alt/elsefragment generation - FunctionCall model: Extended with
is_conditionalandconditionfields - CallTreeNode model: Extended with
is_optionalandconditionfields - CParser enhancements: Line-by-line parsing to track conditional context
- Requirements documentation for conditional call tracking (SWR_MODEL_00026-00028)
Fixed
- Linting errors (flake8 W292, W391) for proper file endings
- Type annotations in
c_parser.py:442for mypy compliance
Technical
- 298 tests passing, 89% code coverage
- All CI quality checks passing (ruff, isort, flake8, mypy)
- Python 3.8-3.12 test matrix
[Version 0.4.0] - 2026-02-03
Added
- XMI/UML 2.5 output format: Complete XMI generation with UML 2.5 compliance
- XMIGenerator: New generator class for XMI document creation
- CLI
--format xmioption: Support for XMI output format - CLI
--format bothoption: Generate both Mermaid and XMI simultaneously - XMI requirements documentation:
docs/requirements/requirements_xmi.md - UML combined fragments: Support for
opt,alt,elseinteractions - XMI demo output:
demo/demo_main.xmiexample file
Technical
- XMI documents importable into Enterprise Architect, Visual Paradigm, MagicDraw
- Proper XML namespaces and structure (UML 2.5, XMI 2.5)
- Message events with sendEvent and receiveEvent elements
[Version 0.3.3] - 2026-02-02
Fixed
- AUTOSAR macro false positives: Performance degradation caused by incorrect macro matching
- Parser optimization to reduce false positive detections
- Improved AUTOSAR pattern matching accuracy
[Version 0.3.2] - 2026-02-01
Added
- File size display: Show file sizes during processing in verbose mode
- Enhanced progress reporting with line counts and file sizes
- Improved user feedback for large file processing
[Version 0.3.1] - 2026-01-31
Added
- Verbose file progress: File-by-file progress display during database building
- Line count reporting: Show number of lines processed per file
- Enhanced cache loading: File-by-file progress when loading from cache
- C parser line-by-line tests: Comprehensive testing for line-by-line processing
Fixed
- Import sorting to pass isort checks
- Minor documentation updates
[Version 0.3.0] - 2026-01-30
Added
- SW Module Configuration System: YAML-based file-to-module mapping
- Module-aware diagrams: Generate diagrams with SW module names as participants
- Comprehensive test suite: 298 tests across all modules (89% coverage)
- Requirements traceability: Complete traceability matrix between requirements and tests
- Integration tests: End-to-end CLI testing
- PyPI publishing workflow: Automated PyPI releases with OIDC trusted publishing
- ModuleConfig class: Load, validate, and perform module lookups
- Module assignment: Functions tagged with SW module information
- FunctionDatabase integration: Module assignments preserved in cache
- CLI
--use-module-namesoption: Enable module-level diagrams - CLI
--module-configoption: Specify module mapping YAML file
Technical
- Glob pattern support for file mappings (e.g.,
hw_*.c) - Default module fallback for unmapped files
- Module lookup caching for performance
- Cache preserves module assignments across runs
Earlier Versions
Version 0.2.x - Initial development releases with basic AUTOSAR parsing and Mermaid output
Installation
pip install autosar-calltree
For development:
git clone https://github.com/melodypapa/autosar-calltree.git
cd autosar-calltree
pip install -e ".[dev]"
Building Distribution Packages
This project uses pyproject.toml for modern Python packaging (PEP 621). To build distribution packages:
# Install build dependencies
pip install build
# Build source distribution (sdist) and wheel
python -m build
# The built packages will be in the dist/ directory:
# - autosar_calltree-<version>.tar.gz (source distribution)
# - autosar_calltree-<version>-py3-none-any.whl (wheel)
To install from the built packages:
pip install dist/autosar_calltree-<version>-py3-none-any.whl
Note: This project no longer uses setup.py. All configuration is managed through pyproject.toml.
Quick Start
Basic Usage
# Analyze a function with default settings (depth=3)
calltree --start-function Demo_Init --source-dir demo/src
# Use SW module configuration for architecture-level diagrams
calltree --start-function Demo_Init \
--source-dir demo/src \
--module-config demo/module_mapping.yaml \
--use-module-names \
--output demo/demo.md
# Specify depth and output
calltree --start-function Demo_Init \
--max-depth 2 \
--output demo/output.md
# Generate XMI format (with opt/loop block support)
calltree --start-function Demo_MainFunction \
--source-dir demo/src \
--format rhapsody \
--output demo/demo.xmi
# Generate Rhapsody-compatible XMI 2.1
calltree --start-function Demo_Init \
--source-dir demo/src \
--format rhapsody \
--output demo/rhapsody_demo.xmi
# Generate Rhapsody XMI with nested package structure
calltree --start-function Demo_Init \
--source-dir demo/src \
--format rhapsody \
--output demo/rhapsody_nested.xmi \
--rhapsody-package-path "MyPackage/SubPackage/DeepPackage"
# Generate Rhapsody XMI with custom model name
calltree --start-function Demo_Init \
--source-dir demo/src \
--format rhapsody \
--output demo/rhapsody_custom_model.xmi \
--rhapsody-model-name "MyProjectModel"
# Generate Rhapsody XMI with both custom model name and nested packages
calltree --start-function Demo_Init \
--source-dir demo/src \
--format rhapsody \
--output demo/rhapsody_full.xmi \
--rhapsody-model-name "MyProjectModel" \
--rhapsody-package-path "MyPackage/SubPackage/DeepPackage"
# Enable loop detection
calltree --start-function Demo_MainFunction \
--source-dir demo/src \
--enable-loops \
--output demo/demo_loops.md
# Enable conditional detection
calltree --start-function Demo_MainFunction \
--source-dir demo/src \
--enable-conditionals \
--output demo/demo_conditionals.md
# Enable both loops and conditionals
calltree --start-function Demo_MainFunction \
--source-dir demo/src \
--enable-loops \
--enable-conditionals \
--output demo/demo_full.md
# Verbose mode with detailed statistics and cache progress
calltree --start-function Demo_Init \
--source-dir demo/src \
--verbose
Python API
from autosar_calltree.database.function_database import FunctionDatabase
from autosar_calltree.analyzers.call_tree_builder import CallTreeBuilder
from autosar_calltree.generators.mermaid_generator import MermaidGenerator
from autosar_calltree.config.module_config import ModuleConfig
from pathlib import Path
# Load module configuration (optional)
config = ModuleConfig(Path("demo/module_mapping.yaml"))
# Build function database (with caching and module config)
db = FunctionDatabase(source_dir="demo/src", module_config=config)
db.build_database(use_cache=True)
# Build call tree with loop and conditional detection
builder = CallTreeBuilder(db)
result = builder.build_tree(
start_function="Demo_Init",
max_depth=3,
enable_loops=True, # Enable loop detection
enable_conditionals=True # Enable conditional detection
)
# Generate Mermaid diagram with module names and parameters
# include_returns=False (default) omits return statements for cleaner diagrams
generator = MermaidGenerator(
use_module_names=True,
include_returns=False
)
generator.generate(result, output_path="call_tree.md")
Command-Line Options
calltree [OPTIONS]
Options:
--start-function TEXT Starting function name [required]
--max-depth INTEGER Maximum call depth (default: 3)
--source-dir PATH Source code directory (default: ./demo/src)
--format [mermaid|rhapsody] Output format (default: mermaid)
--output PATH Output file path (default: call_tree.md)
--module-config PATH YAML file mapping C files to SW modules
--use-module-names/--no-use-module-names
Use SW module names as Mermaid participants (default: True)
--enable-loops Enable loop detection and representation (default: False)
--enable-conditionals Enable if-else conditional detection and representation (default: False)
--rhapsody-package-path TEXT Package path for Rhapsody XMI output (e.g., 'Package1/Package2/Package3').
Creates nested packages in the XMI structure (default: flat package structure)
Max depth: 30 levels, max name length: 50 characters, valid characters: alphanumeric, underscore, space
--rhapsody-model-name TEXT Custom name for the UML model in Rhapsody XMI output (default: CallTree_{root_function})
--cache-dir PATH Cache directory (default: <source-dir>/.cache) --no-cache Disable cache usage
--rebuild-cache Force rebuild of cache
--no-abbreviate-rte Do not abbreviate RTE function names
--verbose, -v Enable verbose output
--list-functions, -l List all available functions and exit
--search TEXT Search for functions matching pattern
--help Show this message and exit
Output Examples
Mermaid Sequence Diagram with Opt Blocks
sequenceDiagram
participant DemoModule
participant CommunicationModule
participant HardwareModule
participant SoftwareModule
DemoModule->>CommunicationModule: COM_InitCommunication(baud_rate, buffer_size)
opt mode > 0x00
DemoModule->>DemoModule: Demo_Update(mode)
opt mode == 0x05
DemoModule->>CommunicationModule: COM_SendLINMessage(msg_id, data)
end
DemoModule->>SoftwareModule: SW_UpdateState(new_state)
end
DemoModule->>HardwareModule: HW_ReadSensor(sensor_id)
DemoModule->>SoftwareModule: SW_ProcessData(data, length)
Key Features:
- Conditional calls are automatically wrapped in
optblocks - Shows actual condition text from source code (e.g.,
mode > 0x00,mode == 0x05) - Supports nested conditionals
- Participants appear in the order they are first encountered
- Function parameters are displayed in the call arrows
- Return statements are omitted by default for cleaner visualization
- Module names are used as participants when
--use-module-namesis enabled
XMI Output with Opt Blocks
The XMI output also supports opt blocks using UML combined fragments:
<uml:fragment name="opt" interactionOperator="opt">
<uml:operand name="update_mode == 0x05">
<uml:message name="COM_SendLINMessage"
signature="COM_SendLINMessage(msg_id, data)"
messageSort="synchCall">
<uml:sendEvent xmi:id="calltree_22"/>
<uml:receiveEvent xmi:id="calltree_23"/>
</uml:message>
</uml:operand>
</uml:fragment>
XMI Features:
- UML 2.5 compliant XMI documents
- Combined fragments with
optinteraction operator - Operand elements display the condition text
- Can be imported into UML tools like Enterprise Architect, Visual Paradigm, MagicDraw
- Proper XML structure with correct namespaces
Rhapsody Package Path
When generating Rhapsody XMI output, you can specify a nested package structure using the --rhapsody-package-path option. This allows you to organize your sequence diagrams within a hierarchical package structure that matches your project's organization.
Usage:
# Create nested packages: MyPackage โ SubPackage โ DeepPackage โ Sequence_Diagram
calltree --start-function Demo_Init \
--source-dir demo/src \
--format rhapsody \
--output demo/rhapsody_nested.xmi \
--rhapsody-package-path "MyPackage/SubPackage/DeepPackage"
Generated XMI Structure:
<uml:Model name="CallTree_Demo_Init">
<packagedElement xmi:type="uml:Package" name="MyPackage">
<packagedElement xmi:type="uml:Package" name="SubPackage">
<packagedElement xmi:type="uml:Package" name="DeepPackage">
<packagedElement xmi:type="uml:Package" name="Sequence_Diagram">
<packagedElement xmi:type="uml:Interaction" name="seq_Demo_Init">
<!-- Interaction content -->
</packagedElement>
</packagedElement>
</packagedElement>
</packagedElement>
</packagedElement>
</uml:Model>
Package Path Constraints:
- Maximum depth: 30 levels
- Maximum name length: 50 characters per package name
- Valid characters: Alphanumeric, underscore, and space only
- Whitespace handling: Leading/trailing whitespace is automatically stripped
- Empty segments: Trailing slashes are handled gracefully
Examples:
# Valid: 3 levels
--rhapsody-package-path "MyPackage/SubPackage/DeepPackage"
# Valid: At maximum depth (30 levels)
--rhapsody-package-path "P1/P2/P3/.../P30"
# Invalid: Exceeds maximum depth (31 levels)
--rhapsody-package-path "P1/P2/.../P31"
# Error: Package path depth exceeds maximum of 30 levels. Got 31 levels.
# Invalid: Contains hyphen
--rhapsody-package-path "My-Package"
# Error: Package name 'My-Package' contains invalid characters: -.
# Invalid: Name too long (51 characters)
--rhapsody-package-path "A" * 51
# Error: Package name 'AAA...' exceeds maximum length of 50 characters.
Benefits:
- Organize diagrams within project-specific package hierarchies
- Match your Rhapsody project structure
- Better integration with existing Rhapsody models
- Clear separation between different analysis results
Note: If not specified, the default behavior creates a flat package structure with a single Sequence_Diagram package directly under the Model.
Rhapsody Model Name
You can also customize the UML model name in the Rhapsody XMI output using the --rhapsody-model-name option. By default, the model name is set to CallTree_{root_function}, but you can specify any custom name to match your project's naming conventions.
Usage:
# Generate Rhapsody XMI with custom model name
calltree --start-function Demo_Init \
--source-dir demo/src \
--format rhapsody \
--output demo/rhapsody_custom.xmi \
--rhapsody-model-name "MyProjectModel"
Generated XMI Structure:
<uml:Model name="MyProjectModel">
<packagedElement xmi:type="uml:Package" name="Sequence_Diagram">
<!-- Interaction content -->
</packagedElement>
</uml:Model>
Default Behavior:
# Without --rhapsody-model-name, uses default naming
calltree --start-function Demo_Init --format rhapsody --output demo/rhapsody.xmi
Generated XMI with Default Name:
<uml:Model name="CallTree_Demo_Init">
<packagedElement xmi:type="uml:Package" name="Sequence_Diagram">
<!-- Interaction content -->
</packagedElement>
</uml:Model>
Combined with Package Path:
# Use both custom model name and nested package path
calltree --start-function Demo_Init \
--source-dir demo/src \
--format rhapsody \
--output demo/rhapsody_full.xmi \
--rhapsody-model-name "MyProjectModel" \
--rhapsody-package-path "MyPackage/SubPackage/DeepPackage"
Benefits:
- Match your Rhapsody project's model naming conventions
- Better integration with existing Rhapsody models
- Clear identification of different analysis results
- Consistent naming across multiple XMI exports
Note: The model name is independent of the package path. You can use a custom model name with or without nested packages.
Generated Markdown Structure
The tool generates comprehensive Markdown files with:
- Metadata header (timestamp, settings, statistics)
- Mermaid sequence diagram with function parameters and opt/loop blocks
- Function details table with parameter information
- Text-based call tree
- Circular dependency warnings
- Analysis statistics
Note: Return statements are omitted from sequence diagrams by default for cleaner visualization. This can be configured programmatically when using the Python API.
Loop and Conditional Detection
The tool automatically detects for, while, and if/else statements in your C code and represents them as loop and opt blocks in Mermaid diagrams and combined fragments in XMI.
Note: Loop and conditional detection are disabled by default to keep diagrams clean. Use --enable-loops and --enable-conditionals flags to enable them.
Mermaid Loop Example
Source Code:
for (sensor_count = 0; sensor_count < 10; sensor_count++) {
HW_ReadSensor(sensor_count);
SW_ProcessData((uint8*)0x20001000, 0x64);
}
Generated Mermaid Diagram (with --enable-loops):
sequenceDiagram
participant Demo_MainFunction
participant HW_ReadSensor
participant SW_ProcessData
loop sensor_count < 10
Demo_MainFunction->>HW_ReadSensor: call(sensor_id)
Demo_MainFunction->>SW_ProcessData: call(data, length)
end
Mermaid Conditional Example
Source Code:
if (update_mode == 0x05) {
COM_SendLINMessage(0x456, (uint8*)0x20003000);
}
Generated Mermaid Diagram (with --enable-conditionals):
sequenceDiagram
participant Demo_Update
participant COM_SendLINMessage
opt update_mode == 0x05
Demo_Update->>COM_SendLINMessage: call(msg_id, data)
end
XMI Combined Fragments
Both loops and conditionals are represented as UML combined fragments in XMI output:
<!-- Loop fragment -->
<uml:fragment name="loop" interactionOperator="loop">
<uml:operand name="sensor_count < 10">
<uml:message name="HW_ReadSensor" />
<uml:message name="SW_ProcessData" />
</uml:operand>
</uml:fragment>
<!-- Conditional fragment -->
<uml:fragment name="opt" interactionOperator="opt">
<uml:operand name="update_mode == 0x05">
<uml:message name="COM_SendLINMessage" />
</uml:operand>
</uml:fragment>
Features:
- โ
Automatic detection of
for,while, andif/elsestatements - โ Actual condition text extracted from source code
- โ Nested conditionals and loops supported
- โ Works with both Mermaid and XMI output formats
- โ Disabled by default for cleaner diagrams
Supported AUTOSAR Patterns
The tool recognizes and parses:
// AUTOSAR function declarations
FUNC(void, RTE_CODE) Function_Name(void);
FUNC(Std_ReturnType, RTE_CODE) Com_Test(VAR(uint32, AUTOMATIC) timerId);
STATIC FUNC(uint8, CODE) Internal_Function(void);
// AUTOSAR pointer returns
FUNC_P2VAR(uint8, AUTOMATIC, APPL_VAR) Get_Buffer(void);
FUNC_P2CONST(ConfigType, AUTOMATIC, APPL_VAR) Get_Config(void);
// AUTOSAR parameters
VAR(uint32, AUTOMATIC) variable
P2VAR(uint8, AUTOMATIC, APPL_DATA) buffer
P2CONST(ConfigType, AUTOMATIC, APPL_DATA) config
CONST(uint16, AUTOMATIC) constant
// Traditional C (fallback)
void traditional_function(uint8 param);
static uint32 helper_function(void);
SW Module Configuration
Map C source files to SW modules using YAML configuration:
# module_mapping.yaml
version: "1.0"
# Specific file mappings
file_mappings:
demo.c: DemoModule
# Pattern-based mappings (glob patterns)
pattern_mappings:
"hw_*.c": HardwareModule
"sw_*.c": SoftwareModule
"com_*.c": CommunicationModule
# Default module for unmapped files (optional)
default_module: "Other"
Benefits:
- Generate architecture-level diagrams showing module interactions
- Identify cross-module dependencies
- Verify architectural boundaries
- Support high-level design documentation
Usage:
calltree --start-function Demo_Init --module-config demo/module_mapping.yaml --use-module-names --max-depth 3 --output demo/demo_sequence.md
This generates diagrams with:
- Participants: SW module names (HardwareModule, SoftwareModule, etc.) in the order they are first encountered
- Arrows: Function names with parameters being called between modules
- Opt Blocks: Conditional calls wrapped with actual condition text
- Function Table: Includes module column showing each function's SW module
- Clean Visualization: Return statements omitted by default
Use Cases
- Documentation: Generate call flow diagrams for documentation
- Code Review: Visualize function dependencies
- Impact Analysis: Understand change impact before modifications
- Onboarding: Help new developers understand codebase structure
- Compliance: Generate diagrams for safety certification (ISO 26262)
- Refactoring: Identify tightly coupled components
- Architecture: Verify architectural boundaries
Project Structure
autosar-calltree/
โโโ src/autosar_calltree/
โ โโโ cli/ # Command-line interface
โ โโโ config/ # Configuration management (module mappings)
โ โโโ parsers/ # Code parsers (AUTOSAR, C)
โ โโโ analyzers/ # Analysis logic (call tree, dependencies)
โ โโโ database/ # Data models and caching
โ โโโ generators/ # Output generators (Mermaid, XMI, Rhapsody)
โ โโโ utils/ # Utilities (empty, for future use)
โโโ demo/ # Demo AUTOSAR C files and examples
โ โโโ src/ # C source code
โ โ โโโ communication.c
โ โ โโโ demo.c
โ โ โโโ demo.h
โ โ โโโ hardware.c
โ โ โโโ software.c
โ โโโ module_mapping.yaml # Module configuration
โ โโโ demo.md # Example Mermaid output
โ โโโ demo_main.md # Example Mermaid output
โ โโโ rhapsody_demo_main.xmi # Example Rhapsody XMI 2.1 output
โ โโโ README.md # Demo usage guide
โโโ tests/ # Test suite
โ โโโ unit/ # Unit tests
โ โโโ integration/ # Integration tests
โ โโโ fixtures/ # Test data
โโโ docs/ # Documentation
โ โโโ requirements/ # Software requirements
โ โโโ rhapsody_export.md # Rhapsody export guide
โ โโโ rhapsody_troubleshooting.md # Rhapsody troubleshooting
โโโ scripts/ # Utility scripts
Development
Running Tests
The project has comprehensive test coverage with 298 tests across all modules:
# Run all tests
pytest tests/
# Run with verbose output
pytest -vv tests/
# Run specific test module
pytest tests/test_models.py
pytest tests/test_parsers.py
pytest tests/test_database.py
pytest tests/test_analyzers.py
pytest tests/test_config.py
pytest tests/test_generators.py
pytest tests/test_cli.py
pytest tests/test_integration.py
# Run specific test case
pytest tests/test_models.py::TestFunctionType::test_function_type_enum_values
# Run tests with live stdout output (useful for debugging)
pytest -vv -s tests/
# Run tests and show coverage report
pytest --cov=autosar_calltree --cov-report=html --cov-report=term
# Run tests with coverage and omit tests from coverage report
pytest --cov=autosar_calltree --cov-report=html --cov-report=term --omit=tests/
Test Coverage
The project maintains 89% code coverage across all modules:
| Module | Coverage | Tests |
|---|---|---|
| Models | 97% | 28 |
| AUTOSAR Parser | 97% | 15 |
| C Parser | 86% | 18 |
| Database | 83% | 20 |
| Analyzers | 95% | 20 |
| Config | 97% | 25 |
| Generators | 89% | 45 |
| CLI (Integration) | 90% | 14 |
| End-to-End | ~90% | 120 |
| Total | 89% | 298 |
Code Quality
# Format code with Black
black src/ tests/
# Sort imports with isort
isort src/ tests/
# Lint with flake8
flake8 src/ tests/
# Type checking with mypy
mypy src/
# Run all quality checks (uses pre-configured scripts)
./scripts/run_quality.sh
# Check for traceability between requirements and tests
python scripts/check_traceability.py
Slash Commands
The project provides convenient slash commands for common development tasks:
# Run all tests
/test
# Run quality checks
/quality
# Test requirement management
/req
# Merge a pull request
/merge-pr
# Generate GitHub workflow
/gh-workflow
# Parse and update documentation
/parse
# Sync documentation
/sync-docs
These commands are documented in .claude/commands/ and can be used from within Claude Code.
Requirements Traceability
The project maintains 100% traceability between requirements and tests:
# Check traceability matrix
python scripts/check_traceability.py
# View traceability documentation
cat docs/TRACEABILITY.md
# View requirements index
cat docs/requirements/README.md
# View test index
cat docs/tests/README.md
Building Documentation
cd docs
make html
Contributing
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
See CONTRIBUTING.md for detailed guidelines.
License
MIT License - see LICENSE file for details.
Authors
- Melodypapa melodypapa@outlook.com
Acknowledgments
- Inspired by the need for better AUTOSAR code analysis tools
- Built for the automotive embedded systems community
Related Projects
Roadmap
- PlantUML output format
- GraphViz DOT format
- HTML interactive viewer
- VS Code extension
- GitHub Actions integration
- Configuration file support (YAML for module mappings)
- Multi-threading for large codebases
- Function complexity metrics
- Dead code detection
- XMI/UML 2.5 output format with opt/loop/alt block support
- Automatic conditional call detection with opt/alt/else blocks
- Loop detection (for/while) with condition extraction
- Rhapsody XMI 2.1 export with full structural compatibility
Support
- Issues: GitHub Issues
- Documentation: Read the Docs
- Discussions: GitHub Discussions
Made with โค๏ธ for the embedded systems community
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file autosar_calltree-0.8.2.tar.gz.
File metadata
- Download URL: autosar_calltree-0.8.2.tar.gz
- Upload date:
- Size: 76.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
585bf4fc2c2925dda4bb1a0eafa1c67e1dab2ef781c61d9d0784eafa40abcde6
|
|
| MD5 |
7337aa06560de559394ee8d5dcdd85ad
|
|
| BLAKE2b-256 |
be664432e38d22a11b424fe00176ae39d6762e0418eae84e15fdf46c98f7bf4f
|
Provenance
The following attestation bundles were made for autosar_calltree-0.8.2.tar.gz:
Publisher:
publish.yml on melodypapa/autosar_calltree
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
autosar_calltree-0.8.2.tar.gz -
Subject digest:
585bf4fc2c2925dda4bb1a0eafa1c67e1dab2ef781c61d9d0784eafa40abcde6 - Sigstore transparency entry: 1007432121
- Sigstore integration time:
-
Permalink:
melodypapa/autosar_calltree@5aa079607bb777a2a4d456fd2257a26bbb9b0efe -
Branch / Tag:
refs/tags/v0.8.2 - Owner: https://github.com/melodypapa
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@5aa079607bb777a2a4d456fd2257a26bbb9b0efe -
Trigger Event:
push
-
Statement type:
File details
Details for the file autosar_calltree-0.8.2-py3-none-any.whl.
File metadata
- Download URL: autosar_calltree-0.8.2-py3-none-any.whl
- Upload date:
- Size: 61.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6cc5f197775a4b9cc8e97718ec81aa5bbc1c89ee1639cecdcd206bb215ba5e36
|
|
| MD5 |
1d729bc11ed76e59383bef2dfd5c2841
|
|
| BLAKE2b-256 |
b3d1fe201578a93251366ed1259b002c095827adabd6997956f52c9f91d74288
|
Provenance
The following attestation bundles were made for autosar_calltree-0.8.2-py3-none-any.whl:
Publisher:
publish.yml on melodypapa/autosar_calltree
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
autosar_calltree-0.8.2-py3-none-any.whl -
Subject digest:
6cc5f197775a4b9cc8e97718ec81aa5bbc1c89ee1639cecdcd206bb215ba5e36 - Sigstore transparency entry: 1007432147
- Sigstore integration time:
-
Permalink:
melodypapa/autosar_calltree@5aa079607bb777a2a4d456fd2257a26bbb9b0efe -
Branch / Tag:
refs/tags/v0.8.2 - Owner: https://github.com/melodypapa
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@5aa079607bb777a2a4d456fd2257a26bbb9b0efe -
Trigger Event:
push
-
Statement type: