golang/go · error

syntax error

Error message

syntax error

What it means

The import reader encountered malformed Go syntax while scanning a source file for import declarations. The sentinel error errSyntax is set when the reader hits unexpected tokens or structure while parsing comments, build tags, the package clause, or import blocks. This is a lightweight parser-level error from the imports reader, not a full Go compiler syntax error — it fires during the fast import-scanning pass.

Source

Thrown at src/cmd/go/internal/imports/read.go:44

var bom = []byte{0xef, 0xbb, 0xbf}

func newImportReader(b *bufio.Reader) *importReader {
	// Remove leading UTF-8 BOM.
	// Per https://golang.org/ref/spec#Source_code_representation:
	// a compiler may ignore a UTF-8-encoded byte order mark (U+FEFF)
	// if it is the first Unicode code point in the source text.
	if leadingBytes, err := b.Peek(3); err == nil && bytes.Equal(leadingBytes, bom) {
		b.Discard(3)
	}
	return &importReader{b: b}
}

func isIdent(c byte) bool {
	return 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' || c == '_' || c >= utf8.RuneSelf
}

var (
	errSyntax = errors.New("syntax error")
	errNUL    = errors.New("unexpected NUL in input")
)

// syntaxError records a syntax error, but only if an I/O error has not already been recorded.
func (r *importReader) syntaxError() {
	if r.err == nil {
		r.err = errSyntax
	}
}

// readByte reads the next byte from the input, saves it in buf, and returns it.
// If an error occurs, readByte records the error in r.err and returns 0.
func (r *importReader) readByte() byte {
	c, err := r.b.ReadByte()
	if err == nil {
		r.buf = append(r.buf, c)
		if c == 0 {
			err = errNUL

View on GitHub (pinned to b6b368adc5)

Solutions

  1. Open the source file in question and fix the syntax error — check for unbalanced parens, missing quotes, or invalid tokens
  2. Run gofmt -w or go vet on the file to identify the exact syntax error location
  3. If the file is generated, regenerate it from the source template
  4. Check for encoding issues — ensure UTF-8 without BOM (the reader skips BOM but other encoding issues may persist)
  5. Temporarily exclude the file from scanning if it's not valid Go (e.g., a template file with a .go extension)

Example fix

// before: malformed import block causes syntax error
// package main
// import (
//     "fmt"
//     "os"
// // missing closing paren

// after: fix the syntax
// package main
// import (
//     "fmt"
//     "os"
// )
Defensive patterns

Strategy: validation

Validate before calling

// Validate Go source files before scanning by attempting a parse.
import "go/parser"

func isValidGoSource(path string) error {
    fset := token.NewFileSet()
    _, err := parser.ParseFile(fset, path, nil, parser.AllErrors)
    return err // nil means syntactically valid
}

// For faster pre-checks without full parsing:
func quickSyntaxCheck(path string) error {
    data, err := os.ReadFile(path)
    if err != nil {
        return err
    }
    // Check for balanced parentheses in import blocks
    // Check for BOM (the import reader skips it, but other tools may not)
    if len(data) >= 3 && data[0] == 0xEF && data[1] == 0xBB && data[2] == 0xBF {
        return fmt.Errorf("%s: BOM detected, remove it", path)
    }
    return nil
}

Type guard

// This is a scanning error, returned as the sentinel errSyntax.
// Detect by message since the sentinel is package-private:
func isImportSyntaxError(err error) bool {
    return err != nil && (err.Error() == "syntax error" || strings.Contains(err.Error(), "syntax error"))
}

Try / catch

// For tooling that uses the import scanner:
// err := importReader.Err()
// if isImportSyntaxError(err) {
//     // The source file has syntax errors.
//     // Skip it or report to the user.
//     log.Printf("skipping %s: syntax error", path)
//     continue
// }
//
// For end users: this error surfaces during go list, go build, goimports.
// Fix the source file's syntax to resolve it.

Prevention

When it happens

Trigger: The importReader in imports/read.go encounters invalid token sequences while scanning — a malformed identifier in an import path, unexpected keyword in package or import position, unbalanced parentheses in an import block, or invalid characters where syntax tokens are expected. readByte or parsing logic calls syntaxError() which sets r.err = errSyntax.

Common situations: A .go file with syntax errors that hasn't been compiled yet; a file being scanned during go list or goimports that has partial or templated content; encoding issues with BOM or invalid UTF-8; a generated file that was incompletely written; a file with embedded code in comments that confuses the scanner.

Related errors


AI-assisted analysis of golang/go@b6b368adc5 (2026-08-12). Data as JSON: /api/errors/0c16173199bd67ea. Report an issue: GitHub.