1"""Parser for attributes::
2
3 attributes { id = "foo", class = "bar baz",
4 key1 = "val1", key2 = "val2" }
5
6Adapted from:
7https://github.com/jgm/djot/blob/fae7364b86bfce69bc6d5b5eede1f5196d845fd6/djot/attributes.lua#L1
8
9syntax:
10
11attributes <- '{' whitespace* attribute (whitespace attribute)* whitespace* '}'
12attribute <- identifier | class | keyval
13identifier <- '#' name
14class <- '.' name
15name <- (nonspace, nonpunctuation other than ':', '_', '-')+
16keyval <- key '=' val
17key <- (ASCII_ALPHANUM | ':' | '_' | '-')+
18val <- bareval | quotedval
19bareval <- (ASCII_ALPHANUM | ':' | '_' | '-')+
20quotedval <- '"' ([^"] | '\"') '"'
21"""
22
23from __future__ import annotations
24
25from collections.abc import Callable
26from enum import Enum
27import re
28
29
30class State(Enum):
31 START = 0
32 SCANNING = 1
33 SCANNING_ID = 2
34 SCANNING_CLASS = 3
35 SCANNING_KEY = 4
36 SCANNING_VALUE = 5
37 SCANNING_BARE_VALUE = 6
38 SCANNING_QUOTED_VALUE = 7
39 SCANNING_COMMENT = 8
40 SCANNING_ESCAPED = 9
41 DONE = 10
42
43
44REGEX_SPACE = re.compile(r"\s")
45REGEX_SPACE_PUNCTUATION = re.compile(r"[\s!\"#$%&'()*+,./;<=>?@[\]^`{|}~]")
46REGEX_KEY_CHARACTERS = re.compile(r"[a-zA-Z\d_:-]")
47
48
49class TokenState:
50 def __init__(self) -> None:
51 self._tokens: list[tuple[int, int, str]] = []
52 self.start: int = 0
53
54 def set_start(self, start: int) -> None:
55 self.start = start
56
57 def append(self, start: int, end: int, ttype: str) -> None:
58 self._tokens.append((start, end, ttype))
59
60 def compile(self, string: str) -> dict[str, str]:
61 """compile the tokens into a dictionary"""
62 attributes = {}
63 classes = []
64 idx = 0
65 while idx < len(self._tokens):
66 start, end, ttype = self._tokens[idx]
67 if ttype == "id":
68 attributes["id"] = string[start:end]
69 elif ttype == "class":
70 classes.append(string[start:end])
71 elif ttype == "key":
72 key = string[start:end]
73 if idx + 1 < len(self._tokens):
74 start, end, ttype = self._tokens[idx + 1]
75 if ttype == "value":
76 if key == "class":
77 classes.append(string[start:end])
78 else:
79 attributes[key] = string[start:end]
80 idx += 1
81 idx += 1
82 if classes:
83 attributes["class"] = " ".join(classes)
84 return attributes
85
86 def __str__(self) -> str:
87 return str(self._tokens)
88
89 def __repr__(self) -> str:
90 return repr(self._tokens)
91
92
93class ParseError(Exception):
94 def __init__(self, msg: str, pos: int) -> None:
95 self.pos = pos
96 super().__init__(msg + f" at position {pos}")
97
98
99def parse(string: str) -> tuple[int, dict[str, str]]:
100 """Parse attributes from start of string.
101
102 :returns: (length of parsed string, dict of attributes)
103 :raises ParseError: if the attributes are malformed,
104 or the string ends before the closing `}`
105 """
106 pos = 0
107 state: State = State.START
108 tokens = TokenState()
109 # found once, so that checking for a later `%` at each `}` does not
110 # rescan the rest of the string (which would be quadratic in its length)
111 last_percent = string.rfind("%")
112 while pos < len(string):
113 if (
114 state == State.SCANNING_COMMENT
115 and string[pos] == "}"
116 and pos > last_percent
117 ):
118 # a comment ends at the next `%`, but there is none left to close it,
119 # so this `}` ends both the comment and the attributes
120 state = State.DONE
121 else:
122 state = HANDLERS[state](string[pos], pos, tokens)
123 if state == State.DONE:
124 return pos, tokens.compile(string)
125 pos = pos + 1
126
127 raise ParseError("Attributes not terminated", pos)
128
129
130def handle_start(char: str, pos: int, tokens: TokenState) -> State:
131 if char == "{":
132 return State.SCANNING
133 raise ParseError("Attributes must start with '{'", pos)
134
135
136def handle_scanning(char: str, pos: int, tokens: TokenState) -> State:
137 if char == " " or char == "\t" or char == "\n" or char == "\r":
138 return State.SCANNING
139 if char == "}":
140 return State.DONE
141 if char == "#":
142 tokens.set_start(pos)
143 return State.SCANNING_ID
144 if char == "%":
145 tokens.set_start(pos)
146 return State.SCANNING_COMMENT
147 if char == ".":
148 tokens.set_start(pos)
149 return State.SCANNING_CLASS
150 if REGEX_KEY_CHARACTERS.fullmatch(char):
151 tokens.set_start(pos)
152 return State.SCANNING_KEY
153
154 raise ParseError(f"Unexpected character whilst scanning: {char}", pos)
155
156
157def handle_scanning_comment(char: str, pos: int, tokens: TokenState) -> State:
158 if char == "%":
159 return State.SCANNING
160
161 return State.SCANNING_COMMENT
162
163
164def handle_scanning_id(char: str, pos: int, tokens: TokenState) -> State:
165 if not REGEX_SPACE_PUNCTUATION.fullmatch(char):
166 return State.SCANNING_ID
167
168 if char == "}":
169 if (pos - 1) > tokens.start:
170 tokens.append(tokens.start + 1, pos, "id")
171 return State.DONE
172
173 if REGEX_SPACE.fullmatch(char):
174 if (pos - 1) > tokens.start:
175 tokens.append(tokens.start + 1, pos, "id")
176 return State.SCANNING
177
178 raise ParseError(f"Unexpected character whilst scanning id: {char}", pos)
179
180
181def handle_scanning_class(char: str, pos: int, tokens: TokenState) -> State:
182 if not REGEX_SPACE_PUNCTUATION.fullmatch(char):
183 return State.SCANNING_CLASS
184
185 if char == "}":
186 if (pos - 1) > tokens.start:
187 tokens.append(tokens.start + 1, pos, "class")
188 return State.DONE
189
190 if REGEX_SPACE.fullmatch(char):
191 if (pos - 1) > tokens.start:
192 tokens.append(tokens.start + 1, pos, "class")
193 return State.SCANNING
194
195 raise ParseError(f"Unexpected character whilst scanning class: {char}", pos)
196
197
198def handle_scanning_key(char: str, pos: int, tokens: TokenState) -> State:
199 if char == "=":
200 tokens.append(tokens.start, pos, "key")
201 return State.SCANNING_VALUE
202
203 if REGEX_KEY_CHARACTERS.fullmatch(char):
204 return State.SCANNING_KEY
205
206 raise ParseError(f"Unexpected character whilst scanning key: {char}", pos)
207
208
209def handle_scanning_value(char: str, pos: int, tokens: TokenState) -> State:
210 if char == '"':
211 tokens.set_start(pos)
212 return State.SCANNING_QUOTED_VALUE
213
214 if REGEX_KEY_CHARACTERS.fullmatch(char):
215 tokens.set_start(pos)
216 return State.SCANNING_BARE_VALUE
217
218 raise ParseError(f"Unexpected character whilst scanning value: {char}", pos)
219
220
221def handle_scanning_bare_value(char: str, pos: int, tokens: TokenState) -> State:
222 if REGEX_KEY_CHARACTERS.fullmatch(char):
223 return State.SCANNING_BARE_VALUE
224
225 if char == "}":
226 tokens.append(tokens.start, pos, "value")
227 return State.DONE
228
229 if REGEX_SPACE.fullmatch(char):
230 tokens.append(tokens.start, pos, "value")
231 return State.SCANNING
232
233 raise ParseError(f"Unexpected character whilst scanning bare value: {char}", pos)
234
235
236def handle_scanning_escaped(char: str, pos: int, tokens: TokenState) -> State:
237 return State.SCANNING_QUOTED_VALUE
238
239
240def handle_scanning_quoted_value(char: str, pos: int, tokens: TokenState) -> State:
241 if char == '"':
242 tokens.append(tokens.start + 1, pos, "value")
243 return State.SCANNING
244
245 if char == "\\":
246 return State.SCANNING_ESCAPED
247
248 if char == "{" or char == "}":
249 raise ParseError(
250 f"Unexpected character whilst scanning quoted value: {char}", pos
251 )
252
253 if char == "\n":
254 tokens.append(tokens.start + 1, pos, "value")
255 return State.SCANNING_QUOTED_VALUE
256
257 return State.SCANNING_QUOTED_VALUE
258
259
260HANDLERS: dict[State, Callable[[str, int, TokenState], State]] = {
261 State.START: handle_start,
262 State.SCANNING: handle_scanning,
263 State.SCANNING_COMMENT: handle_scanning_comment,
264 State.SCANNING_ID: handle_scanning_id,
265 State.SCANNING_CLASS: handle_scanning_class,
266 State.SCANNING_KEY: handle_scanning_key,
267 State.SCANNING_VALUE: handle_scanning_value,
268 State.SCANNING_BARE_VALUE: handle_scanning_bare_value,
269 State.SCANNING_QUOTED_VALUE: handle_scanning_quoted_value,
270 State.SCANNING_ESCAPED: handle_scanning_escaped,
271}