1 // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use config::file_lines::FileLines;
12 use config::options::WidthHeuristics;
14 /// Trait for types that can be used in `Config`.
15 pub trait ConfigType: Sized {
16 /// Returns hint text for use in `Config::print_docs()`. For enum types, this is a
17 /// pipe-separated list of variants; for other types it returns "<type>".
18 fn doc_hint() -> String;
21 impl ConfigType for bool {
22 fn doc_hint() -> String {
23 String::from("<boolean>")
27 impl ConfigType for usize {
28 fn doc_hint() -> String {
29 String::from("<unsigned integer>")
33 impl ConfigType for isize {
34 fn doc_hint() -> String {
35 String::from("<signed integer>")
39 impl ConfigType for String {
40 fn doc_hint() -> String {
41 String::from("<string>")
45 impl ConfigType for FileLines {
46 fn doc_hint() -> String {
47 String::from("<json>")
51 impl ConfigType for WidthHeuristics {
52 fn doc_hint() -> String {
57 /// Check if we're in a nightly build.
59 /// The environment variable `CFG_RELEASE_CHANNEL` is set during the rustc bootstrap
60 /// to "stable", "beta", or "nightly" depending on what toolchain is being built.
61 /// If we are being built as part of the stable or beta toolchains, we want
62 /// to disable unstable configuration options.
64 /// If we're being built by cargo (e.g. `cargo +nightly install rustfmt-nightly`),
65 /// `CFG_RELEASE_CHANNEL` is not set. As we only support being built against the
66 /// nightly compiler when installed from crates.io, default to nightly mode.
67 macro_rules! is_nightly_channel {
69 option_env!("CFG_RELEASE_CHANNEL")
70 .map(|c| c == "nightly")
75 macro_rules! create_config {
76 ($($i:ident: $ty:ty, $def:expr, $stb:expr, $( $dstring:expr ),+ );+ $(;)*) => (
77 use std::collections::HashSet;
81 // For each config item, we store a bool indicating whether it has
82 // been accessed and the value, and a bool whether the option was
83 // manually initialised, or taken from the default,
84 $($i: (Cell<bool>, bool, $ty, bool)),+
87 // Just like the Config struct but with each property wrapped
88 // as Option<T>. This is used to parse a rustfmt.toml that doesn't
89 // specify all properties of `Config`.
90 // We first parse into `PartialConfig`, then create a default `Config`
91 // and overwrite the properties with corresponding values from `PartialConfig`.
92 #[derive(Deserialize, Serialize, Clone)]
93 pub struct PartialConfig {
94 $(pub $i: Option<$ty>),+
98 pub fn to_toml(&self) -> Result<String, String> {
99 // Non-user-facing options can't be specified in TOML
100 let mut cloned = self.clone();
101 cloned.file_lines = None;
102 cloned.verbose = None;
103 cloned.width_heuristics = None;
105 ::toml::to_string(&cloned)
106 .map_err(|e| format!("Could not output config: {}", e.to_string()))
110 // Macro hygiene won't allow us to make `set_$i()` methods on Config
111 // for each item, so this struct is used to give the API to set values:
112 // `config.set().option(false)`. It's pretty ugly. Consider replacing
113 // with `config.set_option(false)` if we ever get a stable/usable
114 // `concat_idents!()`.
115 pub struct ConfigSetter<'a>(&'a mut Config);
117 impl<'a> ConfigSetter<'a> {
119 pub fn $i(&mut self, value: $ty) {
120 (self.0).$i.2 = value;
121 if stringify!($i) == "use_small_heuristics" {
122 self.0.set_heuristics();
128 // Query each option, returns true if the user set the option, false if
129 // a default was used.
130 pub struct ConfigWasSet<'a>(&'a Config);
132 impl<'a> ConfigWasSet<'a> {
134 pub fn $i(&self) -> bool {
141 pub fn version_meets_requirement(&self, error_summary: &mut Summary) -> bool {
142 if self.was_set().required_version() {
143 let version = env!("CARGO_PKG_VERSION");
144 let required_version = self.required_version();
145 if version != required_version {
147 "Error: rustfmt version ({}) doesn't match the required version ({})",
151 error_summary.add_formatting_error();
160 pub fn $i(&self) -> $ty {
166 pub fn set<'a>(&'a mut self) -> ConfigSetter<'a> {
170 pub fn was_set<'a>(&'a self) -> ConfigWasSet<'a> {
174 fn fill_from_parsed_config(mut self, parsed: PartialConfig) -> Config {
176 if let Some(val) = parsed.$i {
181 if is_nightly_channel!() {
185 eprintln!("Warning: can't set `{} = {:?}`, unstable features are only \
186 available in nightly channel.", stringify!($i), val);
191 self.set_heuristics();
195 /// Returns a hash set initialized with every user-facing config option name.
196 pub fn hash_set() -> HashSet<String> {
197 let mut hash_set = HashSet::new();
199 hash_set.insert(stringify!($i).to_owned());
204 pub fn is_valid_name(name: &str) -> bool {
207 stringify!($i) => true,
213 pub fn from_toml(toml: &str) -> Result<Config, String> {
214 let parsed: ::toml::Value =
215 toml.parse().map_err(|e| format!("Could not parse TOML: {}", e))?;
216 let mut err: String = String::new();
220 .ok_or(String::from("Parsed config was not table"))?;
221 for key in table.keys() {
222 if !Config::is_valid_name(key) {
223 let msg = &format!("Warning: Unknown configuration option `{}`\n", key);
228 match parsed.try_into() {
229 Ok(parsed_config) => {
233 Ok(Config::default().fill_from_parsed_config(parsed_config))
236 err.push_str("Error: Decoding config file failed:\n");
237 err.push_str(format!("{}\n", e).as_str());
238 err.push_str("Please check your config file.");
244 pub fn used_options(&self) -> PartialConfig {
247 $i: if self.$i.0.get() {
248 Some(self.$i.2.clone())
256 pub fn all_options(&self) -> PartialConfig {
259 $i: Some(self.$i.2.clone()),
264 pub fn override_value(&mut self, key: &str, val: &str)
269 self.$i.2 = val.parse::<$ty>()
270 .expect(&format!("Failed to parse override for {} (\"{}\") as a {}",
276 _ => panic!("Unknown config key in override: {}", key)
279 if key == "use_small_heuristics" {
280 self.set_heuristics();
284 /// Construct a `Config` from the toml file specified at `file_path`.
286 /// This method only looks at the provided path, for a method that
287 /// searches parents for a `rustfmt.toml` see `from_resolved_toml_path`.
289 /// Return a `Config` if the config could be read and parsed from
290 /// the file, Error otherwise.
291 pub fn from_toml_path(file_path: &Path) -> Result<Config, Error> {
292 let mut file = File::open(&file_path)?;
293 let mut toml = String::new();
294 file.read_to_string(&mut toml)?;
295 Config::from_toml(&toml).map_err(|err| Error::new(ErrorKind::InvalidData, err))
298 /// Resolve the config for input in `dir`.
300 /// Searches for `rustfmt.toml` beginning with `dir`, and
301 /// recursively checking parents of `dir` if no config file is found.
302 /// If no config file exists in `dir` or in any parent, a
303 /// default `Config` will be returned (and the returned path will be empty).
305 /// Returns the `Config` to use, and the path of the project file if there was
307 pub fn from_resolved_toml_path(dir: &Path) -> Result<(Config, Option<PathBuf>), Error> {
309 /// Try to find a project file in the given directory and its parents.
310 /// Returns the path of a the nearest project file if one exists,
311 /// or `None` if no project file was found.
312 fn resolve_project_file(dir: &Path) -> Result<Option<PathBuf>, Error> {
313 let mut current = if dir.is_relative() {
314 env::current_dir()?.join(dir)
319 current = fs::canonicalize(current)?;
322 match get_toml_path(¤t) {
323 Ok(Some(path)) => return Ok(Some(path)),
324 Err(e) => return Err(e),
328 // If the current directory has no parent, we're done searching.
335 match resolve_project_file(dir)? {
336 None => Ok((Config::default(), None)),
337 Some(path) => Config::from_toml_path(&path).map(|config| (config, Some(path))),
341 pub fn is_hidden_option(name: &str) -> bool {
342 const HIDE_OPTIONS: [&str; 3] = ["verbose", "file_lines", "width_heuristics"];
343 HIDE_OPTIONS.contains(&name)
346 pub fn print_docs() {
349 $( let max = cmp::max(max, stringify!($i).len()+1); )+
350 let mut space_str = String::with_capacity(max);
354 println!("Configuration Options:");
356 let name_raw = stringify!($i);
358 if !Config::is_hidden_option(name_raw) {
359 let mut name_out = String::with_capacity(max);
360 for _ in name_raw.len()..max-1 {
363 name_out.push_str(name_raw);
365 println!("{}{} Default: {:?}",
370 println!("{}{}", space_str, $dstring);
377 fn set_heuristics(&mut self) {
378 if self.use_small_heuristics.2 {
379 let max_width = self.max_width.2;
380 self.set().width_heuristics(WidthHeuristics::scaled(max_width));
382 self.set().width_heuristics(WidthHeuristics::null());
387 // Template for the default configuration
388 impl Default for Config {
389 fn default() -> Config {
392 $i: (Cell::new(false), false, $def, $stb),