Skip to main content

vvv_engine/
error.rs

1use crate::{ApplyError, ErrorCode, SelectionError, TemplateError, VfsError};
2
3use vvv_core::RelPath;
4use vvv_core::{
5    EditConflict, LanguageId, Position, QueryError, ResolveError, SearchError, SymbolKind,
6};
7
8use crate::history::HistoryError;
9
10#[derive(Debug, thiserror::Error)]
11pub enum EngineError {
12    #[error("select exactly one symbol-move declaration: {}", candidates.iter().enumerate().map(|(index, candidate)| format!("{}: {} {}:{}", index + 1, candidate.declaration.id, candidate.declaration.path, candidate.declaration.start.line + 1)).collect::<Vec<_>>().join(", "))]
13    SymbolMoveSelection {
14        candidates: Vec<crate::SymbolMoveCandidate>,
15    },
16    #[error("selected declaration cannot be moved: {reason}")]
17    UnsupportedSymbolMove {
18        declaration: Box<crate::Match>,
19        reason: crate::SymbolMoveUnsupported,
20    },
21    #[error("invalid symbol-move ownership evidence")]
22    InvalidSymbolMoveEvidence,
23    #[error("validation requires a disk workspace on a supported platform")]
24    ValidationUnavailable,
25    #[error(
26        "validation requires an applied plan, one to four valid check commands, and relative extra input paths"
27    )]
28    InvalidValidation,
29    #[error("invalid plan handle")]
30    InvalidPlan,
31    #[error("move paths must be nonempty workspace-relative paths without .. components: {path}")]
32    InvalidMovePath { path: RelPath },
33    #[error("plan expired or belongs to another session; prepare and review a new plan")]
34    PlanExpired,
35    #[error("plan cannot be applied again; inspect its terminal outcome")]
36    PlanConsumed,
37    #[error("workspace changed since review; prepare and review a new plan")]
38    StalePlan,
39    #[error("plan retention limit reached; discard pending plans or wait for expiry")]
40    PlanRetentionLimit,
41    #[error(
42        "search paths must be workspace-relative with / separators and no .. components; package filters must be nonempty"
43    )]
44    InvalidSearchScope,
45    #[error("request cancelled")]
46    ReadCancelled,
47    #[error("a cancellation handle can execute only one call")]
48    ReusedCancellation,
49    #[error("cooperative cancellation is only supported for reads and explicit validation")]
50    MutationCancellation,
51    #[error("query sources changed; start a new query")]
52    StaleQuery,
53    #[error("cursor expired or belongs to another session; start a new query")]
54    CursorExpired,
55    #[error("invalid cursor or wrong cursor kind")]
56    InvalidCursor,
57    #[error("query exceeds retained-state limits; narrow the request")]
58    RetentionLimit,
59    #[error("result needs {required_bytes} bytes; output budget is {max_bytes}")]
60    PageOutputLimit {
61        max_bytes: usize,
62        required_bytes: usize,
63        anchor: Option<crate::SourceAnchor>,
64    },
65    #[cfg(feature = "schema")]
66    #[error("command schemas require for_command; call and reply schemas do not accept it")]
67    InvalidSchemaQuery,
68    #[error("invalid output or context budget")]
69    InvalidBudget,
70    #[error("output budgets are only supported for read-only requests")]
71    MutationBudget,
72    #[error("result needs {required_bytes} bytes; output budget is {max_bytes}")]
73    OutputLimit {
74        max_bytes: usize,
75        required_bytes: usize,
76    },
77    #[error("navigation cancelled")]
78    NavigationCancelled,
79    #[error("semantic provider state changed")]
80    StaleSemantic,
81    #[error("semantic provider returned invalid or inconsistent source evidence")]
82    InvalidSemantic,
83
84    #[error("source changed: {path}")]
85    StaleSource { path: RelPath },
86    #[error("invalid navigation range in {path}")]
87    InvalidAnchor { path: RelPath },
88    #[error("navigation exceeded its resolution budget")]
89    NavigationLimit,
90    #[error("select exactly one navigation candidate")]
91    NavigationSelection,
92
93    #[error("expected {expected} execution, got {actual}")]
94    ExecutionKind {
95        expected: crate::ExecutionKind,
96        actual: crate::ExecutionKind,
97    },
98    #[error("{}: {source}", path.display())]
99    Open {
100        path: RelPath,
101        #[source]
102        source: std::io::Error,
103    },
104    #[error(transparent)]
105    Vfs(#[from] VfsError),
106    #[error(transparent)]
107    Query(#[from] QueryError),
108    #[error("search failed in {}", path.display())]
109    Search {
110        path: RelPath,
111        #[source]
112        source: SearchError,
113    },
114    #[error(transparent)]
115    Selection(#[from] SelectionError),
116    #[error("{}:{}", path.display(), line + 1)]
117    Template {
118        path: RelPath,
119        line: u32,
120        #[source]
121        source: TemplateError,
122    },
123    #[error(transparent)]
124    Conflict(#[from] EditConflict),
125    #[error(transparent)]
126    Extraction(#[from] crate::ExtractionError),
127    #[error(transparent)]
128    Regroup(#[from] vvv_core::RegroupError),
129    #[error("`{name}` is declared in several places ({})", declarations.iter().map(ToString::to_string).collect::<Vec<_>>().join(", "))]
130    AmbiguousSymbol {
131        name: String,
132        declarations: Vec<crate::graph::DeclarationSite>,
133    },
134    #[error("no {} named `{name}`", kind.map_or("symbol", SymbolKind::as_str))]
135    NoSuchSymbol {
136        name: String,
137        kind: Option<SymbolKind>,
138    },
139    #[error("{} already exists", .0.display())]
140    Exists(RelPath),
141    #[error("no registered language claims {}", .0.display())]
142    NoLanguage(RelPath),
143    #[error("{0} has no layout yet, so its paths cannot be followed or its files moved")]
144    NoLayout(LanguageId),
145    #[error("{}:{} is past the end of the file", path.display(), position.display())]
146    NoSuchPosition { path: RelPath, position: Position },
147    #[error(transparent)]
148    Resolve(#[from] ResolveError),
149    #[error(transparent)]
150    Apply(#[from] ApplyError),
151    #[error(transparent)]
152    History(#[from] HistoryError),
153    #[error(transparent)]
154    Recovery(#[from] RecoveryError),
155}
156
157impl EngineError {
158    /// The stable code a client branches on.
159    pub fn code(&self) -> ErrorCode {
160        match self {
161            Self::SymbolMoveSelection { .. } => ErrorCode::BadSelection,
162            Self::UnsupportedSymbolMove { .. } => ErrorCode::Unmovable,
163            Self::InvalidSymbolMoveEvidence => ErrorCode::Conflict,
164            Self::InvalidPlan => ErrorCode::InvalidPlan,
165            Self::PlanExpired => ErrorCode::PlanExpired,
166            Self::PlanConsumed => ErrorCode::PlanConsumed,
167            Self::StalePlan => ErrorCode::Stale,
168            Self::PlanRetentionLimit => ErrorCode::RetentionLimit,
169            Self::InvalidSearchScope | Self::InvalidMovePath { .. } => ErrorCode::BadRequest,
170            Self::ReadCancelled => ErrorCode::Cancelled,
171            Self::ReusedCancellation | Self::MutationCancellation => ErrorCode::BadRequest,
172            #[cfg(feature = "schema")]
173            Self::InvalidSchemaQuery => ErrorCode::BadRequest,
174            Self::InvalidBudget
175            | Self::InvalidValidation
176            | Self::ValidationUnavailable
177            | Self::MutationBudget => ErrorCode::BadRequest,
178            Self::StaleQuery => ErrorCode::Stale,
179            Self::CursorExpired => ErrorCode::CursorExpired,
180            Self::InvalidCursor => ErrorCode::InvalidCursor,
181            Self::RetentionLimit => ErrorCode::RetentionLimit,
182            Self::PageOutputLimit { .. } | Self::OutputLimit { .. } => ErrorCode::OutputLimit,
183            Self::NavigationCancelled => ErrorCode::Cancelled,
184            Self::StaleSemantic => ErrorCode::Stale,
185            Self::InvalidSemantic => ErrorCode::BadRequest,
186            Self::StaleSource { .. } => ErrorCode::Stale,
187            Self::InvalidAnchor { .. } => ErrorCode::BadRequest,
188            Self::NavigationSelection => ErrorCode::BadSelection,
189            Self::NavigationLimit => ErrorCode::Incomplete,
190            Self::ExecutionKind { .. } => ErrorCode::BadRequest,
191            Self::Open { .. } => ErrorCode::Io,
192            Self::Vfs(e)
193            | Self::History(HistoryError::Vfs(e))
194            | Self::Apply(ApplyError::Vfs(e)) => match e {
195                VfsError::NotFound(_) => ErrorCode::NotFound,
196                VfsError::Exists(_) => ErrorCode::Exists,
197                _ => ErrorCode::Io,
198            },
199            Self::Query(_) => ErrorCode::BadQuery,
200            Self::Search {
201                source: SearchError::Facts(_) | SearchError::Span(_),
202                ..
203            } => ErrorCode::Conflict,
204            Self::Search { .. } => ErrorCode::BadPattern,
205            Self::Selection(_) => ErrorCode::BadSelection,
206            Self::Template { .. } => ErrorCode::BadTemplate,
207            Self::Conflict(_) | Self::Extraction(_) | Self::Regroup(_) => ErrorCode::Conflict,
208            Self::AmbiguousSymbol { .. } => ErrorCode::AmbiguousSymbol,
209            Self::NoSuchSymbol { .. } => ErrorCode::NoSuchSymbol,
210            Self::Exists(_) => ErrorCode::Exists,
211            Self::NoLanguage(_) => ErrorCode::NoLanguage,
212            Self::NoLayout(_) => ErrorCode::NoLayout,
213            Self::NoSuchPosition { .. } => ErrorCode::NoSuchPosition,
214            Self::Resolve(e) => match e {
215                ResolveError::Missing(_) | ResolveError::NoDeclaringFile { .. } => {
216                    ErrorCode::NotFound
217                }
218                _ => ErrorCode::Unmovable,
219            },
220            Self::Apply(e) => match e {
221                ApplyError::Edit(_) => ErrorCode::Conflict,
222                ApplyError::DestinationExists { .. } => ErrorCode::Exists,
223                ApplyError::Stale { .. } | ApplyError::Modified { .. } => ErrorCode::Stale,
224                _ => ErrorCode::Io,
225            },
226            Self::History(_) => ErrorCode::NoHistory,
227            Self::Recovery(_) => ErrorCode::RecoveryFailed,
228        }
229    }
230
231    /// What to try instead, when the error suggests something.
232    pub fn hint(&self) -> Option<String> {
233        match self {
234            Self::InvalidPlan => Some("Pass the exact plan_id returned by preparation".into()),
235            Self::PlanExpired | Self::StalePlan => Some("Prepare a new plan and review its diff before applying".into()),
236            Self::PlanConsumed => Some("Use inspect_plan to retrieve the recorded outcome; do not retry by rebuilding the mutation".into()),
237            Self::PlanRetentionLimit => Some("Discard pending plans, narrow the rename, or wait for terminal outcomes to expire".into()),
238            Self::InvalidBudget => Some("Use discover to check supported output and context budget ranges".into()),
239            Self::OutputLimit { .. } => Some("Increase max_output_bytes, narrow the query, or request bounded context".into()),
240            Self::NoSuchSymbol { name, .. } => Some(format!(
241                "declarations are matched by exact name; `vvv search --name {name}` shows what exists"
242            )),
243            Self::AmbiguousSymbol { declarations, .. } => Some(format!(
244                "for example: --in {}",
245                declarations
246                    .first()
247                    .map(|d| d.path.display().to_string())
248                    .unwrap_or_default()
249            )),
250            Self::Query(_) => Some(
251                "search by pattern:  vvv search 'fn $NAME($$$) { $$$ }'\nby declaration:     vvv search --symbol trait   |   vvv search --name Foo"
252                    .to_owned(),
253            ),
254            _ => None,
255        }
256    }
257}
258
259/// A failed mutation whose effects could not all be restored and verified.
260#[derive(Debug)]
261pub struct RecoveryError {
262    pub cause: Box<EngineError>,
263    pub details: crate::Recovery,
264}
265
266impl std::fmt::Display for RecoveryError {
267    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
268        write!(f, "{}; recovery incomplete", self.cause)?;
269        for effect in &self.details.remaining {
270            write!(
271                f,
272                "; {}: expected {:?}, observed {:?}",
273                effect.path.display(),
274                effect.expected,
275                effect.observed
276            )?;
277        }
278        for issue in &self.details.unverified {
279            write!(
280                f,
281                "; {}: state unverified ({})",
282                issue.path.display(),
283                issue.message
284            )?;
285        }
286        Ok(())
287    }
288}
289
290impl std::error::Error for RecoveryError {
291    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
292        Some(self.cause.as_ref())
293    }
294}