dissect.cstruct 5.0.dev15__py3-none-any.whl → 5.0.dev16__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.
@@ -27,3 +27,7 @@ class ArraySizeError(Error):
27
27
 
28
28
  class ExpressionParserError(Error):
29
29
  pass
30
+
31
+
32
+ class UnknownIdentifierError(ExpressionParserError):
33
+ pass
@@ -2,8 +2,8 @@ from __future__ import annotations
2
2
 
3
3
  from typing import TYPE_CHECKING, Any
4
4
 
5
- from dissect.cstruct.exception import ExpressionParserError
6
- from dissect.cstruct.lexer import IDENTIFIER_TYPES, Lexer, TokenCursor, TokenType
5
+ from dissect.cstruct.exception import ExpressionParserError, UnknownIdentifierError
6
+ from dissect.cstruct.lexer import IDENTIFIER_TYPES, Lexer, TokenCursor, TokenType, join_tokens
7
7
  from dissect.cstruct.util import offsetof, sizeof
8
8
 
9
9
  if TYPE_CHECKING:
@@ -87,11 +87,7 @@ FUNCTIONS: dict[TokenType, Callable[..., int]] = {
87
87
  }
88
88
 
89
89
 
90
- def _error(msg: str, line: int) -> ExpressionParserError:
91
- return ExpressionParserError(f"line {line}: {msg}")
92
-
93
-
94
- def _identifier(cs: cstruct, context: dict[str, Any], ident: str, line: int) -> int:
90
+ def _identifier(cs: cstruct, context: dict[str, Any], ident: str) -> int:
95
91
  """Resolve an identifier to an integer value."""
96
92
  obj = None
97
93
  for i, part in enumerate(ident.split(".")):
@@ -103,16 +99,16 @@ def _identifier(cs: cstruct, context: dict[str, Any], ident: str, line: int) ->
103
99
  elif part in cs.types:
104
100
  obj = cs.types[part]
105
101
  else:
106
- raise _error(f"Unknown identifier: '{ident}'", line)
102
+ raise UnknownIdentifierError(f"Unknown identifier: '{ident}'")
107
103
  else:
108
104
  obj = obj.get(part, _MISSING) if isinstance(obj, dict) else getattr(obj, part, _MISSING)
109
105
  if obj is _MISSING:
110
- raise _error(f"Unknown identifier: '{ident}'", line)
106
+ raise UnknownIdentifierError(f"Unknown identifier: '{ident}'")
111
107
 
112
108
  try:
113
109
  return int(obj)
114
110
  except (ValueError, TypeError):
115
- raise _error(f"Identifier '{ident}' does not resolve to an integer", line)
111
+ raise ExpressionParserError(f"Identifier '{ident}' does not resolve to an integer")
116
112
 
117
113
 
118
114
  # Globals used by the source code of an expression
@@ -129,8 +125,8 @@ class _Evaluator:
129
125
  def number(self, value: int) -> int:
130
126
  return value
131
127
 
132
- def identifier(self, ident: str, token: Token) -> int:
133
- return _identifier(self.cs, self.context, ident, token.line)
128
+ def identifier(self, ident: str) -> int:
129
+ return _identifier(self.cs, self.context, ident)
134
130
 
135
131
  def unary(self, operator: TokenType, value: int) -> int:
136
132
  return UNARY_OPERATORS[operator](value)
@@ -152,10 +148,10 @@ class _SourceBuilder:
152
148
  def number(self, value: int) -> str:
153
149
  return repr(value)
154
150
 
155
- def identifier(self, ident: str, token: Token) -> str:
151
+ def identifier(self, ident: str) -> str:
156
152
  if ident in self.variables:
157
153
  return self.variables[ident]
158
- return f"_identifier(cs, {self.context}, {ident!r}, {token.line})"
154
+ return f"_identifier(cs, {self.context}, {ident!r})"
159
155
 
160
156
  def unary(self, operator: TokenType, value: str) -> str:
161
157
  return f"({OPERATOR_SOURCE[operator]}{value})"
@@ -195,7 +191,7 @@ class Expression(TokenCursor):
195
191
  self._queue = []
196
192
 
197
193
  def _error(self, msg: str, *, token: Token | None = None) -> ExpressionParserError:
198
- return _error(msg, (token if token is not None else self._current()).line)
194
+ return ExpressionParserError(msg)
199
195
 
200
196
  def _evaluate_expression(self, backend: _Evaluator | _SourceBuilder) -> None:
201
197
  operator = self._stack.pop(-1)
@@ -266,18 +262,18 @@ class Expression(TokenCursor):
266
262
 
267
263
  num_args = FUNCTION_TOKENS[func]
268
264
  while num_args > 1:
269
- self._queue.append(self._collect_until(TokenType.COMMA))
265
+ self._queue.append(join_tokens(self._collect_until(TokenType.COMMA)))
270
266
  self._expect(TokenType.COMMA)
271
267
  num_args -= 1
272
268
 
273
- self._queue.append(self._collect_until(TokenType.RPAREN))
269
+ self._queue.append(join_tokens(self._collect_until(TokenType.RPAREN)))
274
270
  self._expect(TokenType.RPAREN)
275
271
 
276
272
  # Evaluate immediately
277
273
  self._evaluate_expression(backend)
278
274
 
279
275
  elif token.type in IDENTIFIER_TYPES:
280
- self._queue.append(backend.identifier(self._take().value, token))
276
+ self._queue.append(backend.identifier(self._take().value))
281
277
 
282
278
  elif token.type == TokenType.LPAREN:
283
279
  if self._previous().type == TokenType.NUMBER:
dissect/cstruct/lexer.py CHANGED
@@ -143,6 +143,11 @@ def format_error_context(data: str, lineno: int, window: int = 1) -> str:
143
143
  return "\n".join(f"{start + i + 1:>{no_len}}: {line}" for i, line in enumerate(context))
144
144
 
145
145
 
146
+ def join_tokens(tokens: list[Token]) -> str:
147
+ """Join the values of the tokens with spaces, e.g. to evaluate them as an expression."""
148
+ return " ".join(token.value for token in tokens)
149
+
150
+
146
151
  class Lexer:
147
152
  """Lexer compatible with C-like syntax for struct definitions and preprocessor directives."""
148
153
 
@@ -566,11 +571,11 @@ class TokenCursor:
566
571
  raise self._error(f"expected {expected}, got {actual}")
567
572
  return self._take()
568
573
 
569
- def _collect_until(self, *terminators: TokenType) -> str:
570
- """Collect token values until one of the terminators is reached, tracking nesting."""
574
+ def _collect_until(self, *terminators: TokenType) -> list[Token]:
575
+ """Collect tokens until one of the terminators is reached, tracking nesting."""
571
576
  terminators_set = set(terminators)
572
577
  start = self._current()
573
- parts: list[str] = []
578
+ tokens: list[Token] = []
574
579
  depth = 0
575
580
 
576
581
  while (token := self._current()).type != TokenType.EOF:
@@ -584,13 +589,13 @@ class TokenCursor:
584
589
  if depth < 0:
585
590
  raise self._error("unmatched closing bracket", token=token)
586
591
 
587
- parts.append(token.value)
592
+ tokens.append(token)
588
593
  self._pos += 1
589
594
 
590
595
  if depth > 0:
591
596
  raise self._error("unclosed opening bracket", token=start)
592
597
 
593
- return " ".join(parts)
598
+ return tokens
594
599
 
595
600
  def _error(self, msg: str, *, token: Token | None = None) -> Exception:
596
601
  """Subclasses should override to return an appropriate exception."""
dissect/cstruct/parser.py CHANGED
@@ -9,9 +9,10 @@ from dissect.cstruct.exception import (
9
9
  ExpressionParserError,
10
10
  LexerError,
11
11
  ParserError,
12
+ UnknownIdentifierError,
12
13
  )
13
14
  from dissect.cstruct.expression import Expression
14
- from dissect.cstruct.lexer import IDENTIFIER_TYPES, TokenCursor, TokenType, format_error_context, tokenize
15
+ from dissect.cstruct.lexer import IDENTIFIER_TYPES, TokenCursor, TokenType, format_error_context, join_tokens, tokenize
15
16
  from dissect.cstruct.types import BaseArray, BaseType, Field, Structure
16
17
 
17
18
  if TYPE_CHECKING:
@@ -422,8 +423,13 @@ class CStyleParser(Parser):
422
423
  member_name = self._expect(TokenType.IDENTIFIER).value
423
424
 
424
425
  if self._match(TokenType.EQUALS):
425
- expression = self._collect_until(TokenType.COMMA, TokenType.RBRACE)
426
- value = Expression(expression).evaluate(self.cs, values)
426
+ if not (tokens := self._collect_until(TokenType.COMMA, TokenType.RBRACE)):
427
+ raise self._error("expected an expression")
428
+
429
+ try:
430
+ value = Expression(join_tokens(tokens)).evaluate(self.cs, values)
431
+ except ExpressionParserError as e:
432
+ raise self._error(str(e), token=tokens[0]) from None
427
433
  else:
428
434
  value = next_value
429
435
 
@@ -508,17 +514,21 @@ class CStyleParser(Parser):
508
514
  dimensions: list[int | Expression] = []
509
515
 
510
516
  while self._match(TokenType.LBRACKET):
511
- if self._at(TokenType.RBRACKET):
512
- dimensions.append(None)
513
- else:
514
- expression = self._collect_until(TokenType.RBRACKET)
515
- count = Expression(expression)
517
+ tokens = self._collect_until(TokenType.RBRACKET)
518
+ self._expect(TokenType.RBRACKET)
519
+
520
+ count = None
521
+ if tokens:
522
+ count = Expression(join_tokens(tokens))
516
523
  try:
517
524
  count = count.evaluate(self.cs)
518
- except Exception:
525
+ except UnknownIdentifierError:
526
+ # The size refers to a field, so it's evaluated when reading the structure
519
527
  pass
520
- dimensions.append(count)
521
- self._expect(TokenType.RBRACKET)
528
+ except ExpressionParserError as e:
529
+ raise self._error(str(e), token=tokens[0]) from None
530
+
531
+ dimensions.append(count)
522
532
 
523
533
  type_ = base_type
524
534
  for count in reversed(dimensions):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dissect.cstruct
3
- Version: 5.0.dev15
3
+ Version: 5.0.dev16
4
4
  Summary: A Dissect module implementing a parser for C-like structures: structure parsing in Python made easy
5
5
  Author-email: Dissect Team <dissect@fox-it.com>
6
6
  License-Expression: Apache-2.0
@@ -2,10 +2,10 @@ dissect/cstruct/__init__.py,sha256=KOyNeUvu4c0JaAiyOfj7iftGwUIjTmD8MwHtFsLPLSU,1
2
2
  dissect/cstruct/bitbuffer.py,sha256=aNzY4lkWe8ffAc8j7FODXzwZc8gZwbey77UosyoYCsw,2711
3
3
  dissect/cstruct/compiler.py,sha256=0u58J5pB4izosBj8G4wiBI1JSAAgHFMLM63IaSG4YO4,54509
4
4
  dissect/cstruct/cstruct.py,sha256=mJerzPouWV29RdK5LqjGitDDMvNKcadoT2hj1zpExnM,26551
5
- dissect/cstruct/exception.py,sha256=RqD08LuBkbMqa3iQ1A05DNN8XgEmQR_SUnguwe9LGo8,316
6
- dissect/cstruct/expression.py,sha256=Y27-N48BomBoRFozbWhGDF_DS2lfklRwWVUbCzGnxHE,10873
7
- dissect/cstruct/lexer.py,sha256=FbAoUVGAoH4tvnLGBwVoEf6FAxfpz9QQXpJGzykAoc4,20237
8
- dissect/cstruct/parser.py,sha256=92SCg1lldmFy4CUZjf3gWz9UJaGdYeprL1PV-JXAmY4,22122
5
+ dissect/cstruct/exception.py,sha256=box-mw6FoP6c3vndvYLcTeJCZVgIG8IQVPEAg4zW0C8,380
6
+ dissect/cstruct/expression.py,sha256=SbZRv7ueasYU4k-4k2eV1fjwL3JTAgF2UBaBvNjwiv4,10736
7
+ dissect/cstruct/lexer.py,sha256=N7eqCOlcaQriUUIswJv16i-CE_sahYXGO-YdFO0IKKY,20421
8
+ dissect/cstruct/parser.py,sha256=6PovhIbicENg3jBgopdArupmQNd-Ti7rd_te9au4z6U,22569
9
9
  dissect/cstruct/util.py,sha256=vAf-kdOkk3zprW_gD6QmQeN3VIRgQqhPS4B_ha1jEpQ,18040
10
10
  dissect/cstruct/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
11
  dissect/cstruct/tools/stubgen.py,sha256=MeZkLmSeNSLNcAEwlAdIGv1lKvlvK3UQ4WN85ovsxTM,7672
@@ -21,10 +21,10 @@ dissect/cstruct/types/pointer.py,sha256=FNuB9bfENWRebbKX-R6Vs6xWPMHepjvOhhomeUhr
21
21
  dissect/cstruct/types/structure.py,sha256=mxDvurQ0oAjI2flykhAPlT-03280cDpwGTz0-bqbr-0,39558
22
22
  dissect/cstruct/types/void.py,sha256=fV4hKk50uop_EKbR1nfy1cdtAzvUYrSymXsdakCyFk8,1222
23
23
  dissect/cstruct/types/wchar.py,sha256=VrnPXsP_lsyA-1xr4D2aSIVijumMhUuZWNlDHcn12-s,3964
24
- dissect_cstruct-5.0.dev15.dist-info/licenses/COPYRIGHT,sha256=H-18RXfshdH9AdHwW2eO1Xa-5s6tY5eipHh5c0whDu4,316
25
- dissect_cstruct-5.0.dev15.dist-info/licenses/LICENSE,sha256=PhUqiw6jAh2KbBdVRPBq_hfAvfcTBin7nZ3CK7NQbTM,11341
26
- dissect_cstruct-5.0.dev15.dist-info/METADATA,sha256=9aR35qikIsQ5Y746lVzVxt7NV1pYQ7GyzCiHbtB0BXE,9256
27
- dissect_cstruct-5.0.dev15.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
28
- dissect_cstruct-5.0.dev15.dist-info/entry_points.txt,sha256=z53zqZqwD2OLrAkRwrP4wTeiU9CQe7xrMly0T2c0_wQ,71
29
- dissect_cstruct-5.0.dev15.dist-info/top_level.txt,sha256=Mn-CQzEYsAbkxrUI0TnplHuXnGVKzxpDw_po_sXpvv4,8
30
- dissect_cstruct-5.0.dev15.dist-info/RECORD,,
24
+ dissect_cstruct-5.0.dev16.dist-info/licenses/COPYRIGHT,sha256=H-18RXfshdH9AdHwW2eO1Xa-5s6tY5eipHh5c0whDu4,316
25
+ dissect_cstruct-5.0.dev16.dist-info/licenses/LICENSE,sha256=PhUqiw6jAh2KbBdVRPBq_hfAvfcTBin7nZ3CK7NQbTM,11341
26
+ dissect_cstruct-5.0.dev16.dist-info/METADATA,sha256=xdol4wRzYoijmhDPLkLFrAn0S8-Ag4LquHg3MRZ3Hu8,9256
27
+ dissect_cstruct-5.0.dev16.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
28
+ dissect_cstruct-5.0.dev16.dist-info/entry_points.txt,sha256=z53zqZqwD2OLrAkRwrP4wTeiU9CQe7xrMly0T2c0_wQ,71
29
+ dissect_cstruct-5.0.dev16.dist-info/top_level.txt,sha256=Mn-CQzEYsAbkxrUI0TnplHuXnGVKzxpDw_po_sXpvv4,8
30
+ dissect_cstruct-5.0.dev16.dist-info/RECORD,,