Skip to content

Latest commit

 

History

History
301 lines (226 loc) · 9.66 KB

architecture.md

File metadata and controls

301 lines (226 loc) · 9.66 KB

Architecture

Internal structure of IFC Inspector — layered design, parsing pipeline, and data flow.


System overview

┌─────────────────────────────────────────────────────────────┐
│                        CLI (main.rs)                        │
│                   clap · TUI or export flags                │
└────────────────────────────┬────────────────────────────────┘
                             │
         ┌───────────────────┼───────────────────┐
         ▼                   ▼                   ▼
┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐
│     Parser      │  │     Export      │  │       UI        │
│  step · ifc     │  │  csv · dto · json│  │ app · dashboard │
└────────┬────────┘  └────────┬────────┘  └────────┬────────┘
         │                    │                     │
         └────────────────────┼─────────────────────┘
                              ▼
                    ┌─────────────────┐
                    │      Model      │
                    │ project · query │
                    └─────────────────┘

Dependency rule: Parser and Model have no knowledge of Ratatui. UI depends on Model; Export depends on Model. CLI wires everything together.


Crate layout

src/
├── main.rs              Entry point, argument parsing, terminal lifecycle
├── lib.rs               Public module exports
├── error.rs             ParseError, ExportError (thiserror)
├── parser/
│   ├── step.rs          STEP tokenizer + type index
│   ├── attrs.rs         EntityId, attribute helpers, length formatting
│   └── ifc/
│       ├── mod.rs       Re-exports
│       ├── extract.rs   parse_step · extract_model · parse_ifc_file
│       └── registry.rs  Entity → category mappings
├── model/
│   ├── project.rs       IfcProject, Category, Storey
│   ├── instance.rs      Instance (single record per element)
│   ├── element_type.rs  ElementType (family/type)
│   └── query.rs         ProjectView, storey filtering
├── export/
│   ├── dto.rs           ExportProject (stable JSON schema)
│   ├── csv.rs           Type summary CSV
│   └── json.rs          JSON serialization
└── ui/
    ├── app.rs           State machine, input handling
    ├── dashboard.rs     Ratatui rendering (3 views)
    └── theme.rs         Brand colors and styles

Parser pipeline

Three-stage pipeline — each stage independently testable:

IFC file (text)
      │
      ▼  std::fs::read_to_string
 Raw String
      │
      ▼  parse_step()
 StepFile { entities, schema, type_index }
      │
      ▼  extract_model()
 IfcProject { categories, storeys, instances, … }

Stage 1: STEP tokenization (step.rs)

IFC files are ISO 10303-21 text. The tokenizer:

  1. Reads FILE_SCHEMA for IFC version
  2. Parses DATA; section line-by-line
  3. Builds StepEntity { id, entity_type, values } per line
  4. Maintains a type index (HashMap<String, Vec<u64>>) for O(1) entity-type lookups

Value types:

pub enum StepValue {
    String(String), Integer(i64), Real(f64), Boolean(bool),
    Enum(String), Reference(u64), List(Vec<StepValue>),
    Null, Derived,
}

Malformed lines increment skipped_entity_count (surfaced in parse_warnings).

Stage 2: Attribute helpers (attrs.rs)

Shared extraction utilities — avoids magic-index duplication:

pub struct EntityId(pub u64);
pub fn attr_string(values: &[StepValue], index: usize) -> Option<String>;
pub fn attr_refs(values: &[StepValue], index: usize) -> Vec<EntityId>;
pub fn format_length(value: f64) -> String;  // mm vs m heuristics

Stage 3: IFC extraction (ifc/extract.rs)

Orchestrates domain extraction:

Step Function Output
Project metadata extract_project_name String
Storeys extract_storeys Vec<Storey>
Spatial extract_spatial_containment instance → storey map
Types extract_type_relationships type → instances map
Properties extract_all_properties instance → props map
Instances build_instances HashMap<u64, Instance>
Categories build_categories Vec<Category> + Untyped

Entity-to-category rules live in ifc/registry.rs.


Model layer

IfcProject

Root container after extraction:

pub struct IfcProject {
    pub name: String,
    pub schema: String,
    pub file_path: String,
    pub categories: Vec<Category>,
    pub storeys: Vec<Storey>,
    pub instances: HashMap<u64, Instance>,
    pub parse_warnings: Vec<String>,
}

Design choice: One Instance map replaces three parallel HashMaps (element_to_storey, element_properties, instance_global_ids). Simpler API, fewer sync bugs.

Instance

pub struct Instance {
    pub id: u64,
    pub global_id: String,
    pub name: String,
    pub tag: Option<String>,
    pub entity_type: String,
    pub type_id: Option<u64>,
    pub storey_id: Option<u64>,
    pub properties: HashMap<String, String>,
}

Query layer (query.rs)

Storey filtering is pure logic — not embedded in the UI frame loop:

pub struct ProjectView<'a> {
    project: &'a IfcProject,
    storey_id: Option<u64>,  // None = All levels
}

Methods: filtered_types, filtered_category_count, filtered_instance_ids, storey_name, instance_global_id.

The TUI creates a ProjectView when rendering; library consumers use the same API.


UI layer

State machine (app.rs)

pub enum View { Dashboard, TypeDetail, InstanceBrowser }
pub enum FocusPanel { Levels, Categories, Types }

Key state decisions:

  • selected_instance_id: Option<u64> — stable across sorted displays (not list index)
  • Level filter applies in Type Detail and Instance Browser, not just dashboard
  • No StepFile in App — UI reads only from IfcProject

Rendering (dashboard.rs + theme.rs)

Three draw functions map 1:1 to views. Theme constants isolated for consistent brand appearance.


Export layer

Module Output Purpose
csv.rs Flat CSV Excel / pivot tables
dto.rs ExportProject Stable JSON schema
json.rs .json file Serializes ExportProject, not raw IfcProject

Why a DTO? Internal maps and STEP IDs are implementation details. External consumers get a documented, versionable schema.


Data flow (end-to-end)

model.ifc
   │
   ├─► parse_ifc_file(path)
   │        │
   │        ├─► parse_step(content) ──► StepFile
   │        └─► extract_model(step) ──► IfcProject
   │
   ├─► App::new(project).run(terminal)  ──► TUI
   │
   ├─► export_csv(&project, path)        ──► types.csv
   │
   └─► export_json(&project, path)       ──► ExportProject JSON

Error handling

pub enum ParseError {
    FileRead { path: PathBuf, source: std::io::Error },
    InvalidStep { message: String },  // e.g. empty DATA section
}

pub enum ExportError {
    FileCreate { … }, WriteError { … },
    JsonSerialize { … }, CsvWrite { … },
}

CLI uses color-eyre for human-readable error reports. Library callers match on typed errors.


Performance characteristics

Aspect Approach
Parse Single pass over file lines
Entity lookup HashMap by ID — O(1)
Type lookup Pre-built index — avoids scanning all entities per query
UI filtering ProjectView scans instance lists per category (acceptable for inspection-scale models)
Memory Roughly proportional to entity count; all entities kept in memory

For 100MB+ coordination models, expect multi-second parse times. Export-only mode avoids TUI overhead.


Testing architecture

tests/fixtures/sample.ifc     Minimal IFC4 model (committed)
tests/parser_tests.rs         Integration tests (parse, export, errors)

src/parser/step.rs            #[cfg(test)] tokenizer tests
src/parser/ifc/extract.rs     #[cfg(test)] extraction smoke test
src/model/query.rs            #[cfg(test)] filter logic tests
src/ui/app.rs                 #[cfg(test)] navigation + filter tests

CI (.github/workflows/ci.yml): cargo fmt --check, cargo clippy -D warnings, cargo test, release build.


Extension points

Reasonable next steps without rewriting the architecture:

  1. Typed entity modules — IfcDoor::from_step(&StepEntity) per entity file
  2. IfcRelAggregates walker — nested spatial containment
  3. Property enum values — IfcPropertyEnumeratedValue
  4. Criterion benchmarks — reproducible parse metrics on fixture set

See Design Decisions for scope boundaries.


Related docs