use std::borrow::Cow;
use crate::options::StyleOption;
use crate::presets;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Style {
values: Vec<Value>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Value {
Unset,
Flag(bool),
Number(i64),
Text(Cow<'static, str>),
}
impl Default for Style {
fn default() -> Self {
Style::default_style()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigError {
pub line: usize,
pub what: String,
}
impl std::fmt::Display for ConfigError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(formatter, "line {}: {}", self.line, self.what)
}
}
impl std::error::Error for ConfigError {}
const LOADER_KEYS: &[&str] = &["BasedOnStyle", "Language", "InheritParentConfig"];
pub fn style_for_file(file: &std::path::Path) -> Style {
match find_config(file) {
Some((_, text)) => parse(&text, None).unwrap_or_else(|_| Style::default_style()),
None => Style::fallback_style(),
}
}
pub fn find_config(file: &std::path::Path) -> Option<(std::path::PathBuf, String)> {
let mut directory = file.parent().map(std::path::Path::to_path_buf);
if directory.is_none() {
directory = std::env::current_dir().ok();
}
while let Some(current) = directory {
let candidate = current.join(".clang-format");
if let Ok(text) = std::fs::read_to_string(&candidate) {
return Some((candidate, text));
}
directory = current.parent().map(std::path::Path::to_path_buf);
}
None
}
impl Style {
pub fn preset(name: &str) -> Option<Style> {
let canonical = canonical_preset(name)?;
let mut style = Style {
values: vec![Value::Unset; StyleOption::COUNT],
};
for (key, value) in presets::LLVM {
style.set_from_text(key, value);
}
if let Some(delta) = presets::delta(canonical) {
for (key, value) in delta {
style.set_from_text(key, value);
}
}
Some(style)
}
pub fn default_style() -> Style {
Style::preset("LLVM").expect("LLVM is a preset")
}
pub fn fallback_style() -> Style {
let mut style = Style::default_style();
style.set_from_text("IndentWidth", "4");
style
}
pub fn value(&self, option: StyleOption) -> &Value {
self.values.get(option as usize).unwrap_or(&Value::Unset)
}
pub fn flag(&self, option: StyleOption) -> bool {
match self.value(option) {
Value::Flag(value) => *value,
Value::Number(value) => *value != 0,
Value::Text(text) => {
matches!(
text.as_ref(),
"true" | "True" | "TRUE" | "Yes" | "On" | "1" | "Always"
)
}
Value::Unset => false,
}
}
pub fn number(&self, option: StyleOption) -> i64 {
match self.value(option) {
Value::Number(value) => *value,
Value::Flag(value) => *value as i64,
Value::Text(text) => text.trim().parse().unwrap_or(0),
Value::Unset => 0,
}
}
pub fn text(&self, option: StyleOption) -> &str {
match self.value(option) {
Value::Text(text) => text.as_ref(),
_ => "",
}
}
pub fn count(&self, option: StyleOption) -> usize {
self.number(option).max(0) as usize
}
pub fn set_from_text(&mut self, key: &str, text: &str) {
let Some(option) = StyleOption::from_key(key) else {
return;
};
let trimmed = text.trim();
let value = if trimmed.is_empty() {
Value::Text(Cow::Borrowed(""))
} else if let Some(flag) = parse_flag(trimmed) {
Value::Flag(flag)
} else if let Ok(number) = trimmed.parse::<i64>() {
Value::Number(number)
} else if let Some(borrowed) = borrow_a_preset_value(trimmed) {
borrowed
} else {
Value::Text(Cow::Owned(normalise_value(trimmed)))
};
if let Some(slot) = self.values.get_mut(option as usize) {
*slot = value;
}
}
pub fn knows(key: &str) -> bool {
LOADER_KEYS.contains(&key)
|| StyleOption::from_key(key).is_some()
|| presets::PARSED_BUT_NOT_DUMPED.contains(&key)
|| StyleOption::ALL.iter().any(|option| {
let name = option.key();
name.len() > key.len()
&& name.starts_with(key)
&& name.as_bytes()[key.len()] == b'.'
})
}
pub fn dump(&self) -> String {
let mut out = String::new();
for option in StyleOption::ALL {
let printed = match self.value(option) {
Value::Flag(true) => "true".to_string(),
Value::Flag(false) => "false".to_string(),
Value::Number(value) => value.to_string(),
Value::Text(text) => text.to_string(),
Value::Unset => String::new(),
};
out.push_str(option.key());
out.push(':');
if !printed.is_empty() {
out.push(' ');
out.push_str(&printed);
}
out.push('\n');
}
out
}
}
fn borrow_a_preset_value(text: &str) -> Option<Value> {
presets::LLVM
.iter()
.find(|(_, value)| *value == text)
.map(|(_, value)| Value::Text(Cow::Borrowed(*value)))
}
pub fn canonical_preset(name: &str) -> Option<&'static str> {
const NAMES: &[&str] = &[
"LLVM",
"Google",
"Chromium",
"Mozilla",
"WebKit",
"Microsoft",
"GNU",
];
NAMES
.iter()
.copied()
.find(|known| known.eq_ignore_ascii_case(name))
}
pub fn parse(text: &str, base: Option<&str>) -> Result<Style, ConfigError> {
let documents = split_documents(text);
let mut chosen: Option<(usize, &String)> = None;
for (start_line, document) in &documents {
let language = document
.lines()
.find_map(|line| line.trim().strip_prefix("Language:"))
.map(|value| value.trim().to_string());
let applies = match language.as_deref() {
None | Some("") => true,
Some("Cpp") => true,
Some(_) => false,
};
if applies {
chosen = Some((*start_line, document));
break;
}
}
let Some((start_line, document)) = chosen else {
return Err(ConfigError {
line: 1,
what: "no document applies to C++".to_string(),
});
};
let mut based_on: Option<String> = None;
for line in document.lines() {
let line = strip_comment(line);
let Some((key, value)) = split_key(&line) else {
continue;
};
if key == "BasedOnStyle" {
based_on = Some(value.trim().to_string());
}
}
let base_name = based_on.as_deref().or(base).unwrap_or("LLVM").to_string();
let mut style = Style::preset(&base_name).ok_or(ConfigError {
line: start_line,
what: format!("unknown style `{base_name}`"),
})?;
apply_document(&mut style, document, start_line)?;
Ok(style)
}
fn apply_document(style: &mut Style, document: &str, start_line: usize) -> Result<(), ConfigError> {
let mut parents: Vec<(usize, String)> = Vec::new();
for (offset, raw) in document.lines().enumerate() {
let line_number = start_line + offset;
let line = strip_comment(raw);
if line.trim().is_empty() {
continue;
}
let indent = line.len() - line.trim_start().len();
let (key, value) = split_key(&line).ok_or(ConfigError {
line: line_number,
what: format!("not a `key: value` line: `{}`", raw.trim()),
})?;
let key = key.trim();
let value = value.trim();
while matches!(parents.last(), Some((parent_indent, _)) if *parent_indent >= indent) {
parents.pop();
}
let qualified = match parents.last() {
Some((_, parent)) => format!("{parent}.{key}"),
None => key.to_string(),
};
if value.is_empty() {
if !Style::knows(&qualified) && !Style::knows(key) {
return Err(ConfigError {
line: line_number,
what: format!("unknown key `{key}`"),
});
}
parents.push((indent, qualified));
continue;
}
if LOADER_KEYS.contains(&key) {
continue;
}
if !Style::knows(&qualified) {
return Err(ConfigError {
line: line_number,
what: format!("unknown key `{qualified}`"),
});
}
if let Some(mapped) = successors(&qualified, value) {
for (successor_key, successor_value) in mapped {
style.set_from_text(successor_key, successor_value);
}
continue;
}
style.set_from_text(&qualified, value);
}
Ok(())
}
fn normalise_value(value: &str) -> String {
let trimmed = value.trim();
if (trimmed.starts_with('"') && trimmed.ends_with('"') && trimmed.len() >= 2)
|| (trimmed.starts_with('\'') && trimmed.ends_with('\'') && trimmed.len() >= 2)
{
return trimmed[1..trimmed.len() - 1].to_string();
}
trimmed.to_string()
}
fn parse_flag(value: &str) -> Option<bool> {
match value.trim() {
"true" | "True" | "TRUE" | "Yes" | "On" => Some(true),
"false" | "False" | "FALSE" | "No" | "Off" => Some(false),
_ => None,
}
}
fn split_key(line: &str) -> Option<(&str, &str)> {
let mut quote: Option<char> = None;
for (index, character) in line.char_indices() {
match character {
'"' | '\'' if quote.is_none() => quote = Some(character),
'"' | '\'' if quote == Some(character) => quote = None,
':' if quote.is_none() => return Some((&line[..index], &line[index + 1..])),
_ => {}
}
}
None
}
fn strip_comment(line: &str) -> String {
let mut quote: Option<char> = None;
for (index, character) in line.char_indices() {
match character {
'"' | '\'' if quote.is_none() => quote = Some(character),
'"' | '\'' if quote == Some(character) => quote = None,
'#' if quote.is_none() => return line[..index].to_string(),
_ => {}
}
}
line.to_string()
}
fn successors(key: &str, value: &str) -> Option<Vec<(&'static str, &'static str)>> {
let on = matches!(value.trim(), "true" | "True" | "Yes" | "On" | "1");
Some(match key {
"SpacesInParentheses" => {
if on {
vec![
("SpacesInParens", "Custom"),
("SpacesInParensOptions.Other", "true"),
("SpacesInParensOptions.InConditionalStatements", "true"),
("SpacesInParensOptions.InEmptyParentheses", "true"),
("SpacesInParensOptions.InCStyleCasts", "true"),
]
} else {
vec![("SpacesInParens", "Never")]
}
}
"SpacesInConditionalStatement"
| "SpacesInCStyleCastParentheses"
| "SpaceInEmptyParentheses" => vec![
("SpacesInParens", "Custom"),
(
match key {
"SpacesInConditionalStatement" => {
"SpacesInParensOptions.InConditionalStatements"
}
"SpacesInCStyleCastParentheses" => "SpacesInParensOptions.InCStyleCasts",
_ => "SpacesInParensOptions.InEmptyParentheses",
},
if on { "true" } else { "false" },
),
],
"AlignTrailingComments" => vec![(
"AlignTrailingComments.Kind",
if on { "Always" } else { "Never" },
)],
"KeepEmptyLinesAtTheStartOfBlocks" => {
vec![(
"KeepEmptyLinesAtStartOfBlock",
if on { "true" } else { "false" },
)]
}
"AlwaysBreakTemplateDeclarations" => {
vec![("BreakTemplateDeclarations", if on { "Yes" } else { "No" })]
}
"AlwaysBreakAfterReturnType" => vec![("BreakAfterReturnType", leak(value.trim()))],
"BreakBeforeInheritanceComma" => vec![("BreakInheritanceList", leak(value.trim()))],
"BreakConstructorInitializersBeforeComma" => {
vec![("BreakConstructorInitializers", leak(value.trim()))]
}
"ConstructorInitializerAllOnOneLineOrOnePerLine" => {
vec![(
"PackConstructorInitializers",
if on { "BinPack" } else { "NextLine" },
)]
}
_ => return None,
})
}
fn leak(value: &str) -> &'static str {
match value {
"Left" => "Left",
"Right" => "Right",
"BeforeComma" => "BeforeComma",
"AfterComma" => "AfterComma",
"CurrentLine" => "CurrentLine",
"NextLine" => "NextLine",
"None" => "None",
"All" => "All",
"TopLevel" => "TopLevel",
"AllDefinitions" => "AllDefinitions",
"BinPack" => "BinPack",
_ => "None",
}
}
fn split_documents(text: &str) -> Vec<(usize, String)> {
let mut documents: Vec<(usize, String)> = Vec::new();
let mut current = String::new();
let mut current_start = 1usize;
let mut current_has_content = false;
for (index, line) in text.lines().enumerate() {
let number = index + 1;
if line.trim() == "---" {
if current_has_content {
documents.push((current_start, std::mem::take(&mut current)));
current_has_content = false;
}
current_start = number + 1;
continue;
}
if !current_has_content && !line.trim().is_empty() {
current_start = number;
current_has_content = true;
}
current.push_str(line);
current.push('\n');
}
if current_has_content {
documents.push((current_start, current));
}
if documents.is_empty() {
documents.push((1, text.to_string()));
}
documents
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_llvm_preset_is_the_base_and_every_other_preset_overrides_it() {
let llvm = Style::preset("LLVM").unwrap();
assert_eq!(llvm.number(StyleOption::IndentWidth), 2);
assert_eq!(llvm.text(StyleOption::BreakBeforeBraces), "Attach");
let google = Style::preset("google").unwrap();
assert_eq!(google.number(StyleOption::ColumnLimit), 80);
assert_eq!(google.text(StyleOption::BreakBeforeBraces), "Attach");
assert_eq!(google.text(StyleOption::PointerAlignment), "Left");
assert!(google.flag(StyleOption::IndentCaseLabels));
assert_eq!(
google.number(StyleOption::TabWidth),
llvm.number(StyleOption::TabWidth)
);
let gnu = Style::preset("GNU").unwrap();
assert_eq!(gnu.number(StyleOption::ColumnLimit), 79);
assert_eq!(gnu.text(StyleOption::BreakBeforeBraces), "GNU");
let microsoft = Style::preset("Microsoft").unwrap();
assert_eq!(microsoft.text(StyleOption::BreakBeforeBraces), "Custom");
assert_eq!(microsoft.number(StyleOption::ColumnLimit), 120);
}
#[test]
fn a_document_overrides_the_preset_and_keeps_the_rest() {
let style = parse(
"BasedOnStyle: LLVM\nIndentWidth: 4\nBraceWrapping:\n AfterClass: true\n",
None,
)
.unwrap();
assert_eq!(style.number(StyleOption::IndentWidth), 4);
assert!(style.flag(StyleOption::BraceWrappingAfterClass));
assert!(!style.flag(StyleOption::BraceWrappingAfterFunction));
assert_eq!(style.number(StyleOption::ColumnLimit), 80);
}
#[test]
fn the_nearest_configuration_wins_and_the_default_is_the_fallback() {
let root = std::env::temp_dir().join(format!("cppfmt-style-{}", std::process::id()));
let nested = root.join("a/b");
std::fs::create_dir_all(&nested).expect("the tree is creatable");
std::fs::write(root.join(".clang-format"), "IndentWidth: 7\n")
.expect("the config is writable");
let inside = nested.join("x.cpp");
std::fs::write(&inside, "int x;\n").expect("the file is writable");
let style = style_for_file(&inside);
assert_eq!(
style.count(crate::options::StyleOption::IndentWidth),
7,
"the nearest `.clang-format` wins"
);
std::fs::remove_dir_all(&root).ok();
let orphan = std::env::temp_dir().join("cppfmt-style-none/x.cpp");
assert_eq!(
style_for_file(&orphan).count(crate::options::StyleOption::IndentWidth),
Style::fallback_style().count(crate::options::StyleOption::IndentWidth),
"with no configuration anywhere the default style is the answer"
);
}
#[test]
fn an_unknown_key_is_an_error_with_its_line() {
let error = parse("BasedOnStyle: LLVM\nIndentWidht: 4\n", None).unwrap_err();
assert_eq!(error.line, 2);
assert!(error.what.contains("IndentWidht"), "{}", error.what);
}
#[test]
fn a_comment_and_a_quoted_colon_do_not_confuse_the_split() {
let style = parse(
"IndentWidth: 3 # three\nTabWidth: 8\nIncludeIsMainRegex: 'a:b'\n",
None,
)
.unwrap();
assert_eq!(style.number(StyleOption::IndentWidth), 3);
assert_eq!(style.text(StyleOption::IncludeIsMainRegex), "a:b");
}
#[test]
fn a_value_is_parsed_once_and_answered_by_index() {
let style = parse("IndentWidth: 4\nIndentCaseLabels: 1\n", None).unwrap();
assert!(matches!(
style.value(StyleOption::IndentWidth),
Value::Number(4)
));
assert!(style.flag(StyleOption::IndentCaseLabels));
assert_eq!(style.count(StyleOption::IndentWidth), 4);
assert!(style.flag(StyleOption::IndentCaseLabels));
assert!(matches!(
Style::default_style().value(StyleOption::BreakBeforeBraces),
Value::Text(Cow::Borrowed(_))
));
}
#[test]
fn a_renamed_key_is_translated_and_not_dropped() {
let style = parse("SpacesInParentheses: true\n", None).unwrap();
assert_eq!(style.text(StyleOption::SpacesInParens), "Custom");
assert!(style.flag(StyleOption::SpacesInParensOptionsOther));
assert!(style.flag(StyleOption::SpacesInParensOptionsInConditionalStatements));
let off = parse("SpacesInParentheses: false\n", None).unwrap();
assert_eq!(off.text(StyleOption::SpacesInParens), "Never");
let comments = parse("AlignTrailingComments: false\n", None).unwrap();
assert_eq!(
comments.text(StyleOption::AlignTrailingCommentsKind),
"Never"
);
let comments = parse("AlignTrailingComments: true\n", None).unwrap();
assert_eq!(
comments.text(StyleOption::AlignTrailingCommentsKind),
"Always"
);
let empty = parse("KeepEmptyLinesAtTheStartOfBlocks: true\n", None).unwrap();
assert!(empty.flag(StyleOption::KeepEmptyLinesAtStartOfBlock));
}
#[test]
fn the_dump_prints_every_option_sorted() {
let dumped = Style::default_style().dump();
let keys: Vec<&str> = dumped
.lines()
.map(|line| line.split(':').next().unwrap_or(""))
.collect();
assert_eq!(keys.len(), StyleOption::COUNT);
let mut sorted = keys.clone();
sorted.sort_unstable();
assert_eq!(keys, sorted);
assert!(dumped.contains("IndentWidth: 2\n"), "{dumped}");
}
}
#[cfg(test)]
mod flag_tests {
use super::*;
#[test]
fn an_enumerated_flag_reads_as_true() {
let style = Style::preset("LLVM").expect("LLVM is a preset");
assert!(style.flag(StyleOption::ReflowComments));
let mut other = Style::preset("LLVM").expect("LLVM is a preset");
other.set_from_text("ReflowComments", "Never");
assert!(!other.flag(StyleOption::ReflowComments));
}
}