1mod address;
12mod project;
13
14use std::path::{Path, PathBuf};
15
16pub use address::{Address, Dependency, Package, PackageId, Packages};
17pub use project::{FileSet, Parsed, Project};
18
19use crate::edit::Edit;
20use crate::import::ImportRef;
21use crate::paths::{ModulePath, RelPath};
22use crate::semantics::ReachKind;
23use crate::symbol::Symbol;
24use crate::text::{SourceText, Span};
25
26#[derive(Debug, thiserror::Error, PartialEq, Eq)]
29pub enum ResolveError {
30 #[error("{} is not addressable in this language (outside the module tree?)", .0.display())]
31 NotAddressable(RelPath),
32 #[error("{} does not exist", .0.display())]
33 Missing(RelPath),
34 #[error("{} is a crate or directory root; moving it is not supported", .0.display())]
35 Root(RelPath),
36 #[error("{} would end up inside itself at {}", from.display(), to.display())]
37 IntoItself { from: RelPath, to: RelPath },
38 #[error("moving between crates is not supported ({} → {})", from.display(), to.display())]
39 CrossProject { from: RelPath, to: RelPath },
40 #[error("cannot find the file declaring `{name}`")]
41 NoDeclaringFile { name: String },
42 #[error(
43 "no file declares module `{module}`; create {} first so `{declaration}` has a home",
44 Candidates(candidates)
45 )]
46 NoParentFile {
47 module: String,
48 candidates: Vec<RelPath>,
49 declaration: String,
50 },
51 #[error("no `{declaration}` in {}; inline or #[path] modules are not supported", parent.display())]
52 NoDeclaration {
53 declaration: String,
54 parent: RelPath,
55 },
56 #[error("cannot parse {}: {reason}", path.display())]
57 Syntax { path: RelPath, reason: String },
58}
59
60struct Candidates<'a>(&'a [RelPath]);
62
63impl std::fmt::Display for Candidates<'_> {
64 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65 match self.0 {
66 [] => write!(f, "the module file"),
67 [only] => write!(f, "{}", only.display()),
68 [first, rest @ ..] => {
69 write!(f, "{}", first.display())?;
70 write!(f, " (or ")?;
71 for (i, p) in rest.iter().enumerate() {
72 if i > 0 {
73 write!(f, ", ")?;
74 }
75 write!(f, "{}", p.display())?;
76 }
77 write!(f, ")")
78 }
79 }
80 }
81}
82
83#[derive(Debug, Clone, PartialEq, Eq)]
85pub struct SideEdit {
86 pub path: PathBuf,
87 pub edit: Edit,
88}
89
90pub trait Layout: Send + Sync {
94 fn manifests(&self) -> &'static [&'static str];
96
97 fn package(&self, manifest: &Path, text: &str) -> Option<Package>;
100
101 fn address(&self, project: &Project, path: &Path) -> Result<Address, ResolveError>;
104
105 fn candidates(&self, project: &Project, address: &Address) -> Vec<PathBuf>;
108
109 fn resolve(&self, project: &Project, from: &Path, import: &ModulePath) -> Option<Address>;
114
115 fn companions(&self, project: &Project, from: &Path, to: &Path) -> Vec<(PathBuf, PathBuf)> {
119 let _ = (project, from, to);
120 Vec::new()
121 }
122
123 fn touched_by_move(
128 &self,
129 project: &Project,
130 from: &Path,
131 to: &Path,
132 ) -> Result<Vec<PathBuf>, ResolveError> {
133 let _ = (project, from, to);
134 Ok(Vec::new())
135 }
136}
137
138pub trait Surgery: Send + Sync {
141 fn render(
145 &self,
146 project: &Project,
147 from: &Path,
148 target: &Address,
149 original: &ModulePath,
150 ) -> ModulePath;
151
152 fn import_statement(
156 &self,
157 project: &Project,
158 from: &Path,
159 target: &Address,
160 name: &str,
161 ) -> Option<String> {
162 let _ = (project, from, target, name);
163 None
164 }
165
166 fn regroup(
174 &self,
175 project: &Project,
176 from: &Path,
177 source: &SourceText,
178 imports: &GroupedImports,
179 ) -> Regrouped {
180 let _ = (project, from, source);
181 Regrouped::skipped(imports)
182 }
183
184 fn relocate(
190 &self,
191 project: &Project,
192 from: &Path,
193 to: &Path,
194 touched: &[Parsed<'_>],
195 widen_to: Option<ReachKind>,
196 ) -> Result<Vec<SideEdit>, ResolveError> {
197 let _ = (project, from, to, touched, widen_to);
198 Ok(Vec::new())
199 }
200
201 fn import_of_path(&self, path: &ModulePath, name: &str) -> Option<String> {
204 let _ = (path, name);
205 None
206 }
207
208 fn import_insertion(&self, file: &Parsed<'_>) -> usize {
211 file.facts
212 .imports
213 .iter()
214 .filter(|i| i.declares)
215 .map(|i| i.span.end)
216 .max()
217 .map_or(0, |end| {
218 file.source.as_str()[end..]
219 .find('\n')
220 .map_or(file.source.len(), |nl| end + nl + 1)
221 })
222 }
223
224 fn item_insertion(&self, file: &Parsed<'_>) -> usize {
226 file.source.len()
227 }
228
229 fn widen(&self, symbol: &Symbol, source: &SourceText, to: ReachKind) -> Option<Edit> {
233 let _ = (symbol, source, to);
234 None
235 }
236}
237
238#[derive(Debug, Clone, PartialEq, Eq)]
240pub struct GroupedImport {
241 pub import: ImportRef,
242 pub target: Address,
243 pub prefix: Option<Address>,
244}
245
246#[derive(Debug, Clone, PartialEq, Eq)]
248pub struct GroupedImports {
249 entries: Vec<GroupedImport>,
250 statement: Span,
251}
252
253impl GroupedImports {
254 pub fn new(entries: Vec<GroupedImport>) -> Result<Self, RegroupError> {
255 let first = entries.first().ok_or(RegroupError::Empty)?;
256 let statement = first
257 .import
258 .group
259 .as_ref()
260 .ok_or(RegroupError::NotGrouped(first.import.span))?
261 .statement;
262 for (i, entry) in entries.iter().enumerate() {
263 let group = entry
264 .import
265 .group
266 .as_ref()
267 .ok_or(RegroupError::NotGrouped(entry.import.span))?;
268 if entry.import.path.head != group.prefix.head
269 || !entry
270 .import
271 .path
272 .segments
273 .starts_with(&group.prefix.segments)
274 {
275 return Err(RegroupError::InvalidPrefix(entry.import.span));
276 }
277 if group.statement != statement {
278 return Err(RegroupError::DifferentStatement(entry.import.span));
279 }
280 if entries[..i]
281 .iter()
282 .any(|e| e.import.span == entry.import.span)
283 {
284 return Err(RegroupError::DuplicateEntry(entry.import.span));
285 }
286 }
287 Ok(Self { entries, statement })
288 }
289
290 pub fn entries(&self) -> &[GroupedImport] {
291 &self.entries
292 }
293 pub fn statement(&self) -> Span {
294 self.statement
295 }
296}
297
298#[derive(Debug, Clone, PartialEq, Eq)]
301pub enum RegroupedOutcome {
302 InPlace { replacement: ModulePath },
303 Structural,
304 Skipped,
305}
306
307#[derive(Debug, Clone, PartialEq, Eq)]
308pub struct RegroupedEntry {
309 pub span: Span,
310 pub outcome: RegroupedOutcome,
311}
312
313#[derive(Debug, Clone, Default, PartialEq, Eq)]
315pub struct Regrouped {
316 pub edits: Vec<Edit>,
317 pub outcomes: Vec<RegroupedEntry>,
318}
319
320impl Regrouped {
321 pub fn skipped(imports: &GroupedImports) -> Self {
322 Self {
323 edits: Vec::new(),
324 outcomes: imports
325 .entries()
326 .iter()
327 .map(|e| RegroupedEntry {
328 span: e.import.span,
329 outcome: RegroupedOutcome::Skipped,
330 })
331 .collect(),
332 }
333 }
334
335 pub fn validate<'a>(
336 &'a self,
337 imports: &'a GroupedImports,
338 ) -> Result<Vec<(&'a GroupedImport, &'a RegroupedOutcome)>, RegroupError> {
339 for (i, outcome) in self.outcomes.iter().enumerate() {
340 if !imports
341 .entries()
342 .iter()
343 .any(|e| e.import.span == outcome.span)
344 {
345 return Err(RegroupError::ForeignOutcome(outcome.span));
346 }
347 if self.outcomes[..i].iter().any(|o| o.span == outcome.span) {
348 return Err(RegroupError::DuplicateOutcome(outcome.span));
349 }
350 }
351 imports
352 .entries()
353 .iter()
354 .map(|entry| {
355 let outcome = self
356 .outcomes
357 .iter()
358 .find(|o| o.span == entry.import.span)
359 .ok_or(RegroupError::MissingOutcome(entry.import.span))?;
360 if let RegroupedOutcome::InPlace { replacement } = &outcome.outcome {
361 let matching: Vec<_> = self
362 .edits
363 .iter()
364 .filter(|e| e.span == entry.import.span)
365 .collect();
366 if matching.len() != 1 || matching[0].replacement != replacement.to_string() {
367 return Err(RegroupError::InconsistentReplacement(entry.import.span));
368 }
369 }
370 Ok((entry, &outcome.outcome))
371 })
372 .collect()
373 }
374}
375
376#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
377pub enum RegroupError {
378 #[error("a grouped rewrite requires at least one entry")]
379 Empty,
380 #[error("entry {0:?} is not grouped")]
381 NotGrouped(Span),
382 #[error("entry {0:?} belongs to another statement")]
383 DifferentStatement(Span),
384 #[error("entry {0:?} does not extend its group prefix")]
385 InvalidPrefix(Span),
386 #[error("duplicate grouped entry {0:?}")]
387 DuplicateEntry(Span),
388 #[error("grouped rewrite returned a foreign entry {0:?}")]
389 ForeignOutcome(Span),
390 #[error("grouped rewrite returned entry {0:?} twice")]
391 DuplicateOutcome(Span),
392 #[error("grouped rewrite omitted entry {0:?}")]
393 MissingOutcome(Span),
394 #[error("grouped rewrite replacement for {0:?} differs from its edit")]
395 InconsistentReplacement(Span),
396}
397
398#[cfg(test)]
399mod regroup_tests {
400 use super::*;
401 use crate::{ImportGroup, PathSyntax};
402
403 struct Fixture {
404 imports: GroupedImports,
405 }
406
407 impl Fixture {
408 fn new() -> Self {
409 let prefix = PathSyntax::Scoped.parse("crate::a");
410 let mut import =
411 ImportRef::new(Span::new(15, 16), PathSyntax::Scoped.parse("crate::a::X"));
412 import.group = Some(ImportGroup {
413 prefix,
414 item: import.span,
415 list: Span::new(14, 17),
416 items: 1,
417 statement: Span::new(0, 18),
418 top_level: true,
419 });
420 Self {
421 imports: GroupedImports::new(vec![GroupedImport {
422 import,
423 target: Address::new("p", ["b", "X"]),
424 prefix: Some(Address::new("p", ["a"])),
425 }])
426 .unwrap(),
427 }
428 }
429
430 fn span(&self) -> Span {
431 self.imports.entries()[0].import.span
432 }
433 fn outcome(&self, outcome: RegroupedOutcome) -> Regrouped {
434 Regrouped {
435 edits: vec![],
436 outcomes: vec![RegroupedEntry {
437 span: self.span(),
438 outcome,
439 }],
440 }
441 }
442 }
443
444 #[test]
445 fn grouped_requests_require_unique_entries_from_one_statement() {
446 let fixture = Fixture::new();
447 assert_eq!(GroupedImports::new(vec![]), Err(RegroupError::Empty));
448 let entry = fixture.imports.entries()[0].clone();
449 assert_eq!(
450 GroupedImports::new(vec![entry.clone(), entry.clone()]),
451 Err(RegroupError::DuplicateEntry(entry.import.span))
452 );
453 let mut other = entry.clone();
454 other.import.group.as_mut().unwrap().statement = Span::new(20, 40);
455 assert_eq!(
456 GroupedImports::new(vec![entry.clone(), other]),
457 Err(RegroupError::DifferentStatement(entry.import.span))
458 );
459 let mut ungrouped = entry;
460 ungrouped.import.group = None;
461 assert_eq!(
462 GroupedImports::new(vec![ungrouped]),
463 Err(RegroupError::NotGrouped(fixture.span()))
464 );
465 }
466
467 #[test]
468 fn regrouped_outcomes_cover_exactly_the_requested_entries() {
469 let fixture = Fixture::new();
470 let mut out = fixture.outcome(RegroupedOutcome::Structural);
471 assert!(out.validate(&fixture.imports).is_ok());
472 out.outcomes.push(out.outcomes[0].clone());
473 assert_eq!(
474 out.validate(&fixture.imports),
475 Err(RegroupError::DuplicateOutcome(fixture.span()))
476 );
477 out.outcomes.pop();
478 out.outcomes[0].span = Span::new(30, 31);
479 assert_eq!(
480 out.validate(&fixture.imports),
481 Err(RegroupError::ForeignOutcome(Span::new(30, 31)))
482 );
483 out.outcomes.clear();
484 assert_eq!(
485 out.validate(&fixture.imports),
486 Err(RegroupError::MissingOutcome(fixture.span()))
487 );
488 }
489
490 #[test]
491 fn in_place_outcomes_report_the_actual_replacement() {
492 let fixture = Fixture::new();
493 let mut out = fixture.outcome(RegroupedOutcome::InPlace {
494 replacement: PathSyntax::Scoped.parse("Y"),
495 });
496 assert_eq!(
497 out.validate(&fixture.imports),
498 Err(RegroupError::InconsistentReplacement(fixture.span()))
499 );
500 out.edits.push(Edit::replace(fixture.span(), "different"));
501 assert_eq!(
502 out.validate(&fixture.imports),
503 Err(RegroupError::InconsistentReplacement(fixture.span()))
504 );
505 out.edits[0].replacement = "Y".into();
506 assert!(out.validate(&fixture.imports).is_ok());
507 }
508
509 #[test]
510 fn default_grouped_outcomes_explicitly_skip_every_target() {
511 let fixture = Fixture::new();
512 let out = Regrouped::skipped(&fixture.imports);
513 let validated = out.validate(&fixture.imports).unwrap();
514 assert_eq!(validated.len(), 1);
515 assert_eq!(validated[0].0.target, Address::new("p", ["b", "X"]));
516 assert!(matches!(validated[0].1, RegroupedOutcome::Skipped));
517 assert!(out.edits.is_empty());
518 }
519}