Skip to content

Commit

Permalink
1.4: Add '==' and '!='
Browse files Browse the repository at this point in the history
  • Loading branch information
nibral committed Jan 10, 2019
1 parent cf28a6d commit 0b77bb3
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
26 changes: 24 additions & 2 deletions lexer/lexer.go
Expand Up @@ -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) {
Expand All @@ -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 '/':
Expand Down
11 changes: 11 additions & 0 deletions lexer/lexer_test.go
Expand Up @@ -21,6 +21,9 @@ if (5 < 10) {
} else {
return false;
}
10 == 10;
10 != 9;
`

tests := []struct {
Expand Down Expand Up @@ -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, ""},
}

Expand Down
3 changes: 3 additions & 0 deletions token/token.go
Expand Up @@ -19,6 +19,9 @@ const (
LT = "<"
GT = ">"

EQ = "=="
NOT_EQ = "!="

// Delimiters
COMMA = ","
SEMICOLON = ";"
Expand Down

0 comments on commit 0b77bb3

Please sign in to comment.