feat: stuff

This commit is contained in:
2025-12-26 01:59:56 -05:00
parent fa44051dec
commit 11e7f70625
6 changed files with 74 additions and 76 deletions

View File

@@ -1,7 +1,6 @@
package main package main
import ( import (
"errors"
"fmt" "fmt"
"os" "os"
"time" "time"
@@ -26,10 +25,8 @@ func main() {
cli.HandleError(err) cli.HandleError(err)
// Parse tokens. // Parse tokens.
tokens, fails := tokenizer.GetTokens([]rune(input)) tokens, err := tokenizer.GetTokens([]rune(input))
if len(fails) > 0 { cli.HandleError(err)
cli.HandleError(errors.Join(fails...))
}
logger.Info("Parsed tokens.", "tokens", tokens) logger.Info("Parsed tokens.", "tokens", tokens)
// Turn tokens into syntax tree. // Turn tokens into syntax tree.

View File

@@ -12,8 +12,8 @@ type Iterator[T any] struct {
} }
// Create a new iterator, over a set of items. // Create a new iterator, over a set of items.
func New[T any](items []T) Iterator[T] { func New[T any](items []T) *Iterator[T] {
return Iterator[T]{data: items, index: 0} return &Iterator[T]{data: items, index: 0}
} }
// Returns the current position of the iterator. // Returns the current position of the iterator.
@@ -40,7 +40,7 @@ func (i Iterator[T]) Peek() (T, error) {
// Moves the iterator pointer to the next item. Returns the current item. Fails // Moves the iterator pointer to the next item. Returns the current item. Fails
// if there are no more items to iterate over. // if there are no more items to iterate over.
func (i *Iterator[T]) Next() (T, error) { func (i *Iterator[T]) Pop() (T, error) {
val, err := i.Peek() val, err := i.Peek()
if err != nil { if err != nil {
return val, err return val, err
@@ -49,3 +49,22 @@ func (i *Iterator[T]) Next() (T, error) {
i.index++ i.index++
return val, nil return val, nil
} }
// Pop until the clause returns false.
func (i *Iterator[T]) PopWhile(fn func(T) bool) []T {
result := []T{}
for {
popped, err := i.Peek()
if err != nil || !fn(popped) {
break
}
result = append(result, popped)
if _, err := i.Pop(); err != nil {
break
}
}
return result
}

View File

@@ -7,12 +7,8 @@ import (
) )
func GenerateFreshName(used set.Set[string]) string { func GenerateFreshName(used set.Set[string]) string {
// Starts as '0', that is the base value of a 'uint64'. for i := uint64(0); ; i++ {
var i uint64
for {
attempt := "_" + string(strconv.AppendUint(nil, i, 10)) attempt := "_" + string(strconv.AppendUint(nil, i, 10))
i++
if !used.Has(attempt) { if !used.Has(attempt) {
return attempt return attempt

View File

@@ -9,7 +9,7 @@ import (
) )
func ParseExpression(i *iterator.Iterator[tokenizer.Token]) (lambda.Expression, error) { func ParseExpression(i *iterator.Iterator[tokenizer.Token]) (lambda.Expression, error) {
token, err := i.Next() token, err := i.Pop()
if err != nil { if err != nil {
return nil, fmt.Errorf("could not get next token: %w", err) return nil, fmt.Errorf("could not get next token: %w", err)
} }
@@ -23,7 +23,7 @@ func ParseExpression(i *iterator.Iterator[tokenizer.Token]) (lambda.Expression,
atoms := []string{} atoms := []string{}
for { for {
atom, atomErr := i.Next() atom, atomErr := i.Pop()
if atomErr != nil { if atomErr != nil {
return nil, fmt.Errorf("could not find parameter or terminator of function: %w", atomErr) return nil, fmt.Errorf("could not find parameter or terminator of function: %w", atomErr)
} else if atom.Type == tokenizer.TokenVariable { } else if atom.Type == tokenizer.TokenVariable {
@@ -72,7 +72,7 @@ func ParseExpression(i *iterator.Iterator[tokenizer.Token]) (lambda.Expression,
args = append(args, arg) args = append(args, arg)
} }
closing, closingErr := i.Next() closing, closingErr := i.Pop()
if closingErr != nil { if closingErr != nil {
return nil, fmt.Errorf("could not parse call terminating parenthesis: %w", closingErr) return nil, fmt.Errorf("could not parse call terminating parenthesis: %w", closingErr)
} else if closing.Type != tokenizer.TokenCloseParen { } else if closing.Type != tokenizer.TokenCloseParen {
@@ -94,6 +94,5 @@ func ParseExpression(i *iterator.Iterator[tokenizer.Token]) (lambda.Expression,
} }
func GetTree(tokens []tokenizer.Token) (lambda.Expression, error) { func GetTree(tokens []tokenizer.Token) (lambda.Expression, error) {
i := iterator.New(tokens) return ParseExpression(iterator.New(tokens))
return ParseExpression(&i)
} }

View File

@@ -1,17 +1,27 @@
package tokenizer package tokenizer
// All tokens in the pseudo-lambda language.
type TokenType int type TokenType int
const ( const (
// Denotes the '(' token.
TokenOpenParen TokenType = iota TokenOpenParen TokenType = iota
// Denotes the ')' token.
TokenCloseParen TokenCloseParen
// Denotes an alpha-numeric variable.
TokenVariable TokenVariable
// Denotes the '/' token.
TokenSlash TokenSlash
// Denotes the '.' token.
TokenDot TokenDot
) )
// A representation of a token in source code.
type Token struct { type Token struct {
// Where the token begins in the source text.
Index int Index int
// What type the token is.
Type TokenType Type TokenType
// The value of the token.
Value string Value string
} }

View File

@@ -1,95 +1,72 @@
package tokenizer package tokenizer
import ( import (
"errors"
"fmt" "fmt"
"strings"
"unicode" "unicode"
"git.maximhutz.com/max/lambda/pkg/iterator" "git.maximhutz.com/max/lambda/pkg/iterator"
) )
// isVariables determines whether a rune can be a valid variable.
func isVariable(r rune) bool { func isVariable(r rune) bool {
return unicode.IsLetter(r) || unicode.IsNumber(r) return unicode.IsLetter(r) || unicode.IsNumber(r)
} }
// Pulls the next token from an iterator over runes. If it cannot, it will
// return nil. If an error occurs, it will return that.
func getToken(i *iterator.Iterator[rune]) (*Token, error) { func getToken(i *iterator.Iterator[rune]) (*Token, error) {
index := i.Index()
if i.IsDone() { if i.IsDone() {
return nil, nil return nil, nil
} }
letter, err := i.Next() letter, err := i.Pop()
if err != nil { if err != nil {
return nil, fmt.Errorf("cannot produce next token: %w", err) return nil, fmt.Errorf("cannot produce next token: %w", err)
} }
// If it is an operand. switch {
switch letter { case letter == '(':
case '(': // The opening deliminator of an application.
return &Token{ return &Token{Type: TokenOpenParen, Index: index, Value: string(letter)}, nil
Type: TokenOpenParen, case letter == ')':
Index: i.Index(), // The terminator of an application.
Value: string(letter), return &Token{Type: TokenCloseParen, Index: index, Value: string(letter)}, nil
}, nil case letter == '.':
case ')': // The terminator of the parameters in an abstraction.
return &Token{ return &Token{Type: TokenDot, Index: index, Value: string(letter)}, nil
Type: TokenCloseParen, case letter == '\\':
Index: i.Index(), // The opening deliminator of an abstraction.
Value: string(letter), return &Token{Type: TokenSlash, Index: index, Value: string(letter)}, nil
}, nil case unicode.IsSpace(letter):
case '.': // If there is a space character, ignore it.
return &Token{
Type: TokenDot,
Index: i.Index(),
Value: string(letter),
}, nil
case '\\':
return &Token{
Type: TokenSlash,
Index: i.Index(),
Value: string(letter),
}, nil
}
// If it is a space.
if unicode.IsSpace(letter) {
return nil, nil return nil, nil
case isVariable(letter):
rest := i.PopWhile(isVariable)
atom := string(append([]rune{letter}, rest...))
return &Token{Index: index, Type: TokenVariable, Value: atom}, nil
} }
// Otherwise, it is an atom. return nil, fmt.Errorf("unknown character '%v'", letter)
atom := strings.Builder{}
index := i.Index()
for !i.IsDone() {
pop, err := i.Peek()
if err != nil || !isVariable(pop) {
break
} }
atom.WriteRune(pop) // Parses a list of runes into tokens. All error encountered are returned, as well.
if _, err := i.Next(); err != nil { func GetTokens(input []rune) ([]Token, error) {
break
}
}
return &Token{
Index: index,
Type: TokenVariable,
Value: atom.String(),
}, nil
}
func GetTokens(input []rune) ([]Token, []error) {
i := iterator.New(input) i := iterator.New(input)
tokens := []Token{} tokens := []Token{}
errors := []error{} errorList := []error{}
for !i.IsDone() { for !i.IsDone() {
token, err := getToken(&i) token, err := getToken(i)
if err != nil { if err != nil {
errors = append(errors, err) errorList = append(errorList, err)
} else if token != nil { } else if token != nil {
tokens = append(tokens, *token) tokens = append(tokens, *token)
} }
} }
return tokens, errors return tokens, errors.Join(errorList...)
} }