make compiler errors general, and better imports
Some checks failed
/ test (push) Failing after 43s

This commit is contained in:
Neemek 2025-10-02 13:03:40 +02:00
parent f2ebcf560f
commit b95d2954ba
Signed by: neemek
GPG key ID: 84FFE4D7D40AB25E
5 changed files with 77 additions and 30 deletions

View file

@ -1,7 +1,6 @@
package core
import (
"errors"
"fmt"
"strings"
)
@ -21,8 +20,13 @@ type Compiler struct {
stack *Stack[LocalVariable]
}
type ImportResult struct {
Source string
Path string
}
type ImportsResolver interface {
Resolve(path string) (string, error)
Resolve(from, path string) (*ImportResult, error)
IsSame(a, b string) bool
}
@ -34,7 +38,7 @@ type LocalVariable struct {
type CompilerError struct {
Description string
Causer Node
Boundary Boundary
Source []rune
Trace []string
}
@ -51,7 +55,7 @@ func (e CompilerError) Format() string {
b.WriteString(e.Description)
// highlight offending area
start, end := e.Causer.Bounds()
start, end := e.Boundary.Bounds()
lineEnd := 0
lineStart := 0
@ -1254,7 +1258,7 @@ func (c *Compiler) addDescend() {
c.add(InstructionDescend)
}
func (c *Compiler) error(msg string, causer Node) CompilerError {
func (c *Compiler) error(msg string, causer Boundary) CompilerError {
return CompilerError{
msg,
causer,
@ -1267,34 +1271,34 @@ func (c *Compiler) warn(msg string, causer Node) {
c.Warnings = append(c.Warnings, c.error(msg, causer))
}
func (c *Compiler) resolveImport(path string) error {
func (c *Compiler) resolveImport(imp Import) error {
res, err := c.resolver.Resolve(c.fileStack.Peek(), imp.path)
if err != nil {
return err
}
// if already imported and available
for _, i := range c.imports {
if c.resolver.IsSame(path, i) {
if c.resolver.IsSame(res.Path, i) {
return nil
}
}
// stop recursive imports
for i := c.fileStack.Current - 1; i >= 0; i-- {
if c.resolver.IsSame(path, c.fileStack.items[i]) {
return errors.New("recursive import")
if c.resolver.IsSame(res.Path, c.fileStack.items[i]) {
return c.error("recursive import", imp)
}
}
src, err := c.resolver.Resolve(path)
if err != nil {
return err
}
l := NewLexer(src)
l := NewLexer(res.Source)
tokens, err := l.Tokenize()
if err != nil {
return err
}
parser := NewParser(src, append(c.fileStack.Slice(), path), tokens)
p, err := parser.Parse(path)
parser := NewParser(res.Source, append(c.fileStack.Slice(), res.Path), tokens)
p, err := parser.Parse(res.Path)
if err != nil {
return err
}
@ -1302,7 +1306,7 @@ func (c *Compiler) resolveImport(path string) error {
oldSrc := c.source
// update source for more descriptive errors
c.source = []rune(src)
c.source = []rune(res.Source)
if err := c.Compile(p); err != nil {
return err
}