Debian Codegraph @

blueprintcompiler/language/values.py

raw
1 # values.py
2 #
3 # Copyright 2022 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
22 from blueprintcompiler.gir import ArrayType
23 from blueprintcompiler.lsp_utils import SemanticToken
24
25 from .common import *
26 from .contexts import ExprValueCtx, ScopeCtx, ValueTypeCtx
27 from .expression import Expression
28 from .gobject_object import Object
29 from .translated import *
30 from .types import TypeName
31
32
33 class TypeLiteral(AstNode):
34 grammar = [
35 "typeof",
36 AnyOf(
37 [
38 "<",
39 to_parse_node(TypeName).expected("type name"),
40 Match(">").expected(),
41 ],
42 [
43 UseExact("lparen", "("),
44 to_parse_node(TypeName).expected("type name"),
45 UseExact("rparen", ")").expected("')'"),
46 ],
47 ),
48 ]
49
50 @property
51 def type(self):
52 return gir.TypeType()
53
54 @property
55 def type_name(self) -> TypeName:
56 return self.children[TypeName][0]
57
58 @validate()
59 def validate_for_type(self) -> None:
60 expected_type = self.context[ValueTypeCtx].value_type
61 if expected_type is not None and not isinstance(expected_type, gir.TypeType):
62 raise CompileError(f"Cannot convert GType to {expected_type.full_name}")
63
64 @validate("lparen", "rparen")
65 def upgrade_to_angle_brackets(self):
66 if self.tokens["lparen"]:
67 raise UpgradeWarning(
68 "Use angle bracket syntax introduced in blueprint 0.8.0",
69 actions=[
70 CodeAction(
71 "Use <> instead of ()",
72 f"<{self.children[TypeName][0].as_string}>",
73 )
74 ],
75 )
76
77 @docs()
78 def ref_docs(self):
79 return get_docs_section("Syntax TypeLiteral")
80
81
82 class QuotedLiteral(AstNode):
83 grammar = UseQuoted("value")
84
85 @property
86 def value(self) -> str:
87 return self.tokens["value"]
88
89 @property
90 def value_token(self) -> Token:
91 return self.group.tokens["value"]
92
93 @property
94 def type(self):
95 return gir.StringType()
96
97 @validate()
98 def validate_for_type(self) -> None:
99 expected_type = self.context[ValueTypeCtx].value_type
100 if (
101 isinstance(expected_type, gir.IntType)
102 or isinstance(expected_type, gir.UIntType)
103 or isinstance(expected_type, gir.FloatType)
104 ):
105 raise CompileError(f"Cannot convert string to number")
106
107 elif isinstance(expected_type, gir.StringType):
108 pass
109
110 elif (
111 isinstance(expected_type, gir.Class)
112 or isinstance(expected_type, gir.Interface)
113 or isinstance(expected_type, gir.Boxed)
114 ):
115 parseable_types = [
116 "Gdk.Paintable",
117 "Gdk.Texture",
118 "Gdk.Pixbuf",
119 "Gio.File",
120 "Gtk.ShortcutTrigger",
121 "Gtk.ShortcutAction",
122 "Gdk.RGBA",
123 "Gdk.ContentFormats",
124 "Gsk.Transform",
125 "GLib.Variant",
126 "Pango.AttrList",
127 "Pango.FontDescription",
128 "Pango.TabArray",
129 ]
130 if expected_type.full_name not in parseable_types:
131 hints = []
132 if isinstance(expected_type, gir.TypeType):
133 hints.append(f"use the typeof operator: 'typeof({self.value})'")
134 raise CompileError(
135 f"Cannot convert string to {expected_type.full_name}", hints=hints
136 )
137
138 elif expected_type is not None:
139 raise CompileError(f"Cannot convert string to {expected_type.full_name}")
140
141
142 class NumberLiteral(AstNode):
143 grammar = [
144 Optional(AnyOf(UseExact("sign", "-"), UseExact("sign", "+"))),
145 UseNumber("value"),
146 ]
147
148 @property
149 def type(self) -> gir.GirType:
150 if isinstance(self.value, int):
151 return gir.IntType()
152 else:
153 return gir.FloatType()
154
155 @property
156 def value(self) -> T.Union[int, float]:
157 if self.tokens["sign"] == "-":
158 return -self.tokens["value"]
159 else:
160 return self.tokens["value"]
161
162 @validate()
163 def validate_for_type(self) -> None:
164 expected_type = self.context[ValueTypeCtx].value_type
165 if isinstance(expected_type, gir.IntType):
166 if not isinstance(self.value, int):
167 raise CompileError(
168 f"Cannot convert {self.group.tokens['value']} to integer"
169 )
170
171 elif isinstance(expected_type, gir.UIntType):
172 if self.value < 0:
173 raise CompileError(
174 f"Cannot convert -{self.group.tokens['value']} to unsigned integer"
175 )
176
177 elif not isinstance(expected_type, gir.FloatType) and expected_type is not None:
178 raise CompileError(f"Cannot convert number to {expected_type.full_name}")
179
180
181 class Flag(AstNode):
182 grammar = UseIdent("value")
183
184 @property
185 def name(self) -> str:
186 return self.tokens["value"]
187
188 @property
189 def value(self) -> T.Optional[str]:
190 type = self.context[ValueTypeCtx].value_type
191 if not isinstance(type, Enumeration):
192 return None
193 elif member := type.members.get(self.name):
194 return member.nick
195 else:
196 return None
197
198 def get_semantic_tokens(self) -> T.Iterator[SemanticToken]:
199 yield SemanticToken(
200 self.group.tokens["value"].start,
201 self.group.tokens["value"].end,
202 SemanticTokenType.EnumMember,
203 )
204
205 @docs()
206 def docs(self):
207 type = self.context[ValueTypeCtx].value_type
208 if not isinstance(type, Enumeration):
209 return
210 if member := type.members.get(self.tokens["value"]):
211 return member.doc
212
213 @validate()
214 def validate_for_type(self):
215 expected_type = self.context[ValueTypeCtx].value_type
216 if (
217 isinstance(expected_type, gir.Bitfield)
218 and self.tokens["value"] not in expected_type.members
219 ):
220 raise CompileError(
221 f"{self.tokens['value']} is not a member of {expected_type.full_name}",
222 did_you_mean=(self.tokens["value"], expected_type.members.keys()),
223 )
224
225 @validate()
226 def unique(self):
227 self.validate_unique_in_parent(
228 f"Duplicate flag '{self.name}'", lambda x: x.name == self.name
229 )
230
231
232 class Flags(AstNode):
233 grammar = [Flag, "|", Flag, ZeroOrMore(["|", Flag])]
234
235 @property
236 def flags(self) -> T.List[Flag]:
237 return self.children
238
239 @validate()
240 def validate_for_type(self) -> None:
241 expected_type = self.context[ValueTypeCtx].value_type
242 if expected_type is not None and not isinstance(expected_type, gir.Bitfield):
243 raise CompileError(f"{expected_type.full_name} is not a bitfield type")
244
245 @docs()
246 def ref_docs(self):
247 return get_docs_section("Syntax Flags")
248
249
250 class IdentLiteral(AstNode):
251 grammar = UseIdent("value")
252
253 @property
254 def ident(self) -> str:
255 return self.tokens["value"]
256
257 @property
258 def type(self) -> T.Optional[gir.GirType]:
259 # If the expected type is known, then use that. Otherwise, guess.
260 if expected_type := self.context[ValueTypeCtx].value_type:
261 return expected_type
262 elif self.ident in ["true", "false"]:
263 return gir.BoolType()
264 elif object := self.context[ScopeCtx].objects.get(self.ident):
265 return object.gir_class
266 elif self.root.is_legacy_template(self.ident):
267 return self.root.template.class_name.gir_type
268 else:
269 return None
270
271 @validate()
272 def validate_for_type(self) -> None:
273 expected_type = self.context[ValueTypeCtx].value_type
274 if isinstance(expected_type, gir.BoolType):
275 if self.ident not in ["true", "false"]:
276 raise CompileError(f"Expected 'true' or 'false' for boolean value")
277
278 elif isinstance(expected_type, gir.Enumeration):
279 if self.ident not in expected_type.members:
280 raise CompileError(
281 f"{self.ident} is not a member of {expected_type.full_name}",
282 did_you_mean=(self.ident, list(expected_type.members.keys())),
283 )
284
285 elif self.root.is_legacy_template(self.ident):
286 raise UpgradeWarning(
287 "Use 'template' instead of the class name (introduced in 0.8.0)",
288 actions=[CodeAction("Use 'template'", "template")],
289 )
290
291 elif expected_type is not None or self.context[ValueTypeCtx].must_infer_type:
292 object = self.context[ScopeCtx].objects.get(self.ident)
293 if object is None:
294 if self.ident == "null":
295 if not self.context[ValueTypeCtx].allow_null:
296 raise CompileError("null is not permitted here")
297 elif self.ident == "item":
298 if not self.context[ExprValueCtx]:
299 raise CompileError(
300 '"item" can only be used in an expression literal'
301 )
302 elif self.ident in ["true", "false"]:
303 if expected_type is not None and not isinstance(
304 expected_type, gir.BoolType
305 ):
306 raise CompileError(
307 f"Cannot assign boolean to {expected_type.full_name}"
308 )
309 else:
310 raise CompileError(
311 f"Could not find object with ID {self.ident}",
312 did_you_mean=(
313 self.ident,
314 self.context[ScopeCtx].objects.keys(),
315 ),
316 )
317 elif (
318 expected_type is not None
319 and object.gir_class is not None
320 and not object.gir_class.assignable_to(expected_type)
321 ):
322 raise CompileError(
323 f"Cannot assign {object.gir_class.full_name} to {expected_type.full_name}"
324 )
325
326 @docs()
327 def docs(self) -> T.Optional[str]:
328 expected_type = self.context[ValueTypeCtx].value_type
329 if isinstance(expected_type, gir.BoolType):
330 return None
331 elif isinstance(expected_type, gir.Enumeration):
332 if member := expected_type.members.get(self.ident):
333 return member.doc
334 else:
335 return expected_type.doc
336 elif self.ident == "null" and self.context[ValueTypeCtx].allow_null:
337 return None
338 elif object := self.context[ScopeCtx].objects.get(self.ident):
339 return f"```\n{object.signature}\n```"
340 elif self.root.is_legacy_template(self.ident):
341 return f"```\n{self.root.template.signature}\n```"
342 else:
343 return None
344
345 def get_semantic_tokens(self) -> T.Iterator[SemanticToken]:
346 type = self.context[ValueTypeCtx].value_type
347 if isinstance(type, gir.Enumeration):
348 token = self.group.tokens["value"]
349 yield SemanticToken(token.start, token.end, SemanticTokenType.EnumMember)
350
351 def get_reference(self, _idx: int) -> T.Optional[LocationLink]:
352 ref = self.context[ScopeCtx].objects.get(self.ident)
353 if ref is None and self.root.is_legacy_template(self.ident):
354 ref = self.root.template
355
356 if ref:
357 return LocationLink(self.range, ref.range, ref.ranges["id"])
358 else:
359 return None
360
361
362 class Literal(AstNode):
363 grammar = AnyOf(
364 TypeLiteral,
365 QuotedLiteral,
366 NumberLiteral,
367 IdentLiteral,
368 )
369
370 @property
371 def value(
372 self,
373 ) -> T.Union[TypeLiteral, QuotedLiteral, NumberLiteral, IdentLiteral]:
374 return self.children[0]
375
376
377 class ObjectValue(AstNode):
378 grammar = Object
379
380 @property
381 def object(self) -> Object:
382 return self.children[Object][0]
383
384 @validate()
385 def validate_for_type(self) -> None:
386 expected_type = self.context[ValueTypeCtx].value_type
387 if (
388 expected_type is not None
389 and self.object.gir_class is not None
390 and not self.object.gir_class.assignable_to(expected_type)
391 ):
392 raise CompileError(
393 f"Cannot assign {self.object.gir_class.full_name} to {expected_type.full_name}"
394 )
395
396
397 class ExprValue(AstNode):
398 grammar = [Keyword("expr"), Expression]
399
400 @property
401 def expression(self) -> Expression:
402 return self.children[Expression][0]
403
404 @validate("expr")
405 def validate_for_type(self) -> None:
406 expected_type = self.parent.context[ValueTypeCtx].value_type
407 expr_type = self.root.gir.get_type("Expression", "Gtk")
408 if expected_type is not None and not expected_type.assignable_to(expr_type):
409 raise CompileError(
410 f"Cannot convert Gtk.Expression to {expected_type.full_name}"
411 )
412
413 @docs("expr")
414 def ref_docs(self):
415 return get_docs_section("Syntax ExprValue")
416
417 @context(ExprValueCtx)
418 def expr_literal(self):
419 return ExprValueCtx()
420
421 @context(ValueTypeCtx)
422 def value_type(self):
423 return ValueTypeCtx(None, must_infer_type=True)
424
425
426 class Value(AstNode):
427 grammar = AnyOf(Translated, Flags, Literal)
428
429 @property
430 def child(
431 self,
432 ) -> T.Union[Translated, Flags, Literal]:
433 return self.children[0]
434
435
436 class ArrayValue(AstNode):
437 grammar = ["[", Delimited(Value, ","), "]"]
438
439 @validate()
440 def validate_for_type(self) -> None:
441 expected_type = self.gir_type
442 if expected_type is not None and not isinstance(expected_type, gir.ArrayType):
443 raise CompileError(f"Cannot assign array to {expected_type.full_name}")
444
445 if expected_type is not None and not isinstance(
446 expected_type.inner, StringType
447 ):
448 raise CompileError("Only string arrays are supported")
449
450 @validate()
451 def validate_invalid_newline(self) -> None:
452 expected_type = self.gir_type
453 if isinstance(expected_type, gir.ArrayType) and isinstance(
454 expected_type.inner, StringType
455 ):
456 errors = []
457 for value in self.values:
458 if isinstance(value.child, Literal) and isinstance(
459 value.child.value, QuotedLiteral
460 ):
461 quoted_literal = value.child.value
462 literal_value = quoted_literal.value
463 # literal_value can be None if there's an invalid escape sequence
464 if literal_value is not None and "\n" in literal_value:
465 errors.append(
466 CompileError(
467 "String literals inside arrays can't contain newlines",
468 range=quoted_literal.range,
469 )
470 )
471 elif isinstance(value.child, Translated):
472 errors.append(
473 CompileError(
474 "Arrays can't contain translated strings",
475 range=value.child.range,
476 )
477 )
478
479 if len(errors) > 0:
480 raise MultipleErrors(errors)
481
482 @property
483 def values(self) -> T.List[Value]:
484 return self.children
485
486 @property
487 def gir_type(self):
488 return self.parent.context[ValueTypeCtx].value_type
489
490 @context(ValueTypeCtx)
491 def child_value(self):
492 if self.gir_type is None or not isinstance(self.gir_type, ArrayType):
493 return ValueTypeCtx(None)
494 else:
495 return ValueTypeCtx(self.gir_type.inner)
496
497
498 class StringValue(AstNode):
499 grammar = AnyOf(Translated, QuotedLiteral)
500
501 @property
502 def child(
503 self,
504 ) -> T.Union[Translated, QuotedLiteral]:
505 return self.children[0]
506
507 @property
508 def string(self) -> str:
509 if isinstance(self.child, Translated):
510 return self.child.string
511 else:
512 return self.child.value
513
514 @context(ValueTypeCtx)
515 def value_type(self) -> ValueTypeCtx:
516 return ValueTypeCtx(StringType())