dbt-antlr-codegen 0.10.0

ANTLR v4 grammar compiler and Rust source generator
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2026 Bo Lin
//! Build-script entry point: generate recognizers during `cargo build`, in
//! the style of `prost-build` or `lalrpop`.

use std::path::PathBuf;

use crate::OptimizationOptions;
#[cfg(feature = "generator")]
use crate::emission::emit_files_with_options;
use crate::error::{Diagnostic, EmitError, Severity};

/// Generator configuration, primarily for use from a `build.rs` build script.
///
/// With the generator as a build dependency, no separate tool installation is
/// needed and the generator version is pinned by `Cargo.lock` like any other
/// dependency:
///
/// ```toml
/// [dependencies]
/// dbt-antlr-runtime = "0.1"
///
/// [build-dependencies]
/// # default-features = false skips the `fancy` diagnostics rendering the
/// # command-line tool uses; it shrinks the build-dependency tree by ~40%.
/// dbt-antlr-codegen = { version = "0.1", default-features = false, features = ["generator"] }
/// ```
///
/// ```rust,no_run
/// // build.rs
/// dbt_antlr_codegen::Config::new("grammars/Expr.g4")
///     .generate()
///     .unwrap_or_else(|error| panic!("{error:?}"));
/// ```
///
/// Generated files land in the [output directory](Config::out_dir), which
/// defaults to the `OUT_DIR` environment variable cargo sets for build
/// scripts; pull them into the crate with `include!`:
///
/// ```rust,ignore
/// mod expr {
///     #![allow(clippy::all)]
///     include!(concat!(env!("OUT_DIR"), "/exprparser.rs"));
/// }
/// ```
///
/// [`generate`](Config::generate) prints `cargo:rerun-if-changed` directives
/// for the configured grammars and library directories (including each root
/// grammar's own directory, which the loader searches for imported grammars),
/// so the build script reruns exactly when grammar inputs change. It also
/// prints each compiler diagnostic as a `cargo:warning` directive, so that
/// cargo shows the warnings of the grammar (for example `G4S030` for a token
/// that the lexer never emits) in the build output. Call
/// [`quiet`](Config::quiet) to print only the errors.
#[derive(Clone, Debug)]
pub struct Config {
    grammars: Vec<PathBuf>,
    out_dir: Option<PathBuf>,
    lib_dirs: Vec<PathBuf>,
    gen_listener: bool,
    gen_visitor: bool,
    cargo_directives: bool,
    quiet: bool,
    optimization: OptimizationOptions,
    pinned_release_version: Option<String>,
    pinned_release_sha256: Option<String>,
    pinned_release_base_url: Option<String>,
}

impl Config {
    /// Starts a configuration generating from `grammar`.
    pub fn new(grammar: impl Into<PathBuf>) -> Self {
        Self {
            grammars: vec![grammar.into()],
            out_dir: None,
            lib_dirs: Vec::new(),
            gen_listener: true,
            gen_visitor: false,
            cargo_directives: true,
            quiet: false,
            optimization: OptimizationOptions::default(),
            pinned_release_version: None,
            pinned_release_sha256: None,
            pinned_release_base_url: None,
        }
    }

    /// Adds another root grammar to generate from.
    pub fn grammar(&mut self, grammar: impl Into<PathBuf>) -> &mut Self {
        self.grammars.push(grammar.into());
        self
    }

    /// Sets the output directory. Defaults to the `OUT_DIR` environment
    /// variable at [`generate`](Config::generate) time.
    pub fn out_dir(&mut self, out_dir: impl Into<PathBuf>) -> &mut Self {
        self.out_dir = Some(out_dir.into());
        self
    }

    /// Adds a grammar library search directory (the command line's `-lib`):
    /// imported grammars and `tokenVocab` `.tokens` files are looked up here
    /// after the importing grammar's own directory.
    pub fn lib_dir(&mut self, dir: impl Into<PathBuf>) -> &mut Self {
        self.lib_dirs.push(dir.into());
        self
    }

    /// Toggles listener (+ base listener) generation. Default: `true`.
    pub const fn listener(&mut self, generate: bool) -> &mut Self {
        self.gen_listener = generate;
        self
    }

    /// Toggles visitor (+ base visitor) generation. Default: `false`.
    pub const fn visitor(&mut self, generate: bool) -> &mut Self {
        self.gen_visitor = generate;
        self
    }

    /// Toggles printing of `cargo:rerun-if-changed` directives.
    /// Default: `true`.
    pub const fn cargo_directives(&mut self, print: bool) -> &mut Self {
        self.cargo_directives = print;
        self
    }

    /// Stops [`generate`](Config::generate) from printing warning diagnostics
    /// as `cargo:warning` directives (`--quiet`, `-q`). Error diagnostics
    /// are still printed. Default: `false`.
    ///
    /// This setting changes only what is printed:
    /// [`Generation::diagnostics`] still contains all the diagnostics.
    /// Pinned-release generation prints no `cargo:warning` directives, so
    /// this setting has no effect on it.
    pub const fn quiet(&mut self, enabled: bool) -> &mut Self {
        self.quiet = enabled;
        self
    }

    /// Precomputes static lexer DFA tables (`--static-lexer-dfa`, lexer scope
    /// only). Default: `false`.
    /// When the flag is off, the generated output is byte-identical to a run
    /// without it.
    pub const fn static_lexer_dfa(&mut self, enabled: bool) -> &mut Self {
        self.optimization.static_lexer_dfa(enabled);
        self
    }

    /// Precomputes static parser DFA tables (`--static-parser-dfa`, parser
    /// scope only). Default: `false`.
    pub const fn static_parser_dfa(&mut self, enabled: bool) -> &mut Self {
        self.optimization.static_parser_dfa(enabled);
        self
    }

    /// Generates only fully static lexers and parsers (`--static-dfa-only`),
    /// which never fall back to the adaptive ATN simulation. Default: `false`.
    /// See [`OptimizationOptions::static_dfa_only`].
    pub const fn static_dfa_only(&mut self, enabled: bool) -> &mut Self {
        self.optimization.static_dfa_only(enabled);
        self
    }

    /// Renders the static parser DFA tables matching `spec` into
    /// [`Generation::reports`] (`--dump-dfas <SPEC>`, printed to stdout by the
    /// CLI). Implies report-only mode.
    pub fn dump_dfas(&mut self, spec: impl Into<String>) -> &mut Self {
        self.optimization.dump_dfas(spec);
        self
    }

    /// Renders the time and the work that the static parser DFA pass spends
    /// on each parser decision into [`Generation::reports`]
    /// (`--profile-decisions`, printed to stdout by the CLI). Implies
    /// report-only mode.
    pub const fn profile_decisions(&mut self, enabled: bool) -> &mut Self {
        self.optimization.profile_decisions(enabled);
        self
    }

    /// Returns the optimization selection for in-place configuration.
    /// See [`OptimizationOptions`] for the available options. The
    /// convenience setters on [`Config`] delegate to it.
    pub const fn optimization(&mut self) -> &mut OptimizationOptions {
        &mut self.optimization
    }

    /// Marks `name` as an explicit parser entry rule (the command line's
    /// `--entry-rule`). Repeatable.
    pub fn entry_rule(&mut self, name: impl Into<String>) -> &mut Self {
        self.optimization.entry_rule(name);
        self
    }

    /// Deletes parser rules that are unreachable from the entry rules (the
    /// command line's `--prune-unreachable-rules`). Default: `false`.
    pub const fn prune_unreachable_rules(&mut self, enabled: bool) -> &mut Self {
        self.optimization.prune_unreachable_rules(enabled);
        self
    }

    /// Inlines trivial pure parser rules into their call sites (the command
    /// line's `--inline-trivial-rules`). Default: `false`.
    pub const fn inline_trivial_rules(&mut self, enabled: bool) -> &mut Self {
        self.optimization.inline_trivial_rules(enabled);
        self
    }

    /// Collapses precedence-ladder rule chains into left-recursive rules
    /// (`--optimize-precedence-ladders`). Default: `false`.
    pub const fn optimize_precedence_ladders(&mut self, enabled: bool) -> &mut Self {
        self.optimization.optimize_precedence_ladders(enabled);
        self
    }

    /// Compiles, analyzes, and optimizes the input grammars without writing
    /// output files (`--report-only`, `--dry-run`, `-n`). Default: `false`.
    pub const fn report_only(&mut self, enabled: bool) -> &mut Self {
        self.optimization.report_only(enabled);
        self
    }

    /// Reports an implicit token definition in a parser grammar (`G4S030`)
    /// as an error instead of a warning (`--strict`). Default: `false`.
    /// See [`OptimizationOptions::strict`].
    pub const fn strict(&mut self, enabled: bool) -> &mut Self {
        self.optimization.strict(enabled);
        self
    }

    /// Switches generation to a pinned prebuilt `dbt-antlr-codegen` release
    /// binary (requires the `download` feature).
    ///
    /// Instead of compiling and running the generator in-process, the
    /// release archive for the build host's target triple is downloaded from
    /// the GitHub release `dbt-antlr-codegen-v{version}`, verified against a
    /// SHA-256 checksum, cached under the output directory, and invoked with
    /// the configured arguments. Use this in build environments where the
    /// generator's dependency tree is too expensive to compile:
    ///
    /// ```toml
    /// [build-dependencies]
    /// dbt-antlr-codegen = { version = "0.1", default-features = false, features = ["download"] }
    /// ```
    ///
    /// The pinned `version` is independent of this crate's own version.
    /// Requires `curl` on `PATH`.
    #[cfg(feature = "download")]
    pub fn pinned_release(&mut self, version: impl Into<String>) -> &mut Self {
        self.pinned_release_version = Some(version.into());
        self
    }

    /// Pins the expected SHA-256 checksum of the release archive (requires
    /// the `download` feature and [`Config::pinned_release`]). When unset,
    /// the checksum is read from the `.sha256` file published next to the
    /// archive.
    #[cfg(feature = "download")]
    pub fn pinned_release_sha256(&mut self, sha256: impl Into<String>) -> &mut Self {
        self.pinned_release_sha256 = Some(sha256.into());
        self
    }

    /// Overrides the release download base URL (requires the `download`
    /// feature), for mirrors or GitHub Enterprise hosts. Defaults to the
    /// `sdf-labs/dbt-antlr` GitHub releases.
    #[cfg(feature = "download")]
    pub fn pinned_release_base_url(&mut self, base_url: impl Into<String>) -> &mut Self {
        self.pinned_release_base_url = Some(base_url.into());
        self
    }

    /// Generates all configured grammars into the output directory, creating
    /// it when needed, and returns the paths written.
    ///
    /// When [`cargo_directives`](Config::cargo_directives) is on, each
    /// diagnostic of the run is also printed as a `cargo:warning` directive.
    /// With [`quiet`](Config::quiet), only the error diagnostics are printed.
    /// Use [`generate_detailed`](Config::generate_detailed) to get the
    /// diagnostics instead.
    ///
    /// # Errors
    ///
    /// Returns [`EmitError::Config`] when no grammars are configured or no
    /// output directory is available, [`EmitError::Compile`] or
    /// [`EmitError::Template`] when a grammar fails to generate, and
    /// [`EmitError::Write`] when an output file cannot be written.
    // Cargo's build-script protocol reads directives from stdout.
    #[allow(clippy::print_stdout)]
    pub fn generate(&self) -> Result<Vec<PathBuf>, EmitError> {
        let generation = self.generate_detailed()?;
        if self.cargo_directives {
            for directive in cargo_warnings(generation.diagnostics(), self.quiet) {
                println!("{directive}");
            }
        }
        Ok(generation.into_written_files())
    }

    /// [`generate`](Config::generate) with the rest of the run output:
    /// compiler diagnostics (for example unreachable parser rules), transform
    /// notes (for example `pruned: ...` lines), and the reports of the report
    /// modes (`dump_dfas`, `profile_decisions`).
    ///
    /// # Errors
    ///
    /// See [`generate`](Config::generate).
    // Cargo's build-script protocol reads directives from stdout.
    #[allow(clippy::print_stdout)]
    pub fn generate_detailed(&self) -> Result<Generation, EmitError> {
        if self.grammars.is_empty() {
            return Err(EmitError::Config("no grammars configured".to_owned()));
        }
        if self.cargo_directives {
            for grammar in &self.grammars {
                println!("cargo:rerun-if-changed={}", grammar.display());
                if let Some(parent) = grammar.parent().filter(|dir| !dir.as_os_str().is_empty()) {
                    println!("cargo:rerun-if-changed={}", parent.display());
                }
            }
            for dir in &self.lib_dirs {
                println!("cargo:rerun-if-changed={}", dir.display());
            }
        }
        if let Some(version) = &self.pinned_release_version {
            let out_dir = self.output_dir()?;
            create_out_dir(&out_dir)?;
            return self.generate_pinned(version, &out_dir);
        }
        // Report-only runs render their reports without touching the output
        // directory, so it stays optional here.
        let out_dir = if self.optimization.is_report_only() {
            None
        } else {
            let out_dir = self.output_dir()?;
            create_out_dir(&out_dir)?;
            Some(out_dir)
        };
        self.generate_in_process(out_dir.as_deref())
    }

    /// The configured output directory, defaulting to Cargo's `OUT_DIR`.
    fn output_dir(&self) -> Result<PathBuf, EmitError> {
        if let Some(dir) = &self.out_dir {
            return Ok(dir.clone());
        }
        let out_dir = std::env::var_os("OUT_DIR").ok_or_else(|| {
            EmitError::Config(
                "no output directory: call Config::out_dir or run from a build \
                 script (OUT_DIR is not set)"
                    .to_owned(),
            )
        })?;
        Ok(PathBuf::from(out_dir))
    }

    #[cfg(feature = "download")]
    fn generate_pinned(
        &self,
        version: &str,
        out_dir: &std::path::Path,
    ) -> Result<Generation, EmitError> {
        if self.optimization.has_parser_reports() {
            return Err(EmitError::Config(
                "dump_dfas and profile_decisions need the in-process generator; \
                 pinned-release generation cannot render their reports"
                    .to_owned(),
            ));
        }
        let release = crate::download::PinnedRelease {
            version: version.to_owned(),
            expected_sha256: self.pinned_release_sha256.clone(),
            base_url: self.pinned_release_base_url.clone(),
        };
        let written = crate::download::generate_with_pinned_binary(
            &release,
            &self.grammars,
            &self.lib_dirs,
            self.gen_listener,
            self.gen_visitor,
            &self.optimization,
            out_dir,
        )?;
        Ok(Generation {
            written,
            diagnostics: Vec::new(),
            optimization_messages: Vec::new(),
            reports: Vec::new(),
        })
    }

    #[cfg(not(feature = "download"))]
    fn generate_pinned(
        &self,
        version: &str,
        out_dir: &std::path::Path,
    ) -> Result<Generation, EmitError> {
        let _ = (version, out_dir);
        let _ = (&self.pinned_release_sha256, &self.pinned_release_base_url);
        Err(EmitError::Config(
            "pinned_release requires the `download` feature of dbt-antlr-codegen".to_owned(),
        ))
    }

    /// Generates in process. `out_dir` is `None` in report-only mode, where
    /// the run renders reports instead of writing files.
    #[cfg(feature = "generator")]
    fn generate_in_process(
        &self,
        out_dir: Option<&std::path::Path>,
    ) -> Result<Generation, EmitError> {
        let mut written = Vec::new();
        let mut diagnostics = Vec::new();
        let mut optimization_messages = Vec::new();
        let mut reports = Vec::new();
        for grammar in &self.grammars {
            let output = emit_files_with_options(
                grammar,
                &self.lib_dirs,
                self.gen_listener,
                self.gen_visitor,
                &self.optimization,
            )?;
            if let Some(out_dir) = out_dir {
                for file in &output.files {
                    let path = out_dir.join(&file.name);
                    std::fs::write(&path, &file.content).map_err(|source| EmitError::Write {
                        path: path.clone(),
                        source,
                    })?;
                    written.push(path);
                }
                write_optimization_manifest(
                    out_dir,
                    grammar,
                    output.optimization_manifest,
                    &mut written,
                )?;
            }
            diagnostics.extend(output.diagnostics);
            optimization_messages.extend(output.optimization_messages);
            reports.extend(output.reports);
        }
        Ok(Generation {
            written,
            diagnostics,
            optimization_messages,
            reports,
        })
    }

    #[cfg(not(feature = "generator"))]
    fn generate_in_process(
        &self,
        out_dir: Option<&std::path::Path>,
    ) -> Result<Generation, EmitError> {
        let _ = out_dir;
        Err(EmitError::Config(
            "this build of dbt-antlr-codegen was compiled without the `generator` feature; \
             enable it or use Config::pinned_release"
                .to_owned(),
        ))
    }
}

/// The `cargo:warning` directives that show `diagnostics` in the cargo build
/// output. A directive holds one line, so each line of a diagnostic gets its
/// own directive. When `quiet` is set, only the errors get directives.
fn cargo_warnings(diagnostics: &[Diagnostic], quiet: bool) -> Vec<String> {
    diagnostics
        .iter()
        .filter(|diagnostic| !quiet || diagnostic.severity() == Severity::Error)
        .flat_map(|diagnostic| {
            diagnostic
                .to_string()
                .lines()
                .map(|line| format!("cargo:warning={line}"))
                .collect::<Vec<_>>()
        })
        .collect()
}

fn create_out_dir(out_dir: &std::path::Path) -> Result<(), EmitError> {
    std::fs::create_dir_all(out_dir).map_err(|source| EmitError::Write {
        path: out_dir.to_path_buf(),
        source,
    })
}

/// Writes the optimization manifest of `grammar` next to the generated files
/// when the selected transforms produced one, and removes a stale manifest
/// from an earlier optimized run when they did not.
///
/// The manifest file name starts with the lowercase grammar file stem
/// (`clickhouselexer.optimizations.txt`), so that the grammars of a split
/// grammar or of one [`Config`] do not overwrite the manifests of the others.
/// The shared `optimizations.txt` and `optimizations.json` manifests of
/// earlier releases are removed.
#[cfg(feature = "generator")]
fn write_optimization_manifest(
    out_dir: &std::path::Path,
    grammar: &std::path::Path,
    manifest: Option<String>,
    written: &mut Vec<PathBuf>,
) -> Result<(), EmitError> {
    let path = out_dir.join(optimization_manifest_name(grammar));
    match manifest {
        Some(manifest) => {
            std::fs::write(&path, manifest).map_err(|source| EmitError::Write {
                path: path.clone(),
                source,
            })?;
            written.push(path);
        }
        None => remove_stale_manifest(&path)?,
    }
    for legacy in ["optimizations.txt", "optimizations.json"] {
        remove_stale_manifest(&out_dir.join(legacy))?;
    }
    Ok(())
}

/// The file name of the optimization manifest of `grammar`, for example
/// `clickhouseparser.optimizations.txt` for `ClickHouseParser.g4`.
#[cfg(feature = "generator")]
fn optimization_manifest_name(grammar: &std::path::Path) -> String {
    let stem = grammar
        .file_stem()
        .map_or_else(String::new, |stem| stem.to_string_lossy().to_lowercase());
    format!("{stem}.optimizations.txt")
}

#[cfg(feature = "generator")]
fn remove_stale_manifest(path: &std::path::Path) -> Result<(), EmitError> {
    match std::fs::remove_file(path) {
        Ok(()) => Ok(()),
        Err(source) if source.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(source) => Err(EmitError::Write {
            path: path.to_path_buf(),
            source,
        }),
    }
}

/// Files and non-fatal output of [`Config::generate_detailed`].
#[derive(Clone, Debug)]
pub struct Generation {
    written: Vec<PathBuf>,
    diagnostics: Vec<Diagnostic>,
    optimization_messages: Vec<String>,
    reports: Vec<String>,
}

impl Generation {
    /// Every file written into the output directory, in write order.
    pub fn written_files(&self) -> &[PathBuf] {
        &self.written
    }

    /// Diagnostics of the run that did not abort it: warnings (for example
    /// unreachable parser rule warnings) and errors a caller must surface
    /// (for example an unmatched `--dump-dfas` selector). Empty for
    /// pinned-release generation, where diagnostics stay on the release
    /// binary's stderr.
    pub fn diagnostics(&self) -> &[Diagnostic] {
        &self.diagnostics
    }

    /// Transform notes of the run (for example `pruned: ...` lines).
    pub fn optimization_messages(&self) -> &[String] {
        &self.optimization_messages
    }

    /// Rendered reports of the report modes (`dump_dfas` and
    /// `profile_decisions`), in selection order.
    pub fn reports(&self) -> &[String] {
        &self.reports
    }

    /// Consumes the generation and returns the written files.
    pub fn into_written_files(self) -> Vec<PathBuf> {
        self.written
    }
}

#[cfg(all(test, feature = "generator"))]
mod tests {
    use std::path::PathBuf;

    use super::cargo_warnings;
    use crate::error::{Diagnostic, Severity};

    #[test]
    fn cargo_warnings_give_each_diagnostic_line_a_directive() {
        let diagnostics = [
            Diagnostic::new(
                "G4S030",
                Severity::Warning,
                "implicit definition of token CACHE in parser".to_owned(),
                PathBuf::from("P.g4"),
                Some((3, 24)),
                None,
            ),
            Diagnostic::new(
                "G4S192",
                Severity::Warning,
                "first line\nsecond line".to_owned(),
                PathBuf::from("P.g4"),
                None,
                None,
            ),
        ];
        assert_eq!(
            cargo_warnings(&diagnostics, false),
            [
                "cargo:warning=warning[G4S030]: P.g4:3:24: implicit definition of token CACHE in parser",
                "cargo:warning=warning[G4S192]: P.g4: first line",
                "cargo:warning=second line",
            ]
        );
    }

    #[test]
    fn quiet_cargo_warnings_keep_only_the_errors() {
        let diagnostics = [
            Diagnostic::new(
                "G4S192",
                Severity::Warning,
                "lookahead budget".to_owned(),
                PathBuf::from("P.g4"),
                Some((7, 1)),
                None,
            ),
            Diagnostic::new(
                "G4S030",
                Severity::Error,
                "implicit definition of token CACHE in parser".to_owned(),
                PathBuf::from("P.g4"),
                Some((3, 24)),
                None,
            ),
        ];
        assert_eq!(
            cargo_warnings(&diagnostics, true),
            [
                "cargo:warning=error[G4S030]: P.g4:3:24: implicit definition of token CACHE in parser"
            ]
        );
    }
}