1 # The MIT License (MIT)
3 # Copyright (c) 2023 Philippe Proulx <eeppeliteloop@gmail.com>
5 # Permission is hereby granted, free of charge, to any person obtaining
6 # a copy of this software and associated documentation files (the
7 # "Software"), to deal in the Software without restriction, including
8 # without limitation the rights to use, copy, modify, merge, publish,
9 # distribute, sublicense, and/or sell copies of the Software, and to
10 # permit persons to whom the Software is furnished to do so, subject to
11 # the following conditions:
13 # The above copyright notice and this permission notice shall be
14 # included in all copies or substantial portions of the Software.
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19 # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20 # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21 # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22 # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 # This module is the portable Normand processor. It offers both the
25 # parse() function and the command-line tool (run the module itself)
26 # without external dependencies except a `typing` module for Python 3.4.
28 # Feel free to copy this module file to your own project to use Normand.
30 # Upstream repository: <https://github.com/efficios/normand>.
32 __author__
= "Philippe Proulx"
33 __version__
= "0.22.0"
61 from typing
import Any
, Set
, Dict
, List
, Union
, Pattern
, Callable
, NoReturn
, Optional
64 # Text location (line and column numbers).
67 def _create(cls
, line_no
: int, col_no
: int):
68 self
= cls
.__new
__(cls
)
69 self
._init
(line_no
, col_no
)
72 def __init__(*args
, **kwargs
): # type: ignore
73 raise NotImplementedError
75 def _init(self
, line_no
: int, col_no
: int):
76 self
._line
_no
= line_no
90 return "TextLocation({}, {})".format(self
._line
_no
, self
._col
_no
)
95 def __init__(self
, text_loc
: TextLocation
):
96 self
._text
_loc
= text_loc
98 # Source text location.
101 return self
._text
_loc
105 class _ScalarItem(_Item
):
106 # Returns the size, in bytes, of this item.
109 def size(self
) -> int:
119 class _Byte(_ScalarItem
, _RepableItem
):
120 def __init__(self
, val
: int, text_loc
: TextLocation
):
121 super().__init
__(text_loc
)
134 return "_Byte({}, {})".format(hex(self
._val
), repr(self
._text
_loc
))
138 class _LitStr(_ScalarItem
, _RepableItem
):
139 def __init__(self
, data
: bytes
, text_loc
: TextLocation
):
140 super().__init
__(text_loc
)
150 return len(self
._data
)
153 return "_LitStr({}, {})".format(repr(self
._data
), repr(self
._text
_loc
))
158 class ByteOrder(enum
.Enum
):
166 # Byte order setting.
168 def __init__(self
, bo
: ByteOrder
, text_loc
: TextLocation
):
169 super().__init
__(text_loc
)
177 return "_SetBo({}, {})".format(repr(self
._bo
), repr(self
._text
_loc
))
182 def __init__(self
, name
: str, text_loc
: TextLocation
):
183 super().__init
__(text_loc
)
192 return "_Label({}, {})".format(repr(self
._name
), repr(self
._text
_loc
))
196 class _SetOffset(_Item
):
197 def __init__(self
, val
: int, text_loc
: TextLocation
):
198 super().__init
__(text_loc
)
201 # Offset value (bytes).
207 return "_SetOffset({}, {})".format(repr(self
._val
), repr(self
._text
_loc
))
211 class _AlignOffset(_Item
):
212 def __init__(self
, val
: int, pad_val
: int, text_loc
: TextLocation
):
213 super().__init
__(text_loc
)
215 self
._pad
_val
= pad_val
217 # Alignment value (bits).
222 # Padding byte value.
228 return "_AlignOffset({}, {}, {})".format(
229 repr(self
._val
), repr(self
._pad
_val
), repr(self
._text
_loc
)
233 # Mixin of containing an AST expression and its string.
235 def __init__(self
, expr_str
: str, expr
: ast
.Expression
):
236 self
._expr
_str
= expr_str
242 return self
._expr
_str
244 # Expression node to evaluate.
250 # Fill until some offset.
251 class _FillUntil(_Item
, _ExprMixin
):
253 self
, expr_str
: str, expr
: ast
.Expression
, pad_val
: int, text_loc
: TextLocation
255 super().__init
__(text_loc
)
256 _ExprMixin
.__init
__(self
, expr_str
, expr
)
257 self
._pad
_val
= pad_val
259 # Padding byte value.
265 return "_FillUntil({}, {}, {}, {})".format(
266 repr(self
._expr
_str
),
269 repr(self
._text
_loc
),
273 # Variable assignment.
274 class _VarAssign(_Item
, _ExprMixin
):
276 self
, name
: str, expr_str
: str, expr
: ast
.Expression
, text_loc
: TextLocation
278 super().__init
__(text_loc
)
279 _ExprMixin
.__init
__(self
, expr_str
, expr
)
288 return "_VarAssign({}, {}, {}, {})".format(
290 repr(self
._expr
_str
),
292 repr(self
._text
_loc
),
296 # Fixed-length number, possibly needing more than one byte.
297 class _FlNum(_ScalarItem
, _RepableItem
, _ExprMixin
):
299 self
, expr_str
: str, expr
: ast
.Expression
, len: int, text_loc
: TextLocation
301 super().__init
__(text_loc
)
302 _ExprMixin
.__init
__(self
, expr_str
, expr
)
312 return self
._len
// 8
315 return "_FlNum({}, {}, {}, {})".format(
316 repr(self
._expr
_str
),
319 repr(self
._text
_loc
),
324 class _Leb128Int(_Item
, _RepableItem
, _ExprMixin
):
325 def __init__(self
, expr_str
: str, expr
: ast
.Expression
, text_loc
: TextLocation
):
326 super().__init
__(text_loc
)
327 _ExprMixin
.__init
__(self
, expr_str
, expr
)
330 return "{}({}, {}, {})".format(
331 self
.__class
__.__name
__,
332 repr(self
._expr
_str
),
334 repr(self
._text
_loc
),
338 # Unsigned LEB128 integer.
339 class _ULeb128Int(_Leb128Int
, _RepableItem
, _ExprMixin
):
343 # Signed LEB128 integer.
344 class _SLeb128Int(_Leb128Int
, _RepableItem
, _ExprMixin
):
349 class _Str(_Item
, _RepableItem
, _ExprMixin
):
351 self
, expr_str
: str, expr
: ast
.Expression
, codec
: str, text_loc
: TextLocation
353 super().__init
__(text_loc
)
354 _ExprMixin
.__init
__(self
, expr_str
, expr
)
363 return "_Str({}, {}, {}, {})".format(
364 repr(self
._expr
_str
),
367 repr(self
._text
_loc
),
372 class _Group(_Item
, _RepableItem
):
373 def __init__(self
, items
: List
[_Item
], text_loc
: TextLocation
):
374 super().__init
__(text_loc
)
383 return "_Group({}, {})".format(repr(self
._items
), repr(self
._text
_loc
))
387 class _Rep(_Group
, _ExprMixin
):
392 expr
: ast
.Expression
,
393 text_loc
: TextLocation
,
395 super().__init
__(items
, text_loc
)
396 _ExprMixin
.__init
__(self
, expr_str
, expr
)
399 return "_Rep({}, {}, {}, {})".format(
401 repr(self
._expr
_str
),
403 repr(self
._text
_loc
),
408 class _Cond(_Item
, _ExprMixin
):
414 expr
: ast
.Expression
,
415 text_loc
: TextLocation
,
417 super().__init
__(text_loc
)
418 _ExprMixin
.__init
__(self
, expr_str
, expr
)
419 self
._true
_item
= true_item
420 self
._false
_item
= false_item
422 # Item when condition is true.
425 return self
._true
_item
427 # Item when condition is false.
429 def false_item(self
):
430 return self
._false
_item
433 return "_Cond({}, {}, {}, {}, {})".format(
434 repr(self
._true
_item
),
435 repr(self
._false
_item
),
436 repr(self
._expr
_str
),
438 repr(self
._text
_loc
),
443 class _Trans(_Group
, _RepableItem
):
448 func
: Callable
[[Union
[bytes
, bytearray
]], bytes
],
449 text_loc
: TextLocation
,
451 super().__init
__(items
, text_loc
)
459 # Transforms the data `data`.
460 def trans(self
, data
: Union
[bytes
, bytearray
]):
461 return self
._func
(data
)
464 return "_Trans({}, {}, {}, {})".format(
468 repr(self
._text
_loc
),
472 # Macro definition item.
473 class _MacroDef(_Group
):
477 param_names
: List
[str],
479 text_loc
: TextLocation
,
481 super().__init
__(items
, text_loc
)
483 self
._param
_names
= param_names
492 def param_names(self
):
493 return self
._param
_names
496 return "_MacroDef({}, {}, {}, {})".format(
498 repr(self
._param
_names
),
500 repr(self
._text
_loc
),
504 # Macro expansion parameter.
505 class _MacroExpParam
:
506 def __init__(self
, expr_str
: str, expr
: ast
.Expression
, text_loc
: TextLocation
):
507 self
._expr
_str
= expr_str
509 self
._text
_loc
= text_loc
514 return self
._expr
_str
521 # Source text location.
524 return self
._text
_loc
527 return "_MacroExpParam({}, {}, {})".format(
528 repr(self
._expr
_str
), repr(self
._expr
), repr(self
._text
_loc
)
532 # Macro expansion item.
533 class _MacroExp(_Item
, _RepableItem
):
537 params
: List
[_MacroExpParam
],
538 text_loc
: TextLocation
,
540 super().__init
__(text_loc
)
542 self
._params
= params
555 return "_MacroExp({}, {}, {})".format(
558 repr(self
._text
_loc
),
562 # A parsing error message: a string and a text location.
563 class ParseErrorMessage
:
565 def _create(cls
, text
: str, text_loc
: TextLocation
):
566 self
= cls
.__new
__(cls
)
567 self
._init
(text
, text_loc
)
570 def __init__(self
, *args
, **kwargs
): # type: ignore
571 raise NotImplementedError
573 def _init(self
, text
: str, text_loc
: TextLocation
):
575 self
._text
_loc
= text_loc
582 # Source text location.
584 def text_location(self
):
585 return self
._text
_loc
588 # A parsing error containing one or more messages (`ParseErrorMessage`).
589 class ParseError(RuntimeError):
591 def _create(cls
, msg
: str, text_loc
: TextLocation
):
592 self
= cls
.__new
__(cls
)
593 self
._init
(msg
, text_loc
)
596 def __init__(self
, *args
, **kwargs
): # type: ignore
597 raise NotImplementedError
599 def _init(self
, msg
: str, text_loc
: TextLocation
):
600 super().__init
__(msg
)
601 self
._msgs
= [] # type: List[ParseErrorMessage]
602 self
._add
_msg
(msg
, text_loc
)
604 def _add_msg(self
, msg
: str, text_loc
: TextLocation
):
606 ParseErrorMessage
._create
( # pyright: ignore[reportPrivateUsage]
611 # Parsing error messages.
613 # The first message is the most specific one.
619 # Raises a parsing error, forwarding the parameters to the constructor.
620 def _raise_error(msg
: str, text_loc
: TextLocation
) -> NoReturn
:
621 raise ParseError
._create
(msg
, text_loc
) # pyright: ignore[reportPrivateUsage]
624 # Adds a message to the parsing error `exc`.
625 def _add_error_msg(exc
: ParseError
, msg
: str, text_loc
: TextLocation
):
626 exc
._add
_msg
(msg
, text_loc
) # pyright: ignore[reportPrivateUsage]
629 # Appends a message to the parsing error `exc` and reraises it.
630 def _augment_error(exc
: ParseError
, msg
: str, text_loc
: TextLocation
) -> NoReturn
:
631 _add_error_msg(exc
, msg
, text_loc
)
635 # Returns a normalized version (so as to be parseable by int()) of
636 # the constant integer string `s`, possibly negative, dealing with
638 def _norm_const_int(s
: str):
642 if s
.startswith("-"):
647 if pos
.startswith("0" + r
):
663 for suf
in asm_suf_base
:
665 s
= "{}0{}{}".format(neg
, asm_suf_base
[suf
], pos
.rstrip(suf
))
670 # Encodes the string `s` using the codec `codec`, raising `ParseError`
671 # with `text_loc` on encoding error.
672 def _encode_str(s
: str, codec
: str, text_loc
: TextLocation
):
674 return s
.encode(codec
)
675 except UnicodeEncodeError:
677 "Cannot encode `{}` with the `{}` encoding".format(s
, codec
), text_loc
681 # Variables dictionary type (for type hints).
682 VariablesT
= Dict
[str, Union
[int, float, str]]
685 # Labels dictionary type (for type hints).
686 LabelsT
= Dict
[str, int]
690 _py_name_pat
= re
.compile(r
"[a-zA-Z_][a-zA-Z0-9_]*")
691 _pos_const_int_pat
= re
.compile(
692 r
"(?:0[Xx][A-Fa-f0-9]+|0[Oo][0-7]+|0[Bb][01]+|[A-Fa-f0-9]+[hH]|[0-7]+[qQoO]|[01]+[bB]|\d+)\b"
694 _const_int_pat
= re
.compile(r
"(?P<neg>-)?(?:{})".format(_pos_const_int_pat
.pattern
))
695 _const_float_pat
= re
.compile(
696 r
"[-+]?(?:(?:\d*\.\d+)|(?:\d+\.))(?:[Ee][+-]?\d+)?(?=\W|)"
700 # Macro definition dictionary.
701 _MacroDefsT
= Dict
[str, _MacroDef
]
706 # The constructor accepts a Normand input. After building, use the `res`
707 # property to get the resulting main group.
709 # Builds a parser to parse the Normand input `normand`, parsing
711 def __init__(self
, normand
: str, variables
: VariablesT
, labels
: LabelsT
):
712 self
._normand
= normand
716 self
._label
_names
= set(labels
.keys())
717 self
._var
_names
= set(variables
.keys())
718 self
._macro
_defs
= {} # type: _MacroDefsT
719 self
._base
_item
_parse
_funcs
= [
720 self
._try
_parse
_byte
,
723 self
._try
_parse
_var
_assign
,
724 self
._try
_parse
_set
_bo
,
725 self
._try
_parse
_label
_or
_set
_offset
,
726 self
._try
_parse
_align
_offset
,
727 self
._try
_parse
_fill
_until
,
728 self
._try
_parse
_group
,
729 self
._try
_parse
_rep
_block
,
730 self
._try
_parse
_cond
_block
,
731 self
._try
_parse
_macro
_exp
,
732 self
._try
_parse
_trans
_block
,
736 # Result (main group).
743 def macro_defs(self
):
744 return self
._macro
_defs
746 # Current text location.
749 return TextLocation
._create
( # pyright: ignore[reportPrivateUsage]
750 self
._line
_no
, self
._col
_no
753 # Returns `True` if this parser is done parsing.
755 return self
._at
== len(self
._normand
)
757 # Returns `True` if this parser isn't done parsing.
758 def _isnt_done(self
):
759 return not self
._is
_done
()
761 # Raises a parse error, creating it using the message `msg` and the
762 # current text location.
763 def _raise_error(self
, msg
: str) -> NoReturn
:
764 _raise_error(msg
, self
._text
_loc
)
766 # Tries to make the pattern `pat` match the current substring,
767 # returning the match object and updating `self._at`,
768 # `self._line_no`, and `self._col_no` on success.
769 def _try_parse_pat(self
, pat
: Pattern
[str]):
770 m
= pat
.match(self
._normand
, self
._at
)
775 # Skip matched string
776 self
._at
+= len(m
.group(0))
779 self
._line
_no
+= m
.group(0).count("\n")
781 # Update column number
782 for i
in reversed(range(self
._at
)):
783 if self
._normand
[i
] == "\n" or i
== 0:
785 self
._col
_no
= self
._at
+ 1
787 self
._col
_no
= self
._at
- i
791 # Return match object
794 # Expects the pattern `pat` to match the current substring,
795 # returning the match object and updating `self._at`,
796 # `self._line_no`, and `self._col_no` on success, or raising a parse
797 # error with the message `error_msg` on error.
798 def _expect_pat(self
, pat
: Pattern
[str], error_msg
: str):
800 m
= self
._try
_parse
_pat
(pat
)
804 self
._raise
_error
(error_msg
)
806 # Return match object
809 # Patterns for _skip_*()
810 _comment_pat
= re
.compile(r
"#[^#]*?(?:$|#)", re
.M
)
811 _ws_or_comments_pat
= re
.compile(r
"(?:\s|{})*".format(_comment_pat
.pattern
), re
.M
)
812 _ws_or_syms_or_comments_pat
= re
.compile(
813 r
"(?:[\s/\\?&:;.,_=|-]|{})*".format(_comment_pat
.pattern
), re
.M
816 # Skips as many whitespaces and comments as possible, but not
817 # insignificant symbol characters.
818 def _skip_ws_and_comments(self
):
819 self
._try
_parse
_pat
(self
._ws
_or
_comments
_pat
)
821 # Skips as many whitespaces, insignificant symbol characters, and
822 # comments as possible.
823 def _skip_ws_and_comments_and_syms(self
):
824 self
._try
_parse
_pat
(self
._ws
_or
_syms
_or
_comments
_pat
)
826 # Pattern for _try_parse_hex_byte()
827 _nibble_pat
= re
.compile(r
"[A-Fa-f0-9]")
829 # Tries to parse a hexadecimal byte, returning a byte item on
831 def _try_parse_hex_byte(self
):
832 begin_text_loc
= self
._text
_loc
834 # Match initial nibble
835 m_high
= self
._try
_parse
_pat
(self
._nibble
_pat
)
841 # Expect another nibble
842 self
._skip
_ws
_and
_comments
_and
_syms
()
843 m_low
= self
._expect
_pat
(
844 self
._nibble
_pat
, "Expecting another hexadecimal nibble"
848 return _Byte(int(m_high
.group(0) + m_low
.group(0), 16), begin_text_loc
)
850 # Patterns for _try_parse_bin_byte()
851 _bin_byte_bit_pat
= re
.compile(r
"[01]")
852 _bin_byte_prefix_pat
= re
.compile(r
"%+")
854 # Tries to parse a binary byte, returning a byte item on success.
855 def _try_parse_bin_byte(self
):
856 begin_text_loc
= self
._text
_loc
859 m
= self
._try
_parse
_pat
(self
._bin
_byte
_prefix
_pat
)
865 # Expect as many bytes as there are `%` prefixes
866 items
= [] # type: List[_Item]
868 for _
in range(len(m
.group(0))):
869 self
._skip
_ws
_and
_comments
_and
_syms
()
870 byte_text_loc
= self
._text
_loc
871 bits
= [] # type: List[str]
875 self
._skip
_ws
_and
_comments
_and
_syms
()
876 m
= self
._expect
_pat
(
877 self
._bin
_byte
_bit
_pat
, "Expecting a bit (`0` or `1`)"
879 bits
.append(m
.group(0))
881 items
.append(_Byte(int("".join(bits
), 2), byte_text_loc
))
888 return _Group(items
, begin_text_loc
)
890 # Patterns for _try_parse_dec_byte()
891 _dec_byte_prefix_pat
= re
.compile(r
"\$")
892 _dec_byte_val_pat
= re
.compile(r
"(?P<neg>-?)(?P<val>\d+)")
894 # Tries to parse a decimal byte, returning a byte item on success.
895 def _try_parse_dec_byte(self
):
896 begin_text_loc
= self
._text
_loc
899 if self
._try
_parse
_pat
(self
._dec
_byte
_prefix
_pat
) is None:
904 self
._skip
_ws
_and
_comments
()
905 m
= self
._expect
_pat
(self
._dec
_byte
_val
_pat
, "Expecting a decimal constant")
908 val
= int(m
.group("val")) * (-1 if m
.group("neg") == "-" else 1)
911 if val
< -128 or val
> 255:
912 _raise_error("Invalid decimal byte value {}".format(val
), begin_text_loc
)
918 return _Byte(val
, begin_text_loc
)
920 # Tries to parse a byte, returning a byte item on success.
921 def _try_parse_byte(self
):
923 item
= self
._try
_parse
_hex
_byte
()
929 item
= self
._try
_parse
_bin
_byte
()
935 item
= self
._try
_parse
_dec
_byte
()
940 # Strings corresponding to escape sequence characters
941 _lit_str_escape_seq_strs
= {
955 # Patterns for _try_parse_lit_str()
956 _lit_str_prefix_suffix_pat
= re
.compile(r
'"')
957 _lit_str_contents_pat
= re
.compile(r
'(?:(?:\\.)|[^"])*')
959 # Parses a literal string between double quotes (without an encoding
960 # prefix) and returns the resulting string.
961 def _try_parse_lit_str(self
, with_prefix
: bool):
962 # Match prefix if needed
964 if self
._try
_parse
_pat
(self
._lit
_str
_prefix
_suffix
_pat
) is None:
968 # Expect literal string
969 m
= self
._expect
_pat
(self
._lit
_str
_contents
_pat
, "Expecting a literal string")
971 # Expect end of string
973 self
._lit
_str
_prefix
_suffix
_pat
, 'Expecting `"` (end of literal string)'
976 # Replace escape sequences
979 for ec
in '0abefnrtv"\\':
980 val
= val
.replace(r
"\{}".format(ec
), self
._lit
_str
_escape
_seq
_strs
[ec
])
985 # Patterns for _try_parse_utf_str_encoding()
986 _str_encoding_utf_prefix_pat
= re
.compile(r
"u")
987 _str_encoding_utf_pat
= re
.compile(r
"(?:8|(?:(?:16|32)(?:[bl]e)))\b")
989 # Tries to parse a UTF encoding specification, returning the Python
990 # codec name on success.
991 def _try_parse_utf_str_encoding(self
):
993 if self
._try
_parse
_pat
(self
._str
_encoding
_utf
_prefix
_pat
) is None:
997 # Expect UTF specification
998 m
= self
._expect
_pat
(
999 self
._str
_encoding
_utf
_pat
,
1000 "Expecting `8`, `16be`, `16le`, `32be` or `32le`",
1003 # Convert to codec name
1006 "16be": "utf_16_be",
1007 "16le": "utf_16_le",
1008 "32be": "utf_32_be",
1009 "32le": "utf_32_le",
1012 # Patterns for _try_parse_str_encoding()
1013 _str_encoding_gen_prefix_pat
= re
.compile(r
"s")
1014 _str_encoding_colon_pat
= re
.compile(r
":")
1015 _str_encoding_non_utf_pat
= re
.compile(r
"latin(?:[1-9]|10)\b")
1017 # Tries to parse a string encoding specification, returning the
1018 # Python codec name on success.
1020 # Requires the general prefix (`s:`) if `req_gen_prefix` is `True`.
1021 def _try_parse_str_encoding(self
, req_gen_prefix
: bool = False):
1023 if self
._try
_parse
_pat
(self
._str
_encoding
_gen
_prefix
_pat
) is not None:
1025 self
._skip
_ws
_and
_comments
()
1026 self
._expect
_pat
(self
._str
_encoding
_colon
_pat
, "Expecting `:`")
1028 # Expect encoding specification
1029 self
._skip
_ws
_and
_comments
()
1032 codec
= self
._try
_parse
_utf
_str
_encoding
()
1034 if codec
is not None:
1038 m
= self
._expect
_pat
(
1039 self
._str
_encoding
_non
_utf
_pat
,
1040 "Expecting `u8`, `u16be`, `u16le`, `u32be`, `u32le`, or `latin1` to `latin10`",
1045 if not req_gen_prefix
:
1046 return self
._try
_parse
_utf
_str
_encoding
()
1048 # Patterns for _try_parse_str()
1049 _lit_str_prefix_pat
= re
.compile(r
'"')
1050 _str_prefix_pat
= re
.compile(r
'"|\{')
1051 _str_expr_pat
= re
.compile(r
"[^}]+")
1052 _str_expr_suffix_pat
= re
.compile(r
"\}")
1054 # Tries to parse a string, returning a literal string or string item
1056 def _try_parse_str(self
):
1057 begin_text_loc
= self
._text
_loc
1060 codec
= self
._try
_parse
_str
_encoding
()
1062 # Match prefix (expect if there's an encoding specification)
1063 self
._skip
_ws
_and
_comments
()
1066 # No encoding: only a literal string (UTF-8) is legal
1067 m_prefix
= self
._try
_parse
_pat
(self
._lit
_str
_prefix
_pat
)
1069 if m_prefix
is None:
1072 # Encoding present: expect a string prefix
1073 m_prefix
= self
._expect
_pat
(self
._str
_prefix
_pat
, 'Expecting `"` or `{`')
1075 # Literal string or expression?
1076 prefix
= m_prefix
.group(0)
1079 # Expect literal string
1080 str_text_loc
= self
._text
_loc
1081 val
= self
._try
_parse
_lit
_str
(False)
1084 self
._raise
_error
("Expecting a literal string")
1087 data
= _encode_str(val
, "utf_8" if codec
is None else codec
, str_text_loc
)
1090 return _LitStr(data
, begin_text_loc
)
1093 self
._skip
_ws
_and
_comments
()
1094 expr_text_loc
= self
._text
_loc
1095 m
= self
._expect
_pat
(self
._str
_expr
_pat
, "Expecting an expression")
1098 self
._expect
_pat
(self
._str
_expr
_suffix
_pat
, "Expecting `}`")
1100 # Create an expression node from the expression string
1101 expr_str
, expr
= self
._ast
_expr
_from
_str
(m
.group(0), expr_text_loc
)
1104 assert codec
is not None
1105 return _Str(expr_str
, expr
, codec
, begin_text_loc
)
1107 # Common right parenthesis pattern
1108 _right_paren_pat
= re
.compile(r
"\)")
1110 # Patterns for _try_parse_group()
1111 _group_prefix_pat
= re
.compile(r
"\(|!g(?:roup)?\b")
1113 # Tries to parse a group, returning a group item on success.
1114 def _try_parse_group(self
):
1115 begin_text_loc
= self
._text
_loc
1118 m_open
= self
._try
_parse
_pat
(self
._group
_prefix
_pat
)
1125 items
= self
._parse
_items
()
1127 # Expect end of group
1128 self
._skip
_ws
_and
_comments
_and
_syms
()
1130 if m_open
.group(0) == "(":
1131 pat
= self
._right
_paren
_pat
1134 pat
= self
._block
_end
_pat
1137 self
._expect
_pat
(pat
, "Expecting an item or `{}` (end of group)".format(exp
))
1140 return _Group(items
, begin_text_loc
)
1142 # Returns a stripped expression string and an AST expression node
1143 # from the expression string `expr_str` at text location `text_loc`.
1144 def _ast_expr_from_str(self
, expr_str
: str, text_loc
: TextLocation
):
1145 # Create an expression node from the expression string
1146 expr_str
= expr_str
.strip().replace("\n", " ")
1149 expr
= ast
.parse(expr_str
, mode
="eval")
1152 "Invalid expression `{}`: invalid syntax".format(expr_str
),
1156 return expr_str
, expr
1158 # Patterns for _try_parse_val()
1159 _val_prefix_pat
= re
.compile(r
"\[")
1160 _val_expr_pat
= re
.compile(r
"([^\]:]+):")
1161 _fl_num_len_fmt_pat
= re
.compile(r
"8|16|24|32|40|48|56|64")
1162 _leb128_int_fmt_pat
= re
.compile(r
"(u|s)leb128")
1163 _val_suffix_pat
= re
.compile(r
"]")
1165 # Tries to parse a value (number or string) and format (fixed length
1166 # in bits, `uleb128`, `sleb128`, or `s:` followed with an encoding
1167 # name), returning an item on success.
1168 def _try_parse_val(self
):
1170 if self
._try
_parse
_pat
(self
._val
_prefix
_pat
) is None:
1174 # Expect expression and `:`
1175 self
._skip
_ws
_and
_comments
()
1176 expr_text_loc
= self
._text
_loc
1177 m
= self
._expect
_pat
(self
._val
_expr
_pat
, "Expecting an expression")
1179 # Create an expression node from the expression string
1180 expr_str
, expr
= self
._ast
_expr
_from
_str
(m
.group(1), expr_text_loc
)
1183 self
._skip
_ws
_and
_comments
()
1184 m_fmt
= self
._try
_parse
_pat
(self
._fl
_num
_len
_fmt
_pat
)
1186 if m_fmt
is not None:
1187 # Create fixed-length number item
1191 int(m_fmt
.group(0)),
1196 m_fmt
= self
._try
_parse
_pat
(self
._leb
128_int
_fmt
_pat
)
1198 if m_fmt
is not None:
1199 # Create LEB128 integer item
1200 cls
= _ULeb128Int
if m_fmt
.group(1) == "u" else _SLeb128Int
1201 item
= cls(expr_str
, expr
, expr_text_loc
)
1204 codec
= self
._try
_parse
_str
_encoding
(True)
1206 if codec
is not None:
1207 # Create string item
1208 item
= _Str(expr_str
, expr
, codec
, expr_text_loc
)
1210 # At this point it's invalid
1212 "Expecting a fixed length (multiple of eight bits), `uleb128`, `sleb128`, or `s:` followed with a valid encoding (`u8`, `u16be`, `u16le`, `u32be`, `u32le`, or `latin1` to `latin10`)"
1216 self
._skip
_ws
_and
_comments
()
1217 m
= self
._expect
_pat
(self
._val
_suffix
_pat
, "Expecting `]`")
1222 # Patterns for _try_parse_var_assign()
1223 _var_assign_prefix_pat
= re
.compile(r
"\{")
1224 _var_assign_equal_pat
= re
.compile(r
"=")
1225 _var_assign_expr_pat
= re
.compile(r
"[^}]+")
1226 _var_assign_suffix_pat
= re
.compile(r
"\}")
1228 # Tries to parse a variable assignment, returning a variable
1229 # assignment item on success.
1230 def _try_parse_var_assign(self
):
1232 if self
._try
_parse
_pat
(self
._var
_assign
_prefix
_pat
) is None:
1237 self
._skip
_ws
_and
_comments
()
1238 name_text_loc
= self
._text
_loc
1239 m
= self
._expect
_pat
(_py_name_pat
, "Expecting a valid Python name")
1243 self
._skip
_ws
_and
_comments
()
1244 self
._expect
_pat
(self
._var
_assign
_equal
_pat
, "Expecting `=`")
1247 self
._skip
_ws
_and
_comments
()
1248 expr_text_loc
= self
._text
_loc
1249 m_expr
= self
._expect
_pat
(self
._var
_assign
_expr
_pat
, "Expecting an expression")
1252 self
._skip
_ws
_and
_comments
()
1253 self
._expect
_pat
(self
._var
_assign
_suffix
_pat
, "Expecting `}`")
1256 if name
== _icitte_name
:
1258 "`{}` is a reserved variable name".format(_icitte_name
), name_text_loc
1261 if name
in self
._label
_names
:
1262 _raise_error("Existing label named `{}`".format(name
), name_text_loc
)
1264 # Create an expression node from the expression string
1265 expr_str
, expr
= self
._ast
_expr
_from
_str
(m_expr
.group(0), expr_text_loc
)
1267 # Add to known variable names
1268 self
._var
_names
.add(name
)
1278 # Pattern for _try_parse_set_bo()
1279 _set_bo_pat
= re
.compile(r
"!([bl]e)\b")
1281 # Tries to parse a byte order setting, returning a byte order
1282 # setting item on success.
1283 def _try_parse_set_bo(self
):
1284 begin_text_loc
= self
._text
_loc
1287 m
= self
._try
_parse
_pat
(self
._set
_bo
_pat
)
1293 # Return corresponding item
1294 if m
.group(1) == "be":
1297 assert m
.group(1) == "le"
1300 return _SetBo(bo
, begin_text_loc
)
1302 # Tries to parse an offset setting value (after the initial `<`),
1303 # returning an offset item on success.
1304 def _try_parse_set_offset_val(self
):
1305 begin_text_loc
= self
._text
_loc
1308 m
= self
._try
_parse
_pat
(_pos_const_int_pat
)
1315 return _SetOffset(int(_norm_const_int(m
.group(0)), 0), begin_text_loc
)
1317 # Tries to parse a label name (after the initial `<`), returning a
1318 # label item on success.
1319 def _try_parse_label_name(self
):
1320 begin_text_loc
= self
._text
_loc
1323 m
= self
._try
_parse
_pat
(_py_name_pat
)
1332 if name
== _icitte_name
:
1334 "`{}` is a reserved label name".format(_icitte_name
), begin_text_loc
1337 if name
in self
._label
_names
:
1338 _raise_error("Duplicate label name `{}`".format(name
), begin_text_loc
)
1340 if name
in self
._var
_names
:
1341 _raise_error("Existing variable named `{}`".format(name
), begin_text_loc
)
1343 # Add to known label names
1344 self
._label
_names
.add(name
)
1347 return _Label(name
, begin_text_loc
)
1349 # Patterns for _try_parse_label_or_set_offset()
1350 _label_set_offset_prefix_pat
= re
.compile(r
"<")
1351 _label_set_offset_suffix_pat
= re
.compile(r
">")
1353 # Tries to parse a label or an offset setting, returning an item on
1355 def _try_parse_label_or_set_offset(self
):
1357 if self
._try
_parse
_pat
(self
._label
_set
_offset
_prefix
_pat
) is None:
1361 # Offset setting item?
1362 self
._skip
_ws
_and
_comments
()
1363 item
= self
._try
_parse
_set
_offset
_val
()
1367 item
= self
._try
_parse
_label
_name
()
1370 # At this point it's invalid
1371 self
._raise
_error
("Expecting a label name or an offset setting value")
1374 self
._skip
_ws
_and
_comments
()
1375 self
._expect
_pat
(self
._label
_set
_offset
_suffix
_pat
, "Expecting `>`")
1378 # Pattern for _parse_pad_val()
1379 _pad_val_prefix_pat
= re
.compile(r
"~")
1381 # Tries to parse a padding value, returning the padding value, or 0
1383 def _parse_pad_val(self
):
1385 self
._skip
_ws
_and
_comments
()
1388 if self
._try
_parse
_pat
(self
._pad
_val
_prefix
_pat
) is not None:
1389 self
._skip
_ws
_and
_comments
()
1390 pad_val_text_loc
= self
._text
_loc
1391 m
= self
._expect
_pat
(
1393 "Expecting a positive constant integer (byte value)",
1397 pad_val
= int(_norm_const_int(m
.group(0)), 0)
1401 "Invalid padding byte value {}".format(pad_val
),
1407 # Patterns for _try_parse_align_offset()
1408 _align_offset_prefix_pat
= re
.compile(r
"@")
1409 _align_offset_val_pat
= re
.compile(r
"\d+")
1411 # Tries to parse an offset alignment, returning an offset alignment
1413 def _try_parse_align_offset(self
):
1414 begin_text_loc
= self
._text
_loc
1417 if self
._try
_parse
_pat
(self
._align
_offset
_prefix
_pat
) is None:
1421 # Expect an alignment
1422 self
._skip
_ws
_and
_comments
()
1423 align_text_loc
= self
._text
_loc
1424 m
= self
._expect
_pat
(
1425 self
._align
_offset
_val
_pat
,
1426 "Expecting an alignment (positive multiple of eight bits)",
1429 # Validate alignment
1430 val
= int(m
.group(0))
1432 if val
<= 0 or (val
% 8) != 0:
1434 "Invalid alignment value {} (not a positive multiple of eight)".format(
1441 pad_val
= self
._parse
_pad
_val
()
1444 return _AlignOffset(val
, pad_val
, begin_text_loc
)
1446 # Patterns for _expect_expr()
1447 _inner_expr_prefix_pat
= re
.compile(r
"\{")
1448 _inner_expr_pat
= re
.compile(r
"[^}]+")
1449 _inner_expr_suffix_pat
= re
.compile(r
"\}")
1451 # Parses an expression outside a `{`/`}` context.
1453 # This function accepts:
1455 # • A Python expression within `{` and `}`.
1457 # • A Python name.
1459 # • If `accept_const_int` is `True`: a constant integer, which may
1460 # be negative if `allow_neg_int` is `True`.
1462 # • If `accept_float` is `True`: a constant floating point number.
1464 # Returns the stripped expression string and AST expression.
1467 accept_const_int
: bool = False,
1468 allow_neg_int
: bool = False,
1469 accept_const_float
: bool = False,
1470 accept_lit_str
: bool = False,
1472 begin_text_loc
= self
._text
_loc
1474 # Constant floating point number?
1475 if accept_const_float
:
1476 m
= self
._try
_parse
_pat
(_const_float_pat
)
1479 return self
._ast
_expr
_from
_str
(m
.group(0), begin_text_loc
)
1482 if accept_const_int
:
1483 m
= self
._try
_parse
_pat
(_const_int_pat
)
1486 # Negative and allowed?
1487 if m
.group("neg") == "-" and not allow_neg_int
:
1489 "Expecting a positive constant integer", begin_text_loc
1492 expr_str
= _norm_const_int(m
.group(0))
1493 return self
._ast
_expr
_from
_str
(expr_str
, begin_text_loc
)
1496 m
= self
._try
_parse
_pat
(_py_name_pat
)
1499 return self
._ast
_expr
_from
_str
(m
.group(0), begin_text_loc
)
1503 val
= self
._try
_parse
_lit
_str
(True)
1506 return self
._ast
_expr
_from
_str
(repr(val
), begin_text_loc
)
1509 msg_accepted_parts
= ["a name", "or `{`"]
1512 msg_accepted_parts
.insert(0, "a literal string")
1514 if accept_const_float
:
1515 msg_accepted_parts
.insert(0, "a constant floating point number")
1517 if accept_const_int
:
1518 msg_pos
= "" if allow_neg_int
else "positive "
1519 msg_accepted_parts
.insert(0, "a {}constant integer".format(msg_pos
))
1521 if len(msg_accepted_parts
) == 2:
1522 msg_accepted
= " ".join(msg_accepted_parts
)
1524 msg_accepted
= ", ".join(msg_accepted_parts
)
1527 self
._inner
_expr
_prefix
_pat
,
1528 "Expecting {}".format(msg_accepted
),
1531 # Expect an expression
1532 self
._skip
_ws
_and
_comments
()
1533 expr_text_loc
= self
._text
_loc
1534 m
= self
._expect
_pat
(self
._inner
_expr
_pat
, "Expecting an expression")
1535 expr_str
= m
.group(0)
1538 self
._skip
_ws
_and
_comments
()
1539 self
._expect
_pat
(self
._inner
_expr
_suffix
_pat
, "Expecting `}`")
1541 return self
._ast
_expr
_from
_str
(expr_str
, expr_text_loc
)
1543 # Patterns for _try_parse_fill_until()
1544 _fill_until_prefix_pat
= re
.compile(r
"\+")
1545 _fill_until_pad_val_prefix_pat
= re
.compile(r
"~")
1547 # Tries to parse a filling, returning a filling item on success.
1548 def _try_parse_fill_until(self
):
1549 begin_text_loc
= self
._text
_loc
1552 if self
._try
_parse
_pat
(self
._fill
_until
_prefix
_pat
) is None:
1557 self
._skip
_ws
_and
_comments
()
1558 expr_str
, expr
= self
._expect
_expr
(accept_const_int
=True)
1561 pad_val
= self
._parse
_pad
_val
()
1564 return _FillUntil(expr_str
, expr
, pad_val
, begin_text_loc
)
1566 # Parses the multiplier expression of a repetition (block or
1567 # post-item) and returns the expression string and AST node.
1568 def _expect_rep_mul_expr(self
):
1569 return self
._expect
_expr
(accept_const_int
=True)
1571 # Common block end pattern
1572 _block_end_pat
= re
.compile(r
"!end\b")
1574 # Pattern for _try_parse_rep_block()
1575 _rep_block_prefix_pat
= re
.compile(r
"!r(?:epeat)?\b")
1577 # Tries to parse a repetition block, returning a repetition item on
1579 def _try_parse_rep_block(self
):
1580 begin_text_loc
= self
._text
_loc
1583 if self
._try
_parse
_pat
(self
._rep
_block
_prefix
_pat
) is None:
1588 self
._skip
_ws
_and
_comments
()
1589 expr_str
, expr
= self
._expect
_rep
_mul
_expr
()
1592 self
._skip
_ws
_and
_comments
_and
_syms
()
1593 items
= self
._parse
_items
()
1595 # Expect end of block
1596 self
._skip
_ws
_and
_comments
_and
_syms
()
1598 self
._block
_end
_pat
, "Expecting an item or `!end` (end of repetition block)"
1602 return _Rep(items
, expr_str
, expr
, begin_text_loc
)
1604 # Pattern for _try_parse_cond_block()
1605 _cond_block_prefix_pat
= re
.compile(r
"!if\b")
1606 _cond_block_else_pat
= re
.compile(r
"!else\b")
1608 # Tries to parse a conditional block, returning a conditional item
1610 def _try_parse_cond_block(self
):
1611 begin_text_loc
= self
._text
_loc
1614 if self
._try
_parse
_pat
(self
._cond
_block
_prefix
_pat
) is None:
1619 self
._skip
_ws
_and
_comments
()
1620 expr_str
, expr
= self
._expect
_expr
()
1622 # Parse "true" items
1623 self
._skip
_ws
_and
_comments
_and
_syms
()
1624 true_items_text_loc
= self
._text
_loc
1625 true_items
= self
._parse
_items
()
1626 false_items
= [] # type: List[_Item]
1627 false_items_text_loc
= begin_text_loc
1630 self
._skip
_ws
_and
_comments
_and
_syms
()
1632 if self
._try
_parse
_pat
(self
._cond
_block
_else
_pat
) is not None:
1633 # Parse "false" items
1634 self
._skip
_ws
_and
_comments
_and
_syms
()
1635 false_items_text_loc
= self
._text
_loc
1636 false_items
= self
._parse
_items
()
1638 # Expect end of block
1640 self
._block
_end
_pat
,
1641 "Expecting an item, `!else`, or `!end` (end of conditional block)",
1646 _Group(true_items
, true_items_text_loc
),
1647 _Group(false_items
, false_items_text_loc
),
1653 # Pattern for _try_parse_trans_block()
1654 _trans_block_prefix_pat
= re
.compile(r
"!t(?:ransform)?\b")
1655 _trans_block_type_pat
= re
.compile(
1656 r
"(?:(?:base|b)64(?:u)?|(?:base|b)(?:16|32)|(?:ascii|a|base|b)85(?:p)?|(?:quopri|qp)(?:t)?|gzip|gz|bzip2|bz2)\b"
1659 # Tries to parse a transformation block, returning a transformation
1660 # block item on success.
1661 def _try_parse_trans_block(self
):
1662 begin_text_loc
= self
._text
_loc
1665 if self
._try
_parse
_pat
(self
._trans
_block
_prefix
_pat
) is None:
1670 self
._skip
_ws
_and
_comments
()
1671 m
= self
._expect
_pat
(
1672 self
._trans
_block
_type
_pat
, "Expecting a known transformation type"
1676 self
._skip
_ws
_and
_comments
_and
_syms
()
1677 items
= self
._parse
_items
()
1679 # Expect end of block
1681 self
._block
_end
_pat
,
1682 "Expecting an item or `!end` (end of transformation block)",
1685 # Choose encoding function
1688 if enc
in ("base64", "b64"):
1689 func
= base64
.standard_b64encode
1690 name
= "standard Base64"
1691 elif enc
in ("base64u", "b64u"):
1692 func
= base64
.urlsafe_b64encode
1693 name
= "URL-safe Base64"
1694 elif enc
in ("base32", "b32"):
1695 func
= base64
.b32encode
1697 elif enc
in ("base16", "b16"):
1698 func
= base64
.b16encode
1700 elif enc
in ("ascii85", "a85"):
1701 func
= base64
.a85encode
1703 elif enc
in ("ascii85p", "a85p"):
1704 func
= functools
.partial(base64
.a85encode
, pad
=True)
1705 name
= "padded Ascii85"
1706 elif enc
in ("base85", "b85"):
1707 func
= base64
.b85encode
1709 elif enc
in ("base85p", "b85p"):
1710 func
= functools
.partial(base64
.b85encode
, pad
=True)
1711 name
= "padded Base85"
1712 elif enc
in ("quopri", "qp"):
1713 func
= quopri
.encodestring
1714 name
= "MIME quoted-printable"
1715 elif enc
in ("quoprit", "qpt"):
1716 func
= functools
.partial(quopri
.encodestring
, quotetabs
=True)
1717 name
= "MIME quoted-printable (with quoted tabs)"
1718 elif enc
in ("gzip", "gz"):
1719 func
= gzip
.compress
1722 assert enc
in ("bzip2", "bz2")
1734 # Common left parenthesis pattern
1735 _left_paren_pat
= re
.compile(r
"\(")
1737 # Patterns for _try_parse_macro_def() and _try_parse_macro_exp()
1738 _macro_params_comma_pat
= re
.compile(",")
1740 # Patterns for _try_parse_macro_def()
1741 _macro_def_prefix_pat
= re
.compile(r
"!m(?:acro)?\b")
1743 # Tries to parse a macro definition, adding it to `self._macro_defs`
1744 # and returning `True` on success.
1745 def _try_parse_macro_def(self
):
1746 begin_text_loc
= self
._text
_loc
1749 if self
._try
_parse
_pat
(self
._macro
_def
_prefix
_pat
) is None:
1754 self
._skip
_ws
_and
_comments
()
1755 name_text_loc
= self
._text
_loc
1756 m
= self
._expect
_pat
(_py_name_pat
, "Expecting a valid macro name")
1761 if name
in self
._macro
_defs
:
1762 _raise_error("Duplicate macro named `{}`".format(name
), name_text_loc
)
1765 self
._skip
_ws
_and
_comments
()
1766 self
._expect
_pat
(self
._left
_paren
_pat
, "Expecting `(`")
1768 # Try to parse comma-separated parameter names
1769 param_names
= [] # type: List[str]
1770 expect_comma
= False
1773 self
._skip
_ws
_and
_comments
()
1776 if self
._try
_parse
_pat
(self
._right
_paren
_pat
) is not None:
1782 self
._expect
_pat
(self
._macro
_params
_comma
_pat
, "Expecting `,`")
1784 # Expect parameter name
1785 self
._skip
_ws
_and
_comments
()
1786 param_text_loc
= self
._text
_loc
1787 m
= self
._expect
_pat
(_py_name_pat
, "Expecting valid parameter name")
1789 if m
.group(0) in param_names
:
1791 "Duplicate macro parameter named `{}`".format(m
.group(0)),
1795 param_names
.append(m
.group(0))
1799 self
._skip
_ws
_and
_comments
_and
_syms
()
1800 old_var_names
= self
._var
_names
.copy()
1801 old_label_names
= self
._label
_names
.copy()
1802 self
._var
_names
= set() # type: Set[str]
1803 self
._label
_names
= set() # type: Set[str]
1804 items
= self
._parse
_items
()
1805 self
._var
_names
= old_var_names
1806 self
._label
_names
= old_label_names
1810 self
._block
_end
_pat
, "Expecting an item or `!end` (end of macro block)"
1814 self
._macro
_defs
[name
] = _MacroDef(name
, param_names
, items
, begin_text_loc
)
1818 # Patterns for _try_parse_macro_exp()
1819 _macro_exp_prefix_pat
= re
.compile(r
"m\b")
1820 _macro_exp_colon_pat
= re
.compile(r
":")
1822 # Tries to parse a macro expansion, returning a macro expansion item
1824 def _try_parse_macro_exp(self
):
1825 begin_text_loc
= self
._text
_loc
1828 if self
._try
_parse
_pat
(self
._macro
_exp
_prefix
_pat
) is None:
1833 self
._skip
_ws
_and
_comments
()
1834 self
._expect
_pat
(self
._macro
_exp
_colon
_pat
, "Expecting `:`")
1836 # Expect a macro name
1837 self
._skip
_ws
_and
_comments
()
1838 name_text_loc
= self
._text
_loc
1839 m
= self
._expect
_pat
(_py_name_pat
, "Expecting a valid macro name")
1843 macro_def
= self
._macro
_defs
.get(name
)
1845 if macro_def
is None:
1846 _raise_error("Unknown macro name `{}`".format(name
), name_text_loc
)
1849 self
._skip
_ws
_and
_comments
()
1850 self
._expect
_pat
(self
._left
_paren
_pat
, "Expecting `(`")
1852 # Try to parse comma-separated parameter values
1853 params_text_loc
= self
._text
_loc
1854 params
= [] # type: List[_MacroExpParam]
1855 expect_comma
= False
1858 self
._skip
_ws
_and
_comments
()
1861 if self
._try
_parse
_pat
(self
._right
_paren
_pat
) is not None:
1867 self
._expect
_pat
(self
._macro
_params
_comma
_pat
, "Expecting `,`")
1869 self
._skip
_ws
_and
_comments
()
1870 param_text_loc
= self
._text
_loc
1874 accept_const_int
=True,
1876 accept_const_float
=True,
1877 accept_lit_str
=True,
1879 text_loc
=param_text_loc
1884 # Validate parameter values
1885 if len(params
) != len(macro_def
.param_names
):
1886 sing_plur
= "" if len(params
) == 1 else "s"
1888 "Macro expansion passes {} parameter{} while the definition expects {}".format(
1889 len(params
), sing_plur
, len(macro_def
.param_names
)
1895 return _MacroExp(name
, params
, begin_text_loc
)
1897 # Tries to parse a base item (anything except a post-item
1898 # repetition), returning it on success.
1899 def _try_parse_base_item(self
):
1900 for func
in self
._base
_item
_parse
_funcs
:
1903 if item
is not None:
1906 # Pattern for _try_parse_rep_post()
1907 _rep_post_prefix_pat
= re
.compile(r
"\*")
1909 # Tries to parse a post-item repetition, returning the expression
1910 # string and AST expression node on success.
1911 def _try_parse_rep_post(self
):
1913 if self
._try
_parse
_pat
(self
._rep
_post
_prefix
_pat
) is None:
1917 # Return expression string and AST expression
1918 self
._skip
_ws
_and
_comments
()
1919 return self
._expect
_rep
_mul
_expr
()
1921 # Tries to parse an item, possibly followed by a repetition,
1922 # returning `True` on success.
1924 # Appends any parsed item to `items`.
1925 def _try_append_item(self
, items
: List
[_Item
]):
1926 self
._skip
_ws
_and
_comments
_and
_syms
()
1929 item
= self
._try
_parse
_base
_item
()
1934 # Parse repetition if the base item is repeatable
1935 if isinstance(item
, _RepableItem
):
1936 self
._skip
_ws
_and
_comments
()
1937 rep_text_loc
= self
._text
_loc
1938 rep_ret
= self
._try
_parse
_rep
_post
()
1940 if rep_ret
is not None:
1941 item
= _Rep([item
], *rep_ret
, text_loc
=rep_text_loc
)
1946 # Parses and returns items, skipping whitespaces, insignificant
1947 # symbols, and comments when allowed, and stopping at the first
1948 # unknown character.
1950 # Accepts and registers macro definitions if `accept_macro_defs`
1952 def _parse_items(self
, accept_macro_defs
: bool = False) -> List
[_Item
]:
1953 items
= [] # type: List[_Item]
1955 while self
._isnt
_done
():
1956 # Try to append item
1957 if not self
._try
_append
_item
(items
):
1958 if accept_macro_defs
and self
._try
_parse
_macro
_def
():
1961 # Unknown at this point
1966 # Parses the whole Normand input, setting `self._res` to the main
1967 # group item on success.
1969 if len(self
._normand
.strip()) == 0:
1970 # Special case to make sure there's something to consume
1971 self
._res
= _Group([], self
._text
_loc
)
1974 # Parse first level items
1975 items
= self
._parse
_items
(True)
1977 # Make sure there's nothing left
1978 self
._skip
_ws
_and
_comments
_and
_syms
()
1980 if self
._isnt
_done
():
1982 "Unexpected character `{}`".format(self
._normand
[self
._at
])
1985 # Set main group item
1986 self
._res
= _Group(items
, self
._text
_loc
)
1989 # The return type of parse().
1995 variables
: VariablesT
,
1998 bo
: Optional
[ByteOrder
],
2000 self
= cls
.__new
__(cls
)
2001 self
._init
(data
, variables
, labels
, offset
, bo
)
2004 def __init__(self
, *args
, **kwargs
): # type: ignore
2005 raise NotImplementedError
2010 variables
: VariablesT
,
2013 bo
: Optional
[ByteOrder
],
2016 self
._vars
= variables
2017 self
._labels
= labels
2018 self
._offset
= offset
2026 # Dictionary of updated variable names to their last computed value.
2028 def variables(self
):
2031 # Dictionary of updated main group label names to their computed
2042 # Updated byte order.
2044 def byte_order(self
):
2048 # Raises a parse error for the item `item`, creating it using the
2050 def _raise_error_for_item(msg
: str, item
: _Item
) -> NoReturn
:
2051 _raise_error(msg
, item
.text_loc
)
2054 # The `ICITTE` reserved name.
2055 _icitte_name
= "ICITTE"
2058 # Base node visitor.
2060 # Calls the _visit_name() method for each name node which isn't the name
2062 class _NodeVisitor(ast
.NodeVisitor
):
2064 self
._parent
_is
_call
= False
2066 def generic_visit(self
, node
: ast
.AST
):
2067 if type(node
) is ast
.Call
:
2068 self
._parent
_is
_call
= True
2069 elif type(node
) is ast
.Name
and not self
._parent
_is
_call
:
2070 self
._visit
_name
(node
.id)
2072 super().generic_visit(node
)
2073 self
._parent
_is
_call
= False
2076 def _visit_name(self
, name
: str):
2080 # Expression validator: validates that all the names within the
2081 # expression are allowed.
2082 class _ExprValidator(_NodeVisitor
):
2083 def __init__(self
, expr_str
: str, text_loc
: TextLocation
, allowed_names
: Set
[str]):
2085 self
._expr
_str
= expr_str
2086 self
._text
_loc
= text_loc
2087 self
._allowed
_names
= allowed_names
2089 def _visit_name(self
, name
: str):
2090 # Make sure the name refers to a known and reachable
2091 # variable/label name.
2092 if name
!= _icitte_name
and name
not in self
._allowed
_names
:
2093 msg
= "Illegal (unknown or unreachable) variable/label name `{}` in expression `{}`".format(
2094 name
, self
._expr
_str
2097 allowed_names
= self
._allowed
_names
.copy()
2098 allowed_names
.add(_icitte_name
)
2100 if len(allowed_names
) > 0:
2101 allowed_names_str
= ", ".join(
2102 sorted(["`{}`".format(name
) for name
in allowed_names
])
2104 msg
+= "; the legal names are {{{}}}".format(allowed_names_str
)
2116 variables
: VariablesT
,
2119 bo
: Optional
[ByteOrder
],
2121 self
.variables
= variables
.copy()
2122 self
.labels
= labels
.copy()
2123 self
.offset
= offset
2127 return "_GenState({}, {}, {}, {})".format(
2128 repr(self
.variables
), repr(self
.labels
), repr(self
.offset
), repr(self
.bo
)
2132 # Fixed-length number item instance.
2133 class _FlNumItemInst
:
2137 offset_in_data
: int,
2139 parse_error_msgs
: List
[ParseErrorMessage
],
2142 self
._offset
_in
_data
= offset_in_data
2144 self
._parse
_error
_msgs
= parse_error_msgs
2151 def offset_in_data(self
):
2152 return self
._offset
_in
_data
2159 def parse_error_msgs(self
):
2160 return self
._parse
_error
_msgs
2163 # Generator of data and final state from a group item.
2165 # Generation happens in memory at construction time. After building, use
2166 # the `data`, `variables`, `labels`, `offset`, and `bo` properties to
2167 # get the resulting context.
2169 # The steps of generation are:
2171 # 1. Handle each item in prefix order.
2173 # The handlers append bytes to `self._data` and update some current
2174 # state object (`_GenState` instance).
2176 # When handling a fixed-length number item, try to evaluate its
2177 # expression using the current state. If this fails, then it might be
2178 # because the expression refers to a "future" label: save the current
2179 # offset in `self._data` (generated data) and a snapshot of the
2180 # current state within `self._fl_num_item_insts` (`_FlNumItemInst`
2181 # object). _gen_fl_num_item_insts() will deal with this later. A
2182 # `_FlNumItemInst` instance also contains a snapshot of the current
2183 # parsing error messages (`self._parse_error_msgs`) which need to be
2184 # taken into account when handling the instance later.
2186 # When handling the items of a group, keep a map of immediate label
2187 # names to their offset. Then, after having processed all the items,
2188 # update the relevant saved state snapshots in
2189 # `self._fl_num_item_insts` with those immediate label values.
2190 # _gen_fl_num_item_insts() will deal with this later.
2192 # 2. Handle all the fixed-length number item instances of which the
2193 # expression evaluation failed before.
2195 # At this point, `self._fl_num_item_insts` contains everything that's
2196 # needed to evaluate the expressions, including the values of
2197 # "future" labels from the point of view of some fixed-length number
2200 # If an evaluation fails at this point, then it's a user error. Add
2201 # to the parsing error all the saved parsing error messages of the
2202 # instance. Those additional messages add precious context to the
2208 macro_defs
: _MacroDefsT
,
2209 variables
: VariablesT
,
2212 bo
: Optional
[ByteOrder
],
2214 self
._macro
_defs
= macro_defs
2215 self
._fl
_num
_item
_insts
= [] # type: List[_FlNumItemInst]
2216 self
._parse
_error
_msgs
= [] # type: List[ParseErrorMessage]
2217 self
._in
_trans
= False
2218 self
._gen
(group
, _GenState(variables
, labels
, offset
, bo
))
2225 # Updated variables.
2227 def variables(self
):
2228 return self
._final
_state
.variables
2230 # Updated main group labels.
2233 return self
._final
_state
.labels
2238 return self
._final
_state
.offset
2240 # Updated byte order.
2243 return self
._final
_state
.bo
2245 # Evaluates the expression `expr` of which the original string is
2246 # `expr_str` at the location `text_loc` considering the current
2247 # generation state `state`.
2249 # If `accept_float` is `True`, then the type of the result may be
2252 # If `accept_str` is `True`, then the type of the result may be
2257 expr
: ast
.Expression
,
2258 text_loc
: TextLocation
,
2260 accept_float
: bool = False,
2261 accept_str
: bool = False,
2263 syms
= {} # type: VariablesT
2264 syms
.update(state
.labels
)
2266 # Set the `ICITTE` name to the current offset
2267 syms
[_icitte_name
] = state
.offset
2269 # Add the current variables
2270 syms
.update(state
.variables
)
2272 # Validate the node and its children
2273 _ExprValidator(expr_str
, text_loc
, set(syms
.keys())).visit(expr
)
2275 # Compile and evaluate expression node
2277 val
= eval(compile(expr
, "", "eval"), None, syms
)
2278 except Exception as exc
:
2280 "Failed to evaluate expression `{}`: {}".format(expr_str
, exc
),
2284 # Convert `bool` result type to `int` to normalize
2285 if type(val
) is bool:
2288 # Validate result type
2289 expected_types
= {int}
# type: Set[type]
2292 expected_types
.add(float)
2295 expected_types
.add(str)
2297 if type(val
) not in expected_types
:
2298 expected_types_str
= sorted(
2299 ["`{}`".format(t
.__name
__) for t
in expected_types
]
2302 if len(expected_types_str
) == 1:
2303 msg_expected
= expected_types_str
[0]
2304 elif len(expected_types_str
) == 2:
2305 msg_expected
= " or ".join(expected_types_str
)
2307 expected_types_str
[-1] = "or {}".format(expected_types_str
[-1])
2308 msg_expected
= ", ".join(expected_types_str
)
2311 "Invalid expression `{}`: expecting result type {}, not `{}`".format(
2312 expr_str
, msg_expected
, type(val
).__name
__
2319 # Forwards to _eval_expr() with the expression and text location of
2322 def _eval_item_expr(
2323 item
: Union
[_Cond
, _FillUntil
, _FlNum
, _Leb128Int
, _Rep
, _Str
, _VarAssign
],
2325 accept_float
: bool = False,
2326 accept_str
: bool = False,
2328 return _Gen
._eval
_expr
(
2329 item
.expr_str
, item
.expr
, item
.text_loc
, state
, accept_float
, accept_str
2332 # Handles the byte item `item`.
2333 def _handle_byte_item(self
, item
: _Byte
, state
: _GenState
):
2334 self
._data
.append(item
.val
)
2335 state
.offset
+= item
.size
2337 # Handles the literal string item `item`.
2338 def _handle_lit_str_item(self
, item
: _LitStr
, state
: _GenState
):
2339 self
._data
+= item
.data
2340 state
.offset
+= item
.size
2342 # Handles the byte order setting item `item`.
2343 def _handle_set_bo_item(self
, item
: _SetBo
, state
: _GenState
):
2344 # Update current byte order
2347 # Handles the variable assignment item `item`.
2348 def _handle_var_assign_item(self
, item
: _VarAssign
, state
: _GenState
):
2350 state
.variables
[item
.name
] = self
._eval
_item
_expr
(
2351 item
, state
, accept_float
=True, accept_str
=True
2354 # Handles the fixed-length number item `item`.
2355 def _handle_fl_num_item(self
, item
: _FlNum
, state
: _GenState
):
2356 # Validate current byte order
2357 if state
.bo
is None and item
.len > 8:
2358 _raise_error_for_item(
2359 "Current byte order isn't defined at first fixed-length number (`{}`) to encode on more than 8 bits".format(
2365 # Try an immediate evaluation. If it fails, then keep everything
2366 # needed to (try to) generate the bytes of this item later.
2368 data
= self
._gen
_fl
_num
_item
_inst
_data
(item
, state
)
2371 _raise_error_for_item(
2372 "Invalid expression `{}`: failed to evaluate within a transformation block".format(
2378 self
._fl
_num
_item
_insts
.append(
2382 copy
.deepcopy(state
),
2383 copy
.deepcopy(self
._parse
_error
_msgs
),
2387 # Reserve space in `self._data` for this instance
2388 data
= bytes([0] * (item
.len // 8))
2394 state
.offset
+= len(data
)
2396 # Returns the size, in bytes, required to encode the value `val`
2397 # with LEB128 (signed version if `is_signed` is `True`).
2399 def _leb128_size_for_val(val
: int, is_signed
: bool):
2401 # Equivalent upper bound.
2403 # For example, if `val` is -128, then the full integer for
2404 # this number of bits would be [-128, 127].
2407 # Number of bits (add one for the sign if needed)
2408 bits
= val
.bit_length() + int(is_signed
)
2413 # Seven bits per byte
2414 return math
.ceil(bits
/ 7)
2416 # Handles the LEB128 integer item `item`.
2417 def _handle_leb128_int_item(self
, item
: _Leb128Int
, state
: _GenState
):
2419 val
= self
._eval
_item
_expr
(item
, state
)
2422 size
= self
._leb
128_size
_for
_val
(val
, type(item
) is _SLeb128Int
)
2425 for _
in range(size
):
2426 # Seven LSBs, MSB of the byte set (continue)
2427 self
._data
.append((val
& 0x7F) |
0x80)
2430 # Clear MSB of last byte (stop)
2431 self
._data
[-1] &= ~
0x80
2434 state
.offset
+= size
2436 # Handles the string item `item`.
2437 def _handle_str_item(self
, item
: _Str
, state
: _GenState
):
2439 val
= str(self
._eval
_item
_expr
(item
, state
, accept_float
=True, accept_str
=True))
2442 data
= _encode_str(val
, item
.codec
, item
.text_loc
)
2448 state
.offset
+= len(data
)
2450 # Handles the group item `item`, removing the immediate labels from
2451 # `state` at the end if `remove_immediate_labels` is `True`.
2452 def _handle_group_item(
2453 self
, item
: _Group
, state
: _GenState
, remove_immediate_labels
: bool = True
2455 first_fl_num_item_inst_index
= len(self
._fl
_num
_item
_insts
)
2456 immediate_labels
= {} # type: LabelsT
2459 for subitem
in item
.items
:
2460 if type(subitem
) is _Label
:
2461 # Add to local immediate labels
2462 immediate_labels
[subitem
.name
] = state
.offset
2464 self
._handle
_item
(subitem
, state
)
2466 # Remove immediate labels from current state if needed
2467 if remove_immediate_labels
:
2468 for name
in immediate_labels
:
2469 del state
.labels
[name
]
2471 # Add all immediate labels to all state snapshots since
2472 # `first_fl_num_item_inst_index`.
2473 for inst
in self
._fl
_num
_item
_insts
[first_fl_num_item_inst_index
:]:
2474 inst
.state
.labels
.update(immediate_labels
)
2476 # Handles the repetition item `item`.
2477 def _handle_rep_item(self
, item
: _Rep
, state
: _GenState
):
2478 # Compute the repetition count
2479 mul
= _Gen
._eval
_item
_expr
(item
, state
)
2483 _raise_error_for_item(
2484 "Invalid expression `{}`: unexpected negative result {:,}".format(
2490 # Generate group data `mul` times
2491 for _
in range(mul
):
2492 self
._handle
_group
_item
(item
, state
)
2494 # Handles the conditional item `item`.
2495 def _handle_cond_item(self
, item
: _Cond
, state
: _GenState
):
2496 # Compute the conditional value
2497 val
= _Gen
._eval
_item
_expr
(item
, state
)
2499 # Generate selected group data
2501 self
._handle
_group
_item
(item
.true_item
, state
)
2503 self
._handle
_group
_item
(item
.false_item
, state
)
2505 # Handles the transformation item `item`.
2506 def _handle_trans_item(self
, item
: _Trans
, state
: _GenState
):
2507 init_in_trans
= self
._in
_trans
2508 self
._in
_trans
= True
2509 init_data_len
= len(self
._data
)
2510 init_offset
= state
.offset
2512 # Generate group data
2513 self
._handle
_group
_item
(item
, state
)
2515 # Remove and keep group data
2516 to_trans
= self
._data
[init_data_len
:]
2517 del self
._data
[init_data_len
:]
2519 # Encode group data and append to current data
2521 transformed
= item
.trans(to_trans
)
2522 except Exception as exc
:
2523 _raise_error_for_item(
2524 "Cannot apply the {} transformation to this data: {}".format(
2530 self
._data
+= transformed
2532 # Update offset and restore
2533 state
.offset
= init_offset
+ len(transformed
)
2534 self
._in
_trans
= init_in_trans
2536 # Evaluates the parameters of the macro expansion item `item`
2537 # considering the initial state `init_state` and returns a new state
2538 # to handle the items of the macro.
2539 def _eval_macro_exp_params(self
, item
: _MacroExp
, init_state
: _GenState
):
2541 exp_state
= _GenState({}, {}, init_state
.offset
, init_state
.bo
)
2543 # Evaluate the parameter expressions
2544 macro_def
= self
._macro
_defs
[item
.name
]
2546 for param_name
, param
in zip(macro_def
.param_names
, item
.params
):
2547 exp_state
.variables
[param_name
] = _Gen
._eval
_expr
(
2558 # Handles the macro expansion item `item`.
2559 def _handle_macro_exp_item(self
, item
: _MacroExp
, state
: _GenState
):
2560 parse_error_msg_text
= "While expanding the macro `{}`:".format(item
.name
)
2564 exp_state
= self
._eval
_macro
_exp
_params
(item
, state
)
2566 # Process the contained group
2567 init_data_size
= len(self
._data
)
2569 ParseErrorMessage
._create
( # pyright: ignore[reportPrivateUsage]
2570 parse_error_msg_text
, item
.text_loc
2573 self
._parse
_error
_msgs
.append(parse_error_msg
)
2574 self
._handle
_group
_item
(self
._macro
_defs
[item
.name
], exp_state
)
2575 self
._parse
_error
_msgs
.pop()
2576 except ParseError
as exc
:
2577 _augment_error(exc
, parse_error_msg_text
, item
.text_loc
)
2579 # Update state offset and return
2580 state
.offset
+= len(self
._data
) - init_data_size
2582 # Handles the offset setting item `item`.
2583 def _handle_set_offset_item(self
, item
: _SetOffset
, state
: _GenState
):
2584 state
.offset
= item
.val
2586 # Handles the offset alignment item `item` (adds padding).
2587 def _handle_align_offset_item(self
, item
: _AlignOffset
, state
: _GenState
):
2588 init_offset
= state
.offset
2589 align_bytes
= item
.val
// 8
2590 state
.offset
= (state
.offset
+ align_bytes
- 1) // align_bytes
* align_bytes
2591 self
._data
+= bytes([item
.pad_val
] * (state
.offset
- init_offset
))
2593 # Handles the filling item `item` (adds padding).
2594 def _handle_fill_until_item(self
, item
: _FillUntil
, state
: _GenState
):
2595 # Compute the new offset
2596 new_offset
= _Gen
._eval
_item
_expr
(item
, state
)
2598 # Validate the new offset
2599 if new_offset
< state
.offset
:
2600 _raise_error_for_item(
2601 "Invalid expression `{}`: new offset {:,} is less than current offset {:,}".format(
2602 item
.expr_str
, new_offset
, state
.offset
2608 self
._data
+= bytes([item
.pad_val
] * (new_offset
- state
.offset
))
2611 state
.offset
= new_offset
2613 # Handles the label item `item`.
2614 def _handle_label_item(self
, item
: _Label
, state
: _GenState
):
2615 state
.labels
[item
.name
] = state
.offset
2617 # Handles the item `item`, returning the updated next repetition
2619 def _handle_item(self
, item
: _Item
, state
: _GenState
):
2620 return self
._item
_handlers
[type(item
)](item
, state
)
2622 # Generates the data for a fixed-length integer item instance having
2623 # the value `val` and returns it.
2624 def _gen_fl_int_item_inst_data(self
, val
: int, item
: _FlNum
, state
: _GenState
):
2626 if val
< -(2 ** (item
.len - 1)) or val
> 2**item
.len - 1:
2627 _raise_error_for_item(
2628 "Value {:,} is outside the {}-bit range when evaluating expression `{}`".format(
2629 val
, item
.len, item
.expr_str
2634 # Encode result on 64 bits (to extend the sign bit whatever the
2635 # value of `item.len`).
2638 ">" if state
.bo
in (None, ByteOrder
.BE
) else "<",
2639 "Q" if val
>= 0 else "q",
2644 # Keep only the requested length
2645 len_bytes
= item
.len // 8
2647 if state
.bo
in (None, ByteOrder
.BE
):
2648 # Big endian: keep last bytes
2649 data
= data
[-len_bytes
:]
2651 # Little endian: keep first bytes
2652 assert state
.bo
== ByteOrder
.LE
2653 data
= data
[:len_bytes
]
2658 # Generates the data for a fixed-length floating point number item
2659 # instance having the value `val` and returns it.
2660 def _gen_fl_float_item_inst_data(self
, val
: float, item
: _FlNum
, state
: _GenState
):
2662 if item
.len not in (32, 64):
2663 _raise_error_for_item(
2664 "Invalid {}-bit length for a fixed-length floating point number (value {:,})".format(
2670 # Encode and return result
2673 ">" if state
.bo
in (None, ByteOrder
.BE
) else "<",
2674 "f" if item
.len == 32 else "d",
2679 # Generates the data for a fixed-length number item instance and
2681 def _gen_fl_num_item_inst_data(self
, item
: _FlNum
, state
: _GenState
):
2683 val
= self
._eval
_item
_expr
(item
, state
, True)
2685 # Handle depending on type
2686 if type(val
) is int:
2687 return self
._gen
_fl
_int
_item
_inst
_data
(val
, item
, state
)
2689 assert type(val
) is float
2690 return self
._gen
_fl
_float
_item
_inst
_data
(val
, item
, state
)
2692 # Generates the data for all the fixed-length number item instances
2693 # and writes it at the correct offset within `self._data`.
2694 def _gen_fl_num_item_insts(self
):
2695 for inst
in self
._fl
_num
_item
_insts
:
2698 data
= self
._gen
_fl
_num
_item
_inst
_data
(inst
.item
, inst
.state
)
2699 except ParseError
as exc
:
2700 # Add all the saved parse error messages for this
2702 for msg
in reversed(inst
.parse_error_msgs
):
2703 _add_error_msg(exc
, msg
.text
, msg
.text_location
)
2707 # Insert bytes into `self._data`
2708 self
._data
[inst
.offset_in_data
: inst
.offset_in_data
+ len(data
)] = data
2710 # Generates the data (`self._data`) and final state
2711 # (`self._final_state`) from `group` and the initial state `state`.
2712 def _gen(self
, group
: _Group
, state
: _GenState
):
2714 self
._data
= bytearray()
2717 self
._item
_handlers
= {
2718 _AlignOffset
: self
._handle
_align
_offset
_item
,
2719 _Byte
: self
._handle
_byte
_item
,
2720 _Cond
: self
._handle
_cond
_item
,
2721 _FillUntil
: self
._handle
_fill
_until
_item
,
2722 _FlNum
: self
._handle
_fl
_num
_item
,
2723 _Group
: self
._handle
_group
_item
,
2724 _Label
: self
._handle
_label
_item
,
2725 _LitStr
: self
._handle
_lit
_str
_item
,
2726 _MacroExp
: self
._handle
_macro
_exp
_item
,
2727 _Rep
: self
._handle
_rep
_item
,
2728 _SetBo
: self
._handle
_set
_bo
_item
,
2729 _SetOffset
: self
._handle
_set
_offset
_item
,
2730 _SLeb128Int
: self
._handle
_leb
128_int
_item
,
2731 _Str
: self
._handle
_str
_item
,
2732 _Trans
: self
._handle
_trans
_item
,
2733 _ULeb128Int
: self
._handle
_leb
128_int
_item
,
2734 _VarAssign
: self
._handle
_var
_assign
_item
,
2735 } # type: Dict[type, Callable[[Any, _GenState], None]]
2737 # Handle the group item, _not_ removing the immediate labels
2738 # because the `labels` property offers them.
2739 self
._handle
_group
_item
(group
, state
, False)
2741 # This is actually the final state
2742 self
._final
_state
= state
2744 # Generate all the fixed-length number bytes now that we know
2746 self
._gen
_fl
_num
_item
_insts
()
2749 # Returns a `ParseResult` instance containing the bytes encoded by the
2750 # input string `normand`.
2752 # `init_variables` is a dictionary of initial variable names (valid
2753 # Python names) to integral values. A variable name must not be the
2754 # reserved name `ICITTE`.
2756 # `init_labels` is a dictionary of initial label names (valid Python
2757 # names) to integral values. A label name must not be the reserved name
2760 # `init_offset` is the initial offset.
2762 # `init_byte_order` is the initial byte order.
2764 # Raises `ParseError` on any parsing error.
2767 init_variables
: Optional
[VariablesT
] = None,
2768 init_labels
: Optional
[LabelsT
] = None,
2769 init_offset
: int = 0,
2770 init_byte_order
: Optional
[ByteOrder
] = None,
2772 if init_variables
is None:
2775 if init_labels
is None:
2778 parser
= _Parser(normand
, init_variables
, init_labels
)
2787 return ParseResult
._create
( # pyright: ignore[reportPrivateUsage]
2788 gen
.data
, gen
.variables
, gen
.labels
, gen
.offset
, gen
.bo
2792 # Raises a command-line error with the message `msg`.
2793 def _raise_cli_error(msg
: str) -> NoReturn
:
2794 raise RuntimeError("Command-line error: {}".format(msg
))
2797 # Returns the `int` or `float` value out of a CLI assignment value.
2798 def _val_from_assign_val_str(s
: str, is_label
: bool):
2801 # Floating point number?
2803 m
= _const_float_pat
.fullmatch(s
)
2806 return float(m
.group(0))
2809 m
= _const_int_pat
.fullmatch(s
)
2812 return int(_norm_const_int(m
.group(0)), 0)
2814 exp
= "an integer" if is_label
else "a number"
2815 _raise_cli_error("Invalid assignment value `{}`: expecting {}".format(s
, exp
))
2818 # Returns a dictionary of string to numbers from the list of strings
2819 # `args` containing `NAME=VAL` entries.
2820 def _dict_from_arg(args
: Optional
[List
[str]], is_label
: bool, is_str_only
: bool):
2821 d
= {} # type: VariablesT
2827 m
= re
.match(r
"({})\s*=\s*(.*)$".format(_py_name_pat
.pattern
), arg
)
2830 _raise_cli_error("Invalid assignment `{}`".format(arg
))
2835 val
= _val_from_assign_val_str(m
.group(2), is_label
)
2842 # Parses the command-line arguments and returns, in this order:
2844 # 1. The input file path, or `None` if none.
2845 # 2. The Normand input text.
2846 # 3. The initial offset.
2847 # 4. The initial byte order.
2848 # 5. The initial variables.
2849 # 6. The initial labels.
2850 def _parse_cli_args():
2854 ap
= argparse
.ArgumentParser()
2861 help="initial offset (positive)",
2867 choices
=["be", "le"],
2869 help="initial byte order (`be` or `le`)",
2876 help="add an initial numeric variable (may be repeated)",
2883 help="add an initial string variable (may be repeated)",
2890 help="add an initial label (may be repeated)",
2893 "--version", action
="version", version
="Normand {}".format(__version__
)
2900 help="input path (none means standard input)",
2904 args
= ap
.parse_args()
2907 if args
.path
is None:
2908 normand
= sys
.stdin
.read()
2910 with
open(args
.path
) as f
:
2913 # Variables and labels
2914 variables
= _dict_from_arg(args
.var
, False, False)
2915 variables
.update(_dict_from_arg(args
.var_str
, False, True))
2916 labels
= _dict_from_arg(args
.label
, True, False)
2920 _raise_cli_error("Invalid negative offset {}")
2922 # Validate and set byte order
2923 bo
= None # type: Optional[ByteOrder]
2925 if args
.byte_order
is not None:
2926 if args
.byte_order
== "be":
2929 assert args
.byte_order
== "le"
2932 # Return input and initial state
2933 return args
.path
, normand
, args
.offset
, bo
, variables
, typing
.cast(LabelsT
, labels
)
2936 # CLI entry point without exception handling.
2937 def _run_cli_with_args(
2940 bo
: Optional
[ByteOrder
],
2941 variables
: VariablesT
,
2944 sys
.stdout
.buffer.write(parse(normand
, variables
, labels
, offset
, bo
).data
)
2947 # Prints the exception message `msg` and exits with status 1.
2948 def _fail(msg
: str) -> NoReturn
:
2949 if not msg
.endswith("."):
2952 print(msg
.strip(), file=sys
.stderr
)
2959 args
= _parse_cli_args()
2960 except Exception as exc
:
2964 _run_cli_with_args(*args
[1:])
2965 except ParseError
as exc
:
2968 prefix
= "" if args
[0] is None else "{}:".format(os
.path
.abspath(args
[0]))
2971 for msg
in reversed(exc
.messages
):
2972 fail_msg
+= "{}{}:{} - {}".format(
2974 msg
.text_location
.line_no
,
2975 msg
.text_location
.col_no
,
2979 if fail_msg
[-1] not in ".:;":
2984 _fail(fail_msg
.strip())
2985 except Exception as exc
:
2989 if __name__
== "__main__":