Merge remote-tracking branch 'origin/master' into refactor-apply-newline-style

This commit is contained in:
Ruben Schmidmeister 2019-05-02 06:47:41 +02:00
commit 703a2eab19
No known key found for this signature in database
GPG key ID: 29387B5A7AAF863F
18 changed files with 567 additions and 188 deletions

View file

@ -1,6 +1,7 @@
//! Configuration options related to rewriting a list.
use crate::config::config_type::ConfigType;
use config_proc_macro::config_type;
use crate::config::IndentStyle;
/// The definitive formatting tactic for lists.
@ -25,31 +26,27 @@ impl DefinitiveListTactic {
/// Formatting tactic for lists. This will be cast down to a
/// `DefinitiveListTactic` depending on the number and length of the items and
/// their comments.
#[derive(Eq, PartialEq, Debug, Copy, Clone)]
#[config_type]
pub enum ListTactic {
// One item per row.
/// One item per row.
Vertical,
// All items on one row.
/// All items on one row.
Horizontal,
// Try Horizontal layout, if that fails then vertical.
/// Try Horizontal layout, if that fails then vertical.
HorizontalVertical,
// HorizontalVertical with a soft limit of n characters.
/// HorizontalVertical with a soft limit of n characters.
LimitedHorizontalVertical(usize),
// Pack as many items as possible per row over (possibly) many rows.
/// Pack as many items as possible per row over (possibly) many rows.
Mixed,
}
impl_enum_serialize_and_deserialize!(ListTactic, Vertical, Horizontal, HorizontalVertical, Mixed);
#[derive(Eq, PartialEq, Debug, Copy, Clone)]
#[config_type]
pub enum SeparatorTactic {
Always,
Never,
Vertical,
}
impl_enum_serialize_and_deserialize!(SeparatorTactic, Always, Never, Vertical);
impl SeparatorTactic {
pub fn from_bool(b: bool) -> SeparatorTactic {
if b {
@ -61,14 +58,12 @@ impl SeparatorTactic {
}
/// Where to put separator.
#[derive(Eq, PartialEq, Debug, Copy, Clone)]
#[config_type]
pub enum SeparatorPlace {
Front,
Back,
}
impl_enum_serialize_and_deserialize!(SeparatorPlace, Front, Back);
impl SeparatorPlace {
pub fn is_front(self) -> bool {
self == SeparatorPlace::Front

View file

@ -3,182 +3,85 @@ use std::fmt;
use std::path::{Path, PathBuf};
use atty;
use config_proc_macro::config_type;
use serde::de::{Deserialize, Deserializer, SeqAccess, Visitor};
use crate::config::config_type::ConfigType;
use crate::config::lists::*;
use crate::config::Config;
/// Macro that will stringify the enum variants or a provided textual repr
#[macro_export]
macro_rules! configuration_option_enum_stringify {
($variant:ident) => {
stringify!($variant)
};
($_variant:ident: $value:expr) => {
stringify!($value)
};
#[config_type]
pub enum NewlineStyle {
/// Auto-detect based on the raw source input.
Auto,
/// Force CRLF (`\r\n`).
Windows,
/// Force CR (`\n).
Unix,
/// `\r\n` in Windows, `\n`` on other platforms.
Native,
}
/// Macro for deriving implementations of Serialize/Deserialize for enums
#[macro_export]
macro_rules! impl_enum_serialize_and_deserialize {
( $e:ident, $( $variant:ident $(: $value:expr)* ),* ) => {
impl ::serde::ser::Serialize for $e {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: ::serde::ser::Serializer
{
use serde::ser::Error;
// We don't know whether the user of the macro has given us all options.
#[allow(unreachable_patterns)]
match *self {
$(
$e::$variant => serializer.serialize_str(
configuration_option_enum_stringify!($variant $(: $value)*)
),
)*
_ => {
Err(S::Error::custom(format!("Cannot serialize {:?}", self)))
}
}
}
}
impl<'de> ::serde::de::Deserialize<'de> for $e {
fn deserialize<D>(d: D) -> Result<Self, D::Error>
where D: ::serde::Deserializer<'de> {
use serde::de::{Error, Visitor};
use std::marker::PhantomData;
use std::fmt;
struct StringOnly<T>(PhantomData<T>);
impl<'de, T> Visitor<'de> for StringOnly<T>
where T: ::serde::Deserializer<'de> {
type Value = String;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("string")
}
fn visit_str<E>(self, value: &str) -> Result<String, E> {
Ok(String::from(value))
}
}
let s = d.deserialize_string(StringOnly::<D>(PhantomData))?;
$(
if configuration_option_enum_stringify!($variant $(: $value)*)
.eq_ignore_ascii_case(&s) {
return Ok($e::$variant);
}
)*
static ALLOWED: &'static[&str] = &[
$(configuration_option_enum_stringify!($variant $(: $value)*),)*];
Err(D::Error::unknown_variant(&s, ALLOWED))
}
}
impl ::std::str::FromStr for $e {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
$(
if configuration_option_enum_stringify!($variant $(: $value)*)
.eq_ignore_ascii_case(s) {
return Ok($e::$variant);
}
)*
Err("Bad variant")
}
}
impl ConfigType for $e {
fn doc_hint() -> String {
let mut variants = Vec::new();
$(
variants.push(
configuration_option_enum_stringify!($variant $(: $value)*)
);
)*
format!("[{}]", variants.join("|"))
}
}
};
}
macro_rules! configuration_option_enum {
($e:ident: $( $name:ident $(: $value:expr)* ),+ $(,)*) => (
#[derive(Copy, Clone, Eq, PartialEq)]
pub enum $e {
$( $name ),+
}
impl ::std::fmt::Debug for $e {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
f.write_str(match self {
$(
$e::$name => configuration_option_enum_stringify!($name $(: $value)*),
)+
})
}
}
impl_enum_serialize_and_deserialize!($e, $( $name $(: $value)* ),+);
);
}
configuration_option_enum! { NewlineStyle:
Auto, // Auto-detect based on the raw source input
Windows, // \r\n
Unix, // \n
Native, // \r\n in Windows, \n on other platforms
}
configuration_option_enum! { BraceStyle:
#[config_type]
/// Where to put the opening brace of items (`fn`, `impl`, etc.).
pub enum BraceStyle {
/// Put the opening brace on the next line.
AlwaysNextLine,
/// Put the opening brace on the same line, if possible.
PreferSameLine,
// Prefer same line except where there is a where-clause, in which case force
// the brace to the next line.
/// Prefer the same line except where there is a where-clause, in which
/// case force the brace to be put on the next line.
SameLineWhere,
}
configuration_option_enum! { ControlBraceStyle:
// K&R style, Rust community default
#[config_type]
/// Where to put the opening brace of conditional expressions (`if`, `match`, etc.).
pub enum ControlBraceStyle {
/// K&R style, Rust community default
AlwaysSameLine,
// Stroustrup style
/// Stroustrup style
ClosingNextLine,
// Allman style
/// Allman style
AlwaysNextLine,
}
configuration_option_enum! { IndentStyle:
// First line on the same line as the opening brace, all lines aligned with
// the first line.
#[config_type]
/// How to indent.
pub enum IndentStyle {
/// First line on the same line as the opening brace, all lines aligned with
/// the first line.
Visual,
// First line is on a new line and all lines align with block indent.
/// First line is on a new line and all lines align with **block** indent.
Block,
}
configuration_option_enum! { Density:
// Fit as much on one line as possible.
#[config_type]
/// How to place a list-like items.
pub enum Density {
/// Fit as much on one line as possible.
Compressed,
// Use more lines.
/// Use more lines.
Tall,
// Place every item on a separate line.
/// Place every item on a separate line.
Vertical,
}
configuration_option_enum! { TypeDensity:
// No spaces around "=" and "+"
#[config_type]
/// Spacing around type combinators.
pub enum TypeDensity {
/// No spaces around "=" and "+"
Compressed,
// Spaces around " = " and " + "
/// Spaces around " = " and " + "
Wide,
}
configuration_option_enum! { Heuristics:
// Turn off any heuristics
#[config_type]
/// To what extent does rustfmt pursue its heuristics?
pub enum Heuristics {
/// Turn off any heuristics
Off,
// Turn on max heuristics
/// Turn on max heuristics
Max,
// Use Rustfmt's defaults
/// Use Rustfmt's defaults
Default,
}
@ -193,45 +96,51 @@ impl Density {
}
}
configuration_option_enum! { ReportTactic:
#[config_type]
pub enum ReportTactic {
Always,
Unnumbered,
Never,
}
// What Rustfmt should emit. Mostly corresponds to the `--emit` command line
// option.
configuration_option_enum! { EmitMode:
// Emits to files.
/// What Rustfmt should emit. Mostly corresponds to the `--emit` command line
/// option.
#[config_type]
pub enum EmitMode {
/// Emits to files.
Files,
// Writes the output to stdout.
/// Writes the output to stdout.
Stdout,
// Displays how much of the input file was processed
/// Displays how much of the input file was processed
Coverage,
// Unfancy stdout
/// Unfancy stdout
Checkstyle,
// Output the changed lines (for internal value only)
/// Output the changed lines (for internal value only)
ModifiedLines,
// Checks if a diff can be generated. If so, rustfmt outputs a diff and quits with exit code 1.
// This option is designed to be run in CI where a non-zero exit signifies non-standard code
// formatting. Used for `--check`.
/// Checks if a diff can be generated. If so, rustfmt outputs a diff and
/// quits with exit code 1.
/// This option is designed to be run in CI where a non-zero exit signifies
/// non-standard code formatting. Used for `--check`.
Diff,
}
// Client-preference for coloured output.
configuration_option_enum! { Color:
// Always use color, whether it is a piped or terminal output
/// Client-preference for coloured output.
#[config_type]
pub enum Color {
/// Always use color, whether it is a piped or terminal output
Always,
// Never use color
/// Never use color
Never,
// Automatically use color, if supported by terminal
/// Automatically use color, if supported by terminal
Auto,
}
configuration_option_enum! { Version:
// 1.x.y
#[config_type]
/// rustfmt format style version.
pub enum Version {
/// 1.x.y. When specified, rustfmt will format in the same style as 1.0.0.
One,
// 2.x.y
/// 2.x.y. When specified, rustfmt will formatin the the latest style.
Two,
}
@ -246,12 +155,14 @@ impl Color {
}
}
// How chatty should Rustfmt be?
configuration_option_enum! { Verbosity:
// Emit more.
/// How chatty should Rustfmt be?
#[config_type]
pub enum Verbosity {
/// Emit more.
Verbose,
/// Default.
Normal,
// Emit as little as possible.
/// Emit as little as possible.
Quiet,
}
@ -417,10 +328,17 @@ pub trait CliOptions {
fn config_path(&self) -> Option<&Path>;
}
// The edition of the compiler (RFC 2052)
configuration_option_enum! { Edition:
Edition2015: 2015,
Edition2018: 2018,
/// The edition of the syntax and semntics of code (RFC 2052).
#[config_type]
pub enum Edition {
#[value = "2015"]
#[doc_hint = "2015"]
/// Edition 2015.
Edition2015,
#[value = "2018"]
#[doc_hint = "2018"]
/// Edition 2018.
Edition2018,
}
impl Default for Edition {

View file

@ -612,7 +612,7 @@ pub fn extract_post_comment(
post_snippet[1..].trim_matches(white_space)
} else if post_snippet.starts_with(separator) {
post_snippet[separator.len()..].trim_matches(white_space)
} else if post_snippet.ends_with(',') {
} else if post_snippet.ends_with(',') && !post_snippet.trim().starts_with("//") {
post_snippet[..(post_snippet.len() - 1)].trim_matches(white_space)
} else {
post_snippet