1#![allow(unused_assignments)] use std::fmt::{self, Write as _};
5
6use miette::{Diagnostic, SourceSpan};
7use pest::{
8 error::{Error as PestError, ErrorVariant, InputLocation, LineColLocation},
9 iterators::Pair,
10};
11use strsim::jaro;
12
13use crate::{parser::Rule, query::ParamDeclaration};
14
15#[derive(thiserror::Error, Debug, Diagnostic)]
17pub enum ParseError {
18 #[error("MPL syntax error: {message}")]
20 #[diagnostic(code(mpl_lang::syntax_error))]
21 SyntaxError {
22 #[label("{label}")]
24 span: SourceSpan,
25 label: String,
27 message: String,
29 #[help]
31 suggestion: Option<Suggestion>,
32 },
33
34 #[error("This feature is not supported at the moment: {rule:?}")]
35 #[diagnostic(
37 code(mpl_lang::not_supported),
38 help("This feature may be added in a future version")
39 )]
40 NotSupported {
41 #[label("unsupported: {rule:?}")]
43 span: SourceSpan,
44 rule: Rule,
46 },
47
48 #[error("Unexpected rule: {rule:?} expected one of {expected:?}")]
50 #[diagnostic(code(mpl_lang::unexpected_rule))]
51 Unexpected {
52 #[label("unexpected {rule:?}")]
54 span: SourceSpan,
55 rule: Rule,
57 expected: Vec<Rule>,
59 },
60
61 #[error("Found unexpected tokens: {rules:?}")]
63 #[diagnostic(code(mpl_lang::unexpected_tokens))]
64 UnexpectedTokens {
65 #[label("unexpected tokens")]
67 span: SourceSpan,
68 rules: Vec<Rule>,
70 },
71
72 #[error("Unexpected end of input")]
74 #[diagnostic(
75 code(mpl_lang::unexpected_eof),
76 help("The query appears to be incomplete")
77 )]
78 EOF {
79 #[label("expected more input here")]
81 span: SourceSpan,
82 },
83
84 #[error("Invalid float: {0}")]
86 #[diagnostic(code(mpl_lang::invalid_float))]
87 InvalidFloat(#[from] std::num::ParseFloatError),
88
89 #[error("Invalid integer: {0}")]
91 #[diagnostic(code(mpl_lang::invalid_integer))]
92 InvalidInteger(#[from] std::num::ParseIntError),
93
94 #[error("Invalid bool: {0}")]
96 #[diagnostic(code(mpl_lang::invalid_bool))]
97 InvalidBool(#[from] std::str::ParseBoolError),
98
99 #[error("Invalid date: {0}")]
101 #[diagnostic(code(mpl_lang::invalid_date))]
102 InvalidDate(#[from] chrono::ParseError),
103
104 #[error("Invalid Regex: {0}")]
106 #[diagnostic(code(mpl_lang::invalid_regex))]
107 InvalidRegex(#[from] regex::Error),
108
109 #[error("Unsupported align function: {name}")]
111 #[diagnostic(
112 code(mpl_lang::unsupported_align_function),
113 help("Check the documentation for available align functions")
114 )]
115 UnsupportedAlignFunction {
116 #[label("unknown function")]
118 span: SourceSpan,
119 name: String,
121 },
122
123 #[error("Unsupported group function: {name}")]
125 #[diagnostic(
126 code(mpl_lang::unsupported_group_function),
127 help("Check the documentation for available group functions")
128 )]
129 UnsupportedGroupFunction {
130 #[label("unknown function")]
132 span: SourceSpan,
133 name: String,
135 },
136
137 #[error("Unsupported compute function: {name}")]
139 #[diagnostic(
140 code(mpl_lang::unsupported_compute_function),
141 help("Check the documentation for available compute functions")
142 )]
143 UnsupportedComputeFunction {
144 #[label("unknown function")]
146 span: SourceSpan,
147 name: String,
149 },
150
151 #[error("Unsupported bucket function: {name}")]
153 #[diagnostic(
154 code(mpl_lang::unsupported_bucket_function),
155 help(
156 "Available functions: histogram, interpolate_delta_histogram, interpolate_cumulative_histogram"
157 )
158 )]
159 UnsupportedBucketFunction {
160 #[label("unknown function")]
162 span: SourceSpan,
163 name: String,
165 },
166
167 #[error("Unsupported map evaluation: {name}")]
169 #[diagnostic(
170 code(mpl_lang::unsupported_map_evaluation),
171 help("Check the documentation for available map operations")
172 )]
173 UnsupportedMapEvaluation {
174 #[label("unknown operation")]
176 span: SourceSpan,
177 name: String,
179 },
180
181 #[error("Unsupported map function: {name}")]
183 #[diagnostic(
184 code(mpl_lang::unsupported_map_function),
185 help("Check the documentation for available map functions")
186 )]
187 UnsupportedMapFunction {
188 #[label("unknown function")]
190 span: SourceSpan,
191 name: String,
193 },
194
195 #[error("Unsupported regexp comparison: {op}")]
197 #[diagnostic(
198 code(mpl_lang::unsupported_regexp_comparison),
199 help("Use '==' or '!=' for regex comparisons")
200 )]
201 UnsupportedRegexpComparison {
202 #[label("invalid operator")]
204 span: SourceSpan,
205 op: String,
207 },
208
209 #[error("Unsupported tag comparison: {op}")]
211 #[diagnostic(
212 code(mpl_lang::unsupported_tag_comparison),
213 help("Supported operators: ==, !=, >, >=, <, <=")
214 )]
215 UnsupportedTagComparison {
216 #[label("invalid operator")]
218 span: SourceSpan,
219 op: String,
221 },
222
223 #[error("Not implemented: {0}")]
225 #[diagnostic(
226 code(mpl_lang::not_implemented),
227 help("This feature is planned but not yet implemented")
228 )]
229 NotImplemented(&'static str),
230
231 #[error("String construction error: {0}")]
233 #[diagnostic(code(mpl_lang::strumbra_error))]
234 StrumbraError(#[from] strumbra::Error),
235
236 #[error("Unreachable error: {0}")]
238 #[diagnostic(
239 code(mpl_lang::unreachable),
240 help("This error should never be reached")
241 )]
242 Unreachable(&'static str),
243
244 #[error("The param ${param} is defined multiple times")]
246 #[diagnostic(
247 code(mpl_lang::param_defined_multiple_times),
248 help("This param has been defined more than once")
249 )]
250 ParamDefinedMultipleTimes {
251 #[label("duplicate definition")]
253 span: SourceSpan,
254 param: String,
256 },
257
258 #[error("The param ${param} is not defined")]
260 #[diagnostic(code(mpl_lang::undefined_param))]
261 UndefinedParam {
262 #[label("undefined param")]
264 span: SourceSpan,
265 param: String,
267 },
268 #[error("The type {tpe} is not a valid type for tags")]
270 #[diagnostic(code(mpl_lang::invalid_tag_type))]
271 InvalidTagType {
272 #[label("invalid type")]
274 span: miette::SourceSpan,
275 tpe: String,
277 },
278 #[error("The parameter {} is not declared as optional", param.name)]
280 #[diagnostic(code(mpl_lang::ifdef_not_optional))]
281 IfdefNotOptional {
282 #[label("param declaration")]
284 span: miette::SourceSpan,
285 param: ParamDeclaration,
287 },
288}
289
290impl From<PestError<Rule>> for ParseError {
291 fn from(err: PestError<Rule>) -> Self {
292 let (start, mut len) = match err.location {
293 InputLocation::Pos(pos) => (pos, 0),
294 InputLocation::Span((start, end)) => (start, end - start),
295 };
296
297 let (label, message, suggestion) = match &err.variant {
298 ErrorVariant::ParsingError {
299 positives,
300 negatives,
301 } => {
302 let mut keywords = Vec::new();
303 let mut operations = Vec::new();
304 let mut other = Vec::new();
305
306 for rule in positives {
307 let name = friendly_rule(*rule);
308 if name.contains("keyword") {
309 keywords.push(name);
310 } else if name.contains("operation") {
311 operations.push(name);
312 } else {
313 other.push(name);
314 }
315 }
316
317 let mut label = String::new();
318 if keywords.is_empty() && operations.is_empty() && other.is_empty() {
319 label.push_str("unexpected token");
320 } else {
321 label.push_str("expected one of:\n");
322 if !keywords.is_empty() {
323 let kws: Vec<_> = keywords
324 .iter()
325 .map(|k| k.trim_end_matches(" keyword"))
326 .collect();
327 let _ = writeln!(label, " keywords: {}", join_with_or(&kws));
328 }
329 if !operations.is_empty() {
330 let ops: Vec<_> = operations
331 .iter()
332 .map(|o| {
333 o.trim_start_matches("a ")
334 .trim_start_matches("an ")
335 .trim_end_matches(" operation")
336 })
337 .collect();
338 let _ = writeln!(label, " operations: {}", join_with_or(&ops));
339 }
340 if !other.is_empty() {
341 for name in &other {
342 let _ = writeln!(label, " - {name}");
343 }
344 }
345 }
346
347 let mut msg = "unexpected token or operation".to_string();
348 if !negatives.is_empty() {
349 if !msg.is_empty() {
350 msg.push_str(" ");
351 }
352 msg.push_str("but found ");
353 msg.push_str(&friendly_rules(negatives));
354 }
355
356 let line_pos = match &err.line_col {
357 LineColLocation::Pos((_, col)) | LineColLocation::Span((_, col), _) => {
358 col.saturating_sub(1)
359 }
360 };
361 let suggestion = generate_suggestion(err.line(), line_pos, positives);
362
363 if len == 0 {
365 len = token_length(err.line(), line_pos);
366 }
367
368 let label = label.trim_end().to_string();
369 (label, msg, suggestion)
370 }
371 ErrorVariant::CustomError { message } => (message.clone(), message.clone(), None),
372 };
373
374 ParseError::SyntaxError {
375 span: SourceSpan::new(start.into(), len),
376 label,
377 message,
378 suggestion,
379 }
380 }
381}
382
383fn join_with_or(items: &[&str]) -> String {
385 match items.len() {
386 0 => String::new(),
387 1 => items[0].to_string(),
388 2 => format!("{} or {}", items[0], items[1]),
389 _ => {
390 let last = items[items.len() - 1];
391 let rest = &items[..items.len() - 1];
392 format!("{}, or {last}", rest.join(", "))
393 }
394 }
395}
396
397pub(crate) fn pair_to_source_span(pair: &Pair<Rule>) -> SourceSpan {
399 let span = pair.as_span();
400 let start = span.start();
401 let len = span.end() - start;
402 SourceSpan::new(start.into(), len)
403}
404
405fn friendly_rules(rules: &[Rule]) -> String {
407 let names: Vec<_> = rules.iter().copied().map(friendly_rule).collect();
408
409 match names.len() {
410 0 => String::new(),
411 1 => names[0].clone(),
412 2 => format!("{} or {}", names[0], names[1]),
413 _ => {
414 let last = &names[names.len() - 1];
415 let rest = &names[..names.len() - 1];
416 format!("{}, or {last}", rest.join(", "))
417 }
418 }
419}
420
421fn friendly_rule(rule: Rule) -> String {
423 match rule {
424 Rule::EOI => "end of query".to_string(),
426 Rule::pipe_keyword => "`|` (pipe)".to_string(),
427
428 Rule::time_range => "time range (e.g., [1h..])".to_string(),
430 Rule::time_relative => "relative time (e.g., 5m, 1h, 7d)".to_string(),
431 Rule::time_timestamp => "timestamp".to_string(),
432 Rule::time_rfc_3339 => "RFC3339 timestamp".to_string(),
433 Rule::time_modifier => "time modifier".to_string(),
434
435 Rule::filter_keyword | Rule::kw_filter => "`filter` keyword".to_string(),
437 Rule::kw_where => "`where` keyword".to_string(),
438 Rule::r#as => "`as` keyword".to_string(),
439
440 Rule::cmp => "a comparison operator (==, !=, <, >, <=, >=)".to_string(),
442 Rule::cmp_re => "a regex operator (==, !=)".to_string(),
443 Rule::regex => "a regex pattern (e.g., /pattern/)".to_string(),
444
445 Rule::value => "value (string, number, or bool)".to_string(),
447 Rule::string => "string value".to_string(),
448 Rule::number => "number".to_string(),
449 Rule::bool => "bool (true or false)".to_string(),
450
451 Rule::plain_ident => "identifier".to_string(),
453 Rule::escaped_ident => "escaped identifier".to_string(),
454 Rule::source => "source metric".to_string(),
455 Rule::metric_name => "metric name".to_string(),
456 Rule::metric_id => "metric identifier (e.g., dataset:metric)".to_string(),
457 Rule::dataset => "dataset name".to_string(),
458
459 Rule::align => "an align operation".to_string(),
461 Rule::group_by => "a group by operation".to_string(),
462 Rule::bucket_by => "a bucket by operation".to_string(),
463 Rule::map => "a map operation".to_string(),
464 Rule::replace => "a replace operation".to_string(),
465 Rule::join => "a join operation".to_string(),
466
467 Rule::simple_query => "simple query".to_string(),
469 Rule::compute_query => "compute query".to_string(),
470
471 Rule::directive => "directive".to_string(),
473
474 Rule::param => "param".to_string(),
476 Rule::param_ident => "param identifier".to_string(),
477 Rule::param_type => {
478 "param type (Duration, Dataset, Regex, string, int, float, bool)".to_string()
479 }
480
481 Rule::func => "function".to_string(),
483 Rule::compute_fn => "compute function".to_string(),
484 Rule::bucket_by_fn => {
485 "bucket function (histogram, interpolate_delta_histogram)".to_string()
486 }
487 Rule::bucket_by_with_conversion_fn => {
488 "bucket function (interpolate_cumulative_histogram)".to_string()
489 }
490 Rule::bucket_conversion => "conversion method (rate, increase)".to_string(),
491 Rule::bucket_specs => "bucket specifications".to_string(),
492 Rule::bucket_fn_call | Rule::bucket_fn_call_simple => "bucket function call".to_string(),
493 Rule::bucket_fn_call_with_conversion => "bucket function call with conversion".to_string(),
494
495 Rule::filter_rule => "filter rule".to_string(),
497 Rule::filter_expr => "filter expression".to_string(),
498 Rule::sample_expr => "sample expression".to_string(),
499 Rule::value_filter => "value filter".to_string(),
500 Rule::regex_filter => "regex filter".to_string(),
501 Rule::kw_is => "`is` keyword".to_string(),
502 Rule::is_filter => "type filter (e.g., is string)".to_string(),
503 Rule::tag_type => "tag type (string, int, float, or bool)".to_string(),
504
505 Rule::tags => "tags (comma-separated field names)".to_string(),
507 Rule::tag => "tag name".to_string(),
508
509 _ => {
511 let name = format!("{rule:?}");
512 name.to_lowercase().replace('_', " ")
513 }
514 }
515}
516
517#[derive(Debug, Clone)]
519pub struct Suggestion(String);
520
521impl Suggestion {
522 #[must_use]
524 pub fn suggestion(&self) -> &str {
525 &self.0
526 }
527}
528
529impl fmt::Display for Suggestion {
530 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
531 write!(f, "Did you mean \"{}\"?", self.0)
532 }
533}
534
535fn generate_suggestion(
537 line: &str,
538 error_pos: usize,
539 expected_rules: &[Rule],
540) -> Option<Suggestion> {
541 let actual_token = extract_token(line, error_pos)?;
542
543 if actual_token.len() < 2 {
544 return None;
545 }
546
547 let possible_keywords = rules_keywords(expected_rules);
548
549 let mut best_match: Option<(&str, f64)> = None;
550
551 for keyword in &possible_keywords {
552 let similarity = jaro(&actual_token.to_lowercase(), &keyword.to_lowercase());
553
554 if similarity > 0.8 {
555 if let Some((_, best_score)) = best_match {
556 if similarity > best_score {
557 best_match = Some((keyword, similarity));
558 }
559 } else {
560 best_match = Some((keyword, similarity));
561 }
562 }
563 }
564
565 best_match.map(|(keyword, _)| Suggestion(keyword.to_string()))
566}
567
568fn extract_token(line: &str, pos: usize) -> Option<String> {
570 let chars: Vec<char> = line.chars().collect();
571
572 if pos >= chars.len() {
573 return None;
574 }
575
576 let mut pos = pos;
578 while pos < chars.len() && chars[pos].is_whitespace() {
579 pos += 1;
580 }
581
582 if pos >= chars.len() {
583 return None;
584 }
585
586 let mut start = pos;
588 while start > 0 && chars[start - 1].is_alphanumeric() {
589 start -= 1;
590 }
591
592 let mut end = pos;
594 while end < chars.len() && chars[end].is_alphanumeric() {
595 end += 1;
596 }
597
598 if start < end {
599 Some(chars[start..end].iter().collect())
600 } else {
601 None
602 }
603}
604
605fn token_length(line: &str, pos: usize) -> usize {
607 let chars: Vec<char> = line.chars().collect();
608
609 if pos >= chars.len() {
610 return 0;
611 }
612
613 if !chars[pos].is_alphanumeric() {
614 return 1;
615 }
616
617 let mut end = pos;
618 while end < chars.len() && chars[end].is_alphanumeric() {
619 end += 1;
620 }
621
622 end - pos
623}
624
625fn rules_keywords(rules: &[Rule]) -> Vec<&'static str> {
627 let mut keywords = Vec::new();
628
629 for rule in rules {
630 match rule {
631 Rule::filter_keyword | Rule::kw_filter | Rule::kw_where => {
632 keywords.push("where");
633 keywords.push("filter");
634 }
635 Rule::r#as => keywords.push("as"),
636 Rule::align => keywords.push("align"),
637 Rule::group_by => keywords.push("group"),
638 Rule::bucket_by => keywords.push("bucket"),
639 Rule::map => keywords.push("map"),
640 Rule::replace => keywords.push("replace"),
641 Rule::join => keywords.push("join"),
642 Rule::kw_is => keywords.push("is"),
643 Rule::tag_type => {
644 keywords.push("string");
645 keywords.push("int");
646 keywords.push("float");
647 keywords.push("bool");
648 }
649 _ => {}
650 }
651 }
652
653 keywords
654}