Skip to content

Commit

Permalink
swap uses of Matches with pre-parsed args
Browse files Browse the repository at this point in the history
  • Loading branch information
QuietMisdreavus committed Nov 2, 2018
1 parent f5f496e commit 157833c
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 111 deletions.
22 changes: 22 additions & 0 deletions src/librustdoc/config.rs
Expand Up @@ -32,6 +32,7 @@ use opts;
use passes::{self, DefaultPassOption};
use theme;

#[derive(Clone)]
pub struct Options {
// Basic options / Options passed directly to rustc

Expand Down Expand Up @@ -330,6 +331,14 @@ impl Options {
}
};

match matches.opt_str("r").as_ref().map(|s| &**s) {
Some("rust") | None => {}
Some(s) => {
diag.struct_err(&format!("unknown input format: {}", s)).emit();
return Err(1);
}
}

match matches.opt_str("w").as_ref().map(|s| &**s) {
Some("html") | None => {}
Some(s) => {
Expand Down Expand Up @@ -448,6 +457,19 @@ fn check_deprecated_options(matches: &getopts::Matches, diag: &errors::Handler)
err.emit();
}
}

let removed_flags = [
"plugins",
"plugin-path",
];

for &flag in removed_flags.iter() {
if matches.opt_present(flag) {
diag.struct_warn(&format!("the '{}' flag no longer functions", flag))
.warn("see CVE-2018-1000622")
.emit();
}
}
}

/// Extracts `--extern-html-root-url` arguments from `matches` and returns a map of crate names to
Expand Down
2 changes: 1 addition & 1 deletion src/librustdoc/html/markdown.rs
Expand Up @@ -905,7 +905,7 @@ pub fn markdown_links(md: &str) -> Vec<(String, Option<Range<usize>>)> {
links
}

#[derive(Default)]
#[derive(Clone, Default)]
pub struct IdMap {
map: FxHashMap<String, usize>,
}
Expand Down
16 changes: 9 additions & 7 deletions src/librustdoc/html/render.rs
Expand Up @@ -55,7 +55,6 @@ use std::rc::Rc;
use externalfiles::ExternalHtml;

use errors;
use getopts;

use serialize::json::{ToJson, Json, as_json};
use syntax::ast;
Expand All @@ -70,6 +69,7 @@ use rustc::util::nodemap::{FxHashMap, FxHashSet};
use rustc_data_structures::flock;

use clean::{self, AttributesExt, GetDefId, SelfTy, Mutability};
use config;
use doctree;
use fold::DocFolder;
use html::escape::Escape;
Expand Down Expand Up @@ -509,7 +509,7 @@ pub fn run(mut krate: clean::Crate,
id_map: IdMap,
enable_index_page: bool,
index_page: Option<PathBuf>,
matches: &getopts::Matches,
options: config::Options,
diag: &errors::Handler,
) -> Result<(), Error> {
let src_root = match krate.src {
Expand Down Expand Up @@ -678,7 +678,7 @@ pub fn run(mut krate: clean::Crate,
CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());

write_shared(&cx, &krate, &*cache, index, enable_minification, matches, diag)?;
write_shared(&cx, &krate, &*cache, index, enable_minification, &options, diag)?;

// And finally render the whole crate's documentation
cx.krate(krate)
Expand Down Expand Up @@ -760,7 +760,7 @@ fn write_shared(
cache: &Cache,
search_index: String,
enable_minification: bool,
matches: &getopts::Matches,
options: &config::Options,
diag: &errors::Handler,
) -> Result<(), Error> {
// Write out the shared files. Note that these are shared among all rustdoc
Expand Down Expand Up @@ -994,9 +994,11 @@ themePicker.onblur = handleThemeButtonsBlur;
if let Some(ref index_page) = cx.index_page {
::markdown::render(index_page,
cx.dst.clone(),
&matches, &(*cx.shared).layout.external_html,
!matches.opt_present("markdown-no-toc"),
diag);
&options.markdown_css.clone(),
options.markdown_playground_url.clone()
.or_else(|| options.playground_url.clone()),
&(*cx.shared).layout.external_html,
!options.markdown_no_toc, diag);
} else {
let dst = cx.dst.join("index.html");
let mut w = BufWriter::new(try_err!(File::create(&dst), &dst));
Expand Down
128 changes: 31 additions & 97 deletions src/librustdoc/lib.rs
Expand Up @@ -56,16 +56,11 @@ extern crate serialize as rustc_serialize; // used by deriving
use std::default::Default;
use std::env;
use std::panic;
use std::path::PathBuf;
use std::process;
use std::sync::mpsc::channel;

use syntax::edition::Edition;
use rustc::session::{early_warn, early_error};
use rustc::session::search_paths::SearchPaths;
use rustc::session::config::{ErrorOutputType, RustcOptGroup, Externs, CodegenOptions};
use rustc_target::spec::TargetTriple;
use rustc::session::config::get_cmd_lint_options;
use rustc::session::config::{ErrorOutputType, RustcOptGroup};

#[macro_use]
mod externalfiles;
Expand Down Expand Up @@ -387,17 +382,23 @@ fn main_args(args: &[String]) -> isize {
options.codegen_options)
}
(false, true) => return markdown::render(&options.input, options.output,
&matches,
&options.markdown_css,
options.markdown_playground_url
.or(options.playground_url),
&options.external_html,
!options.markdown_no_toc, &diag),
(false, false) => {}
}

let res = acquire_input(options.input.clone(), options.externs.clone(), options.edition,
options.codegen_options.clone(), matches, options.error_format,
move |out, matches| {
//TODO: split render-time options into their own struct so i don't have to clone here
rust_input(options.clone(), move |out| {
let Output { krate, passes, renderinfo } = out;
info!("going to format");
let diag = core::new_handler(options.error_format,
None,
options.debugging_options.treat_err_as_bug,
options.debugging_options.ui_testing);
let html_opts = options.clone();
html::render::run(krate, options.extern_html_root_urls, &options.external_html, options.playground_url,
options.output,
options.resource_suffix,
Expand All @@ -408,106 +409,48 @@ fn main_args(args: &[String]) -> isize {
options.themes,
options.enable_minification, options.id_map,
options.enable_index_page, options.index_page,
&matches,
html_opts,
&diag)
.expect("failed to generate documentation");
0
});
res.unwrap_or_else(|s| {
diag.struct_err(&format!("input error: {}", s)).emit();
1
})
}

/// Looks inside the command line arguments to extract the relevant input format
/// and files and then generates the necessary rustdoc output for formatting.
fn acquire_input<R, F>(input: PathBuf,
externs: Externs,
edition: Edition,
cg: CodegenOptions,
matches: getopts::Matches,
error_format: ErrorOutputType,
f: F)
-> Result<R, String>
where R: 'static + Send, F: 'static + Send + FnOnce(Output, &getopts::Matches) -> R {
match matches.opt_str("r").as_ref().map(|s| &**s) {
Some("rust") => Ok(rust_input(input, externs, edition, cg, matches, error_format, f)),
Some(s) => Err(format!("unknown input format: {}", s)),
None => Ok(rust_input(input, externs, edition, cg, matches, error_format, f))
}
}

/// Interprets the input file as a rust source file, passing it through the
/// compiler all the way through the analysis passes. The rustdoc output is then
/// generated from the cleaned AST of the crate.
///
/// This form of input will run all of the plug/cleaning passes
fn rust_input<R, F>(cratefile: PathBuf,
externs: Externs,
edition: Edition,
cg: CodegenOptions,
matches: getopts::Matches,
error_format: ErrorOutputType,
fn rust_input<R, F>(options: config::Options,
f: F) -> R
where R: 'static + Send,
F: 'static + Send + FnOnce(Output, &getopts::Matches) -> R
F: 'static + Send + FnOnce(Output) -> R
{
let default_passes = if matches.opt_present("no-defaults") {
passes::DefaultPassOption::None
} else if matches.opt_present("document-private-items") {
passes::DefaultPassOption::Private
} else {
passes::DefaultPassOption::Default
};

let manual_passes = matches.opt_strs("passes");
let plugins = matches.opt_strs("plugins");

// First, parse the crate and extract all relevant information.
let mut paths = SearchPaths::new();
for s in &matches.opt_strs("L") {
paths.add_path(s, ErrorOutputType::default());
}
let mut cfgs = matches.opt_strs("cfg");
cfgs.push("rustdoc".to_string());
let triple = matches.opt_str("target").map(|target| {
if target.ends_with(".json") {
TargetTriple::TargetPath(PathBuf::from(target))
} else {
TargetTriple::TargetTriple(target)
}
});
let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
let crate_name = matches.opt_str("crate-name");
let crate_version = matches.opt_str("crate-version");
let plugin_path = matches.opt_str("plugin-path");

info!("starting to run rustc");
let display_warnings = matches.opt_present("display-warnings");

let force_unstable_if_unmarked = matches.opt_strs("Z").iter().any(|x| {
*x == "force-unstable-if-unmarked"
});
let treat_err_as_bug = matches.opt_strs("Z").iter().any(|x| {
*x == "treat-err-as-bug"
});
let ui_testing = matches.opt_strs("Z").iter().any(|x| {
*x == "ui-testing"
});

let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(&matches, error_format);

let (tx, rx) = channel();

let result = rustc_driver::monitor(move || syntax::with_globals(move || {
use rustc::session::config::Input;

let paths = options.libs;
let cfgs = options.cfgs;
let triple = options.target;
let maybe_sysroot = options.maybe_sysroot;
let crate_name = options.crate_name;
let crate_version = options.crate_version;
let force_unstable_if_unmarked = options.debugging_options.force_unstable_if_unmarked;
let treat_err_as_bug = options.debugging_options.treat_err_as_bug;
let ui_testing = options.debugging_options.ui_testing;

let (mut krate, renderinfo, passes) =
core::run_core(paths, cfgs, externs, Input::File(cratefile), triple, maybe_sysroot,
display_warnings, crate_name.clone(),
force_unstable_if_unmarked, edition, cg, error_format,
lint_opts, lint_cap, describe_lints, manual_passes, default_passes,
treat_err_as_bug, ui_testing);
core::run_core(paths, cfgs, options.externs, Input::File(options.input), triple, maybe_sysroot,
options.display_warnings, crate_name.clone(),
force_unstable_if_unmarked, options.edition, options.codegen_options, options.error_format,
options.lint_opts, options.lint_cap, options.describe_lints,
options.manual_passes, options.default_passes, treat_err_as_bug,
ui_testing);

info!("finished with rustc");

Expand All @@ -517,14 +460,6 @@ where R: 'static + Send,

krate.version = crate_version;

if !plugins.is_empty() {
eprintln!("WARNING: --plugins no longer functions; see CVE-2018-1000622");
}

if !plugin_path.is_none() {
eprintln!("WARNING: --plugin-path no longer functions; see CVE-2018-1000622");
}

info!("Executing passes");

for pass in &passes {
Expand All @@ -547,8 +482,7 @@ where R: 'static + Send,
krate = pass(krate);
}

tx.send(f(Output { krate: krate, renderinfo: renderinfo, passes: passes },
&matches)).unwrap();
tx.send(f(Output { krate: krate, renderinfo: renderinfo, passes: passes })).unwrap();
}));

match result {
Expand Down
11 changes: 5 additions & 6 deletions src/librustdoc/markdown.rs
Expand Up @@ -15,7 +15,6 @@ use std::path::{PathBuf, Path};
use std::cell::RefCell;

use errors;
use getopts;
use testing;
use rustc::session::search_paths::SearchPaths;
use rustc::session::config::{Externs, CodegenOptions};
Expand Down Expand Up @@ -51,13 +50,14 @@ fn extract_leading_metadata<'a>(s: &'a str) -> (Vec<&'a str>, &'a str) {

/// Render `input` (e.g. "foo.md") into an HTML file in `output`
/// (e.g. output = "bar" => "bar/foo.html").
pub fn render(input: &Path, mut output: PathBuf, matches: &getopts::Matches,
external_html: &ExternalHtml, include_toc: bool, diag: &errors::Handler) -> isize {
pub fn render(input: &Path, mut output: PathBuf, markdown_css: &[String],
playground_url: Option<String>, external_html: &ExternalHtml, include_toc: bool,
diag: &errors::Handler) -> isize {
output.push(input.file_stem().unwrap());
output.set_extension("html");

let mut css = String::new();
for name in &matches.opt_strs("markdown-css") {
for name in markdown_css {
let s = format!("<link rel=\"stylesheet\" type=\"text/css\" href=\"{}\">\n", name);
css.push_str(&s)
}
Expand All @@ -67,8 +67,7 @@ pub fn render(input: &Path, mut output: PathBuf, matches: &getopts::Matches,
Err(LoadStringError::ReadFail) => return 1,
Err(LoadStringError::BadUtf8) => return 2,
};
if let Some(playground) = matches.opt_str("markdown-playground-url").or(
matches.opt_str("playground-url")) {
if let Some(playground) = playground_url {
markdown::PLAYGROUND.with(|s| { *s.borrow_mut() = Some((None, playground)); });
}

Expand Down

0 comments on commit 157833c

Please sign in to comment.