File: values.py

package info (click to toggle)
blueprint-compiler 0.18.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,140 kB
  • sloc: python: 8,504; sh: 31; makefile: 6
file content (548 lines) | stat: -rw-r--r-- 18,036 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
# values.py
#
# Copyright 2022 James Westman <james@jwestman.net>
#
# This file is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This file is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# SPDX-License-Identifier: LGPL-3.0-or-later

import typing as T

from blueprintcompiler.gir import ArrayType
from blueprintcompiler.lsp_utils import SemanticToken

from .common import *
from .contexts import ExprValueCtx, ScopeCtx, ValueTypeCtx
from .expression import Expression
from .gobject_object import Object
from .types import TypeName


class Translated(AstNode):
    grammar = AnyOf(
        ["_", "(", UseQuoted("string"), ")"],
        [
            "C_",
            "(",
            UseQuoted("context"),
            ",",
            UseQuoted("string"),
            ")",
        ],
    )

    @property
    def string(self) -> str:
        return self.tokens["string"]

    @property
    def translate_context(self) -> T.Optional[str]:
        return self.tokens["context"]

    @validate()
    def validate_for_type(self) -> None:
        expected_type = self.context[ValueTypeCtx].value_type
        if expected_type is not None and not expected_type.assignable_to(StringType()):
            raise CompileError(
                f"Cannot convert translated string to {expected_type.full_name}"
            )

    @validate("context")
    def context_double_quoted(self):
        if self.translate_context is None:
            return

        if not str(self.group.tokens["context"]).startswith('"'):
            raise CompileWarning("gettext may not recognize single-quoted strings")

    @validate("string")
    def string_double_quoted(self):
        if not str(self.group.tokens["string"]).startswith('"'):
            raise CompileWarning("gettext may not recognize single-quoted strings")

    @docs()
    def ref_docs(self):
        return get_docs_section("Syntax Translated")


class TypeLiteral(AstNode):
    grammar = [
        "typeof",
        AnyOf(
            [
                "<",
                to_parse_node(TypeName).expected("type name"),
                Match(">").expected(),
            ],
            [
                UseExact("lparen", "("),
                to_parse_node(TypeName).expected("type name"),
                UseExact("rparen", ")").expected("')'"),
            ],
        ),
    ]

    @property
    def type(self):
        return gir.TypeType()

    @property
    def type_name(self) -> TypeName:
        return self.children[TypeName][0]

    @validate()
    def validate_for_type(self) -> None:
        expected_type = self.context[ValueTypeCtx].value_type
        if expected_type is not None and not isinstance(expected_type, gir.TypeType):
            raise CompileError(f"Cannot convert GType to {expected_type.full_name}")

    @validate("lparen", "rparen")
    def upgrade_to_angle_brackets(self):
        if self.tokens["lparen"]:
            raise UpgradeWarning(
                "Use angle bracket syntax introduced in blueprint 0.8.0",
                actions=[
                    CodeAction(
                        "Use <> instead of ()",
                        f"<{self.children[TypeName][0].as_string}>",
                    )
                ],
            )

    @docs()
    def ref_docs(self):
        return get_docs_section("Syntax TypeLiteral")


class QuotedLiteral(AstNode):
    grammar = UseQuoted("value")

    @property
    def value(self) -> str:
        return self.tokens["value"]

    @property
    def type(self):
        return gir.StringType()

    @validate()
    def validate_for_type(self) -> None:
        expected_type = self.context[ValueTypeCtx].value_type
        if (
            isinstance(expected_type, gir.IntType)
            or isinstance(expected_type, gir.UIntType)
            or isinstance(expected_type, gir.FloatType)
        ):
            raise CompileError(f"Cannot convert string to number")

        elif isinstance(expected_type, gir.StringType):
            pass

        elif (
            isinstance(expected_type, gir.Class)
            or isinstance(expected_type, gir.Interface)
            or isinstance(expected_type, gir.Boxed)
        ):
            parseable_types = [
                "Gdk.Paintable",
                "Gdk.Texture",
                "Gdk.Pixbuf",
                "Gio.File",
                "Gtk.ShortcutTrigger",
                "Gtk.ShortcutAction",
                "Gdk.RGBA",
                "Gdk.ContentFormats",
                "Gsk.Transform",
                "GLib.Variant",
            ]
            if expected_type.full_name not in parseable_types:
                hints = []
                if isinstance(expected_type, gir.TypeType):
                    hints.append(f"use the typeof operator: 'typeof({self.value})'")
                raise CompileError(
                    f"Cannot convert string to {expected_type.full_name}", hints=hints
                )

        elif expected_type is not None:
            raise CompileError(f"Cannot convert string to {expected_type.full_name}")


class NumberLiteral(AstNode):
    grammar = [
        Optional(AnyOf(UseExact("sign", "-"), UseExact("sign", "+"))),
        UseNumber("value"),
    ]

    @property
    def type(self) -> gir.GirType:
        if isinstance(self.value, int):
            return gir.IntType()
        else:
            return gir.FloatType()

    @property
    def value(self) -> T.Union[int, float]:
        if self.tokens["sign"] == "-":
            return -self.tokens["value"]
        else:
            return self.tokens["value"]

    @validate()
    def validate_for_type(self) -> None:
        expected_type = self.context[ValueTypeCtx].value_type
        if isinstance(expected_type, gir.IntType):
            if not isinstance(self.value, int):
                raise CompileError(
                    f"Cannot convert {self.group.tokens['value']} to integer"
                )

        elif isinstance(expected_type, gir.UIntType):
            if self.value < 0:
                raise CompileError(
                    f"Cannot convert -{self.group.tokens['value']} to unsigned integer"
                )

        elif not isinstance(expected_type, gir.FloatType) and expected_type is not None:
            raise CompileError(f"Cannot convert number to {expected_type.full_name}")


class Flag(AstNode):
    grammar = UseIdent("value")

    @property
    def name(self) -> str:
        return self.tokens["value"]

    @property
    def value(self) -> T.Optional[str]:
        type = self.context[ValueTypeCtx].value_type
        if not isinstance(type, Enumeration):
            return None
        elif member := type.members.get(self.name):
            return member.nick
        else:
            return None

    def get_semantic_tokens(self) -> T.Iterator[SemanticToken]:
        yield SemanticToken(
            self.group.tokens["value"].start,
            self.group.tokens["value"].end,
            SemanticTokenType.EnumMember,
        )

    @docs()
    def docs(self):
        type = self.context[ValueTypeCtx].value_type
        if not isinstance(type, Enumeration):
            return
        if member := type.members.get(self.tokens["value"]):
            return member.doc

    @validate()
    def validate_for_type(self):
        expected_type = self.context[ValueTypeCtx].value_type
        if (
            isinstance(expected_type, gir.Bitfield)
            and self.tokens["value"] not in expected_type.members
        ):
            raise CompileError(
                f"{self.tokens['value']} is not a member of {expected_type.full_name}",
                did_you_mean=(self.tokens["value"], expected_type.members.keys()),
            )

    @validate()
    def unique(self):
        self.validate_unique_in_parent(
            f"Duplicate flag '{self.name}'", lambda x: x.name == self.name
        )


class Flags(AstNode):
    grammar = [Flag, "|", Flag, ZeroOrMore(["|", Flag])]

    @property
    def flags(self) -> T.List[Flag]:
        return self.children

    @validate()
    def validate_for_type(self) -> None:
        expected_type = self.context[ValueTypeCtx].value_type
        if expected_type is not None and not isinstance(expected_type, gir.Bitfield):
            raise CompileError(f"{expected_type.full_name} is not a bitfield type")

    @docs()
    def ref_docs(self):
        return get_docs_section("Syntax Flags")


class IdentLiteral(AstNode):
    grammar = UseIdent("value")

    @property
    def ident(self) -> str:
        return self.tokens["value"]

    @property
    def type(self) -> T.Optional[gir.GirType]:
        # If the expected type is known, then use that. Otherwise, guess.
        if expected_type := self.context[ValueTypeCtx].value_type:
            return expected_type
        elif self.ident in ["true", "false"]:
            return gir.BoolType()
        elif object := self.context[ScopeCtx].objects.get(self.ident):
            return object.gir_class
        elif self.root.is_legacy_template(self.ident):
            return self.root.template.class_name.gir_type
        else:
            return None

    @validate()
    def validate_for_type(self) -> None:
        expected_type = self.context[ValueTypeCtx].value_type
        if isinstance(expected_type, gir.BoolType):
            if self.ident not in ["true", "false"]:
                raise CompileError(f"Expected 'true' or 'false' for boolean value")

        elif isinstance(expected_type, gir.Enumeration):
            if self.ident not in expected_type.members:
                raise CompileError(
                    f"{self.ident} is not a member of {expected_type.full_name}",
                    did_you_mean=(self.ident, list(expected_type.members.keys())),
                )

        elif self.root.is_legacy_template(self.ident):
            raise UpgradeWarning(
                "Use 'template' instead of the class name (introduced in 0.8.0)",
                actions=[CodeAction("Use 'template'", "template")],
            )

        elif expected_type is not None or self.context[ValueTypeCtx].must_infer_type:
            object = self.context[ScopeCtx].objects.get(self.ident)
            if object is None:
                if self.ident == "null":
                    if not self.context[ValueTypeCtx].allow_null:
                        raise CompileError("null is not permitted here")
                elif self.ident == "item":
                    if not self.context[ExprValueCtx]:
                        raise CompileError(
                            '"item" can only be used in an expression literal'
                        )
                elif self.ident not in ["true", "false"]:
                    raise CompileError(
                        f"Could not find object with ID {self.ident}",
                        did_you_mean=(
                            self.ident,
                            self.context[ScopeCtx].objects.keys(),
                        ),
                    )
            elif (
                expected_type is not None
                and object.gir_class is not None
                and not object.gir_class.assignable_to(expected_type)
            ):
                raise CompileError(
                    f"Cannot assign {object.gir_class.full_name} to {expected_type.full_name}"
                )

    @docs()
    def docs(self) -> T.Optional[str]:
        expected_type = self.context[ValueTypeCtx].value_type
        if isinstance(expected_type, gir.BoolType):
            return None
        elif isinstance(expected_type, gir.Enumeration):
            if member := expected_type.members.get(self.ident):
                return member.doc
            else:
                return expected_type.doc
        elif self.ident == "null" and self.context[ValueTypeCtx].allow_null:
            return None
        elif object := self.context[ScopeCtx].objects.get(self.ident):
            return f"```\n{object.signature}\n```"
        elif self.root.is_legacy_template(self.ident):
            return f"```\n{self.root.template.signature}\n```"
        else:
            return None

    def get_semantic_tokens(self) -> T.Iterator[SemanticToken]:
        type = self.context[ValueTypeCtx].value_type
        if isinstance(type, gir.Enumeration):
            token = self.group.tokens["value"]
            yield SemanticToken(token.start, token.end, SemanticTokenType.EnumMember)

    def get_reference(self, _idx: int) -> T.Optional[LocationLink]:
        ref = self.context[ScopeCtx].objects.get(self.ident)
        if ref is None and self.root.is_legacy_template(self.ident):
            ref = self.root.template

        if ref:
            return LocationLink(self.range, ref.range, ref.ranges["id"])
        else:
            return None


class Literal(AstNode):
    grammar = AnyOf(
        TypeLiteral,
        QuotedLiteral,
        NumberLiteral,
        IdentLiteral,
    )

    @property
    def value(
        self,
    ) -> T.Union[TypeLiteral, QuotedLiteral, NumberLiteral, IdentLiteral]:
        return self.children[0]


class ObjectValue(AstNode):
    grammar = Object

    @property
    def object(self) -> Object:
        return self.children[Object][0]

    @validate()
    def validate_for_type(self) -> None:
        expected_type = self.context[ValueTypeCtx].value_type
        if (
            expected_type is not None
            and self.object.gir_class is not None
            and not self.object.gir_class.assignable_to(expected_type)
        ):
            raise CompileError(
                f"Cannot assign {self.object.gir_class.full_name} to {expected_type.full_name}"
            )


class ExprValue(AstNode):
    grammar = [Keyword("expr"), Expression]

    @property
    def expression(self) -> Expression:
        return self.children[Expression][0]

    @validate("expr")
    def validate_for_type(self) -> None:
        expected_type = self.parent.context[ValueTypeCtx].value_type
        expr_type = self.root.gir.get_type("Expression", "Gtk")
        if expected_type is not None and not expected_type.assignable_to(expr_type):
            raise CompileError(
                f"Cannot convert Gtk.Expression to {expected_type.full_name}"
            )

    @docs("expr")
    def ref_docs(self):
        return get_docs_section("Syntax ExprValue")

    @context(ExprValueCtx)
    def expr_literal(self):
        return ExprValueCtx()

    @context(ValueTypeCtx)
    def value_type(self):
        return ValueTypeCtx(None, must_infer_type=True)


class Value(AstNode):
    grammar = AnyOf(Translated, Flags, Literal)

    @property
    def child(
        self,
    ) -> T.Union[Translated, Flags, Literal]:
        return self.children[0]


class ArrayValue(AstNode):
    grammar = ["[", Delimited(Value, ","), "]"]

    @validate()
    def validate_for_type(self) -> None:
        expected_type = self.gir_type
        if expected_type is not None and not isinstance(expected_type, gir.ArrayType):
            raise CompileError(f"Cannot assign array to {expected_type.full_name}")

        if expected_type is not None and not isinstance(
            expected_type.inner, StringType
        ):
            raise CompileError("Only string arrays are supported")

    @validate()
    def validate_invalid_newline(self) -> None:
        expected_type = self.gir_type
        if isinstance(expected_type, gir.ArrayType) and isinstance(
            expected_type.inner, StringType
        ):
            errors = []
            for value in self.values:
                if isinstance(value.child, Literal) and isinstance(
                    value.child.value, QuotedLiteral
                ):
                    quoted_literal = value.child.value
                    literal_value = quoted_literal.value
                    # literal_value can be None if there's an invalid escape sequence
                    if literal_value is not None and "\n" in literal_value:
                        errors.append(
                            CompileError(
                                "String literals inside arrays can't contain newlines",
                                range=quoted_literal.range,
                            )
                        )
                elif isinstance(value.child, Translated):
                    errors.append(
                        CompileError(
                            "Arrays can't contain translated strings",
                            range=value.child.range,
                        )
                    )

            if len(errors) > 0:
                raise MultipleErrors(errors)

    @property
    def values(self) -> T.List[Value]:
        return self.children

    @property
    def gir_type(self):
        return self.parent.context[ValueTypeCtx].value_type

    @context(ValueTypeCtx)
    def child_value(self):
        if self.gir_type is None or not isinstance(self.gir_type, ArrayType):
            return ValueTypeCtx(None)
        else:
            return ValueTypeCtx(self.gir_type.inner)


class StringValue(AstNode):
    grammar = AnyOf(Translated, QuotedLiteral)

    @property
    def child(
        self,
    ) -> T.Union[Translated, QuotedLiteral]:
        return self.children[0]

    @property
    def string(self) -> str:
        if isinstance(self.child, Translated):
            return self.child.string
        else:
            return self.child.value

    @context(ValueTypeCtx)
    def value_type(self) -> ValueTypeCtx:
        return ValueTypeCtx(StringType())