use cpp_formatter::config::Style;
#[track_caller]
fn check(input: &str, expected: &str) {
let style = style();
let path = std::path::Path::new("snippet.cpp");
let actual = cpp_formatter::format_file(path, input, &style);
let actual = actual.trim_end_matches('\n');
let expected = expected.trim_end_matches('\n');
assert_eq!(
actual, expected,
"formatting drifted\ninput:\n{input}\nexpected:\n{expected}\nactual:\n{actual}"
);
let again = cpp_formatter::format_file(path, expected, &style);
assert_eq!(again, expected, "the expected text is not a fixed point");
}
fn style() -> Style {
let mut style = Style::preset("LLVM").expect("LLVM is a preset");
style.set_from_text("IndentWidth", "4");
style.set_from_text("ContinuationIndentWidth", "8");
style.set_from_text("ColumnLimit", "0");
style
}
#[test]
fn preprocessor_01_define() {
check(
r#"#define MAX(a, b) ((a) > (b) ? (a) : (b))"#,
r#"#define MAX(a, b) ((a) > (b) ? (a) : (b))"#,
);
}
#[test]
fn preprocessor_02_if() {
check(
r#"#if DEBUG
int debug = 1;
#endif"#,
r#"#if DEBUG
int debug = 1;
#endif"#,
);
}
#[test]
fn preprocessor_03_include() {
check(
r#"#include <vector>
#include "local.h""#,
r#"#include "local.h"
#include <vector>"#,
);
}
#[test]
fn preprocessor_04_multiline() {
check(
r#"#define M(a) \
do { \
(void)(a); \
} while (0)"#,
r#"#define M(a) \
do { \
(void)(a); \
} while (0)"#,
);
}
#[test]
fn preprocessor_05_pragma() {
check(r#"#pragma once"#, r#"#pragma once"#);
}
#[test]
fn preprocessor_06_undef() {
check(r#"#undef FOO"#, r#"#undef FOO"#);
}
#[test]
fn preprocessor_07_define_alignment() {
let mut styled = style();
styled.set_from_text("ColumnLimit", "80");
let input = "#define BOOL_OPTION(op) \\\n if (auto n = root.GetValue(#op); n.IsBool()) \\\n { \\\n op = n.AsBool(); \\\n }\n";
let expected = "#define BOOL_OPTION(op) \\\n if (auto n = root.GetValue(#op); n.IsBool()) \\\n { \\\n op = n.AsBool(); \\\n }\n";
let path = std::path::Path::new("snippet.cpp");
let actual = cpp_formatter::format_file(path, input, &styled);
assert_eq!(actual, expected, "the backslashes end at column 80");
let again = cpp_formatter::format_file(path, expected, &styled);
assert_eq!(again, expected, "the expected text is not a fixed point");
}
#[test]
fn preprocessor_08_a_bare_macro_line() {
check(
"NLOHMANN_JSON_NAMESPACE_BEGIN\nnamespace detail {\nvoid f();\n}\n",
"NLOHMANN_JSON_NAMESPACE_BEGIN\nnamespace detail {\nvoid f();\n}\n",
);
}
#[test]
fn preprocessor_09_a_define_after_an_include() {
check(
"#if defined(A)\n#define THROW(e) throw e\n#else\n#include <cstdlib>\n#define THROW(e) std::abort()\n#endif\n",
"#if defined(A)\n#define THROW(e) throw e\n#else\n#include <cstdlib>\n#define THROW(e) std::abort()\n#endif\n",
);
}
#[test]
fn preprocessor_10_a_spliced_macro_keeps_its_lines() {
check(
"#define TWICE(x) \\\n int y = (x); \\\n use(y)\n",
"#define TWICE(x) \\\n int y = (x); \\\n use(y)\n",
);
}