libgraphql-parser 0.0.5

A blazing fast, error-focused, lossless GraphQL parser for schema, executable, and mixed documents.
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
409
410
411
use crate::GraphQLErrorNote;
use crate::GraphQLErrorNoteKind;
use crate::GraphQLParseErrorKind;
use crate::smallvec::SmallVec;
use crate::SourceSpan;

/// A parse error with location information and contextual notes.
///
/// This structure provides comprehensive error information for both
/// human-readable CLI output and programmatic handling by tools.
#[derive(Debug, Clone)]
pub struct GraphQLParseError {
    /// Human-readable primary error message.
    ///
    /// This is the main error description shown to users.
    /// Examples: "Expected `:` after field name", "Unclosed `{`"
    message: String,

    /// Categorized error kind for programmatic handling.
    ///
    /// Enables tools to pattern-match on error types without parsing messages.
    kind: GraphQLParseErrorKind,

    /// Additional notes providing context, suggestions, and related locations.
    ///
    /// Each note has a kind (General, Help, Spec), message, and optional span:
    /// - With span: Points to a related location (e.g., "opening `{` here")
    /// - Without span: General advice not tied to a specific location
    ///
    /// Uses `SmallVec<[GraphQLErrorNote; 2]>` for consistency with lexer errors.
    notes: SmallVec<[GraphQLErrorNote; 2]>,

    /// Pre-resolved source span with line/column/byte-offset/file info.
    ///
    /// Eagerly resolved at construction time from the `SourceMap`, so
    /// all position information (including byte offsets) is always
    /// available without requiring a `SourceMap` at access time.
    ///
    /// The `SourcePosition::byte_offset()` values on
    /// `start_inclusive` / `end_exclusive` carry the original byte
    /// offsets from the `ByteSpan` that was resolved — these are the
    /// same synthetic offsets used for `SpanMap` lookup in the
    /// proc-macro path.
    source_span: SourceSpan,
}

impl GraphQLParseError {
    /// Creates a new parse error with no notes.
    pub fn new(
        message: impl Into<String>,
        kind: GraphQLParseErrorKind,
        source_span: SourceSpan,
    ) -> Self {
        Self {
            message: message.into(),
            kind,
            notes: SmallVec::new(),
            source_span,
        }
    }

    /// Creates a new parse error with notes.
    pub fn with_notes(
        message: impl Into<String>,
        kind: GraphQLParseErrorKind,
        notes: SmallVec<[GraphQLErrorNote; 2]>,
        source_span: SourceSpan,
    ) -> Self {
        Self {
            message: message.into(),
            kind,
            notes,
            source_span,
        }
    }

    /// Creates a parse error from a lexer error token.
    ///
    /// When the parser encounters a `GraphQLTokenKind::Error` token,
    /// this method converts it to a `GraphQLParseError`, preserving
    /// the lexer's message and notes.
    pub fn from_lexer_error(
        message: impl Into<String>,
        lexer_notes: SmallVec<[GraphQLErrorNote; 2]>,
        source_span: SourceSpan,
    ) -> Self {
        Self {
            message: message.into(),
            kind: GraphQLParseErrorKind::LexerError,
            notes: lexer_notes,
            source_span,
        }
    }

    /// Returns the human-readable error message.
    pub fn message(&self) -> &str {
        &self.message
    }

    /// Returns the pre-resolved source span for this error.
    ///
    /// This span is resolved at construction time, so it is always
    /// available without a `SourceMap`. When the error was
    /// constructed without position info, this returns a
    /// zero-position span.
    ///
    /// The `SourcePosition::byte_offset()` values on
    /// `start_inclusive` / `end_exclusive` carry the original byte
    /// offsets that can be used for `SpanMap` lookup or
    /// `SourceMap::resolve_offset()` calls.
    pub fn source_span(&self) -> &SourceSpan {
        &self.source_span
    }

    /// Returns the categorized error kind.
    pub fn kind(&self) -> &GraphQLParseErrorKind {
        &self.kind
    }

    /// Returns the additional notes for this error.
    pub fn notes(&self) -> &SmallVec<[GraphQLErrorNote; 2]> {
        &self.notes
    }

    /// Adds a general note without a span.
    pub fn add_note(&mut self, message: impl Into<String>) {
        self.notes.push(GraphQLErrorNote::general(message));
    }

    /// Adds a general note with a pre-resolved span (pointing to
    /// a related location).
    pub fn add_note_with_span(
        &mut self,
        message: impl Into<String>,
        span: SourceSpan,
    ) {
        self.notes.push(
            GraphQLErrorNote::general_with_span(message, span),
        );
    }

    /// Adds a help note without a span.
    pub fn add_help(&mut self, message: impl Into<String>) {
        self.notes.push(GraphQLErrorNote::help(message));
    }

    /// Adds a help note with a pre-resolved span.
    pub fn add_help_with_span(
        &mut self,
        message: impl Into<String>,
        span: SourceSpan,
    ) {
        self.notes.push(
            GraphQLErrorNote::help_with_span(message, span),
        );
    }

    /// Adds a spec reference note.
    pub fn add_spec(&mut self, url: impl Into<String>) {
        self.notes.push(GraphQLErrorNote::spec(url));
    }

    /// Formats this error as a diagnostic string for CLI output.
    ///
    /// Produces output like:
    /// ```text
    /// error: Expected `:` after field name
    ///   --> schema.graphql:5:12
    ///    |
    ///  5 |     userName String
    ///    |              ^^^^^^
    ///    |
    ///    = note: Field definitions require `:` between name and type
    ///    = help: Did you mean: `userName: String`?
    /// ```
    ///
    /// All position information (file path, line, column) comes
    /// from the pre-resolved `source_span` and note spans. The
    /// optional `source` parameter provides the original source
    /// text for snippet display — when `None`, the diagnostic
    /// omits source snippets but still shows the error header,
    /// location, and notes.
    pub fn format_detailed(
        &self,
        source: Option<&str>,
    ) -> String {
        let mut output = String::new();

        // Error header
        output.push_str("error: ");
        output.push_str(&self.message);
        output.push('\n');

        // Location line
        let file_name = self.source_span.file_path
            .as_ref()
            .map(|p| p.display().to_string())
            .unwrap_or_else(|| "<input>".to_string());
        let line =
            self.source_span.start_inclusive.line() + 1;
        let column =
            self.source_span.start_inclusive.col_utf8() + 1;
        output.push_str(
            &format!("  --> {file_name}:{line}:{column}\n"),
        );

        // Source snippet
        if let Some(snippet) =
            self.format_source_snippet(source)
        {
            output.push_str(&snippet);
        }

        // Notes
        for note in &self.notes {
            let prefix = match note.kind {
                GraphQLErrorNoteKind::General => "note",
                GraphQLErrorNoteKind::Help => "help",
                GraphQLErrorNoteKind::Spec => "spec",
            };
            output.push_str(
                &format!(
                    "   = {prefix}: {}\n",
                    note.message,
                ),
            );

            if let Some(note_span) = &note.span
                && let Some(snippet) =
                    Self::format_note_snippet(
                        source, note_span,
                    )
            {
                output.push_str(&snippet);
            }
        }

        output
    }

    /// Formats this error as a single-line summary.
    ///
    /// Produces output like:
    /// ```text
    /// schema.graphql:5:12: error: Expected `:` after field name
    /// ```
    ///
    /// This is equivalent to the `Display` impl. Prefer using
    /// `format!("{error}")` or `error.to_string()` directly.
    pub fn format_oneline(&self) -> String {
        self.to_string()
    }

    /// Formats the source snippet for the primary error span.
    fn format_source_snippet(
        &self,
        source: Option<&str>,
    ) -> Option<String> {
        let source = source?;
        let start_pos = &self.source_span.start_inclusive;
        let end_pos = &self.source_span.end_exclusive;

        let line_num = start_pos.line();
        let line_content = get_line(source, line_num)?;
        let display_line_num = line_num + 1;
        let line_num_width =
            display_line_num.to_string().len().max(2);

        let mut output = String::new();

        // Separator line
        output.push_str(
            &format!(
                "{:>width$} |\n",
                "",
                width = line_num_width,
            ),
        );

        // Source line
        output.push_str(&format!(
            "{display_line_num:>line_num_width$} | \
             {line_content}\n"
        ));

        // Underline (caret line)
        let col_start = start_pos.col_utf8();
        let col_end = end_pos.col_utf8();
        let underline_len = if col_end > col_start {
            col_end - col_start
        } else {
            1
        };

        output.push_str(&format!(
            "{:>width$} | {:>padding$}{}\n",
            "",
            "",
            "^".repeat(underline_len),
            width = line_num_width,
            padding = col_start
        ));

        Some(output)
    }

    /// Formats a source snippet for a note's pre-resolved span.
    fn format_note_snippet(
        source: Option<&str>,
        span: &SourceSpan,
    ) -> Option<String> {
        let source = source?;
        let start_pos = &span.start_inclusive;

        let line_num = start_pos.line();
        let line_content = get_line(source, line_num)?;
        let display_line_num = line_num + 1;
        let line_num_width =
            display_line_num.to_string().len().max(2);

        let mut output = String::new();

        // Source line with line number
        output.push_str(&format!(
            "     {display_line_num:>line_num_width$} | \
             {line_content}\n"
        ));

        // Underline
        let col_start = start_pos.col_utf8();
        output.push_str(&format!(
            "     {:>width$} | {:>padding$}-\n",
            "",
            "",
            width = line_num_width,
            padding = col_start
        ));

        Some(output)
    }
}

impl std::fmt::Display for GraphQLParseError {
    fn fmt(
        &self,
        f: &mut std::fmt::Formatter<'_>,
    ) -> std::fmt::Result {
        let file_name = self.source_span.file_path
            .as_ref()
            .map(|p| p.display().to_string())
            .unwrap_or_else(|| "<input>".to_string());
        let line =
            self.source_span.start_inclusive.line() + 1;
        let col =
            self.source_span.start_inclusive.col_utf8() + 1;
        write!(
            f,
            "{file_name}:{line}:{col}: error: {}",
            self.message,
        )
    }
}

impl std::error::Error for GraphQLParseError {}

/// Extracts the content of the line at the given 0-based line
/// index from source text.
///
/// Recognizes `\n`, `\r\n`, and bare `\r` as line terminators per
/// the GraphQL spec (Section 2.2). The returned line content is
/// stripped of its trailing line terminator.
///
/// Returns `None` if `line_index` is out of bounds.
///
/// Note: `SourceMap::get_line()` provides similar functionality but
/// uses a pre-computed `line_starts` table for O(1) line-start
/// lookup. This version scans from the beginning each time (O(n)),
/// which is fine for error formatting but would be less suitable
/// for hot paths. Both must use the same line-terminator semantics.
fn get_line(source: &str, line_index: usize) -> Option<&str> {
    let bytes = source.as_bytes();
    let mut current_line = 0;
    let mut pos = 0;

    // Skip lines until we reach the target line index
    while current_line < line_index {
        match memchr::memchr2(b'\n', b'\r', &bytes[pos..]) {
            Some(offset) => {
                pos += offset;
                if bytes[pos] == b'\r'
                    && pos + 1 < bytes.len()
                    && bytes[pos + 1] == b'\n'
                {
                    pos += 2; // \r\n
                } else {
                    pos += 1; // \n or bare \r
                }
                current_line += 1;
            },
            None => return None, // line_index exceeds line count
        }
    }

    // Find the end of the target line
    let line_start = pos;
    let line_end = memchr::memchr2(b'\n', b'\r', &bytes[pos..])
        .map(|offset| pos + offset)
        .unwrap_or(bytes.len());

    Some(&source[line_start..line_end])
}