omena-bridge 0.3.0

CME-coupled bridge crate for Omena semantic graph inputs
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
use omena_abstract_value::FactPrecision;
use serde::Serialize;

use omena_parser::ParserRangeV0;

use crate::{
    SourceClassValueUniverseEntryV0, SourceDomainClassReferenceFactV0, SourceSyntaxIndexV0,
};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StyleIntelligenceProviderMetadataV0 {
    pub provider_id: &'static str,
    pub version: &'static str,
    pub stability: &'static str,
    pub domains: &'static [&'static str],
    pub owns_surfaces: &'static [&'static str],
    pub import_targets: &'static [&'static str],
    pub utility_targets: &'static [&'static str],
    pub precision: FactPrecision,
    pub precision_backed: bool,
}

#[derive(Debug, Clone, Copy)]
pub struct StyleIntelligenceSnapshotV0<'snapshot> {
    source_syntax_index: &'snapshot SourceSyntaxIndexV0,
    graph_bindings: &'snapshot [StyleIntelligenceGraphBindingV0],
}

impl<'snapshot> StyleIntelligenceSnapshotV0<'snapshot> {
    pub const fn new(source_syntax_index: &'snapshot SourceSyntaxIndexV0) -> Self {
        Self {
            source_syntax_index,
            graph_bindings: &[],
        }
    }

    pub const fn with_graph_bindings(
        source_syntax_index: &'snapshot SourceSyntaxIndexV0,
        graph_bindings: &'snapshot [StyleIntelligenceGraphBindingV0],
    ) -> Self {
        Self {
            source_syntax_index,
            graph_bindings,
        }
    }

    pub const fn source_syntax_index(&self) -> &'snapshot SourceSyntaxIndexV0 {
        self.source_syntax_index
    }

    pub const fn graph_bindings(&self) -> &'snapshot [StyleIntelligenceGraphBindingV0] {
        self.graph_bindings
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StyleIntelligenceGraphBindingV0 {
    pub class_name: String,
    pub uri: String,
    pub range: ParserRangeV0,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StyleIntelligenceSourceContextV0 {
    pub byte_offset: usize,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StyleIntelligenceClassUniverseV0 {
    pub provider_id: &'static str,
    pub entries: Vec<SourceClassValueUniverseEntryV0>,
    pub precision: FactPrecision,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StyleIntelligenceCompletionV0 {
    pub provider_id: &'static str,
    pub label: String,
    pub precision: FactPrecision,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StyleIntelligenceHoverV0 {
    pub provider_id: &'static str,
    pub owner_name: String,
    pub domain: &'static str,
    pub axis_name: String,
    pub current_option: Option<String>,
    pub known_options: Vec<String>,
    pub known_patterns: Vec<String>,
    pub unresolved_reasons: Vec<String>,
    pub graph_bindings: Vec<StyleIntelligenceGraphBindingV0>,
    pub precision: FactPrecision,
}

pub trait StyleIntelligenceProvider: Sync {
    fn metadata(&self) -> &'static StyleIntelligenceProviderMetadataV0;

    fn class_universe(
        &self,
        snapshot: &StyleIntelligenceSnapshotV0<'_>,
    ) -> StyleIntelligenceClassUniverseV0;

    fn completions(
        &self,
        snapshot: &StyleIntelligenceSnapshotV0<'_>,
        context: StyleIntelligenceSourceContextV0,
    ) -> Vec<StyleIntelligenceCompletionV0>;

    fn hover(
        &self,
        snapshot: &StyleIntelligenceSnapshotV0<'_>,
        context: StyleIntelligenceSourceContextV0,
    ) -> Option<StyleIntelligenceHoverV0>;
}

#[derive(Debug, Clone, Copy)]
pub struct BuiltInStyleIntelligenceProviderV0 {
    metadata: &'static StyleIntelligenceProviderMetadataV0,
    pub(crate) binder_summary_visible: bool,
    pub(crate) recipe: Option<BuiltInRecipeProviderConfigV0>,
}

impl StyleIntelligenceProvider for BuiltInStyleIntelligenceProviderV0 {
    fn metadata(&self) -> &'static StyleIntelligenceProviderMetadataV0 {
        self.metadata
    }

    fn class_universe(
        &self,
        snapshot: &StyleIntelligenceSnapshotV0<'_>,
    ) -> StyleIntelligenceClassUniverseV0 {
        StyleIntelligenceClassUniverseV0 {
            provider_id: self.metadata.provider_id,
            entries: snapshot
                .source_syntax_index
                .class_value_universes
                .iter()
                .filter(|entry| entry.plugin_id == self.metadata.provider_id)
                .cloned()
                .collect(),
            precision: self.metadata.precision,
        }
    }

    fn completions(
        &self,
        snapshot: &StyleIntelligenceSnapshotV0<'_>,
        context: StyleIntelligenceSourceContextV0,
    ) -> Vec<StyleIntelligenceCompletionV0> {
        let Some(reference) = reference_at_offset(
            snapshot.source_syntax_index,
            context.byte_offset,
            self.metadata.provider_id,
        ) else {
            return Vec::new();
        };
        let universe = self.class_universe(snapshot);
        let mut labels = universe
            .entries
            .iter()
            .filter(|entry| entry_matches_reference(entry, reference))
            .flat_map(|entry| {
                let mut values = entry
                    .axes
                    .iter()
                    .filter(|axis| axis.axis_name == reference.axis_name)
                    .flat_map(|axis| axis.values.iter().cloned())
                    .collect::<Vec<_>>();
                if reference.plugin_id == "tailwind-uno-utility-domain" {
                    values.extend(entry.class_names.iter().cloned());
                    values.extend(
                        entry
                            .patterns
                            .iter()
                            .map(|pattern| pattern.completion_hint.clone()),
                    );
                }
                values
            })
            .collect::<Vec<_>>();
        labels.sort();
        labels.dedup();
        labels
            .into_iter()
            .map(|label| StyleIntelligenceCompletionV0 {
                provider_id: self.metadata.provider_id,
                label,
                precision: universe.precision,
            })
            .collect()
    }

    fn hover(
        &self,
        snapshot: &StyleIntelligenceSnapshotV0<'_>,
        context: StyleIntelligenceSourceContextV0,
    ) -> Option<StyleIntelligenceHoverV0> {
        let reference = reference_at_offset(
            snapshot.source_syntax_index,
            context.byte_offset,
            self.metadata.provider_id,
        )?;
        let known_options = self
            .completions(snapshot, context)
            .into_iter()
            .map(|item| item.label)
            .collect();
        let universe = self.class_universe(snapshot);
        let mut known_patterns = universe
            .entries
            .iter()
            .filter(|entry| entry_matches_reference(entry, reference))
            .flat_map(|entry| entry.patterns.iter().map(|pattern| pattern.source.clone()))
            .collect::<Vec<_>>();
        known_patterns.sort();
        known_patterns.dedup();
        let mut unresolved_reasons = universe
            .entries
            .iter()
            .filter(|entry| entry_matches_reference(entry, reference))
            .flat_map(|entry| entry.unresolved.iter().map(|item| item.reason.clone()))
            .collect::<Vec<_>>();
        unresolved_reasons.sort();
        unresolved_reasons.dedup();
        let current_option = reference
            .option_name
            .clone()
            .or_else(|| reference.prefix.clone());
        let graph_bindings = snapshot
            .graph_bindings
            .iter()
            .filter(|binding| current_option.as_ref() == Some(&binding.class_name))
            .cloned()
            .collect();
        Some(StyleIntelligenceHoverV0 {
            provider_id: self.metadata.provider_id,
            owner_name: reference.owner_name.clone(),
            domain: reference.domain,
            axis_name: reference.axis_name.clone(),
            current_option,
            known_options,
            known_patterns,
            unresolved_reasons,
            graph_bindings,
            precision: self.metadata.precision,
        })
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum BuiltInRecipeCallShapeV0 {
    BaseThenConfig,
    ObjectConfig,
}

#[derive(Debug, Clone, Copy)]
pub(crate) struct BuiltInRecipeProviderConfigV0 {
    pub(crate) plugin_id: &'static str,
    pub(crate) domain: &'static str,
    pub(crate) import_sources: &'static [&'static str],
    pub(crate) import_names: &'static [&'static str],
    pub(crate) call_shape: BuiltInRecipeCallShapeV0,
}

const CSS_MODULES_METADATA: StyleIntelligenceProviderMetadataV0 =
    StyleIntelligenceProviderMetadataV0 {
        provider_id: "css-modules-classnames-bind",
        version: "0",
        stability: "builtIn",
        domains: &["css-modules"],
        owns_surfaces: &[
            "styleImportRecognition",
            "classUtilityRecognition",
            "classReferenceExtraction",
            "sourceExpressionProjection",
        ],
        import_targets: &["*.module.css", "*.module.scss", "*.module.less"],
        utility_targets: &["classnames/bind", "classnames", "clsx", "clsx/lite"],
        precision: FactPrecision::Exact,
        precision_backed: true,
    };

const UTILITY_DOMAIN_METADATA: StyleIntelligenceProviderMetadataV0 =
    StyleIntelligenceProviderMetadataV0 {
        provider_id: "tailwind-uno-utility-domain",
        version: "0",
        stability: "builtIn",
        domains: &["tailwind-utilities", "unocss-utilities", "utility-classes"],
        owns_surfaces: &[
            "domainClassReferenceExtraction",
            "classUniverseProjection",
            "completionProjection",
            "graphBoundHoverProjection",
        ],
        import_targets: &[],
        utility_targets: &["class", "className", "classnames", "clsx", "clsx/lite"],
        precision: FactPrecision::Unknown,
        precision_backed: false,
    };

const VANILLA_EXTRACT_METADATA: StyleIntelligenceProviderMetadataV0 =
    StyleIntelligenceProviderMetadataV0 {
        provider_id: "vanilla-extract-recipe-domain",
        version: "0",
        stability: "builtIn",
        domains: &["vanilla-extract-recipes"],
        owns_surfaces: &["domainClassReferenceExtraction"],
        import_targets: &["@vanilla-extract/recipes"],
        utility_targets: &["recipe"],
        precision: FactPrecision::Exact,
        precision_backed: true,
    };

const VUE_STYLE_MODULE_METADATA: StyleIntelligenceProviderMetadataV0 =
    StyleIntelligenceProviderMetadataV0 {
        provider_id: "vue-style-module-domain",
        version: "0",
        stability: "builtIn",
        domains: &["vue-style-modules"],
        owns_surfaces: &["domainClassReferenceExtraction"],
        import_targets: &["*.vue"],
        utility_targets: &["useCssModule"],
        precision: FactPrecision::Exact,
        precision_backed: true,
    };

const CVA_RECIPE_METADATA: StyleIntelligenceProviderMetadataV0 =
    StyleIntelligenceProviderMetadataV0 {
        provider_id: "cva-recipe-domain",
        version: "0",
        stability: "builtIn",
        domains: &["cva-recipe"],
        owns_surfaces: &["domainClassReferenceExtraction"],
        import_targets: &["class-variance-authority", "cva"],
        utility_targets: &["cva"],
        precision: FactPrecision::Exact,
        precision_backed: true,
    };

const VANILLA_EXTRACT_RECIPE_CONFIG: BuiltInRecipeProviderConfigV0 =
    BuiltInRecipeProviderConfigV0 {
        plugin_id: "vanilla-extract-recipe-domain",
        domain: "vanilla-extract-recipe",
        import_sources: &["@vanilla-extract/recipes"],
        import_names: &["recipe"],
        call_shape: BuiltInRecipeCallShapeV0::ObjectConfig,
    };

const CVA_RECIPE_CONFIG: BuiltInRecipeProviderConfigV0 = BuiltInRecipeProviderConfigV0 {
    plugin_id: "cva-recipe-domain",
    domain: "cva-recipe",
    import_sources: &["class-variance-authority", "cva"],
    import_names: &["cva"],
    call_shape: BuiltInRecipeCallShapeV0::BaseThenConfig,
};

const BUILT_IN_STYLE_INTELLIGENCE_PROVIDERS: [BuiltInStyleIntelligenceProviderV0; 5] = [
    BuiltInStyleIntelligenceProviderV0 {
        metadata: &CSS_MODULES_METADATA,
        binder_summary_visible: true,
        recipe: None,
    },
    BuiltInStyleIntelligenceProviderV0 {
        metadata: &UTILITY_DOMAIN_METADATA,
        binder_summary_visible: true,
        recipe: None,
    },
    BuiltInStyleIntelligenceProviderV0 {
        metadata: &VANILLA_EXTRACT_METADATA,
        binder_summary_visible: true,
        recipe: Some(VANILLA_EXTRACT_RECIPE_CONFIG),
    },
    BuiltInStyleIntelligenceProviderV0 {
        metadata: &VUE_STYLE_MODULE_METADATA,
        binder_summary_visible: true,
        recipe: None,
    },
    BuiltInStyleIntelligenceProviderV0 {
        metadata: &CVA_RECIPE_METADATA,
        binder_summary_visible: false,
        recipe: Some(CVA_RECIPE_CONFIG),
    },
];

pub fn built_in_style_intelligence_providers() -> &'static [BuiltInStyleIntelligenceProviderV0] {
    &BUILT_IN_STYLE_INTELLIGENCE_PROVIDERS
}

pub fn built_in_style_intelligence_provider(
    provider_id: &str,
) -> Option<&'static BuiltInStyleIntelligenceProviderV0> {
    BUILT_IN_STYLE_INTELLIGENCE_PROVIDERS
        .iter()
        .find(|provider| provider.metadata.provider_id == provider_id)
}

pub(crate) fn built_in_recipe_provider_configs() -> Vec<BuiltInRecipeProviderConfigV0> {
    let mut configs = BUILT_IN_STYLE_INTELLIGENCE_PROVIDERS
        .iter()
        .filter_map(|provider| provider.recipe)
        .collect::<Vec<_>>();
    configs.sort_by_key(|config| match config.plugin_id {
        "cva-recipe-domain" => 0,
        _ => 1,
    });
    configs
}

pub fn style_intelligence_completions_at_offset(
    snapshot: &StyleIntelligenceSnapshotV0<'_>,
    byte_offset: usize,
) -> Vec<StyleIntelligenceCompletionV0> {
    let Some(reference) = snapshot
        .source_syntax_index
        .domain_class_references
        .iter()
        .find(|reference| {
            byte_offset >= reference.byte_span.start && byte_offset <= reference.byte_span.end
        })
    else {
        return Vec::new();
    };
    built_in_style_intelligence_provider(reference.plugin_id).map_or_else(Vec::new, |provider| {
        provider.completions(snapshot, StyleIntelligenceSourceContextV0 { byte_offset })
    })
}

pub fn style_intelligence_hover_at_offset(
    snapshot: &StyleIntelligenceSnapshotV0<'_>,
    byte_offset: usize,
) -> Option<StyleIntelligenceHoverV0> {
    let reference = snapshot
        .source_syntax_index
        .domain_class_references
        .iter()
        .find(|reference| {
            byte_offset >= reference.byte_span.start && byte_offset <= reference.byte_span.end
        })?;
    built_in_style_intelligence_provider(reference.plugin_id)?
        .hover(snapshot, StyleIntelligenceSourceContextV0 { byte_offset })
}

fn reference_at_offset<'snapshot>(
    index: &'snapshot SourceSyntaxIndexV0,
    byte_offset: usize,
    provider_id: &str,
) -> Option<&'snapshot SourceDomainClassReferenceFactV0> {
    index.domain_class_references.iter().find(|reference| {
        reference.plugin_id == provider_id
            && byte_offset >= reference.byte_span.start
            && byte_offset <= reference.byte_span.end
    })
}

fn entry_matches_reference(
    entry: &SourceClassValueUniverseEntryV0,
    reference: &SourceDomainClassReferenceFactV0,
) -> bool {
    entry.owner_name == reference.owner_name
        && (entry.domain == reference.domain
            || reference.plugin_id == "tailwind-uno-utility-domain")
}

#[cfg(test)]
mod tests {
    use omena_abstract_value::FactPrecision;
    use std::path::Path;

    use super::*;
    use crate::{
        append_omena_bridge_utility_class_intelligence, summarize_omena_bridge_source_syntax_index,
        summarize_omena_bridge_utility_class_intelligence_for_config,
    };

    #[test]
    fn provider_registry_supersedes_binder_and_recipe_catalogs() -> Result<(), &'static str> {
        let providers = built_in_style_intelligence_providers();
        assert_eq!(providers.len(), 5);
        assert_eq!(
            providers
                .iter()
                .filter(|provider| provider.binder_summary_visible)
                .count(),
            4
        );
        let utility = built_in_style_intelligence_provider("tailwind-uno-utility-domain")
            .ok_or("utility provider should be registered")?;
        assert_eq!(utility.metadata.precision, FactPrecision::Unknown);
        assert!(!utility.metadata.precision_backed);
        assert!(
            providers
                .iter()
                .filter(|provider| {
                    provider.metadata.provider_id != "tailwind-uno-utility-domain"
                })
                .all(|provider| provider.metadata.precision_backed)
        );
        assert!(built_in_style_intelligence_provider("cva-recipe-domain").is_some());
        Ok(())
    }

    #[test]
    fn provider_projects_recipe_completions_and_hover_from_source_facts() -> Result<(), &'static str>
    {
        let source = r#"import { cva } from "class-variance-authority";
const button = cva("btn", { variants: { intent: { primary: "a", secondary: "b" } } });
const value = button({ intent: "pri" });"#;
        let index = summarize_omena_bridge_source_syntax_index(source, Vec::new(), Vec::new());
        let reference = index
            .domain_class_references
            .first()
            .ok_or("CVA reference should be indexed")?;
        let snapshot = StyleIntelligenceSnapshotV0::new(&index);
        let completions =
            style_intelligence_completions_at_offset(&snapshot, reference.byte_span.start);
        assert_eq!(
            completions
                .iter()
                .map(|item| item.label.as_str())
                .collect::<Vec<_>>(),
            vec!["primary", "secondary"]
        );
        assert!(
            completions
                .iter()
                .all(|item| item.precision == FactPrecision::Exact)
        );

        let hover = style_intelligence_hover_at_offset(&snapshot, reference.byte_span.start)
            .ok_or("CVA hover should be projected")?;
        assert_eq!(hover.provider_id, "cva-recipe-domain");
        assert_eq!(hover.known_options, vec!["primary", "secondary"]);
        assert_eq!(hover.precision, FactPrecision::Exact);
        Ok(())
    }

    #[test]
    fn utility_provider_projects_patterns_and_graph_bindings_from_shared_facts()
    -> Result<(), &'static str> {
        let source = r#"export const Card = () => <div className="bg-brand" />;"#;
        let mut index = summarize_omena_bridge_source_syntax_index(source, Vec::new(), Vec::new());
        let report = summarize_omena_bridge_utility_class_intelligence_for_config(
            Path::new("tailwind.config.ts"),
            r##"export default { theme: { extend: { colors: { brand: "#123" } } } }"##,
        );
        append_omena_bridge_utility_class_intelligence(&mut index, source, &report);
        let reference = index
            .domain_class_references
            .iter()
            .find(|reference| reference.plugin_id == "tailwind-uno-utility-domain")
            .ok_or("missing utility reference")?;
        let graph_bindings = vec![StyleIntelligenceGraphBindingV0 {
            class_name: "bg-brand".to_string(),
            uri: "file:///workspace/theme.css".to_string(),
            range: ParserRangeV0 {
                start: omena_parser::ParserPositionV0 {
                    line: 2,
                    character: 0,
                },
                end: omena_parser::ParserPositionV0 {
                    line: 2,
                    character: 9,
                },
            },
        }];
        let snapshot = StyleIntelligenceSnapshotV0::with_graph_bindings(&index, &graph_bindings);
        let completions =
            style_intelligence_completions_at_offset(&snapshot, reference.byte_span.start);
        assert!(completions.iter().any(|item| item.label == "bg-brand"));
        assert!(completions.iter().any(|item| item.label == "bg-[...]"));
        let hover = style_intelligence_hover_at_offset(&snapshot, reference.byte_span.start)
            .ok_or("missing utility hover")?;
        assert_eq!(hover.current_option.as_deref(), Some("bg-brand"));
        assert_eq!(hover.graph_bindings, graph_bindings);
        assert!(
            hover
                .known_patterns
                .iter()
                .any(|pattern| pattern == "bg-[<value>]")
        );
        Ok(())
    }
}