use cpp_code_analysis::format::{FormatKind, PieceKind, pieces_in};
fn pieces(literal: &str, kind: FormatKind) -> Vec<(&'static str, &str)> {
let mut found = Vec::new();
pieces_in(literal, kind, &mut found);
found
.iter()
.map(|piece| {
let name = match piece.kind {
PieceKind::Specifier => "specifier",
PieceKind::Argument => "argument",
PieceKind::Conversion => "conversion",
PieceKind::Escape => "escape",
PieceKind::DynamicWidth => "dynamic",
};
(name, &literal[piece.start..piece.end])
})
.collect()
}
#[test]
fn a_std_field_is_its_own_pieces() {
for (literal, expected) in [
(r#""{}""#, vec![("specifier", "{}")]),
(r#""hello {}""#, vec![("specifier", "{}")]),
(
r#""{0}""#,
vec![("specifier", "{"), ("argument", "0"), ("specifier", "}")],
),
(
r#""{name}""#,
vec![("specifier", "{"), ("argument", "name"), ("specifier", "}")],
),
(
r#""{:.3f}""#,
vec![
("specifier", "{:.3"),
("conversion", "f"),
("specifier", "}"),
],
),
(r#""{:>10}""#, vec![("specifier", "{:>10}")]),
(r#""{:*<8}""#, vec![("specifier", "{:*<8}")]),
(
r#""{:+08.2f}""#,
vec![
("specifier", "{:+08.2"),
("conversion", "f"),
("specifier", "}"),
],
),
(
r#""{:?}""#,
vec![("specifier", "{:"), ("conversion", "?"), ("specifier", "}")],
),
(r#""{:L}""#, vec![("specifier", "{:L}")]),
(
r#""{:{}}""#,
vec![("specifier", "{:"), ("dynamic", "{}"), ("specifier", "}")],
),
(
r#""{0:{1}.{2}f}""#,
vec![
("specifier", "{"),
("argument", "0"),
("specifier", ":"),
("dynamic", "{1}"),
("specifier", "."),
("dynamic", "{2}"),
("conversion", "f"),
("specifier", "}"),
],
),
(r#""{{}}""#, vec![("escape", "{{}}")]),
(r#""{{x}}""#, vec![("escape", "{{"), ("escape", "}}")]),
(
r#""值 = {:.3f},宽度 {:{}} {{ok}}""#,
vec![
("specifier", "{:.3"),
("conversion", "f"),
("specifier", "}"),
("specifier", "{:"),
("dynamic", "{}"),
("specifier", "}"),
("escape", "{{"),
("escape", "}}"),
],
),
] {
assert_eq!(pieces(literal, FormatKind::Std), expected, "{literal}");
}
}
#[test]
fn an_unclosed_field_stops_at_the_end_of_the_literal() {
for (literal, expected) in [
(r#""{""#, vec![("specifier", "{")]),
(r#""{:""#, vec![("specifier", "{:")]),
(r#""{0""#, vec![("specifier", "{"), ("argument", "0")]),
(r#""{:.2""#, vec![("specifier", "{:.2")]),
(
r#""{0x}""#,
vec![("specifier", "{"), ("argument", "0"), ("specifier", "x}")],
),
(r#""a{b""#, vec![("specifier", "{"), ("argument", "b")]),
] {
assert_eq!(pieces(literal, FormatKind::Std), expected, "{literal}");
}
}
#[test]
fn a_printf_conversion_is_its_own_pieces() {
for (literal, expected) in [
(r#""%d""#, vec![("specifier", "%"), ("conversion", "d")]),
(r#""%.2f""#, vec![("specifier", "%.2"), ("conversion", "f")]),
(
r#""%-8.2f""#,
vec![("specifier", "%-8.2"), ("conversion", "f")],
),
(
r#""%+05d""#,
vec![("specifier", "%+05"), ("conversion", "d")],
),
(r#""%#x""#, vec![("specifier", "%#"), ("conversion", "x")]),
(
r#""%1$s""#,
vec![("specifier", "%"), ("argument", "1$"), ("conversion", "s")],
),
(
r#""%*d""#,
vec![("specifier", "%"), ("argument", "*"), ("conversion", "d")],
),
(
r#""%.*f""#,
vec![("specifier", "%."), ("argument", "*"), ("conversion", "f")],
),
(r#""%zu""#, vec![("specifier", "%z"), ("conversion", "u")]),
(r#""%lld""#, vec![("specifier", "%ll"), ("conversion", "d")]),
(r#""%Lf""#, vec![("specifier", "%L"), ("conversion", "f")]),
(r#""%n""#, vec![("specifier", "%"), ("conversion", "n")]),
(r#""%m""#, vec![("specifier", "%"), ("conversion", "m")]),
(r#""%%""#, vec![("escape", "%%")]),
(r#""%%d""#, vec![("escape", "%%")]),
(
r#""%-8.2f|%*d|%1$s|%%""#,
vec![
("specifier", "%-8.2"),
("conversion", "f"),
("specifier", "%"),
("argument", "*"),
("conversion", "d"),
("specifier", "%"),
("argument", "1$"),
("conversion", "s"),
("escape", "%%"),
],
),
] {
assert_eq!(pieces(literal, FormatKind::Printf), expected, "{literal}");
}
}
#[test]
fn a_broken_printf_conversion_is_left_alone() {
for (literal, expected) in [
(r#""%""#, vec![]),
(r#""100%""#, vec![]),
(r#""%5""#, vec![]),
(r#""%.2""#, vec![]),
(r#""%y""#, vec![]),
(r#""%y %d""#, vec![("specifier", "%"), ("conversion", "d")]),
] {
assert_eq!(pieces(literal, FormatKind::Printf), expected, "{literal}");
}
}
#[test]
fn a_scanf_conversion_is_its_own_pieces() {
for (literal, expected) in [
(r#""%d""#, vec![("specifier", "%"), ("conversion", "d")]),
(r#""%3d""#, vec![("specifier", "%3"), ("conversion", "d")]),
(r#""%ld""#, vec![("specifier", "%l"), ("conversion", "d")]),
(
r#""%*d""#,
vec![("specifier", "%"), ("argument", "*"), ("conversion", "d")],
),
(
r#""%[a-z]""#,
vec![("specifier", "%"), ("conversion", "[a-z]")],
),
(
r#""%[^,]\n""#,
vec![("specifier", "%"), ("conversion", "[^,]")],
),
(r#""%[]]""#, vec![("specifier", "%"), ("conversion", "[]]")]),
(
r#""%[abc""#,
vec![("specifier", "%"), ("conversion", "[abc")],
),
(r#""%n""#, vec![("specifier", "%"), ("conversion", "n")]),
(r#""%p""#, vec![("specifier", "%"), ("conversion", "p")]),
(r#""%-d""#, vec![]),
(r#""%.2f""#, vec![]),
(
r#""%3d %[a-z] %n""#,
vec![
("specifier", "%3"),
("conversion", "d"),
("specifier", "%"),
("conversion", "[a-z]"),
("specifier", "%"),
("conversion", "n"),
],
),
] {
assert_eq!(pieces(literal, FormatKind::Scanf), expected, "{literal}");
}
}
#[test]
fn backslashes_are_read_the_way_the_language_reads_them() {
assert_eq!(
pieces(r#""\n%d""#, FormatKind::Printf),
vec![("specifier", "%"), ("conversion", "d")],
"a newline is not a conversion's start"
);
assert_eq!(
pieces(r#""\{""#, FormatKind::Std),
vec![],
"`\\{{` is a brace the format string never sees"
);
assert_eq!(
pieces(r#""%%\n""#, FormatKind::Printf),
vec![("escape", "%%")],
"the escape is painted and the newline after it is not part of it"
);
assert_eq!(
pieces(r#"R"(\{d})""#, FormatKind::Std),
vec![("specifier", "{"), ("argument", "d"), ("specifier", "}")],
"in a raw string the brace is real"
);
assert_eq!(
pieces(r#"R"xy({{)xy""#, FormatKind::Std),
vec![("escape", "{{")],
"a raw string's delimiter is not content"
);
assert_eq!(
pieces(r#"R"(%d)""#, FormatKind::Printf),
vec![("specifier", "%"), ("conversion", "d")],
"and a conversion is still a conversion"
);
}
#[test]
fn a_literal_prefix_is_skipped() {
for prefix in ["", "u8", "L", "u", "U"] {
let literal = format!(r#"{prefix}"%d""#);
assert_eq!(
pieces(&literal, FormatKind::Printf),
vec![("specifier", "%"), ("conversion", "d")],
"{literal}"
);
let literal = format!(r#"{prefix}R"(%d)""#);
assert_eq!(
pieces(&literal, FormatKind::Printf),
vec![("specifier", "%"), ("conversion", "d")],
"{literal}"
);
}
}
#[test]
fn every_piece_is_in_order_and_inside_the_literal() {
let literals = [
(r#""值 = {:.3f},宽度 {:{}} {{ok}}""#, FormatKind::Std),
(r#""{0:{1}.{2}f}""#, FormatKind::Std),
(r#""{""#, FormatKind::Std),
(r#""{0x}""#, FormatKind::Std),
(r#""%-8.2f|%*d|%1$s|%%""#, FormatKind::Printf),
(r#""%y %d""#, FormatKind::Printf),
(r#""%3d %[a-z] %n""#, FormatKind::Scanf),
(r#""%[]]""#, FormatKind::Scanf),
];
for (literal, kind) in literals {
let mut found = Vec::new();
pieces_in(literal, kind, &mut found);
let mut previous_end = 0usize;
for piece in &found {
assert!(
piece.start >= previous_end,
"{literal}: {:?} starts at {} before the previous piece ends at {previous_end}",
piece.kind,
piece.start
);
assert!(
piece.end <= literal.len(),
"{literal}: {:?} ends at {} past the literal's {} bytes",
piece.kind,
piece.end,
literal.len()
);
assert!(piece.start < piece.end, "{literal}: an empty piece");
assert!(
literal.is_char_boundary(piece.start) && literal.is_char_boundary(piece.end),
"{literal}: a piece that splits a character"
);
previous_end = piece.end;
}
}
}
#[test]
fn a_piece_carries_the_bytes_it_covers() {
let mut found = Vec::new();
pieces_in(r#""%-8.2f|%*d""#, FormatKind::Printf, &mut found);
let ranges: Vec<(usize, usize, &str)> = found
.iter()
.map(|piece| {
(
piece.start,
piece.end,
match piece.kind {
PieceKind::Specifier => "specifier",
PieceKind::Argument => "argument",
PieceKind::Conversion => "conversion",
PieceKind::Escape => "escape",
PieceKind::DynamicWidth => "dynamic",
},
)
})
.collect();
assert_eq!(
ranges,
vec![
(1, 6, "specifier"), (6, 7, "conversion"), (8, 9, "specifier"), (9, 10, "argument"), (10, 11, "conversion"), ]
);
let mut found = Vec::new();
pieces_in(r#""{:{}}""#, FormatKind::Std, &mut found);
let ranges: Vec<(usize, usize)> = found.iter().map(|p| (p.start, p.end)).collect();
assert_eq!(
ranges,
vec![(1, 3), (3, 5), (5, 6)],
"`{{:` then the nested `{{}}` then the closing brace"
);
}
#[test]
fn a_token_that_is_not_a_literal_is_ignored() {
for text in ["", "abc", "\"", "\"unterminated", "R\"", "R\"(", "u8", "%%"] {
let mut found = Vec::new();
pieces_in(text, FormatKind::Std, &mut found);
pieces_in(text, FormatKind::Printf, &mut found);
pieces_in(text, FormatKind::Scanf, &mut found);
assert!(
found.iter().all(|piece| piece.end <= text.len()),
"{text:?}: a piece past the end of the token"
);
}
}
#[test]
fn a_piece_explains_itself() {
use cpp_code_analysis::format::describe;
fn of(literal: &str, needle: &str, kind: FormatKind) -> Vec<String> {
let mut found = Vec::new();
pieces_in(literal, kind, &mut found);
let at = literal.find(needle).expect("the fixture writes it");
let piece = found
.iter()
.find(|piece| piece.start <= at && at < piece.end)
.unwrap_or_else(|| panic!("{needle:?} is inside a piece of {literal}"));
describe(literal, kind, piece)
.into_iter()
.map(|(label, value)| format!("{label}: {value}"))
.collect()
}
assert_eq!(
of(r#""%.2f""#, "f", FormatKind::Printf),
vec!["type: fixed-point decimal — a `double` written as `-.--`"],
"the conversion the reader looks up"
);
assert_eq!(
of(r#""%zu""#, "u", FormatKind::Printf),
vec!["type: unsigned decimal"],
"…and what the letter after the length modifier means"
);
assert_eq!(
of(r#""%-8.2f""#, "-8.2", FormatKind::Printf),
vec!["flags: left-aligned", "width: 8", "precision: 2"]
);
assert_eq!(
of(r#""%#llx""#, "#ll", FormatKind::Printf),
vec![
"flags: an alternative form (`0x`, a leading `0`)",
"length: a `long long`"
]
);
assert_eq!(
of(r#""%d""#, "%", FormatKind::Printf),
vec!["conversion: introduced by `%`; the letter after any flags and width says which"]
);
assert_eq!(
of(r#""%*d""#, "*", FormatKind::Printf),
vec!["argument: the width or precision comes from an argument"]
);
assert_eq!(
of(r#""%1$s""#, "1$", FormatKind::Printf),
vec!["argument: number 1, counted from 1 — and this conversion does not advance the count"]
);
assert_eq!(
of(r#""%[a-z]""#, "[a-z]", FormatKind::Scanf),
vec!["set: one or more characters from `a-z`"]
);
assert_eq!(
of(r#""%[^,]\n""#, "[^,]", FormatKind::Scanf),
vec!["set: one or more characters **not** in `,`"]
);
assert_eq!(
of(r#""%*d""#, "*", FormatKind::Scanf),
vec!["argument: assigns nothing: the conversion is read and discarded"]
);
assert_eq!(
of(r#""{:>10}""#, ">10", FormatKind::Std),
vec!["align: right", "width: 10"]
);
assert_eq!(
of(r#""{:*<8}""#, "*<8", FormatKind::Std),
vec!["fill: `*`", "align: left", "width: 8"]
);
assert_eq!(
of(r#""{:.3f}""#, "f", FormatKind::Std),
vec!["type: fixed-point decimal"]
);
assert_eq!(
of(r#""{:#x}""#, "#", FormatKind::Std),
vec!["flags: an alternative form (`0x`, `0b`, a leading `0`)"],
"a std flag, whose alternative form is not printf's"
);
assert_eq!(
of(r#""{}""#, "{}", FormatKind::Std),
vec!["field: formatted the way the argument's type defaults to"]
);
assert_eq!(
of(r#""{""#, "{", FormatKind::Std),
vec!["field: formatted the way the argument's type defaults to"]
);
}
#[test]
fn a_conversion_is_offered_where_one_can_go() {
use cpp_code_analysis::format::completions_at;
fn at(literal: &str, kind: FormatKind) -> Vec<String> {
let at = literal.find('|').expect("the fixture marks the cursor");
let without = literal.replace('|', "");
completions_at(&without, kind, at)
.into_iter()
.map(|item| item.label)
.collect()
}
assert!(at(r#""%|""#, FormatKind::Printf).contains(&"d".to_string()));
assert!(at(r#""%-8.2|""#, FormatKind::Printf).contains(&"f".to_string()));
assert!(at(r#""%5.|""#, FormatKind::Printf).contains(&"x".to_string()));
assert!(at(r#""%ll|""#, FormatKind::Printf).contains(&"u".to_string()));
assert!(
!at(r#""%*|""#, FormatKind::Scanf).is_empty(),
"after a suppression a conversion goes"
);
assert!(
at(r#""%[a-z]|""#, FormatKind::Scanf).is_empty(),
"after a whole scanset there is nothing left to say"
);
assert!(at(r#""%|""#, FormatKind::Scanf).contains(&"s".to_string()));
assert!(at(r#""{:|}""#, FormatKind::Std).contains(&"d".to_string()));
assert!(
at(r#""{:>10|""#, FormatKind::Std).contains(&"f".to_string()),
"after a width the type still goes"
);
assert!(
at(r#""%%|""#, FormatKind::Printf).is_empty(),
"after an escape"
);
assert!(
at(r#""%d|""#, FormatKind::Printf).is_empty(),
"after a whole conversion"
);
assert!(
at(r#""%-|8d""#, FormatKind::Printf).is_empty(),
"in the middle of the flags"
);
assert_eq!(
at(r#""{|}""#, FormatKind::Std),
vec![":", "}"],
"right after `{{` the field continues with a specification or ends — not with a type, and an argument \\
index is not something this layer can know"
);
assert!(
at(r#""hello |world""#, FormatKind::Printf).is_empty(),
"prose"
);
}
#[test]
fn a_completion_replaces_the_spelling_under_the_cursor() {
use cpp_code_analysis::format::completions_at;
let literal = r#""%d""#;
let at = literal.find('d').expect("the fixture writes it");
let items = completions_at(literal, FormatKind::Printf, at);
let x = items
.iter()
.find(|item| item.label == "x")
.expect("`x` is a conversion");
assert_eq!(
(&literal[x.start..x.end], x.end - x.start),
("d", 1),
"the edit covers the `d`, so the result is `%x` and not `%dx`"
);
let literal = r#""%""#;
let at = literal.find('"').expect("the closing quote");
let items = completions_at(literal, FormatKind::Printf, at);
assert!(
items.iter().all(|item| item.start == item.end),
"an insertion, not a replacement"
);
}