]> Cypherpunks repositories - gostls13.git/commitdiff
go/parser: exit early if source file does not contain text
authorRobert Griesemer <gri@golang.org>
Sun, 12 Aug 2012 04:06:40 +0000 (21:06 -0700)
committerRobert Griesemer <gri@golang.org>
Sun, 12 Aug 2012 04:06:40 +0000 (21:06 -0700)
Partial fix for issue 3943.

R=r
CC=golang-dev
https://golang.org/cl/6458115

src/pkg/go/parser/interface.go
src/pkg/go/parser/parser.go

index 5c203a7846e22b7b2fe583f15cfea034a05a45c7..4a84a97ae7957b478d4eec9004e8916bb81da213 100644 (file)
@@ -90,6 +90,15 @@ func ParseFile(fset *token.FileSet, filename string, src interface{}, mode Mode)
        var p parser
        p.init(fset, filename, text, mode)
        f := p.parseFile()
+       if f == nil {
+               // source is not a valid Go source file - satisfy
+               // ParseFile API and return a valid (but) empty
+               // *ast.File
+               f = &ast.File{
+                       Name:  new(ast.Ident),
+                       Scope: ast.NewScope(nil),
+               }
+       }
 
        // sort errors
        if p.mode&SpuriousErrors == 0 {
index 80f4b5a7a260274630bd6ff9080e76a923adc301..d35a9410a6723be5dec9af4e337eaeac15e8ffe6 100644 (file)
@@ -2285,6 +2285,12 @@ func (p *parser) parseFile() *ast.File {
                defer un(trace(p, "File"))
        }
 
+       // Don't bother parsing the rest if we had errors scanning the first token.
+       // Likely not a Go source file at all.
+       if p.errors.Len() != 0 {
+               return nil
+       }
+
        // package clause
        doc := p.leadComment
        pos := p.expect(token.PACKAGE)
@@ -2296,13 +2302,16 @@ func (p *parser) parseFile() *ast.File {
        }
        p.expectSemi()
 
-       // Don't bother parsing the rest if we had errors already.
+       // Don't bother parsing the rest if we had errors parsing the package clause.
        // Likely not a Go source file at all.
+       if p.errors.Len() != 0 {
+               return nil
+       }
 
        p.openScope()
        p.pkgScope = p.topScope
        var decls []ast.Decl
-       if p.errors.Len() == 0 && p.mode&PackageClauseOnly == 0 {
+       if p.mode&PackageClauseOnly == 0 {
                // import decls
                for p.tok == token.IMPORT {
                        decls = append(decls, p.parseGenDecl(token.IMPORT, parseImportSpec))