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.12.0"
55 from typing
import Any
, Set
, Dict
, List
, Union
, Pattern
, Callable
, NoReturn
, Optional
58 # Text location (line and column numbers).
61 def _create(cls
, line_no
: int, col_no
: int):
62 self
= cls
.__new
__(cls
)
63 self
._init
(line_no
, col_no
)
66 def __init__(*args
, **kwargs
): # type: ignore
67 raise NotImplementedError
69 def _init(self
, line_no
: int, col_no
: int):
70 self
._line
_no
= line_no
84 return "TextLocation({}, {})".format(self
._line
_no
, self
._col
_no
)
89 def __init__(self
, text_loc
: TextLocation
):
90 self
._text
_loc
= text_loc
92 # Source text location.
99 class _ScalarItem(_Item
):
100 # Returns the size, in bytes, of this item.
103 def size(self
) -> int:
113 class _Byte(_ScalarItem
, _RepableItem
):
114 def __init__(self
, val
: int, text_loc
: TextLocation
):
115 super().__init
__(text_loc
)
128 return "_Byte({}, {})".format(hex(self
._val
), repr(self
._text
_loc
))
132 class _Str(_ScalarItem
, _RepableItem
):
133 def __init__(self
, data
: bytes
, text_loc
: TextLocation
):
134 super().__init
__(text_loc
)
144 return len(self
._data
)
147 return "_Str({}, {})".format(repr(self
._data
), repr(self
._text
_loc
))
152 class ByteOrder(enum
.Enum
):
160 # Byte order setting.
162 def __init__(self
, bo
: ByteOrder
, text_loc
: TextLocation
):
163 super().__init
__(text_loc
)
171 return "_SetBo({}, {})".format(repr(self
._bo
), repr(self
._text
_loc
))
176 def __init__(self
, name
: str, text_loc
: TextLocation
):
177 super().__init
__(text_loc
)
186 return "_Label({}, {})".format(repr(self
._name
), repr(self
._text
_loc
))
190 class _SetOffset(_Item
):
191 def __init__(self
, val
: int, text_loc
: TextLocation
):
192 super().__init
__(text_loc
)
195 # Offset value (bytes).
201 return "_SetOffset({}, {})".format(repr(self
._val
), repr(self
._text
_loc
))
205 class _AlignOffset(_Item
):
206 def __init__(self
, val
: int, pad_val
: int, text_loc
: TextLocation
):
207 super().__init
__(text_loc
)
209 self
._pad
_val
= pad_val
211 # Alignment value (bits).
216 # Padding byte value.
222 return "_AlignOffset({}, {}, {})".format(
223 repr(self
._val
), repr(self
._pad
_val
), repr(self
._text
_loc
)
227 # Mixin of containing an AST expression and its string.
229 def __init__(self
, expr_str
: str, expr
: ast
.Expression
):
230 self
._expr
_str
= expr_str
236 return self
._expr
_str
238 # Expression node to evaluate.
244 # Fill until some offset.
245 class _FillUntil(_Item
, _ExprMixin
):
247 self
, expr_str
: str, expr
: ast
.Expression
, pad_val
: int, text_loc
: TextLocation
249 super().__init
__(text_loc
)
250 _ExprMixin
.__init
__(self
, expr_str
, expr
)
251 self
._pad
_val
= pad_val
253 # Padding byte value.
259 return "_FillUntil({}, {}, {}, {})".format(
260 repr(self
._expr
_str
),
263 repr(self
._text
_loc
),
267 # Variable assignment.
268 class _VarAssign(_Item
, _ExprMixin
):
270 self
, name
: str, expr_str
: str, expr
: ast
.Expression
, text_loc
: TextLocation
272 super().__init
__(text_loc
)
273 _ExprMixin
.__init
__(self
, expr_str
, expr
)
282 return "_VarAssign({}, {}, {}, {})".format(
284 repr(self
._expr
_str
),
286 repr(self
._text
_loc
),
290 # Fixed-length number, possibly needing more than one byte.
291 class _FlNum(_ScalarItem
, _RepableItem
, _ExprMixin
):
293 self
, expr_str
: str, expr
: ast
.Expression
, len: int, text_loc
: TextLocation
295 super().__init
__(text_loc
)
296 _ExprMixin
.__init
__(self
, expr_str
, expr
)
306 return self
._len
// 8
309 return "_FlNum({}, {}, {}, {})".format(
310 repr(self
._expr
_str
),
313 repr(self
._text
_loc
),
318 class _Leb128Int(_Item
, _RepableItem
, _ExprMixin
):
319 def __init__(self
, expr_str
: str, expr
: ast
.Expression
, text_loc
: TextLocation
):
320 super().__init
__(text_loc
)
321 _ExprMixin
.__init
__(self
, expr_str
, expr
)
324 return "{}({}, {}, {})".format(
325 self
.__class
__.__name
__,
326 repr(self
._expr
_str
),
328 repr(self
._text
_loc
),
332 # Unsigned LEB128 integer.
333 class _ULeb128Int(_Leb128Int
, _RepableItem
, _ExprMixin
):
337 # Signed LEB128 integer.
338 class _SLeb128Int(_Leb128Int
, _RepableItem
, _ExprMixin
):
343 class _Group(_Item
, _RepableItem
):
344 def __init__(self
, items
: List
[_Item
], text_loc
: TextLocation
):
345 super().__init
__(text_loc
)
354 return "_Group({}, {})".format(repr(self
._items
), repr(self
._text
_loc
))
358 class _Rep(_Item
, _ExprMixin
):
360 self
, item
: _Item
, expr_str
: str, expr
: ast
.Expression
, text_loc
: TextLocation
362 super().__init
__(text_loc
)
363 _ExprMixin
.__init
__(self
, expr_str
, expr
)
372 return "_Rep({}, {}, {}, {})".format(
374 repr(self
._expr
_str
),
376 repr(self
._text
_loc
),
381 class _Cond(_Item
, _ExprMixin
):
383 self
, item
: _Item
, expr_str
: str, expr
: ast
.Expression
, text_loc
: TextLocation
385 super().__init
__(text_loc
)
386 _ExprMixin
.__init
__(self
, expr_str
, expr
)
395 return "_Cond({}, {}, {}, {})".format(
397 repr(self
._expr
_str
),
399 repr(self
._text
_loc
),
403 # Macro definition item.
404 class _MacroDef(_Item
):
406 self
, name
: str, param_names
: List
[str], group
: _Group
, text_loc
: TextLocation
408 super().__init
__(text_loc
)
410 self
._param
_names
= param_names
420 def param_names(self
):
421 return self
._param
_names
429 return "_MacroDef({}, {}, {}, {})".format(
431 repr(self
._param
_names
),
433 repr(self
._text
_loc
),
437 # Macro expansion parameter.
438 class _MacroExpParam
:
439 def __init__(self
, expr_str
: str, expr
: ast
.Expression
, text_loc
: TextLocation
):
440 self
._expr
_str
= expr_str
442 self
._text
_loc
= text_loc
447 return self
._expr
_str
454 # Source text location.
457 return self
._text
_loc
460 return "_MacroExpParam({}, {}, {})".format(
461 repr(self
._expr
_str
), repr(self
._expr
), repr(self
._text
_loc
)
465 # Macro expansion item.
466 class _MacroExp(_Item
, _RepableItem
):
470 params
: List
[_MacroExpParam
],
471 text_loc
: TextLocation
,
473 super().__init
__(text_loc
)
475 self
._params
= params
488 return "_MacroExp({}, {}, {})".format(
491 repr(self
._text
_loc
),
495 # A parsing error containing a message and a text location.
496 class ParseError(RuntimeError):
498 def _create(cls
, msg
: str, text_loc
: TextLocation
):
499 self
= cls
.__new
__(cls
)
500 self
._init
(msg
, text_loc
)
503 def __init__(self
, *args
, **kwargs
): # type: ignore
504 raise NotImplementedError
506 def _init(self
, msg
: str, text_loc
: TextLocation
):
507 super().__init
__(msg
)
508 self
._text
_loc
= text_loc
510 # Source text location.
513 return self
._text
_loc
516 # Raises a parsing error, forwarding the parameters to the constructor.
517 def _raise_error(msg
: str, text_loc
: TextLocation
) -> NoReturn
:
518 raise ParseError
._create
(msg
, text_loc
) # pyright: ignore[reportPrivateUsage]
521 # Variables dictionary type (for type hints).
522 VariablesT
= Dict
[str, Union
[int, float]]
525 # Labels dictionary type (for type hints).
526 LabelsT
= Dict
[str, int]
529 # Python name pattern.
530 _py_name_pat
= re
.compile(r
"[a-zA-Z_][a-zA-Z0-9_]*")
533 # Macro definition dictionary.
534 _MacroDefsT
= Dict
[str, _MacroDef
]
539 # The constructor accepts a Normand input. After building, use the `res`
540 # property to get the resulting main group.
542 # Builds a parser to parse the Normand input `normand`, parsing
544 def __init__(self
, normand
: str, variables
: VariablesT
, labels
: LabelsT
):
545 self
._normand
= normand
549 self
._label
_names
= set(labels
.keys())
550 self
._var
_names
= set(variables
.keys())
551 self
._macro
_defs
= {} # type: _MacroDefsT
554 # Result (main group).
561 def macro_defs(self
):
562 return self
._macro
_defs
564 # Current text location.
567 return TextLocation
._create
( # pyright: ignore[reportPrivateUsage]
568 self
._line
_no
, self
._col
_no
571 # Returns `True` if this parser is done parsing.
573 return self
._at
== len(self
._normand
)
575 # Returns `True` if this parser isn't done parsing.
576 def _isnt_done(self
):
577 return not self
._is
_done
()
579 # Raises a parse error, creating it using the message `msg` and the
580 # current text location.
581 def _raise_error(self
, msg
: str) -> NoReturn
:
582 _raise_error(msg
, self
._text
_loc
)
584 # Tries to make the pattern `pat` match the current substring,
585 # returning the match object and updating `self._at`,
586 # `self._line_no`, and `self._col_no` on success.
587 def _try_parse_pat(self
, pat
: Pattern
[str]):
588 m
= pat
.match(self
._normand
, self
._at
)
593 # Skip matched string
594 self
._at
+= len(m
.group(0))
597 self
._line
_no
+= m
.group(0).count("\n")
599 # Update column number
600 for i
in reversed(range(self
._at
)):
601 if self
._normand
[i
] == "\n" or i
== 0:
603 self
._col
_no
= self
._at
+ 1
605 self
._col
_no
= self
._at
- i
609 # Return match object
612 # Expects the pattern `pat` to match the current substring,
613 # returning the match object and updating `self._at`,
614 # `self._line_no`, and `self._col_no` on success, or raising a parse
615 # error with the message `error_msg` on error.
616 def _expect_pat(self
, pat
: Pattern
[str], error_msg
: str):
618 m
= self
._try
_parse
_pat
(pat
)
622 self
._raise
_error
(error_msg
)
624 # Return match object
627 # Pattern for _skip_ws_and_comments()
628 _ws_or_syms_or_comments_pat
= re
.compile(
629 r
"(?:[\s/\\?&:;.,[\]_=|-]|#[^#]*?(?:\n|#))*"
632 # Skips as many whitespaces, insignificant symbol characters, and
633 # comments as possible.
634 def _skip_ws_and_comments(self
):
635 self
._try
_parse
_pat
(self
._ws
_or
_syms
_or
_comments
_pat
)
637 # Pattern for _skip_ws()
638 _ws_pat
= re
.compile(r
"\s*")
640 # Skips as many whitespaces as possible.
642 self
._try
_parse
_pat
(self
._ws
_pat
)
644 # Pattern for _try_parse_hex_byte()
645 _nibble_pat
= re
.compile(r
"[A-Fa-f0-9]")
647 # Tries to parse a hexadecimal byte, returning a byte item on
649 def _try_parse_hex_byte(self
):
650 begin_text_loc
= self
._text
_loc
652 # Match initial nibble
653 m_high
= self
._try
_parse
_pat
(self
._nibble
_pat
)
659 # Expect another nibble
660 self
._skip
_ws
_and
_comments
()
661 m_low
= self
._expect
_pat
(
662 self
._nibble
_pat
, "Expecting another hexadecimal nibble"
666 return _Byte(int(m_high
.group(0) + m_low
.group(0), 16), begin_text_loc
)
668 # Patterns for _try_parse_bin_byte()
669 _bin_byte_bit_pat
= re
.compile(r
"[01]")
670 _bin_byte_prefix_pat
= re
.compile(r
"%")
672 # Tries to parse a binary byte, returning a byte item on success.
673 def _try_parse_bin_byte(self
):
674 begin_text_loc
= self
._text
_loc
677 if self
._try
_parse
_pat
(self
._bin
_byte
_prefix
_pat
) is None:
682 bits
= [] # type: List[str]
685 self
._skip
_ws
_and
_comments
()
686 m
= self
._expect
_pat
(self
._bin
_byte
_bit
_pat
, "Expecting a bit (`0` or `1`)")
687 bits
.append(m
.group(0))
690 return _Byte(int("".join(bits
), 2), begin_text_loc
)
692 # Patterns for _try_parse_dec_byte()
693 _dec_byte_prefix_pat
= re
.compile(r
"\$")
694 _dec_byte_val_pat
= re
.compile(r
"(?P<neg>-?)(?P<val>\d+)")
696 # Tries to parse a decimal byte, returning a byte item on success.
697 def _try_parse_dec_byte(self
):
698 begin_text_loc
= self
._text
_loc
701 if self
._try
_parse
_pat
(self
._dec
_byte
_prefix
_pat
) is None:
707 m
= self
._expect
_pat
(self
._dec
_byte
_val
_pat
, "Expecting a decimal constant")
710 val
= int(m
.group("val")) * (-1 if m
.group("neg") == "-" else 1)
713 if val
< -128 or val
> 255:
714 _raise_error("Invalid decimal byte value {}".format(val
), begin_text_loc
)
720 return _Byte(val
, begin_text_loc
)
722 # Tries to parse a byte, returning a byte item on success.
723 def _try_parse_byte(self
):
725 item
= self
._try
_parse
_hex
_byte
()
731 item
= self
._try
_parse
_bin
_byte
()
737 item
= self
._try
_parse
_dec
_byte
()
742 # Patterns for _try_parse_str()
743 _str_prefix_pat
= re
.compile(r
'(?:u(?P<len>16|32)(?P<bo>be|le))?\s*"')
744 _str_suffix_pat
= re
.compile(r
'"')
745 _str_str_pat
= re
.compile(r
'(?:(?:\\.)|[^"])*')
747 # Strings corresponding to escape sequence characters
748 _str_escape_seq_strs
= {
762 # Tries to parse a string, returning a string item on success.
763 def _try_parse_str(self
):
764 begin_text_loc
= self
._text
_loc
767 m
= self
._try
_parse
_pat
(self
._str
_prefix
_pat
)
776 if m
.group("len") is not None:
777 encoding
= "utf_{}_{}".format(m
.group("len"), m
.group("bo"))
780 m
= self
._expect
_pat
(self
._str
_str
_pat
, "Expecting a literal string")
782 # Expect end of string
783 self
._expect
_pat
(self
._str
_suffix
_pat
, 'Expecting `"` (end of literal string)')
785 # Replace escape sequences
788 for ec
in '0abefnrtv"\\':
789 val
= val
.replace(r
"\{}".format(ec
), self
._str
_escape
_seq
_strs
[ec
])
792 data
= val
.encode(encoding
)
795 return _Str(data
, begin_text_loc
)
797 # Common right parenthesis pattern
798 _right_paren_pat
= re
.compile(r
"\)")
800 # Patterns for _try_parse_group()
801 _group_prefix_pat
= re
.compile(r
"\(|!g(?:roup)?\b")
803 # Tries to parse a group, returning a group item on success.
804 def _try_parse_group(self
):
805 begin_text_loc
= self
._text
_loc
808 m_open
= self
._try
_parse
_pat
(self
._group
_prefix
_pat
)
815 items
= self
._parse
_items
()
817 # Expect end of group
818 self
._skip
_ws
_and
_comments
()
820 if m_open
.group(0) == "(":
821 pat
= self
._right
_paren
_pat
824 pat
= self
._block
_end
_pat
827 self
._expect
_pat
(pat
, "Expecting an item or `{}` (end of group)".format(exp
))
830 return _Group(items
, begin_text_loc
)
832 # Returns a stripped expression string and an AST expression node
833 # from the expression string `expr_str` at text location `text_loc`.
834 def _ast_expr_from_str(self
, expr_str
: str, text_loc
: TextLocation
):
835 # Create an expression node from the expression string
836 expr_str
= expr_str
.strip().replace("\n", " ")
839 expr
= ast
.parse(expr_str
, mode
="eval")
842 "Invalid expression `{}`: invalid syntax".format(expr_str
),
846 return expr_str
, expr
848 # Patterns for _try_parse_num_and_attr()
849 _val_expr_pat
= re
.compile(r
"([^}:]+):\s*")
850 _fl_num_len_attr_pat
= re
.compile(r
"8|16|24|32|40|48|56|64")
851 _leb128_int_attr_pat
= re
.compile(r
"(u|s)leb128")
853 # Tries to parse a value and attribute (fixed length in bits or
854 # `leb128`), returning a value item on success.
855 def _try_parse_num_and_attr(self
):
856 begin_text_loc
= self
._text
_loc
859 m_expr
= self
._try
_parse
_pat
(self
._val
_expr
_pat
)
865 # Create an expression node from the expression string
866 expr_str
, expr
= self
._ast
_expr
_from
_str
(m_expr
.group(1), begin_text_loc
)
869 m_attr
= self
._try
_parse
_pat
(self
._fl
_num
_len
_attr
_pat
)
873 m_attr
= self
._try
_parse
_pat
(self
._leb
128_int
_attr
_pat
)
876 # At this point it's invalid
878 "Expecting a length (multiple of eight bits), `uleb128`, or `sleb128`"
881 # Return LEB128 integer item
882 cls
= _ULeb128Int
if m_attr
.group(1) == "u" else _SLeb128Int
883 return cls(expr_str
, expr
, begin_text_loc
)
885 # Return fixed-length number item
889 int(m_attr
.group(0)),
893 # Patterns for _try_parse_var_assign()
894 _var_assign_name_equal_pat
= re
.compile(r
"({})\s*=".format(_py_name_pat
.pattern
))
895 _var_assign_expr_pat
= re
.compile(r
"[^}]+")
897 # Tries to parse a variable assignment, returning a variable
898 # assignment item on success.
899 def _try_parse_var_assign(self
):
900 begin_text_loc
= self
._text
_loc
903 m
= self
._try
_parse
_pat
(self
._var
_assign
_name
_equal
_pat
)
912 if name
== _icitte_name
:
914 "`{}` is a reserved variable name".format(_icitte_name
), begin_text_loc
917 if name
in self
._label
_names
:
918 _raise_error("Existing label named `{}`".format(name
), begin_text_loc
)
920 # Expect an expression
922 m
= self
._expect
_pat
(self
._var
_assign
_expr
_pat
, "Expecting an expression")
924 # Create an expression node from the expression string
925 expr_str
, expr
= self
._ast
_expr
_from
_str
(m
.group(0), begin_text_loc
)
927 # Add to known variable names
928 self
._var
_names
.add(name
)
938 # Pattern for _try_parse_set_bo()
939 _bo_pat
= re
.compile(r
"[bl]e")
941 # Tries to parse a byte order name, returning a byte order setting
943 def _try_parse_set_bo(self
):
944 begin_text_loc
= self
._text
_loc
947 m
= self
._try
_parse
_pat
(self
._bo
_pat
)
953 # Return corresponding item
954 if m
.group(0) == "be":
955 return _SetBo(ByteOrder
.BE
, begin_text_loc
)
957 assert m
.group(0) == "le"
958 return _SetBo(ByteOrder
.LE
, begin_text_loc
)
960 # Patterns for _try_parse_val_or_bo()
961 _val_var_assign_set_bo_prefix_pat
= re
.compile(r
"\{")
962 _val_var_assign_set_bo_suffix_pat
= re
.compile(r
"\}")
964 # Tries to parse a value, a variable assignment, or a byte order
965 # setting, returning an item on success.
966 def _try_parse_val_or_var_assign_or_set_bo(self
):
968 if self
._try
_parse
_pat
(self
._val
_var
_assign
_set
_bo
_prefix
_pat
) is None:
974 # Variable assignment item?
975 item
= self
._try
_parse
_var
_assign
()
979 item
= self
._try
_parse
_num
_and
_attr
()
982 # Byte order setting item?
983 item
= self
._try
_parse
_set
_bo
()
986 # At this point it's invalid
988 "Expecting a fixed-length number, a variable assignment, or a byte order setting"
993 self
._expect
_pat
(self
._val
_var
_assign
_set
_bo
_suffix
_pat
, "Expecting `}`")
996 # Common constant integer patterns
997 _pos_const_int_pat
= re
.compile(r
"0[Xx][A-Fa-f0-9]+|\d+")
998 _const_int_pat
= re
.compile(r
"(?P<neg>-)?(?:{})".format(_pos_const_int_pat
.pattern
))
1000 # Tries to parse an offset setting value (after the initial `<`),
1001 # returning an offset item on success.
1002 def _try_parse_set_offset_val(self
):
1003 begin_text_loc
= self
._text
_loc
1006 m
= self
._try
_parse
_pat
(self
._pos
_const
_int
_pat
)
1013 return _SetOffset(int(m
.group(0), 0), begin_text_loc
)
1015 # Tries to parse a label name (after the initial `<`), returning a
1016 # label item on success.
1017 def _try_parse_label_name(self
):
1018 begin_text_loc
= self
._text
_loc
1021 m
= self
._try
_parse
_pat
(_py_name_pat
)
1030 if name
== _icitte_name
:
1032 "`{}` is a reserved label name".format(_icitte_name
), begin_text_loc
1035 if name
in self
._label
_names
:
1036 _raise_error("Duplicate label name `{}`".format(name
), begin_text_loc
)
1038 if name
in self
._var
_names
:
1039 _raise_error("Existing variable named `{}`".format(name
), begin_text_loc
)
1041 # Add to known label names
1042 self
._label
_names
.add(name
)
1045 return _Label(name
, begin_text_loc
)
1047 # Patterns for _try_parse_label_or_set_offset()
1048 _label_set_offset_prefix_pat
= re
.compile(r
"<")
1049 _label_set_offset_suffix_pat
= re
.compile(r
">")
1051 # Tries to parse a label or an offset setting, returning an item on
1053 def _try_parse_label_or_set_offset(self
):
1055 if self
._try
_parse
_pat
(self
._label
_set
_offset
_prefix
_pat
) is None:
1059 # Offset setting item?
1061 item
= self
._try
_parse
_set
_offset
_val
()
1065 item
= self
._try
_parse
_label
_name
()
1068 # At this point it's invalid
1069 self
._raise
_error
("Expecting a label name or an offset setting value")
1073 self
._expect
_pat
(self
._label
_set
_offset
_suffix
_pat
, "Expecting `>`")
1076 # Pattern for _parse_pad_val()
1077 _pad_val_prefix_pat
= re
.compile(r
"~")
1079 # Tries to parse a padding value, returning the padding value, or 0
1081 def _parse_pad_val(self
):
1086 if self
._try
_parse
_pat
(self
._pad
_val
_prefix
_pat
) is not None:
1088 pad_val_text_loc
= self
._text
_loc
1089 m
= self
._expect
_pat
(
1090 self
._pos
_const
_int
_pat
,
1091 "Expecting a positive constant integer (byte value)",
1095 pad_val
= int(m
.group(0), 0)
1099 "Invalid padding byte value {}".format(pad_val
),
1105 # Patterns for _try_parse_align_offset()
1106 _align_offset_prefix_pat
= re
.compile(r
"@")
1107 _align_offset_val_pat
= re
.compile(r
"\d+")
1109 # Tries to parse an offset alignment, returning an offset alignment
1111 def _try_parse_align_offset(self
):
1112 begin_text_loc
= self
._text
_loc
1115 if self
._try
_parse
_pat
(self
._align
_offset
_prefix
_pat
) is None:
1119 # Expect an alignment
1121 align_text_loc
= self
._text
_loc
1122 m
= self
._expect
_pat
(
1123 self
._align
_offset
_val
_pat
,
1124 "Expecting an alignment (positive multiple of eight bits)",
1127 # Validate alignment
1128 val
= int(m
.group(0))
1130 if val
<= 0 or (val
% 8) != 0:
1132 "Invalid alignment value {} (not a positive multiple of eight)".format(
1139 pad_val
= self
._parse
_pad
_val
()
1142 return _AlignOffset(val
, pad_val
, begin_text_loc
)
1144 # Patterns for _try_parse_fill_until()
1145 _fill_until_prefix_pat
= re
.compile(r
"\+")
1146 _fill_until_pad_val_prefix_pat
= re
.compile(r
"~")
1148 # Tries to parse a filling, returning a filling item on success.
1149 def _try_parse_fill_until(self
):
1150 begin_text_loc
= self
._text
_loc
1153 if self
._try
_parse
_pat
(self
._fill
_until
_prefix
_pat
) is None:
1159 expr_str
, expr
= self
._expect
_const
_int
_name
_expr
(True)
1162 pad_val
= self
._parse
_pad
_val
()
1165 return _FillUntil(expr_str
, expr
, pad_val
, begin_text_loc
)
1167 # Patterns for _expect_rep_mul_expr()
1168 _inner_expr_prefix_pat
= re
.compile(r
"\{")
1169 _inner_expr_pat
= re
.compile(r
"[^}]+")
1170 _inner_expr_suffix_pat
= re
.compile(r
"\}")
1172 # Parses a constant integer if `accept_const_int` is `True`
1173 # (possibly negative if `allow_neg` is `True`), a name, or an
1174 # expression within `{` and `}`.
1175 def _expect_const_int_name_expr(
1176 self
, accept_const_int
: bool, allow_neg
: bool = False
1178 expr_text_loc
= self
._text
_loc
1183 if accept_const_int
:
1184 m
= self
._try
_parse
_pat
(self
._const
_int
_pat
)
1188 m
= self
._try
_parse
_pat
(_py_name_pat
)
1192 if self
._try
_parse
_pat
(self
._inner
_expr
_prefix
_pat
) is None:
1193 pos_msg
= "" if allow_neg
else "positive "
1195 if accept_const_int
:
1196 mid_msg
= "a {}constant integer, a name, or `{{`".format(
1200 mid_msg
= "a name or `{`"
1202 # At this point it's invalid
1203 self
._raise
_error
("Expecting {}".format(mid_msg
))
1205 # Expect an expression
1207 expr_text_loc
= self
._text
_loc
1208 m
= self
._expect
_pat
(self
._inner
_expr
_pat
, "Expecting an expression")
1209 expr_str
= m
.group(0)
1213 self
._expect
_pat
(self
._inner
_expr
_suffix
_pat
, "Expecting `}`")
1215 expr_str
= m
.group(0)
1217 if m
.group("neg") == "-" and not allow_neg
:
1218 _raise_error("Expecting a positive constant integer", expr_text_loc
)
1220 expr_str
= m
.group(0)
1222 return self
._ast
_expr
_from
_str
(expr_str
, expr_text_loc
)
1224 # Parses the multiplier expression of a repetition (block or
1225 # post-item) and returns the expression string and AST node.
1226 def _expect_rep_mul_expr(self
):
1227 return self
._expect
_const
_int
_name
_expr
(True)
1229 # Common block end pattern
1230 _block_end_pat
= re
.compile(r
"!end\b")
1232 # Pattern for _try_parse_rep_block()
1233 _rep_block_prefix_pat
= re
.compile(r
"!r(?:epeat)?\b")
1235 # Tries to parse a repetition block, returning a repetition item on
1237 def _try_parse_rep_block(self
):
1238 begin_text_loc
= self
._text
_loc
1241 if self
._try
_parse
_pat
(self
._rep
_block
_prefix
_pat
) is None:
1246 self
._skip
_ws
_and
_comments
()
1247 expr_str
, expr
= self
._expect
_rep
_mul
_expr
()
1250 self
._skip
_ws
_and
_comments
()
1251 items_text_loc
= self
._text
_loc
1252 items
= self
._parse
_items
()
1254 # Expect end of block
1255 self
._skip
_ws
_and
_comments
()
1257 self
._block
_end
_pat
, "Expecting an item or `!end` (end of repetition block)"
1261 return _Rep(_Group(items
, items_text_loc
), expr_str
, expr
, begin_text_loc
)
1263 # Pattern for _try_parse_cond_block()
1264 _cond_block_prefix_pat
= re
.compile(r
"!if\b")
1266 # Tries to parse a conditional block, returning a conditional item
1268 def _try_parse_cond_block(self
):
1269 begin_text_loc
= self
._text
_loc
1272 if self
._try
_parse
_pat
(self
._cond
_block
_prefix
_pat
) is None:
1277 self
._skip
_ws
_and
_comments
()
1278 expr_str
, expr
= self
._expect
_const
_int
_name
_expr
(False)
1281 self
._skip
_ws
_and
_comments
()
1282 items_text_loc
= self
._text
_loc
1283 items
= self
._parse
_items
()
1285 # Expect end of block
1286 self
._skip
_ws
_and
_comments
()
1288 self
._block
_end
_pat
,
1289 "Expecting an item or `!end` (end of conditional block)",
1293 return _Cond(_Group(items
, items_text_loc
), expr_str
, expr
, begin_text_loc
)
1295 # Common left parenthesis pattern
1296 _left_paren_pat
= re
.compile(r
"\(")
1298 # Patterns for _try_parse_macro_def() and _try_parse_macro_exp()
1299 _macro_params_comma_pat
= re
.compile(",")
1301 # Patterns for _try_parse_macro_def()
1302 _macro_def_prefix_pat
= re
.compile(r
"!m(?:acro)?\b")
1304 # Tries to parse a macro definition, adding it to `self._macro_defs`
1305 # and returning `True` on success.
1306 def _try_parse_macro_def(self
):
1307 begin_text_loc
= self
._text
_loc
1310 if self
._try
_parse
_pat
(self
._macro
_def
_prefix
_pat
) is None:
1316 name_text_loc
= self
._text
_loc
1317 m
= self
._expect
_pat
(_py_name_pat
, "Expecting a valid macro name")
1322 if name
in self
._macro
_defs
:
1323 _raise_error("Duplicate macro named `{}`".format(name
), name_text_loc
)
1327 self
._expect
_pat
(self
._left
_paren
_pat
, "Expecting `(`")
1329 # Try to parse comma-separated parameter names
1330 param_names
= [] # type: List[str]
1331 expect_comma
= False
1337 if self
._try
_parse
_pat
(self
._right
_paren
_pat
) is not None:
1343 self
._expect
_pat
(self
._macro
_params
_comma
_pat
, "Expecting `,`")
1345 # Expect parameter name
1347 param_text_loc
= self
._text
_loc
1348 m
= self
._expect
_pat
(_py_name_pat
, "Expecting valid parameter name")
1350 if m
.group(0) in param_names
:
1352 "Duplicate macro parameter named `{}`".format(m
.group(0)),
1356 param_names
.append(m
.group(0))
1360 self
._skip
_ws
_and
_comments
()
1361 items_text_loc
= self
._text
_loc
1362 old_var_names
= self
._var
_names
.copy()
1363 old_label_names
= self
._label
_names
.copy()
1364 self
._var
_names
= set() # type: Set[str]
1365 self
._label
_names
= set() # type: Set[str]
1366 items
= self
._parse
_items
()
1367 self
._var
_names
= old_var_names
1368 self
._label
_names
= old_label_names
1372 self
._block
_end
_pat
, "Expecting an item or `!end` (end of macro block)"
1376 self
._macro
_defs
[name
] = _MacroDef(
1377 name
, param_names
, _Group(items
, items_text_loc
), begin_text_loc
1382 # Patterns for _try_parse_macro_exp()
1383 _macro_exp_prefix_pat
= re
.compile(r
"m\b")
1384 _macro_exp_colon_pat
= re
.compile(r
":")
1386 # Tries to parse a macro expansion, returning a macro expansion item
1388 def _try_parse_macro_exp(self
):
1389 begin_text_loc
= self
._text
_loc
1392 if self
._try
_parse
_pat
(self
._macro
_exp
_prefix
_pat
) is None:
1398 self
._expect
_pat
(self
._macro
_exp
_colon
_pat
, "Expecting `:`")
1400 # Expect a macro name
1402 name_text_loc
= self
._text
_loc
1403 m
= self
._expect
_pat
(_py_name_pat
, "Expecting a valid macro name")
1407 macro_def
= self
._macro
_defs
.get(name
)
1409 if macro_def
is None:
1410 _raise_error("Unknown macro name `{}`".format(name
), name_text_loc
)
1414 self
._expect
_pat
(self
._left
_paren
_pat
, "Expecting `(`")
1416 # Try to parse comma-separated parameter values
1417 params_text_loc
= self
._text
_loc
1418 params
= [] # type: List[_MacroExpParam]
1419 expect_comma
= False
1425 if self
._try
_parse
_pat
(self
._right
_paren
_pat
) is not None:
1431 self
._expect
_pat
(self
._macro
_params
_comma
_pat
, "Expecting `,`")
1434 param_text_loc
= self
._text
_loc
1437 *self
._expect
_const
_int
_name
_expr
(True, True), param_text_loc
1442 # Validate parameter values
1443 if len(params
) != len(macro_def
.param_names
):
1444 sing_plur
= "" if len(params
) == 1 else "s"
1446 "Macro expansion passes {} parameter{} while the definition expects {}".format(
1447 len(params
), sing_plur
, len(macro_def
.param_names
)
1453 return _MacroExp(name
, params
, begin_text_loc
)
1455 # Tries to parse a base item (anything except a repetition),
1456 # returning it on success.
1457 def _try_parse_base_item(self
):
1459 item
= self
._try
_parse
_byte
()
1461 if item
is not None:
1465 item
= self
._try
_parse
_str
()
1467 if item
is not None:
1470 # Value, variable assignment, or byte order setting item?
1471 item
= self
._try
_parse
_val
_or
_var
_assign
_or
_set
_bo
()
1473 if item
is not None:
1476 # Label or offset setting item?
1477 item
= self
._try
_parse
_label
_or
_set
_offset
()
1479 if item
is not None:
1482 # Offset alignment item?
1483 item
= self
._try
_parse
_align
_offset
()
1485 if item
is not None:
1489 item
= self
._try
_parse
_fill
_until
()
1491 if item
is not None:
1495 item
= self
._try
_parse
_group
()
1497 if item
is not None:
1500 # Repetition block item?
1501 item
= self
._try
_parse
_rep
_block
()
1503 if item
is not None:
1506 # Conditional block item?
1507 item
= self
._try
_parse
_cond
_block
()
1509 if item
is not None:
1513 item
= self
._try
_parse
_macro
_exp
()
1515 if item
is not None:
1518 # Pattern for _try_parse_rep_post()
1519 _rep_post_prefix_pat
= re
.compile(r
"\*")
1521 # Tries to parse a post-item repetition, returning the expression
1522 # string and AST expression node on success.
1523 def _try_parse_rep_post(self
):
1525 if self
._try
_parse
_pat
(self
._rep
_post
_prefix
_pat
) is None:
1529 # Return expression string and AST expression
1530 self
._skip
_ws
_and
_comments
()
1531 return self
._expect
_rep
_mul
_expr
()
1533 # Tries to parse an item, possibly followed by a repetition,
1534 # returning `True` on success.
1536 # Appends any parsed item to `items`.
1537 def _try_append_item(self
, items
: List
[_Item
]):
1538 self
._skip
_ws
_and
_comments
()
1541 item
= self
._try
_parse
_base
_item
()
1546 # Parse repetition if the base item is repeatable
1547 if isinstance(item
, _RepableItem
):
1548 self
._skip
_ws
_and
_comments
()
1549 rep_text_loc
= self
._text
_loc
1550 rep_ret
= self
._try
_parse
_rep
_post
()
1552 if rep_ret
is not None:
1553 item
= _Rep(item
, *rep_ret
, rep_text_loc
)
1558 # Parses and returns items, skipping whitespaces, insignificant
1559 # symbols, and comments when allowed, and stopping at the first
1560 # unknown character.
1562 # Accepts and registers macro definitions if `accept_macro_defs`
1564 def _parse_items(self
, accept_macro_defs
: bool = False) -> List
[_Item
]:
1565 items
= [] # type: List[_Item]
1567 while self
._isnt
_done
():
1568 # Try to append item
1569 if not self
._try
_append
_item
(items
):
1570 if accept_macro_defs
and self
._try
_parse
_macro
_def
():
1573 # Unknown at this point
1578 # Parses the whole Normand input, setting `self._res` to the main
1579 # group item on success.
1581 if len(self
._normand
.strip()) == 0:
1582 # Special case to make sure there's something to consume
1583 self
._res
= _Group([], self
._text
_loc
)
1586 # Parse first level items
1587 items
= self
._parse
_items
(True)
1589 # Make sure there's nothing left
1590 self
._skip
_ws
_and
_comments
()
1592 if self
._isnt
_done
():
1594 "Unexpected character `{}`".format(self
._normand
[self
._at
])
1597 # Set main group item
1598 self
._res
= _Group(items
, self
._text
_loc
)
1601 # The return type of parse().
1607 variables
: VariablesT
,
1610 bo
: Optional
[ByteOrder
],
1612 self
= cls
.__new
__(cls
)
1613 self
._init
(data
, variables
, labels
, offset
, bo
)
1616 def __init__(self
, *args
, **kwargs
): # type: ignore
1617 raise NotImplementedError
1622 variables
: VariablesT
,
1625 bo
: Optional
[ByteOrder
],
1628 self
._vars
= variables
1629 self
._labels
= labels
1630 self
._offset
= offset
1638 # Dictionary of updated variable names to their last computed value.
1640 def variables(self
):
1643 # Dictionary of updated main group label names to their computed
1654 # Updated byte order.
1656 def byte_order(self
):
1660 # Raises a parse error for the item `item`, creating it using the
1662 def _raise_error_for_item(msg
: str, item
: _Item
) -> NoReturn
:
1663 _raise_error(msg
, item
.text_loc
)
1666 # The `ICITTE` reserved name.
1667 _icitte_name
= "ICITTE"
1670 # Base node visitor.
1672 # Calls the _visit_name() method for each name node which isn't the name
1674 class _NodeVisitor(ast
.NodeVisitor
):
1676 self
._parent
_is
_call
= False
1678 def generic_visit(self
, node
: ast
.AST
):
1679 if type(node
) is ast
.Call
:
1680 self
._parent
_is
_call
= True
1681 elif type(node
) is ast
.Name
and not self
._parent
_is
_call
:
1682 self
._visit
_name
(node
.id)
1684 super().generic_visit(node
)
1685 self
._parent
_is
_call
= False
1688 def _visit_name(self
, name
: str):
1692 # Expression validator: validates that all the names within the
1693 # expression are allowed.
1694 class _ExprValidator(_NodeVisitor
):
1695 def __init__(self
, expr_str
: str, text_loc
: TextLocation
, allowed_names
: Set
[str]):
1697 self
._expr
_str
= expr_str
1698 self
._text
_loc
= text_loc
1699 self
._allowed
_names
= allowed_names
1701 def _visit_name(self
, name
: str):
1702 # Make sure the name refers to a known and reachable
1703 # variable/label name.
1704 if name
!= _icitte_name
and name
not in self
._allowed
_names
:
1705 msg
= "Illegal (unknown or unreachable) variable/label name `{}` in expression `{}`".format(
1706 name
, self
._expr
_str
1709 allowed_names
= self
._allowed
_names
.copy()
1710 allowed_names
.add(_icitte_name
)
1712 if len(allowed_names
) > 0:
1713 allowed_names_str
= ", ".join(
1714 sorted(["`{}`".format(name
) for name
in allowed_names
])
1716 msg
+= "; the legal names are {{{}}}".format(allowed_names_str
)
1728 variables
: VariablesT
,
1731 bo
: Optional
[ByteOrder
],
1733 self
.variables
= variables
.copy()
1734 self
.labels
= labels
.copy()
1735 self
.offset
= offset
1739 return "_GenState({}, {}, {}, {})".format(
1740 repr(self
.variables
), repr(self
.labels
), repr(self
.offset
), repr(self
.bo
)
1744 # Fixed-length number item instance.
1745 class _FlNumItemInst
:
1746 def __init__(self
, item
: _FlNum
, offset_in_data
: int, state
: _GenState
):
1748 self
._offset
_in
_data
= offset_in_data
1756 def offset_in_data(self
):
1757 return self
._offset
_in
_data
1764 # Generator of data and final state from a group item.
1766 # Generation happens in memory at construction time. After building, use
1767 # the `data`, `variables`, `labels`, `offset`, and `bo` properties to
1768 # get the resulting context.
1770 # The steps of generation are:
1772 # 1. Handle each item in prefix order.
1774 # The handlers append bytes to `self._data` and update some current
1775 # state object (`_GenState` instance).
1777 # When handling a fixed-length number item, try to evaluate its
1778 # expression using the current state. If this fails, then it might be
1779 # because the expression refers to a "future" label: save the current
1780 # offset in `self._data` (generated data) and a snapshot of the
1781 # current state within `self._fl_num_item_insts` (`_FlNumItemInst`
1782 # object). _gen_fl_num_item_insts() will deal with this later.
1784 # When handling the items of a group, keep a map of immediate label
1785 # names to their offset. Then, after having processed all the items,
1786 # update the relevant saved state snapshots in
1787 # `self._fl_num_item_insts` with those immediate label values.
1788 # _gen_fl_num_item_insts() will deal with this later.
1790 # 2. Handle all the fixed-length number item instances of which the
1791 # expression evaluation failed before.
1793 # At this point, `self._fl_num_item_insts` contains everything that's
1794 # needed to evaluate the expressions, including the values of
1795 # "future" labels from the point of view of some fixed-length number
1798 # If an evaluation fails at this point, then it's a user error.
1803 macro_defs
: _MacroDefsT
,
1804 variables
: VariablesT
,
1807 bo
: Optional
[ByteOrder
],
1809 self
._macro
_defs
= macro_defs
1810 self
._fl
_num
_item
_insts
= [] # type: List[_FlNumItemInst]
1811 self
._gen
(group
, _GenState(variables
, labels
, offset
, bo
))
1818 # Updated variables.
1820 def variables(self
):
1821 return self
._final
_state
.variables
1823 # Updated main group labels.
1826 return self
._final
_state
.labels
1831 return self
._final
_state
.offset
1833 # Updated byte order.
1836 return self
._final
_state
.bo
1838 # Evaluates the expression `expr` of which the original string is
1839 # `expr_str` at the location `text_loc` considering the current
1840 # generation state `state`.
1842 # If `allow_float` is `True`, then the type of the result may be
1847 expr
: ast
.Expression
,
1848 text_loc
: TextLocation
,
1850 allow_float
: bool = False,
1852 syms
= {} # type: VariablesT
1853 syms
.update(state
.labels
)
1855 # Set the `ICITTE` name to the current offset
1856 syms
[_icitte_name
] = state
.offset
1858 # Add the current variables
1859 syms
.update(state
.variables
)
1861 # Validate the node and its children
1862 _ExprValidator(expr_str
, text_loc
, set(syms
.keys())).visit(expr
)
1864 # Compile and evaluate expression node
1866 val
= eval(compile(expr
, "", "eval"), None, syms
)
1867 except Exception as exc
:
1869 "Failed to evaluate expression `{}`: {}".format(expr_str
, exc
),
1873 # Convert `bool` result type to `int` to normalize
1874 if type(val
) is bool:
1877 # Validate result type
1878 expected_types
= {int}
# type: Set[type]
1882 expected_types
.add(float)
1883 type_msg
+= " or `float`"
1885 if type(val
) not in expected_types
:
1887 "Invalid expression `{}`: expecting result type {}, not `{}`".format(
1888 expr_str
, type_msg
, type(val
).__name
__
1895 # Evaluates the expression of `item` considering the current
1896 # generation state `state`.
1898 # If `allow_float` is `True`, then the type of the result may be
1901 def _eval_item_expr(
1902 item
: Union
[_FlNum
, _Leb128Int
, _FillUntil
, _VarAssign
, _Rep
, _Cond
],
1904 allow_float
: bool = False,
1906 return _Gen
._eval
_expr
(
1907 item
.expr_str
, item
.expr
, item
.text_loc
, state
, allow_float
1910 # Handles the byte item `item`.
1911 def _handle_byte_item(self
, item
: _Byte
, state
: _GenState
):
1912 self
._data
.append(item
.val
)
1913 state
.offset
+= item
.size
1915 # Handles the string item `item`.
1916 def _handle_str_item(self
, item
: _Str
, state
: _GenState
):
1917 self
._data
+= item
.data
1918 state
.offset
+= item
.size
1920 # Handles the byte order setting item `item`.
1921 def _handle_set_bo_item(self
, item
: _SetBo
, state
: _GenState
):
1922 # Update current byte order
1925 # Handles the variable assignment item `item`.
1926 def _handle_var_assign_item(self
, item
: _VarAssign
, state
: _GenState
):
1928 state
.variables
[item
.name
] = self
._eval
_item
_expr
(item
, state
, True)
1930 # Handles the fixed-length number item `item`.
1931 def _handle_fl_num_item(self
, item
: _FlNum
, state
: _GenState
):
1932 # Validate current byte order
1933 if state
.bo
is None and item
.len > 8:
1934 _raise_error_for_item(
1935 "Current byte order isn't defined at first fixed-length number (`{}`) to encode on more than 8 bits".format(
1941 # Try an immediate evaluation. If it fails, then keep everything
1942 # needed to (try to) generate the bytes of this item later.
1944 data
= self
._gen
_fl
_num
_item
_inst
_data
(item
, state
)
1946 self
._fl
_num
_item
_insts
.append(
1947 _FlNumItemInst(item
, len(self
._data
), copy
.deepcopy(state
))
1950 # Reserve space in `self._data` for this instance
1951 data
= bytes([0] * (item
.len // 8))
1957 state
.offset
+= len(data
)
1959 # Returns the size, in bytes, required to encode the value `val`
1960 # with LEB128 (signed version if `is_signed` is `True`).
1962 def _leb128_size_for_val(val
: int, is_signed
: bool):
1964 # Equivalent upper bound.
1966 # For example, if `val` is -128, then the full integer for
1967 # this number of bits would be [-128, 127].
1970 # Number of bits (add one for the sign if needed)
1971 bits
= val
.bit_length() + int(is_signed
)
1976 # Seven bits per byte
1977 return math
.ceil(bits
/ 7)
1979 # Handles the LEB128 integer item `item`.
1980 def _handle_leb128_int_item(self
, item
: _Leb128Int
, state
: _GenState
):
1982 val
= self
._eval
_item
_expr
(item
, state
, False)
1985 size
= self
._leb
128_size
_for
_val
(val
, type(item
) is _SLeb128Int
)
1988 for _
in range(size
):
1989 # Seven LSBs, MSB of the byte set (continue)
1990 self
._data
.append((val
& 0x7F) |
0x80)
1993 # Clear MSB of last byte (stop)
1994 self
._data
[-1] &= ~
0x80
1997 state
.offset
+= size
1999 # Handles the group item `item`, removing the immediate labels from
2000 # `state` at the end if `remove_immediate_labels` is `True`.
2001 def _handle_group_item(
2002 self
, item
: _Group
, state
: _GenState
, remove_immediate_labels
: bool = True
2004 first_fl_num_item_inst_index
= len(self
._fl
_num
_item
_insts
)
2005 immediate_labels
= {} # type: LabelsT
2008 for subitem
in item
.items
:
2009 if type(subitem
) is _Label
:
2010 # Add to local immediate labels
2011 immediate_labels
[subitem
.name
] = state
.offset
2013 self
._handle
_item
(subitem
, state
)
2015 # Remove immediate labels from current state if needed
2016 if remove_immediate_labels
:
2017 for name
in immediate_labels
:
2018 del state
.labels
[name
]
2020 # Add all immediate labels to all state snapshots since
2021 # `first_fl_num_item_inst_index`.
2022 for inst
in self
._fl
_num
_item
_insts
[first_fl_num_item_inst_index
:]:
2023 inst
.state
.labels
.update(immediate_labels
)
2025 # Handles the repetition item `item`.
2026 def _handle_rep_item(self
, item
: _Rep
, state
: _GenState
):
2027 # Compute the repetition count
2028 mul
= _Gen
._eval
_item
_expr
(item
, state
)
2032 _raise_error_for_item(
2033 "Invalid expression `{}`: unexpected negative result {:,}".format(
2039 # Generate item data `mul` times
2040 for _
in range(mul
):
2041 self
._handle
_item
(item
.item
, state
)
2043 # Handles the conditional item `item`.
2044 def _handle_cond_item(self
, item
: _Rep
, state
: _GenState
):
2045 # Compute the conditional value
2046 val
= _Gen
._eval
_item
_expr
(item
, state
)
2048 # Generate item data if needed
2050 self
._handle
_item
(item
.item
, state
)
2052 # Evaluates the parameters of the macro expansion item `item`
2053 # considering the initial state `init_state` and returns a new state
2054 # to handle the items of the macro.
2055 def _eval_macro_exp_params(self
, item
: _MacroExp
, init_state
: _GenState
):
2057 exp_state
= _GenState({}, {}, init_state
.offset
, init_state
.bo
)
2059 # Evaluate the parameter expressions
2060 macro_def
= self
._macro
_defs
[item
.name
]
2062 for param_name
, param
in zip(macro_def
.param_names
, item
.params
):
2063 exp_state
.variables
[param_name
] = _Gen
._eval
_expr
(
2064 param
.expr_str
, param
.expr
, param
.text_loc
, init_state
, True
2069 # Handles the macro expansion item `item`.
2070 def _handle_macro_exp_item(self
, item
: _MacroExp
, state
: _GenState
):
2072 exp_state
= self
._eval
_macro
_exp
_params
(item
, state
)
2074 # Process the contained group
2075 init_data_size
= len(self
._data
)
2076 self
._handle
_item
(self
._macro
_defs
[item
.name
].group
, exp_state
)
2078 # Update state offset and return
2079 state
.offset
+= len(self
._data
) - init_data_size
2081 # Handles the offset setting item `item`.
2082 def _handle_set_offset_item(self
, item
: _SetOffset
, state
: _GenState
):
2083 state
.offset
= item
.val
2085 # Handles the offset alignment item `item` (adds padding).
2086 def _handle_align_offset_item(self
, item
: _AlignOffset
, state
: _GenState
):
2087 init_offset
= state
.offset
2088 align_bytes
= item
.val
// 8
2089 state
.offset
= (state
.offset
+ align_bytes
- 1) // align_bytes
* align_bytes
2090 self
._data
+= bytes([item
.pad_val
] * (state
.offset
- init_offset
))
2092 # Handles the filling item `item` (adds padding).
2093 def _handle_fill_until_item(self
, item
: _FillUntil
, state
: _GenState
):
2094 # Compute the new offset
2095 new_offset
= _Gen
._eval
_item
_expr
(item
, state
)
2097 # Validate the new offset
2098 if new_offset
< state
.offset
:
2099 _raise_error_for_item(
2100 "Invalid expression `{}`: new offset {:,} is less than current offset {:,}".format(
2101 item
.expr_str
, new_offset
, state
.offset
2107 self
._data
+= bytes([item
.pad_val
] * (new_offset
- state
.offset
))
2110 state
.offset
= new_offset
2112 # Handles the label item `item`.
2113 def _handle_label_item(self
, item
: _Label
, state
: _GenState
):
2114 state
.labels
[item
.name
] = state
.offset
2116 # Handles the item `item`, returning the updated next repetition
2118 def _handle_item(self
, item
: _Item
, state
: _GenState
):
2119 return self
._item
_handlers
[type(item
)](item
, state
)
2121 # Generates the data for a fixed-length integer item instance having
2122 # the value `val` and returns it.
2123 def _gen_fl_int_item_inst_data(self
, val
: int, item
: _FlNum
, state
: _GenState
):
2125 if val
< -(2 ** (item
.len - 1)) or val
> 2**item
.len - 1:
2126 _raise_error_for_item(
2127 "Value {:,} is outside the {}-bit range when evaluating expression `{}`".format(
2128 val
, item
.len, item
.expr_str
2133 # Encode result on 64 bits (to extend the sign bit whatever the
2134 # value of `item.len`).
2137 ">" if state
.bo
in (None, ByteOrder
.BE
) else "<",
2138 "Q" if val
>= 0 else "q",
2143 # Keep only the requested length
2144 len_bytes
= item
.len // 8
2146 if state
.bo
in (None, ByteOrder
.BE
):
2147 # Big endian: keep last bytes
2148 data
= data
[-len_bytes
:]
2150 # Little endian: keep first bytes
2151 assert state
.bo
== ByteOrder
.LE
2152 data
= data
[:len_bytes
]
2157 # Generates the data for a fixed-length floating point number item
2158 # instance having the value `val` and returns it.
2159 def _gen_fl_float_item_inst_data(self
, val
: float, item
: _FlNum
, state
: _GenState
):
2161 if item
.len not in (32, 64):
2162 _raise_error_for_item(
2163 "Invalid {}-bit length for a fixed-length floating point number (value {:,})".format(
2169 # Encode and return result
2172 ">" if state
.bo
in (None, ByteOrder
.BE
) else "<",
2173 "f" if item
.len == 32 else "d",
2178 # Generates the data for a fixed-length number item instance and
2180 def _gen_fl_num_item_inst_data(self
, item
: _FlNum
, state
: _GenState
):
2182 val
= self
._eval
_item
_expr
(item
, state
, True)
2184 # Handle depending on type
2185 if type(val
) is int:
2186 return self
._gen
_fl
_int
_item
_inst
_data
(val
, item
, state
)
2188 assert type(val
) is float
2189 return self
._gen
_fl
_float
_item
_inst
_data
(val
, item
, state
)
2191 # Generates the data for all the fixed-length number item instances
2192 # and writes it at the correct offset within `self._data`.
2193 def _gen_fl_num_item_insts(self
):
2194 for inst
in self
._fl
_num
_item
_insts
:
2196 data
= self
._gen
_fl
_num
_item
_inst
_data
(inst
.item
, inst
.state
)
2198 # Insert bytes into `self._data`
2199 self
._data
[inst
.offset_in_data
: inst
.offset_in_data
+ len(data
)] = data
2201 # Generates the data (`self._data`) and final state
2202 # (`self._final_state`) from `group` and the initial state `state`.
2203 def _gen(self
, group
: _Group
, state
: _GenState
):
2205 self
._data
= bytearray()
2208 self
._item
_handlers
= {
2209 _AlignOffset
: self
._handle
_align
_offset
_item
,
2210 _Byte
: self
._handle
_byte
_item
,
2211 _Cond
: self
._handle
_cond
_item
,
2212 _FillUntil
: self
._handle
_fill
_until
_item
,
2213 _FlNum
: self
._handle
_fl
_num
_item
,
2214 _Group
: self
._handle
_group
_item
,
2215 _Label
: self
._handle
_label
_item
,
2216 _MacroExp
: self
._handle
_macro
_exp
_item
,
2217 _Rep
: self
._handle
_rep
_item
,
2218 _SetBo
: self
._handle
_set
_bo
_item
,
2219 _SetOffset
: self
._handle
_set
_offset
_item
,
2220 _SLeb128Int
: self
._handle
_leb
128_int
_item
,
2221 _Str
: self
._handle
_str
_item
,
2222 _ULeb128Int
: self
._handle
_leb
128_int
_item
,
2223 _VarAssign
: self
._handle
_var
_assign
_item
,
2224 } # type: Dict[type, Callable[[Any, _GenState], None]]
2226 # Handle the group item, _not_ removing the immediate labels
2227 # because the `labels` property offers them.
2228 self
._handle
_group
_item
(group
, state
, False)
2230 # This is actually the final state
2231 self
._final
_state
= state
2233 # Generate all the fixed-length number bytes now that we know
2235 self
._gen
_fl
_num
_item
_insts
()
2238 # Returns a `ParseResult` instance containing the bytes encoded by the
2239 # input string `normand`.
2241 # `init_variables` is a dictionary of initial variable names (valid
2242 # Python names) to integral values. A variable name must not be the
2243 # reserved name `ICITTE`.
2245 # `init_labels` is a dictionary of initial label names (valid Python
2246 # names) to integral values. A label name must not be the reserved name
2249 # `init_offset` is the initial offset.
2251 # `init_byte_order` is the initial byte order.
2253 # Raises `ParseError` on any parsing error.
2256 init_variables
: Optional
[VariablesT
] = None,
2257 init_labels
: Optional
[LabelsT
] = None,
2258 init_offset
: int = 0,
2259 init_byte_order
: Optional
[ByteOrder
] = None,
2261 if init_variables
is None:
2264 if init_labels
is None:
2267 parser
= _Parser(normand
, init_variables
, init_labels
)
2276 return ParseResult
._create
( # pyright: ignore[reportPrivateUsage]
2277 gen
.data
, gen
.variables
, gen
.labels
, gen
.offset
, gen
.bo
2281 # Parses the command-line arguments.
2282 def _parse_cli_args():
2286 ap
= argparse
.ArgumentParser()
2293 help="initial offset (positive)",
2299 choices
=["be", "le"],
2301 help="initial byte order (`be` or `le`)",
2307 help="add an initial variable (may be repeated)",
2314 help="add an initial label (may be repeated)",
2317 "--version", action
="version", version
="Normand {}".format(__version__
)
2324 help="input path (none means standard input)",
2328 return ap
.parse_args()
2331 # Raises a command-line error with the message `msg`.
2332 def _raise_cli_error(msg
: str) -> NoReturn
:
2333 raise RuntimeError("Command-line error: {}".format(msg
))
2336 # Returns a dictionary of string to integers from the list of strings
2337 # `args` containing `NAME=VAL` entries.
2338 def _dict_from_arg(args
: Optional
[List
[str]]):
2339 d
= {} # type: LabelsT
2345 m
= re
.match(r
"({})=(\d+)$".format(_py_name_pat
.pattern
), arg
)
2348 _raise_cli_error("Invalid assignment {}".format(arg
))
2350 d
[m
.group(1)] = int(m
.group(2))
2355 # CLI entry point without exception handling.
2360 args
= _parse_cli_args()
2363 if args
.path
is None:
2364 normand
= sys
.stdin
.read()
2366 with
open(args
.path
) as f
:
2369 # Variables and labels
2370 variables
= typing
.cast(VariablesT
, _dict_from_arg(args
.var
))
2371 labels
= _dict_from_arg(args
.label
)
2375 _raise_cli_error("Invalid negative offset {}")
2377 # Validate and set byte order
2378 bo
= None # type: Optional[ByteOrder]
2380 if args
.byte_order
is not None:
2381 if args
.byte_order
== "be":
2384 assert args
.byte_order
== "le"
2389 res
= parse(normand
, variables
, labels
, args
.offset
, bo
)
2390 except ParseError
as exc
:
2393 if args
.path
is not None:
2394 prefix
= "{}:".format(os
.path
.abspath(args
.path
))
2397 "{}{}:{} - {}".format(
2398 prefix
, exc
.text_loc
.line_no
, exc
.text_loc
.col_no
, str(exc
)
2403 sys
.stdout
.buffer.write(res
.data
)
2406 # Prints the exception message `msg` and exits with status 1.
2407 def _fail(msg
: str) -> NoReturn
:
2408 if not msg
.endswith("."):
2411 print(msg
, file=sys
.stderr
)
2419 except Exception as exc
:
2423 if __name__
== "__main__":