Debian Codegraph @

crazy_complete/string_stream.py

raw
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 # Copyright (C) 2025-2026 Benjamin Abendroth <[email protected]>
3
4 '''Module containing code for parsing strings as a stream.'''
5
6
7 class StringStream:
8 '''String stream class for reading a string.'''
9
10 def __init__(self, string):
11 self.s = string
12 self.i = 0
13 self.length = len(string)
14
15 def peek(self, seek=0):
16 '''Return character at current position + seek without advancing.'''
17
18 try:
19 return self.s[self.i + seek]
20 except IndexError:
21 return None
22
23 def peek_str(self, length=1):
24 '''Return substring of given length from current position.'''
25
26 return self.s[self.i:length]
27
28 def get(self):
29 '''Return current character and advance position by one.'''
30
31 c = self.s[self.i]
32 self.i += 1
33 return c
34
35 def have(self):
36 '''Return True if iterator is not at its end.'''
37
38 return self.i < self.length
39
40 def advance(self, length):
41 '''Advance the stream by a given length.'''
42
43 self.i += length
44
45 def parse_shell_single_quote(self, in_quotes=False):
46 '''Parse a single-quoted shell string.'''
47
48 if not in_quotes:
49 assert self.get() == "'"
50
51 string = ''
52
53 while True:
54 try:
55 c = self.get()
56 except IndexError as e:
57 raise ValueError("Unclosed single quote") from e
58
59 if c == "'":
60 return string
61
62 string += c
63
64 def parse_shell_double_quote(self, in_quotes=False):
65 '''Parse a double-quoted shell string.'''
66
67 if not in_quotes:
68 assert self.get() == '"'
69
70 string = ''
71
72 while True:
73 try:
74 c = self.get()
75 except IndexError as e:
76 raise ValueError("Unclosed double quote") from e
77
78 if c == '\\':
79 try:
80 string += self.get()
81 except IndexError as e:
82 raise ValueError("Missing character after backslash") from e
83
84 elif c == '"':
85 return string
86
87 else:
88 string += c