dissect.cstruct 5.0.dev21__tar.gz → 5.0.dev23__tar.gz
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.
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/CHANGELOG.md +19 -3
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/PKG-INFO +1 -1
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect/cstruct/__init__.py +12 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect/cstruct/bitbuffer.py +5 -3
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect/cstruct/compiler.py +21 -10
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect/cstruct/cstruct.py +8 -6
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect/cstruct/declarative.py +3 -2
- dissect_cstruct-5.0.dev23/dissect/cstruct/exception.py +47 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect/cstruct/expression.py +142 -79
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect/cstruct/lexer.py +15 -6
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect/cstruct/parser.py +77 -34
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect/cstruct/types/base.py +27 -5
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect/cstruct/types/char.py +8 -4
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect/cstruct/types/enum.py +2 -1
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect/cstruct/types/int.py +7 -1
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect/cstruct/types/leb128.py +2 -1
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect/cstruct/types/packed.py +11 -6
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect/cstruct/types/pointer.py +6 -2
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect/cstruct/types/structure.py +11 -2
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect/cstruct/types/wchar.py +16 -8
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect/cstruct/util.py +22 -5
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect.cstruct.egg-info/PKG-INFO +1 -1
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect.cstruct.egg-info/SOURCES.txt +1 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect.cstruct.egg-info/scm_file_list.json +1 -0
- dissect_cstruct-5.0.dev23/dissect.cstruct.egg-info/scm_version.json +8 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_basic.py +26 -9
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_bitbuffer.py +2 -1
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_bitfield.py +30 -1
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_compiler.py +21 -22
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_declarative.py +7 -4
- dissect_cstruct-5.0.dev23/tests/test_exception.py +63 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_expression.py +133 -22
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_parser.py +107 -1
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_types_base.py +65 -6
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_types_char.py +12 -8
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_types_enum.py +2 -1
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_types_int.py +18 -13
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_types_leb128.py +3 -1
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_types_packed.py +9 -4
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_types_pointer.py +10 -3
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_types_structure.py +11 -8
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_types_union.py +1 -1
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_types_wchar.py +15 -11
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_util.py +56 -1
- dissect_cstruct-5.0.dev21/dissect/cstruct/exception.py +0 -33
- dissect_cstruct-5.0.dev21/dissect.cstruct.egg-info/scm_version.json +0 -8
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/.git-blame-ignore-revs +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/.gitattributes +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/COPYRIGHT +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/LICENSE +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/MANIFEST.in +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/README.md +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect/cstruct/dump.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect/cstruct/tools/__init__.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect/cstruct/tools/stubgen.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect/cstruct/types/__init__.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect/cstruct/types/flag.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect/cstruct/types/void.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect.cstruct.egg-info/dependency_links.txt +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect.cstruct.egg-info/entry_points.txt +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect.cstruct.egg-info/requires.txt +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/dissect.cstruct.egg-info/top_level.txt +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/examples/disk.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/examples/mirai.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/examples/pe.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/examples/protobuf.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/examples/secdesc.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/pyproject.toml +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/setup.cfg +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/__init__.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/_data/testdef.txt +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/_docs/Makefile +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/_docs/__init__.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/_docs/conf.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/_docs/index.rst +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/conftest.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_align.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_annotations.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_benchmark.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_ctypes.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_dump.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_lexer.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_tools_stubgen.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_types_custom.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_types_flag.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/test_types_void.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tests/util.py +0 -0
- {dissect_cstruct-5.0.dev21 → dissect_cstruct-5.0.dev23}/tox.ini +0 -0
|
@@ -9,7 +9,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
|
9
9
|
### Added
|
|
10
10
|
|
|
11
11
|
- Declarative syntax for structures and unions in `dissect.cstruct.declarative`, using classes with type annotations.
|
|
12
|
-
- `asdict()`
|
|
12
|
+
- `asdict()` method return the field values of a structure or union as a dict, with nested structures as dicts and arrays as lists. `asjson()` returns them as a JSON string, with bytes as base64 and enum members as numbers. `JSONEncoder` encodes structures as part of other data with `json.dumps()`.
|
|
13
|
+
- `sizeof` and `offsetof` in expressions accept a type name like the type of a field, e.g. `sizeof(struct header *[4])`. An argument that isn't a type name raises an `ExpressionParserError` when the expression is created.
|
|
13
14
|
|
|
14
15
|
### Changed
|
|
15
16
|
|
|
@@ -32,6 +33,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
|
32
33
|
- `obj.dumps()` and `obj.write()` no longer create a `functools.partial` on every access. As a result, they no longer accept a `value` argument.
|
|
33
34
|
- `dumpstruct` can return a tree of all fields with their offset, size and value, with `output="dict"` or `output="json"`. `dumpstruct` and `hexdump` moved from `dissect.cstruct.util` to `dissect.cstruct.dump`.
|
|
34
35
|
- `dumpstruct` shows the fields of every element of an array of structures or unions.
|
|
36
|
+
- Errors are subclasses of `dissect.cstruct.Error`: `DefinitionError` for invalid definitions, `ReadError` for data that can't be parsed and `WriteError` for values that can't be written. All three are also subclasses of `ValueError`.
|
|
37
|
+
- A short read raises `dissect.cstruct.exception.EOFError`, which is a subclass of `Error` and of the built-in `EOFError`. This has also been made more consistent in many places, such as `wchar`, which previously raised a `UnicodeDecodeError`.
|
|
38
|
+
- Arithmetic errors in expressions, such as division by zero, now raise a `ReadError`.
|
|
39
|
+
- A value that can't be written raises a `WriteError` with the original error as its cause
|
|
40
|
+
- Invalid definitions raise a `DefinitionError`.
|
|
41
|
+
- A constant expression that can't be calculated during `load`, e.g. a division by zero, raises a `ParserError`.
|
|
42
|
+
- `offsetof` raises a `TypeError` for a type that isn't a structure, instead of an `AttributeError` or an error about a missing field. In an expression, the errors of `sizeof` and `offsetof` raise a `DefinitionError`.
|
|
43
|
+
- Errors that `load` raises include the line of the definition.
|
|
44
|
+
- `ArraySizeError` is removed. A value that is longer than its static array raises a `WriteError`.
|
|
45
|
+
- `write()` raises a `TypeError` for an object that can't be written to, like `read()` does.
|
|
35
46
|
|
|
36
47
|
### Fixed
|
|
37
48
|
|
|
@@ -40,12 +51,17 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
|
40
51
|
- Unions can be created with default values and read if they have doubly nested structures or nested unions.
|
|
41
52
|
- Writing a `bytearray` to a `char` array no longer modifies the `bytearray`.
|
|
42
53
|
- Writing a structure correctly returns the amount of bytes written, including padding and bit fields.
|
|
43
|
-
- Writing a structure raises
|
|
54
|
+
- Writing a structure raises a `WriteError` for missing attributes and for values of a nested structure field that aren't a structure, instead of writing default values.
|
|
44
55
|
- A surrogate pair takes up two entries of a `wchar` array, so writing it no longer writes more bytes than the size of the array.
|
|
45
56
|
- A `wchar` string can hold a lone surrogate, instead of raising an error for the whole structure when reading or writing it. Bytes are written back as they were stored.
|
|
46
|
-
- Writing more than a single character to a `char` or `wchar` raises a `
|
|
57
|
+
- Writing more than a single character to a `char` or `wchar` raises a `WriteError`, instead of writing all of it and moving the fields after it. An empty value is padded.
|
|
47
58
|
- A plain integer can be written to an enum or flag field, including a bit field.
|
|
48
59
|
- `dumpstruct` shows the fields of a structure in a union in a union, instead of only its `repr`.
|
|
60
|
+
- Writing a value that doesn't fit in its bit field raises a `WriteError`, instead of changing the fields next to it.
|
|
61
|
+
- Bit fields of a type that isn't an integer, `char`, enum or flag raise a `DefinitionError` when they're defined, instead of an error or wrong bytes when they're read or written.
|
|
62
|
+
- An `Expression` is parsed when it's created. An invalid array size that refers to a field, e.g. `char a[n +]`, raises a `ParserError` during `load`, instead of an `ExpressionParserError` on every read.
|
|
63
|
+
- `offsetof` gives the offsets of C for the fields of a union and the fields of an anonymous nested structure or union, instead of an error or the offset in the nested type.
|
|
64
|
+
- An empty expression raises "not enough operands" instead of "too many operands".
|
|
49
65
|
|
|
50
66
|
## [4.5] - 20-05-2025
|
|
51
67
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: dissect.cstruct
|
|
3
|
-
Version: 5.0.
|
|
3
|
+
Version: 5.0.dev23
|
|
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
|
|
@@ -4,10 +4,16 @@ from dissect.cstruct.bitbuffer import BitBuffer
|
|
|
4
4
|
from dissect.cstruct.cstruct import cstruct, ctypes, ctypes_type
|
|
5
5
|
from dissect.cstruct.dump import dumpstruct, hexdump
|
|
6
6
|
from dissect.cstruct.exception import (
|
|
7
|
+
DefinitionError,
|
|
7
8
|
Error,
|
|
9
|
+
ExpressionParserError,
|
|
10
|
+
LexerError,
|
|
8
11
|
NullPointerDereference,
|
|
9
12
|
ParserError,
|
|
13
|
+
ReadError,
|
|
10
14
|
ResolveError,
|
|
15
|
+
UnknownIdentifierError,
|
|
16
|
+
WriteError,
|
|
11
17
|
)
|
|
12
18
|
from dissect.cstruct.expression import Expression
|
|
13
19
|
from dissect.cstruct.types import (
|
|
@@ -60,24 +66,30 @@ __all__ = [
|
|
|
60
66
|
"BitBuffer",
|
|
61
67
|
"Char",
|
|
62
68
|
"CharArray",
|
|
69
|
+
"DefinitionError",
|
|
63
70
|
"Enum",
|
|
64
71
|
"Error",
|
|
65
72
|
"Expression",
|
|
73
|
+
"ExpressionParserError",
|
|
66
74
|
"Field",
|
|
67
75
|
"Flag",
|
|
68
76
|
"Int",
|
|
69
77
|
"JSONEncoder",
|
|
78
|
+
"LexerError",
|
|
70
79
|
"MetaType",
|
|
71
80
|
"NullPointerDereference",
|
|
72
81
|
"Packed",
|
|
73
82
|
"ParserError",
|
|
74
83
|
"Pointer",
|
|
84
|
+
"ReadError",
|
|
75
85
|
"ResolveError",
|
|
76
86
|
"Structure",
|
|
77
87
|
"Union",
|
|
88
|
+
"UnknownIdentifierError",
|
|
78
89
|
"Void",
|
|
79
90
|
"Wchar",
|
|
80
91
|
"WcharArray",
|
|
92
|
+
"WriteError",
|
|
81
93
|
"asdict",
|
|
82
94
|
"asjson",
|
|
83
95
|
"cstruct",
|
|
@@ -2,6 +2,8 @@ from __future__ import annotations
|
|
|
2
2
|
|
|
3
3
|
from typing import TYPE_CHECKING, BinaryIO
|
|
4
4
|
|
|
5
|
+
from dissect.cstruct.exception import DefinitionError
|
|
6
|
+
|
|
5
7
|
if TYPE_CHECKING:
|
|
6
8
|
from dissect.cstruct.types import BaseType
|
|
7
9
|
|
|
@@ -20,7 +22,7 @@ class BitBuffer:
|
|
|
20
22
|
def read(self, field_type: type[BaseType], bits: int) -> int:
|
|
21
23
|
if self._remaining == 0 or self._type != field_type:
|
|
22
24
|
if field_type.__size__ is None:
|
|
23
|
-
raise
|
|
25
|
+
raise DefinitionError("Reading variable-length fields is unsupported")
|
|
24
26
|
|
|
25
27
|
self._type = field_type
|
|
26
28
|
self._remaining = field_type.__size__ * 8
|
|
@@ -33,7 +35,7 @@ class BitBuffer:
|
|
|
33
35
|
self._buffer = int.from_bytes(self._buffer, "big")
|
|
34
36
|
|
|
35
37
|
if bits > self._remaining:
|
|
36
|
-
raise
|
|
38
|
+
raise DefinitionError("Reading straddled bits is unsupported")
|
|
37
39
|
|
|
38
40
|
if self.endian == "<":
|
|
39
41
|
v = self._buffer & ((1 << bits) - 1)
|
|
@@ -52,7 +54,7 @@ class BitBuffer:
|
|
|
52
54
|
self.flush()
|
|
53
55
|
|
|
54
56
|
if field_type.__size__ is None:
|
|
55
|
-
raise
|
|
57
|
+
raise DefinitionError("Writing variable-length fields is unsupported")
|
|
56
58
|
|
|
57
59
|
self._remaining = field_type.__size__ * 8
|
|
58
60
|
self._type = field_type
|
|
@@ -12,7 +12,13 @@ from operator import itemgetter
|
|
|
12
12
|
from textwrap import indent
|
|
13
13
|
from typing import TYPE_CHECKING, Any
|
|
14
14
|
|
|
15
|
-
from dissect.cstruct.exception import
|
|
15
|
+
from dissect.cstruct.exception import (
|
|
16
|
+
DefinitionError,
|
|
17
|
+
EOFError,
|
|
18
|
+
Error,
|
|
19
|
+
ReadError,
|
|
20
|
+
WriteError,
|
|
21
|
+
)
|
|
16
22
|
from dissect.cstruct.expression import SOURCE_GLOBALS, Expression
|
|
17
23
|
from dissect.cstruct.types import (
|
|
18
24
|
Array,
|
|
@@ -212,7 +218,7 @@ def _field_bytes(type_: type[BaseType], value: Any, endian: str) -> bytes:
|
|
|
212
218
|
"""Return the bytes of a char or wchar field that isn't of the right type yet or doesn't fit."""
|
|
213
219
|
buf = type_.dumps(type_.__default__() if value is None else value, endian=endian)
|
|
214
220
|
if len(buf) > type_.__size__:
|
|
215
|
-
raise
|
|
221
|
+
raise WriteError(f"Expected {type_.__size__} bytes for {type_.__name__}, got {len(buf)} instead.")
|
|
216
222
|
return buf
|
|
217
223
|
|
|
218
224
|
|
|
@@ -241,6 +247,11 @@ _GLOBALS = {
|
|
|
241
247
|
"_struct_write": StructureMetaType._write,
|
|
242
248
|
"_union_write": UnionMetaType._write,
|
|
243
249
|
"_struct_error": struct.error,
|
|
250
|
+
"_Error": Error,
|
|
251
|
+
"_EOFError": EOFError,
|
|
252
|
+
"_ReadError": ReadError,
|
|
253
|
+
"_WriteError": WriteError,
|
|
254
|
+
"_DefinitionError": DefinitionError,
|
|
244
255
|
"_field_bytes": _field_bytes,
|
|
245
256
|
"_array_values": _array_values,
|
|
246
257
|
"_or_default": _or_default,
|
|
@@ -552,13 +563,13 @@ class _ReadSourceGenerator(_SourceGenerator):
|
|
|
552
563
|
# Integer fields that were read before are used directly
|
|
553
564
|
types = {field._name: field.type for field in self.fields}
|
|
554
565
|
variables = {name: f"int({var})" for name, var in self._assigned if issubclass(types[name], _INTEGER_TYPES)}
|
|
555
|
-
|
|
556
|
-
count = num_entries.source(variables, context)
|
|
557
|
-
except ExpressionParserError:
|
|
558
|
-
# Invalid expressions raise their error when reading the array
|
|
559
|
-
return read
|
|
566
|
+
count = num_entries.source(variables, context)
|
|
560
567
|
|
|
561
|
-
|
|
568
|
+
# E.g. a division by a field that is zero.
|
|
569
|
+
message = f"Invalid array size '{num_entries.expression}': "
|
|
570
|
+
lines.append(f"try: _count = max(0, {count})")
|
|
571
|
+
lines.append("except _Error: raise")
|
|
572
|
+
lines.append(f"except (ArithmeticError, ValueError) as e: raise _ReadError({message!r} + str(e)) from e")
|
|
562
573
|
element = self._type_symbol(field.type.__type__)
|
|
563
574
|
return f"_type_call({type_}, {element}._read_array(stream, _count, context={context}, endian=endian))"
|
|
564
575
|
|
|
@@ -573,7 +584,7 @@ class _ReadSourceGenerator(_SourceGenerator):
|
|
|
573
584
|
lines.append(f"_bit_buffer = {self._type_symbol(read_type)}._read(stream, endian=endian)")
|
|
574
585
|
|
|
575
586
|
if field.bits > remaining:
|
|
576
|
-
lines.append('raise
|
|
587
|
+
lines.append('raise _DefinitionError("Reading straddled bits is unsupported")')
|
|
577
588
|
yield _block(lines)
|
|
578
589
|
return
|
|
579
590
|
|
|
@@ -1251,7 +1262,7 @@ def _member_lookup(type_: str, value: str) -> str:
|
|
|
1251
1262
|
|
|
1252
1263
|
def _check_eof(size: int) -> str:
|
|
1253
1264
|
"""Return the code to raise an ``EOFError`` if fewer than ``size`` bytes were read into ``buf``."""
|
|
1254
|
-
return f'if len(buf) != {size}: raise
|
|
1265
|
+
return f'if len(buf) != {size}: raise _EOFError(f"Read {{len(buf)}} bytes, but expected {size}")'
|
|
1255
1266
|
|
|
1256
1267
|
|
|
1257
1268
|
def _block(lines: list[str]) -> str:
|
|
@@ -12,7 +12,7 @@ from functools import lru_cache
|
|
|
12
12
|
from pathlib import Path
|
|
13
13
|
from typing import TYPE_CHECKING, Any, BinaryIO, Literal, TypeVar, cast
|
|
14
14
|
|
|
15
|
-
from dissect.cstruct.exception import ResolveError
|
|
15
|
+
from dissect.cstruct.exception import DefinitionError, ResolveError
|
|
16
16
|
from dissect.cstruct.expression import Expression
|
|
17
17
|
from dissect.cstruct.parser import CStyleParser
|
|
18
18
|
from dissect.cstruct.types import (
|
|
@@ -285,11 +285,11 @@ class cstruct:
|
|
|
285
285
|
replace: Whether to replace the type if it already exists.
|
|
286
286
|
|
|
287
287
|
Raises:
|
|
288
|
-
|
|
288
|
+
DefinitionError: If the type already exists.
|
|
289
289
|
"""
|
|
290
290
|
typeobj = self.resolve(type_)
|
|
291
291
|
if not replace and (existing := self.types.get(name)) is not None and existing is not typeobj:
|
|
292
|
-
raise
|
|
292
|
+
raise DefinitionError(f"Duplicate type: {name}")
|
|
293
293
|
|
|
294
294
|
self.types[name] = typeobj
|
|
295
295
|
self._add_attr(name, typeobj)
|
|
@@ -532,11 +532,13 @@ class cstruct:
|
|
|
532
532
|
if num_entries is None:
|
|
533
533
|
null_terminated = True
|
|
534
534
|
size = None
|
|
535
|
-
elif isinstance(num_entries, Expression)
|
|
535
|
+
elif isinstance(num_entries, Expression):
|
|
536
|
+
size = None
|
|
537
|
+
elif num_entries < 0:
|
|
538
|
+
raise DefinitionError(f"Array size must not be negative: {num_entries}")
|
|
539
|
+
elif type_.__dynamic__:
|
|
536
540
|
size = None
|
|
537
541
|
else:
|
|
538
|
-
if type_.__size__ is None:
|
|
539
|
-
raise ValueError(f"Cannot create array of dynamic type: {type_.__name__}")
|
|
540
542
|
size = num_entries * type_.__size__
|
|
541
543
|
|
|
542
544
|
name = f"{type_.__name__}[]" if null_terminated else f"{type_.__name__}[{num_entries}]"
|
|
@@ -60,6 +60,7 @@ from typing import TYPE_CHECKING, Annotated, Any, BinaryIO, ForwardRef, get_args
|
|
|
60
60
|
|
|
61
61
|
from dissect.cstruct import compiler
|
|
62
62
|
from dissect.cstruct.cstruct import cstruct
|
|
63
|
+
from dissect.cstruct.exception import DefinitionError
|
|
63
64
|
from dissect.cstruct.types.base import BaseArray, MetaType
|
|
64
65
|
from dissect.cstruct.types.structure import Field
|
|
65
66
|
from dissect.cstruct.types.structure import Structure as _Structure
|
|
@@ -370,7 +371,7 @@ def _resolve_type(type_: Any, cs: cstruct) -> type:
|
|
|
370
371
|
if isinstance(type_, str):
|
|
371
372
|
return _resolve_string(type_, cs)
|
|
372
373
|
|
|
373
|
-
raise
|
|
374
|
+
raise DefinitionError(f"Unsupported field annotation: {type_!r}")
|
|
374
375
|
|
|
375
376
|
|
|
376
377
|
def _resolve_field(cls: type, name: str, spec: FieldSpec) -> Field:
|
|
@@ -380,7 +381,7 @@ def _resolve_field(cls: type, name: str, spec: FieldSpec) -> Field:
|
|
|
380
381
|
while issubclass(embedded, BaseArray):
|
|
381
382
|
embedded = embedded.__type__
|
|
382
383
|
if embedded is cls:
|
|
383
|
-
raise
|
|
384
|
+
raise DefinitionError(f"Field {name!r} embeds {cls.__name__!r} in itself, use a pointer instead")
|
|
384
385
|
|
|
385
386
|
return Field(name, type_, spec.bits, spec.offset)
|
|
386
387
|
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import builtins
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Error(Exception):
|
|
7
|
+
"""Base class for all exceptions."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class DefinitionError(Error, ValueError):
|
|
11
|
+
"""A type definition is invalid."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class LexerError(DefinitionError):
|
|
15
|
+
"""The type definition can't be tokenized."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ParserError(DefinitionError):
|
|
19
|
+
"""The type definition can't be parsed."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ResolveError(DefinitionError):
|
|
23
|
+
"""The type definition can't be resolved."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ExpressionParserError(DefinitionError):
|
|
27
|
+
"""The expression can't be parsed."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class UnknownIdentifierError(ExpressionParserError):
|
|
31
|
+
"""The identifier is not defined."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class ReadError(Error, ValueError):
|
|
35
|
+
"""The data can't be parsed."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class NullPointerDereference(ReadError):
|
|
39
|
+
"""A pointer is null, but it was dereferenced."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class WriteError(Error, ValueError):
|
|
43
|
+
"""The value can't be written."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class EOFError(Error, builtins.EOFError):
|
|
47
|
+
"""The data ends before the value does."""
|
|
@@ -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
|
|
77
|
-
|
|
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
|
|
81
|
-
|
|
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:
|
|
138
|
-
|
|
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:
|
|
163
|
-
|
|
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.
|
|
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
|
|
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.
|
|
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.
|
|
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
|
-
|
|
241
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
264
|
-
|
|
265
|
-
|
|
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
|
-
|
|
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
|
-
|
|
273
|
-
|
|
331
|
+
output.append((func, tuple(args)))
|
|
332
|
+
operands += 1
|
|
274
333
|
|
|
275
334
|
elif token.type in IDENTIFIER_TYPES:
|
|
276
|
-
|
|
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
|
|
341
|
+
f"Parser expected sizeof or an arithmethic operator instead got: '{self._previous().value}'",
|
|
282
342
|
token=self._previous(),
|
|
283
343
|
)
|
|
284
344
|
|
|
285
|
-
|
|
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(
|
|
354
|
+
if len(stack) == 0:
|
|
295
355
|
raise self._error("Mismatched parentheses")
|
|
296
356
|
|
|
297
|
-
while
|
|
298
|
-
self.
|
|
299
|
-
if len(
|
|
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
|
-
|
|
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(
|
|
309
|
-
if TokenType.LPAREN in
|
|
368
|
+
while len(stack) != 0:
|
|
369
|
+
if TokenType.LPAREN in stack:
|
|
310
370
|
raise self._error("Mismatched parentheses")
|
|
311
|
-
self.
|
|
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
|
|
376
|
+
if operands > 1:
|
|
314
377
|
raise self._error("Invalid expression: too many operands")
|
|
315
378
|
|
|
316
|
-
return
|
|
379
|
+
return output
|