Compiling to Rust
TreeLDR can generate a Rust type definition for each defined layout. For instance, consider the following layout for the
schema:BlogPosting
type:// example/basic_post.tldr
base <https://example.com/>;
use <https://schema.org/> as schema;
layout BasicPost for schema:BlogPosting {
/// Title of the post.
schema:title: schema:Text,
/// Content of the post.
schema:body: schema:Text
}
TreeLDR can generate the following Rust type:
pub struct BasicPost {
/// Title of the post.
title: Option<schema::Text>,
/// Content of the post.
body: Option<schema:Text>
}
Non
required
properties are automatically translated into fields with an Option
type.We can embed TreeLDR-generated code inside a Rust program using the
tldr
procedural macro attribute provided by the treeldr-rust-macros
crate. This attribute allows us to annotate a module that will host all the TreeLDR-generated definitions. It requires two inputs:- The list of all the TreeLDR files we need to import, given as parameters of the
tldr
attribute; and - The destination (path in the module) of each type definition. This is done by declaring a submodule for each IRI prefix of interest. The type definition of each layout will be generated in the submodule whose prefix matches the identifier of the layout.
#[tldr(
"examples/schema.org.tldr",
"examples/basic_post.tldr"
)]
pub mod example {
/// schema.org types.
#[prefix("https://schema.org/")]
pub mod schema {}
/// Basic Post example types.
#[prefix("https://example.com/example/")]
pub mod basic_post {}
}
This will expand into the following code:
pub mod example {
pub mod schema {
pub type Text = String;
}
pub mod basic_post {
pub struct BasicPost {
/// Title of the post.
title: Option<super::schema::Text>,
/// Content of the post.
body: Option<super::schema:Text>
}
}
}
In addition to the type definitions, TreeLDR will also provide some traits implementations for those types.
Each type will implement
Clone
, PartialEq
, Eq
, PartialOrd
, Ord
and Hash
.Each type will implement the
FromRdf
trait provided by the treeldr_rust_prelude
crate. This trait provides the from_rdf
constructor function that can extract an instance of the given type from an RDF dataset defined with the grdf
crate.use treeldr_rust_prelude::FromRdf;
let post = example::basic_post::BasicPost::from_rdf(
id,
dataset.default_graph(),
).expect("invalid post");
Each type will implement the
IntoJsonLd
trait provided by the treeldr_rust_prelude
crate. This trait provides the into_json_ld
method that converts the value into a json_ld::syntax::Value
.use treeldr_rust_prelude::IntoJsonLd;
// Schema to JSON-LD.
let json_ld: json_ld::syntax::Value<json_ld::syntax::ContextEntry<()>, _> =
vc.into_json_ld();
Last modified 9mo ago