Skip to main content

rustdoc/
doctest.rs

1mod extracted;
2mod make;
3mod markdown;
4mod runner;
5mod rust;
6
7use std::fs::File;
8use std::hash::{Hash, Hasher};
9use std::io::{self, Write};
10use std::path::{Path, PathBuf};
11use std::process::{self, Command, ExitCode, Stdio};
12use std::str::FromStr;
13use std::sync::atomic::{AtomicUsize, Ordering};
14use std::sync::{Arc, Mutex};
15use std::time::{Duration, Instant};
16use std::{panic, str};
17
18pub(crate) use make::{BuildDocTestBuilder, DocTestBuilder};
19pub(crate) use markdown::test as test_markdown;
20use proc_macro2::{TokenStream, TokenTree};
21use rustc_attr_ir::{Attribute, AttributeKind};
22use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxHasher, FxIndexMap, FxIndexSet};
23use rustc_errors::emitter::HumanReadableErrorType;
24use rustc_errors::{ColorConfig, DiagCtxtHandle};
25use rustc_hir::CRATE_HIR_ID;
26use rustc_hir::def_id::LOCAL_CRATE;
27use rustc_interface::interface;
28use rustc_lint as lint;
29use rustc_middle::ty::TyCtxt;
30use rustc_session::config::{self, Input};
31use rustc_session::output::ErrorOutputType;
32use rustc_span::edition::Edition;
33use rustc_span::{FileName, RemapPathScopeComponents, Span};
34use rustc_structures::CrateType;
35use rustc_target::spec::{Target, TargetTuple};
36use tempfile::{Builder as TempFileBuilder, TempDir};
37use tracing::{debug, info};
38
39use self::rust::HirCollector;
40use crate::config::{MergeDoctests, Options as RustdocOptions, OutputFormat};
41use crate::html::markdown::{CodeBlockPosition, CodeLineMapping, ErrorCodes, Ignore, LangString};
42use crate::lint::init_lints;
43
44/// Type used to display times (compilation and total) information for merged doctests.
45struct MergedDoctestTimes {
46    total_time: Instant,
47    /// Total time spent compiling all merged doctests.
48    compilation_time: Duration,
49    /// This field is used to keep track of how many merged doctests we (tried to) compile.
50    added_compilation_times: usize,
51}
52
53impl MergedDoctestTimes {
54    fn new() -> Self {
55        Self {
56            total_time: Instant::now(),
57            compilation_time: Duration::default(),
58            added_compilation_times: 0,
59        }
60    }
61
62    fn add_compilation_time(&mut self, duration: Duration) {
63        self.compilation_time += duration;
64        self.added_compilation_times += 1;
65    }
66
67    /// Returns `(total_time, compilation_time)`.
68    fn times_in_secs(&self) -> Option<(f64, f64)> {
69        // If no merged doctest was compiled, then there is nothing to display since the numbers
70        // displayed by `libtest` for standalone tests are already accurate (they include both
71        // compilation and runtime).
72        if self.added_compilation_times == 0 {
73            return None;
74        }
75        Some((self.total_time.elapsed().as_secs_f64(), self.compilation_time.as_secs_f64()))
76    }
77}
78
79/// Options that apply to all doctests in a crate or Markdown file (for `rustdoc foo.md`).
80#[derive(Clone)]
81pub(crate) struct GlobalTestOptions {
82    /// Name of the crate (for regular `rustdoc`) or Markdown file (for `rustdoc foo.md`).
83    pub(crate) crate_name: String,
84    /// Whether to disable the default `extern crate my_crate;` when creating doctests.
85    pub(crate) no_crate_inject: bool,
86    /// Whether inserting extra indent spaces in code block,
87    /// default is `false`, only `true` for generating code link of Rust playground
88    pub(crate) insert_indent_space: bool,
89    /// Path to file containing arguments for the invocation of rustc.
90    pub(crate) args_file: PathBuf,
91}
92
93pub(crate) fn generate_args_file(file_path: &Path, options: &RustdocOptions) -> Result<(), String> {
94    let mut file = File::create(file_path)
95        .map_err(|error| format!("failed to create args file: {error:?}"))?;
96
97    // We now put the common arguments into the file we created.
98    let mut content = vec![];
99
100    for cfg in &options.cfgs {
101        content.push(format!("--cfg={cfg}"));
102    }
103    for check_cfg in &options.check_cfgs {
104        content.push(format!("--check-cfg={check_cfg}"));
105    }
106
107    for prefix in &options.remap_path_prefix_strs {
108        content.push(format!("--remap-path-prefix={prefix}"));
109    }
110    if let Some(scope) = &options.remap_path_scope_str {
111        content.push(format!("--remap-path-scope={scope}"));
112    }
113
114    for lib_str in &options.lib_strs {
115        content.push(format!("-L{lib_str}"));
116    }
117    for extern_str in &options.extern_strs {
118        content.push(format!("--extern={extern_str}"));
119    }
120    content.push("-Ccodegen-units=1".to_string());
121    for codegen_options_str in &options.codegen_options_strs {
122        content.push(format!("-C{codegen_options_str}"));
123    }
124    for unstable_option_str in &options.unstable_opts_strs {
125        content.push(format!("-Z{unstable_option_str}"));
126    }
127
128    content.extend(options.doctest_build_args.clone());
129
130    let content = content.join("\n");
131
132    file.write_all(content.as_bytes())
133        .map_err(|error| format!("failed to write arguments to temporary file: {error:?}"))?;
134    Ok(())
135}
136
137fn get_doctest_dir(opts: &RustdocOptions) -> io::Result<TempDir> {
138    let mut builder = TempFileBuilder::new();
139    builder.prefix("rustdoctest");
140    if opts.codegen_options.save_temps {
141        builder.disable_cleanup(true);
142    }
143    builder.tempdir()
144}
145
146pub(crate) fn run(dcx: DiagCtxtHandle<'_>, input: Input, options: RustdocOptions) -> ExitCode {
147    let invalid_codeblock_attributes_name = crate::lint::INVALID_CODEBLOCK_ATTRIBUTES.name;
148
149    // See core::create_config for what's going on here.
150    let allowed_lints = vec![
151        invalid_codeblock_attributes_name.to_owned(),
152        lint::builtin::UNKNOWN_LINTS.name.to_owned(),
153        lint::builtin::RENAMED_AND_REMOVED_LINTS.name.to_owned(),
154    ];
155
156    let (lint_opts, lint_caps) = init_lints(allowed_lints, options.lint_opts.clone(), |lint| {
157        if lint.name == invalid_codeblock_attributes_name {
158            None
159        } else {
160            Some((lint.name_lower(), lint::Allow))
161        }
162    });
163
164    debug!(?lint_opts);
165
166    let crate_types =
167        if options.proc_macro_crate { vec![CrateType::ProcMacro] } else { vec![CrateType::Rlib] };
168
169    let sessopts = config::Options {
170        sysroot: options.sysroot.clone(),
171        search_paths: options.libs.clone(),
172        crate_types,
173        lint_opts,
174        lint_cap: Some(options.lint_cap.unwrap_or(lint::Forbid)),
175        cg: options.codegen_options.clone(),
176        externs: options.externs.clone(),
177        unstable_features: options.unstable_features.clone(),
178        actually_rustdoc: true,
179        edition: options.edition,
180        target_triple: options.target.clone(),
181        crate_name: options.crate_name.clone(),
182        remap_path_prefix: options.remap_path_prefix.clone(),
183        remap_path_scope: options.remap_path_scope.clone(),
184        unstable_opts: options.unstable_opts.clone(),
185        error_format: options.error_format.clone(),
186        target_modifiers: options.target_modifiers.clone(),
187        describe_lints: options.describe_lints,
188        ..config::Options::default()
189    };
190
191    let mut cfgs = options.cfgs.clone();
192    cfgs.push("doc".to_owned());
193    cfgs.push("doctest".to_owned());
194    let config = interface::Config {
195        opts: sessopts,
196        crate_cfg: cfgs,
197        crate_check_cfg: options.check_cfgs.clone(),
198        input: input.clone(),
199        output_file: None,
200        output_dir: None,
201        file_loader: None,
202        lint_caps,
203        psess_created: None,
204        track_state: None,
205        register_lints: Some(Box::new(crate::lint::register_lints)),
206        override_queries: None,
207        extra_symbols: Vec::new(),
208        make_codegen_backend: None,
209        ice_file: None,
210        using_internal_features: &rustc_driver::USING_INTERNAL_FEATURES,
211    };
212
213    let externs = options.externs.clone();
214    let json_unused_externs = options.json_unused_externs;
215
216    let temp_dir = match get_doctest_dir(&options)
217        .map_err(|error| format!("failed to create temporary directory: {error:?}"))
218    {
219        Ok(temp_dir) => temp_dir,
220        Err(error) => dcx.fatal(error),
221    };
222    let args_path = temp_dir.path().join("rustdoc-cfgs");
223    crate::wrap_return(dcx, generate_args_file(&args_path, &options));
224
225    let extract_doctests = options.output_format == OutputFormat::Doctest;
226    let save_temps = options.codegen_options.save_temps;
227    let registered_lints = config.register_lints.is_some();
228    let result = interface::run_compiler(config, |compiler| {
229        let sess = &compiler.sess;
230
231        // -W help
232        if sess.opts.describe_lints {
233            rustc_driver::describe_lints(sess, registered_lints);
234            return Ok(None);
235        }
236
237        let krate = rustc_interface::passes::parse(sess);
238
239        let (collector, _incr_comp_session) =
240            rustc_interface::create_and_enter_global_ctxt(compiler, krate, |tcx| {
241                let crate_name = tcx.crate_name(LOCAL_CRATE).to_string();
242                let opts = scrape_test_config(tcx, crate_name, args_path);
243
244                let hir_collector = HirCollector::new(
245                    ErrorCodes::from(compiler.sess.opts.unstable_features.is_nightly_build()),
246                    tcx,
247                );
248                let tests = hir_collector.collect_crate();
249                if extract_doctests {
250                    let mut collector = extracted::ExtractedDocTests::new();
251                    tests.into_iter().for_each(|t| collector.add_test(t, &opts, &options));
252
253                    let stdout = std::io::stdout();
254                    let mut stdout = stdout.lock();
255                    if let Err(error) = serde_json::ser::to_writer(&mut stdout, &collector) {
256                        eprintln!();
257                        Err(format!("Failed to generate JSON output for doctests: {error:?}"))
258                    } else {
259                        Ok(None)
260                    }
261                } else {
262                    let mut collector = CreateRunnableDocTests::new(options, opts);
263                    tests
264                        .into_iter()
265                        .for_each(|t| collector.add_test(t, Some(compiler.sess.dcx())));
266
267                    Ok(Some(collector))
268                }
269            });
270        compiler.sess.dcx().abort_if_errors();
271
272        collector
273    });
274
275    let CreateRunnableDocTests {
276        standalone_tests,
277        mergeable_tests,
278        rustdoc_options,
279        opts,
280        unused_extern_reports,
281        compiling_test_count,
282        ..
283    } = match result {
284        Ok(Some(collector)) => collector,
285        Ok(None) => return ExitCode::SUCCESS,
286        Err(error) => {
287            eprintln!("{error}");
288            // Since some files in the temporary folder are still owned and alive, we need
289            // to manually remove the folder.
290            if !save_temps {
291                let _ = std::fs::remove_dir_all(temp_dir.path());
292            }
293            return ExitCode::FAILURE;
294        }
295    };
296
297    let exit_code = run_tests(
298        dcx,
299        opts,
300        &rustdoc_options,
301        &unused_extern_reports,
302        standalone_tests,
303        mergeable_tests,
304    );
305    if exit_code != ExitCode::SUCCESS {
306        return exit_code;
307    }
308
309    let compiling_test_count = compiling_test_count.load(Ordering::SeqCst);
310
311    // Collect and warn about unused externs, but only if we've gotten
312    // reports for each doctest
313    if json_unused_externs.is_enabled() {
314        let unused_extern_reports: Vec<_> =
315            std::mem::take(&mut unused_extern_reports.lock().unwrap());
316        if unused_extern_reports.len() == compiling_test_count {
317            let extern_names =
318                externs.iter().map(|(name, _)| name).collect::<FxIndexSet<&String>>();
319            let mut unused_extern_names = unused_extern_reports
320                .iter()
321                .map(|uexts| uexts.unused_extern_names.iter().collect::<FxIndexSet<&String>>())
322                .fold(extern_names, |uextsa, uextsb| {
323                    uextsa.intersection(&uextsb).copied().collect::<FxIndexSet<&String>>()
324                })
325                .iter()
326                .map(|v| (*v).clone())
327                .collect::<Vec<String>>();
328            unused_extern_names.sort();
329            // Take the most severe lint level
330            let lint_level = unused_extern_reports
331                .iter()
332                .map(|uexts| uexts.lint_level.as_str())
333                .max_by_key(|v| match *v {
334                    "warn" => 1,
335                    "deny" => 2,
336                    "forbid" => 3,
337                    // The allow lint level is not expected,
338                    // as if allow is specified, no message
339                    // is to be emitted.
340                    v => unreachable!("Invalid lint level '{v}'"),
341                })
342                .unwrap_or("warn")
343                .to_string();
344            let uext = UnusedExterns { lint_level, unused_extern_names };
345            let unused_extern_json = serde_json::to_string(&uext).unwrap();
346            eprintln!("{unused_extern_json}");
347        }
348    }
349    ExitCode::SUCCESS
350}
351
352pub(crate) fn run_tests(
353    dcx: DiagCtxtHandle<'_>,
354    opts: GlobalTestOptions,
355    rustdoc_options: &Arc<RustdocOptions>,
356    unused_extern_reports: &Arc<Mutex<Vec<UnusedExterns>>>,
357    mut standalone_tests: Vec<test::TestDescAndFn>,
358    mergeable_tests: FxIndexMap<MergeableTestKey, Vec<(DocTestBuilder, ScrapedDocTest)>>,
359) -> ExitCode {
360    let mut test_args = Vec::with_capacity(rustdoc_options.test_args.len() + 1);
361    test_args.insert(0, "rustdoctest".to_string());
362    test_args.extend_from_slice(&rustdoc_options.test_args);
363    if rustdoc_options.no_capture {
364        test_args.push("--no-capture".to_string());
365    }
366
367    let mut nb_errors = 0;
368    let mut ran_edition_tests = 0;
369    let mut times = MergedDoctestTimes::new();
370    let target_str = rustdoc_options.target.to_string();
371
372    for (MergeableTestKey { edition, global_crate_attrs_hash }, mut doctests) in mergeable_tests {
373        if doctests.is_empty() {
374            continue;
375        }
376        doctests.sort_by(|(_, a), (_, b)| a.name.cmp(&b.name));
377
378        let mut tests_runner = runner::DocTestRunner::new();
379
380        let rustdoc_test_options = IndividualTestOptions::new(
381            rustdoc_options,
382            &Some(format!("merged_doctest_{edition}_{global_crate_attrs_hash}")),
383            PathBuf::from(format!("doctest_{edition}_{global_crate_attrs_hash}.rs")),
384        );
385
386        for (doctest, scraped_test) in &doctests {
387            tests_runner.add_test(doctest, scraped_test, &target_str);
388        }
389        let (duration, ret) = tests_runner.run_merged_tests(
390            rustdoc_test_options,
391            edition,
392            &opts,
393            &test_args,
394            rustdoc_options,
395        );
396        times.add_compilation_time(duration);
397        if let Ok(success) = ret {
398            ran_edition_tests += 1;
399            if !success {
400                nb_errors += 1;
401            }
402            continue;
403        }
404
405        if rustdoc_options.merge_doctests == MergeDoctests::Always {
406            let mut diag = dcx.struct_fatal("failed to merge doctests");
407            diag.note("requested explicitly on the command line with `--merge-doctests=yes`");
408            diag.emit();
409        }
410
411        // We failed to compile all compatible tests as one so we push them into the
412        // `standalone_tests` doctests.
413        debug!("Failed to compile compatible doctests for edition {} all at once", edition);
414        for (doctest, scraped_test) in doctests {
415            doctest.generate_unique_doctest(
416                &scraped_test.text,
417                scraped_test.langstr.test_harness,
418                &opts,
419                Some(&opts.crate_name),
420            );
421            standalone_tests.push(generate_test_desc_and_fn(
422                doctest,
423                scraped_test,
424                opts.clone(),
425                Arc::clone(rustdoc_options),
426                unused_extern_reports.clone(),
427            ));
428        }
429    }
430
431    // We need to call `test_main` even if there is no doctest to run to get the output
432    // `running 0 tests...`.
433    if ran_edition_tests == 0 || !standalone_tests.is_empty() {
434        standalone_tests.sort_by(|a, b| a.desc.name.as_slice().cmp(b.desc.name.as_slice()));
435        // We need a vector of `&TestDescAndFn`.
436        let standalone_test_refs = &standalone_tests.iter().collect::<Vec<_>>();
437        let exit = test::test_main(&test_args, standalone_test_refs);
438        let times = times.times_in_secs();
439        if let Some((total_time, compilation_time)) = times {
440            test::print_merged_doctests_times(&test_args, total_time, compilation_time);
441        }
442        // Fall through on success, the caller may want to do more stuff.
443        if exit != std::process::ExitCode::SUCCESS {
444            return exit;
445        }
446    } else {
447        // If the first condition branch exited successfully, it will
448        // not exit the process. So to prevent displaying the times twice, we put it behind an
449        // `else` condition.
450        if let Some((total_time, compilation_time)) = times.times_in_secs() {
451            test::print_merged_doctests_times(&test_args, total_time, compilation_time);
452        }
453    }
454    if nb_errors != 0 { test::ERROR_EXIT_CODE.into() } else { ExitCode::SUCCESS }
455}
456
457// Look for `#![doc(test(no_crate_inject))]`, used by crates in the std facade.
458fn scrape_test_config(
459    tcx: TyCtxt<'_>,
460    crate_name: String,
461    args_file: PathBuf,
462) -> GlobalTestOptions {
463    let mut opts = GlobalTestOptions {
464        crate_name,
465        no_crate_inject: false,
466        insert_indent_space: false,
467        args_file,
468    };
469
470    let source_map = tcx.sess.source_map();
471    'main: for attr in tcx.hir_attrs(CRATE_HIR_ID) {
472        let Attribute::Parsed(AttributeKind::Doc(d)) = attr else { continue };
473        for attr_span in &d.test_attrs {
474            // FIXME: This is ugly, remove when `test_attrs` has been ported to new attribute API.
475            if let Ok(snippet) = source_map.span_to_snippet(*attr_span)
476                && let Ok(stream) = TokenStream::from_str(&snippet)
477            {
478                // NOTE: `test(attr(..))` is handled when discovering the individual tests
479                if stream.into_iter().any(|token| {
480                    matches!(
481                        token,
482                        TokenTree::Ident(i) if i.to_string() == "no_crate_inject",
483                    )
484                }) {
485                    opts.no_crate_inject = true;
486                    break 'main;
487                }
488            }
489        }
490    }
491
492    opts
493}
494
495/// Documentation test failure modes.
496enum TestFailure {
497    /// The test failed to compile.
498    CompileError,
499    /// The test is marked `compile_fail` but compiled successfully.
500    UnexpectedCompilePass,
501    /// The test failed to compile (as expected) but the compiler output did not contain all
502    /// expected error codes.
503    MissingErrorCodes(Vec<String>),
504    /// The test binary was unable to be executed.
505    ExecutionError(io::Error),
506    /// The test binary exited with a non-zero exit code.
507    ///
508    /// This typically means an assertion in the test failed or another form of panic occurred.
509    ExecutionFailure(process::Output),
510    /// The test is marked `should_panic` but the test binary executed successfully.
511    UnexpectedRunPass,
512}
513
514enum DirState {
515    Temp(TempDir),
516    Perm(PathBuf),
517}
518
519impl DirState {
520    fn path(&self) -> &std::path::Path {
521        match self {
522            DirState::Temp(t) => t.path(),
523            DirState::Perm(p) => p.as_path(),
524        }
525    }
526}
527
528// NOTE: Keep this in sync with the equivalent structs in rustc
529// and cargo.
530// We could unify this struct the one in rustc but they have different
531// ownership semantics, so doing so would create wasteful allocations.
532#[derive(serde::Serialize, serde::Deserialize)]
533pub(crate) struct UnusedExterns {
534    /// Lint level of the unused_crate_dependencies lint
535    lint_level: String,
536    /// List of unused externs by their names.
537    unused_extern_names: Vec<String>,
538}
539
540fn add_exe_suffix(input: String, target: &TargetTuple) -> String {
541    let exe_suffix = match target {
542        TargetTuple::TargetTuple(_) => Target::expect_builtin(target).options.exe_suffix,
543        TargetTuple::TargetJson { contents, .. } => {
544            Target::from_json(contents).unwrap().0.options.exe_suffix
545        }
546    };
547    input + &exe_suffix
548}
549
550fn wrapped_rustc_command(rustc_wrappers: &[PathBuf], rustc_binary: &Path) -> Command {
551    let mut args = rustc_wrappers.iter().map(PathBuf::as_path).chain([rustc_binary]);
552
553    let exe = args.next().expect("unable to create rustc command");
554    let mut command = Command::new(exe);
555    for arg in args {
556        command.arg(arg);
557    }
558
559    command
560}
561
562/// Information needed for running a bundle of doctests.
563///
564/// This data structure contains the "full" test code, including the wrappers
565/// (if multiple doctests are merged), `main` function,
566/// and everything needed to calculate the compiler's command-line arguments.
567/// The `# ` prefix on boring lines has also been stripped.
568pub(crate) struct RunnableDocTest<'a> {
569    /// In a merged test, this is the code for the "bundle" that contains the actual doctests.
570    /// In a standalone test this is just the regular test code.
571    full_test_code: String,
572    full_test_line_offset: usize,
573    test_opts: IndividualTestOptions,
574    global_opts: &'a GlobalTestOptions,
575    langstr: LangString,
576    line: usize,
577    edition: Edition,
578    no_run: bool,
579    /// If `Some`, this is a merged test and the string is the code for the "runner" that contains
580    /// the test harness to invoke the doctests.
581    merged_test_runner_code: Option<String>,
582}
583
584impl RunnableDocTest<'_> {
585    fn path_for_merged_doctest_bundle(&self) -> PathBuf {
586        self.test_opts.outdir.path().join(format!("doctest_bundle_{}.rs", self.edition))
587    }
588    fn path_for_merged_doctest_runner(&self) -> PathBuf {
589        self.test_opts.outdir.path().join(format!("doctest_runner_{}.rs", self.edition))
590    }
591    fn is_multiple_tests(&self) -> bool {
592        self.merged_test_runner_code.is_some()
593    }
594}
595
596/// Execute a `RunnableDoctest`.
597///
598/// This is the function that calculates the compiler command line, invokes the compiler, then
599/// invokes the test or tests in a separate executable (if applicable).
600///
601/// Returns a tuple containing the `Duration` of the compilation and the `Result` of the test.
602fn run_test(
603    doctest: RunnableDocTest<'_>,
604    rustdoc_options: &RustdocOptions,
605    supports_color: bool,
606    report_unused_externs: impl Fn(UnusedExterns),
607) -> (Duration, Result<(), TestFailure>) {
608    let langstr = &doctest.langstr;
609    // Make sure we emit well-formed executable names for our target.
610    let rust_out = add_exe_suffix("rust_out".to_owned(), &rustdoc_options.target);
611    let output_file = doctest.test_opts.outdir.path().join(rust_out);
612    let instant = Instant::now();
613
614    // Common arguments used for compiling the doctest runner.
615    // On merged doctests, the compiler is invoked twice: once for the test code itself,
616    // and once for the runner wrapper (which needs to use `#![feature]` on stable).
617    let mut compiler_args = vec![];
618
619    compiler_args.push(format!("@{}", doctest.global_opts.args_file.display()));
620
621    let sysroot = &rustdoc_options.sysroot;
622    if let Some(explicit_sysroot) = &sysroot.explicit {
623        compiler_args.push(format!("--sysroot={}", explicit_sysroot.display()));
624    }
625
626    compiler_args.extend_from_slice(&["--edition".to_owned(), doctest.edition.to_string()]);
627    if langstr.test_harness {
628        compiler_args.push("--test".to_owned());
629    }
630    if rustdoc_options.json_unused_externs.is_enabled() && !langstr.compile_fail {
631        compiler_args.push("--error-format=json".to_owned());
632        compiler_args.extend_from_slice(&["--json".to_owned(), "unused-externs".to_owned()]);
633        compiler_args.extend_from_slice(&["-W".to_owned(), "unused_crate_dependencies".to_owned()]);
634        compiler_args.extend_from_slice(&["-Z".to_owned(), "unstable-options".to_owned()]);
635    }
636
637    if doctest.no_run && !langstr.compile_fail && rustdoc_options.persist_doctests.is_none() {
638        // FIXME: why does this code check if it *shouldn't* persist doctests
639        //        -- shouldn't it be the negation?
640        compiler_args.push("--emit=metadata".to_owned());
641    }
642    compiler_args.extend_from_slice(&[
643        "--target".to_owned(),
644        match &rustdoc_options.target {
645            TargetTuple::TargetTuple(s) => s.clone(),
646            TargetTuple::TargetJson { path_for_rustdoc, .. } => {
647                path_for_rustdoc.to_str().expect("target path must be valid unicode").to_owned()
648            }
649        },
650    ]);
651    if let ErrorOutputType::HumanReadable { kind, color_config } = rustdoc_options.error_format {
652        let HumanReadableErrorType { no_graphics, short, unicode } = kind;
653
654        if no_graphics {
655            compiler_args
656                .extend_from_slice(&["--error-format".to_owned(), "human-no-graphics".to_owned()]);
657        }
658        if short {
659            compiler_args.extend_from_slice(&["--error-format".to_owned(), "short".to_owned()]);
660        }
661        if unicode {
662            compiler_args
663                .extend_from_slice(&["--error-format".to_owned(), "human-unicode".to_owned()]);
664        }
665
666        match color_config {
667            ColorConfig::Never => {
668                compiler_args.extend_from_slice(&["--color".to_owned(), "never".to_owned()]);
669            }
670            ColorConfig::Always => {
671                compiler_args.extend_from_slice(&["--color".to_owned(), "always".to_owned()]);
672            }
673            ColorConfig::Auto => {
674                compiler_args.extend_from_slice(&[
675                    "--color".to_owned(),
676                    if supports_color { "always" } else { "never" }.to_owned(),
677                ]);
678            }
679        }
680    }
681
682    let rustc_binary = rustdoc_options
683        .test_builder
684        .as_deref()
685        .unwrap_or_else(|| rustc_interface::util::rustc_path(sysroot).expect("found rustc"));
686    let mut compiler = wrapped_rustc_command(&rustdoc_options.test_builder_wrappers, rustc_binary);
687
688    compiler.args(&compiler_args);
689
690    // If this is a merged doctest, we need to write it into a file instead of using stdin
691    // because if the size of the merged doctests is too big, it'll simply break stdin.
692    if doctest.is_multiple_tests() {
693        // It makes the compilation failure much faster if it is for a combined doctest.
694        compiler.arg("--error-format=short");
695        let input_file = doctest.path_for_merged_doctest_bundle();
696        if std::fs::write(&input_file, &doctest.full_test_code).is_err() {
697            // If we cannot write this file for any reason, we leave. All combined tests will be
698            // tested as standalone tests.
699            return (Duration::default(), Err(TestFailure::CompileError));
700        }
701        if !rustdoc_options.no_capture && rustdoc_options.merge_doctests == MergeDoctests::Auto {
702            // If `no_capture` is disabled, and we might fallback to standalone tests, then we don't
703            // display rustc's output when compiling the merged doctests.
704            compiler.stderr(Stdio::null());
705        }
706        // bundled tests are an rlib, loaded by a separate runner executable
707        compiler
708            .arg("--crate-type=lib")
709            .arg("--out-dir")
710            .arg(doctest.test_opts.outdir.path())
711            .arg(input_file);
712    } else {
713        compiler.arg("--crate-type=bin").arg("-o").arg(&output_file);
714        // Setting these environment variables is unneeded if this is a merged doctest.
715        compiler.env("UNSTABLE_RUSTDOC_TEST_PATH", &doctest.test_opts.path);
716        compiler.env(
717            "UNSTABLE_RUSTDOC_TEST_LINE",
718            format!("{}", doctest.line as isize - doctest.full_test_line_offset as isize),
719        );
720        compiler.arg("-");
721        compiler.stdin(Stdio::piped());
722        compiler.stderr(Stdio::piped());
723    }
724
725    info!("compiler invocation for doctest: {compiler:?}");
726
727    let mut child = match compiler.spawn() {
728        Ok(child) => child,
729        Err(error) => {
730            eprintln!("Failed to spawn {:?}: {error:?}", compiler.get_program());
731            return (Duration::default(), Err(TestFailure::CompileError));
732        }
733    };
734    let output = if let Some(merged_test_runner_code) = &doctest.merged_test_runner_code {
735        // compile-fail tests never get merged, so this should always pass
736        let status = child.wait().expect("Failed to wait");
737
738        // the actual test runner is a separate component, built with nightly-only features;
739        // build it now
740        let runner_input_file = doctest.path_for_merged_doctest_runner();
741
742        let mut runner_compiler =
743            wrapped_rustc_command(&rustdoc_options.test_builder_wrappers, rustc_binary);
744        // the test runner does not contain any user-written code, so this doesn't allow
745        // the user to exploit nightly-only features on stable
746        runner_compiler.env("RUSTC_BOOTSTRAP", "1");
747        runner_compiler.args(compiler_args);
748        runner_compiler.args(["--crate-type=bin", "-o"]).arg(&output_file);
749        let mut extern_path = std::ffi::OsString::from(format!(
750            "--extern=doctest_bundle_{edition}=",
751            edition = doctest.edition
752        ));
753
754        // Deduplicate passed -L directory paths, since usually all dependencies will be in the
755        // same directory (e.g. target/debug/deps from Cargo).
756        let mut seen_search_dirs = FxHashSet::default();
757        for extern_str in &rustdoc_options.extern_strs {
758            if let Some((_cratename, path)) = extern_str.split_once('=') {
759                // Direct dependencies of the tests themselves are
760                // indirect dependencies of the test runner.
761                // They need to be in the library search path.
762                let dir = Path::new(path)
763                    .parent()
764                    .filter(|x| x.components().count() > 0)
765                    .unwrap_or(Path::new("."));
766                if seen_search_dirs.insert(dir) {
767                    runner_compiler.arg("-L").arg(dir);
768                }
769            }
770        }
771        let output_bundle_file = doctest
772            .test_opts
773            .outdir
774            .path()
775            .join(format!("libdoctest_bundle_{edition}.rlib", edition = doctest.edition));
776        extern_path.push(&output_bundle_file);
777        runner_compiler.arg(extern_path);
778        runner_compiler.arg(&runner_input_file);
779        if std::fs::write(&runner_input_file, merged_test_runner_code).is_err() {
780            // If we cannot write this file for any reason, we leave. All combined tests will be
781            // tested as standalone tests.
782            return (instant.elapsed(), Err(TestFailure::CompileError));
783        }
784        if !rustdoc_options.no_capture && rustdoc_options.merge_doctests == MergeDoctests::Auto {
785            // If `no_capture` is disabled and we're autodetecting whether to merge,
786            // we don't display rustc's output when compiling the merged doctests.
787            runner_compiler.stderr(Stdio::null());
788        } else {
789            runner_compiler.stderr(Stdio::inherit());
790        }
791        runner_compiler.arg("--error-format=short");
792        info!("compiler invocation for doctest runner: {runner_compiler:?}");
793
794        let status = if !status.success() {
795            status
796        } else {
797            let mut child_runner = match runner_compiler.spawn() {
798                Ok(child) => child,
799                Err(error) => {
800                    eprintln!("Failed to spawn {:?}: {error:?}", runner_compiler.get_program());
801                    return (Duration::default(), Err(TestFailure::CompileError));
802                }
803            };
804            child_runner.wait().expect("Failed to wait")
805        };
806
807        process::Output { status, stdout: Vec::new(), stderr: Vec::new() }
808    } else {
809        let stdin = child.stdin.as_mut().expect("Failed to open stdin");
810        stdin.write_all(doctest.full_test_code.as_bytes()).expect("could write out test sources");
811        child.wait_with_output().expect("Failed to read stdout")
812    };
813
814    struct Bomb<'a>(&'a str);
815    impl Drop for Bomb<'_> {
816        fn drop(&mut self) {
817            eprint!("{}", self.0);
818        }
819    }
820    let mut out = str::from_utf8(&output.stderr)
821        .unwrap()
822        .lines()
823        .filter(|l| {
824            if let Ok(uext) = serde_json::from_str::<UnusedExterns>(l) {
825                report_unused_externs(uext);
826                false
827            } else {
828                true
829            }
830        })
831        .intersperse_with(|| "\n")
832        .collect::<String>();
833
834    // Add a \n to the end to properly terminate the last line,
835    // but only if there was output to be printed
836    if !out.is_empty() {
837        out.push('\n');
838    }
839
840    let _bomb = Bomb(&out);
841    match (output.status.success(), langstr.compile_fail) {
842        (true, true) => {
843            return (instant.elapsed(), Err(TestFailure::UnexpectedCompilePass));
844        }
845        (true, false) => {}
846        (false, true) => {
847            if !langstr.error_codes.is_empty() {
848                // We used to check if the output contained "error[{}]: " but since we added the
849                // colored output, we can't anymore because of the color escape characters before
850                // the ":".
851                let missing_codes: Vec<String> = langstr
852                    .error_codes
853                    .iter()
854                    .filter(|err| !out.contains(&format!("error[{err}]")))
855                    .cloned()
856                    .collect();
857
858                if !missing_codes.is_empty() {
859                    return (instant.elapsed(), Err(TestFailure::MissingErrorCodes(missing_codes)));
860                }
861            }
862        }
863        (false, false) => {
864            return (instant.elapsed(), Err(TestFailure::CompileError));
865        }
866    }
867
868    let duration = instant.elapsed();
869    if doctest.no_run {
870        return (duration, Ok(()));
871    }
872
873    // Run the code!
874    let mut cmd;
875
876    let output_file = make_maybe_absolute_path(output_file);
877    if let Some(tool) = &rustdoc_options.test_runtool {
878        let tool = make_maybe_absolute_path(tool.into());
879        cmd = Command::new(tool);
880        cmd.args(&rustdoc_options.test_runtool_args);
881        cmd.arg(&output_file);
882    } else {
883        cmd = Command::new(&output_file);
884        if doctest.is_multiple_tests() {
885            cmd.env("RUSTDOC_DOCTEST_BIN_PATH", &output_file);
886        }
887    }
888    if let Some(run_directory) = &rustdoc_options.test_run_directory {
889        cmd.current_dir(run_directory);
890    }
891
892    info!("running doctest executable: {cmd:?}");
893
894    let result = if doctest.is_multiple_tests() || rustdoc_options.no_capture {
895        cmd.status().map(|status| process::Output {
896            status,
897            stdout: Vec::new(),
898            stderr: Vec::new(),
899        })
900    } else {
901        cmd.output()
902    };
903    match result {
904        Err(e) => return (duration, Err(TestFailure::ExecutionError(e))),
905        Ok(out) => {
906            if langstr.should_panic && out.status.success() {
907                return (duration, Err(TestFailure::UnexpectedRunPass));
908            } else if !langstr.should_panic && !out.status.success() {
909                return (duration, Err(TestFailure::ExecutionFailure(out)));
910            }
911        }
912    }
913
914    (duration, Ok(()))
915}
916
917/// Converts a path intended to use as a command to absolute if it is
918/// relative, and not a single component.
919///
920/// This is needed to deal with relative paths interacting with
921/// `Command::current_dir` in a platform-specific way.
922fn make_maybe_absolute_path(path: PathBuf) -> PathBuf {
923    if path.components().count() == 1 {
924        // Look up process via PATH.
925        path
926    } else {
927        std::env::current_dir().map(|c| c.join(&path)).unwrap_or_else(|_| path)
928    }
929}
930struct IndividualTestOptions {
931    outdir: DirState,
932    path: PathBuf,
933}
934
935impl IndividualTestOptions {
936    fn new(options: &RustdocOptions, test_id: &Option<String>, test_path: PathBuf) -> Self {
937        let outdir = if let Some(ref path) = options.persist_doctests {
938            let mut path = path.clone();
939            path.push(test_id.as_deref().unwrap_or("<doctest>"));
940
941            if let Err(err) = std::fs::create_dir_all(&path) {
942                eprintln!("Couldn't create directory for doctest executables: {err}");
943                panic::resume_unwind(Box::new(()));
944            }
945
946            DirState::Perm(path)
947        } else {
948            DirState::Temp(get_doctest_dir(options).expect("rustdoc needs a tempdir"))
949        };
950
951        Self { outdir, path: test_path }
952    }
953}
954
955/// A doctest scraped from the code, ready to be turned into a runnable test.
956///
957/// The pipeline goes: [`clean`] AST -> `ScrapedDoctest` -> `RunnableDoctest`.
958/// [`run_merged_tests`] converts a bunch of scraped doctests to a single runnable doctest,
959/// while [`generate_unique_doctest`] does the standalones.
960///
961/// [`clean`]: crate::clean
962/// [`run_merged_tests`]: crate::doctest::runner::DocTestRunner::run_merged_tests
963/// [`generate_unique_doctest`]: crate::doctest::make::DocTestBuilder::generate_unique_doctest
964#[derive(Debug)]
965pub(crate) struct ScrapedDocTest {
966    filename: FileName,
967    line: usize,
968    langstr: LangString,
969    text: String,
970    name: String,
971    span: Span,
972    code_mappings: Vec<CodeLineMapping>,
973    global_crate_attrs: Vec<String>,
974}
975
976impl ScrapedDocTest {
977    fn new(
978        filename: FileName,
979        line: usize,
980        logical_path: Vec<String>,
981        langstr: LangString,
982        text: String,
983        span: Span,
984        code_mappings: Vec<CodeLineMapping>,
985        global_crate_attrs: Vec<String>,
986    ) -> Self {
987        let mut item_path = logical_path.join("::");
988        item_path.retain(|c| c != ' ');
989        if !item_path.is_empty() {
990            item_path.push(' ');
991        }
992        let name = format!(
993            "{} - {item_path}(line {line})",
994            filename.display(RemapPathScopeComponents::DIAGNOSTICS)
995        );
996
997        Self { filename, line, langstr, text, name, span, code_mappings, global_crate_attrs }
998    }
999    fn edition(&self, opts: &RustdocOptions) -> Edition {
1000        self.langstr.edition.unwrap_or(opts.edition)
1001    }
1002
1003    fn no_run(&self, opts: &RustdocOptions) -> bool {
1004        self.langstr.no_run || opts.no_run
1005    }
1006
1007    fn path(&self, scope: RemapPathScopeComponents) -> String {
1008        self.filename.display(scope).to_string()
1009    }
1010
1011    fn local_path(&self) -> PathBuf {
1012        self.filename.clone().into_local_path().unwrap_or_else(|| PathBuf::from(r"doctest.rs"))
1013    }
1014}
1015
1016pub(crate) trait DocTestVisitor {
1017    fn visit_test(
1018        &mut self,
1019        test: String,
1020        config: LangString,
1021        position: CodeBlockPosition,
1022        code_mappings: Vec<CodeLineMapping>,
1023    );
1024    fn visit_header(&mut self, _name: &str, _level: u32) {}
1025}
1026
1027#[derive(Clone, Debug, Hash, Eq, PartialEq)]
1028pub(crate) struct MergeableTestKey {
1029    edition: Edition,
1030    global_crate_attrs_hash: u64,
1031}
1032
1033struct CreateRunnableDocTests {
1034    standalone_tests: Vec<test::TestDescAndFn>,
1035    mergeable_tests: FxIndexMap<MergeableTestKey, Vec<(DocTestBuilder, ScrapedDocTest)>>,
1036
1037    rustdoc_options: Arc<RustdocOptions>,
1038    opts: GlobalTestOptions,
1039    visited_tests: FxHashMap<(String, usize), usize>,
1040    unused_extern_reports: Arc<Mutex<Vec<UnusedExterns>>>,
1041    compiling_test_count: AtomicUsize,
1042    can_merge_doctests: MergeDoctests,
1043}
1044
1045impl CreateRunnableDocTests {
1046    fn new(rustdoc_options: RustdocOptions, opts: GlobalTestOptions) -> CreateRunnableDocTests {
1047        CreateRunnableDocTests {
1048            standalone_tests: Vec::new(),
1049            mergeable_tests: FxIndexMap::default(),
1050            opts,
1051            visited_tests: FxHashMap::default(),
1052            unused_extern_reports: Default::default(),
1053            compiling_test_count: AtomicUsize::new(0),
1054            can_merge_doctests: rustdoc_options.merge_doctests,
1055            rustdoc_options: Arc::new(rustdoc_options),
1056        }
1057    }
1058
1059    fn add_test(&mut self, scraped_test: ScrapedDocTest, dcx: Option<DiagCtxtHandle<'_>>) {
1060        // For example `module/file.rs` would become `module_file_rs`
1061        //
1062        // Note that we are kind-of extending the definition of the MACRO scope here, but
1063        // after all `#[doc]` is kind-of a macro.
1064        let file = scraped_test
1065            .filename
1066            .display(RemapPathScopeComponents::MACRO)
1067            .to_string_lossy()
1068            .chars()
1069            .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
1070            .collect::<String>();
1071        let test_id = format!(
1072            "{file}_{line}_{number}",
1073            file = file,
1074            line = scraped_test.line,
1075            number = {
1076                // Increases the current test number, if this file already
1077                // exists or it creates a new entry with a test number of 0.
1078                self.visited_tests
1079                    .entry((file.clone(), scraped_test.line))
1080                    .and_modify(|v| *v += 1)
1081                    .or_insert(0)
1082            },
1083        );
1084
1085        let edition = scraped_test.edition(&self.rustdoc_options);
1086        let doctest = BuildDocTestBuilder::new(&scraped_test.text)
1087            .crate_name(&self.opts.crate_name)
1088            .global_crate_attrs(scraped_test.global_crate_attrs.clone())
1089            .edition(edition)
1090            .can_merge_doctests(self.can_merge_doctests)
1091            .test_id(test_id)
1092            .lang_str(&scraped_test.langstr)
1093            .span(scraped_test.span)
1094            .code_mappings(&scraped_test.code_mappings)
1095            .build(dcx);
1096        let is_standalone = !doctest.can_be_merged
1097            || self.rustdoc_options.no_capture
1098            || self.rustdoc_options.test_args.iter().any(|arg| arg == "--show-output");
1099        if is_standalone {
1100            let test_desc = self.generate_test_desc_and_fn(doctest, scraped_test);
1101            self.standalone_tests.push(test_desc);
1102        } else {
1103            self.mergeable_tests
1104                .entry(MergeableTestKey {
1105                    edition,
1106                    global_crate_attrs_hash: {
1107                        let mut hasher = FxHasher::default();
1108                        scraped_test.global_crate_attrs.hash(&mut hasher);
1109                        hasher.finish()
1110                    },
1111                })
1112                .or_default()
1113                .push((doctest, scraped_test));
1114        }
1115    }
1116
1117    fn generate_test_desc_and_fn(
1118        &mut self,
1119        test: DocTestBuilder,
1120        scraped_test: ScrapedDocTest,
1121    ) -> test::TestDescAndFn {
1122        if !scraped_test.langstr.compile_fail {
1123            self.compiling_test_count.fetch_add(1, Ordering::SeqCst);
1124        }
1125
1126        generate_test_desc_and_fn(
1127            test,
1128            scraped_test,
1129            self.opts.clone(),
1130            Arc::clone(&self.rustdoc_options),
1131            self.unused_extern_reports.clone(),
1132        )
1133    }
1134}
1135
1136fn generate_test_desc_and_fn(
1137    test: DocTestBuilder,
1138    scraped_test: ScrapedDocTest,
1139    opts: GlobalTestOptions,
1140    rustdoc_options: Arc<RustdocOptions>,
1141    unused_externs: Arc<Mutex<Vec<UnusedExterns>>>,
1142) -> test::TestDescAndFn {
1143    let target_str = rustdoc_options.target.to_string();
1144
1145    debug!("creating test {}: {}", scraped_test.name, scraped_test.text);
1146    test::TestDescAndFn {
1147        desc: test::TestDesc {
1148            name: test::DynTestName(scraped_test.name.clone()),
1149            ignore: match scraped_test.langstr.ignore {
1150                Ignore::All => true,
1151                Ignore::None => false,
1152                Ignore::Some(ref ignores) => ignores.iter().any(|s| target_str.contains(s)),
1153            },
1154            ignore_message: None,
1155            source_file: "",
1156            start_line: 0,
1157            start_col: 0,
1158            end_line: 0,
1159            end_col: 0,
1160            // compiler failures are test failures
1161            should_panic: test::ShouldPanic::No,
1162            compile_fail: scraped_test.langstr.compile_fail,
1163            no_run: scraped_test.no_run(&rustdoc_options),
1164            test_type: test::TestType::DocTest,
1165        },
1166        testfn: test::DynTestFn(Arc::new(move || {
1167            let rustdoc_test_options = IndividualTestOptions::new(
1168                &rustdoc_options,
1169                &test.test_id,
1170                scraped_test.local_path(),
1171            );
1172            doctest_run_fn(
1173                rustdoc_test_options,
1174                &opts,
1175                &test,
1176                &scraped_test,
1177                &rustdoc_options,
1178                &unused_externs,
1179            )
1180        })),
1181    }
1182}
1183
1184fn doctest_run_fn(
1185    test_opts: IndividualTestOptions,
1186    global_opts: &GlobalTestOptions,
1187    doctest: &DocTestBuilder,
1188    scraped_test: &ScrapedDocTest,
1189    rustdoc_options: &RustdocOptions,
1190    unused_externs: &Mutex<Vec<UnusedExterns>>,
1191) -> Result<(), String> {
1192    let report_unused_externs = |uext| {
1193        unused_externs.lock().unwrap().push(uext);
1194    };
1195    let (wrapped, full_test_line_offset) = doctest.generate_unique_doctest(
1196        &scraped_test.text,
1197        scraped_test.langstr.test_harness,
1198        &global_opts,
1199        Some(&global_opts.crate_name),
1200    );
1201    let runnable_test = RunnableDocTest {
1202        full_test_code: wrapped.to_string(),
1203        full_test_line_offset,
1204        test_opts,
1205        global_opts,
1206        langstr: scraped_test.langstr.clone(),
1207        line: scraped_test.line,
1208        edition: scraped_test.edition(&rustdoc_options),
1209        no_run: scraped_test.no_run(&rustdoc_options),
1210        merged_test_runner_code: None,
1211    };
1212    let (_, res) =
1213        run_test(runnable_test, &rustdoc_options, doctest.supports_color, report_unused_externs);
1214
1215    if let Err(err) = res {
1216        match err {
1217            TestFailure::CompileError => {
1218                eprint!("Couldn't compile the test.");
1219            }
1220            TestFailure::UnexpectedCompilePass => {
1221                eprint!("Test compiled successfully, but it's marked `compile_fail`.");
1222            }
1223            TestFailure::UnexpectedRunPass => {
1224                eprint!("Test executable succeeded, but it's marked `should_panic`.");
1225            }
1226            TestFailure::MissingErrorCodes(codes) => {
1227                eprint!("Some expected error codes were not found: {codes:?}");
1228            }
1229            TestFailure::ExecutionError(err) => {
1230                eprint!("Couldn't run the test: {err}");
1231                if err.kind() == io::ErrorKind::PermissionDenied {
1232                    eprint!(" - maybe your tempdir is mounted with noexec?");
1233                }
1234            }
1235            TestFailure::ExecutionFailure(out) => {
1236                eprintln!("Test executable failed ({reason}).", reason = out.status);
1237
1238                // FIXME(#12309): An unfortunate side-effect of capturing the test
1239                // executable's output is that the relative ordering between the test's
1240                // stdout and stderr is lost. However, this is better than the
1241                // alternative: if the test executable inherited the parent's I/O
1242                // handles the output wouldn't be captured at all, even on success.
1243                //
1244                // The ordering could be preserved if the test process' stderr was
1245                // redirected to stdout, but that functionality does not exist in the
1246                // standard library, so it may not be portable enough.
1247                let stdout = str::from_utf8(&out.stdout).unwrap_or_default();
1248                let stderr = str::from_utf8(&out.stderr).unwrap_or_default();
1249
1250                if !stdout.is_empty() || !stderr.is_empty() {
1251                    eprintln!();
1252
1253                    if !stdout.is_empty() {
1254                        eprintln!("stdout:\n{stdout}");
1255                    }
1256
1257                    if !stderr.is_empty() {
1258                        eprintln!("stderr:\n{stderr}");
1259                    }
1260                }
1261            }
1262        }
1263
1264        panic::resume_unwind(Box::new(()));
1265    }
1266    Ok(())
1267}
1268
1269#[cfg(test)] // used in tests
1270impl DocTestVisitor for Vec<usize> {
1271    fn visit_test(
1272        &mut self,
1273        _test: String,
1274        _config: LangString,
1275        position: CodeBlockPosition,
1276        _code_mappings: Vec<CodeLineMapping>,
1277    ) {
1278        let line = match position {
1279            CodeBlockPosition::Relative(rel_line) => 1 + rel_line.offset(),
1280            CodeBlockPosition::Span(_) => unreachable!(),
1281        };
1282        self.push(line);
1283    }
1284}
1285
1286#[cfg(test)]
1287mod tests;