Skip to main content

codeint_model/
lib.rs

1#![forbid(unsafe_code)]
2
3use std::borrow::Borrow;
4use std::collections::btree_map::Entry;
5use std::collections::{BTreeMap, HashSet};
6use std::fmt;
7
8pub mod frameworks;
9mod metric;
10mod runtime_imports;
11pub mod scan;
12mod source_set;
13#[cfg(test)]
14mod tests;
15mod tooling;
16mod workspace;
17
18mod bindings {
19    wit_bindgen::generate!({
20        world: "language-plugin",
21        path: "wit",
22        additional_derives: [PartialEq, Eq],
23        additional_derives_ignore: ["reference-range", "framework-profile-result"],
24    });
25}
26
27pub use bindings::exports::codeint::plugin::language;
28pub use language::{
29    DeclaredDep, DepKind, DependencyManifestOwner, FileDiagnostic, FileHazards, FileModel,
30    FileScopeArtifact, FrameworkProfileResult, FrameworkProfileSelection, FunctionCoverage,
31    HazardLine, Manifest, ManifestAnalysis, PackageDependency, PackageFrameworkProfiles,
32    ReferenceRange, ScopeAnalysis, ScopeSummary, SourceSet, SummaryField, Token, TokenKind,
33};
34pub use metric::{
35    ExternalFinding, ExternalMetricMeasurement, Metric, MetricCapability, MetricDescriptor,
36    MetricKind, MetricPlugin, MetricPluginError, MetricScope, NewFindingsRule,
37    STRUCTURAL_REPORT_KEYS, is_reserved_report_key,
38};
39pub use runtime_imports::{
40    ImportResolution, ResolveError, RuntimeImport, choose_manifests,
41    is_valid_external_package_name, resolve_runtime_imports,
42};
43pub use source_set::{
44    STANDARD_GENERATED_MARKERS, contains_ascii_ignore_case, has_any_ascii_marker, has_folder_named,
45    has_generated_header_marker, has_generated_header_marker_with_extra, path_file_name,
46    settle_source_set,
47};
48pub use tooling::UniversalToolingPaths;
49pub use workspace::{Package, SkippedManifest, Workspace, WorkspaceError};
50
51pub fn token_text_hash(text: &str) -> u64 {
52    StableHasher::new().write_bytes(text.as_bytes()).finish()
53}
54
55#[derive(Clone, Copy, Debug)]
56pub struct StableHasher(u64);
57
58impl StableHasher {
59    const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
60    const FNV_PRIME: u64 = 0x0100_0000_01b3;
61
62    pub fn new() -> StableHasher {
63        StableHasher(StableHasher::FNV_OFFSET_BASIS)
64    }
65
66    pub fn write_bytes(self, bytes: &[u8]) -> StableHasher {
67        StableHasher(bytes.iter().fold(self.0, |hash, byte| {
68            (hash ^ u64::from(*byte)).wrapping_mul(StableHasher::FNV_PRIME)
69        }))
70    }
71
72    pub fn write_u64(self, value: u64) -> StableHasher {
73        self.write_bytes(&value.to_le_bytes())
74    }
75
76    pub fn finish(self) -> u64 {
77        self.0
78    }
79}
80
81impl Default for StableHasher {
82    fn default() -> StableHasher {
83        StableHasher::new()
84    }
85}
86
87#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
88pub struct RepoPath(String);
89
90#[derive(Debug, thiserror::Error)]
91#[error("{path:?} is not a repository-relative path with forward slashes")]
92pub struct InvalidRepoPath {
93    path: String,
94}
95
96impl RepoPath {
97    pub fn new(path: impl Into<String>) -> Result<RepoPath, InvalidRepoPath> {
98        let path = path.into();
99        let is_relative_with_forward_slashes = !path.contains('\\')
100            && path
101                .split('/')
102                .all(|segment| !matches!(segment, "" | "." | ".."));
103        if is_relative_with_forward_slashes {
104            Ok(RepoPath(path))
105        } else {
106            Err(InvalidRepoPath { path })
107        }
108    }
109
110    pub fn as_str(&self) -> &str {
111        &self.0
112    }
113
114    pub fn file_name(&self) -> &str {
115        path_file_name(&self.0)
116    }
117
118    pub fn extension(&self) -> Option<&str> {
119        match self.file_name().rsplit_once('.') {
120            Some((stem, extension)) if !stem.is_empty() => Some(extension),
121            _ => None,
122        }
123    }
124}
125
126impl Borrow<str> for RepoPath {
127    fn borrow(&self) -> &str {
128        &self.0
129    }
130}
131
132impl AsRef<str> for RepoPath {
133    fn as_ref(&self) -> &str {
134        &self.0
135    }
136}
137
138impl fmt::Display for RepoPath {
139    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
140        formatter.write_str(&self.0)
141    }
142}
143
144#[derive(Clone, Debug, PartialEq, Eq)]
145pub struct SourceFile {
146    pub path: RepoPath,
147    pub model: FileModel,
148}
149
150#[derive(Clone, Debug, PartialEq, Eq)]
151pub struct SkippedFile {
152    pub path: RepoPath,
153    pub reason: String,
154}
155
156#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
157pub struct DependencyManifest {
158    pub package_root: String,
159    pub path: RepoPath,
160}
161
162#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
163pub struct ManifestUsedDep {
164    pub package_root: String,
165    pub name: String,
166}
167
168#[derive(Clone, Debug, PartialEq, Eq)]
169pub struct LanguageFacts {
170    pub language: String,
171    pub has_coverage: bool,
172    pub has_hazard_rules: bool,
173    pub has_imports: bool,
174}
175
176#[derive(Clone, Debug, Default, PartialEq, Eq)]
177pub struct CodeModel {
178    pub files: Vec<SourceFile>,
179    pub skipped: Vec<SkippedFile>,
180    pub declaration_only: Vec<RepoPath>,
181    pub workspace: Workspace,
182    pub runtime_imports: Vec<RuntimeImport>,
183    pub declared_dependencies: Vec<DeclaredDep>,
184    pub dependency_manifests: Vec<DependencyManifest>,
185    pub manifest_used_dependencies: Vec<ManifestUsedDep>,
186    pub root_dependency_inheritance: Vec<String>,
187    pub languages: Vec<LanguageFacts>,
188}
189
190#[derive(Clone, Debug, PartialEq, Eq)]
191pub struct SourceSetModel {
192    pub source_set: SourceSet,
193    pub files: Vec<SourceFile>,
194    pub workspace: Workspace,
195    pub runtime_imports: Vec<RuntimeImport>,
196    pub languages: Vec<LanguageFacts>,
197}
198
199impl Default for SourceSetModel {
200    fn default() -> SourceSetModel {
201        SourceSetModel::empty(SourceSet::Production)
202    }
203}
204
205impl SourceSetModel {
206    pub fn empty(source_set: SourceSet) -> SourceSetModel {
207        SourceSetModel {
208            source_set,
209            files: Vec::new(),
210            workspace: Workspace::default(),
211            runtime_imports: Vec::new(),
212            languages: Vec::new(),
213        }
214    }
215
216    pub fn merge(
217        source_set: SourceSet,
218        models: impl IntoIterator<Item = SourceSetModel>,
219    ) -> SourceSetModel {
220        let mut merged = SourceSetModel::empty(source_set);
221        let mut languages: BTreeMap<String, LanguageFacts> = BTreeMap::new();
222        for model in models {
223            merged.files.extend(model.files);
224            merged.runtime_imports.extend(model.runtime_imports);
225            merged.workspace.join(model.workspace);
226            merge_language_facts(&mut languages, model.languages);
227        }
228        merged
229            .files
230            .sort_by(|left, right| left.path.cmp(&right.path));
231        merged.languages = languages.into_values().collect();
232        merged
233    }
234
235    pub fn to_code_model(&self) -> CodeModel {
236        CodeModel {
237            files: self.files.clone(),
238            workspace: self.workspace.clone(),
239            runtime_imports: self.runtime_imports.clone(),
240            languages: self.languages.clone(),
241            ..CodeModel::default()
242        }
243    }
244}
245
246#[derive(Clone, Debug, PartialEq, Eq)]
247pub struct SourceSets {
248    production: SourceSetModel,
249    test: SourceSetModel,
250    generated: SourceSetModel,
251    vendored: SourceSetModel,
252}
253
254impl Default for SourceSets {
255    fn default() -> SourceSets {
256        SourceSets {
257            production: SourceSetModel::empty(SourceSet::Production),
258            test: SourceSetModel::empty(SourceSet::Test),
259            generated: SourceSetModel::empty(SourceSet::Generated),
260            vendored: SourceSetModel::empty(SourceSet::Vendored),
261        }
262    }
263}
264
265fn merge_language_facts(
266    target: &mut BTreeMap<String, LanguageFacts>,
267    incoming: impl IntoIterator<Item = LanguageFacts>,
268) {
269    for facts in incoming {
270        target
271            .entry(facts.language.clone())
272            .and_modify(|existing| {
273                existing.has_coverage |= facts.has_coverage;
274                existing.has_hazard_rules |= facts.has_hazard_rules;
275                existing.has_imports |= facts.has_imports;
276            })
277            .or_insert(facts);
278    }
279}
280
281impl CodeModel {
282    pub fn merge(models: impl IntoIterator<Item = CodeModel>) -> CodeModel {
283        let mut merged = CodeModel::default();
284        let mut languages: BTreeMap<String, LanguageFacts> = BTreeMap::new();
285        for model in models {
286            merged.files.extend(model.files);
287            merged.skipped.extend(model.skipped);
288            merged.declaration_only.extend(model.declaration_only);
289            merged.runtime_imports.extend(model.runtime_imports);
290            merged.workspace.join(model.workspace);
291            merged
292                .declared_dependencies
293                .extend(model.declared_dependencies);
294            merged
295                .dependency_manifests
296                .extend(model.dependency_manifests);
297            merged
298                .manifest_used_dependencies
299                .extend(model.manifest_used_dependencies);
300            merged
301                .root_dependency_inheritance
302                .extend(model.root_dependency_inheritance);
303            merge_language_facts(&mut languages, model.languages);
304        }
305        merged
306            .files
307            .sort_by(|left, right| left.path.cmp(&right.path));
308        merged
309            .skipped
310            .sort_by(|left, right| left.path.cmp(&right.path));
311        merged.declaration_only.sort();
312        merged.dependency_manifests.sort();
313        merged.dependency_manifests.dedup();
314        merged.manifest_used_dependencies.sort();
315        merged.manifest_used_dependencies.dedup();
316        merged.root_dependency_inheritance.sort();
317        merged.root_dependency_inheritance.dedup();
318        merged.languages = languages.into_values().collect();
319        merged
320    }
321
322    pub fn into_source_sets(self) -> SourceSets {
323        let source_set_of_importer: BTreeMap<RepoPath, SourceSet> = self
324            .files
325            .iter()
326            .map(|file| (file.path.clone(), file.model.source_set))
327            .collect();
328        let mut source_sets = SourceSets::default();
329        for source_set in [
330            &mut source_sets.production,
331            &mut source_sets.test,
332            &mut source_sets.generated,
333            &mut source_sets.vendored,
334        ] {
335            source_set.workspace = self.workspace.clone();
336            source_set.languages = self.languages.clone();
337        }
338        for file in self.files {
339            source_sets.get_mut(file.model.source_set).files.push(file);
340        }
341        for import in self.runtime_imports {
342            if let Some(&source_set) = source_set_of_importer.get(&import.importer) {
343                source_sets.get_mut(source_set).runtime_imports.push(import);
344            }
345        }
346        source_sets
347    }
348
349    pub fn is_tooling_file(&self, file: &SourceFile) -> bool {
350        file.model.is_tooling_file
351            || UniversalToolingPaths::from_model(self).is_universal_tooling_path(&file.path)
352    }
353
354    pub fn is_tooling_path(&self, path: &RepoPath) -> bool {
355        self.files
356            .iter()
357            .find(|file| &file.path == path)
358            .is_some_and(|file| file.model.is_tooling_file)
359            || UniversalToolingPaths::from_model(self).is_universal_tooling_path(path)
360    }
361}
362
363impl SourceSets {
364    pub fn get(&self, source_set: SourceSet) -> &SourceSetModel {
365        match source_set {
366            SourceSet::Production => &self.production,
367            SourceSet::Test => &self.test,
368            SourceSet::Generated => &self.generated,
369            SourceSet::Vendored => &self.vendored,
370        }
371    }
372
373    fn get_mut(&mut self, source_set: SourceSet) -> &mut SourceSetModel {
374        match source_set {
375            SourceSet::Production => &mut self.production,
376            SourceSet::Test => &mut self.test,
377            SourceSet::Generated => &mut self.generated,
378            SourceSet::Vendored => &mut self.vendored,
379        }
380    }
381
382    pub fn merge(sets: impl IntoIterator<Item = SourceSets>) -> SourceSets {
383        let mut production = Vec::new();
384        let mut test = Vec::new();
385        let mut generated = Vec::new();
386        let mut vendored = Vec::new();
387        for set in sets {
388            production.push(set.production);
389            test.push(set.test);
390            generated.push(set.generated);
391            vendored.push(set.vendored);
392        }
393        SourceSets {
394            production: SourceSetModel::merge(SourceSet::Production, production),
395            test: SourceSetModel::merge(SourceSet::Test, test),
396            generated: SourceSetModel::merge(SourceSet::Generated, generated),
397            vendored: SourceSetModel::merge(SourceSet::Vendored, vendored),
398        }
399    }
400
401    pub fn iter(&self) -> std::array::IntoIter<(SourceSet, &SourceSetModel), 4> {
402        [
403            SourceSet::Production,
404            SourceSet::Test,
405            SourceSet::Generated,
406            SourceSet::Vendored,
407        ]
408        .map(|source_set| (source_set, self.get(source_set)))
409        .into_iter()
410    }
411}
412
413#[derive(Debug, thiserror::Error)]
414pub enum LowerError {
415    #[error("cannot parse: {message}")]
416    Unparsable { message: String },
417    #[error("no Language plugin rule covers this file: {message}")]
418    UnsupportedFile { message: String },
419    #[error("the file has more source lines than the Code model can hold")]
420    TooLarge,
421    #[error("the file only declares types and holds no code to measure")]
422    DeclarationOnly,
423    #[error("Plugin {plugin:?} exceeded its memory cap of {memory_mb} MiB")]
424    MemoryLimitExceeded { plugin: String, memory_mb: u64 },
425    #[error("Plugin {plugin:?} exceeded its time limit of {timeout_ms} ms")]
426    TimeLimitExceeded { plugin: String, timeout_ms: u64 },
427    #[error(transparent)]
428    Contract(#[from] LanguagePluginError),
429}
430
431impl From<language::LowerError> for LowerError {
432    fn from(error: language::LowerError) -> LowerError {
433        match error {
434            language::LowerError::Unparsable(message) => LowerError::Unparsable { message },
435            language::LowerError::UnsupportedFile(message) => {
436                LowerError::UnsupportedFile { message }
437            }
438            language::LowerError::TooLarge => LowerError::TooLarge,
439            language::LowerError::DeclarationOnly => LowerError::DeclarationOnly,
440        }
441    }
442}
443
444impl ReferenceRange {
445    pub fn is_stale_for(&self, current_metric_version: u32) -> bool {
446        self.metric_version != current_metric_version
447    }
448}
449
450#[derive(Clone, Debug, Default)]
451pub struct ReferenceRanges {
452    by_metric: BTreeMap<String, ReferenceRange>,
453}
454
455#[derive(Debug, thiserror::Error)]
456pub enum InvalidReferenceRange {
457    #[error("the Language plugin supplies more than one Reference range for {metric}")]
458    Duplicate { metric: String },
459    #[error(
460        "the Reference range for {metric} runs from {low} to {high}, but a Reference range runs from a lower to a higher ratio between 0 and 1"
461    )]
462    Bounds { metric: String, low: f64, high: f64 },
463}
464
465impl ReferenceRanges {
466    pub fn new(ranges: Vec<ReferenceRange>) -> Result<ReferenceRanges, InvalidReferenceRange> {
467        let mut by_metric = BTreeMap::new();
468        for range in ranges {
469            if !(0.0 <= range.low && range.low <= range.high && range.high <= 1.0) {
470                return Err(InvalidReferenceRange::Bounds {
471                    metric: range.metric,
472                    low: range.low,
473                    high: range.high,
474                });
475            }
476            match by_metric.entry(range.metric.clone()) {
477                Entry::Occupied(_) => {
478                    return Err(InvalidReferenceRange::Duplicate {
479                        metric: range.metric,
480                    });
481                }
482                Entry::Vacant(vacant) => {
483                    vacant.insert(range);
484                }
485            }
486        }
487        Ok(ReferenceRanges { by_metric })
488    }
489
490    pub fn for_metric(&self, metric: &str) -> Option<&ReferenceRange> {
491        self.by_metric.get(metric)
492    }
493
494    pub fn iter(&self) -> impl Iterator<Item = &ReferenceRange> {
495        self.by_metric.values()
496    }
497}
498
499#[derive(Debug, thiserror::Error)]
500pub enum LanguagePluginError {
501    #[error("the Language plugin returned an invalid entry point path {path:?}")]
502    InvalidEntryPointPath { path: String },
503    #[error(
504        "the Language plugin returned entry point {path:?}, which is not a file of the repository"
505    )]
506    UnknownEntryPoint { path: String },
507    #[error("the Language plugin returned an invalid generated path {path:?}")]
508    InvalidGeneratedPath { path: String },
509    #[error(
510        "the Language plugin returned generated path {path:?}, which is not a file of the package"
511    )]
512    UnknownGeneratedPath { path: String },
513    #[error("the Language plugin returned an unlisted Framework profile {profile:?}")]
514    UnlistedFrameworkProfile { profile: String },
515    #[error("the Language plugin failed to resolve Framework profiles: {message}")]
516    FrameworkProfile { message: String },
517    #[error("the Language plugin returned an invalid Framework profile Reference range")]
518    InvalidFrameworkReferenceRange(#[from] InvalidReferenceRange),
519    #[error("the Language plugin returned an invalid Reference range")]
520    InvalidReferenceRange(#[source] InvalidReferenceRange),
521    #[error(
522        "the Language plugin declared a dependency with an invalid package root {package_root:?}"
523    )]
524    InvalidDependencyPackageRoot { package_root: String },
525    #[error(
526        "the Language plugin declared a dependency with an empty name in package root {package_root:?}"
527    )]
528    EmptyDependencyName { package_root: String },
529    #[error("the Language plugin returned an invalid workspace package root {path:?}")]
530    InvalidWorkspacePackageRoot { path: String },
531    #[error(
532        "the Language plugin reported invalid manifest {path:?} which was not passed in: {message}"
533    )]
534    UnknownInvalidManifest { path: String, message: String },
535    #[error("the Language plugin reported duplicate invalid manifest {path:?}")]
536    DuplicateInvalidManifest { path: String },
537    #[error("the Language plugin returned an invalid dependency manifest path {path:?}")]
538    InvalidDependencyManifestPath { path: String },
539    #[error("the Language plugin returned dependency manifest {path:?}, which was not passed in")]
540    UnknownDependencyManifest { path: String },
541    #[error(
542        "the Language plugin reported manifest {path:?} as both invalid and a dependency manifest"
543    )]
544    InvalidAndDependencyManifest { path: String },
545    #[error(
546        "the Language plugin returned an invalid root-dependency inheritance package root {package_root:?}"
547    )]
548    InvalidInheritancePackageRoot { package_root: String },
549    #[error("Plugin {plugin:?} exceeded its time limit of {timeout_ms} ms")]
550    TimeLimitExceeded { plugin: String, timeout_ms: u64 },
551    #[error("Plugin {plugin:?} exceeded its memory cap of {memory_mb} MiB")]
552    MemoryLimitExceeded { plugin: String, memory_mb: u64 },
553    #[error("Language plugin {plugin:?} failed during {call}: {reason}")]
554    Call {
555        plugin: String,
556        call: &'static str,
557        reason: String,
558    },
559    #[error(
560        "Language plugin {plugin:?} returned Hazard line {line} in {path}, which is outside the file's {line_count} lines"
561    )]
562    HazardLineOutOfRange {
563        plugin: String,
564        path: RepoPath,
565        line: u32,
566        line_count: usize,
567    },
568    #[error(
569        "Language plugin {plugin:?} returned a Hazard line with unlisted rule {rule:?} in {path}"
570    )]
571    UnlistedHazardRule {
572        plugin: String,
573        path: RepoPath,
574        rule: String,
575    },
576    #[error(
577        "Language plugin {plugin:?} returned Flagged line {line} in {path}, which is outside the file's {line_count} lines"
578    )]
579    FlaggedLineOutOfRange {
580        plugin: String,
581        path: RepoPath,
582        line: u32,
583        line_count: usize,
584    },
585    #[error(
586        "Language plugin {plugin:?} returned a Flagged line with unlisted rule {rule:?} in {path}"
587    )]
588    UnlistedFlaggedLineRule {
589        plugin: String,
590        path: RepoPath,
591        rule: String,
592    },
593    #[error("Language plugin {plugin:?} returned an invalid extra-hazards path {path:?}")]
594    InvalidScopeHazardPath { plugin: String, path: String },
595    #[error(
596        "Language plugin {plugin:?} returned extra-hazards path {path:?}, which was not in the analyzed artifacts"
597    )]
598    UnknownScopeHazardPath { plugin: String, path: String },
599    #[error("Language plugin {plugin:?} returned invalid extra Hazard line {line} in {path}")]
600    InvalidScopeHazardLine {
601        plugin: String,
602        path: RepoPath,
603        line: u32,
604    },
605    #[error("Language plugin {plugin:?} returned an invalid scope summary: {reason}")]
606    InvalidScopeSummary { plugin: String, reason: String },
607    #[error(
608        "Language plugin {plugin:?} returned a diagnostic on line {line} in {path}, which is outside the file's {line_count} lines"
609    )]
610    DiagnosticLineOutOfRange {
611        plugin: String,
612        path: RepoPath,
613        line: u32,
614        line_count: usize,
615    },
616    #[error("Language plugin {plugin:?} returned an invalid diagnostic in {path}: {reason}")]
617    InvalidDiagnostic {
618        plugin: String,
619        path: RepoPath,
620        reason: &'static str,
621    },
622}
623
624#[derive(Clone, Copy)]
625enum RuleLineKind {
626    Flagged,
627    Hazard,
628}
629
630trait RuleLine {
631    const KIND: RuleLineKind;
632    fn line(&self) -> u32;
633    fn rule(&self) -> &str;
634}
635
636impl RuleLine for language::FlaggedLine {
637    const KIND: RuleLineKind = RuleLineKind::Flagged;
638    fn line(&self) -> u32 {
639        self.line
640    }
641    fn rule(&self) -> &str {
642        &self.rule
643    }
644}
645
646impl RuleLine for HazardLine {
647    const KIND: RuleLineKind = RuleLineKind::Hazard;
648    fn line(&self) -> u32 {
649        self.line
650    }
651    fn rule(&self) -> &str {
652        &self.rule
653    }
654}
655
656fn validate_rule_lines<T: RuleLine>(
657    plugin_name: &str,
658    path: &RepoPath,
659    line_count: usize,
660    entries: &[T],
661    listed_rules: &HashSet<String>,
662) -> Result<(), LanguagePluginError> {
663    for entry in entries {
664        let line_number = usize::try_from(entry.line()).unwrap_or(usize::MAX);
665        if line_number < 1 || line_number > line_count {
666            let plugin = plugin_name.to_owned();
667            let path = path.clone();
668            let line = entry.line();
669            return Err(match T::KIND {
670                RuleLineKind::Flagged => LanguagePluginError::FlaggedLineOutOfRange {
671                    plugin,
672                    path,
673                    line,
674                    line_count,
675                },
676                RuleLineKind::Hazard => LanguagePluginError::HazardLineOutOfRange {
677                    plugin,
678                    path,
679                    line,
680                    line_count,
681                },
682            });
683        }
684    }
685    for entry in entries {
686        if !listed_rules.contains(entry.rule()) {
687            let plugin = plugin_name.to_owned();
688            let path = path.clone();
689            let rule = entry.rule().to_owned();
690            return Err(match T::KIND {
691                RuleLineKind::Flagged => {
692                    LanguagePluginError::UnlistedFlaggedLineRule { plugin, path, rule }
693                }
694                RuleLineKind::Hazard => {
695                    LanguagePluginError::UnlistedHazardRule { plugin, path, rule }
696                }
697            });
698        }
699    }
700    Ok(())
701}
702
703pub fn validate_flagged_lines(
704    plugin_name: &str,
705    path: &RepoPath,
706    line_count: usize,
707    flagged_lines: &[language::FlaggedLine],
708    listed_rules: &HashSet<String>,
709) -> Result<(), LanguagePluginError> {
710    validate_rule_lines(plugin_name, path, line_count, flagged_lines, listed_rules)
711}
712
713pub fn validate_file_diagnostics(
714    plugin_name: &str,
715    path: &RepoPath,
716    line_count: usize,
717    diagnostics: &[FileDiagnostic],
718) -> Result<(), LanguagePluginError> {
719    for diagnostic in diagnostics {
720        let line_number = usize::try_from(diagnostic.line).unwrap_or(usize::MAX);
721        if line_number < 1 || line_number > line_count {
722            return Err(LanguagePluginError::DiagnosticLineOutOfRange {
723                plugin: plugin_name.to_owned(),
724                path: path.clone(),
725                line: diagnostic.line,
726                line_count,
727            });
728        }
729        if diagnostic.kind.trim().is_empty() {
730            return Err(LanguagePluginError::InvalidDiagnostic {
731                plugin: plugin_name.to_owned(),
732                path: path.clone(),
733                reason: "diagnostic kind must not be empty",
734            });
735        }
736        if diagnostic.message.trim().is_empty() {
737            return Err(LanguagePluginError::InvalidDiagnostic {
738                plugin: plugin_name.to_owned(),
739                path: path.clone(),
740                reason: "diagnostic message must not be empty",
741            });
742        }
743    }
744    Ok(())
745}
746
747pub fn validate_scope_analysis(
748    plugin_name: &str,
749    artifact_paths: &[&str],
750    known_hazard_rules: &HashSet<String>,
751    line_counts: Option<&BTreeMap<String, usize>>,
752    analysis: ScopeAnalysis,
753) -> Result<ScopeAnalysis, LanguagePluginError> {
754    let artifact_path_set: HashSet<&str> = artifact_paths.iter().copied().collect();
755    for entry in &analysis.extra_hazards {
756        validate_scope_hazards(
757            plugin_name,
758            entry,
759            &artifact_path_set,
760            known_hazard_rules,
761            line_counts,
762        )?;
763    }
764    for summary in &analysis.summaries {
765        if summary.kind.trim().is_empty()
766            || summary
767                .fields
768                .iter()
769                .any(|field| field.key.trim().is_empty())
770        {
771            return Err(LanguagePluginError::InvalidScopeSummary {
772                plugin: plugin_name.to_owned(),
773                reason: "scope summary has an empty kind or field key".to_owned(),
774            });
775        }
776    }
777    Ok(analysis)
778}
779
780fn validate_scope_hazards(
781    plugin_name: &str,
782    entry: &FileHazards,
783    artifact_paths: &HashSet<&str>,
784    known_hazard_rules: &HashSet<String>,
785    line_counts: Option<&BTreeMap<String, usize>>,
786) -> Result<(), LanguagePluginError> {
787    let repo_path = RepoPath::new(entry.path.as_str()).map_err(|_| {
788        LanguagePluginError::InvalidScopeHazardPath {
789            plugin: plugin_name.to_owned(),
790            path: entry.path.clone(),
791        }
792    })?;
793    if !artifact_paths.contains(entry.path.as_str()) {
794        return Err(LanguagePluginError::UnknownScopeHazardPath {
795            plugin: plugin_name.to_owned(),
796            path: entry.path.clone(),
797        });
798    }
799    if let Some(counts) = line_counts {
800        let max_lines = counts.get(&entry.path).copied().unwrap_or(0);
801        return validate_hazard_lines(
802            plugin_name,
803            &repo_path,
804            max_lines,
805            &entry.hazard_lines,
806            known_hazard_rules,
807        );
808    }
809    for hazard in &entry.hazard_lines {
810        if hazard.line < 1 {
811            return Err(LanguagePluginError::InvalidScopeHazardLine {
812                plugin: plugin_name.to_owned(),
813                path: repo_path.clone(),
814                line: hazard.line,
815            });
816        }
817        if !known_hazard_rules.contains(&hazard.rule) {
818            return Err(LanguagePluginError::UnlistedHazardRule {
819                plugin: plugin_name.to_owned(),
820                path: repo_path.clone(),
821                rule: hazard.rule.clone(),
822            });
823        }
824    }
825    Ok(())
826}
827
828pub fn validate_hazard_lines(
829    plugin_name: &str,
830    path: &RepoPath,
831    line_count: usize,
832    hazard_lines: &[HazardLine],
833    listed_rules: &HashSet<String>,
834) -> Result<(), LanguagePluginError> {
835    validate_rule_lines(plugin_name, path, line_count, hazard_lines, listed_rules)
836}
837
838pub fn validate_workspace_packages(roots: Vec<String>) -> Result<Vec<RepoPath>, WorkspaceError> {
839    roots
840        .into_iter()
841        .map(|root| Ok(RepoPath::new(root)?))
842        .collect()
843}
844
845pub fn validate_declared_dependencies(
846    deps: Vec<DeclaredDep>,
847) -> Result<Vec<DeclaredDep>, LanguagePluginError> {
848    for dep in &deps {
849        if !dep.package_root.is_empty() && RepoPath::new(dep.package_root.as_str()).is_err() {
850            return Err(LanguagePluginError::InvalidDependencyPackageRoot {
851                package_root: dep.package_root.clone(),
852            });
853        }
854        if dep.name.trim().is_empty() {
855            return Err(LanguagePluginError::EmptyDependencyName {
856                package_root: dep.package_root.clone(),
857            });
858        }
859    }
860    Ok(deps)
861}
862
863pub fn validate_entry_points(
864    repository_paths: &[RepoPath],
865    entries: Vec<String>,
866) -> Result<Vec<RepoPath>, LanguagePluginError> {
867    let known: HashSet<&str> = repository_paths.iter().map(RepoPath::as_str).collect();
868    entries
869        .into_iter()
870        .map(|path| {
871            let repo_path = RepoPath::new(path.clone())
872                .map_err(|_| LanguagePluginError::InvalidEntryPointPath { path: path.clone() })?;
873            if !known.contains(repo_path.as_str()) {
874                return Err(LanguagePluginError::UnknownEntryPoint { path });
875            }
876            Ok(repo_path)
877        })
878        .collect()
879}
880
881fn validate_known_paths(
882    paths: &[String],
883    known_files: &HashSet<&str>,
884    invalid: fn(String) -> LanguagePluginError,
885    unknown: fn(String) -> LanguagePluginError,
886) -> Result<(), LanguagePluginError> {
887    for path in paths {
888        let repo_path = RepoPath::new(path.clone()).map_err(|_| invalid(path.clone()))?;
889        if !known_files.contains(repo_path.as_str()) {
890            return Err(unknown(path.clone()));
891        }
892    }
893    Ok(())
894}
895
896pub fn validate_framework_profile_result(
897    known_profiles: &[String],
898    files: &[RepoPath],
899    result: FrameworkProfileResult,
900) -> Result<FrameworkProfileResult, LanguagePluginError> {
901    let known_profile_set: HashSet<&str> = known_profiles.iter().map(String::as_str).collect();
902    for profile in &result.active_profiles {
903        if !known_profile_set.contains(profile.as_str()) {
904            return Err(LanguagePluginError::UnlistedFrameworkProfile {
905                profile: profile.clone(),
906            });
907        }
908    }
909    let known_files: HashSet<&str> = files.iter().map(RepoPath::as_str).collect();
910    validate_known_paths(
911        &result.entry_points,
912        &known_files,
913        |path| LanguagePluginError::InvalidEntryPointPath { path },
914        |path| LanguagePluginError::UnknownEntryPoint { path },
915    )?;
916    validate_known_paths(
917        &result.generated_paths,
918        &known_files,
919        |path| LanguagePluginError::InvalidGeneratedPath { path },
920        |path| LanguagePluginError::UnknownGeneratedPath { path },
921    )?;
922    let _ = ReferenceRanges::new(result.reference_ranges.clone())?;
923    Ok(result)
924}
925
926pub fn require_extension<'a>(
927    path: &'a RepoPath,
928    suffix: &str,
929    language: &str,
930) -> Result<&'a str, LowerError> {
931    let raw = path.as_str();
932    if raw.ends_with(suffix) {
933        Ok(raw)
934    } else {
935        Err(LowerError::UnsupportedFile {
936            message: format!("{raw} is not a {language} source file"),
937        })
938    }
939}
940
941pub fn empty_file_model(source_set: SourceSet) -> FileModel {
942    FileModel {
943        source_set,
944        source_lines: 0,
945        functions: Vec::new(),
946        tokens: Vec::new(),
947        flagged_lines: Vec::new(),
948        hazard_lines: Vec::new(),
949        runtime_imports: Vec::new(),
950        program_start: false,
951        is_tooling_file: false,
952        diagnostics: Vec::new(),
953        scope_artifact: None,
954    }
955}
956
957pub fn empty_manifest_analysis() -> ManifestAnalysis {
958    ManifestAnalysis {
959        workspace_packages: Vec::new(),
960        invalid_manifests: Vec::new(),
961        dependency_manifests: Vec::new(),
962        declared_dependencies: Vec::new(),
963        manifest_used_dependencies: Vec::new(),
964        root_dependency_inheritance: Vec::new(),
965    }
966}
967
968pub fn empty_scope_analysis() -> ScopeAnalysis {
969    ScopeAnalysis {
970        extra_hazards: Vec::new(),
971        summaries: Vec::new(),
972    }
973}
974
975pub fn active_profiles_for_path<'a>(
976    package_profiles: &'a [PackageFrameworkProfiles],
977    path: &str,
978) -> &'a [String] {
979    let mut best: Option<(usize, &'a [String])> = None;
980    for entry in package_profiles {
981        let matches = if entry.package_root.is_empty() {
982            true
983        } else {
984            path == entry.package_root
985                || path
986                    .strip_prefix(entry.package_root.as_str())
987                    .is_some_and(|rest| rest.starts_with('/'))
988        };
989        if matches {
990            let depth = entry.package_root.len();
991            if best.is_none_or(|(best_depth, _)| depth >= best_depth) {
992                best = Some((depth, entry.active_profiles.as_slice()));
993            }
994        }
995    }
996    best.map_or(&[], |(_, profiles)| profiles)
997}
998
999pub fn validate_manifest_analysis(
1000    manifests: &[Manifest],
1001    analysis: ManifestAnalysis,
1002) -> Result<ManifestAnalysis, LanguagePluginError> {
1003    let passed_paths: HashSet<&str> = manifests.iter().map(|m| m.path.as_str()).collect();
1004    for root in &analysis.workspace_packages {
1005        if RepoPath::new(root.as_str()).is_err() {
1006            return Err(LanguagePluginError::InvalidWorkspacePackageRoot { path: root.clone() });
1007        }
1008    }
1009    let mut seen_invalid: HashSet<&str> = HashSet::with_capacity(analysis.invalid_manifests.len());
1010    for invalid in &analysis.invalid_manifests {
1011        if !passed_paths.contains(invalid.path.as_str()) {
1012            return Err(LanguagePluginError::UnknownInvalidManifest {
1013                path: invalid.path.clone(),
1014                message: invalid.message.clone(),
1015            });
1016        }
1017        if !seen_invalid.insert(invalid.path.as_str()) {
1018            return Err(LanguagePluginError::DuplicateInvalidManifest {
1019                path: invalid.path.clone(),
1020            });
1021        }
1022    }
1023    validate_dependency_owners(&analysis.dependency_manifests, &passed_paths, &seen_invalid)?;
1024    let _ = validate_declared_dependencies(analysis.declared_dependencies.clone())?;
1025    validate_package_dependencies(&analysis.manifest_used_dependencies)?;
1026    validate_inheritance_roots(&analysis.root_dependency_inheritance)?;
1027    Ok(analysis)
1028}
1029
1030fn validate_optional_package_root(package_root: &str) -> Result<(), LanguagePluginError> {
1031    if !package_root.is_empty() && RepoPath::new(package_root).is_err() {
1032        return Err(LanguagePluginError::InvalidDependencyPackageRoot {
1033            package_root: package_root.to_owned(),
1034        });
1035    }
1036    Ok(())
1037}
1038
1039fn validate_dependency_owners(
1040    owners: &[DependencyManifestOwner],
1041    passed_paths: &HashSet<&str>,
1042    seen_invalid: &HashSet<&str>,
1043) -> Result<(), LanguagePluginError> {
1044    for owner in owners {
1045        validate_optional_package_root(&owner.package_root)?;
1046        if RepoPath::new(owner.path.as_str()).is_err() {
1047            return Err(LanguagePluginError::InvalidDependencyManifestPath {
1048                path: owner.path.clone(),
1049            });
1050        }
1051        if !passed_paths.contains(owner.path.as_str()) {
1052            return Err(LanguagePluginError::UnknownDependencyManifest {
1053                path: owner.path.clone(),
1054            });
1055        }
1056        if seen_invalid.contains(owner.path.as_str()) {
1057            return Err(LanguagePluginError::InvalidAndDependencyManifest {
1058                path: owner.path.clone(),
1059            });
1060        }
1061    }
1062    Ok(())
1063}
1064
1065fn validate_package_dependencies(deps: &[PackageDependency]) -> Result<(), LanguagePluginError> {
1066    for dep in deps {
1067        validate_optional_package_root(&dep.package_root)?;
1068        if dep.name.trim().is_empty() {
1069            return Err(LanguagePluginError::EmptyDependencyName {
1070                package_root: dep.package_root.clone(),
1071            });
1072        }
1073    }
1074    Ok(())
1075}
1076
1077fn validate_inheritance_roots(roots: &[String]) -> Result<(), LanguagePluginError> {
1078    for root in roots {
1079        if !root.is_empty() && RepoPath::new(root.as_str()).is_err() {
1080            return Err(LanguagePluginError::InvalidInheritancePackageRoot {
1081                package_root: root.clone(),
1082            });
1083        }
1084    }
1085    Ok(())
1086}
1087
1088pub fn empty_framework_profile_result() -> FrameworkProfileResult {
1089    FrameworkProfileResult {
1090        active_profiles: Vec::new(),
1091        entry_points: Vec::new(),
1092        generated_paths: Vec::new(),
1093        reference_ranges: Vec::new(),
1094        reference_range_note: None,
1095    }
1096}
1097
1098#[macro_export]
1099macro_rules! empty_v05_guest_methods {
1100    () => {
1101        fn known_dialects() -> ::std::vec::Vec<::std::string::String> {
1102            ::std::vec::Vec::new()
1103        }
1104
1105        fn flagged_line_rules() -> ::std::vec::Vec<::std::string::String> {
1106            ::std::vec::Vec::new()
1107        }
1108
1109        fn has_scope_analysis() -> bool {
1110            false
1111        }
1112
1113        fn analyze_scope(
1114            _package_root: ::std::string::String,
1115            _dialect: ::core::option::Option<::std::string::String>,
1116            _artifacts: ::std::vec::Vec<$crate::language::FileScopeArtifact>,
1117        ) -> $crate::language::ScopeAnalysis {
1118            $crate::empty_scope_analysis()
1119        }
1120    };
1121}
1122
1123#[macro_export]
1124macro_rules! empty_framework_profile_guest_methods {
1125    () => {
1126        fn known_framework_profiles() -> ::std::vec::Vec<::std::string::String> {
1127            ::std::vec::Vec::new()
1128        }
1129
1130        fn resolve_framework_profiles(
1131            _package_root: ::std::string::String,
1132            _files: ::std::vec::Vec<::std::string::String>,
1133            _manifests: ::std::vec::Vec<$crate::language::Manifest>,
1134            _selection: $crate::language::FrameworkProfileSelection,
1135        ) -> ::std::result::Result<$crate::language::FrameworkProfileResult, ::std::string::String>
1136        {
1137            ::std::result::Result::Ok($crate::empty_framework_profile_result())
1138        }
1139    };
1140}
1141
1142#[macro_export]
1143macro_rules! empty_framework_profile_plugin_methods {
1144    () => {};
1145}
1146
1147#[macro_export]
1148macro_rules! impl_builtin_language_plugin {
1149    (
1150        $plugin:ty,
1151        $extensions:expr,
1152        lower_ext($lower:path, $suffix:literal, $label:literal),
1153        $($rest:tt)*
1154    ) => {
1155        $crate::impl_builtin_language_plugin!(
1156            @build
1157            $plugin,
1158            $extensions,
1159            { lower_ext($lower, $suffix, $label) },
1160            $($rest)*
1161        );
1162    };
1163    (
1164        $plugin:ty,
1165        $extensions:expr,
1166        $lower:path,
1167        $($rest:tt)*
1168    ) => {
1169        $crate::impl_builtin_language_plugin!(
1170            @build
1171            $plugin,
1172            $extensions,
1173            { direct($lower) },
1174            $($rest)*
1175        );
1176    };
1177    (
1178        @build
1179        $plugin:ty,
1180        $extensions:expr,
1181        { $($lower_spec:tt)* },
1182        $ranges:expr,
1183        flagged_lines($flagged:expr),
1184        imports($($imports:tt)*),
1185        frameworks($($frameworks:tt)*),
1186        hazards($($hazards:tt)*) $(,)?
1187    ) => {
1188        impl $crate::LanguagePlugin for $plugin {
1189            fn extensions(&self) -> ::std::vec::Vec<::std::string::String> {
1190                $extensions
1191                    .iter()
1192                    .map(::std::string::ToString::to_string)
1193                    .collect()
1194            }
1195
1196            $crate::impl_builtin_language_plugin!(@lower $($lower_spec)*);
1197
1198            fn flagged_line_rules(&self) -> ::std::vec::Vec<::std::string::String> {
1199                $flagged.map(::std::string::ToString::to_string).collect()
1200            }
1201
1202            fn reference_ranges(
1203                &self,
1204            ) -> ::std::result::Result<$crate::ReferenceRanges, $crate::LanguagePluginError> {
1205                $crate::ReferenceRanges::new($ranges)
1206                    .map_err($crate::LanguagePluginError::InvalidReferenceRange)
1207            }
1208
1209            $crate::impl_builtin_language_plugin!(@imports $($imports)*);
1210            $crate::impl_builtin_language_plugin!(@frameworks $($frameworks)*);
1211            $crate::impl_builtin_language_plugin!(@hazards $($hazards)*);
1212        }
1213    };
1214    (@lower lower_ext($lower:path, $suffix:literal, $label:literal)) => {
1215        fn lower(
1216            &self,
1217            path: &$crate::RepoPath,
1218            text: &str,
1219            _dialect: ::core::option::Option<&str>,
1220        ) -> ::std::result::Result<$crate::FileModel, $crate::LowerError> {
1221            let raw = $crate::require_extension(path, $suffix, $label)?;
1222            $lower(raw, text)
1223        }
1224    };
1225    (@lower direct($lower:path)) => {
1226        fn lower(
1227            &self,
1228            path: &$crate::RepoPath,
1229            text: &str,
1230            dialect: ::core::option::Option<&str>,
1231        ) -> ::std::result::Result<$crate::FileModel, $crate::LowerError> {
1232            $lower(self, path, text, dialect)
1233        }
1234    };
1235    (@imports none) => {};
1236    (@imports $manifest_paths:path, $analyze_manifests:path, $resolve_imports:expr, $entry_points:path $(,)?) => {
1237        fn has_imports(&self) -> bool {
1238            true
1239        }
1240
1241        fn manifest_paths(
1242            &self,
1243            repository_paths: &[$crate::RepoPath],
1244        ) -> ::std::result::Result<::std::vec::Vec<::std::string::String>, $crate::LanguagePluginError>
1245        {
1246            ::std::result::Result::Ok($manifest_paths(repository_paths))
1247        }
1248
1249        fn analyze_manifests(
1250            &self,
1251            manifests: ::std::vec::Vec<$crate::Manifest>,
1252        ) -> ::std::result::Result<$crate::ManifestAnalysis, $crate::LanguagePluginError> {
1253            let analysis = $analyze_manifests(&manifests);
1254            $crate::validate_manifest_analysis(&manifests, analysis)
1255        }
1256
1257        fn resolve_imports(
1258            &self,
1259            repository_paths: &[$crate::RepoPath],
1260            manifests: ::std::vec::Vec<$crate::Manifest>,
1261            requests: ::std::vec::Vec<$crate::language::ImportRequest>,
1262            package_profiles: &[$crate::PackageFrameworkProfiles],
1263        ) -> ::std::result::Result<
1264            ::std::vec::Vec<$crate::language::Resolution>,
1265            $crate::LanguagePluginError,
1266        > {
1267            let resolve: fn(
1268                &[$crate::RepoPath],
1269                &[$crate::Manifest],
1270                &[$crate::language::ImportRequest],
1271                &[$crate::PackageFrameworkProfiles],
1272            ) -> ::std::vec::Vec<$crate::language::Resolution> = $resolve_imports;
1273            ::std::result::Result::Ok(resolve(
1274                repository_paths,
1275                &manifests,
1276                &requests,
1277                package_profiles,
1278            ))
1279        }
1280
1281        fn entry_points(
1282            &self,
1283            repository_paths: &[$crate::RepoPath],
1284            manifests: ::std::vec::Vec<$crate::Manifest>,
1285        ) -> ::std::result::Result<::std::vec::Vec<$crate::RepoPath>, $crate::LanguagePluginError>
1286        {
1287            $crate::validate_entry_points(repository_paths, $entry_points(repository_paths, &manifests))
1288        }
1289    };
1290    (@frameworks none) => {};
1291    (@frameworks $module:ident) => {
1292        fn known_framework_profiles(&self) -> ::std::vec::Vec<::std::string::String> {
1293            $module::known_profiles()
1294        }
1295
1296        fn resolve_framework_profiles(
1297            &self,
1298            package_root: &str,
1299            files: &[$crate::RepoPath],
1300            manifests: ::std::vec::Vec<$crate::Manifest>,
1301            selection: $crate::FrameworkProfileSelection,
1302        ) -> ::std::result::Result<$crate::FrameworkProfileResult, $crate::LanguagePluginError> {
1303            let result =
1304                $module::resolve_framework_profiles(package_root, files, &manifests, selection)
1305                    .map_err(|message| $crate::LanguagePluginError::FrameworkProfile { message })?;
1306            $crate::validate_framework_profile_result(
1307                &self.known_framework_profiles(),
1308                files,
1309                result,
1310            )
1311        }
1312    };
1313    (@hazards none) => {};
1314    (@hazards $rules:expr) => {
1315        fn has_hazard_rules(&self) -> bool {
1316            true
1317        }
1318
1319        fn hazard_rules(&self) -> ::std::vec::Vec<::std::string::String> {
1320            $rules.iter().map(|rule| (*rule).to_owned()).collect()
1321        }
1322    };
1323}
1324
1325pub trait LanguagePlugin: Sync {
1326    fn extensions(&self) -> Vec<String>;
1327
1328    fn known_dialects(&self) -> Vec<String> {
1329        Vec::new()
1330    }
1331
1332    fn lower(
1333        &self,
1334        path: &RepoPath,
1335        text: &str,
1336        dialect: Option<&str>,
1337    ) -> Result<FileModel, LowerError>;
1338
1339    fn flagged_line_rules(&self) -> Vec<String> {
1340        Vec::new()
1341    }
1342
1343    fn manifest_paths(
1344        &self,
1345        _repository_paths: &[RepoPath],
1346    ) -> Result<Vec<String>, LanguagePluginError> {
1347        Ok(Vec::new())
1348    }
1349
1350    fn analyze_manifests(
1351        &self,
1352        _manifests: Vec<Manifest>,
1353    ) -> Result<ManifestAnalysis, LanguagePluginError> {
1354        Ok(empty_manifest_analysis())
1355    }
1356
1357    fn resolve_imports(
1358        &self,
1359        _repository_paths: &[RepoPath],
1360        _manifests: Vec<Manifest>,
1361        _requests: Vec<language::ImportRequest>,
1362        _package_profiles: &[PackageFrameworkProfiles],
1363    ) -> Result<Vec<language::Resolution>, LanguagePluginError> {
1364        Ok(Vec::new())
1365    }
1366
1367    fn entry_points(
1368        &self,
1369        _repository_paths: &[RepoPath],
1370        _manifests: Vec<Manifest>,
1371    ) -> Result<Vec<RepoPath>, LanguagePluginError> {
1372        Ok(Vec::new())
1373    }
1374
1375    fn reference_ranges(&self) -> Result<ReferenceRanges, LanguagePluginError>;
1376
1377    fn known_framework_profiles(&self) -> Vec<String> {
1378        Vec::new()
1379    }
1380
1381    fn resolve_framework_profiles(
1382        &self,
1383        _package_root: &str,
1384        _files: &[RepoPath],
1385        _manifests: Vec<Manifest>,
1386        _selection: FrameworkProfileSelection,
1387    ) -> Result<FrameworkProfileResult, LanguagePluginError> {
1388        Ok(empty_framework_profile_result())
1389    }
1390
1391    fn has_hazard_rules(&self) -> bool {
1392        false
1393    }
1394
1395    fn hazard_rules(&self) -> Vec<String> {
1396        Vec::new()
1397    }
1398
1399    fn has_imports(&self) -> bool {
1400        false
1401    }
1402
1403    fn has_scope_analysis(&self) -> bool {
1404        false
1405    }
1406
1407    fn analyze_scope(
1408        &self,
1409        _package_root: &str,
1410        _dialect: Option<&str>,
1411        _artifacts: Vec<FileScopeArtifact>,
1412    ) -> Result<ScopeAnalysis, LanguagePluginError> {
1413        Ok(empty_scope_analysis())
1414    }
1415}
1416
1417impl<Plugin: language::Guest + Sync> LanguagePlugin for Plugin {
1418    fn extensions(&self) -> Vec<String> {
1419        Plugin::extensions()
1420    }
1421
1422    fn known_dialects(&self) -> Vec<String> {
1423        Plugin::known_dialects()
1424    }
1425
1426    fn lower(
1427        &self,
1428        path: &RepoPath,
1429        text: &str,
1430        dialect: Option<&str>,
1431    ) -> Result<FileModel, LowerError> {
1432        Plugin::lower(
1433            path.as_str().to_owned(),
1434            text.to_owned(),
1435            dialect.map(str::to_owned),
1436        )
1437        .map_err(LowerError::from)
1438    }
1439
1440    fn flagged_line_rules(&self) -> Vec<String> {
1441        Plugin::flagged_line_rules()
1442    }
1443
1444    fn manifest_paths(
1445        &self,
1446        repository_paths: &[RepoPath],
1447    ) -> Result<Vec<String>, LanguagePluginError> {
1448        Ok(Plugin::manifest_paths(owned_paths(repository_paths)))
1449    }
1450
1451    fn analyze_manifests(
1452        &self,
1453        manifests: Vec<Manifest>,
1454    ) -> Result<ManifestAnalysis, LanguagePluginError> {
1455        let analysis = Plugin::analyze_manifests(manifests.clone());
1456        validate_manifest_analysis(&manifests, analysis)
1457    }
1458
1459    fn resolve_imports(
1460        &self,
1461        repository_paths: &[RepoPath],
1462        manifests: Vec<Manifest>,
1463        requests: Vec<language::ImportRequest>,
1464        package_profiles: &[PackageFrameworkProfiles],
1465    ) -> Result<Vec<language::Resolution>, LanguagePluginError> {
1466        Ok(Plugin::resolve_imports(
1467            owned_paths(repository_paths),
1468            manifests,
1469            requests,
1470            package_profiles.to_vec(),
1471        ))
1472    }
1473
1474    fn entry_points(
1475        &self,
1476        repository_paths: &[RepoPath],
1477        manifests: Vec<Manifest>,
1478    ) -> Result<Vec<RepoPath>, LanguagePluginError> {
1479        validate_entry_points(
1480            repository_paths,
1481            Plugin::entry_points(owned_paths(repository_paths), manifests),
1482        )
1483    }
1484
1485    fn reference_ranges(&self) -> Result<ReferenceRanges, LanguagePluginError> {
1486        ReferenceRanges::new(Plugin::reference_ranges())
1487            .map_err(LanguagePluginError::InvalidReferenceRange)
1488    }
1489
1490    fn known_framework_profiles(&self) -> Vec<String> {
1491        Plugin::known_framework_profiles()
1492    }
1493
1494    fn resolve_framework_profiles(
1495        &self,
1496        package_root: &str,
1497        files: &[RepoPath],
1498        manifests: Vec<Manifest>,
1499        selection: FrameworkProfileSelection,
1500    ) -> Result<FrameworkProfileResult, LanguagePluginError> {
1501        let result = Plugin::resolve_framework_profiles(
1502            package_root.to_owned(),
1503            owned_paths(files),
1504            manifests,
1505            selection,
1506        )
1507        .map_err(|message| LanguagePluginError::FrameworkProfile { message })?;
1508        validate_framework_profile_result(&Plugin::known_framework_profiles(), files, result)
1509    }
1510
1511    fn has_hazard_rules(&self) -> bool {
1512        Plugin::has_hazard_rules()
1513    }
1514
1515    fn hazard_rules(&self) -> Vec<String> {
1516        Plugin::hazard_rules()
1517    }
1518
1519    fn has_imports(&self) -> bool {
1520        Plugin::has_imports()
1521    }
1522
1523    fn has_scope_analysis(&self) -> bool {
1524        Plugin::has_scope_analysis()
1525    }
1526
1527    fn analyze_scope(
1528        &self,
1529        package_root: &str,
1530        dialect: Option<&str>,
1531        artifacts: Vec<FileScopeArtifact>,
1532    ) -> Result<ScopeAnalysis, LanguagePluginError> {
1533        let artifact_paths: Vec<String> = artifacts.iter().map(|item| item.path.clone()).collect();
1534        let analysis = Plugin::analyze_scope(
1535            package_root.to_owned(),
1536            dialect.map(str::to_owned),
1537            artifacts,
1538        );
1539        let path_refs: Vec<&str> = artifact_paths.iter().map(String::as_str).collect();
1540        let listed: HashSet<String> = Plugin::hazard_rules().into_iter().collect();
1541        validate_scope_analysis("", &path_refs, &listed, None, analysis)
1542    }
1543}
1544
1545fn owned_paths(repository_paths: &[RepoPath]) -> Vec<String> {
1546    repository_paths
1547        .iter()
1548        .map(|path| path.as_str().to_owned())
1549        .collect()
1550}