Documentation
¶
Overview ¶
Package protocompile provides the entry point for a high performance native Go protobuf compiler. "Compile" in this case just means parsing and validating source and generating fully-linked descriptors in the end. Unlike the protoc command-line tool, this package does not try to use the descriptors to perform code generation.
The various sub-packages represent the various compile phases and contain models for the intermediate results. Those phases follow:
- Parse into AST. Also see: parser.Parse
- Convert AST to unlinked descriptor protos. Also see: parser.ResultFromAST
- Link descriptor protos into "rich" descriptors. Also see: linker.Link
- Interpret custom options. Also see: options.InterpretOptions
- Generate source code info. Also see: sourceinfo.GenerateSourceInfo
This package provides an easy-to-use interface that does all the relevant phases, based on the inputs given. If an input is provided as source, all phases apply. If an input is provided as a descriptor proto, only phases 3 to 5 apply. Nothing is necessary if provided a linked descriptor (which is usually only the case for select system dependencies).
This package is also capable of taking advantage of multiple CPU cores, so a compilation involving thousands of files can be done very quickly by compiling things in parallel.
Resolvers ¶
A Resolver is how the compiler locates artifacts that are inputs to the compilation. For example, it can load protobuf source code that must be processed. A Resolver could also supply some already-compiled dependencies as fully-linked descriptors, alleviating the need to re-compile them.
A Resolver can provide any of the following in response to a query for an input.
- Source code: If a resolver answers a query with protobuf source, the compiler will parse and compile it.
- AST: If a resolver answers a query with an AST, the parsing step can be skipped, and the rest of the compilation steps will be applied.
- Descriptor proto: If a resolver answers a query with an unlinked proto, only the other compilation steps, including linking, need to be applied.
- Descriptor: If a resolver answers a query with a fully-linked descriptor, nothing further needs to be done. The descriptor is used as-is.
Compilation will use the Resolver to load the files that are to be compiled and also to load all dependencies (i.e. other files imported by those being compiled).
Compiler ¶
A Compiler accepts a list of file names and produces the list of descriptors. A Compiler has several fields that control how it works but only the Resolver field is required. A minimal Compiler, that resolves files by loading them from the file system based on the current working directory, can be had with the following simple snippet:
compiler := protocompile.Compiler{
Resolver: &protocompile.SourceResolver{},
}
This minimal Compiler will use default parallelism, equal to the number of CPU cores detected; it will not generate source code info in the resulting descriptors; and it will fail fast at the first sign of any error. All of these aspects can be customized by setting other fields.
Index ¶
- Constants
- func IsEditionSupported(edition descriptorpb.Edition) bool
- func RegisterExperimentalCompile(...)deprecated
- func SourceAccessorFromMap(srcs map[string]string) func(string) (io.ReadCloser, error)
- type Compiler
- type CompositeResolver
- type PanicErrordeprecated
- type Resolver
- type ResolverFunc
- type SearchResult
- type SourceInfoMode
- type SourceResolver
Constants ¶
const ( // SourceInfoNone indicates that no source code info is generated. SourceInfoNone = SourceInfoMode(0) // SourceInfoStandard indicates that the standard source code info is // generated, which includes comments only for complete declarations. SourceInfoStandard = SourceInfoMode(1) // SourceInfoExtraComments is currently treated the same as // SourceInfoStandard on the experimental pipeline. SourceInfoExtraComments = SourceInfoMode(2) // SourceInfoExtraOptionLocations indicates that source code info is // generated with additional locations for elements inside of message // literals in option values. This can be combined with the above by // bitwise-OR'ing. SourceInfoExtraOptionLocations = SourceInfoMode(4) )
Variables ¶
This section is empty.
Functions ¶
func IsEditionSupported ¶
func IsEditionSupported(edition descriptorpb.Edition) bool
IsEditionSupported returns true if this module can compile sources for the given edition. This returns true for the special EDITION_PROTO2 and EDITION_PROTO3 as well as all actual editions supported.
func RegisterExperimentalCompile
deprecated
func RegisterExperimentalCompile(fn func(ctx context.Context, c *Compiler, files []string) (linker.Files, error))
RegisterExperimentalCompile is preserved as a compatibility shim for pre-Track-C callers that wired the experimental pipeline by hand. It now delegates to exphook.Register; new code should use exphook.Register (via a blank import of `experimentalcompile`).
Deprecated: use a blank import of `github.com/trendvidia/protocompile/experimentalcompile`. This function will be removed in a future release.
func SourceAccessorFromMap ¶
SourceAccessorFromMap returns a function that can be used as the Accessor field of a SourceResolver that uses the given map to load source. The map keys are file names and the values are the corresponding file contents.
The given map is used directly and not copied. Since accessor functions must be thread-safe, this means that the provided map must not be mutated once this accessor is provided to a compile operation.
Types ¶
type Compiler ¶
type Compiler struct {
// Resolver locates source code for the files to be compiled and
// their dependencies. The only field of [SearchResult] that the
// experimental pipeline honours is `Source`.
Resolver Resolver
// MaxParallelism is reserved for forwards compatibility and is
// currently ignored — the experimental pipeline manages its own
// parallelism via the incremental query executor.
MaxParallelism int
// Reporter receives error and warning diagnostics, with source
// positions attached. If nil, a default reporter is used that fails
// compilation on the first error and ignores warnings.
//
// The legacy reporter contract holds: if the reporter's Error
// method returns nil, compilation continues so that as many
// diagnostics as possible are reported, and Compile returns the
// files that did compile — with nil placeholders in the slots of
// files that didn't — alongside [reporter.ErrInvalidSource]. If the
// Error method returns a non-nil error, the batch aborts
// immediately with that error.
Reporter reporter.Reporter
// SourceInfoMode controls whether and how source-code-info is
// emitted in the resulting descriptors.
SourceInfoMode SourceInfoMode
// Symbols, when non-nil, accumulates every compiled file. A
// duplicate-symbol collision across this and previous Compile
// calls surfaces as an error.
Symbols *linker.Symbols
// RetainASTs causes the returned [linker.File] values to also
// implement `experimentalcompile.IRHolder`, exposing the
// experimental IR (and AST) via a type assertion. If false, ASTs
// may be garbage-collected after Compile returns.
RetainASTs bool
// NullMask, when non-nil, selects the files whose messages get a
// generated `_null` field of type google.protobuf.FieldMask, the
// field PXF decoders record null fields in so that a null survives
// protobuf binary (protocompile#248). A message gets one when it has
// a field able to hold a PXF null and declares no `_null` itself;
// an authored field that takes the mask's number or JSON name is an
// error, and a range or name the author reserved over it is a
// warning that leaves the message without one. google/protobuf/
// files never get one; a caller that also compiles its own canonical
// schemas from source leaves them out by returning false for their
// paths. Nil, the default, generates none: the owner decided on #248
// (2026-10-28) that protocompile's output stays identical to protoc's
// unless a caller asks, and protowire's tools ask.
NullMask func(path string) bool
}
Compiler turns protobuf source files into fully linked descriptors via the experimental parser/ir/fdp pipeline. (The legacy parser/linker/options/sourceinfo pipeline was deleted in Track C of the M1 migration.)
func (*Compiler) Compile ¶
Compile compiles the given file names into fully-linked descriptors. The compiler's Resolver is used to locate source code; the experimental pipeline reads the resolver's `Source` field.
Elements in the returned files implement `experimentalcompile.IRHolder` when Compiler.RetainASTs is true.
type CompositeResolver ¶
type CompositeResolver []Resolver
CompositeResolver is a slice of resolvers, which are consulted in order until one can supply a result. If none of the constituent resolvers can supply a result, the error returned by the first resolver is returned. If the slice of resolvers is empty, all operations return protoregistry.NotFound.
func (CompositeResolver) FindFileByPath ¶
func (f CompositeResolver) FindFileByPath(path string) (SearchResult, error)
type PanicError
deprecated
PanicError is preserved for backwards compatibility with callers that referenced it. The experimental pipeline reports panics as internal-compiler-error diagnostics through the [Reporter] instead of returning a PanicError, so this type is no longer produced by [Compile].
Deprecated: PanicError will be removed in a future release.
type Resolver ¶
type Resolver interface {
// FindFileByPath searches for information for the given file path. If no
// result is available, it should return a non-nil error, such as
// protoregistry.NotFound.
FindFileByPath(path string) (SearchResult, error)
}
Resolver is used by the compiler to resolve a proto source file name into some unit that is usable by the compiler. The result could be source for a proto file or it could be an already-parsed AST or descriptor.
Resolver implementations must be thread-safe as a single compilation operation could invoke FindFileByPath from multiple goroutines.
func WithStandardImports ¶
WithStandardImports returns a new resolver that knows about the same standard imports that are included with protoc.
The standard files are served as **source**, from the copies embedded in this module, so they carry everything source carries — including the extension declarations on "google/protobuf/descriptor.proto" that prevent a source file from illegally re-defining the custom features for C++, Java, and Go.
It previously answered with runtime descriptors from generated code, which do not retain extension declarations — those exist only in source. While SearchResult.Desc was inert that made no difference, because the compiler's own built-in copies served these paths instead. Once Desc was honoured the declaration-less descriptors would have won and silently dropped that guard, so the source form is served directly (see #155).
The set of paths served is unchanged. This now behaves equivalently to github.com/trendvidia/protocompile/wellknownimports.WithStandardImports, which composes a source resolver over the same embedded files; prefer either, and note that the compiler already falls back to these files for an import no resolver answers.
type ResolverFunc ¶
type ResolverFunc func(string) (SearchResult, error)
ResolverFunc is a simple function type that implements Resolver.
func (ResolverFunc) FindFileByPath ¶
func (f ResolverFunc) FindFileByPath(path string) (SearchResult, error)
type SearchResult ¶
type SearchResult struct {
// Source carries the file's source bytes. The pipeline reads from this
// and treats a nil reader (with no error) as not-found.
//
// When set, Source wins: Proto and Desc are not consulted.
Source io.Reader
// Proto carries the file as a descriptor, which is rendered back to
// source and compiled. Used only when Source is nil.
Proto *descriptorpb.FileDescriptorProto
// Desc carries the file as a linked descriptor — the shape of the
// `protoregistry.GlobalFiles` pattern — which is rendered back to
// source and compiled. Used only when Source and Proto are nil.
Desc protoreflect.FileDescriptor
}
SearchResult represents information about a proto source file.
A resolver answers with exactly one of the fields below; a wholly zero SearchResult (with no error) means not-found.
After Track C of the M1 migration the pipeline itself reads source bytes and nothing else. `Proto` and `Desc` remain supported: a descriptor supplied through either is rendered back to source and compiled. That rendering is all-or-nothing — a descriptor carrying something that cannot be expressed in source produces an error naming the file and the reason, never a silent not-found.
The pre-Track-C `AST` and `ParseResult` fields, which carried the legacy AST and parser-result types, were removed along with the legacy `ast/` and `parser/` packages.
type SourceInfoMode ¶
type SourceInfoMode int
SourceInfoMode indicates how source code info is generated by a Compiler.
type SourceResolver ¶
type SourceResolver struct {
// Optional list of import paths. If present and not empty, then all
// file paths to find are assumed to be relative to one of these paths.
// If nil or empty, all file paths to find are assumed to be relative to
// the current working directory.
ImportPaths []string
// Optional function for returning a file's contents. If nil, then
// os.Open is used to open files on the file system.
//
// This function must be thread-safe as a single compilation operation
// could result in concurrent invocations of this function from
// multiple goroutines.
Accessor func(path string) (io.ReadCloser, error)
}
SourceResolver can resolve file names by returning source code. It uses an optional list of import paths to search. By default, it searches the file system.
func (*SourceResolver) FindFileByPath ¶
func (r *SourceResolver) FindFileByPath(path string) (SearchResult, error)
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package ast is a high-performance implementation of a Protobuf IDL abstract syntax tree.
|
Package ast is a high-performance implementation of a Protobuf IDL abstract syntax tree. |
|
edit
Package edit applies declaration-level mutations to a Protobuf AST before it is rendered.
|
Package edit applies declaration-level mutations to a Protobuf AST before it is rendered. |
|
predeclared
Package predeclared provides all of the identifiers with a special meaning in Protobuf.
|
Package predeclared provides all of the identifiers with a special meaning in Protobuf. |
|
printer
Package printer renders an ast.File (or an individual ast.DeclAny) back to protobuf source text.
|
Package printer renders an ast.File (or an individual ast.DeclAny) back to protobuf source text. |
|
syntax
Package syntax specifies all of the syntax pragmas (including editions) that Protocompile understands.
|
Package syntax specifies all of the syntax pragmas (including editions) that Protocompile understands. |
|
Package catalogs implements the reference loader for protowire locale catalog sources (RFC-001 §7).
|
Package catalogs implements the reference loader for protowire locale catalog sources (RFC-001 §7). |
|
cmd
|
|
|
protocollide
command
Command protocollide reports Protobuf namespace collisions between modules, so that two modules vendoring the same `.proto` are caught in CI rather than as an `init()` panic in whatever binary first links both.
|
Command protocollide reports Protobuf namespace collisions between modules, so that two modules vendoring the same `.proto` are caught in CI rather than as an `init()` panic in whatever binary first links both. |
|
Package collide detects Protobuf namespace collisions between modules.
|
Package collide detects Protobuf namespace collisions between modules. |
|
Package dom is a Go port of https://github.com/mcy/strings/tree/main/allman, a high-performance meta-formatting library.
|
Package dom is a Go port of https://github.com/mcy/strings/tree/main/allman, a high-performance meta-formatting library. |
|
Package engineconfig implements the reference loader for protowire project-level engine configuration (RFC-001 §9.4).
|
Package engineconfig implements the reference loader for protowire project-level engine configuration (RFC-001 §9.4). |
|
Package experimentalcompile registers the experimental Compile implementation with the legacy [protocompile.Compiler] so that [protocompile.Compiler.UseExperimentalParser] becomes a working flag instead of returning an error.
|
Package experimentalcompile registers the experimental Compile implementation with the legacy [protocompile.Compiler] so that [protocompile.Compiler.UseExperimentalParser] becomes a working flag instead of returning an error. |
|
Package expr provides an abstract syntax tree implementation for an expression language.
|
Package expr provides an abstract syntax tree implementation for an expression language. |
|
Package fdp provides functionality for lowering the IR to a FileDescriptorSet.
|
Package fdp provides functionality for lowering the IR to a FileDescriptorSet. |
|
gen
|
|
|
Package id provides helpers for working with node-oriented data structures (such as ASTs and graphs) using compressed pointers (IDs).
|
Package id provides helpers for working with node-oriented data structures (such as ASTs and graphs) using compressed pointers (IDs). |
|
Package incremental implements a query-oriented incremental compilation framework.
|
Package incremental implements a query-oriented incremental compilation framework. |
|
queries
Package queries provides specific incremental.Query types for various parts of Protocompile.
|
Package queries provides specific incremental.Query types for various parts of Protocompile. |
|
arena
Package arena defines an Arena type with compressed pointers.
|
Package arena defines an Arena type with compressed pointers. |
|
cases
Package cases provides functions for inter-converting between different case styles.
|
Package cases provides functions for inter-converting between different case styles. |
|
cycle
Package cycle contains internal helpers for dealing with dependency cycles.
|
Package cycle contains internal helpers for dealing with dependency cycles. |
|
decimal
Package decimal provides a big decimal type, i.e., a version of big.Float which works on a base 10 exponent, rather than base 2, allowing it to represent values such as 0.1 exactly.
|
Package decimal provides a big decimal type, i.e., a version of big.Float which works on a base 10 exponent, rather than base 2, allowing it to represent values such as 0.1 exactly. |
|
descsrc
Package descsrc renders a descriptorpb.FileDescriptorProto back into Protobuf source text.
|
Package descsrc renders a descriptorpb.FileDescriptorProto back into Protobuf source text. |
|
editions
Package editions contains helpers related to resolving features for Protobuf editions.
|
Package editions contains helpers related to resolving features for Protobuf editions. |
|
enum
command
enum is a helper for generating boilerplate related to Go enums.
|
enum is a helper for generating boilerplate related to Go enums. |
|
erredition
Package erredition defines common diagnostics for issuing errors about the wrong edition being used.
|
Package erredition defines common diagnostics for issuing errors about the wrong edition being used. |
|
errtoken
Package errtoken contains standard diagnostics involving tokens, usually emitted by the lexer.
|
Package errtoken contains standard diagnostics involving tokens, usually emitted by the lexer. |
|
exphook
Package exphook is the minimal contract between the root `protocompile` package and the `experimentalcompile` package.
|
Package exphook is the minimal contract between the root `protocompile` package and the `experimentalcompile` package. |
|
ext/bigx
Package bigx provides direct access to arithmetic primitives from math/big.
|
Package bigx provides direct access to arithmetic primitives from math/big. |
|
ext/bitsx
Package bitsx contains extensions to Go's package math/bits.
|
Package bitsx contains extensions to Go's package math/bits. |
|
ext/cmpx
package cmpx contains extensions to Go's package cmp.
|
package cmpx contains extensions to Go's package cmp. |
|
ext/iterx
Package iterx contains extensions to Go's package iter.
|
Package iterx contains extensions to Go's package iter. |
|
ext/mapsx
package mapsx contains extensions to Go's package maps.
|
package mapsx contains extensions to Go's package maps. |
|
ext/osx
Package osx contains extensions to the os package.
|
Package osx contains extensions to the os package. |
|
ext/slicesx
Package slicesx contains extensions to Go's package slices.
|
Package slicesx contains extensions to Go's package slices. |
|
ext/stringsx
Package stringsx contains extensions to Go's package strings.
|
Package stringsx contains extensions to Go's package strings. |
|
ext/unsafex
Package unsafex contains extensions to Go's package unsafe.
|
Package unsafex contains extensions to Go's package unsafe. |
|
featuresext
Package featuresext provides file descriptors for the "google/protobuf/cpp_features.proto" and "google/protobuf/java_features.proto" standard import files.
|
Package featuresext provides file descriptors for the "google/protobuf/cpp_features.proto" and "google/protobuf/java_features.proto" standard import files. |
|
golden
Package golden provides a framework for writing file-based golden tests.
|
Package golden provides a framework for writing file-based golden tests. |
|
intern
Package intern provides an interning table abstraction to optimize symbol resolution.
|
Package intern provides an interning table abstraction to optimize symbol resolution. |
|
just
package just adds a "justification" helper for diagnostics.
|
package just adds a "justification" helper for diagnostics. |
|
protoc
Package protoc contains some helpers for invoking protoc from tests.
|
Package protoc contains some helpers for invoking protoc from tests. |
|
tags
Package tag contains all of the numeric field and enum value tag numbers from descriptor.proto.
|
Package tag contains all of the numeric field and enum value tag numbers from descriptor.proto. |
|
tags/gen
command
|
|
|
taxa
Package taxa (plural of taxon, an element of a taxonomy) provides support for classifying Protobuf syntax productions for use in the parser and in diagnostics.
|
Package taxa (plural of taxon, an element of a taxonomy) provides support for classifying Protobuf syntax productions for use in the parser and in diagnostics. |
|
testing/googleapis
Package googleapis makes a checked-in download of https://github.com/googleapis/googleapis available for use by tests.
|
Package googleapis makes a checked-in download of https://github.com/googleapis/googleapis available for use by tests. |
|
testing/googleapis/gen
command
|
|
|
testing/protoctest
Package protoctest wraps protocompile.Compiler behind a tiny abstraction the sweep harness can use.
|
Package protoctest wraps protocompile.Compiler behind a tiny abstraction the sweep harness can use. |
|
tokenmeta
Package meta defines internal metadata types shared between the token package and the lexer.
|
Package meta defines internal metadata types shared between the token package and the lexer. |
|
toposort
Package toposort provides a generic topological sort implementation.
|
Package toposort provides a generic topological sort implementation. |
|
Package ir defines the intermediate representation used by Protocompile.
|
Package ir defines the intermediate representation used by Protocompile. |
|
presence
Package presence provides Kind, which denotes the way in which a field can be present in a Protobuf message.
|
Package presence provides Kind, which denotes the way in which a field can be present in a Protobuf message. |
|
sourceinfo
Package sourceinfo contains decoding operations for Protobuf descriptor SourceCodeInfo paths.
|
Package sourceinfo contains decoding operations for Protobuf descriptor SourceCodeInfo paths. |
|
sourceinfo/decode
command
decode is a helper tool for ingesting an encoded FileDescriptorSet and dumping its SourceCodeInfo in a readable format.
|
decode is a helper tool for ingesting an encoded FileDescriptorSet and dumping its SourceCodeInfo in a readable format. |
|
Package linker contains logic and APIs related to linking a protobuf file.
|
Package linker contains logic and APIs related to linking a protobuf file. |
|
Package protoutil contains useful functions for interacting with descriptors.
|
Package protoutil contains useful functions for interacting with descriptors. |
|
Package report provides a robust diagnostics framework.
|
Package report provides a robust diagnostics framework. |
|
rtags
Package rtags defines publicly-exposed diagnostic tag constants for use with [report.Tag].
|
Package rtags defines publicly-exposed diagnostic tag constants for use with [report.Tag]. |
|
Package reporter contains the types used for reporting errors from protocompile operations.
|
Package reporter contains the types used for reporting errors from protocompile operations. |
|
Package seq provides an interface for sequence-like types that can be indexed and inserted into.
|
Package seq provides an interface for sequence-like types that can be indexed and inserted into. |
|
Package source provides a standard interfaces for working with source files and spans within them.
|
Package source provides a standard interfaces for working with source files and spans within them. |
|
length
Package length provides various length that can be used for configuring the behavior of line/column calculations.
|
Package length provides various length that can be used for configuring the behavior of line/column calculations. |
|
Package token provides a memory-efficient representation of a token tree stream for the Protobuf IDL.
|
Package token provides a memory-efficient representation of a token tree stream for the Protobuf IDL. |
|
keyword
Package keyword provides Keyword, an enum of all special "grammar particles" (i.e., literal tokens with special meaning in the grammar such as identifier keywords and punctuation) recognized by Protocompile.
|
Package keyword provides Keyword, an enum of all special "grammar particles" (i.e., literal tokens with special meaning in the grammar such as identifier keywords and punctuation) recognized by Protocompile. |
|
Package walk provides helper functions for traversing all elements in a protobuf file descriptor.
|
Package walk provides helper functions for traversing all elements in a protobuf file descriptor. |
|
Package wellknownimports provides source code for the well-known import files for use with a protocompile.Compiler.
|
Package wellknownimports provides source code for the well-known import files for use with a protocompile.Compiler. |
|
fs
Package fs hosts the embedded source code for the well-known import files (`google/protobuf/*.proto`) and the matching pre-built FileDescriptorSet, packaged so consumers can pick them up *without* pulling in the `protocompile` root package.
|
Package fs hosts the embedded source code for the well-known import files (`google/protobuf/*.proto`) and the matching pre-built FileDescriptorSet, packaged so consumers can pick them up *without* pulling in the `protocompile` root package. |