mod display;
pub use Alignment::*;
pub use Count::*;
pub use Flag::*;
pub use Piece::*;
pub use Position::*;
use std::iter;
use std::str;
use std::string;
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct InnerSpan {
pub start: usize,
pub end: usize,
}
impl InnerSpan {
pub fn new(start: usize, end: usize) -> InnerSpan {
InnerSpan { start, end }
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ParseMode {
Format,
InlineAsm,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
struct InnerOffset(pub usize);
impl InnerOffset {
fn to(self, end: InnerOffset) -> InnerSpan {
InnerSpan::new(self.0, end.0)
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Piece<'a> {
String(&'a str),
NextArgument(Argument<'a>),
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Argument<'a> {
pub position: Position<'a>,
pub position_span: InnerSpan,
pub format: FormatSpec<'a>,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct FormatSpec<'a> {
pub fill: Option<char>,
pub align: Alignment,
pub flags: u32,
pub precision: Count<'a>,
pub precision_span: Option<InnerSpan>,
pub width: Count<'a>,
pub width_span: Option<InnerSpan>,
pub ty: &'a str,
pub ty_span: Option<InnerSpan>,
}
impl<'a> FormatSpec<'a> {
pub fn new(ty: &'a str) -> Self {
Self {
fill: None,
align: AlignUnknown,
flags: 0,
precision: CountImplied,
precision_span: None,
width: CountImplied,
width_span: None,
ty,
ty_span: None,
}
}
pub fn is_empty(&self) -> bool {
self.fill.is_none()
&& self.align == AlignUnknown
&& self.flags == 0
&& self.precision == CountImplied
&& self.width == CountImplied
&& self.ty.is_empty()
}
}
impl<'a> Default for FormatSpec<'a> {
#[inline]
fn default() -> Self {
Self::new("")
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Position<'a> {
ArgumentImplicitlyIs(usize),
ArgumentIs(usize),
ArgumentNamed(&'a str),
}
impl Position<'_> {
pub fn index(&self) -> Option<usize> {
match self {
ArgumentIs(i, ..) | ArgumentImplicitlyIs(i) => Some(*i),
_ => None,
}
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Alignment {
AlignLeft,
AlignRight,
AlignCenter,
AlignUnknown,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Flag {
FlagSignPlus,
FlagSignMinus,
FlagAlternate,
FlagSignAwareZeroPad,
FlagDebugLowerHex,
FlagDebugUpperHex,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Count<'a> {
CountIs(usize),
CountIsName(&'a str, InnerSpan),
CountIsParam(usize),
CountIsStar(usize),
CountImplied,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParseError {
pub description: string::String,
pub note: Option<string::String>,
pub label: string::String,
pub span: InnerSpan,
pub secondary_label: Option<(string::String, InnerSpan)>,
pub should_be_replaced_with_positional_argument: bool,
}
#[derive(Clone, Debug)]
pub struct Parser<'a> {
mode: ParseMode,
input: &'a str,
cur: iter::Peekable<str::CharIndices<'a>>,
pub errors: Vec<ParseError>,
pub curarg: usize,
style: Option<usize>,
pub arg_places: Vec<InnerSpan>,
skips: Vec<usize>,
last_opening_brace: Option<InnerSpan>,
append_newline: bool,
pub is_literal: bool,
cur_line_start: usize,
pub line_spans: Vec<InnerSpan>,
}
impl<'a> Iterator for Parser<'a> {
type Item = Piece<'a>;
fn next(&mut self) -> Option<Piece<'a>> {
if let Some(&(pos, c)) = self.cur.peek() {
match c {
'{' => {
let curr_last_brace = self.last_opening_brace;
let byte_pos = self.to_span_index(pos);
let lbrace_end = self.to_span_index(pos + 1);
self.last_opening_brace = Some(byte_pos.to(lbrace_end));
self.cur.next();
if self.consume('{') {
self.last_opening_brace = curr_last_brace;
Some(String(self.string(pos + 1)))
} else {
let arg = self.argument(lbrace_end);
if let Some(rbrace_byte_idx) = self.must_consume('}') {
let lbrace_inner_offset = self.to_span_index(pos);
let rbrace_inner_offset = self.to_span_index(rbrace_byte_idx);
if self.is_literal {
self.arg_places.push(
lbrace_inner_offset.to(InnerOffset(rbrace_inner_offset.0 + 1)),
);
}
} else {
self.suggest_positional_arg_instead_of_captured_arg(arg);
}
Some(NextArgument(arg))
}
}
'}' => {
self.cur.next();
if self.consume('}') {
Some(String(self.string(pos + 1)))
} else {
let err_pos = self.to_span_index(pos);
self.err_with_note(
"unmatched `}` found",
"unmatched `}`",
"if you intended to print `}`, you can escape it using `}}`",
err_pos.to(err_pos),
);
None
}
}
_ => Some(String(self.string(pos))),
}
} else {
if self.is_literal {
let span = self.span(self.cur_line_start, self.input.len());
if self.line_spans.last() != Some(&span) {
self.line_spans.push(span);
}
}
None
}
}
}
impl<'a> Parser<'a> {
pub fn new(
s: &'a str,
style: Option<usize>,
snippet: Option<string::String>,
append_newline: bool,
mode: ParseMode,
) -> Parser<'a> {
let (skips, is_literal) = find_skips_from_snippet(snippet, style);
Parser {
mode,
input: s,
cur: s.char_indices().peekable(),
errors: vec![],
curarg: 0,
style,
arg_places: vec![],
skips,
last_opening_brace: None,
append_newline,
is_literal,
cur_line_start: 0,
line_spans: vec![],
}
}
fn err<S1: Into<string::String>, S2: Into<string::String>>(
&mut self,
description: S1,
label: S2,
span: InnerSpan,
) {
self.errors.push(ParseError {
description: description.into(),
note: None,
label: label.into(),
span,
secondary_label: None,
should_be_replaced_with_positional_argument: false,
});
}
fn err_with_note<
S1: Into<string::String>,
S2: Into<string::String>,
S3: Into<string::String>,
>(
&mut self,
description: S1,
label: S2,
note: S3,
span: InnerSpan,
) {
self.errors.push(ParseError {
description: description.into(),
note: Some(note.into()),
label: label.into(),
span,
secondary_label: None,
should_be_replaced_with_positional_argument: false,
});
}
fn consume(&mut self, c: char) -> bool {
self.consume_pos(c).is_some()
}
fn consume_pos(&mut self, c: char) -> Option<usize> {
if let Some(&(pos, maybe)) = self.cur.peek() {
if c == maybe {
self.cur.next();
return Some(pos);
}
}
None
}
fn to_span_index(&self, pos: usize) -> InnerOffset {
let mut pos = pos;
let raw = self.style.map_or(0, |raw| raw + 1);
for skip in &self.skips {
if pos > *skip {
pos += 1;
} else if pos == *skip && raw == 0 {
pos += 1;
} else {
break;
}
}
InnerOffset(raw + pos + 1)
}
fn span(&self, start_pos: usize, end_pos: usize) -> InnerSpan {
let start = self.to_span_index(start_pos);
let end = self.to_span_index(end_pos);
start.to(end)
}
fn must_consume(&mut self, c: char) -> Option<usize> {
self.ws();
if let Some(&(pos, maybe)) = self.cur.peek() {
if c == maybe {
self.cur.next();
Some(pos)
} else {
let pos = self.to_span_index(pos);
let description = format!("expected `'}}'`, found `{:?}`", maybe);
let label = "expected `}`".to_owned();
let (note, secondary_label) = if c == '}' {
(
Some(
"if you intended to print `{`, you can escape it using `{{`".to_owned(),
),
self.last_opening_brace
.map(|sp| ("because of this opening brace".to_owned(), sp)),
)
} else {
(None, None)
};
self.errors.push(ParseError {
description,
note,
label,
span: pos.to(pos),
secondary_label,
should_be_replaced_with_positional_argument: false,
});
None
}
} else {
let description = format!("expected `{:?}` but string was terminated", c);
let pos = self.input.len() - if self.append_newline { 1 } else { 0 };
let pos = self.to_span_index(pos);
if c == '}' {
let label = format!("expected `{:?}`", c);
let (note, secondary_label) = if c == '}' {
(
Some(
"if you intended to print `{`, you can escape it using `{{`".to_owned(),
),
self.last_opening_brace
.map(|sp| ("because of this opening brace".to_owned(), sp)),
)
} else {
(None, None)
};
self.errors.push(ParseError {
description,
note,
label,
span: pos.to(pos),
secondary_label,
should_be_replaced_with_positional_argument: false,
});
} else {
self.err(description, format!("expected `{:?}`", c), pos.to(pos));
}
None
}
}
fn ws(&mut self) {
while let Some(&(_, c)) = self.cur.peek() {
if c.is_whitespace() {
self.cur.next();
} else {
break;
}
}
}
fn string(&mut self, start: usize) -> &'a str {
while let Some(&(pos, c)) = self.cur.peek() {
match c {
'{' | '}' => {
return &self.input[start..pos];
}
'\n' if self.is_literal => {
self.line_spans.push(self.span(self.cur_line_start, pos));
self.cur_line_start = pos + 1;
self.cur.next();
}
_ => {
if self.is_literal && pos == self.cur_line_start && c.is_whitespace() {
self.cur_line_start = pos + c.len_utf8();
}
self.cur.next();
}
}
}
&self.input[start..self.input.len()]
}
fn argument(&mut self, start: InnerOffset) -> Argument<'a> {
let pos = self.position();
let end = self
.cur
.clone()
.find(|(_, ch)| !ch.is_whitespace())
.map_or(start, |(end, _)| self.to_span_index(end));
let position_span = start.to(end);
let format = match self.mode {
ParseMode::Format => self.format(),
ParseMode::InlineAsm => self.inline_asm(),
};
let pos = match pos {
Some(position) => position,
None => {
let i = self.curarg;
self.curarg += 1;
ArgumentImplicitlyIs(i)
}
};
Argument {
position: pos,
position_span,
format,
}
}
fn position(&mut self) -> Option<Position<'a>> {
if let Some(i) = self.integer() {
Some(ArgumentIs(i))
} else {
match self.cur.peek() {
Some(&(_, c)) if is_id_start(c) => Some(ArgumentNamed(self.word())),
_ => None,
}
}
}
fn current_pos(&mut self) -> usize {
if let Some(&(pos, _)) = self.cur.peek() {
pos
} else {
self.input.len()
}
}
fn format(&mut self) -> FormatSpec<'a> {
let mut spec = FormatSpec::new(&self.input[..0]);
if !self.consume(':') {
return spec;
}
if let Some(&(_, c)) = self.cur.peek() {
if let Some((_, '>' | '<' | '^')) = self.cur.clone().nth(1) {
spec.fill = Some(c);
self.cur.next();
}
}
if self.consume('<') {
spec.align = AlignLeft;
} else if self.consume('>') {
spec.align = AlignRight;
} else if self.consume('^') {
spec.align = AlignCenter;
}
if self.consume('+') {
spec.flags |= 1 << (FlagSignPlus as u32);
} else if self.consume('-') {
spec.flags |= 1 << (FlagSignMinus as u32);
}
if self.consume('#') {
spec.flags |= 1 << (FlagAlternate as u32);
}
let mut havewidth = false;
if self.consume('0') {
if let Some(end) = self.consume_pos('$') {
spec.width = CountIsParam(0);
spec.width_span = Some(self.span(end - 1, end + 1));
havewidth = true;
} else {
spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
}
}
if !havewidth {
let start = self.current_pos();
spec.width = self.count(start);
if spec.width != CountImplied {
let end = self.current_pos();
spec.width_span = Some(self.span(start, end));
}
}
if let Some(start) = self.consume_pos('.') {
if self.consume('*') {
let i = self.curarg;
self.curarg += 1;
spec.precision = CountIsStar(i);
} else {
spec.precision = self.count(start + 1);
}
let end = self.current_pos();
spec.precision_span = Some(self.span(start, end));
}
let ty_span_start = self.current_pos();
if self.consume('x') {
if self.consume('?') {
spec.flags |= 1 << (FlagDebugLowerHex as u32);
spec.ty = "?";
} else {
spec.ty = "x";
}
} else if self.consume('X') {
if self.consume('?') {
spec.flags |= 1 << (FlagDebugUpperHex as u32);
spec.ty = "?";
} else {
spec.ty = "X";
}
} else if self.consume('?') {
spec.ty = "?";
} else {
spec.ty = self.word();
if !spec.ty.is_empty() {
let ty_span_end = self.current_pos();
spec.ty_span = Some(self.span(ty_span_start, ty_span_end));
}
}
spec
}
fn inline_asm(&mut self) -> FormatSpec<'a> {
let mut spec = FormatSpec::new(&self.input[..0]);
if !self.consume(':') {
return spec;
}
let ty_span_start = self.current_pos();
spec.ty = self.word();
if !spec.ty.is_empty() {
let ty_span_end = self.current_pos();
spec.ty_span = Some(self.span(ty_span_start, ty_span_end));
}
spec
}
fn count(&mut self, start: usize) -> Count<'a> {
if let Some(i) = self.integer() {
if self.consume('$') {
CountIsParam(i)
} else {
CountIs(i)
}
} else {
let tmp = self.cur.clone();
let word = self.word();
if word.is_empty() {
self.cur = tmp;
CountImplied
} else if let Some(end) = self.consume_pos('$') {
let name_span = self.span(start, end);
CountIsName(word, name_span)
} else {
self.cur = tmp;
CountImplied
}
}
}
fn word(&mut self) -> &'a str {
let start = match self.cur.peek() {
Some(&(pos, c)) if is_id_start(c) => {
self.cur.next();
pos
}
_ => {
return "";
}
};
let mut end = None;
while let Some(&(pos, c)) = self.cur.peek() {
if is_id_continue(c) {
self.cur.next();
} else {
end = Some(pos);
break;
}
}
let end = end.unwrap_or(self.input.len());
let word = &self.input[start..end];
if word == "_" {
self.err_with_note(
"invalid argument name `_`",
"invalid argument name",
"argument name cannot be a single underscore",
self.span(start, end),
);
}
word
}
fn integer(&mut self) -> Option<usize> {
let mut cur: usize = 0;
let mut found = false;
let mut overflow = false;
let start = self.current_pos();
while let Some(&(_, c)) = self.cur.peek() {
if let Some(i) = c.to_digit(10) {
let (tmp, mul_overflow) = cur.overflowing_mul(10);
let (tmp, add_overflow) = tmp.overflowing_add(i as usize);
if mul_overflow || add_overflow {
overflow = true;
}
cur = tmp;
found = true;
self.cur.next();
} else {
break;
}
}
if overflow {
let end = self.current_pos();
let overflowed_int = &self.input[start..end];
self.err(
format!(
"integer `{}` does not fit into the type `usize` whose range is `0..={}`",
overflowed_int,
usize::MAX
),
"integer out of range for `usize`",
self.span(start, end),
);
}
if found {
Some(cur)
} else {
None
}
}
fn suggest_positional_arg_instead_of_captured_arg(&mut self, arg: Argument<'a>) {
if let Some(end) = self.consume_pos('.') {
let byte_pos = self.to_span_index(end);
let start = InnerOffset(byte_pos.0 + 1);
let field = self.argument(start);
if !self.consume('}') {
return;
}
if let ArgumentNamed(_) = arg.position {
if let ArgumentNamed(_) = field.position {
self.errors.insert(
0,
ParseError {
description: "field access isn't supported".to_string(),
note: None,
label: "not supported".to_string(),
span: InnerSpan::new(arg.position_span.start, field.position_span.end),
secondary_label: None,
should_be_replaced_with_positional_argument: true,
},
);
}
}
}
}
}
fn find_skips_from_snippet(
snippet: Option<string::String>,
str_style: Option<usize>,
) -> (Vec<usize>, bool) {
let snippet = match snippet {
Some(ref s) if s.starts_with('"') || s.starts_with("r\"") || s.starts_with("r#") => s,
_ => return (vec![], false),
};
if str_style.is_some() {
return (vec![], true);
}
let snippet = &snippet[1..snippet.len() - 1];
let mut s = snippet.char_indices();
let mut skips = vec![];
while let Some((pos, c)) = s.next() {
match (c, s.clone().next()) {
('\\', Some((next_pos, '\n'))) => {
skips.push(pos);
skips.push(next_pos);
let _ = s.next();
while let Some((pos, c)) = s.clone().next() {
if matches!(c, ' ' | '\n' | '\t') {
skips.push(pos);
let _ = s.next();
} else {
break;
}
}
}
('\\', Some((next_pos, 'n' | 't' | 'r' | '0' | '\\' | '\'' | '\"'))) => {
skips.push(next_pos);
let _ = s.next();
}
('\\', Some((_, 'x'))) => {
for _ in 0..3 {
if let Some((pos, _)) = s.next() {
skips.push(pos);
} else {
break;
}
}
}
('\\', Some((_, 'u'))) => {
if let Some((pos, _)) = s.next() {
skips.push(pos);
}
if let Some((next_pos, next_c)) = s.next() {
if next_c == '{' {
let digits_len = s
.clone()
.take(6)
.take_while(|(_, c)| c.is_digit(16))
.count();
let len_utf8 = s
.as_str()
.get(..digits_len)
.and_then(|digits| u32::from_str_radix(digits, 16).ok())
.and_then(char::from_u32)
.map_or(1, char::len_utf8);
let required_skips = digits_len.saturating_sub(len_utf8.saturating_sub(1));
for pos in (next_pos..).take(required_skips + 2) {
skips.push(pos)
}
s.nth(digits_len);
} else if next_c.is_digit(16) {
skips.push(next_pos);
let mut i = 0; while let (Some((next_pos, c)), _) = (s.next(), i < 6) {
if c.is_digit(16) {
skips.push(next_pos);
} else {
break;
}
i += 1;
}
}
}
}
_ => {}
}
}
(skips, true)
}
#[inline]
fn is_id_start(ch: char) -> bool {
ch == '_' || unicode_ident::is_xid_start(ch)
}
#[inline]
fn is_id_continue(ch: char) -> bool {
unicode_ident::is_xid_start(ch)
}
#[cfg(test)]
mod tests;