libgrammstein 0.1.0

Hybrid language model (N-gram + Embeddings) for WFST text correction
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
# Semantic Corrector

The semantic corrector analyzes code semantics using Code Property Graphs (CPG) and Graph Neural Networks (GNN) to detect contextual issues like variable misuse, unused bindings, and type errors.

## Overview

The `SemanticCorrector` provides:

- **Variable misuse detection**: Wrong variable names in context
- **Unused binding detection**: Variables defined but never used
- **Type error detection**: Type mismatches (when type info available)
- **GNN-based scoring**: Neural network analysis of code patterns

## Architecture

```
┌──────────────────────────────────────────────────────────────────┐
│                    SemanticCorrector                             │
│                                                                  │
│  ┌────────────────────────────────────────────────────────────┐ │
│  │                  GnnSemanticScorer                          │ │
│  │                                                             │ │
│  │  • Feature extraction from CPG nodes                        │ │
│  │  • Message passing for pattern detection                    │ │
│  │  • Issue scoring and ranking                                │ │
│  └────────────────────────────────────────────────────────────┘ │
│                              │                                   │
│                              ▼                                   │
│  ┌────────────────────────────────────────────────────────────┐ │
│  │               CodePropertyGraph (CPG)                       │ │
│  │                                                             │ │
│  │  ┌─────────┐    ┌─────────┐    ┌─────────┐                 │ │
│  │  │   AST   │    │   CFG   │    │   DFG   │                 │ │
│  │  │         │    │         │    │         │                 │ │
│  │  │ Parent  │    │ Next    │    │ Read    │                 │ │
│  │  │ Child   │    │ Branch  │    │ Write   │                 │ │
│  │  │ Sibling │    │ Back    │    │ Flow    │                 │ │
│  │  └─────────┘    └─────────┘    └─────────┘                 │ │
│  └────────────────────────────────────────────────────────────┘ │
│                              │                                   │
│  ┌───────────────────────────┴────────────────────────────────┐ │
│  │              Known Variables / Functions                    │ │
│  │                                                             │ │
│  │  Variables: userCount(int), userName(string), ...           │ │
│  │  Functions: calculateTotal(2), processData(1), ...          │ │
│  └────────────────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────────────┘
```

## SemanticCorrectorConfig

Configuration options for the semantic corrector:

```rust
pub struct SemanticCorrectorConfig {
    /// Minimum confidence threshold for reporting (default: 0.5)
    pub min_confidence: f64,
    /// Maximum candidates per issue (default: 5)
    pub max_candidates: usize,
    /// Whether to check for variable misuse (default: true)
    pub check_variable_misuse: bool,
    /// Whether to check for unused bindings (default: true)
    pub check_unused_bindings: bool,
    /// Whether to check for type errors (default: true)
    pub check_type_errors: bool,
    /// GNN configuration
    pub gnn_config: GnnConfig,
}
```

### Configuration Parameters

| Parameter | Default | Description |
|-----------|---------|-------------|
| `min_confidence` | 0.5 | Threshold for reporting issues |
| `max_candidates` | 5 | Maximum suggestions per issue |
| `check_variable_misuse` | true | Enable variable misuse detection |
| `check_unused_bindings` | true | Enable unused variable detection |
| `check_type_errors` | true | Enable type mismatch detection |

## Creating a Semantic Corrector

### Basic Creation

```rust
use libgrammstein::code::{SemanticCorrector, SemanticCorrectorConfig, Python};
use std::sync::Arc;

let python = Arc::new(Python::new());

// With default configuration
let corrector = SemanticCorrector::with_defaults(python.clone());

// With custom configuration
let config = SemanticCorrectorConfig {
    min_confidence: 0.6,
    max_candidates: 10,
    check_variable_misuse: true,
    check_unused_bindings: true,
    check_type_errors: false,  // Disable type checking
    gnn_config: GnnConfig::default(),
};
let corrector = SemanticCorrector::new(python, config);
```

### Registering Project Context

Provide the corrector with knowledge of your project's symbols:

```rust
let mut corrector = SemanticCorrector::with_defaults(python);

// Register known variables with optional type information
corrector.register_variable(
    "userCount".to_string(),
    Some("int".to_string()),
    0,  // scope level
);
corrector.register_variable(
    "userName".to_string(),
    Some("string".to_string()),
    0,
);

// Register known functions with arity and return type
corrector.register_function(
    "calculateTotal".to_string(),
    2,  // arity (number of parameters)
    Some("float".to_string()),  // return type
);
```

## VariableInfo and FunctionInfo

### VariableInfo

Information about a known variable:

```rust
pub struct VariableInfo {
    /// Variable name
    pub name: String,
    /// Inferred or declared type (if known)
    pub type_name: Option<String>,
    /// Scope level where defined
    pub scope_level: usize,
    /// Number of times used
    pub use_count: usize,
}
```

### FunctionInfo

Information about a known function:

```rust
pub struct FunctionInfo {
    /// Function name
    pub name: String,
    /// Parameter types (if known)
    pub param_types: Vec<Option<String>>,
    /// Return type (if known)
    pub return_type: Option<String>,
    /// Number of parameters
    pub arity: usize,
}
```

## Analyzing Code Property Graphs

### Basic CPG Analysis

```rust
use libgrammstein::code::{CodeParser, CodePropertyGraph, Python};

let python = Arc::new(Python::new());
let mut parser = CodeParser::new(python.clone()).unwrap();
let corrector = SemanticCorrector::with_defaults(python);

let source = r#"
def calculate(x, y):
    result = x + y
    return resutl  # Typo: should be 'result'
"#;

let parsed = parser.parse(source).unwrap();
let cpg = CodePropertyGraph::from_parsed_code(&parsed);

// Analyze CPG for semantic issues
let issues = corrector.analyze_cpg(&cpg);

for issue in &issues {
    println!("Issue at node {}: {:?} (confidence: {:.2})",
        issue.node_idx, issue.issue_type, issue.confidence);
}
```

### Full Analysis with Corrections

```rust
// Get corrections from parsed code and CPG
let corrections = corrector.analyze_parsed(&parsed, &cpg);

for correction in &corrections {
    println!("{} → {} ({:?}, confidence: {:.2})",
        correction.original,
        correction.replacement,
        correction.kind,
        correction.confidence
    );
}
```

## Issue Types

The semantic corrector detects several issue types:

```rust
pub enum IssueType {
    VariableMisuse,        // Wrong variable in context
    UnusedBinding,         // Variable defined but never used
    TypeError,             // Type mismatch
    MissingErrorHandling,  // Unhandled error case
    // ... other types
}
```

### Variable Misuse

Detects when a variable name is likely wrong:

```rust
// Source: "return resutl" (should be "result")
// Issue: VariableMisuse at "resutl" node
// Suggestion: "result" based on data flow and name similarity
```

### Unused Binding

Detects variables that are defined but never read:

```rust
// Source:
// def foo():
//     unused = 42  # Never read
//     return 0

// Issue: UnusedBinding at "unused" definition
// Suggestion: Remove or use the variable
```

### Type Error

Detects type mismatches when type information is available:

```rust
// Source (with type annotations):
// def add(x: int, y: int) -> int:
//     return x + "hello"  # Type error

// Issue: TypeError at string literal
// Suggestion: Expected int
```

## Finding Variable Misuse

Find candidates for variable replacement:

```rust
// Find alternatives for a potentially misused variable
let candidates = corrector.find_variable_misuse(&cpg, "resutl", node_idx);

for (name, score) in &candidates {
    println!("  {} (score: {:.2})", name, score);
}
// Output:
//   result (score: 0.85)
//   results (score: 0.65)
```

## Name Similarity

The corrector uses Levenshtein distance for name similarity:

```rust
// Similarity calculation
fn name_similarity(a: &str, b: &str) -> f64 {
    if a == b { return 1.0; }
    let distance = levenshtein_distance(a, b);
    let max_len = a.len().max(b.len());
    1.0 - (distance as f64 / max_len as f64)
}

// Examples:
// "result" vs "resutl" → similarity ~0.83
// "count" vs "counter" → similarity ~0.71
// "foo" vs "bar" → similarity ~0.0
```

## Token-Level Correction

The semantic corrector can also correct individual tokens:

```rust
use libgrammstein::code::{CodeToken, TokenContext, TokenType, CodeCorrector};

let mut corrector = SemanticCorrector::with_defaults(python);

// Register known identifiers
corrector.register_variable("calculateTotal".to_string(), None, 0);
corrector.register_variable("calculateAverage".to_string(), None, 0);

// Correct an unknown identifier
let token = CodeToken::new(
    "calulateTotal",  // Misspelled
    0, 1, 0,
    TokenType::Identifier,
    "identifier",
);

let context = TokenContext::new(TokenType::Identifier);
let corrections = corrector.correct_token(&token, &context);

// Suggests: "calculateTotal" (high similarity)
```

## Correction Sources

Semantic corrections are tagged with their analysis source:

```rust
pub enum CorrectionSource {
    Neural,         // From GNN analysis
    TypeInference,  // From type checking
    ControlFlow,    // From CFG analysis
    DataFlow,       // From DFG analysis
    // ...
}
```

Usage:

```rust
for correction in corrections {
    match correction.source {
        CorrectionSource::Neural => {
            println!("GNN detected: {}", correction.context.as_deref().unwrap_or(""));
        }
        CorrectionSource::DataFlow => {
            println!("Data flow issue: {}", correction.context.as_deref().unwrap_or(""));
        }
        CorrectionSource::TypeInference => {
            println!("Type error: {}", correction.context.as_deref().unwrap_or(""));
        }
        _ => {}
    }
}
```

## Integration Example

Complete example using the semantic corrector:

```rust
use libgrammstein::code::{
    CodeParser, CodeTokenizer, CodePropertyGraph,
    SemanticCorrector, Python, CorrectionKind
};
use std::sync::Arc;

fn analyze_semantics(source: &str) -> Vec<String> {
    let python = Arc::new(Python::new());
    let mut parser = CodeParser::new(python.clone()).unwrap();
    let mut corrector = SemanticCorrector::with_defaults(python.clone());

    // Parse and build CPG
    let parsed = parser.parse(source).unwrap();
    let cpg = CodePropertyGraph::from_parsed_code(&parsed);

    // Extract and register known variables from the code
    let tokenizer = CodeTokenizer::new(python.as_ref());
    let tokens = tokenizer.tokenize(&parsed.tree, source);

    for token in &tokens {
        if token.token_type == TokenType::Identifier {
            // Check if this is a definition (simplified check)
            if let Some(parent) = &token.context.parent_node_type {
                if parent.contains("assignment") || parent.contains("parameter") {
                    corrector.register_variable(token.text.clone(), None, 0);
                }
            }
        }
    }

    // Analyze for semantic issues
    let corrections = corrector.analyze_parsed(&parsed, &cpg);

    let mut messages = Vec::new();
    for c in &corrections {
        let msg = match c.kind {
            CorrectionKind::VariableMisuse => {
                format!("Variable '{}' might be '{}' (line {})",
                    c.original, c.replacement,
                    // Would need line mapping
                    0
                )
            }
            CorrectionKind::Deletion => {
                format!("'{}' appears to be unused", c.original)
            }
            CorrectionKind::TypeError => {
                format!("Type error at '{}': {}", c.original,
                    c.context.as_deref().unwrap_or(""))
            }
            _ => format!("Issue at '{}': {:?}", c.original, c.kind),
        };
        messages.push(msg);
    }

    messages
}

let source = r#"
def process_data(items):
    total = 0
    for item in items:
        totla += item.value  # Typo: should be 'total'
    return total
"#;

let issues = analyze_semantics(source);
for issue in issues {
    println!("  {}", issue);
}
```

## GNN Integration

The semantic corrector uses `GnnSemanticScorer` for pattern detection:

```rust
// Access the GNN scorer
let scorer = corrector.gnn_scorer();

// The scorer extracts features from CPG nodes
// and uses message passing to detect semantic patterns
```

### GnnConfig

Configure the GNN behavior:

```rust
pub struct GnnConfig {
    /// Number of message passing layers
    pub num_layers: usize,
    /// Hidden dimension size
    pub hidden_dim: usize,
    /// Dropout rate
    pub dropout: f64,
    // ...
}
```

## Performance

| Operation | Complexity | Notes |
|-----------|------------|-------|
| CPG analysis | O(n + e) | n = nodes, e = edges |
| Variable misuse | O(v) | v = known variables |
| Name similarity | O(len²) | Levenshtein distance |
| GNN inference | O(L × n) | L = layers, n = nodes |

### Optimization Tips

1. **Register variables early**: Populate known variables at project load
2. **Use confidence threshold**: Set `min_confidence` appropriately
3. **Disable unused checks**: Turn off `check_unused_bindings` if not needed
4. **Cache CPG**: Build CPG once and reuse for multiple analyses

## Thread Safety

`SemanticCorrector` is `Send + Sync` when its language type is:

```rust
use std::sync::Arc;

let corrector = Arc::new(SemanticCorrector::with_defaults(python));

// Share across threads for read-only analysis
let results: Vec<_> = cpgs.par_iter()
    .map(|cpg| corrector.analyze_cpg(cpg))
    .collect();
```

Note: Modifying the corrector (registering variables) requires mutable access.

## Limitations

1. **Requires full AST**: Token-level correction is limited
2. **Type inference**: Depends on available type annotations
3. **Scope tracking**: Simplified scope model
4. **Cross-file analysis**: Limited to single-file context

## See Also

- [Correctors Overview]overview.md - Architecture and comparison
- [Lexical Corrector]lexical.md - Fuzzy matching
- [Grammar Corrector]grammar.md - Syntax-based correction
- [Ensemble Corrector]ensemble.md - Multi-source aggregation
- [CPG]../cpg.md - Code Property Graphs
- [GNN]../gnn.md - Graph Neural Networks