// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package modfile

import (
	
	
	
)

// A WorkFile is the parsed, interpreted form of a go.work file.
type WorkFile struct {
	Go        *Go
	Toolchain *Toolchain
	Godebug   []*Godebug
	Use       []*Use
	Replace   []*Replace

	Syntax *FileSyntax
}

// A Use is a single directory statement.
type Use struct {
	Path       string // Use path of module.
	ModulePath string // Module path in the comment.
	Syntax     *Line
}

// ParseWork parses and returns a go.work file.
//
// file is the name of the file, used in positions and errors.
//
// data is the content of the file.
//
// fix is an optional function that canonicalizes module versions.
// If fix is nil, all module versions must be canonical ([module.CanonicalVersion]
// must return the same string).
func ( string,  []byte,  VersionFixer) (*WorkFile, error) {
	,  := parse(, )
	if  != nil {
		return nil, 
	}
	 := &WorkFile{
		Syntax: ,
	}
	var  ErrorList

	for ,  := range .Stmt {
		switch x := .(type) {
		case *Line:
			.add(&, , .Token[0], .Token[1:], )

		case *LineBlock:
			if len(.Token) > 1 {
				 = append(, Error{
					Filename: ,
					Pos:      .Start,
					Err:      fmt.Errorf("unknown block type: %s", strings.Join(.Token, " ")),
				})
				continue
			}
			switch .Token[0] {
			default:
				 = append(, Error{
					Filename: ,
					Pos:      .Start,
					Err:      fmt.Errorf("unknown block type: %s", strings.Join(.Token, " ")),
				})
				continue
			case "godebug", "use", "replace":
				for ,  := range .Line {
					.add(&, , .Token[0], .Token, )
				}
			}
		}
	}

	if len() > 0 {
		return nil, 
	}
	return , nil
}

// Cleanup cleans up the file f after any edit operations.
// To avoid quadratic behavior, modifications like [WorkFile.DropUse]
// clear the entry but do not remove it from the slice.
// Cleanup cleans out all the cleared entries.
func ( *WorkFile) () {
	 := 0
	for ,  := range .Use {
		if .Path != "" {
			.Use[] = 
			++
		}
	}
	.Use = .Use[:]

	 = 0
	for ,  := range .Replace {
		if .Old.Path != "" {
			.Replace[] = 
			++
		}
	}
	.Replace = .Replace[:]

	.Syntax.Cleanup()
}

func ( *WorkFile) ( string) error {
	if !GoVersionRE.MatchString() {
		return fmt.Errorf("invalid language version %q", )
	}
	if .Go == nil {
		 := &Line{Token: []string{"go", }}
		.Go = &Go{
			Version: ,
			Syntax:  ,
		}
		// Find the first non-comment-only block and add
		// the go statement before it. That will keep file comments at the top.
		 := 0
		for  = 0;  < len(.Syntax.Stmt); ++ {
			if ,  := .Syntax.Stmt[].(*CommentBlock); ! {
				break
			}
		}
		.Syntax.Stmt = append(append(.Syntax.Stmt[::], ), .Syntax.Stmt[:]...)
	} else {
		.Go.Version = 
		.Syntax.updateLine(.Go.Syntax, "go", )
	}
	return nil
}

func ( *WorkFile) ( string) error {
	if !ToolchainRE.MatchString() {
		return fmt.Errorf("invalid toolchain name %q", )
	}
	if .Toolchain == nil {
		 := &Line{Token: []string{"toolchain", }}
		.Toolchain = &Toolchain{
			Name:   ,
			Syntax: ,
		}
		// Find the go line and add the toolchain line after it.
		// Or else find the first non-comment-only block and add
		// the toolchain line before it. That will keep file comments at the top.
		 := 0
		for  = 0;  < len(.Syntax.Stmt); ++ {
			if ,  := .Syntax.Stmt[].(*Line);  && len(.Token) > 0 && .Token[0] == "go" {
				++
				goto 
			}
		}
		for  = 0;  < len(.Syntax.Stmt); ++ {
			if ,  := .Syntax.Stmt[].(*CommentBlock); ! {
				break
			}
		}
	:
		.Syntax.Stmt = append(append(.Syntax.Stmt[::], ), .Syntax.Stmt[:]...)
	} else {
		.Toolchain.Name = 
		.Syntax.updateLine(.Toolchain.Syntax, "toolchain", )
	}
	return nil
}

// DropGoStmt deletes the go statement from the file.
func ( *WorkFile) () {
	if .Go != nil {
		.Go.Syntax.markRemoved()
		.Go = nil
	}
}

// DropToolchainStmt deletes the toolchain statement from the file.
func ( *WorkFile) () {
	if .Toolchain != nil {
		.Toolchain.Syntax.markRemoved()
		.Toolchain = nil
	}
}

// AddGodebug sets the first godebug line for key to value,
// preserving any existing comments for that line and removing all
// other godebug lines for key.
//
// If no line currently exists for key, AddGodebug adds a new line
// at the end of the last godebug block.
func ( *WorkFile) (,  string) error {
	 := true
	for ,  := range .Godebug {
		if .Key ==  {
			if  {
				.Value = 
				.Syntax.updateLine(.Syntax, "godebug", +"="+)
				 = false
			} else {
				.Syntax.markRemoved()
				* = Godebug{}
			}
		}
	}

	if  {
		.addNewGodebug(, )
	}
	return nil
}

// addNewGodebug adds a new godebug key=value line at the end
// of the last godebug block, regardless of any existing godebug lines for key.
func ( *WorkFile) (,  string) {
	 := .Syntax.addLine(nil, "godebug", +"="+)
	 := &Godebug{
		Key:    ,
		Value:  ,
		Syntax: ,
	}
	.Godebug = append(.Godebug, )
}

func ( *WorkFile) ( string) error {
	for ,  := range .Godebug {
		if .Key ==  {
			.Syntax.markRemoved()
			* = Godebug{}
		}
	}
	return nil
}

func ( *WorkFile) (,  string) error {
	 := true
	for ,  := range .Use {
		if .Path ==  {
			if  {
				.ModulePath = 
				.Syntax.updateLine(.Syntax, "use", AutoQuote())
				 = false
			} else {
				.Syntax.markRemoved()
				* = Use{}
			}
		}
	}

	if  {
		.AddNewUse(, )
	}
	return nil
}

func ( *WorkFile) (,  string) {
	 := .Syntax.addLine(nil, "use", AutoQuote())
	.Use = append(.Use, &Use{Path: , ModulePath: , Syntax: })
}

func ( *WorkFile) ( []*Use) {
	 := make(map[string]string)
	for ,  := range  {
		[.Path] = .ModulePath
	}

	for ,  := range .Use {
		if ,  := [.Path];  {
			.ModulePath = 
		} else {
			.Syntax.markRemoved()
			* = Use{}
		}
	}

	// TODO(#45713): Add module path to comment.

	for ,  := range  {
		.AddNewUse(, )
	}
	.SortBlocks()
}

func ( *WorkFile) ( string) error {
	for ,  := range .Use {
		if .Path ==  {
			.Syntax.markRemoved()
			* = Use{}
		}
	}
	return nil
}

func ( *WorkFile) (, , ,  string) error {
	return addReplace(.Syntax, &.Replace, , , , )
}

func ( *WorkFile) (,  string) error {
	for ,  := range .Replace {
		if .Old.Path ==  && .Old.Version ==  {
			.Syntax.markRemoved()
			* = Replace{}
		}
	}
	return nil
}

func ( *WorkFile) () {
	.removeDups() // otherwise sorting is unsafe

	for ,  := range .Syntax.Stmt {
		,  := .(*LineBlock)
		if ! {
			continue
		}
		slices.SortStableFunc(.Line, compareLine)
	}
}

// removeDups removes duplicate replace directives.
//
// Later replace directives take priority.
//
// require directives are not de-duplicated. That's left up to higher-level
// logic (MVS).
//
// retract directives are not de-duplicated since comments are
// meaningful, and versions may be retracted multiple times.
func ( *WorkFile) () {
	removeDups(.Syntax, nil, &.Replace, nil, nil)
}