omena-semantic 0.1.14

Semantic boundary crate for CSS Module Explainer style analysis
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
//! Source input evidence for semantic promotion.
//!
//! This module preserves reference-site identity, certainty reasons, binding
//! origins, style-module edges, and value-domain explanations so semantic
//! consumers can explain why a source expression maps to a CSS selector fact.

use std::collections::{BTreeMap, BTreeSet};

use engine_input_producers::{
    EngineInputV2, ExpressionSemanticsEvaluatorCandidatePayloadV0,
    summarize_expression_semantics_evaluator_candidates_input,
    summarize_selector_usage_evaluator_candidates_input,
};
use serde::Serialize;

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SourceInputPromotionEvidenceSummaryV0 {
    pub schema_version: &'static str,
    pub product: &'static str,
    pub input_version: String,
    pub reference_site_identity: ReferenceSiteIdentityEvidenceV0,
    pub certainty_reason: CertaintyReasonEvidenceV0,
    pub binding_origin: BindingOriginEvidenceV0,
    pub style_module_edge: StyleModuleEdgeEvidenceV0,
    pub value_domain_explanation: ValueDomainExplanationEvidenceV0,
    pub blocking_gaps: Vec<&'static str>,
    pub next_priorities: Vec<&'static str>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReferenceSiteIdentityEvidenceV0 {
    pub status: &'static str,
    pub selector_count: usize,
    pub reference_site_count: usize,
    pub direct_reference_site_count: usize,
    pub expanded_reference_site_count: usize,
    pub style_dependency_reference_site_count: usize,
    pub editable_direct_site_count: usize,
    pub reference_kind_counts: BTreeMap<String, usize>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CertaintyReasonEvidenceV0 {
    pub status: &'static str,
    pub expression_count: usize,
    pub exact_count: usize,
    pub inferred_count: usize,
    pub possible_count: usize,
    pub missing_reason_count: usize,
    pub reason_counts: BTreeMap<String, usize>,
    pub shape_kind_counts: BTreeMap<String, usize>,
    pub shape_label_counts: BTreeMap<String, usize>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BindingOriginEvidenceV0 {
    pub status: &'static str,
    pub expression_count: usize,
    pub direct_class_name_count: usize,
    pub root_binding_count: usize,
    pub access_path_count: usize,
    pub access_path_segment_count: usize,
    pub expression_kind_counts: BTreeMap<String, usize>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StyleModuleEdgeEvidenceV0 {
    pub status: &'static str,
    pub source_style_edge_count: usize,
    pub distinct_style_module_count: usize,
    pub missing_style_document_edge_count: usize,
    pub composed_edge_count: usize,
    pub imported_composed_edge_count: usize,
    pub global_composed_edge_count: usize,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ValueDomainExplanationEvidenceV0 {
    pub status: &'static str,
    pub expression_count: usize,
    pub exact_expression_count: usize,
    pub finite_value_expression_count: usize,
    pub constrained_expression_count: usize,
    pub unknown_expression_count: usize,
    pub finite_value_count: usize,
    pub derivation_count: usize,
    pub derivation_step_count: usize,
    pub value_domain_kind_counts: BTreeMap<String, usize>,
    pub constraint_kind_counts: BTreeMap<String, usize>,
    pub derivation_product_counts: BTreeMap<String, usize>,
    pub derivation_reduced_kind_counts: BTreeMap<String, usize>,
    pub derivation_operation_counts: BTreeMap<String, usize>,
}

pub fn summarize_source_input_evidence(
    input: &EngineInputV2,
) -> SourceInputPromotionEvidenceSummaryV0 {
    let reference_site_identity = summarize_reference_site_identity(input);
    let certainty_reason = summarize_certainty_reason(input);
    let binding_origin = summarize_binding_origin(input);
    let style_module_edge = summarize_style_module_edge(input);
    let value_domain_explanation = summarize_value_domain_explanation(input);
    let mut blocking_gaps = Vec::new();

    if reference_site_identity.status == "gap" {
        blocking_gaps.push("referenceSiteIdentity");
    }
    if certainty_reason.status == "gap" {
        blocking_gaps.push("certaintyReason");
    }
    if binding_origin.status == "gap" {
        blocking_gaps.push("bindingOrigin");
    }
    if style_module_edge.status == "gap" {
        blocking_gaps.push("styleModuleEdge");
    }
    if value_domain_explanation.status == "gap" {
        blocking_gaps.push("valueDomainExplanation");
    }

    SourceInputPromotionEvidenceSummaryV0 {
        schema_version: "0",
        product: "omena-semantic.source-input-evidence",
        input_version: input.version.clone(),
        reference_site_identity,
        certainty_reason,
        binding_origin,
        style_module_edge,
        value_domain_explanation,
        blocking_gaps,
        next_priorities: Vec::new(),
    }
}

fn summarize_reference_site_identity(input: &EngineInputV2) -> ReferenceSiteIdentityEvidenceV0 {
    let selector_usage = summarize_selector_usage_evaluator_candidates_input(input);
    let selector_count = selector_usage.results.len();
    let mut reference_site_count = 0usize;
    let mut direct_reference_site_count = 0usize;
    let mut expanded_reference_site_count = 0usize;
    let mut style_dependency_reference_site_count = 0usize;
    let mut editable_direct_site_count = 0usize;
    let mut reference_kind_counts = BTreeMap::new();

    for result in selector_usage.results {
        editable_direct_site_count += result.payload.editable_direct_sites.len();
        for site in result.payload.all_sites {
            reference_site_count += 1;
            if site.expansion == "direct" {
                direct_reference_site_count += 1;
            } else {
                expanded_reference_site_count += 1;
            }
            if site.reference_kind == "styleDependency" {
                style_dependency_reference_site_count += 1;
            }
            *reference_kind_counts
                .entry(site.reference_kind)
                .or_insert(0) += 1;
        }
    }

    ReferenceSiteIdentityEvidenceV0 {
        status: if reference_site_count > 0 {
            "ready"
        } else {
            "gap"
        },
        selector_count,
        reference_site_count,
        direct_reference_site_count,
        expanded_reference_site_count,
        style_dependency_reference_site_count,
        editable_direct_site_count,
        reference_kind_counts,
    }
}

fn summarize_certainty_reason(input: &EngineInputV2) -> CertaintyReasonEvidenceV0 {
    let expression_semantics = summarize_expression_semantics_evaluator_candidates_input(input);
    let mut expression_count = 0usize;
    let mut exact_count = 0usize;
    let mut inferred_count = 0usize;
    let mut possible_count = 0usize;
    let mut missing_reason_count = 0usize;
    let mut reason_counts = BTreeMap::new();
    let mut shape_kind_counts = BTreeMap::new();
    let mut shape_label_counts = BTreeMap::new();

    for result in expression_semantics.results {
        expression_count += 1;
        let payload = result.payload;
        match payload.selector_certainty.as_str() {
            "exact" => exact_count += 1,
            "inferred" => inferred_count += 1,
            "possible" => possible_count += 1,
            _ => {}
        }
        *shape_kind_counts
            .entry(payload.selector_certainty_shape_kind.clone())
            .or_insert(0) += 1;
        *shape_label_counts
            .entry(payload.selector_certainty_shape_label.clone())
            .or_insert(0) += 1;

        if let Some(reason) = selector_certainty_reason(&payload) {
            *reason_counts.entry(reason).or_insert(0) += 1;
        } else {
            missing_reason_count += 1;
        }
    }

    CertaintyReasonEvidenceV0 {
        status: if expression_count == 0 {
            "gap"
        } else if missing_reason_count == 0 {
            "ready"
        } else {
            "partial"
        },
        expression_count,
        exact_count,
        inferred_count,
        possible_count,
        missing_reason_count,
        reason_counts,
        shape_kind_counts,
        shape_label_counts,
    }
}

fn summarize_binding_origin(input: &EngineInputV2) -> BindingOriginEvidenceV0 {
    let mut expression_count = 0usize;
    let mut direct_class_name_count = 0usize;
    let mut root_binding_count = 0usize;
    let mut access_path_count = 0usize;
    let mut access_path_segment_count = 0usize;
    let mut expression_kind_counts = BTreeMap::new();

    for source in &input.sources {
        for expression in &source.document.class_expressions {
            expression_count += 1;
            *expression_kind_counts
                .entry(expression.kind.clone())
                .or_insert(0) += 1;
            if expression.class_name.is_some() {
                direct_class_name_count += 1;
            }
            if expression.root_binding_decl_id.is_some() {
                root_binding_count += 1;
            }
            if let Some(access_path) = &expression.access_path {
                access_path_count += 1;
                access_path_segment_count += access_path.len();
            }
        }
    }

    BindingOriginEvidenceV0 {
        status: if expression_count == 0 {
            "gap"
        } else if direct_class_name_count + root_binding_count + access_path_count > 0 {
            "ready"
        } else {
            "partial"
        },
        expression_count,
        direct_class_name_count,
        root_binding_count,
        access_path_count,
        access_path_segment_count,
        expression_kind_counts,
    }
}

fn summarize_style_module_edge(input: &EngineInputV2) -> StyleModuleEdgeEvidenceV0 {
    let style_paths = input
        .styles
        .iter()
        .map(|style| style.file_path.clone())
        .collect::<BTreeSet<_>>();
    let mut referenced_style_paths = BTreeSet::new();
    let mut source_style_edge_count = 0usize;
    let mut missing_style_document_edge_count = 0usize;
    let mut composed_edge_count = 0usize;
    let mut imported_composed_edge_count = 0usize;
    let mut global_composed_edge_count = 0usize;

    for source in &input.sources {
        for expression in &source.document.class_expressions {
            source_style_edge_count += 1;
            referenced_style_paths.insert(expression.scss_module_path.clone());
            if !style_paths.contains(&expression.scss_module_path) {
                missing_style_document_edge_count += 1;
            }
        }
    }

    for style in &input.styles {
        for selector in &style.document.selectors {
            let Some(composes) = &selector.composes else {
                continue;
            };
            composed_edge_count += composes.len();
            for compose in composes {
                if compose
                    .get("fromGlobal")
                    .and_then(|value| value.as_bool())
                    .unwrap_or(false)
                {
                    global_composed_edge_count += 1;
                } else if compose
                    .get("from")
                    .and_then(|value| value.as_str())
                    .is_some()
                {
                    imported_composed_edge_count += 1;
                }
            }
        }
    }

    StyleModuleEdgeEvidenceV0 {
        status: if source_style_edge_count == 0 {
            "gap"
        } else if missing_style_document_edge_count == 0 {
            "ready"
        } else {
            "partial"
        },
        source_style_edge_count,
        distinct_style_module_count: referenced_style_paths.len(),
        missing_style_document_edge_count,
        composed_edge_count,
        imported_composed_edge_count,
        global_composed_edge_count,
    }
}

fn summarize_value_domain_explanation(input: &EngineInputV2) -> ValueDomainExplanationEvidenceV0 {
    let expression_semantics = summarize_expression_semantics_evaluator_candidates_input(input);
    let mut expression_count = 0usize;
    let mut exact_expression_count = 0usize;
    let mut finite_value_expression_count = 0usize;
    let mut constrained_expression_count = 0usize;
    let mut unknown_expression_count = 0usize;
    let mut finite_value_count = 0usize;
    let mut derivation_count = 0usize;
    let mut derivation_step_count = 0usize;
    let mut value_domain_kind_counts = BTreeMap::new();
    let mut constraint_kind_counts = BTreeMap::new();
    let mut derivation_product_counts = BTreeMap::new();
    let mut derivation_reduced_kind_counts = BTreeMap::new();
    let mut derivation_operation_counts = BTreeMap::new();

    for result in expression_semantics.results {
        expression_count += 1;
        let payload = result.payload;
        *value_domain_kind_counts
            .entry(payload.value_domain_kind.clone())
            .or_insert(0) += 1;

        match payload.value_domain_kind.as_str() {
            "exact" => exact_expression_count += 1,
            "finiteSet" => finite_value_expression_count += 1,
            "constrained" => constrained_expression_count += 1,
            "none" | "unknown" | "top" => unknown_expression_count += 1,
            _ => {}
        }

        if let Some(values) = &payload.finite_values {
            finite_value_count += values.len();
        }
        if let Some(kind) = &payload.value_constraint_kind {
            *constraint_kind_counts.entry(kind.clone()).or_insert(0) += 1;
        }

        derivation_count += 1;
        let derivation = payload.value_domain_derivation;
        *derivation_product_counts
            .entry(derivation.product.to_string())
            .or_insert(0) += 1;
        *derivation_reduced_kind_counts
            .entry(derivation.reduced_kind.to_string())
            .or_insert(0) += 1;
        for step in derivation.steps {
            derivation_step_count += 1;
            *derivation_operation_counts
                .entry(step.operation.to_string())
                .or_insert(0) += 1;
        }
    }

    ValueDomainExplanationEvidenceV0 {
        status: if expression_count == 0 {
            "gap"
        } else if exact_expression_count
            + finite_value_expression_count
            + constrained_expression_count
            > 0
            && derivation_count == expression_count
        {
            "ready"
        } else {
            "partial"
        },
        expression_count,
        exact_expression_count,
        finite_value_expression_count,
        constrained_expression_count,
        unknown_expression_count,
        finite_value_count,
        derivation_count,
        derivation_step_count,
        value_domain_kind_counts,
        constraint_kind_counts,
        derivation_product_counts,
        derivation_reduced_kind_counts,
        derivation_operation_counts,
    }
}

fn selector_certainty_reason(
    payload: &ExpressionSemanticsEvaluatorCandidatePayloadV0,
) -> Option<String> {
    match payload.selector_certainty.as_str() {
        "exact" => {
            if payload.selector_names.len() == 1 {
                Some("single selector matched".to_string())
            } else {
                Some("selector set exactly matched the proven value domain".to_string())
            }
        }
        "inferred" => match payload.selector_constraint_kind.as_deref() {
            Some("prefix" | "suffix" | "prefixSuffix" | "charInclusion" | "composite") => {
                Some("constrained runtime shape matched a bounded selector set".to_string())
            }
            _ => Some("finite candidate values matched a bounded selector set".to_string()),
        },
        "possible" => {
            if payload.selector_names.is_empty() {
                Some("no selector could be proven for this value".to_string())
            } else {
                Some("analysis could not prove an exact selector set".to_string())
            }
        }
        _ => None,
    }
}