Marcel van Lohuizen | d96ad3d | 2018-12-10 15:30:20 +0100 | [diff] [blame] | 1 | // Copyright 2018 The CUE Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | // This file contains the exported entry points for invoking the |
| 16 | |
| 17 | package parser |
| 18 | |
| 19 | import ( |
| 20 | "bytes" |
| 21 | "fmt" |
| 22 | "io" |
| 23 | "io/ioutil" |
| 24 | |
| 25 | "cuelang.org/go/cue/ast" |
| 26 | "cuelang.org/go/cue/token" |
| 27 | ) |
| 28 | |
| 29 | // If src != nil, readSource converts src to a []byte if possible; |
| 30 | // otherwise it returns an error. If src == nil, readSource returns |
| 31 | // the result of reading the file specified by filename. |
| 32 | // |
| 33 | func readSource(filename string, src interface{}) ([]byte, error) { |
| 34 | if src != nil { |
| 35 | switch s := src.(type) { |
| 36 | case string: |
| 37 | return []byte(s), nil |
| 38 | case []byte: |
| 39 | return s, nil |
| 40 | case *bytes.Buffer: |
| 41 | // is io.Reader, but src is already available in []byte form |
| 42 | if s != nil { |
| 43 | return s.Bytes(), nil |
| 44 | } |
| 45 | case io.Reader: |
| 46 | var buf bytes.Buffer |
| 47 | if _, err := io.Copy(&buf, s); err != nil { |
| 48 | return nil, err |
| 49 | } |
| 50 | return buf.Bytes(), nil |
| 51 | } |
| 52 | return nil, fmt.Errorf("invalid source type %T", src) |
| 53 | } |
| 54 | return ioutil.ReadFile(filename) |
| 55 | } |
| 56 | |
Marcel van Lohuizen | 76b92b5 | 2018-12-16 10:47:03 +0100 | [diff] [blame] | 57 | // Option specifies a parse option. |
Marcel van Lohuizen | d96ad3d | 2018-12-10 15:30:20 +0100 | [diff] [blame] | 58 | type Option func(p *parser) |
| 59 | |
| 60 | var ( |
| 61 | // PackageClauseOnly causes parsing to stop after the package clause. |
| 62 | PackageClauseOnly Option = packageClauseOnly |
| 63 | packageClauseOnly = func(p *parser) { |
| 64 | p.mode |= packageClauseOnlyMode |
| 65 | } |
| 66 | |
| 67 | // ImportsOnly causes parsing to stop parsing after the import declarations. |
| 68 | ImportsOnly Option = importsOnly |
| 69 | importsOnly = func(p *parser) { |
| 70 | p.mode |= importsOnlyMode |
| 71 | } |
| 72 | |
| 73 | // ParseComments causes comments to be parsed. |
| 74 | ParseComments Option = parseComments |
| 75 | parseComments = func(p *parser) { |
| 76 | p.mode |= parseCommentsMode |
| 77 | } |
| 78 | |
Marcel van Lohuizen | d96ad3d | 2018-12-10 15:30:20 +0100 | [diff] [blame] | 79 | // Trace causes parsing to print a trace of parsed productions. |
| 80 | Trace Option = traceOpt |
| 81 | traceOpt = func(p *parser) { |
| 82 | p.mode |= traceMode |
| 83 | } |
| 84 | |
| 85 | // DeclarationErrors causes parsing to report declaration errors. |
| 86 | DeclarationErrors Option = declarationErrors |
| 87 | declarationErrors = func(p *parser) { |
| 88 | p.mode |= declarationErrorsMode |
| 89 | } |
| 90 | |
| 91 | // AllErrors causes all errors to be reported (not just the first 10 on different lines). |
| 92 | AllErrors Option = allErrors |
| 93 | allErrors = func(p *parser) { |
| 94 | p.mode |= allErrorsMode |
| 95 | } |
| 96 | |
| 97 | // AllowPartial allows the parser to be used on a prefix buffer. |
| 98 | AllowPartial Option = allowPartial |
| 99 | allowPartial = func(p *parser) { |
| 100 | p.mode |= partialMode |
| 101 | } |
| 102 | ) |
| 103 | |
| 104 | // A mode value is a set of flags (or 0). |
| 105 | // They control the amount of source code parsed and other optional |
| 106 | // parser functionality. |
| 107 | type mode uint |
| 108 | |
| 109 | const ( |
| 110 | packageClauseOnlyMode mode = 1 << iota // stop parsing after package clause |
| 111 | importsOnlyMode // stop parsing after import declarations |
| 112 | parseCommentsMode // parse comments and add them to AST |
Marcel van Lohuizen | d96ad3d | 2018-12-10 15:30:20 +0100 | [diff] [blame] | 113 | partialMode |
| 114 | traceMode // print a trace of parsed productions |
| 115 | declarationErrorsMode // report declaration errors |
| 116 | allErrorsMode // report all errors (not just the first 10 on different lines) |
| 117 | ) |
| 118 | |
| 119 | // ParseFile parses the source code of a single CUE source file and returns |
| 120 | // the corresponding File node. The source code may be provided via |
| 121 | // the filename of the source file, or via the src parameter. |
| 122 | // |
| 123 | // If src != nil, ParseFile parses the source from src and the filename is |
| 124 | // only used when recording position information. The type of the argument |
| 125 | // for the src parameter must be string, []byte, or io.Reader. |
| 126 | // If src == nil, ParseFile parses the file specified by filename. |
| 127 | // |
| 128 | // The mode parameter controls the amount of source text parsed and other |
| 129 | // optional parser functionality. Position information is recorded in the |
| 130 | // file set fset, which must not be nil. |
| 131 | // |
| 132 | // If the source couldn't be read, the returned AST is nil and the error |
| 133 | // indicates the specific failure. If the source was read but syntax |
| 134 | // errors were found, the result is a partial AST (with Bad* nodes |
| 135 | // representing the fragments of erroneous source code). Multiple errors |
| 136 | // are returned via a ErrorList which is sorted by file position. |
| 137 | func ParseFile(p *token.FileSet, filename string, src interface{}, mode ...Option) (f *ast.File, err error) { |
| 138 | if p == nil { |
| 139 | panic("ParseFile: no file.FileSet provided (fset == nil)") |
| 140 | } |
| 141 | |
| 142 | // get source |
| 143 | text, err := readSource(filename, src) |
| 144 | if err != nil { |
| 145 | return nil, err |
| 146 | } |
| 147 | |
| 148 | var pp parser |
| 149 | defer func() { |
| 150 | if e := recover(); e != nil { |
| 151 | // resume same panic if it's not a bailout |
| 152 | if _, ok := e.(bailout); !ok { |
| 153 | panic(e) |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | // set result values |
| 158 | if f == nil { |
| 159 | // source is not a valid Go source file - satisfy |
| 160 | // ParseFile API and return a valid (but) empty |
| 161 | // *File |
| 162 | f = &ast.File{ |
| 163 | Name: new(ast.Ident), |
| 164 | // Scope: NewScope(nil), |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | pp.errors.Sort() |
| 169 | err = pp.errors.Err() |
| 170 | }() |
| 171 | |
| 172 | // parse source |
| 173 | pp.init(p, filename, text, mode) |
| 174 | f = pp.parseFile() |
| 175 | if f == nil { |
| 176 | return nil, pp.errors |
| 177 | } |
| 178 | f.Filename = filename |
| 179 | resolve(f, pp.error) |
| 180 | |
| 181 | return |
| 182 | } |
| 183 | |
| 184 | // ParseExpr is a convenience function for parsing an expression. |
| 185 | // The arguments have the same meaning as for Parse, but the source must |
| 186 | // be a valid CUE (type or value) expression. Specifically, fset must not |
| 187 | // be nil. |
| 188 | func ParseExpr(fset *token.FileSet, filename string, src interface{}, mode ...Option) (ast.Expr, error) { |
| 189 | if fset == nil { |
| 190 | panic("ParseExprFrom: no file.FileSet provided (fset == nil)") |
| 191 | } |
| 192 | |
| 193 | // get source |
| 194 | text, err := readSource(filename, src) |
| 195 | if err != nil { |
| 196 | return nil, err |
| 197 | } |
| 198 | |
| 199 | var p parser |
| 200 | defer func() { |
| 201 | if e := recover(); e != nil { |
| 202 | // resume same panic if it's not a bailout |
| 203 | if _, ok := e.(bailout); !ok { |
| 204 | panic(e) |
| 205 | } |
| 206 | } |
| 207 | p.errors.Sort() |
| 208 | err = p.errors.Err() |
| 209 | }() |
| 210 | |
| 211 | // parse expr |
| 212 | p.init(fset, filename, text, mode) |
| 213 | // Set up pkg-level scopes to avoid nil-pointer errors. |
| 214 | // This is not needed for a correct expression x as the |
| 215 | // parser will be ok with a nil topScope, but be cautious |
| 216 | // in case of an erroneous x. |
| 217 | e := p.parseRHS() |
| 218 | |
| 219 | // If a comma was inserted, consume it; |
| 220 | // report an error if there's more tokens. |
| 221 | if p.tok == token.COMMA && p.lit == "\n" { |
| 222 | p.next() |
| 223 | } |
| 224 | if p.mode&partialMode == 0 { |
| 225 | p.expect(token.EOF) |
| 226 | } |
| 227 | |
| 228 | if p.errors.Len() > 0 { |
| 229 | p.errors.Sort() |
| 230 | return nil, p.errors.Err() |
| 231 | } |
| 232 | |
| 233 | return e, nil |
| 234 | } |
| 235 | |
| 236 | // parseExprString is a convenience function for obtaining the AST of an |
| 237 | // expression x. The position information recorded in the AST is undefined. The |
| 238 | // filename used in error messages is the empty string. |
| 239 | func parseExprString(x string) (ast.Expr, error) { |
| 240 | return ParseExpr(token.NewFileSet(), "", []byte(x)) |
| 241 | } |