From 0b77bb38b7d1edd437350a49ae44fd2a20240c06 Mon Sep 17 00:00:00 2001 From: nibral Date: Thu, 10 Jan 2019 09:57:44 +0900 Subject: [PATCH] 1.4: Add '==' and '!=' --- lexer/lexer.go | 26 ++++++++++++++++++++++++-- lexer/lexer_test.go | 11 +++++++++++ token/token.go | 3 +++ 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/lexer/lexer.go b/lexer/lexer.go index b401208..e2788b4 100644 --- a/lexer/lexer.go +++ b/lexer/lexer.go @@ -41,6 +41,14 @@ func (l *Lexer) readChar() { l.readPosition += 1 } +func (l *Lexer) peekChar() byte { + if l.readPosition >= len(l.input) { + return 0 // NULL + } else { + return l.input[l.readPosition] + } +} + func (l *Lexer) readIdentifier() string { position := l.position for isLetter(l.ch) { @@ -64,13 +72,27 @@ func (l *Lexer) NextToken() token.Token { switch l.ch { case '=': - tok = newToken(token.ASSIGN, l.ch) + if l.peekChar() == '=' { + ch := l.ch + l.readChar() + literal := string(ch) + string(l.ch) + tok = token.Token{Type: token.EQ, Literal: literal} + } 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() + literal := string(ch) + string(l.ch) + tok = token.Token{Type: token.NOT_EQ, Literal: literal} + } else { + tok = newToken(token.BANG, l.ch) + } case '*': tok = newToken(token.ASTERISK, l.ch) case '/': diff --git a/lexer/lexer_test.go b/lexer/lexer_test.go index cfa77ca..de6fc1b 100644 --- a/lexer/lexer_test.go +++ b/lexer/lexer_test.go @@ -21,6 +21,9 @@ if (5 < 10) { } else { return false; } + +10 == 10; +10 != 9; ` tests := []struct { @@ -92,6 +95,14 @@ if (5 < 10) { {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 ba0611b..72debf5 100644 --- a/token/token.go +++ b/token/token.go @@ -19,6 +19,9 @@ const ( LT = "<" GT = ">" + EQ = "==" + NOT_EQ = "!=" + // Delimiters COMMA = "," SEMICOLON = ";"