Esempio n. 1
0
File: parse.go Progetto: unreal/calc
func ParseFile(fset *token.FileSet, filename string) *ast.File {
	fi, err := os.Stat(filename)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	var p parser
	var f *ast.File
	if ext := filepath.Ext(fi.Name()); ext == ".calc" {
		src, err := ioutil.ReadFile(filename)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		file := fset.Add(filepath.Base(filename), string(src))
		p.init(file, filename, string(src))
		f = p.parseFile()
	}

	if p.errors.Count() > 0 {
		p.errors.Print()
		return nil
	}

	return f
}
Esempio n. 2
0
// ParseFile parses the file identified by filename and returns a pointer
// to an ast.File object. The file should contain Calc source code and
// have the .calc file extension.
// The returned AST object ast.File is nil if there is an error.
func ParseFile(fset *token.FileSet, filename, src string) (*ast.File, error) {
	var r io.Reader
	var sz int64
	if src == "" {
		f, err := os.Open(filename)
		if err != nil {
			return nil, err
		}
		defer f.Close()

		fi, err := f.Stat()
		if err != nil {
			return nil, err
		}

		if ext := filepath.Ext(fi.Name()); ext != ".calc" {
			return nil, fmt.Errorf("invalid file extension %s, must be .calc", ext)
		}
		r = f
		sz = fi.Size()
		fmt.Printf("%s:%d\n", fi.Name(), sz)
	} else {
		sr := strings.NewReader(src)
		r = io.Reader(sr)
		sz = sr.Size()
	}

	file := fset.Add(filepath.Base(filename), int(sz))
	var p parser
	p.init(file, filename, r, ast.NewScope(nil))
	f := p.parseFile()

	if p.errors.Count() > 0 {
		return nil, p.errors
	}

	return f, nil
}