Involved Source Filesprint.goread.go
Package modfile implements a parser and formatter for go.mod files.
The go.mod syntax is described in
https://golang.org/cmd/go/#hdr-The_go_mod_file.
The Parse and ParseLax functions both parse a go.mod file and return an
abstract syntax tree. ParseLax ignores unknown statements and may be used to
parse go.mod files that may have been developed with newer versions of Go.
The File struct returned by Parse and ParseLax represent an abstract
go.mod file. File has several methods like AddNewRequire and DropReplace
that can be used to programmatically edit a file.
The Format function formats a File back to a byte slice which can be
written to a file.
Package-Level Type Names (total 25, in which 21 are exported)
/* sort exporteds by: | */
A Comment represents a single // comment.
StartPosition
// an end of line (not whole line) comment
// without trailing newline
func commentsAdd(x, y []Comment) []Comment
func commentsAdd(x, y []Comment) []Comment
func reverseComments(list []Comment)
A CommentBlock represents a top-level block of comments separate
from any rule.
CommentsComments
For top-level expressions only, After lists whole-line
comments following the expression.
// whole-line comments before this expression
// end-of-line comments after this expression
StartPosition
Comment returns the receiver. This isn't useful by itself, but
a Comments struct is embedded into all the expression
implementation types, and this gives each of those a Comment
method to satisfy the Expr interface.
(*T) Span() (start, end Position)
*T : Expr
Comments collects the comments associated with an expression.
For top-level expressions only, After lists whole-line
comments following the expression.
// whole-line comments before this expression
// end-of-line comments after this expression
Comment returns the receiver. This isn't useful by itself, but
a Comments struct is embedded into all the expression
implementation types, and this gives each of those a Comment
method to satisfy the Expr interface.
func (*Comments).Comment() *Comments
func Expr.Comment() *Comments
An Expr represents an input element.
Comment returns the comments attached to the expression.
This method would normally be named 'Comments' but that
would interfere with embedding a type of the same name.
Span returns the start and end position of the expression,
excluding leading or trailing comments.
*CommentBlock
*FileSyntax
*Line
*LineBlock
*LParen
*RParen
func (*FileSyntax).addLine(hint Expr, tokens ...string) *Line
A FileSyntax represents an entire go.mod file.
CommentsComments
For top-level expressions only, After lists whole-line
comments following the expression.
// whole-line comments before this expression
// end-of-line comments after this expression
// file path
Stmt[]Expr
Cleanup cleans up the file syntax x after any edit operations.
To avoid quadratic behavior, removeLine marks the line as dead
by setting line.Token = nil but does not remove it from the slice
in which it appears. After edits have all been indicated,
calling Cleanup cleans out the dead lines.
Comment returns the receiver. This isn't useful by itself, but
a Comments struct is embedded into all the expression
implementation types, and this gives each of those a Comment
method to satisfy the Expr interface.
(*T) Span() (start, end Position)
addLine adds a line containing the given tokens to the file.
If the first token of the hint matches the first token of the
line, the new line is added at the end of the block containing hint,
extracting hint into a new block if it is not yet in one.
If the hint is non-nil buts its first token does not match,
the new line is added after the block containing hint
(or hint itself, if not in a block).
If no hint is provided, addLine appends the line to the end of
the last block with a matching first token,
or to the end of the file if no such block exists.
(*T) removeLine(line *Line)(*T) updateLine(line *Line, tokens ...string)
*T : Expr
func parse(file string, data []byte) (f *FileSyntax, err error)
func Format(f *FileSyntax) []byte
A LineBlock is a factored block of lines, like
require (
"x"
"y"
)
CommentsComments
For top-level expressions only, After lists whole-line
comments following the expression.
// whole-line comments before this expression
// end-of-line comments after this expression
LParenLParenLine[]*LineRParenRParenStartPositionToken[]string
Comment returns the receiver. This isn't useful by itself, but
a Comments struct is embedded into all the expression
implementation types, and this gives each of those a Comment
method to satisfy the Expr interface.
(*T) Span() (start, end Position)
*T : Expr
func parseRetractRationale(block *LineBlock, line *Line) string
func (*File).add(errs *ErrorList, block *LineBlock, line *Line, verb string, args []string, fix VersionFixer, strict bool)
An LParen represents the beginning of a parenthesized line block.
It is a place to store suffix comments.
CommentsComments
For top-level expressions only, After lists whole-line
comments following the expression.
// whole-line comments before this expression
// end-of-line comments after this expression
PosPosition
Comment returns the receiver. This isn't useful by itself, but
a Comments struct is embedded into all the expression
implementation types, and this gives each of those a Comment
method to satisfy the Expr interface.
(*T) Span() (start, end Position)
*T : Expr
A Position describes an arbitrary source position in a file, including the
file, line, column, and byte offset.
// byte in input (starting at 0)
// line in input (starting at 1)
// rune in line (starting at 1)
add returns the position at the end of s, assuming it starts at p.
func (*CommentBlock).Span() (start, end Position)
func Expr.Span() (start, end Position)
func (*FileSyntax).Span() (start, end Position)
func (*Line).Span() (start, end Position)
func (*LineBlock).Span() (start, end Position)
func (*LParen).Span() (start, end Position)
func (*RParen).Span() (start, end Position)
func Position.add(s string) Position
An RParen represents the end of a parenthesized line block.
It is a place to store whole-line (before) comments.
CommentsComments
For top-level expressions only, After lists whole-line
comments following the expression.
// whole-line comments before this expression
// end-of-line comments after this expression
PosPosition
Comment returns the receiver. This isn't useful by itself, but
a Comments struct is embedded into all the expression
implementation types, and this gives each of those a Comment
method to satisfy the Expr interface.
(*T) Span() (start, end Position)
*T : Expr
A VersionInterval represents a range of versions with upper and lower bounds.
Intervals are closed: both bounds are included. When Low is equal to High,
the interval may refer to a single version ('v1.2.3') or an interval
('[v1.2.3, v1.2.3]'); both have the same representation.
HighstringLowstring
func parseVersionInterval(verb string, args *[]string, fix VersionFixer) (VersionInterval, error)
func (*File).AddRetract(vi VersionInterval, rationale string) error
func (*File).DropRetract(vi VersionInterval) error
An input represents a single input file being parsed.
// accumulated comments
// entire input
Parser state.
// returned top-level syntax tree
Lexing state.
// name of input file, for errors
// errors encountered during parsing
// current input position
// all expressions, in postorder traversal
Comment assignment state.
// all expressions, in preorder traversal
// remaining input
// next token to be returned by lex, peek
// token being scanned to end of input
Error is called to report an error.
Error does not return: it panics.
assignComments attaches comments to nearby syntax.
endToken marks the end of an input token.
It records the actual token string in tok.text.
A single trailing newline (LF or CRLF) will be removed from comment tokens.
eof reports whether the input has reached end of file.
lex is called from the parser to obtain the next input token.
order walks the expression adding it and its subexpressions to the
preorder and postorder lists.
(*T) parseFile()(*T) parseLine() *Line(*T) parseLineBlock(start Position, token []string, lparen token) *LineBlock(*T) parseStmt()
peek returns the kind of the the next token returned by lex.
peekPrefix reports whether the remaining input begins with the given prefix.
peekRune returns the next rune in the input without consuming it.
readRune consumes and returns the next rune in the input.
readToken lexes the next token from the text and stores it in in.token.
startToken marks the beginning of the next input token.
It must be followed by a call to endToken, once the token's text has
been consumed using readRune.
func newInput(filename string, data []byte) *input
A printer collects the state during printing of a file or expression.
// output buffer
// contents are the bytes buf[off : len(buf)]
// last read operation, so that Unread* can work correctly.
// read at &buf[off], write at &buf[len(buf)]
// pending end-of-line comments
// left margin (indent), a number of tabs
Bytes returns a slice of length b.Len() holding the unread portion of the buffer.
The slice is valid for use only until the next buffer modification (that is,
only until the next call to a method like Read, Write, Reset, or Truncate).
The slice aliases the buffer content at least until the next buffer modification,
so immediate changes to the slice will affect the result of future reads.
Cap returns the capacity of the buffer's underlying byte slice, that is, the
total space allocated for the buffer's data.
Grow grows the buffer's capacity, if necessary, to guarantee space for
another n bytes. After Grow(n), at least n bytes can be written to the
buffer without another allocation.
If n is negative, Grow will panic.
If the buffer can't grow it will panic with ErrTooLarge.
Len returns the number of bytes of the unread portion of the buffer;
b.Len() == len(b.Bytes()).
Next returns a slice containing the next n bytes from the buffer,
advancing the buffer as if the bytes had been returned by Read.
If there are fewer than n bytes in the buffer, Next returns the entire buffer.
The slice is only valid until the next call to a read or write method.
Read reads the next len(p) bytes from the buffer or until the buffer
is drained. The return value n is the number of bytes read. If the
buffer has no data to return, err is io.EOF (unless len(p) is zero);
otherwise it is nil.
ReadByte reads and returns the next byte from the buffer.
If no byte is available, it returns error io.EOF.
ReadBytes reads until the first occurrence of delim in the input,
returning a slice containing the data up to and including the delimiter.
If ReadBytes encounters an error before finding a delimiter,
it returns the data read before the error and the error itself (often io.EOF).
ReadBytes returns err != nil if and only if the returned data does not end in
delim.
ReadFrom reads data from r until EOF and appends it to the buffer, growing
the buffer as needed. The return value n is the number of bytes read. Any
error except io.EOF encountered during the read is also returned. If the
buffer becomes too large, ReadFrom will panic with ErrTooLarge.
ReadRune reads and returns the next UTF-8-encoded
Unicode code point from the buffer.
If no bytes are available, the error returned is io.EOF.
If the bytes are an erroneous UTF-8 encoding, it
consumes one byte and returns U+FFFD, 1.
ReadString reads until the first occurrence of delim in the input,
returning a string containing the data up to and including the delimiter.
If ReadString encounters an error before finding a delimiter,
it returns the data read before the error and the error itself (often io.EOF).
ReadString returns err != nil if and only if the returned data does not end
in delim.
Reset resets the buffer to be empty,
but it retains the underlying storage for use by future writes.
Reset is the same as Truncate(0).
String returns the contents of the unread portion of the buffer
as a string. If the Buffer is a nil pointer, it returns "<nil>".
To build strings more efficiently, see the strings.Builder type.
Truncate discards all but the first n unread bytes from the buffer
but continues to use the same allocated storage.
It panics if n is negative or greater than the length of the buffer.
UnreadByte unreads the last byte returned by the most recent successful
read operation that read at least one byte. If a write has happened since
the last read, if the last read returned an error, or if the read read zero
bytes, UnreadByte returns an error.
UnreadRune unreads the last rune returned by ReadRune.
If the most recent read or write operation on the buffer was
not a successful ReadRune, UnreadRune returns an error. (In this regard
it is stricter than UnreadByte, which will unread the last byte
from any read operation.)
Write appends the contents of p to the buffer, growing the buffer as
needed. The return value n is the length of p; err is always nil. If the
buffer becomes too large, Write will panic with ErrTooLarge.
WriteByte appends the byte c to the buffer, growing the buffer as needed.
The returned error is always nil, but is included to match bufio.Writer's
WriteByte. If the buffer becomes too large, WriteByte will panic with
ErrTooLarge.
WriteRune appends the UTF-8 encoding of Unicode code point r to the
buffer, returning its length and an error, which is always nil but is
included to match bufio.Writer's WriteRune. The buffer is grown as needed;
if it becomes too large, WriteRune will panic with ErrTooLarge.
WriteString appends the contents of s to the buffer, growing the buffer as
needed. The return value n is the length of s; err is always nil. If the
buffer becomes too large, WriteString will panic with ErrTooLarge.
WriteTo writes data to w until the buffer is drained or an error occurs.
The return value n is the number of bytes written; it always fits into an
int, but it is int64 to match the io.WriterTo interface. Any error
encountered during the write is also returned.
empty reports whether the unread portion of the buffer is empty.
(*T) expr(x Expr)
file formats the given file into the print buffer.
grow grows the buffer to guarantee space for n more bytes.
It returns the index where bytes should be written.
If the buffer can't grow it will panic with ErrTooLarge.
indent returns the position on the current line, in bytes, 0-indexed.
newline ends the current line, flushing end-of-line comments.
printf prints to the buffer.
readSlice is like ReadBytes but returns a reference to internal buffer data.
(*T) tokens(tokens []string)
trim removes trailing spaces and tabs from the current line.
tryGrowByReslice is a inlineable version of grow for the fast-case where the
internal buffer only needs to be resliced.
It returns the index where bytes should be written and whether it succeeded.
*T : compress/flate.Reader
*T : expvar.Var
*T : fmt.Stringer
*T : github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband.Progress
*T : github.com/jbenet/go-context/io.Reader
*T : github.com/jbenet/go-context/io.Writer
*T : image/jpeg.Reader
*T : io.ByteReader
*T : io.ByteScanner
*T : io.ByteWriter
*T : io.Reader
*T : io.ReaderFrom
*T : io.ReadWriter
*T : io.RuneReader
*T : io.RuneScanner
*T : io.StringWriter
*T : io.Writer
*T : io.WriterTo
*T : golang.org/x/net/html.writer
*T : golang.org/x/net/http2.pipeBuffer
*T : golang.org/x/net/http2.stringWriter
*T : context.stringer
*T : github.com/aws/aws-sdk-go/aws/corehandlers.lener
*T : github.com/go-redis/redis/v8/internal/proto.writer
*T : github.com/prometheus/common/expfmt.enhancedWriter
*T : net/http.http2pipeBuffer
*T : net/http.http2stringWriter
*T : runtime.stringer
Package-Level Functions (total 23, in which 7 are exported)
AutoQuote returns s or, if quoting is required for s to appear in a go.mod,
the quotation of s.
Format returns a go.mod file as a byte slice, formatted in standard style.
IsDirectoryPath reports whether the given path should be interpreted
as a directory path. Just like on the go command line, relative paths
and rooted paths are directory paths; the rest are module paths.
ModulePath returns the module path from the gomod file text.
If it cannot find a module path, it returns an empty string.
It is tolerant of unrelated problems in the go.mod file.
MustQuote reports whether s must be quoted in order to appear as
a single token in a go.mod line.
Parse parses the data, reported in errors as being from file,
into a File struct. It applies fix, if non-nil, to canonicalize all module versions found.
ParseLax is like Parse but ignores unknown statements.
It is used when parsing go.mod files other than the main module,
under the theory that most statement types we add in the future will
only apply in the main module, like exclude and replace,
and so we get better gradual deployments if old go commands
simply ignore those statements when found in go.mod files
in dependencies.
isIdent reports whether c is an identifier rune.
We treat most printable runes as identifier runes, except for a handful of
ASCII punctuation characters.
isIndirect reports whether line has a "// indirect" comment,
meaning it is in go.mod only for its effect on indirect dependencies,
so that it can be dropped entirely once the effective version of the
indirect dependency reaches the given minimum version.
lineLess returns whether li should be sorted before lj. It sorts
lexicographically without assigning any special meaning to tokens.
lineRetractLess returns whether li should be sorted before lj for lines in
a "retract" block. It treats each line as a version interval. Single versions
are compared as if they were intervals with the same low and high version.
Intervals are sorted in descending order, first by low version, then by
high version, using semver.Compare.
parseRetractRationale extracts the rationale for a retract directive from the
surrounding comments. If the line does not have comments and is part of a
block that does have comments, the block's comments are used.
The pages are generated with Goldsv0.3.2-preview. (GOOS=darwin GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds.