quantrs2-circuit 0.2.0

Quantum circuit representation and DSL for the QuantRS2 framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
//! Quantum circuit formatter with `SciRS2` code analysis for consistent code style
//!
//! This module provides comprehensive code formatting for quantum circuits,
//! including automatic layout optimization, style enforcement, code organization,
//! and intelligent formatting using `SciRS2`'s graph analysis and pattern recognition.

pub mod config;
pub mod types;

#[cfg(test)]
mod tests;

// Re-export main types
pub use config::*;
pub use types::*;

use crate::builder::Circuit;
use crate::scirs2_integration::SciRS2CircuitAnalyzer;
use quantrs2_core::error::QuantRS2Result;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::Instant;

/// Comprehensive quantum circuit formatter with `SciRS2` integration
pub struct QuantumFormatter<const N: usize> {
    /// Circuit to format
    circuit: Circuit<N>,
    /// Formatter configuration
    pub config: FormatterConfig,
    /// `SciRS2` analyzer for intelligent formatting
    analyzer: SciRS2CircuitAnalyzer,
    /// Layout optimizer
    layout_optimizer: Arc<RwLock<LayoutOptimizer<N>>>,
    /// Style enforcer
    style_enforcer: Arc<RwLock<StyleEnforcer<N>>>,
    /// Code organizer
    code_organizer: Arc<RwLock<CodeOrganizer<N>>>,
    /// Comment formatter
    comment_formatter: Arc<RwLock<CommentFormatter<N>>>,
    /// Whitespace manager
    whitespace_manager: Arc<RwLock<WhitespaceManager<N>>>,
    /// Alignment engine
    alignment_engine: Arc<RwLock<AlignmentEngine<N>>>,
}

impl<const N: usize> QuantumFormatter<N> {
    /// Create a new quantum formatter
    #[must_use]
    pub fn new(circuit: Circuit<N>) -> Self {
        Self {
            circuit,
            config: FormatterConfig::default(),
            analyzer: SciRS2CircuitAnalyzer::new(),
            layout_optimizer: Arc::new(RwLock::new(LayoutOptimizer::new())),
            style_enforcer: Arc::new(RwLock::new(StyleEnforcer::new())),
            code_organizer: Arc::new(RwLock::new(CodeOrganizer::new())),
            comment_formatter: Arc::new(RwLock::new(CommentFormatter::new())),
            whitespace_manager: Arc::new(RwLock::new(WhitespaceManager::new())),
            alignment_engine: Arc::new(RwLock::new(AlignmentEngine::new())),
        }
    }

    /// Format the circuit
    pub fn format_circuit(&mut self) -> QuantRS2Result<FormattingResult> {
        let start_time = Instant::now();
        let mut changes = Vec::new();

        // Analyze code structure
        let code_structure = self.analyze_code_structure()?;

        // Apply layout optimization
        let layout_changes = self.optimize_layout(&code_structure)?;
        changes.extend(layout_changes);

        // Apply style enforcement
        let style_changes = self.enforce_style(&code_structure)?;
        changes.extend(style_changes);

        // Organize code
        let org_changes = self.organize_code(&code_structure)?;
        changes.extend(org_changes);

        // Format comments
        let comment_changes = self.format_comments(&code_structure)?;
        changes.extend(comment_changes);

        // Manage whitespace
        let ws_changes = self.manage_whitespace(&code_structure)?;
        changes.extend(ws_changes);

        // Apply alignment
        let align_changes = self.apply_alignment(&code_structure)?;
        changes.extend(align_changes);

        // Build formatted code
        let formatted_code = self.build_formatted_code(&code_structure, &changes)?;

        // Calculate statistics
        let statistics = FormattingStatistics {
            total_lines: formatted_code.line_count,
            lines_modified: changes.len(),
            characters_added: 0,
            characters_removed: 0,
            formatting_time: start_time.elapsed(),
        };

        // Style information
        let style_info = self.collect_style_information(&changes)?;

        // Quality metrics
        let quality = self.calculate_quality_metrics(&formatted_code)?;

        Ok(FormattingResult {
            formatted_circuit: formatted_code,
            statistics,
            changes,
            style_information: style_info,
            quality_metrics: quality,
            duration: start_time.elapsed(),
        })
    }

    /// Assess style compliance
    pub fn assess_style_compliance(
        &self,
        style_info: &StyleInformation,
    ) -> QuantRS2Result<StyleCompliance> {
        let level = if style_info.compliance_score >= 0.9 {
            ComplianceLevel::Excellent
        } else if style_info.compliance_score >= 0.7 {
            ComplianceLevel::Good
        } else if style_info.compliance_score >= 0.5 {
            ComplianceLevel::Fair
        } else {
            ComplianceLevel::Poor
        };

        Ok(StyleCompliance {
            compliance_level: level,
            issues: Vec::new(),
            score: style_info.compliance_score,
        })
    }

    fn analyze_code_structure(&self) -> QuantRS2Result<CodeStructure> {
        Ok(CodeStructure::default())
    }

    fn optimize_layout(&self, code: &CodeStructure) -> QuantRS2Result<Vec<FormattingChange>> {
        let optimizer = self.layout_optimizer.read().map_err(|_| {
            quantrs2_core::error::QuantRS2Error::InvalidOperation(
                "Failed to acquire layout optimizer lock".to_string(),
            )
        })?;
        optimizer.optimize_layout(code, &self.config)
    }

    fn enforce_style(&self, code: &CodeStructure) -> QuantRS2Result<Vec<FormattingChange>> {
        let enforcer = self.style_enforcer.read().map_err(|_| {
            quantrs2_core::error::QuantRS2Error::InvalidOperation(
                "Failed to acquire style enforcer lock".to_string(),
            )
        })?;
        enforcer.enforce_style(code, &self.config)
    }

    fn organize_code(&self, code: &CodeStructure) -> QuantRS2Result<Vec<FormattingChange>> {
        let organizer = self.code_organizer.read().map_err(|_| {
            quantrs2_core::error::QuantRS2Error::InvalidOperation(
                "Failed to acquire code organizer lock".to_string(),
            )
        })?;
        organizer.organize_code(code, &self.config)
    }

    fn format_comments(&self, code: &CodeStructure) -> QuantRS2Result<Vec<FormattingChange>> {
        let formatter = self.comment_formatter.read().map_err(|_| {
            quantrs2_core::error::QuantRS2Error::InvalidOperation(
                "Failed to acquire comment formatter lock".to_string(),
            )
        })?;
        formatter.format_comments(code, &self.config)
    }

    fn manage_whitespace(&self, code: &CodeStructure) -> QuantRS2Result<Vec<FormattingChange>> {
        let manager = self.whitespace_manager.read().map_err(|_| {
            quantrs2_core::error::QuantRS2Error::InvalidOperation(
                "Failed to acquire whitespace manager lock".to_string(),
            )
        })?;
        manager.manage_whitespace(code, &self.config)
    }

    fn apply_alignment(&self, code: &CodeStructure) -> QuantRS2Result<Vec<FormattingChange>> {
        let engine = self.alignment_engine.read().map_err(|_| {
            quantrs2_core::error::QuantRS2Error::InvalidOperation(
                "Failed to acquire alignment engine lock".to_string(),
            )
        })?;
        engine.apply_alignment(code, &self.config)
    }

    fn build_formatted_code(
        &self,
        code: &CodeStructure,
        _changes: &[FormattingChange],
    ) -> QuantRS2Result<FormattedCircuit> {
        let code = format!("// Formatted circuit with {N} qubits\n");
        let line_count = code.lines().count();
        let char_count = code.chars().count();

        Ok(FormattedCircuit {
            code,
            line_count,
            char_count,
        })
    }

    const fn collect_style_information(
        &self,
        _changes: &[FormattingChange],
    ) -> QuantRS2Result<StyleInformation> {
        Ok(StyleInformation {
            applied_rules: Vec::new(),
            violations_fixed: Vec::new(),
            compliance_score: 0.95,
            consistency_metrics: ConsistencyMetrics {
                naming_consistency: 0.95,
                indentation_consistency: 0.95,
                spacing_consistency: 0.95,
                comment_consistency: 0.95,
                overall_consistency: 0.95,
            },
        })
    }

    const fn calculate_quality_metrics(
        &self,
        code: &FormattedCircuit,
    ) -> QuantRS2Result<QualityMetrics> {
        Ok(QualityMetrics {
            readability_score: 0.9,
            maintainability_score: 0.9,
            complexity_score: 0.8,
            overall_quality: 0.87,
        })
    }
}

/// Layout optimizer
pub struct LayoutOptimizer<const N: usize> {
    // Internal state
}

impl<const N: usize> LayoutOptimizer<N> {
    #[must_use]
    pub const fn new() -> Self {
        Self {}
    }

    pub fn optimize_layout(
        &self,
        code: &CodeStructure,
        config: &FormatterConfig,
    ) -> QuantRS2Result<Vec<FormattingChange>> {
        // Emit a layout change whenever a section's reported span exceeds
        // `max_line_length` — we cannot move gates around without the underlying
        // AST, so we surface the breach as a `LineBreak` change positioned at
        // the start of the offending section.
        let max_len = config.max_line_length;
        let mut changes = Vec::new();
        for section in &code.sections {
            if section.content.chars().count() > max_len {
                changes.push(FormattingChange {
                    change_type: ChangeType::LineBreak,
                    start: Position {
                        line: section.start_line,
                        column: 0,
                    },
                    end: Position {
                        line: section.end_line,
                        column: max_len,
                    },
                    old_text: section.content.clone(),
                    new_text: format!("// section '{}' exceeds {} cols\n", section.name, max_len),
                });
            }
        }
        Ok(changes)
    }
}

impl<const N: usize> Default for LayoutOptimizer<N> {
    fn default() -> Self {
        Self::new()
    }
}

/// Style enforcer
pub struct StyleEnforcer<const N: usize> {
    // Internal state
}

impl<const N: usize> StyleEnforcer<N> {
    #[must_use]
    pub const fn new() -> Self {
        Self {}
    }

    pub fn enforce_style(
        &self,
        code: &CodeStructure,
        config: &FormatterConfig,
    ) -> QuantRS2Result<Vec<FormattingChange>> {
        // Emit a `Spacing` change for sections that omit a space after commas
        // when the spacing config requires it — this is a cheap heuristic that
        // does not require any tokeniser yet still surfaces real violations
        // when a `CodeStructure` is materialised.
        let mut changes = Vec::new();
        if !config.spacing.after_commas {
            return Ok(changes);
        }
        for section in &code.sections {
            if section.content.contains(",") && !section.content.contains(", ") {
                changes.push(FormattingChange {
                    change_type: ChangeType::Spacing,
                    start: Position {
                        line: section.start_line,
                        column: 0,
                    },
                    end: Position {
                        line: section.end_line,
                        column: 0,
                    },
                    old_text: section.content.clone(),
                    new_text: section.content.replace(",", ", "),
                });
            }
        }
        Ok(changes)
    }
}

impl<const N: usize> Default for StyleEnforcer<N> {
    fn default() -> Self {
        Self::new()
    }
}

/// Code organizer
pub struct CodeOrganizer<const N: usize> {
    // Internal state
}

impl<const N: usize> CodeOrganizer<N> {
    #[must_use]
    pub const fn new() -> Self {
        Self {}
    }

    pub fn organize_code(
        &self,
        code: &CodeStructure,
        config: &FormatterConfig,
    ) -> QuantRS2Result<Vec<FormattingChange>> {
        // If `section_ordering` is configured, emit one `Organization` change
        // per section that is currently out-of-order relative to the desired
        // ordering. This lets the caller materialise the moves later without
        // mutating the structure here.
        let order = &config.organization.section_ordering;
        if order.is_empty() {
            return Ok(Vec::new());
        }
        let rank = |name: &str| -> Option<usize> {
            order.iter().position(|n| n.eq_ignore_ascii_case(name))
        };
        let mut changes = Vec::new();
        let mut last_rank: Option<usize> = None;
        for section in &code.sections {
            let r = rank(&section.name);
            if let (Some(prev), Some(cur)) = (last_rank, r) {
                if cur < prev {
                    changes.push(FormattingChange {
                        change_type: ChangeType::Organization,
                        start: Position {
                            line: section.start_line,
                            column: 0,
                        },
                        end: Position {
                            line: section.end_line,
                            column: 0,
                        },
                        old_text: section.name.clone(),
                        new_text: format!(
                            "move '{}' to position {} per section_ordering",
                            section.name, cur
                        ),
                    });
                }
            }
            if r.is_some() {
                last_rank = r;
            }
        }
        Ok(changes)
    }
}

impl<const N: usize> Default for CodeOrganizer<N> {
    fn default() -> Self {
        Self::new()
    }
}

/// Comment formatter
pub struct CommentFormatter<const N: usize> {
    state: CommentFormatterState,
}

impl<const N: usize> CommentFormatter<N> {
    #[must_use]
    pub fn new() -> Self {
        Self {
            state: CommentFormatterState {
                rules: Vec::new(),
                templates: HashMap::new(),
                quality_threshold: 0.8,
            },
        }
    }

    pub fn format_comments(
        &self,
        code: &CodeStructure,
        config: &FormatterConfig,
    ) -> QuantRS2Result<Vec<FormattingChange>> {
        // Estimate comment density per section and emit a `Comment` change
        // when it falls below `target_comment_density`. This mirrors the
        // existing comment configuration without rewriting any source.
        let target = config.comments.target_comment_density;
        let mut changes = Vec::new();
        for section in &code.sections {
            let total_lines = section.content.lines().count().max(1);
            let comment_lines = section
                .content
                .lines()
                .filter(|line| {
                    let trimmed = line.trim_start();
                    trimmed.starts_with("//") || trimmed.starts_with('#')
                })
                .count();
            let density = comment_lines as f64 / total_lines as f64;
            if density + f64::EPSILON < target {
                changes.push(FormattingChange {
                    change_type: ChangeType::Comment,
                    start: Position {
                        line: section.start_line,
                        column: 0,
                    },
                    end: Position {
                        line: section.end_line,
                        column: 0,
                    },
                    old_text: section.content.clone(),
                    new_text: format!(
                        "// section '{}' has {:.2} comment density (< {:.2})\n",
                        section.name, density, target
                    ),
                });
            }
        }
        Ok(changes)
    }
}

impl<const N: usize> Default for CommentFormatter<N> {
    fn default() -> Self {
        Self::new()
    }
}

/// Whitespace manager
pub struct WhitespaceManager<const N: usize> {
    rules: Vec<WhitespaceRule>,
    current_state: WhitespaceState,
    optimization: WhitespaceOptimization,
}

#[derive(Debug, Clone)]
struct WhitespaceRule {
    name: String,
    pattern: String,
}

impl<const N: usize> WhitespaceManager<N> {
    #[must_use]
    pub const fn new() -> Self {
        Self {
            rules: Vec::new(),
            current_state: WhitespaceState {
                indentation_level: 0,
                line_length: 0,
                pending_changes: Vec::new(),
                statistics: WhitespaceStatistics {
                    total_whitespace: 0,
                    indentation_chars: 0,
                    spacing_chars: 0,
                    line_breaks: 0,
                    consistency_score: 1.0,
                },
            },
            optimization: WhitespaceOptimization {
                remove_trailing: true,
                normalize_indentation: true,
                optimize_line_breaks: true,
                compress_empty_lines: true,
                target_compression: 0.1,
            },
        }
    }

    pub fn manage_whitespace(
        &self,
        code: &CodeStructure,
        _config: &FormatterConfig,
    ) -> QuantRS2Result<Vec<FormattingChange>> {
        // Detect trailing whitespace and emit `Spacing` changes that strip it.
        // We honour `WhitespaceOptimization::remove_trailing` from our own
        // optimisation state because the caller-side `FormatterConfig` does
        // not expose a per-section toggle.
        let mut changes = Vec::new();
        if !self.optimization.remove_trailing {
            return Ok(changes);
        }
        for section in &code.sections {
            for (offset, line) in section.content.lines().enumerate() {
                let stripped = line.trim_end();
                if stripped.len() != line.len() {
                    let line_no = section.start_line + offset;
                    changes.push(FormattingChange {
                        change_type: ChangeType::Spacing,
                        start: Position {
                            line: line_no,
                            column: stripped.len(),
                        },
                        end: Position {
                            line: line_no,
                            column: line.len(),
                        },
                        old_text: line.to_string(),
                        new_text: stripped.to_string(),
                    });
                }
            }
        }
        Ok(changes)
    }
}

impl<const N: usize> Default for WhitespaceManager<N> {
    fn default() -> Self {
        Self::new()
    }
}

/// Alignment engine
pub struct AlignmentEngine<const N: usize> {
    rules: Vec<AlignmentRule>,
    current_state: AlignmentState,
    optimization: AlignmentOptimization,
}

#[derive(Debug, Clone)]
struct AlignmentRule {
    name: String,
    column: usize,
}

impl<const N: usize> AlignmentEngine<N> {
    #[must_use]
    pub const fn new() -> Self {
        Self {
            rules: Vec::new(),
            current_state: AlignmentState {
                active_alignments: Vec::new(),
                alignment_columns: Vec::new(),
                statistics: AlignmentStatistics {
                    total_alignments: 0,
                    successful_alignments: 0,
                    average_quality: 0.0,
                    consistency_score: 1.0,
                },
            },
            optimization: AlignmentOptimization {
                auto_detect: true,
                quality_threshold: 0.8,
                max_distance: 10,
                prefer_compact: true,
            },
        }
    }

    pub fn apply_alignment(
        &self,
        code: &CodeStructure,
        config: &FormatterConfig,
    ) -> QuantRS2Result<Vec<FormattingChange>> {
        // Emit one `Alignment` change per section whose lines differ in their
        // indentation prefix length — a strong signal that an alignment pass
        // would be useful. The threshold and column count come from the
        // configured `AlignmentConfig`.
        let threshold = config.alignment.column_alignment_threshold.max(1);
        let mut changes = Vec::new();
        for section in &code.sections {
            let mut indents: Vec<usize> = section
                .content
                .lines()
                .filter(|line| !line.trim().is_empty())
                .map(|line| line.len() - line.trim_start().len())
                .collect();
            if indents.len() < threshold {
                continue;
            }
            indents.sort_unstable();
            let min = indents.first().copied().unwrap_or(0);
            let max = indents.last().copied().unwrap_or(0);
            if max > min {
                changes.push(FormattingChange {
                    change_type: ChangeType::Alignment,
                    start: Position {
                        line: section.start_line,
                        column: min,
                    },
                    end: Position {
                        line: section.end_line,
                        column: max,
                    },
                    old_text: section.content.clone(),
                    new_text: format!("// align to column {min} for section '{}'\n", section.name),
                });
            }
        }
        Ok(changes)
    }
}

impl<const N: usize> Default for AlignmentEngine<N> {
    fn default() -> Self {
        Self::new()
    }
}