github.com/panjjo/go@v0.0.0-20161104043856-d62b31386338/src/cmd/compile/internal/syntax/syntax.go (about) 1 // Copyright 2016 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package syntax 6 7 import ( 8 "errors" 9 "fmt" 10 "io" 11 "os" 12 ) 13 14 type Mode uint 15 16 // A Pragma value is a set of flags that augment a function or 17 // type declaration. Callers may assign meaning to the flags as 18 // appropriate. 19 type Pragma uint16 20 21 type ErrorHandler func(pos, line int, msg string) 22 23 // A PragmaHandler is used to process //line and //go: directives as 24 // they're scanned. The returned Pragma value will be unioned into the 25 // next FuncDecl node. 26 type PragmaHandler func(pos, line int, text string) Pragma 27 28 // TODO(gri) These need a lot more work. 29 30 func ReadFile(filename string, errh ErrorHandler, pragh PragmaHandler, mode Mode) (*File, error) { 31 src, err := os.Open(filename) 32 if err != nil { 33 return nil, err 34 } 35 defer src.Close() 36 return Read(src, errh, pragh, mode) 37 } 38 39 type bytesReader struct { 40 data []byte 41 } 42 43 func (r *bytesReader) Read(p []byte) (int, error) { 44 if len(r.data) > 0 { 45 n := copy(p, r.data) 46 r.data = r.data[n:] 47 return n, nil 48 } 49 return 0, io.EOF 50 } 51 52 func ReadBytes(src []byte, errh ErrorHandler, pragh PragmaHandler, mode Mode) (*File, error) { 53 return Read(&bytesReader{src}, errh, pragh, mode) 54 } 55 56 func Read(src io.Reader, errh ErrorHandler, pragh PragmaHandler, mode Mode) (ast *File, err error) { 57 defer func() { 58 if p := recover(); p != nil { 59 if msg, ok := p.(parserError); ok { 60 err = errors.New(string(msg)) 61 return 62 } 63 panic(p) 64 } 65 }() 66 67 var p parser 68 p.init(src, errh, pragh) 69 p.next() 70 ast = p.file() 71 72 // TODO(gri) This isn't quite right: Even if there's an error handler installed 73 // we should report an error if parsing found syntax errors. This also 74 // requires updating the noder's ReadFile call. 75 if errh == nil && p.nerrors > 0 { 76 ast = nil 77 err = fmt.Errorf("%d syntax errors", p.nerrors) 78 } 79 80 return 81 } 82 83 func Write(w io.Writer, n *File) error { 84 panic("unimplemented") 85 }