Skip to content

Commit

Permalink
Merge pull request #4 from akos011221/feat/initial
Browse files Browse the repository at this point in the history
Extend tokenizer with identifiers/keywords and digits
  • Loading branch information
akos011221 authored Oct 6, 2024
2 parents 639ae3a + 3e8dd1e commit 6a319ec
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 8 deletions.
25 changes: 25 additions & 0 deletions lexer/lexer.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import "moodeng/token"
func (l *Lexer) NextToken() token.Token {
var tok token.Token

l.skipWhitespace()

switch l.ch {
case '=':
tok = newToken(token.ASSIGN, l.ch)
Expand All @@ -28,6 +30,11 @@ func (l *Lexer) NextToken() token.Token {
default:
if isLetter(l.ch) {
tok.Literal = l.readIdentifier()
tok.Type = token.LookupIdent(tok.Literal)
return tok
} else if isDigit(l.ch) {
tok.Type = token.INT
tok.Literal = l.readNumber()
return tok
} else {
tok = newToken(token.ILLEGAL, l.ch)
Expand Down Expand Up @@ -76,3 +83,21 @@ func (l *Lexer) readIdentifier() string {
func isLetter(ch byte) bool {
return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_'
}

func (l *Lexer) skipWhitespace() {
for l.ch == ' ' || l.ch == '\t' || l.ch == '\r' || l.ch == '\n' {
l.readChar()
}
}

func (l *Lexer) readNumber() string {
position := l.position
for isDigit(l.ch) {
l.readChar()
}
return l.input[position:l.position]
}

func isDigit(ch byte) bool {
return '0' <= ch && ch <= '9'
}
14 changes: 6 additions & 8 deletions lexer/lexer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,14 @@ import (
)

func TestNextToken(t *testing.T) {
input := `
let five = 5;
let ten = 10;
input := `let five = 5;
let ten = 10;
let add = fn(x, y) {
x + y;
};
let add = fn(x, y) {
x + y;
};
let result = add(five, ten);
`
let result = add(five, ten);`

tests := []struct {
expectedType token.TokenType
Expand Down
12 changes: 12 additions & 0 deletions token/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,18 @@ type Token struct {
Literal string
}

var keywords = map[string]TokenType{
"fn": FUNCTION,
"let": LET,
}

func LookupIdent(ident string) TokenType {
if tok, ok := keywords[ident]; ok {
return tok
}
return IDENT
}

const (
ILLEGAL = "ILLEGAL"
EOF = "EOF"
Expand Down

0 comments on commit 6a319ec

Please sign in to comment.