Skip to main content

eventql_parser/
error.rs

1//! Error types for lexical analysis and parsing.
2//!
3//! This module defines the error types that can occur during tokenization
4//! and parsing of EventQL queries. All errors include position information
5//! (line and column numbers) to help diagnose issues in query strings.
6
7use crate::token::Symbol;
8use serde::Serialize;
9use thiserror::Error;
10
11/// Top-level error type for the EventQL parser.
12///
13/// This enum wraps both lexer and parser errors, providing a unified
14/// error type for the entire parsing pipeline.
15#[derive(Debug, Error, Serialize)]
16pub enum Error {
17    /// Error during lexical analysis (tokenization).
18    #[error(transparent)]
19    Lexer(LexerError),
20
21    /// Error during syntactic analysis (parsing).
22    #[error(transparent)]
23    Parser(ParserError),
24
25    /// Error during static analysis.
26    #[error(transparent)]
27    Analysis(AnalysisError),
28}
29
30/// Errors that can occur during lexical analysis.
31///
32/// These errors are produced by the tokenizer when the input string
33/// contains invalid characters or ends unexpectedly.
34#[derive(Debug, Error, Serialize)]
35pub enum LexerError {
36    /// The input ended unexpectedly while parsing a token.
37    ///
38    /// This typically occurs when a string literal or other multi-character
39    /// token is not properly closed.
40    #[error("unexpected end of input")]
41    IncompleteInput,
42
43    /// An invalid character was encountered at the specified position.
44    ///
45    /// The tuple contains `(line_number, column_number)`.
46    #[error("{0}:{1}: invalid character")]
47    InvalidSymbol(u32, u32),
48}
49
50/// Errors that can occur during syntactic analysis.
51///
52/// These errors are produced by the parser when the token sequence
53/// does not match the expected grammar of EventQL.
54#[derive(Debug, Error, Serialize)]
55pub enum ParserError {
56    /// Expected an identifier but found something else.
57    ///
58    /// Fields: `(line, column, found_token)`
59    #[error("{0}:{1}: expected identifier but got {2}")]
60    ExpectedIdent(u32, u32, String),
61
62    /// The query is missing a required FROM statement.
63    ///
64    /// Fields: `(line, column)`
65    #[error("{0}:{1}: missing FROM statement")]
66    MissingFromStatement(u32, u32),
67
68    /// Expected a specific keyword but found something else.
69    ///
70    /// Fields: `(line, column, expected_keyword, found_token)`
71    #[error("{0}:{1}: expected keyword {2} but got {3}")]
72    ExpectedKeyword(u32, u32, &'static str, String),
73
74    /// Expected a specific symbol but found something else.
75    ///
76    /// Fields: `(line, column, expected_symbol, found_token)`
77    #[error("{0}:{1}: expected {2} but got {3}")]
78    ExpectedSymbol(u32, u32, Symbol, String),
79
80    /// An unexpected token was encountered.
81    ///
82    /// Fields: `(line, column, found_token)`
83    ///
84    /// This is a general error for tokens that don't fit the current parse context.
85    #[error("{0}:{1}: unexpected token {2}")]
86    UnexpectedToken(u32, u32, String),
87
88    /// Expected a type name but found something else.
89    ///
90    /// Fields: `(line, column, found_token)`
91    ///
92    /// This occurs when defining a type conversion operation but the left side is
93    /// not a type.
94    #[error("{0}:{1}: expected a type")]
95    ExpectedType(u32, u32),
96
97    /// The input ended unexpectedly while parsing.
98    ///
99    /// This occurs when the parser expects more tokens but encounters
100    /// the end of the token stream.
101    #[error("unexpected end of file")]
102    UnexpectedEof,
103}
104
105/// Errors that can occur during static analysis.
106///
107/// These errors are produced by the type checker when it encounters
108/// type mismatches, undeclared variables, or other semantic issues
109/// in the query.
110#[derive(Debug, Error, Serialize)]
111pub enum AnalysisError {
112    /// A binding with the same name already exists in the current scope.
113    ///
114    /// Fields: `(line, column, binding_name)`
115    ///
116    /// This occurs when trying to declare a variable that shadows an existing
117    /// binding in the same scope, such as using the same alias for multiple
118    /// FROM sources.
119    #[error("{0}:{1}: binding '{2}' already exists")]
120    BindingAlreadyExists(u32, u32, String),
121
122    /// A variable was referenced but not declared in any accessible scope.
123    ///
124    /// Fields: `(line, column, variable_name)`
125    ///
126    /// This occurs when referencing a variable that hasn't been bound by a
127    /// FROM clause or defined in the default scope.
128    #[error("{0}:{1}: variable '{2}' is undeclared")]
129    VariableUndeclared(u32, u32, String),
130
131    /// A type mismatch occurred between expected and actual types.
132    ///
133    /// Fields: `(line, column, expected_type, actual_type)`
134    ///
135    /// This occurs when an expression has a different type than what is
136    /// required by its context (e.g., using a string where a number is expected).
137    #[error("{0}:{1}: type mismatch: expected {2} but got {3} ")]
138    TypeMismatch(u32, u32, String, String),
139
140    /// A record field was accessed but doesn't exist in the record type.
141    ///
142    /// Fields: `(line, column, field_name)`
143    ///
144    /// This occurs when trying to access a field that is not defined in the
145    /// record's type definition.
146    #[error("{0}:{1}: record field '{2}' is undeclared ")]
147    FieldUndeclared(u32, u32, String),
148
149    /// A function was called but is not declared in the scope.
150    ///
151    /// Fields: `(line, column, function_name)`
152    ///
153    /// This occurs when calling a function that is not defined in the default
154    /// scope or any accessible scope.
155    #[error("{0}:{1}: function '{2}' is undeclared ")]
156    FuncUndeclared(u32, u32, String),
157
158    /// Expected a record type but found a different type.
159    ///
160    /// Fields: `(line, column, actual_type)`
161    ///
162    /// This occurs when a record type is required (e.g., for field access)
163    /// but a different type was found.
164    #[error("{0}:{1}: expected record but got {2}")]
165    ExpectRecord(u32, u32, String),
166
167    /// Expected a record or sourced-property but found a different type.
168    ///
169    /// Fields: `(line, column, actual_type)`
170    ///
171    /// This occurs when checking a projection and the static analysis found
172    /// out the project into clause doesn't return a record nor a sourced-based property.
173    #[error("{0}:{1}: expected a record or a sourced-property but got {2}")]
174    ExpectRecordOrSourcedProperty(u32, u32, String),
175
176    /// Expected an array type but found a different type.
177    ///
178    /// Fields: `(line, column, actual_type)`
179    ///
180    /// This occurs when an array type is required but a different type was found.
181    #[error("{0}:{1}: expected an array but got {2}")]
182    ExpectArray(u32, u32, String),
183
184    /// Expected a field literal but found a different expression.
185    ///
186    /// Fields: `(line, column)`
187    ///
188    /// This occurs in contexts where only a simple field reference is allowed,
189    /// such as in GROUP BY or ORDER BY clauses.
190    #[error("{0}:{1}: expected a field")]
191    ExpectFieldLiteral(u32, u32),
192
193    /// Expected a record literal but found a different expression.
194    ///
195    /// Fields: `(line, column)`
196    ///
197    /// This occurs when a record literal is required, such as in the
198    /// PROJECT INTO clause.
199    #[error("{0}:{1}: expected a record")]
200    ExpectRecordLiteral(u32, u32),
201
202    /// When a type is not supported by EventQL.
203    #[error("{0}:{1}: unknown type '{2}'")]
204    UnknownType(u32, u32, String),
205
206    /// A function was called with the wrong number of arguments.
207    ///
208    /// Fields: `(line, column, function_name)`
209    ///
210    /// This occurs when calling a function with a different number of arguments
211    /// than what the function signature requires.
212    #[error("{0}:{1}: incorrect number of arguments supplied to function '{2}'")]
213    FunWrongArgumentCount(u32, u32, String),
214
215    /// An aggregate function was used outside of a PROJECT INTO clause.
216    ///
217    /// Fields: `(line, column, function_name)`
218    ///
219    /// This occurs when an aggregate function (e.g., SUM, COUNT, AVG) is used
220    /// in a context where aggregation is not allowed, such as in WHERE, GROUP BY,
221    /// or ORDER BY clauses. Aggregate functions can only be used in the PROJECT INTO
222    /// clause to compute aggregated values over groups of events.
223    ///
224    /// # Example
225    ///
226    /// Invalid usage:
227    /// ```eql
228    /// FROM e IN events
229    /// WHERE COUNT() > 5  // Error: aggregate function in WHERE clause
230    /// PROJECT INTO e
231    /// ```
232    ///
233    /// Valid usage:
234    /// ```eql
235    /// FROM e IN events
236    /// PROJECT INTO { total: COUNT() }
237    /// ```
238    #[error("{0}:{1}: aggregate function '{2}' can only be used in a PROJECT INTO clause")]
239    WrongAggFunUsage(u32, u32, String),
240
241    /// An aggregate function was used together with source-bound fields.
242    ///
243    /// Fields: `(line, column)`
244    ///
245    /// This occurs when attempting to mix aggregate functions with fields that are
246    /// bound to source events within the same projection field. Aggregate functions
247    /// operate on groups of events, while source-bound fields refer to individual
248    /// event properties. These cannot be mixed in a single field expression.
249    ///
250    /// # Example
251    ///
252    /// Invalid usage:
253    /// ```eql
254    /// FROM e IN events
255    /// // Error: mixing aggregate (SUM) with source field (e.id)
256    /// PROJECT INTO { count: SUM(e.data.price), id: e.id }
257    /// ```
258    ///
259    /// Valid usage:
260    /// ```eql
261    /// FROM e IN events
262    /// PROJECT INTO { sum: SUM(e.data.price), label: "total" }
263    /// ```
264    #[error("{0}:{1}: aggregate functions cannot be used with source-bound fields")]
265    UnallowedAggFuncUsageWithSrcField(u32, u32),
266
267    /// An empty record literal was used in a context where it is not allowed.
268    ///
269    /// Fields: `(line, column)`
270    ///
271    /// This occurs when using an empty record `{}` as a projection, which would
272    /// result in a query that produces no output fields. Projections must contain
273    /// at least one field.
274    ///
275    /// # Example
276    ///
277    /// Invalid usage:
278    /// ```eql
279    /// FROM e IN events
280    /// PROJECT INTO {}  // Error: empty record
281    /// ```
282    ///
283    /// Valid usage:
284    /// ```eql
285    /// FROM e IN events
286    /// PROJECT INTO { id: e.id }
287    /// ```
288    #[error("{0}:{1}: unexpected empty record")]
289    EmptyRecord(u32, u32),
290
291    /// An aggregate function was called with an argument that is not a source-bound field.
292    ///
293    /// Fields: `(line, column)`
294    ///
295    /// This occurs when an aggregate function (e.g., SUM, COUNT, AVG) is called with
296    /// an argument that is not derived from source event properties. Aggregate functions
297    /// must operate on fields that come from the source events being queried, not on
298    /// constants, literals, or results from other functions.
299    ///
300    /// # Example
301    ///
302    /// Invalid usage:
303    /// ```eql
304    /// FROM e IN events
305    /// // Error: RAND() is constant value
306    /// PROJECT INTO { sum: SUM(RAND()) }
307    /// ```
308    ///
309    /// Valid usage:
310    /// ```eql
311    /// FROM e IN events
312    /// PROJECT INTO { sum: SUM(e.data.price) }
313    /// ```
314    #[error("{0}:{1}: aggregate functions arguments must be source-bound fields")]
315    ExpectSourceBoundProperty(u32, u32),
316
317    /// A constant expression is used in PROJECT INTO clause.
318    ///
319    /// Fields: `(line, column)`
320    ///
321    /// # Example
322    ///
323    /// Invalid usage:
324    /// ```eql
325    /// FROM e IN events
326    /// // Error: NOW() is constant value
327    /// PROJECT INTO NOW()
328    ///
329    /// ```
330    /// Invalid usage:
331    /// ```eql
332    /// FROM e IN events
333    /// // Error: DAY(NOW()) is also constant value
334    /// PROJECT INTO DAY(NOW())
335    /// ```
336    ///
337    /// Valid usage:
338    /// ```eql
339    /// FROM e IN events
340    /// PROJECT INTO DAY(e.data.date)
341    /// ```
342    #[error("{0}:{1}: constant expressions are forbidden in PROJECT INTO clause")]
343    ConstantExprInProjectIntoClause(u32, u32),
344
345    /// Expect an aggregate expression at this position in the query.
346    ///
347    /// Fields: `(line, column)`
348    ///
349    /// Invalid usage:
350    /// ```eql
351    /// FROM e IN events
352    /// GROUP BY e.data.department
353    /// // ERROR: the order by clause should use an aggregage expresion because GROUP Bys
354    /// // require an aggregate expression in this context.
355    /// ORDER BY e.data.salary
356    /// PROJECT INTO AVG(e.data.salary)
357    /// ```
358    /// Valid usage:
359    /// ```eql
360    /// FROM e IN events
361    /// GROUP BY e.data.department
362    /// ORDER BY AVG(e.data.salary)
363    /// PROJECT INTO AVG(e.data.salary)
364    /// ```
365    #[error("{0}:{1}: expect aggregate expression")]
366    ExpectAggExpr(u32, u32),
367}
368
369impl From<LexerError> for Error {
370    fn from(value: LexerError) -> Self {
371        Self::Lexer(value)
372    }
373}
374
375impl From<ParserError> for Error {
376    fn from(value: ParserError) -> Self {
377        Self::Parser(value)
378    }
379}
380
381impl From<AnalysisError> for Error {
382    fn from(value: AnalysisError) -> Self {
383        Self::Analysis(value)
384    }
385}