Skip to main content

i_slint_compiler/
lib.rs

1// Copyright © SixtyFPS GmbH <info@slint.dev>
2// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
3
4#![doc = include_str!("README.md")]
5#![doc(html_logo_url = "https://slint.dev/logo/slint-logo-square-light.svg")]
6#![cfg_attr(docsrs, feature(doc_cfg))]
7// It would be nice to keep the compiler free of unsafe code
8#![deny(unsafe_code)]
9
10#[cfg(feature = "proc_macro_span")]
11extern crate proc_macro;
12
13use core::future::Future;
14use core::pin::Pin;
15use std::cell::RefCell;
16use std::collections::HashMap;
17use std::rc::Rc;
18#[cfg(feature = "software-renderer")]
19use std::sync::Arc;
20
21pub mod builtin_macros;
22pub mod diagnostics;
23pub mod embedded_resources;
24pub mod expression_tree;
25pub mod fileaccess;
26pub mod generator;
27pub mod langtype;
28pub mod layout;
29pub mod lexer;
30pub mod literals;
31pub mod llr;
32pub(crate) mod load_builtins;
33pub mod lookup;
34pub mod namedreference;
35pub mod object_tree;
36pub mod parser;
37pub mod pathutils;
38#[cfg(feature = "bundle-translations")]
39pub mod translations;
40pub mod typeloader;
41pub mod typeregister;
42
43pub mod passes;
44
45use crate::generator::OutputFormat;
46use std::path::Path;
47
48/// Specify how the resources are embedded by the compiler
49#[derive(Clone, Copy, Debug, Eq, PartialEq)]
50pub enum EmbedResourcesKind {
51    /// Embeds nothing (only useful for interpreter)
52    Nothing,
53    /// Only embed builtin resources
54    OnlyBuiltinResources,
55    /// Do not embed resources, but list them in the Document as if they were embedded
56    ListAllResources,
57    /// Embed all images resources (the content of their files)
58    EmbedAllResources,
59    #[cfg(feature = "software-renderer")]
60    /// Embed raw texture (process images and fonts)
61    EmbedTextures,
62}
63
64/// This enum specifies the default translation context when no context is explicitly
65/// specified in the `@tr("context" => ...)` macro.
66#[derive(Clone, Debug, Eq, PartialEq)]
67#[non_exhaustive]
68pub enum DefaultTranslationContext {
69    /// The default translation context is the component name in which the `@tr` is written.
70    ///
71    /// This is the default behavior of `slint-tr-extractor`.
72    ComponentName,
73    /// Opt out of the default translation context.
74    ///
75    /// When using this option, invoke `slint-tr-extractor` with `--no-default-translation-context`
76    /// to make sure that the translation files have no context for strings which didn't specify a context.
77    None,
78}
79
80#[derive(Clone, Debug, Eq, PartialEq, Default)]
81#[non_exhaustive]
82pub enum ComponentSelection {
83    /// All components that inherit from Window.
84    ///
85    /// Note: Components marked for export but lacking Window inheritance are not selected (this will produce a warning),
86    /// For compatibility reason, the last exported component is still selected even if it doesn't inherit Window,
87    /// and if no component is exported, the last component is selected
88    #[default]
89    ExportedWindows,
90
91    /// The Last component (legacy for the viewer / interpreter)
92    ///
93    /// Only the last exported component is generated, regardless if this is a Window or not,
94    /// (and it will be transformed in a Window)
95    LastExported,
96
97    /// The component with the given name is generated
98    Named(String),
99}
100
101#[cfg(feature = "software-renderer")]
102pub type FontCache = Rc<
103    RefCell<
104        std::collections::HashMap<
105            (i_slint_common::sharedfontique::fontique::FamilyId, usize),
106            fontdue::FontResult<Arc<fontdue::Font>>,
107        >,
108    >,
109>;
110
111/// Type alias for the callback to open files mentioned in `import` statements
112///
113/// This is a dyn-compatible version of:
114///
115/// ```ignore
116/// async fn(String) -> Option<std::io::Result<String>>
117/// ```
118///
119/// Unfortunately AsyncFn is not dyn-compatible yet.
120pub type OpenImportCallback =
121    Rc<dyn Fn(String) -> Pin<Box<dyn Future<Output = Option<std::io::Result<String>>>>>>;
122pub type ResourceUrlMapper = Rc<dyn Fn(&str) -> Pin<Box<dyn Future<Output = Option<String>>>>>;
123
124/// CompilationConfiguration allows configuring different aspects of the compiler.
125#[derive(Clone)]
126pub struct CompilerConfiguration {
127    /// Indicate whether to embed resources such as images in the generated output or whether
128    /// to retain references to the resources on the file system.
129    pub embed_resources: EmbedResourcesKind,
130    /// Whether to use SDF when pre-rendering fonts.
131    #[cfg(all(feature = "software-renderer", feature = "sdf-fonts"))]
132    pub use_sdf_fonts: bool,
133    /// The compiler will look in these paths for components used in the file to compile.
134    pub include_paths: Vec<std::path::PathBuf>,
135    /// The compiler will look in these paths for library imports.
136    pub library_paths: HashMap<String, std::path::PathBuf>,
137    /// the name of the style. (eg: "native")
138    pub style: Option<String>,
139
140    /// Callback to load import files
141    ///
142    /// The callback should open the file specified by the given file name and
143    /// return a future that provides the text content of the file as output.
144    pub open_import_callback: Option<OpenImportCallback>,
145    /// Callback to map URLs for resources
146    ///
147    /// The function takes the url and returns the mapped URL (or None if not mapped)
148    pub resource_url_mapper: Option<ResourceUrlMapper>,
149
150    /// Run the pass that inlines all the elements.
151    ///
152    /// This may help optimization to optimize the runtime resources usages,
153    /// but at the cost of much more generated code and binary size.
154    pub inline_all_elements: bool,
155
156    /// Compile time scale factor to apply to embedded resources such as images and glyphs.
157    /// It will also be set as a const scale factor on the `slint::Window`.
158    pub const_scale_factor: Option<f32>,
159
160    /// expose the accessible role and properties
161    pub accessibility: bool,
162
163    /// Add support for experimental features
164    pub enable_experimental: bool,
165
166    /// The domain used as one of the parameter to the translate function
167    pub translation_domain: Option<String>,
168    /// When Some, this is the path where the translations are looked at to bundle the translations
169    #[cfg(feature = "bundle-translations")]
170    pub translation_path_bundle: Option<std::path::PathBuf>,
171    /// Default translation context
172    pub default_translation_context: DefaultTranslationContext,
173
174    /// Do not generate the hook to create native menus
175    pub no_native_menu: bool,
176
177    /// C++ namespace
178    pub cpp_namespace: Option<String>,
179
180    /// When true, fail the build when a binding loop is detected with a window layout property
181    /// (otherwise this is a compatibility warning)
182    pub error_on_binding_loop_with_window_layout: bool,
183
184    /// Generate debug information for elements (ids, type names)
185    pub debug_info: bool,
186
187    /// Generate debug hooks to inspect/override properties.
188    pub debug_hooks: Option<std::hash::RandomState>,
189
190    pub components_to_generate: ComponentSelection,
191
192    #[cfg(feature = "software-renderer")]
193    pub font_cache: FontCache,
194
195    /// The name of the library when compiling as a library.
196    pub library_name: Option<String>,
197
198    /// Specify the Rust module to place the generated code in.
199    pub rust_module: Option<String>,
200}
201
202impl CompilerConfiguration {
203    pub fn new(output_format: OutputFormat) -> Self {
204        let embed_resources = if std::env::var_os("SLINT_EMBED_TEXTURES").is_some()
205            || std::env::var_os("DEP_MCU_BOARD_SUPPORT_MCU_EMBED_TEXTURES").is_some()
206        {
207            #[cfg(not(feature = "software-renderer"))]
208            panic!(
209                "the software-renderer feature must be enabled in i-slint-compiler when embedding textures"
210            );
211            #[cfg(feature = "software-renderer")]
212            EmbedResourcesKind::EmbedTextures
213        } else if let Ok(var) = std::env::var("SLINT_EMBED_RESOURCES") {
214            let var = var.parse::<bool>().unwrap_or_else(|_|{
215                panic!("SLINT_EMBED_RESOURCES has incorrect value. Must be either unset, 'true' or 'false'")
216            });
217            match var {
218                true => EmbedResourcesKind::EmbedAllResources,
219                false => EmbedResourcesKind::OnlyBuiltinResources,
220            }
221        } else {
222            match output_format {
223                #[cfg(feature = "rust")]
224                OutputFormat::Rust => EmbedResourcesKind::EmbedAllResources,
225                OutputFormat::Interpreter => EmbedResourcesKind::Nothing,
226                _ => EmbedResourcesKind::OnlyBuiltinResources,
227            }
228        };
229
230        let inline_all_elements = match std::env::var("SLINT_INLINING") {
231            Ok(var) => var.parse::<bool>().unwrap_or_else(|_| {
232                panic!(
233                    "SLINT_INLINING has incorrect value. Must be either unset, 'true' or 'false'"
234                )
235            }),
236            // Currently, the interpreter needs the inlining to be on.
237            Err(_) => output_format == OutputFormat::Interpreter,
238        };
239
240        let const_scale_factor = std::env::var("SLINT_SCALE_FACTOR")
241            .ok()
242            .and_then(|x| x.parse::<f32>().ok())
243            .filter(|f| *f > 0.);
244
245        let enable_experimental = std::env::var_os("SLINT_ENABLE_EXPERIMENTAL_FEATURES").is_some();
246
247        let debug_info = std::env::var_os("SLINT_EMIT_DEBUG_INFO").is_some();
248
249        let cpp_namespace = match output_format {
250            #[cfg(feature = "cpp")]
251            OutputFormat::Cpp(config) => match config.namespace {
252                Some(namespace) => Some(namespace),
253                None => match std::env::var("SLINT_CPP_NAMESPACE") {
254                    Ok(namespace) => Some(namespace),
255                    Err(_) => None,
256                },
257            },
258            _ => None,
259        };
260
261        Self {
262            embed_resources,
263            include_paths: Default::default(),
264            library_paths: Default::default(),
265            style: Default::default(),
266            open_import_callback: None,
267            resource_url_mapper: None,
268            inline_all_elements,
269            const_scale_factor,
270            accessibility: true,
271            enable_experimental,
272            translation_domain: None,
273            default_translation_context: DefaultTranslationContext::ComponentName,
274            no_native_menu: false,
275            cpp_namespace,
276            error_on_binding_loop_with_window_layout: false,
277            debug_info,
278            debug_hooks: None,
279            components_to_generate: ComponentSelection::ExportedWindows,
280            #[cfg(feature = "software-renderer")]
281            font_cache: Default::default(),
282            #[cfg(all(feature = "software-renderer", feature = "sdf-fonts"))]
283            use_sdf_fonts: false,
284            #[cfg(feature = "bundle-translations")]
285            translation_path_bundle: std::env::var("SLINT_BUNDLE_TRANSLATIONS")
286                .ok()
287                .map(|x| x.into()),
288            library_name: None,
289            rust_module: None,
290        }
291    }
292
293    #[cfg(feature = "software-renderer")]
294    fn load_font_by_id(
295        &self,
296        font: &i_slint_common::sharedfontique::fontique::QueryFont,
297    ) -> fontdue::FontResult<Arc<fontdue::Font>> {
298        self.font_cache
299            .borrow_mut()
300            .entry(font.family)
301            .or_insert_with(|| {
302                fontdue::Font::from_bytes(
303                    font.blob.data(),
304                    fontdue::FontSettings {
305                        collection_index: font.index,
306                        scale: 40.,
307                        ..Default::default()
308                    },
309                )
310                .map(Arc::new)
311            })
312            .clone()
313    }
314}
315
316/// Prepare for compilation of the source file
317/// - storing parser configuration
318/// - setting up the parser
319fn prepare_for_compile(
320    diagnostics: &mut diagnostics::BuildDiagnostics,
321    #[allow(unused_mut)] mut compiler_config: CompilerConfiguration,
322) -> typeloader::TypeLoader {
323    #[cfg(feature = "software-renderer")]
324    if compiler_config.embed_resources == EmbedResourcesKind::EmbedTextures {
325        // HACK: disable accessibility when compiling for the software renderer
326        // accessibility is not supported with backend that support software renderer anyway
327        compiler_config.accessibility = false;
328    }
329
330    diagnostics.enable_experimental = compiler_config.enable_experimental;
331
332    typeloader::TypeLoader::new(compiler_config, diagnostics)
333}
334
335pub async fn compile_syntax_node(
336    doc_node: parser::SyntaxNode,
337    mut diagnostics: diagnostics::BuildDiagnostics,
338    #[allow(unused_mut)] mut compiler_config: CompilerConfiguration,
339) -> (object_tree::Document, diagnostics::BuildDiagnostics, typeloader::TypeLoader) {
340    let mut loader = prepare_for_compile(&mut diagnostics, compiler_config);
341
342    let doc_node: parser::syntax_nodes::Document = doc_node.into();
343
344    let type_registry =
345        Rc::new(RefCell::new(typeregister::TypeRegister::new(&loader.global_type_registry)));
346    let (foreign_imports, reexports) =
347        loader.load_dependencies_recursively(&doc_node, &mut diagnostics, &type_registry).await;
348
349    let mut doc = crate::object_tree::Document::from_node(
350        doc_node,
351        foreign_imports,
352        reexports,
353        &mut diagnostics,
354        &type_registry,
355    );
356
357    if !diagnostics.has_errors() {
358        passes::run_passes(&mut doc, &mut loader, false, &mut diagnostics).await;
359    } else {
360        // Don't run all the passes in case of errors because because some invariants are not met.
361        passes::run_import_passes(&doc, &loader, &mut diagnostics);
362    }
363    (doc, diagnostics, loader)
364}
365
366/// Pass a file to the compiler and process it fully, applying all the
367/// necessary compilation passes.
368///
369/// This returns a `Tuple` containing the actual cleaned `path` to the file,
370/// a set of `BuildDiagnostics` and a `TypeLoader` with all compilation passes applied.
371pub async fn load_root_file(
372    path: &Path,
373    source_path: &Path,
374    source_code: String,
375    mut diagnostics: diagnostics::BuildDiagnostics,
376    #[allow(unused_mut)] mut compiler_config: CompilerConfiguration,
377) -> (std::path::PathBuf, diagnostics::BuildDiagnostics, typeloader::TypeLoader) {
378    let mut loader = prepare_for_compile(&mut diagnostics, compiler_config);
379
380    let (path, _) =
381        loader.load_root_file(path, source_path, source_code, false, &mut diagnostics).await;
382
383    (path, diagnostics, loader)
384}
385
386/// Pass a file to the compiler and process it fully, applying all the
387/// necessary compilation passes, just like `load_root_file`.
388///
389/// This returns a `Tuple` containing the actual cleaned `path` to the file,
390/// a set of `BuildDiagnostics`, a `TypeLoader` with all compilation passes
391/// applied and another `TypeLoader` with a minimal set of passes applied to it.
392pub async fn load_root_file_with_raw_type_loader(
393    path: &Path,
394    source_path: &Path,
395    source_code: String,
396    mut diagnostics: diagnostics::BuildDiagnostics,
397    #[allow(unused_mut)] mut compiler_config: CompilerConfiguration,
398) -> (
399    std::path::PathBuf,
400    diagnostics::BuildDiagnostics,
401    typeloader::TypeLoader,
402    Option<typeloader::TypeLoader>,
403) {
404    let mut loader = prepare_for_compile(&mut diagnostics, compiler_config);
405
406    let (path, raw_type_loader) =
407        loader.load_root_file(path, source_path, source_code, true, &mut diagnostics).await;
408
409    (path, diagnostics, loader, raw_type_loader)
410}