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.20.0"
56 from typing
import Any
, Set
, Dict
, List
, Union
, Pattern
, Callable
, NoReturn
, Optional
59 # Text location (line and column numbers).
62 def _create(cls
, line_no
: int, col_no
: int):
63 self
= cls
.__new
__(cls
)
64 self
._init
(line_no
, col_no
)
67 def __init__(*args
, **kwargs
): # type: ignore
68 raise NotImplementedError
70 def _init(self
, line_no
: int, col_no
: int):
71 self
._line
_no
= line_no
85 return "TextLocation({}, {})".format(self
._line
_no
, self
._col
_no
)
90 def __init__(self
, text_loc
: TextLocation
):
91 self
._text
_loc
= text_loc
93 # Source text location.
100 class _ScalarItem(_Item
):
101 # Returns the size, in bytes, of this item.
104 def size(self
) -> int:
114 class _Byte(_ScalarItem
, _RepableItem
):
115 def __init__(self
, val
: int, text_loc
: TextLocation
):
116 super().__init
__(text_loc
)
129 return "_Byte({}, {})".format(hex(self
._val
), repr(self
._text
_loc
))
133 class _LitStr(_ScalarItem
, _RepableItem
):
134 def __init__(self
, data
: bytes
, text_loc
: TextLocation
):
135 super().__init
__(text_loc
)
145 return len(self
._data
)
148 return "_LitStr({}, {})".format(repr(self
._data
), repr(self
._text
_loc
))
153 class ByteOrder(enum
.Enum
):
161 # Byte order setting.
163 def __init__(self
, bo
: ByteOrder
, text_loc
: TextLocation
):
164 super().__init
__(text_loc
)
172 return "_SetBo({}, {})".format(repr(self
._bo
), repr(self
._text
_loc
))
177 def __init__(self
, name
: str, text_loc
: TextLocation
):
178 super().__init
__(text_loc
)
187 return "_Label({}, {})".format(repr(self
._name
), repr(self
._text
_loc
))
191 class _SetOffset(_Item
):
192 def __init__(self
, val
: int, text_loc
: TextLocation
):
193 super().__init
__(text_loc
)
196 # Offset value (bytes).
202 return "_SetOffset({}, {})".format(repr(self
._val
), repr(self
._text
_loc
))
206 class _AlignOffset(_Item
):
207 def __init__(self
, val
: int, pad_val
: int, text_loc
: TextLocation
):
208 super().__init
__(text_loc
)
210 self
._pad
_val
= pad_val
212 # Alignment value (bits).
217 # Padding byte value.
223 return "_AlignOffset({}, {}, {})".format(
224 repr(self
._val
), repr(self
._pad
_val
), repr(self
._text
_loc
)
228 # Mixin of containing an AST expression and its string.
230 def __init__(self
, expr_str
: str, expr
: ast
.Expression
):
231 self
._expr
_str
= expr_str
237 return self
._expr
_str
239 # Expression node to evaluate.
245 # Fill until some offset.
246 class _FillUntil(_Item
, _ExprMixin
):
248 self
, expr_str
: str, expr
: ast
.Expression
, pad_val
: int, text_loc
: TextLocation
250 super().__init
__(text_loc
)
251 _ExprMixin
.__init
__(self
, expr_str
, expr
)
252 self
._pad
_val
= pad_val
254 # Padding byte value.
260 return "_FillUntil({}, {}, {}, {})".format(
261 repr(self
._expr
_str
),
264 repr(self
._text
_loc
),
268 # Variable assignment.
269 class _VarAssign(_Item
, _ExprMixin
):
271 self
, name
: str, expr_str
: str, expr
: ast
.Expression
, text_loc
: TextLocation
273 super().__init
__(text_loc
)
274 _ExprMixin
.__init
__(self
, expr_str
, expr
)
283 return "_VarAssign({}, {}, {}, {})".format(
285 repr(self
._expr
_str
),
287 repr(self
._text
_loc
),
291 # Fixed-length number, possibly needing more than one byte.
292 class _FlNum(_ScalarItem
, _RepableItem
, _ExprMixin
):
294 self
, expr_str
: str, expr
: ast
.Expression
, len: int, text_loc
: TextLocation
296 super().__init
__(text_loc
)
297 _ExprMixin
.__init
__(self
, expr_str
, expr
)
307 return self
._len
// 8
310 return "_FlNum({}, {}, {}, {})".format(
311 repr(self
._expr
_str
),
314 repr(self
._text
_loc
),
319 class _Leb128Int(_Item
, _RepableItem
, _ExprMixin
):
320 def __init__(self
, expr_str
: str, expr
: ast
.Expression
, text_loc
: TextLocation
):
321 super().__init
__(text_loc
)
322 _ExprMixin
.__init
__(self
, expr_str
, expr
)
325 return "{}({}, {}, {})".format(
326 self
.__class
__.__name
__,
327 repr(self
._expr
_str
),
329 repr(self
._text
_loc
),
333 # Unsigned LEB128 integer.
334 class _ULeb128Int(_Leb128Int
, _RepableItem
, _ExprMixin
):
338 # Signed LEB128 integer.
339 class _SLeb128Int(_Leb128Int
, _RepableItem
, _ExprMixin
):
344 class _Str(_Item
, _RepableItem
, _ExprMixin
):
346 self
, expr_str
: str, expr
: ast
.Expression
, codec
: str, text_loc
: TextLocation
348 super().__init
__(text_loc
)
349 _ExprMixin
.__init
__(self
, expr_str
, expr
)
358 return "_Str({}, {}, {}, {})".format(
359 self
.__class
__.__name
__,
360 repr(self
._expr
_str
),
363 repr(self
._text
_loc
),
368 class _Group(_Item
, _RepableItem
):
369 def __init__(self
, items
: List
[_Item
], text_loc
: TextLocation
):
370 super().__init
__(text_loc
)
379 return "_Group({}, {})".format(repr(self
._items
), repr(self
._text
_loc
))
383 class _Rep(_Item
, _ExprMixin
):
385 self
, item
: _Item
, expr_str
: str, expr
: ast
.Expression
, text_loc
: TextLocation
387 super().__init
__(text_loc
)
388 _ExprMixin
.__init
__(self
, expr_str
, expr
)
397 return "_Rep({}, {}, {}, {})".format(
399 repr(self
._expr
_str
),
401 repr(self
._text
_loc
),
406 class _Cond(_Item
, _ExprMixin
):
412 expr
: ast
.Expression
,
413 text_loc
: TextLocation
,
415 super().__init
__(text_loc
)
416 _ExprMixin
.__init
__(self
, expr_str
, expr
)
417 self
._true
_item
= true_item
418 self
._false
_item
= false_item
420 # Item when condition is true.
423 return self
._true
_item
425 # Item when condition is false.
427 def false_item(self
):
428 return self
._false
_item
431 return "_Cond({}, {}, {}, {}, {})".format(
432 repr(self
._true
_item
),
433 repr(self
._false
_item
),
434 repr(self
._expr
_str
),
436 repr(self
._text
_loc
),
440 # Macro definition item.
441 class _MacroDef(_Item
):
443 self
, name
: str, param_names
: List
[str], group
: _Group
, text_loc
: TextLocation
445 super().__init
__(text_loc
)
447 self
._param
_names
= param_names
457 def param_names(self
):
458 return self
._param
_names
466 return "_MacroDef({}, {}, {}, {})".format(
468 repr(self
._param
_names
),
470 repr(self
._text
_loc
),
474 # Macro expansion parameter.
475 class _MacroExpParam
:
476 def __init__(self
, expr_str
: str, expr
: ast
.Expression
, text_loc
: TextLocation
):
477 self
._expr
_str
= expr_str
479 self
._text
_loc
= text_loc
484 return self
._expr
_str
491 # Source text location.
494 return self
._text
_loc
497 return "_MacroExpParam({}, {}, {})".format(
498 repr(self
._expr
_str
), repr(self
._expr
), repr(self
._text
_loc
)
502 # Macro expansion item.
503 class _MacroExp(_Item
, _RepableItem
):
507 params
: List
[_MacroExpParam
],
508 text_loc
: TextLocation
,
510 super().__init
__(text_loc
)
512 self
._params
= params
525 return "_MacroExp({}, {}, {})".format(
528 repr(self
._text
_loc
),
532 # A parsing error message: a string and a text location.
533 class ParseErrorMessage
:
535 def _create(cls
, text
: str, text_loc
: TextLocation
):
536 self
= cls
.__new
__(cls
)
537 self
._init
(text
, text_loc
)
540 def __init__(self
, *args
, **kwargs
): # type: ignore
541 raise NotImplementedError
543 def _init(self
, text
: str, text_loc
: TextLocation
):
545 self
._text
_loc
= text_loc
552 # Source text location.
554 def text_location(self
):
555 return self
._text
_loc
558 # A parsing error containing one or more messages (`ParseErrorMessage`).
559 class ParseError(RuntimeError):
561 def _create(cls
, msg
: str, text_loc
: TextLocation
):
562 self
= cls
.__new
__(cls
)
563 self
._init
(msg
, text_loc
)
566 def __init__(self
, *args
, **kwargs
): # type: ignore
567 raise NotImplementedError
569 def _init(self
, msg
: str, text_loc
: TextLocation
):
570 super().__init
__(msg
)
571 self
._msgs
= [] # type: List[ParseErrorMessage]
572 self
._add
_msg
(msg
, text_loc
)
574 def _add_msg(self
, msg
: str, text_loc
: TextLocation
):
576 ParseErrorMessage
._create
( # pyright: ignore[reportPrivateUsage]
581 # Parsing error messages.
583 # The first message is the most specific one.
589 # Raises a parsing error, forwarding the parameters to the constructor.
590 def _raise_error(msg
: str, text_loc
: TextLocation
) -> NoReturn
:
591 raise ParseError
._create
(msg
, text_loc
) # pyright: ignore[reportPrivateUsage]
594 # Adds a message to the parsing error `exc`.
595 def _add_error_msg(exc
: ParseError
, msg
: str, text_loc
: TextLocation
):
596 exc
._add
_msg
(msg
, text_loc
) # pyright: ignore[reportPrivateUsage]
599 # Appends a message to the parsing error `exc` and reraises it.
600 def _augment_error(exc
: ParseError
, msg
: str, text_loc
: TextLocation
) -> NoReturn
:
601 _add_error_msg(exc
, msg
, text_loc
)
605 # Returns a normalized version (so as to be parseable by int()) of
606 # the constant integer string `s`, possibly negative, dealing with
608 def _norm_const_int(s
: str):
612 if s
.startswith("-"):
617 if pos
.startswith("0" + r
):
633 for suf
in asm_suf_base
:
635 s
= "{}0{}{}".format(neg
, asm_suf_base
[suf
], pos
.rstrip(suf
))
640 # Encodes the string `s` using the codec `codec`, raising `ParseError`
641 # with `text_loc` on encoding error.
642 def _encode_str(s
: str, codec
: str, text_loc
: TextLocation
):
644 return s
.encode(codec
)
645 except UnicodeEncodeError:
647 "Cannot encode `{}` with the `{}` encoding".format(s
, codec
), text_loc
651 # Variables dictionary type (for type hints).
652 VariablesT
= Dict
[str, Union
[int, float, str]]
655 # Labels dictionary type (for type hints).
656 LabelsT
= Dict
[str, int]
660 _py_name_pat
= re
.compile(r
"[a-zA-Z_][a-zA-Z0-9_]*")
661 _pos_const_int_pat
= re
.compile(
662 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"
664 _const_int_pat
= re
.compile(r
"(?P<neg>-)?(?:{})".format(_pos_const_int_pat
.pattern
))
665 _const_float_pat
= re
.compile(
666 r
"[-+]?(?:(?:\d*\.\d+)|(?:\d+\.))(?:[Ee][+-]?\d+)?(?=\W|)"
670 # Macro definition dictionary.
671 _MacroDefsT
= Dict
[str, _MacroDef
]
676 # The constructor accepts a Normand input. After building, use the `res`
677 # property to get the resulting main group.
679 # Builds a parser to parse the Normand input `normand`, parsing
681 def __init__(self
, normand
: str, variables
: VariablesT
, labels
: LabelsT
):
682 self
._normand
= normand
686 self
._label
_names
= set(labels
.keys())
687 self
._var
_names
= set(variables
.keys())
688 self
._macro
_defs
= {} # type: _MacroDefsT
691 # Result (main group).
698 def macro_defs(self
):
699 return self
._macro
_defs
701 # Current text location.
704 return TextLocation
._create
( # pyright: ignore[reportPrivateUsage]
705 self
._line
_no
, self
._col
_no
708 # Returns `True` if this parser is done parsing.
710 return self
._at
== len(self
._normand
)
712 # Returns `True` if this parser isn't done parsing.
713 def _isnt_done(self
):
714 return not self
._is
_done
()
716 # Raises a parse error, creating it using the message `msg` and the
717 # current text location.
718 def _raise_error(self
, msg
: str) -> NoReturn
:
719 _raise_error(msg
, self
._text
_loc
)
721 # Tries to make the pattern `pat` match the current substring,
722 # returning the match object and updating `self._at`,
723 # `self._line_no`, and `self._col_no` on success.
724 def _try_parse_pat(self
, pat
: Pattern
[str]):
725 m
= pat
.match(self
._normand
, self
._at
)
730 # Skip matched string
731 self
._at
+= len(m
.group(0))
734 self
._line
_no
+= m
.group(0).count("\n")
736 # Update column number
737 for i
in reversed(range(self
._at
)):
738 if self
._normand
[i
] == "\n" or i
== 0:
740 self
._col
_no
= self
._at
+ 1
742 self
._col
_no
= self
._at
- i
746 # Return match object
749 # Expects the pattern `pat` to match the current substring,
750 # returning the match object and updating `self._at`,
751 # `self._line_no`, and `self._col_no` on success, or raising a parse
752 # error with the message `error_msg` on error.
753 def _expect_pat(self
, pat
: Pattern
[str], error_msg
: str):
755 m
= self
._try
_parse
_pat
(pat
)
759 self
._raise
_error
(error_msg
)
761 # Return match object
764 # Patterns for _skip_*()
765 _comment_pat
= re
.compile(r
"#[^#]*?(?:$|#)", re
.M
)
766 _ws_or_comments_pat
= re
.compile(r
"(?:\s|{})*".format(_comment_pat
.pattern
), re
.M
)
767 _ws_or_syms_or_comments_pat
= re
.compile(
768 r
"(?:[\s/\\?&:;.,[\]_=|-]|{})*".format(_comment_pat
.pattern
), re
.M
771 # Skips as many whitespaces and comments as possible, but not
772 # insignificant symbol characters.
773 def _skip_ws_and_comments(self
):
774 self
._try
_parse
_pat
(self
._ws
_or
_comments
_pat
)
776 # Skips as many whitespaces, insignificant symbol characters, and
777 # comments as possible.
778 def _skip_ws_and_comments_and_syms(self
):
779 self
._try
_parse
_pat
(self
._ws
_or
_syms
_or
_comments
_pat
)
781 # Pattern for _try_parse_hex_byte()
782 _nibble_pat
= re
.compile(r
"[A-Fa-f0-9]")
784 # Tries to parse a hexadecimal byte, returning a byte item on
786 def _try_parse_hex_byte(self
):
787 begin_text_loc
= self
._text
_loc
789 # Match initial nibble
790 m_high
= self
._try
_parse
_pat
(self
._nibble
_pat
)
796 # Expect another nibble
797 self
._skip
_ws
_and
_comments
_and
_syms
()
798 m_low
= self
._expect
_pat
(
799 self
._nibble
_pat
, "Expecting another hexadecimal nibble"
803 return _Byte(int(m_high
.group(0) + m_low
.group(0), 16), begin_text_loc
)
805 # Patterns for _try_parse_bin_byte()
806 _bin_byte_bit_pat
= re
.compile(r
"[01]")
807 _bin_byte_prefix_pat
= re
.compile(r
"%+")
809 # Tries to parse a binary byte, returning a byte item on success.
810 def _try_parse_bin_byte(self
):
811 begin_text_loc
= self
._text
_loc
814 m
= self
._try
_parse
_pat
(self
._bin
_byte
_prefix
_pat
)
820 # Expect as many bytes as there are `%` prefixes
821 items
= [] # type: List[_Item]
823 for _
in range(len(m
.group(0))):
824 self
._skip
_ws
_and
_comments
_and
_syms
()
825 byte_text_loc
= self
._text
_loc
826 bits
= [] # type: List[str]
830 self
._skip
_ws
_and
_comments
_and
_syms
()
831 m
= self
._expect
_pat
(
832 self
._bin
_byte
_bit
_pat
, "Expecting a bit (`0` or `1`)"
834 bits
.append(m
.group(0))
836 items
.append(_Byte(int("".join(bits
), 2), byte_text_loc
))
843 return _Group(items
, begin_text_loc
)
845 # Patterns for _try_parse_dec_byte()
846 _dec_byte_prefix_pat
= re
.compile(r
"\$")
847 _dec_byte_val_pat
= re
.compile(r
"(?P<neg>-?)(?P<val>\d+)")
849 # Tries to parse a decimal byte, returning a byte item on success.
850 def _try_parse_dec_byte(self
):
851 begin_text_loc
= self
._text
_loc
854 if self
._try
_parse
_pat
(self
._dec
_byte
_prefix
_pat
) is None:
859 self
._skip
_ws
_and
_comments
()
860 m
= self
._expect
_pat
(self
._dec
_byte
_val
_pat
, "Expecting a decimal constant")
863 val
= int(m
.group("val")) * (-1 if m
.group("neg") == "-" else 1)
866 if val
< -128 or val
> 255:
867 _raise_error("Invalid decimal byte value {}".format(val
), begin_text_loc
)
873 return _Byte(val
, begin_text_loc
)
875 # Tries to parse a byte, returning a byte item on success.
876 def _try_parse_byte(self
):
878 item
= self
._try
_parse
_hex
_byte
()
884 item
= self
._try
_parse
_bin
_byte
()
890 item
= self
._try
_parse
_dec
_byte
()
895 # Strings corresponding to escape sequence characters
896 _lit_str_escape_seq_strs
= {
910 # Patterns for _try_parse_lit_str()
911 _lit_str_prefix_suffix_pat
= re
.compile(r
'"')
912 _lit_str_contents_pat
= re
.compile(r
'(?:(?:\\.)|[^"])*')
914 # Parses a literal string between double quotes (without an encoding
915 # prefix) and returns the resulting string.
916 def _try_parse_lit_str(self
, with_prefix
: bool):
917 # Match prefix if needed
919 if self
._try
_parse
_pat
(self
._lit
_str
_prefix
_suffix
_pat
) is None:
923 # Expect literal string
924 m
= self
._expect
_pat
(self
._lit
_str
_contents
_pat
, "Expecting a literal string")
926 # Expect end of string
928 self
._lit
_str
_prefix
_suffix
_pat
, 'Expecting `"` (end of literal string)'
931 # Replace escape sequences
934 for ec
in '0abefnrtv"\\':
935 val
= val
.replace(r
"\{}".format(ec
), self
._lit
_str
_escape
_seq
_strs
[ec
])
940 # Patterns for _try_parse_utf_str_encoding()
941 _str_encoding_utf_prefix_pat
= re
.compile(r
"u")
942 _str_encoding_utf_pat
= re
.compile(r
"(?:8|(?:(?:16|32)(?:[bl]e)))\b")
944 # Tries to parse a UTF encoding specification, returning the Python
945 # codec name on success.
946 def _try_parse_utf_str_encoding(self
):
948 if self
._try
_parse
_pat
(self
._str
_encoding
_utf
_prefix
_pat
) is None:
952 # Expect UTF specification
953 m
= self
._expect
_pat
(
954 self
._str
_encoding
_utf
_pat
,
955 "Expecting `8`, `16be`, `16le`, `32be` or `32le`",
958 # Convert to codec name
967 # Patterns for _try_parse_str_encoding()
968 _str_encoding_gen_prefix_pat
= re
.compile(r
"s")
969 _str_encoding_colon_pat
= re
.compile(r
":")
970 _str_encoding_non_utf_pat
= re
.compile(r
"latin(?:[1-9]|10)\b")
972 # Tries to parse a string encoding specification, returning the
973 # Python codec name on success.
975 # Requires the general prefix (`s:`) if `req_gen_prefix` is `True`.
976 def _try_parse_str_encoding(self
, req_gen_prefix
: bool = False):
978 if self
._try
_parse
_pat
(self
._str
_encoding
_gen
_prefix
_pat
) is not None:
980 self
._skip
_ws
_and
_comments
()
981 self
._expect
_pat
(self
._str
_encoding
_colon
_pat
, "Expecting `:`")
983 # Expect encoding specification
984 self
._skip
_ws
_and
_comments
()
987 codec
= self
._try
_parse
_utf
_str
_encoding
()
989 if codec
is not None:
993 m
= self
._expect
_pat
(
994 self
._str
_encoding
_non
_utf
_pat
,
995 "Expecting `u8`, `u16be`, `u16le`, `u32be`, `u32le`, or `latin1` to `latin10`",
1000 if not req_gen_prefix
:
1001 return self
._try
_parse
_utf
_str
_encoding
()
1003 # Patterns for _try_parse_str()
1004 _lit_str_prefix_pat
= re
.compile(r
'"')
1005 _str_prefix_pat
= re
.compile(r
'"|\{')
1006 _str_expr_pat
= re
.compile(r
"[^}]+")
1007 _str_expr_suffix_pat
= re
.compile(r
"\}")
1009 # Tries to parse a string, returning a literal string or string item
1011 def _try_parse_str(self
):
1012 begin_text_loc
= self
._text
_loc
1015 codec
= self
._try
_parse
_str
_encoding
()
1017 # Match prefix (expect if there's an encoding specification)
1018 self
._skip
_ws
_and
_comments
()
1021 # No encoding: only a literal string (UTF-8) is legal
1022 m_prefix
= self
._try
_parse
_pat
(self
._lit
_str
_prefix
_pat
)
1024 if m_prefix
is None:
1027 # Encoding present: expect a string prefix
1028 m_prefix
= self
._expect
_pat
(self
._str
_prefix
_pat
, 'Expecting `"` or `{`')
1030 # Literal string or expression?
1031 prefix
= m_prefix
.group(0)
1034 # Expect literal string
1035 str_text_loc
= self
._text
_loc
1036 val
= self
._try
_parse
_lit
_str
(False)
1039 self
._raise
_error
("Expecting a literal string")
1042 data
= _encode_str(val
, "utf_8" if codec
is None else codec
, str_text_loc
)
1045 return _LitStr(data
, begin_text_loc
)
1048 self
._skip
_ws
_and
_comments
()
1049 expr_text_loc
= self
._text
_loc
1050 m
= self
._expect
_pat
(self
._str
_expr
_pat
, "Expecting an expression")
1053 self
._expect
_pat
(self
._str
_expr
_suffix
_pat
, "Expecting `}`")
1055 # Create an expression node from the expression string
1056 expr_str
, expr
= self
._ast
_expr
_from
_str
(m
.group(0), expr_text_loc
)
1059 assert codec
is not None
1060 return _Str(expr_str
, expr
, codec
, begin_text_loc
)
1062 # Common right parenthesis pattern
1063 _right_paren_pat
= re
.compile(r
"\)")
1065 # Patterns for _try_parse_group()
1066 _group_prefix_pat
= re
.compile(r
"\(|!g(?:roup)?\b")
1068 # Tries to parse a group, returning a group item on success.
1069 def _try_parse_group(self
):
1070 begin_text_loc
= self
._text
_loc
1073 m_open
= self
._try
_parse
_pat
(self
._group
_prefix
_pat
)
1080 items
= self
._parse
_items
()
1082 # Expect end of group
1083 self
._skip
_ws
_and
_comments
_and
_syms
()
1085 if m_open
.group(0) == "(":
1086 pat
= self
._right
_paren
_pat
1089 pat
= self
._block
_end
_pat
1092 self
._expect
_pat
(pat
, "Expecting an item or `{}` (end of group)".format(exp
))
1095 return _Group(items
, begin_text_loc
)
1097 # Returns a stripped expression string and an AST expression node
1098 # from the expression string `expr_str` at text location `text_loc`.
1099 def _ast_expr_from_str(self
, expr_str
: str, text_loc
: TextLocation
):
1100 # Create an expression node from the expression string
1101 expr_str
= expr_str
.strip().replace("\n", " ")
1104 expr
= ast
.parse(expr_str
, mode
="eval")
1107 "Invalid expression `{}`: invalid syntax".format(expr_str
),
1111 return expr_str
, expr
1113 # Patterns for _try_parse_val()
1114 _val_expr_pat
= re
.compile(r
"([^}:]+):\s*")
1115 _fl_num_len_fmt_pat
= re
.compile(r
"8|16|24|32|40|48|56|64")
1116 _leb128_int_fmt_pat
= re
.compile(r
"(u|s)leb128")
1118 # Tries to parse a value (number or string) and format (fixed length
1119 # in bits, `uleb128`, `sleb128`, or `s:` followed with an encoding
1120 # name), returning an item on success.
1121 def _try_parse_val(self
):
1122 begin_text_loc
= self
._text
_loc
1125 m_expr
= self
._try
_parse
_pat
(self
._val
_expr
_pat
)
1131 # Create an expression node from the expression string
1132 expr_str
, expr
= self
._ast
_expr
_from
_str
(m_expr
.group(1), begin_text_loc
)
1135 self
._skip
_ws
_and
_comments
()
1136 m_fmt
= self
._try
_parse
_pat
(self
._fl
_num
_len
_fmt
_pat
)
1140 m_fmt
= self
._try
_parse
_pat
(self
._leb
128_int
_fmt
_pat
)
1144 codec
= self
._try
_parse
_str
_encoding
(True)
1147 # At this point it's invalid
1149 "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`)"
1152 # Return string item
1153 return _Str(expr_str
, expr
, codec
, begin_text_loc
)
1155 # Return LEB128 integer item
1156 cls
= _ULeb128Int
if m_fmt
.group(1) == "u" else _SLeb128Int
1157 return cls(expr_str
, expr
, begin_text_loc
)
1159 # Return fixed-length number item
1163 int(m_fmt
.group(0)),
1167 # Patterns for _try_parse_var_assign()
1168 _var_assign_name_equal_pat
= re
.compile(
1169 r
"({})\s*=(?!=)".format(_py_name_pat
.pattern
)
1171 _var_assign_expr_pat
= re
.compile(r
"[^}]+")
1173 # Tries to parse a variable assignment, returning a variable
1174 # assignment item on success.
1175 def _try_parse_var_assign(self
):
1176 begin_text_loc
= self
._text
_loc
1179 m
= self
._try
_parse
_pat
(self
._var
_assign
_name
_equal
_pat
)
1188 if name
== _icitte_name
:
1190 "`{}` is a reserved variable name".format(_icitte_name
), begin_text_loc
1193 if name
in self
._label
_names
:
1194 _raise_error("Existing label named `{}`".format(name
), begin_text_loc
)
1196 # Expect an expression
1197 self
._skip
_ws
_and
_comments
()
1198 m
= self
._expect
_pat
(self
._var
_assign
_expr
_pat
, "Expecting an expression")
1200 # Create an expression node from the expression string
1201 expr_str
, expr
= self
._ast
_expr
_from
_str
(m
.group(0), begin_text_loc
)
1203 # Add to known variable names
1204 self
._var
_names
.add(name
)
1214 # Pattern for _try_parse_set_bo()
1215 _bo_pat
= re
.compile(r
"[bl]e")
1217 # Tries to parse a byte order name, returning a byte order setting
1219 def _try_parse_set_bo(self
):
1220 begin_text_loc
= self
._text
_loc
1223 m
= self
._try
_parse
_pat
(self
._bo
_pat
)
1229 # Return corresponding item
1230 if m
.group(0) == "be":
1231 return _SetBo(ByteOrder
.BE
, begin_text_loc
)
1233 assert m
.group(0) == "le"
1234 return _SetBo(ByteOrder
.LE
, begin_text_loc
)
1236 # Patterns for _try_parse_val_or_bo()
1237 _val_var_assign_set_bo_prefix_pat
= re
.compile(r
"\{")
1238 _val_var_assign_set_bo_suffix_pat
= re
.compile(r
"\}")
1240 # Tries to parse a value, a variable assignment, or a byte order
1241 # setting, returning an item on success.
1242 def _try_parse_val_or_var_assign_or_set_bo(self
):
1244 if self
._try
_parse
_pat
(self
._val
_var
_assign
_set
_bo
_prefix
_pat
) is None:
1248 self
._skip
_ws
_and
_comments
()
1250 # Variable assignment item?
1251 item
= self
._try
_parse
_var
_assign
()
1255 item
= self
._try
_parse
_val
()
1258 # Byte order setting item?
1259 item
= self
._try
_parse
_set
_bo
()
1262 # At this point it's invalid
1264 "Expecting a fixed-length number, a string, a variable assignment, or a byte order setting"
1268 self
._skip
_ws
_and
_comments
()
1269 self
._expect
_pat
(self
._val
_var
_assign
_set
_bo
_suffix
_pat
, "Expecting `}`")
1272 # Tries to parse an offset setting value (after the initial `<`),
1273 # returning an offset item on success.
1274 def _try_parse_set_offset_val(self
):
1275 begin_text_loc
= self
._text
_loc
1278 m
= self
._try
_parse
_pat
(_pos_const_int_pat
)
1285 return _SetOffset(int(_norm_const_int(m
.group(0)), 0), begin_text_loc
)
1287 # Tries to parse a label name (after the initial `<`), returning a
1288 # label item on success.
1289 def _try_parse_label_name(self
):
1290 begin_text_loc
= self
._text
_loc
1293 m
= self
._try
_parse
_pat
(_py_name_pat
)
1302 if name
== _icitte_name
:
1304 "`{}` is a reserved label name".format(_icitte_name
), begin_text_loc
1307 if name
in self
._label
_names
:
1308 _raise_error("Duplicate label name `{}`".format(name
), begin_text_loc
)
1310 if name
in self
._var
_names
:
1311 _raise_error("Existing variable named `{}`".format(name
), begin_text_loc
)
1313 # Add to known label names
1314 self
._label
_names
.add(name
)
1317 return _Label(name
, begin_text_loc
)
1319 # Patterns for _try_parse_label_or_set_offset()
1320 _label_set_offset_prefix_pat
= re
.compile(r
"<")
1321 _label_set_offset_suffix_pat
= re
.compile(r
">")
1323 # Tries to parse a label or an offset setting, returning an item on
1325 def _try_parse_label_or_set_offset(self
):
1327 if self
._try
_parse
_pat
(self
._label
_set
_offset
_prefix
_pat
) is None:
1331 # Offset setting item?
1332 self
._skip
_ws
_and
_comments
()
1333 item
= self
._try
_parse
_set
_offset
_val
()
1337 item
= self
._try
_parse
_label
_name
()
1340 # At this point it's invalid
1341 self
._raise
_error
("Expecting a label name or an offset setting value")
1344 self
._skip
_ws
_and
_comments
()
1345 self
._expect
_pat
(self
._label
_set
_offset
_suffix
_pat
, "Expecting `>`")
1348 # Pattern for _parse_pad_val()
1349 _pad_val_prefix_pat
= re
.compile(r
"~")
1351 # Tries to parse a padding value, returning the padding value, or 0
1353 def _parse_pad_val(self
):
1355 self
._skip
_ws
_and
_comments
()
1358 if self
._try
_parse
_pat
(self
._pad
_val
_prefix
_pat
) is not None:
1359 self
._skip
_ws
_and
_comments
()
1360 pad_val_text_loc
= self
._text
_loc
1361 m
= self
._expect
_pat
(
1363 "Expecting a positive constant integer (byte value)",
1367 pad_val
= int(_norm_const_int(m
.group(0)), 0)
1371 "Invalid padding byte value {}".format(pad_val
),
1377 # Patterns for _try_parse_align_offset()
1378 _align_offset_prefix_pat
= re
.compile(r
"@")
1379 _align_offset_val_pat
= re
.compile(r
"\d+")
1381 # Tries to parse an offset alignment, returning an offset alignment
1383 def _try_parse_align_offset(self
):
1384 begin_text_loc
= self
._text
_loc
1387 if self
._try
_parse
_pat
(self
._align
_offset
_prefix
_pat
) is None:
1391 # Expect an alignment
1392 self
._skip
_ws
_and
_comments
()
1393 align_text_loc
= self
._text
_loc
1394 m
= self
._expect
_pat
(
1395 self
._align
_offset
_val
_pat
,
1396 "Expecting an alignment (positive multiple of eight bits)",
1399 # Validate alignment
1400 val
= int(m
.group(0))
1402 if val
<= 0 or (val
% 8) != 0:
1404 "Invalid alignment value {} (not a positive multiple of eight)".format(
1411 pad_val
= self
._parse
_pad
_val
()
1414 return _AlignOffset(val
, pad_val
, begin_text_loc
)
1416 # Patterns for _expect_expr()
1417 _inner_expr_prefix_pat
= re
.compile(r
"\{")
1418 _inner_expr_pat
= re
.compile(r
"[^}]+")
1419 _inner_expr_suffix_pat
= re
.compile(r
"\}")
1421 # Parses an expression outside a `{`/`}` context.
1423 # This function accepts:
1425 # • A Python expression within `{` and `}`.
1427 # • A Python name.
1429 # • If `accept_const_int` is `True`: a constant integer, which may
1430 # be negative if `allow_neg_int` is `True`.
1432 # • If `accept_float` is `True`: a constant floating point number.
1434 # Returns the stripped expression string and AST expression.
1437 accept_const_int
: bool = False,
1438 allow_neg_int
: bool = False,
1439 accept_const_float
: bool = False,
1440 accept_lit_str
: bool = False,
1442 begin_text_loc
= self
._text
_loc
1444 # Constant floating point number?
1445 if accept_const_float
:
1446 m
= self
._try
_parse
_pat
(_const_float_pat
)
1449 return self
._ast
_expr
_from
_str
(m
.group(0), begin_text_loc
)
1452 if accept_const_int
:
1453 m
= self
._try
_parse
_pat
(_const_int_pat
)
1456 # Negative and allowed?
1457 if m
.group("neg") == "-" and not allow_neg_int
:
1459 "Expecting a positive constant integer", begin_text_loc
1462 expr_str
= _norm_const_int(m
.group(0))
1463 return self
._ast
_expr
_from
_str
(expr_str
, begin_text_loc
)
1466 m
= self
._try
_parse
_pat
(_py_name_pat
)
1469 return self
._ast
_expr
_from
_str
(m
.group(0), begin_text_loc
)
1473 val
= self
._try
_parse
_lit
_str
(True)
1476 return self
._ast
_expr
_from
_str
(repr(val
), begin_text_loc
)
1479 msg_accepted_parts
= ["a name", "or `{`"]
1482 msg_accepted_parts
.insert(0, "a literal string")
1484 if accept_const_float
:
1485 msg_accepted_parts
.insert(0, "a constant floating point number")
1487 if accept_const_int
:
1488 msg_pos
= "" if allow_neg_int
else "positive "
1489 msg_accepted_parts
.insert(0, "a {}constant integer".format(msg_pos
))
1491 if len(msg_accepted_parts
) == 2:
1492 msg_accepted
= " ".join(msg_accepted_parts
)
1494 msg_accepted
= ", ".join(msg_accepted_parts
)
1497 self
._inner
_expr
_prefix
_pat
,
1498 "Expecting {}".format(msg_accepted
),
1501 # Expect an expression
1502 self
._skip
_ws
_and
_comments
()
1503 expr_text_loc
= self
._text
_loc
1504 m
= self
._expect
_pat
(self
._inner
_expr
_pat
, "Expecting an expression")
1505 expr_str
= m
.group(0)
1508 self
._skip
_ws
_and
_comments
()
1509 self
._expect
_pat
(self
._inner
_expr
_suffix
_pat
, "Expecting `}`")
1511 return self
._ast
_expr
_from
_str
(expr_str
, expr_text_loc
)
1513 # Patterns for _try_parse_fill_until()
1514 _fill_until_prefix_pat
= re
.compile(r
"\+")
1515 _fill_until_pad_val_prefix_pat
= re
.compile(r
"~")
1517 # Tries to parse a filling, returning a filling item on success.
1518 def _try_parse_fill_until(self
):
1519 begin_text_loc
= self
._text
_loc
1522 if self
._try
_parse
_pat
(self
._fill
_until
_prefix
_pat
) is None:
1527 self
._skip
_ws
_and
_comments
()
1528 expr_str
, expr
= self
._expect
_expr
(accept_const_int
=True)
1531 pad_val
= self
._parse
_pad
_val
()
1534 return _FillUntil(expr_str
, expr
, pad_val
, begin_text_loc
)
1536 # Parses the multiplier expression of a repetition (block or
1537 # post-item) and returns the expression string and AST node.
1538 def _expect_rep_mul_expr(self
):
1539 return self
._expect
_expr
(accept_const_int
=True)
1541 # Common block end pattern
1542 _block_end_pat
= re
.compile(r
"!end\b")
1544 # Pattern for _try_parse_rep_block()
1545 _rep_block_prefix_pat
= re
.compile(r
"!r(?:epeat)?\b")
1547 # Tries to parse a repetition block, returning a repetition item on
1549 def _try_parse_rep_block(self
):
1550 begin_text_loc
= self
._text
_loc
1553 if self
._try
_parse
_pat
(self
._rep
_block
_prefix
_pat
) is None:
1558 self
._skip
_ws
_and
_comments
()
1559 expr_str
, expr
= self
._expect
_rep
_mul
_expr
()
1562 self
._skip
_ws
_and
_comments
_and
_syms
()
1563 items_text_loc
= self
._text
_loc
1564 items
= self
._parse
_items
()
1566 # Expect end of block
1567 self
._skip
_ws
_and
_comments
_and
_syms
()
1569 self
._block
_end
_pat
, "Expecting an item or `!end` (end of repetition block)"
1573 return _Rep(_Group(items
, items_text_loc
), expr_str
, expr
, begin_text_loc
)
1575 # Pattern for _try_parse_cond_block()
1576 _cond_block_prefix_pat
= re
.compile(r
"!if\b")
1577 _cond_block_else_pat
= re
.compile(r
"!else\b")
1579 # Tries to parse a conditional block, returning a conditional item
1581 def _try_parse_cond_block(self
):
1582 begin_text_loc
= self
._text
_loc
1585 if self
._try
_parse
_pat
(self
._cond
_block
_prefix
_pat
) is None:
1590 self
._skip
_ws
_and
_comments
()
1591 expr_str
, expr
= self
._expect
_expr
()
1593 # Parse "true" items
1594 self
._skip
_ws
_and
_comments
_and
_syms
()
1595 true_items_text_loc
= self
._text
_loc
1596 true_items
= self
._parse
_items
()
1597 false_items
= [] # type: List[_Item]
1598 false_items_text_loc
= begin_text_loc
1601 self
._skip
_ws
_and
_comments
_and
_syms
()
1603 if self
._try
_parse
_pat
(self
._cond
_block
_else
_pat
) is not None:
1604 # Parse "false" items
1605 self
._skip
_ws
_and
_comments
_and
_syms
()
1606 false_items_text_loc
= self
._text
_loc
1607 false_items
= self
._parse
_items
()
1609 # Expect end of block
1611 self
._block
_end
_pat
,
1612 "Expecting an item, `!else`, or `!end` (end of conditional block)",
1617 _Group(true_items
, true_items_text_loc
),
1618 _Group(false_items
, false_items_text_loc
),
1624 # Common left parenthesis pattern
1625 _left_paren_pat
= re
.compile(r
"\(")
1627 # Patterns for _try_parse_macro_def() and _try_parse_macro_exp()
1628 _macro_params_comma_pat
= re
.compile(",")
1630 # Patterns for _try_parse_macro_def()
1631 _macro_def_prefix_pat
= re
.compile(r
"!m(?:acro)?\b")
1633 # Tries to parse a macro definition, adding it to `self._macro_defs`
1634 # and returning `True` on success.
1635 def _try_parse_macro_def(self
):
1636 begin_text_loc
= self
._text
_loc
1639 if self
._try
_parse
_pat
(self
._macro
_def
_prefix
_pat
) is None:
1644 self
._skip
_ws
_and
_comments
()
1645 name_text_loc
= self
._text
_loc
1646 m
= self
._expect
_pat
(_py_name_pat
, "Expecting a valid macro name")
1651 if name
in self
._macro
_defs
:
1652 _raise_error("Duplicate macro named `{}`".format(name
), name_text_loc
)
1655 self
._skip
_ws
_and
_comments
()
1656 self
._expect
_pat
(self
._left
_paren
_pat
, "Expecting `(`")
1658 # Try to parse comma-separated parameter names
1659 param_names
= [] # type: List[str]
1660 expect_comma
= False
1663 self
._skip
_ws
_and
_comments
()
1666 if self
._try
_parse
_pat
(self
._right
_paren
_pat
) is not None:
1672 self
._expect
_pat
(self
._macro
_params
_comma
_pat
, "Expecting `,`")
1674 # Expect parameter name
1675 self
._skip
_ws
_and
_comments
()
1676 param_text_loc
= self
._text
_loc
1677 m
= self
._expect
_pat
(_py_name_pat
, "Expecting valid parameter name")
1679 if m
.group(0) in param_names
:
1681 "Duplicate macro parameter named `{}`".format(m
.group(0)),
1685 param_names
.append(m
.group(0))
1689 self
._skip
_ws
_and
_comments
_and
_syms
()
1690 items_text_loc
= self
._text
_loc
1691 old_var_names
= self
._var
_names
.copy()
1692 old_label_names
= self
._label
_names
.copy()
1693 self
._var
_names
= set() # type: Set[str]
1694 self
._label
_names
= set() # type: Set[str]
1695 items
= self
._parse
_items
()
1696 self
._var
_names
= old_var_names
1697 self
._label
_names
= old_label_names
1701 self
._block
_end
_pat
, "Expecting an item or `!end` (end of macro block)"
1705 self
._macro
_defs
[name
] = _MacroDef(
1706 name
, param_names
, _Group(items
, items_text_loc
), begin_text_loc
1711 # Patterns for _try_parse_macro_exp()
1712 _macro_exp_prefix_pat
= re
.compile(r
"m\b")
1713 _macro_exp_colon_pat
= re
.compile(r
":")
1715 # Tries to parse a macro expansion, returning a macro expansion item
1717 def _try_parse_macro_exp(self
):
1718 begin_text_loc
= self
._text
_loc
1721 if self
._try
_parse
_pat
(self
._macro
_exp
_prefix
_pat
) is None:
1726 self
._skip
_ws
_and
_comments
()
1727 self
._expect
_pat
(self
._macro
_exp
_colon
_pat
, "Expecting `:`")
1729 # Expect a macro name
1730 self
._skip
_ws
_and
_comments
()
1731 name_text_loc
= self
._text
_loc
1732 m
= self
._expect
_pat
(_py_name_pat
, "Expecting a valid macro name")
1736 macro_def
= self
._macro
_defs
.get(name
)
1738 if macro_def
is None:
1739 _raise_error("Unknown macro name `{}`".format(name
), name_text_loc
)
1742 self
._skip
_ws
_and
_comments
()
1743 self
._expect
_pat
(self
._left
_paren
_pat
, "Expecting `(`")
1745 # Try to parse comma-separated parameter values
1746 params_text_loc
= self
._text
_loc
1747 params
= [] # type: List[_MacroExpParam]
1748 expect_comma
= False
1751 self
._skip
_ws
_and
_comments
()
1754 if self
._try
_parse
_pat
(self
._right
_paren
_pat
) is not None:
1760 self
._expect
_pat
(self
._macro
_params
_comma
_pat
, "Expecting `,`")
1762 self
._skip
_ws
_and
_comments
()
1763 param_text_loc
= self
._text
_loc
1767 accept_const_int
=True,
1769 accept_const_float
=True,
1770 accept_lit_str
=True,
1772 text_loc
=param_text_loc
1777 # Validate parameter values
1778 if len(params
) != len(macro_def
.param_names
):
1779 sing_plur
= "" if len(params
) == 1 else "s"
1781 "Macro expansion passes {} parameter{} while the definition expects {}".format(
1782 len(params
), sing_plur
, len(macro_def
.param_names
)
1788 return _MacroExp(name
, params
, begin_text_loc
)
1790 # Tries to parse a base item (anything except a repetition),
1791 # returning it on success.
1792 def _try_parse_base_item(self
):
1794 item
= self
._try
_parse
_byte
()
1796 if item
is not None:
1800 item
= self
._try
_parse
_str
()
1802 if item
is not None:
1805 # Value, variable assignment, or byte order setting item?
1806 item
= self
._try
_parse
_val
_or
_var
_assign
_or
_set
_bo
()
1808 if item
is not None:
1811 # Label or offset setting item?
1812 item
= self
._try
_parse
_label
_or
_set
_offset
()
1814 if item
is not None:
1817 # Offset alignment item?
1818 item
= self
._try
_parse
_align
_offset
()
1820 if item
is not None:
1824 item
= self
._try
_parse
_fill
_until
()
1826 if item
is not None:
1830 item
= self
._try
_parse
_group
()
1832 if item
is not None:
1835 # Repetition block item?
1836 item
= self
._try
_parse
_rep
_block
()
1838 if item
is not None:
1841 # Conditional block item?
1842 item
= self
._try
_parse
_cond
_block
()
1844 if item
is not None:
1848 item
= self
._try
_parse
_macro
_exp
()
1850 if item
is not None:
1853 # Pattern for _try_parse_rep_post()
1854 _rep_post_prefix_pat
= re
.compile(r
"\*")
1856 # Tries to parse a post-item repetition, returning the expression
1857 # string and AST expression node on success.
1858 def _try_parse_rep_post(self
):
1860 if self
._try
_parse
_pat
(self
._rep
_post
_prefix
_pat
) is None:
1864 # Return expression string and AST expression
1865 self
._skip
_ws
_and
_comments
()
1866 return self
._expect
_rep
_mul
_expr
()
1868 # Tries to parse an item, possibly followed by a repetition,
1869 # returning `True` on success.
1871 # Appends any parsed item to `items`.
1872 def _try_append_item(self
, items
: List
[_Item
]):
1873 self
._skip
_ws
_and
_comments
_and
_syms
()
1876 item
= self
._try
_parse
_base
_item
()
1881 # Parse repetition if the base item is repeatable
1882 if isinstance(item
, _RepableItem
):
1883 self
._skip
_ws
_and
_comments
()
1884 rep_text_loc
= self
._text
_loc
1885 rep_ret
= self
._try
_parse
_rep
_post
()
1887 if rep_ret
is not None:
1888 item
= _Rep(item
, *rep_ret
, text_loc
=rep_text_loc
)
1893 # Parses and returns items, skipping whitespaces, insignificant
1894 # symbols, and comments when allowed, and stopping at the first
1895 # unknown character.
1897 # Accepts and registers macro definitions if `accept_macro_defs`
1899 def _parse_items(self
, accept_macro_defs
: bool = False) -> List
[_Item
]:
1900 items
= [] # type: List[_Item]
1902 while self
._isnt
_done
():
1903 # Try to append item
1904 if not self
._try
_append
_item
(items
):
1905 if accept_macro_defs
and self
._try
_parse
_macro
_def
():
1908 # Unknown at this point
1913 # Parses the whole Normand input, setting `self._res` to the main
1914 # group item on success.
1916 if len(self
._normand
.strip()) == 0:
1917 # Special case to make sure there's something to consume
1918 self
._res
= _Group([], self
._text
_loc
)
1921 # Parse first level items
1922 items
= self
._parse
_items
(True)
1924 # Make sure there's nothing left
1925 self
._skip
_ws
_and
_comments
_and
_syms
()
1927 if self
._isnt
_done
():
1929 "Unexpected character `{}`".format(self
._normand
[self
._at
])
1932 # Set main group item
1933 self
._res
= _Group(items
, self
._text
_loc
)
1936 # The return type of parse().
1942 variables
: VariablesT
,
1945 bo
: Optional
[ByteOrder
],
1947 self
= cls
.__new
__(cls
)
1948 self
._init
(data
, variables
, labels
, offset
, bo
)
1951 def __init__(self
, *args
, **kwargs
): # type: ignore
1952 raise NotImplementedError
1957 variables
: VariablesT
,
1960 bo
: Optional
[ByteOrder
],
1963 self
._vars
= variables
1964 self
._labels
= labels
1965 self
._offset
= offset
1973 # Dictionary of updated variable names to their last computed value.
1975 def variables(self
):
1978 # Dictionary of updated main group label names to their computed
1989 # Updated byte order.
1991 def byte_order(self
):
1995 # Raises a parse error for the item `item`, creating it using the
1997 def _raise_error_for_item(msg
: str, item
: _Item
) -> NoReturn
:
1998 _raise_error(msg
, item
.text_loc
)
2001 # The `ICITTE` reserved name.
2002 _icitte_name
= "ICITTE"
2005 # Base node visitor.
2007 # Calls the _visit_name() method for each name node which isn't the name
2009 class _NodeVisitor(ast
.NodeVisitor
):
2011 self
._parent
_is
_call
= False
2013 def generic_visit(self
, node
: ast
.AST
):
2014 if type(node
) is ast
.Call
:
2015 self
._parent
_is
_call
= True
2016 elif type(node
) is ast
.Name
and not self
._parent
_is
_call
:
2017 self
._visit
_name
(node
.id)
2019 super().generic_visit(node
)
2020 self
._parent
_is
_call
= False
2023 def _visit_name(self
, name
: str):
2027 # Expression validator: validates that all the names within the
2028 # expression are allowed.
2029 class _ExprValidator(_NodeVisitor
):
2030 def __init__(self
, expr_str
: str, text_loc
: TextLocation
, allowed_names
: Set
[str]):
2032 self
._expr
_str
= expr_str
2033 self
._text
_loc
= text_loc
2034 self
._allowed
_names
= allowed_names
2036 def _visit_name(self
, name
: str):
2037 # Make sure the name refers to a known and reachable
2038 # variable/label name.
2039 if name
!= _icitte_name
and name
not in self
._allowed
_names
:
2040 msg
= "Illegal (unknown or unreachable) variable/label name `{}` in expression `{}`".format(
2041 name
, self
._expr
_str
2044 allowed_names
= self
._allowed
_names
.copy()
2045 allowed_names
.add(_icitte_name
)
2047 if len(allowed_names
) > 0:
2048 allowed_names_str
= ", ".join(
2049 sorted(["`{}`".format(name
) for name
in allowed_names
])
2051 msg
+= "; the legal names are {{{}}}".format(allowed_names_str
)
2063 variables
: VariablesT
,
2066 bo
: Optional
[ByteOrder
],
2068 self
.variables
= variables
.copy()
2069 self
.labels
= labels
.copy()
2070 self
.offset
= offset
2074 return "_GenState({}, {}, {}, {})".format(
2075 repr(self
.variables
), repr(self
.labels
), repr(self
.offset
), repr(self
.bo
)
2079 # Fixed-length number item instance.
2080 class _FlNumItemInst
:
2084 offset_in_data
: int,
2086 parse_error_msgs
: List
[ParseErrorMessage
],
2089 self
._offset
_in
_data
= offset_in_data
2091 self
._parse
_error
_msgs
= parse_error_msgs
2098 def offset_in_data(self
):
2099 return self
._offset
_in
_data
2106 def parse_error_msgs(self
):
2107 return self
._parse
_error
_msgs
2110 # Generator of data and final state from a group item.
2112 # Generation happens in memory at construction time. After building, use
2113 # the `data`, `variables`, `labels`, `offset`, and `bo` properties to
2114 # get the resulting context.
2116 # The steps of generation are:
2118 # 1. Handle each item in prefix order.
2120 # The handlers append bytes to `self._data` and update some current
2121 # state object (`_GenState` instance).
2123 # When handling a fixed-length number item, try to evaluate its
2124 # expression using the current state. If this fails, then it might be
2125 # because the expression refers to a "future" label: save the current
2126 # offset in `self._data` (generated data) and a snapshot of the
2127 # current state within `self._fl_num_item_insts` (`_FlNumItemInst`
2128 # object). _gen_fl_num_item_insts() will deal with this later. A
2129 # `_FlNumItemInst` instance also contains a snapshot of the current
2130 # parsing error messages (`self._parse_error_msgs`) which need to be
2131 # taken into account when handling the instance later.
2133 # When handling the items of a group, keep a map of immediate label
2134 # names to their offset. Then, after having processed all the items,
2135 # update the relevant saved state snapshots in
2136 # `self._fl_num_item_insts` with those immediate label values.
2137 # _gen_fl_num_item_insts() will deal with this later.
2139 # 2. Handle all the fixed-length number item instances of which the
2140 # expression evaluation failed before.
2142 # At this point, `self._fl_num_item_insts` contains everything that's
2143 # needed to evaluate the expressions, including the values of
2144 # "future" labels from the point of view of some fixed-length number
2147 # If an evaluation fails at this point, then it's a user error. Add
2148 # to the parsing error all the saved parsing error messages of the
2149 # instance. Those additional messages add precious context to the
2155 macro_defs
: _MacroDefsT
,
2156 variables
: VariablesT
,
2159 bo
: Optional
[ByteOrder
],
2161 self
._macro
_defs
= macro_defs
2162 self
._fl
_num
_item
_insts
= [] # type: List[_FlNumItemInst]
2163 self
._parse
_error
_msgs
= [] # type: List[ParseErrorMessage]
2164 self
._gen
(group
, _GenState(variables
, labels
, offset
, bo
))
2171 # Updated variables.
2173 def variables(self
):
2174 return self
._final
_state
.variables
2176 # Updated main group labels.
2179 return self
._final
_state
.labels
2184 return self
._final
_state
.offset
2186 # Updated byte order.
2189 return self
._final
_state
.bo
2191 # Evaluates the expression `expr` of which the original string is
2192 # `expr_str` at the location `text_loc` considering the current
2193 # generation state `state`.
2195 # If `accept_float` is `True`, then the type of the result may be
2198 # If `accept_str` is `True`, then the type of the result may be
2203 expr
: ast
.Expression
,
2204 text_loc
: TextLocation
,
2206 accept_float
: bool = False,
2207 accept_str
: bool = False,
2209 syms
= {} # type: VariablesT
2210 syms
.update(state
.labels
)
2212 # Set the `ICITTE` name to the current offset
2213 syms
[_icitte_name
] = state
.offset
2215 # Add the current variables
2216 syms
.update(state
.variables
)
2218 # Validate the node and its children
2219 _ExprValidator(expr_str
, text_loc
, set(syms
.keys())).visit(expr
)
2221 # Compile and evaluate expression node
2223 val
= eval(compile(expr
, "", "eval"), None, syms
)
2224 except Exception as exc
:
2226 "Failed to evaluate expression `{}`: {}".format(expr_str
, exc
),
2230 # Convert `bool` result type to `int` to normalize
2231 if type(val
) is bool:
2234 # Validate result type
2235 expected_types
= {int}
# type: Set[type]
2238 expected_types
.add(float)
2241 expected_types
.add(str)
2243 if type(val
) not in expected_types
:
2244 expected_types_str
= sorted(
2245 ["`{}`".format(t
.__name
__) for t
in expected_types
]
2248 if len(expected_types_str
) == 1:
2249 msg_expected
= expected_types_str
[0]
2250 elif len(expected_types_str
) == 2:
2251 msg_expected
= " or ".join(expected_types_str
)
2253 expected_types_str
[-1] = "or {}".format(expected_types_str
[-1])
2254 msg_expected
= ", ".join(expected_types_str
)
2257 "Invalid expression `{}`: expecting result type {}, not `{}`".format(
2258 expr_str
, msg_expected
, type(val
).__name
__
2265 # Forwards to _eval_expr() with the expression and text location of
2268 def _eval_item_expr(
2269 item
: Union
[_Cond
, _FillUntil
, _FlNum
, _Leb128Int
, _Rep
, _Str
, _VarAssign
],
2271 accept_float
: bool = False,
2272 accept_str
: bool = False,
2274 return _Gen
._eval
_expr
(
2275 item
.expr_str
, item
.expr
, item
.text_loc
, state
, accept_float
, accept_str
2278 # Handles the byte item `item`.
2279 def _handle_byte_item(self
, item
: _Byte
, state
: _GenState
):
2280 self
._data
.append(item
.val
)
2281 state
.offset
+= item
.size
2283 # Handles the literal string item `item`.
2284 def _handle_lit_str_item(self
, item
: _LitStr
, state
: _GenState
):
2285 self
._data
+= item
.data
2286 state
.offset
+= item
.size
2288 # Handles the byte order setting item `item`.
2289 def _handle_set_bo_item(self
, item
: _SetBo
, state
: _GenState
):
2290 # Update current byte order
2293 # Handles the variable assignment item `item`.
2294 def _handle_var_assign_item(self
, item
: _VarAssign
, state
: _GenState
):
2296 state
.variables
[item
.name
] = self
._eval
_item
_expr
(
2297 item
, state
, accept_float
=True, accept_str
=True
2300 # Handles the fixed-length number item `item`.
2301 def _handle_fl_num_item(self
, item
: _FlNum
, state
: _GenState
):
2302 # Validate current byte order
2303 if state
.bo
is None and item
.len > 8:
2304 _raise_error_for_item(
2305 "Current byte order isn't defined at first fixed-length number (`{}`) to encode on more than 8 bits".format(
2311 # Try an immediate evaluation. If it fails, then keep everything
2312 # needed to (try to) generate the bytes of this item later.
2314 data
= self
._gen
_fl
_num
_item
_inst
_data
(item
, state
)
2316 self
._fl
_num
_item
_insts
.append(
2320 copy
.deepcopy(state
),
2321 copy
.deepcopy(self
._parse
_error
_msgs
),
2325 # Reserve space in `self._data` for this instance
2326 data
= bytes([0] * (item
.len // 8))
2332 state
.offset
+= len(data
)
2334 # Returns the size, in bytes, required to encode the value `val`
2335 # with LEB128 (signed version if `is_signed` is `True`).
2337 def _leb128_size_for_val(val
: int, is_signed
: bool):
2339 # Equivalent upper bound.
2341 # For example, if `val` is -128, then the full integer for
2342 # this number of bits would be [-128, 127].
2345 # Number of bits (add one for the sign if needed)
2346 bits
= val
.bit_length() + int(is_signed
)
2351 # Seven bits per byte
2352 return math
.ceil(bits
/ 7)
2354 # Handles the LEB128 integer item `item`.
2355 def _handle_leb128_int_item(self
, item
: _Leb128Int
, state
: _GenState
):
2357 val
= self
._eval
_item
_expr
(item
, state
)
2360 size
= self
._leb
128_size
_for
_val
(val
, type(item
) is _SLeb128Int
)
2363 for _
in range(size
):
2364 # Seven LSBs, MSB of the byte set (continue)
2365 self
._data
.append((val
& 0x7F) |
0x80)
2368 # Clear MSB of last byte (stop)
2369 self
._data
[-1] &= ~
0x80
2372 state
.offset
+= size
2374 # Handles the string item `item`.
2375 def _handle_str_item(self
, item
: _Str
, state
: _GenState
):
2377 val
= str(self
._eval
_item
_expr
(item
, state
, accept_float
=True, accept_str
=True))
2380 data
= _encode_str(val
, item
.codec
, item
.text_loc
)
2386 state
.offset
+= len(data
)
2388 # Handles the group item `item`, removing the immediate labels from
2389 # `state` at the end if `remove_immediate_labels` is `True`.
2390 def _handle_group_item(
2391 self
, item
: _Group
, state
: _GenState
, remove_immediate_labels
: bool = True
2393 first_fl_num_item_inst_index
= len(self
._fl
_num
_item
_insts
)
2394 immediate_labels
= {} # type: LabelsT
2397 for subitem
in item
.items
:
2398 if type(subitem
) is _Label
:
2399 # Add to local immediate labels
2400 immediate_labels
[subitem
.name
] = state
.offset
2402 self
._handle
_item
(subitem
, state
)
2404 # Remove immediate labels from current state if needed
2405 if remove_immediate_labels
:
2406 for name
in immediate_labels
:
2407 del state
.labels
[name
]
2409 # Add all immediate labels to all state snapshots since
2410 # `first_fl_num_item_inst_index`.
2411 for inst
in self
._fl
_num
_item
_insts
[first_fl_num_item_inst_index
:]:
2412 inst
.state
.labels
.update(immediate_labels
)
2414 # Handles the repetition item `item`.
2415 def _handle_rep_item(self
, item
: _Rep
, state
: _GenState
):
2416 # Compute the repetition count
2417 mul
= _Gen
._eval
_item
_expr
(item
, state
)
2421 _raise_error_for_item(
2422 "Invalid expression `{}`: unexpected negative result {:,}".format(
2428 # Generate item data `mul` times
2429 for _
in range(mul
):
2430 self
._handle
_item
(item
.item
, state
)
2432 # Handles the conditional item `item`.
2433 def _handle_cond_item(self
, item
: _Cond
, state
: _GenState
):
2434 # Compute the conditional value
2435 val
= _Gen
._eval
_item
_expr
(item
, state
)
2437 # Generate item data if needed
2439 self
._handle
_item
(item
.true_item
, state
)
2441 self
._handle
_item
(item
.false_item
, state
)
2443 # Evaluates the parameters of the macro expansion item `item`
2444 # considering the initial state `init_state` and returns a new state
2445 # to handle the items of the macro.
2446 def _eval_macro_exp_params(self
, item
: _MacroExp
, init_state
: _GenState
):
2448 exp_state
= _GenState({}, {}, init_state
.offset
, init_state
.bo
)
2450 # Evaluate the parameter expressions
2451 macro_def
= self
._macro
_defs
[item
.name
]
2453 for param_name
, param
in zip(macro_def
.param_names
, item
.params
):
2454 exp_state
.variables
[param_name
] = _Gen
._eval
_expr
(
2465 # Handles the macro expansion item `item`.
2466 def _handle_macro_exp_item(self
, item
: _MacroExp
, state
: _GenState
):
2467 parse_error_msg_text
= "While expanding the macro `{}`:".format(item
.name
)
2471 exp_state
= self
._eval
_macro
_exp
_params
(item
, state
)
2473 # Process the contained group
2474 init_data_size
= len(self
._data
)
2476 ParseErrorMessage
._create
( # pyright: ignore[reportPrivateUsage]
2477 parse_error_msg_text
, item
.text_loc
2480 self
._parse
_error
_msgs
.append(parse_error_msg
)
2481 self
._handle
_item
(self
._macro
_defs
[item
.name
].group
, exp_state
)
2482 self
._parse
_error
_msgs
.pop()
2483 except ParseError
as exc
:
2484 _augment_error(exc
, parse_error_msg_text
, item
.text_loc
)
2486 # Update state offset and return
2487 state
.offset
+= len(self
._data
) - init_data_size
2489 # Handles the offset setting item `item`.
2490 def _handle_set_offset_item(self
, item
: _SetOffset
, state
: _GenState
):
2491 state
.offset
= item
.val
2493 # Handles the offset alignment item `item` (adds padding).
2494 def _handle_align_offset_item(self
, item
: _AlignOffset
, state
: _GenState
):
2495 init_offset
= state
.offset
2496 align_bytes
= item
.val
// 8
2497 state
.offset
= (state
.offset
+ align_bytes
- 1) // align_bytes
* align_bytes
2498 self
._data
+= bytes([item
.pad_val
] * (state
.offset
- init_offset
))
2500 # Handles the filling item `item` (adds padding).
2501 def _handle_fill_until_item(self
, item
: _FillUntil
, state
: _GenState
):
2502 # Compute the new offset
2503 new_offset
= _Gen
._eval
_item
_expr
(item
, state
)
2505 # Validate the new offset
2506 if new_offset
< state
.offset
:
2507 _raise_error_for_item(
2508 "Invalid expression `{}`: new offset {:,} is less than current offset {:,}".format(
2509 item
.expr_str
, new_offset
, state
.offset
2515 self
._data
+= bytes([item
.pad_val
] * (new_offset
- state
.offset
))
2518 state
.offset
= new_offset
2520 # Handles the label item `item`.
2521 def _handle_label_item(self
, item
: _Label
, state
: _GenState
):
2522 state
.labels
[item
.name
] = state
.offset
2524 # Handles the item `item`, returning the updated next repetition
2526 def _handle_item(self
, item
: _Item
, state
: _GenState
):
2527 return self
._item
_handlers
[type(item
)](item
, state
)
2529 # Generates the data for a fixed-length integer item instance having
2530 # the value `val` and returns it.
2531 def _gen_fl_int_item_inst_data(self
, val
: int, item
: _FlNum
, state
: _GenState
):
2533 if val
< -(2 ** (item
.len - 1)) or val
> 2**item
.len - 1:
2534 _raise_error_for_item(
2535 "Value {:,} is outside the {}-bit range when evaluating expression `{}`".format(
2536 val
, item
.len, item
.expr_str
2541 # Encode result on 64 bits (to extend the sign bit whatever the
2542 # value of `item.len`).
2545 ">" if state
.bo
in (None, ByteOrder
.BE
) else "<",
2546 "Q" if val
>= 0 else "q",
2551 # Keep only the requested length
2552 len_bytes
= item
.len // 8
2554 if state
.bo
in (None, ByteOrder
.BE
):
2555 # Big endian: keep last bytes
2556 data
= data
[-len_bytes
:]
2558 # Little endian: keep first bytes
2559 assert state
.bo
== ByteOrder
.LE
2560 data
= data
[:len_bytes
]
2565 # Generates the data for a fixed-length floating point number item
2566 # instance having the value `val` and returns it.
2567 def _gen_fl_float_item_inst_data(self
, val
: float, item
: _FlNum
, state
: _GenState
):
2569 if item
.len not in (32, 64):
2570 _raise_error_for_item(
2571 "Invalid {}-bit length for a fixed-length floating point number (value {:,})".format(
2577 # Encode and return result
2580 ">" if state
.bo
in (None, ByteOrder
.BE
) else "<",
2581 "f" if item
.len == 32 else "d",
2586 # Generates the data for a fixed-length number item instance and
2588 def _gen_fl_num_item_inst_data(self
, item
: _FlNum
, state
: _GenState
):
2590 val
= self
._eval
_item
_expr
(item
, state
, True)
2592 # Handle depending on type
2593 if type(val
) is int:
2594 return self
._gen
_fl
_int
_item
_inst
_data
(val
, item
, state
)
2596 assert type(val
) is float
2597 return self
._gen
_fl
_float
_item
_inst
_data
(val
, item
, state
)
2599 # Generates the data for all the fixed-length number item instances
2600 # and writes it at the correct offset within `self._data`.
2601 def _gen_fl_num_item_insts(self
):
2602 for inst
in self
._fl
_num
_item
_insts
:
2605 data
= self
._gen
_fl
_num
_item
_inst
_data
(inst
.item
, inst
.state
)
2606 except ParseError
as exc
:
2607 # Add all the saved parse error messages for this
2609 for msg
in reversed(inst
.parse_error_msgs
):
2610 _add_error_msg(exc
, msg
.text
, msg
.text_location
)
2614 # Insert bytes into `self._data`
2615 self
._data
[inst
.offset_in_data
: inst
.offset_in_data
+ len(data
)] = data
2617 # Generates the data (`self._data`) and final state
2618 # (`self._final_state`) from `group` and the initial state `state`.
2619 def _gen(self
, group
: _Group
, state
: _GenState
):
2621 self
._data
= bytearray()
2624 self
._item
_handlers
= {
2625 _AlignOffset
: self
._handle
_align
_offset
_item
,
2626 _Byte
: self
._handle
_byte
_item
,
2627 _Cond
: self
._handle
_cond
_item
,
2628 _FillUntil
: self
._handle
_fill
_until
_item
,
2629 _FlNum
: self
._handle
_fl
_num
_item
,
2630 _Group
: self
._handle
_group
_item
,
2631 _Label
: self
._handle
_label
_item
,
2632 _LitStr
: self
._handle
_lit
_str
_item
,
2633 _MacroExp
: self
._handle
_macro
_exp
_item
,
2634 _Rep
: self
._handle
_rep
_item
,
2635 _SetBo
: self
._handle
_set
_bo
_item
,
2636 _SetOffset
: self
._handle
_set
_offset
_item
,
2637 _SLeb128Int
: self
._handle
_leb
128_int
_item
,
2638 _Str
: self
._handle
_str
_item
,
2639 _ULeb128Int
: self
._handle
_leb
128_int
_item
,
2640 _VarAssign
: self
._handle
_var
_assign
_item
,
2641 } # type: Dict[type, Callable[[Any, _GenState], None]]
2643 # Handle the group item, _not_ removing the immediate labels
2644 # because the `labels` property offers them.
2645 self
._handle
_group
_item
(group
, state
, False)
2647 # This is actually the final state
2648 self
._final
_state
= state
2650 # Generate all the fixed-length number bytes now that we know
2652 self
._gen
_fl
_num
_item
_insts
()
2655 # Returns a `ParseResult` instance containing the bytes encoded by the
2656 # input string `normand`.
2658 # `init_variables` is a dictionary of initial variable names (valid
2659 # Python names) to integral values. A variable name must not be the
2660 # reserved name `ICITTE`.
2662 # `init_labels` is a dictionary of initial label names (valid Python
2663 # names) to integral values. A label name must not be the reserved name
2666 # `init_offset` is the initial offset.
2668 # `init_byte_order` is the initial byte order.
2670 # Raises `ParseError` on any parsing error.
2673 init_variables
: Optional
[VariablesT
] = None,
2674 init_labels
: Optional
[LabelsT
] = None,
2675 init_offset
: int = 0,
2676 init_byte_order
: Optional
[ByteOrder
] = None,
2678 if init_variables
is None:
2681 if init_labels
is None:
2684 parser
= _Parser(normand
, init_variables
, init_labels
)
2693 return ParseResult
._create
( # pyright: ignore[reportPrivateUsage]
2694 gen
.data
, gen
.variables
, gen
.labels
, gen
.offset
, gen
.bo
2698 # Raises a command-line error with the message `msg`.
2699 def _raise_cli_error(msg
: str) -> NoReturn
:
2700 raise RuntimeError("Command-line error: {}".format(msg
))
2703 # Returns the `int` or `float` value out of a CLI assignment value.
2704 def _val_from_assign_val_str(s
: str, is_label
: bool):
2707 # Floating point number?
2709 m
= _const_float_pat
.fullmatch(s
)
2712 return float(m
.group(0))
2715 m
= _const_int_pat
.fullmatch(s
)
2718 return int(_norm_const_int(m
.group(0)), 0)
2720 exp
= "an integer" if is_label
else "a number"
2721 _raise_cli_error("Invalid assignment value `{}`: expecting {}".format(s
, exp
))
2724 # Returns a dictionary of string to numbers from the list of strings
2725 # `args` containing `NAME=VAL` entries.
2726 def _dict_from_arg(args
: Optional
[List
[str]], is_label
: bool, is_str_only
: bool):
2727 d
= {} # type: VariablesT
2733 m
= re
.match(r
"({})\s*=\s*(.*)$".format(_py_name_pat
.pattern
), arg
)
2736 _raise_cli_error("Invalid assignment `{}`".format(arg
))
2741 val
= _val_from_assign_val_str(m
.group(2), is_label
)
2748 # Parses the command-line arguments and returns, in this order:
2750 # 1. The input file path, or `None` if none.
2751 # 2. The Normand input text.
2752 # 3. The initial offset.
2753 # 4. The initial byte order.
2754 # 5. The initial variables.
2755 # 6. The initial labels.
2756 def _parse_cli_args():
2760 ap
= argparse
.ArgumentParser()
2767 help="initial offset (positive)",
2773 choices
=["be", "le"],
2775 help="initial byte order (`be` or `le`)",
2782 help="add an initial numeric variable (may be repeated)",
2789 help="add an initial string variable (may be repeated)",
2796 help="add an initial label (may be repeated)",
2799 "--version", action
="version", version
="Normand {}".format(__version__
)
2806 help="input path (none means standard input)",
2810 args
= ap
.parse_args()
2813 if args
.path
is None:
2814 normand
= sys
.stdin
.read()
2816 with
open(args
.path
) as f
:
2819 # Variables and labels
2820 variables
= _dict_from_arg(args
.var
, False, False)
2821 variables
.update(_dict_from_arg(args
.var_str
, False, True))
2822 labels
= _dict_from_arg(args
.label
, True, False)
2826 _raise_cli_error("Invalid negative offset {}")
2828 # Validate and set byte order
2829 bo
= None # type: Optional[ByteOrder]
2831 if args
.byte_order
is not None:
2832 if args
.byte_order
== "be":
2835 assert args
.byte_order
== "le"
2838 # Return input and initial state
2839 return args
.path
, normand
, args
.offset
, bo
, variables
, typing
.cast(LabelsT
, labels
)
2842 # CLI entry point without exception handling.
2843 def _run_cli_with_args(
2846 bo
: Optional
[ByteOrder
],
2847 variables
: VariablesT
,
2850 sys
.stdout
.buffer.write(parse(normand
, variables
, labels
, offset
, bo
).data
)
2853 # Prints the exception message `msg` and exits with status 1.
2854 def _fail(msg
: str) -> NoReturn
:
2855 if not msg
.endswith("."):
2858 print(msg
.strip(), file=sys
.stderr
)
2865 args
= _parse_cli_args()
2866 except Exception as exc
:
2870 _run_cli_with_args(*args
[1:])
2871 except ParseError
as exc
:
2874 prefix
= "" if args
[0] is None else "{}:".format(os
.path
.abspath(args
[0]))
2877 for msg
in reversed(exc
.messages
):
2878 fail_msg
+= "{}{}:{} - {}".format(
2880 msg
.text_location
.line_no
,
2881 msg
.text_location
.col_no
,
2885 if fail_msg
[-1] not in ".:;":
2890 _fail(fail_msg
.strip())
2891 except Exception as exc
:
2895 if __name__
== "__main__":