package shlex

// elvishFormat implements Format for elvish lexing.
// Key differences from bash:
// - ” inside single quotes → literal ' (same as zsh RC_QUOTES)
// - \ is NOT an escape character outside quotes (it's a bareword char)
// - No POSIX list operators (no &&, ||, &)
type elvishFormat struct{}

func (elvishFormat) () tokenClassifier {
	 := newBaseClassifier(escapeRunes)
	// Elvish operators: |, >, <, >>, <>, ;
	// No &, &&, || — & is for map literals and background pipelines
	// ( and ) are output-capture delimiters (always word breaks)
	// [ and ] are list-literal/indexing delimiters (word break at word start,
	// but not when following a word char for indexing — handled in PostProcess)
	.addWordbreaks("|><;()[]")
	return 
}

func (elvishFormat) ( string) WordbreakType {
	switch  {
	case "|":
		return WORDBREAK_PIPE
	case ">", ">>", "<>", "<":
		return WORDBREAK_REDIRECT_OUTPUT // simplified; elvish redirects
	case ";":
		return WORDBREAK_LIST_SEQUENTIAL
	case "(", ")":
		return WORDBREAK_OUTPUT_CAPTURE
	case "[", "]":
		return WORDBREAK_BRACKET
	default:
		return WORDBREAK_UNKNOWN
	}
}

func (elvishFormat) () map[string]WordbreakType { return nil }

func (elvishFormat) () bool           { return true } // '' → '
func (elvishFormat) () bool  { return false }
func (elvishFormat) () bool                 { return false }
func (elvishFormat) () bool          { return false }
func (elvishFormat) () map[rune]bool { return nil }
func (elvishFormat) ( string) string               { return elvishQuoteWord() }
func (elvishFormat) () bool                { return false }
func (elvishFormat) () bool                  { return false }

// LineContinuationChar implements lineContinuationWhitespace. Elvish uses ^
// followed by \n or \r\n as whitespace (a word break), not as concatenation.
func (elvishFormat) () rune { return '^' }
func (elvishFormat) ( rune) bool {
	return  == '\n' ||  == '\r'
}

// braceState tracks the parser context inside braces.
type braceState int

const (
	braceOutside    braceState = iota // not inside braces
	braceLambdaOpen                   // saw '{' followed by |/space/newline → lambda, no params yet
	braceParams                       // inside {|...| parameter list (between first | and second |)
	braceLambdaBody                   // after closing | of params, in lambda body
	braceBraced                       // inside braced list {a,b}
)

// PostProcess reclassifies WORDBREAK_PIPE tokens that are inside elvish
// lambda parameter lists as WORDBREAK_LAMBDA_PIPE, and reclassifies
// output-capture delimiters ( and ) as substitution delimiters.
func (elvishFormat) ( TokenSlice) TokenSlice {
	var  []braceState

	for  := range  {
		 := &[]

		// Reclassify output-capture delimiters as substitution delimiters
		if .Type == WORDBREAK_TOKEN && .WordbreakType == WORDBREAK_OUTPUT_CAPTURE {
			if .Value == "(" {
				.WordbreakType = WORDBREAK_SUBSTITUTION_OPEN
			} else if .Value == ")" {
				.WordbreakType = WORDBREAK_SUBSTITUTION_CLOSE
			}
		}

		if .Type == WORD_TOKEN && .Value == "{" {
			 := false
			 := false
			if +1 < len() {
				 := [+1]
				if .Type == WORDBREAK_TOKEN && .Value == "|" {
					 = true
				} else if !.adjoins() {
					// { followed by space then a non-| token: lambda with
					// no params, body starts immediately. Any | inside is
					// a real pipeline pipe, not a param delimiter.
					 = true
				}
			} else {
				// { at EOF: incomplete lambda, treat as lambda open
				 = true
			}
			if  {
				 = append(, braceLambdaOpen)
			} else if  {
				 = append(, braceLambdaBody)
			} else {
				 = append(, braceBraced)
			}
			continue
		}

		if .Type == WORD_TOKEN {
			// Count { and } in non-standalone words to maintain brace stack.
			// This handles cases like $a} where } is embedded in a word
			// and doesn't match the standalone t.Value == "}" check above.
			if .Value != "{" && .Value != "}" {
				for ,  := range .Value {
					switch  {
					case '{':
						 = append(, braceBraced)
					case '}':
						if len() > 0 {
							 = [:len()-1]
						}
					}
				}
			} else if .Value == "}" {
				if len() > 0 {
					 = [:len()-1]
				}
				continue
			}
		}

		if .Type == WORDBREAK_TOKEN && .Value == "|" && len() > 0 {
			 := &[len()-1]
			switch * {
			case braceLambdaOpen:
				* = braceParams
				.WordbreakType = WORDBREAK_LAMBDA_PIPE
			case braceParams:
				* = braceLambdaBody
				.WordbreakType = WORDBREAK_LAMBDA_PIPE
			case braceBraced:
				.WordbreakType = WORDBREAK_LAMBDA_PIPE
			}
		}
	}

	return 
}

// Variable implements variableExpander. Elvish expands `$name` in
// barewords and double quotes; there is no `${` form. Backslash is a
// literal bareword character, so escapes only apply inside double quotes
// (`\$HO` in a bareword is a literal backslash followed by the expansion).
func (elvishFormat) ( Token) (Variable, bool) {
	return variableRef(, variableRules{
		expands:         func( LexerState) bool { return  != QUOTING_STATE },
		barewordEscapes: false,
		nameStart:       isPosixNameStart,
		nameRune:        isPosixNameRune,
	})
}

func (elvishFormat) ( string) bool {
	return bareWordRe.MatchString()
}