use super::{FormatKind, Piece, PieceKind, pieces_in};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Completion {
pub label: String,
pub detail: String,
pub start: usize,
pub end: usize,
}
pub fn completions_at(literal: &str, kind: FormatKind, at: usize) -> Vec<Completion> {
let Some((body_from, body_to)) = body_range(literal) else {
return Vec::new();
};
if at < body_from || at > body_to {
return Vec::new();
}
let mut pieces = Vec::new();
pieces_in(literal, kind, &mut pieces);
match kind {
FormatKind::Std => complete_a_std_field(literal, at, &pieces),
FormatKind::Printf | FormatKind::Scanf => complete_a_c_conversion(literal, kind, at),
}
}
fn body_range(literal: &str) -> Option<(usize, usize)> {
let bytes = literal.as_bytes();
let mut at = 0usize;
while at < bytes.len() && bytes[at] != b'"' {
at += 1;
}
if at >= bytes.len() {
return None;
}
at += 1;
let end = literal
.rfind('"')
.filter(|end| *end >= at)
.unwrap_or(literal.len());
Some((at, end))
}
fn complete_a_c_conversion(literal: &str, kind: FormatKind, at: usize) -> Vec<Completion> {
let bytes = literal.as_bytes();
let mut run = at;
while run > 0 && is_a_prefix_byte(bytes[run - 1], kind) {
run -= 1;
}
if run == 0 || bytes[run - 1] != b'%' {
return Vec::new();
}
let percent = run - 1;
let mut before_the_run = percent;
let mut percents = 0usize;
while before_the_run > 0 && bytes[before_the_run - 1] == b'%' {
percents += 1;
before_the_run -= 1;
}
if percents % 2 == 1 {
return Vec::new();
}
let before = &literal[percent..at];
if !is_prefix_of_a_conversion(before, kind) {
return Vec::new();
}
if bytes
.get(at)
.is_some_and(|byte| is_a_prefix_byte(*byte, kind))
{
return Vec::new();
}
let (start, end) = replacement_at(literal, at, kind);
conversions_of(kind)
.into_iter()
.map(|(label, detail)| Completion {
label: label.to_string(),
detail: detail.to_string(),
start,
end,
})
.collect()
}
fn is_a_prefix_byte(byte: u8, kind: FormatKind) -> bool {
if byte.is_ascii_digit() {
return true;
}
match kind {
FormatKind::Printf => {
matches!(byte, b'-' | b'+' | b' ' | b'#' | b'0' | b'.' | b'*' | b'$')
|| matches!(byte, b'h' | b'l' | b'j' | b'z' | b't' | b'L')
}
FormatKind::Scanf => {
matches!(byte, b'*') || matches!(byte, b'h' | b'l' | b'j' | b'z' | b't' | b'L')
}
FormatKind::Std => false,
}
}
fn is_prefix_of_a_conversion(text: &str, kind: FormatKind) -> bool {
let bytes = text.as_bytes();
if bytes.first() != Some(&b'%') {
return false;
}
let mut at = 1usize;
if kind == FormatKind::Printf {
let digits_from = at;
while bytes.get(at).is_some_and(|byte| byte.is_ascii_digit()) {
at += 1;
}
if at > digits_from && bytes.get(at) == Some(&b'$') {
at += 1;
} else {
at = digits_from;
}
while matches!(bytes.get(at), Some(b'-' | b'+' | b' ' | b'#' | b'0')) {
at += 1;
}
}
if bytes.get(at) == Some(&b'*') {
at += 1;
} else {
while bytes.get(at).is_some_and(|byte| byte.is_ascii_digit()) {
at += 1;
}
}
if kind == FormatKind::Printf && bytes.get(at) == Some(&b'.') {
at += 1;
if bytes.get(at) == Some(&b'*') {
at += 1;
} else {
while bytes.get(at).is_some_and(|byte| byte.is_ascii_digit()) {
at += 1;
}
}
}
match bytes.get(at) {
Some(b'h' | b'l') if bytes.get(at + 1) == bytes.get(at) => at += 2,
Some(b'h' | b'l' | b'j' | b'z' | b't' | b'L') => at += 1,
_ => {}
}
at == bytes.len()
}
fn complete_a_std_field(literal: &str, at: usize, pieces: &[Piece]) -> Vec<Completion> {
let Some((index, piece)) = piece_at(pieces, at) else {
return Vec::new();
};
if piece.kind == PieceKind::Escape {
return Vec::new();
}
let mut field_from = piece.start;
let mut first = index;
while first > 0 && pieces[first - 1].end == pieces[first].start {
first -= 1;
field_from = pieces[first].start;
if literal.as_bytes().get(field_from) == Some(&b'{') {
break;
}
}
if literal.as_bytes().get(field_from) != Some(&b'{') {
return Vec::new();
}
let before = &literal[field_from..at.min(piece.end)];
let Some(colon) = before.find(':') else {
let (start, end) = replacement_at(literal, at, FormatKind::Std);
return vec![
Completion {
label: ":".to_string(),
detail: "a specification follows: fill, align, width, precision and the type"
.to_string(),
start,
end,
},
Completion {
label: "}".to_string(),
detail: "an empty field — the argument formatted the way its type defaults to"
.to_string(),
start,
end,
},
];
};
let (start, end) = replacement_at(literal, at, FormatKind::Std);
let mut items: Vec<Completion> = Vec::new();
let at_the_start = before[colon + 1..]
.chars()
.all(|ch| matches!(ch, '<' | '>' | '^'));
if at_the_start {
for (label, detail) in [
("<", "align left"),
(">", "align right"),
("^", "centre"),
("+", "always signed"),
("#", "an alternative form (`0x`, `0b`, a leading `0`)"),
("0", "zero-padded"),
(".", "a precision follows"),
("{", "a width taken from an argument"),
("L", "the locale-specific form"),
] {
items.push(Completion {
label: label.to_string(),
detail: detail.to_string(),
start,
end,
});
}
}
for (label, detail) in conversions_of(FormatKind::Std) {
items.push(Completion {
label: label.to_string(),
detail: detail.to_string(),
start,
end,
});
}
items
}
fn piece_at(pieces: &[Piece], at: usize) -> Option<(usize, &Piece)> {
pieces
.iter()
.enumerate()
.find(|(_, piece)| piece.start <= at && at <= piece.end)
}
fn conversions_of(kind: FormatKind) -> Vec<(char, &'static str)> {
match kind {
FormatKind::Printf => vec![
('d', "signed decimal"),
('i', "signed decimal, the base read from the text"),
('u', "unsigned decimal"),
('o', "unsigned octal"),
('x', "unsigned hexadecimal, lowercase"),
('X', "unsigned hexadecimal, uppercase"),
('e', "scientific, lowercase"),
('E', "scientific, uppercase"),
('f', "fixed-point decimal"),
('F', "fixed-point decimal, `INF`/`NAN` in capitals"),
('g', "whichever of fixed-point and scientific is shorter"),
('G', "the same, `INF`/`NAN` in capitals"),
('a', "hexadecimal floating point"),
('A', "hexadecimal floating point, uppercase"),
('c', "one character"),
('s', "a string"),
('p', "a pointer, printed as an address"),
('n', "writes the number of characters written so far"),
('m', "`strerror(errno)` — takes no argument (glibc)"),
],
FormatKind::Scanf => vec![
('d', "signed decimal"),
('i', "signed decimal, the base read from the text"),
('u', "unsigned decimal"),
('o', "unsigned octal"),
('x', "unsigned hexadecimal"),
('X', "unsigned hexadecimal"),
('e', "a floating-point number"),
('f', "a floating-point number"),
('g', "a floating-point number"),
('a', "a floating-point number"),
('c', "one character, with no terminating `\\0`"),
('s', "a word, and a `char*` gets a terminating `\\0`"),
('p', "a pointer"),
('n', "stores the number of characters read so far"),
],
FormatKind::Std => vec![
('d', "decimal"),
('b', "binary"),
('B', "binary, uppercase"),
('o', "octal"),
('x', "hexadecimal, lowercase"),
('X', "hexadecimal, uppercase"),
('c', "one character"),
('s', "a string"),
('e', "scientific"),
('E', "scientific, uppercase"),
('f', "fixed-point decimal"),
('F', "fixed-point decimal, uppercase"),
('g', "whichever of fixed-point and scientific is shorter"),
('G', "the same, uppercase"),
('a', "hexadecimal floating point"),
('A', "hexadecimal floating point, uppercase"),
('p', "a pointer"),
('?', "the debug form — the type's own, for a reader"),
],
}
}
fn replacement_at(literal: &str, at: usize, kind: FormatKind) -> (usize, usize) {
let bytes = literal.as_bytes();
let could_be_a_conversion = |byte: u8| match kind {
FormatKind::Std => {
(byte.is_ascii_alphanumeric() && byte != b'L') || matches!(byte, b'?' | b'#' | b'0')
}
_ => byte.is_ascii_alphanumeric(),
};
match bytes.get(at) {
Some(byte) if could_be_a_conversion(*byte) => (at, at + 1),
_ => (at, at),
}
}