​fly-in /
src / parser.py
63 commits
09-08-2026
295 lines 10 kB
  1"""Reading a map file into a Scenario."""
  2
  3from typing import Final
  4
  5from .connection import Connection
  6from .errors import FlyInError, ParserError
  7from .network import Network
  8from .scenario import Scenario
  9from .zone import Zone, ZoneRole, ZoneType
 10
 11ROLES: Final[dict[str, ZoneRole]] = {
 12    "start_hub": ZoneRole.START,
 13    "end_hub": ZoneRole.END,
 14    "hub": ZoneRole.INTERMEDIATE,
 15}
 16KEYWORDS: Final[frozenset[str]] = frozenset(ROLES) | {
 17    "nb_drones",
 18    "connection",
 19}
 20ZONE_KEYS: Final[frozenset[str]] = frozenset(
 21    {"zone", "color", "max_drones"}
 22)
 23LINK_KEYS: Final[frozenset[str]] = frozenset({"max_link_capacity"})
 24
 25
 26class MapParser:
 27    """Turns the lines of a map file into a scenario.
 28
 29    Every helper reports a problem as a plain ValueError carrying
 30    only the reason. _handle_line is the single place that
 31    knows the line number, and it converts those into ParserError.
 32    """
 33
 34    def __init__(self, path: str) -> None:
 35        """Prepare a parser for one map file.
 36
 37        Args:
 38            path: Filesystem path of the map to read.
 39        """
 40        self._path = path
 41        self._nb_drones: int | None = None
 42        self._network = Network()
 43
 44    def parse(self) -> Scenario:
 45        """Read the whole file and build the scenario.
 46
 47        Returns: The drone count and the network the map describes.
 48
 49        Raises:
 50            ParserError: If a line violates the map format.
 51            FlyInError: If the file cannot be read, if it declares no
 52                drone count, or if a start or end zone is missing.
 53        """
 54        try:
 55            with open(self._path, encoding="utf-8") as stream:
 56                for line_no, raw in enumerate(stream, start=1):
 57                    self._handle_line(line_no, raw.rstrip("\n"))
 58        except OSError as err:
 59            raise FlyInError(f"cannot read {self._path!r}: {err}") from err
 60        if self._nb_drones is None:
 61            raise FlyInError("map must start with 'nb_drones: <count>'")
 62        self._require_endpoints()
 63        return Scenario(self._nb_drones, self._network)
 64
 65    def _require_endpoints(self) -> None:
 66        """Check that the map declared both a start and an end zone.
 67
 68        Raises:
 69            FlyInError: If either one is missing. The error carries no
 70                line number: it is the file as a whole that is wrong.
 71        """
 72        try:
 73            self._network.start
 74            self._network.end
 75        except ValueError as err:
 76            raise FlyInError(str(err)) from err
 77
 78    def _handle_line(self, line_no: int, raw: str) -> None:
 79        """Strip, split and dispatch one line of the file.
 80
 81        Args:
 82            line_no: 1-based number of the line.
 83            raw: The line as read, without its trailing newline.
 84
 85        Raises:
 86            ParserError: If the line is malformed or breaks a rule.
 87        """
 88        line = raw.split("#", 1)[0].strip()
 89        if not line:
 90            return
 91        if ":" not in line:
 92            raise ParserError(line_no, raw, "expected '<keyword>: <value>'")
 93        keyword, _, rest = line.partition(":")
 94        try:
 95            self._dispatch(keyword.strip(), rest.strip())
 96        except ValueError as err:
 97            raise ParserError(line_no, raw, str(err)) from err
 98
 99    def _dispatch(self, keyword: str, rest: str) -> None:
100        """Route one line to the handler for its keyword.
101
102        Args:
103            keyword: Text before the colon.
104            rest: Text after the colon, already stripped.
105
106        Raises:
107            ValueError: If the keyword is unknown, if it comes before
108                the drone count, or if the body is malformed.
109        """
110        if keyword not in KEYWORDS:
111            raise ValueError(f"unknown keyword {keyword!r}")
112        if keyword == "nb_drones":
113            self._set_nb_drones(rest)
114            return
115        if self._nb_drones is None:
116            raise ValueError(f"{keyword!r} before nb_drones")
117        if keyword in ROLES:
118            self._network.add_zone(self._parse_zone(ROLES[keyword], rest))
119        else:
120            self._network.add_connection(self._parse_connection(rest))
121
122    def _set_nb_drones(self, rest: str) -> None:
123        """Record the drone count declared by the first line.
124
125        Args:
126            rest: Text after the nb_drones: keyword.
127
128        Raises:
129            ValueError: If the count was already given, or is not a
130                positive integer.
131        """
132        if self._nb_drones is not None:
133            raise ValueError("nb_drones declared twice")
134        self._nb_drones = self._positive_int(rest, "nb_drones")
135
136    def _parse_zone(self, role: ZoneRole, rest: str) -> Zone:
137        """Build a zone from hub-family line.
138
139        Args:
140            role: Whether the keyword was start, end or plain hub.
141            rest: Text after the colon.
142
143        Returns:
144            The zone the line describes.
145
146        Raises:
147            ValueError: If the fields or the metadata are malformed.
148        """
149        head, block = self._split_metadata(rest)
150        fields = head.split()
151        if len(fields) != 3:
152            raise ValueError("expected '<name> <x> <y> [metadata]'")
153        name, raw_x, raw_y = fields
154        if "-" in name:
155            raise ValueError(f"zone name {name!r} contains a dash")
156        data = self._parse_metadata(block, ZONE_KEYS)
157        zone_type = ZoneType.NORMAL
158        if "zone" in data:
159            zone_type = ZoneType.from_label(data["zone"])
160        max_drones = 1
161        if "max_drones" in data:
162            max_drones = self._positive_int(data["max_drones"], "max_drones")
163        return Zone(
164            name=name,
165            x=self._coordinate(raw_x),
166            y=self._coordinate(raw_y),
167            zone_type=zone_type,
168            role=role,
169            color=data.get("color"),
170            max_drones=max_drones,
171        )
172
173    def _parse_connection(self, rest: str) -> Connection:
174        """Build a connection from a connection: line.
175
176        Args:
177            rest: Text after the colon.
178
179        Returns:
180            The connection the line describes.
181
182        Raises:
183            ValueError: If the endpoints or the metadata are malformed.
184        """
185        head, block = self._split_metadata(rest)
186        fields = head.split()
187        if len(fields) != 1:
188            raise ValueError("expected '<zone1>-<zone2> [metadata]'")
189        endpoints = fields[0].split("-")
190        if len(endpoints) != 2 or not all(endpoints):
191            raise ValueError(f"malformed connection {fields[0]!r}")
192        data = self._parse_metadata(block, LINK_KEYS)
193        capacity = 1
194        if "max_link_capacity" in data:
195            capacity = self._positive_int(
196                data["max_link_capacity"], "max_link_capacity"
197            )
198        return Connection(endpoints[0], endpoints[1], capacity)
199
200    @staticmethod
201    def _split_metadata(text: str) -> tuple[str, str]:
202        """Cut a line body into its fields and its metadata block.
203
204        Args:
205            text: Everything after the colon of a zone or link line.
206
207        Returns:
208            The field before the block, and the block's contents
209            without its brackets. Both are stripped, and the second is
210            empty when the line carries no metadata.
211
212        Raises:
213            ValueError: If the brackets are unbalanced or misplaced.
214        """
215        opening = text.find("[")
216        if opening == -1:
217            if "]" in text:
218                raise ValueError("metadata block is missing its '['")
219            return text.strip(), ""
220        head, block = text[:opening], text[opening:].strip()
221        misplaced = "[" in block[1:] or "]" in block[:-1]
222        if not block.endswith("]") or misplaced:
223            raise ValueError(f"malformed metadata block {block!r}")
224        return head.strip(), block[1:-1].strip()
225
226    @staticmethod
227    def _parse_metadata(block: str, allowed: frozenset[str]) -> dict[str, str]:
228        """Read the key=value pairs of metadata block.
229
230        Args:
231            block: Contents of the block, without its brackets.
232            allowed: Keys this kind of line accepts.
233
234        Returns:
235            The pairs found, keyed by name. Empty when the block is.
236
237        Raises:
238            ValueError: On a malformed entry, an unknown key, an empty
239                value, or a key given twice.
240        """
241        data: dict[str, str] = {}
242        for entry in block.split():
243            if entry.count("=") != 1:
244                raise ValueError(f"malformed metadata entry {entry!r}")
245            key, value = entry.split("=")
246            if key not in allowed:
247                raise ValueError(f"unknown metadata key {key!r}")
248            if not value:
249                raise ValueError(f"metadata key {key!r} has no value")
250            if key in data:
251                raise ValueError(f"metadata key {key!r} given twice")
252            data[key] = value
253        return data
254
255    @staticmethod
256    def _positive_int(text: str, key: str) -> int:
257        """Read a strictly positive integer.
258
259        Args:
260            text: The written value.
261            key: Name of the field, used in the error message.
262
263        Returns:
264            The parsed value.
265
266        Raises:
267            ValueError: If the text is not a positive decimal integer.
268        """
269        digits = text.strip()
270        if not digits.isascii() or not digits.isdigit():
271            raise ValueError(
272                f"{key} must be a positive integer, got {text!r}"
273            )
274        value = int(digits)
275        if value == 0:
276            raise ValueError(f"{key} must be positive, got 0")
277        return value
278
279    @staticmethod
280    def _coordinate(text: str) -> int:
281        """Read a possibly negative integer coordinate.
282
283        Args:
284            text: The written value.
285
286        Returns:
287            The parsed coordinate.
288
289        Raises:
290            ValueError: If the text is not a decimal integer.
291        """
292        digits = text[1:] if text[:1] in {"+", "-"} else text
293        if not digits.isascii() or not digits.isdigit():
294            raise ValueError(f"coordinate {text!r} is not an integer")
295        return int(text)