diff --git a/lexer/lexer.go b/lexer/lexer.go index b68ff36..b91145e 100644 --- a/lexer/lexer.go +++ b/lexer/lexer.go @@ -34,13 +34,25 @@ func (l *Lexer) NextToken() token.Token { switch l.ch { case '=': - tok = newToken(token.ASSIGN, l.ch) + if l.peekChar() == '=' { + ch := l.ch + l.readChar() + tok = token.Token{Type: token.EQ, Literal: string(ch) + string(l.ch)} + } else { + tok = newToken(token.ASSIGN, l.ch) + } case '+': tok = newToken(token.PLUS, l.ch) case '-': tok = newToken(token.MINUS, l.ch) case '!': - tok = newToken(token.BANG, l.ch) + if l.peekChar() == '=' { + ch := l.ch + l.readChar() + tok = token.Token{Type: token.NOT_EQ, Literal: string(ch) + string(l.ch)} + } else { + tok = newToken(token.BANG, l.ch) + } case '/': tok = newToken(token.SLASH, l.ch) case '*': @@ -114,3 +126,11 @@ func (l *Lexer) readNumber() string { } return l.input[position:l.position] } + +func (l *Lexer) peekChar() byte { + if l.readPosition >= len(l.input) { + return 0 + } else { + return l.input[l.readPosition] + } +} diff --git a/lexer/lexer_test.go b/lexer/lexer_test.go index b1436ad..4fd13b8 100644 --- a/lexer/lexer_test.go +++ b/lexer/lexer_test.go @@ -22,7 +22,9 @@ if (5 < 10) { } else { return false; } -// [...] + +10 == 10; +10 != 9; ` tests := []struct { @@ -77,6 +79,31 @@ if (5 < 10) { {token.GT, ">"}, {token.INT, "5"}, {token.SEMICOLON, ";"}, + {token.IF, "if"}, + {token.LPAREN, "("}, + {token.INT, "5"}, + {token.LT, "<"}, + {token.INT, "10"}, + {token.RPAREN, ")"}, + {token.LBRACE, "{"}, + {token.RETURN, "return"}, + {token.TRUE, "true"}, + {token.SEMICOLON, ";"}, + {token.RBRACE, "}"}, + {token.ELSE, "else"}, + {token.LBRACE, "{"}, + {token.RETURN, "return"}, + {token.FALSE, "false"}, + {token.SEMICOLON, ";"}, + {token.RBRACE, "}"}, + {token.INT, "10"}, + {token.EQ, "=="}, + {token.INT, "10"}, + {token.SEMICOLON, ";"}, + {token.INT, "10"}, + {token.NOT_EQ, "!="}, + {token.INT, "9"}, + {token.SEMICOLON, ";"}, {token.EOF, ""}, } diff --git a/token/token.go b/token/token.go index a3ed311..fe8a05c 100644 --- a/token/token.go +++ b/token/token.go @@ -26,6 +26,9 @@ const ( LT = "<" GT = ">" + EQ = "==" + NOT_EQ = "!=" + //DELIM COMMA = "" SEMICOLON = ";"