Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
67 changes: 43 additions & 24 deletions compiler/noirc_frontend/src/lexer/lexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ pub struct Lexer<'a> {
char_iter: Peekable<Zip<Chars<'a>, RangeFrom<u32>>>,
position: Position,
done: bool,
skip_trivia: bool,
}

pub type SpannedTokenResult = Result<SpannedToken, LexerErrorKind>;
Expand All @@ -39,15 +40,20 @@ impl<'a> Lexer<'a> {
(Tokens(tokens), errors)
}

fn new(source: &'a str) -> Self {
pub fn new(source: &'a str) -> Self {
Lexer {
// We zip with the character index here to ensure the first char has index 0
char_iter: source.chars().zip(0..).peekable(),
position: 0,
done: false,
skip_trivia: true,
}
}

pub fn set_skip_trivia(&mut self, flag: bool) {
self.skip_trivia = flag;
}

/// Iterates the cursor and returns the char at the new cursor position
fn next_char(&mut self) -> Option<char> {
let (c, index) = self.char_iter.next()?;
Expand Down Expand Up @@ -176,13 +182,16 @@ impl<'a> Lexer<'a> {
Token::Minus => self.single_double_peek_token('>', prev_token, Token::Arrow),
Token::Colon => self.single_double_peek_token(':', prev_token, Token::DoubleColon),
Token::Slash => {
let start = self.position;

if self.peek_char_is('/') {
self.next_char();
return self.parse_comment();
return self.parse_comment(start);
} else if self.peek_char_is('*') {
self.next_char();
return self.parse_block_comment();
return self.parse_block_comment(start);
}

Ok(spanned_prev_token)
}
_ => Err(LexerErrorKind::NotADoubleChar {
Expand Down Expand Up @@ -377,15 +386,15 @@ impl<'a> Lexer<'a> {
}
}

fn parse_comment(&mut self) -> SpannedTokenResult {
let _ = self.eat_while(None, |ch| ch != '\n');
self.next_token()
fn parse_comment(&mut self, start: u32) -> SpannedTokenResult {
let comment = self.eat_while(None, |ch| ch != '\n');
Ok(Token::LineComment(comment).into_span(start, self.position))
}

fn parse_block_comment(&mut self) -> SpannedTokenResult {
let start = self.position;
fn parse_block_comment(&mut self, start: u32) -> SpannedTokenResult {
let mut depth = 1usize;

let mut content = String::new();
while let Some(ch) = self.next_char() {
match ch {
'/' if self.peek_char_is('*') => {
Expand All @@ -403,12 +412,12 @@ impl<'a> Lexer<'a> {
break;
}
}
_ => {}
ch => content.push(ch),
}
}

if depth == 0 {
self.next_token()
Ok(Token::BlockComment(content).into_span(start, self.position))
} else {
let span = Span::inclusive(start, self.position);
Err(LexerErrorKind::UnterminatedBlockComment { span })
Expand All @@ -424,10 +433,20 @@ impl<'a> Lexer<'a> {
impl<'a> Iterator for Lexer<'a> {
type Item = SpannedTokenResult;
fn next(&mut self) -> Option<Self::Item> {
if self.done {
None
} else {
Some(self.next_token())
loop {
if self.done {
return None;
} else {
let token = self.next_token();

if self.skip_trivia
&& token.as_ref().map_or(false, |spanned| spanned.token().is_trivia())
{
continue;
}

return Some(token);
}
}
}
}
Expand Down Expand Up @@ -532,7 +551,7 @@ mod tests {

let mut lexer = Lexer::new(input);
for token in expected.into_iter() {
let got = lexer.next_token().unwrap();
let got = lexer.next().unwrap().unwrap();
assert_eq!(got, token);
}
}
Expand Down Expand Up @@ -638,7 +657,7 @@ mod tests {

let mut lexer = Lexer::new(input);
for token in expected.into_iter() {
let got = lexer.next_token().unwrap();
let got = lexer.next().unwrap().unwrap();
assert_eq!(got, token);
}
}
Expand All @@ -662,7 +681,7 @@ mod tests {

let mut lexer = Lexer::new(input);
for token in expected.into_iter() {
let got = lexer.next_token().unwrap();
let got = lexer.next().unwrap().unwrap();
assert_eq!(got, token);
}
}
Expand Down Expand Up @@ -692,7 +711,7 @@ mod tests {

let mut lexer = Lexer::new(input);
for token in expected.into_iter() {
let first_lexer_output = lexer.next_token().unwrap();
let first_lexer_output = lexer.next().unwrap().unwrap();
assert_eq!(first_lexer_output, token);
}
}
Expand All @@ -714,7 +733,7 @@ mod tests {

let mut lexer = Lexer::new(input);
for token in expected.into_iter() {
let first_lexer_output = lexer.next_token().unwrap();
let first_lexer_output = lexer.next().unwrap().unwrap();
assert_eq!(first_lexer_output, token);
}
}
Expand All @@ -736,7 +755,7 @@ mod tests {

let mut lexer = Lexer::new(input);
for token in expected.into_iter() {
let first_lexer_output = lexer.next_token().unwrap();
let first_lexer_output = lexer.next().unwrap().unwrap();
assert_eq!(first_lexer_output, token);
}
}
Expand All @@ -753,7 +772,7 @@ mod tests {
let mut lexer = Lexer::new(input);

for token in expected.into_iter() {
let got = lexer.next_token().unwrap();
let got = lexer.next().unwrap().unwrap();
assert_eq!(got, token);
}
}
Expand All @@ -766,7 +785,7 @@ mod tests {
let mut lexer = Lexer::new(input);

for token in expected.into_iter() {
let got = lexer.next_token().unwrap();
let got = lexer.next().unwrap().unwrap();
assert_eq!(got, token);
}
}
Expand Down Expand Up @@ -805,7 +824,7 @@ mod tests {
let mut lexer = Lexer::new(input);

for spanned_token in expected.into_iter() {
let got = lexer.next_token().unwrap();
let got = lexer.next().unwrap().unwrap();
assert_eq!(got.to_span(), spanned_token.to_span());
assert_eq!(got, spanned_token);
}
Expand Down Expand Up @@ -876,7 +895,7 @@ mod tests {
let mut lexer = Lexer::new(input);

for token in expected.into_iter() {
let got = lexer.next_token().unwrap();
let got = lexer.next().unwrap().unwrap();
assert_eq!(got, token);
}
}
Expand Down
10 changes: 10 additions & 0 deletions compiler/noirc_frontend/src/lexer/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ pub enum Token {
Keyword(Keyword),
IntType(IntType),
Attribute(Attribute),
LineComment(String),
BlockComment(String),
/// <
Less,
/// <=
Expand Down Expand Up @@ -95,6 +97,12 @@ pub enum Token {
Invalid(char),
}

impl Token {
pub fn is_trivia(&self) -> bool {
matches!(self, Token::LineComment(_) | Token::BlockComment(_))
}
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SpannedToken(Spanned<Token>);

Expand Down Expand Up @@ -149,6 +157,8 @@ impl fmt::Display for Token {
Token::FmtStr(ref b) => write!(f, "f{b}"),
Token::Keyword(k) => write!(f, "{k}"),
Token::Attribute(ref a) => write!(f, "{a}"),
Token::LineComment(ref s) => write!(f, "//{s}"),
Token::BlockComment(ref s) => write!(f, "/*{s}*/"),
Token::IntType(ref i) => write!(f, "{i}"),
Token::Less => write!(f, "<"),
Token::LessEqual => write!(f, "<="),
Expand Down
34 changes: 32 additions & 2 deletions tooling/nargo_fmt/src/visitor/expr.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use noirc_frontend::{
hir::resolution::errors::Span, ArrayLiteral, BlockExpression, Expression, ExpressionKind,
Literal, Statement,
hir::resolution::errors::Span, lexer::Lexer, token::Token, ArrayLiteral, BlockExpression,
Expression, ExpressionKind, Literal, Statement,
};

use super::FmtVisitor;
Expand All @@ -10,6 +10,7 @@ impl FmtVisitor<'_> {
let span = expr.span;

let rewrite = self.format_expr(expr);
let rewrite = recover_comment_removed(slice!(self, span.start(), span.end()), rewrite);
self.push_rewrite(rewrite, span);

self.last_position = span.end();
Expand Down Expand Up @@ -159,3 +160,32 @@ impl FmtVisitor<'_> {
self.push_str(&block_str);
}
}

fn recover_comment_removed(original: &str, new: String) -> String {
if changed_comment_content(original, &new) {
original.to_string()
} else {
new
}
}

fn changed_comment_content(original: &str, new: &str) -> bool {
comments(original) != comments(new)
}

fn comments(source: &str) -> Vec<String> {
let mut lexer = Lexer::new(source);
lexer.set_skip_trivia(false);

lexer
.flatten()
.filter_map(|spanned| {
if let Token::LineComment(content) | Token::BlockComment(content) = spanned.into_token()
{
Some(content)
} else {
None
}
})
.collect()
}
3 changes: 3 additions & 0 deletions tooling/nargo_fmt/tests/expected/infix.nr
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@ fn foo() {
40 + 2;
!40 + 2;
40 + 2 == 42;

40/*test*/ + 2 == 42;
40 + 2/*test*/ == 42;
}
4 changes: 3 additions & 1 deletion tooling/nargo_fmt/tests/expected/unary_operators.nr
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
fn main() {
-1
-1;
-/*test*/1;
-/*test*/1;
}
3 changes: 3 additions & 0 deletions tooling/nargo_fmt/tests/input/infix.nr
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@ fn foo() {
40 + 2;
!40+2;
40 + 2 == 42;

40/*test*/ + 2 == 42;
40 + 2/*test*/ == 42;
}
4 changes: 3 additions & 1 deletion tooling/nargo_fmt/tests/input/unary_operators.nr
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
fn main() {
-1
-1;
-/*test*/1;
-/*test*/1;
}