1#![cfg_attr(
54 feature = "document-features",
55 doc = concat!("## Feature flags\n\n", document_features::document_features!())
56)]
57#![doc(html_logo_url = "https://slint.dev/logo/slint-logo-square-light.svg")]
58#![warn(missing_docs)]
59
60#[cfg(not(feature = "compat-1-18"))]
61compile_error!(
62 "The feature `compat-1-18` must be enabled to ensure \
63 forward compatibility with future version of this crate"
64);
65
66use std::collections::HashMap;
67use std::env;
68use std::io::{BufWriter, Write};
69use std::path::{Path, PathBuf};
70
71use i_slint_compiler::diagnostics::BuildDiagnostics;
72#[cfg(test)]
73use i_slint_compiler::project_file::FILE_NAME as PROJECT_FILE_NAME;
74use i_slint_compiler::project_file::{self, ProjectFile};
75use i_slint_compiler::source_path::SourcePath;
76
77pub use i_slint_compiler::DefaultTranslationContext;
80
81#[derive(Clone, Default)]
83pub struct CompilerConfiguration {
84 overrides: project_file::Overrides,
85}
86
87#[derive(Clone, PartialEq)]
91pub enum EmbedResourcesKind {
92 AsAbsolutePath,
97 EmbedFiles,
100 #[cfg(feature = "renderer-software")]
101 EmbedForSoftwareRenderer,
109}
110
111impl CompilerConfiguration {
112 pub fn new() -> Self {
114 Self::default()
115 }
116
117 #[must_use]
122 pub fn with_include_paths(mut self, include_paths: Vec<std::path::PathBuf>) -> Self {
123 self.overrides.project.include_paths = Some(include_paths);
124 self
125 }
126
127 #[must_use]
157 pub fn with_library_paths(
158 mut self,
159 library_paths: HashMap<String, std::path::PathBuf>,
160 ) -> Self {
161 self.overrides.project.library_paths = Some(library_paths);
162 self
163 }
164
165 #[must_use]
168 pub fn with_style(mut self, style: String) -> Self {
169 self.overrides.style = Some(style);
170 self
171 }
172
173 #[must_use]
177 pub fn embed_resources(mut self, kind: EmbedResourcesKind) -> Self {
178 self.overrides.embed_resources = Some(match kind {
179 EmbedResourcesKind::AsAbsolutePath => {
180 i_slint_compiler::EmbedResourcesKind::OnlyBuiltinResources
181 }
182 EmbedResourcesKind::EmbedFiles => {
183 i_slint_compiler::EmbedResourcesKind::EmbedAllResources
184 }
185 #[cfg(feature = "renderer-software")]
186 EmbedResourcesKind::EmbedForSoftwareRenderer => {
187 i_slint_compiler::EmbedResourcesKind::EmbedTextures
188 }
189 });
190 self
191 }
192
193 #[must_use]
200 pub fn with_scale_factor(mut self, factor: f32) -> Self {
201 self.overrides.const_scale_factor = Some(factor);
202 self
203 }
204
205 #[must_use]
214 pub fn with_bundled_translations(
215 mut self,
216 path: impl Into<std::path::PathBuf>,
217 ) -> CompilerConfiguration {
218 self.overrides.bundled_translations_path = Some(path.into());
219 self
220 }
221
222 #[must_use]
228 pub fn with_default_translation_context(
229 mut self,
230 default_translation_context: DefaultTranslationContext,
231 ) -> Self {
232 self.overrides.default_translation_context = Some(default_translation_context);
233 self
234 }
235
236 #[doc(hidden)]
241 #[must_use]
242 pub fn with_debug_info(mut self, enable: bool) -> Self {
243 self.overrides.debug_info = Some(enable);
244 self
245 }
246
247 #[cfg(feature = "experimental-module-builds")]
254 #[must_use]
255 pub fn as_library(mut self, library_name: &str) -> Self {
256 self.overrides.library_name = Some(library_name.to_string());
257 self
258 }
259
260 #[cfg(feature = "experimental-module-builds")]
269 #[must_use]
270 pub fn rust_module(mut self, rust_module: &str) -> Self {
271 self.overrides.rust_module = Some(rust_module.to_string());
272 self
273 }
274 #[cfg(feature = "sdf-fonts")]
285 #[must_use]
286 pub fn with_sdf_fonts(mut self, enable: bool) -> Self {
287 self.overrides.use_sdf_fonts = Some(enable);
288 self
289 }
290
291 #[must_use]
293 fn with_absolute_paths(mut self, manifest_dir: &std::path::Path) -> Self {
294 let to_absolute_path = |path: &mut std::path::PathBuf| {
295 *path = project_file::resolve_relative_path(manifest_dir, std::mem::take(path));
296 };
297
298 for path in
299 self.overrides.project.library_paths.iter_mut().flat_map(|paths| paths.values_mut())
300 {
301 to_absolute_path(path);
302 }
303
304 for path in self.overrides.project.include_paths.iter_mut().flatten() {
305 to_absolute_path(path);
306 }
307
308 self
309 }
310
311 fn resolve(
313 self,
314 project_file: Option<&ProjectFile>,
315 ) -> i_slint_compiler::CompilerConfiguration {
316 let mut config = i_slint_compiler::CompilerConfiguration::new(
317 i_slint_compiler::generator::OutputFormat::Rust,
318 );
319 self.overrides.apply(project_file, &mut config);
320 config
321 }
322
323 fn resolve_for_cargo(
324 self,
325 project_file: Option<&ProjectFile>,
326 manifest_dir: &Path,
327 ) -> i_slint_compiler::CompilerConfiguration {
328 let mut config = self.with_absolute_paths(manifest_dir).resolve(project_file);
329 if let Some(path) = config.bundled_translations_path.as_mut()
330 && path.is_relative()
331 {
332 *path = manifest_dir.join(&path);
333 }
334 config
335 }
336
337 #[cfg(test)]
338 fn resolve_project_file(
339 self,
340 project_directory: &Path,
341 ) -> Result<(i_slint_compiler::CompilerConfiguration, Option<ProjectFile>), String> {
342 let (_, project_file) = project_file::resolve_input(project_directory)?;
343 Ok((self.resolve(project_file.as_ref()), project_file))
344 }
345}
346
347#[derive(derive_more::Error, derive_more::Display, Debug)]
349#[non_exhaustive]
350pub enum CompileError {
351 #[display(
353 "Cannot read environment variable CARGO_MANIFEST_DIR or OUT_DIR. The build script need to be run via cargo."
354 )]
355 NotRunViaCargo,
356 #[display("{_0:?}")]
358 CompileError(#[error(not(source))] Vec<String>),
359 #[display("Cannot write the generated file: {_0}")]
361 SaveError(std::io::Error),
362}
363
364#[cfg(test)]
365fn project_file_path_in(manifest_dir: impl AsRef<Path>) -> PathBuf {
366 manifest_dir.as_ref().join(PROJECT_FILE_NAME)
367}
368
369pub fn compile(path: impl AsRef<std::path::Path>) -> Result<(), CompileError> {
398 compile_with_config(path, CompilerConfiguration::default())
399}
400
401pub fn compile_with_config(
413 path: impl AsRef<std::path::Path>,
414 config: CompilerConfiguration,
415) -> Result<(), CompileError> {
416 let manifest_path = std::path::PathBuf::from(
417 env::var_os("CARGO_MANIFEST_DIR").ok_or(CompileError::NotRunViaCargo)?,
418 );
419 let (input, input_files) = load_input(project_file::resolve_relative_path(
420 &manifest_path,
421 path.as_ref().to_path_buf(),
422 ))?;
423
424 let absolute_rust_output_file_path =
425 Path::new(&env::var_os("OUT_DIR").ok_or(CompileError::NotRunViaCargo)?).join(
426 input
427 .source
428 .as_native_path()
429 .and_then(Path::file_stem)
430 .map(Path::new)
431 .unwrap_or_else(|| Path::new("slint_out"))
432 .with_extension("rs"),
433 );
434
435 let config = config.resolve_for_cargo(input.project_file.as_ref(), &manifest_path);
436
437 #[cfg(feature = "experimental-module-builds")]
438 if let Some(library_name) = config.library_name.clone() {
439 let rust_module = config
440 .rust_module
441 .as_deref()
442 .map(i_slint_compiler::generator::rust::parse_rust_module)
443 .transpose()
444 .map_err(|error| CompileError::CompileError(vec![error.to_string()]))?;
445 println!("cargo::metadata=SLINT_LIBRARY_NAME={}", library_name);
446 println!(
447 "cargo::metadata=SLINT_LIBRARY_PACKAGE={}",
448 std::env::var("CARGO_PKG_NAME").ok().unwrap_or_default()
449 );
450 println!("cargo::metadata=SLINT_LIBRARY_SOURCE={}", input.source);
451 if let Some(rust_module) = rust_module {
452 println!("cargo::metadata=SLINT_LIBRARY_MODULE={}", rust_module);
453 }
454 }
455 if let Some(bundle_path) = &config.bundled_translations_path {
457 println!("cargo:rerun-if-changed={}", bundle_path.display());
458 }
459
460 let paths_dependencies =
461 compile_resolved(input, input_files, &absolute_rust_output_file_path, config)?;
462
463 for path_dependency in paths_dependencies {
464 println!("cargo:rerun-if-changed={}", path_dependency.display());
465 }
466
467 println!("cargo:rerun-if-env-changed=SLINT_STYLE");
468 println!("cargo:rerun-if-env-changed=SLINT_FONT_SIZES");
469 println!("cargo:rerun-if-env-changed=SLINT_SCALE_FACTOR");
470 println!("cargo:rerun-if-env-changed=SLINT_ASSET_SECTION");
471 println!("cargo:rerun-if-env-changed=SLINT_EMBED_RESOURCES");
472 println!("cargo:rerun-if-env-changed=SLINT_EMIT_DEBUG_INFO");
473 println!("cargo:rerun-if-env-changed=SLINT_LIVE_PREVIEW");
474 println!("cargo:rerun-if-env-changed=SLINT_BUNDLE_TRANSLATIONS");
475 println!("cargo:rerun-if-env-changed=SLINT_ENABLE_EXPERIMENTAL_FEATURES");
476 println!("cargo:rerun-if-env-changed=SLINT_EDITION");
477
478 println!(
479 "cargo:rustc-env=SLINT_INCLUDE_GENERATED={}",
480 absolute_rust_output_file_path.display()
481 );
482
483 Ok(())
484}
485
486pub fn compile_with_output_path(
500 input_slint_file_path: impl AsRef<std::path::Path>,
501 output_rust_file_path: impl AsRef<std::path::Path>,
502 config: CompilerConfiguration,
503) -> Result<Vec<std::path::PathBuf>, CompileError> {
504 let (input, input_files) = load_input(input_slint_file_path.as_ref().to_path_buf())?;
505 let config = config.resolve(input.project_file.as_ref());
506 compile_resolved(input, input_files, output_rust_file_path.as_ref(), config)
507}
508
509fn load_input(path: PathBuf) -> Result<(project_file::Input, Vec<PathBuf>), CompileError> {
512 let mut diag = BuildDiagnostics::default();
513 let (input, input_files) = spin_on::spin_on(project_file::load_input(
514 &SourcePath::File(path),
515 None,
516 None,
517 None,
518 &mut diag,
519 ));
520 let input = input.ok_or_else(|| {
521 let vec = diag.iter().map(|d| d.message().to_string()).collect();
523 diag.print();
524 CompileError::CompileError(vec)
525 })?;
526 Ok((input, input_files.into_iter().filter_map(SourcePath::into_native_path).collect()))
527}
528
529fn compile_resolved(
532 input: project_file::Input,
533 input_files: Vec<PathBuf>,
534 output_rust_file_path: &Path,
535 mut compiler_config: i_slint_compiler::CompilerConfiguration,
536) -> Result<Vec<std::path::PathBuf>, CompileError> {
537 let mut diag = BuildDiagnostics::default();
538 let syntax_node =
539 i_slint_compiler::parser::parse(input.source_code, Some(input.source), &mut diag);
540
541 if diag.has_errors() {
542 let vec = diag.to_string_vec();
543 diag.print();
544 return Err(CompileError::CompileError(vec));
545 }
546
547 compiler_config.translation_domain = std::env::var("CARGO_PKG_NAME").ok();
548
549 let (doc, mut diag, loader) =
551 spin_on::spin_on(i_slint_compiler::compile_syntax_node(syntax_node, diag, compiler_config));
552 diag.remove_infos();
553
554 if diag.has_errors()
555 || (!diag.is_empty() && std::env::var("SLINT_COMPILER_DENY_WARNINGS").is_ok())
556 {
557 let vec = diag.to_string_vec();
558 diag.print();
559 return Err(CompileError::CompileError(vec));
560 }
561
562 let generated = i_slint_compiler::generator::rust::generate(&doc, &loader.compiler_config)
563 .map_err(|e| CompileError::CompileError(vec![e.to_string()]))?;
564 let mut output_file = BufWriter::new(
565 std::fs::File::create(output_rust_file_path).map_err(CompileError::SaveError)?,
566 );
567
568 let mut dependencies = input_files;
569
570 for x in diag.all_loaded_files.iter().filter_map(|p| p.as_native_path()) {
571 if x.is_absolute() {
572 dependencies.push(x.to_path_buf());
573 }
574 }
575
576 diag.diagnostics_as_string().lines().for_each(|w| {
578 if !w.is_empty() {
579 println!("cargo:warning={}", w.strip_prefix("warning: ").unwrap_or(w))
580 }
581 });
582
583 i_slint_compiler::generator::rust_code_formatter::write_formatted(&generated, &mut output_file)
584 .map_err(CompileError::SaveError)?;
585
586 for er in doc.embedded_file_resources.borrow().iter() {
587 if let Some(resource) = er.path.as_ref().and_then(|p| p.as_native_path()) {
588 dependencies.push(resource.to_path_buf());
589 }
590 }
591
592 output_file.flush().map_err(CompileError::SaveError)?;
593
594 Ok(dependencies)
595}
596
597pub fn print_rustc_flags() -> std::io::Result<()> {
600 if let Some(board_config_path) =
601 std::env::var_os("DEP_MCU_BOARD_SUPPORT_BOARD_CONFIG_PATH").map(std::path::PathBuf::from)
602 {
603 let config = std::fs::read_to_string(board_config_path.as_path())?;
604 let toml = config.parse::<toml_edit::DocumentMut>().expect("invalid board config toml");
605
606 for link_arg in
607 toml.get("link_args").and_then(toml_edit::Item::as_array).into_iter().flatten()
608 {
609 if let Some(option) = link_arg.as_str() {
610 println!("cargo:rustc-link-arg={option}");
611 }
612 }
613
614 for link_search_path in
615 toml.get("link_search_path").and_then(toml_edit::Item::as_array).into_iter().flatten()
616 {
617 if let Some(mut path) = link_search_path.as_str().map(std::path::PathBuf::from) {
618 if path.is_relative() {
619 path = board_config_path.parent().unwrap().join(path);
620 }
621 println!("cargo:rustc-link-search={}", path.to_string_lossy());
622 }
623 }
624 println!("cargo:rerun-if-env-changed=DEP_MCU_BOARD_SUPPORT_MCU_BOARD_CONFIG_PATH");
625 println!("cargo:rerun-if-changed={}", board_config_path.display());
626 }
627
628 Ok(())
629}
630
631#[cfg(test)]
632fn root_path_prefix() -> std::path::PathBuf {
633 #[cfg(windows)]
634 return std::path::PathBuf::from("C:/");
635 #[cfg(not(windows))]
636 return std::path::PathBuf::from("/");
637}
638
639#[cfg(test)]
640fn with_temp_test_dir<R>(test_name: &str, f: impl FnOnce(&Path) -> R) -> R {
641 let stamp =
642 std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
643 let test_dir =
644 std::env::temp_dir().join("slint-build-tests").join(format!("{test_name}-{stamp}"));
645 std::fs::create_dir_all(&test_dir).unwrap();
646 let result = f(&test_dir);
647 std::fs::remove_dir_all(test_dir).unwrap();
648 result
649}
650
651#[cfg(test)]
652mod tests {
653 use super::*;
654
655 #[test]
656 fn with_absolute_library_paths_test() {
657 use std::path::PathBuf;
658
659 let library_paths = std::collections::HashMap::from([
660 ("relative".to_string(), PathBuf::from("some/relative/path")),
661 ("absolute".to_string(), root_path_prefix().join("some/absolute/path")),
662 ]);
663 let config = CompilerConfiguration::new().with_library_paths(library_paths);
664
665 let manifest_path = root_path_prefix().join("path/to/manifest");
666 let absolute_config = config.clone().with_absolute_paths(&manifest_path);
667 let library_paths = absolute_config.overrides.project.library_paths.unwrap();
668 let relative = &library_paths["relative"];
669 assert!(relative.is_absolute());
670 assert!(relative.starts_with(&manifest_path));
671
672 assert!(!library_paths["absolute"].starts_with(&manifest_path));
673 }
674
675 #[test]
676 fn with_absolute_include_paths_test() {
677 use std::path::PathBuf;
678
679 let config = CompilerConfiguration::new().with_include_paths(Vec::from([
680 root_path_prefix().join("some/absolute/path"),
681 PathBuf::from("some/relative/path"),
682 PathBuf::from("windows\\style"),
683 ]));
684
685 let manifest_path = root_path_prefix().join("path/to/manifest");
686 let absolute_config = config.clone().with_absolute_paths(&manifest_path);
687 assert_eq!(
688 absolute_config.overrides.project.include_paths.unwrap(),
689 Vec::from([
690 root_path_prefix().join("some/absolute/path"),
691 manifest_path.join("some/relative/path"),
692 manifest_path.join("windows").join("style"),
693 ])
694 )
695 }
696
697 #[cfg(feature = "experimental-module-builds")]
698 #[test]
699 fn invalid_rust_module_is_a_compilation_error() {
700 let directory = tempfile::tempdir().unwrap();
701 let source_path = directory.path().join("main.slint");
702 let output_path = directory.path().join("main.rs");
703 std::fs::write(&source_path, "export component Main inherits Window {}").unwrap();
704
705 let config = CompilerConfiguration::new().as_library("TestLibrary").rust_module("🍰🍔🍕");
706 let error = compile_with_output_path(&source_path, &output_path, config).unwrap_err();
707
708 let CompileError::CompileError(messages) = error else {
709 panic!("Expected a compilation error, got {error:?}");
710 };
711 assert!(
712 messages.iter().any(|message| message.contains("Invalid rust_module")),
713 "{messages:?}"
714 );
715 assert!(!output_path.exists());
716 }
717}
718
719#[test]
720fn project_file_defaults_use_project_file_directory_for_relative_paths() {
721 use std::{collections::HashMap, fs};
722
723 with_temp_test_dir("relative-paths", |test_root| {
724 let project_file = project_file_path_in(test_root);
725 fs::write(
726 &project_file,
727 r#"{
728 "slint-edition": "1.19",
729 "main": "main.slint",
730 "include-paths": ["project-include"],
731 "library-paths": {"widgets": "project-lib.slint"}
732 }"#,
733 )
734 .unwrap();
735
736 let test_root = fs::canonicalize(test_root).unwrap();
737 let (config, project_file) = CompilerConfiguration::new()
738 .with_absolute_paths(&test_root)
739 .resolve_project_file(&test_root)
740 .unwrap();
741
742 assert_eq!(config.include_paths, vec![test_root.join("project-include")]);
743 assert_eq!(
744 config.library_paths,
745 HashMap::from([("widgets".to_string(), test_root.join("project-lib.slint"))])
746 );
747 assert_eq!(
748 project_file.unwrap().source_path().as_native_path().unwrap(),
749 project_file_path_in(&test_root)
750 );
751 });
752}
753
754#[test]
755fn explicit_settings_add_to_the_project_file_paths() {
756 use std::{collections::HashMap, fs, path::PathBuf};
757
758 with_temp_test_dir("override-precedence", |test_root| {
759 let project_file = project_file_path_in(test_root);
760 fs::write(
761 &project_file,
762 r#"{
763 "slint-edition": "1.19",
764 "main": "main.slint",
765 "include-paths": ["project-include"],
766 "library-paths": {"widgets": "project-lib.slint", "icons": "icons.slint"}
767 }"#,
768 )
769 .unwrap();
770
771 let test_root = fs::canonicalize(test_root).unwrap();
772 let (config, _) = CompilerConfiguration::new()
773 .with_include_paths(vec![PathBuf::from("build-include")])
774 .with_library_paths(HashMap::from([(
775 "widgets".to_string(),
776 PathBuf::from("build-lib.slint"),
777 )]))
778 .with_style("build-style".into())
779 .with_absolute_paths(&test_root)
780 .resolve_project_file(&test_root)
781 .unwrap();
782
783 assert_eq!(
784 config.include_paths,
785 vec![test_root.join("build-include"), test_root.join("project-include")]
786 );
787 assert_eq!(
788 config.library_paths,
789 HashMap::from([
790 ("widgets".to_string(), test_root.join("build-lib.slint")),
791 ("icons".to_string(), test_root.join("icons.slint")),
792 ])
793 );
794 assert_eq!(config.style.as_deref(), Some("build-style"));
795 });
796}
797
798#[test]
799fn explicit_build_settings_preserve_empty_values_and_false() {
800 with_temp_test_dir("empty-overrides", |test_root| {
801 let project_path = project_file_path_in(test_root);
802 std::fs::write(
803 &project_path,
804 r#"{"slint-edition":"1.19","include-paths":["include"],"library-paths":{"widgets":"lib"}}"#,
805 )
806 .unwrap();
807 let project = ProjectFile::load(project_path).unwrap();
808 let config = CompilerConfiguration::new()
809 .with_include_paths(vec![])
810 .with_library_paths(HashMap::new())
811 .with_style(String::new())
812 .with_scale_factor(0.)
813 .with_bundled_translations(PathBuf::new())
814 .with_default_translation_context(DefaultTranslationContext::None)
815 .with_debug_info(false)
816 .resolve(Some(&project));
817 let project_data = project.resolved_data();
818 assert_eq!(Some(config.include_paths), project_data.include_paths);
819 assert_eq!(Some(config.library_paths), project_data.library_paths);
820 assert_eq!(config.style.as_deref(), Some(""));
821 assert_eq!(config.const_scale_factor, Some(0.));
822 assert_eq!(config.bundled_translations_path, Some(PathBuf::new()));
823 assert_eq!(config.default_translation_context, DefaultTranslationContext::None);
824 assert!(!config.debug_info);
825 });
826}
827
828#[test]
829fn build_settings_adapt_all_resource_kinds() {
830 use i_slint_compiler::EmbedResourcesKind as InternalKind;
831 for (public_kind, internal_kind) in [
832 (EmbedResourcesKind::AsAbsolutePath, InternalKind::OnlyBuiltinResources),
833 (EmbedResourcesKind::EmbedFiles, InternalKind::EmbedAllResources),
834 #[cfg(feature = "renderer-software")]
835 (EmbedResourcesKind::EmbedForSoftwareRenderer, InternalKind::EmbedTextures),
836 ] {
837 assert_eq!(
838 CompilerConfiguration::new().embed_resources(public_kind).resolve(None).embed_resources,
839 internal_kind
840 );
841 }
842}
843
844#[test]
845fn omitted_build_settings_keep_compiler_defaults() {
846 let config = CompilerConfiguration::new().resolve(None);
847 let defaults = i_slint_compiler::CompilerConfiguration::new(
848 i_slint_compiler::generator::OutputFormat::Rust,
849 );
850 assert_eq!(config.embed_resources, defaults.embed_resources);
851 assert_eq!(config.const_scale_factor, defaults.const_scale_factor);
852 assert_eq!(config.bundled_translations_path, defaults.bundled_translations_path);
853 assert_eq!(config.default_translation_context, defaults.default_translation_context);
854 assert_eq!(config.debug_info, defaults.debug_info);
855 assert_eq!(config.library_name, defaults.library_name);
856 assert_eq!(config.rust_module, defaults.rust_module);
857 #[cfg(feature = "sdf-fonts")]
858 assert_eq!(config.use_sdf_fonts, defaults.use_sdf_fonts);
859}
860
861#[test]
862fn cargo_translation_paths_include_environment_defaults() {
863 let manifest_dir = root_path_prefix().join("cargo-manifest");
864 let defaults = i_slint_compiler::CompilerConfiguration::new(
865 i_slint_compiler::generator::OutputFormat::Rust,
866 );
867 assert_eq!(
868 CompilerConfiguration::new()
869 .resolve_for_cargo(None, &manifest_dir)
870 .bundled_translations_path,
871 defaults.bundled_translations_path.map(|path| manifest_dir.join(path))
872 );
873 for path in [PathBuf::from("translations"), root_path_prefix().join("absolute/translations")] {
874 assert_eq!(
875 CompilerConfiguration::new()
876 .with_bundled_translations(&path)
877 .resolve_for_cargo(None, &manifest_dir)
878 .bundled_translations_path,
879 Some(manifest_dir.join(path))
880 );
881 }
882}
883
884#[cfg(feature = "experimental-module-builds")]
885#[test]
886fn build_module_settings_preserve_empty_values() {
887 for name in ["", "widgets"] {
888 let config = CompilerConfiguration::new().as_library(name).rust_module(name).resolve(None);
889 assert_eq!(config.library_name.as_deref(), Some(name));
890 assert_eq!(config.rust_module.as_deref(), Some(name));
891 }
892}
893
894#[cfg(feature = "sdf-fonts")]
895#[test]
896fn build_sdf_settings_preserve_false() {
897 for enabled in [false, true] {
898 let config = CompilerConfiguration::new().with_sdf_fonts(enabled).resolve(None);
899 assert_eq!(config.use_sdf_fonts, enabled);
900 }
901}
902
903#[test]
904fn compiler_configuration_defaults_without_project_file() {
905 use std::fs;
906
907 with_temp_test_dir("optional-project-file", |test_root| {
908 let (config, project_file) = CompilerConfiguration::new()
909 .resolve_project_file(&test_root.join("main.slint"))
910 .unwrap();
911 assert!(config.style.is_none());
912 assert!(project_file.is_none());
913
914 let project_file = project_file_path_in(test_root);
915 fs::write(
916 &project_file,
917 r#"{"slint-edition": "1.19", "main":"main.slint","include-paths":["include"]}"#,
918 )
919 .unwrap();
920
921 let (config, _) = CompilerConfiguration::new().resolve_project_file(test_root).unwrap();
922 assert_eq!(config.include_paths, vec![test_root.join("include")]);
923 });
924}
925
926#[test]
927fn file_compilation_ignores_project_files() {
928 use std::fs;
929
930 with_temp_test_dir("standalone-slint-file", |test_root| {
931 let ui_directory = test_root.join("ui");
932 fs::create_dir_all(&ui_directory).unwrap();
933 fs::write(project_file_path_in(test_root), "{").unwrap();
934 fs::write(project_file_path_in(&ui_directory), "{").unwrap();
935
936 let input_file = ui_directory.join("main.slint");
937 let output_file = test_root.join("main.rs");
938 fs::write(&input_file, "export component Test inherits Rectangle {}").unwrap();
939
940 let dependencies =
941 compile_with_output_path(&input_file, &output_file, CompilerConfiguration::new())
942 .unwrap();
943 assert!(dependencies.contains(&input_file));
944 for project_file in [project_file_path_in(test_root), project_file_path_in(&ui_directory)] {
945 assert!(!dependencies.contains(&project_file), "{dependencies:#?}");
946 }
947 });
948}
949
950#[test]
951fn project_file_discovery_loads_present_paths() {
952 use std::fs;
953
954 with_temp_test_dir("discovery-present-paths", |test_root| {
955 let project_file = project_file_path_in(test_root);
956
957 fs::create_dir_all(&project_file).unwrap();
958
959 assert!(CompilerConfiguration::new().resolve_project_file(test_root).is_err());
962 });
963}
964
965#[test]
966fn missing_main_is_a_compilation_error() {
967 use std::fs;
968
969 with_temp_test_dir("project-file-error", |test_root| {
970 let project_file = project_file_path_in(test_root);
971 fs::write(&project_file, r#"{ "slint-edition": "1.19" }"#).unwrap();
972
973 let error = compile_with_output_path(
974 test_root,
975 test_root.join("main.rs"),
976 CompilerConfiguration::new(),
977 )
978 .unwrap_err();
979
980 let CompileError::CompileError(messages) = error else {
981 panic!("Expected a compilation error, got {error:?}");
982 };
983 assert_eq!(messages, vec![format!("{} has no 'main' to compile", project_file.display())]);
984 });
985}
986
987#[test]
988fn output_path_compilation_tracks_project_file_dependency() {
989 use std::fs;
990
991 with_temp_test_dir("output-deps", |test_root| {
992 let project_file = project_file_path_in(test_root);
993 let input_file = test_root.join("main.slint");
994 let output_file = test_root.join("main.rs");
995
996 fs::write(
997 &project_file,
998 r#"{"slint-edition": "1.19", "main":"main.slint","include-paths":["include"]}"#,
999 )
1000 .unwrap();
1001 fs::write(&input_file, "export component Test inherits Rectangle {}").unwrap();
1002
1003 let config = CompilerConfiguration::new();
1004 let dependencies = compile_with_output_path(test_root, &output_file, config).unwrap();
1005
1006 let project_file = i_slint_compiler::source_path::clean_path(&project_file);
1007 assert!(
1008 dependencies.iter().any(|dependency| dependency == &project_file),
1009 "expected: {:?}\ndeps: {dependencies:#?}",
1010 project_file
1011 );
1012 });
1013}
1014
1015#[test]
1016fn output_path_compilation_does_not_track_missing_project_file() {
1017 use std::fs;
1018
1019 with_temp_test_dir("missing-project-deps", |test_root| {
1020 let project_file = project_file_path_in(test_root);
1021 let input_file = test_root.join("main.slint");
1022 let output_file = test_root.join("main.rs");
1023
1024 fs::write(&input_file, "export component Test inherits Rectangle {}").unwrap();
1025
1026 let config = CompilerConfiguration::new();
1027 let dependencies = compile_with_output_path(&input_file, &output_file, config).unwrap();
1028
1029 let project_file = i_slint_compiler::source_path::clean_path(&project_file);
1030 assert!(
1031 dependencies
1032 .iter()
1033 .all(|dependency| i_slint_compiler::source_path::clean_path(dependency)
1034 != project_file),
1035 "{dependencies:#?}"
1036 );
1037 });
1038}
1039
1040#[test]
1041fn a_project_directory_compiles_its_main_file() {
1042 use std::fs;
1043
1044 with_temp_test_dir("project-file-input", |test_root| {
1045 let test_root = fs::canonicalize(test_root).unwrap();
1046 let ui_dir = test_root.join("ui");
1047 let shared_dir = test_root.join("shared");
1048 fs::create_dir_all(&ui_dir).unwrap();
1049 fs::create_dir_all(&shared_dir).unwrap();
1050
1051 let project_file = project_file_path_in(&test_root);
1052 fs::write(
1053 &project_file,
1054 r#"{ "slint-edition": "1.19", "main": "ui/main.slint", "include-paths": ["shared"] }"#,
1055 )
1056 .unwrap();
1057 fs::write(
1058 project_file_path_in(&ui_dir),
1059 r#"{ "slint-edition": "1.19", "include-paths": ["nowhere"] }"#,
1060 )
1061 .unwrap();
1062 fs::write(shared_dir.join("shared.slint"), "export component Shared {}").unwrap();
1063 let main = ui_dir.join("main.slint");
1064 fs::write(
1065 &main,
1066 r#"import { Shared } from "shared.slint";
1067 export component Test inherits Rectangle { Shared {} }"#,
1068 )
1069 .unwrap();
1070
1071 let dependencies = compile_with_output_path(
1072 &test_root,
1073 test_root.join("main.rs"),
1074 CompilerConfiguration::new(),
1075 )
1076 .unwrap();
1077
1078 assert!(dependencies.contains(&main), "{dependencies:#?}");
1079 assert!(dependencies.contains(&project_file), "{dependencies:#?}");
1080 });
1081}
1082
1083#[test]
1084fn directory_without_project_file_is_a_compilation_error() {
1085 with_temp_test_dir("missing-project-file", |test_root| {
1086 let error = compile_with_output_path(
1087 test_root,
1088 test_root.join("main.rs"),
1089 CompilerConfiguration::new(),
1090 )
1091 .unwrap_err();
1092 assert!(error.to_string().contains("slint-project.json"), "{error}");
1093 });
1094}
1095
1096#[test]
1097fn project_file_cannot_be_compiled_directly() {
1098 with_temp_test_dir("direct-project-file", |test_root| {
1099 let project_file = project_file_path_in(test_root);
1100 std::fs::write(&project_file, r#"{"slint-edition":"1.19","main":"main.slint"}"#).unwrap();
1101 let error = compile_with_output_path(
1102 &project_file,
1103 test_root.join("main.rs"),
1104 CompilerConfiguration::new(),
1105 )
1106 .unwrap_err();
1107 let CompileError::CompileError(messages) = error else {
1108 panic!("Expected a compilation error, got {error:?}");
1109 };
1110 assert_eq!(
1111 messages,
1112 vec![format!(
1113 "A `{PROJECT_FILE_NAME}` cannot be compiled directly; pass its directory instead ({})",
1114 test_root.display()
1115 )]
1116 );
1117 });
1118}