presolve-compiler 0.2.0-beta.2

The Presolve compiler toolchain for TypeScript web applications.
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
//! Canonical authored semantics, normalized at the syntax/TypeScript boundary.
//!
//! The parser owns source syntax and the TypeScript-authority package owns
//! resolved symbols. This module accepts the product of joining those two
//! boundaries; it deliberately does not inspect intrinsic spelling or import
//! paths. Legacy decorator extraction is a separate lowering concern.

use std::path::PathBuf;

use presolve_parser::ParsedFile;
use serde::{Deserialize, Serialize};

pub const CANONICAL_AUTHORED_SEMANTICS_SCHEMA_VERSION: u32 = 3;

/// A serializable source range shared by the syntax and semantic boundaries.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct AuthoredSourceRangeV1 {
    pub start: usize,
    pub end: usize,
    pub line: usize,
    pub column: usize,
}

/// A resolved declaration identity supplied by the TypeScript authority adapter.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct ResolvedIntrinsicIdentityV1 {
    pub name: String,
    pub flags: u32,
    pub declaration_modules: Vec<String>,
}

/// The canonical intrinsic classification of a syntax-selected use site.
///
/// `kind` is only produced by the resolved-identity registry. It must never be
/// inferred from source spelling by a compiler consumer.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CanonicalIntrinsicKindV1 {
    Component,
    State,
    Action,
    Computed,
    Effect,
    Slot,
    Context,
    Provide,
    Consume,
    Form,
    Serialize,
    Field,
    Validate,
    Submit,
    Resource,
    Loader,
    ServerAction,
    Opaque,
}

/// The authority-backed basis for one syntax-selected semantic candidate.
///
/// Intrinsics require a resolved framework identity. TSX bindings and event
/// references are syntax facts whose expression/type validation is supplied by
/// TypeScript queries, but they are not framework intrinsics themselves.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuthoredSemanticCandidateKindV1 {
    ResolvedIntrinsic {
        intrinsic_kind: CanonicalIntrinsicKindV1,
        intrinsic_identity: ResolvedIntrinsicIdentityV1,
    },
    /// A non-intrinsic getter admitted by compiler-owned reactive/purity
    /// analysis. Its evidence is explicit because no framework symbol exists.
    DerivedComputedGetter {
        state_dependencies: Vec<String>,
        computed_dependencies: Vec<String>,
    },
    TsxBinding,
    TsxEventReference,
}

/// Evidence retained for a non-intrinsic declaration admitted by compiler
/// analysis rather than resolved framework-symbol identity.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DerivedAuthoredEvidenceV2 {
    ComputedGetter {
        state_dependencies: Vec<String>,
        computed_dependencies: Vec<String>,
    },
}

/// One candidate selected from the general source AST and checked by the
/// TypeScript authority adapter.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct ResolvedAuthoredSemanticCandidateV1 {
    /// The source declaration or use-site being described. This is data for
    /// tooling and stable snapshots, not an identity authority.
    pub subject: String,
    pub source: AuthoredSourceRangeV1,
    pub kind: AuthoredSemanticCandidateKindV1,
}

/// A normalized authored declaration which later compiler products extend.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct CanonicalAuthoredDeclarationV1 {
    pub kind: CanonicalAuthoredDeclarationKindV1,
    pub subject: String,
    pub source: AuthoredSourceRangeV1,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub intrinsic_identity: Option<ResolvedIntrinsicIdentityV1>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub derived_evidence: Option<DerivedAuthoredEvidenceV2>,
}

/// The source-independent vocabulary emitted at the authored-semantics
/// boundary. Each case records a framework meaning, not legacy syntax.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CanonicalAuthoredDeclarationKindV1 {
    Component,
    State,
    Action,
    Computed,
    Effect,
    Slot,
    ContextToken,
    ContextProvider,
    ContextConsumer,
    Form,
    Serialization,
    FormField,
    Validation,
    Submission,
    Resource,
    RouteLoader,
    ServerAction,
    Capability,
    TsxBinding,
    TsxEventReference,
}

/// The canonical output of syntax selection plus resolved intrinsic identity.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CanonicalAuthoredSemanticModelV1 {
    pub schema_version: u32,
    pub source_path: PathBuf,
    pub declarations: Vec<CanonicalAuthoredDeclarationV1>,
}

/// A boundary violation while normalizing authored semantic candidates.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuthoredSemanticNormalizationErrorV1 {
    InvalidSourceRange {
        subject: String,
        start: usize,
        end: usize,
        source_length: usize,
    },
}

impl std::fmt::Display for AuthoredSemanticNormalizationErrorV1 {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidSourceRange {
                subject,
                start,
                end,
                source_length,
            } => write!(
                formatter,
                "authored semantic candidate `{subject}` has invalid source range {start}..{end} for source length {source_length}"
            ),
        }
    }
}

impl std::error::Error for AuthoredSemanticNormalizationErrorV1 {}

/// A boundary violation while composing independently lowered source forms.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuthoredSemanticCompositionErrorV1 {
    Empty,
    SchemaVersion { actual: u32 },
    SourcePathMismatch { expected: PathBuf, actual: PathBuf },
}

impl std::fmt::Display for AuthoredSemanticCompositionErrorV1 {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Empty => write!(formatter, "cannot compose zero authored semantic models"),
            Self::SchemaVersion { actual } => write!(
                formatter,
                "cannot compose authored semantic schema version {actual}; expected {CANONICAL_AUTHORED_SEMANTICS_SCHEMA_VERSION}"
            ),
            Self::SourcePathMismatch { expected, actual } => write!(
                formatter,
                "cannot compose authored semantic models from {} and {}",
                expected.display(),
                actual.display()
            ),
        }
    }
}

impl std::error::Error for AuthoredSemanticCompositionErrorV1 {}

/// Normalize already-resolved syntax candidates for one parser product.
///
/// This is intentionally the first point where the two V2 authorities meet:
/// `ParsedFile::syntax` supplies the source extent, while callers supply a
/// resolved intrinsic classification from `typescript-authority`. No source
/// text, decorator name, or module specifier is used for recognition here.
pub fn normalize_authored_semantics_v1(
    parsed: &ParsedFile,
    candidates: impl IntoIterator<Item = ResolvedAuthoredSemanticCandidateV1>,
) -> Result<CanonicalAuthoredSemanticModelV1, AuthoredSemanticNormalizationErrorV1> {
    let source_length = parsed.syntax.source.len();
    let mut declarations = candidates
        .into_iter()
        .map(|candidate| {
            if candidate.source.start > candidate.source.end || candidate.source.end > source_length
            {
                return Err(AuthoredSemanticNormalizationErrorV1::InvalidSourceRange {
                    subject: candidate.subject,
                    start: candidate.source.start,
                    end: candidate.source.end,
                    source_length,
                });
            }
            let (kind, mut intrinsic_identity, mut derived_evidence) =
                declaration_kind(candidate.kind);
            if let Some(identity) = &mut intrinsic_identity {
                identity.declaration_modules.sort();
                identity.declaration_modules.dedup();
            }
            if let Some(DerivedAuthoredEvidenceV2::ComputedGetter {
                state_dependencies,
                computed_dependencies,
            }) = &mut derived_evidence
            {
                state_dependencies.sort();
                state_dependencies.dedup();
                computed_dependencies.sort();
                computed_dependencies.dedup();
            }
            Ok(CanonicalAuthoredDeclarationV1 {
                kind,
                subject: candidate.subject,
                source: candidate.source,
                intrinsic_identity,
                derived_evidence,
            })
        })
        .collect::<Result<Vec<_>, _>>()?;

    declarations.sort();
    declarations.dedup();
    Ok(CanonicalAuthoredSemanticModelV1 {
        schema_version: CANONICAL_AUTHORED_SEMANTICS_SCHEMA_VERSION,
        source_path: parsed.path.clone(),
        declarations,
    })
}

/// Compose independently lowered source forms for one source file.
///
/// Each input has already crossed the source-AST and TypeScript-authority
/// boundary. This function only verifies a common schema/path and restores the
/// canonical deterministic ordering and deduplication rule; it never assigns
/// framework meaning from source spelling.
pub fn compose_authored_semantics_v1(
    models: impl IntoIterator<Item = CanonicalAuthoredSemanticModelV1>,
) -> Result<CanonicalAuthoredSemanticModelV1, AuthoredSemanticCompositionErrorV1> {
    let mut models = models.into_iter();
    let first = models
        .next()
        .ok_or(AuthoredSemanticCompositionErrorV1::Empty)?;
    if first.schema_version != CANONICAL_AUTHORED_SEMANTICS_SCHEMA_VERSION {
        return Err(AuthoredSemanticCompositionErrorV1::SchemaVersion {
            actual: first.schema_version,
        });
    }
    let source_path = first.source_path.clone();
    let mut declarations = first.declarations;
    for model in models {
        if model.schema_version != CANONICAL_AUTHORED_SEMANTICS_SCHEMA_VERSION {
            return Err(AuthoredSemanticCompositionErrorV1::SchemaVersion {
                actual: model.schema_version,
            });
        }
        if model.source_path != source_path {
            return Err(AuthoredSemanticCompositionErrorV1::SourcePathMismatch {
                expected: source_path,
                actual: model.source_path,
            });
        }
        declarations.extend(model.declarations);
    }
    declarations.sort();
    declarations.dedup();
    Ok(CanonicalAuthoredSemanticModelV1 {
        schema_version: CANONICAL_AUTHORED_SEMANTICS_SCHEMA_VERSION,
        source_path,
        declarations,
    })
}

fn declaration_kind(
    kind: AuthoredSemanticCandidateKindV1,
) -> (
    CanonicalAuthoredDeclarationKindV1,
    Option<ResolvedIntrinsicIdentityV1>,
    Option<DerivedAuthoredEvidenceV2>,
) {
    let AuthoredSemanticCandidateKindV1::ResolvedIntrinsic {
        intrinsic_kind,
        intrinsic_identity,
    } = kind
    else {
        return match kind {
            AuthoredSemanticCandidateKindV1::DerivedComputedGetter {
                state_dependencies,
                computed_dependencies,
            } => (
                CanonicalAuthoredDeclarationKindV1::Computed,
                None,
                Some(DerivedAuthoredEvidenceV2::ComputedGetter {
                    state_dependencies,
                    computed_dependencies,
                }),
            ),
            AuthoredSemanticCandidateKindV1::TsxBinding => {
                (CanonicalAuthoredDeclarationKindV1::TsxBinding, None, None)
            }
            AuthoredSemanticCandidateKindV1::TsxEventReference => (
                CanonicalAuthoredDeclarationKindV1::TsxEventReference,
                None,
                None,
            ),
            AuthoredSemanticCandidateKindV1::ResolvedIntrinsic { .. } => unreachable!(),
        };
    };

    let declaration_kind = match intrinsic_kind {
        CanonicalIntrinsicKindV1::Component => CanonicalAuthoredDeclarationKindV1::Component,
        CanonicalIntrinsicKindV1::State => CanonicalAuthoredDeclarationKindV1::State,
        CanonicalIntrinsicKindV1::Action => CanonicalAuthoredDeclarationKindV1::Action,
        CanonicalIntrinsicKindV1::Computed => CanonicalAuthoredDeclarationKindV1::Computed,
        CanonicalIntrinsicKindV1::Effect => CanonicalAuthoredDeclarationKindV1::Effect,
        CanonicalIntrinsicKindV1::Slot => CanonicalAuthoredDeclarationKindV1::Slot,
        CanonicalIntrinsicKindV1::Context => CanonicalAuthoredDeclarationKindV1::ContextToken,
        CanonicalIntrinsicKindV1::Provide => CanonicalAuthoredDeclarationKindV1::ContextProvider,
        CanonicalIntrinsicKindV1::Consume => CanonicalAuthoredDeclarationKindV1::ContextConsumer,
        CanonicalIntrinsicKindV1::Form => CanonicalAuthoredDeclarationKindV1::Form,
        CanonicalIntrinsicKindV1::Serialize => CanonicalAuthoredDeclarationKindV1::Serialization,
        CanonicalIntrinsicKindV1::Field => CanonicalAuthoredDeclarationKindV1::FormField,
        CanonicalIntrinsicKindV1::Validate => CanonicalAuthoredDeclarationKindV1::Validation,
        CanonicalIntrinsicKindV1::Submit => CanonicalAuthoredDeclarationKindV1::Submission,
        CanonicalIntrinsicKindV1::Resource => CanonicalAuthoredDeclarationKindV1::Resource,
        CanonicalIntrinsicKindV1::Loader => CanonicalAuthoredDeclarationKindV1::RouteLoader,
        CanonicalIntrinsicKindV1::ServerAction => CanonicalAuthoredDeclarationKindV1::ServerAction,
        CanonicalIntrinsicKindV1::Opaque => CanonicalAuthoredDeclarationKindV1::Capability,
    };
    (declaration_kind, Some(intrinsic_identity), None)
}

#[cfg(test)]
mod tests {
    use presolve_parser::parse_file;

    use super::{
        compose_authored_semantics_v1, normalize_authored_semantics_v1,
        AuthoredSemanticCandidateKindV1, AuthoredSemanticCompositionErrorV1,
        AuthoredSemanticNormalizationErrorV1, AuthoredSourceRangeV1,
        CanonicalAuthoredDeclarationKindV1, CanonicalIntrinsicKindV1,
        ResolvedAuthoredSemanticCandidateV1, ResolvedIntrinsicIdentityV1,
    };

    fn candidate(
        subject: &str,
        start: usize,
        kind: CanonicalIntrinsicKindV1,
    ) -> ResolvedAuthoredSemanticCandidateV1 {
        ResolvedAuthoredSemanticCandidateV1 {
            subject: subject.to_owned(),
            source: AuthoredSourceRangeV1 {
                start,
                end: start + 5,
                line: 1,
                column: start + 1,
            },
            kind: AuthoredSemanticCandidateKindV1::ResolvedIntrinsic {
                intrinsic_kind: kind,
                intrinsic_identity: ResolvedIntrinsicIdentityV1 {
                    name: "renamedFrameworkExport".to_owned(),
                    flags: 2_097_152,
                    declaration_modules: vec![
                        "node_modules/@presolve/framework/index.d.ts".to_owned()
                    ],
                },
            },
        }
    }

    #[test]
    fn normalizes_resolved_candidates_without_using_source_spelling() {
        let parsed = parse_file("src/Card.tsx", "const Card = frameworkUse();");
        let state = candidate("Card.count", 20, CanonicalIntrinsicKindV1::State);
        let component = candidate("Card", 6, CanonicalIntrinsicKindV1::Component);

        let model =
            normalize_authored_semantics_v1(&parsed, [state.clone(), component.clone(), state])
                .expect("valid resolved candidates");

        assert_eq!(model.schema_version, 3);
        assert_eq!(model.declarations.len(), 2);
        assert_eq!(model.declarations[0].subject, "Card");
        assert_eq!(
            model.declarations[0].kind,
            CanonicalAuthoredDeclarationKindV1::Component
        );
        assert_eq!(model.declarations[1].subject, "Card.count");
        assert_eq!(
            model.declarations[1].kind,
            CanonicalAuthoredDeclarationKindV1::State
        );
        assert_eq!(
            model.declarations[1]
                .intrinsic_identity
                .as_ref()
                .unwrap()
                .name,
            "renamedFrameworkExport"
        );
        assert_eq!(
            serde_json::to_value(&model).expect("serializable model"),
            serde_json::json!({
                "schema_version": 3,
                "source_path": "src/Card.tsx",
                "declarations": [
                    {
                        "kind": "component",
                        "subject": "Card",
                        "source": { "start": 6, "end": 11, "line": 1, "column": 7 },
                        "intrinsic_identity": {
                            "name": "renamedFrameworkExport",
                            "flags": 2_097_152,
                            "declaration_modules": ["node_modules/@presolve/framework/index.d.ts"]
                        }
                    },
                    {
                        "kind": "state",
                        "subject": "Card.count",
                        "source": { "start": 20, "end": 25, "line": 1, "column": 21 },
                        "intrinsic_identity": {
                            "name": "renamedFrameworkExport",
                            "flags": 2_097_152,
                            "declaration_modules": ["node_modules/@presolve/framework/index.d.ts"]
                        }
                    }
                ]
            })
        );
    }

    #[test]
    fn composes_same_source_models_and_rejects_cross_source_mixing() {
        let parsed = parse_file("src/Card.tsx", "const Card = frameworkUse();");
        let component = normalize_authored_semantics_v1(
            &parsed,
            [candidate("Card", 6, CanonicalIntrinsicKindV1::Component)],
        )
        .unwrap();
        let state = normalize_authored_semantics_v1(
            &parsed,
            [candidate("Card.count", 20, CanonicalIntrinsicKindV1::State)],
        )
        .unwrap();
        let composed = compose_authored_semantics_v1([component.clone(), state]).unwrap();
        assert_eq!(composed.declarations.len(), 2);

        let other = normalize_authored_semantics_v1(
            &parse_file("src/Other.tsx", "const Other = frameworkUse();"),
            [candidate("Other", 6, CanonicalIntrinsicKindV1::Component)],
        )
        .unwrap();
        assert!(matches!(
            compose_authored_semantics_v1([component, other]),
            Err(AuthoredSemanticCompositionErrorV1::SourcePathMismatch { .. })
        ));
    }

    #[test]
    fn retains_tsx_binding_and_event_facts_without_an_intrinsic_identity() {
        let parsed = parse_file(
            "src/Card.tsx",
            "const Card = <button onClick={save}>{count}</button>;",
        );
        let binding = ResolvedAuthoredSemanticCandidateV1 {
            subject: "count".to_owned(),
            source: AuthoredSourceRangeV1 {
                start: 44,
                end: 49,
                line: 1,
                column: 45,
            },
            kind: AuthoredSemanticCandidateKindV1::TsxBinding,
        };
        let event = ResolvedAuthoredSemanticCandidateV1 {
            subject: "save".to_owned(),
            source: AuthoredSourceRangeV1 {
                start: 37,
                end: 41,
                line: 1,
                column: 38,
            },
            kind: AuthoredSemanticCandidateKindV1::TsxEventReference,
        };

        let model = normalize_authored_semantics_v1(&parsed, [binding, event])
            .expect("TSX syntax candidates fit the source AST");

        assert_eq!(model.declarations.len(), 2);
        assert!(model.declarations.iter().any(|declaration| {
            declaration.kind == CanonicalAuthoredDeclarationKindV1::TsxBinding
                && declaration.intrinsic_identity.is_none()
        }));
        assert!(model.declarations.iter().any(|declaration| {
            declaration.kind == CanonicalAuthoredDeclarationKindV1::TsxEventReference
                && declaration.intrinsic_identity.is_none()
        }));
    }

    #[test]
    fn rejects_candidates_outside_the_general_source_ast_extent() {
        let parsed = parse_file("src/Card.tsx", "const Card = 1;");
        let error = normalize_authored_semantics_v1(
            &parsed,
            [candidate("Card", 99, CanonicalIntrinsicKindV1::Component)],
        )
        .expect_err("invalid range must not enter the canonical model");

        assert!(matches!(
            error,
            AuthoredSemanticNormalizationErrorV1::InvalidSourceRange { subject, .. }
                if subject == "Card"
        ));
    }
}