1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
// -*- coding: utf-8 -*-
// ------------------------------------------------------------------------------------------------
// Copyright © 2021, tree-sitter authors.
// Licensed under either of Apache License, Version 2.0, or MIT license, at your option.
// Please see the LICENSE-APACHE or LICENSE-MIT files in this distribution for license details.
// ------------------------------------------------------------------------------------------------

use std::path::Path;
use thiserror::Error;

use crate::ast::Stanza;
use crate::ast::Statement;
use crate::execution::CancellationError;
use crate::parse_error::Excerpt;
use crate::Location;

/// An error that can occur while executing a graph DSL file
#[derive(Debug, Error)]
pub enum ExecutionError {
    #[error(transparent)]
    Cancelled(#[from] CancellationError),
    #[error("Cannot assign immutable variable {0}")]
    CannotAssignImmutableVariable(String),
    #[error("Cannot assign scoped variable {0}")]
    CannotAssignScopedVariable(String),
    #[error("Cannot define mutable scoped variable {0}")]
    CannotDefineMutableScopedVariable(String),
    #[error("Duplicate attribute {0}")]
    DuplicateAttribute(String),
    #[error("Duplicate edge {0}")]
    DuplicateEdge(String),
    #[error("Duplicate variable {0}")]
    DuplicateVariable(String),
    #[error("Expected a graph node reference {0}")]
    ExpectedGraphNode(String),
    #[error("Expected a list {0}")]
    ExpectedList(String),
    #[error("Expected a boolean {0}")]
    ExpectedBoolean(String),
    #[error("Expected an integer {0}")]
    ExpectedInteger(String),
    #[error("Expected a string {0}")]
    ExpectedString(String),
    #[error("Expected a syntax node {0}")]
    ExpectedSyntaxNode(String),
    #[error("Invalid parameters {0}")]
    InvalidParameters(String),
    #[error("Scoped variables can only be attached to syntax nodes {0}")]
    InvalidVariableScope(String),
    #[error("Missing global variable {0}")]
    MissingGlobalVariable(String),
    #[error("Recursively defined scoped variable {0}")]
    RecursivelyDefinedScopedVariable(String),
    #[error("Recursively defined variable {0}")]
    RecursivelyDefinedVariable(String),
    #[error("Undefined capture {0}")]
    UndefinedCapture(String),
    #[error("Undefined function {0}")]
    UndefinedFunction(String),
    #[error("Undefined regex capture {0}")]
    UndefinedRegexCapture(String),
    #[error("Undefined scoped variable {0}")]
    UndefinedScopedVariable(String),
    #[error("Empty regex capture {0}")]
    EmptyRegexCapture(String),
    #[error("Undefined edge {0}")]
    UndefinedEdge(String),
    #[error("Undefined variable {0}")]
    UndefinedVariable(String),
    #[error("Cannot add scoped variable after being forced {0}")]
    VariableScopesAlreadyForced(String),
    #[error("Function {0} failed: {1}")]
    FunctionFailed(String, String),
    #[error("{0}. Caused by: {1}")]
    InContext(Context, Box<ExecutionError>),
}

#[derive(Clone, Debug)]
pub enum Context {
    Statement(Vec<StatementContext>),
    Other(String),
}

#[derive(Clone, Debug)]
pub struct StatementContext {
    pub statement: String,
    pub statement_location: Location,
    pub stanza_location: Location,
    pub source_location: Location,
    pub node_kind: String,
}

impl StatementContext {
    pub(crate) fn new(stmt: &Statement, stanza: &Stanza, source_node: &tree_sitter::Node) -> Self {
        Self {
            statement: format!("{}", stmt),
            statement_location: stmt.location(),
            stanza_location: stanza.range.start,
            source_location: Location::from(source_node.range().start_point),
            node_kind: source_node.kind().to_string(),
        }
    }

    pub(crate) fn update_statement(&mut self, stmt: &Statement) {
        self.statement = format!("{}", stmt);
        self.statement_location = stmt.location();
    }
}

impl From<StatementContext> for Context {
    fn from(value: StatementContext) -> Self {
        Self::Statement(vec![value])
    }
}

impl From<(StatementContext, StatementContext)> for Context {
    fn from((left, right): (StatementContext, StatementContext)) -> Self {
        Self::Statement(vec![left, right])
    }
}

impl From<String> for Context {
    fn from(value: String) -> Self {
        Self::Other(value)
    }
}

impl std::fmt::Display for Context {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Statement(stmts) => {
                let mut first = true;
                for stmt in stmts {
                    stmt.fmt(f, first)?;
                    first = false;
                }
            }
            Self::Other(msg) => write!(f, "{}", msg)?,
        }
        Ok(())
    }
}

impl StatementContext {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>, first: bool) -> std::fmt::Result {
        if first {
            write!(f, "Error executing",)?;
        } else {
            write!(f, " and executing",)?;
        }
        write!(
            f,
            " {} in stanza at {} matching ({}) node at {}",
            self.statement, self.stanza_location, self.node_kind, self.source_location
        )?;
        Ok(())
    }
}

pub(super) trait ResultWithExecutionError<R> {
    fn with_context<F>(self, with_context: F) -> Result<R, ExecutionError>
    where
        F: FnOnce() -> Context;
}

impl<R> ResultWithExecutionError<R> for Result<R, ExecutionError> {
    fn with_context<F>(self, with_context: F) -> Result<R, ExecutionError>
    where
        F: FnOnce() -> Context,
    {
        self.map_err(|e| match e {
            cancelled @ ExecutionError::Cancelled(_) => cancelled,
            in_other_context @ ExecutionError::InContext(Context::Other(_), _) => {
                ExecutionError::InContext(with_context(), Box::new(in_other_context))
            }
            in_stmt_context @ ExecutionError::InContext(_, _) => in_stmt_context,
            _ => ExecutionError::InContext(with_context(), Box::new(e)),
        })
    }
}

impl ExecutionError {
    pub fn display_pretty<'a>(
        &'a self,
        source_path: &'a Path,
        source: &'a str,
        tsg_path: &'a Path,
        tsg: &'a str,
    ) -> impl std::fmt::Display + 'a {
        DisplayExecutionErrorPretty {
            error: self,
            source_path,
            source,
            tsg_path,
            tsg,
        }
    }
}

struct DisplayExecutionErrorPretty<'a> {
    error: &'a ExecutionError,
    source_path: &'a Path,
    source: &'a str,
    tsg_path: &'a Path,
    tsg: &'a str,
}

impl std::fmt::Display for DisplayExecutionErrorPretty<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.fmt_entry(f, 0, self.error)
    }
}

impl DisplayExecutionErrorPretty<'_> {
    fn fmt_entry(
        &self,
        f: &mut std::fmt::Formatter<'_>,
        index: usize,
        error: &ExecutionError,
    ) -> std::fmt::Result {
        match error {
            ExecutionError::InContext(context, cause) => {
                match context {
                    Context::Statement(stmts) => {
                        let mut first = true;
                        for stmt in stmts {
                            stmt.fmt_pretty(
                                f,
                                self.source_path,
                                self.source,
                                self.tsg_path,
                                self.tsg,
                                index,
                                first,
                            )?;
                            first = false;
                        }
                    }
                    Context::Other(msg) => writeln!(f, "{:>5}: {}", index, msg)?,
                };
                self.fmt_entry(f, index + 1, cause)?;
                Ok(())
            }
            other => writeln!(f, "{:>5}: {}", index, other),
        }
    }
}

impl StatementContext {
    fn fmt_pretty(
        &self,
        f: &mut std::fmt::Formatter<'_>,
        source_path: &Path,
        source: &str,
        tsg_path: &Path,
        tsg: &str,
        index: usize,
        first: bool,
    ) -> std::fmt::Result {
        if first {
            writeln!(
                f,
                "{:>5}: Error executing statement {}",
                index, self.statement
            )?;
        } else {
            writeln!(f, "     > and executing statement {}", self.statement)?;
        }
        write!(
            f,
            "{}",
            Excerpt::from_source(
                tsg_path,
                tsg,
                self.statement_location.row,
                self.statement_location.to_column_range(),
                7
            )
        )?;
        writeln!(f, "{}in stanza", " ".repeat(7))?;
        write!(
            f,
            "{}",
            Excerpt::from_source(
                tsg_path,
                tsg,
                self.stanza_location.row,
                self.stanza_location.to_column_range(),
                7
            )
        )?;
        writeln!(f, "{}matching ({}) node", " ".repeat(7), self.node_kind)?;
        write!(
            f,
            "{}",
            Excerpt::from_source(
                source_path,
                source,
                self.source_location.row,
                self.source_location.to_column_range(),
                7
            )
        )?;
        Ok(())
    }
}