Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deny all rust keywords as macro names #23

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 33 additions & 37 deletions rinja_derive/src/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2285,29 +2285,12 @@ struct WritePartsBuffers {
expr: Option<Buffer>,
}

// Identifiers to be replaced with raw identifiers, so as to avoid
// collisions between template syntax and Rust's syntax. In particular
// [Rust keywords](https://doc.rust-lang.org/reference/keywords.html)
// should be replaced, since they're not reserved words in Rinja
// syntax but have a high probability of causing problems in the
// generated code.
//
// This list excludes the Rust keywords *self*, *Self*, and *super*
// because they are not allowed to be raw identifiers, and *loop*
// because it's used something like a keyword in the template
// language.
fn normalize_identifier(ident: &str) -> &str {
// This table works for as long as the replacement string is the original string
// prepended with "r#". The strings get right-padded to the same length with b'_'.
// While the code does not need it, please keep the list sorted when adding new
// keywords.

// FIXME: Replace with `[core:ascii::Char; MAX_REPL_LEN]` once
const MAX_KW_LEN: usize = 8;
const MAX_REPL_LEN: usize = MAX_KW_LEN + 2;
const KWS: &[&[[u8; MAX_REPL_LEN]]] = {
// FIXME: Replace `u8` with `[core:ascii::Char; MAX_REPL_LEN]` once
// <https://github.com/rust-lang/rust/issues/110998> is stable.

const MAX_KW_LEN: usize = 8;
const MAX_REPL_LEN: usize = MAX_KW_LEN + 2;

const KW0: &[[u8; MAX_REPL_LEN]] = &[];
const KW1: &[[u8; MAX_REPL_LEN]] = &[];
const KW2: &[[u8; MAX_REPL_LEN]] = &[
Expand Down Expand Up @@ -2365,24 +2348,37 @@ fn normalize_identifier(ident: &str) -> &str {
const KW7: &[[u8; MAX_REPL_LEN]] = &[*b"r#unsized_", *b"r#virtual_"];
const KW8: &[[u8; MAX_REPL_LEN]] = &[*b"r#abstract", *b"r#continue", *b"r#override"];

const KWS: &[&[[u8; MAX_REPL_LEN]]] = &[KW0, KW1, KW2, KW3, KW4, KW5, KW6, KW7, KW8];

// Ensure that all strings are ASCII, because we use `from_utf8_unchecked()` further down.
const _: () = {
let mut i = 0;
while i < KWS.len() {
let mut j = 0;
while KWS[i].len() < j {
let mut k = 0;
while KWS[i][j].len() < k {
assert!(KWS[i][j][k].is_ascii());
k += 1;
}
j += 1;
&[KW0, KW1, KW2, KW3, KW4, KW5, KW6, KW7, KW8]
};

/// Ensure that all strings are UTF-8, because we use `from_utf8_unchecked()` further down.
#[test]
fn ensure_utf8() {
for kws in KWS {
for kw in *kws {
if std::str::from_utf8(kw).is_err() {
panic!("not UTF-8: {:?}", kw);
}
i += 1;
}
};
}
}

/// Identifiers to be replaced with raw identifiers, so as to avoid
/// collisions between template syntax and Rust's syntax. In particular
/// [Rust keywords](https://doc.rust-lang.org/reference/keywords.html)
/// should be replaced, since they're not reserved words in Rinja
/// syntax but have a high probability of causing problems in the
/// generated code.
///
/// This list excludes the Rust keywords *self*, *Self*, and *super*
/// because they are not allowed to be raw identifiers, and *loop*
/// because it's used something like a keyword in the template
/// language.
fn normalize_identifier(ident: &str) -> &str {
// This table works for as long as the replacement string is the original string
// prepended with "r#". The strings get right-padded to the same length with b'_'.
// While the code does not need it, please keep the list sorted when adding new
// keywords.

if ident.len() > MAX_KW_LEN {
return ident;
Expand Down
99 changes: 97 additions & 2 deletions rinja_parser/src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -592,9 +592,9 @@ impl<'a> Macro<'a> {
))),
));
let (j, (pws1, _, (name, params, nws1, _))) = start(i)?;
if name == "super" {
if is_rust_keyword(name) {
return Err(nom::Err::Failure(ErrorContext::new(
"'super' is not a valid name for a macro",
format!("'{name}' is not a valid name for a macro"),
i,
)));
}
Expand Down Expand Up @@ -1202,3 +1202,98 @@ impl<'a> Comment<'a> {
/// Second field is "minus/plus sign was used on the right part of the item".
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Ws(pub Option<Whitespace>, pub Option<Whitespace>);

const MAX_KW_LEN: usize = 8;
const KWS: &[&[[u8; MAX_KW_LEN]]] = {
// FIXME: Replace `u8` with `[core:ascii::Char; MAX_REPL_LEN]` once
// <https://github.com/rust-lang/rust/issues/110998> is stable.

const KW0: &[[u8; MAX_KW_LEN]] = &[];
const KW1: &[[u8; MAX_KW_LEN]] = &[];
const KW2: &[[u8; MAX_KW_LEN]] = &[
*b"as______",
*b"do______",
*b"fn______",
*b"if______",
*b"in______",
];
const KW3: &[[u8; MAX_KW_LEN]] = &[
*b"box_____",
*b"dyn_____",
*b"for_____",
*b"let_____",
*b"mod_____",
*b"mut_____",
*b"pub_____",
*b"ref_____",
*b"try_____",
*b"use_____",
];
const KW4: &[[u8; MAX_KW_LEN]] = &[
*b"else____",
*b"enum____",
*b"impl____",
*b"loop____",
*b"move____",
*b"priv____",
*b"self____",
*b"Self____",
*b"true____",
*b"type____",
];
const KW5: &[[u8; MAX_KW_LEN]] = &[
*b"async___",
*b"await___",
*b"break___",
*b"const___",
*b"crate___",
*b"false___",
*b"final___",
*b"macro___",
*b"match___",
*b"super___",
*b"trait___",
*b"union___",
*b"where___",
*b"while___",
*b"yield___",
];
const KW6: &[[u8; MAX_KW_LEN]] = &[
*b"become__",
*b"extern__",
*b"return__",
*b"static__",
*b"struct__",
*b"typeof__",
*b"unsafe__",
];
const KW7: &[[u8; MAX_KW_LEN]] = &[*b"unsized_", *b"virtual_"];
const KW8: &[[u8; MAX_KW_LEN]] = &[*b"abstract", *b"continue", *b"override"];

&[KW0, KW1, KW2, KW3, KW4, KW5, KW6, KW7, KW8]
};

/// Ensure that all strings are UTF-8, because we use `from_utf8_unchecked()` further down.
#[test]
fn ensure_utf8() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a need to duplicate these consts between the two crates? Can't we make them public behind #[doc(hidden)] instead?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a need to duplicate these consts between the two crates?

Sadly, I think yes. The list items are not the same with loop self Self missing from the generator list.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Then why not add another list for these 3 keywords in rinja_parser? Having some much code duplicated is itching me strongly. ^^'

If you want I don't mind doing it. In this case just merge this PR and I'll take a look.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this case just merge this PR and I'll take a look.

Thanks! Sure, go ahead. :)

for kws in KWS {
for kw in *kws {
if std::str::from_utf8(kw).is_err() {
panic!("not UTF-8: {:?}", kw);
}
}
}
}

fn is_rust_keyword(ident: &str) -> bool {
if ident.len() > MAX_KW_LEN {
return false;
}
let kws = KWS[ident.len()];

let mut padded_ident = [b'_'; MAX_KW_LEN];
padded_ident[..ident.len()].copy_from_slice(ident.as_bytes());

// Since the individual buckets are quite short, a linear search is faster than a binary search.
kws.iter().any(|&probe| padded_ident == probe)
}