github.com/coyove/nj@v0.0.0-20221110084952-c7f8db1065c3/nj.go (about)

     1  package nj
     2  
     3  import (
     4  	"io"
     5  	"io/ioutil"
     6  	"os"
     7  	"unsafe"
     8  
     9  	"github.com/coyove/nj/bas"
    10  	"github.com/coyove/nj/internal"
    11  	"github.com/coyove/nj/parser"
    12  )
    13  
    14  type LoadOptions struct {
    15  	Globals      bas.Map
    16  	MaxStackSize int64
    17  	Stdout       io.Writer
    18  	Stderr       io.Writer
    19  	Stdin        io.Reader
    20  }
    21  
    22  func LoadFile(path string, opt *LoadOptions) (*bas.Program, error) {
    23  	code, err := ioutil.ReadFile(path)
    24  	if err != nil {
    25  		return nil, err
    26  	}
    27  	return loadCode(*(*string)(unsafe.Pointer(&code)), path, opt)
    28  }
    29  
    30  func LoadString(code string, opt *LoadOptions) (*bas.Program, error) {
    31  	return loadCode(code, internal.UnnamedLoadString(), opt)
    32  }
    33  
    34  func loadCode(code, name string, opt *LoadOptions) (*bas.Program, error) {
    35  	n, err := parser.Parse(code, name)
    36  	if err != nil {
    37  		return nil, err
    38  	}
    39  	if internal.IsDebug() {
    40  		n.Dump(os.Stderr)
    41  	}
    42  	return compileNodeTopLevel(name, code, n, opt)
    43  }
    44  
    45  func Run(p *bas.Program, err error) bas.Value {
    46  	if err != nil {
    47  		return bas.Error(nil, err)
    48  	}
    49  	return p.Run()
    50  }
    51  
    52  func MustRun(p *bas.Program, err error) bas.Value {
    53  	internal.PanicErr(err)
    54  	return p.Run()
    55  }