From 92fc4654676dca68b8993b3b474f2b45f1652a45 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Thu, 12 Jun 2025 19:01:32 +0000 Subject: [PATCH 1/2] Initial plan for issue From 9240cd6f129456e24aa062941dbbde809fe1ae63 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 13 Jun 2025 05:08:42 +0000 Subject: [PATCH 2/2] Implement comprehensive architecture documentation with Mermaid diagrams Co-authored-by: drzo <15202748+drzo@users.noreply.github.com> --- README.md | 32 +++ docs/ARCHITECTURE.md | 456 +++++++++++++++++++++++++++++++++++ docs/COMPONENTS.md | 561 +++++++++++++++++++++++++++++++++++++++++++ docs/EXAMPLES.md | 558 ++++++++++++++++++++++++++++++++++++++++++ docs/README.md | 409 +++++++++++++++++++++++++++++++ 5 files changed, 2016 insertions(+) create mode 100644 docs/ARCHITECTURE.md create mode 100644 docs/COMPONENTS.md create mode 100644 docs/EXAMPLES.md create mode 100644 docs/README.md diff --git a/README.md b/README.md index f92dd9c..bc7e71b 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,16 @@ # plingua The P-Lingua language for Membrane Computing +P-Lingua is a comprehensive framework for membrane computing that provides a complete ecosystem for defining, parsing, simulating, and generating code for P-systems (membrane systems). + +## 📚 Documentation + +### [Comprehensive Architecture Documentation](docs/README.md) +Detailed architectural insights with Mermaid diagrams covering: +- **[System Architecture](docs/ARCHITECTURE.md)**: High-level design patterns and data flows +- **[Component Deep Dive](docs/COMPONENTS.md)**: Internal architecture of parser, simulator, and generator +- **[Usage Examples](docs/EXAMPLES.md)**: Practical demonstrations and integration guides + ## Dependencies * Linux OS (tested on Ubuntu 16.04 and Ubuntu 18.04) @@ -19,3 +29,25 @@ sudo apt-get install build-essential flex bison libboost-filesystem-dev libboost * make simulator * sudo make install +## Architecture Overview + +```mermaid +graph TD + A[P-Lingua Source] --> B[Parser] + B --> C[P-System Model] + C --> D[Simulator] + C --> E[Code Generator] + D --> F[Results] + E --> G[Generated Code] + + style A fill:#e3f2fd + style C fill:#f3e5f5 + style F fill:#e8f5e8 + style G fill:#fff3e0 +``` + +The framework consists of three main components: +- **Parser**: Transforms P-Lingua source into executable models +- **Simulator**: Executes membrane computing simulations +- **Generator**: Produces optimized C++ implementations + diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..5eaf44d --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,456 @@ +# P-Lingua Architecture Documentation + +## Overview + +P-Lingua is a comprehensive framework for membrane computing that provides a complete ecosystem for defining, parsing, simulating, and generating code for P-systems (membrane systems). This documentation provides detailed architectural insights with visual diagrams to facilitate understanding and contribution. + +## High-Level System Architecture + +```mermaid +graph TD + A[P-Lingua Source Files] --> B[Lexical Analyzer] + B --> C[Parser] + C --> D[Syntax Tree] + D --> E[Semantic Analyzer] + E --> F[P-System Model] + F --> G[Simulator Engine] + F --> H[Code Generator] + G --> I[Configuration Output] + H --> J[C++ Generated Code] + + subgraph "Core Components" + K[Parser Module] + L[Simulator Module] + M[Generator Module] + N[Serialization Module] + end + + C --> K + G --> L + H --> M + F --> N + + style A fill:#e1f5fe + style F fill:#f3e5f5 + style I fill:#e8f5e8 + style J fill:#fff3e0 +``` + +## Core Data Structures + +```mermaid +classDiagram + class Psystem { + +String model + +Membrane structure + +map~Label,Multiset~ multisets + +set~Rule~ rules + +Semantics semantics + +Features features + } + + class Membrane { + +char charge + +Label label + +vector~Membrane~ data + } + + class Rule { + +LHR lhr + +char arrow + +RHR rhr + +Features features + } + + class Configuration { + +unsigned long time + +Multiset environment + +vector~CMembrane~ membranes + } + + class Parser { + +getInstance() + +parse() + +error() + +addNode() + +getRoot() + } + + class Simulator { + +step() + +selectRules() + +executeRules() + +getCurrentConfiguration() + } + + Psystem --> Membrane + Psystem --> Rule + Parser --> Psystem + Simulator --> Configuration + Configuration --> Membrane +``` + +## Module Interaction Architecture + +```mermaid +graph LR + subgraph "Input Layer" + A[P-Lingua Files] + B[Include Files] + C[Command Line Args] + end + + subgraph "Parser Module" + D[Lexical Analyzer] + E[Syntax Analyzer] + F[Semantic Analyzer] + G[Pattern Matcher] + end + + subgraph "Core Engine" + H[Memory Manager] + I[Symbol Table] + J[Error Handler] + K[File Manager] + end + + subgraph "Execution Layer" + L[Simulator Engine] + M[Rule Selector] + N[Configuration Manager] + O[Random Generator] + end + + subgraph "Output Layer" + P[C++ Generator] + Q[Binary Serializer] + R[Text Formatter] + S[Visualization] + end + + A --> D + B --> D + C --> L + + D --> E + E --> F + F --> G + + G --> H + G --> I + E --> J + A --> K + + I --> L + H --> L + L --> M + L --> N + L --> O + + L --> P + N --> Q + L --> R + N --> S + + style A fill:#e3f2fd + style L fill:#f1f8e9 + style P fill:#fff8e1 +``` + +## Parsing Data Flow + +```mermaid +sequenceDiagram + participant User + participant Parser + participant Lexer + participant Grammar + participant AST + participant Semantic + participant Model + + User->>Parser: Input .pli file + Parser->>Lexer: Tokenize input + Lexer-->>Parser: Token stream + Parser->>Grammar: Parse tokens + Grammar-->>Parser: Parse tree + Parser->>AST: Build syntax tree + AST-->>Parser: Abstract syntax tree + Parser->>Semantic: Analyze semantics + Semantic->>Model: Validate & transform + Model-->>Semantic: P-System model + Semantic-->>Parser: Validated model + Parser-->>User: Success/Error result +``` + +## Simulation Execution Flow + +```mermaid +stateDiagram-v2 + [*] --> Initialize + Initialize --> LoadPsystem: Parse input + LoadPsystem --> BuildConfiguration: Create initial state + BuildConfiguration --> SelectRules: Start simulation + + SelectRules --> EvaluateRules: Find applicable rules + EvaluateRules --> ApplyRules: Rules selected + ApplyRules --> UpdateConfiguration: Execute rules + UpdateConfiguration --> CheckTermination: Update state + + CheckTermination --> SelectRules: Continue simulation + CheckTermination --> OutputResults: Termination condition met + + EvaluateRules --> OutputResults: No rules applicable + OutputResults --> [*] + + note right of SelectRules + Rule selection considers: + - Priority levels + - Randomization + - Maximum applications + end note + + note right of ApplyRules + Rule application involves: + - Membrane dissolution + - Object production/consumption + - Membrane division + end note +``` + +## Memory and Object Management + +```mermaid +graph TB + subgraph "Memory Management" + A[Value Objects] + B[String Pool] + C[Multiset Manager] + D[Membrane Pool] + end + + subgraph "Object Lifecycle" + E[Creation] + F[Usage] + G[Modification] + H[Cleanup] + end + + subgraph "Data Types" + I[Primitive Values] + J[Object Strings] + K[Label Strings] + L[Feature Strings] + end + + A --> I + B --> J + B --> K + B --> L + + E --> A + E --> B + E --> C + E --> D + + F --> G + G --> H + + C --> F + D --> F + + style A fill:#e8eaf6 + style B fill:#e0f2f1 + style C fill:#fce4ec + style D fill:#fff3e0 +``` + +## Code Generation Architecture + +```mermaid +flowchart TD + A[P-System Model] --> B[Code Generator] + B --> C[Template Engine] + B --> D[Symbol Mapper] + B --> E[Rule Compiler] + + C --> F[Header Generation] + C --> G[Implementation Generation] + D --> H[Name Resolution] + D --> I[Type Mapping] + E --> J[Rule Translation] + E --> K[Optimization] + + F --> L[Generated Headers] + G --> M[Generated Source] + H --> M + I --> M + J --> M + K --> M + + L --> N[Compilation Unit] + M --> N + + style A fill:#e1f5fe + style N fill:#e8f5e8 +``` + +## Error Handling and Diagnostics + +```mermaid +graph LR + subgraph "Error Sources" + A[Lexical Errors] + B[Syntax Errors] + C[Semantic Errors] + D[Runtime Errors] + end + + subgraph "Error Processing" + E[Error Collector] + F[Message Formatter] + G[Location Tracker] + H[Recovery Manager] + end + + subgraph "Error Output" + I[Console Messages] + J[Error Codes] + K[Diagnostic Info] + L[Suggestions] + end + + A --> E + B --> E + C --> E + D --> E + + E --> F + E --> G + E --> H + + F --> I + G --> K + H --> L + E --> J + + style A fill:#ffebee + style E fill:#fff3e0 + style I fill:#f3e5f5 +``` + +## File I/O and Serialization + +```mermaid +sequenceDiagram + participant App + participant FileManager + participant Serializer + participant Storage + + App->>FileManager: Load P-System + FileManager->>Storage: Read file + Storage-->>FileManager: Raw data + FileManager->>Serializer: Deserialize + Serializer-->>FileManager: P-System object + FileManager-->>App: Loaded system + + App->>FileManager: Save Configuration + FileManager->>Serializer: Serialize config + Serializer-->>FileManager: Binary data + FileManager->>Storage: Write file + Storage-->>FileManager: Success + FileManager-->>App: Saved +``` + +## Extension and Plugin Architecture + +```mermaid +graph TD + subgraph "Core Framework" + A[Base Parser] + B[Base Simulator] + C[Base Generator] + end + + subgraph "Extension Points" + D[Custom Models] + E[Rule Patterns] + F[Output Formats] + G[Optimization Passes] + end + + subgraph "Plugin Interface" + H[Model Registry] + I[Pattern Registry] + J[Format Registry] + K[Pass Manager] + end + + A --> H + B --> I + C --> J + C --> K + + D --> H + E --> I + F --> J + G --> K + + style A fill:#e8eaf6 + style D fill:#f3e5f5 + style H fill:#e0f2f1 +``` + +## Performance and Optimization + +```mermaid +graph LR + subgraph "Performance Bottlenecks" + A[Rule Selection] + B[Membrane Operations] + C[Memory Allocation] + D[Pattern Matching] + end + + subgraph "Optimization Strategies" + E[Rule Indexing] + F[Membrane Pooling] + G[Object Reuse] + H[Compile-time Analysis] + end + + subgraph "Monitoring" + I[Performance Counters] + J[Memory Profiling] + K[Execution Tracing] + L[Bottleneck Detection] + end + + A --> E + B --> F + C --> G + D --> H + + E --> I + F --> J + G --> K + H --> L + + style A fill:#ffebee + style E fill:#e8f5e8 + style I fill:#e3f2fd +``` + +## Conclusion + +This architecture documentation provides a comprehensive view of the P-Lingua framework's design and implementation. The system demonstrates sophisticated patterns for domain-specific language processing, including robust parsing, flexible simulation engines, and extensible code generation capabilities. + +Key architectural strengths include: +- **Modular Design**: Clear separation between parsing, simulation, and generation +- **Extensibility**: Plugin architecture for custom models and optimizations +- **Performance**: Optimized data structures and algorithms for membrane computing +- **Robustness**: Comprehensive error handling and diagnostics +- **Maintainability**: Well-structured codebase with clear interfaces + +The framework serves as an excellent foundation for membrane computing research and applications, providing both high-level abstractions and low-level control when needed. \ No newline at end of file diff --git a/docs/COMPONENTS.md b/docs/COMPONENTS.md new file mode 100644 index 0000000..c298d3a --- /dev/null +++ b/docs/COMPONENTS.md @@ -0,0 +1,561 @@ +# P-Lingua Component Deep Dive + +## Parser Component Architecture + +The parser component is the heart of P-Lingua's language processing pipeline, responsible for transforming P-Lingua source code into executable P-system models. + +### Parser Internal Architecture + +```mermaid +graph TD + subgraph "Lexical Analysis Layer" + A[Flex Scanner] --> B[Token Recognition] + B --> C[Symbol Classification] + C --> D[Token Stream] + end + + subgraph "Syntactic Analysis Layer" + D --> E[Bison Parser] + E --> F[Grammar Rules] + F --> G[Parse Tree] + G --> H[AST Construction] + end + + subgraph "Semantic Analysis Layer" + H --> I[Symbol Table] + I --> J[Type Checking] + J --> K[Pattern Validation] + K --> L[Model Generation] + end + + subgraph "Error Recovery" + M[Error Detection] + N[Error Recovery] + O[Error Reporting] + end + + E --> M + J --> M + M --> N + N --> O + + style A fill:#e3f2fd + style L fill:#e8f5e8 + style M fill:#ffebee +``` + +### Parser State Management + +```mermaid +stateDiagram-v2 + [*] --> Initialization + Initialization --> FileLoading: Start parsing + FileLoading --> Lexing: File loaded + Lexing --> Parsing: Tokens ready + Parsing --> SemanticAnalysis: Parse tree built + SemanticAnalysis --> ModelCreation: Semantics validated + ModelCreation --> [*]: Model complete + + Lexing --> ErrorRecovery: Lexical error + Parsing --> ErrorRecovery: Syntax error + SemanticAnalysis --> ErrorRecovery: Semantic error + ErrorRecovery --> FileLoading: Recoverable error + ErrorRecovery --> [*]: Fatal error + + note right of SemanticAnalysis + Performs: + - Symbol resolution + - Type checking + - Pattern matching + - Rule validation + end note +``` + +### Pattern Matching System + +```mermaid +flowchart LR + A[Rule Definition] --> B[Pattern Extractor] + B --> C[Pattern Database] + C --> D[Pattern Matcher] + D --> E[Match Validation] + E --> F[Rule Integration] + + subgraph "Pattern Types" + G[Object Patterns] + H[Membrane Patterns] + I[Rule Patterns] + J[Feature Patterns] + end + + B --> G + B --> H + B --> I + B --> J + + G --> D + H --> D + I --> D + J --> D + + style A fill:#e1f5fe + style F fill:#e8f5e8 +``` + +## Simulator Component Architecture + +The simulator executes P-system models by applying evolution rules and managing membrane configurations. + +### Simulation Engine Core + +```mermaid +graph TB + subgraph "Rule Management" + A[Rule Sets] + B[Rule Indexing] + C[Priority Management] + D[Rule Selection] + end + + subgraph "Configuration Management" + E[Current Configuration] + F[Membrane Hierarchy] + G[Object Tracking] + H[State Updates] + end + + subgraph "Execution Engine" + I[Step Controller] + J[Rule Applicator] + K[Conflict Resolver] + L[Termination Detector] + end + + subgraph "Optimization Layer" + M[Rule Caching] + N[Memory Pooling] + O[Parallel Execution] + P[Performance Monitoring] + end + + A --> D + B --> D + C --> D + D --> J + + E --> I + F --> I + G --> I + I --> H + + J --> K + K --> L + L --> I + + D --> M + I --> N + J --> O + L --> P + + style I fill:#f1f8e9 + style M fill:#fff3e0 +``` + +### Rule Selection Algorithm + +```mermaid +sequenceDiagram + participant Engine as Simulation Engine + participant Selector as Rule Selector + participant Membrane as Membrane State + participant Rules as Rule Set + participant Random as Random Generator + + Engine->>Selector: Start rule selection + Selector->>Membrane: Get current state + Membrane-->>Selector: Membrane configuration + + loop For each membrane + Selector->>Rules: Get applicable rules + Rules-->>Selector: Rule candidates + Selector->>Selector: Calculate max applications + Selector->>Random: Apply randomization + Random-->>Selector: Final applications + Selector->>Membrane: Update virtual state + end + + Selector-->>Engine: Selected rules + Engine->>Engine: Execute selected rules +``` + +### Memory Management in Simulation + +```mermaid +graph LR + subgraph "Object Pool" + A[Free Objects] + B[Active Objects] + C[Recycled Objects] + end + + subgraph "Membrane Pool" + D[Available Membranes] + E[Active Membranes] + F[Dissolved Membranes] + end + + subgraph "Configuration Pool" + G[Configuration Cache] + H[State Snapshots] + I[Rollback Points] + end + + A --> B + B --> C + C --> A + + D --> E + E --> F + F --> D + + G --> H + H --> I + I --> G + + B --> E + E --> H + + style A fill:#e0f2f1 + style D fill:#f3e5f5 + style G fill:#e8eaf6 +``` + +## Code Generator Architecture + +The code generator transforms P-system models into efficient C++ implementations. + +### Generation Pipeline + +```mermaid +flowchart TD + A[P-System Model] --> B[Analysis Phase] + B --> C[Template Selection] + B --> D[Symbol Mapping] + B --> E[Optimization Analysis] + + C --> F[Header Template] + C --> G[Implementation Template] + D --> H[Name Generation] + D --> I[Type Mapping] + E --> J[Loop Unrolling] + E --> K[Inline Expansion] + + F --> L[Header Code] + G --> M[Implementation Code] + H --> M + I --> M + J --> M + K --> M + + L --> N[Final C++ Code] + M --> N + + style A fill:#e1f5fe + style N fill:#e8f5e8 +``` + +### Code Templates and Patterns + +```mermaid +graph TB + subgraph "Template Categories" + A[Rule Templates] + B[Membrane Templates] + C[Object Templates] + D[Utility Templates] + end + + subgraph "Generation Strategies" + E[Direct Translation] + F[Loop Generation] + G[Table-driven] + H[State Machine] + end + + subgraph "Optimization Passes" + I[Dead Code Elimination] + J[Constant Folding] + K[Loop Optimization] + L[Inlining] + end + + A --> E + A --> F + B --> G + C --> H + + E --> I + F --> J + G --> K + H --> L + + style A fill:#e3f2fd + style E fill:#f1f8e9 + style I fill:#fff3e0 +``` + +## Data Serialization Architecture + +The serialization system provides persistent storage and exchange of P-system models and configurations. + +### Serialization Framework + +```mermaid +classDiagram + class Serializable { + <> + +save(archive) + +load(archive) + } + + class Psystem { + +model: String + +structure: Membrane + +rules: set~Rule~ + +serialize(archive) + } + + class Configuration { + +time: unsigned long + +environment: Multiset + +membranes: vector~CMembrane~ + +serialize(archive) + } + + class Value { + +type: Type + +value: union + +save(archive) + +load(archive) + } + + class Membrane { + +charge: char + +label: Label + +data: vector~Membrane~ + +serialize(archive) + } + + Serializable <|.. Psystem + Serializable <|.. Configuration + Serializable <|.. Value + Serializable <|.. Membrane +``` + +### Binary Format Structure + +```mermaid +graph LR + subgraph "File Header" + A[Magic Number] + B[Version Info] + C[Metadata] + end + + subgraph "Model Section" + D[P-System Model] + E[Rules Data] + F[Structure Data] + end + + subgraph "Configuration Section" + G[Initial Config] + H[Membrane States] + I[Object Counts] + end + + subgraph "Footer" + J[Checksums] + K[Index Table] + end + + A --> B + B --> C + C --> D + D --> E + E --> F + F --> G + G --> H + H --> I + I --> J + J --> K + + style A fill:#e3f2fd + style D fill:#f1f8e9 + style G fill:#fff3e0 + style J fill:#ffebee +``` + +## Inter-Component Communication + +### Message Passing Architecture + +```mermaid +sequenceDiagram + participant Parser + participant ModelBuilder + participant Simulator + participant Generator + participant FileManager + + Parser->>ModelBuilder: AST data + ModelBuilder->>Parser: Validation results + Parser->>FileManager: Save model + + FileManager->>Simulator: Load model + Simulator->>Simulator: Execute simulation + Simulator->>FileManager: Save configuration + + FileManager->>Generator: Load model + Generator->>Generator: Generate code + Generator->>FileManager: Save generated code +``` + +### Event System + +```mermaid +graph TD + subgraph "Event Sources" + A[Parser Events] + B[Simulation Events] + C[Error Events] + D[I/O Events] + end + + subgraph "Event Bus" + E[Event Dispatcher] + F[Event Queue] + G[Event Router] + end + + subgraph "Event Handlers" + H[Log Handler] + I[UI Handler] + J[Monitoring Handler] + K[Debug Handler] + end + + A --> E + B --> E + C --> E + D --> E + + E --> F + F --> G + + G --> H + G --> I + G --> J + G --> K + + style E fill:#f1f8e9 + style H fill:#e3f2fd +``` + +## Thread Safety and Concurrency + +### Concurrent Execution Model + +```mermaid +graph TB + subgraph "Main Thread" + A[Command Processing] + B[UI Management] + C[Result Collection] + end + + subgraph "Parser Thread Pool" + D[File Parser 1] + E[File Parser 2] + F[File Parser N] + end + + subgraph "Simulation Thread Pool" + G[Simulator 1] + H[Simulator 2] + I[Simulator N] + end + + subgraph "I/O Thread Pool" + J[File Reader] + K[File Writer] + L[Network Handler] + end + + A --> D + A --> E + A --> F + + A --> G + A --> H + A --> I + + A --> J + A --> K + A --> L + + D --> C + E --> C + F --> C + G --> C + H --> C + I --> C + + style A fill:#f1f8e9 + style C fill:#e8f5e8 +``` + +### Synchronization Mechanisms + +```mermaid +graph LR + subgraph "Synchronization Primitives" + A[Mutexes] + B[Condition Variables] + C[Atomic Operations] + D[Read-Write Locks] + end + + subgraph "High-Level Constructs" + E[Thread-Safe Containers] + F[Producer-Consumer Queues] + G[Barrier Synchronization] + H[Future/Promise] + end + + subgraph "Lock-Free Structures" + I[Lock-Free Stack] + J[Lock-Free Queue] + K[Atomic Counters] + L[Memory Pools] + end + + A --> E + B --> F + C --> I + D --> G + + E --> H + F --> H + G --> H + + I --> J + J --> K + K --> L + + style A fill:#e3f2fd + style E fill:#f1f8e9 + style I fill:#fff3e0 +``` + +This deep dive into P-Lingua's component architecture reveals the sophisticated design patterns and engineering decisions that make the framework both powerful and maintainable. Each component is designed with clear responsibilities and well-defined interfaces, enabling extensibility and optimization. \ No newline at end of file diff --git a/docs/EXAMPLES.md b/docs/EXAMPLES.md new file mode 100644 index 0000000..14c0a81 --- /dev/null +++ b/docs/EXAMPLES.md @@ -0,0 +1,558 @@ +# P-Lingua Usage and Examples + +## Introduction + +This document demonstrates the practical usage of P-Lingua through detailed examples, showing how the architectural components work together to process membrane computing models. + +## Basic Workflow + +```mermaid +graph LR + A[Write P-Lingua Code] --> B[Parse with plingua] + B --> C[Generate Binary Model] + C --> D[Simulate with psim] + D --> E[Analyze Results] + + subgraph "File Types" + F[.pli - Source files] + G[.psb - Binary models] + H[.psc - Configurations] + I[.cpp - Generated code] + end + + A --> F + C --> G + D --> H + B --> I + + style A fill:#e3f2fd + style D fill:#f1f8e9 + style E fill:#e8f5e8 +``` + +## Example 1: Simple Membrane System + +### P-Lingua Source Code + +```plingua +@model + +def main() { + // Define a simple membrane with objects + @mu = [a{3}, b{2}]'1; + + // Evolution rules + [a --> b]'1; + [b --> c]'1; + [c --> @d]'1; // dissolution +} +``` + +### Parsing Process Flow + +```mermaid +sequenceDiagram + participant Source as P-Lingua Source + participant Lexer as Lexical Analyzer + participant Parser as Parser + participant Semantic as Semantic Analyzer + participant Model as P-System Model + + Source->>Lexer: @model... + Lexer->>Parser: TOKEN_MODEL, TOKEN_IDENTIFIER... + Parser->>Semantic: AST nodes + Note over Semantic: Validates membrane structure + Note over Semantic: Checks rule consistency + Semantic->>Model: Validated P-System + Model-->>Source: Success/Error +``` + +### Generated Internal Representation + +```mermaid +graph TD + subgraph "P-System Model" + A[Model: transition] + B[Initial Structure] + C[Rules Set] + D[Semantics] + end + + subgraph "Membrane Structure" + E[Membrane '1'] + F[Objects: a{3}, b{2}] + G[Charge: neutral] + end + + subgraph "Evolution Rules" + H[Rule 1: a → b] + I[Rule 2: b → c] + J[Rule 3: c → @d] + end + + A --> B + A --> C + A --> D + + B --> E + E --> F + E --> G + + C --> H + C --> I + C --> J + + style A fill:#e3f2fd + style E fill:#f1f8e9 + style H fill:#fff3e0 +``` + +## Example 2: Complex Membrane Division + +### P-Lingua Source Code + +```plingua +@model + +def division_example() { + // Membrane with division rules + @mu = [a{5}, trigger]'1; + + // Division rule: one membrane becomes two + [trigger [ ]'1 --> [result1]'1 [result2]'1]; + + // Object evolution within membranes + [a --> b]'1; + [b --> c]'1; +} +``` + +### Division Process Visualization + +```mermaid +stateDiagram-v2 + state "Initial Configuration" as Init { + [*] --> Membrane1 + Membrane1 : Label: 1 + Membrane1 : Objects: a{5}, trigger + } + + state "After Division" as Divided { + [*] --> Membrane1_copy1 + [*] --> Membrane1_copy2 + Membrane1_copy1 : Label: 1 + Membrane1_copy1 : Objects: result1, a{5} + Membrane1_copy2 : Label: 1 + Membrane1_copy2 : Objects: result2, a{5} + } + + Init --> Divided : Division rule applied + + state "Evolution Continues" as Evolution { + [*] --> Membrane1_evolved1 + [*] --> Membrane1_evolved2 + Membrane1_evolved1 : Objects: result1, b{n}, c{m} + Membrane1_evolved2 : Objects: result2, b{p}, c{q} + } + + Divided --> Evolution : Object evolution rules +``` + +### Simulation Step Details + +```mermaid +sequenceDiagram + participant Simulator + participant RuleSelector + participant Configuration + participant Membrane1 + participant NewMembrane + + Simulator->>RuleSelector: Select applicable rules + RuleSelector->>Configuration: Check current state + Configuration->>Membrane1: Get membrane state + Membrane1-->>Configuration: {trigger, a{5}} + + RuleSelector->>RuleSelector: Find division rule + RuleSelector-->>Simulator: Division rule applicable + + Simulator->>Configuration: Apply division + Configuration->>NewMembrane: Create new membrane + Configuration->>Membrane1: Update original + Configuration->>Configuration: Update parent references + + Note over Configuration: Membrane division complete + Simulator->>Simulator: Continue with next step +``` + +## Example 3: Pattern Matching and Variables + +### P-Lingua Source Code + +```plingua +@model + +def pattern_example(n) { + // Parameterized membrane structure + @mu = [ ]'1; + @ms(1) += obj{i} : 1 <= i <= n; + + // Pattern-based rules with variables + [obj{x}, obj{y} --> result{x+y}]'1 : x < y; + [result{z} --> final{z}]'1 : z > 10; +} +``` + +### Pattern Resolution Process + +```mermaid +flowchart TD + A[Rule Pattern] --> B[Variable Extraction] + B --> C[Constraint Analysis] + C --> D[Object Matching] + D --> E[Substitution] + E --> F[Rule Instance] + + subgraph "Pattern Components" + G[Variables: x, y, z] + H[Constraints: x < y, z > 10] + I[Objects: obj{x}, obj{y}] + J[Products: result{x+y}] + end + + B --> G + C --> H + D --> I + E --> J + + style A fill:#e3f2fd + style F fill:#e8f5e8 +``` + +### Variable Binding Example + +```mermaid +graph TB + subgraph "Available Objects" + A[obj{1}] + B[obj{2}] + C[obj{3}] + D[obj{5}] + end + + subgraph "Valid Bindings" + E[x=1, y=2 → result{3}] + F[x=1, y=3 → result{4}] + G[x=1, y=5 → result{6}] + H[x=2, y=3 → result{5}] + I[x=2, y=5 → result{7}] + J[x=3, y=5 → result{8}] + end + + subgraph "Constraint Check" + K[x < y: satisfied] + L[Generate rule instances] + end + + A --> E + A --> F + A --> G + B --> H + B --> I + C --> J + + E --> K + F --> K + G --> K + H --> K + I --> K + J --> K + + K --> L + + style A fill:#e3f2fd + style E fill:#f1f8e9 + style K fill:#e8f5e8 +``` + +## Example 4: Multi-Environment System + +### P-Lingua Source Code + +```plingua +@model + +def multi_env_system() { + // Multiple environments with communication + @mu = [ env1 ]'E1 [ env2 ]'E2; + + @ms(E1) += signal{1}; + @ms(E2) += receptor{1}; + + // Cross-environment communication + signal{x} [ ]'E1 <--> [ message{x} ]'E2; + + // Local evolution in each environment + [receptor{y}, message{z} --> activated{y+z}]'E2; +} +``` + +### Multi-Environment Architecture + +```mermaid +graph TB + subgraph "Environment E1" + A[signal{1}] + B[Local Rules] + C[Communication Port] + end + + subgraph "Environment E2" + D[receptor{1}] + E[Local Rules] + F[Communication Port] + end + + subgraph "Communication Channel" + G[Message Queue] + H[Protocol Handler] + I[Synchronization] + end + + C <--> G + F <--> G + G --> H + H --> I + + A --> B + D --> E + + style A fill:#e3f2fd + style D fill:#f1f8e9 + style G fill:#fff3e0 +``` + +## Build and Execution Process + +### Compilation Workflow + +```mermaid +graph LR + A[P-Lingua Source] --> B[plingua compiler] + B --> C[Binary Model File] + C --> D[psim simulator] + D --> E[Results/Output] + + subgraph "Compiler Stages" + F[Lexical Analysis] + G[Syntax Analysis] + H[Semantic Analysis] + I[Code Generation] + end + + subgraph "Simulator Stages" + J[Model Loading] + K[Initial Configuration] + L[Rule Application] + M[Termination Check] + end + + B --> F + F --> G + G --> H + H --> I + + D --> J + J --> K + K --> L + L --> M + + style B fill:#e3f2fd + style D fill:#f1f8e9 +``` + +### Command Line Usage + +```bash +# Compile P-Lingua source to binary model +./bin/plingua -i examples/graph.pli -o models/graph.psb + +# Simulate the model +./bin/psim -i models/graph.psb -s 100 -v 2 + +# Generate C++ code +./bin/plingua -i examples/graph.pli -o generated/graph.cpp -f cpp +``` + +### Performance Monitoring + +```mermaid +graph TD + subgraph "Execution Metrics" + A[Parse Time] + B[Memory Usage] + C[Rule Applications] + D[Step Count] + end + + subgraph "Performance Counters" + E[Object Operations] + F[Membrane Operations] + G[Pattern Matches] + H[Rule Conflicts] + end + + subgraph "Output Formats" + I[Console Stats] + J[Log Files] + K[CSV Reports] + L[JSON Metrics] + end + + A --> I + B --> J + C --> K + D --> L + + E --> I + F --> J + G --> K + H --> L + + style A fill:#e3f2fd + style E fill:#f1f8e9 + style I fill:#e8f5e8 +``` + +## Error Handling Examples + +### Common Parsing Errors + +```mermaid +graph LR + subgraph "Syntax Errors" + A[Missing Semicolon] + B[Unmatched Brackets] + C[Invalid Identifiers] + end + + subgraph "Semantic Errors" + D[Undefined Variables] + E[Type Mismatches] + F[Invalid Rule Patterns] + end + + subgraph "Error Recovery" + G[Error Location] + H[Suggested Fixes] + I[Continue Parsing] + end + + A --> G + B --> G + C --> G + D --> G + E --> G + F --> G + + G --> H + H --> I + + style A fill:#ffebee + style G fill:#fff3e0 + style I fill:#e8f5e8 +``` + +### Runtime Error Handling + +```mermaid +sequenceDiagram + participant Simulator + participant ErrorHandler + participant Logger + participant Recovery + + Simulator->>Simulator: Execute rule + Note over Simulator: Division by zero detected + + Simulator->>ErrorHandler: Report error + ErrorHandler->>Logger: Log error details + ErrorHandler->>Recovery: Attempt recovery + + alt Recovery Successful + Recovery-->>Simulator: Continue execution + else Recovery Failed + Recovery-->>Simulator: Terminate with error + end + + Logger->>Logger: Write error report +``` + +## Integration Examples + +### Using P-Lingua in C++ Applications + +```cpp +#include +#include + +int main() { + // Load P-system model + plingua::File file; + loadFromFile("model.psb", file); + + // Create simulator + plingua::simulator::Simulator sim; + + // Run simulation + while (sim.ok()) { + sim.step(); + + // Access current configuration + auto config = sim.getCurrentConfiguration(); + + // Process results... + } + + return 0; +} +``` + +### Integration Architecture + +```mermaid +graph TB + subgraph "Host Application" + A[Main Program] + B[P-Lingua Interface] + C[Result Processor] + end + + subgraph "P-Lingua Library" + D[Parser API] + E[Simulator API] + F[Serialization API] + end + + subgraph "External Tools" + G[Visualization Tools] + H[Analysis Tools] + I[Debugging Tools] + end + + A --> B + B --> D + B --> E + B --> F + B --> C + + C --> G + C --> H + C --> I + + style A fill:#e3f2fd + style D fill:#f1f8e9 + style G fill:#fff3e0 +``` + +This documentation demonstrates how P-Lingua's architecture supports various usage patterns, from simple membrane systems to complex multi-environment models with pattern matching and variable binding. The framework's design enables both interactive exploration and programmatic integration. \ No newline at end of file diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..3bc826e --- /dev/null +++ b/docs/README.md @@ -0,0 +1,409 @@ +# P-Lingua Documentation Index + +## Welcome to P-Lingua Architecture Documentation + +This comprehensive documentation suite provides detailed insights into the P-Lingua framework for membrane computing, featuring architectural diagrams, component analysis, and practical examples. + +## Documentation Structure + +```mermaid +graph TD + A[Documentation Root] --> B[Architecture Overview] + A --> C[Component Deep Dive] + A --> D[Usage Examples] + A --> E[API Reference] + + B --> F[System Architecture] + B --> G[Data Flow Diagrams] + B --> H[Module Interactions] + + C --> I[Parser Components] + C --> J[Simulator Engine] + C --> K[Code Generator] + C --> L[Serialization System] + + D --> M[Basic Examples] + D --> N[Advanced Patterns] + D --> O[Integration Guides] + D --> P[Performance Analysis] + + E --> Q[Parser API] + E --> R[Simulator API] + E --> S[Generator API] + E --> T[Utility Functions] + + style A fill:#e3f2fd + style B fill:#f1f8e9 + style C fill:#fff3e0 + style D fill:#e8f5e8 + style E fill:#f3e5f5 +``` + +## Quick Navigation + +### 📐 [Architecture Overview](ARCHITECTURE.md) +Comprehensive system-level view of P-Lingua's design patterns and architectural decisions. + +**Key Diagrams:** +- High-level system architecture +- Core data structures +- Module interaction patterns +- Data flow and execution models +- Memory management strategies + +### 🔧 [Component Deep Dive](COMPONENTS.md) +Detailed analysis of individual components and their internal architectures. + +**Covered Components:** +- Parser component with lexical/semantic analysis +- Simulator engine with rule selection algorithms +- Code generator with template systems +- Serialization framework with binary formats +- Inter-component communication patterns + +### 💡 [Usage Examples](EXAMPLES.md) +Practical demonstrations of P-Lingua features through working examples. + +**Example Categories:** +- Basic membrane systems +- Complex division patterns +- Pattern matching with variables +- Multi-environment communication +- Error handling scenarios + +## Architecture Highlights + +### Modular Design Philosophy + +```mermaid +graph LR + subgraph "Core Principles" + A[Separation of Concerns] + B[Single Responsibility] + C[Interface Segregation] + D[Dependency Inversion] + end + + subgraph "Implementation Benefits" + E[Testability] + F[Maintainability] + G[Extensibility] + H[Performance] + end + + A --> E + B --> F + C --> G + D --> H + + style A fill:#e3f2fd + style E fill:#e8f5e8 +``` + +### Key Architectural Patterns + +#### 1. **Parser Pattern** +- Lexical analysis with Flex +- Syntactic analysis with Bison +- Abstract syntax tree construction +- Semantic validation pipeline + +#### 2. **Simulation Engine Pattern** +- Rule-based execution model +- Configuration state management +- Conflict resolution strategies +- Performance optimization + +#### 3. **Code Generation Pattern** +- Template-driven generation +- Symbol table management +- Optimization pass framework +- Target-specific backends + +#### 4. **Serialization Pattern** +- Binary format efficiency +- Version compatibility +- Cross-platform support +- Incremental loading + +## Component Interaction Map + +```mermaid +graph TB + subgraph "Input Processing" + A[Source Files] + B[Command Line] + C[Configuration Files] + end + + subgraph "Core Processing" + D[Parser Engine] + E[Model Builder] + F[Validator] + G[Optimizer] + end + + subgraph "Execution Engines" + H[Simulator] + I[Code Generator] + J[Analyzer] + end + + subgraph "Output Generation" + K[Binary Models] + L[Generated Code] + M[Reports] + N[Visualizations] + end + + A --> D + B --> D + C --> D + + D --> E + E --> F + F --> G + + G --> H + G --> I + G --> J + + H --> K + H --> M + I --> L + J --> N + + style D fill:#e3f2fd + style H fill:#f1f8e9 + style K fill:#e8f5e8 +``` + +## Performance Characteristics + +### Computational Complexity + +```mermaid +graph TD + subgraph "Parsing Complexity" + A[Lexical: O(n)] + B[Syntactic: O(n³)] + C[Semantic: O(n·m)] + end + + subgraph "Simulation Complexity" + D[Rule Selection: O(r·m)] + E[Rule Application: O(a·c)] + F[State Update: O(m·o)] + end + + subgraph "Generation Complexity" + G[Template Processing: O(t·s)] + H[Optimization: O(n²)] + I[Code Emission: O(n)] + end + + A --> D + B --> E + C --> F + + D --> G + E --> H + F --> I + + style A fill:#e3f2fd + style D fill:#f1f8e9 + style G fill:#fff3e0 +``` + +Where: +- `n` = source code size +- `m` = number of membranes +- `r` = number of rules +- `a` = rule applications +- `c` = configuration complexity +- `o` = number of objects +- `t` = template size +- `s` = symbol count + +## Memory Usage Patterns + +### Memory Allocation Strategy + +```mermaid +pie title Memory Distribution + "Parser Data Structures" : 25 + "P-System Models" : 35 + "Simulation State" : 30 + "Code Generation" : 10 +``` + +### Memory Management Features + +- **Object Pooling**: Reduces allocation overhead +- **String Interning**: Minimizes memory duplication +- **Lazy Loading**: Defers expensive operations +- **Reference Counting**: Manages object lifetimes +- **Memory Mapping**: Efficient file I/O + +## Threading and Concurrency + +### Concurrency Model + +```mermaid +graph LR + subgraph "Thread-Safe Components" + A[Parser Pool] + B[Simulator Pool] + C[I/O Pool] + end + + subgraph "Synchronization" + D[Mutex Guards] + E[Atomic Operations] + F[Lock-Free Queues] + end + + subgraph "Parallel Execution" + G[Rule Evaluation] + H[Pattern Matching] + I[Code Generation] + end + + A --> D + B --> E + C --> F + + D --> G + E --> H + F --> I + + style A fill:#e3f2fd + style D fill:#f1f8e9 + style G fill:#e8f5e8 +``` + +## Error Handling Philosophy + +### Error Categories and Recovery + +```mermaid +graph TD + subgraph "Error Types" + A[Lexical Errors] + B[Syntax Errors] + C[Semantic Errors] + D[Runtime Errors] + end + + subgraph "Recovery Strategies" + E[Skip and Continue] + F[Insert Missing Tokens] + G[Rollback State] + H[Graceful Degradation] + end + + subgraph "Error Reporting" + I[Location Information] + J[Contextual Messages] + K[Suggested Fixes] + L[Error Codes] + end + + A --> E + B --> F + C --> G + D --> H + + E --> I + F --> J + G --> K + H --> L + + style A fill:#ffebee + style E fill:#fff3e0 + style I fill:#f3e5f5 +``` + +## Extension Points + +### Customization Opportunities + +1. **Custom Models**: Define new computational models +2. **Rule Patterns**: Add domain-specific rule types +3. **Output Formats**: Support additional target languages +4. **Optimization Passes**: Implement custom optimizations +5. **Visualization**: Create custom diagram generators + +### Plugin Architecture + +```mermaid +graph TB + subgraph "Core Framework" + A[Base Classes] + B[Interface Definitions] + C[Registry System] + end + + subgraph "Plugin Types" + D[Model Plugins] + E[Format Plugins] + F[Optimizer Plugins] + G[Visualizer Plugins] + end + + subgraph "Plugin Management" + H[Dynamic Loading] + I[Dependency Resolution] + J[Version Compatibility] + end + + A --> D + B --> E + C --> F + C --> G + + D --> H + E --> I + F --> J + G --> J + + style A fill:#e3f2fd + style D fill:#f1f8e9 + style H fill:#fff3e0 +``` + +## Getting Started + +### Prerequisites +- GCC 4.9.0 or higher +- Flex and Bison +- Boost libraries (filesystem, program_options) + +### Build Process +```bash +make grammar +make compiler +make simulator +sudo make install +``` + +### First Steps +1. Read the [Architecture Overview](ARCHITECTURE.md) +2. Explore [Component Details](COMPONENTS.md) +3. Try the [Usage Examples](EXAMPLES.md) +4. Build your first P-system model + +## Contributing + +This documentation is part of the living architecture of P-Lingua. Contributions, corrections, and enhancements are welcome. The diagrams use Mermaid syntax for maintainability and can be updated as the system evolves. + +### Documentation Standards +- Use Mermaid diagrams for all visualizations +- Maintain consistency in color schemes +- Include practical examples with explanations +- Update diagrams when architecture changes +- Cross-reference between documentation sections + +--- + +*This documentation represents the current state of P-Lingua's architecture and will be updated as the system evolves.* \ No newline at end of file