Skip to content

Commit

Permalink
+ skip comment (#39)
Browse files Browse the repository at this point in the history
  • Loading branch information
meloalright authored Nov 5, 2023
1 parent e531aef commit 4dcb3ae
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 1 deletion.
17 changes: 17 additions & 0 deletions interpreter/src/evaluator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1225,4 +1225,21 @@ f()

assert_eq!(Some(object::Object::Int(5)), eval(input));
}

#[test]
fn test_comment() {
let tests = vec![
(
"let identity = fn(x) { // function defination here
x; // just x
};
identity(5); // run with param 5",
Some(object::Object::Int(5)),
),
];

for (input, expect) in tests {
assert_eq!(expect, eval(input));
}
}
}
26 changes: 25 additions & 1 deletion interpreter/src/lexer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,15 @@ impl Lexer {
let tok = match self.ch {
'+' => Token::Plus,
'-' => Token::Minus,
'/' => Token::Slash,
'/' => {
if self.next_is('/') {
self.walk_char();
self.skip_comment();
return self.next_token();
} else {
Token::Slash
}
},
'*' => Token::Asterisk,
'<' => {
if self.next_is('=') {
Expand Down Expand Up @@ -181,6 +189,13 @@ impl Lexer {
}
}

fn skip_comment(&mut self) {
while !matches!(self.next_ch(), '\n' | '\0') {
self.walk_char();
}
self.walk_char();
}

fn consume_identifier(&mut self) -> Token {
let start_pos = self.pos;

Expand Down Expand Up @@ -331,6 +346,9 @@ if (5 < 10) {
"foobar";
"foo bar";
'foo bar';
"foobar";//
"foo bar"; // just a comment
'foo bar'; // 一段注释
[1, 2];
Expand Down Expand Up @@ -433,6 +451,12 @@ if (5 < 10) {
Token::Semicolon,
Token::String(String::from("foo bar")),
Token::Semicolon,
Token::String(String::from("foobar")),
Token::Semicolon,
Token::String(String::from("foo bar")),
Token::Semicolon,
Token::String(String::from("foo bar")),
Token::Semicolon,
Token::Blank,
Token::LBracket,
Token::Int(1),
Expand Down
23 changes: 23 additions & 0 deletions interpreter/src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1891,6 +1891,29 @@ return 993322;
);
}

#[test]
fn test_comment() {
let input = "fn(x, y){
x + y // just return x + y 即可
}";

let mut parser = Parser::new(Lexer::new(input));
let program = parser.parse();

check_parse_errors(&mut parser);
assert_eq!(
vec![Stmt::Expr(Expr::Function {
params: vec![Ident(String::from("x")), Ident(String::from("y"))],
body: vec![Stmt::Expr(Expr::Infix(
Infix::Plus,
Box::new(Expr::Ident(Ident(String::from("x")))),
Box::new(Expr::Ident(Ident(String::from("y")))),
))],
})],
program,
);
}

/// errors panic
#[test]
Expand Down

0 comments on commit 4dcb3ae

Please sign in to comment.