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.19.0"
56 from typing
import Any
, Set
, Dict
, List
, Union
, Pattern
, Callable
, NoReturn
, Optional
59 # Text location (line and column numbers).
62 def _create(cls
, line_no
: int, col_no
: int):
63 self
= cls
.__new
__(cls
)
64 self
._init
(line_no
, col_no
)
67 def __init__(*args
, **kwargs
): # type: ignore
68 raise NotImplementedError
70 def _init(self
, line_no
: int, col_no
: int):
71 self
._line
_no
= line_no
85 return "TextLocation({}, {})".format(self
._line
_no
, self
._col
_no
)
90 def __init__(self
, text_loc
: TextLocation
):
91 self
._text
_loc
= text_loc
93 # Source text location.
100 class _ScalarItem(_Item
):
101 # Returns the size, in bytes, of this item.
104 def size(self
) -> int:
114 class _Byte(_ScalarItem
, _RepableItem
):
115 def __init__(self
, val
: int, text_loc
: TextLocation
):
116 super().__init
__(text_loc
)
129 return "_Byte({}, {})".format(hex(self
._val
), repr(self
._text
_loc
))
133 class _LitStr(_ScalarItem
, _RepableItem
):
134 def __init__(self
, data
: bytes
, text_loc
: TextLocation
):
135 super().__init
__(text_loc
)
145 return len(self
._data
)
148 return "_LitStr({}, {})".format(repr(self
._data
), repr(self
._text
_loc
))
153 class ByteOrder(enum
.Enum
):
161 # Byte order setting.
163 def __init__(self
, bo
: ByteOrder
, text_loc
: TextLocation
):
164 super().__init
__(text_loc
)
172 return "_SetBo({}, {})".format(repr(self
._bo
), repr(self
._text
_loc
))
177 def __init__(self
, name
: str, text_loc
: TextLocation
):
178 super().__init
__(text_loc
)
187 return "_Label({}, {})".format(repr(self
._name
), repr(self
._text
_loc
))
191 class _SetOffset(_Item
):
192 def __init__(self
, val
: int, text_loc
: TextLocation
):
193 super().__init
__(text_loc
)
196 # Offset value (bytes).
202 return "_SetOffset({}, {})".format(repr(self
._val
), repr(self
._text
_loc
))
206 class _AlignOffset(_Item
):
207 def __init__(self
, val
: int, pad_val
: int, text_loc
: TextLocation
):
208 super().__init
__(text_loc
)
210 self
._pad
_val
= pad_val
212 # Alignment value (bits).
217 # Padding byte value.
223 return "_AlignOffset({}, {}, {})".format(
224 repr(self
._val
), repr(self
._pad
_val
), repr(self
._text
_loc
)
228 # Mixin of containing an AST expression and its string.
230 def __init__(self
, expr_str
: str, expr
: ast
.Expression
):
231 self
._expr
_str
= expr_str
237 return self
._expr
_str
239 # Expression node to evaluate.
245 # Fill until some offset.
246 class _FillUntil(_Item
, _ExprMixin
):
248 self
, expr_str
: str, expr
: ast
.Expression
, pad_val
: int, text_loc
: TextLocation
250 super().__init
__(text_loc
)
251 _ExprMixin
.__init
__(self
, expr_str
, expr
)
252 self
._pad
_val
= pad_val
254 # Padding byte value.
260 return "_FillUntil({}, {}, {}, {})".format(
261 repr(self
._expr
_str
),
264 repr(self
._text
_loc
),
268 # Variable assignment.
269 class _VarAssign(_Item
, _ExprMixin
):
271 self
, name
: str, expr_str
: str, expr
: ast
.Expression
, text_loc
: TextLocation
273 super().__init
__(text_loc
)
274 _ExprMixin
.__init
__(self
, expr_str
, expr
)
283 return "_VarAssign({}, {}, {}, {})".format(
285 repr(self
._expr
_str
),
287 repr(self
._text
_loc
),
291 # Fixed-length number, possibly needing more than one byte.
292 class _FlNum(_ScalarItem
, _RepableItem
, _ExprMixin
):
294 self
, expr_str
: str, expr
: ast
.Expression
, len: int, text_loc
: TextLocation
296 super().__init
__(text_loc
)
297 _ExprMixin
.__init
__(self
, expr_str
, expr
)
307 return self
._len
// 8
310 return "_FlNum({}, {}, {}, {})".format(
311 repr(self
._expr
_str
),
314 repr(self
._text
_loc
),
319 class _Leb128Int(_Item
, _RepableItem
, _ExprMixin
):
320 def __init__(self
, expr_str
: str, expr
: ast
.Expression
, text_loc
: TextLocation
):
321 super().__init
__(text_loc
)
322 _ExprMixin
.__init
__(self
, expr_str
, expr
)
325 return "{}({}, {}, {})".format(
326 self
.__class
__.__name
__,
327 repr(self
._expr
_str
),
329 repr(self
._text
_loc
),
333 # Unsigned LEB128 integer.
334 class _ULeb128Int(_Leb128Int
, _RepableItem
, _ExprMixin
):
338 # Signed LEB128 integer.
339 class _SLeb128Int(_Leb128Int
, _RepableItem
, _ExprMixin
):
344 class _Str(_Item
, _RepableItem
, _ExprMixin
):
346 self
, expr_str
: str, expr
: ast
.Expression
, codec
: str, text_loc
: TextLocation
348 super().__init
__(text_loc
)
349 _ExprMixin
.__init
__(self
, expr_str
, expr
)
358 return "_Str({}, {}, {}, {})".format(
359 self
.__class
__.__name
__,
360 repr(self
._expr
_str
),
363 repr(self
._text
_loc
),
368 class _Group(_Item
, _RepableItem
):
369 def __init__(self
, items
: List
[_Item
], text_loc
: TextLocation
):
370 super().__init
__(text_loc
)
379 return "_Group({}, {})".format(repr(self
._items
), repr(self
._text
_loc
))
383 class _Rep(_Item
, _ExprMixin
):
385 self
, item
: _Item
, expr_str
: str, expr
: ast
.Expression
, text_loc
: TextLocation
387 super().__init
__(text_loc
)
388 _ExprMixin
.__init
__(self
, expr_str
, expr
)
397 return "_Rep({}, {}, {}, {})".format(
399 repr(self
._expr
_str
),
401 repr(self
._text
_loc
),
406 class _Cond(_Item
, _ExprMixin
):
412 expr
: ast
.Expression
,
413 text_loc
: TextLocation
,
415 super().__init
__(text_loc
)
416 _ExprMixin
.__init
__(self
, expr_str
, expr
)
417 self
._true
_item
= true_item
418 self
._false
_item
= false_item
420 # Item when condition is true.
423 return self
._true
_item
425 # Item when condition is false.
427 def false_item(self
):
428 return self
._false
_item
431 return "_Cond({}, {}, {}, {}, {})".format(
432 repr(self
._true
_item
),
433 repr(self
._false
_item
),
434 repr(self
._expr
_str
),
436 repr(self
._text
_loc
),
440 # Macro definition item.
441 class _MacroDef(_Item
):
443 self
, name
: str, param_names
: List
[str], group
: _Group
, text_loc
: TextLocation
445 super().__init
__(text_loc
)
447 self
._param
_names
= param_names
457 def param_names(self
):
458 return self
._param
_names
466 return "_MacroDef({}, {}, {}, {})".format(
468 repr(self
._param
_names
),
470 repr(self
._text
_loc
),
474 # Macro expansion parameter.
475 class _MacroExpParam
:
476 def __init__(self
, expr_str
: str, expr
: ast
.Expression
, text_loc
: TextLocation
):
477 self
._expr
_str
= expr_str
479 self
._text
_loc
= text_loc
484 return self
._expr
_str
491 # Source text location.
494 return self
._text
_loc
497 return "_MacroExpParam({}, {}, {})".format(
498 repr(self
._expr
_str
), repr(self
._expr
), repr(self
._text
_loc
)
502 # Macro expansion item.
503 class _MacroExp(_Item
, _RepableItem
):
507 params
: List
[_MacroExpParam
],
508 text_loc
: TextLocation
,
510 super().__init
__(text_loc
)
512 self
._params
= params
525 return "_MacroExp({}, {}, {})".format(
528 repr(self
._text
_loc
),
532 # A parsing error message: a string and a text location.
533 class ParseErrorMessage
:
535 def _create(cls
, text
: str, text_loc
: TextLocation
):
536 self
= cls
.__new
__(cls
)
537 self
._init
(text
, text_loc
)
540 def __init__(self
, *args
, **kwargs
): # type: ignore
541 raise NotImplementedError
543 def _init(self
, text
: str, text_loc
: TextLocation
):
545 self
._text
_loc
= text_loc
552 # Source text location.
554 def text_location(self
):
555 return self
._text
_loc
558 # A parsing error containing one or more messages (`ParseErrorMessage`).
559 class ParseError(RuntimeError):
561 def _create(cls
, msg
: str, text_loc
: TextLocation
):
562 self
= cls
.__new
__(cls
)
563 self
._init
(msg
, text_loc
)
566 def __init__(self
, *args
, **kwargs
): # type: ignore
567 raise NotImplementedError
569 def _init(self
, msg
: str, text_loc
: TextLocation
):
570 super().__init
__(msg
)
571 self
._msgs
= [] # type: List[ParseErrorMessage]
572 self
._add
_msg
(msg
, text_loc
)
574 def _add_msg(self
, msg
: str, text_loc
: TextLocation
):
576 ParseErrorMessage
._create
( # pyright: ignore[reportPrivateUsage]
581 # Parsing error messages.
583 # The first message is the most specific one.
589 # Raises a parsing error, forwarding the parameters to the constructor.
590 def _raise_error(msg
: str, text_loc
: TextLocation
) -> NoReturn
:
591 raise ParseError
._create
(msg
, text_loc
) # pyright: ignore[reportPrivateUsage]
594 # Adds a message to the parsing error `exc`.
595 def _add_error_msg(exc
: ParseError
, msg
: str, text_loc
: TextLocation
):
596 exc
._add
_msg
(msg
, text_loc
) # pyright: ignore[reportPrivateUsage]
599 # Appends a message to the parsing error `exc` and reraises it.
600 def _augment_error(exc
: ParseError
, msg
: str, text_loc
: TextLocation
) -> NoReturn
:
601 _add_error_msg(exc
, msg
, text_loc
)
605 # Returns a normalized version (so as to be parseable by int()) of
606 # the constant integer string `s`, possibly negative, dealing with
608 def _norm_const_int(s
: str):
612 if s
.startswith("-"):
617 if pos
.startswith("0" + r
):
633 for suf
in asm_suf_base
:
635 s
= "{}0{}{}".format(neg
, asm_suf_base
[suf
], pos
.rstrip(suf
))
640 # Encodes the string `s` using the codec `codec`, raising `ParseError`
641 # with `text_loc` on encoding error.
642 def _encode_str(s
: str, codec
: str, text_loc
: TextLocation
):
644 return s
.encode(codec
)
645 except UnicodeEncodeError:
647 "Cannot encode `{}` with the `{}` encoding".format(s
, codec
), text_loc
651 # Variables dictionary type (for type hints).
652 VariablesT
= Dict
[str, Union
[int, float, str]]
655 # Labels dictionary type (for type hints).
656 LabelsT
= Dict
[str, int]
660 _py_name_pat
= re
.compile(r
"[a-zA-Z_][a-zA-Z0-9_]*")
661 _pos_const_int_pat
= re
.compile(
662 r
"(?:0[Xx][A-Fa-f0-9]+|0[Oo][0-7]+|0[Bb][01]+|[A-Fa-f0-9]+[hH]|[0-7]+[qQoO]|[01]+[bB]|\d+)\b"
664 _const_int_pat
= re
.compile(r
"(?P<neg>-)?(?:{})".format(_pos_const_int_pat
.pattern
))
665 _const_float_pat
= re
.compile(
666 r
"[-+]?(?:(?:\d*\.\d+)|(?:\d+\.))(?:[Ee][+-]?\d+)?(?=\W|)"
670 # Macro definition dictionary.
671 _MacroDefsT
= Dict
[str, _MacroDef
]
676 # The constructor accepts a Normand input. After building, use the `res`
677 # property to get the resulting main group.
679 # Builds a parser to parse the Normand input `normand`, parsing
681 def __init__(self
, normand
: str, variables
: VariablesT
, labels
: LabelsT
):
682 self
._normand
= normand
686 self
._label
_names
= set(labels
.keys())
687 self
._var
_names
= set(variables
.keys())
688 self
._macro
_defs
= {} # type: _MacroDefsT
691 # Result (main group).
698 def macro_defs(self
):
699 return self
._macro
_defs
701 # Current text location.
704 return TextLocation
._create
( # pyright: ignore[reportPrivateUsage]
705 self
._line
_no
, self
._col
_no
708 # Returns `True` if this parser is done parsing.
710 return self
._at
== len(self
._normand
)
712 # Returns `True` if this parser isn't done parsing.
713 def _isnt_done(self
):
714 return not self
._is
_done
()
716 # Raises a parse error, creating it using the message `msg` and the
717 # current text location.
718 def _raise_error(self
, msg
: str) -> NoReturn
:
719 _raise_error(msg
, self
._text
_loc
)
721 # Tries to make the pattern `pat` match the current substring,
722 # returning the match object and updating `self._at`,
723 # `self._line_no`, and `self._col_no` on success.
724 def _try_parse_pat(self
, pat
: Pattern
[str]):
725 m
= pat
.match(self
._normand
, self
._at
)
730 # Skip matched string
731 self
._at
+= len(m
.group(0))
734 self
._line
_no
+= m
.group(0).count("\n")
736 # Update column number
737 for i
in reversed(range(self
._at
)):
738 if self
._normand
[i
] == "\n" or i
== 0:
740 self
._col
_no
= self
._at
+ 1
742 self
._col
_no
= self
._at
- i
746 # Return match object
749 # Expects the pattern `pat` to match the current substring,
750 # returning the match object and updating `self._at`,
751 # `self._line_no`, and `self._col_no` on success, or raising a parse
752 # error with the message `error_msg` on error.
753 def _expect_pat(self
, pat
: Pattern
[str], error_msg
: str):
755 m
= self
._try
_parse
_pat
(pat
)
759 self
._raise
_error
(error_msg
)
761 # Return match object
764 # Pattern for _skip_ws_and_comments()
765 _ws_or_syms_or_comments_pat
= re
.compile(
766 r
"(?:[\s/\\?&:;.,[\]_=|-]|#[^#]*?(?:\n|#))*"
769 # Skips as many whitespaces, insignificant symbol characters, and
770 # comments as possible.
771 def _skip_ws_and_comments(self
):
772 self
._try
_parse
_pat
(self
._ws
_or
_syms
_or
_comments
_pat
)
774 # Pattern for _skip_ws()
775 _ws_pat
= re
.compile(r
"\s*")
777 # Skips as many whitespaces as possible.
779 self
._try
_parse
_pat
(self
._ws
_pat
)
781 # Pattern for _try_parse_hex_byte()
782 _nibble_pat
= re
.compile(r
"[A-Fa-f0-9]")
784 # Tries to parse a hexadecimal byte, returning a byte item on
786 def _try_parse_hex_byte(self
):
787 begin_text_loc
= self
._text
_loc
789 # Match initial nibble
790 m_high
= self
._try
_parse
_pat
(self
._nibble
_pat
)
796 # Expect another nibble
797 self
._skip
_ws
_and
_comments
()
798 m_low
= self
._expect
_pat
(
799 self
._nibble
_pat
, "Expecting another hexadecimal nibble"
803 return _Byte(int(m_high
.group(0) + m_low
.group(0), 16), begin_text_loc
)
805 # Patterns for _try_parse_bin_byte()
806 _bin_byte_bit_pat
= re
.compile(r
"[01]")
807 _bin_byte_prefix_pat
= re
.compile(r
"%+")
809 # Tries to parse a binary byte, returning a byte item on success.
810 def _try_parse_bin_byte(self
):
811 begin_text_loc
= self
._text
_loc
814 m
= self
._try
_parse
_pat
(self
._bin
_byte
_prefix
_pat
)
820 # Expect as many bytes as there are `%` prefixes
821 items
= [] # type: List[_Item]
823 for _
in range(len(m
.group(0))):
824 self
._skip
_ws
_and
_comments
()
825 byte_text_loc
= self
._text
_loc
826 bits
= [] # type: List[str]
830 self
._skip
_ws
_and
_comments
()
831 m
= self
._expect
_pat
(
832 self
._bin
_byte
_bit
_pat
, "Expecting a bit (`0` or `1`)"
834 bits
.append(m
.group(0))
836 items
.append(_Byte(int("".join(bits
), 2), byte_text_loc
))
843 return _Group(items
, begin_text_loc
)
845 # Patterns for _try_parse_dec_byte()
846 _dec_byte_prefix_pat
= re
.compile(r
"\$")
847 _dec_byte_val_pat
= re
.compile(r
"(?P<neg>-?)(?P<val>\d+)")
849 # Tries to parse a decimal byte, returning a byte item on success.
850 def _try_parse_dec_byte(self
):
851 begin_text_loc
= self
._text
_loc
854 if self
._try
_parse
_pat
(self
._dec
_byte
_prefix
_pat
) is None:
860 m
= self
._expect
_pat
(self
._dec
_byte
_val
_pat
, "Expecting a decimal constant")
863 val
= int(m
.group("val")) * (-1 if m
.group("neg") == "-" else 1)
866 if val
< -128 or val
> 255:
867 _raise_error("Invalid decimal byte value {}".format(val
), begin_text_loc
)
873 return _Byte(val
, begin_text_loc
)
875 # Tries to parse a byte, returning a byte item on success.
876 def _try_parse_byte(self
):
878 item
= self
._try
_parse
_hex
_byte
()
884 item
= self
._try
_parse
_bin
_byte
()
890 item
= self
._try
_parse
_dec
_byte
()
895 # Strings corresponding to escape sequence characters
896 _lit_str_escape_seq_strs
= {
910 # Patterns for _try_parse_lit_str()
911 _lit_str_prefix_suffix_pat
= re
.compile(r
'"')
912 _lit_str_contents_pat
= re
.compile(r
'(?:(?:\\.)|[^"])*')
914 # Parses a literal string between double quotes (without an encoding
915 # prefix) and returns the resulting string.
916 def _try_parse_lit_str(self
, with_prefix
: bool):
917 # Match prefix if needed
919 if self
._try
_parse
_pat
(self
._lit
_str
_prefix
_suffix
_pat
) is None:
923 # Expect literal string
924 m
= self
._expect
_pat
(self
._lit
_str
_contents
_pat
, "Expecting a literal string")
926 # Expect end of string
928 self
._lit
_str
_prefix
_suffix
_pat
, 'Expecting `"` (end of literal string)'
931 # Replace escape sequences
934 for ec
in '0abefnrtv"\\':
935 val
= val
.replace(r
"\{}".format(ec
), self
._lit
_str
_escape
_seq
_strs
[ec
])
940 # Patterns for _try_parse_utf_str_encoding()
941 _str_encoding_utf_prefix_pat
= re
.compile(r
"u")
942 _str_encoding_utf_pat
= re
.compile(r
"(?:8|(?:(?:16|32)(?:[bl]e)))\b")
944 # Tries to parse a UTF encoding specification, returning the Python
945 # codec name on success.
946 def _try_parse_utf_str_encoding(self
):
948 if self
._try
_parse
_pat
(self
._str
_encoding
_utf
_prefix
_pat
) is None:
952 # Expect UTF specification
953 m
= self
._expect
_pat
(
954 self
._str
_encoding
_utf
_pat
,
955 "Expecting `8`, `16be`, `16le`, `32be` or `32le`",
958 # Convert to codec name
967 # Patterns for _try_parse_str_encoding()
968 _str_encoding_gen_prefix_pat
= re
.compile(r
"s")
969 _str_encoding_colon_pat
= re
.compile(r
":")
970 _str_encoding_non_utf_pat
= re
.compile(r
"latin(?:[1-9]|10)\b")
972 # Tries to parse a string encoding specification, returning the
973 # Python codec name on success.
975 # Requires the general prefix (`s:`) if `req_gen_prefix` is `True`.
976 def _try_parse_str_encoding(self
, req_gen_prefix
: bool = False):
978 if self
._try
_parse
_pat
(self
._str
_encoding
_gen
_prefix
_pat
) is not None:
981 self
._expect
_pat
(self
._str
_encoding
_colon
_pat
, "Expecting `:`")
983 # Expect encoding specification
987 codec
= self
._try
_parse
_utf
_str
_encoding
()
989 if codec
is not None:
993 m
= self
._expect
_pat
(
994 self
._str
_encoding
_non
_utf
_pat
,
995 "Expecting `u8`, `u16be`, `u16le`, `u32be`, `u32le`, or `latin1` to `latin10`",
1000 if not req_gen_prefix
:
1001 return self
._try
_parse
_utf
_str
_encoding
()
1003 # Patterns for _try_parse_str()
1004 _lit_str_prefix_pat
= re
.compile(r
'"')
1005 _str_prefix_pat
= re
.compile(r
'"|\{')
1006 _str_expr_pat
= re
.compile(r
"[^}]+")
1007 _str_expr_suffix_pat
= re
.compile(r
"\}")
1009 # Tries to parse a string, returning a literal string or string item
1011 def _try_parse_str(self
):
1012 begin_text_loc
= self
._text
_loc
1015 codec
= self
._try
_parse
_str
_encoding
()
1017 # Match prefix (expect if there's an encoding specification)
1021 # No encoding: only a literal string (UTF-8) is legal
1022 m_prefix
= self
._try
_parse
_pat
(self
._lit
_str
_prefix
_pat
)
1024 if m_prefix
is None:
1027 # Encoding present: expect a string prefix
1028 m_prefix
= self
._expect
_pat
(self
._str
_prefix
_pat
, 'Expecting `"` or `{`')
1030 # Literal string or expression?
1031 prefix
= m_prefix
.group(0)
1034 # Expect literal string
1035 str_text_loc
= self
._text
_loc
1036 val
= self
._try
_parse
_lit
_str
(False)
1039 self
._raise
_error
("Expecting a literal string")
1042 data
= _encode_str(val
, "utf_8" if codec
is None else codec
, str_text_loc
)
1045 return _LitStr(data
, begin_text_loc
)
1049 expr_text_loc
= self
._text
_loc
1050 m
= self
._expect
_pat
(self
._str
_expr
_pat
, "Expecting an expression")
1053 self
._expect
_pat
(self
._str
_expr
_suffix
_pat
, "Expecting `}`")
1055 # Create an expression node from the expression string
1056 expr_str
, expr
= self
._ast
_expr
_from
_str
(m
.group(0), expr_text_loc
)
1059 assert codec
is not None
1060 return _Str(expr_str
, expr
, codec
, begin_text_loc
)
1062 # Common right parenthesis pattern
1063 _right_paren_pat
= re
.compile(r
"\)")
1065 # Patterns for _try_parse_group()
1066 _group_prefix_pat
= re
.compile(r
"\(|!g(?:roup)?\b")
1068 # Tries to parse a group, returning a group item on success.
1069 def _try_parse_group(self
):
1070 begin_text_loc
= self
._text
_loc
1073 m_open
= self
._try
_parse
_pat
(self
._group
_prefix
_pat
)
1080 items
= self
._parse
_items
()
1082 # Expect end of group
1083 self
._skip
_ws
_and
_comments
()
1085 if m_open
.group(0) == "(":
1086 pat
= self
._right
_paren
_pat
1089 pat
= self
._block
_end
_pat
1092 self
._expect
_pat
(pat
, "Expecting an item or `{}` (end of group)".format(exp
))
1095 return _Group(items
, begin_text_loc
)
1097 # Returns a stripped expression string and an AST expression node
1098 # from the expression string `expr_str` at text location `text_loc`.
1099 def _ast_expr_from_str(self
, expr_str
: str, text_loc
: TextLocation
):
1100 # Create an expression node from the expression string
1101 expr_str
= expr_str
.strip().replace("\n", " ")
1104 expr
= ast
.parse(expr_str
, mode
="eval")
1107 "Invalid expression `{}`: invalid syntax".format(expr_str
),
1111 return expr_str
, expr
1113 # Patterns for _try_parse_val()
1114 _val_expr_pat
= re
.compile(r
"([^}:]+):\s*")
1115 _fl_num_len_fmt_pat
= re
.compile(r
"8|16|24|32|40|48|56|64")
1116 _leb128_int_fmt_pat
= re
.compile(r
"(u|s)leb128")
1118 # Tries to parse a value (number or string) and format (fixed length
1119 # in bits, `uleb128`, `sleb128`, or `s:` followed with an encoding
1120 # name), returning an item on success.
1121 def _try_parse_val(self
):
1122 begin_text_loc
= self
._text
_loc
1125 m_expr
= self
._try
_parse
_pat
(self
._val
_expr
_pat
)
1131 # Create an expression node from the expression string
1132 expr_str
, expr
= self
._ast
_expr
_from
_str
(m_expr
.group(1), begin_text_loc
)
1135 m_fmt
= self
._try
_parse
_pat
(self
._fl
_num
_len
_fmt
_pat
)
1139 m_fmt
= self
._try
_parse
_pat
(self
._leb
128_int
_fmt
_pat
)
1143 codec
= self
._try
_parse
_str
_encoding
(True)
1146 # At this point it's invalid
1148 "Expecting a fixed length (multiple of eight bits), `uleb128`, `sleb128`, or `s:` followed with a valid encoding (`u8`, `u16be`, `u16le`, `u32be`, `u32le`, or `latin1` to `latin10`)"
1151 # Return string item
1152 return _Str(expr_str
, expr
, codec
, begin_text_loc
)
1154 # Return LEB128 integer item
1155 cls
= _ULeb128Int
if m_fmt
.group(1) == "u" else _SLeb128Int
1156 return cls(expr_str
, expr
, begin_text_loc
)
1158 # Return fixed-length number item
1162 int(m_fmt
.group(0)),
1166 # Patterns for _try_parse_var_assign()
1167 _var_assign_name_equal_pat
= re
.compile(
1168 r
"({})\s*=(?!=)".format(_py_name_pat
.pattern
)
1170 _var_assign_expr_pat
= re
.compile(r
"[^}]+")
1172 # Tries to parse a variable assignment, returning a variable
1173 # assignment item on success.
1174 def _try_parse_var_assign(self
):
1175 begin_text_loc
= self
._text
_loc
1178 m
= self
._try
_parse
_pat
(self
._var
_assign
_name
_equal
_pat
)
1187 if name
== _icitte_name
:
1189 "`{}` is a reserved variable name".format(_icitte_name
), begin_text_loc
1192 if name
in self
._label
_names
:
1193 _raise_error("Existing label named `{}`".format(name
), begin_text_loc
)
1195 # Expect an expression
1197 m
= self
._expect
_pat
(self
._var
_assign
_expr
_pat
, "Expecting an expression")
1199 # Create an expression node from the expression string
1200 expr_str
, expr
= self
._ast
_expr
_from
_str
(m
.group(0), begin_text_loc
)
1202 # Add to known variable names
1203 self
._var
_names
.add(name
)
1213 # Pattern for _try_parse_set_bo()
1214 _bo_pat
= re
.compile(r
"[bl]e")
1216 # Tries to parse a byte order name, returning a byte order setting
1218 def _try_parse_set_bo(self
):
1219 begin_text_loc
= self
._text
_loc
1222 m
= self
._try
_parse
_pat
(self
._bo
_pat
)
1228 # Return corresponding item
1229 if m
.group(0) == "be":
1230 return _SetBo(ByteOrder
.BE
, begin_text_loc
)
1232 assert m
.group(0) == "le"
1233 return _SetBo(ByteOrder
.LE
, begin_text_loc
)
1235 # Patterns for _try_parse_val_or_bo()
1236 _val_var_assign_set_bo_prefix_pat
= re
.compile(r
"\{")
1237 _val_var_assign_set_bo_suffix_pat
= re
.compile(r
"\}")
1239 # Tries to parse a value, a variable assignment, or a byte order
1240 # setting, returning an item on success.
1241 def _try_parse_val_or_var_assign_or_set_bo(self
):
1243 if self
._try
_parse
_pat
(self
._val
_var
_assign
_set
_bo
_prefix
_pat
) is None:
1249 # Variable assignment item?
1250 item
= self
._try
_parse
_var
_assign
()
1254 item
= self
._try
_parse
_val
()
1257 # Byte order setting item?
1258 item
= self
._try
_parse
_set
_bo
()
1261 # At this point it's invalid
1263 "Expecting a fixed-length number, a string, a variable assignment, or a byte order setting"
1268 self
._expect
_pat
(self
._val
_var
_assign
_set
_bo
_suffix
_pat
, "Expecting `}`")
1271 # Tries to parse an offset setting value (after the initial `<`),
1272 # returning an offset item on success.
1273 def _try_parse_set_offset_val(self
):
1274 begin_text_loc
= self
._text
_loc
1277 m
= self
._try
_parse
_pat
(_pos_const_int_pat
)
1284 return _SetOffset(int(_norm_const_int(m
.group(0)), 0), begin_text_loc
)
1286 # Tries to parse a label name (after the initial `<`), returning a
1287 # label item on success.
1288 def _try_parse_label_name(self
):
1289 begin_text_loc
= self
._text
_loc
1292 m
= self
._try
_parse
_pat
(_py_name_pat
)
1301 if name
== _icitte_name
:
1303 "`{}` is a reserved label name".format(_icitte_name
), begin_text_loc
1306 if name
in self
._label
_names
:
1307 _raise_error("Duplicate label name `{}`".format(name
), begin_text_loc
)
1309 if name
in self
._var
_names
:
1310 _raise_error("Existing variable named `{}`".format(name
), begin_text_loc
)
1312 # Add to known label names
1313 self
._label
_names
.add(name
)
1316 return _Label(name
, begin_text_loc
)
1318 # Patterns for _try_parse_label_or_set_offset()
1319 _label_set_offset_prefix_pat
= re
.compile(r
"<")
1320 _label_set_offset_suffix_pat
= re
.compile(r
">")
1322 # Tries to parse a label or an offset setting, returning an item on
1324 def _try_parse_label_or_set_offset(self
):
1326 if self
._try
_parse
_pat
(self
._label
_set
_offset
_prefix
_pat
) is None:
1330 # Offset setting item?
1332 item
= self
._try
_parse
_set
_offset
_val
()
1336 item
= self
._try
_parse
_label
_name
()
1339 # At this point it's invalid
1340 self
._raise
_error
("Expecting a label name or an offset setting value")
1344 self
._expect
_pat
(self
._label
_set
_offset
_suffix
_pat
, "Expecting `>`")
1347 # Pattern for _parse_pad_val()
1348 _pad_val_prefix_pat
= re
.compile(r
"~")
1350 # Tries to parse a padding value, returning the padding value, or 0
1352 def _parse_pad_val(self
):
1357 if self
._try
_parse
_pat
(self
._pad
_val
_prefix
_pat
) is not None:
1359 pad_val_text_loc
= self
._text
_loc
1360 m
= self
._expect
_pat
(
1362 "Expecting a positive constant integer (byte value)",
1366 pad_val
= int(_norm_const_int(m
.group(0)), 0)
1370 "Invalid padding byte value {}".format(pad_val
),
1376 # Patterns for _try_parse_align_offset()
1377 _align_offset_prefix_pat
= re
.compile(r
"@")
1378 _align_offset_val_pat
= re
.compile(r
"\d+")
1380 # Tries to parse an offset alignment, returning an offset alignment
1382 def _try_parse_align_offset(self
):
1383 begin_text_loc
= self
._text
_loc
1386 if self
._try
_parse
_pat
(self
._align
_offset
_prefix
_pat
) is None:
1390 # Expect an alignment
1392 align_text_loc
= self
._text
_loc
1393 m
= self
._expect
_pat
(
1394 self
._align
_offset
_val
_pat
,
1395 "Expecting an alignment (positive multiple of eight bits)",
1398 # Validate alignment
1399 val
= int(m
.group(0))
1401 if val
<= 0 or (val
% 8) != 0:
1403 "Invalid alignment value {} (not a positive multiple of eight)".format(
1410 pad_val
= self
._parse
_pad
_val
()
1413 return _AlignOffset(val
, pad_val
, begin_text_loc
)
1415 # Patterns for _expect_expr()
1416 _inner_expr_prefix_pat
= re
.compile(r
"\{")
1417 _inner_expr_pat
= re
.compile(r
"[^}]+")
1418 _inner_expr_suffix_pat
= re
.compile(r
"\}")
1420 # Parses an expression outside a `{`/`}` context.
1422 # This function accepts:
1424 # • A Python expression within `{` and `}`.
1426 # • A Python name.
1428 # • If `accept_const_int` is `True`: a constant integer, which may
1429 # be negative if `allow_neg_int` is `True`.
1431 # • If `accept_float` is `True`: a constant floating point number.
1433 # Returns the stripped expression string and AST expression.
1436 accept_const_int
: bool = False,
1437 allow_neg_int
: bool = False,
1438 accept_const_float
: bool = False,
1439 accept_lit_str
: bool = False,
1441 begin_text_loc
= self
._text
_loc
1443 # Constant floating point number?
1444 if accept_const_float
:
1445 m
= self
._try
_parse
_pat
(_const_float_pat
)
1448 return self
._ast
_expr
_from
_str
(m
.group(0), begin_text_loc
)
1451 if accept_const_int
:
1452 m
= self
._try
_parse
_pat
(_const_int_pat
)
1455 # Negative and allowed?
1456 if m
.group("neg") == "-" and not allow_neg_int
:
1458 "Expecting a positive constant integer", begin_text_loc
1461 expr_str
= _norm_const_int(m
.group(0))
1462 return self
._ast
_expr
_from
_str
(expr_str
, begin_text_loc
)
1465 m
= self
._try
_parse
_pat
(_py_name_pat
)
1468 return self
._ast
_expr
_from
_str
(m
.group(0), begin_text_loc
)
1472 val
= self
._try
_parse
_lit
_str
(True)
1475 return self
._ast
_expr
_from
_str
(repr(val
), begin_text_loc
)
1478 msg_accepted_parts
= ["a name", "or `{`"]
1481 msg_accepted_parts
.insert(0, "a literal string")
1483 if accept_const_float
:
1484 msg_accepted_parts
.insert(0, "a constant floating point number")
1486 if accept_const_int
:
1487 msg_pos
= "" if allow_neg_int
else "positive "
1488 msg_accepted_parts
.insert(0, "a {}constant integer".format(msg_pos
))
1490 if len(msg_accepted_parts
) == 2:
1491 msg_accepted
= " ".join(msg_accepted_parts
)
1493 msg_accepted
= ", ".join(msg_accepted_parts
)
1496 self
._inner
_expr
_prefix
_pat
,
1497 "Expecting {}".format(msg_accepted
),
1500 # Expect an expression
1502 expr_text_loc
= self
._text
_loc
1503 m
= self
._expect
_pat
(self
._inner
_expr
_pat
, "Expecting an expression")
1504 expr_str
= m
.group(0)
1508 self
._expect
_pat
(self
._inner
_expr
_suffix
_pat
, "Expecting `}`")
1510 return self
._ast
_expr
_from
_str
(expr_str
, expr_text_loc
)
1512 # Patterns for _try_parse_fill_until()
1513 _fill_until_prefix_pat
= re
.compile(r
"\+")
1514 _fill_until_pad_val_prefix_pat
= re
.compile(r
"~")
1516 # Tries to parse a filling, returning a filling item on success.
1517 def _try_parse_fill_until(self
):
1518 begin_text_loc
= self
._text
_loc
1521 if self
._try
_parse
_pat
(self
._fill
_until
_prefix
_pat
) is None:
1527 expr_str
, expr
= self
._expect
_expr
(accept_const_int
=True)
1530 pad_val
= self
._parse
_pad
_val
()
1533 return _FillUntil(expr_str
, expr
, pad_val
, begin_text_loc
)
1535 # Parses the multiplier expression of a repetition (block or
1536 # post-item) and returns the expression string and AST node.
1537 def _expect_rep_mul_expr(self
):
1538 return self
._expect
_expr
(accept_const_int
=True)
1540 # Common block end pattern
1541 _block_end_pat
= re
.compile(r
"!end\b")
1543 # Pattern for _try_parse_rep_block()
1544 _rep_block_prefix_pat
= re
.compile(r
"!r(?:epeat)?\b")
1546 # Tries to parse a repetition block, returning a repetition item on
1548 def _try_parse_rep_block(self
):
1549 begin_text_loc
= self
._text
_loc
1552 if self
._try
_parse
_pat
(self
._rep
_block
_prefix
_pat
) is None:
1557 self
._skip
_ws
_and
_comments
()
1558 expr_str
, expr
= self
._expect
_rep
_mul
_expr
()
1561 self
._skip
_ws
_and
_comments
()
1562 items_text_loc
= self
._text
_loc
1563 items
= self
._parse
_items
()
1565 # Expect end of block
1566 self
._skip
_ws
_and
_comments
()
1568 self
._block
_end
_pat
, "Expecting an item or `!end` (end of repetition block)"
1572 return _Rep(_Group(items
, items_text_loc
), expr_str
, expr
, begin_text_loc
)
1574 # Pattern for _try_parse_cond_block()
1575 _cond_block_prefix_pat
= re
.compile(r
"!if\b")
1576 _cond_block_else_pat
= re
.compile(r
"!else\b")
1578 # Tries to parse a conditional block, returning a conditional item
1580 def _try_parse_cond_block(self
):
1581 begin_text_loc
= self
._text
_loc
1584 if self
._try
_parse
_pat
(self
._cond
_block
_prefix
_pat
) is None:
1589 self
._skip
_ws
_and
_comments
()
1590 expr_str
, expr
= self
._expect
_expr
()
1592 # Parse "true" items
1593 self
._skip
_ws
_and
_comments
()
1594 true_items_text_loc
= self
._text
_loc
1595 true_items
= self
._parse
_items
()
1596 false_items
= [] # type: List[_Item]
1597 false_items_text_loc
= begin_text_loc
1600 self
._skip
_ws
_and
_comments
()
1602 if self
._try
_parse
_pat
(self
._cond
_block
_else
_pat
) is not None:
1603 # Parse "false" items
1604 self
._skip
_ws
_and
_comments
()
1605 false_items_text_loc
= self
._text
_loc
1606 false_items
= self
._parse
_items
()
1608 # Expect end of block
1610 self
._block
_end
_pat
,
1611 "Expecting an item, `!else`, or `!end` (end of conditional block)",
1616 _Group(true_items
, true_items_text_loc
),
1617 _Group(false_items
, false_items_text_loc
),
1623 # Common left parenthesis pattern
1624 _left_paren_pat
= re
.compile(r
"\(")
1626 # Patterns for _try_parse_macro_def() and _try_parse_macro_exp()
1627 _macro_params_comma_pat
= re
.compile(",")
1629 # Patterns for _try_parse_macro_def()
1630 _macro_def_prefix_pat
= re
.compile(r
"!m(?:acro)?\b")
1632 # Tries to parse a macro definition, adding it to `self._macro_defs`
1633 # and returning `True` on success.
1634 def _try_parse_macro_def(self
):
1635 begin_text_loc
= self
._text
_loc
1638 if self
._try
_parse
_pat
(self
._macro
_def
_prefix
_pat
) is None:
1644 name_text_loc
= self
._text
_loc
1645 m
= self
._expect
_pat
(_py_name_pat
, "Expecting a valid macro name")
1650 if name
in self
._macro
_defs
:
1651 _raise_error("Duplicate macro named `{}`".format(name
), name_text_loc
)
1655 self
._expect
_pat
(self
._left
_paren
_pat
, "Expecting `(`")
1657 # Try to parse comma-separated parameter names
1658 param_names
= [] # type: List[str]
1659 expect_comma
= False
1665 if self
._try
_parse
_pat
(self
._right
_paren
_pat
) is not None:
1671 self
._expect
_pat
(self
._macro
_params
_comma
_pat
, "Expecting `,`")
1673 # Expect parameter name
1675 param_text_loc
= self
._text
_loc
1676 m
= self
._expect
_pat
(_py_name_pat
, "Expecting valid parameter name")
1678 if m
.group(0) in param_names
:
1680 "Duplicate macro parameter named `{}`".format(m
.group(0)),
1684 param_names
.append(m
.group(0))
1688 self
._skip
_ws
_and
_comments
()
1689 items_text_loc
= self
._text
_loc
1690 old_var_names
= self
._var
_names
.copy()
1691 old_label_names
= self
._label
_names
.copy()
1692 self
._var
_names
= set() # type: Set[str]
1693 self
._label
_names
= set() # type: Set[str]
1694 items
= self
._parse
_items
()
1695 self
._var
_names
= old_var_names
1696 self
._label
_names
= old_label_names
1700 self
._block
_end
_pat
, "Expecting an item or `!end` (end of macro block)"
1704 self
._macro
_defs
[name
] = _MacroDef(
1705 name
, param_names
, _Group(items
, items_text_loc
), begin_text_loc
1710 # Patterns for _try_parse_macro_exp()
1711 _macro_exp_prefix_pat
= re
.compile(r
"m\b")
1712 _macro_exp_colon_pat
= re
.compile(r
":")
1714 # Tries to parse a macro expansion, returning a macro expansion item
1716 def _try_parse_macro_exp(self
):
1717 begin_text_loc
= self
._text
_loc
1720 if self
._try
_parse
_pat
(self
._macro
_exp
_prefix
_pat
) is None:
1726 self
._expect
_pat
(self
._macro
_exp
_colon
_pat
, "Expecting `:`")
1728 # Expect a macro name
1730 name_text_loc
= self
._text
_loc
1731 m
= self
._expect
_pat
(_py_name_pat
, "Expecting a valid macro name")
1735 macro_def
= self
._macro
_defs
.get(name
)
1737 if macro_def
is None:
1738 _raise_error("Unknown macro name `{}`".format(name
), name_text_loc
)
1742 self
._expect
_pat
(self
._left
_paren
_pat
, "Expecting `(`")
1744 # Try to parse comma-separated parameter values
1745 params_text_loc
= self
._text
_loc
1746 params
= [] # type: List[_MacroExpParam]
1747 expect_comma
= False
1753 if self
._try
_parse
_pat
(self
._right
_paren
_pat
) is not None:
1759 self
._expect
_pat
(self
._macro
_params
_comma
_pat
, "Expecting `,`")
1762 param_text_loc
= self
._text
_loc
1766 accept_const_int
=True,
1768 accept_const_float
=True,
1769 accept_lit_str
=True,
1771 text_loc
=param_text_loc
1776 # Validate parameter values
1777 if len(params
) != len(macro_def
.param_names
):
1778 sing_plur
= "" if len(params
) == 1 else "s"
1780 "Macro expansion passes {} parameter{} while the definition expects {}".format(
1781 len(params
), sing_plur
, len(macro_def
.param_names
)
1787 return _MacroExp(name
, params
, begin_text_loc
)
1789 # Tries to parse a base item (anything except a repetition),
1790 # returning it on success.
1791 def _try_parse_base_item(self
):
1793 item
= self
._try
_parse
_byte
()
1795 if item
is not None:
1799 item
= self
._try
_parse
_str
()
1801 if item
is not None:
1804 # Value, variable assignment, or byte order setting item?
1805 item
= self
._try
_parse
_val
_or
_var
_assign
_or
_set
_bo
()
1807 if item
is not None:
1810 # Label or offset setting item?
1811 item
= self
._try
_parse
_label
_or
_set
_offset
()
1813 if item
is not None:
1816 # Offset alignment item?
1817 item
= self
._try
_parse
_align
_offset
()
1819 if item
is not None:
1823 item
= self
._try
_parse
_fill
_until
()
1825 if item
is not None:
1829 item
= self
._try
_parse
_group
()
1831 if item
is not None:
1834 # Repetition block item?
1835 item
= self
._try
_parse
_rep
_block
()
1837 if item
is not None:
1840 # Conditional block item?
1841 item
= self
._try
_parse
_cond
_block
()
1843 if item
is not None:
1847 item
= self
._try
_parse
_macro
_exp
()
1849 if item
is not None:
1852 # Pattern for _try_parse_rep_post()
1853 _rep_post_prefix_pat
= re
.compile(r
"\*")
1855 # Tries to parse a post-item repetition, returning the expression
1856 # string and AST expression node on success.
1857 def _try_parse_rep_post(self
):
1859 if self
._try
_parse
_pat
(self
._rep
_post
_prefix
_pat
) is None:
1863 # Return expression string and AST expression
1864 self
._skip
_ws
_and
_comments
()
1865 return self
._expect
_rep
_mul
_expr
()
1867 # Tries to parse an item, possibly followed by a repetition,
1868 # returning `True` on success.
1870 # Appends any parsed item to `items`.
1871 def _try_append_item(self
, items
: List
[_Item
]):
1872 self
._skip
_ws
_and
_comments
()
1875 item
= self
._try
_parse
_base
_item
()
1880 # Parse repetition if the base item is repeatable
1881 if isinstance(item
, _RepableItem
):
1882 self
._skip
_ws
_and
_comments
()
1883 rep_text_loc
= self
._text
_loc
1884 rep_ret
= self
._try
_parse
_rep
_post
()
1886 if rep_ret
is not None:
1887 item
= _Rep(item
, *rep_ret
, text_loc
=rep_text_loc
)
1892 # Parses and returns items, skipping whitespaces, insignificant
1893 # symbols, and comments when allowed, and stopping at the first
1894 # unknown character.
1896 # Accepts and registers macro definitions if `accept_macro_defs`
1898 def _parse_items(self
, accept_macro_defs
: bool = False) -> List
[_Item
]:
1899 items
= [] # type: List[_Item]
1901 while self
._isnt
_done
():
1902 # Try to append item
1903 if not self
._try
_append
_item
(items
):
1904 if accept_macro_defs
and self
._try
_parse
_macro
_def
():
1907 # Unknown at this point
1912 # Parses the whole Normand input, setting `self._res` to the main
1913 # group item on success.
1915 if len(self
._normand
.strip()) == 0:
1916 # Special case to make sure there's something to consume
1917 self
._res
= _Group([], self
._text
_loc
)
1920 # Parse first level items
1921 items
= self
._parse
_items
(True)
1923 # Make sure there's nothing left
1924 self
._skip
_ws
_and
_comments
()
1926 if self
._isnt
_done
():
1928 "Unexpected character `{}`".format(self
._normand
[self
._at
])
1931 # Set main group item
1932 self
._res
= _Group(items
, self
._text
_loc
)
1935 # The return type of parse().
1941 variables
: VariablesT
,
1944 bo
: Optional
[ByteOrder
],
1946 self
= cls
.__new
__(cls
)
1947 self
._init
(data
, variables
, labels
, offset
, bo
)
1950 def __init__(self
, *args
, **kwargs
): # type: ignore
1951 raise NotImplementedError
1956 variables
: VariablesT
,
1959 bo
: Optional
[ByteOrder
],
1962 self
._vars
= variables
1963 self
._labels
= labels
1964 self
._offset
= offset
1972 # Dictionary of updated variable names to their last computed value.
1974 def variables(self
):
1977 # Dictionary of updated main group label names to their computed
1988 # Updated byte order.
1990 def byte_order(self
):
1994 # Raises a parse error for the item `item`, creating it using the
1996 def _raise_error_for_item(msg
: str, item
: _Item
) -> NoReturn
:
1997 _raise_error(msg
, item
.text_loc
)
2000 # The `ICITTE` reserved name.
2001 _icitte_name
= "ICITTE"
2004 # Base node visitor.
2006 # Calls the _visit_name() method for each name node which isn't the name
2008 class _NodeVisitor(ast
.NodeVisitor
):
2010 self
._parent
_is
_call
= False
2012 def generic_visit(self
, node
: ast
.AST
):
2013 if type(node
) is ast
.Call
:
2014 self
._parent
_is
_call
= True
2015 elif type(node
) is ast
.Name
and not self
._parent
_is
_call
:
2016 self
._visit
_name
(node
.id)
2018 super().generic_visit(node
)
2019 self
._parent
_is
_call
= False
2022 def _visit_name(self
, name
: str):
2026 # Expression validator: validates that all the names within the
2027 # expression are allowed.
2028 class _ExprValidator(_NodeVisitor
):
2029 def __init__(self
, expr_str
: str, text_loc
: TextLocation
, allowed_names
: Set
[str]):
2031 self
._expr
_str
= expr_str
2032 self
._text
_loc
= text_loc
2033 self
._allowed
_names
= allowed_names
2035 def _visit_name(self
, name
: str):
2036 # Make sure the name refers to a known and reachable
2037 # variable/label name.
2038 if name
!= _icitte_name
and name
not in self
._allowed
_names
:
2039 msg
= "Illegal (unknown or unreachable) variable/label name `{}` in expression `{}`".format(
2040 name
, self
._expr
_str
2043 allowed_names
= self
._allowed
_names
.copy()
2044 allowed_names
.add(_icitte_name
)
2046 if len(allowed_names
) > 0:
2047 allowed_names_str
= ", ".join(
2048 sorted(["`{}`".format(name
) for name
in allowed_names
])
2050 msg
+= "; the legal names are {{{}}}".format(allowed_names_str
)
2062 variables
: VariablesT
,
2065 bo
: Optional
[ByteOrder
],
2067 self
.variables
= variables
.copy()
2068 self
.labels
= labels
.copy()
2069 self
.offset
= offset
2073 return "_GenState({}, {}, {}, {})".format(
2074 repr(self
.variables
), repr(self
.labels
), repr(self
.offset
), repr(self
.bo
)
2078 # Fixed-length number item instance.
2079 class _FlNumItemInst
:
2083 offset_in_data
: int,
2085 parse_error_msgs
: List
[ParseErrorMessage
],
2088 self
._offset
_in
_data
= offset_in_data
2090 self
._parse
_error
_msgs
= parse_error_msgs
2097 def offset_in_data(self
):
2098 return self
._offset
_in
_data
2105 def parse_error_msgs(self
):
2106 return self
._parse
_error
_msgs
2109 # Generator of data and final state from a group item.
2111 # Generation happens in memory at construction time. After building, use
2112 # the `data`, `variables`, `labels`, `offset`, and `bo` properties to
2113 # get the resulting context.
2115 # The steps of generation are:
2117 # 1. Handle each item in prefix order.
2119 # The handlers append bytes to `self._data` and update some current
2120 # state object (`_GenState` instance).
2122 # When handling a fixed-length number item, try to evaluate its
2123 # expression using the current state. If this fails, then it might be
2124 # because the expression refers to a "future" label: save the current
2125 # offset in `self._data` (generated data) and a snapshot of the
2126 # current state within `self._fl_num_item_insts` (`_FlNumItemInst`
2127 # object). _gen_fl_num_item_insts() will deal with this later. A
2128 # `_FlNumItemInst` instance also contains a snapshot of the current
2129 # parsing error messages (`self._parse_error_msgs`) which need to be
2130 # taken into account when handling the instance later.
2132 # When handling the items of a group, keep a map of immediate label
2133 # names to their offset. Then, after having processed all the items,
2134 # update the relevant saved state snapshots in
2135 # `self._fl_num_item_insts` with those immediate label values.
2136 # _gen_fl_num_item_insts() will deal with this later.
2138 # 2. Handle all the fixed-length number item instances of which the
2139 # expression evaluation failed before.
2141 # At this point, `self._fl_num_item_insts` contains everything that's
2142 # needed to evaluate the expressions, including the values of
2143 # "future" labels from the point of view of some fixed-length number
2146 # If an evaluation fails at this point, then it's a user error. Add
2147 # to the parsing error all the saved parsing error messages of the
2148 # instance. Those additional messages add precious context to the
2154 macro_defs
: _MacroDefsT
,
2155 variables
: VariablesT
,
2158 bo
: Optional
[ByteOrder
],
2160 self
._macro
_defs
= macro_defs
2161 self
._fl
_num
_item
_insts
= [] # type: List[_FlNumItemInst]
2162 self
._parse
_error
_msgs
= [] # type: List[ParseErrorMessage]
2163 self
._gen
(group
, _GenState(variables
, labels
, offset
, bo
))
2170 # Updated variables.
2172 def variables(self
):
2173 return self
._final
_state
.variables
2175 # Updated main group labels.
2178 return self
._final
_state
.labels
2183 return self
._final
_state
.offset
2185 # Updated byte order.
2188 return self
._final
_state
.bo
2190 # Evaluates the expression `expr` of which the original string is
2191 # `expr_str` at the location `text_loc` considering the current
2192 # generation state `state`.
2194 # If `accept_float` is `True`, then the type of the result may be
2197 # If `accept_str` is `True`, then the type of the result may be
2202 expr
: ast
.Expression
,
2203 text_loc
: TextLocation
,
2205 accept_float
: bool = False,
2206 accept_str
: bool = False,
2208 syms
= {} # type: VariablesT
2209 syms
.update(state
.labels
)
2211 # Set the `ICITTE` name to the current offset
2212 syms
[_icitte_name
] = state
.offset
2214 # Add the current variables
2215 syms
.update(state
.variables
)
2217 # Validate the node and its children
2218 _ExprValidator(expr_str
, text_loc
, set(syms
.keys())).visit(expr
)
2220 # Compile and evaluate expression node
2222 val
= eval(compile(expr
, "", "eval"), None, syms
)
2223 except Exception as exc
:
2225 "Failed to evaluate expression `{}`: {}".format(expr_str
, exc
),
2229 # Convert `bool` result type to `int` to normalize
2230 if type(val
) is bool:
2233 # Validate result type
2234 expected_types
= {int}
# type: Set[type]
2237 expected_types
.add(float)
2240 expected_types
.add(str)
2242 if type(val
) not in expected_types
:
2243 expected_types_str
= sorted(
2244 ["`{}`".format(t
.__name
__) for t
in expected_types
]
2247 if len(expected_types_str
) == 1:
2248 msg_expected
= expected_types_str
[0]
2249 elif len(expected_types_str
) == 2:
2250 msg_expected
= " or ".join(expected_types_str
)
2252 expected_types_str
[-1] = "or {}".format(expected_types_str
[-1])
2253 msg_expected
= ", ".join(expected_types_str
)
2256 "Invalid expression `{}`: expecting result type {}, not `{}`".format(
2257 expr_str
, msg_expected
, type(val
).__name
__
2264 # Forwards to _eval_expr() with the expression and text location of
2267 def _eval_item_expr(
2268 item
: Union
[_Cond
, _FillUntil
, _FlNum
, _Leb128Int
, _Rep
, _Str
, _VarAssign
],
2270 accept_float
: bool = False,
2271 accept_str
: bool = False,
2273 return _Gen
._eval
_expr
(
2274 item
.expr_str
, item
.expr
, item
.text_loc
, state
, accept_float
, accept_str
2277 # Handles the byte item `item`.
2278 def _handle_byte_item(self
, item
: _Byte
, state
: _GenState
):
2279 self
._data
.append(item
.val
)
2280 state
.offset
+= item
.size
2282 # Handles the literal string item `item`.
2283 def _handle_lit_str_item(self
, item
: _LitStr
, state
: _GenState
):
2284 self
._data
+= item
.data
2285 state
.offset
+= item
.size
2287 # Handles the byte order setting item `item`.
2288 def _handle_set_bo_item(self
, item
: _SetBo
, state
: _GenState
):
2289 # Update current byte order
2292 # Handles the variable assignment item `item`.
2293 def _handle_var_assign_item(self
, item
: _VarAssign
, state
: _GenState
):
2295 state
.variables
[item
.name
] = self
._eval
_item
_expr
(
2296 item
, state
, accept_float
=True, accept_str
=True
2299 # Handles the fixed-length number item `item`.
2300 def _handle_fl_num_item(self
, item
: _FlNum
, state
: _GenState
):
2301 # Validate current byte order
2302 if state
.bo
is None and item
.len > 8:
2303 _raise_error_for_item(
2304 "Current byte order isn't defined at first fixed-length number (`{}`) to encode on more than 8 bits".format(
2310 # Try an immediate evaluation. If it fails, then keep everything
2311 # needed to (try to) generate the bytes of this item later.
2313 data
= self
._gen
_fl
_num
_item
_inst
_data
(item
, state
)
2315 self
._fl
_num
_item
_insts
.append(
2319 copy
.deepcopy(state
),
2320 copy
.deepcopy(self
._parse
_error
_msgs
),
2324 # Reserve space in `self._data` for this instance
2325 data
= bytes([0] * (item
.len // 8))
2331 state
.offset
+= len(data
)
2333 # Returns the size, in bytes, required to encode the value `val`
2334 # with LEB128 (signed version if `is_signed` is `True`).
2336 def _leb128_size_for_val(val
: int, is_signed
: bool):
2338 # Equivalent upper bound.
2340 # For example, if `val` is -128, then the full integer for
2341 # this number of bits would be [-128, 127].
2344 # Number of bits (add one for the sign if needed)
2345 bits
= val
.bit_length() + int(is_signed
)
2350 # Seven bits per byte
2351 return math
.ceil(bits
/ 7)
2353 # Handles the LEB128 integer item `item`.
2354 def _handle_leb128_int_item(self
, item
: _Leb128Int
, state
: _GenState
):
2356 val
= self
._eval
_item
_expr
(item
, state
)
2359 size
= self
._leb
128_size
_for
_val
(val
, type(item
) is _SLeb128Int
)
2362 for _
in range(size
):
2363 # Seven LSBs, MSB of the byte set (continue)
2364 self
._data
.append((val
& 0x7F) |
0x80)
2367 # Clear MSB of last byte (stop)
2368 self
._data
[-1] &= ~
0x80
2371 state
.offset
+= size
2373 # Handles the string item `item`.
2374 def _handle_str_item(self
, item
: _Str
, state
: _GenState
):
2376 val
= str(self
._eval
_item
_expr
(item
, state
, accept_float
=True, accept_str
=True))
2379 data
= _encode_str(val
, item
.codec
, item
.text_loc
)
2385 state
.offset
+= len(data
)
2387 # Handles the group item `item`, removing the immediate labels from
2388 # `state` at the end if `remove_immediate_labels` is `True`.
2389 def _handle_group_item(
2390 self
, item
: _Group
, state
: _GenState
, remove_immediate_labels
: bool = True
2392 first_fl_num_item_inst_index
= len(self
._fl
_num
_item
_insts
)
2393 immediate_labels
= {} # type: LabelsT
2396 for subitem
in item
.items
:
2397 if type(subitem
) is _Label
:
2398 # Add to local immediate labels
2399 immediate_labels
[subitem
.name
] = state
.offset
2401 self
._handle
_item
(subitem
, state
)
2403 # Remove immediate labels from current state if needed
2404 if remove_immediate_labels
:
2405 for name
in immediate_labels
:
2406 del state
.labels
[name
]
2408 # Add all immediate labels to all state snapshots since
2409 # `first_fl_num_item_inst_index`.
2410 for inst
in self
._fl
_num
_item
_insts
[first_fl_num_item_inst_index
:]:
2411 inst
.state
.labels
.update(immediate_labels
)
2413 # Handles the repetition item `item`.
2414 def _handle_rep_item(self
, item
: _Rep
, state
: _GenState
):
2415 # Compute the repetition count
2416 mul
= _Gen
._eval
_item
_expr
(item
, state
)
2420 _raise_error_for_item(
2421 "Invalid expression `{}`: unexpected negative result {:,}".format(
2427 # Generate item data `mul` times
2428 for _
in range(mul
):
2429 self
._handle
_item
(item
.item
, state
)
2431 # Handles the conditional item `item`.
2432 def _handle_cond_item(self
, item
: _Cond
, state
: _GenState
):
2433 # Compute the conditional value
2434 val
= _Gen
._eval
_item
_expr
(item
, state
)
2436 # Generate item data if needed
2438 self
._handle
_item
(item
.true_item
, state
)
2440 self
._handle
_item
(item
.false_item
, state
)
2442 # Evaluates the parameters of the macro expansion item `item`
2443 # considering the initial state `init_state` and returns a new state
2444 # to handle the items of the macro.
2445 def _eval_macro_exp_params(self
, item
: _MacroExp
, init_state
: _GenState
):
2447 exp_state
= _GenState({}, {}, init_state
.offset
, init_state
.bo
)
2449 # Evaluate the parameter expressions
2450 macro_def
= self
._macro
_defs
[item
.name
]
2452 for param_name
, param
in zip(macro_def
.param_names
, item
.params
):
2453 exp_state
.variables
[param_name
] = _Gen
._eval
_expr
(
2464 # Handles the macro expansion item `item`.
2465 def _handle_macro_exp_item(self
, item
: _MacroExp
, state
: _GenState
):
2466 parse_error_msg_text
= "While expanding the macro `{}`:".format(item
.name
)
2470 exp_state
= self
._eval
_macro
_exp
_params
(item
, state
)
2472 # Process the contained group
2473 init_data_size
= len(self
._data
)
2475 ParseErrorMessage
._create
( # pyright: ignore[reportPrivateUsage]
2476 parse_error_msg_text
, item
.text_loc
2479 self
._parse
_error
_msgs
.append(parse_error_msg
)
2480 self
._handle
_item
(self
._macro
_defs
[item
.name
].group
, exp_state
)
2481 self
._parse
_error
_msgs
.pop()
2482 except ParseError
as exc
:
2483 _augment_error(exc
, parse_error_msg_text
, item
.text_loc
)
2485 # Update state offset and return
2486 state
.offset
+= len(self
._data
) - init_data_size
2488 # Handles the offset setting item `item`.
2489 def _handle_set_offset_item(self
, item
: _SetOffset
, state
: _GenState
):
2490 state
.offset
= item
.val
2492 # Handles the offset alignment item `item` (adds padding).
2493 def _handle_align_offset_item(self
, item
: _AlignOffset
, state
: _GenState
):
2494 init_offset
= state
.offset
2495 align_bytes
= item
.val
// 8
2496 state
.offset
= (state
.offset
+ align_bytes
- 1) // align_bytes
* align_bytes
2497 self
._data
+= bytes([item
.pad_val
] * (state
.offset
- init_offset
))
2499 # Handles the filling item `item` (adds padding).
2500 def _handle_fill_until_item(self
, item
: _FillUntil
, state
: _GenState
):
2501 # Compute the new offset
2502 new_offset
= _Gen
._eval
_item
_expr
(item
, state
)
2504 # Validate the new offset
2505 if new_offset
< state
.offset
:
2506 _raise_error_for_item(
2507 "Invalid expression `{}`: new offset {:,} is less than current offset {:,}".format(
2508 item
.expr_str
, new_offset
, state
.offset
2514 self
._data
+= bytes([item
.pad_val
] * (new_offset
- state
.offset
))
2517 state
.offset
= new_offset
2519 # Handles the label item `item`.
2520 def _handle_label_item(self
, item
: _Label
, state
: _GenState
):
2521 state
.labels
[item
.name
] = state
.offset
2523 # Handles the item `item`, returning the updated next repetition
2525 def _handle_item(self
, item
: _Item
, state
: _GenState
):
2526 return self
._item
_handlers
[type(item
)](item
, state
)
2528 # Generates the data for a fixed-length integer item instance having
2529 # the value `val` and returns it.
2530 def _gen_fl_int_item_inst_data(self
, val
: int, item
: _FlNum
, state
: _GenState
):
2532 if val
< -(2 ** (item
.len - 1)) or val
> 2**item
.len - 1:
2533 _raise_error_for_item(
2534 "Value {:,} is outside the {}-bit range when evaluating expression `{}`".format(
2535 val
, item
.len, item
.expr_str
2540 # Encode result on 64 bits (to extend the sign bit whatever the
2541 # value of `item.len`).
2544 ">" if state
.bo
in (None, ByteOrder
.BE
) else "<",
2545 "Q" if val
>= 0 else "q",
2550 # Keep only the requested length
2551 len_bytes
= item
.len // 8
2553 if state
.bo
in (None, ByteOrder
.BE
):
2554 # Big endian: keep last bytes
2555 data
= data
[-len_bytes
:]
2557 # Little endian: keep first bytes
2558 assert state
.bo
== ByteOrder
.LE
2559 data
= data
[:len_bytes
]
2564 # Generates the data for a fixed-length floating point number item
2565 # instance having the value `val` and returns it.
2566 def _gen_fl_float_item_inst_data(self
, val
: float, item
: _FlNum
, state
: _GenState
):
2568 if item
.len not in (32, 64):
2569 _raise_error_for_item(
2570 "Invalid {}-bit length for a fixed-length floating point number (value {:,})".format(
2576 # Encode and return result
2579 ">" if state
.bo
in (None, ByteOrder
.BE
) else "<",
2580 "f" if item
.len == 32 else "d",
2585 # Generates the data for a fixed-length number item instance and
2587 def _gen_fl_num_item_inst_data(self
, item
: _FlNum
, state
: _GenState
):
2589 val
= self
._eval
_item
_expr
(item
, state
, True)
2591 # Handle depending on type
2592 if type(val
) is int:
2593 return self
._gen
_fl
_int
_item
_inst
_data
(val
, item
, state
)
2595 assert type(val
) is float
2596 return self
._gen
_fl
_float
_item
_inst
_data
(val
, item
, state
)
2598 # Generates the data for all the fixed-length number item instances
2599 # and writes it at the correct offset within `self._data`.
2600 def _gen_fl_num_item_insts(self
):
2601 for inst
in self
._fl
_num
_item
_insts
:
2604 data
= self
._gen
_fl
_num
_item
_inst
_data
(inst
.item
, inst
.state
)
2605 except ParseError
as exc
:
2606 # Add all the saved parse error messages for this
2608 for msg
in reversed(inst
.parse_error_msgs
):
2609 _add_error_msg(exc
, msg
.text
, msg
.text_location
)
2613 # Insert bytes into `self._data`
2614 self
._data
[inst
.offset_in_data
: inst
.offset_in_data
+ len(data
)] = data
2616 # Generates the data (`self._data`) and final state
2617 # (`self._final_state`) from `group` and the initial state `state`.
2618 def _gen(self
, group
: _Group
, state
: _GenState
):
2620 self
._data
= bytearray()
2623 self
._item
_handlers
= {
2624 _AlignOffset
: self
._handle
_align
_offset
_item
,
2625 _Byte
: self
._handle
_byte
_item
,
2626 _Cond
: self
._handle
_cond
_item
,
2627 _FillUntil
: self
._handle
_fill
_until
_item
,
2628 _FlNum
: self
._handle
_fl
_num
_item
,
2629 _Group
: self
._handle
_group
_item
,
2630 _Label
: self
._handle
_label
_item
,
2631 _LitStr
: self
._handle
_lit
_str
_item
,
2632 _MacroExp
: self
._handle
_macro
_exp
_item
,
2633 _Rep
: self
._handle
_rep
_item
,
2634 _SetBo
: self
._handle
_set
_bo
_item
,
2635 _SetOffset
: self
._handle
_set
_offset
_item
,
2636 _SLeb128Int
: self
._handle
_leb
128_int
_item
,
2637 _Str
: self
._handle
_str
_item
,
2638 _ULeb128Int
: self
._handle
_leb
128_int
_item
,
2639 _VarAssign
: self
._handle
_var
_assign
_item
,
2640 } # type: Dict[type, Callable[[Any, _GenState], None]]
2642 # Handle the group item, _not_ removing the immediate labels
2643 # because the `labels` property offers them.
2644 self
._handle
_group
_item
(group
, state
, False)
2646 # This is actually the final state
2647 self
._final
_state
= state
2649 # Generate all the fixed-length number bytes now that we know
2651 self
._gen
_fl
_num
_item
_insts
()
2654 # Returns a `ParseResult` instance containing the bytes encoded by the
2655 # input string `normand`.
2657 # `init_variables` is a dictionary of initial variable names (valid
2658 # Python names) to integral values. A variable name must not be the
2659 # reserved name `ICITTE`.
2661 # `init_labels` is a dictionary of initial label names (valid Python
2662 # names) to integral values. A label name must not be the reserved name
2665 # `init_offset` is the initial offset.
2667 # `init_byte_order` is the initial byte order.
2669 # Raises `ParseError` on any parsing error.
2672 init_variables
: Optional
[VariablesT
] = None,
2673 init_labels
: Optional
[LabelsT
] = None,
2674 init_offset
: int = 0,
2675 init_byte_order
: Optional
[ByteOrder
] = None,
2677 if init_variables
is None:
2680 if init_labels
is None:
2683 parser
= _Parser(normand
, init_variables
, init_labels
)
2692 return ParseResult
._create
( # pyright: ignore[reportPrivateUsage]
2693 gen
.data
, gen
.variables
, gen
.labels
, gen
.offset
, gen
.bo
2697 # Raises a command-line error with the message `msg`.
2698 def _raise_cli_error(msg
: str) -> NoReturn
:
2699 raise RuntimeError("Command-line error: {}".format(msg
))
2702 # Returns the `int` or `float` value out of a CLI assignment value.
2703 def _val_from_assign_val_str(s
: str, is_label
: bool):
2706 # Floating point number?
2708 m
= _const_float_pat
.fullmatch(s
)
2711 return float(m
.group(0))
2714 m
= _const_int_pat
.fullmatch(s
)
2717 return int(_norm_const_int(m
.group(0)), 0)
2719 exp
= "an integer" if is_label
else "a number"
2720 _raise_cli_error("Invalid assignment value `{}`: expecting {}".format(s
, exp
))
2723 # Returns a dictionary of string to numbers from the list of strings
2724 # `args` containing `NAME=VAL` entries.
2725 def _dict_from_arg(args
: Optional
[List
[str]], is_label
: bool, is_str_only
: bool):
2726 d
= {} # type: VariablesT
2732 m
= re
.match(r
"({})\s*=\s*(.*)$".format(_py_name_pat
.pattern
), arg
)
2735 _raise_cli_error("Invalid assignment `{}`".format(arg
))
2740 val
= _val_from_assign_val_str(m
.group(2), is_label
)
2747 # Parses the command-line arguments and returns, in this order:
2749 # 1. The input file path, or `None` if none.
2750 # 2. The Normand input text.
2751 # 3. The initial offset.
2752 # 4. The initial byte order.
2753 # 5. The initial variables.
2754 # 6. The initial labels.
2755 def _parse_cli_args():
2759 ap
= argparse
.ArgumentParser()
2766 help="initial offset (positive)",
2772 choices
=["be", "le"],
2774 help="initial byte order (`be` or `le`)",
2781 help="add an initial numeric variable (may be repeated)",
2788 help="add an initial string variable (may be repeated)",
2795 help="add an initial label (may be repeated)",
2798 "--version", action
="version", version
="Normand {}".format(__version__
)
2805 help="input path (none means standard input)",
2809 args
= ap
.parse_args()
2812 if args
.path
is None:
2813 normand
= sys
.stdin
.read()
2815 with
open(args
.path
) as f
:
2818 # Variables and labels
2819 variables
= _dict_from_arg(args
.var
, False, False)
2820 variables
.update(_dict_from_arg(args
.var_str
, False, True))
2821 labels
= _dict_from_arg(args
.label
, True, False)
2825 _raise_cli_error("Invalid negative offset {}")
2827 # Validate and set byte order
2828 bo
= None # type: Optional[ByteOrder]
2830 if args
.byte_order
is not None:
2831 if args
.byte_order
== "be":
2834 assert args
.byte_order
== "le"
2837 # Return input and initial state
2838 return args
.path
, normand
, args
.offset
, bo
, variables
, typing
.cast(LabelsT
, labels
)
2841 # CLI entry point without exception handling.
2842 def _run_cli_with_args(
2845 bo
: Optional
[ByteOrder
],
2846 variables
: VariablesT
,
2849 sys
.stdout
.buffer.write(parse(normand
, variables
, labels
, offset
, bo
).data
)
2852 # Prints the exception message `msg` and exits with status 1.
2853 def _fail(msg
: str) -> NoReturn
:
2854 if not msg
.endswith("."):
2857 print(msg
.strip(), file=sys
.stderr
)
2864 args
= _parse_cli_args()
2865 except Exception as exc
:
2869 _run_cli_with_args(*args
[1:])
2870 except ParseError
as exc
:
2873 prefix
= "" if args
[0] is None else "{}:".format(os
.path
.abspath(args
[0]))
2876 for msg
in reversed(exc
.messages
):
2877 fail_msg
+= "{}{}:{} - {}".format(
2879 msg
.text_location
.line_no
,
2880 msg
.text_location
.col_no
,
2884 if fail_msg
[-1] not in ".:;":
2889 _fail(fail_msg
.strip())
2890 except Exception as exc
:
2894 if __name__
== "__main__":