vendor/github.com/charmbracelet/x/ansi/parser.go

370 lines · 10171 bytes

  1package ansi
  2
  3import (
  4	"unicode/utf8"
  5	"unsafe"
  6
  7	"github.com/charmbracelet/x/ansi/parser"
  8)
  9
 10// ParserDispatcher is a function that dispatches a sequence.
 11type ParserDispatcher func(Sequence)
 12
 13// Parser represents a DEC ANSI compatible sequence parser.
 14//
 15// It uses a state machine to parse ANSI escape sequences and control
 16// characters. The parser is designed to be used with a terminal emulator or
 17// similar application that needs to parse ANSI escape sequences and control
 18// characters.
 19// See package [parser] for more information.
 20//
 21//go:generate go run ./gen.go
 22type Parser struct {
 23	// Params contains the raw parameters of the sequence.
 24	// These parameters used when constructing CSI and DCS sequences.
 25	Params []int
 26
 27	// Data contains the raw data of the sequence.
 28	// These data used when constructing OSC, DCS, SOS, PM, and APC sequences.
 29	Data []byte
 30
 31	// DataLen keeps track of the length of the data buffer.
 32	// If DataLen is -1, the data buffer is unlimited and will grow as needed.
 33	// Otherwise, DataLen is limited by the size of the Data buffer.
 34	DataLen int
 35
 36	// ParamsLen keeps track of the number of parameters.
 37	// This is limited by the size of the Params buffer.
 38	//
 39	// This is also used when collecting UTF-8 runes to keep track of the
 40	// number of rune bytes collected.
 41	ParamsLen int
 42
 43	// Cmd contains the raw command along with the private marker and
 44	// intermediate bytes of the sequence.
 45	// The first lower byte contains the command byte, the next byte contains
 46	// the private marker, and the next byte contains the intermediate byte.
 47	//
 48	// This is also used when collecting UTF-8 runes treating it as a slice of
 49	// 4 bytes.
 50	Cmd int
 51
 52	// State is the current state of the parser.
 53	State byte
 54}
 55
 56// NewParser returns a new parser with the given sizes allocated.
 57// If dataSize is zero, the underlying data buffer will be unlimited and will
 58// grow as needed.
 59func NewParser(paramsSize, dataSize int) *Parser {
 60	s := new(Parser)
 61	if dataSize <= 0 {
 62		dataSize = 0
 63		s.DataLen = -1
 64	}
 65	s.Params = make([]int, paramsSize)
 66	s.Data = make([]byte, dataSize)
 67	return s
 68}
 69
 70// Reset resets the parser to its initial state.
 71func (p *Parser) Reset() {
 72	p.clear()
 73	p.State = parser.GroundState
 74}
 75
 76// clear clears the parser parameters and command.
 77func (p *Parser) clear() {
 78	if len(p.Params) > 0 {
 79		p.Params[0] = parser.MissingParam
 80	}
 81	p.ParamsLen = 0
 82	p.Cmd = 0
 83}
 84
 85// clearCmd clears the parser command, params len and data len.
 86func (p *Parser) clearCmd() {
 87	p.Cmd = 0
 88	p.ParamsLen = 0
 89	p.DataLen = 0
 90}
 91
 92// StateName returns the name of the current state.
 93func (p *Parser) StateName() string {
 94	return parser.StateNames[p.State]
 95}
 96
 97// Parse parses the given dispatcher and byte buffer.
 98func (p *Parser) Parse(dispatcher ParserDispatcher, b []byte) {
 99	for i := 0; i < len(b); i++ {
100		p.Advance(dispatcher, b[i], i < len(b)-1)
101	}
102}
103
104// Advance advances the parser with the given dispatcher and byte.
105func (p *Parser) Advance(dispatcher ParserDispatcher, b byte, more bool) parser.Action {
106	switch p.State {
107	case parser.Utf8State:
108		// We handle UTF-8 here.
109		return p.advanceUtf8(dispatcher, b)
110	default:
111		return p.advance(dispatcher, b, more)
112	}
113}
114
115func (p *Parser) collectRune(b byte) {
116	if p.ParamsLen >= utf8.UTFMax {
117		return
118	}
119
120	shift := p.ParamsLen * 8
121	p.Cmd &^= 0xff << shift
122	p.Cmd |= int(b) << shift
123	p.ParamsLen++
124}
125
126func (p *Parser) advanceUtf8(dispatcher ParserDispatcher, b byte) parser.Action {
127	// Collect UTF-8 rune bytes.
128	p.collectRune(b)
129	rw := utf8ByteLen(byte(p.Cmd & 0xff))
130	if rw == -1 {
131		// We panic here because the first byte comes from the state machine,
132		// if this panics, it means there is a bug in the state machine!
133		panic("invalid rune") // unreachable
134	}
135
136	if p.ParamsLen < rw {
137		return parser.CollectAction
138	}
139
140	// We have enough bytes to decode the rune using unsafe
141	r, _ := utf8.DecodeRune((*[utf8.UTFMax]byte)(unsafe.Pointer(&p.Cmd))[:rw])
142	if dispatcher != nil {
143		dispatcher(Rune(r))
144	}
145
146	p.State = parser.GroundState
147	p.ParamsLen = 0
148
149	return parser.PrintAction
150}
151
152func (p *Parser) advance(d ParserDispatcher, b byte, more bool) parser.Action {
153	state, action := parser.Table.Transition(p.State, b)
154
155	// We need to clear the parser state if the state changes from EscapeState.
156	// This is because when we enter the EscapeState, we don't get a chance to
157	// clear the parser state. For example, when a sequence terminates with a
158	// ST (\x1b\\ or \x9c), we dispatch the current sequence and transition to
159	// EscapeState. However, the parser state is not cleared in this case and
160	// we need to clear it here before dispatching the esc sequence.
161	if p.State != state {
162		if p.State == parser.EscapeState {
163			p.performAction(d, parser.ClearAction, state, b)
164		}
165		if action == parser.PutAction &&
166			p.State == parser.DcsEntryState && state == parser.DcsStringState {
167			// XXX: This is a special case where we need to start collecting
168			// non-string parameterized data i.e. doesn't follow the ECMA-48 §
169			// 5.4.1 string parameters format.
170			p.performAction(d, parser.StartAction, state, 0)
171		}
172	}
173
174	// Handle special cases
175	switch {
176	case b == ESC && p.State == parser.EscapeState:
177		// Two ESCs in a row
178		p.performAction(d, parser.ExecuteAction, state, b)
179		if !more {
180			// Two ESCs at the end of the buffer
181			p.performAction(d, parser.ExecuteAction, state, b)
182		}
183	case b == ESC && !more:
184		// Last byte is an ESC
185		p.performAction(d, parser.ExecuteAction, state, b)
186	case p.State == parser.EscapeState && b == 'P' && !more:
187		// ESC P (DCS) at the end of the buffer
188		p.performAction(d, parser.DispatchAction, state, b)
189	case p.State == parser.EscapeState && b == 'X' && !more:
190		// ESC X (SOS) at the end of the buffer
191		p.performAction(d, parser.DispatchAction, state, b)
192	case p.State == parser.EscapeState && b == '[' && !more:
193		// ESC [ (CSI) at the end of the buffer
194		p.performAction(d, parser.DispatchAction, state, b)
195	case p.State == parser.EscapeState && b == ']' && !more:
196		// ESC ] (OSC) at the end of the buffer
197		p.performAction(d, parser.DispatchAction, state, b)
198	case p.State == parser.EscapeState && b == '^' && !more:
199		// ESC ^ (PM) at the end of the buffer
200		p.performAction(d, parser.DispatchAction, state, b)
201	case p.State == parser.EscapeState && b == '_' && !more:
202		// ESC _ (APC) at the end of the buffer
203		p.performAction(d, parser.DispatchAction, state, b)
204	default:
205		p.performAction(d, action, state, b)
206	}
207
208	p.State = state
209
210	return action
211}
212
213func (p *Parser) performAction(dispatcher ParserDispatcher, action parser.Action, state parser.State, b byte) {
214	switch action {
215	case parser.IgnoreAction:
216		break
217
218	case parser.ClearAction:
219		p.clear()
220
221	case parser.PrintAction:
222		if dispatcher != nil {
223			dispatcher(Rune(b))
224		}
225
226	case parser.ExecuteAction:
227		if dispatcher != nil {
228			dispatcher(ControlCode(b))
229		}
230
231	case parser.MarkerAction:
232		// Collect private marker
233		// we only store the last marker
234		p.Cmd &^= 0xff << parser.MarkerShift
235		p.Cmd |= int(b) << parser.MarkerShift
236
237	case parser.CollectAction:
238		if state == parser.Utf8State {
239			// Reset the UTF-8 counter
240			p.ParamsLen = 0
241			p.collectRune(b)
242		} else {
243			// Collect intermediate bytes
244			// we only store the last intermediate byte
245			p.Cmd &^= 0xff << parser.IntermedShift
246			p.Cmd |= int(b) << parser.IntermedShift
247		}
248
249	case parser.ParamAction:
250		// Collect parameters
251		if p.ParamsLen >= len(p.Params) {
252			break
253		}
254
255		if b >= '0' && b <= '9' {
256			if p.Params[p.ParamsLen] == parser.MissingParam {
257				p.Params[p.ParamsLen] = 0
258			}
259
260			p.Params[p.ParamsLen] *= 10
261			p.Params[p.ParamsLen] += int(b - '0')
262		}
263
264		if b == ':' {
265			p.Params[p.ParamsLen] |= parser.HasMoreFlag
266		}
267
268		if b == ';' || b == ':' {
269			p.ParamsLen++
270			if p.ParamsLen < len(p.Params) {
271				p.Params[p.ParamsLen] = parser.MissingParam
272			}
273		}
274
275	case parser.StartAction:
276		if p.DataLen < 0 && p.Data != nil {
277			p.Data = p.Data[:0]
278		} else {
279			p.DataLen = 0
280		}
281		if p.State >= parser.DcsEntryState && p.State <= parser.DcsStringState {
282			// Collect the command byte for DCS
283			p.Cmd |= int(b)
284		} else {
285			p.Cmd = parser.MissingCommand
286		}
287
288	case parser.PutAction:
289		switch p.State {
290		case parser.OscStringState:
291			if b == ';' && p.Cmd == parser.MissingCommand {
292				// Try to parse the command
293				datalen := len(p.Data)
294				if p.DataLen >= 0 {
295					datalen = p.DataLen
296				}
297				for i := 0; i < datalen; i++ {
298					d := p.Data[i]
299					if d < '0' || d > '9' {
300						break
301					}
302					if p.Cmd == parser.MissingCommand {
303						p.Cmd = 0
304					}
305					p.Cmd *= 10
306					p.Cmd += int(d - '0')
307				}
308			}
309		}
310
311		if p.DataLen < 0 {
312			p.Data = append(p.Data, b)
313		} else {
314			if p.DataLen < len(p.Data) {
315				p.Data[p.DataLen] = b
316				p.DataLen++
317			}
318		}
319
320	case parser.DispatchAction:
321		// Increment the last parameter
322		if p.ParamsLen > 0 && p.ParamsLen < len(p.Params)-1 ||
323			p.ParamsLen == 0 && len(p.Params) > 0 && p.Params[0] != parser.MissingParam {
324			p.ParamsLen++
325		}
326
327		if dispatcher == nil {
328			break
329		}
330
331		var seq Sequence
332		data := p.Data
333		if p.DataLen >= 0 {
334			data = data[:p.DataLen]
335		}
336		switch p.State {
337		case parser.CsiEntryState, parser.CsiParamState, parser.CsiIntermediateState:
338			p.Cmd |= int(b)
339			seq = CsiSequence{Cmd: p.Cmd, Params: p.Params[:p.ParamsLen]}
340		case parser.EscapeState, parser.EscapeIntermediateState:
341			p.Cmd |= int(b)
342			seq = EscSequence(p.Cmd)
343		case parser.DcsEntryState, parser.DcsParamState, parser.DcsIntermediateState, parser.DcsStringState:
344			seq = DcsSequence{Cmd: p.Cmd, Params: p.Params[:p.ParamsLen], Data: data}
345		case parser.OscStringState:
346			seq = OscSequence{Cmd: p.Cmd, Data: data}
347		case parser.SosStringState:
348			seq = SosSequence{Data: data}
349		case parser.PmStringState:
350			seq = PmSequence{Data: data}
351		case parser.ApcStringState:
352			seq = ApcSequence{Data: data}
353		}
354
355		dispatcher(seq)
356	}
357}
358
359func utf8ByteLen(b byte) int {
360	if b <= 0b0111_1111 { // 0x00-0x7F
361		return 1
362	} else if b >= 0b1100_0000 && b <= 0b1101_1111 { // 0xC0-0xDF
363		return 2
364	} else if b >= 0b1110_0000 && b <= 0b1110_1111 { // 0xE0-0xEF
365		return 3
366	} else if b >= 0b1111_0000 && b <= 0b1111_0111 { // 0xF0-0xF7
367		return 4
368	}
369	return -1
370}