package shlex

import (
	
	
	
	
	
)

// TokenType is a top-level token classification: A word, space, comment, unknown.
type TokenType int

func ( TokenType) () ([]byte, error) {
	return json.Marshal(tokenTypes[])
}

// runeTokenClass is the type of a UTF-8 character classification: A quote, space, escape.
type runeTokenClass int

// the internal state used by the lexer state machine
type LexerState int

func ( LexerState) () ([]byte, error) {
	return json.Marshal(lexerStates[])
}

// Token is a (type, value) pair representing a lexicographic token.
type Token struct {
	Type           TokenType
	Value          string
	RawValue       string
	Span           Span
	State          LexerState
	WordbreakType  WordbreakType `json:",omitempty"`
	WordbreakIndex int           // index of last opening quote in Value (only correct when in quoting state)
}

func ( *Token) ( rune) {
	.Value += string()
}

func ( *Token) () {
	 := []rune(.RawValue)
	.RawValue = string([:len()-1])
}

func ( Token) ( Token) bool {
	return .Span.End == .Span.Start || .Span.Start == .Span.End
}

// Equal reports whether tokens a, and b, are equal.
// Two tokens are equal if both their types and values are equal. A nil token can
// never be equal to another token.
func ( *Token) ( *Token) bool {
	switch {
	case  == nil,
		 == nil,
		.Type != .Type,
		.Value != .Value,
		.RawValue != .RawValue,
		.Span != .Span,
		.State != .State,
		.WordbreakType != .WordbreakType,
		.WordbreakIndex != .WordbreakIndex:
		return false
	default:
		return true
	}
}

// Named classes of UTF-8 runes
const (
	spaceRunes            = " \t\r\n"
	escapingQuoteRunes    = `"`
	nonEscapingQuoteRunes = "'"
	escapeRunes           = `\`
	commentRunes          = "#"
)

// Classes of rune token
const (
	unknownRuneClass runeTokenClass = iota
	spaceRuneClass
	escapingQuoteRuneClass
	nonEscapingQuoteRuneClass
	escapeRuneClass
	commentRuneClass
	wordbreakRuneClass
	eofRuneClass
)

// Classes of lexographic token
const (
	UNKNOWN_TOKEN TokenType = iota
	WORD_TOKEN
	SPACE_TOKEN
	COMMENT_TOKEN
	WORDBREAK_TOKEN
)

var tokenTypes = map[TokenType]string{
	UNKNOWN_TOKEN:   "UNKNOWN_TOKEN",
	WORD_TOKEN:      "WORD_TOKEN",
	SPACE_TOKEN:     "SPACE_TOKEN",
	COMMENT_TOKEN:   "COMMENT_TOKEN",
	WORDBREAK_TOKEN: "WORDBREAK_TOKEN",
}

// Lexer state machine states
const (
	START_STATE                   LexerState = iota // no runes have been seen
	IN_WORD_STATE                                   // processing regular runes in a word
	ESCAPING_STATE                                  // we have just consumed an escape rune; the next rune is literal
	ESCAPING_QUOTED_STATE                           // we have just consumed an escape rune within a quoted string
	QUOTING_ESCAPING_STATE                          // we are within a quoted string that supports escaping ("...")
	QUOTING_STATE                                   // we are within a string that does not support escaping ('...')
	QUOTING_TRIPLE_STATE                            // we are within a triple-quoted non-escaping string ('''...''')
	QUOTING_TRIPLE_ESCAPING_STATE                   // we are within a triple-quoted escaping string ("""...""")
	COMMENT_STATE                                   // we are within a comment (everything following an unquoted or unescaped #
	BLOCK_COMMENT_STATE                             // we are within a block comment (e.g. PowerShell <# ... #>)
	STOP_PARSING_STATE                              // we are in raw mode after a stop-parsing token (e.g. PowerShell --%)
	WORDBREAK_STATE                                 // we have just consumed a wordbreak rune
)

var lexerStates = map[LexerState]string{
	START_STATE:                   "START_STATE",
	IN_WORD_STATE:                 "IN_WORD_STATE",
	ESCAPING_STATE:                "ESCAPING_STATE",
	ESCAPING_QUOTED_STATE:         "ESCAPING_QUOTED_STATE",
	QUOTING_ESCAPING_STATE:        "QUOTING_ESCAPING_STATE",
	QUOTING_STATE:                 "QUOTING_STATE",
	QUOTING_TRIPLE_STATE:          "QUOTING_TRIPLE_STATE",
	QUOTING_TRIPLE_ESCAPING_STATE: "QUOTING_TRIPLE_ESCAPING_STATE",
	COMMENT_STATE:                 "COMMENT_STATE",
	BLOCK_COMMENT_STATE:           "BLOCK_COMMENT_STATE",
	STOP_PARSING_STATE:            "STOP_PARSING_STATE",
	WORDBREAK_STATE:               "WORDBREAK_STATE",
}

// tokenClassifier is used for classifying rune characters.
type tokenClassifier map[rune]runeTokenClass

func ( tokenClassifier) ( string,  runeTokenClass) {
	for ,  := range  {
		[] = 
	}
}

// ClassifyRune classifies a rune
func ( tokenClassifier) ( rune) runeTokenClass {
	return []
}

// newBaseClassifier creates a classifier with the standard POSIX rune classes
// (space, escaping quote, non-escaping quote, escape, comment) but without
// any wordbreak runes. Formats add their own wordbreaks on top.
func newBaseClassifier( string) tokenClassifier {
	 := tokenClassifier{}
	.addRuneClass(spaceRunes, spaceRuneClass)
	.addRuneClass(escapingQuoteRunes, escapingQuoteRuneClass)
	.addRuneClass(nonEscapingQuoteRunes, nonEscapingQuoteRuneClass)
	.addRuneClass(, escapeRuneClass)
	.addRuneClass(commentRunes, commentRuneClass)
	return 
}

// addWordbreaks adds wordbreak runes to a classifier, filtering out any
// that are already classified as space/quote/escape/comment.
func ( tokenClassifier) ( string) {
	 := make([]rune, 0)
	for ,  := range  {
		if .ClassifyRune() == unknownRuneClass {
			 = append(, )
		}
	}
	.addRuneClass(string(), wordbreakRuneClass)
}

// lexer turns an input stream into a sequence of tokens. Whitespace and comments are skipped.
type lexer tokenizer

// newLexer creates a new lexer from an input stream and format.
func newLexer( io.Reader,  formatImpl) *lexer {
	return (*lexer)(newTokenizer(, ))
}

// Next returns the next token, or an error. If there are no more tokens,
// the error will be io.EOF.
func ( *lexer) () (*Token, error) {
	for {
		,  := (*tokenizer)().Next()
		if  != nil {
			return , 
		}
		switch .Type {
		case WORD_TOKEN, WORDBREAK_TOKEN:
			return , nil
		case COMMENT_TOKEN:
			// skip comments
		default:
			return nil, fmt.Errorf("unknown token type: %v", .Type)
		}
	}
}

// tokenizer turns an input stream into a sequence of typed tokens
type tokenizer struct {
	input            bufio.Reader
	classifier       tokenClassifier
	format           formatImpl
	index            int
	state            LexerState
	rawQuote         bool   // true when current quote was opened with a raw prefix (r/R)
	tripleQuoteRune  rune   // the quote char (' or ") that opened a triple-quote
	blockCloser      string // the closer string for the current block comment
	blockCloserIdx   int    // index into blockCloser for match tracking
	stopParsingDelim string // pipeline delimiter set for stop-parsing mode
}

func ( *tokenizer) () ( rune,  int,  error) {
	if , ,  = .input.ReadRune();  == nil {
		.index += 1
	}
	return
}

func ( *tokenizer) () ( error) {
	if  = .input.UnreadRune();  == nil {
		.index -= 1
	}
	return
}

// newTokenizer creates a new tokenizer from an input stream and format.
func newTokenizer( io.Reader,  formatImpl) *tokenizer {
	 := bufio.NewReader()
	 := .Classifier()
	return &tokenizer{
		input:      *,
		classifier: ,
		format:     }
}

// checkTripleQuote peeks ahead two runes to check if this is a triple-quote.
// Returns true if the next two runes match the quote rune. The two runes are
// consumed (added to index) and returned so the caller can add them to RawValue.
// If not a triple-quote, all peeked runes are unread (at most one unread is
// needed since bufio.Reader only supports one level of UnreadRune; the first
// rune is returned via the consumedRune parameter so the caller can handle it).
func ( *tokenizer) ( rune) ( bool,  rune,  rune,  rune) {
	if !.format.TripleQuoteSupport() {
		return false, 0, 0, 0
	}
	, ,  := .ReadRune()
	if  != nil {
		return false, 0, 0, 0
	}
	if  !=  {
		.UnreadRune()
		return false, 0, 0, 0
	}
	, ,  := .ReadRune()
	if  != nil {
		// peek1 matched but EOF after — can't unread peek1, return it as consumed
		return false, 0, 0, 
	}
	if  !=  {
		// peek1 matched but peek2 didn't — unread peek2, return peek1 as consumed
		.UnreadRune()
		return false, 0, 0, 
	}
	return true, , , 0
}

// checkRawPrefix examines the current token's Value to see if it ends with
// a raw string prefix (r or R) that qualifies as a Python string prefix.
// The r/R must be at word start or preceded only by other valid prefix
// characters (b, B, p, P, f, F, u, U, r, R). This prevents false positives
// like "abr" where the r is part of a regular word.
func ( *tokenizer) ( *Token) bool {
	if !.format.RawPrefixSupport() {
		return false
	}
	 := .Value
	if len() == 0 {
		return false
	}
	// Check that all chars are valid string prefix chars with no duplicates
	// (case-insensitive). Python allows at most one of each prefix type.
	 := make(map[byte]bool)
	for  := 0;  < len(); ++ {
		 := lowerByte([])
		if !isStringPrefixChar([]) {
			return false
		}
		if [] {
			return false
		}
		[] = true
	}
	// Must contain r or R (can be anywhere in the prefix, e.g. rb, rf)
	return containsRawChar()
}

// isStringPrefixChar returns true for characters valid in Python string
// prefixes: b, B, p, P, r, R, u, U, f, F.
func isStringPrefixChar( byte) bool {
	switch  {
	case 'b', 'B', 'p', 'P', 'r', 'R', 'u', 'U', 'f', 'F':
		return true
	}
	return false
}

func lowerByte( byte) byte {
	if  >= 'A' &&  <= 'Z' {
		return  + 32
	}
	return 
}

func containsRawChar( string) bool {
	for  := 0;  < len(); ++ {
		if [] == 'r' || [] == 'R' {
			return true
		}
	}
	return false
}

// checkTripleClose checks if the current quote rune (already consumed and added
// to RawValue at the top of the loop) is the start of a closing triple-quote.
// Reads two more runes. Returns:
//   - closed=true: both runes matched, closing triple-quote consumed (added to RawValue by caller)
//   - closed=false, consumedRune!=0: first rune matched but second didn't. The first rune was
//     consumed and cannot be unread; it's returned as consumedRune so the caller can add it
//     to RawValue and emit it as a literal. The second rune was unread.
//   - closed=false, consumedRune=0: first rune didn't match (or EOF), it was unread.
//     The caller should emit the current quote rune as a literal.
func ( *tokenizer) () ( bool,  rune,  rune,  rune) {
	, ,  := .ReadRune()
	if  != nil {
		return false, 0, 0, 0
	}
	if  != .tripleQuoteRune {
		.UnreadRune()
		return false, 0, 0, 0
	}
	, ,  := .ReadRune()
	if  != nil {
		return false, 0, 0, 
	}
	if  != .tripleQuoteRune {
		.UnreadRune()
		return false, 0, 0, 
	}
	return true, , , 0
}

// checkBlockCommentOpener checks if the current position matches a block
// comment opener (e.g. "<#" for PowerShell). The firstRune has already been
// consumed and added to token.RawValue by the caller. If the remaining runes
// of the opener match, they are consumed and added to token.RawValue, and
// the tokenizer enters BLOCK_COMMENT_STATE. Returns true if the opener was
// matched and consumed. On mismatch, peeked runes are unread.
func ( *tokenizer) ( rune,  *Token) bool {
	,  := .format.(blockCommenter)
	if ! {
		return false
	}
	 := .BlockCommentOpener()
	if len() == 0 || rune([0]) !=  {
		return false
	}
	// bufio.Reader only supports one UnreadRune. The first rune was
	// consumed by the caller; only one more can be unread on mismatch,
	// so openers longer than 2 runes are not supported here.
	if len() > 2 {
		return false
	}
	// Try to match remaining runes of the opener (index 1 onward)
	for  := 1;  < len(); ++ {
		, ,  := .ReadRune()
		if  != nil {
			// EOF before full match — unread what we consumed
			for  := 0;  < -1; ++ {
				.UnreadRune()
			}
			return false
		}
		if rune([]) !=  {
			// Mismatch — unread this rune and any previously consumed runes
			.UnreadRune()
			for  := 0;  < -1; ++ {
				.UnreadRune()
			}
			return false
		}
	}
	// Full match — add remaining opener runes to RawValue
	for  := 1;  < len(); ++ {
		.RawValue += string([])
	}
	.blockCloser = .BlockCommentCloser()
	.blockCloserIdx = 0
	return true
}

// scanStream scans the stream for the next token using the internal state machine.
// It will panic if it encounters a rune which it does not know how to handle.
func ( *tokenizer) () (*Token, error) {
	 := .state
	.state = START_STATE
	.rawQuote = false
	.tripleQuoteRune = 0
	 := &Token{}
	var  rune
	var  runeTokenClass
	var  error
	 := false

	for {
		, _,  = .ReadRune()
		 = .classifier.ClassifyRune()
		.RawValue += string()

		switch {
		case  == io.EOF:
			 = eofRuneClass
			 = nil
		case  != nil:
			return nil, 
		}

		switch .state {
		case START_STATE: // no runes read yet
			{
				if  != spaceRuneClass {
					.Span.Start = .index - 1
				}
				// Check for block comment opener before other classification
				if .checkBlockCommentOpener(, ) {
					.Type = COMMENT_TOKEN
					.state = BLOCK_COMMENT_STATE
					continue
				}
				switch  {
				case eofRuneClass:
					switch {
					case .index == 0: // tokenizer contains an empty string
						.removeLastRaw()
						.Type = WORD_TOKEN
						.Span.Start = .index
						.Span.End = .index
						.index += 1
						return , nil // return an additional empty token for current cursor position
					case  == WORDBREAK_STATE, : // sawSpace when there were spaceRunes before
						.removeLastRaw()
						.Type = WORD_TOKEN
						.Span.Start = .index
						.Span.End = .index
						return , nil // return an additional empty token for current cursor position
					default:
						return nil, io.EOF
					}
				case spaceRuneClass:
					.removeLastRaw()
					 = true
				case escapingQuoteRuneClass:
					.Type = WORD_TOKEN
					.WordbreakIndex = len(.Value)
					if , , ,  := .checkTripleQuote();  {
						.RawValue += string()
						.RawValue += string()
						.tripleQuoteRune = 
						if .checkRawPrefix() {
							.rawQuote = true
							.state = QUOTING_TRIPLE_STATE
						} else {
							.state = QUOTING_TRIPLE_ESCAPING_STATE
						}
					} else if  != 0 {
						.RawValue += string()
						.state = IN_WORD_STATE
					} else if .checkRawPrefix() {
						.rawQuote = true
						.state = QUOTING_ESCAPING_STATE
					} else {
						.state = QUOTING_ESCAPING_STATE
					}
				case nonEscapingQuoteRuneClass:
					.Type = WORD_TOKEN
					.WordbreakIndex = len(.Value)
					if , , ,  := .checkTripleQuote();  {
						.RawValue += string()
						.RawValue += string()
						.tripleQuoteRune = 
						.state = QUOTING_TRIPLE_STATE
					} else if  != 0 {
						.RawValue += string()
						.state = IN_WORD_STATE
					} else {
						.state = QUOTING_STATE
					}
				case escapeRuneClass:
					.Type = WORD_TOKEN
					if .format.EscapeNotBareword() {
						// Check for line continuation (e.g. PowerShell backtick + newline)
						if ,  := .format.(lineContinuationEscaper);  {
							, ,  := .ReadRune()
							if  != nil {
								// EOF after escape — enter ESCAPING_STATE to handle
								.UnreadRune() // can't unread EOF, but harmless
								_ = 
								.state = ESCAPING_STATE
								continue
							}
							if .IsLineContinuation() {
								// Consume optional \n after \r
								if  == '\r' {
									, ,  := .ReadRune()
									if  == nil &&  == '\n' {
										// CRLF consumed — don't add to RawValue
									} else if  == nil {
										.UnreadRune()
									}
								}
								// Line continuation: remove escape char from RawValue and Value
								.removeLastRaw() // remove the escape char
								// Stay in START_STATE (no word content yet)
								continue
							}
							// Not a line continuation — unread and enter ESCAPING_STATE
							.UnreadRune()
						}
						.state = ESCAPING_STATE
					} else {
						.add()
						.state = IN_WORD_STATE
					}
				case commentRuneClass:
					.Type = COMMENT_TOKEN
					.state = COMMENT_STATE
				case wordbreakRuneClass:
					.Type = WORDBREAK_TOKEN
					.add()
					.state = WORDBREAK_STATE
				default:
					// Check for line-continuation whitespace (e.g. elvish ^+newline)
					if ,  := .format.(lineContinuationWhitespace);  &&  == .LineContinuationChar() {
						, ,  := .ReadRune()
						if  == nil && .IsLineContinuationWhitespace() {
							if  == '\r' {
								, ,  := .ReadRune()
								if  == nil &&  == '\n' {
									// CRLF consumed
								} else if  == nil {
									.UnreadRune()
								}
							}
							// ^+newline at word start: pure whitespace, stay in START_STATE
							.removeLastRaw() // remove the ^ char
							continue
						}
						if  == nil {
							.UnreadRune()
						}
					}
					.Type = WORD_TOKEN
					.add()
					.state = IN_WORD_STATE
				}
			}
		case WORDBREAK_STATE:
			// Check for block comment opener: the current wordbreak token
			// may be the first rune of the opener (e.g. "<" in "<#").
			// token.RawValue includes nextRune (added at top of loop), so
			// we check if the RawValue without nextRune matches the opener start.
			if ,  := .format.(blockCommenter);  {
				 := .BlockCommentOpener()
				// bufio.Reader only supports one UnreadRune. The first
				// rune is in token.Value and the second is nextRune (in
				// RawValue); only one more can be unread on mismatch, so
				// openers longer than 3 runes are not supported here.
				if len() > 0 && len() <= 3 {
					// The wordbreak portion is token.Value (without nextRune).
					// token.RawValue includes nextRune; we need to check if
					// token.Value (the wordbreak so far) is the opener prefix.
					 := .Value
					if  == string([0]) && len() > 1 {
						// nextRune should be opener[1]
						if rune([1]) ==  {
							// Match remaining opener runes from index 2
							 := true
							for  := 2;  < len(); ++ {
								, ,  := .ReadRune()
								if  != nil || rune([]) !=  {
									if  == nil {
										.UnreadRune()
									}
									for  := 0;  < -2; ++ {
										.UnreadRune()
									}
									 = false
									break
								}
							}
							if  {
								// Add remaining opener runes to RawValue
								for  := 2;  < len(); ++ {
									.RawValue += string([])
								}
								.Type = COMMENT_TOKEN
								.blockCloser = .BlockCommentCloser()
								.blockCloserIdx = 0
								.state = BLOCK_COMMENT_STATE
								continue
							}
						}
					}
				}
			}
			switch  {
			case wordbreakRuneClass:
				// token.RawValue already includes nextRune (added at top of loop).
				// If the extended raw value is not a known operator, the current
				// rune starts a new operator — unread it and return the current token.
				if .format.ClassifyOperator(.RawValue) == WORDBREAK_UNKNOWN {
					.removeLastRaw()
					.UnreadRune()
					return , 
				}
				.add()
			default:
				.removeLastRaw()
				.UnreadRune()
				return , 
			}
		case IN_WORD_STATE: // in a regular word
			switch  {
			case wordbreakRuneClass:
				.removeLastRaw()
				.UnreadRune()
				return , 
			case eofRuneClass, spaceRuneClass:
				.removeLastRaw()
				.UnreadRune()
				return , 
			case escapingQuoteRuneClass:
				.WordbreakIndex = len(.Value)
				if , , ,  := .checkTripleQuote();  {
					.RawValue += string()
					.RawValue += string()
					.tripleQuoteRune = 
					if .checkRawPrefix() {
						.rawQuote = true
						.state = QUOTING_TRIPLE_STATE
					} else {
						.state = QUOTING_TRIPLE_ESCAPING_STATE
					}
				} else if  != 0 {
					.RawValue += string()
					.state = IN_WORD_STATE
				} else if .checkRawPrefix() {
					.rawQuote = true
					.state = QUOTING_ESCAPING_STATE
				} else {
					.state = QUOTING_ESCAPING_STATE
				}
			case nonEscapingQuoteRuneClass:
				.WordbreakIndex = len(.Value)
				if , , ,  := .checkTripleQuote();  {
					.RawValue += string()
					.RawValue += string()
					.tripleQuoteRune = 
					.state = QUOTING_TRIPLE_STATE
				} else if  != 0 {
					.RawValue += string()
					.state = IN_WORD_STATE
				} else {
					.state = QUOTING_STATE
				}
			case escapeRuneClass:
				if .format.EscapeNotBareword() {
					// Check for line continuation (e.g. PowerShell backtick + newline)
					if ,  := .format.(lineContinuationEscaper);  {
						, ,  := .ReadRune()
						if  != nil {
							// EOF after escape — enter ESCAPING_STATE to handle
							.UnreadRune()
							_ = 
							.state = ESCAPING_STATE
							continue
						}
						if .IsLineContinuation() {
							// Consume optional \n after \r
							if  == '\r' {
								, ,  := .ReadRune()
								if  == nil &&  == '\n' {
									// CRLF consumed — don't add to RawValue
								} else if  == nil {
									.UnreadRune()
								}
							}
							// Line continuation: remove escape char from RawValue
							.removeLastRaw() // remove the escape char
							// Stay in IN_WORD_STATE (word continues on next line)
							continue
						}
						// Not a line continuation — unread and enter ESCAPING_STATE
						.UnreadRune()
					}
					.state = ESCAPING_STATE
				} else {
					.add() // elvish: \ is a bareword char
				}
			default:
				// Check for line-continuation whitespace (e.g. elvish ^+newline)
				if ,  := .format.(lineContinuationWhitespace);  &&  == .LineContinuationChar() {
					, ,  := .ReadRune()
					if  == nil && .IsLineContinuationWhitespace() {
						// Consume optional \n after \r
						if  == '\r' {
							, ,  := .ReadRune()
							if  == nil &&  == '\n' {
								// CRLF consumed
							} else if  == nil {
								.UnreadRune()
							}
						}
						// ^+newline acts as whitespace: end the current word
						.removeLastRaw() // remove the ^ char
						.UnreadRune()
						return , 
					}
					if  == nil {
						.UnreadRune()
					}
				}
				.add()
			}
		case ESCAPING_STATE: // the rune after an escape character
			switch  {
			case eofRuneClass: // EOF found after escape character
				.removeLastRaw()
				return , 
			default:
				// Check for line continuation (e.g. PowerShell backtick + newline)
				if ,  := .format.(lineContinuationEscaper);  && .IsLineContinuation() {
					// Consume optional \n after \r (without adding to RawValue)
					if  == '\r' {
						, ,  := .ReadRune()
						if  == nil &&  == '\n' {
							// CRLF consumed
						} else if  == nil {
							.UnreadRune()
						}
					}
					// Line continuation: remove newline and escape char from RawValue
					.removeLastRaw() // remove newline (\n or \r)
					.removeLastRaw() // remove escape char
					// If we have word content, continue in IN_WORD_STATE;
					// otherwise go back to START_STATE
					if len(.Value) > 0 {
						.state = IN_WORD_STATE
					} else {
						.state = START_STATE
					}
					continue
				}
				.state = IN_WORD_STATE
				.add()
			}
		case ESCAPING_QUOTED_STATE: // the next rune after an escape character, in double quotes
			switch  {
			case eofRuneClass: // EOF found after escape character
				.removeLastRaw()
				return , 
			default:
				// Check for line continuation (e.g. bash/fish \+newline inside "...")
				if ,  := .format.(lineContinuationEscaper);  && .IsLineContinuation() &&
					lineContinuationInsideQuotes(.format) {
					// Consume optional \n after \r (without adding to RawValue)
					if  == '\r' {
						, ,  := .ReadRune()
						if  == nil &&  == '\n' {
							// CRLF consumed
						} else if  == nil {
							.UnreadRune()
						}
					}
					// Line continuation: remove newline and escape char from RawValue
					.removeLastRaw() // remove newline (\n or \r)
					.removeLastRaw() // remove escape char
					// Return to the normal double-quote state
					.state = QUOTING_ESCAPING_STATE
					continue
				}
				.state = QUOTING_ESCAPING_STATE
				if ,  := .format.(escapingQuoteUnescaper);  {
					if ,  := .EscapingQuoteUnescape();  {
						.Value += 
					} else {
						.add('\\')
						.add()
					}
				} else if  := .format.EscapingQuoteEscapeChars();  != nil {
					if [] {
						.add()
					} else {
						.add('\\')
						.add()
					}
				} else {
					.add()
				}
			}
		case QUOTING_ESCAPING_STATE: // in escaping double quotes
			switch  {
			case eofRuneClass: // EOF found when expecting closing quote
				.removeLastRaw()
				return , 
			case escapingQuoteRuneClass:
				if .format.NonEscapingQuoteEscapes() {
					// PowerShell: "" → literal " (doubled quote), else close
					, ,  := .ReadRune()
					if  == nil && .classifier.ClassifyRune() == escapingQuoteRuneClass {
						.RawValue += string()
						.add() // emit one literal "
						// stay in QUOTING_ESCAPING_STATE
					} else {
						if  == nil {
							.UnreadRune()
						}
						.rawQuote = false
						.state = IN_WORD_STATE
					}
				} else {
					.rawQuote = false
					.state = IN_WORD_STATE
				}
			case escapeRuneClass:
				if .rawQuote {
					.add() // raw string: backslash is literal
				} else if .format.EscapeNotInEscapingQuote() {
					.add() // cmd: caret is literal inside double quotes
				} else {
					.state = ESCAPING_QUOTED_STATE
				}
			default:
				.add()
			}
		case QUOTING_STATE: // in non-escaping single quotes
			switch  {
			case eofRuneClass: // EOF found when expecting closing quote
				.removeLastRaw()
				return , 
			case nonEscapingQuoteRuneClass:
				.rawQuote = false
				if .format.NonEscapingQuoteEscapes() {
					// Peek: '' → literal ' (stay in quote), else close
					, ,  := .ReadRune()
					if  == nil && .classifier.ClassifyRune() == nonEscapingQuoteRuneClass {
						.RawValue += string()
						.add() // emit one literal '
						// stay in QUOTING_STATE
					} else {
						// Not a doubled quote — unread and close
						if  == nil {
							.UnreadRune()
						}
						.state = IN_WORD_STATE
					}
				} else {
					.state = IN_WORD_STATE
				}
			case escapeRuneClass:
				if .format.NonEscapingQuoteBackslashEscapes() {
					// Fish: only \' and \\ are escapes inside single quotes.
					// Other \X sequences are literal (\ + X).
					, ,  := .ReadRune()
					if  == nil {
						.RawValue += string()
						switch  {
						case '\'', '\\':
							.add() // emit just the escaped char
						default:
							// Not an escape — emit both \ and the char
							.add()
							.add()
						}
						// stay in QUOTING_STATE
					} else {
						// EOF after \ — emit \ as literal
						.add()
					}
				} else {
					.add() // literal backslash
				}
			default:
				.add()
			}
		case QUOTING_TRIPLE_STATE: // in triple-quoted non-escaping string ('''...''')
			switch  {
			case eofRuneClass: // EOF found when expecting closing triple-quote
				.removeLastRaw()
				return , 
			case nonEscapingQuoteRuneClass, escapingQuoteRuneClass:
				if  == .tripleQuoteRune {
					, , ,  := .checkTripleClose()
					if  {
						.RawValue += string()
						.RawValue += string()
						.rawQuote = false
						.tripleQuoteRune = 0
						.state = IN_WORD_STATE
					} else if  != 0 {
						.RawValue += string()
						.add()
						.add()
					} else {
						.add()
					}
				} else {
					.add()
				}
			default:
				.add()
			}
		case QUOTING_TRIPLE_ESCAPING_STATE: // in triple-quoted escaping string ("""...""")
			switch  {
			case eofRuneClass: // EOF found when expecting closing triple-quote
				.removeLastRaw()
				return , 
			case escapingQuoteRuneClass, nonEscapingQuoteRuneClass:
				if  == .tripleQuoteRune {
					, , ,  := .checkTripleClose()
					if  {
						.RawValue += string()
						.RawValue += string()
						.rawQuote = false
						.tripleQuoteRune = 0
						.state = IN_WORD_STATE
					} else if  != 0 {
						.RawValue += string()
						.add()
						.add()
					} else {
						.add()
					}
				} else {
					.add()
				}
			case escapeRuneClass:
				if .rawQuote {
					.add() // raw string: backslash is literal
				} else {
					.state = ESCAPING_QUOTED_STATE
				}
			default:
				.add()
			}
		case COMMENT_STATE: // in a comment
			switch  {
			case eofRuneClass:
				return , 
			case spaceRuneClass:
				if  == '\n' {
					.removeLastRaw()
					.state = START_STATE
					return , 
				} else {
					.add()
				}
			default:
				.add()
			}
		case BLOCK_COMMENT_STATE: // in a block comment (e.g. PowerShell <# ... #>)
			// Match the closer rune-by-rune. nextRune is already in RawValue.
			if rune(.blockCloser[.blockCloserIdx]) ==  {
				.blockCloserIdx++
				if .blockCloserIdx >= len(.blockCloser) {
					// Full closer matched — return the comment token
					.blockCloser = ""
					.blockCloserIdx = 0
					.state = START_STATE
					return , 
				}
				// Partial match — keep scanning
			} else {
				// Reset closer match index
				.blockCloserIdx = 0
				// Check if this rune restarts the closer match
				if rune(.blockCloser[.blockCloserIdx]) ==  {
					.blockCloserIdx++
				}
			}
			if  == eofRuneClass {
				.removeLastRaw()
				return , 
			}
		default:
			return nil, fmt.Errorf("unexpected state: %v", .state)
		}
	}
}

// scanStopParsing reads tokens in raw mode after a stop-parsing token (e.g.
// PowerShell --%). In this mode, everything is literal until newline or
// a pipeline delimiter (|). Double quotes toggle an "in quotes" state
// where | is not treated as a delimiter, matching PowerShell's
// GetVerbatimCommandArgument behavior. Single & is treated as literal
// (&& is not specially handled due to bufio's single-unread limitation;
// in practice --% mode passes everything literally to native commands).
func ( *tokenizer) () (*Token, error) {
	 := &Token{}
	.Type = WORD_TOKEN
	.state = STOP_PARSING_STATE
	 := false

	// Skip leading whitespace (matches PowerShell's GetVerbatimCommandArgument
	// which calls SkipWhiteSpace before collecting the raw argument)
	for {
		, ,  := .ReadRune()
		if  != nil {
			if  == io.EOF {
				// No content after --% — return empty word at cursor
				.Span.Start = .index
				.Span.End = .index
				.state = START_STATE
				return , nil
			}
			return nil, 
		}
		if  != ' ' &&  != '\t' &&  != '\r' &&  != '\n' {
			.UnreadRune()
			break
		}
		// If we hit a newline, there's no raw content on this line
		if  == '\r' ||  == '\n' {
			.UnreadRune()
			.Span.Start = .index
			.Span.End = .index
			.state = START_STATE
			return , nil
		}
	}

	for {
		, ,  := .ReadRune()
		if  != nil {
			if  == io.EOF {
				if len(.RawValue) == 0 {
					return nil, 
				}
				.Span.End = .Span.Start + len([]rune(.RawValue))
				.State = STOP_PARSING_STATE
				.state = START_STATE
				return , nil
			}
			return nil, 
		}

		// Set span start on first rune
		if len(.RawValue) == 0 {
			.Span.Start = .index - 1
		}

		// Check for end conditions before adding to token
		if  == '\r' ||  == '\n' {
			.UnreadRune()
			if len(.RawValue) == 0 {
				.Span.Start = .index
				.Span.End = .index
				.state = START_STATE
				return , nil
			}
			.Span.End = .Span.Start + len([]rune(.RawValue))
			.State = STOP_PARSING_STATE
			.state = START_STATE
			return , nil
		}

		.RawValue += string()

		if  == '"' {
			 = !
			.add()
			continue
		}

		if ! &&  == '|' {
			// Pipeline delimiter — return word before it
			.removeLastRaw()
			.UnreadRune()
			if len(.RawValue) == 0 {
				.Span.Start = .index
				.Span.End = .index
			} else {
				.Span.End = .Span.Start + len([]rune(.RawValue))
			}
			.State = STOP_PARSING_STATE
			.state = START_STATE
			return , nil
		}

		.add()
	}
}

// Next returns the next token in the stream.
func ( *tokenizer) () (*Token, error) {
	// If we're in stop-parsing state, scan in raw mode
	if .state == STOP_PARSING_STATE {
		,  := .scanStopParsing()
		if  == nil {
			// scanStopParsing already sets token.State and t.state
			if .Span.End == 0 && .Span.Start >= 0 {
				.Span.End = .Span.Start + len([]rune(.RawValue))
			}
		}
		return , 
	}

	,  := .scanStream()
	if  == nil {
		.State = .state
		if .Span.End == 0 && .Span.Start >= 0 {
			.Span.End = .Span.Start + len([]rune(.RawValue))
		}
		if .Type == WORDBREAK_TOKEN {
			.WordbreakType = .format.ClassifyOperator(.RawValue)
		}
		// Keyword operators (fish and/or/not): reclassify WORD_TOKEN as WORDBREAK_TOKEN
		if .Type == WORD_TOKEN {
			if  := .format.KeywordOperators();  != nil {
				if ,  := [.RawValue];  {
					.Type = WORDBREAK_TOKEN
					.WordbreakType = 
				}
			}
			// Check for stop-parsing token (e.g. PowerShell --%)
			if ,  := .format.(stopParsingToken);  {
				if .Value == .StopParsingWord() && .Value == .RawValue {
					.state = STOP_PARSING_STATE
					.stopParsingDelim = ""
				}
			}
		}
	}
	return , 
}

// Split partitions a string into tokens using the given format.
// Unknown format names are rejected.
func ( string,  Format) (TokenSlice, error) {
	,  := formatImplFor()
	if ! {
		return nil, fmt.Errorf("unknown format: %q", )
	}
	 := newLexer(strings.NewReader(), )
	 := make(TokenSlice, 0)
	for {
		,  := .Next()
		if  != nil {
			if  == io.EOF {
				break
			}
			return nil, 
		}
		 = append(, *)
	}
	if ,  := .(postProcessor);  {
		 = .PostProcess()
	}
	return , nil
}

// Join concatenates words using the given format's quoting rules.
// Unknown format names fall back to the default format.
func ( []string,  Format) string {
	,  := formatImplFor()
	if ! {
		 = formatImpls[Default]
	}
	 := make([]string, 0, len())
	for ,  := range  {
		 = append(, .QuoteWord())
	}
	return strings.Join(, " ")
}

// Quote returns the given word quoted according to the format's quoting
// rules, so that it parses back into a single token when split with the same
// format. Unknown format names fall back to the default format.
func ( string,  Format) string {
	,  := formatImplFor()
	if ! {
		 = formatImpls[Default]
	}
	return .QuoteWord()
}

// Escape returns the word's content escaped for embedding inside
// string literals whose surrounding quote characters the caller supplies,
// e.g. when a generated template already carries the quotes. It is the
// interior variant of Quote. Unknown format names fall back to the default
// format. Formats without a dedicated string-interior rule (cmd, tcsh,
// and others) also fall back; the result may not be valid for those
// formats' own string literals (e.g. a newline close/reopen sequence is a
// syntax error in tcsh). The bash/zsh/oil result is meant to be
// embedded in double quotes by the caller: newlines are represented by a
// quote close/reopen sequence instead of backslash-newline. The nushell
// result is meant to be embedded in double quotes: it uses only escape
// sequences from nushell's own set, as unrecognized escapes are parse
// errors there.
func ( string,  Format) string {
	switch  {
	case Default, Bash, Zsh, Oil:
		return bashStringEscape()
	case Fish:
		return fishStringEscape()
	case Elvish:
		return elvishStringEscape()
	case Nushell:
		return nushellStringEscape()
	case Powershell:
		return powershellStringEscape()
	case Xonsh:
		return xonshStringEscape()
	case Lua:
		return luaStringEscape()
	}
	return posixStringEscape()
}

// IsBareWord reports whether the given word is a bareword for the format:
// it stands as a single inert token in unquoted position. Identifier
// validity is not implied. Empty words are not barewords. Unknown formats
// fall back to the default format, like in Quote.
func ( string,  Format) bool {
	,  := formatImplFor()
	if ! {
		 = formatImpls[Default]
	}
	return .IsBareWord()
}