Debian Codegraph @

blueprintcompiler/language/expression.py

raw
1 # expressions.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
21 from functools import cached_property
22
23 from ..decompiler import decompile_element, full_name
24 from ..utils import TextEdit
25 from .common import *
26 from .contexts import ScopeCtx, ValueTypeCtx
27 from .translated import *
28 from .types import TypeName
29
30 expr = Sequence()
31
32
33 class ExprBase(AstNode):
34 @context(ValueTypeCtx)
35 def value_type(self) -> ValueTypeCtx:
36 if rhs := self.rhs:
37 return rhs.context[ValueTypeCtx]
38 else:
39 return self.parent.context[ValueTypeCtx]
40
41 @property
42 def type(self) -> T.Optional[GirType]:
43 raise NotImplementedError()
44
45 @property
46 def rhs(self) -> T.Optional["ExprBase"]:
47 if isinstance(self.parent, Expression):
48 children = list(self.parent.children)
49 if children.index(self) + 1 < len(children):
50 return children[children.index(self) + 1]
51 else:
52 return self.parent.rhs
53 else:
54 return None
55
56
57 class Expression(ExprBase):
58 grammar = expr
59
60 @property
61 def last(self) -> ExprBase:
62 return self.children[-1]
63
64 @property
65 def type(self) -> T.Optional[GirType]:
66 return self.last.type
67
68 @validate()
69 def validate_for_type(self):
70 expected_type = self.parent.context[ValueTypeCtx].value_type
71 if self.type is not None and expected_type is not None:
72 if not self.type.assignable_to(expected_type):
73 castable = (
74 " without casting" if self.type.castable_to(expected_type) else ""
75 )
76 raise CompileWarning(
77 f"Cannot assign {self.type.full_name} to {expected_type.full_name}{castable}"
78 )
79
80 @autofix
81 def autofix_cast(self):
82 expected_type = self.parent.context[ValueTypeCtx].value_type
83 if self.type is not None and expected_type is not None:
84 if not self.type.assignable_to(expected_type):
85 if self.type.castable_to(expected_type):
86 range = Range(
87 self.range.end, self.range.end, self.range.original_text
88 )
89 return TextEdit(range, f" as <{expected_type.full_name}>")
90
91
92 class InfixExpr(ExprBase):
93 @property
94 def lhs(self):
95 children = list(self.parent_by_type(Expression).children)
96 return children[children.index(self) - 1]
97
98
99 class LiteralExpr(ExprBase):
100 grammar = LITERAL
101
102 @property
103 def is_object(self) -> bool:
104 from .values import IdentLiteral
105
106 return isinstance(self.literal.value, IdentLiteral) and (
107 self.literal.value.ident in self.context[ScopeCtx].objects
108 or self.root.is_legacy_template(self.literal.value.ident)
109 )
110
111 @property
112 def is_this(self) -> bool:
113 from .values import IdentLiteral
114
115 return (
116 not self.is_object
117 and isinstance(self.literal.value, IdentLiteral)
118 and self.literal.value.ident == "item"
119 )
120
121 @property
122 def literal(self):
123 from .values import Literal
124
125 return self.children[Literal][0]
126
127 @property
128 def type(self) -> T.Optional[GirType]:
129 return self.literal.value.type
130
131 @validate()
132 def item_validations(self):
133 if self.is_this:
134 if not isinstance(self.rhs, CastExpr):
135 raise CompileError('"item" must be cast to its object type')
136
137 if not isinstance(self.rhs.rhs, LookupOp):
138 raise CompileError('"item" can only be used for looking up properties')
139
140
141 class TranslatedExpr(ExprBase):
142 grammar = Translated
143
144 @property
145 def translated(self) -> Translated:
146 return self.children[Translated][0]
147
148 @property
149 def type(self) -> GirType:
150 return StringType()
151
152
153 class LookupOp(InfixExpr):
154 grammar = [".", UseIdent("property")]
155
156 @context(ValueTypeCtx)
157 def value_type(self) -> ValueTypeCtx:
158 return ValueTypeCtx(None, must_infer_type=True)
159
160 @property
161 def property_name(self) -> str:
162 return self.tokens["property"]
163
164 @property
165 def type(self) -> T.Optional[GirType]:
166 if isinstance(self.lhs.type, gir.Class) or isinstance(
167 self.lhs.type, gir.Interface
168 ):
169 if property := self.lhs.type.properties.get(self.property_name):
170 return property.type
171
172 return None
173
174 @docs("property")
175 def property_docs(self):
176 if not (
177 isinstance(self.lhs.type, gir.Class)
178 or isinstance(self.lhs.type, gir.Interface)
179 ):
180 return None
181
182 if property := self.lhs.type.properties.get(self.property_name):
183 return property.doc
184
185 @validate("property")
186 def property_exists(self):
187 if self.lhs.type is None:
188 # Literal values throw their own errors if the type isn't known
189 if isinstance(self.lhs, LiteralExpr):
190 return
191
192 raise CompileError(
193 f"Could not determine the type of the preceding expression",
194 hints=[
195 f"add a type cast so blueprint knows which type the property {self.property_name} belongs to"
196 ],
197 )
198
199 if self.lhs.type.incomplete:
200 return
201
202 elif not isinstance(self.lhs.type, gir.Class) and not isinstance(
203 self.lhs.type, gir.Interface
204 ):
205 raise CompileError(
206 f"Type {self.lhs.type.full_name} does not have properties"
207 )
208
209 elif self.lhs.type.properties.get(self.property_name) is None:
210 raise CompileError(
211 f"{self.lhs.type.full_name} does not have a property called {self.property_name}",
212 did_you_mean=(self.property_name, self.lhs.type.properties.keys()),
213 )
214
215 @validate("property")
216 def property_deprecated(self):
217 if self.lhs.type is None or not (
218 isinstance(self.lhs.type, gir.Class)
219 or isinstance(self.lhs.type, gir.Interface)
220 ):
221 return
222
223 if property := self.lhs.type.properties.get(self.property_name):
224 if property.deprecated:
225 hints = []
226 if property.deprecated_doc:
227 hints.append(property.deprecated_doc)
228 raise DeprecatedWarning(
229 f"{property.signature} is deprecated",
230 hints=hints,
231 )
232
233
234 class CastExpr(InfixExpr):
235 grammar = [
236 Keyword("as"),
237 AnyOf(
238 ["<", to_parse_node(TypeName).expected("type name"), Match(">").expected()],
239 [
240 UseExact("lparen", "("),
241 TypeName,
242 UseExact("rparen", ")").expected("')'"),
243 ],
244 ),
245 ]
246
247 @context(ValueTypeCtx)
248 def value_type(self):
249 return ValueTypeCtx(self.type, allow_null=True)
250
251 @property
252 def type(self) -> T.Optional[GirType]:
253 return self.children[TypeName][0].gir_type
254
255 @validate()
256 def cast_makes_sense(self) -> None:
257 if self.type is None or self.lhs.type is None:
258 return
259
260 if not self.type.castable_to(self.lhs.type) and not self.lhs.type.castable_to(
261 self.type
262 ):
263 raise CompileError(
264 f"Invalid cast. No instance of {self.lhs.type.full_name} can be an instance of {self.type.full_name}."
265 )
266
267 @validate("lparen", "rparen")
268 def upgrade_to_angle_brackets(self):
269 if self.tokens["lparen"]:
270 raise UpgradeWarning(
271 "Use angle bracket syntax introduced in blueprint 0.8.0",
272 actions=[
273 CodeAction(
274 "Use <> instead of ()",
275 f"<{self.children[TypeName][0].as_string}>",
276 )
277 ],
278 )
279
280 @docs("as")
281 def ref_docs(self):
282 return get_docs_section("Syntax CastExpression")
283
284 @autofix
285 def autofix_unnecessary_cast(self):
286 if self.type is None:
287 return
288
289 expected_type = self.parent.context[ValueTypeCtx].value_type
290 if (
291 expected_type is not None
292 and self.type.assignable_to(expected_type)
293 and expected_type.assignable_to(self.type)
294 ):
295 return TextEdit(self.range.with_preceding_whitespace, "")
296
297
298 class ClosureArg(AstNode):
299 grammar = Expression
300
301 @property
302 def expr(self) -> Expression:
303 return self.children[Expression][0]
304
305 @context(ValueTypeCtx)
306 def value_type(self) -> ValueTypeCtx:
307 return ValueTypeCtx(None, must_infer_type=True, allow_null=True)
308
309
310 class ClosureExpr(ExprBase):
311 grammar = [
312 Optional(["$", UseLiteral("extern", True)]),
313 UseIdent("name"),
314 "(",
315 Delimited(ClosureArg, ","),
316 ")",
317 ]
318
319 @property
320 def type(self) -> T.Optional[GirType]:
321 return self.context[ValueTypeCtx].value_type
322
323 @property
324 def closure_name(self) -> str:
325 return self.tokens["name"]
326
327 @property
328 def args(self) -> T.List[ClosureArg]:
329 return self.children[ClosureArg]
330
331 @validate()
332 def return_type_known(self):
333 if self.type is None:
334 raise CompileError(
335 "Closure expression must be cast to the closure's return type",
336 hints=[
337 "The return type of this closure cannot be inferred, so you must add a type cast to indicate the return type."
338 ],
339 )
340
341 @validate()
342 def builtin_exists(self):
343 if not self.tokens["extern"]:
344 raise CompileError(f"{self.closure_name} is not a builtin function")
345
346 @docs("name")
347 def ref_docs(self):
348 return get_docs_section("Syntax ClosureExpression")
349
350
351 class TryExpr(ExprBase):
352 grammar = [
353 Keyword("try"),
354 UseExact("lbrace", "{"),
355 Delimited(Expression, ","),
356 UseExact("rbrace", "}").expected("'}'"),
357 ]
358
359 @property
360 def expressions(self) -> T.List[Expression]:
361 return self.children[Expression]
362
363 @cached_property
364 def type(self) -> T.Optional[GirType]:
365 return None
366
367 @docs("try")
368 def ref_docs(self):
369 return get_docs_section("Syntax TryExpression")
370
371 @validate()
372 def at_least_one_expression(self):
373 exprs = self.children[Expression]
374 if len(exprs) == 0:
375 raise CompileError("A try expression must have at least one branch")
376
377 @validate("try")
378 def at_least_two_expressions(self):
379 exprs = self.children[Expression]
380 if len(exprs) < 2:
381 raise CompileWarning(
382 "This try expression has only one branch",
383 actions=[
384 CodeAction(
385 "Remove try",
386 "",
387 additional_edits=[
388 TextEdit(self.ranges["lbrace"], ""),
389 TextEdit(self.ranges["rbrace"], ""),
390 ],
391 )
392 ],
393 )
394
395 @validate()
396 def expressions_have_same_type(self):
397 if len(self.expressions) < 2:
398 return
399
400 types = [expr.type for expr in self.expressions]
401 if None in types:
402 return None
403
404 t = GirType.common_ancestor(T.cast(T.List[GirType], types))
405
406 if t is None:
407 raise CompileError(
408 "All branches of a try expression must have compatible types"
409 )
410
411
412 expr.children = [
413 AnyOf(TranslatedExpr, TryExpr, ClosureExpr, LiteralExpr, ["(", Expression, ")"]),
414 ZeroOrMore(AnyOf(LookupOp, CastExpr)),
415 ]
416
417
418 @decompiler("lookup", skip_children=True, cdata=True)
419 def decompile_lookup(
420 ctx: DecompileCtx,
421 gir: gir.GirContext,
422 cdata: str,
423 name: str,
424 type: T.Optional[str] = None,
425 ):
426 if ctx.parent_node is not None and ctx.parent_node.tag == "property":
427 ctx.print("expr ")
428
429 if type is None:
430 type = ""
431 elif t := ctx.type_by_cname(type):
432 type = decompile.full_name(t)
433 else:
434 type = "$" + type
435
436 assert ctx.current_node is not None
437
438 constant = None
439 if len(ctx.current_node.children) == 0:
440 constant = cdata
441 elif (
442 len(ctx.current_node.children) == 1
443 and ctx.current_node.children[0].tag == "constant"
444 ):
445 constant = ctx.current_node.children[0].cdata
446
447 if constant is not None:
448 if constant == ctx.template_class:
449 ctx.print("template." + name)
450 elif constant == "":
451 ctx.print(f"item as <{type}>.{name}")
452 else:
453 ctx.print(constant + "." + name)
454 return
455 else:
456 for child in ctx.current_node.children:
457 decompile.decompile_element(ctx, gir, child)
458
459 ctx.print(f" as <{type}>.{name}")
460
461
462 @decompiler("constant", cdata=True)
463 def decompile_constant(
464 ctx: DecompileCtx,
465 gir: gir.GirContext,
466 cdata: str,
467 type: T.Optional[str] = None,
468 translatable="false",
469 context=None,
470 comment=None,
471 initial="false",
472 ):
473 if ctx.parent_node is not None and ctx.parent_node.tag == "property":
474 ctx.print("expr ")
475
476 if truthy(initial) and type is not None:
477 t = ctx.type_by_cname(type)
478 if t is None:
479 ctx.print(f"null as <${type}>")
480 else:
481 ctx.print(f"null as <{full_name(t)}>")
482 elif type is None:
483 if cdata == ctx.template_class:
484 ctx.print("template")
485 else:
486 ctx.print(cdata)
487 else:
488 _, string = ctx.decompile_value(
489 cdata,
490 ctx.type_by_cname(type),
491 (translatable, context, comment),
492 )
493 ctx.print(string)
494
495
496 @decompiler("closure", skip_children=True)
497 def decompile_closure(ctx: DecompileCtx, gir: gir.GirContext, function: str, type: str):
498 if ctx.parent_node is not None and ctx.parent_node.tag == "property":
499 ctx.print("expr ")
500
501 if t := ctx.type_by_cname(type):
502 type = decompile.full_name(t)
503 else:
504 type = "$" + type
505
506 ctx.print(f"${function}(")
507
508 assert ctx.current_node is not None
509 for i, node in enumerate(ctx.current_node.children):
510 decompile_element(ctx, gir, node)
511
512 assert ctx.current_node is not None
513 if i < len(ctx.current_node.children) - 1:
514 ctx.print(", ")
515
516 ctx.end_block_with(f") as <{type}>")
517
518
519 @decompiler("try", skip_children=True)
520 def decompile_try(ctx: DecompileCtx, gir: gir.GirContext):
521 if ctx.parent_node is not None and ctx.parent_node.tag == "property":
522 ctx.print("expr ")
523
524 ctx.print("try{")
525
526 assert ctx.current_node is not None
527 for i, node in enumerate(ctx.current_node.children):
528 decompile_element(ctx, gir, node)
529
530 assert ctx.current_node is not None
531 if i < len(ctx.current_node.children) - 1:
532 ctx.print(", ")
533
534 ctx.end_block_with("}")