dissect.cstruct 5.0.dev20__py3-none-any.whl → 5.0.dev22__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,7 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  from typing import TYPE_CHECKING, Any
4
4
 
5
- from dissect.cstruct.exception import ExpressionParserError, UnknownIdentifierError
5
+ from dissect.cstruct.exception import DefinitionError, ExpressionParserError, UnknownIdentifierError
6
6
  from dissect.cstruct.lexer import IDENTIFIER_TYPES, Lexer, TokenCursor, TokenType, join_tokens
7
7
  from dissect.cstruct.util import offsetof, sizeof
8
8
 
@@ -11,6 +11,7 @@ if TYPE_CHECKING:
11
11
 
12
12
  from dissect.cstruct import cstruct
13
13
  from dissect.cstruct.lexer import Token
14
+ from dissect.cstruct.types import BaseType
14
15
 
15
16
  _MISSING = object()
16
17
 
@@ -73,12 +74,28 @@ PRECEDENCE_LEVELS = {
73
74
  }
74
75
 
75
76
 
76
- def _sizeof(cs: cstruct, name: str) -> int:
77
- return sizeof(cs.resolve(name))
77
+ def _resolve_type(cs: cstruct, name: str, pointers: int, dimensions: list[int]) -> type[BaseType]:
78
+ """Resolve the type of ``sizeof`` or ``offsetof`` like the type of a field, e.g. ``uint8 *[4]``."""
79
+ type_ = cs.resolve(name)
80
+ for _ in range(pointers):
81
+ type_ = cs._make_pointer(type_)
82
+ for count in reversed(dimensions):
83
+ type_ = cs._make_array(type_, max(0, count))
84
+ return type_
78
85
 
79
86
 
80
- def _offsetof(cs: cstruct, name: str, field: str) -> int:
81
- return offsetof(cs.resolve(name), field)
87
+ def _sizeof(type_: type[BaseType]) -> int:
88
+ try:
89
+ return sizeof(type_)
90
+ except TypeError:
91
+ raise DefinitionError(f"Type '{type_.__name__}' has a dynamic size") from None
92
+
93
+
94
+ def _offsetof(type_: type[BaseType], field: str) -> int:
95
+ try:
96
+ return offsetof(type_, field)
97
+ except (TypeError, ValueError) as e:
98
+ raise DefinitionError(str(e)) from None
82
99
 
83
100
 
84
101
  FUNCTIONS: dict[TokenType, Callable[..., int]] = {
@@ -112,7 +129,7 @@ def _identifier(cs: cstruct, context: dict[str, Any], ident: str) -> int:
112
129
 
113
130
 
114
131
  # Globals used by the source code of an expression
115
- SOURCE_GLOBALS = {func.__name__: func for func in (_identifier, *FUNCTIONS.values())}
132
+ SOURCE_GLOBALS = {func.__name__: func for func in (_identifier, _resolve_type, *FUNCTIONS.values())}
116
133
 
117
134
 
118
135
  class _Evaluator:
@@ -134,8 +151,14 @@ class _Evaluator:
134
151
  def binary(self, operator: TokenType, left: int, right: int) -> int:
135
152
  return BINARY_OPERATORS[operator](left, right)
136
153
 
137
- def function(self, operator: TokenType, args: list[str]) -> int:
138
- return FUNCTIONS[operator](self.cs, *args)
154
+ def function(self, operator: TokenType, args: tuple[Any, ...]) -> int:
155
+ (name, pointers, dimensions), *fields = args
156
+ if pointers or dimensions:
157
+ counts = [dimension._run(self) for dimension in dimensions]
158
+ type_ = _resolve_type(self.cs, name, pointers, counts)
159
+ else:
160
+ type_ = self.cs.resolve(name)
161
+ return FUNCTIONS[operator](type_, *fields)
139
162
 
140
163
 
141
164
  class _SourceBuilder:
@@ -159,8 +182,14 @@ class _SourceBuilder:
159
182
  def binary(self, operator: TokenType, left: str, right: str) -> str:
160
183
  return f"({left} {OPERATOR_SOURCE[operator]} {right})"
161
184
 
162
- def function(self, operator: TokenType, args: list[str]) -> str:
163
- return f"{FUNCTIONS[operator].__name__}(cs, {', '.join(map(repr, args))})"
185
+ def function(self, operator: TokenType, args: tuple[Any, ...]) -> str:
186
+ (name, pointers, dimensions), *fields = args
187
+ if pointers or dimensions:
188
+ counts = ", ".join(dimension._run(self) for dimension in dimensions)
189
+ type_ = f"_resolve_type(cs, {name!r}, {pointers}, [{counts}])"
190
+ else:
191
+ type_ = f"cs.resolve({name!r})"
192
+ return f"{FUNCTIONS[operator].__name__}({', '.join([type_, *map(repr, fields)])})"
164
193
 
165
194
 
166
195
  def precedence(o1: TokenType, o2: TokenType) -> bool:
@@ -171,62 +200,36 @@ def precedence(o1: TokenType, o2: TokenType) -> bool:
171
200
 
172
201
 
173
202
  class Expression(TokenCursor):
174
- """Expression parser for calculations in definitions."""
203
+ """Expression parser for calculations in definitions.
204
+
205
+ The expression is parsed when it's created, so a syntax error raises right away.
206
+ Calculating with invalid operands (e.g. division by zero) raises an exception when evaluating.
207
+
208
+ Raises:
209
+ ExpressionParserError: If the expression is invalid.
210
+ """
175
211
 
176
212
  def __init__(self, expression: str):
177
213
  self.expression = expression
178
214
 
179
215
  tokens = Lexer(expression).tokenize()
180
216
  super().__init__(tokens)
181
- self._stack: list[TokenType] = []
182
- self._queue: list[int | str] = []
217
+ self._postfix = self._parse()
183
218
 
184
219
  def __repr__(self) -> str:
185
220
  return self.expression
186
221
 
187
- def _reset(self) -> None:
188
- """Reset the expression state for a new input."""
189
- self._reset_cursor()
190
- self._stack = []
191
- self._queue = []
192
-
193
222
  def _error(self, msg: str, *, token: Token | None = None) -> ExpressionParserError:
194
223
  return ExpressionParserError(msg)
195
224
 
196
- def _evaluate_expression(self, backend: _Evaluator | _SourceBuilder) -> None:
197
- operator = self._stack.pop(-1)
198
- result = 0
199
-
200
- if operator in UNARY_OPERATORS:
201
- if len(self._queue) < 1:
202
- raise ExpressionParserError("Invalid expression: not enough operands")
203
-
204
- result = backend.unary(operator, self._queue.pop(-1))
205
- elif operator in BINARY_OPERATORS:
206
- if len(self._queue) < 2:
207
- raise ExpressionParserError("Invalid expression: not enough operands")
208
-
209
- right = self._queue.pop(-1)
210
- left = self._queue.pop(-1)
211
- result = backend.binary(operator, left, right)
212
- elif operator in FUNCTION_TOKENS:
213
- num_args = FUNCTION_TOKENS[operator]
214
- if len(self._queue) < num_args:
215
- raise ExpressionParserError("Invalid expression: not enough operands")
216
-
217
- args = [self._queue.pop(-1) for _ in range(num_args)][::-1]
218
- result = backend.function(operator, args)
219
-
220
- self._queue.append(result)
221
-
222
225
  def evaluate(self, cs: cstruct, context: dict[str, int] | None = None) -> int:
223
- """Evaluates an expression using a Shunting-Yard implementation.
226
+ """Evaluates an expression.
224
227
 
225
228
  Args:
226
229
  cs: The cstruct instance to evaluate against.
227
230
  context: The context to evaluate against.
228
231
  """
229
- return self._evaluate(_Evaluator(cs, context or {}))
232
+ return self._run(_Evaluator(cs, context or {}))
230
233
 
231
234
  def source(self, variables: dict[str, str] | None = None, context: str = "context") -> str:
232
235
  """Return the Python source code of this expression.
@@ -235,54 +238,111 @@ class Expression(TokenCursor):
235
238
  variables: The source code map for accessing local variables.
236
239
  context: The symbol name of the context.
237
240
  """
238
- return self._evaluate(_SourceBuilder(variables or {}, context))
241
+ return self._run(_SourceBuilder(variables or {}, context))
242
+
243
+ def _run(self, backend: _Evaluator | _SourceBuilder) -> int | str:
244
+ """Calculate the expression from its postfix notation."""
245
+ stack = []
246
+
247
+ for type_, value in self._postfix:
248
+ if type_ in BINARY_OPERATORS:
249
+ right = stack.pop()
250
+ stack[-1] = backend.binary(type_, stack[-1], right)
251
+ elif type_ in UNARY_OPERATORS:
252
+ stack[-1] = backend.unary(type_, stack[-1])
253
+ elif type_ in FUNCTION_TOKENS:
254
+ stack.append(backend.function(type_, value))
255
+ elif type_ == TokenType.NUMBER:
256
+ stack.append(backend.number(value))
257
+ else:
258
+ stack.append(backend.identifier(value))
259
+
260
+ return stack[0]
261
+
262
+ def _pop_operator(self, stack: list[TokenType], output: list[tuple[TokenType, Any]], operands: int) -> int:
263
+ """Move an operator from the stack to the output, and return the amount of values the output calculates."""
264
+ operator = stack.pop(-1)
265
+ needed = 2 if operator in BINARY_OPERATORS else 1
266
+ if operands < needed:
267
+ raise ExpressionParserError("Invalid expression: not enough operands")
268
+
269
+ output.append((operator, None))
270
+ return operands - needed + 1
271
+
272
+ def _parse_type_name(self) -> tuple[str, int, list[Expression]]:
273
+ """Parse a type name like the type of a field, e.g. ``struct header *[4]``."""
274
+ # Types share a single namespace, so the kind of a type is optional
275
+ self._match(TokenType.STRUCT, TokenType.UNION, TokenType.ENUM, TokenType.FLAG)
239
276
 
240
- def _evaluate(self, backend: _Evaluator | _SourceBuilder) -> int | str:
241
- self._reset()
277
+ if not self._at(TokenType.IDENTIFIER):
278
+ raise self._error(f"expected a type name, got {self._describe(self._current())}")
279
+
280
+ # E.g. unsigned long long
281
+ parts = []
282
+ while token := self._match(TokenType.IDENTIFIER):
283
+ parts.append(token.value)
284
+
285
+ pointers = 0
286
+ while self._match(TokenType.STAR):
287
+ pointers += 1
288
+
289
+ dimensions = []
290
+ while self._match(TokenType.LBRACKET):
291
+ if not (tokens := self._collect_until(TokenType.RBRACKET)):
292
+ raise self._error("expected an array size")
293
+ self._expect(TokenType.RBRACKET)
294
+ dimensions.append(Expression(join_tokens(tokens)))
295
+
296
+ return " ".join(parts), pointers, dimensions
297
+
298
+ def _parse(self) -> list[tuple[TokenType, Any]]:
299
+ """Convert the expression to postfix notation using a Shunting-Yard implementation."""
300
+ output: list[tuple[TokenType, Any]] = []
301
+ stack: list[TokenType] = []
302
+ # The amount of values the output calculates
303
+ operands = 0
242
304
 
243
305
  while (token := self._current()).type != TokenType.EOF:
244
306
  if token.type == TokenType.NUMBER:
245
- self._queue.append(backend.number(int(self._take().value, 0)))
307
+ output.append((TokenType.NUMBER, int(self._take().value, 0)))
308
+ operands += 1
246
309
 
247
310
  elif token.type in OPERATORS:
248
- while (
249
- len(self._stack) != 0
250
- and self._stack[-1] != TokenType.LPAREN
251
- and precedence(self._stack[-1], token.type)
252
- ):
253
- self._evaluate_expression(backend)
311
+ while len(stack) != 0 and stack[-1] != TokenType.LPAREN and precedence(stack[-1], token.type):
312
+ operands = self._pop_operator(stack, output, operands)
254
313
 
255
- self._stack.append(self._take().type)
314
+ stack.append(self._take().type)
256
315
 
257
316
  elif token.type in FUNCTION_TOKENS:
258
317
  func = self._take().type
259
- self._stack.append(func)
260
318
 
261
319
  self._expect(TokenType.LPAREN)
262
320
 
263
- num_args = FUNCTION_TOKENS[func]
264
- while num_args > 1:
265
- self._queue.append(join_tokens(self._collect_until(TokenType.COMMA)))
321
+ # The type, followed by the names of fields
322
+ args = [self._parse_type_name()]
323
+ for _ in range(FUNCTION_TOKENS[func] - 1):
266
324
  self._expect(TokenType.COMMA)
267
- num_args -= 1
325
+ if not self._at(*IDENTIFIER_TYPES):
326
+ raise self._error(f"expected a field name, got {self._describe(self._current())}")
327
+ args.append(self._take().value)
268
328
 
269
- self._queue.append(join_tokens(self._collect_until(TokenType.RPAREN)))
270
329
  self._expect(TokenType.RPAREN)
271
330
 
272
- # Evaluate immediately
273
- self._evaluate_expression(backend)
331
+ output.append((func, tuple(args)))
332
+ operands += 1
274
333
 
275
334
  elif token.type in IDENTIFIER_TYPES:
276
- self._queue.append(backend.identifier(self._take().value))
335
+ output.append((token.type, self._take().value))
336
+ operands += 1
277
337
 
278
338
  elif token.type == TokenType.LPAREN:
279
339
  if self._previous().type == TokenType.NUMBER:
280
340
  raise self._error(
281
- f"Parser expected sizeof or an arethmethic operator instead got: '{self._previous().value}'",
341
+ f"Parser expected sizeof or an arithmethic operator instead got: '{self._previous().value}'",
282
342
  token=self._previous(),
283
343
  )
284
344
 
285
- self._stack.append(self._take().type)
345
+ stack.append(self._take().type)
286
346
 
287
347
  elif token.type == TokenType.RPAREN:
288
348
  if self._previous().type == TokenType.LPAREN:
@@ -291,26 +351,29 @@ class Expression(TokenCursor):
291
351
  token=self._previous(),
292
352
  )
293
353
 
294
- if len(self._stack) == 0:
354
+ if len(stack) == 0:
295
355
  raise self._error("Mismatched parentheses")
296
356
 
297
- while self._stack[-1] != TokenType.LPAREN:
298
- self._evaluate_expression(backend)
299
- if len(self._stack) == 0:
357
+ while stack[-1] != TokenType.LPAREN:
358
+ operands = self._pop_operator(stack, output, operands)
359
+ if len(stack) == 0:
300
360
  raise self._error("Mismatched parentheses")
301
361
 
302
- self._stack.pop(-1) # Pop the '('
362
+ stack.pop(-1) # Pop the '('
303
363
  self._take()
304
364
 
305
365
  else:
306
366
  raise self._error(f"Unmatched token: '{token.value}'", token=token)
307
367
 
308
- while len(self._stack) != 0:
309
- if TokenType.LPAREN in self._stack:
368
+ while len(stack) != 0:
369
+ if TokenType.LPAREN in stack:
310
370
  raise self._error("Mismatched parentheses")
311
- self._evaluate_expression(backend)
371
+ operands = self._pop_operator(stack, output, operands)
372
+
373
+ if operands == 0:
374
+ raise self._error("Invalid expression: not enough operands")
312
375
 
313
- if len(self._queue) != 1:
376
+ if operands > 1:
314
377
  raise self._error("Invalid expression: too many operands")
315
378
 
316
- return self._queue[0]
379
+ return output
dissect/cstruct/lexer.py CHANGED
@@ -532,10 +532,6 @@ class TokenCursor:
532
532
  self._tokens = tokens
533
533
  self._pos = 0
534
534
 
535
- def _reset_cursor(self) -> None:
536
- """Reset only the cursor position while keeping the current tokens."""
537
- self._pos = 0
538
-
539
535
  def _assert_not_eof(self) -> None:
540
536
  """Raise an error if EOF is reached."""
541
537
  if self._tokens[self._pos].type == TokenType.EOF:
@@ -561,14 +557,27 @@ class TokenCursor:
561
557
  self._pos += 1
562
558
  return token
563
559
 
560
+ def _match(self, *types: TokenType) -> Token | None:
561
+ """Consume and return the current token if it matches any of the given types, otherwise return ``None``."""
562
+ if self._current().type in types:
563
+ return self._take()
564
+ return None
565
+
566
+ def _at(self, *types: TokenType) -> bool:
567
+ """Return whether the current token matches any of the given types."""
568
+ return self._tokens[self._pos].type in types
569
+
570
+ def _describe(self, token: Token) -> str:
571
+ """Describe a token for an error message."""
572
+ return "end of input" if token.type == TokenType.EOF else token.value
573
+
564
574
  def _expect(self, *types: TokenType) -> Token:
565
575
  """Consume and return the current token if it matches, otherwise raise an error."""
566
576
  token = self._current()
567
577
  if token.type not in types:
568
- actual = "end of input" if token.type == TokenType.EOF else token.value
569
578
  expected = " or ".join(t.value for t in types)
570
579
  expected = f"one of {expected}" if len(types) > 1 else expected
571
- raise self._error(f"expected {expected}, got {actual}")
580
+ raise self._error(f"expected {expected}, got {self._describe(token)}")
572
581
  return self._take()
573
582
 
574
583
  def _collect_until(self, *terminators: TokenType) -> list[Token]:
dissect/cstruct/parser.py CHANGED
@@ -6,9 +6,11 @@ from typing import TYPE_CHECKING
6
6
 
7
7
  from dissect.cstruct import compiler
8
8
  from dissect.cstruct.exception import (
9
+ DefinitionError,
9
10
  ExpressionParserError,
10
11
  LexerError,
11
12
  ParserError,
13
+ ResolveError,
12
14
  UnknownIdentifierError,
13
15
  )
14
16
  from dissect.cstruct.expression import Expression
@@ -85,23 +87,21 @@ class CStyleParser(Parser):
85
87
  self._reset_tokens(tokenize(data))
86
88
  self._parse()
87
89
 
88
- def _match(self, *types: TokenType) -> Token | None:
89
- """Consume and return the current token if it matches any of the given types, otherwise return None."""
90
- if self._current().type in types:
91
- return self._take()
92
- return None
90
+ def _error(self, msg: str, *, token: Token | None = None) -> ParserError:
91
+ return ParserError(self._error_message(msg, token=token))
93
92
 
94
- def _at(self, *types: TokenType) -> bool:
95
- """Return whether the current token matches any of the given types."""
96
- return self._tokens[self._pos].type in types
93
+ def _located(self, error: DefinitionError, token: Token) -> DefinitionError:
94
+ """Return the error with the line of the token, and keep its class."""
95
+ return type(error)(self._error_message(str(error), token=token))
97
96
 
98
- def _error(self, msg: str, *, token: Token | None = None) -> ParserError:
97
+ def _error_message(self, msg: str, *, token: Token | None = None) -> str:
98
+ """Return the message with the line of the token, the current token by default."""
99
99
  lineno = (token if token is not None else self._tokens[self._pos]).line
100
100
  if self._data is None:
101
- return ParserError(f"line {lineno}: {msg}")
101
+ return f"line {lineno}: {msg}"
102
102
 
103
103
  content = format_error_context(self._data, lineno)
104
- return ParserError(f"line {lineno}: {msg}\n{content}")
104
+ return f"line {lineno}: {msg}\n{content}"
105
105
 
106
106
  def _in_false_branch(self) -> bool:
107
107
  """Return whether we're currently in a false conditional branch."""
@@ -218,6 +218,12 @@ class CStyleParser(Parser):
218
218
  except (LexerError, ExpressionParserError):
219
219
  # If evaluation fails, just keep it as a string (e.g. for macro-like constants)
220
220
  pass
221
+ except ResolveError as e:
222
+ # E.g. sizeof of an unknown type
223
+ raise self._located(e, token) from e
224
+ except (ArithmeticError, ValueError) as e:
225
+ # E.g. a division by zero or sizeof of a type with a dynamic size
226
+ raise self._error(str(e), token=token) from None
221
227
 
222
228
  self.cs.add_const(name_token.value, value)
223
229
 
@@ -317,6 +323,7 @@ class CStyleParser(Parser):
317
323
 
318
324
  # Parse one or more typedef names with modifiers (pointers, arrays)
319
325
  while self._at(TokenType.IDENTIFIER, TokenType.STAR):
326
+ start_token = self._current()
320
327
  type_, name, bits = self._parse_field_name(base_type)
321
328
  if bits is not None:
322
329
  raise self._error("typedefs cannot have bitfields")
@@ -327,7 +334,10 @@ class CStyleParser(Parser):
327
334
  base_type.__name__ = name
328
335
  base_type.__qualname__ = name
329
336
 
330
- self.cs.add_type(name, type_)
337
+ try:
338
+ self.cs.add_type(name, type_)
339
+ except DefinitionError as e:
340
+ raise self._located(e, start_token) from e
331
341
 
332
342
  if not self._match(TokenType.COMMA):
333
343
  break
@@ -360,26 +370,37 @@ class CStyleParser(Parser):
360
370
  type = factory(name, [], align=self.align)
361
371
  if self.compiled and "nocompile" not in self._flags:
362
372
  type = compiler.compile_structure(type)
363
- self.cs.add_type(name, type)
373
+
374
+ try:
375
+ self.cs.add_type(name, type)
376
+ except DefinitionError as e:
377
+ raise self._located(e, start_token) from e
364
378
  else:
365
379
  # struct typename ... (type reference)
366
- return self.cs.resolve(name)
380
+ try:
381
+ return self.cs.resolve(name)
382
+ except ResolveError as e:
383
+ raise self._located(e, start_token) from e
367
384
 
368
385
  # Parse body
369
386
  self._expect(TokenType.LBRACE)
370
387
  fields = self._parse_field_list()
371
388
  self._expect(TokenType.RBRACE)
372
389
 
373
- if type is None:
374
- is_anonymous = name is None
375
- name = name or self.cs._next_anonymous()
390
+ # The fields are checked when the type is built from all of them, e.g. for a duplicate name
391
+ try:
392
+ if type is None:
393
+ is_anonymous = name is None
394
+ name = name or self.cs._next_anonymous()
376
395
 
377
- type = factory(name, fields, align=self.align, anonymous=is_anonymous)
378
- if self.compiled and "nocompile" not in self._flags:
379
- type = compiler.compile_structure(type)
380
- else:
381
- type.__fields__.extend(fields)
382
- type.commit()
396
+ type = factory(name, fields, align=self.align, anonymous=is_anonymous)
397
+ if self.compiled and "nocompile" not in self._flags:
398
+ type = compiler.compile_structure(type)
399
+ else:
400
+ type.__fields__.extend(fields)
401
+ type.commit()
402
+ except DefinitionError as e:
403
+ raise self._located(e, start_token) from e
383
404
 
384
405
  self._flags.clear()
385
406
  return type
@@ -402,6 +423,11 @@ class CStyleParser(Parser):
402
423
  parts.append(token.value)
403
424
  base_type_str = " ".join(parts)
404
425
 
426
+ try:
427
+ base_type = self.cs.resolve(base_type_str)
428
+ except ResolveError as e:
429
+ raise self._located(e, start_token) from e
430
+
405
431
  self._expect(TokenType.LBRACE)
406
432
 
407
433
  next_value = 1 if is_flag else 0
@@ -428,7 +454,10 @@ class CStyleParser(Parser):
428
454
 
429
455
  try:
430
456
  value = Expression(join_tokens(tokens)).evaluate(self.cs, values)
431
- except ExpressionParserError as e:
457
+ except ResolveError as e:
458
+ # E.g. sizeof of an unknown type
459
+ raise self._located(e, tokens[0]) from e
460
+ except (ExpressionParserError, ArithmeticError, ValueError) as e:
432
461
  raise self._error(str(e), token=tokens[0]) from None
433
462
  else:
434
463
  value = next_value
@@ -445,12 +474,15 @@ class CStyleParser(Parser):
445
474
  self._expect(TokenType.RBRACE)
446
475
 
447
476
  factory = self.cs._make_flag if is_flag else self.cs._make_enum
448
- type_ = factory(name or "", self.cs.resolve(base_type_str), values)
477
+ try:
478
+ type_ = factory(name or "", base_type, values)
449
479
 
450
- if name is not None:
451
- # Register the enum/flag type if it has a name
452
- # Anonymous enums/flags are handled in the top level parse loop
453
- self.cs.add_type(type_.__name__, type_)
480
+ if name is not None:
481
+ # Register the enum/flag type if it has a name
482
+ # Anonymous enums/flags are handled in the top level parse loop
483
+ self.cs.add_type(type_.__name__, type_)
484
+ except DefinitionError as e:
485
+ raise self._located(e, start_token) from e
454
486
 
455
487
  return type_
456
488
 
@@ -511,6 +543,7 @@ class CStyleParser(Parser):
511
543
 
512
544
  def _parse_array_dimensions(self, base_type: type[BaseType]) -> type[BaseType]:
513
545
  """Parse array dimensions following a field name, e.g., ``field[10][20]``."""
546
+ start_token = self._current()
514
547
  dimensions: list[int | Expression] = []
515
548
 
516
549
  while self._match(TokenType.LBRACKET):
@@ -519,13 +552,16 @@ class CStyleParser(Parser):
519
552
 
520
553
  count = None
521
554
  if tokens:
522
- count = Expression(join_tokens(tokens))
523
555
  try:
556
+ count = Expression(join_tokens(tokens))
524
557
  count = count.evaluate(self.cs)
525
558
  except UnknownIdentifierError:
526
559
  # The size refers to a field, so it's evaluated when reading the structure
527
560
  pass
528
- except ExpressionParserError as e:
561
+ except ResolveError as e:
562
+ # E.g. sizeof of an unknown type
563
+ raise self._located(e, tokens[0]) from e
564
+ except (ExpressionParserError, ArithmeticError, ValueError) as e:
529
565
  raise self._error(str(e), token=tokens[0]) from None
530
566
 
531
567
  dimensions.append(count)
@@ -533,8 +569,12 @@ class CStyleParser(Parser):
533
569
  type_ = base_type
534
570
  for count in reversed(dimensions):
535
571
  if issubclass(type_, BaseArray) and count is None:
536
- raise ParserError("Depth required for multi-dimensional array")
537
- type_ = self.cs._make_array(type_, count)
572
+ raise self._error("Depth required for multi-dimensional array", token=start_token)
573
+
574
+ try:
575
+ type_ = self.cs._make_array(type_, count)
576
+ except DefinitionError as e:
577
+ raise self._located(e, start_token) from e
538
578
 
539
579
  return type_
540
580
 
@@ -587,4 +627,7 @@ class CStyleParser(Parser):
587
627
  else:
588
628
  break
589
629
 
590
- return self.cs.resolve(" ".join(parts))
630
+ try:
631
+ return self.cs.resolve(" ".join(parts))
632
+ except ResolveError as e:
633
+ raise self._located(e, first) from e