Skip to main content

hawdb_sql_syntax/
error.rs

1// Copyright 2026 Nowledge
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt;
16
17use crate::Span;
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20pub enum SyntaxErrorCode {
21    InputTooLarge,
22    TokenLimitExceeded,
23    CommentNestingLimitExceeded,
24    ExpressionNestingLimitExceeded,
25    GraphPatternNestingLimitExceeded,
26    UnterminatedBlockComment,
27    UnterminatedQuotedIdentifier,
28    UnterminatedString,
29    UnterminatedDollarQuotedString,
30    InvalidParameter,
31    InvalidCharacter,
32    UnexpectedToken,
33    UnexpectedEnd,
34}
35
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct SyntaxError {
38    pub code: SyntaxErrorCode,
39    pub span: Span,
40    pub expected: Option<&'static str>,
41    pub found: Option<String>,
42}
43
44impl SyntaxError {
45    pub fn new(code: SyntaxErrorCode, span: Span) -> Self {
46        Self {
47            code,
48            span,
49            expected: None,
50            found: None,
51        }
52    }
53
54    pub fn expected(mut self, expected: &'static str) -> Self {
55        self.expected = Some(expected);
56        self
57    }
58
59    pub fn found(mut self, found: impl Into<String>) -> Self {
60        self.found = Some(found.into());
61        self
62    }
63}
64
65impl fmt::Display for SyntaxError {
66    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
67        write!(
68            formatter,
69            "SQL syntax error {:?} at bytes {}..{}",
70            self.code, self.span.start, self.span.end
71        )?;
72        if let Some(expected) = self.expected {
73            write!(formatter, "; expected {expected}")?;
74        }
75        if let Some(found) = &self.found {
76            write!(formatter, "; found {found}")?;
77        }
78        Ok(())
79    }
80}
81
82impl std::error::Error for SyntaxError {}