1
0
mirror of https://github.com/golang/go synced 2024-11-25 15:27:57 -07:00

go/parser: exit early if source file does not contain text

Partial fix for issue 3943.

R=r
CC=golang-dev
https://golang.org/cl/6458115
This commit is contained in:
Robert Griesemer 2012-08-11 21:06:40 -07:00
parent 2253f67157
commit a9d0ff6ead
2 changed files with 20 additions and 2 deletions

View File

@ -90,6 +90,15 @@ func ParseFile(fset *token.FileSet, filename string, src interface{}, mode Mode)
var p parser var p parser
p.init(fset, filename, text, mode) p.init(fset, filename, text, mode)
f := p.parseFile() 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 // sort errors
if p.mode&SpuriousErrors == 0 { if p.mode&SpuriousErrors == 0 {

View File

@ -2285,6 +2285,12 @@ func (p *parser) parseFile() *ast.File {
defer un(trace(p, "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 // package clause
doc := p.leadComment doc := p.leadComment
pos := p.expect(token.PACKAGE) pos := p.expect(token.PACKAGE)
@ -2296,13 +2302,16 @@ func (p *parser) parseFile() *ast.File {
} }
p.expectSemi() 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. // Likely not a Go source file at all.
if p.errors.Len() != 0 {
return nil
}
p.openScope() p.openScope()
p.pkgScope = p.topScope p.pkgScope = p.topScope
var decls []ast.Decl var decls []ast.Decl
if p.errors.Len() == 0 && p.mode&PackageClauseOnly == 0 { if p.mode&PackageClauseOnly == 0 {
// import decls // import decls
for p.tok == token.IMPORT { for p.tok == token.IMPORT {
decls = append(decls, p.parseGenDecl(token.IMPORT, parseImportSpec)) decls = append(decls, p.parseGenDecl(token.IMPORT, parseImportSpec))