add file trace to parser, refactor, fix inner type

This commit is contained in:
Neemek 2025-09-30 14:09:05 +02:00
parent bcf0978b68
commit c8660a6471
Signed by: neemek
GPG key ID: 84FFE4D7D40AB25E
10 changed files with 131 additions and 51 deletions

View file

@ -9,6 +9,7 @@ import (
"os"
"path"
"path/filepath"
"strings"
)
type Context struct {
@ -21,24 +22,28 @@ type RunCmd struct {
File string `arg:"" name:"file" help:"File to read program from" type:"existingfile"`
}
// WorkingDirectoryResolver resolves imports relative to the working directory
type WorkingDirectoryResolver struct {
workingDirectory string
// DirectoryResolver resolves imports from several directories
type DirectoryResolver struct {
// directories to search through, in decreasing priority.
directories []string
}
func (r *WorkingDirectoryResolver) Resolve(path string) (string, error) {
pth := filepath.Join(r.workingDirectory, path)
f, err := os.ReadFile(pth)
if err != nil {
return "", err
func (r *DirectoryResolver) Resolve(path string) (string, error) {
for _, d := range r.directories {
pth := filepath.Join(d, path)
f, err := os.ReadFile(pth)
if err == nil {
return string(f), nil
}
}
return string(f), nil
return "", errors.New("couldn't resolve import")
}
func (r *WorkingDirectoryResolver) IsSame(a, b string) bool {
apath := filepath.Clean(filepath.Join(r.workingDirectory, a))
bpath := filepath.Clean(filepath.Join(r.workingDirectory, b))
func (r *DirectoryResolver) IsSame(a, b string) bool {
apath := filepath.Clean(a)
bpath := filepath.Clean(b)
return apath == bpath
}
@ -57,7 +62,7 @@ func makeChunk(ctx *Context, fpath string, ignoreWarnings bool) (*core.Chunk, er
src := string(f)
if ctx.Debug {
log.Println("Initialized lexer")
log.Println("Initializing lexer")
}
l := core.NewLexer(src)
@ -78,7 +83,7 @@ func makeChunk(ctx *Context, fpath string, ignoreWarnings bool) (*core.Chunk, er
log.Printf("Lexed %d tokens", len(tokens))
}
p := core.NewParser(src, tokens)
p := core.NewParser(src, []string{fpath}, tokens)
if ctx.Debug {
log.Println("Initialized parser")
@ -110,9 +115,14 @@ func makeChunk(ctx *Context, fpath string, ignoreWarnings bool) (*core.Chunk, er
log.Println("Setting imports resolver")
}
lib := os.Getenv("ANGLAIS_PATH")
dirs := strings.Split(lib, ":")
dir, _ := path.Split(fpath)
c.SetImportsResolver(&WorkingDirectoryResolver{
dir,
c.SetImportsResolver(&DirectoryResolver{
append([]string{
dir,
}, dirs...),
})
if ctx.Debug {
@ -231,7 +241,7 @@ type ReplCmd struct {
}
func (cmd *ReplCmd) Run(ctx *Context) error {
c := core.NewCompiler([]rune(""))
c := core.NewCompiler([]rune{})
vm := core.NewVM(core.NewChunk([]core.Bytecode{}, []core.Value{}), 256, 256)
reader := bufio.NewReader(os.Stdin)
@ -249,7 +259,7 @@ func (cmd *ReplCmd) Run(ctx *Context) error {
continue
}
p := core.NewParser(src, tokens)
p := core.NewParser(src, []string{}, tokens)
prog, err := p.Parse("REPL")
if err != nil {
var e core.FormatedError