package modfile
import (
)
type Position struct {
Line int
LineRune int
Byte int
}
func ( Position) ( string) Position {
.Byte += len()
if := strings.Count(, "\n"); > 0 {
.Line +=
= [strings.LastIndex(, "\n")+1:]
.LineRune = 1
}
.LineRune += utf8.RuneCountInString()
return
}
type Expr interface {
Span() (start, end Position)
Comment() *Comments
}
type Comment struct {
Start Position
Token string
Suffix bool
}
type Comments struct {
Before []Comment
Suffix []Comment
After []Comment
}
func ( *Comments) () *Comments {
return
}
type FileSyntax struct {
Name string
Comments
Stmt []Expr
}
func ( *FileSyntax) () (, Position) {
if len(.Stmt) == 0 {
return
}
, _ = .Stmt[0].Span()
_, = .Stmt[len(.Stmt)-1].Span()
return ,
}
func ( *FileSyntax) ( Expr, ...string) *Line {
if == nil {
:
for , := range slices.Backward(.Stmt) {
switch stmt := .(type) {
case *Line:
if .Token != nil && .Token[0] == [0] {
=
break
}
case *LineBlock:
if .Token[0] == [0] {
=
break
}
}
}
}
:= func( int) *Line {
:= &Line{Token: }
if == len(.Stmt) {
.Stmt = append(.Stmt, )
} else {
.Stmt = append(.Stmt, nil)
copy(.Stmt[+2:], .Stmt[+1:])
.Stmt[+1] =
}
return
}
if != nil {
for , := range .Stmt {
switch stmt := .(type) {
case *Line:
if == {
if .Token == nil || .Token[0] != [0] {
return ()
}
.InBlock = true
:= &LineBlock{Token: .Token[:1], Line: []*Line{}}
.Token = .Token[1:]
.Stmt[] =
:= &Line{Token: [1:], InBlock: true}
.Line = append(.Line, )
return
}
case *LineBlock:
if == {
if .Token[0] != [0] {
return ()
}
:= &Line{Token: [1:], InBlock: true}
.Line = append(.Line, )
return
}
for , := range .Line {
if == {
if .Token[0] != [0] {
return ()
}
.Line = append(.Line, nil)
copy(.Line[+2:], .Line[+1:])
:= &Line{Token: [1:], InBlock: true}
.Line[+1] =
return
}
}
}
}
}
:= &Line{Token: }
.Stmt = append(.Stmt, )
return
}
func ( *FileSyntax) ( *Line, ...string) {
if .InBlock {
= [1:]
}
.Token =
}
func ( *Line) () {
.Token = nil
.Comments.Suffix = nil
}
func ( *FileSyntax) () {
:= 0
for , := range .Stmt {
switch stmt := .(type) {
case *Line:
if .Token == nil {
continue
}
case *LineBlock:
:= 0
for , := range .Line {
if .Token != nil {
.Line[] =
++
}
}
if == 0 {
continue
}
if == 1 && len(.RParen.Comments.Before) == 0 {
*.Line[0] = Line{
Comments: Comments{
Before: commentsAdd(.Before, .Line[0].Before),
Suffix: commentsAdd(.Line[0].Suffix, .Suffix),
After: commentsAdd(.Line[0].After, .After),
},
Token: stringsAdd(.Token, .Line[0].Token),
}
.Stmt[] = .Line[0]
++
continue
}
.Line = .Line[:]
}
.Stmt[] =
++
}
.Stmt = .Stmt[:]
}
func (, []Comment) []Comment {
return append([:len():len()], ...)
}
func (, []string) []string {
return append([:len():len()], ...)
}
type CommentBlock struct {
Comments
Start Position
}
func ( *CommentBlock) () (, Position) {
return .Start, .Start
}
type Line struct {
Comments
Start Position
Token []string
InBlock bool
End Position
}
func ( *Line) () (, Position) {
return .Start, .End
}
type LineBlock struct {
Comments
Start Position
LParen LParen
Token []string
Line []*Line
RParen RParen
}
func ( *LineBlock) () (, Position) {
return .Start, .RParen.Pos.add(")")
}
type LParen struct {
Comments
Pos Position
}
func ( *LParen) () (, Position) {
return .Pos, .Pos.add(")")
}
type RParen struct {
Comments
Pos Position
}
func ( *RParen) () (, Position) {
return .Pos, .Pos.add(")")
}
type input struct {
filename string
complete []byte
remaining []byte
tokenStart []byte
token token
pos Position
comments []Comment
file *FileSyntax
parseErrors ErrorList
pre []Expr
post []Expr
}
func ( string, []byte) *input {
return &input{
filename: ,
complete: ,
remaining: ,
pos: Position{Line: 1, LineRune: 1, Byte: 0},
}
}
func ( string, []byte) ( *FileSyntax, error) {
:= newInput(, )
defer func() {
if := recover(); != nil && != &.parseErrors {
.parseErrors = append(.parseErrors, Error{
Filename: .filename,
Pos: .pos,
Err: fmt.Errorf("internal error: %v", ),
})
}
if == nil && len(.parseErrors) > 0 {
= .parseErrors
}
}()
.readToken()
.parseFile()
if len(.parseErrors) > 0 {
return nil, .parseErrors
}
.file.Name = .filename
.assignComments()
return .file, nil
}
func ( *input) ( string) {
.parseErrors = append(.parseErrors, Error{
Filename: .filename,
Pos: .pos,
Err: errors.New(),
})
panic(&.parseErrors)
}
func ( *input) () bool {
return len(.remaining) == 0
}
func ( *input) () int {
if len(.remaining) == 0 {
return 0
}
, := utf8.DecodeRune(.remaining)
return int()
}
func ( *input) ( string) bool {
for := 0; < len(); ++ {
if >= len(.remaining) || .remaining[] != [] {
return false
}
}
return true
}
func ( *input) () int {
if len(.remaining) == 0 {
.Error("internal lexer error: readRune at EOF")
}
, := utf8.DecodeRune(.remaining)
.remaining = .remaining[:]
if == '\n' {
.pos.Line++
.pos.LineRune = 1
} else {
.pos.LineRune++
}
.pos.Byte +=
return int()
}
type token struct {
kind tokenKind
pos Position
endPos Position
text string
}
type tokenKind int
const (
_EOF tokenKind = -(iota + 1)
_EOLCOMMENT
_IDENT
_STRING
_COMMENT
)
func ( tokenKind) () bool {
return == _COMMENT || == _EOLCOMMENT
}
func ( tokenKind) () bool {
return == _EOF || == _EOLCOMMENT || == '\n'
}
func ( *input) () {
.tokenStart = .remaining
.token.text = ""
.token.pos = .pos
}
func ( *input) ( tokenKind) {
.token.kind =
:= string(.tokenStart[:len(.tokenStart)-len(.remaining)])
if .isComment() {
if strings.HasSuffix(, "\r\n") {
= [:len()-2]
} else {
= strings.TrimSuffix(, "\n")
}
}
.token.text =
.token.endPos = .pos
}
func ( *input) () tokenKind {
return .token.kind
}
func ( *input) () token {
:= .token
.readToken()
return
}
func ( *input) () {
for !.eof() {
:= .peekRune()
if == ' ' || == '\t' || == '\r' {
.readRune()
continue
}
if .peekPrefix("//") {
.startToken()
:= bytes.LastIndex(.complete[:.pos.Byte], []byte("\n"))
:= len(bytes.TrimSpace(.complete[+1:.pos.Byte])) > 0
.readRune()
.readRune()
for len(.remaining) > 0 && .readRune() != '\n' {
}
if ! {
.endToken(_COMMENT)
return
}
.endToken(_EOLCOMMENT)
.comments = append(.comments, Comment{.token.pos, .token.text, })
return
}
if .peekPrefix("/*") {
.Error("mod files must use // comments (not /* */ comments)")
}
break
}
.startToken()
if .eof() {
.endToken(_EOF)
return
}
switch := .peekRune(); {
case '\n', '(', ')', '[', ']', '{', '}', ',':
.readRune()
.endToken(tokenKind())
return
case '"', '`':
:=
.readRune()
for {
if .eof() {
.pos = .token.pos
.Error("unexpected EOF in string")
}
if .peekRune() == '\n' {
.Error("unexpected newline in string")
}
:= .readRune()
if == {
break
}
if == '\\' && != '`' {
if .eof() {
.pos = .token.pos
.Error("unexpected EOF in string")
}
.readRune()
}
}
.endToken(_STRING)
return
}
if := .peekRune(); !isIdent() {
.Error(fmt.Sprintf("unexpected input character %#q", rune()))
}
for isIdent(.peekRune()) {
if .peekPrefix("//") {
break
}
if .peekPrefix("/*") {
.Error("mod files must use // comments (not /* */ comments)")
}
.readRune()
}
.endToken(_IDENT)
}
func ( int) bool {
switch := rune(); {
case ' ', '(', ')', '[', ']', '{', '}', ',':
return false
default:
return !unicode.IsSpace() && unicode.IsPrint()
}
}
func ( *input) ( Expr) {
if != nil {
.pre = append(.pre, )
}
switch x := .(type) {
default:
panic(fmt.Errorf("order: unexpected type %T", ))
case nil:
case *LParen, *RParen:
case *CommentBlock:
case *Line:
case *FileSyntax:
for , := range .Stmt {
.()
}
case *LineBlock:
.(&.LParen)
for , := range .Line {
.()
}
.(&.RParen)
}
if != nil {
.post = append(.post, )
}
}
func ( *input) () {
const = false
.order(.file)
var , []Comment
for , := range .comments {
if .Suffix {
= append(, )
} else {
= append(, )
}
}
if {
for , := range {
fmt.Fprintf(os.Stderr, "LINE %q :%d:%d #%d\n", .Token, .Start.Line, .Start.LineRune, .Start.Byte)
}
}
for , := range .pre {
, := .Span()
if {
fmt.Fprintf(os.Stderr, "pre %T :%d:%d #%d\n", , .Line, .LineRune, .Byte)
}
:= .Comment()
for len() > 0 && .Byte >= [0].Start.Byte {
if {
fmt.Fprintf(os.Stderr, "ASSIGN LINE %q #%d\n", [0].Token, [0].Start.Byte)
}
.Before = append(.Before, [0])
= [1:]
}
}
.file.After = append(.file.After, ...)
if {
for , := range {
fmt.Fprintf(os.Stderr, "SUFFIX %q :%d:%d #%d\n", .Token, .Start.Line, .Start.LineRune, .Start.Byte)
}
}
for , := range slices.Backward(.post) {
, := .Span()
if {
fmt.Fprintf(os.Stderr, "post %T :%d:%d #%d :%d:%d #%d\n", , .Line, .LineRune, .Byte, .Line, .LineRune, .Byte)
}
switch .(type) {
case *FileSyntax:
continue
}
if .Line != .Line {
continue
}
:= .Comment()
for len() > 0 && .Byte <= [len()-1].Start.Byte {
if {
fmt.Fprintf(os.Stderr, "ASSIGN SUFFIX %q #%d\n", [len()-1].Token, [len()-1].Start.Byte)
}
.Suffix = append(.Suffix, [len()-1])
= [:len()-1]
}
}
for , := range .post {
reverseComments(.Comment().Suffix)
}
.file.Before = append(.file.Before, ...)
}
func ( []Comment) {
for , := 0, len()-1; < ; , = +1, -1 {
[], [] = [], []
}
}
func ( *input) () {
.file = new(FileSyntax)
var *CommentBlock
for {
switch .peek() {
case '\n':
.lex()
if != nil {
.file.Stmt = append(.file.Stmt, )
= nil
}
case _COMMENT:
:= .lex()
if == nil {
= &CommentBlock{Start: .pos}
}
:= .Comment()
.Before = append(.Before, Comment{Start: .pos, Token: .text})
case _EOF:
if != nil {
.file.Stmt = append(.file.Stmt, )
}
return
default:
.parseStmt()
if != nil {
.file.Stmt[len(.file.Stmt)-1].Comment().Before = .Before
= nil
}
}
}
}
func ( *input) () {
:= .lex()
:= .pos
:= .endPos
:= []string{.text}
for {
:= .lex()
switch {
case .kind.isEOL():
.file.Stmt = append(.file.Stmt, &Line{
Start: ,
Token: ,
End: ,
})
return
case .kind == '(':
if := .peek(); .isEOL() {
.file.Stmt = append(.file.Stmt, .parseLineBlock(, , ))
return
} else if == ')' {
:= .lex()
if .peek().isEOL() {
.lex()
.file.Stmt = append(.file.Stmt, &LineBlock{
Start: ,
Token: ,
LParen: LParen{Pos: .pos},
RParen: RParen{Pos: .pos},
})
return
}
= append(, .text, .text)
} else {
= append(, .text)
}
default:
= append(, .text)
= .endPos
}
}
}
func ( *input) ( Position, []string, token) *LineBlock {
:= &LineBlock{
Start: ,
Token: ,
LParen: LParen{Pos: .pos},
}
var []Comment
for {
switch .peek() {
case _EOLCOMMENT:
.lex()
case '\n':
.lex()
if len() == 0 && len(.Line) > 0 || len() > 0 && [len()-1].Token != "" {
= append(, Comment{})
}
case _COMMENT:
:= .lex()
= append(, Comment{Start: .pos, Token: .text})
case _EOF:
.Error(fmt.Sprintf("syntax error (unterminated block started at %s:%d:%d)", .filename, .Start.Line, .Start.LineRune))
case ')':
:= .lex()
if len() == 1 && [0] == (Comment{}) {
= nil
}
.RParen.Before =
.RParen.Pos = .pos
if !.peek().isEOL() {
.Error("syntax error (expected newline after closing paren)")
}
.lex()
return
default:
:= .parseLine()
.Line = append(.Line, )
.Comment().Before =
= nil
}
}
}
func ( *input) () *Line {
:= .lex()
if .kind.isEOL() {
.Error("internal parse error: parseLine at end of line")
}
:= .pos
:= .endPos
:= []string{.text}
for {
:= .lex()
if .kind.isEOL() {
return &Line{
Start: ,
Token: ,
End: ,
InBlock: true,
}
}
= append(, .text)
= .endPos
}
}
var (
slashSlash = []byte("//")
moduleStr = []byte("module")
)
func ( []byte) string {
for len() > 0 {
:=
= nil
if := bytes.IndexByte(, '\n'); >= 0 {
, = [:], [+1:]
}
if := bytes.Index(, slashSlash); >= 0 {
= [:]
}
= bytes.TrimSpace()
if !bytes.HasPrefix(, moduleStr) {
continue
}
= [len(moduleStr):]
:= len()
= bytes.TrimSpace()
if len() == || len() == 0 {
continue
}
if [0] == '"' || [0] == '`' {
, := strconv.Unquote(string())
if != nil {
return ""
}
return
}
return string()
}
return ""
}