package shlex

import (
	
	
)

// xonshFormat implements Format for xonsh lexing.
// Xonsh is a Python/shell hybrid. For lexing purposes:
//   - Standard single/double quotes work like bash
//   - Prefix strings (r'...', f'...', p'...', b'...') work because the
//     prefix is a word char and Words() merges the segments
//   - Triple-quotes (”'...”', """...""") detected via 2-rune lookahead
//   - Raw strings (r"...", r"""...""") suppress escape processing in double quotes
//   - Shell operators: |, >, >>, <, ;, &&, ||, &
//   - Keyword operators: and, or (bare words with surrounding whitespace)
//   - Stream redirect operators: e>, e>>, o>, o>>, a>, a>>, err>, out>, all>,
//     and pipe-channel variants (e>p, o>p, a>p) handled in PostProcess
//   - \ is the escape char (Python rules inside quotes, literal in raw strings)
type xonshFormat struct{}

func (xonshFormat) () tokenClassifier {
	 := newBaseClassifier(escapeRunes)
	// Xonsh operators: |, >, >>, <, ;, &&, ||, &
	// ( and ) are subprocess/eval delimiters
	.addWordbreaks("|<>&;()")
	return 
}

func (xonshFormat) ( string) WordbreakType {
	return bashWordbreakType() // xonsh uses POSIX operators
}

func (xonshFormat) () map[string]WordbreakType {
	return map[string]WordbreakType{
		"and": WORDBREAK_LIST_AND,
		"or":  WORDBREAK_LIST_OR,
	}
}

func (xonshFormat) () bool           { return false }
func (xonshFormat) () bool  { return true } // \' and \\ inside single quotes (Python syntax)
func (xonshFormat) () bool                 { return true }
func (xonshFormat) () bool          { return false }
func (xonshFormat) () map[rune]bool { return nil }
func (xonshFormat) ( string) string               { return xonshQuoteWord() }
func (xonshFormat) () bool                { return true }
func (xonshFormat) () bool                  { return true }

// IsLineContinuation implements lineContinuationEscaper. Xonsh (Python)
// treats backslash followed by \n or \r as a line continuation inside
// string literals and outside quotes.
func (xonshFormat) ( rune) bool {
	return  == '\n' ||  == '\r'
}

// xonshStreamRedirects maps the word portion of xonsh stream-redirect
// operators (the part before > or <) to their WordbreakType. The PostProcess
// step merges these with a following > or < wordbreak token.
// See xonsh _REDIR_REGEX: (o(?:ut)?|e(?:rr)?|a(?:ll)?|&?\d?)(>?>|<)(...)
var xonshStreamRedirects = map[string]WordbreakType{
	"e":   WORDBREAK_REDIRECT_OUTPUT,
	"err": WORDBREAK_REDIRECT_OUTPUT,
	"o":   WORDBREAK_REDIRECT_OUTPUT,
	"out": WORDBREAK_REDIRECT_OUTPUT,
	"a":   WORDBREAK_REDIRECT_OUTPUT_BOTH,
	"all": WORDBREAK_REDIRECT_OUTPUT_BOTH,
}

// PostProcess merges xonsh stream-redirect operators. The tokenizer produces
// e.g. `e` as a WORD_TOKEN and `>` (or `>>`) as a WORDBREAK_TOKEN because the
// rune-classifier only handles single-rune word breaks. This step detects
// adjacent word+wordbreak sequences like `e>`, `o>>`, `a>`, `err>`, `out>`
// and reclassifies them as single WORDBREAK_TOKENs with the appropriate
// WordbreakType. Also handles the pipe-channel variants `e>p`, `o>p`, `a>p`.
func (xonshFormat) ( TokenSlice) TokenSlice {
	 := make(TokenSlice, 0, len())
	for  := 0;  < len(); ++ {
		 := []

		// Look for bare WORD_TOKEN immediately followed by WORDBREAK_TOKEN
		// starting with '>' or '<'. Only merge bare words (Value == RawValue)
		// — quoted words like 'e' or "out" are string literals, not operators.
		if .Type == WORD_TOKEN && .Value == .RawValue && +1 < len() {
			 := [+1]
			if .Type == WORDBREAK_TOKEN && .adjoins() && len(.RawValue) > 0 &&
				(.RawValue[0] == '>' || .RawValue[0] == '<') {
				if ,  := xonshStreamRedirects[.Value];  {
					 := Token{
						Type:          WORDBREAK_TOKEN,
						Value:         .Value + .Value,
						RawValue:      .RawValue + .RawValue,
						Span:          Span{Start: .Span.Start, End: .Span.End},
						State:         .State,
						WordbreakType: ,
					}

					// Check for pipe-channel suffix: e>p, o>p, a>p
					// The 'p' would be a separate adjacent WORD_TOKEN
					if +2 < len() {
						 := [+2]
						if .Type == WORD_TOKEN && .Value == "p" &&
							.Value == .RawValue && .adjoins() {
							.Value += "p"
							.RawValue += "p"
							.Span.End = .Span.End
							 = append(, )
							 += 2
							continue
						}
					}

					 = append(, )
					 += 1
					continue
				}
			}
		}

		 = append(, )
	}

	// Second pass: merge $/@ + ( into substitution opener and reclassify ) as closer
	 := make(TokenSlice, 0, len())
	for  := 0;  < len(); ++ {
		 := []
		// Detect $ + ( or @ + ( adjacency → merge into WORDBREAK_SUBSTITUTION_OPEN
		if .Type == WORD_TOKEN && (.Value == "$" || .Value == "@") && +1 < len() {
			 := [+1]
			if .Type == WORDBREAK_TOKEN && .Value == "(" && .adjoins() {
				 := Token{
					Type:          WORDBREAK_TOKEN,
					Value:         .Value + "(",
					RawValue:      .RawValue + .RawValue,
					Span:          Span{Start: .Span.Start, End: .Span.End},
					State:         .State,
					WordbreakType: WORDBREAK_SUBSTITUTION_OPEN,
				}
				 = append(, )
				++
				continue
			}
		}
		// Reclassify standalone ( as substitution opener
		if .Type == WORDBREAK_TOKEN && .Value == "(" {
			.WordbreakType = WORDBREAK_SUBSTITUTION_OPEN
		}
		// Reclassify ) as substitution closer
		if .Type == WORDBREAK_TOKEN && .Value == ")" {
			.WordbreakType = WORDBREAK_SUBSTITUTION_CLOSE
		}
		 = append(, )
	}
	return 
}

// Variable implements variableExpander. Xonsh strings are Python
// literals, so `$` expands only in barewords; both `$name` and the
// expression form `${name` exist.
func (xonshFormat) ( Token) (Variable, bool) {
	return variableRef(, variableRules{
		brace:           true,
		expands:         func( LexerState) bool { return  == IN_WORD_STATE },
		barewordEscapes: true,
		nameStart:       isPosixNameStart,
		nameRune:        isPosixNameRune,
	})
}

// xonshNumericWordRe matches digit-leading words that Python evaluates
// silently in xonsh (e.g. 0x1f -> 31, 1_000, 2. -> 2.0, 2e3 -> 2000.0,
// plain 42 -> 42). Words that fail to parse stay inert in subprocess mode.
var xonshNumericWordRe = regexp.MustCompile(
	`^0[xX][0-9a-fA-F_]+$` +
		`|^0[oO][0-7_]+$` +
		`|^0[bB][01_]+$` +
		`|^[0-9][0-9_]*\.?[0-9_]*([eE][0-9]+)?$`,
)

func (xonshFormat) ( string) bool {
	// digit-leading words with operator runes or numeric literal shape are
	// valid Python expressions and evaluate in xonsh (e.g. 2+2 silently
	// computes), so they are not inert
	if  != "" && [0] >= '0' && [0] <= '9' &&
		(strings.ContainsAny(, "+-*/%") || xonshNumericWordRe.MatchString()) {
		return false
	}
	return bareWordRe.MatchString()
}