mpl-lang 0.5.1

Axioms Metrics Processing Language
Documentation
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! Diagnostics and code actions for `MPL` queries.
use std::collections::HashMap;

use miette::Diagnostic as _;
use serde::Serialize;
use strsim::jaro;
use wasm_bindgen::prelude::*;

use crate::errors::Suggestion;
use crate::query::{Warning, WarningReason};
use crate::{CompileError, GroupError, IfdefError, ParseError, TypeError, compile};

use super::Span;
use super::completions::{
    ALIGN_FN_NAMES, BUCKET_FN_NAMES, COMPUTE_FN_NAMES, GROUP_FN_NAMES, MAP_FN_NAMES,
};

#[derive(Clone, Copy, Serialize)]
#[serde(rename_all = "lowercase")]
pub(super) enum Severity {
    Error,
    Warning,
    Info,
    Hint,
}

#[derive(Clone, Serialize)]
pub(super) struct DiagnosticAction {
    /// notification
    pub(super) name: String,
    /// location to replace/insert
    #[serde(flatten)]
    pub(super) span: Span,
    /// the string to insert/replace the span with
    pub(super) insert: String,
}

impl DiagnosticAction {
    fn replace_with(span: Span, suggestion: &str) -> DiagnosticAction {
        DiagnosticAction {
            name: format!("Replace with `{suggestion}`"),
            span,
            insert: suggestion.to_string(),
        }
    }
}

#[derive(Serialize)]
pub(super) struct DiagnosticItem {
    #[serde(flatten)]
    pub(super) span: Span,
    pub(super) severity: Severity,
    pub(super) message: String,
    pub(super) help: Option<String>,
    pub(super) actions: Vec<DiagnosticAction>,
}

/// Returns diagnostics (errors/warnings) for the given query string.
#[must_use]
#[wasm_bindgen]
pub fn diagnostics(query: &str) -> JsValue {
    let items = match compile(query, HashMap::new()) {
        Ok((_, warnings)) => {
            let mut items: Vec<DiagnosticItem> = warnings
                .as_slice()
                .iter()
                .map(Warning::to_diagnostic_item)
                .collect();
            items.extend(super::lints::detect_hints(query));
            items
        }
        Err(CompileError::Parse(error)) => {
            let items = error.diagnostic_items();
            maybe_rewrite_escaped_dataset_error(query, items)
        }
        Err(CompileError::Type(error)) => error.diagnostic_items(),
        Err(CompileError::Group(error)) => error.diagnostic_items(),
        Err(CompileError::Ifdef(error)) => error.diagnostic_items(),
    };
    super::to_js_value(&items)
}

impl Warning {
    /// Convert a parser-emitted warning to a `DiagnosticItem`.
    ///
    /// Each `WarningReason` variant is responsible for crafting its own
    /// user-facing message, help text, and (where applicable) quick-fix
    /// action — the parser's `Display` impl is intentionally not reused, so
    /// editor-surfaced copy can be tuned without touching the core types.
    pub(super) fn to_diagnostic_item(&self) -> DiagnosticItem {
        let span = self.source().map_or_else(
            || Span::new(0, 0),
            |s| Span::new(s.offset(), s.offset() + s.len()),
        );

        match self.warning() {
            WarningReason::OldDuration => DiagnosticItem {
                span,
                severity: Severity::Warning,
                message: "`duration` is deprecated; use `Duration`".to_string(),
                help: Some(
                    "Param types use PascalCase: `Duration`, `Dataset`, `Regex`".to_string(),
                ),
                actions: vec![DiagnosticAction {
                    name: "Replace with `Duration`".to_string(),
                    span,
                    insert: "Duration".to_string(),
                }],
            },
            WarningReason::ParamNotDeclared(_) | WarningReason::ParamUsingSystemPrefix { .. } => {
                DiagnosticItem {
                    span,
                    severity: Severity::Warning,
                    message: self.warning().to_string(),
                    help: None,
                    actions: vec![],
                }
            }
        }
    }
}

/// When the query starts with a backtick-escaped identifier containing `.`
/// that is not followed by `:`, rewrite the generic parse error to point at
/// the end of the identifier with a message about the missing metric name.
pub(crate) fn maybe_rewrite_escaped_dataset_error(
    query: &str,
    items: Vec<DiagnosticItem>,
) -> Vec<DiagnosticItem> {
    if items.len() != 1 || !matches!(items[0].severity, Severity::Error) {
        return items;
    }

    let Some(ident_end) = find_escaped_ident_end(query, 0) else {
        return items;
    };

    let inner = &query[1..ident_end - 1];

    // Only fire when the backtick ident is NOT followed by `:`
    let rest = query[ident_end..].trim_start();
    if rest.starts_with(':') {
        return items;
    }

    // The inner text has a dot — suggest dataset:metric syntax
    let Some(dot_pos) = inner.find('.') else {
        return items;
    };
    let dataset_part = &inner[..dot_pos];
    let metric_part = &inner[dot_pos + 1..];

    vec![DiagnosticItem {
        span: Span::new(ident_end, ident_end),
        severity: Severity::Error,
        message: "expected ':' and a metric name after the dataset".to_string(),
        help: Some(format!(
            "MPL uses ':' to separate dataset and metric, e.g. `{dataset_part}`:`{metric_part}`"
        )),
        actions: vec![],
    }]
}

/// Finds the byte position just past the closing backtick of an escaped
/// identifier starting at `start`. Returns `None` if no closing backtick.
fn find_escaped_ident_end(s: &str, start: usize) -> Option<usize> {
    let bytes = s.as_bytes();
    if bytes.get(start) != Some(&b'`') {
        return None;
    }
    let mut i = start + 1;
    while i < bytes.len() {
        if bytes[i] == b'\\' {
            i += 2;
        } else if bytes[i] == b'`' {
            return Some(i + 1);
        } else {
            i += 1;
        }
    }
    None
}

impl TypeError {
    pub(super) fn diagnostic_items(&self) -> Vec<DiagnosticItem> {
        let message = self.to_string();
        let help = self.help().map(|h| h.to_string());

        if let Some(labels) = self.labels() {
            let items: Vec<_> = labels
                .map(|label| {
                    let src = label.inner();
                    let span = Span::new(src.offset(), src.offset() + src.len());
                    let is_declaration = label.label().is_some_and(|l| l.contains("declaration"));

                    if is_declaration {
                        DiagnosticItem {
                            span,
                            severity: Severity::Info,
                            message: label.label().unwrap_or("declared here").to_string(),
                            help: None,
                            actions: vec![],
                        }
                    } else {
                        DiagnosticItem {
                            span,
                            severity: Severity::Error,
                            message: message.clone(),
                            help: help.clone(),
                            actions: vec![],
                        }
                    }
                })
                .collect();

            if items.is_empty() {
                vec![DiagnosticItem {
                    span: Span::new(0, 0),
                    severity: Severity::Error,
                    message,
                    help,
                    actions: vec![],
                }]
            } else {
                items
            }
        } else {
            vec![DiagnosticItem {
                span: Span::new(0, 0),
                severity: Severity::Error,
                message,
                help,
                actions: vec![],
            }]
        }
    }
}

impl IfdefError {
    pub(super) fn diagnostic_items(&self) -> Vec<DiagnosticItem> {
        let message = self.to_string();
        let help = self.help().map(|h| h.to_string());
        let span = match self {
            IfdefError::OptionalOutsideOfIfdef { span, .. }
            | IfdefError::OptionalNotUsed { span, .. } => {
                Span::new(span.offset(), span.offset() + span.len())
            }
        };
        vec![DiagnosticItem {
            span,
            severity: Severity::Error,
            message,
            help,
            actions: vec![],
        }]
    }
}

impl GroupError {
    pub(super) fn diagnostic_items(&self) -> Vec<DiagnosticItem> {
        let message = self.to_string();
        let help = self.help().map(|h| h.to_string());
        let (prev_span, next_span) = match self {
            GroupError::InvalidGroups {
                prev_span,
                next_span,
                ..
            } => (
                Span::new(prev_span.offset(), prev_span.offset() + prev_span.len()),
                Span::new(next_span.offset(), next_span.offset() + next_span.len()),
            ),
        };
        vec![
            DiagnosticItem {
                span: prev_span,
                severity: Severity::Info,
                message: "previous groups declared here".to_string(),
                help: None,
                actions: vec![],
            },
            DiagnosticItem {
                span: next_span,
                severity: Severity::Error,
                message,
                help,
                actions: vec![],
            },
        ]
    }
}

impl ParseError {
    pub(super) fn diagnostic_items(&self) -> Vec<DiagnosticItem> {
        let message = self.to_string();
        let help = self.help().map(|h| h.to_string());
        let actions = self.diagnostic_actions();

        if let Some(labels) = self.labels() {
            let items: Vec<_> = labels
                .map(|label| {
                    let src = label.inner();
                    DiagnosticItem {
                        span: Span::new(src.offset(), src.offset() + src.len()),
                        severity: Severity::Error,
                        message: message.clone(),
                        help: help.clone(),
                        actions: actions.clone(),
                    }
                })
                .collect();

            if items.is_empty() {
                vec![DiagnosticItem {
                    span: Span::new(0, 0),
                    severity: Severity::Error,
                    message,
                    help,
                    actions,
                }]
            } else {
                items
            }
        } else {
            vec![DiagnosticItem {
                span: Span::new(0, 0),
                severity: Severity::Error,
                message,
                help,
                actions,
            }]
        }
    }

    /// Extracts quick-fix actions by matching on the error variant and
    /// fuzzy-matching against known function names or keywords.
    fn diagnostic_actions(&self) -> Vec<DiagnosticAction> {
        match self {
            ParseError::SyntaxError {
                span,
                suggestion: Some(suggestion),
                ..
            } => {
                vec![suggestion.to_diagnostic(Span::new(span.offset(), span.offset() + span.len()))]
            }

            ParseError::UnsupportedMapFunction { span, name }
            | ParseError::UnsupportedMapEvaluation { span, name } => {
                suggest_function_replacements(name, span.offset(), &MAP_FN_NAMES)
            }

            ParseError::UnsupportedAlignFunction { span, name } => {
                suggest_function_replacements(name, span.offset(), &ALIGN_FN_NAMES)
            }

            ParseError::UnsupportedGroupFunction { span, name } => {
                suggest_function_replacements(name, span.offset(), &GROUP_FN_NAMES)
            }

            ParseError::UnsupportedComputeFunction { span, name } => {
                suggest_function_replacements(name, span.offset(), &COMPUTE_FN_NAMES)
            }

            ParseError::UnsupportedBucketFunction { span, name } => {
                suggest_function_replacements(name, span.offset(), &BUCKET_FN_NAMES)
            }

            _ => vec![],
        }
    }
}

impl Suggestion {
    /// The suggested text
    fn to_diagnostic(&self, span: Span) -> DiagnosticAction {
        DiagnosticAction::replace_with(span, self.suggestion())
    }
}

/// Fuzzy-matches `input` against `candidates` using Jaro similarity and returns
/// up to 3 replacement actions for the best matches.
fn suggest_function_replacements(
    input: &str,
    from: usize,
    candidates: &[String],
) -> Vec<DiagnosticAction> {
    let input_lc = input.to_lowercase();
    let span = Span::new(from, from + input.len());
    let threshold = 0.8;

    let mut scored: Vec<_> = candidates
        .iter()
        .filter_map(|c| {
            let score = jaro(&input_lc, &c.to_lowercase());
            (score >= threshold).then(|| (c.clone(), score))
        })
        .collect();

    scored.sort_by(|a, b| b.1.total_cmp(&a.1));
    scored.truncate(3);

    scored
        .into_iter()
        .map(|(name, _)| DiagnosticAction::replace_with(span, &name))
        .collect()
}

#[cfg(test)]
mod tests;