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

feat: Add multi-line comments #1936

Merged
merged 1 commit into from Jul 17, 2023
Merged
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
71 changes: 71 additions & 0 deletions crates/noirc_frontend/src/lexer/lexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,9 @@ impl<'a> Lexer<'a> {
if self.peek_char_is('/') {
self.next_char();
return self.parse_comment();
} else if self.peek_char_is('*') {
self.next_char();
return self.parse_block_comment();
}
Ok(spanned_prev_token)
}
Expand Down Expand Up @@ -335,6 +338,31 @@ impl<'a> Lexer<'a> {
self.next_token()
}

fn parse_block_comment(&mut self) -> SpannedTokenResult {
let mut depth = 1usize;

while let Some(ch) = self.next_char() {
match ch {
'/' if self.peek_char_is('*') => {
self.next_char();
depth += 1;
}
'*' if self.peek_char_is('/') => {
self.next_char();
depth -= 1;
jfecher marked this conversation as resolved.
Show resolved Hide resolved

// This block comment is closed, so for a construction like "/* */ */"
jfecher marked this conversation as resolved.
Show resolved Hide resolved
if depth == 0 {
break;
}
}
_ => {}
}
}

self.next_token()
}

/// Skips white space. They are not significant in the source language
fn eat_whitespace(&mut self) {
self.eat_while(None, |ch| ch.is_whitespace());
Expand Down Expand Up @@ -480,6 +508,49 @@ fn test_comment() {
}
}

#[test]
fn test_block_comment() {
let input = "
/* comment */
let x = 5
/* comment */
";

let expected = vec![
Token::Keyword(Keyword::Let),
Token::Ident("x".to_string()),
Token::Assign,
Token::Int(FieldElement::from(5_i128)),
];

let mut lexer = Lexer::new(input);
for token in expected.into_iter() {
let first_lexer_output = lexer.next_token().unwrap();
assert_eq!(first_lexer_output, token);
}
}

#[test]
fn test_nested_block_comments() {
let input = "
/* /* */ /** */ /*! */ */
let x = 5
/* /* */ /** */ /*! */ */
";

let expected = vec![
Token::Keyword(Keyword::Let),
Token::Ident("x".to_string()),
Token::Assign,
Token::Int(FieldElement::from(5_i128)),
];

let mut lexer = Lexer::new(input);
for token in expected.into_iter() {
let first_lexer_output = lexer.next_token().unwrap();
assert_eq!(first_lexer_output, token);
}
}
#[test]
fn test_eat_string_literal() {
let input = "let _word = \"hello\"";
Expand Down