Debian Codegraph @

third_party/python/moz.l10n/moz/l10n/resource/dtd/parse.py

raw
1 # Copyright Mozilla Foundation
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # The core logic of the parser used here is taken from silme:
16 # https://github.com/mozilla/silme/blob/2f7af3dd87fff27a3c3650d442a065b5a290268e/lib/silme/format/dtd/parser.py
17
18 from __future__ import annotations
19
20 from collections.abc import Iterator
21 from re import DOTALL, MULTILINE, UNICODE, compile
22 from sys import maxsize
23 from typing import Any
24
25 from moz.l10n.message import Message, PatternMessage
26
27 from ..data import Comment, Entry, Resource, Section
28 from ..format import Format
29
30 name_start_char = (
31 ":A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff"
32 "\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fef"
33 "\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd"
34 )
35 name_char = name_start_char + r"\-\.0-9" + "\xb7\u0300-\u036f\u203f-\u2040"
36 name = f"[{name_start_char}][{name_char}]*"
37 re_entity = compile(
38 r"<!ENTITY\s+(" + name + r")\s+((?:\"[^\"]*\")|(?:'[^']*'))\s*>",
39 DOTALL | UNICODE,
40 )
41
42 re_comment = compile(r"\<!\s*--(.*?)--\s*\>", MULTILINE | DOTALL)
43
44
45 def dtd_parse(source: str | bytes) -> Resource[Message, Any]:
46 """
47 Parse a .dtd file into a message resource.
48
49 The parsed resource will not include any metadata.
50 """
51 entries: list[Entry[Message, Any] | Comment] = []
52 resource = Resource(Format.dtd, [Section((), entries)])
53 pos = 0
54 at_newline = True
55 comment: str = ""
56 if not isinstance(source, str):
57 source = source.decode()
58 for match in re_comment.finditer(source):
59 cstart = match.start(0)
60 has_prev_entries = False
61 for entry in dtd_iter(source, pos, endpos=cstart):
62 if isinstance(entry, str):
63 if entry and not entry.isspace():
64 raise ValueError(f"Unexpected content in DTD: {entry}")
65 lines = entry.split("\n")
66 if comment and len(lines) > 2:
67 if entries or resource.comment:
68 entries.append(Comment(comment))
69 else:
70 resource.comment = comment
71 comment = ""
72 at_newline = len(lines) > 1
73 else:
74 if comment:
75 entry.comment = comment
76 comment = ""
77 entries.append(entry)
78 has_prev_entries = True
79 nc = match.group(1).strip().replace("\r\n", "\n")
80 comment = f"{comment}\n{nc}" if comment else nc
81 if comment:
82 if not at_newline and has_prev_entries:
83 prev = entries[-1]
84 pc = prev.comment
85 prev.comment = f"{pc}\n{comment}" if pc else comment
86 comment = ""
87 if re_entity.search(comment):
88 entries.append(Comment(comment))
89 comment = ""
90 pos = match.end(0)
91 if len(source) > pos:
92 for entry in dtd_iter(source, pos):
93 if isinstance(entry, str):
94 if entry and not entry.isspace():
95 raise ValueError(f"Unexpected content in DTD: {entry}")
96 else:
97 if comment:
98 entry.comment = comment
99 comment = ""
100 entries.append(entry)
101 if comment:
102 entries.append(Comment(comment))
103 return resource
104
105
106 def dtd_iter(
107 text: str, pos: int, endpos: int = maxsize
108 ) -> Iterator[str | Entry[Message, Any]]:
109 for match in re_entity.finditer(text, pos, endpos):
110 yield text[pos : match.start(0)]
111 id, value = match.groups()
112 yield Entry((id,), PatternMessage([value[1:-1]]))
113 pos = match.end(0)
114 yield text[pos:endpos]