Type check

This commit is contained in:
silva guimaraes 2025-06-01 15:05:45 -03:00
parent 8f5b16878f
commit 0cd6040a1f
7 changed files with 625 additions and 256 deletions

30
lex.go
View file

@ -3,6 +3,7 @@ package main
import (
"fmt"
"regexp"
"slices"
"strconv"
"strings"
)
@ -37,9 +38,9 @@ type Id string
type Token token[string]
type Int token[int]
type IntToken token[int]
type Float token[float64]
type FloatToken token[float64]
type Identifier token[Id]
@ -52,13 +53,16 @@ var (
SingleQuote = &Token{value: "'"}
Let = &Token{value: "let"}
LambdaTok = &Token{value: "lambda"}
If = &Token{value: "if"}
TrueTok = &Token{value: "t"}
NilTok = &Token{value: "nil"}
)
func (t Token) String() string {
return fmt.Sprint(t.value)
}
func (t Int) String() string {
func (t IntToken) String() string {
return fmt.Sprint(t.value)
}
@ -75,6 +79,9 @@ var knownTokens = []*Token{
SingleQuote,
Let,
LambdaTok,
If,
TrueTok,
NilTok,
}
func (t *Token) Equals(a Lexeme) bool {
@ -86,8 +93,8 @@ func (t *Token) Equals(a Lexeme) bool {
}
}
func (t *Int) Equals(a Lexeme) bool { return false }
func (t *Float) Equals(a Lexeme) bool { return false }
func (t *IntToken) Equals(a Lexeme) bool { return false }
func (t *FloatToken) Equals(a Lexeme) bool { return false }
func (t *Identifier) Equals(a Lexeme) bool {
switch x := a.(type) {
@ -110,6 +117,15 @@ func lex(source string) (*Input, error) {
outer:
for len(source) > 0 {
p := position{pos: pos, line: line, column: column, filepath: "stdin"}
if source[0] == ';' {
idx := slices.Index([]byte(source), '\n')
if idx < 0 {
break
} else {
source = source[idx:]
continue
}
}
for _, try := range knownTokens {
if !strings.HasPrefix(source, try.value) {
continue
@ -137,7 +153,7 @@ outer:
a := source[index[0]:index[1]]
conv, err := strconv.ParseFloat(a, 64)
if err == nil {
var i = &Float{position: p, value: conv}
var i = &FloatToken{position: p, value: conv}
tokens = append(tokens, i)
l := len(a)
source = source[l:]
@ -151,7 +167,7 @@ outer:
a := source[index[0]:index[1]]
conv, err := strconv.Atoi(a)
if err == nil {
var i = &Int{position: p, value: conv}
var i = &IntToken{position: p, value: conv}
tokens = append(tokens, i)
l := len(a)
source = source[l:]