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
/// Code snippet formatting error.
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum FormatError {
    /// An `io::Error` occurred.
    ///
    /// This usually occurs when the stdio redirection fails.
    Io,
    /// Converting `stdout` to `str` failed.
    StrConvertFailed,
    /// `rustfmt` failed in formatting.
    RustfmtFailure,
}

/// Format a code snippet using an external `rustfmt` call.
///
/// # Example
/// ```rust
/// let src = "fn a_b(  s: & str) -> String {   String::new(  )  }";
/// let fmtd = papyrus::fmt::format(src).unwrap();
/// assert_eq!(&fmtd, r#"fn a_b(s: &str) -> String {
///     String::new()
/// }"#);
/// ```
pub fn format(code_snippet: &str) -> Result<String, FormatError> {
    use std::{io::Write, process::*};

    let (success, outputbuf) = {
        let mut child = Command::new("rustfmt")
            .args(&["--config", "newline_style=Unix"])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .map_err(|_| FormatError::RustfmtFailure)?;

        let stdin = child.stdin.as_mut().expect("stdin has been set");
        write!(stdin, "fn __fmt_wrapper() {{ {} }}", code_snippet)
            .map_err(|_| FormatError::RustfmtFailure)?;

        let output = child
            .wait_with_output()
            .map_err(|_| FormatError::RustfmtFailure)?;

        (output.status.success(), output.stdout)
    };

    if success && !outputbuf.is_empty() {
        let s = std::str::from_utf8(&outputbuf).map_err(|_| FormatError::StrConvertFailed)?;

        let trimmed = s.trim();
        let end = trimmed.len().saturating_sub(2); // \n}

        // the output of rustfmt can change...
        // at the moment it is
        // fn __fmt_wrapper() {\n
        // 0....................^ 21 chars long
        Ok(reduce_indent(&trimmed[21..end]))
    } else {
        Err(FormatError::RustfmtFailure)
    }
}

fn reduce_indent(s: &str) -> String {
    #[derive(Copy, Clone, PartialEq, Eq)]
    enum LitType {
        Literal,
        Str,
        None,
    };
    use LitType::*;
    const LITERALS: [(&str, &str); 6] = [
        (r##"r#""##, r##""#"##),
        (r###"r##""###, r###""#"###),
        (r####"r###""####, r####""###"####),
        (r#####"r####""#####, r#####""####"#####),
        (r######"r#####""######, r######""#####"######),
        (r#######"r######""#######, r#######""######"#######),
    ];
    let mut literal = None;
    let mut idx = 0;
    let mut reduced = String::with_capacity(s.len());
    for line in s.lines() {
        match literal {
            Str => {
                reduced.push_str(line);
                if odd_quotations(line) {
                    literal = None;
                }
            }
            Literal => {
                reduced.push_str(line);
                if line.contains(LITERALS[idx].1) {
                    literal = None;
                }
            }
            None => {
                reduced.push_str(&line[4..]);
                for (i, l) in LITERALS.iter().enumerate() {
                    if line.contains(l.0) && !line.contains(l.1) {
                        idx = i;
                        literal = Literal;
                        break;
                    }
                }
                if literal == None && odd_quotations(line) {
                    literal = Str;
                }
            }
        }
        reduced.push('\n');
    }
    reduced.pop();
    reduced
}

/// Counts quotations and returns if odd or not, indicating if there is unmatched string.
/// Ignores escaped quotes. (so string contains sequence `\"`).
fn odd_quotations(s: &str) -> bool {
    let mut odd = false;
    let mut escaped = false;
    for ch in s.chars() {
        match ch {
            '\\' => escaped = true,
            '\"' if !escaped => odd = !odd,
            _ if escaped => escaped = false,
            _ => (),
        }
    }
    odd
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_format_expr() {
        let snippet = "a+b";
        let s = format(snippet);
        let ans = s.as_ref().map(|x| x.as_str());
        assert_eq!(ans, Ok("a + b"));
    }

    #[test]
    fn test_format_stmt() {
        let snippet = "println! ( \"  \", aaaa ) ;";
        let s = format(snippet);
        let ans = s.as_ref().map(|x| x.as_str());
        assert_eq!(ans, Ok("println!(\"  \", aaaa);"));
    }

    #[test]
    fn test_format_func() {
        let snippet = "fn fmt(){ let a = 1  ; a + b  } ";
        let s = format(snippet);
        let ans = s.as_ref().map(|x| x.as_str());
        assert_eq!(
            ans,
            Ok(r#"fn fmt() {
    let a = 1;
    a + b
}"#)
        );
    }

    #[test]
    fn test_format_err() {
        let snippet = "fn fmt(){ let a = 1  ; a + b   ";
        let s = format(snippet);
        let ans = s.as_ref().map(|x| x.as_str());
        assert_eq!(ans, Err(&FormatError::RustfmtFailure));
    }

    #[test]
    fn test_odd_quotations() {
        assert_eq!(odd_quotations(""), false);
        assert_eq!(odd_quotations("no quoates"), false);
        assert_eq!(odd_quotations(r#""this is a matched string""#), false);
        assert_eq!(odd_quotations(r#""This has \"String\" string""#), false);
        assert_eq!(odd_quotations(r#""This is missing closing quote"#), true);
        assert_eq!(odd_quotations(r#""This has \"escaped\" and missing"#), true);
        assert_eq!(odd_quotations(r#""one "two "three"#), true);
        assert_eq!(odd_quotations(r#""one", "two""#), false);
    }

    #[test]
    fn test_multiline_literal_str() {
        let s = r##"   let s =  r#"Hello
    World
    What
        Up"#;  "##;
        let fmtd = format(s);
        let ans = fmtd.as_ref().map(|x| x.as_str());
        assert_eq!(
            ans,
            Ok(r##"let s = r#"Hello
    World
    What
        Up"#;"##)
        );

        let s = r#""Hello
World
    This
        Indent""#;
        let fmtd = format(s);
        let ans = fmtd.as_ref().map(|x| x.as_str());
        assert_eq!(ans, Ok(s));
    }
}