Skip to content

Commit

Permalink
Allow underscores at the start of a variable
Browse files Browse the repository at this point in the history
  • Loading branch information
Josh Dutton authored and udoprog committed Aug 8, 2023
1 parent 2f0e7af commit ffb6cfe
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 6 deletions.
1 change: 1 addition & 0 deletions crates/rune/src/ast/ident.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ fn ast_parse() {

rt::<ast::Ident>("foo");
rt::<ast::Ident>("a42");
rt::<ast::Ident>("_ignored");
}

/// An identifier, like `foo` or `Hello`.
Expand Down
18 changes: 12 additions & 6 deletions crates/rune/src/parse/lexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,10 +143,17 @@ impl<'a> Lexer<'a> {
self.iter.next();
}

let (ident, span) = self.iter.source_from(start);
let kind = ast::Kind::from_keyword(ident)
.unwrap_or(ast::Kind::Ident(ast::LitSource::Text(self.source_id)));
Ok(Some(ast::Token { kind, span }))
match self.iter.source_from(start) {
("_", span) => Ok(Some(ast::Token {
span,
kind: ast::Kind::Underscore,
})),
(ident, span) => {
let kind = ast::Kind::from_keyword(ident)
.unwrap_or(ast::Kind::Ident(ast::LitSource::Text(self.source_id)));
Ok(Some(ast::Token { kind, span }))
}
}
}

/// Consume a number literal.
Expand Down Expand Up @@ -781,7 +788,6 @@ impl<'a> Lexer<'a> {
}
'[' => ast::Kind::Open(ast::Delimiter::Bracket),
']' => ast::Kind::Close(ast::Delimiter::Bracket),
'_' => ast::Kind::Underscore,
',' => ast::Kind::Comma,
':' => ast::Kind::Colon,
'#' => ast::Kind::Pound,
Expand All @@ -803,7 +809,7 @@ impl<'a> Lexer<'a> {
'@' => ast::Kind::At,
'$' => ast::Kind::Dollar,
'~' => ast::Kind::Tilde,
'a'..='z' | 'A'..='Z' => {
'_' | 'a'..='z' | 'A'..='Z' => {
return self.next_ident(start);
}
'0'..='9' => {
Expand Down
18 changes: 18 additions & 0 deletions crates/rune/src/tests/vm_assign_exprs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,24 @@ fn test_basic_assign() {
assert_eq!(out, 42);
}

#[test]
fn test_assign_underscore() {
let out: i64 = rune! {
pub fn main() { let _a = 0; _a = 42; _a }
};

assert_eq!(out, 42);
}

#[test]
fn test_assign_underscores() {
let out: i64 = rune! {
pub fn main() { let ___ = 0; ___ = 42; ___ }
};

assert_eq!(out, 42);
}

#[test]
fn test_assign_anon_object() {
let out: i64 = rune! {
Expand Down

0 comments on commit ffb6cfe

Please sign in to comment.