Debian Codegraph @

blueprintcompiler/language/contexts.py

raw
1 # contexts.py
2 #
3 # Copyright 2023 James Westman <[email protected]>
4 #
5 # This file is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU Lesser General Public License as
7 # published by the Free Software Foundation; either version 3 of the
8 # License, or (at your option) any later version.
9 #
10 # This file is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this program. If not, see <http://www.gnu.org/licenses/>.
17 #
18 # SPDX-License-Identifier: LGPL-3.0-or-later
19
20 import typing as T
21 from dataclasses import dataclass
22 from functools import cached_property
23
24 from .common import *
25 from .gobject_object import Object
26 from .gtkbuilder_template import Template
27
28
29 @dataclass
30 class ValueTypeCtx:
31 value_type: T.Optional[GirType]
32 allow_null: bool = False
33 must_infer_type: bool = False
34
35
36 @dataclass
37 class ScopeCtx:
38 node: AstNode
39
40 @cached_property
41 def template(self):
42 from .gtk_list_item_factory import ExtListItemFactory
43 from .ui import UI
44
45 if isinstance(self.node, UI):
46 return self.node.template
47 elif isinstance(self.node, ExtListItemFactory):
48 return self.node
49
50 @cached_property
51 def objects(self) -> T.Dict[str, Object]:
52 return {
53 obj.tokens["id"]: obj
54 for obj in self._iter_recursive(self.node)
55 if obj.tokens["id"] is not None
56 }
57
58 def validate_unique_ids(self) -> None:
59 from .gtk_list_item_factory import ExtListItemFactory
60
61 passed = {}
62 for obj in self._iter_recursive(self.node):
63 from .gtk_menu import Menu
64
65 if not (isinstance(obj, Object) or isinstance(obj, Menu)) or obj.id is None:
66 continue
67
68 if obj.id in passed:
69 token = obj.group.tokens["id"]
70 if not isinstance(obj, Template) and not isinstance(
71 obj, ExtListItemFactory
72 ):
73 raise CompileError(
74 f"Duplicate object ID '{obj.id}'",
75 token.range,
76 )
77 passed[obj.id] = obj
78
79 def _iter_recursive(self, node: AstNode):
80 yield node
81 for child in node.children:
82 if child.context[ScopeCtx] is self:
83 yield from self._iter_recursive(child)
84
85
86 @dataclass
87 class ExprValueCtx:
88 """Indicates that the context is an expression literal, where the
89 "item" keyword may be used."""