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