Skip to content

Commit

Permalink
Disallow int literals in attribute values (#415)
Browse files Browse the repository at this point in the history
  • Loading branch information
lambda-fairy committed Jan 14, 2024
1 parent 320add8 commit 26a9d74
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 10 deletions.
12 changes: 12 additions & 0 deletions maud/tests/warnings/non-string-literal.stderr
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
error: literal must be double-quoted: `"42"`
--> tests/warnings/non-string-literal.rs:5:9
|
5 | 42
| ^^

error: literal must be double-quoted: `"42usize"`
--> tests/warnings/non-string-literal.rs:6:9
|
6 | 42usize
| ^^^^^^^

error: literal must be double-quoted: `"42.0"`
--> tests/warnings/non-string-literal.rs:7:9
|
Expand Down
5 changes: 0 additions & 5 deletions maud_macros/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,11 +223,6 @@ pub fn name_to_string(name: TokenStream) -> String {
if let TokenTree::Literal(literal) = token {
match Lit::new(literal.clone()) {
Lit::Str(str) => str.value(),
Lit::Char(char) => char.value().to_string(),
Lit::ByteStr(byte) => {
String::from_utf8(byte.value()).expect("Invalid utf8 byte")
}
Lit::Byte(byte) => (byte.value() as char).to_string(),
_ => literal.to_string(),
}
} else {
Expand Down
13 changes: 8 additions & 5 deletions maud_macros/src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ impl Parser {
// Literal
TokenTree::Literal(literal) => {
self.advance();
self.literal(literal)
self.literal(literal, false)
}
// Special form
TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
Expand Down Expand Up @@ -194,7 +194,10 @@ impl Parser {
}

/// Parses a literal string.
fn literal(&mut self, literal: Literal) -> ast::Markup {
///
/// If `allow_int_literal` is `true`, then integer literals (like `123`) will be accepted and
/// returned.
fn literal(&mut self, literal: Literal, allow_int_literal: bool) -> ast::Markup {
match Lit::new(literal.clone()) {
Lit::Str(lit_str) => {
return ast::Markup::Literal {
Expand All @@ -204,13 +207,13 @@ impl Parser {
}
// Boolean literals are idents, so `Lit::Bool` is handled in
// `markup`, not here.
Lit::Int(lit_int) => {
Lit::Int(lit_int) if allow_int_literal => {
return ast::Markup::Literal {
content: lit_int.to_string(),
span: SpanRange::single_span(literal.span()),
};
}
Lit::Float(..) => {
Lit::Int(..) | Lit::Float(..) => {
emit_error!(literal, r#"literal must be double-quoted: `"{}"`"#, literal);
}
Lit::Char(lit_char) => {
Expand Down Expand Up @@ -722,7 +725,7 @@ impl Parser {
false
}
Some(TokenTree::Literal(ref literal)) if expect_ident_or_literal => {
self.literal(literal.clone());
self.literal(literal.clone(), true);
self.advance();
result.push(TokenTree::Literal(literal.clone()));
false
Expand Down

0 comments on commit 26a9d74

Please sign in to comment.