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.16.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 _Str(_ScalarItem
, _RepableItem
):
134 def __init__(self
, data
: bytes
, text_loc
: TextLocation
):
135 super().__init
__(text_loc
)
145 return len(self
._data
)
148 return "_Str({}, {})".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 _Group(_Item
, _RepableItem
):
345 def __init__(self
, items
: List
[_Item
], text_loc
: TextLocation
):
346 super().__init
__(text_loc
)
355 return "_Group({}, {})".format(repr(self
._items
), repr(self
._text
_loc
))
359 class _Rep(_Item
, _ExprMixin
):
361 self
, item
: _Item
, expr_str
: str, expr
: ast
.Expression
, text_loc
: TextLocation
363 super().__init
__(text_loc
)
364 _ExprMixin
.__init
__(self
, expr_str
, expr
)
373 return "_Rep({}, {}, {}, {})".format(
375 repr(self
._expr
_str
),
377 repr(self
._text
_loc
),
382 class _Cond(_Item
, _ExprMixin
):
388 expr
: ast
.Expression
,
389 text_loc
: TextLocation
,
391 super().__init
__(text_loc
)
392 _ExprMixin
.__init
__(self
, expr_str
, expr
)
393 self
._true
_item
= true_item
394 self
._false
_item
= false_item
396 # Item when condition is true.
399 return self
._true
_item
401 # Item when condition is false.
403 def false_item(self
):
404 return self
._false
_item
407 return "_Cond({}, {}, {}, {}, {})".format(
408 repr(self
._true
_item
),
409 repr(self
._false
_item
),
410 repr(self
._expr
_str
),
412 repr(self
._text
_loc
),
416 # Macro definition item.
417 class _MacroDef(_Item
):
419 self
, name
: str, param_names
: List
[str], group
: _Group
, text_loc
: TextLocation
421 super().__init
__(text_loc
)
423 self
._param
_names
= param_names
433 def param_names(self
):
434 return self
._param
_names
442 return "_MacroDef({}, {}, {}, {})".format(
444 repr(self
._param
_names
),
446 repr(self
._text
_loc
),
450 # Macro expansion parameter.
451 class _MacroExpParam
:
452 def __init__(self
, expr_str
: str, expr
: ast
.Expression
, text_loc
: TextLocation
):
453 self
._expr
_str
= expr_str
455 self
._text
_loc
= text_loc
460 return self
._expr
_str
467 # Source text location.
470 return self
._text
_loc
473 return "_MacroExpParam({}, {}, {})".format(
474 repr(self
._expr
_str
), repr(self
._expr
), repr(self
._text
_loc
)
478 # Macro expansion item.
479 class _MacroExp(_Item
, _RepableItem
):
483 params
: List
[_MacroExpParam
],
484 text_loc
: TextLocation
,
486 super().__init
__(text_loc
)
488 self
._params
= params
501 return "_MacroExp({}, {}, {})".format(
504 repr(self
._text
_loc
),
508 # A parsing error message: a string and a text location.
509 class ParseErrorMessage
:
511 def _create(cls
, text
: str, text_loc
: TextLocation
):
512 self
= cls
.__new
__(cls
)
513 self
._init
(text
, text_loc
)
516 def __init__(self
, *args
, **kwargs
): # type: ignore
517 raise NotImplementedError
519 def _init(self
, text
: str, text_loc
: TextLocation
):
521 self
._text
_loc
= text_loc
528 # Source text location.
530 def text_location(self
):
531 return self
._text
_loc
534 # A parsing error containing one or more messages (`ParseErrorMessage`).
535 class ParseError(RuntimeError):
537 def _create(cls
, msg
: str, text_loc
: TextLocation
):
538 self
= cls
.__new
__(cls
)
539 self
._init
(msg
, text_loc
)
542 def __init__(self
, *args
, **kwargs
): # type: ignore
543 raise NotImplementedError
545 def _init(self
, msg
: str, text_loc
: TextLocation
):
546 super().__init
__(msg
)
547 self
._msgs
= [] # type: List[ParseErrorMessage]
548 self
._add
_msg
(msg
, text_loc
)
550 def _add_msg(self
, msg
: str, text_loc
: TextLocation
):
552 ParseErrorMessage
._create
( # pyright: ignore[reportPrivateUsage]
557 # Parsing error messages.
559 # The first message is the most specific one.
565 # Raises a parsing error, forwarding the parameters to the constructor.
566 def _raise_error(msg
: str, text_loc
: TextLocation
) -> NoReturn
:
567 raise ParseError
._create
(msg
, text_loc
) # pyright: ignore[reportPrivateUsage]
570 # Adds a message to the parsing error `exc`.
571 def _add_error_msg(exc
: ParseError
, msg
: str, text_loc
: TextLocation
):
572 exc
._add
_msg
(msg
, text_loc
) # pyright: ignore[reportPrivateUsage]
575 # Appends a message to the parsing error `exc` and reraises it.
576 def _augment_error(exc
: ParseError
, msg
: str, text_loc
: TextLocation
) -> NoReturn
:
577 _add_error_msg(exc
, msg
, text_loc
)
581 # Variables dictionary type (for type hints).
582 VariablesT
= Dict
[str, Union
[int, float]]
585 # Labels dictionary type (for type hints).
586 LabelsT
= Dict
[str, int]
589 # Python name pattern.
590 _py_name_pat
= re
.compile(r
"[a-zA-Z_][a-zA-Z0-9_]*")
593 # Macro definition dictionary.
594 _MacroDefsT
= Dict
[str, _MacroDef
]
599 # The constructor accepts a Normand input. After building, use the `res`
600 # property to get the resulting main group.
602 # Builds a parser to parse the Normand input `normand`, parsing
604 def __init__(self
, normand
: str, variables
: VariablesT
, labels
: LabelsT
):
605 self
._normand
= normand
609 self
._label
_names
= set(labels
.keys())
610 self
._var
_names
= set(variables
.keys())
611 self
._macro
_defs
= {} # type: _MacroDefsT
614 # Result (main group).
621 def macro_defs(self
):
622 return self
._macro
_defs
624 # Current text location.
627 return TextLocation
._create
( # pyright: ignore[reportPrivateUsage]
628 self
._line
_no
, self
._col
_no
631 # Returns `True` if this parser is done parsing.
633 return self
._at
== len(self
._normand
)
635 # Returns `True` if this parser isn't done parsing.
636 def _isnt_done(self
):
637 return not self
._is
_done
()
639 # Raises a parse error, creating it using the message `msg` and the
640 # current text location.
641 def _raise_error(self
, msg
: str) -> NoReturn
:
642 _raise_error(msg
, self
._text
_loc
)
644 # Tries to make the pattern `pat` match the current substring,
645 # returning the match object and updating `self._at`,
646 # `self._line_no`, and `self._col_no` on success.
647 def _try_parse_pat(self
, pat
: Pattern
[str]):
648 m
= pat
.match(self
._normand
, self
._at
)
653 # Skip matched string
654 self
._at
+= len(m
.group(0))
657 self
._line
_no
+= m
.group(0).count("\n")
659 # Update column number
660 for i
in reversed(range(self
._at
)):
661 if self
._normand
[i
] == "\n" or i
== 0:
663 self
._col
_no
= self
._at
+ 1
665 self
._col
_no
= self
._at
- i
669 # Return match object
672 # Expects the pattern `pat` to match the current substring,
673 # returning the match object and updating `self._at`,
674 # `self._line_no`, and `self._col_no` on success, or raising a parse
675 # error with the message `error_msg` on error.
676 def _expect_pat(self
, pat
: Pattern
[str], error_msg
: str):
678 m
= self
._try
_parse
_pat
(pat
)
682 self
._raise
_error
(error_msg
)
684 # Return match object
687 # Pattern for _skip_ws_and_comments()
688 _ws_or_syms_or_comments_pat
= re
.compile(
689 r
"(?:[\s/\\?&:;.,[\]_=|-]|#[^#]*?(?:\n|#))*"
692 # Skips as many whitespaces, insignificant symbol characters, and
693 # comments as possible.
694 def _skip_ws_and_comments(self
):
695 self
._try
_parse
_pat
(self
._ws
_or
_syms
_or
_comments
_pat
)
697 # Pattern for _skip_ws()
698 _ws_pat
= re
.compile(r
"\s*")
700 # Skips as many whitespaces as possible.
702 self
._try
_parse
_pat
(self
._ws
_pat
)
704 # Pattern for _try_parse_hex_byte()
705 _nibble_pat
= re
.compile(r
"[A-Fa-f0-9]")
707 # Tries to parse a hexadecimal byte, returning a byte item on
709 def _try_parse_hex_byte(self
):
710 begin_text_loc
= self
._text
_loc
712 # Match initial nibble
713 m_high
= self
._try
_parse
_pat
(self
._nibble
_pat
)
719 # Expect another nibble
720 self
._skip
_ws
_and
_comments
()
721 m_low
= self
._expect
_pat
(
722 self
._nibble
_pat
, "Expecting another hexadecimal nibble"
726 return _Byte(int(m_high
.group(0) + m_low
.group(0), 16), begin_text_loc
)
728 # Patterns for _try_parse_bin_byte()
729 _bin_byte_bit_pat
= re
.compile(r
"[01]")
730 _bin_byte_prefix_pat
= re
.compile(r
"%+")
732 # Tries to parse a binary byte, returning a byte item on success.
733 def _try_parse_bin_byte(self
):
734 begin_text_loc
= self
._text
_loc
737 m
= self
._try
_parse
_pat
(self
._bin
_byte
_prefix
_pat
)
743 # Expect as many bytes as there are `%` prefixes
744 items
= [] # type: List[_Item]
746 for _
in range(len(m
.group(0))):
747 self
._skip
_ws
_and
_comments
()
748 byte_text_loc
= self
._text
_loc
749 bits
= [] # type: List[str]
753 self
._skip
_ws
_and
_comments
()
754 m
= self
._expect
_pat
(
755 self
._bin
_byte
_bit
_pat
, "Expecting a bit (`0` or `1`)"
757 bits
.append(m
.group(0))
759 items
.append(_Byte(int("".join(bits
), 2), byte_text_loc
))
766 return _Group(items
, begin_text_loc
)
768 # Patterns for _try_parse_dec_byte()
769 _dec_byte_prefix_pat
= re
.compile(r
"\$")
770 _dec_byte_val_pat
= re
.compile(r
"(?P<neg>-?)(?P<val>\d+)")
772 # Tries to parse a decimal byte, returning a byte item on success.
773 def _try_parse_dec_byte(self
):
774 begin_text_loc
= self
._text
_loc
777 if self
._try
_parse
_pat
(self
._dec
_byte
_prefix
_pat
) is None:
783 m
= self
._expect
_pat
(self
._dec
_byte
_val
_pat
, "Expecting a decimal constant")
786 val
= int(m
.group("val")) * (-1 if m
.group("neg") == "-" else 1)
789 if val
< -128 or val
> 255:
790 _raise_error("Invalid decimal byte value {}".format(val
), begin_text_loc
)
796 return _Byte(val
, begin_text_loc
)
798 # Tries to parse a byte, returning a byte item on success.
799 def _try_parse_byte(self
):
801 item
= self
._try
_parse
_hex
_byte
()
807 item
= self
._try
_parse
_bin
_byte
()
813 item
= self
._try
_parse
_dec
_byte
()
818 # Patterns for _try_parse_str()
819 _str_prefix_pat
= re
.compile(r
'(?:u(?P<len>16|32)(?P<bo>be|le))?\s*"')
820 _str_suffix_pat
= re
.compile(r
'"')
821 _str_str_pat
= re
.compile(r
'(?:(?:\\.)|[^"])*')
823 # Strings corresponding to escape sequence characters
824 _str_escape_seq_strs
= {
838 # Tries to parse a string, returning a string item on success.
839 def _try_parse_str(self
):
840 begin_text_loc
= self
._text
_loc
843 m
= self
._try
_parse
_pat
(self
._str
_prefix
_pat
)
852 if m
.group("len") is not None:
853 encoding
= "utf_{}_{}".format(m
.group("len"), m
.group("bo"))
856 m
= self
._expect
_pat
(self
._str
_str
_pat
, "Expecting a literal string")
858 # Expect end of string
859 self
._expect
_pat
(self
._str
_suffix
_pat
, 'Expecting `"` (end of literal string)')
861 # Replace escape sequences
864 for ec
in '0abefnrtv"\\':
865 val
= val
.replace(r
"\{}".format(ec
), self
._str
_escape
_seq
_strs
[ec
])
868 data
= val
.encode(encoding
)
871 return _Str(data
, begin_text_loc
)
873 # Common right parenthesis pattern
874 _right_paren_pat
= re
.compile(r
"\)")
876 # Patterns for _try_parse_group()
877 _group_prefix_pat
= re
.compile(r
"\(|!g(?:roup)?\b")
879 # Tries to parse a group, returning a group item on success.
880 def _try_parse_group(self
):
881 begin_text_loc
= self
._text
_loc
884 m_open
= self
._try
_parse
_pat
(self
._group
_prefix
_pat
)
891 items
= self
._parse
_items
()
893 # Expect end of group
894 self
._skip
_ws
_and
_comments
()
896 if m_open
.group(0) == "(":
897 pat
= self
._right
_paren
_pat
900 pat
= self
._block
_end
_pat
903 self
._expect
_pat
(pat
, "Expecting an item or `{}` (end of group)".format(exp
))
906 return _Group(items
, begin_text_loc
)
908 # Returns a stripped expression string and an AST expression node
909 # from the expression string `expr_str` at text location `text_loc`.
910 def _ast_expr_from_str(self
, expr_str
: str, text_loc
: TextLocation
):
911 # Create an expression node from the expression string
912 expr_str
= expr_str
.strip().replace("\n", " ")
915 expr
= ast
.parse(expr_str
, mode
="eval")
918 "Invalid expression `{}`: invalid syntax".format(expr_str
),
922 return expr_str
, expr
924 # Patterns for _try_parse_num_and_attr()
925 _val_expr_pat
= re
.compile(r
"([^}:]+):\s*")
926 _fl_num_len_attr_pat
= re
.compile(r
"8|16|24|32|40|48|56|64")
927 _leb128_int_attr_pat
= re
.compile(r
"(u|s)leb128")
929 # Tries to parse a value and attribute (fixed length in bits or
930 # `leb128`), returning a value item on success.
931 def _try_parse_num_and_attr(self
):
932 begin_text_loc
= self
._text
_loc
935 m_expr
= self
._try
_parse
_pat
(self
._val
_expr
_pat
)
941 # Create an expression node from the expression string
942 expr_str
, expr
= self
._ast
_expr
_from
_str
(m_expr
.group(1), begin_text_loc
)
945 m_attr
= self
._try
_parse
_pat
(self
._fl
_num
_len
_attr
_pat
)
949 m_attr
= self
._try
_parse
_pat
(self
._leb
128_int
_attr
_pat
)
952 # At this point it's invalid
954 "Expecting a length (multiple of eight bits), `uleb128`, or `sleb128`"
957 # Return LEB128 integer item
958 cls
= _ULeb128Int
if m_attr
.group(1) == "u" else _SLeb128Int
959 return cls(expr_str
, expr
, begin_text_loc
)
961 # Return fixed-length number item
965 int(m_attr
.group(0)),
969 # Patterns for _try_parse_var_assign()
970 _var_assign_name_equal_pat
= re
.compile(r
"({})\s*=".format(_py_name_pat
.pattern
))
971 _var_assign_expr_pat
= re
.compile(r
"[^}]+")
973 # Tries to parse a variable assignment, returning a variable
974 # assignment item on success.
975 def _try_parse_var_assign(self
):
976 begin_text_loc
= self
._text
_loc
979 m
= self
._try
_parse
_pat
(self
._var
_assign
_name
_equal
_pat
)
988 if name
== _icitte_name
:
990 "`{}` is a reserved variable name".format(_icitte_name
), begin_text_loc
993 if name
in self
._label
_names
:
994 _raise_error("Existing label named `{}`".format(name
), begin_text_loc
)
996 # Expect an expression
998 m
= self
._expect
_pat
(self
._var
_assign
_expr
_pat
, "Expecting an expression")
1000 # Create an expression node from the expression string
1001 expr_str
, expr
= self
._ast
_expr
_from
_str
(m
.group(0), begin_text_loc
)
1003 # Add to known variable names
1004 self
._var
_names
.add(name
)
1014 # Pattern for _try_parse_set_bo()
1015 _bo_pat
= re
.compile(r
"[bl]e")
1017 # Tries to parse a byte order name, returning a byte order setting
1019 def _try_parse_set_bo(self
):
1020 begin_text_loc
= self
._text
_loc
1023 m
= self
._try
_parse
_pat
(self
._bo
_pat
)
1029 # Return corresponding item
1030 if m
.group(0) == "be":
1031 return _SetBo(ByteOrder
.BE
, begin_text_loc
)
1033 assert m
.group(0) == "le"
1034 return _SetBo(ByteOrder
.LE
, begin_text_loc
)
1036 # Patterns for _try_parse_val_or_bo()
1037 _val_var_assign_set_bo_prefix_pat
= re
.compile(r
"\{")
1038 _val_var_assign_set_bo_suffix_pat
= re
.compile(r
"\}")
1040 # Tries to parse a value, a variable assignment, or a byte order
1041 # setting, returning an item on success.
1042 def _try_parse_val_or_var_assign_or_set_bo(self
):
1044 if self
._try
_parse
_pat
(self
._val
_var
_assign
_set
_bo
_prefix
_pat
) is None:
1050 # Variable assignment item?
1051 item
= self
._try
_parse
_var
_assign
()
1055 item
= self
._try
_parse
_num
_and
_attr
()
1058 # Byte order setting item?
1059 item
= self
._try
_parse
_set
_bo
()
1062 # At this point it's invalid
1064 "Expecting a fixed-length number, a variable assignment, or a byte order setting"
1069 self
._expect
_pat
(self
._val
_var
_assign
_set
_bo
_suffix
_pat
, "Expecting `}`")
1072 # Returns a normalized version (so as to be parseable by int()) of
1073 # the constant integer string `s`, possibly negative, dealing with
1076 def _norm_const_int(s
: str):
1080 if s
.startswith("-"):
1085 if pos
.startswith("0" + r
):
1101 for suf
in asm_suf_base
:
1103 s
= "{}0{}{}".format(neg
, asm_suf_base
[suf
], pos
.rstrip(suf
))
1107 # Common constant integer patterns
1108 _pos_const_int_pat
= re
.compile(
1109 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+"
1111 _const_int_pat
= re
.compile(r
"(?P<neg>-)?(?:{})".format(_pos_const_int_pat
.pattern
))
1113 # Tries to parse an offset setting value (after the initial `<`),
1114 # returning an offset item on success.
1115 def _try_parse_set_offset_val(self
):
1116 begin_text_loc
= self
._text
_loc
1119 m
= self
._try
_parse
_pat
(self
._pos
_const
_int
_pat
)
1126 return _SetOffset(int(self
._norm
_const
_int
(m
.group(0)), 0), begin_text_loc
)
1128 # Tries to parse a label name (after the initial `<`), returning a
1129 # label item on success.
1130 def _try_parse_label_name(self
):
1131 begin_text_loc
= self
._text
_loc
1134 m
= self
._try
_parse
_pat
(_py_name_pat
)
1143 if name
== _icitte_name
:
1145 "`{}` is a reserved label name".format(_icitte_name
), begin_text_loc
1148 if name
in self
._label
_names
:
1149 _raise_error("Duplicate label name `{}`".format(name
), begin_text_loc
)
1151 if name
in self
._var
_names
:
1152 _raise_error("Existing variable named `{}`".format(name
), begin_text_loc
)
1154 # Add to known label names
1155 self
._label
_names
.add(name
)
1158 return _Label(name
, begin_text_loc
)
1160 # Patterns for _try_parse_label_or_set_offset()
1161 _label_set_offset_prefix_pat
= re
.compile(r
"<")
1162 _label_set_offset_suffix_pat
= re
.compile(r
">")
1164 # Tries to parse a label or an offset setting, returning an item on
1166 def _try_parse_label_or_set_offset(self
):
1168 if self
._try
_parse
_pat
(self
._label
_set
_offset
_prefix
_pat
) is None:
1172 # Offset setting item?
1174 item
= self
._try
_parse
_set
_offset
_val
()
1178 item
= self
._try
_parse
_label
_name
()
1181 # At this point it's invalid
1182 self
._raise
_error
("Expecting a label name or an offset setting value")
1186 self
._expect
_pat
(self
._label
_set
_offset
_suffix
_pat
, "Expecting `>`")
1189 # Pattern for _parse_pad_val()
1190 _pad_val_prefix_pat
= re
.compile(r
"~")
1192 # Tries to parse a padding value, returning the padding value, or 0
1194 def _parse_pad_val(self
):
1199 if self
._try
_parse
_pat
(self
._pad
_val
_prefix
_pat
) is not None:
1201 pad_val_text_loc
= self
._text
_loc
1202 m
= self
._expect
_pat
(
1203 self
._pos
_const
_int
_pat
,
1204 "Expecting a positive constant integer (byte value)",
1208 pad_val
= int(self
._norm
_const
_int
(m
.group(0)), 0)
1212 "Invalid padding byte value {}".format(pad_val
),
1218 # Patterns for _try_parse_align_offset()
1219 _align_offset_prefix_pat
= re
.compile(r
"@")
1220 _align_offset_val_pat
= re
.compile(r
"\d+")
1222 # Tries to parse an offset alignment, returning an offset alignment
1224 def _try_parse_align_offset(self
):
1225 begin_text_loc
= self
._text
_loc
1228 if self
._try
_parse
_pat
(self
._align
_offset
_prefix
_pat
) is None:
1232 # Expect an alignment
1234 align_text_loc
= self
._text
_loc
1235 m
= self
._expect
_pat
(
1236 self
._align
_offset
_val
_pat
,
1237 "Expecting an alignment (positive multiple of eight bits)",
1240 # Validate alignment
1241 val
= int(m
.group(0))
1243 if val
<= 0 or (val
% 8) != 0:
1245 "Invalid alignment value {} (not a positive multiple of eight)".format(
1252 pad_val
= self
._parse
_pad
_val
()
1255 return _AlignOffset(val
, pad_val
, begin_text_loc
)
1257 # Patterns for _try_parse_fill_until()
1258 _fill_until_prefix_pat
= re
.compile(r
"\+")
1259 _fill_until_pad_val_prefix_pat
= re
.compile(r
"~")
1261 # Tries to parse a filling, returning a filling item on success.
1262 def _try_parse_fill_until(self
):
1263 begin_text_loc
= self
._text
_loc
1266 if self
._try
_parse
_pat
(self
._fill
_until
_prefix
_pat
) is None:
1272 expr_str
, expr
= self
._expect
_const
_int
_name
_expr
(True)
1275 pad_val
= self
._parse
_pad
_val
()
1278 return _FillUntil(expr_str
, expr
, pad_val
, begin_text_loc
)
1280 # Patterns for _expect_rep_mul_expr()
1281 _inner_expr_prefix_pat
= re
.compile(r
"\{")
1282 _inner_expr_pat
= re
.compile(r
"[^}]+")
1283 _inner_expr_suffix_pat
= re
.compile(r
"\}")
1285 # Parses a constant integer if `accept_const_int` is `True`
1286 # (possibly negative if `allow_neg` is `True`), a name, or an
1287 # expression within `{` and `}`.
1288 def _expect_const_int_name_expr(
1289 self
, accept_const_int
: bool, allow_neg
: bool = False
1291 expr_text_loc
= self
._text
_loc
1296 if accept_const_int
:
1297 m
= self
._try
_parse
_pat
(self
._const
_int
_pat
)
1301 m
= self
._try
_parse
_pat
(_py_name_pat
)
1305 if self
._try
_parse
_pat
(self
._inner
_expr
_prefix
_pat
) is None:
1306 pos_msg
= "" if allow_neg
else "positive "
1308 if accept_const_int
:
1309 mid_msg
= "a {}constant integer, a name, or `{{`".format(
1313 mid_msg
= "a name or `{`"
1315 # At this point it's invalid
1316 self
._raise
_error
("Expecting {}".format(mid_msg
))
1318 # Expect an expression
1320 expr_text_loc
= self
._text
_loc
1321 m
= self
._expect
_pat
(self
._inner
_expr
_pat
, "Expecting an expression")
1322 expr_str
= m
.group(0)
1326 self
._expect
_pat
(self
._inner
_expr
_suffix
_pat
, "Expecting `}`")
1328 expr_str
= m
.group(0)
1330 if m
.group("neg") == "-" and not allow_neg
:
1331 _raise_error("Expecting a positive constant integer", expr_text_loc
)
1333 expr_str
= self
._norm
_const
_int
(m
.group(0))
1335 return self
._ast
_expr
_from
_str
(expr_str
, expr_text_loc
)
1337 # Parses the multiplier expression of a repetition (block or
1338 # post-item) and returns the expression string and AST node.
1339 def _expect_rep_mul_expr(self
):
1340 return self
._expect
_const
_int
_name
_expr
(True)
1342 # Common block end pattern
1343 _block_end_pat
= re
.compile(r
"!end\b")
1345 # Pattern for _try_parse_rep_block()
1346 _rep_block_prefix_pat
= re
.compile(r
"!r(?:epeat)?\b")
1348 # Tries to parse a repetition block, returning a repetition item on
1350 def _try_parse_rep_block(self
):
1351 begin_text_loc
= self
._text
_loc
1354 if self
._try
_parse
_pat
(self
._rep
_block
_prefix
_pat
) is None:
1359 self
._skip
_ws
_and
_comments
()
1360 expr_str
, expr
= self
._expect
_rep
_mul
_expr
()
1363 self
._skip
_ws
_and
_comments
()
1364 items_text_loc
= self
._text
_loc
1365 items
= self
._parse
_items
()
1367 # Expect end of block
1368 self
._skip
_ws
_and
_comments
()
1370 self
._block
_end
_pat
, "Expecting an item or `!end` (end of repetition block)"
1374 return _Rep(_Group(items
, items_text_loc
), expr_str
, expr
, begin_text_loc
)
1376 # Pattern for _try_parse_cond_block()
1377 _cond_block_prefix_pat
= re
.compile(r
"!if\b")
1378 _cond_block_else_pat
= re
.compile(r
"!else\b")
1380 # Tries to parse a conditional block, returning a conditional item
1382 def _try_parse_cond_block(self
):
1383 begin_text_loc
= self
._text
_loc
1386 if self
._try
_parse
_pat
(self
._cond
_block
_prefix
_pat
) is None:
1391 self
._skip
_ws
_and
_comments
()
1392 expr_str
, expr
= self
._expect
_const
_int
_name
_expr
(False)
1394 # Parse "true" items
1395 self
._skip
_ws
_and
_comments
()
1396 true_items_text_loc
= self
._text
_loc
1397 true_items
= self
._parse
_items
()
1398 false_items
= [] # type: List[_Item]
1399 false_items_text_loc
= begin_text_loc
1402 self
._skip
_ws
_and
_comments
()
1404 if self
._try
_parse
_pat
(self
._cond
_block
_else
_pat
) is not None:
1405 # Parse "false" items
1406 self
._skip
_ws
_and
_comments
()
1407 false_items_text_loc
= self
._text
_loc
1408 false_items
= self
._parse
_items
()
1410 # Expect end of block
1412 self
._block
_end
_pat
,
1413 "Expecting an item, `!else`, or `!end` (end of conditional block)",
1418 _Group(true_items
, true_items_text_loc
),
1419 _Group(false_items
, false_items_text_loc
),
1425 # Common left parenthesis pattern
1426 _left_paren_pat
= re
.compile(r
"\(")
1428 # Patterns for _try_parse_macro_def() and _try_parse_macro_exp()
1429 _macro_params_comma_pat
= re
.compile(",")
1431 # Patterns for _try_parse_macro_def()
1432 _macro_def_prefix_pat
= re
.compile(r
"!m(?:acro)?\b")
1434 # Tries to parse a macro definition, adding it to `self._macro_defs`
1435 # and returning `True` on success.
1436 def _try_parse_macro_def(self
):
1437 begin_text_loc
= self
._text
_loc
1440 if self
._try
_parse
_pat
(self
._macro
_def
_prefix
_pat
) is None:
1446 name_text_loc
= self
._text
_loc
1447 m
= self
._expect
_pat
(_py_name_pat
, "Expecting a valid macro name")
1452 if name
in self
._macro
_defs
:
1453 _raise_error("Duplicate macro named `{}`".format(name
), name_text_loc
)
1457 self
._expect
_pat
(self
._left
_paren
_pat
, "Expecting `(`")
1459 # Try to parse comma-separated parameter names
1460 param_names
= [] # type: List[str]
1461 expect_comma
= False
1467 if self
._try
_parse
_pat
(self
._right
_paren
_pat
) is not None:
1473 self
._expect
_pat
(self
._macro
_params
_comma
_pat
, "Expecting `,`")
1475 # Expect parameter name
1477 param_text_loc
= self
._text
_loc
1478 m
= self
._expect
_pat
(_py_name_pat
, "Expecting valid parameter name")
1480 if m
.group(0) in param_names
:
1482 "Duplicate macro parameter named `{}`".format(m
.group(0)),
1486 param_names
.append(m
.group(0))
1490 self
._skip
_ws
_and
_comments
()
1491 items_text_loc
= self
._text
_loc
1492 old_var_names
= self
._var
_names
.copy()
1493 old_label_names
= self
._label
_names
.copy()
1494 self
._var
_names
= set() # type: Set[str]
1495 self
._label
_names
= set() # type: Set[str]
1496 items
= self
._parse
_items
()
1497 self
._var
_names
= old_var_names
1498 self
._label
_names
= old_label_names
1502 self
._block
_end
_pat
, "Expecting an item or `!end` (end of macro block)"
1506 self
._macro
_defs
[name
] = _MacroDef(
1507 name
, param_names
, _Group(items
, items_text_loc
), begin_text_loc
1512 # Patterns for _try_parse_macro_exp()
1513 _macro_exp_prefix_pat
= re
.compile(r
"m\b")
1514 _macro_exp_colon_pat
= re
.compile(r
":")
1516 # Tries to parse a macro expansion, returning a macro expansion item
1518 def _try_parse_macro_exp(self
):
1519 begin_text_loc
= self
._text
_loc
1522 if self
._try
_parse
_pat
(self
._macro
_exp
_prefix
_pat
) is None:
1528 self
._expect
_pat
(self
._macro
_exp
_colon
_pat
, "Expecting `:`")
1530 # Expect a macro name
1532 name_text_loc
= self
._text
_loc
1533 m
= self
._expect
_pat
(_py_name_pat
, "Expecting a valid macro name")
1537 macro_def
= self
._macro
_defs
.get(name
)
1539 if macro_def
is None:
1540 _raise_error("Unknown macro name `{}`".format(name
), name_text_loc
)
1544 self
._expect
_pat
(self
._left
_paren
_pat
, "Expecting `(`")
1546 # Try to parse comma-separated parameter values
1547 params_text_loc
= self
._text
_loc
1548 params
= [] # type: List[_MacroExpParam]
1549 expect_comma
= False
1555 if self
._try
_parse
_pat
(self
._right
_paren
_pat
) is not None:
1561 self
._expect
_pat
(self
._macro
_params
_comma
_pat
, "Expecting `,`")
1564 param_text_loc
= self
._text
_loc
1567 *self
._expect
_const
_int
_name
_expr
(True, True),
1568 text_loc
=param_text_loc
1573 # Validate parameter values
1574 if len(params
) != len(macro_def
.param_names
):
1575 sing_plur
= "" if len(params
) == 1 else "s"
1577 "Macro expansion passes {} parameter{} while the definition expects {}".format(
1578 len(params
), sing_plur
, len(macro_def
.param_names
)
1584 return _MacroExp(name
, params
, begin_text_loc
)
1586 # Tries to parse a base item (anything except a repetition),
1587 # returning it on success.
1588 def _try_parse_base_item(self
):
1590 item
= self
._try
_parse
_byte
()
1592 if item
is not None:
1596 item
= self
._try
_parse
_str
()
1598 if item
is not None:
1601 # Value, variable assignment, or byte order setting item?
1602 item
= self
._try
_parse
_val
_or
_var
_assign
_or
_set
_bo
()
1604 if item
is not None:
1607 # Label or offset setting item?
1608 item
= self
._try
_parse
_label
_or
_set
_offset
()
1610 if item
is not None:
1613 # Offset alignment item?
1614 item
= self
._try
_parse
_align
_offset
()
1616 if item
is not None:
1620 item
= self
._try
_parse
_fill
_until
()
1622 if item
is not None:
1626 item
= self
._try
_parse
_group
()
1628 if item
is not None:
1631 # Repetition block item?
1632 item
= self
._try
_parse
_rep
_block
()
1634 if item
is not None:
1637 # Conditional block item?
1638 item
= self
._try
_parse
_cond
_block
()
1640 if item
is not None:
1644 item
= self
._try
_parse
_macro
_exp
()
1646 if item
is not None:
1649 # Pattern for _try_parse_rep_post()
1650 _rep_post_prefix_pat
= re
.compile(r
"\*")
1652 # Tries to parse a post-item repetition, returning the expression
1653 # string and AST expression node on success.
1654 def _try_parse_rep_post(self
):
1656 if self
._try
_parse
_pat
(self
._rep
_post
_prefix
_pat
) is None:
1660 # Return expression string and AST expression
1661 self
._skip
_ws
_and
_comments
()
1662 return self
._expect
_rep
_mul
_expr
()
1664 # Tries to parse an item, possibly followed by a repetition,
1665 # returning `True` on success.
1667 # Appends any parsed item to `items`.
1668 def _try_append_item(self
, items
: List
[_Item
]):
1669 self
._skip
_ws
_and
_comments
()
1672 item
= self
._try
_parse
_base
_item
()
1677 # Parse repetition if the base item is repeatable
1678 if isinstance(item
, _RepableItem
):
1679 self
._skip
_ws
_and
_comments
()
1680 rep_text_loc
= self
._text
_loc
1681 rep_ret
= self
._try
_parse
_rep
_post
()
1683 if rep_ret
is not None:
1684 item
= _Rep(item
, *rep_ret
, text_loc
=rep_text_loc
)
1689 # Parses and returns items, skipping whitespaces, insignificant
1690 # symbols, and comments when allowed, and stopping at the first
1691 # unknown character.
1693 # Accepts and registers macro definitions if `accept_macro_defs`
1695 def _parse_items(self
, accept_macro_defs
: bool = False) -> List
[_Item
]:
1696 items
= [] # type: List[_Item]
1698 while self
._isnt
_done
():
1699 # Try to append item
1700 if not self
._try
_append
_item
(items
):
1701 if accept_macro_defs
and self
._try
_parse
_macro
_def
():
1704 # Unknown at this point
1709 # Parses the whole Normand input, setting `self._res` to the main
1710 # group item on success.
1712 if len(self
._normand
.strip()) == 0:
1713 # Special case to make sure there's something to consume
1714 self
._res
= _Group([], self
._text
_loc
)
1717 # Parse first level items
1718 items
= self
._parse
_items
(True)
1720 # Make sure there's nothing left
1721 self
._skip
_ws
_and
_comments
()
1723 if self
._isnt
_done
():
1725 "Unexpected character `{}`".format(self
._normand
[self
._at
])
1728 # Set main group item
1729 self
._res
= _Group(items
, self
._text
_loc
)
1732 # The return type of parse().
1738 variables
: VariablesT
,
1741 bo
: Optional
[ByteOrder
],
1743 self
= cls
.__new
__(cls
)
1744 self
._init
(data
, variables
, labels
, offset
, bo
)
1747 def __init__(self
, *args
, **kwargs
): # type: ignore
1748 raise NotImplementedError
1753 variables
: VariablesT
,
1756 bo
: Optional
[ByteOrder
],
1759 self
._vars
= variables
1760 self
._labels
= labels
1761 self
._offset
= offset
1769 # Dictionary of updated variable names to their last computed value.
1771 def variables(self
):
1774 # Dictionary of updated main group label names to their computed
1785 # Updated byte order.
1787 def byte_order(self
):
1791 # Raises a parse error for the item `item`, creating it using the
1793 def _raise_error_for_item(msg
: str, item
: _Item
) -> NoReturn
:
1794 _raise_error(msg
, item
.text_loc
)
1797 # The `ICITTE` reserved name.
1798 _icitte_name
= "ICITTE"
1801 # Base node visitor.
1803 # Calls the _visit_name() method for each name node which isn't the name
1805 class _NodeVisitor(ast
.NodeVisitor
):
1807 self
._parent
_is
_call
= False
1809 def generic_visit(self
, node
: ast
.AST
):
1810 if type(node
) is ast
.Call
:
1811 self
._parent
_is
_call
= True
1812 elif type(node
) is ast
.Name
and not self
._parent
_is
_call
:
1813 self
._visit
_name
(node
.id)
1815 super().generic_visit(node
)
1816 self
._parent
_is
_call
= False
1819 def _visit_name(self
, name
: str):
1823 # Expression validator: validates that all the names within the
1824 # expression are allowed.
1825 class _ExprValidator(_NodeVisitor
):
1826 def __init__(self
, expr_str
: str, text_loc
: TextLocation
, allowed_names
: Set
[str]):
1828 self
._expr
_str
= expr_str
1829 self
._text
_loc
= text_loc
1830 self
._allowed
_names
= allowed_names
1832 def _visit_name(self
, name
: str):
1833 # Make sure the name refers to a known and reachable
1834 # variable/label name.
1835 if name
!= _icitte_name
and name
not in self
._allowed
_names
:
1836 msg
= "Illegal (unknown or unreachable) variable/label name `{}` in expression `{}`".format(
1837 name
, self
._expr
_str
1840 allowed_names
= self
._allowed
_names
.copy()
1841 allowed_names
.add(_icitte_name
)
1843 if len(allowed_names
) > 0:
1844 allowed_names_str
= ", ".join(
1845 sorted(["`{}`".format(name
) for name
in allowed_names
])
1847 msg
+= "; the legal names are {{{}}}".format(allowed_names_str
)
1859 variables
: VariablesT
,
1862 bo
: Optional
[ByteOrder
],
1864 self
.variables
= variables
.copy()
1865 self
.labels
= labels
.copy()
1866 self
.offset
= offset
1870 return "_GenState({}, {}, {}, {})".format(
1871 repr(self
.variables
), repr(self
.labels
), repr(self
.offset
), repr(self
.bo
)
1875 # Fixed-length number item instance.
1876 class _FlNumItemInst
:
1880 offset_in_data
: int,
1882 parse_error_msgs
: List
[ParseErrorMessage
],
1885 self
._offset
_in
_data
= offset_in_data
1887 self
._parse
_error
_msgs
= parse_error_msgs
1894 def offset_in_data(self
):
1895 return self
._offset
_in
_data
1902 def parse_error_msgs(self
):
1903 return self
._parse
_error
_msgs
1906 # Generator of data and final state from a group item.
1908 # Generation happens in memory at construction time. After building, use
1909 # the `data`, `variables`, `labels`, `offset`, and `bo` properties to
1910 # get the resulting context.
1912 # The steps of generation are:
1914 # 1. Handle each item in prefix order.
1916 # The handlers append bytes to `self._data` and update some current
1917 # state object (`_GenState` instance).
1919 # When handling a fixed-length number item, try to evaluate its
1920 # expression using the current state. If this fails, then it might be
1921 # because the expression refers to a "future" label: save the current
1922 # offset in `self._data` (generated data) and a snapshot of the
1923 # current state within `self._fl_num_item_insts` (`_FlNumItemInst`
1924 # object). _gen_fl_num_item_insts() will deal with this later. A
1925 # `_FlNumItemInst` instance also contains a snapshot of the current
1926 # parsing error messages (`self._parse_error_msgs`) which need to be
1927 # taken into account when handling the instance later.
1929 # When handling the items of a group, keep a map of immediate label
1930 # names to their offset. Then, after having processed all the items,
1931 # update the relevant saved state snapshots in
1932 # `self._fl_num_item_insts` with those immediate label values.
1933 # _gen_fl_num_item_insts() will deal with this later.
1935 # 2. Handle all the fixed-length number item instances of which the
1936 # expression evaluation failed before.
1938 # At this point, `self._fl_num_item_insts` contains everything that's
1939 # needed to evaluate the expressions, including the values of
1940 # "future" labels from the point of view of some fixed-length number
1943 # If an evaluation fails at this point, then it's a user error. Add
1944 # to the parsing error all the saved parsing error messages of the
1945 # instance. Those additional messages add precious context to the
1951 macro_defs
: _MacroDefsT
,
1952 variables
: VariablesT
,
1955 bo
: Optional
[ByteOrder
],
1957 self
._macro
_defs
= macro_defs
1958 self
._fl
_num
_item
_insts
= [] # type: List[_FlNumItemInst]
1959 self
._parse
_error
_msgs
= [] # type: List[ParseErrorMessage]
1960 self
._gen
(group
, _GenState(variables
, labels
, offset
, bo
))
1967 # Updated variables.
1969 def variables(self
):
1970 return self
._final
_state
.variables
1972 # Updated main group labels.
1975 return self
._final
_state
.labels
1980 return self
._final
_state
.offset
1982 # Updated byte order.
1985 return self
._final
_state
.bo
1987 # Evaluates the expression `expr` of which the original string is
1988 # `expr_str` at the location `text_loc` considering the current
1989 # generation state `state`.
1991 # If `allow_float` is `True`, then the type of the result may be
1996 expr
: ast
.Expression
,
1997 text_loc
: TextLocation
,
1999 allow_float
: bool = False,
2001 syms
= {} # type: VariablesT
2002 syms
.update(state
.labels
)
2004 # Set the `ICITTE` name to the current offset
2005 syms
[_icitte_name
] = state
.offset
2007 # Add the current variables
2008 syms
.update(state
.variables
)
2010 # Validate the node and its children
2011 _ExprValidator(expr_str
, text_loc
, set(syms
.keys())).visit(expr
)
2013 # Compile and evaluate expression node
2015 val
= eval(compile(expr
, "", "eval"), None, syms
)
2016 except Exception as exc
:
2018 "Failed to evaluate expression `{}`: {}".format(expr_str
, exc
),
2022 # Convert `bool` result type to `int` to normalize
2023 if type(val
) is bool:
2026 # Validate result type
2027 expected_types
= {int}
# type: Set[type]
2031 expected_types
.add(float)
2032 type_msg
+= " or `float`"
2034 if type(val
) not in expected_types
:
2036 "Invalid expression `{}`: expecting result type {}, not `{}`".format(
2037 expr_str
, type_msg
, type(val
).__name
__
2044 # Evaluates the expression of `item` considering the current
2045 # generation state `state`.
2047 # If `allow_float` is `True`, then the type of the result may be
2050 def _eval_item_expr(
2051 item
: Union
[_FlNum
, _Leb128Int
, _FillUntil
, _VarAssign
, _Rep
, _Cond
],
2053 allow_float
: bool = False,
2055 return _Gen
._eval
_expr
(
2056 item
.expr_str
, item
.expr
, item
.text_loc
, state
, allow_float
2059 # Handles the byte item `item`.
2060 def _handle_byte_item(self
, item
: _Byte
, state
: _GenState
):
2061 self
._data
.append(item
.val
)
2062 state
.offset
+= item
.size
2064 # Handles the string item `item`.
2065 def _handle_str_item(self
, item
: _Str
, state
: _GenState
):
2066 self
._data
+= item
.data
2067 state
.offset
+= item
.size
2069 # Handles the byte order setting item `item`.
2070 def _handle_set_bo_item(self
, item
: _SetBo
, state
: _GenState
):
2071 # Update current byte order
2074 # Handles the variable assignment item `item`.
2075 def _handle_var_assign_item(self
, item
: _VarAssign
, state
: _GenState
):
2077 state
.variables
[item
.name
] = self
._eval
_item
_expr
(item
, state
, True)
2079 # Handles the fixed-length number item `item`.
2080 def _handle_fl_num_item(self
, item
: _FlNum
, state
: _GenState
):
2081 # Validate current byte order
2082 if state
.bo
is None and item
.len > 8:
2083 _raise_error_for_item(
2084 "Current byte order isn't defined at first fixed-length number (`{}`) to encode on more than 8 bits".format(
2090 # Try an immediate evaluation. If it fails, then keep everything
2091 # needed to (try to) generate the bytes of this item later.
2093 data
= self
._gen
_fl
_num
_item
_inst
_data
(item
, state
)
2095 self
._fl
_num
_item
_insts
.append(
2099 copy
.deepcopy(state
),
2100 copy
.deepcopy(self
._parse
_error
_msgs
),
2104 # Reserve space in `self._data` for this instance
2105 data
= bytes([0] * (item
.len // 8))
2111 state
.offset
+= len(data
)
2113 # Returns the size, in bytes, required to encode the value `val`
2114 # with LEB128 (signed version if `is_signed` is `True`).
2116 def _leb128_size_for_val(val
: int, is_signed
: bool):
2118 # Equivalent upper bound.
2120 # For example, if `val` is -128, then the full integer for
2121 # this number of bits would be [-128, 127].
2124 # Number of bits (add one for the sign if needed)
2125 bits
= val
.bit_length() + int(is_signed
)
2130 # Seven bits per byte
2131 return math
.ceil(bits
/ 7)
2133 # Handles the LEB128 integer item `item`.
2134 def _handle_leb128_int_item(self
, item
: _Leb128Int
, state
: _GenState
):
2136 val
= self
._eval
_item
_expr
(item
, state
, False)
2139 size
= self
._leb
128_size
_for
_val
(val
, type(item
) is _SLeb128Int
)
2142 for _
in range(size
):
2143 # Seven LSBs, MSB of the byte set (continue)
2144 self
._data
.append((val
& 0x7F) |
0x80)
2147 # Clear MSB of last byte (stop)
2148 self
._data
[-1] &= ~
0x80
2151 state
.offset
+= size
2153 # Handles the group item `item`, removing the immediate labels from
2154 # `state` at the end if `remove_immediate_labels` is `True`.
2155 def _handle_group_item(
2156 self
, item
: _Group
, state
: _GenState
, remove_immediate_labels
: bool = True
2158 first_fl_num_item_inst_index
= len(self
._fl
_num
_item
_insts
)
2159 immediate_labels
= {} # type: LabelsT
2162 for subitem
in item
.items
:
2163 if type(subitem
) is _Label
:
2164 # Add to local immediate labels
2165 immediate_labels
[subitem
.name
] = state
.offset
2167 self
._handle
_item
(subitem
, state
)
2169 # Remove immediate labels from current state if needed
2170 if remove_immediate_labels
:
2171 for name
in immediate_labels
:
2172 del state
.labels
[name
]
2174 # Add all immediate labels to all state snapshots since
2175 # `first_fl_num_item_inst_index`.
2176 for inst
in self
._fl
_num
_item
_insts
[first_fl_num_item_inst_index
:]:
2177 inst
.state
.labels
.update(immediate_labels
)
2179 # Handles the repetition item `item`.
2180 def _handle_rep_item(self
, item
: _Rep
, state
: _GenState
):
2181 # Compute the repetition count
2182 mul
= _Gen
._eval
_item
_expr
(item
, state
)
2186 _raise_error_for_item(
2187 "Invalid expression `{}`: unexpected negative result {:,}".format(
2193 # Generate item data `mul` times
2194 for _
in range(mul
):
2195 self
._handle
_item
(item
.item
, state
)
2197 # Handles the conditional item `item`.
2198 def _handle_cond_item(self
, item
: _Cond
, state
: _GenState
):
2199 # Compute the conditional value
2200 val
= _Gen
._eval
_item
_expr
(item
, state
)
2202 # Generate item data if needed
2204 self
._handle
_item
(item
.true_item
, state
)
2206 self
._handle
_item
(item
.false_item
, state
)
2208 # Evaluates the parameters of the macro expansion item `item`
2209 # considering the initial state `init_state` and returns a new state
2210 # to handle the items of the macro.
2211 def _eval_macro_exp_params(self
, item
: _MacroExp
, init_state
: _GenState
):
2213 exp_state
= _GenState({}, {}, init_state
.offset
, init_state
.bo
)
2215 # Evaluate the parameter expressions
2216 macro_def
= self
._macro
_defs
[item
.name
]
2218 for param_name
, param
in zip(macro_def
.param_names
, item
.params
):
2219 exp_state
.variables
[param_name
] = _Gen
._eval
_expr
(
2220 param
.expr_str
, param
.expr
, param
.text_loc
, init_state
, True
2225 # Handles the macro expansion item `item`.
2226 def _handle_macro_exp_item(self
, item
: _MacroExp
, state
: _GenState
):
2227 parse_error_msg_text
= "While expanding the macro `{}`:".format(item
.name
)
2231 exp_state
= self
._eval
_macro
_exp
_params
(item
, state
)
2233 # Process the contained group
2234 init_data_size
= len(self
._data
)
2236 ParseErrorMessage
._create
( # pyright: ignore[reportPrivateUsage]
2237 parse_error_msg_text
, item
.text_loc
2240 self
._parse
_error
_msgs
.append(parse_error_msg
)
2241 self
._handle
_item
(self
._macro
_defs
[item
.name
].group
, exp_state
)
2242 self
._parse
_error
_msgs
.pop()
2243 except ParseError
as exc
:
2244 _augment_error(exc
, parse_error_msg_text
, item
.text_loc
)
2246 # Update state offset and return
2247 state
.offset
+= len(self
._data
) - init_data_size
2249 # Handles the offset setting item `item`.
2250 def _handle_set_offset_item(self
, item
: _SetOffset
, state
: _GenState
):
2251 state
.offset
= item
.val
2253 # Handles the offset alignment item `item` (adds padding).
2254 def _handle_align_offset_item(self
, item
: _AlignOffset
, state
: _GenState
):
2255 init_offset
= state
.offset
2256 align_bytes
= item
.val
// 8
2257 state
.offset
= (state
.offset
+ align_bytes
- 1) // align_bytes
* align_bytes
2258 self
._data
+= bytes([item
.pad_val
] * (state
.offset
- init_offset
))
2260 # Handles the filling item `item` (adds padding).
2261 def _handle_fill_until_item(self
, item
: _FillUntil
, state
: _GenState
):
2262 # Compute the new offset
2263 new_offset
= _Gen
._eval
_item
_expr
(item
, state
)
2265 # Validate the new offset
2266 if new_offset
< state
.offset
:
2267 _raise_error_for_item(
2268 "Invalid expression `{}`: new offset {:,} is less than current offset {:,}".format(
2269 item
.expr_str
, new_offset
, state
.offset
2275 self
._data
+= bytes([item
.pad_val
] * (new_offset
- state
.offset
))
2278 state
.offset
= new_offset
2280 # Handles the label item `item`.
2281 def _handle_label_item(self
, item
: _Label
, state
: _GenState
):
2282 state
.labels
[item
.name
] = state
.offset
2284 # Handles the item `item`, returning the updated next repetition
2286 def _handle_item(self
, item
: _Item
, state
: _GenState
):
2287 return self
._item
_handlers
[type(item
)](item
, state
)
2289 # Generates the data for a fixed-length integer item instance having
2290 # the value `val` and returns it.
2291 def _gen_fl_int_item_inst_data(self
, val
: int, item
: _FlNum
, state
: _GenState
):
2293 if val
< -(2 ** (item
.len - 1)) or val
> 2**item
.len - 1:
2294 _raise_error_for_item(
2295 "Value {:,} is outside the {}-bit range when evaluating expression `{}`".format(
2296 val
, item
.len, item
.expr_str
2301 # Encode result on 64 bits (to extend the sign bit whatever the
2302 # value of `item.len`).
2305 ">" if state
.bo
in (None, ByteOrder
.BE
) else "<",
2306 "Q" if val
>= 0 else "q",
2311 # Keep only the requested length
2312 len_bytes
= item
.len // 8
2314 if state
.bo
in (None, ByteOrder
.BE
):
2315 # Big endian: keep last bytes
2316 data
= data
[-len_bytes
:]
2318 # Little endian: keep first bytes
2319 assert state
.bo
== ByteOrder
.LE
2320 data
= data
[:len_bytes
]
2325 # Generates the data for a fixed-length floating point number item
2326 # instance having the value `val` and returns it.
2327 def _gen_fl_float_item_inst_data(self
, val
: float, item
: _FlNum
, state
: _GenState
):
2329 if item
.len not in (32, 64):
2330 _raise_error_for_item(
2331 "Invalid {}-bit length for a fixed-length floating point number (value {:,})".format(
2337 # Encode and return result
2340 ">" if state
.bo
in (None, ByteOrder
.BE
) else "<",
2341 "f" if item
.len == 32 else "d",
2346 # Generates the data for a fixed-length number item instance and
2348 def _gen_fl_num_item_inst_data(self
, item
: _FlNum
, state
: _GenState
):
2350 val
= self
._eval
_item
_expr
(item
, state
, True)
2352 # Handle depending on type
2353 if type(val
) is int:
2354 return self
._gen
_fl
_int
_item
_inst
_data
(val
, item
, state
)
2356 assert type(val
) is float
2357 return self
._gen
_fl
_float
_item
_inst
_data
(val
, item
, state
)
2359 # Generates the data for all the fixed-length number item instances
2360 # and writes it at the correct offset within `self._data`.
2361 def _gen_fl_num_item_insts(self
):
2362 for inst
in self
._fl
_num
_item
_insts
:
2365 data
= self
._gen
_fl
_num
_item
_inst
_data
(inst
.item
, inst
.state
)
2366 except ParseError
as exc
:
2367 # Add all the saved parse error messages for this
2369 for msg
in reversed(inst
.parse_error_msgs
):
2370 _add_error_msg(exc
, msg
.text
, msg
.text_location
)
2374 # Insert bytes into `self._data`
2375 self
._data
[inst
.offset_in_data
: inst
.offset_in_data
+ len(data
)] = data
2377 # Generates the data (`self._data`) and final state
2378 # (`self._final_state`) from `group` and the initial state `state`.
2379 def _gen(self
, group
: _Group
, state
: _GenState
):
2381 self
._data
= bytearray()
2384 self
._item
_handlers
= {
2385 _AlignOffset
: self
._handle
_align
_offset
_item
,
2386 _Byte
: self
._handle
_byte
_item
,
2387 _Cond
: self
._handle
_cond
_item
,
2388 _FillUntil
: self
._handle
_fill
_until
_item
,
2389 _FlNum
: self
._handle
_fl
_num
_item
,
2390 _Group
: self
._handle
_group
_item
,
2391 _Label
: self
._handle
_label
_item
,
2392 _MacroExp
: self
._handle
_macro
_exp
_item
,
2393 _Rep
: self
._handle
_rep
_item
,
2394 _SetBo
: self
._handle
_set
_bo
_item
,
2395 _SetOffset
: self
._handle
_set
_offset
_item
,
2396 _SLeb128Int
: self
._handle
_leb
128_int
_item
,
2397 _Str
: self
._handle
_str
_item
,
2398 _ULeb128Int
: self
._handle
_leb
128_int
_item
,
2399 _VarAssign
: self
._handle
_var
_assign
_item
,
2400 } # type: Dict[type, Callable[[Any, _GenState], None]]
2402 # Handle the group item, _not_ removing the immediate labels
2403 # because the `labels` property offers them.
2404 self
._handle
_group
_item
(group
, state
, False)
2406 # This is actually the final state
2407 self
._final
_state
= state
2409 # Generate all the fixed-length number bytes now that we know
2411 self
._gen
_fl
_num
_item
_insts
()
2414 # Returns a `ParseResult` instance containing the bytes encoded by the
2415 # input string `normand`.
2417 # `init_variables` is a dictionary of initial variable names (valid
2418 # Python names) to integral values. A variable name must not be the
2419 # reserved name `ICITTE`.
2421 # `init_labels` is a dictionary of initial label names (valid Python
2422 # names) to integral values. A label name must not be the reserved name
2425 # `init_offset` is the initial offset.
2427 # `init_byte_order` is the initial byte order.
2429 # Raises `ParseError` on any parsing error.
2432 init_variables
: Optional
[VariablesT
] = None,
2433 init_labels
: Optional
[LabelsT
] = None,
2434 init_offset
: int = 0,
2435 init_byte_order
: Optional
[ByteOrder
] = None,
2437 if init_variables
is None:
2440 if init_labels
is None:
2443 parser
= _Parser(normand
, init_variables
, init_labels
)
2452 return ParseResult
._create
( # pyright: ignore[reportPrivateUsage]
2453 gen
.data
, gen
.variables
, gen
.labels
, gen
.offset
, gen
.bo
2457 # Raises a command-line error with the message `msg`.
2458 def _raise_cli_error(msg
: str) -> NoReturn
:
2459 raise RuntimeError("Command-line error: {}".format(msg
))
2462 # Returns a dictionary of string to integers from the list of strings
2463 # `args` containing `NAME=VAL` entries.
2464 def _dict_from_arg(args
: Optional
[List
[str]]):
2465 d
= {} # type: LabelsT
2471 m
= re
.match(r
"({})=(\d+)$".format(_py_name_pat
.pattern
), arg
)
2474 _raise_cli_error("Invalid assignment {}".format(arg
))
2476 d
[m
.group(1)] = int(m
.group(2))
2481 # Parses the command-line arguments and returns, in this order:
2483 # 1. The input file path, or `None` if none.
2484 # 2. The Normand input text.
2485 # 3. The initial offset.
2486 # 4. The initial byte order.
2487 # 5. The initial variables.
2488 # 6. The initial labels.
2489 def _parse_cli_args():
2493 ap
= argparse
.ArgumentParser()
2500 help="initial offset (positive)",
2506 choices
=["be", "le"],
2508 help="initial byte order (`be` or `le`)",
2514 help="add an initial variable (may be repeated)",
2521 help="add an initial label (may be repeated)",
2524 "--version", action
="version", version
="Normand {}".format(__version__
)
2531 help="input path (none means standard input)",
2535 args
= ap
.parse_args()
2538 if args
.path
is None:
2539 normand
= sys
.stdin
.read()
2541 with
open(args
.path
) as f
:
2544 # Variables and labels
2545 variables
= typing
.cast(VariablesT
, _dict_from_arg(args
.var
))
2546 labels
= _dict_from_arg(args
.label
)
2550 _raise_cli_error("Invalid negative offset {}")
2552 # Validate and set byte order
2553 bo
= None # type: Optional[ByteOrder]
2555 if args
.byte_order
is not None:
2556 if args
.byte_order
== "be":
2559 assert args
.byte_order
== "le"
2562 # Return input and initial state
2563 return args
.path
, normand
, args
.offset
, bo
, variables
, labels
2566 # CLI entry point without exception handling.
2567 def _run_cli_with_args(
2570 bo
: Optional
[ByteOrder
],
2571 variables
: VariablesT
,
2574 sys
.stdout
.buffer.write(parse(normand
, variables
, labels
, offset
, bo
).data
)
2577 # Prints the exception message `msg` and exits with status 1.
2578 def _fail(msg
: str) -> NoReturn
:
2579 if not msg
.endswith("."):
2582 print(msg
.strip(), file=sys
.stderr
)
2589 args
= _parse_cli_args()
2590 except Exception as exc
:
2594 _run_cli_with_args(*args
[1:])
2595 except ParseError
as exc
:
2598 prefix
= "" if args
[0] is None else "{}:".format(os
.path
.abspath(args
[0]))
2601 for msg
in reversed(exc
.messages
):
2602 fail_msg
+= "{}{}:{} - {}".format(
2604 msg
.text_location
.line_no
,
2605 msg
.text_location
.col_no
,
2609 if fail_msg
[-1] not in ".:;":
2614 _fail(fail_msg
.strip())
2615 except Exception as exc
:
2619 if __name__
== "__main__":