mirror of
https://gitlab.gnome.org/jwestman/blueprint-compiler.git
synced 2025-05-04 15:59:08 -04:00
Add GObject Introspection integration
- Parse .gir files - Validate class, property, and signal names
This commit is contained in:
parent
2ad2f1c54a
commit
e553e5db29
10 changed files with 734 additions and 58 deletions
|
@ -18,13 +18,102 @@
|
|||
# SPDX-License-Identifier: LGPL-3.0-or-later
|
||||
|
||||
|
||||
from .errors import assert_true
|
||||
from .errors import assert_true, AlreadyCaughtError, CompileError, CompilerBugError, MultipleErrors
|
||||
from .gir import GirContext, get_namespace
|
||||
from .utils import lazy_prop
|
||||
from .xml_emitter import XmlEmitter
|
||||
|
||||
|
||||
class Validator():
|
||||
def __init__(self, func, token_name=None, end_token_name=None):
|
||||
self.func = func
|
||||
self.token_name = token_name
|
||||
self.end_token_name = end_token_name
|
||||
|
||||
def __get__(self, instance, owner):
|
||||
if instance is None:
|
||||
return self
|
||||
|
||||
key = "_validation_result_" + self.func.__name__
|
||||
|
||||
if key + "_err" in instance.__dict__:
|
||||
# If the validator has failed before, raise a generic Exception.
|
||||
# We want anything that depends on this validation result to
|
||||
# fail, but not report the exception twice.
|
||||
raise AlreadyCaughtError()
|
||||
|
||||
if key not in instance.__dict__:
|
||||
try:
|
||||
instance.__dict__[key] = self.func(instance)
|
||||
except CompileError as e:
|
||||
# Mark the validator as already failed so we don't print the
|
||||
# same message again
|
||||
instance.__dict__[key + "_err"] = True
|
||||
|
||||
# This mess of code sets the error's start and end positions
|
||||
# from the tokens passed to the decorator, if they have not
|
||||
# already been set
|
||||
if self.token_name is not None and e.start is None:
|
||||
group = instance.group.tokens.get(self.token_name)
|
||||
if self.end_token_name is not None and group is None:
|
||||
group = instance.group.tokens[self.end_token_name]
|
||||
e.start = group.start
|
||||
if (self.token_name is not None or self.end_token_name is not None) and e.end is None:
|
||||
e.end = instance.group.tokens[self.end_token_name or self.token_name].end
|
||||
|
||||
# Re-raise the exception
|
||||
raise e
|
||||
|
||||
# Return the validation result (which other validators, or the code
|
||||
# generation phase, might depend on)
|
||||
return instance.__dict__[key]
|
||||
|
||||
|
||||
def validate(*args, **kwargs):
|
||||
""" Decorator for functions that validate an AST node. Exceptions raised
|
||||
during validation are marked with range information from the tokens. Also
|
||||
creates a cached property out of the function. """
|
||||
|
||||
def decorator(func):
|
||||
return Validator(func, *args, **kwargs)
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
class AstNode:
|
||||
""" Base class for nodes in the abstract syntax tree. """
|
||||
|
||||
def __init__(self):
|
||||
self.group = None
|
||||
self.parent = None
|
||||
self.child_nodes = None
|
||||
|
||||
@lazy_prop
|
||||
def root(self):
|
||||
if self.parent is None:
|
||||
return self
|
||||
else:
|
||||
return self.parent.root
|
||||
|
||||
@lazy_prop
|
||||
def errors(self):
|
||||
return list(self._get_errors())
|
||||
|
||||
def _get_errors(self):
|
||||
for name in dir(type(self)):
|
||||
item = getattr(type(self), name)
|
||||
if isinstance(item, Validator):
|
||||
try:
|
||||
getattr(self, name)
|
||||
except AlreadyCaughtError:
|
||||
pass
|
||||
except CompileError as e:
|
||||
yield e
|
||||
|
||||
for child in self.child_nodes:
|
||||
yield from child._get_errors()
|
||||
|
||||
|
||||
def generate(self) -> str:
|
||||
""" Generates an XML string from the node. """
|
||||
xml = XmlEmitter()
|
||||
|
@ -40,6 +129,7 @@ class UI(AstNode):
|
|||
""" The AST node for the entire file """
|
||||
|
||||
def __init__(self, gtk_directives=[], imports=[], objects=[], templates=[]):
|
||||
super().__init__()
|
||||
assert_true(len(gtk_directives) == 1)
|
||||
|
||||
self.gtk_directive = gtk_directives[0]
|
||||
|
@ -47,6 +137,22 @@ class UI(AstNode):
|
|||
self.objects = objects
|
||||
self.templates = templates
|
||||
|
||||
@validate()
|
||||
def gir(self):
|
||||
gir = GirContext()
|
||||
|
||||
gir.add_namespace(self.gtk_directive.gir_namespace)
|
||||
for i in self.imports:
|
||||
gir.add_namespace(i.gir_namespace)
|
||||
|
||||
return gir
|
||||
|
||||
@validate()
|
||||
def at_most_one_template(self):
|
||||
if len(self.templates) > 1:
|
||||
raise CompileError(f"Only one template may be defined per file, but this file contains {len(self.templates)}",
|
||||
self.templates[1].group.start)
|
||||
|
||||
def emit_xml(self, xml: XmlEmitter):
|
||||
xml.start_tag("interface")
|
||||
self.gtk_directive.emit_xml(xml)
|
||||
|
@ -60,8 +166,21 @@ class UI(AstNode):
|
|||
class GtkDirective(AstNode):
|
||||
child_type = "gtk_directives"
|
||||
def __init__(self, version):
|
||||
super().__init__()
|
||||
self.version = version
|
||||
|
||||
@validate("version")
|
||||
def gir_namespace(self):
|
||||
if self.version in ["4.0"]:
|
||||
return get_namespace("Gtk", self.version)
|
||||
else:
|
||||
err = CompileError("Only GTK 4 is supported")
|
||||
if self.version.startswith("4"):
|
||||
err.hint("Expected the GIR version, not an exact version number. Use `@gtk \"4.0\";`.")
|
||||
else:
|
||||
err.hint("Expected `@gtk \"4.0\";`")
|
||||
raise err
|
||||
|
||||
def emit_xml(self, xml: XmlEmitter):
|
||||
xml.put_self_closing("requires", lib="gtk", version=self.version)
|
||||
|
||||
|
@ -69,9 +188,14 @@ class GtkDirective(AstNode):
|
|||
class Import(AstNode):
|
||||
child_type = "imports"
|
||||
def __init__(self, namespace, version):
|
||||
super().__init__()
|
||||
self.namespace = namespace
|
||||
self.version = version
|
||||
|
||||
@validate("namespace", "version")
|
||||
def gir_namespace(self):
|
||||
return get_namespace(self.namespace, self.version)
|
||||
|
||||
def emit_xml(self, xml: XmlEmitter):
|
||||
pass
|
||||
|
||||
|
@ -79,6 +203,7 @@ class Import(AstNode):
|
|||
class Template(AstNode):
|
||||
child_type = "templates"
|
||||
def __init__(self, name, class_name, object_content, namespace=None):
|
||||
super().__init__()
|
||||
assert_true(len(object_content) == 1)
|
||||
|
||||
self.name = name
|
||||
|
@ -86,10 +211,16 @@ class Template(AstNode):
|
|||
self.parent_class = class_name
|
||||
self.object_content = object_content[0]
|
||||
|
||||
|
||||
@validate("namespace", "class_name")
|
||||
def gir_parent(self):
|
||||
return self.root.gir.get_class(self.parent_class, self.parent_namespace)
|
||||
|
||||
|
||||
def emit_xml(self, xml: XmlEmitter):
|
||||
xml.start_tag("template", **{
|
||||
"class": self.name,
|
||||
"parent": self.parent_namespace + self.parent_class,
|
||||
"parent": self.gir_parent.glib_type_name,
|
||||
})
|
||||
self.object_content.emit_xml(xml)
|
||||
xml.end_tag()
|
||||
|
@ -98,6 +229,7 @@ class Template(AstNode):
|
|||
class Object(AstNode):
|
||||
child_type = "objects"
|
||||
def __init__(self, class_name, object_content, namespace=None, id=None):
|
||||
super().__init__()
|
||||
assert_true(len(object_content) == 1)
|
||||
|
||||
self.namespace = namespace
|
||||
|
@ -105,9 +237,13 @@ class Object(AstNode):
|
|||
self.id = id
|
||||
self.object_content = object_content[0]
|
||||
|
||||
@validate("namespace", "class_name")
|
||||
def gir_class(self):
|
||||
return self.root.gir.get_class(self.class_name, self.namespace)
|
||||
|
||||
def emit_xml(self, xml: XmlEmitter):
|
||||
xml.start_tag("object", **{
|
||||
"class": self.namespace + self.class_name,
|
||||
"class": self.gir_class.glib_type_name,
|
||||
"id": self.id,
|
||||
})
|
||||
self.object_content.emit_xml(xml)
|
||||
|
@ -117,6 +253,7 @@ class Object(AstNode):
|
|||
class Child(AstNode):
|
||||
child_type = "children"
|
||||
def __init__(self, objects, child_type=None):
|
||||
super().__init__()
|
||||
assert_true(len(objects) == 1)
|
||||
self.object = objects[0]
|
||||
self.child_type = child_type
|
||||
|
@ -130,28 +267,62 @@ class Child(AstNode):
|
|||
class ObjectContent(AstNode):
|
||||
child_type = "object_content"
|
||||
def __init__(self, properties=[], signals=[], children=[]):
|
||||
super().__init__()
|
||||
self.properties = properties
|
||||
self.signals = signals
|
||||
self.children = children
|
||||
|
||||
def emit_xml(self, xml: XmlEmitter):
|
||||
for prop in self.properties:
|
||||
prop.emit_xml(xml)
|
||||
for signal in self.signals:
|
||||
signal.emit_xml(xml)
|
||||
for child in self.children:
|
||||
child.emit_xml(xml)
|
||||
for x in [*self.properties, *self.signals, *self.children]:
|
||||
x.emit_xml(xml)
|
||||
|
||||
|
||||
class Property(AstNode):
|
||||
child_type = "properties"
|
||||
def __init__(self, name, value=None, translatable=False, bind_source=None, bind_property=None):
|
||||
super().__init__()
|
||||
self.name = name
|
||||
self.value = value
|
||||
self.translatable = translatable
|
||||
self.bind_source = bind_source
|
||||
self.bind_property = bind_property
|
||||
|
||||
|
||||
@validate()
|
||||
def gir_property(self):
|
||||
if self.gir_class is not None:
|
||||
return self.gir_class.properties.get(self.name)
|
||||
|
||||
@validate()
|
||||
def gir_class(self):
|
||||
parent = self.parent.parent
|
||||
if isinstance(parent, Template):
|
||||
return parent.gir_parent
|
||||
elif isinstance(parent, Object):
|
||||
return parent.gir_class
|
||||
else:
|
||||
raise CompilerBugError()
|
||||
|
||||
|
||||
@validate("name")
|
||||
def property_exists(self):
|
||||
if self.gir_class is None:
|
||||
# Objects that we have no gir data on should not be validated
|
||||
# This happens for classes defined by the app itself
|
||||
return
|
||||
|
||||
if isinstance(self.parent.parent, Template):
|
||||
# If the property is part of a template, it might be defined by
|
||||
# the application and thus not in gir
|
||||
return
|
||||
|
||||
if self.gir_property is None:
|
||||
raise CompileError(
|
||||
f"Class {self.gir_class.full_name} does not contain a property called {self.name}",
|
||||
did_you_mean=(self.name, self.gir_class.properties.keys())
|
||||
)
|
||||
|
||||
|
||||
def emit_xml(self, xml: XmlEmitter):
|
||||
props = {
|
||||
"name": self.name,
|
||||
|
@ -170,6 +341,7 @@ class Property(AstNode):
|
|||
class Signal(AstNode):
|
||||
child_type = "signals"
|
||||
def __init__(self, name, handler, swapped=False, after=False, object=False, detail_name=None):
|
||||
super().__init__()
|
||||
self.name = name
|
||||
self.handler = handler
|
||||
self.swapped = swapped
|
||||
|
@ -177,6 +349,42 @@ class Signal(AstNode):
|
|||
self.object = object
|
||||
self.detail_name = detail_name
|
||||
|
||||
|
||||
@validate()
|
||||
def gir_signal(self):
|
||||
if self.gir_class is not None:
|
||||
return self.gir_class.signals.get(self.name)
|
||||
|
||||
@validate()
|
||||
def gir_class(self):
|
||||
parent = self.parent.parent
|
||||
if isinstance(parent, Template):
|
||||
return parent.gir_parent
|
||||
elif isinstance(parent, Object):
|
||||
return parent.gir_class
|
||||
else:
|
||||
raise CompilerBugError()
|
||||
|
||||
|
||||
@validate("name")
|
||||
def signal_exists(self):
|
||||
if self.gir_class is None:
|
||||
# Objects that we have no gir data on should not be validated
|
||||
# This happens for classes defined by the app itself
|
||||
return
|
||||
|
||||
if isinstance(self.parent.parent, Template):
|
||||
# If the signal is part of a template, it might be defined by
|
||||
# the application and thus not in gir
|
||||
return
|
||||
|
||||
if self.gir_signal is None:
|
||||
print(self.gir_class.signals.keys())
|
||||
raise CompileError(
|
||||
f"Class {self.gir_class.full_name} does not contain a signal called {self.name}",
|
||||
did_you_mean=(self.name, self.gir_class.signals.keys())
|
||||
)
|
||||
|
||||
def emit_xml(self, xml: XmlEmitter):
|
||||
name = self.name
|
||||
if self.detail_name:
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue