lling-llang 0.1.0

WFST framework for text normalization and grammar 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
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
# API Migration Transducers

API migration transducers provide WFST-based automation for transforming code between API versions. This document explains how to define migration rules and apply them to modernize codebases.

## Concepts

### What is API Migration?

**API migration** is the process of updating code to work with a newer version of a library, framework, or language. Common scenarios include:

- **Function renames**: `oldFunction()``newFunction()`
- **Parameter changes**: New required parameters, renamed parameters
- **Signature changes**: Different argument types or orders
- **Deprecations**: Removal of old APIs with replacement suggestions
- **Syntax evolution**: Python 2 to Python 3, ES5 to ES6

### Why WFSTs for Migration?

Traditional approaches (regex, AST rewriting) have limitations:

| Approach | Strengths | Weaknesses |
|----------|-----------|------------|
| Regex | Fast, simple | No context, fragile |
| AST rewriting | Precise, structural | Language-specific, complex |
| **WFST** | Context-aware, composable, weighted | Token-based |

WFSTs excel at:
- **Pattern matching** with context
- **Weighted alternatives** when multiple migrations are possible
- **Composition** of migration passes
- **Incremental application** through streaming

### Architecture

```
┌─────────────────────────────────────────────────────┐
│              API Migration System                    │
├─────────────────────────────────────────────────────┤
│  Migration Rules                                     │
│  ├── RenameFunction("old" → "new")                  │
│  ├── RenameType("OldType" → "NewType")              │
│  ├── ReplaceCall(pattern → replacement)             │
│  └── Custom transformations                          │
├─────────────────────────────────────────────────────┤
│  Version Range                                       │
│  └── from: v1.0.0  to: v2.0.0                       │
├─────────────────────────────────────────────────────┤
│  Migration Transducer                                │
│  ├── Token-based pattern matching                   │
│  ├── Rule application with costs                    │
│  └── WFST compilation for composition               │
└─────────────────────────────────────────────────────┘
```

## Core API

### Version and VersionRange

Semantic versioning support for constraining rule applicability:

```rust
use lling_llang::programming::{Version, VersionRange};

// Create versions
let v1_0 = Version::new(1, 0);           // 1.0.0
let v2_0 = Version::new(2, 0);           // 2.0.0
let v1_2_3 = Version::with_patch(1, 2, 3); // 1.2.3

// Parse from strings
let parsed = Version::parse("1.5.2").unwrap();

// Version ordering
assert!(v1_0 < v2_0);
assert!(v1_0 < v1_2_3);

// Version ranges
let range = VersionRange::new(v1_0, v2_0);
assert!(range.contains(v1_2_3));   // 1.0.0 ≤ 1.2.3 ≤ 2.0.0
assert!(!range.contains(Version::new(3, 0)));
```

### MigrationType

Different kinds of API changes:

```rust
use lling_llang::programming::MigrationType;

// Function rename
MigrationType::RenameFunction {
    old_name: "deprecated_fn".to_string(),
    new_name: "modern_fn".to_string(),
}

// Parameter rename (optionally scoped to a function)
MigrationType::RenameParameter {
    function: Some("my_function".to_string()),
    old_name: "old_param".to_string(),
    new_name: "new_param".to_string(),
}

// Type rename
MigrationType::RenameType {
    old_name: "OldClass".to_string(),
    new_name: "NewClass".to_string(),
}

// Multi-token pattern replacement
MigrationType::ReplaceCall {
    old_pattern: vec!["obj".to_string(), ".", "method".to_string()],
    new_pattern: vec!["obj".to_string(), ".", "newMethod".to_string()],
}

// Deprecation with message
MigrationType::RemoveFunction {
    function: "legacy_fn".to_string(),
    message: "Use modern_fn instead".to_string(),
}

// Custom transformation
MigrationType::Custom {
    description: "Custom transformation".to_string(),
    old_tokens: vec!["old".to_string(), "pattern".to_string()],
    new_tokens: vec!["new".to_string(), "pattern".to_string()],
}
```

### ApiMigrationRule

Rules define individual transformations:

```rust
use lling_llang::programming::{ApiMigrationRule, Version};

// Function rename rule
let rename_rule = ApiMigrationRule::rename_function(
    "getUser",
    "fetchUser",
    Version::new(1, 0),
    Version::new(2, 0),
);

// Type rename rule
let type_rule = ApiMigrationRule::rename_type(
    "Response",
    "ApiResponse",
    Version::new(1, 0),
    Version::new(2, 0),
);

// Parameter rename (function-scoped)
let param_rule = ApiMigrationRule::rename_parameter(
    Some("configure"),  // Only in configure() calls
    "timeout",
    "timeoutMs",
    Version::new(1, 0),
    Version::new(2, 0),
);

// Multi-token pattern replacement
let pattern_rule = ApiMigrationRule::replace(
    ["this", ".", "setState"],  // Old pattern
    ["setState"],               // New pattern
    Version::new(16, 8),
    Version::new(18, 0),
);

// Deprecation warning (requires manual review)
let deprecation = ApiMigrationRule::deprecate(
    "unsafeMethod",
    "This method is deprecated with no replacement",
    Version::new(1, 0),
    Version::new(2, 0),
);

// Customize rule cost and review requirement
let custom_rule = ApiMigrationRule::rename_function("a", "b", Version::new(1, 0), Version::new(2, 0))
    .with_cost(0.5)      // Higher cost = less preferred
    .manual_review();    // Mark as needing human review
```

### ApiMigrationTransducer

The transducer applies rules to token streams:

```rust
use lling_llang::programming::{ApiMigrationTransducer, ApiMigrationRule, Version};
use lling_llang::semiring::TropicalWeight;

// Create transducer with version context
let mut transducer: ApiMigrationTransducer<TropicalWeight> =
    ApiMigrationTransducer::new(
        Version::new(1, 0),  // Source version
        Version::new(2, 0),  // Target version
    );

// Add migration rules
transducer.add_rule(ApiMigrationRule::rename_function(
    "oldFn",
    "newFn",
    Version::new(1, 0),
    Version::new(2, 0),
));

// Apply migration to tokens
let tokens = vec![
    "call".to_string(),
    "oldFn".to_string(),
    "(".to_string(),
    ")".to_string(),
];

let result = transducer.migrate(&tokens);

// Check results
assert_eq!(result.migrated, vec!["call", "newFn", "(", ")"]);
assert_eq!(result.stats.rules_applied, 1);
assert_eq!(result.stats.automatic_migrations, 1);
```

### ApiMigrationBuilder

Fluent API for building transducers:

```rust
use lling_llang::programming::{ApiMigrationBuilder, ApiMigrationRule, Version};
use lling_llang::semiring::TropicalWeight;

let transducer: ApiMigrationTransducer<TropicalWeight> =
    ApiMigrationBuilder::new(Version::new(1, 0), Version::new(2, 0))
        .add_rule(ApiMigrationRule::rename_function(
            "getUserById",
            "fetchUser",
            Version::new(1, 0),
            Version::new(2, 0),
        ))
        .add_rule(ApiMigrationRule::rename_type(
            "UserData",
            "User",
            Version::new(1, 0),
            Version::new(2, 0),
        ))
        .add_rule(ApiMigrationRule::replace(
            ["callback", "(", "err", ",", "data", ")"],
            ["async", "/", "await"],
            Version::new(1, 0),
            Version::new(2, 0),
        ))
        .build();
```

### MigrationResult and MigrationStats

Detailed feedback from migration operations:

```rust
use lling_llang::programming::{MigrationResult, MigrationStats};

// MigrationResult contains:
let result: MigrationResult = transducer.migrate(&tokens);

// Original input tokens
let original: &Vec<String> = &result.original;

// Transformed output tokens
let migrated: &Vec<String> = &result.migrated;

// IDs of rules that were applied
let applied: &Vec<String> = &result.applied_rules;

// Statistics
let stats: &MigrationStats = &result.stats;
println!("Rules applied: {}", stats.rules_applied);
println!("Automatic: {}", stats.automatic_migrations);
println!("Need review: {}", stats.manual_review_items);
println!("Total cost: {}", stats.total_cost);
```

## Examples

### Basic Function Rename

The simplest migration: renaming a function.

```rust
use lling_llang::programming::{ApiMigrationBuilder, ApiMigrationRule, Version};
use lling_llang::semiring::TropicalWeight;

let transducer: ApiMigrationTransducer<TropicalWeight> =
    ApiMigrationBuilder::new(Version::new(1, 0), Version::new(2, 0))
        .add_rule(ApiMigrationRule::rename_function(
            "getUsers",
            "fetchUsers",
            Version::new(1, 0),
            Version::new(2, 0),
        ))
        .build();

// Before: getUsers()
let tokens = vec!["getUsers".to_string(), "(".to_string(), ")".to_string()];

// After: fetchUsers()
let result = transducer.migrate(&tokens);
assert_eq!(result.migrated, vec!["fetchUsers", "(", ")"]);
```

### Multi-Token Pattern Replacement

Replace complex patterns involving multiple tokens.

```rust
use lling_llang::programming::{ApiMigrationBuilder, ApiMigrationRule, Version};
use lling_llang::semiring::TropicalWeight;

let transducer: ApiMigrationTransducer<TropicalWeight> =
    ApiMigrationBuilder::new(Version::new(1, 0), Version::new(2, 0))
        .add_rule(ApiMigrationRule::replace(
            // Old: this.setState({...})
            ["this", ".", "setState"],
            // New: setState(...)
            ["setState"],
            Version::new(16, 8),
            Version::new(18, 0),
        ))
        .build();

// Before: this.setState({ count: 1 })
let tokens = vec![
    "this".to_string(), ".".to_string(), "setState".to_string(),
    "(".to_string(), "{".to_string(), "count".to_string(),
    ":".to_string(), "1".to_string(), "}".to_string(), ")".to_string(),
];

// After: setState({ count: 1 })
let result = transducer.migrate(&tokens);
assert_eq!(result.migrated[0], "setState");
assert_eq!(result.migrated[1], "(");
```

### Version-Constrained Migration

Rules only apply within their version range.

```rust
use lling_llang::programming::{ApiMigrationBuilder, ApiMigrationRule, Version};
use lling_llang::semiring::TropicalWeight;

// Transducer for migrating from v1.0 to v2.0
let transducer: ApiMigrationTransducer<TropicalWeight> =
    ApiMigrationBuilder::new(Version::new(1, 0), Version::new(2, 0))
        // Rule for v1.0 → v1.5 only
        .add_rule(ApiMigrationRule::rename_function(
            "alpha",
            "beta",
            Version::new(1, 0),
            Version::with_patch(1, 5, 0),
        ))
        // Rule for v1.5 → v2.0 only
        .add_rule(ApiMigrationRule::rename_function(
            "beta",
            "gamma",
            Version::with_patch(1, 5, 0),
            Version::new(2, 0),
        ))
        .build();

// With source v1.0, only first rule applies
let tokens = vec!["alpha".to_string()];
let result = transducer.migrate(&tokens);
assert_eq!(result.migrated, vec!["beta"]);
```

### Handling Deprecations

Flag deprecated APIs for manual review.

```rust
use lling_llang::programming::{ApiMigrationBuilder, ApiMigrationRule, Version};
use lling_llang::semiring::TropicalWeight;

let transducer: ApiMigrationTransducer<TropicalWeight> =
    ApiMigrationBuilder::new(Version::new(1, 0), Version::new(2, 0))
        .add_rule(ApiMigrationRule::deprecate(
            "unsafeEval",
            "REMOVED: Use safe alternatives instead",
            Version::new(1, 0),
            Version::new(2, 0),
        ))
        .build();

let tokens = vec!["unsafeEval".to_string(), "(".to_string(), ")".to_string()];
let result = transducer.migrate(&tokens);

// Deprecation requires manual review
assert_eq!(result.stats.manual_review_items, 1);
assert_eq!(result.stats.automatic_migrations, 0);

// Output contains the warning message
assert!(result.migrated.contains(&"REMOVED: Use safe alternatives instead".to_string()));
```

### Building a WFST for Composition

Convert migration rules to a WFST for composition with other transducers.

```rust
use lling_llang::programming::{ApiMigrationBuilder, ApiMigrationRule, Version};
use lling_llang::semiring::TropicalWeight;
use lling_llang::wfst::Wfst;

let transducer: ApiMigrationTransducer<TropicalWeight> =
    ApiMigrationBuilder::new(Version::new(1, 0), Version::new(2, 0))
        .add_rule(ApiMigrationRule::rename_function(
            "old",
            "new",
            Version::new(1, 0),
            Version::new(2, 0),
        ))
        .build();

// Build WFST with cost mapping
let fst = transducer.build_wfst(TropicalWeight::new);

// WFST can be composed with other transducers
// (lexical normalizers, syntax checkers, etc.)
```

## Pattern Libraries

Pre-built migration rules for common frameworks.

### React Class to Function Components

```rust
use lling_llang::programming::patterns;

// Get migration rules for React modernization
let react_rules = patterns::react_class_to_function();

// Includes transformations like:
// - componentDidMount → useEffect(() => { ... })
// - componentWillUnmount → useEffect(() => { return () => { ... }})
// - this.setState → setState
// - this.state → state
```

### Python 2 to Python 3

```rust
use lling_llang::programming::patterns;

let python_rules = patterns::python2_to_python3();

// Includes transformations like:
// - print "x" → print("x")
// - xrange → range
// - raw_input → input
// - unicode → str
// - .iteritems() → .items()
// - .iterkeys() → .keys()
// - .itervalues() → .values()
```

### jQuery to Vanilla JavaScript

```rust
use lling_llang::programming::patterns;

let jquery_rules = patterns::jquery_to_vanilla_js();

// Includes transformations like:
// - $("#id") → document.getElementById("id")
// - $(".class") → document.querySelectorAll(".class")
// - .addClass() → .classList.add()
// - .removeClass() → .classList.remove()
// - .toggleClass() → .classList.toggle()
// - .attr() → .getAttribute()
```

### Using Pattern Libraries

```rust
use lling_llang::programming::{ApiMigrationBuilder, Version, patterns};
use lling_llang::semiring::TropicalWeight;

// Combine pattern libraries with custom rules
let transducer: ApiMigrationTransducer<TropicalWeight> =
    ApiMigrationBuilder::new(Version::new(2, 7), Version::new(3, 10))
        // Add Python 2→3 rules
        .add_rules(patterns::python2_to_python3())
        // Add your custom rules
        .add_rule(ApiMigrationRule::rename_function(
            "my_legacy_fn",
            "my_modern_fn",
            Version::new(2, 7),
            Version::new(3, 10),
        ))
        .build();
```

## Migration Workflow

A typical migration workflow:

```
1. Define Version Context
   ├── Source version (current codebase)
   └── Target version (desired API version)
                  2. Collect Migration Rules
   ├── Use pattern libraries for known frameworks
   ├── Add custom rules for project-specific APIs
   └── Mark breaking changes as manual_review
                  3. Tokenize Source Code
   └── Split code into token stream
                  4. Apply Migration
   ├── Pattern matching against rules
   ├── Apply transformations
   └── Track statistics
                  5. Review Results
   ├── Automatic migrations: apply directly
   └── Manual review items: human verification needed
                  6. Reconstruct Code
   └── Join tokens back into source code
```

## Performance Considerations

### Rule Indexing

Rules are indexed by their first token for O(1) lookup:

```rust
// Internal structure:
// rules_by_token: HashMap<String, Vec<ApiMigrationRule>>
//
// Lookup: O(1) for first token, then linear scan of matching rules
```

### Cost-Based Selection

When multiple rules match, costs influence selection:

| Rule Type | Default Cost | Notes |
|-----------|--------------|-------|
| Rename (function/type/param) | 0.1 | Low cost, highly automatic |
| Replace pattern | 0.2 | Slightly higher due to complexity |
| Deprecation | 1.0 | High cost, needs manual review |

### WFST Compilation

Building a WFST is O(n) in the number of rules. The resulting WFST can be:
- **Composed** with other transducers
- **Determinized** for faster matching
- **Minimized** to reduce state count

## Related Topics

- [WFST Composition]../algorithms/composition.md: Composing transducers
- [WFST Operations]../architecture/wfst-operations.md: Core WFST operations
- [Determinization]../algorithms/determinization.md: Making transducers deterministic
- [Semirings]../architecture/semirings.md: Weight algebras for transducers