repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/type_/tests/target_implementations.rs | compiler-core/src/type_/tests/target_implementations.rs | use ecow::EcoString;
use itertools::Itertools;
use crate::{
analyse::TargetSupport, assert_module_error, build::Target, type_::expression::Implementations,
};
use super::compile_module_with_opts;
macro_rules! assert_targets {
($src:expr, $implementations:expr $(,)?) => {
let result = $crate::type_::tests::target_implementations::implementations($src);
let expected = $implementations
.iter()
.map(|(name, expected_impl)| ((*name).into(), *expected_impl))
.collect_vec();
assert_eq!(expected, result);
};
}
pub fn implementations(src: &str) -> Vec<(EcoString, Implementations)> {
compile_module_with_opts(
"test_module",
src,
None,
vec![],
Target::Erlang,
TargetSupport::NotEnforced,
None,
)
.expect("compile src")
.type_info
.values
.into_iter()
.map(|(name, value)| (name, value.variant.implementations()))
.sorted()
.collect_vec()
}
#[test]
pub fn pure_gleam_function() {
assert_targets!(
r#"
pub fn pure_gleam_1() { 1 + 1 }
pub fn pure_gleam_2() { pure_gleam_1() * 2 }
"#,
[
(
"pure_gleam_1",
Implementations {
gleam: true,
uses_erlang_externals: false,
uses_javascript_externals: false,
can_run_on_erlang: true,
can_run_on_javascript: true,
}
),
(
"pure_gleam_2",
Implementations {
gleam: true,
uses_erlang_externals: false,
uses_javascript_externals: false,
can_run_on_erlang: true,
can_run_on_javascript: true,
}
)
],
);
}
#[test]
pub fn erlang_only_function() {
assert_targets!(
r#"
@external(erlang, "wibble", "wobble")
pub fn erlang_only_1() -> Int
pub fn erlang_only_2() { erlang_only_1() * 2 }
"#,
[
(
"erlang_only_1",
Implementations {
gleam: false,
uses_erlang_externals: true,
uses_javascript_externals: false,
can_run_on_erlang: true,
can_run_on_javascript: false,
}
),
(
"erlang_only_2",
Implementations {
gleam: false,
uses_erlang_externals: true,
uses_javascript_externals: false,
can_run_on_erlang: true,
can_run_on_javascript: false,
}
)
],
);
}
#[test]
pub fn externals_only_function() {
assert_targets!(
r#"
@external(erlang, "wibble", "wobble")
@external(javascript, "wibble", "wobble")
pub fn all_externals_1() -> Int
pub fn all_externals_2() { all_externals_1() * 2 }
"#,
[
(
"all_externals_1",
Implementations {
gleam: false,
uses_erlang_externals: true,
uses_javascript_externals: true,
can_run_on_erlang: true,
can_run_on_javascript: true,
}
),
(
"all_externals_2",
Implementations {
gleam: false,
uses_erlang_externals: true,
uses_javascript_externals: true,
can_run_on_erlang: true,
can_run_on_javascript: true,
}
)
],
);
}
#[test]
pub fn externals_with_pure_gleam_body() {
assert_targets!(
r#"
@external(javascript, "wibble", "wobble")
pub fn javascript_external_and_pure_body() -> Int { 1 + 1 }
@external(erlang, "wibble", "wobble")
pub fn erlang_external_and_pure_body() -> Int { 1 + 1 }
pub fn pure_gleam() {
javascript_external_and_pure_body() + erlang_external_and_pure_body()
}
"#,
[
(
"erlang_external_and_pure_body",
Implementations {
gleam: true,
uses_erlang_externals: true,
uses_javascript_externals: false,
can_run_on_erlang: true,
can_run_on_javascript: true,
}
),
(
"javascript_external_and_pure_body",
Implementations {
gleam: true,
uses_erlang_externals: false,
uses_javascript_externals: true,
can_run_on_erlang: true,
can_run_on_javascript: true,
}
),
(
"pure_gleam",
Implementations {
gleam: true,
uses_erlang_externals: true,
uses_javascript_externals: true,
can_run_on_erlang: true,
can_run_on_javascript: true,
}
)
],
);
}
#[test]
pub fn erlang_external_with_javascript_body() {
assert_targets!(
r#"
@external(javascript, "wibble", "wobble")
fn javascript_only() -> Int
@external(erlang, "wibble", "wobble")
pub fn erlang_external_and_javascript_body() -> Int { javascript_only() }
pub fn all_externals() -> Int { erlang_external_and_javascript_body() }
"#,
[
(
"all_externals",
Implementations {
gleam: false,
uses_erlang_externals: true,
uses_javascript_externals: true,
can_run_on_erlang: true,
can_run_on_javascript: true,
}
),
(
"erlang_external_and_javascript_body",
Implementations {
gleam: false,
uses_erlang_externals: true,
uses_javascript_externals: true,
can_run_on_erlang: true,
can_run_on_javascript: true,
}
),
(
"javascript_only",
Implementations {
gleam: false,
uses_erlang_externals: false,
uses_javascript_externals: true,
can_run_on_erlang: false,
can_run_on_javascript: true,
}
)
],
);
}
#[test]
pub fn javascript_external_with_erlang_body() {
assert_targets!(
r#"
@external(erlang, "wibble", "wobble")
pub fn erlang_only() -> Int
@external(javascript, "wibble", "wobble")
pub fn javascript_external_and_erlang_body() -> Int { erlang_only() }
pub fn all_externals() -> Int { javascript_external_and_erlang_body() }
"#,
[
(
"all_externals",
Implementations {
gleam: false,
uses_erlang_externals: true,
uses_javascript_externals: true,
can_run_on_erlang: true,
can_run_on_javascript: true,
}
),
(
"erlang_only",
Implementations {
gleam: false,
uses_erlang_externals: true,
uses_javascript_externals: false,
can_run_on_erlang: true,
can_run_on_javascript: false,
}
),
(
"javascript_external_and_erlang_body",
Implementations {
gleam: false,
uses_erlang_externals: true,
uses_javascript_externals: true,
can_run_on_erlang: true,
can_run_on_javascript: true,
}
)
],
);
}
#[test]
pub fn function_with_no_valid_implementations() {
assert_module_error!(
r#"
@external(javascript, "wibble", "wobble")
fn javascript_only() -> Int
@external(erlang, "wibble", "wobble")
fn erlang_only() -> Int
pub fn main() {
javascript_only()
erlang_only()
}
"#
);
}
#[test]
pub fn invalid_both_and_one_called_from_erlang() {
let src = r#"
@external(erlang, "wibble", "wobble")
@external(javascript, "wibble", "wobble")
fn both_external() -> Int
@external(javascript, "wibble", "wobble")
fn javascript_only() -> Int
pub fn no_valid_erlang_impl() {
both_external()
javascript_only()
}
"#;
let out = compile_module_with_opts(
"test_module",
src,
None,
vec![],
Target::Erlang,
TargetSupport::Enforced,
None,
);
assert!(out.into_result().is_err());
}
#[test]
pub fn invalid_both_and_one_called_from_javascript() {
let src = r#"
@external(erlang, "wibble", "wobble")
@external(javascript, "wibble", "wobble")
fn both_external() -> Int
@external(erlang, "wibble", "wobble")
fn erlang_only() -> Int
pub fn no_valid_javascript_impl() {
both_external()
erlang_only()
}
"#;
let out = compile_module_with_opts(
"test_module",
src,
None,
vec![],
Target::JavaScript,
TargetSupport::Enforced,
None,
);
assert!(out.into_result().is_err());
}
#[test]
pub fn invalid_both_and_one_called_from_erlang_flipped() {
let src = r#"
@external(erlang, "wibble", "wobble")
@external(javascript, "wibble", "wobble")
fn both_external() -> Int
@external(javascript, "wibble", "wobble")
fn javascript_only() -> Int
pub fn no_valid_erlang_impl() {
javascript_only()
both_external()
}
"#;
let out = compile_module_with_opts(
"test_module",
src,
None,
vec![],
Target::Erlang,
TargetSupport::Enforced,
None,
);
assert!(out.into_result().is_err());
}
#[test]
pub fn invalid_both_and_one_called_from_javascript_flipped() {
let src = r#"
@external(erlang, "wibble", "wobble")
@external(javascript, "wibble", "wobble")
fn both_external() -> Int
@external(erlang, "wibble", "wobble")
fn erlang_only() -> Int
pub fn no_valid_javascript_impl() {
erlang_only()
both_external()
}
"#;
let out = compile_module_with_opts(
"test_module",
src,
None,
vec![],
Target::JavaScript,
TargetSupport::Enforced,
None,
);
assert!(out.into_result().is_err());
}
#[test]
pub fn invalid_erlang_with_external() {
let src = r#"
@external(javascript, "wibble", "wobble")
fn javascript_only() -> Int
@external(javascript, "one", "two")
pub fn no_valid_erlang_impl() {
javascript_only()
}
"#;
let out = compile_module_with_opts(
"test_module",
src,
None,
vec![],
Target::Erlang,
TargetSupport::Enforced,
None,
);
assert!(out.into_result().is_err());
}
#[test]
pub fn invalid_javascript_with_external() {
let src = r#"
@external(erlang, "wibble", "wobble")
fn erlang_only() -> Int
@external(erlang, "one", "two")
pub fn no_valid_javascript_impl() {
erlang_only()
}
"#;
let out = compile_module_with_opts(
"test_module",
src,
None,
vec![],
Target::JavaScript,
TargetSupport::Enforced,
None,
);
assert!(out.into_result().is_err());
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/type_/tests/type_alias.rs | compiler-core/src/type_/tests/type_alias.rs | use crate::{assert_module_error, assert_module_infer};
#[test]
fn alias_dep() {
assert_module_infer!(
r#"
type E = #(F, C)
type F = fn(CustomA) -> CustomB(B)
type A = Int
type B = C
type C = CustomA
type D = CustomB(C)
type CustomA {
CustomA()
}
type CustomB(a) {
CustomB(a)
}
"#,
vec![],
)
}
#[test]
fn custom_type_dep() {
assert_module_infer!(
r#"
type A {
A(Blah)
}
type Blah {
B(Int)
}
"#,
vec![],
)
}
#[test]
fn alias_cycle() {
assert_module_error!(
r#"
type A = B
type B = C
type C = D
type D = E
type E = A
"#
);
}
#[test]
fn alias_direct_cycle() {
assert_module_error!(
r#"
type A = #(A, A)
"#
);
}
#[test]
fn alias_different_module() {
assert_module_infer!(
("other", "pub type Blah = Bool"),
r#"
import other
type Blah = #(other.Blah, other.Blah)
"#,
vec![],
);
}
#[test]
fn duplicate_parameter() {
assert_module_error!(
r#"
type A(a, a) =
List(a)
"#
);
}
#[test]
fn unused_parameter() {
assert_module_error!(
r#"
type A(a) =
Int
"#
);
}
#[test]
fn type_alias_error_does_not_stop_analysis() {
// Both these aliases have errors! We do not stop on the first one.
assert_module_error!(
r#"
type UnusedParameter(a) =
Int
type UnknownType =
Dunno
"#
);
}
#[test]
fn duplicate_variable_error_does_not_stop_analysis() {
// Both these aliases have errors! We do not stop on the first one.
assert_module_error!(
r#"
type Two(a, a) =
#(a, a)
type UnknownType =
Dunno
"#
);
}
// https://github.com/gleam-lang/gleam/issues/3191
#[test]
fn both_errors_are_shown() {
// The alias has an error, and it causes the function to have an error as it
// refers to the type that does not exist.
assert_module_error!(
r#"
type X =
List(Intt)
fn example(a: X) {
todo
}
"#
);
}
#[test]
fn conflict_with_import() {
// We cannot declare a type with the same name as an imported type
assert_module_error!(
("wibble", "pub type Wobble = String"),
"import wibble.{type Wobble} type Wobble = Int",
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/type_/tests/pretty.rs | compiler-core/src/type_/tests/pretty.rs | use std::sync::Arc;
use crate::type_::{
Type,
prelude::{bool, int, tuple},
pretty::Printer,
};
use super::Publicity;
fn print(type_: Arc<Type>) -> String {
Printer::new().pretty_print(&type_, 0)
}
fn custom_bool() -> Arc<Type> {
Arc::new(Type::Named {
publicity: Publicity::Public,
package: "wibble".into(),
module: "one/two".into(),
name: "Bool".into(),
arguments: vec![],
inferred_variant: None,
})
}
#[test]
fn repeated_prelude_type() {
insta::assert_snapshot!(print(tuple(vec![int(), int(), int()])));
}
#[test]
fn prelude_type_clash_prelude_first() {
insta::assert_snapshot!(print(tuple(vec![bool(), custom_bool()])));
}
#[test]
fn prelude_type_clash_custom_first() {
insta::assert_snapshot!(print(tuple(vec![custom_bool(), bool()])));
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/type_/tests/warnings.rs | compiler-core/src/type_/tests/warnings.rs | use super::*;
use crate::{
assert_js_no_warnings, assert_js_warning, assert_no_warnings, assert_warning,
assert_warnings_with_gleam_version,
};
#[test]
fn unknown_label() {
// https://github.com/gleam-lang/gleam/issues/1098
// calling function with unused labelled argument should not emit warnings
assert_no_warnings!(
r#"fn greet(name name: String, title _title: String) { name }
pub fn main() { greet(name: "Sam", title: "Mr") }"#,
);
}
#[test]
fn todo_warning_test() {
assert_warning!("pub fn main() { 1 == todo }");
}
// https://github.com/gleam-lang/gleam/issues/1669
#[test]
fn todo_warning_correct_location() {
assert_warning!(
"pub fn main() {
todo
}"
);
}
#[test]
fn todo_with_known_type() {
assert_warning!(
"pub fn main() -> String {
todo
}"
);
}
#[test]
fn empty_func_warning_test() {
assert_warning!(
"pub fn main() { wibble() }
pub fn wibble() { }
"
);
}
#[test]
fn warning_variable_never_used_test() {
assert_warning!(
"
pub fn wibble() { Ok(5) }
pub fn main() { let five = wibble() }"
);
}
#[test]
fn warning_private_function_never_used() {
assert_warning!("fn main() { 5 }");
}
#[test]
fn warning_many_at_same_time() {
assert_warning!(
"
fn main() { let five = 5 }"
);
}
#[test]
fn result_discard_warning_test() {
// Implicitly discarded Results emit warnings
assert_warning!(
"
pub fn wibble() { Ok(5) }
pub fn main() {
wibble()
5
}"
);
}
#[test]
fn result_discard_warning_test2() {
// Explicitly discarded Results do not emit warnings
assert_no_warnings!(
"
pub fn wibble() { Ok(5) }
pub fn main() { let _ = wibble() 5 }",
);
}
#[test]
fn unused_int() {
assert_warning!("pub fn main() { 1 2 }");
}
#[test]
fn unused_float() {
assert_warning!("pub fn main() { 1.0 2 }");
}
#[test]
fn unused_string() {
assert_warning!(
"
pub fn main() {
\"1\"
2
}"
);
}
#[test]
fn unused_bit_array() {
assert_warning!(
"
pub fn main() {
<<3>>
2
}"
);
}
#[test]
fn unused_tuple() {
assert_warning!(
"
pub fn main() {
#(1.0, \"Hello world\")
2
}"
);
}
#[test]
fn unused_list() {
assert_warning!(
"
pub fn main() {
[1, 2, 3]
2
}"
);
}
#[test]
fn record_update_warnings_test() {
// Some fields are given in a record update do not emit warnings
assert_no_warnings!(
"
pub type Person {
Person(name: String, age: Int)
}
pub fn update_person() {
let past = Person(\"Quinn\", 27)
let present = Person(..past, name: \"Santi\")
present
}",
);
}
#[test]
fn record_update_warnings_test2() {
// No fields are given in a record update emit warnings
assert_warning!(
"
pub type Person {
Person(name: String, age: Int)
}
pub fn update_person() {
let past = Person(\"Quinn\", 27)
let present = Person(..past)
present
}"
);
}
#[test]
fn record_update_warnings_test3() {
// All fields given in a record update emits warnings
assert_warning!(
"
pub type Person {
Person(name: String, age: Int)
}
pub fn update_person() {
let past = Person(\"Quinn\", 27)
let present = Person(..past, name: \"Quinn\", age: 28)
present
}"
);
}
#[test]
fn unused_private_type_warnings_test() {
// External type
assert_warning!("type X");
}
#[test]
fn unused_private_type_warnings_test2() {
assert_no_warnings!("pub type Y");
}
#[test]
fn unused_private_type_warnings_test3() {
// Type alias
assert_warning!("type X = Int");
}
#[test]
fn unused_private_type_warnings_test4() {
assert_no_warnings!("pub type Y = Int");
}
#[test]
fn unused_private_type_warnings_test5() {
assert_no_warnings!("type Y = Int pub fn run(x: Y) { x }");
}
#[test]
fn unused_private_type_warnings_test6() {
// Custom type
assert_warning!("type X { X }");
}
#[test]
fn unused_private_type_warnings_test7() {
assert_no_warnings!("pub type X { X }");
}
#[test]
fn unused_private_type_warnings_test8() {
assert_no_warnings!(
"
type X { X }
pub fn a() {
let b = X
case b {
X -> 1
}
}"
);
}
#[test]
fn unused_private_fn_warnings_test() {
assert_warning!("fn a() { 1 }");
}
#[test]
fn used_private_fn_warnings_test() {
assert_no_warnings!("pub fn a() { 1 }");
}
#[test]
fn used_private_fn_warnings_test2() {
assert_no_warnings!("fn a() { 1 } pub fn b() { a }");
}
#[test]
fn unused_private_const_warnings_test() {
assert_warning!("const a = 1");
}
#[test]
fn used_private_const_warnings_test() {
assert_no_warnings!("pub const a = 1");
}
#[test]
fn used_private_const_warnings_test2() {
assert_no_warnings!("const a = 1 pub fn b() { a }");
}
#[test]
fn unused_variable_warnings_test() {
// function argument
assert_warning!("pub fn a(b) { 1 }");
}
#[test]
fn used_variable_warnings_test() {
assert_no_warnings!("pub fn a(b) { b }");
}
#[test]
fn unused_variable_warnings_test2() {
// Simple let
assert_warning!("pub fn a() { let b = 1 5 }");
}
#[test]
fn used_variable_warnings_test2() {
assert_no_warnings!("pub fn a() { let b = 1 b }");
}
#[test]
fn unused_variable_shadowing_test() {
assert_warning!("pub fn a() { let b = 1 let b = 2 b }");
}
#[test]
fn used_variable_shadowing_test() {
assert_no_warnings!("pub fn a() { let b = 1 let b = b + 1 b }");
}
#[test]
fn unused_destructure() {
// Destructure
assert_warning!("pub fn a(b) { case b { #(c, _) -> 5 } }");
}
#[test]
fn used_destructure() {
assert_no_warnings!("pub fn a(b) { case b { #(c, _) -> c } }");
}
#[test]
fn unused_imported_module_warnings_test() {
assert_warning!(
("gleam/wibble", "pub fn wobble() { 1 }"),
"import gleam/wibble"
);
}
#[test]
fn unused_imported_module_with_alias_warnings_test() {
assert_warning!(
("gleam/wibble", "pub fn wobble() { 1 }"),
"import gleam/wibble as wobble"
);
}
// https://github.com/gleam-lang/gleam/issues/2326
#[test]
fn unused_imported_module_with_alias_and_unqualified_name_warnings_test() {
assert_warning!(
("thepackage", "gleam/one", "pub fn two() { 1 }"),
"import gleam/one.{two} as three"
);
}
#[test]
fn unused_imported_module_with_alias_and_unqualified_name_no_warnings_test() {
assert_warning!(
("package", "gleam/one", "pub fn two() { 1 }"),
"import gleam/one.{two} as three\npub fn wibble() { two() }"
);
}
#[test]
fn unused_imported_module_no_warning_on_used_function_test() {
assert_no_warnings!(
("thepackage", "gleam/wibble", "pub fn wobble() { 1 }"),
"import gleam/wibble pub fn wibble() { wibble.wobble() }",
);
}
#[test]
fn unused_imported_module_no_warning_on_used_type_test() {
assert_no_warnings!(
("thepackage", "gleam/wibble", "pub type Wibble = Int"),
"import gleam/wibble pub fn wibble(a: wibble.Wibble) { a }",
);
}
#[test]
fn unused_imported_module_no_warning_on_used_unqualified_function_test() {
assert_no_warnings!(
("thepackage", "gleam/wibble", "pub fn wobble() { 1 }"),
"import gleam/wibble.{wobble} pub fn wibble() { wobble() }",
);
}
#[test]
fn unused_imported_module_no_warning_on_used_unqualified_type_test() {
assert_no_warnings!(
("thepackage", "gleam/wibble", "pub type Wibble = Int"),
"import gleam/wibble.{type Wibble} pub fn wibble(a: Wibble) { a }",
);
}
// https://github.com/gleam-lang/gleam/issues/3313
#[test]
fn imported_module_with_alias_no_warning_when_only_used_in_case_test() {
assert_no_warnings!(
(
"thepackage",
"gleam/wibble",
"pub type Wibble { Wibble(Int) }"
),
"import gleam/wibble as f\npub fn wibble(a) { case a { f.Wibble(int) -> { int } } }",
);
}
#[test]
fn module_access_registers_import_usage() {
assert_no_warnings!(
("thepackage", "gleam/bibble", "pub const bobble = 1"),
"import gleam/bibble pub fn main() { bibble.bobble }",
);
}
// https://github.com/gleam-lang/gleam/issues/978
#[test]
fn bit_pattern_var_use() {
assert_no_warnings!(
"
pub fn main(x) {
let assert <<name_size:8, name:bytes-size(name_size)>> = x
name
}",
);
}
// https://github.com/gleam-lang/gleam/issues/989
#[test]
fn alternative_case_clause_pattern_variable_usage() {
assert_no_warnings!(
"
pub fn main(s) {
case s {
[a] | [a, _] -> a
_ -> 0
}
}"
);
}
// https://github.com/gleam-lang/gleam/issues/1742
#[test]
fn imported_function_referenced_in_constant() {
assert_no_warnings!(
("thepackage", "one", "pub fn two() { 2 }"),
"
import one
pub const make_two = one.two
"
);
}
// https://github.com/gleam-lang/gleam/issues/1742
#[test]
fn imported_constructor_referenced_in_constant() {
assert_no_warnings!(
("thepackage", "one", "pub type Two { Two(Int) }"),
"
import one
pub const make_two = one.Two
"
);
}
// https://github.com/gleam-lang/gleam/issues/2050
#[test]
fn double_unary_integer_literal() {
assert_warning!("pub fn main() { let _ = --7 }");
}
#[test]
fn even_number_of_multiple_integer_negations_raise_a_single_warning() {
assert_warning!("pub fn main() { let _ = ----7 }");
}
#[test]
fn odd_number_of_multiple_integer_negations_raise_a_single_warning_that_highlights_the_unnecessary_ones()
{
assert_warning!("pub fn main() { let _ = -----7 }");
}
#[test]
fn even_number_of_multiple_bool_negations_raise_a_single_warning() {
assert_warning!("pub fn main() { let _ = !!!!True }");
}
#[test]
fn odd_number_of_multiple_bool_negations_raise_a_single_warning_that_highlights_the_unnecessary_ones()
{
assert_warning!("pub fn main() { let _ = !!!!!False }");
}
// https://github.com/gleam-lang/gleam/issues/2050
#[test]
fn double_unary_integer_variable() {
assert_warning!(
r#"
pub fn main() {
let x = 7
let _ = --x
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2050
#[test]
fn double_unary_bool_literal() {
assert_warning!("pub fn main() { let _ = !!True }");
}
// https://github.com/gleam-lang/gleam/issues/2050
#[test]
fn double_unary_bool_variable() {
assert_warning!(
r#"
pub fn main() {
let x = True
let _ = !!x
}
"#
);
}
/// https://github.com/gleam-lang/gleam/issues/2067
#[test]
fn prefer_list_is_empty_over_list_length_eq_0() {
assert_warning!(
(
"gleam_stdlib",
"gleam/list",
"pub fn length(_list: List(a)) -> Int { 0 }"
),
r#"
import gleam/list
pub fn main() {
let a_list = []
let _ = list.length(a_list) == 0
}
"#
);
}
/// https://github.com/gleam-lang/gleam/issues/2067
#[test]
fn prefer_list_is_empty_over_list_length_eq_negative_0() {
assert_warning!(
(
"gleam_stdlib",
"gleam/list",
"pub fn length(_list: List(a)) -> Int { 0 }"
),
r#"
import gleam/list
pub fn main() {
let a_list = []
let _ = list.length(a_list) == -0
}
"#
);
}
/// https://github.com/gleam-lang/gleam/issues/2067
#[test]
fn prefer_list_is_empty_over_0_eq_list_length() {
assert_warning!(
(
"gleam_stdlib",
"gleam/list",
"pub fn length(_list: List(a)) -> Int { 0 }"
),
r#"
import gleam/list
pub fn main() {
let a_list = []
let _ = 0 == list.length(a_list)
}
"#
);
}
/// https://github.com/gleam-lang/gleam/issues/2067
#[test]
fn prefer_list_is_empty_over_negative_0_eq_list_length() {
assert_warning!(
(
"gleam_stdlib",
"gleam/list",
"pub fn length(_list: List(a)) -> Int { 0 }"
),
r#"
import gleam/list
pub fn main() {
let a_list = []
let _ = -0 == list.length(a_list)
}
"#
);
}
/// https://github.com/gleam-lang/gleam/issues/2067
#[test]
fn prefer_list_is_empty_over_list_length_not_eq_0() {
assert_warning!(
(
"gleam_stdlib",
"gleam/list",
"pub fn length(_list: List(a)) -> Int { 0 }"
),
r#"
import gleam/list
pub fn main() {
let a_list = []
let _ = list.length(a_list) != 0
}
"#
);
}
/// https://github.com/gleam-lang/gleam/issues/2067
#[test]
fn prefer_list_is_empty_over_0_not_eq_list_length() {
assert_warning!(
(
"gleam_stdlib",
"gleam/list",
"pub fn length(_list: List(a)) -> Int { 0 }"
),
r#"
import gleam/list
pub fn main() {
let a_list = []
let _ = 0 != list.length(a_list)
}
"#
);
}
/// https://github.com/gleam-lang/gleam/issues/2067
#[test]
fn prefer_list_is_empty_over_list_length_lt_eq_0() {
assert_warning!(
(
"gleam_stdlib",
"gleam/list",
"pub fn length(_list: List(a)) -> Int { 0 }"
),
r#"
import gleam/list
pub fn main() {
let a_list = []
let _ = list.length(a_list) <= 0
}
"#
);
}
/// https://github.com/gleam-lang/gleam/issues/2067
#[test]
fn prefer_list_is_empty_over_list_length_lt_1() {
assert_warning!(
(
"gleam_stdlib",
"gleam/list",
"pub fn length(_list: List(a)) -> Int { 0 }"
),
r#"
import gleam/list
pub fn main() {
let a_list = []
let _ = list.length(a_list) < 1
}
"#
);
}
/// https://github.com/gleam-lang/gleam/issues/4861
#[test]
fn prefer_list_is_empty_over_list_length_gt_negative_0() {
assert_warning!(
(
"gleam_stdlib",
"gleam/list",
"pub fn length(_list: List(a)) -> Int { 0 }"
),
r#"
import gleam/list
pub fn main() {
let a_list = []
let _ = list.length(a_list) > 0
}
"#
);
}
/// https://github.com/gleam-lang/gleam/issues/4861
#[test]
fn prefer_list_is_empty_over_negative_0_lt_list_length() {
assert_warning!(
(
"gleam_stdlib",
"gleam/list",
"pub fn length(_list: List(a)) -> Int { 0 }"
),
r#"
import gleam/list
pub fn main() {
let a_list = []
let _ = 0 < list.length(a_list)
}
"#
);
}
/// https://github.com/gleam-lang/gleam/issues/4861
#[test]
fn prefer_list_is_empty_over_list_length_gt_0() {
assert_warning!(
(
"gleam_stdlib",
"gleam/list",
"pub fn length(_list: List(a)) -> Int { 0 }"
),
r#"
import gleam/list
pub fn main() {
let a_list = []
let _ = list.length(a_list) > 0
}
"#
);
}
/// https://github.com/gleam-lang/gleam/issues/4861
#[test]
fn prefer_list_is_empty_over_0_lt_list_length() {
assert_warning!(
(
"gleam_stdlib",
"gleam/list",
"pub fn length(_list: List(a)) -> Int { 0 }"
),
r#"
import gleam/list
pub fn main() {
let a_list = []
let _ = 0 < list.length(a_list)
}
"#
);
}
/// https://github.com/gleam-lang/gleam/issues/2067
#[test]
fn allow_list_length_eq_1() {
assert_no_warnings!(
(
"gleam_stdlib",
"gleam/list",
"pub fn length(_list: List(a)) -> Int { 0 }"
),
r#"
import gleam/list
pub fn main() {
let a_list = []
let _ = list.length(a_list) == 1
}
"#
);
}
/// https://github.com/gleam-lang/gleam/issues/2067
#[test]
fn allow_1_eq_list_length() {
assert_no_warnings!(
(
"gleam_stdlib",
"gleam/list",
"pub fn length(_list: List(a)) -> Int { 0 }"
),
r#"
import gleam/list
pub fn main() {
let a_list = []
let _ = 1 == list.length(a_list)
}
"#
);
}
/// https://github.com/gleam-lang/gleam/issues/2067
#[test]
fn allow_list_length_eq_3() {
assert_no_warnings!(
(
"gleam_stdlib",
"gleam/list",
"pub fn length(_list: List(a)) -> Int { 0 }"
),
r#"
import gleam/list
pub fn main() {
let a_list = []
let _ = list.length(a_list) == 3
}
"#
);
}
/// https://github.com/gleam-lang/gleam/issues/2067
#[test]
fn allow_1_lt_list_length() {
assert_no_warnings!(
(
"gleam_stdlib",
"gleam/list",
"pub fn length(_list: List(a)) -> Int { 0 }"
),
r#"
import gleam/list
pub fn main() {
let a_list = []
let _ = 1 < list.length(a_list)
}
"#
);
}
/// https://github.com/gleam-lang/gleam/issues/2067
#[test]
fn allow_list_length_gt_1() {
assert_no_warnings!(
(
"gleam_stdlib",
"gleam/list",
"pub fn length(_list: List(a)) -> Int { 0 }"
),
r#"
import gleam/list
pub fn main() {
let a_list = []
let _ = list.length(a_list) > 1
}
"#
);
}
#[test]
fn unused_external_function_arguments() {
// https://github.com/gleam-lang/gleam/issues/2259
assert_no_warnings!(
r#"
@external(erlang, "go", "go")
pub fn go(a: item_a) -> Nil
"#,
);
}
#[test]
fn importing_non_direct_dep_package() {
// Warn if an imported module is from a package that is not a direct dependency
assert_warning!(
// Magic string package name that the test setup will detect to not
// register this package as a dep.
("non-dependency-package", "some_module", "pub const x = 1"),
r#"
import some_module
pub const x = some_module.x
"#
);
}
#[test]
fn deprecated_constant() {
assert_warning!(
r#"
@deprecated("Don't use this!")
pub const a = Nil
pub fn b() {
a
}
"#
);
}
#[test]
fn deprecated_imported_constant() {
assert_warning!(
(
"package",
"module",
r#"@deprecated("Don't use this!") pub const a = Nil"#
),
r#"
import module
pub fn a() {
module.a
}
"#
);
}
#[test]
fn deprecated_imported_unqualified_constant() {
assert_warning!(
(
"package",
"module",
r#"@deprecated("Don't use this!") pub const a = Nil"#
),
r#"
import module.{a}
pub fn b() {
a
}
"#
);
}
#[test]
fn deprecated_function() {
assert_warning!(
r#"
@deprecated("Don't use this!")
pub fn a() {
Nil
}
pub fn b() {
a
}
"#
);
}
#[test]
fn deprecated_imported_function() {
assert_warning!(
(
"package",
"module",
r#"@deprecated("Don't use this!") pub fn a() { Nil }"#
),
r#"
import module
pub fn a() {
module.a
}
"#
);
}
#[test]
fn deprecated_imported_call_function() {
assert_warning!(
(
"package",
"module",
r#"@deprecated("Don't use this!") pub fn a() { Nil }"#
),
r#"
import module
pub fn a() {
module.a()
}
"#
);
}
#[test]
fn deprecated_imported_unqualified_function() {
assert_warning!(
(
"package",
"module",
r#"@deprecated("Don't use this!") pub fn a() { Nil }"#
),
r#"
import module.{a}
pub fn b() {
a
}
"#
);
}
#[test]
fn deprecated_type_used_in_alias() {
assert_warning!(
r#"
@deprecated("Don't use this!")
pub type Cat {
Cat(name: String)
}
pub type Dog = Cat
"#
);
}
#[test]
fn deprecated_type_used_as_arg() {
assert_warning!(
r#"
@deprecated("Don't use this!")
pub type Cat {
Cat(name: String)
}
pub fn cat_name(cat: Cat) {
cat.name
}
"#
);
}
#[test]
fn deprecated_type_used_as_case_clause() {
assert_warning!(
r#"
@deprecated("The type Animal has been deprecated.")
pub type Animal {
Cat
Dog
}
pub fn sound(animal) -> String {
case animal {
Dog -> "Woof"
Cat -> "Meow"
}
}
pub fn main(){
let cat = Cat
sound(cat)
}
"#
);
}
#[test]
fn const_bytes_option() {
assert_no_warnings!("pub const x = <<<<>>:bits>>");
}
#[test]
fn unused_module_wuth_alias_warning_test() {
assert_warning!(
("gleam/wibble", "pub const one = 1"),
"import gleam/wibble as wobble"
);
}
#[test]
fn unused_alias_warning_test() {
assert_warning!(
("gleam/wibble", "pub const one = 1"),
r#"
import gleam/wibble.{one} as wobble
pub const one = one
"#,
);
}
#[test]
fn used_type_with_import_alias_no_warning_test() {
assert_no_warnings!(
("gleam", "gleam/wibble", "pub const one = 1"),
"import gleam/wibble as _wobble"
);
}
#[test]
fn discarded_module_no_warnings_test() {
assert_no_warnings!(
("gleam", "wibble", "pub const one = 1"),
"import wibble as _wobble"
);
}
#[test]
fn unused_alias_for_duplicate_module_no_warning_for_alias_test() {
assert_warning!(
("a/wibble", "pub const one = 1"),
("b/wibble", "pub const two = 2"),
r#"
import a/wibble
import b/wibble as wobble
pub const one = wibble.one
"#,
);
}
#[test]
fn result_in_case_discarded() {
assert_warning!(
"
pub fn main(x) {
case x {
_ -> Error(Nil)
}
Nil
}"
);
}
#[test]
fn pattern_matching_on_literal_tuple() {
assert_warning!(
"pub fn main() {
case #(1, 2) {
_ -> Nil
}
}"
);
}
#[test]
fn pattern_matching_on_multiple_literal_tuples() {
assert_warning!(
"pub fn main() {
let wibble = 1
case #(1, 2), #(wibble, wibble) {
_, _ -> Nil
}
}"
);
}
#[test]
fn pattern_matching_on_tuples_doesnt_raise_a_warning() {
assert_no_warnings!(
"pub fn main() {
let wibble = #(1, 2)
// This doesn't raise a warning since `wibble` is not a literal tuple.
case wibble {
_ -> Nil
}
}"
);
}
#[test]
fn pattern_matching_on_literal_empty_tuple() {
assert_warning!(
"pub fn main() {
case #() {
_ -> Nil
}
}"
);
}
#[test]
fn pattern_matching_on_literal_list() {
assert_warning!(
"pub fn main() {
case [1, 2] {
_ -> Nil
}
}"
);
}
#[test]
fn pattern_matching_on_literal_list_with_tail() {
assert_warning!(
"pub fn main() {
case [1, 2, ..[]] {
_ -> Nil
}
}"
);
}
#[test]
fn pattern_matching_on_literal_empty_list() {
assert_warning!(
"pub fn main() {
case [] {
_ -> Nil
}
}"
);
}
#[test]
fn pattern_matching_on_literal_empty_bit_array() {
assert_warning!(
"pub fn main() {
case <<>> {
_ -> Nil
}
}"
);
}
#[test]
fn pattern_matching_on_literal_record() {
assert_warning!(
"
pub type Wibble { Wibble(Int) }
pub fn main() {
let n = 1
case Wibble(n) {
_ -> Nil
}
}"
);
}
#[test]
fn pattern_matching_on_literal_record_with_no_args() {
assert_warning!(
"
pub type Wibble { Wibble }
pub fn main() {
case Wibble {
_ -> Nil
}
}"
);
}
#[test]
fn pattern_matching_on_literal_int() {
assert_warning!(
"
pub type Wibble { Wibble }
pub fn main() {
case 1 {
_ -> Nil
}
}"
);
}
#[test]
fn pattern_matching_on_literal_float() {
assert_warning!(
"
pub type Wibble { Wibble }
pub fn main() {
case 1.0 {
_ -> Nil
}
}"
);
}
#[test]
fn pattern_matching_on_literal_string() {
assert_warning!(
"
pub type Wibble { Wibble }
pub fn main() {
case \"hello\" {
_ -> Nil
}
}"
);
}
#[test]
fn opaque_external_type_raises_a_warning() {
assert_warning!("pub opaque type External");
}
#[test]
fn unused_binary_operation_raises_a_warning() {
assert_warning!(
r#"
pub fn main() {
let string = "a" <> "b" "c" <> "d"
string
}
"#
);
}
#[test]
fn unused_record_access_raises_a_warning() {
assert_warning!(
r#"
pub type Thing {
Thing(value: Int)
}
pub fn main() {
let thing = Thing(1)
thing.value
1
}
"#
);
}
#[test]
fn unused_record_constructor_raises_a_warning() {
assert_warning!(
r#"
pub type Thing {
Thing(value: Int)
}
pub fn main() {
Thing(1)
1
}
"#
);
}
#[test]
fn unused_record_update_raises_a_warning() {
assert_warning!(
r#"
pub type Thing {
Thing(value: Int, other: Int)
}
pub fn main() {
let thing = Thing(1, 2)
Thing(..thing, value: 1)
1
}
"#
);
}
#[test]
fn unused_variable_raises_a_warning() {
assert_warning!(
r#"
pub fn main() {
let number = 1
number
1
}
"#
);
}
#[test]
fn unused_function_literal_raises_a_warning() {
assert_warning!(
r#"
pub fn main() {
fn(n) { n + 1 }
1
}
"#
);
}
#[test]
fn unused_tuple_index_raises_a_warning() {
assert_warning!(
r#"
pub fn main() {
#(1, 2).0
1
}
"#
);
}
#[test]
fn unused_bool_negation_raises_a_warning() {
assert_warning!(
r#"
pub fn main() {
!True
1
}
"#
);
}
#[test]
fn unused_int_negation_raises_a_warning() {
assert_warning!(
r#"
pub fn main() {
-1
1
}
"#
);
}
#[test]
fn unused_pipeline_ending_with_variant_raises_a_warning() {
assert_warning!(
r#"
pub type Wibble(a) { Wibble(a) }
pub fn wibble(a) { a }
pub fn main() {
1 |> wibble |> Wibble
1
}
"#
);
}
#[test]
fn unused_pipeline_ending_with_variant_raises_a_warning_2() {
assert_warning!(
("wibble", "pub type Wibble { Wibble(Int) }"),
r#"
import wibble
pub fn wobble(a) { a }
pub fn main() {
1 |> wobble |> wibble.Wibble
1
}
"#
);
}
#[test]
fn unused_pipeline_not_ending_with_variant_raises_no_warnings() {
assert_no_warnings!(
r#"
pub type Wibble(a) { Wibble(a) }
pub fn wibble(a) { echo a }
pub fn main() {
1 |> wibble |> wibble
1
}
"#
);
}
#[test]
fn unused_module_select_constructor() {
assert_warning!(
("wibble", "pub type Wibble { Wibble(Int) }"),
r#"
import wibble
pub fn main() {
wibble.Wibble
1
}
"#
);
}
#[test]
fn unused_module_select_constructor_call() {
assert_warning!(
("wibble", "pub type Wibble { Wibble(Int) }"),
r#"
import wibble
pub fn main() {
wibble.Wibble(1)
1
}
"#
);
}
#[test]
fn unused_module_select_function() {
assert_warning!(
("wibble", "pub fn println(a) { Nil }"),
r#"
import wibble
pub fn main() {
wibble.println
1
}
"#
);
}
#[test]
fn unused_module_select_const() {
assert_warning!(
("wibble", "pub const a = 1"),
r#"
import wibble
pub fn main() {
wibble.a
1
}
"#
);
}
#[test]
fn module_used_by_unused_function_is_not_marked_as_unused() {
assert_warning!(
("wibble", "pub const a = 1"),
"import wibble
fn wobble() {
wibble.a
}
"
);
}
#[test]
fn aliased_module_used_by_unused_function_is_not_marked_as_unused() {
assert_warning!(
("wibble", "pub const a = 1"),
"import wibble as woo
fn wobble() {
woo.a
}
"
);
}
#[test]
fn calling_function_from_other_module_is_not_marked_unused() {
assert_no_warnings!(
("wibble", "wibble", "pub fn println(a) { panic }"),
r#"
import wibble
pub fn main() {
wibble.println("hello!")
1
}
"#
);
}
/*
TODO: These tests are commented out until we figure out a better way to deal
with reexports of internal types and reintroduce the warning.
As things stand it would break both Lustre and Mist.
You can see the thread starting around here for more context:
https://discord.com/channels/768594524158427167/768594524158427170/1227250677734969386
#[test]
fn internal_type_in_public_function_return() {
assert_warning!(
"
@internal
pub type Wibble {
Wibble
}
pub fn wibble() -> Wibble { Wibble }
"
);
}
#[test]
fn type_from_internal_module_in_public_function_return() {
assert_warning!(
("thepackage/internal", "pub type Wibble { Wibble }"),
"
import thepackage/internal.{type Wibble, Wibble}
pub fn wibble() -> Wibble {
Wibble
}"
);
}
#[test]
fn internal_type_in_public_function_argument() {
assert_warning!(
"
@internal
pub type Wibble {
Wibble
}
pub fn wibble(_wibble: Wibble) -> Int { 1 }
"
);
}
#[test]
fn type_from_internal_module_in_public_function_argument() {
assert_warning!(
("thepackage/internal", "pub type Wibble { Wibble }"),
"
import thepackage/internal.{type Wibble}
pub fn wibble(_wibble: Wibble) -> Int {
1
}
"
);
}
#[test]
fn internal_type_in_public_constructor() {
assert_warning!(
"
@internal
pub type Wibble {
Wibble
}
pub type Wobble {
Wobble(Wibble)
}
"
);
}
#[test]
fn type_from_internal_module_in_public_constructor() {
assert_warning!(
("thepackage/internal", "pub type Wibble { Wibble }"),
"
import thepackage/internal.{type Wibble}
pub type Wobble {
Wobble(Wibble)
}"
);
}
#[test]
fn type_from_internal_module_dependency_in_public_constructor() {
assert_warning!(
("dep", "dep/internal", "pub type Wibble { Wibble }"),
"
import dep/internal.{type Wibble}
pub type Wobble {
Wobble(Wibble)
}"
);
}
*/
#[test]
fn redundant_let_assert() {
assert_warning!(
"
pub fn main() {
let assert wibble = [1, 2, 3]
wibble
}
"
);
}
#[test]
fn redundant_let_assert_on_custom_type() {
assert_warning!(
"
pub type Wibble {
Wibble(Int, Bool)
}
pub fn main() {
let assert Wibble(_, bool) = Wibble(1, True)
bool
}
"
);
}
#[test]
fn panic_used_as_function() {
assert_warning!(
"pub fn main() {
panic()
}"
);
}
#[test]
fn panic_used_as_function_2() {
assert_warning!(
"pub fn main() {
panic(1)
}"
);
}
#[test]
fn panic_used_as_function_3() {
assert_warning!(
"pub fn main() {
panic(1, Nil)
}"
);
}
#[test]
fn todo_used_as_function() {
assert_warning!(
"pub fn main() {
todo()
}"
);
}
#[test]
fn todo_used_as_function_2() {
assert_warning!(
"pub fn main() {
todo(1)
}"
);
}
#[test]
fn todo_used_as_function_3() {
assert_warning!(
"pub fn main() {
todo(1, Nil)
}"
);
}
#[test]
fn unreachable_warning_1() {
assert_warning!(
"pub fn main() {
panic
1
}"
);
}
#[test]
fn unreachable_warning_2() {
assert_warning!(
"pub fn main() {
let _ = panic
1
}"
);
}
#[test]
fn unreachable_warning_if_all_branches_panic() {
assert_warning!(
"pub fn main() {
let n = 1
case n {
0 -> panic
_ -> panic
}
1
}"
);
}
#[test]
fn unreachable_warning_if_all_branches_panic_2() {
assert_warning!(
"pub fn main() {
let n = 1
case n {
0 -> {
panic
2
}
_ -> panic
}
1
}"
);
}
#[test]
fn no_unreachable_warning_if_at_least_a_branch_is_reachable() {
assert_no_warnings!(
"pub fn main() {
let n = 1
case n {
0 -> panic
_ -> 1
}
1
}"
);
}
#[test]
fn unreachable_warning_doesnt_escape_out_of_a_block_if_panic_is_not_last() {
assert_warning!(
"pub fn main() {
let n = {
panic
1
}
n
}"
);
}
#[test]
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | true |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/config/stale_package_remover.rs | compiler-core/src/config/stale_package_remover.rs | use crate::manifest::Manifest;
use crate::requirement::Requirement;
use ecow::EcoString;
use hexpm::version::Version;
use std::collections::{HashMap, HashSet};
#[derive(Debug)]
pub struct StalePackageRemover<'a> {
// These are the packages for which the requirement or their parents
// requirement has not changed.
fresh: HashSet<&'a str>,
locked: HashMap<EcoString, &'a Vec<EcoString>>,
}
impl<'a> StalePackageRemover<'a> {
pub fn fresh_and_locked(
requirements: &'a HashMap<EcoString, Requirement>,
manifest: &'a Manifest,
) -> HashMap<EcoString, Version> {
let locked = manifest
.packages
.iter()
.map(|p| (p.name.clone(), &p.requirements))
.collect();
Self {
fresh: HashSet::new(),
locked,
}
.run(requirements, manifest)
}
fn run(
&mut self,
requirements: &'a HashMap<EcoString, Requirement>,
manifest: &'a Manifest,
) -> HashMap<EcoString, Version> {
// Record all the requirements that have not changed
for (name, requirement) in requirements {
if manifest.requirements.get(name) != Some(requirement) {
continue; // This package has changed, don't record it
}
// Recursively record the package and its deps as being fresh
self.record_tree_fresh(name);
}
// Return all the previously resolved packages that have not been
// recorded as fresh
manifest
.packages
.iter()
.filter(|package| {
let new = requirements.contains_key(package.name.as_str())
&& !manifest.requirements.contains_key(package.name.as_str());
let fresh = self.fresh.contains(package.name.as_str());
let locked = !new && fresh;
if !locked {
tracing::info!(name = package.name.as_str(), "unlocking_stale_package");
}
locked
})
.map(|package| (package.name.clone(), package.version.clone()))
.collect()
}
fn record_tree_fresh(&mut self, name: &'a str) {
// Record the top level package
let _ = self.fresh.insert(name);
let Some(deps) = self.locked.get(name) else {
// If the package is not in the manifest then it means that the package is an optional
// dependency that has not been included. That or someone has been editing the manifest
// and broken it, but let's hope that's not the case.
return;
};
// Record each of its deps recursively
for package in *deps {
self.record_tree_fresh(package);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::manifest::{Base16Checksum, Manifest, ManifestPackage, ManifestPackageSource};
use crate::requirement::Requirement;
use hexpm::version::{Range, Version};
use std::collections::HashMap;
// https://github.com/gleam-lang/gleam/issues/4152
#[test]
fn optional_package_not_in_manifest() {
let requirements = HashMap::from_iter([(
"required_package".into(),
Requirement::Hex {
version: Range::new("1.0.0".into()).unwrap(),
},
)]);
let manifest = Manifest {
requirements: requirements.clone(),
packages: vec![ManifestPackage {
name: "required_package".into(),
version: Version::new(1, 0, 0),
build_tools: vec!["gleam".into()],
otp_app: None,
requirements: vec![
// NOTE: this package isn't in the manifest. This will have been because it is
// an optional dep of `required_package`.
"optional_package".into(),
],
source: ManifestPackageSource::Hex {
outer_checksum: Base16Checksum(vec![]),
},
}],
};
assert_eq!(
StalePackageRemover::fresh_and_locked(&requirements, &manifest),
HashMap::from_iter([("required_package".into(), Version::new(1, 0, 0))])
);
}
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/format/tests.rs | compiler-core/src/format/tests.rs | use pretty_assertions::assert_eq;
mod asignments;
mod binary_operators;
mod bit_array;
mod blocks;
mod cases;
mod conditional_compilation;
mod constant;
mod custom_type;
mod echo;
mod external_fn;
mod external_types;
mod function;
mod guards;
mod imports;
mod lists;
mod pipeline;
mod record_update;
mod tuple;
mod use_;
#[macro_export]
macro_rules! assert_format {
($src:expr $(,)?) => {
let mut writer = String::new();
$crate::format::pretty(&mut writer, &$src.into(), camino::Utf8Path::new("<stdin>"))
.unwrap();
assert_eq!($src, writer);
};
}
#[macro_export]
macro_rules! assert_format_rewrite {
($src:expr, $expected:expr $(,)?) => {
let mut writer = String::new();
$crate::format::pretty(&mut writer, &$src.into(), camino::Utf8Path::new("<stdin>"))
.unwrap();
assert_eq!(writer, $expected);
};
}
#[test]
fn imports() {
assert_format!("\n");
assert_format!("import one\n");
assert_format!("import one\nimport two\n");
assert_format!("import one/two/three\n");
assert_format!("import four/five\nimport one/two/three\n");
assert_format!("import one.{fun, fun2, fun3}\n");
assert_format!("import one.{One, Two, fun1, fun2}\n");
assert_format!("import one.{main as entrypoint}\n");
assert_format!("import one/two/three as free\n");
assert_format!("import one/two/three.{thunk} as free\n");
assert_format!("import one/two/three.{thunk as funky} as free\n");
assert_format!(
"import my/cool/module.{
Ane, Bwo, Chree, Dour, Eive, Fix, Geven, Hight, Iine, Jen, Kleven, Lwelve,
Mhirteen, Nifteen, Oixteen,
}
"
);
assert_format!(
"import gleam/result.{
Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, Abcde,
End,
}
"
);
}
#[test]
fn multiple_statements_test() {
assert_format!(
r#"import one
import three
import two
pub type One
pub type Two
pub type Three
pub type Four
"#
);
}
#[test]
fn type_alias() {
assert_format!(
"type Option(a) =
Result(a, Nil)
"
);
assert_format!(
"pub type Option(a) =
Result(a, Nil)
"
);
assert_format!(
"pub type Pair(a, b) =
#(a, b)
"
);
assert_format!(
"pub type Sixteen(element) =
#(
element,
element,
element,
element,
element,
element,
element,
element,
element,
element,
element,
element,
element,
element,
element,
element,
)
"
);
assert_format!(
"pub type Sixteen(element) =
fn(
element,
element,
element,
element,
element,
element,
element,
element,
element,
element,
element,
element,
element,
element,
element,
element,
) ->
#(
element,
element,
element,
element,
element,
element,
element,
element,
element,
element,
element,
element,
element,
element,
element,
element,
)
"
);
// assert_format!(
// "pub type Curried(element) =
// fn() ->
// elementttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt
//"
// );
// assert_format!(
// "pub type Sixteen(element) =
// fn(element) ->
// #(
// element,
// element,
// element,
// element,
// element,
// element,
// element,
// element,
// element,
// element,
// element,
// element,
// element,
// element,
// element,
// element,
// )
//"
// );
assert_format!(
"pub type Curried(element) =
fn(element) -> fn(element) -> element
"
);
// assert_format!(
// "pub type Curried(element) =
// fn(element)
// -> fn(element)
// -> fn(element)
// -> fn(element)
// -> fn(element)
// -> element
//"
// );
assert_format!(
"type WowThisTypeHasJustTheLongestName =
WowThisTypeHasAnEvenLongerNameHowIsThatPossible
"
);
assert_format!(
"type WowThisTypeHasJustTheLongestName =
Container(
Int,
String,
List(a),
SomethingElse,
WowThisTypeHasJustTheLongestName,
)
"
);
assert_format!(
"type WowThisTypeHasJustTheLongestName(
some_long_type_variable,
and_another,
and_another_again,
) =
Container(
Int,
String,
List(a),
SomethingElse,
WowThisTypeHasJustTheLongestName,
)
"
);
assert_format!(
"///
type Many(a) =
List(a)
"
);
}
#[test]
fn expr_fn() {
assert_format!(
r#"fn main() {
fn(x) { x }
}
"#
);
assert_format!(
r#"fn main() {
fn(_) { x }
}
"#
);
assert_format!(
r#"fn main() {
fn(_discarded) { x }
}
"#
);
assert_format!(
r#"fn main() {
fn() {
1
2
}
}
"#
);
assert_format!(
r#"fn main() {
fn() {
let y = x
y
}
}
"#
);
assert_format!(
r#"fn main() {
fn() {
let x: Int = 1
x
}
}
"#
);
assert_format!(
r#"fn main() {
fn() {
let x: Box(_) = call()
x
}
}
"#
);
assert_format!(
r#"fn main() {
fn() {
let x: Box(_whatever) = call()
x
}
}
"#
);
assert_format!(
r#"fn main() {
fn(_) {
1
2
}
}
"#
);
assert_format!(
r#"fn main() {
fn(_) -> Int {
1
2
}
}
"#
);
assert_format!(
r#"fn main() {
fn(_: Int) -> Int { 2 }
}
"#
);
assert_format!(
r#"fn main() {
fn(x) {
case x {
Ok(i) -> i + 1
Error(_) -> 0
}
}
}
"#
);
}
#[test]
fn expr_call() {
assert_format!(
r#"fn main() {
run()
}
"#
);
assert_format!(
r#"fn main() {
run(1)
}
"#
);
assert_format!(
r#"fn main() {
run(with: 1)
}
"#
);
assert_format!(
r#"fn main() {
run(
with: 1,
loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong: 1,
)
}
"#
);
assert_format!(
r#"fn main() {
run(
with: something(1, 2, 3),
loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong: 1,
)
}
"#
);
assert_format!(
r#"fn main() {
run(
with: something(
loooooooooooooooooooooooooooooooooooooooong: 1,
looooooooooooooooooooooooooooooooooooooooong: 2,
),
loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong: 1,
)
}
"#
);
assert_format!(
"fn main() {
succ(1)
}
"
);
assert_format!(
"fn main() {
add(1)(2)(3)
}
"
);
assert_format!(
"fn main() {
Ok(1)
}
"
);
assert_format!(
"fn main() {
Ok(1, {
1
2
})
}
"
);
assert_format!(
r#"fn main() {
Person("Al", is_cool: VeryTrue)
}
"#
);
assert_format!(
r#"fn main() {
Person(name: "Al", is_cool: VeryTrue)
}
"#
);
}
#[test]
fn compact_single_argument_call() {
assert_format!(
r#"fn main() {
thingy(fn(x) {
1
2
})
}
"#
);
assert_format!(
r#"fn main() {
thingy([
// ok!
one(),
two(),
])
}
"#
);
assert_format!(
r#"fn main() {
thingy(<<
// ok!
one(),
two(),
>>)
}
"#
);
assert_format!(
r#"fn main() {
thingy(#(
// ok!
one(),
two(),
))
}
"#
);
assert_format!(
r#"fn main() {
thingy(
wiggle(my_function(
// ok!
one(),
two(),
)),
)
}
"#
);
assert_format!(
r#"fn main() {
thingy(case x {
1 -> 1
_ -> 0
})
}
"#
);
assert_format!(
r#"fn main() {
thingy({
1
2
3
})
}
"#
);
assert_format!(
r#"fn main() {
thingy({
let x = 1
x
})
}
"#
);
}
#[test]
fn expr_tuple() {
assert_format!(
r#"fn main(one, two, three) {
#(1, {
1
2
})
}
"#
);
assert_format!(
r#"fn main() {
#(
atom.create_from_string("module"),
atom.create_from_string("gleam@otp@actor"),
)
}
"#
);
assert_format!(
r#"fn main() {
#()
}
"#
);
assert_format!(
r#"fn main() {
#(1)
}
"#
);
assert_format!(
r#"fn main() {
#(1, 2)
}
"#
);
assert_format!(
r#"fn main() {
#(1, 2, 3)
}
"#
);
assert_format!(
r#"fn main() {
#(
really_long_variable_name,
really_long_variable_name,
really_long_variable_name,
really_long_variable_name,
really_long_variable_name,
)
}
"#
);
}
#[test]
fn statement_fn() {
assert_format!(
r#"fn main(one, two, three) {
Nil
}
"#
);
}
#[test]
fn statement_fn1() {
assert_format!(
r#"fn main(label_one one, label_two two, label_three three) {
Nil
}
"#
);
}
#[test]
fn statement_fn2() {
assert_format!(
r#"fn main(label_one one: One, label_two two: Two) {
Nil
}
"#
);
}
#[test]
fn statement_fn3() {
assert_format!(
r#"fn main(
label_one one: One,
label_two two: Two,
label_three three: Three,
label_four four: Four,
) {
Nil
}
"#
);
assert_format!(
r#"fn main(_discarded) {
Nil
}
"#
);
}
#[test]
fn statement_fn4() {
assert_format!(
r#"fn main(label _discarded) {
Nil
}
"#
);
}
#[test]
fn statement_fn5() {
// https://github.com/gleam-lang/gleam/issues/613
assert_format!(
r#"fn main() {
Nil
// Done
}
"#
);
}
#[test]
fn statement_fn6() {
//
// Module function return annotations
//
assert_format!(
r#"fn main() -> Nil {
Nil
}
"#
);
}
#[test]
fn statement_fn7() {
assert_format!(
r#"fn main() -> Loooooooooooooooooooong(
Looooooooooooooong,
Looooooooooooooooooong,
Loooooooooooooooooooooong,
Looooooooooooooooooooooooong,
) {
Nil
}
"#
);
}
#[test]
fn statement_fn8() {
assert_format!(
r#"fn main() -> Loooooooooooooooooooong(
Loooooooooooooooooooooooooooooooooooooooooong,
) {
Nil
}
"#
);
}
#[test]
fn statement_fn9() {
assert_format!(
r#"fn main() -> program.Exit {
Nil
}
"#
);
}
#[test]
fn statement_fn10() {
assert_format!(
"fn order(
first: Set(member),
second: Set(member),
) -> #(Set(member), Set(member), a) {
Nil
}
"
);
}
#[test]
fn statement_fn11() {
assert_format!(
"///
pub fn try_map(
over list: List(a),
with fun: fn(a) -> Result(b, e),
) -> Result(List(b), e) {
Nil
}
"
);
}
#[test]
fn binary_operators() {
assert_format!(
r#"fn main() {
True && False
}
"#
);
assert_format!(
r#"fn main() {
True || False
}
"#
);
assert_format!(
r#"fn main() {
1 < 1
}
"#
);
assert_format!(
r#"fn main() {
1 <= 1
}
"#
);
assert_format!(
r#"fn main() {
1.0 <. 1.0
}
"#
);
assert_format!(
r#"fn main() {
1.0 <=. 1.0
}
"#
);
assert_format!(
r#"fn main() {
1 == 1
}
"#
);
assert_format!(
r#"fn main() {
1 != 1
}
"#
);
assert_format!(
r#"fn main() {
1 >= 1
}
"#
);
assert_format!(
r#"fn main() {
1 > 1
}
"#
);
assert_format!(
r#"fn main() {
1.0 >=. 1.0
}
"#
);
assert_format!(
r#"fn main() {
1.0 >. 1.0
}
"#
);
assert_format!(
r#"fn main() {
1 + 1
}
"#
);
assert_format!(
r#"fn main() {
1.0 +. 1.0
}
"#
);
assert_format!(
r#"fn main() {
1 - 1
}
"#
);
assert_format!(
r#"fn main() {
1.0 -. 1.0
}
"#
);
assert_format!(
r#"fn main() {
1 * 1
}
"#
);
assert_format!(
r#"fn main() {
1.0 *. 1.0
}
"#
);
assert_format!(
r#"fn main() {
1 / 1
}
"#
);
assert_format!(
r#"fn main() {
1.0 /. 1.0
}
"#
);
assert_format!(
r#"fn main() {
1 % 1
}
"#
);
}
#[test]
fn expr_int() {
assert_format!(
r#"fn i() {
1
}
"#
);
assert_format!(
r#"fn i() {
121_234_345_989_000
}
"#
);
assert_format!(
r#"fn i() {
-12_928_347_925
}
"#
);
assert_format!(
r#"fn i() {
1_234_567_890
}
"#
);
assert_format!(
r#"fn i() {
123_456_789
}
"#
);
assert_format!(
r#"fn i() {
12_345_678
}
"#
);
assert_format!(
r#"fn i() {
1_234_567
}
"#
);
assert_format!(
r#"fn i() {
123_456
}
"#
);
assert_format!(
r#"fn i() {
12_345
}
"#
);
assert_format!(
r#"fn i() {
1234
}
"#
);
assert_format!(
r#"fn i() {
123
}
"#
);
assert_format!(
r#"fn i() {
12
}
"#
);
assert_format!(
r#"fn i() {
1
}
"#
);
assert_format!(
r#"fn i() {
-1_234_567_890
}
"#
);
assert_format!(
r#"fn i() {
-123_456_789
}
"#
);
assert_format!(
r#"fn i() {
-12_345_678
}
"#
);
assert_format!(
r#"fn i() {
-1_234_567
}
"#
);
assert_format!(
r#"fn i() {
-123_456
}
"#
);
assert_format!(
r#"fn i() {
-12_345
}
"#
);
assert_format!(
r#"fn i() {
-1234
}
"#
);
assert_format!(
r#"fn i() {
-123
}
"#
);
assert_format!(
r#"fn i() {
-12
}
"#
);
assert_format!(
r#"fn i() {
-1
}
"#
);
assert_format_rewrite!(
r#"fn i() {
1_234
}
"#,
r#"fn i() {
1234
}
"#
);
assert_format_rewrite!(
r#"fn i() {
12_34
}
"#,
r#"fn i() {
1234
}
"#
);
assert_format_rewrite!(
r#"fn i() {
123_4
}
"#,
r#"fn i() {
1234
}
"#
);
assert_format_rewrite!(
r#"fn i() {
1234_5
}
"#,
r#"fn i() {
12_345
}
"#
);
assert_format_rewrite!(
r#"fn i() {
12345_6
}
"#,
r#"fn i() {
123_456
}
"#
);
assert_format_rewrite!(
r#"fn i() {
123456_7
}
"#,
r#"fn i() {
1_234_567
}
"#
);
assert_format_rewrite!(
r#"fn i() {
1234567_8
}
"#,
r#"fn i() {
12_345_678
}
"#
);
assert_format_rewrite!(
r#"fn i() {
-1_234
}
"#,
r#"fn i() {
-1234
}
"#
);
assert_format_rewrite!(
r#"fn i() {
-12_34
}
"#,
r#"fn i() {
-1234
}
"#
);
assert_format_rewrite!(
r#"fn i() {
-123_4
}
"#,
r#"fn i() {
-1234
}
"#
);
assert_format_rewrite!(
r#"fn i() {
-1234_5
}
"#,
r#"fn i() {
-12_345
}
"#
);
assert_format_rewrite!(
r#"fn i() {
-12345_6
}
"#,
r#"fn i() {
-123_456
}
"#
);
assert_format_rewrite!(
r#"fn i() {
-123456_7
}
"#,
r#"fn i() {
-1_234_567
}
"#
);
assert_format_rewrite!(
r#"fn i() {
-1234567_8
}
"#,
r#"fn i() {
-12_345_678
}
"#
);
assert_format_rewrite!(
r#"fn i() {
let #(1_234, _) = #(1_234, Nil)
}
"#,
r#"fn i() {
let #(1234, _) = #(1234, Nil)
}
"#
);
assert_format_rewrite!(
r#"fn i() {
let #(12_34, _) = #(12_34, Nil)
}
"#,
r#"fn i() {
let #(1234, _) = #(1234, Nil)
}
"#
);
assert_format_rewrite!(
r#"fn i() {
let #(1234567_8, _) = #(1234567_8, Nil)
}
"#,
r#"fn i() {
let #(12_345_678, _) = #(12_345_678, Nil)
}
"#
);
assert_format_rewrite!(
r#"fn i() {
let #(-1_234, _) = #(-1_234, Nil)
}
"#,
r#"fn i() {
let #(-1234, _) = #(-1234, Nil)
}
"#
);
assert_format_rewrite!(
r#"fn i() {
let #(-12_34, _) = #(-12_34, Nil)
}
"#,
r#"fn i() {
let #(-1234, _) = #(-1234, Nil)
}
"#
);
assert_format_rewrite!(
r#"fn i() {
let #(-1234567_8, _) = #(-1234567_8, Nil)
}
"#,
r#"fn i() {
let #(-12_345_678, _) = #(-12_345_678, Nil)
}
"#
);
assert_format_rewrite!(
r#"const an_int = 1_234
"#,
r#"const an_int = 1234
"#
);
assert_format_rewrite!(
r#"const an_int = 12_34
"#,
r#"const an_int = 1234
"#
);
assert_format_rewrite!(
r#"const an_int = 1234567_8
"#,
r#"const an_int = 12_345_678
"#
);
assert_format_rewrite!(
r#"const an_int = -1_234
"#,
r#"const an_int = -1234
"#
);
assert_format_rewrite!(
r#"const an_int = -12_34
"#,
r#"const an_int = -1234
"#
);
assert_format_rewrite!(
r#"const an_int = -1234567_8
"#,
r#"const an_int = -12_345_678
"#
);
assert_format!("fn n() {\n 1_234_567\n}\n");
assert_format!("fn h() {\n 0xCAB005E\n}\n");
assert_format!("fn h() {\n 0xC_AB_00_5E\n}\n");
assert_format!("fn h() {\n 0xCA_B0_05_E\n}\n");
assert_format!("fn b() {\n 0b10100001\n}\n");
assert_format!("fn b() {\n 0b_1010_0001\n}\n");
assert_format!("fn o() {\n 0o1234567\n}\n");
assert_format!("fn o() {\n 0o1_234_567\n}\n");
assert_format!("fn o() {\n 0o_123_456_7\n}\n");
}
#[test]
fn expr_float() {
assert_format_rewrite!(
r#"fn f() {
1.
}
"#,
r#"fn f() {
1.0
}
"#
);
assert_format_rewrite!(
r#"fn f() {
1.00
}
"#,
r#"fn f() {
1.0
}
"#
);
assert_format_rewrite!(
r#"fn f() {
1.00100
}
"#,
r#"fn f() {
1.001
}
"#
);
assert_format_rewrite!(
r#"fn f() {
1.001001
}
"#,
r#"fn f() {
1.001001
}
"#
);
assert_format_rewrite!(
r#"fn f() {
1.00e100_100
}
"#,
r#"fn f() {
1.0e100_100
}
"#
);
assert_format_rewrite!(
r#"fn f() {
1.00100e100_100
}
"#,
r#"fn f() {
1.001e100_100
}
"#
);
assert_format_rewrite!(
r#"fn f() {
1.001001e100_100
}
"#,
r#"fn f() {
1.001001e100_100
}
"#
);
assert_format!(
r#"fn f() {
1.0
}
"#
);
assert_format!(
r#"fn f() {
-1.0
}
"#
);
assert_format!(
r#"fn f() {
9999.6666
}
"#
);
assert_format!(
r#"fn f() {
-1_234_567_890.0
}
"#
);
assert_format!(
r#"fn f() {
-1_234_567_890.0
}
"#
);
assert_format!(
r#"fn f() {
-123_456_789.0
}
"#
);
assert_format!(
r#"fn f() {
-12_345_678.0
}
"#
);
assert_format!(
r#"fn f() {
-1_234_567.0
}
"#
);
assert_format!(
r#"fn f() {
-123_456.0
}
"#
);
assert_format!(
r#"fn f() {
-12_345.0
}
"#
);
assert_format!(
r#"fn f() {
-1234.0
}
"#
);
assert_format!(
r#"fn f() {
-123.0
}
"#
);
assert_format!(
r#"fn f() {
-12.0
}
"#
);
assert_format!(
r#"fn f() {
-1.0
}
"#
);
assert_format!(
r#"fn f() {
-0.0
}
"#
);
assert_format!(
r#"fn f() {
-1_234_567_890.1
}
"#
);
assert_format!(
r#"fn f() {
-123_456_789.1
}
"#
);
assert_format!(
r#"fn f() {
-12_345_678.1
}
"#
);
assert_format!(
r#"fn f() {
-1_234_567.1
}
"#
);
assert_format!(
r#"fn f() {
-123_456.1
}
"#
);
assert_format!(
r#"fn f() {
-12_345.1
}
"#
);
assert_format!(
r#"fn f() {
-1234.1
}
"#
);
assert_format!(
r#"fn f() {
-123.1
}
"#
);
assert_format!(
r#"fn f() {
-12.1
}
"#
);
assert_format!(
r#"fn f() {
-1.1
}
"#
);
assert_format!(
r#"fn f() {
-0.1
}
"#
);
assert_format!(
r#"fn f() {
-1_234_567_890.123456
}
"#
);
assert_format!(
r#"fn f() {
-123_456_789.123456
}
"#
);
assert_format!(
r#"fn f() {
-12_345_678.123456
}
"#
);
assert_format!(
r#"fn f() {
-1_234_567.123456
}
"#
);
assert_format!(
r#"fn f() {
-123_456.123456
}
"#
);
assert_format!(
r#"fn f() {
-12_345.123456
}
"#
);
assert_format!(
r#"fn f() {
-1234.123456
}
"#
);
assert_format!(
r#"fn f() {
-123.123456
}
"#
);
assert_format!(
r#"fn f() {
-12.123456
}
"#
);
assert_format!(
r#"fn f() {
-1.123456
}
"#
);
assert_format!(
r#"fn f() {
-0.123456
}
"#
);
assert_format_rewrite!(
r#"fn f() {
1_234.0
}
"#,
r#"fn f() {
1234.0
}
"#
);
assert_format_rewrite!(
r#"fn f() {
12_34.0
}
"#,
r#"fn f() {
1234.0
}
"#
);
assert_format_rewrite!(
r#"fn f() {
123_4.0
}
"#,
r#"fn f() {
1234.0
}
"#
);
assert_format_rewrite!(
r#"fn f() {
1234_5.0
}
"#,
r#"fn f() {
12_345.0
}
"#
);
assert_format_rewrite!(
r#"fn f() {
12345_6.0
}
"#,
r#"fn f() {
123_456.0
}
"#
);
assert_format_rewrite!(
r#"fn f() {
123456_7.0
}
"#,
r#"fn f() {
1_234_567.0
}
"#
);
assert_format_rewrite!(
r#"fn f() {
1234567_8.0
}
"#,
r#"fn f() {
12_345_678.0
}
"#
);
assert_format_rewrite!(
r#"fn f() {
-1_234.0
}
"#,
r#"fn f() {
-1234.0
}
"#
);
assert_format_rewrite!(
r#"fn f() {
-12_34.0
}
"#,
r#"fn f() {
-1234.0
}
"#
);
assert_format_rewrite!(
r#"fn f() {
-123_4.0
}
"#,
r#"fn f() {
-1234.0
}
"#
);
assert_format_rewrite!(
r#"fn f() {
-1234_5.0
}
"#,
r#"fn f() {
-12_345.0
}
"#
);
assert_format_rewrite!(
r#"fn f() {
-12345_6.0
}
"#,
r#"fn f() {
-123_456.0
}
"#
);
assert_format_rewrite!(
r#"fn f() {
-123456_7.0
}
"#,
r#"fn f() {
-1_234_567.0
}
"#
);
assert_format_rewrite!(
r#"fn f() {
-1234567_8.0
}
"#,
r#"fn f() {
-12_345_678.0
}
"#
);
assert_format_rewrite!(
r#"fn f() {
let #(1_234.0, _) = #(1_234.0, Nil)
}
"#,
r#"fn f() {
let #(1234.0, _) = #(1234.0, Nil)
}
"#
);
assert_format_rewrite!(
r#"fn f() {
let #(12_34.0, _) = #(12_34.0, Nil)
}
"#,
r#"fn f() {
let #(1234.0, _) = #(1234.0, Nil)
}
"#
);
assert_format_rewrite!(
r#"fn f() {
let #(1234567_8.0, _) = #(1234567_8.0, Nil)
}
"#,
r#"fn f() {
let #(12_345_678.0, _) = #(12_345_678.0, Nil)
}
"#
);
assert_format_rewrite!(
r#"fn f() {
let #(-1_234.0, _) = #(-1_234.0, Nil)
}
"#,
r#"fn f() {
let #(-1234.0, _) = #(-1234.0, Nil)
}
"#
);
assert_format_rewrite!(
r#"fn f() {
let #(-12_34.0, _) = #(-12_34.0, Nil)
}
"#,
r#"fn f() {
let #(-1234.0, _) = #(-1234.0, Nil)
}
"#
);
assert_format_rewrite!(
r#"fn f() {
let #(-1234567_8.0, _) = #(-1234567_8.0, Nil)
}
"#,
r#"fn f() {
let #(-12_345_678.0, _) = #(-12_345_678.0, Nil)
}
"#
);
assert_format_rewrite!(
r#"const a_float = 1_234.0
"#,
r#"const a_float = 1234.0
"#
);
assert_format_rewrite!(
r#"const a_float = 12_34.0
"#,
r#"const a_float = 1234.0
"#
);
assert_format_rewrite!(
r#"const a_float = 1234567_8.0
"#,
r#"const a_float = 12_345_678.0
"#
);
assert_format_rewrite!(
r#"const a_float = -1_234.0
"#,
r#"const a_float = -1234.0
"#
);
assert_format_rewrite!(
r#"const a_float = -12_34.0
"#,
r#"const a_float = -1234.0
"#
);
assert_format_rewrite!(
r#"const a_float = -1234567_8.0
"#,
r#"const a_float = -12_345_678.0
"#
);
assert_format_rewrite!(
r#"const a_float = 1234.00
"#,
r#"const a_float = 1234.0
"#
);
assert_format_rewrite!(
r#"const a_float = 1234.00100
"#,
r#"const a_float = 1234.001
"#
);
assert_format_rewrite!(
r#"const a_float = 1234.001001
"#,
r#"const a_float = 1234.001001
"#
);
assert_format!(
r#"fn f() {
1.0e1
}
"#
);
assert_format!(
r#"fn f() {
1.0e-1
}
"#
);
assert_format!(
r#"fn f() {
-1.0e1
}
"#
);
assert_format!(
r#"fn f() {
-1.0e-1
}
"#
);
assert_format!(
r#"fn f() {
1.0e10
}
"#
);
assert_format!(
r#"fn f() {
1.0e-10
}
"#
);
assert_format!(
r#"fn f() {
-1.0e10
}
"#
);
assert_format!(
r#"fn f() {
-11.0e-10
}
"#
);
assert_format!(
r#"fn f() {
1.0e100
}
"#
);
assert_format!(
r#"fn f() {
1.0e-100
}
"#
);
assert_format!(
r#"fn f() {
-1.0e100
}
"#
);
assert_format!(
r#"fn f() {
-11.0e-100
}
"#
);
assert_format!(
r#"fn f() {
1.0e100
}
"#
);
assert_format!(
r#"fn f() {
1.0e100_100
}
"#
);
assert_format!(
r#"fn f() {
1.0e100_100
}
"#
);
assert_format!(
r#"fn f() {
1.001e100_100
}
"#
);
}
#[test]
fn expr_string() {
assert_format!(
r#"fn main() {
"Hello"
}
"#
);
assert_format!(
r#"fn main() {
"Hello
World"
}
"#
);
assert_format!(
r#"fn main() {
"\\n\\t"
}
"#
);
}
#[test]
fn expr_seq() {
assert_format!(
r#"fn main() {
1
2
3
}
"#
);
assert_format!(
r#"fn main() {
first(1)
1
}
"#
);
}
#[test]
fn expr_lists() {
assert_format!(
"fn main() {
[]
}
"
);
assert_format!(
"fn main() {
[1]
}
"
);
assert_format!(
"fn main() {
[
{
1
2
},
]
}
"
);
assert_format!(
"fn main() {
[1, 2, 3]
}
"
);
assert_format!(
"fn main() {
[
1,
{
2
3
},
3,
]
}
"
);
assert_format!(
"fn main() {
[
really_long_variable_name,
really_long_variable_name,
really_long_variable_name,
[1, 2, 3],
really_long_variable_name,
]
}
"
);
assert_format!(
"fn main() {
[
really_long_variable_name,
really_long_variable_name,
really_long_variable_name,
[
really_long_variable_name,
really_long_variable_name,
really_long_variable_name,
2,
3,
[1, 2, 3, 4],
],
really_long_variable_name,
]
}
"
);
assert_format!(
"fn main() {
[1, 2, 3, ..x]
}
"
);
assert_format!(
"fn main() {
[
really_long_variable_name,
really_long_variable_name,
really_long_variable_name,
..tail
]
}
"
);
assert_format!(
"fn main() {
[
really_long_variable_name,
really_long_variable_name,
really_long_variable_name,
[
really_long_variable_name,
really_long_variable_name,
really_long_variable_name,
2,
3,
[1, 2, 3, 4],
..tail
],
really_long_variable_name,
]
}
"
);
}
#[test]
fn expr_pipe() {
assert_format!(
r#"fn main() {
1
|> really_long_variable_name
|> really_long_variable_name
|> really_long_variable_name
|> really_long_variable_name
|> really_long_variable_name
|> really_long_variable_name
}
"#
);
assert_format!(
r#"fn main() {
#(
1
|> succ
|> succ,
2,
3,
)
}
"#
);
assert_format!(
r#"fn main() {
some_call(
1
|> succ
|> succ,
2,
3,
)
}
"#
);
assert_format!(
r#"fn main() {
[
1
|> succ
|> succ,
2,
3,
]
}
"#
);
assert_format!(
r#"fn main() {
let x =
1
|> succ
|> succ
x
}
"#
);
assert_format!(
r#"fn main() {
#(1, 2)
|> pair.first
|> should.equal(1)
}
"#
);
assert_format!(
r#"fn main() {
#(1, 2)
|> pair.first(1, 2, 4)
|> should.equal(1)
}
"#
);
assert_format!(
r#"fn main() {
1
// 1
|> func1
// 2
|> func2
}
"#
);
// https://github.com/gleam-lang/gleam/issues/618
assert_format!(
r#"fn main() {
{
1
2
}
|> func
}
"#
);
assert_format!(
r#"fn main() {
1
|> {
1
2
}
}
"#
);
// https://github.com/gleam-lang/gleam/issues/658
assert_format!(
r#"fn main() {
{ os.system_time(os.Millisecond) < june_12_2020 * 1_000_000 }
|> should.equal(True)
}
"#
);
assert_format!(
r#"fn main() {
{ os.system_time(os.Millisecond) < june_12_2020 * 1_000_000 }
|> transform
|> should.equal(True)
}
"#
);
}
#[test]
fn expr_let() {
assert_format!(
r#"fn main() {
let x = 1
Nil
}
"#
);
}
#[test]
fn expr_let1() {
assert_format!(
r#"fn main() {
let assert x = 1
Nil
}
"#
);
}
#[test]
fn expr_let2() {
assert_format!(
r#"fn main() {
let x = {
let y = 1
y
}
Nil
}
"#
);
}
#[test]
fn expr_let3() {
assert_format!(
r#"fn main() {
let x = {
1
2
}
Nil
}
"#
);
}
#[test]
fn expr_let4() {
assert_format!(
r#"fn main() {
let y = case x {
1 -> 1
_ -> 0
}
y
}
"#
);
}
#[test]
fn expr_let5() {
assert_format!(
r#"fn main() {
let y = case x {
1 -> 1
_ -> 0
}
y
}
"#
);
}
#[test]
fn expr_let6() {
assert_format!(
r#"fn main() {
let x = fn(x) { x }
x
}
"#
);
}
#[test]
fn expr_let7() {
assert_format!(
r#"fn main() {
let x = fn() {
1
2
}
x
}
"#
);
}
#[test]
fn expr_let8() {
assert_format!(
r#"fn main() {
let x = fn(
state: state,
acc: visitor_acc,
visitor: fn(visitor_acc, Pid(a)) -> new_visitor_acc,
) {
1
2
}
x
}
"#
);
}
#[test]
fn expr_let9() {
assert_format!(
r#"fn main() {
let x = fn(
state: state,
acc: visitor_acc,
visitor: fn(visitor_acc, Pid(a)) -> new_visitor_acc,
) {
2
}
x
}
"#
);
}
#[test]
fn expr_let10() {
assert_format!(
r#"fn main() {
let dict = map.from_list([#("a", 0), #("b", 1), #("c", 2), #("d", 3)])
1
}
"#
);
}
#[test]
fn pattern_simple() {
// Pattern::Float
assert_format!(
r#"fn main() {
let 1 = 1
Nil
}
"#
);
// Pattern::String
assert_format!(
r#"fn main() {
let 1.0 = 1
Nil
}
"#
);
// Pattern::Var
assert_format!(
r#"fn main() {
let x = 1
let y = 1
Nil
}
"#
);
}
#[test]
fn breakable_pattern() {
assert_format!(
r#"fn main() {
let Ok(Thingybob(
one: _one,
two: _two,
three: _three,
four: _four,
five: _five,
six: _six,
)) = 1
Nil
}
"#
);
}
#[test]
fn pattern_let() {
assert_format!(
r#"fn main() {
let x as y = 1
Nil
}
"#
);
assert_format!(
r#"fn main() {
let #(x, y, 123 as z) = 1
Nil
}
"#
);
}
#[test]
fn pattern_discard() {
assert_format!(
r#"fn main() {
let _ = 1
Nil
}
"#
);
assert_format!(
r#"fn main() {
let _wibble = 1
Nil
}
"#
);
}
#[test]
fn pattern_lists() {
assert_format!(
r#"fn main() {
let [] = 1
Nil
}
"#
);
assert_format!(
r#"fn main() {
let [1] = 1
Nil
}
"#
);
assert_format!(
r#"fn main() {
let [1, 2, 3, 4] = 1
Nil
}
"#
);
assert_format!(
r#"fn main() {
let [1, 2, 3, 4, ..x] = 1
Nil
}
"#
);
assert_format!(
r#"fn main() {
let [
really_long_variable_name,
really_long_variable_name,
really_long_variable_name,
[1, 2, 3, 4, xyz],
..thingy
] = 1
Nil
}
"#
);
}
#[test]
fn pattern_constructor() {
assert_format!(
r#"fn main() {
let True = 1
Nil
}
"#
);
assert_format!(
r#"fn main() {
let False = 1
Nil
}
"#
);
assert_format!(
r#"fn main() {
let Ok(1) = 1
Nil
}
"#
);
assert_format!(
r#"fn main() {
let Person(name, age: the_age) = 1
Nil
}
"#
);
assert_format!(
r#"fn main() {
let Person(name: the_name, age: the_age) = 1
Nil
}
"#
);
assert_format!(
r#"fn main() {
let Person(age: age, name: name) = 1
Nil
}
"#
);
assert_format!(
r#"fn main() {
let Person(age: really_long_variable_name, name: really_long_variable_name) =
1
Nil
}
"#
);
}
#[test]
fn pattern_tuple() {
assert_format!(
r#"fn main() {
let #() = 1
Nil
}
"#
);
assert_format!(
r#"fn main() {
let #(x) = 1
Nil
}
"#
);
assert_format!(
r#"fn main() {
let #(x, y) = 1
Nil
}
"#
);
assert_format!(
r#"fn main() {
let #(x, y, z) = 1
Nil
}
"#
);
}
#[test]
fn expr_case() {
assert_format!(
r#"fn main() {
case 1 {
1 -> {
1
2
}
1 -> 1
}
}
"#
);
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | true |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/format/tests/external_fn.rs | compiler-core/src/format/tests/external_fn.rs | use crate::assert_format;
#[test]
fn no_body_erlang() {
assert_format!(
r#"@external(erlang, "one", "one")
fn one(x: Int) -> Int
"#
);
}
#[test]
fn no_body_javascript() {
assert_format!(
r#"@external(javascript, "one", "one")
fn one(x: Int) -> Int
"#
);
}
#[test]
fn no_body_body() {
assert_format!(
r#"@external(erlang, "two", "two")
@external(javascript, "one", "one")
fn one(x: Int) -> Int
"#
);
}
#[test]
fn erlang() {
assert_format!(
r#"@external(erlang, "one", "one")
fn one(x: Int) -> Int {
todo
}
"#
);
}
#[test]
fn javascript() {
assert_format!(
r#"@external(javascript, "one", "one")
fn one(x: Int) -> Int {
todo
}
"#
);
}
#[test]
fn body() {
assert_format!(
r#"@external(erlang, "two", "two")
@external(javascript, "one", "one")
fn one(x: Int) -> Int {
todo
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2259
#[test]
fn break_external_fn_arguments() {
assert_format!(
r#"@external(erlang, "ffi", "improper_list_append")
fn improper_list_append(
a: item_a,
b: item_b,
c: improper_tail,
) -> List(anything)
"#
);
}
// Bug found by Hayleigh
#[test]
fn long_long_external() {
assert_format!(
r#"@external(javascript, "./client-component.ffi.mjs", "register")
pub fn register(
_app: App(WebComponent, Nil, model, msg),
_name: String,
) -> Result(Nil, Error) {
Error(NotABrowser)
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/format/tests/use_.rs | compiler-core/src/format/tests/use_.rs | use crate::{assert_format, assert_format_rewrite};
#[test]
fn use_1() {
assert_format!(
r#"pub fn main() {
use <- benchmark("thingy")
todo
}
"#
);
}
#[test]
fn use_2() {
assert_format!(
r#"pub fn main() {
use user <- login()
todo
}
"#
);
}
#[test]
fn use_3() {
assert_format!(
r#"pub fn main() {
use one, two, three, four <- get_multiple_things()
todo
}
"#
);
}
#[test]
fn use_4() {
assert_format!(
r#"pub fn main() {
use
one,
two,
three,
four,
five,
six,
seven,
eight,
nine,
ten,
eleven,
twelve,
thirteen
<- get_multiple_things_with_a_longer_function
todo
}
"#
);
}
#[test]
fn use_5() {
assert_format!(
r#"pub fn main() {
use
one,
two,
three,
four,
five,
six,
seven,
eight,
nine,
ten,
eleven,
twelve,
thirteen
<- get_multiple_things_with_a_longer_function(a, b, c, d)
todo
}
"#
);
}
#[test]
fn use_6() {
assert_format!(
r#"pub fn main() {
use
one,
two,
three,
four,
five,
six,
seven,
eight,
nine,
ten,
eleven,
twelve,
thirteen
<- get_multiple_things_with_a_longer_function(
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
)
todo
}
"#
);
}
#[test]
fn pipe_call() {
assert_format!(
r#"pub fn main() {
use <-
a
|> b
c
}
"#
);
}
#[test]
fn use_pipe_everything() {
assert_format!(
r#"pub fn main() {
{
use <- a
todo
}
|> b
c
}
"#
);
}
#[test]
fn long_right_hand_side_0_arguments() {
assert_format!(
r#"pub fn main() {
use <- some_really_long_function_call(
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
)
todo
}
"#
);
}
#[test]
fn long_right_hand_side_1_argument() {
assert_format!(
r#"pub fn main() {
use x <- some_really_long_function_call(
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
)
todo
}
"#
);
}
#[test]
fn long_right_hand_side_2_arguments() {
assert_format!(
r#"pub fn main() {
use x, y <- some_really_long_function_call(
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
)
todo
}
"#
);
}
#[test]
fn arity_1_var_call() {
assert_format!(
r#"pub fn main() {
use x, y <- await(
file.read()
|> promise.map(something),
)
todo
}
"#
);
}
#[test]
fn arity_1_access_call() {
assert_format!(
r#"pub fn main() {
use x, y <- promise.await(
file.read()
|> promise.map(something),
)
todo
}
"#
);
}
#[test]
fn patterns() {
assert_format!(
r#"pub fn main() {
use Box(x) <- apply(Box(1))
x
}
"#
);
}
#[test]
fn patterns_with_annotation() {
assert_format!(
r#"pub fn main() {
use Box(x): Box(Int) <- apply(Box(1))
x
}
"#
);
}
#[test]
fn long_patterns() {
assert_format!(
r#"pub fn main() {
use
Box(
xxxxxxxxxxxxxxxxxxxxxxx,
yyyyyyyyyyyyyyyyyyyyyyyyyyy,
zzzzzzzzzzzzzzzzzzzzzzzzzzzz,
)
<- apply(Box(1))
x
}
"#
);
}
#[test]
fn multiple_long_patterns() {
assert_format!(
r#"pub fn main() {
use
Box(
xxxxxxxxxxxxxxxxxxxxxxx,
yyyyyyyyyyyyyyyyyyyyyyyyyyy,
zzzzzzzzzzzzzzzzzzzzzzzzzzzz,
),
Box(_),
Box(_),
Box(_)
<- apply(Box(1))
x
}
"#
);
}
#[test]
fn multiple_long_patterns_with_annotations() {
assert_format!(
r#"pub fn main() {
use
Box(
xxxxxxxxxxxxxxxxxxxxxxx,
yyyyyyyyyyyyyyyyyyyyyyyyyyy,
zzzzzzzzzzzzzzzzzzzzzzzzzzzz,
): Box(Int, Bool, String),
Box(_)
<- apply(Box(1))
x
}
"#
);
}
#[test]
fn multiple_long_annotations() {
assert_format!(
r#"pub fn main() {
use
Box(_, _): Box(
Xxzxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,
Yyyyyyyyyyyyyyyyyyyyyyyy,
),
Box(_)
<- apply(Box(1))
x
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2114
#[test]
fn comment() {
assert_format!(
r#"fn main() {
// comment
use x <- result.then(y)
todo
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/3605
#[test]
fn use_with_empty_callback_body_is_rewritten_to_have_a_todo() {
assert_format_rewrite!(
r#"fn main() {
use wibble, wobble <- woo
}
"#,
r#"fn main() {
use wibble, wobble <- woo
todo
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/format/tests/imports.rs | compiler-core/src/format/tests/imports.rs | use crate::{assert_format, assert_format_rewrite};
#[test]
fn types_and_values() {
assert_format!(
"import one/two.{type Abc, type Bcd, Abc, Bcd, abc, bcd}
"
);
}
#[test]
fn discarded_import() {
assert_format!(
"import one/two as _three
"
);
}
#[test]
fn discarded_import_with_unqualified() {
assert_format!(
"import one/two.{type Abc, Bcd, abc} as _three
"
);
}
#[test]
fn redundant_as_name_is_removed() {
assert_format_rewrite!("import wibble/wobble as wobble", "import wibble/wobble\n");
assert_format_rewrite!("import wibble as wibble", "import wibble\n");
}
#[test]
fn imports_are_sorted_alphabetically() {
assert_format_rewrite!(
"import c import a/a import a/c import b import a/ab import a",
"import a
import a/a
import a/ab
import a/c
import b
import c
"
);
}
#[test]
fn import_groups_are_respected() {
assert_format_rewrite!(
"import group_one/a
import group_one/b
// another group
import group_two/wobble
import group_two/wibble
// yet another group
import group_three/b
import group_three/c
import group_three/a
",
"import group_one/a
import group_one/b
// another group
import group_two/wibble
import group_two/wobble
// yet another group
import group_three/a
import group_three/b
import group_three/c
"
);
}
#[test]
fn empty_lines_define_different_groups() {
assert_format_rewrite!(
"import c
@target(javascript)
import b
import a
import gleam/string
import gleam/list",
"@target(javascript)
import b
import c
import a
import gleam/list
import gleam/string
"
);
}
#[test]
fn import_groups_with_empty_lines_and_comments() {
assert_format_rewrite!(
"import c
@target(javascript)
import b
import a
// third group
import gleam/string
import gleam/list
import wobble
import wibble
",
"@target(javascript)
import b
import c
import a
// third group
import gleam/list
import gleam/string
import wibble
import wobble
"
);
}
#[test]
fn type_definition_in_between_imports() {
assert_format!(
r#"import a
import b
pub type Wibble(a) {
Wobble
}
import c
import d
import e
pub type Wabble
import f
"#
);
}
#[test]
fn function_definition_in_between_imports() {
assert_format!(
r#"import a
import b
pub fn wibble() {
todo
}
import c
import d
import e
pub fn wobble() -> Int {
todo
}
import f
"#
);
}
#[test]
fn constant_definition_in_between_imports() {
assert_format!(
r#"import a
import b
pub const wibble = Wibble
import c
import d
import e
const wobble = 1
import f
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2915
#[test]
fn white_lines_between_comments_in_import_groups_are_preserved() {
assert_format!(
r#"import a
// comment
import b
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2915
#[test]
fn import_sorting_doesnt_add_spurious_white_line() {
assert_format!(
r#"// comment
import filepath
import gleam/dynamic.{type Dynamic}
import gleam/io
import gleam/list
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/format/tests/guards.rs | compiler-core/src/format/tests/guards.rs | use crate::assert_format;
#[test]
fn field_access() {
assert_format!(
r#"pub fn main() {
case x {
_ if a.b -> 1
_ -> 0
}
}
"#
);
}
#[test]
fn nested_field_access() {
assert_format!(
r#"pub fn main() {
case x {
_ if a.b.c.d -> 1
_ -> 0
}
}
"#
);
}
#[test]
fn operators_in_guard() {
assert_format!(
r#"pub fn main() {
case list.map(codepoints, string.utf_codepoint_to_int) {
[drive, colon, slash]
if { slash == 47 || slash == 92 }
&& colon == 58
&& drive >= 65
&& drive <= 90
|| drive >= 97
&& drive <= 122
-> {
1
|> 2
}
}
}
"#
);
}
#[test]
fn a_comment_before_a_guard_doesnt_force_it_to_break() {
assert_format!(
r#"pub fn main() {
case wibble {
// Apparently this comment breaks everything
_ if wobble -> Ok(state.newest)
}
}
"#
);
}
#[test]
fn long_guard_with_alternative_patterns() {
assert_format!(
r#"pub fn main() {
case wibble {
Wibble(first_one)
| Wibble(another_one)
| Wibble(
this_is_extra_long_to_go_over_the_line_limit,
this_gets_broken_as_well,
)
if True
-> Ok(wibble)
}
}
"#
);
}
#[test]
fn guard_block_is_not_removed_even_if_redundant() {
assert_format!(
r#"pub fn main() {
case todo {
_ if { True && True } && True -> 1
_ -> 2
}
}
"#
);
}
#[test]
fn nested_guard_block_is_not_removed_even_if_redundant() {
assert_format!(
r#"pub fn main() {
case todo {
_ if { True && { True && False } } && True -> 1
_ -> 2
}
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/format/tests/custom_type.rs | compiler-core/src/format/tests/custom_type.rs | use crate::assert_format;
#[test]
fn custom_type_0() {
assert_format!(
"type WowThisTypeHasJustTheLongestName(
some_long_type_variable,
and_another,
and_another_again,
) {
Make
}
"
);
}
#[test]
fn custom_type_1() {
assert_format!(
"type Result(a, e) {
Ok(a)
Error(e)
}
"
);
}
#[test]
fn custom_type_2() {
assert_format!(
"type Result(a, e) {
Ok(value: a)
Error(error: e)
}
"
);
}
#[test]
fn custom_type_3() {
assert_format!(
"type SillyResult(a, e) {
Ok(
first_value_with_really_long_name: a,
second_value_with_really_long_name: a,
)
Error(error: e)
}
"
);
}
#[test]
fn custom_type_4() {
assert_format!(
"type SillyResult(a, e) {
Ok(
first_value_with_really_long_name: a,
second_value_with_really_long_name: List(
#(Int, fn(a, a, a, a, a, a, a) -> List(a)),
),
)
Error(error: e)
}
"
);
}
#[test]
fn custom_type_5() {
assert_format!(
"type X {
X(
start: fn() -> a_reall_really_long_name_goes_here,
stop: fn() -> a_reall_really_long_name_goes_here,
)
}
"
);
}
#[test]
fn custom_type_6() {
assert_format!(
"pub opaque type X {
X
}
"
);
}
#[test]
fn custom_type_7() {
assert_format!(
"///
pub type Option(a) {
None
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/1757
#[test]
fn multiple_line_custom_type_constructor_field_doc_comments() {
assert_format!(
r#"pub type Thingy {
Thingy(
/// One?
/// One!
one: One,
/// Two?
/// Two!
two: Two,
)
}
"#
);
}
#[test]
fn deprecated_custom_type() {
assert_format!(
r#"@deprecated("Deprecated type")
pub type One {
One
}
"#
);
}
#[test]
fn doc_comments_7_test() {
assert_format!(
r#"import one
/// one
///two
type Whatever {
Whatever
}
"#
);
}
#[test]
fn comments1() {
assert_format!(
r#"import one
// one
//two
type Whatever {
Whatever
}
"#
);
}
#[test]
fn comments2() {
assert_format!(
r#"import one
// one
//two
/// three
type Whatever {
Whatever
}
"#
);
}
#[test]
fn comments6() {
assert_format!(
r#"// one
//two
type Thingy
"#
);
}
#[test]
fn comments7() {
assert_format!(
r#"// one
//two
type Thingy
"#
);
}
#[test]
fn comments8() {
assert_format!(
r#"// one
//two
type Whatever {
Whatever
}
"#
);
}
#[test]
fn comments10() {
assert_format!(
r#"// zero
import one
// one
//two
type Whatever {
Whatever
}
"#
);
}
#[test]
fn comments11() {
assert_format!(
"fn main() {
// Hello
\"world\"
}
"
);
}
#[test]
fn comment21() {
assert_format!(
"pub type Spec {
Spec(
// Hello
hello: Int,
// World
world: Int,
)
}
"
);
}
#[test]
fn commented_constructors() {
assert_format!(
"pub type Number {
// 1
One
// 2
Two
// 3
Three
// ???
More
}
"
);
}
#[test]
fn commented_constructors1() {
assert_format!(
"pub type Number {
/// 1
One
/// 2
Two
/// 3
Three
/// ???
More
}
"
);
}
#[test]
fn commented_constructors2() {
assert_format!(
"pub type Number {
// a
/// 1
One
// b
/// 2
Two
// c
/// 3
Three
// defg
/// ???
More
}
"
);
}
#[test]
fn commented_constructors3() {
assert_format!(
"pub type Number {
/// 1
One(value: Int)
/// > 1
Many(value: Int)
}
"
);
}
#[test]
fn deprecated_variant_1() {
assert_format!(
r#"pub type One {
@deprecated("Deprecated type")
One
}
"#
);
}
#[test]
fn deprecated_variant_2() {
assert_format!(
r#"pub type One {
@deprecated("Deprecated type")
One(Int, Int, Int, Int, Int, Int, Int)
}
"#
);
}
#[test]
fn deprecated_variant_3() {
assert_format!(
r#"pub type One {
@deprecated("Deprecated type with a very long message")
One(Int, Int, Int, Int, Int, Int, Int)
}
"#
);
}
#[test]
fn deprecated_variant_4() {
assert_format!(
r#"pub type One {
@deprecated("Deprecated type with a very long message
It even has multiple lines!
")
One(Int, Int, Int, Int, Int, Int, Int)
}
"#
);
}
#[test]
fn external_custom_type() {
assert_format!(
r#"@external(erlang, "erlang", "map")
@external(javascript, "../dict.d.mts", "Dict")
pub type Dict(key, value)
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/format/tests/lists.rs | compiler-core/src/format/tests/lists.rs | use crate::{assert_format, assert_format_rewrite};
#[test]
fn list_with_trailing_comma_is_broken() {
assert_format_rewrite!(
"pub fn main() { [ 1, 2, a, ] }",
r#"pub fn main() {
[
1,
2,
a,
]
}
"#
);
}
#[test]
fn constant_list_with_trailing_comma_is_broken() {
assert_format_rewrite!(
"const list = [ 1, 2, a, ]",
r#"const list = [
1,
2,
a,
]
"#
);
}
#[test]
fn list_with_trailing_comma_is_kept_broken() {
assert_format!(
r#"pub fn main() {
[
1,
2,
a,
]
}
"#
);
}
#[test]
fn constant_list_with_trailing_comma_is_kept_broken() {
assert_format!(
r#"const list = [
1,
2,
a,
]
"#
);
}
#[test]
fn list_with_no_trailing_comma_is_packed_on_a_single_line() {
assert_format_rewrite!(
r#"pub fn main() {
[
1,
2,
a
]
}
"#,
r#"pub fn main() {
[1, 2, a]
}
"#
);
}
#[test]
fn constant_list_with_no_trailing_comma_is_packed_on_a_single_line() {
assert_format_rewrite!(
r#"const list = [
1,
2,
a
]"#,
"const list = [1, 2, a]\n"
);
}
#[test]
fn list_with_no_comma_is_packed_on_a_single_line_or_split_one_item_per_line() {
assert_format_rewrite!(
"pub fn main() {
[
1,
a,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
b,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312
]
}
",
"pub fn main() {
[
1,
a,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
b,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
]
}
"
);
}
#[test]
fn constant_list_with_no_comma_is_packed_on_a_single_line_or_split_one_item_per_line() {
assert_format_rewrite!(
"const list = [
1,
a,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
b,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312
]
",
"const list = [
1,
a,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
b,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
]
"
);
}
#[test]
fn simple_list_with_no_comma_is_packed_on_a_single_line_or_split_one_item_per_line() {
assert_format_rewrite!(
r#"pub fn main() {
[
"hello",
"wibble wobble",
"these are all simple strings",
"but the list won't be packed",
"the formatter will keep",
"one item",
"per line",
"since there's no trailing comma here ->"
]
}
"#,
r#"pub fn main() {
[
"hello",
"wibble wobble",
"these are all simple strings",
"but the list won't be packed",
"the formatter will keep",
"one item",
"per line",
"since there's no trailing comma here ->",
]
}
"#
);
}
#[test]
fn simple_list_with_trailing_comma_and_multiple_items_per_line_is_packed() {
assert_format_rewrite!(
r#"pub fn main() {
[
"hello",
"wibble wobble",
"these are all simple strings",
"and the list will be packed since the following strings are",
"on the same", "line", "and there's a trailing comma ->",
]
}
"#,
r#"pub fn main() {
[
"hello", "wibble wobble", "these are all simple strings",
"and the list will be packed since the following strings are", "on the same",
"line", "and there's a trailing comma ->",
]
}
"#
);
}
#[test]
fn simple_constant_list_with_trailing_comma_and_multiple_items_per_line_is_packed() {
assert_format_rewrite!(
r#"pub const list = [
"hello",
"wibble wobble",
"these are all simple strings",
"and the list will be packed since the following strings are",
"on the same", "line", "and there's a trailing comma ->",
]
"#,
r#"pub const list = [
"hello", "wibble wobble", "these are all simple strings",
"and the list will be packed since the following strings are", "on the same",
"line", "and there's a trailing comma ->",
]
"#
);
}
#[test]
fn simple_packed_list_with_trailing_comma_is_kept_with_multiple_items_per_line() {
assert_format!(
r#"pub fn main() {
[
"hello", "wibble wobble", "these are all simple strings",
"and the list will be kept packed since it ends with a trailing comma",
"right here! ->",
]
}
"#
);
}
#[test]
fn simple_single_line_list_with_trailing_comma_is_split_one_item_per_line() {
assert_format_rewrite!(
r#"pub fn main() {
["these are all simple strings", "but the list won't be packed", "since it ends with a trailing comma ->",]
}
"#,
r#"pub fn main() {
[
"these are all simple strings",
"but the list won't be packed",
"since it ends with a trailing comma ->",
]
}
"#
);
}
#[test]
fn simple_single_line_list_with_no_trailing_comma_is_split_one_item_per_line() {
assert_format_rewrite!(
r#"pub fn main() {
["these are all simple strings", "but the list won't be packed", "even if it doesn't end with a trailing comma!"]
}
"#,
r#"pub fn main() {
[
"these are all simple strings",
"but the list won't be packed",
"even if it doesn't end with a trailing comma!",
]
}
"#
);
}
#[test]
fn empty_lines_in_list_are_not_ignored() {
assert_format_rewrite!(
"pub fn main() {
[1, 2,
3
]
}
",
"pub fn main() {
[
1,
2,
3,
]
}
"
);
}
#[test]
fn empty_lines_in_const_list_are_not_ignored() {
assert_format_rewrite!(
"const list =
[1, 2,
3
]
",
"const list = [
1,
2,
3,
]
"
);
}
#[test]
fn lists_with_empty_lines_are_always_broken() {
assert_format_rewrite!(
"pub fn main() {
[
1,
2,
3, 4, 5
]
}
",
"pub fn main() {
[
1,
2,
3,
4,
5,
]
}
"
);
}
#[test]
fn const_lists_with_empty_lines_are_always_broken() {
assert_format_rewrite!(
"const list =
[
1,
2,
3, 4, 5
]
",
"const list = [
1,
2,
3,
4,
5,
]
"
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/format/tests/function.rs | compiler-core/src/format/tests/function.rs | use crate::{assert_format, assert_format_rewrite};
#[test]
fn capture_with_single_argument() {
assert_format_rewrite!(
"pub fn main() -> Nil {
wibble([], wobble(_))
}
",
"pub fn main() -> Nil {
wibble([], wobble)
}
"
);
}
#[test]
fn deprecated() {
assert_format!(
r#"@deprecated("use something else instead")
pub fn main() -> Nil {
Nil
}
"#
);
}
#[test]
fn deprecated_external() {
assert_format!(
r#"@deprecated("use something else instead")
@external(erlang, "thing", "main")
pub fn main() -> Nil
"#
);
}
#[test]
fn anonymous_function_as_final_function_argument() {
assert_format!(
r#"pub fn main() {
some_function(123, 456, fn(x) {
let y = x + 1
y
})
}
"#
);
}
#[test]
fn anonymous_function_with_single_line_body_as_final_function_argument() {
assert_format!(
r#"pub fn main() {
some_function(123, 456, fn(x) { x })
}
"#
);
}
#[test]
fn anonymous_function_with_multi_line_unbreakable_body_as_final_function_argument() {
assert_format!(
r#"pub fn main() {
some_function(123, 456, fn(x) {
call_to_other_function(a, b, c, d, e, f, g, h)
})
}
"#
);
}
#[test]
fn anonymous_function_with_multi_line_breakable_body_as_final_function_argument() {
assert_format!(
r#"pub fn main() {
some_function(123, 456, fn(x) {
call_to_other_function(a, b, c, d, e, f, g, { x + x })
})
}
"#
);
}
#[test]
fn anonymous_function_with_multi_line_long_breakable_body_as_final_function_argument() {
assert_format!(
r#"pub fn main() {
some_function(123, 456, fn(x) {
call_to_other_function(a, b, c, d, e, f, g, case wibble {
Wibble -> 1
Wobble -> 2
})
})
}
"#
);
}
#[test]
fn function_call_as_final_function_argument_goes_on_its_own_line() {
assert_format!(
r#"pub fn main() {
some_function_with_a_long_name(
123,
456,
another_function_being_called(123, 456),
)
}
"#
);
}
#[test]
fn tuple_as_final_function_argument() {
assert_format!(
r#"pub fn main() {
some_function(123, 456, #(
"Here is a very long string which causes the formatter to wrap it",
))
}
"#
);
}
#[test]
fn list_as_final_function_argument() {
assert_format!(
r#"pub fn main() {
some_function(123, 456, [
"Here is a very long string which causes the formatter to wrap it",
])
}
"#
);
}
#[test]
fn case_expression_as_final_function_argument() {
assert_format!(
r#"pub fn main() {
some_function(123, 456, case my_var {
True -> True
False -> False
})
}
"#
);
}
#[test]
fn block_as_final_function_argument() {
assert_format!(
r#"pub fn main() {
some_function(123, 456, {
let days = 7
days * 24 * 60 * 60
})
}
"#
);
}
#[test]
fn when_all_arguments_are_too_long_each_one_is_on_its_own_line() {
assert_format!(
r#"pub fn main() {
some_function(
variable_with_really_long_name,
whoah_this_is_getting_out_of_hand,
["Here is a very long string which causes the formatter to wrap it"],
)
}
"#
);
}
#[test]
fn nested_breakable_lists_in_function_calls() {
assert_format!(
r#"pub fn main() {
html([attribute("lang", "en")], [
head([attribute("wibble", "wobble")], [
title([], [text("Hello this is some HTML")]),
]),
body([], [h1([], [text("Hello, world!")])]),
])
}
"#
);
}
#[test]
fn nested_breakable_tuples_in_function_calls() {
assert_format!(
r#"pub fn main() {
html(#(attribute("lang", "en")), #(
head(#(attribute("wibble", "wobble")), #(
title(#(), #(text("Hello this is some HTML"))),
body(#(), #(text("Hello this is some HTML"))),
)),
body(#(), #(h1(#(), #(text("Hello, lisp!"))))),
))
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2435
#[test]
fn only_last_argument_can_be_broken() {
assert_format!(
r#"pub fn main() {
tbd.workbook(for: "my_project")
|> task(
doc: "Run the project tests",
tags: list.concat([["test", "ci"], gleam, typescript]),
action: fn(_, _) { tbd.command(run: "gleam", with: ["test"]) },
)
|> run
}
"#
);
assert_format!(
r#"pub fn main() {
Theme(
flag: styler([32]),
heading: styler([1, 95]),
highlight: styler([1, 36]),
parameter: styler([34]),
tag: styler([33]),
given_tag: styler([3]),
first_tag: styler([1]),
tab: " ",
)
}
"#
);
}
#[test]
fn function_that_is_a_little_over_the_limit() {
assert_format!(
r#"pub fn handle_request(
handler: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,
) -> Nil {
todo
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2571
#[test]
fn expr_function_as_last_argument() {
assert_format!(
r#"pub fn main() {
Builder(
accumulator: "",
update: fn(accum, val) { accum <> val },
final: fn(accum) { accum },
)
}
"#
);
// We want to make sure that, if it goes over the limit NOT with its
// arguments' list the body is still the first thing that gets split.
assert_format!(
r#"pub fn main() {
Builder(accumulator: "", update: fn(accum, val) { accum }, final: fn(accum) {
accum
})
}
"#
);
}
#[test]
fn comment_at_start_of_inline_function_body() {
assert_format!(
r#"pub fn main() {
let add = fn(x: Int, y: Int) {
// This is a comment
x + y
}
}
"#
);
}
#[test]
fn comment_at_start_of_top_level_function_body() {
assert_format!(
r#"pub fn add(x: Int, y: Int) {
// This is a comment
x + y
}
"#
);
}
#[test]
fn comment_at_end_of_inline_function_args() {
assert_format!(
r#"pub fn main() {
let add = fn(
x: Int,
y: Int,
// This is a comment
) {
x + y
}
}
"#
);
}
#[test]
fn comment_middle_of_inline_function_body() {
assert_format!(
r#"pub fn main() {
let add = fn(x: Int, y: Int, z: Int) {
let a = x + y
// This is a comment
a + z
}
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/5004
#[test]
fn comment_in_tuple_return_type() {
assert_format_rewrite!(
r#"pub fn main() -> #(
// This is a string
String, // This is an awesome string
) {
todo
}
"#,
r#"pub fn main() -> #(
String,
// This is a string
// This is an awesome string
) {
todo
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/format/tests/asignments.rs | compiler-core/src/format/tests/asignments.rs | use crate::assert_format;
// https://github.com/gleam-lang/gleam/issues/2095
#[test]
fn comment() {
assert_format!(
r#"pub fn main() {
// Hello
let x = 1
x
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2095
#[test]
fn assert_comment() {
assert_format!(
r#"pub fn main() {
// Hello
let assert x = 1
x
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/format/tests/echo.rs | compiler-core/src/format/tests/echo.rs | use crate::{assert_format, assert_format_rewrite};
#[test]
fn echo() {
assert_format!(
"fn main() {
echo
}
"
);
}
#[test]
fn echo_with_value() {
assert_format!(
r#"fn main() {
echo value
}
"#
);
}
#[test]
fn echo_with_big_value_that_needs_to_be_split() {
assert_format!(
r#"fn main() {
echo [
this_is_a_long_list_and_requires_splitting,
wibble_wobble_woo,
multiple_lines,
]
}
"#
);
}
#[test]
fn echo_inside_a_pipeline() {
assert_format!(
r#"fn main() {
wibble
|> echo
|> wobble
}
"#
);
}
#[test]
fn echo_inside_a_single_line_pipeline() {
assert_format!(
r#"fn main() {
wibble |> echo |> wobble
}
"#
);
}
#[test]
fn echo_as_last_item_of_pipeline() {
assert_format!(
r#"fn main() {
wibble |> wobble |> echo
}
"#
);
}
#[test]
fn echo_as_last_item_of_multiline_pipeline() {
assert_format!(
r#"fn main() {
wibble
|> wobble
|> echo
}
"#
);
}
#[test]
fn echo_with_related_expression_on_following_line() {
assert_format_rewrite!(
r#"fn main() {
panic as echo
"wibble"
}
"#,
r#"fn main() {
panic as echo "wibble"
}
"#
);
}
#[test]
fn echo_with_following_value_in_a_pipeline() {
assert_format_rewrite!(
r#"fn main() {
[]
|> echo wibble
|> wobble
}
"#,
r#"fn main() {
[]
|> echo
wibble
|> wobble
}
"#
);
}
#[test]
fn echo_printing_multiline_pipeline() {
assert_format_rewrite!(
r#"fn main() {
echo first
|> wibble
|> wobble
}
"#,
r#"fn main() {
echo first
|> wibble
|> wobble
}
"#
);
}
#[test]
fn echo_printing_one_line_pipeline() {
assert_format!(
r#"fn main() {
echo first |> wibble |> wobble
}
"#
);
}
#[test]
fn echo_as() {
assert_format!(
"fn main() {
echo as hello
}
"
);
}
#[test]
fn echo_as_with_value() {
assert_format!(
r#"fn main() {
echo value as message
}
"#
);
}
#[test]
fn echo_as_with_big_value_that_needs_to_be_split() {
assert_format!(
r#"fn main() {
echo call([
this_is_a_long_list_and_requires_splitting,
wibble_wobble_woo,
multiple_lines,
])
as "tag!"
}
"#
);
}
#[test]
fn echo_as_inside_a_pipeline() {
assert_format!(
r#"fn main() {
wibble
|> echo as "echooo o o"
|> wobble
}
"#
);
}
#[test]
fn echo_as_inside_a_single_line_pipeline() {
assert_format!(
r#"fn main() {
wibble |> echo as string |> wobble
}
"#
);
}
#[test]
fn echo_as_as_last_item_of_pipeline() {
assert_format!(
r#"fn main() {
wibble |> wobble |> echo as end
}
"#
);
}
#[test]
fn echo_as_as_last_item_of_multiline_pipeline() {
assert_format!(
r#"fn main() {
wibble
|> wobble
|> echo as message
}
"#
);
}
#[test]
fn echo_as_with_related_expression_on_following_line() {
assert_format_rewrite!(
r#"fn main() {
panic as echo
"wibble"
as wobble
}
"#,
r#"fn main() {
panic as echo "wibble" as wobble
}
"#
);
}
#[test]
fn echo_as_with_following_value_in_a_pipeline() {
assert_format_rewrite!(
r#"fn main() {
[]
|> echo as wibble wibble
|> wobble
}
"#,
r#"fn main() {
[]
|> echo as wibble
wibble
|> wobble
}
"#
);
}
#[test]
fn echo_as_printing_multiline_pipeline() {
assert_format_rewrite!(
r#"fn main() {
echo first
|> wibble
|> wobble
as "pipeline"
}
"#,
r#"fn main() {
echo first
|> wibble
|> wobble
as "pipeline"
}
"#
);
}
#[test]
fn echo_as_printing_one_line_pipeline() {
assert_format!(
r#"fn main() {
echo first |> wibble |> wobble as "pipeline"
}
"#
);
}
#[test]
fn echo_as_with_multiline_message() {
assert_format!(
r#"fn main() {
echo [wibble, wobble]
as {
// Force this block to split
"wibble" <> wobble()
}
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/format/tests/external_types.rs | compiler-core/src/format/tests/external_types.rs | use crate::assert_format;
#[test]
fn example1() {
assert_format!("type Private\n");
}
#[test]
fn example2() {
assert_format!("type Box(a)\n");
}
#[test]
fn example3() {
assert_format!("type Box(a, b, zero)\n");
}
#[test]
fn example4() {
assert_format!("pub type Private\n");
}
#[test]
fn example5() {
assert_format!("pub type Box(a)\n");
}
#[test]
fn example6() {
assert_format!("pub type Box(a, b, zero)\n");
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/format/tests/tuple.rs | compiler-core/src/format/tests/tuple.rs | use crate::{assert_format, assert_format_rewrite};
// https://github.com/gleam-lang/gleam/issues/2083
#[test]
fn nested_index_block() {
assert_format!(
r#"pub fn main() {
{ #(1, 2).1 }.1
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2083
#[test]
fn index_block() {
assert_format!(
r#"pub fn main() {
{
1
#(1, 2)
}.1
}
"#
);
}
#[test]
fn tuple_with_last_splittable_arg() {
assert_format!(
r#"fn on_attribute_change() -> Dict(String, Decoder(Msg)) {
dict.from_list([
#("value", fn(attr) {
attr
|> dynamic.int
|> result.map(Value)
|> result.map(AttributeChanged)
}),
])
}
"#
);
assert_format!(
r#"pub fn main() {
#("value", [
"a long list that needs to be split on multiple lines",
"another long string",
])
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/3070
#[test]
fn constant_long_list_of_tuples() {
assert_format!(
r#"const wibble = [
#(1, 2),
#(3, 4),
#(5, 6),
#(7, 8),
#(9, 10),
#(11, 12),
#(1, 2),
#(3, 4),
#(5, 6),
#(7, 8),
#(9, 10),
#(11, 12),
]
pub fn main() {
todo
}
"#
);
}
#[test]
fn nested_tuple_access() {
assert_format!(
r#"pub fn main() {
wibble.1.0
}
"#
);
}
#[test]
fn nested_tuple_with_needless_block() {
assert_format_rewrite!(
r#"pub fn main() {
{ wibble.1 }.0
}
"#,
r#"pub fn main() {
wibble.1.0
}
"#
);
}
#[test]
fn nested_literal_tuple_with_needless_block_is_not_changed() {
assert_format!(
r#"pub fn main() {
{ #(wibble, wobble).1 }.0
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/format/tests/conditional_compilation.rs | compiler-core/src/format/tests/conditional_compilation.rs | use crate::{assert_format, assert_format_rewrite};
#[test]
fn multiple() {
assert_format!(
"type X
@target(erlang)
type Y {
Y
}
@target(javascript)
type Z {
Z
}
"
);
}
#[test]
fn formatter_removes_target_shorthand_erlang() {
assert_format_rewrite!(
"@target(erl)
fn wibble() {
todo
}",
"@target(erlang)
fn wibble() {
todo
}
"
);
}
#[test]
fn formatter_removes_target_shorthand_javascript() {
assert_format_rewrite!(
"@target(js)
fn wibble() {
todo
}",
"@target(javascript)
fn wibble() {
todo
}
"
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/format/tests/pipeline.rs | compiler-core/src/format/tests/pipeline.rs | use crate::{assert_format, assert_format_rewrite};
#[test]
pub fn single_line_pipeline_longer_than_line_limit_gets_split() {
assert_format_rewrite!(
r#"pub fn main() {
wibble |> wobble |> loooooooooooooooooooooooooooooooooooooooooooong_function_name
}
"#,
r#"pub fn main() {
wibble
|> wobble
|> loooooooooooooooooooooooooooooooooooooooooooong_function_name
}
"#,
);
}
#[test]
pub fn single_line_pipeline_shorter_than_line_limit_is_kept_on_a_single_line() {
assert_format!(
r#"pub fn main() {
wibble(1) |> wobble
}
"#
);
}
#[test]
pub fn multi_line_pipeline_is_split_no_matter_the_length() {
assert_format!(
r#"pub fn main() {
wibble(1)
|> wobble
}
"#
);
}
#[test]
pub fn adding_a_newline_to_a_pipeline_splits_all() {
assert_format_rewrite!(
r#"pub fn main() {
wibble |> wobble
|> wabble
}
"#,
r#"pub fn main() {
wibble
|> wobble
|> wabble
}
"#,
);
}
#[test]
pub fn multiline_function_inside_pipeline_function_argument_is_indented_properly() {
assert_format!(
r#"pub fn main() {
function(
arg0,
thing
|> string.replace(
"{something something}",
date.month_to_string(month, config.l10n.context),
),
)
}
"#,
);
}
#[test]
pub fn multiline_function_inside_pipeline_in_list_is_indented_properly() {
assert_format!(
r#"pub fn main() {
[
item1,
thing
|> string.replace(
"{something something}",
date.month_to_string(month, config.l10n.context),
),
]
}
"#,
);
}
#[test]
pub fn multiline_function_inside_pipeline_in_tuple_is_indented_properly() {
assert_format!(
r#"pub fn main() {
#(
item1,
thing
|> string.replace(
"{something something}",
date.month_to_string(month, config.l10n.context),
),
)
}
"#,
);
}
#[test]
fn pipe_with_labelled_first_argument_capture() {
assert_format!(
"fn wibble(label1 a, label2 b, lots c, of d, labels e) {
a + b * c - d / e
}
fn main() {
1 |> wibble(label1: _, label2: 2, lots: 3, of: 4, labels: 5)
}
"
);
}
#[test]
fn pipe_with_labelled_only_argument_capture() {
assert_format!(
"fn wibble(descriptive_label value) {
value
}
fn main() {
42 |> wibble(descriptive_label: _)
}
"
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/format/tests/constant.rs | compiler-core/src/format/tests/constant.rs | use crate::assert_format;
// https://github.com/gleam-lang/gleam/issues/5143
#[test]
pub fn constant_with_deprecated_attribute() {
assert_format!(
r#"@deprecated("Use tau instead")
pub const pi = 3.14
"#
);
}
#[test]
fn const_record_update_simple() {
assert_format!(
r#"pub type Counter {
Counter(a: Int, b: Int)
}
pub const c = Counter(0, 0)
pub const c2 = Counter(..c, a: 1, b: 2)
"#
);
}
#[test]
fn const_record_update_long() {
assert_format!(
r#"pub type Counter {
Counter(loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong: Int)
}
pub const c = Counter(0)
pub const c2 = Counter(
..c,
loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong: 1,
)
"#
);
}
#[test]
fn const_record_update_with_module() {
assert_format!(
r#"pub type Counter {
Counter(a: Int, b: Int)
}
pub const c = Counter(0, 0)
pub const c2 = mod.Counter(..c, a: 1)
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/format/tests/bit_array.rs | compiler-core/src/format/tests/bit_array.rs | use crate::{assert_format, assert_format_rewrite};
#[test]
fn construction() {
assert_format!(
"fn main() {
let a = 1
let x = <<1, a, 2:bytes>>
let size = <<3:2, 4:size(3), 5:bytes-size(4), 6:size(a)>>
let unit = <<7:unit(1), 8:bytes-unit(2)>>
x
}
",
);
}
#[test]
fn pattern() {
assert_format!(
"fn main() {
let a = 1
let <<b, c, d:bytes>> = <<1, a, 2:bytes>>
b
}
",
);
}
#[test]
fn long() {
assert_format!(
"fn main() {
let some_really_long_variable_name_to_force_wrapping = 1
let bits = <<
some_really_long_variable_name_to_force_wrapping,
some_really_long_variable_name_to_force_wrapping,
>>
bits
}
",
);
}
// https://github.com/gleam-lang/gleam/issues/2932
#[test]
fn tight_empty() {
assert_format!(
"fn main() {
let some_really_really_really_really_really_really_really_long_variable_name_to_force_wrapping = <<>>
some_really_really_really_really_really_really_really_long_variable_name_to_force_wrapping
}
"
);
}
#[test]
fn comments_are_not_moved_out_of_empty_bit_array() {
assert_format!(
r#"pub fn main() {
// This is an empty bit array!
<<
// Nothing here...
>>
}
"#
);
}
#[test]
fn empty_bit_arrays_with_comment_inside_are_indented_properly() {
assert_format!(
r#"pub fn main() {
fun(
<<
// Nothing here...
>>,
wibble_wobble_wibble_wobble_wibble_wobble_wibble_wobble,
<<
// Nothing here as well!
>>,
)
}
"#
);
}
#[test]
fn comments_inside_non_empty_bit_arrays_are_not_moved() {
assert_format!(
r#"pub fn main() {
fun(
<<
// One is below me.
1, 2,
// Three is below me.
3,
>>,
wibble_wobble_wibble_wobble_wibble_wobble_wibble_wobble,
<<
// Three is below me.
3,
>>,
)
}
"#
);
}
#[test]
fn concise_wrapping_of_simple_bit_arrays() {
assert_format!(
"pub fn main() {
<<
100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300, 1400,
1500, 1600, 1700, 1800, 1900, 2000,
>>
}
"
);
}
#[test]
fn concise_wrapping_of_simple_bit_arrays1() {
assert_format!(
"pub fn main() {
<<
1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 1.0, 11.0, 12.0, 13.0, 14.0,
15.0, 16.0, 17.0, 18.0, 19.0, 2.0,
>>
}
"
);
}
#[test]
fn concise_wrapping_of_simple_bit_arrays2() {
assert_format!(
r#"pub fn main() {
<<
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve",
>>
}
"#
);
}
#[test]
fn concise_wrapping_of_simple_bit_arrays3() {
assert_format!(
"const values = <<
100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300, 1400,
1500, 1600, 1700, 1800, 1900, 2000,
>>
"
);
}
#[test]
fn concise_wrapping_of_simple_bit_arrays4() {
assert_format!(
"const values = <<
1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 1.0, 11.0, 12.0, 13.0, 14.0, 15.0,
16.0, 17.0, 18.0, 19.0, 2.0,
>>
"
);
}
#[test]
fn concise_wrapping_of_simple_bit_arrays5() {
assert_format!(
r#"const values = <<
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve",
>>
"#
);
}
#[test]
fn binop_value() {
assert_format!(
r#"pub fn main() {
<<{ 1 + 1 }>>
}
"#
);
}
#[test]
fn block_value() {
assert_format!(
r#"pub fn main() {
<<
{
io.println("hi")
1
},
>>
}
"#
);
}
#[test]
fn operator_in_pattern_size() {
assert_format!(
"pub fn main() {
let assert <<len, payload:size({ len + 1 } * 8 + 1)>> = <<>>
}
"
);
}
#[test]
// https://github.com/gleam-lang/gleam/issues/4792#issuecomment-3096177213
fn bit_array_segments_are_kept_one_per_line() {
assert_format!(
"pub fn main() {
<<
1:1,
1:1,
0:2,
opcode:4,
masked:1,
length_section:bits,
mask_key:bits,
data:bits,
>>
|> bytes_tree.from_bit_array
}
"
);
}
#[test]
fn bit_array_with_trailing_comma_is_broken() {
assert_format_rewrite!(
"pub fn main() { <<1, 2, a,>> }",
r#"pub fn main() {
<<
1,
2,
a,
>>
}
"#
);
}
#[test]
fn constant_bit_array_with_trailing_comma_is_broken() {
assert_format_rewrite!(
"const bit_array = <<1, 2, a,>>",
r#"const bit_array = <<
1,
2,
a,
>>
"#
);
}
#[test]
fn bit_array_with_trailing_comma_is_kept_broken() {
assert_format!(
r#"pub fn main() {
<<
1,
2,
a,
>>
}
"#
);
}
#[test]
fn constant_bit_array_with_trailing_comma_is_kept_broken() {
assert_format!(
r#"const bit_array = <<
1,
2,
a,
>>
"#
);
}
#[test]
fn bit_array_with_no_trailing_comma_is_packed_on_a_single_line() {
assert_format_rewrite!(
r#"pub fn main() {
<<
1,
2,
a
>>
}
"#,
r#"pub fn main() {
<<1, 2, a>>
}
"#
);
}
#[test]
fn constant_bit_array_with_no_trailing_comma_is_packed_on_a_single_line() {
assert_format_rewrite!(
r#"const bit_array = <<
1,
2,
a
>>"#,
"const bit_array = <<1, 2, a>>\n"
);
}
#[test]
fn bit_array_with_no_comma_is_packed_on_a_single_line_or_split_one_item_per_line() {
assert_format_rewrite!(
"pub fn main() {
<<
1,
a,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
b,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312
>>
}
",
"pub fn main() {
<<
1,
a,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
b,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
>>
}
"
);
}
#[test]
fn constant_bit_array_with_no_comma_is_packed_on_a_single_line_or_split_one_item_per_line() {
assert_format_rewrite!(
"const bit_array = <<
1,
a,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
b,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312
>>
",
"const bit_array = <<
1,
a,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
b,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
12_312_312_312_312_312_312_312,
>>
"
);
}
#[test]
fn simple_bit_array_with_no_comma_is_packed_on_a_single_line_or_split_one_item_per_line() {
assert_format_rewrite!(
r#"pub fn main() {
<<
"hello",
"wibble wobble",
"these are all simple strings",
"but the bitarray won't be packed",
"the formatter will keep",
"one item",
"per line",
"since there's no trailing comma here ->"
>>
}
"#,
r#"pub fn main() {
<<
"hello",
"wibble wobble",
"these are all simple strings",
"but the bitarray won't be packed",
"the formatter will keep",
"one item",
"per line",
"since there's no trailing comma here ->",
>>
}
"#
);
}
#[test]
fn simple_bit_array_with_trailing_comma_and_multiple_items_per_line_is_packed() {
assert_format_rewrite!(
r#"pub fn main() {
<<
"hello",
"wibble wobble",
"these are all simple strings",
"and the bit array will be packed since the following strings are",
"on the same", "line", "and there's a trailing comma ->",
>>
}
"#,
r#"pub fn main() {
<<
"hello", "wibble wobble", "these are all simple strings",
"and the bit array will be packed since the following strings are",
"on the same", "line", "and there's a trailing comma ->",
>>
}
"#
);
}
#[test]
fn simple_constant_bit_array_with_trailing_comma_and_multiple_items_per_line_is_packed() {
assert_format_rewrite!(
r#"pub const bit_array = <<
"hello",
"wibble wobble",
"these are all simple strings",
"and the bit array will be packed since the following strings are",
"on the same", "line", "and there's a trailing comma ->",
>>
"#,
r#"pub const bit_array = <<
"hello", "wibble wobble", "these are all simple strings",
"and the bit array will be packed since the following strings are",
"on the same", "line", "and there's a trailing comma ->",
>>
"#
);
}
#[test]
fn simple_packed_bit_array_with_trailing_comma_is_kept_with_multiple_items_per_line() {
assert_format!(
r#"pub fn main() {
<<
"hello", "wibble wobble", "these are all simple strings",
"and the bit array will be kept packed since it ends with a trailing comma",
"right here! ->",
>>
}
"#
);
}
#[test]
fn simple_single_line_bit_array_with_trailing_comma_is_split_one_item_per_line() {
assert_format_rewrite!(
r#"pub fn main() {
<<"these are all simple strings", "but the bit array won't be packed", "since it ends with a trailing comma ->",>>
}
"#,
r#"pub fn main() {
<<
"these are all simple strings",
"but the bit array won't be packed",
"since it ends with a trailing comma ->",
>>
}
"#
);
}
#[test]
fn simple_single_line_bit_array_with_no_trailing_comma_is_split_one_item_per_line() {
assert_format_rewrite!(
r#"pub fn main() {
<<"these are all simple strings", "but the bit array won't be packed", "even if it doesn't end with a trailing comma!">>
}
"#,
r#"pub fn main() {
<<
"these are all simple strings",
"but the bit array won't be packed",
"even if it doesn't end with a trailing comma!",
>>
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/format/tests/record_update.rs | compiler-core/src/format/tests/record_update.rs | use crate::assert_format;
#[test]
fn one() {
assert_format!(
"pub type Counter {
Counter(a: Int, b: Int)
}
fn main() {
let c = Counter(0, 0)
let c = Counter(..c, a: c.a + 1, b: c.a + c.b)
c
}
"
);
}
#[test]
fn two() {
// Long record updates are split onto multiple lines
assert_format!(
"pub type Counter {
Counter(loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong: Int)
}
fn main() {
let c = Counter(0)
let c =
Counter(
..c,
loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong: 1,
)
c
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/1872
#[test]
fn comment_before_spread() {
assert_format!(
r#"fn main() {
Thingy(
// Def?
// Def!
..thingy.defaults,
one: One,
)
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/1872
#[test]
fn comment_before_update_label() {
assert_format!(
r#"fn main() {
Thingy(
..thingy.defaults,
// Def?
// Def!
one: One,
)
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/1872
#[test]
fn multiple_line_custom_type_field_comments() {
assert_format!(
r#"fn main() {
Thingy(
// Def?
// Def!
..thingy.defaults,
// One?
// One!
one: One,
// Two?
// Two!
two: Two,
)
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/4120
#[test]
fn record_update_gets_formatted_like_a_function_call() {
assert_format!(
r#"pub fn example() {
Record(..record, field: {
use _ <- list.map(record.field)
io.print("Example")
})
}
"#
);
}
#[test]
fn record_with_record_and_spread_field_is_not_needlessly_broken() {
assert_format!(
"pub fn main() {
case todo {
Wibble(
some_field: Wobble(something: 1, ..),
other_field_1:,
other_field_2:,
other_field_3:,
..,
) -> todo
}
}
"
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/format/tests/blocks.rs | compiler-core/src/format/tests/blocks.rs | use crate::assert_format;
// https://github.com/gleam-lang/gleam/issues/2119
#[test]
fn assignment() {
assert_format!(
r#"fn main() {
let greeting = {
"Hello"
}
greeting
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2131
#[test]
fn comment() {
assert_format!(
r#"fn main() {
wibble(
// Hello
{ Nil },
)
}
"#
);
}
#[test]
fn block_comment() {
assert_format!(
r#"fn main() {
testbldr.demonstrate(
named: "Hello, this argument is longer to make it all wrap",
with: {
// Comment!
Nil
Nil
},
)
}
"#
);
}
#[test]
fn last_comments_are_not_moved_out_of_blocks() {
assert_format!(
r#"fn main() {
{
hello
// Hope I'm not yeeted out of this block!
}
}
"#
);
assert_format!(
r#"fn main() {
{
hello
{
{ hi }
// Some nested comments
}
// At the end of multiple blocks
}
}
"#
);
assert_format!(
r#"fn main() {
case wibble {
wobble -> {
1
// Hope I can stay inside this clause
}
}
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/format/tests/cases.rs | compiler-core/src/format/tests/cases.rs | use crate::assert_format;
#[test]
fn case_with_two_long_subjects() {
assert_format!(
r#"pub fn main() {
case
wibble(one_long_argument, something_else),
wobble(another_argument, this_is_long)
{
_ -> todo
}
}
"#
);
}
#[test]
fn multiple_patterns_get_split_one_on_each_line() {
assert_format!(
r#"pub fn main() {
case wibble, wobble, wubble {
Wibble(one_thing, something_else, wibble),
Wobble(
this_will_go_over_the_line_limit,
and_the_arguments_get_broken_as_well,
wobble,
),
Wubble(this_will_go_over_the_line_limit, wubble)
-> todo
}
}
"#
);
}
#[test]
fn multiple_patterns_with_guard_get_split_one_on_each_line() {
assert_format!(
r#"pub fn main() {
case wibble, wobble, wubble {
Wibble(one_thing, something_else, wibble),
Wobble(this_will_go_over_the_line_limit, wobble),
Wubble(this_will_go_over_the_line_limit, wubble)
if wibble && wobble || wubble
-> todo
}
}
"#
);
}
#[test]
fn multiple_patterns_with_long_guard_get_split_one_on_each_line() {
assert_format!(
r#"pub fn main() {
case wibble, wobble, wubble {
Wibble(one_thing, something_else, wibble),
Wobble(this_will_go_over_the_line_limit, wobble),
Wubble(this_will_go_over_the_line_limit, wubble)
if { wibble || wobble }
&& { wibble || wobble && wibble > 10 }
|| wobble < 10_000_000
-> todo
}
}
"#
);
}
#[test]
fn multiple_patterns_and_alternative_patterns_mixed_together() {
assert_format!(
r#"pub fn main() {
case wibble, wobble, wubble {
Wibble(one_thing, something_else, wibble),
Wobble(this_will_go_over_the_line_limit, wobble),
Wubble(this_will_go_over_the_line_limit, wubble)
| Wibble(a), Wobble(b), Wubble(c)
| Wibble(one_thing, something_else, wibble),
Wobble(this_will_go_over_the_line_limit, wobble),
Wubble(this_will_go_over_the_line_limit, wubble)
if { wibble || wobble }
&& { wibble || wobble && wibble > 10 }
|| wobble < 10_000_000
-> todo
}
}
"#
);
}
#[test]
fn case_pattern_split_on_multiple_lines_is_not_needlessly_nested() {
assert_format!(
r#"pub fn main() {
case thing {
CannotSaveNewSnapshot(
reason: reason,
title: title,
destination: destination,
) -> todo
}
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/3140
#[test]
fn long_comment_before_case_with_multiple_subjects_doesnt_force_a_break() {
assert_format!(
r#"fn main() {
case a, b {
// a very long comment a very long comment a very long comment a very long comment
_, _ -> True
}
}
"#
);
}
#[test]
fn alternatives_are_not_split_if_not_necessary() {
assert_format!(
r#"fn main() {
case thing {
Wibble | Wobble -> {
todo
todo
}
}
}
"#
);
}
#[test]
fn alternatives_are_not_split_if_not_necessary_2() {
assert_format!(
r#"fn main() {
case thing {
Wibble | Wobble | Wabble ->
loooooooong_function_call_that_barely_goes_over_the_limit()
}
}
"#
);
}
#[test]
fn subjects_are_not_split_if_not_necessary() {
assert_format!(
r#"fn main() {
case
is_all_uppercase(remark),
string.ends_with(remark, "?"),
string.trim(remark) == ""
{
_, _, _ -> todo
}
}
"#
);
}
#[test]
fn case_in_call_gets_broken_if_it_goes_over_the_limit_with_subject() {
assert_format!(
r#"fn main() {
do_diff_attributes(
dict.delete(prev, attr.name),
rest,
case attr.value == old.value {
True -> added
False -> [attr, ..added]
},
)
}
"#
);
}
#[test]
fn case_in_call_is_not_broken_if_it_goes_over_the_limit_with_branches() {
assert_format!(
r#"fn main() {
do_diff_attributes(rest, case attr.value == old.value {
True -> added
False -> [attr, ..added]
})
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/format/tests/binary_operators.rs | compiler-core/src/format/tests/binary_operators.rs | use crate::assert_format;
// https://github.com/gleam-lang/gleam/issues/835
#[test]
pub fn long_binary_operation_sequence() {
assert_format!(
r#"pub fn main() {
int.to_string(color.red)
<> ", "
<> int.to_string(color.green)
<> ", "
<> int.to_string(color.blue)
<> ", "
<> float.to_string(color.alpha)
}
"#
);
}
#[test]
pub fn long_comparison_chain() {
assert_format!(
r#"pub fn main() {
trying_a_comparison(this, is, a, function) > with_ints
&& trying_other_comparisons < with_ints
|| trying_other_comparisons <= with_ints
&& trying_other_comparisons >= with_ints
|| and_now_an_equality_check == with_a_function(wibble, wobble)
&& trying_other_comparisons >. with_floats
|| trying_other_comparisons <. with_floats(wobble)
&& trying_other_comparisons <=. with_floats
|| trying_other_comparisons(wibble, wobble) >=. with_floats
&& wibble <> wobble
}
"#
);
}
#[test]
pub fn long_chain_mixing_operators() {
assert_format!(
r#"pub fn main() {
variable + variable - variable * variable / variable
== variable * variable / variable - variable + variable
|| wibble * wobble > 11
}
"#
);
assert_format!(
r#"pub fn main() {
variable +. variable -. variable *. variable /. variable
== variable *. variable /. variable -. variable +. variable
|| wibble *. wobble >=. 11
}
"#
);
}
// Thanks Hayleigh for pointing this out!
#[test]
fn case_branch_is_not_broken_if_can_fit_on_line() {
assert_format!(
r#"pub fn main() {
case remainder {
_ if remainder >=. 0.5 && x >=. 0.0 ->
float_sign(x) *. truncate_float(xabs +. 1.0) /. p
_ -> float_sign(x) *. xabs_truncated /. p
}
}
"#
);
}
// https://discord.com/channels/768594524158427167/1187508793945378847/1187508793945378847
#[test]
fn binary_operation_in_assignment_that_is_almost_80_chars() {
assert_format!(
r#"pub fn main() {
let is_vr_implicit =
dicom_read_context.transfer_syntax == transfer_syntax.ImplicitVrLittleEndian
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2480
#[test]
fn labelled_field_with_binary_operators_are_not_broken_if_they_can_fit() {
assert_format!(
r#"pub fn main() {
Ok(Lesson(
name: names.name,
text: text,
code: code,
path: chapter_path <> "/",
previous: None,
next: None,
))
}
"#
);
assert_format!(
r#"pub fn main() {
Ok(Lesson(
name: names.name,
text:,
code:,
path: chapter_path
<> "/"
<> this_one_doesnt_fit
<> "and ends up on multiple lines",
previous: None,
next: None,
))
}
"#
);
assert_format!(
r#"pub fn main() {
Ok(wibble(
name: names.name,
text:,
code:,
path: chapter_path <> "/",
previous: None,
next: None,
))
}
"#
);
assert_format!(
r#"pub fn main() {
Ok(wibble(
name: names.name,
text:,
code:,
path: chapter_path
<> "/"
<> this_one_doesnt_fit
<> "and ends up on multiple lines",
previous: None,
next: None,
))
}
"#
);
}
#[test]
fn math_binops_kept_on_a_single_line_in_pipes() {
assert_format!(
r#"pub fn main() {
1 + 2 * 3 / 4 - 5
|> wibble
|> wobble
}
"#
);
assert_format!(
r#"pub fn main() {
1 +. 2 *. 3 /. 4 -. 5
|> wibble
|> wobble
}
"#
);
}
#[test]
fn binop_used_as_function_arguments_gets_nested() {
assert_format!(
r#"pub fn main() {
wibble(
a_variable_with_a_long_name
<> another_variable_with_a_long_name
<> yet_another_variable_with_a_long_name,
wobble,
)
}
"#
);
}
#[test]
fn binop_is_not_nested_if_the_only_argument() {
assert_format!(
r#"pub fn main() {
wibble(
a_variable_with_a_long_name
<> another_variable_with_a_long_name
<> yet_another_variable_with_a_long_name,
)
}
"#
);
}
#[test]
fn binop_inside_list_gets_nested() {
assert_format!(
r#"pub fn main() {
[
wibble,
a_variable_with_a_long_name
<> another_variable_with_a_long_name
<> yet_another_variable_with_a_long_name,
]
}
"#
);
}
#[test]
fn binop_inside_list_is_not_nested_if_only_item() {
assert_format!(
r#"pub fn main() {
[
a_variable_with_a_long_name
<> another_variable_with_a_long_name
<> yet_another_variable_with_a_long_name,
]
}
"#
);
}
#[test]
fn binop_inside_tuple_gets_nested() {
assert_format!(
r#"pub fn main() {
#(
wibble,
a_variable_with_a_long_name
<> another_variable_with_a_long_name
<> yet_another_variable_with_a_long_name,
)
}
"#
);
}
#[test]
fn binop_inside_tuple_is_not_nested_if_only_item() {
assert_format!(
r#"pub fn main() {
#(
a_variable_with_a_long_name
<> another_variable_with_a_long_name
<> yet_another_variable_with_a_long_name,
)
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2624
#[test]
fn binop_as_argument_in_variant_with_spread_gets_nested() {
assert_format!(
r#"pub fn main() {
Wibble(
..wibble,
label: string
<> "a long string that is making things go on multiple lines"
<> "another string",
)
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/io/memory.rs | compiler-core/src/io/memory.rs | use super::*;
use std::ops::Deref;
use std::{
cell::RefCell,
collections::{HashMap, HashSet},
rc::Rc,
time::Duration,
};
use camino::{Utf8Path, Utf8PathBuf};
/// An in memory sharable collection of pretend files that can be used in place
/// of a real file system. It is a shared reference to a set of buffer than can
/// be cheaply cloned, all resulting copies pointing to the same internal
/// buffers.
///
/// Useful in tests and in environments like the browser where there is no file
/// system.
///
/// Not thread safe. The compiler is single threaded, so that's OK.
///
/// Only supports absolute paths. The root directory ("/") is always guaranteed
/// to exist.
///
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InMemoryFileSystem {
files: Rc<RefCell<HashMap<Utf8PathBuf, InMemoryFile>>>,
}
impl Default for InMemoryFileSystem {
fn default() -> Self {
let mut files = HashMap::new();
// Ensure root directory always exists.
let _ = files.insert(Utf8PathBuf::from("/"), InMemoryFile::directory());
Self {
files: Rc::new(RefCell::new(files)),
}
}
}
impl InMemoryFileSystem {
pub fn new() -> Self {
Self::default()
}
pub fn reset(&self) {
self.files.deref().borrow_mut().clear();
}
/// Returns the contents of each file, excluding directories.
///
/// # Panics
///
/// Panics if this is not the only reference to the underlying files.
///
pub fn into_contents(self) -> HashMap<Utf8PathBuf, Content> {
Rc::try_unwrap(self.files)
.expect("InMemoryFileSystem::into_files called on a clone")
.into_inner()
.into_iter()
.filter_map(|(path, file)| file.into_content().map(|content| (path, content)))
.collect()
}
/// All files currently in the filesystem (directories are not included).
pub fn files(&self) -> Vec<Utf8PathBuf> {
self.files
.borrow()
.iter()
.filter(|(_, f)| !f.is_directory())
.map(|(path, _)| path)
.cloned()
.collect()
}
#[cfg(test)]
/// Set the modification time of a file.
///
/// Panics if the file does not exist.
///
pub fn set_modification_time(&self, path: &Utf8Path, time: SystemTime) {
self.files
.deref()
.borrow_mut()
.get_mut(path)
.unwrap()
.modification_time = time;
}
pub fn try_set_modification_time(
&self,
path: &Utf8Path,
time: SystemTime,
) -> Result<(), Error> {
self.files
.deref()
.borrow_mut()
.get_mut(path)
.ok_or_else(|| Error::FileIo {
kind: FileKind::File,
action: FileIoAction::Open,
path: path.to_path_buf(),
err: None,
})?
.modification_time = time;
Ok(())
}
}
impl FileSystemWriter for InMemoryFileSystem {
fn delete_directory(&self, path: &Utf8Path) -> Result<(), Error> {
let mut files = self.files.deref().borrow_mut();
if files.get(path).is_some_and(|f| !f.is_directory()) {
return Err(Error::FileIo {
kind: FileKind::Directory,
action: FileIoAction::Delete,
path: path.to_path_buf(),
err: None,
});
}
let root = Utf8Path::new("/");
if path != root {
// Ensure the root path always exists.
// Deleting other files is fine.
let _ = files.remove(path);
}
// Remove any files in the directory
while let Some(file) = files
.keys()
.find(|file| file.as_path() != root && file.starts_with(path))
{
let file = file.clone();
let _ = files.remove(&file);
}
Ok(())
}
fn copy(&self, from: &Utf8Path, to: &Utf8Path) -> Result<(), Error> {
self.write_bytes(to, &self.read_bytes(from)?)
}
fn copy_dir(&self, _: &Utf8Path, _: &Utf8Path) -> Result<(), Error> {
panic!("unimplemented") // TODO
}
fn mkdir(&self, path: &Utf8Path) -> Result<(), Error> {
// Traverse ancestors from parent to root.
// Create each missing ancestor.
for ancestor in path.ancestors() {
if ancestor == "" {
// Ignore the final ancestor of a relative path.
continue;
}
// Ensure we don't overwrite an existing file.
// We can ignore existing directories though.
let mut files = self.files.deref().borrow_mut();
if files.get(ancestor).is_some_and(|f| !f.is_directory()) {
return Err(Error::FileIo {
kind: FileKind::Directory,
action: FileIoAction::Create,
path: ancestor.to_path_buf(),
err: None,
});
}
let dir = InMemoryFile::directory();
_ = files.insert(ancestor.to_path_buf(), dir);
}
Ok(())
}
fn hardlink(&self, _: &Utf8Path, _: &Utf8Path) -> Result<(), Error> {
panic!("unimplemented") // TODO
}
fn symlink_dir(&self, _: &Utf8Path, _: &Utf8Path) -> Result<(), Error> {
panic!("unimplemented") // TODO
}
fn delete_file(&self, path: &Utf8Path) -> Result<(), Error> {
let mut files = self.files.deref().borrow_mut();
if files.get(path).is_some_and(|f| f.is_directory()) {
return Err(Error::FileIo {
kind: FileKind::File,
action: FileIoAction::Delete,
path: path.to_path_buf(),
err: None,
});
}
let _ = files.remove(path);
Ok(())
}
fn write(&self, path: &Utf8Path, content: &str) -> Result<(), Error> {
self.write_bytes(path, content.as_bytes())
}
fn write_bytes(&self, path: &Utf8Path, content: &[u8]) -> Result<(), Error> {
// Ensure directories exist
if let Some(parent) = path.parent() {
self.mkdir(parent)?;
}
let mut file = InMemoryFile::default();
_ = io::Write::write(&mut file, content).expect("channel buffer write");
_ = self
.files
.deref()
.borrow_mut()
.insert(path.to_path_buf(), file);
Ok(())
}
fn exists(&self, path: &Utf8Path) -> bool {
self.files.deref().borrow().contains_key(path)
}
}
impl FileSystemReader for InMemoryFileSystem {
fn canonicalise(&self, path: &Utf8Path) -> Result<Utf8PathBuf, Error> {
Ok(path.to_path_buf())
}
fn read(&self, path: &Utf8Path) -> Result<String, Error> {
let path = path.to_path_buf();
let files = self.files.deref().borrow();
let buffer = files
.get(&path)
.and_then(|file| file.node.as_file_buffer())
.ok_or_else(|| Error::FileIo {
kind: FileKind::File,
action: FileIoAction::Open,
path: path.clone(),
err: None,
})?;
let bytes = buffer.borrow();
let unicode = String::from_utf8(bytes.clone()).map_err(|err| Error::FileIo {
kind: FileKind::File,
action: FileIoAction::Read,
path: path.clone(),
err: Some(err.to_string()),
})?;
Ok(unicode)
}
fn read_bytes(&self, path: &Utf8Path) -> Result<Vec<u8>, Error> {
let path = path.to_path_buf();
let files = self.files.deref().borrow();
let buffer = files
.get(&path)
.and_then(|file| file.node.as_file_buffer())
.ok_or_else(|| Error::FileIo {
kind: FileKind::File,
action: FileIoAction::Open,
path: path.clone(),
err: None,
})?;
let bytes = buffer.borrow().clone();
Ok(bytes)
}
fn is_file(&self, path: &Utf8Path) -> bool {
self.files
.deref()
.borrow()
.get(path)
.is_some_and(|file| !file.is_directory())
}
fn is_directory(&self, path: &Utf8Path) -> bool {
self.files
.deref()
.borrow()
.get(path)
.is_some_and(|file| file.is_directory())
}
fn reader(&self, _path: &Utf8Path) -> Result<WrappedReader, Error> {
// TODO
unreachable!("Memory reader unimplemented")
}
fn read_dir(&self, path: &Utf8Path) -> Result<ReadDir> {
let read_dir = ReadDir::from_iter(
self.files
.deref()
.borrow()
.keys()
.map(|file_path| file_path.to_path_buf())
.filter(|file_path| file_path.parent().is_some_and(|parent| path == parent))
.map(DirEntry::from_pathbuf)
.map(Ok),
);
Ok(read_dir)
}
fn modification_time(&self, path: &Utf8Path) -> Result<SystemTime, Error> {
let files = self.files.deref().borrow();
let file = files.get(path).ok_or_else(|| Error::FileIo {
kind: FileKind::File,
action: FileIoAction::ReadMetadata,
path: path.to_path_buf(),
err: None,
})?;
Ok(file.modification_time)
}
}
/// The representation of a file or directory in the in-memory filesystem.
///
/// Stores a file's buffer of contents.
///
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InMemoryFileNode {
File(Rc<RefCell<Vec<u8>>>),
Directory,
}
impl InMemoryFileNode {
/// Returns this file's file buffer if this isn't a directory.
fn as_file_buffer(&self) -> Option<&Rc<RefCell<Vec<u8>>>> {
match self {
Self::File(buffer) => Some(buffer),
Self::Directory => None,
}
}
/// Returns this file's file buffer if this isn't a directory.
fn into_file_buffer(self) -> Option<Rc<RefCell<Vec<u8>>>> {
match self {
Self::File(buffer) => Some(buffer),
Self::Directory => None,
}
}
}
/// An in memory sharable that can be used in place of a real file. It is a
/// shared reference to a buffer than can be cheaply cloned, all resulting copies
/// pointing to the same internal buffer.
///
/// Useful in tests and in environments like the browser where there is no file
/// system.
///
/// This struct holds common properties of different types of filesystem nodes
/// (files and directories). The `node` field contains the file's content
/// buffer, if this is not a directory.
///
/// Not thread safe. The compiler is single threaded, so that's OK.
///
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InMemoryFile {
node: InMemoryFileNode,
modification_time: SystemTime,
}
impl InMemoryFile {
/// Creates a directory.
pub fn directory() -> Self {
Self {
node: InMemoryFileNode::Directory,
..Default::default()
}
}
/// Checks whether this is a directory's entry.
pub fn is_directory(&self) -> bool {
matches!(self.node, InMemoryFileNode::Directory)
}
/// Returns this file's contents if this is not a directory.
///
/// # Panics
///
/// Panics if this is not the only reference to the underlying files.
///
pub fn into_content(self) -> Option<Content> {
let buffer = self.node.into_file_buffer()?;
let contents = Rc::try_unwrap(buffer)
.expect("InMemoryFile::into_content called with multiple references")
.into_inner();
// All null bytes are usually from when a binary file is empty, and
// aren't particularly useful as text, so we treat them as binary.
if contents.iter().all(|byte| *byte == 0) {
return Some(Content::Binary(contents));
}
match String::from_utf8(contents) {
Ok(s) => Some(Content::Text(s)),
Err(e) => Some(Content::Binary(e.into_bytes())),
}
}
}
impl Default for InMemoryFile {
fn default() -> Self {
Self {
node: InMemoryFileNode::File(Default::default()),
// We use a fixed time here so that the tests are deterministic. In
// future we may want to inject this in some fashion.
modification_time: SystemTime::UNIX_EPOCH + Duration::from_secs(663112800),
}
}
}
impl io::Write for InMemoryFile {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let Some(buffer) = self.node.as_file_buffer() else {
// Not a file
return Err(io::Error::from(io::ErrorKind::NotFound));
};
let mut reference = (*buffer).borrow_mut();
reference.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
let Some(buffer) = self.node.as_file_buffer() else {
// Not a file
return Err(io::Error::from(io::ErrorKind::NotFound));
};
let mut reference = (*buffer).borrow_mut();
reference.flush()
}
}
impl CommandExecutor for InMemoryFileSystem {
fn exec(&self, _command: Command) -> Result<i32, Error> {
Ok(0) // Always succeed.
}
}
impl BeamCompiler for InMemoryFileSystem {
fn compile_beam(
&self,
_out: &Utf8Path,
_lib: &Utf8Path,
_modules: &HashSet<Utf8PathBuf>,
_stdio: Stdio,
) -> Result<Vec<String>, Error> {
Ok(Vec::new()) // Always succeed.
}
}
#[test]
fn test_empty_in_memory_fs_has_root() {
let imfs = InMemoryFileSystem::new();
assert!(imfs.exists(Utf8Path::new("/")));
}
#[test]
fn test_cannot_remove_root_from_in_memory_fs() -> Result<(), Error> {
let imfs = InMemoryFileSystem::new();
imfs.write(&Utf8PathBuf::from("/a/b/c.txt"), "a")?;
imfs.delete_directory(Utf8Path::new("/"))?;
assert!(!imfs.exists(Utf8Path::new("/a/b/c.txt")));
assert!(imfs.exists(Utf8Path::new("/")));
Ok(())
}
#[test]
fn test_files() -> Result<(), Error> {
let imfs = InMemoryFileSystem::new();
imfs.write(&Utf8PathBuf::from("/a/b/c.txt"), "a")?;
imfs.write(&Utf8PathBuf::from("/d/e.txt"), "a")?;
let mut files = imfs.files();
// Sort for test determinism due to hash map usage.
files.sort_unstable();
assert_eq!(
vec![
Utf8PathBuf::from("/a/b/c.txt"),
Utf8PathBuf::from("/d/e.txt"),
],
files
);
Ok(())
}
#[test]
fn test_in_memory_dir_walking() -> Result<(), Error> {
use itertools::Itertools;
let imfs = InMemoryFileSystem::new();
imfs.write(&Utf8PathBuf::from("/a/b/a.txt"), "a")?;
imfs.write(&Utf8PathBuf::from("/a/b/b.txt"), "a")?;
imfs.write(&Utf8PathBuf::from("/a/b/c.txt"), "a")?;
imfs.write(&Utf8PathBuf::from("/b/d.txt"), "a")?;
imfs.write(&Utf8PathBuf::from("/a/c/e.txt"), "a")?;
imfs.write(&Utf8PathBuf::from("/a/c/d/f.txt"), "a")?;
imfs.write(&Utf8PathBuf::from("/a/g.txt"), "a")?;
imfs.write(&Utf8PathBuf::from("/h.txt"), "a")?;
imfs.mkdir(&Utf8PathBuf::from("/a/e"))?;
let mut walked_entries: Vec<String> = DirWalker::new(Utf8PathBuf::from("/a/"))
.into_file_iter(&imfs)
.map_ok(Utf8PathBuf::into_string)
.try_collect()?;
// Keep test deterministic due to hash map usage
walked_entries.sort_unstable();
assert_eq!(
vec![
"/a/b/a.txt".to_owned(),
"/a/b/b.txt".to_owned(),
"/a/b/c.txt".to_owned(),
"/a/c/d/f.txt".to_owned(),
"/a/c/e.txt".to_owned(),
"/a/g.txt".to_owned(),
],
walked_entries,
);
Ok(())
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/package_interface/tests.rs | compiler-core/src/package_interface/tests.rs | use std::time::SystemTime;
use camino::Utf8PathBuf;
use ecow::EcoString;
use globset::GlobBuilder;
use hexpm::version::Identifier;
use crate::{
analyse::TargetSupport,
build::{Module, Origin, Package, Target},
config::{Docs, ErlangConfig, GleamVersion, JavaScriptConfig, PackageConfig},
line_numbers::LineNumbers,
type_::PRELUDE_MODULE_NAME,
uid::UniqueIdGenerator,
warning::{TypeWarningEmitter, WarningEmitter},
};
use super::PackageInterface;
#[macro_export]
macro_rules! assert_package_interface_with_name {
($module_name:expr, $src:expr) => {
let output =
$crate::package_interface::tests::compile_package(Some($module_name), $src, None);
insta::assert_snapshot!(insta::internals::AutoName, output, $src);
};
}
#[macro_export]
macro_rules! assert_package_interface {
(($dep_package:expr, $dep_name:expr, $dep_src:expr), $src:expr $(,)?) => {{
let output = $crate::package_interface::tests::compile_package(
None,
$src,
Some(($dep_package, $dep_name, $dep_src)),
);
insta::assert_snapshot!(insta::internals::AutoName, output, $src);
}};
(($dep_package:expr, $dep_name:expr, $dep_src:expr), $src:expr $(,)?) => {{
let output = $crate::package_interface::tests::compile_package(
None,
$src,
Some(($dep_package, $dep_name, $dep_src)),
);
insta::assert_snapshot!(insta::internals::AutoName, output, $src);
}};
($src:expr) => {{
let output = $crate::package_interface::tests::compile_package(None, $src, None);
insta::assert_snapshot!(insta::internals::AutoName, output, $src);
}};
}
pub fn compile_package(
module_name: Option<&str>,
src: &str,
dep: Option<(&str, &str, &str)>,
) -> String {
let mut modules = im::HashMap::new();
let ids = UniqueIdGenerator::new();
// DUPE: preludeinsertion
// TODO: Currently we do this here and also in the tests. It would be better
// to have one place where we create all this required state for use in each
// place.
let _ = modules.insert(
PRELUDE_MODULE_NAME.into(),
crate::type_::build_prelude(&ids),
);
let mut direct_dependencies = std::collections::HashMap::from_iter(vec![]);
if let Some((dep_package, dep_name, dep_src)) = dep {
let parsed = crate::parse::parse_module(
Utf8PathBuf::from("test/path"),
dep_src,
&WarningEmitter::null(),
)
.expect("dep syntax error");
let mut ast = parsed.module;
ast.name = dep_name.into();
let line_numbers = LineNumbers::new(dep_src);
let mut config = PackageConfig::default();
config.name = dep_package.into();
let dep = crate::analyse::ModuleAnalyzerConstructor::<()> {
target: Target::Erlang,
ids: &ids,
origin: Origin::Src,
importable_modules: &modules,
warnings: &TypeWarningEmitter::null(),
direct_dependencies: &std::collections::HashMap::new(),
dev_dependencies: &std::collections::HashSet::new(),
target_support: TargetSupport::Enforced,
package_config: &config,
}
.infer_module(ast, line_numbers, "".into())
.expect("should successfully infer");
let _ = modules.insert(dep_name.into(), dep.type_info);
let _ = direct_dependencies.insert(dep_package.into(), ());
}
let parsed =
crate::parse::parse_module(Utf8PathBuf::from("test/path"), src, &WarningEmitter::null())
.expect("syntax error");
let mut ast = parsed.module;
let module_name = module_name
.map(EcoString::from)
.unwrap_or("my/module".into());
ast.name = module_name.clone();
let mut config = PackageConfig::default();
config.name = "my_package".into();
let ast = crate::analyse::ModuleAnalyzerConstructor {
target: Target::Erlang,
ids: &ids,
origin: Origin::Src,
importable_modules: &modules,
warnings: &TypeWarningEmitter::null(),
direct_dependencies: &direct_dependencies,
dev_dependencies: &std::collections::HashSet::new(),
target_support: TargetSupport::Enforced,
package_config: &config,
}
.infer_module(ast, LineNumbers::new(src), "".into())
.expect("should successfully infer");
// TODO: all the bits above are basically copy pasted from the javascript
// and erlang test helpers. A refactor might be due here.
let mut module = Module {
name: module_name,
code: src.into(),
mtime: SystemTime::UNIX_EPOCH,
input_path: "wibble".into(),
origin: Origin::Src,
ast,
extra: parsed.extra,
dependencies: vec![],
};
module.attach_doc_and_module_comments();
let package: Package = package_from_module(module);
serde_json::to_string_pretty(&PackageInterface::from_package(
&package,
&Default::default(),
))
.expect("to json")
}
fn package_from_module(module: Module) -> Package {
Package {
config: PackageConfig {
name: "my_package".into(),
version: hexpm::version::Version {
major: 11,
minor: 10,
patch: 9,
pre: vec![
Identifier::Numeric(1),
Identifier::AlphaNumeric("wibble".into()),
],
build: Some("build".into()),
},
gleam_version: Some(GleamVersion::new("1.0.0".to_string()).unwrap()),
licences: vec![],
description: "description".into(),
documentation: Docs { pages: vec![] },
dependencies: std::collections::HashMap::new(),
dev_dependencies: std::collections::HashMap::new(),
repository: None,
links: vec![],
erlang: ErlangConfig::default(),
javascript: JavaScriptConfig::default(),
target: Target::Erlang,
internal_modules: Some(vec![
GlobBuilder::new("internals/*")
.build()
.expect("internals glob"),
]),
},
cached_module_names: Vec::new(),
modules: vec![module],
}
}
#[test]
pub fn package_documentation_is_included() {
assert_package_interface!(
"
//// Some package
//// documentation!
pub fn main() { 1 }
"
);
}
#[test]
pub fn private_definitions_are_not_included() {
assert_package_interface!(
"
const float = 1.1
fn main() {}
type Wibble
type Wob = Int
"
);
}
#[test]
pub fn internal_definitions_are_not_included() {
assert_package_interface!(
"
@internal pub const float = 1.1
@internal pub fn main() {}
@internal pub type Wibble
@internal pub type Wobble = Int
"
);
}
#[test]
pub fn opaque_constructors_are_not_exposed() {
assert_package_interface!("pub opaque type Wibble { Wob }")
}
#[test]
pub fn type_aliases() {
assert_package_interface!("pub type Wibble(a) = List(a)")
}
#[test]
pub fn type_definition() {
assert_package_interface!(
"
/// Wibble's documentation
pub type Wibble(a, b) {
Wibble
Wobble
}
"
)
}
#[test]
pub fn prelude_types() {
assert_package_interface!(
r#"
pub const float = 1.1
pub const string = ""
pub const int = 1
pub const bool = True
"#
);
}
#[test]
pub fn generic_function() {
assert_package_interface!(
r#"
pub type Wob(a) { Wob }
@deprecated("deprecation message")
pub fn main() { Wob }
"#
);
}
#[test]
pub fn imported_type() {
assert_package_interface!(
("other_package", "other_module", "pub type Element(a)"),
r#"
import other_module.{type Element}
pub fn main() -> Element(Int) {}
"#
);
}
#[test]
pub fn imported_aliased_type_keeps_original_name() {
assert_package_interface!(
("other_package", "other_module", "pub type Element(a)"),
r#"
import other_module.{type Element as Alias} as module_alias
pub fn main() -> Alias(module_alias.Element(a)) {}
"#
);
}
#[test]
pub fn multiple_type_variables() {
assert_package_interface!(
r#"
pub type Box(a, b)
pub fn some_type_variables(a: a, b: b, c: Box(c, d)) -> Box(a, d) {}
"#
);
}
#[test]
pub fn type_constructors() {
assert_package_interface!(
r#"
pub type Box(a, b) {
Box(b, Int)
OtherBox(message: String, a: a)
}
"#
);
}
#[test]
pub fn internal_modules_are_not_exported() {
assert_package_interface_with_name!("internals/internal_module", "pub fn main() { 1 }");
}
#[test]
pub fn labelled_function_parameters() {
assert_package_interface!(
r#"
pub fn fold(list: List(a), from acc: b, with f: fn(a, b) -> b) -> b {
todo
}
"#
);
}
#[test]
pub fn constructors_with_documentation() {
assert_package_interface!(
r#"
pub type Wibble {
/// This is the Wibble variant. It contains some example data.
Wibble(Int)
/// This is the Wobble variant. It is a recursive type.
Wobble(Wibble)
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/ast/tests.rs | compiler-core/src/ast/tests.rs | use std::sync::Arc;
use camino::Utf8PathBuf;
use ecow::EcoString;
use crate::analyse::TargetSupport;
use crate::build::{ExpressionPosition, Origin, Target};
use crate::config::PackageConfig;
use crate::line_numbers::LineNumbers;
use crate::type_::error::{VariableDeclaration, VariableOrigin, VariableSyntax};
use crate::type_::expression::{FunctionDefinition, Purity};
use crate::type_::{Deprecation, PRELUDE_MODULE_NAME, Problems};
use crate::warning::WarningEmitter;
use crate::{
ast::{SrcSpan, TypedExpr},
build::Located,
type_::{
self, AccessorsMap, EnvironmentArguments, ExprTyper, FieldMap, ModuleValueConstructor,
RecordAccessor, Type, ValueConstructor, ValueConstructorVariant,
},
uid::UniqueIdGenerator,
warning::TypeWarningEmitter,
};
use super::{Publicity, Statement, TypedModule, TypedStatement};
fn compile_module(src: &str) -> TypedModule {
use crate::type_::build_prelude;
let parsed =
crate::parse::parse_module(Utf8PathBuf::from("test/path"), src, &WarningEmitter::null())
.expect("syntax error");
let ast = parsed.module;
let ids = UniqueIdGenerator::new();
let mut config = PackageConfig::default();
config.name = "thepackage".into();
let mut modules = im::HashMap::new();
// DUPE: preludeinsertion
// TODO: Currently we do this here and also in the tests. It would be better
// to have one place where we create all this required state for use in each
// place.
let _ = modules.insert(PRELUDE_MODULE_NAME.into(), build_prelude(&ids));
let line_numbers = LineNumbers::new(src);
let mut config = PackageConfig::default();
config.name = "thepackage".into();
crate::analyse::ModuleAnalyzerConstructor::<()> {
target: Target::Erlang,
ids: &ids,
origin: Origin::Src,
importable_modules: &modules,
warnings: &TypeWarningEmitter::null(),
direct_dependencies: &std::collections::HashMap::new(),
dev_dependencies: &std::collections::HashSet::new(),
target_support: TargetSupport::Enforced,
package_config: &config,
}
.infer_module(ast, line_numbers, "".into())
.expect("should successfully infer")
}
fn get_bare_expression(statement: &TypedStatement) -> &TypedExpr {
match statement {
Statement::Expression(expression) => expression,
Statement::Use(_) | Statement::Assignment(_) | Statement::Assert(_) => {
panic!("Expected expression, got {statement:?}")
}
}
}
fn compile_expression(src: &str) -> TypedStatement {
let ast = crate::parse::parse_statement_sequence(src).expect("syntax error");
let mut modules = im::HashMap::new();
let ids = UniqueIdGenerator::new();
// DUPE: preludeinsertion
// TODO: Currently we do this here and also in the tests. It would be better
// to have one place where we create all this required state for use in each
// place.
let _ = modules.insert(PRELUDE_MODULE_NAME.into(), type_::build_prelude(&ids));
let dev_dependencies = std::collections::HashSet::new();
let mut environment = EnvironmentArguments {
ids,
current_package: "thepackage".into(),
gleam_version: None,
current_module: "mymod".into(),
target: Target::Erlang,
importable_modules: &modules,
target_support: TargetSupport::Enforced,
current_origin: Origin::Src,
dev_dependencies: &dev_dependencies,
}
.build();
// Insert a cat record to use in the tests
let cat_type = Arc::new(Type::Named {
publicity: Publicity::Public,
package: "mypackage".into(),
module: "mymod".into(),
name: "Cat".into(),
arguments: vec![],
inferred_variant: None,
});
let variant = ValueConstructorVariant::Record {
documentation: Some("wibble".into()),
variants_count: 1,
name: "Cat".into(),
arity: 2,
location: SrcSpan { start: 12, end: 15 },
field_map: Some(FieldMap {
arity: 2,
fields: [("name".into(), 0), ("age".into(), 1)].into(),
}),
module: "mymod".into(),
variant_index: 0,
};
environment.insert_variable(
"Cat".into(),
variant,
type_::fn_(vec![type_::string(), type_::int()], cat_type.clone()),
Publicity::Public,
Deprecation::NotDeprecated,
);
let accessors = [
(
"name".into(),
RecordAccessor {
index: 0,
label: "name".into(),
type_: type_::string(),
documentation: None,
},
),
(
"age".into(),
RecordAccessor {
index: 1,
label: "age".into(),
type_: type_::int(),
documentation: None,
},
),
];
environment.insert_accessors(
"Cat".into(),
AccessorsMap {
publicity: Publicity::Public,
type_: cat_type,
shared_accessors: accessors.clone().into(),
variant_specific_accessors: vec![accessors.into()],
variant_positional_accessors: vec![vec![]],
},
);
let mut problems = Problems::new();
ExprTyper::new(
&mut environment,
FunctionDefinition {
has_body: true,
has_erlang_external: false,
has_javascript_external: false,
},
&mut problems,
)
.infer_statements(ast)
.first()
.clone()
}
#[test]
fn find_node_todo() {
let statement = compile_expression(r#" todo "#);
let expr = get_bare_expression(&statement);
assert_eq!(expr.find_node(0), None);
assert_eq!(
expr.find_node(1),
Some(Located::Expression {
expression: expr,
position: ExpressionPosition::Expression
})
);
assert_eq!(
expr.find_node(4),
Some(Located::Expression {
expression: expr,
position: ExpressionPosition::Expression
})
);
assert_eq!(
expr.find_node(5),
Some(Located::Expression {
expression: expr,
position: ExpressionPosition::Expression
})
);
assert_eq!(expr.find_node(6), None);
}
#[test]
fn find_node_todo_with_string() {
let statement = compile_expression(r#" todo as "ok" "#);
let expr = get_bare_expression(&statement);
let message = TypedExpr::String {
location: SrcSpan { start: 9, end: 13 },
type_: type_::string(),
value: "ok".into(),
};
assert_eq!(expr.find_node(0), None);
assert_eq!(
expr.find_node(1),
Some(Located::Expression {
expression: expr,
position: ExpressionPosition::Expression
})
);
assert_eq!(
expr.find_node(12),
Some(Located::Expression {
expression: &message,
position: ExpressionPosition::Expression
})
);
assert_eq!(
expr.find_node(13),
Some(Located::Expression {
expression: &message,
position: ExpressionPosition::Expression
})
);
assert_eq!(expr.find_node(14), None);
}
#[test]
fn find_node_string() {
let statement = compile_expression(r#" "ok" "#);
let expr = get_bare_expression(&statement);
assert_eq!(expr.find_node(0), None);
assert_eq!(
expr.find_node(1),
Some(Located::Expression {
expression: expr,
position: ExpressionPosition::Expression
})
);
assert_eq!(
expr.find_node(4),
Some(Located::Expression {
expression: expr,
position: ExpressionPosition::Expression
})
);
assert_eq!(
expr.find_node(5),
Some(Located::Expression {
expression: expr,
position: ExpressionPosition::Expression
})
);
assert_eq!(expr.find_node(6), None);
}
#[test]
fn find_node_float() {
let statement = compile_expression(r#" 1.02 "#);
let expr = get_bare_expression(&statement);
assert_eq!(expr.find_node(0), None);
assert_eq!(
expr.find_node(1),
Some(Located::Expression {
expression: expr,
position: ExpressionPosition::Expression
})
);
assert_eq!(
expr.find_node(4),
Some(Located::Expression {
expression: expr,
position: ExpressionPosition::Expression
})
);
assert_eq!(
expr.find_node(5),
Some(Located::Expression {
expression: expr,
position: ExpressionPosition::Expression
})
);
assert_eq!(expr.find_node(6), None);
}
#[test]
fn find_node_int() {
let statement = compile_expression(r#" 1302 "#);
let expr = get_bare_expression(&statement);
assert_eq!(expr.find_node(0), None);
assert_eq!(
expr.find_node(1),
Some(Located::Expression {
expression: expr,
position: ExpressionPosition::Expression
})
);
assert_eq!(
expr.find_node(4),
Some(Located::Expression {
expression: expr,
position: ExpressionPosition::Expression
})
);
assert_eq!(
expr.find_node(5),
Some(Located::Expression {
expression: expr,
position: ExpressionPosition::Expression
})
);
assert_eq!(expr.find_node(6), None);
}
#[test]
fn find_node_var() {
let statement = compile_expression(
r#"{let wibble = 1
wibble}"#,
);
let expr = get_bare_expression(&statement);
let int1 = TypedExpr::Int {
location: SrcSpan { start: 14, end: 15 },
value: "1".into(),
int_value: 1.into(),
type_: type_::int(),
};
let var = TypedExpr::Var {
location: SrcSpan { start: 16, end: 22 },
constructor: ValueConstructor {
deprecation: Deprecation::NotDeprecated,
publicity: Publicity::Private,
variant: ValueConstructorVariant::LocalVariable {
location: SrcSpan { start: 5, end: 11 },
origin: VariableOrigin {
syntax: VariableSyntax::Variable("wibble".into()),
declaration: VariableDeclaration::LetPattern,
},
},
type_: type_::int(),
},
name: "wibble".into(),
};
assert_eq!(
expr.find_node(15),
Some(Located::Expression {
expression: &int1,
position: ExpressionPosition::Expression
})
);
assert_eq!(
expr.find_node(16),
Some(Located::Expression {
expression: &var,
position: ExpressionPosition::Expression
})
);
assert_eq!(
expr.find_node(21),
Some(Located::Expression {
expression: &var,
position: ExpressionPosition::Expression
})
);
assert_eq!(
expr.find_node(22),
Some(Located::Expression {
expression: &var,
position: ExpressionPosition::Expression
})
);
}
#[test]
fn find_node_sequence() {
let block = compile_expression(r#"{ 1 2 3 }"#);
assert!(block.find_node(0).is_none());
assert!(block.find_node(1).is_none());
assert!(block.find_node(2).is_some());
assert!(block.find_node(3).is_some());
assert!(block.find_node(4).is_some());
assert!(block.find_node(5).is_some());
assert!(block.find_node(6).is_some());
assert!(block.find_node(7).is_some());
}
#[test]
fn find_node_list() {
let statement = compile_expression(r#"[1, 2, 3]"#);
let list = get_bare_expression(&statement);
let int1 = TypedExpr::Int {
location: SrcSpan { start: 1, end: 2 },
type_: type_::int(),
value: "1".into(),
int_value: 1.into(),
};
let int2 = TypedExpr::Int {
location: SrcSpan { start: 4, end: 5 },
type_: type_::int(),
value: "2".into(),
int_value: 2.into(),
};
let int3 = TypedExpr::Int {
location: SrcSpan { start: 7, end: 8 },
type_: type_::int(),
value: "3".into(),
int_value: 3.into(),
};
assert_eq!(
list.find_node(0),
Some(Located::Expression {
expression: list,
position: ExpressionPosition::Expression
})
);
assert_eq!(
list.find_node(1),
Some(Located::Expression {
expression: &int1,
position: ExpressionPosition::Expression
})
);
assert_eq!(
list.find_node(2),
Some(Located::Expression {
expression: &int1,
position: ExpressionPosition::Expression
})
);
assert_eq!(
list.find_node(3),
Some(Located::Expression {
expression: list,
position: ExpressionPosition::Expression
})
);
assert_eq!(
list.find_node(4),
Some(Located::Expression {
expression: &int2,
position: ExpressionPosition::Expression
})
);
assert_eq!(
list.find_node(5),
Some(Located::Expression {
expression: &int2,
position: ExpressionPosition::Expression
})
);
assert_eq!(
list.find_node(6),
Some(Located::Expression {
expression: list,
position: ExpressionPosition::Expression
})
);
assert_eq!(
list.find_node(7),
Some(Located::Expression {
expression: &int3,
position: ExpressionPosition::Expression
})
);
assert_eq!(
list.find_node(8),
Some(Located::Expression {
expression: &int3,
position: ExpressionPosition::Expression
})
);
assert_eq!(
list.find_node(9),
Some(Located::Expression {
expression: list,
position: ExpressionPosition::Expression
})
);
}
#[test]
fn find_node_tuple() {
let statement = compile_expression(r#"#(1, 2, 3)"#);
let tuple = get_bare_expression(&statement);
let int1 = TypedExpr::Int {
location: SrcSpan { start: 2, end: 3 },
type_: type_::int(),
value: "1".into(),
int_value: 1.into(),
};
let int2 = TypedExpr::Int {
location: SrcSpan { start: 5, end: 6 },
type_: type_::int(),
value: "2".into(),
int_value: 2.into(),
};
let int3 = TypedExpr::Int {
location: SrcSpan { start: 8, end: 9 },
type_: type_::int(),
value: "3".into(),
int_value: 3.into(),
};
assert_eq!(
tuple.find_node(0),
Some(Located::Expression {
expression: tuple,
position: ExpressionPosition::Expression
})
);
assert_eq!(
tuple.find_node(1),
Some(Located::Expression {
expression: tuple,
position: ExpressionPosition::Expression
})
);
assert_eq!(
tuple.find_node(2),
Some(Located::Expression {
expression: &int1,
position: ExpressionPosition::Expression
})
);
assert_eq!(
tuple.find_node(3),
Some(Located::Expression {
expression: &int1,
position: ExpressionPosition::Expression
})
);
assert_eq!(
tuple.find_node(4),
Some(Located::Expression {
expression: tuple,
position: ExpressionPosition::Expression
})
);
assert_eq!(
tuple.find_node(5),
Some(Located::Expression {
expression: &int2,
position: ExpressionPosition::Expression
})
);
assert_eq!(
tuple.find_node(6),
Some(Located::Expression {
expression: &int2,
position: ExpressionPosition::Expression
})
);
assert_eq!(
tuple.find_node(7),
Some(Located::Expression {
expression: tuple,
position: ExpressionPosition::Expression
})
);
assert_eq!(
tuple.find_node(8),
Some(Located::Expression {
expression: &int3,
position: ExpressionPosition::Expression
})
);
assert_eq!(
tuple.find_node(9),
Some(Located::Expression {
expression: &int3,
position: ExpressionPosition::Expression
})
);
assert_eq!(
tuple.find_node(10),
Some(Located::Expression {
expression: tuple,
position: ExpressionPosition::Expression
})
);
}
#[test]
fn find_node_binop() {
let statement = compile_expression(r#"1 + 2"#);
let expr = get_bare_expression(&statement);
assert!(expr.find_node(0).is_some());
assert!(expr.find_node(1).is_some());
assert!(expr.find_node(2).is_none());
assert!(expr.find_node(3).is_none());
assert!(expr.find_node(4).is_some());
assert!(expr.find_node(5).is_some());
}
#[test]
fn find_node_tuple_index() {
let statement = compile_expression(r#"#(1).0"#);
let expr = get_bare_expression(&statement);
let int = TypedExpr::Int {
location: SrcSpan { start: 2, end: 3 },
value: "1".into(),
int_value: 1.into(),
type_: type_::int(),
};
assert_eq!(
expr.find_node(2),
Some(Located::Expression {
expression: &int,
position: ExpressionPosition::Expression
})
);
assert_eq!(
expr.find_node(5),
Some(Located::Expression {
expression: expr,
position: ExpressionPosition::Expression
})
);
assert_eq!(
expr.find_node(6),
Some(Located::Expression {
expression: expr,
position: ExpressionPosition::Expression
})
);
}
#[test]
fn find_node_module_select() {
let expr = TypedExpr::ModuleSelect {
location: SrcSpan { start: 1, end: 4 },
field_start: 2,
type_: type_::int(),
label: "label".into(),
module_name: "name".into(),
module_alias: "alias".into(),
constructor: ModuleValueConstructor::Fn {
module: "module".into(),
name: "function".into(),
external_erlang: None,
external_javascript: None,
location: SrcSpan { start: 1, end: 55 },
documentation: None,
field_map: None,
purity: Purity::Pure,
},
};
assert_eq!(expr.find_node(0), None);
assert_eq!(
expr.find_node(1),
Some(Located::ModuleName {
location: SrcSpan::new(1, 1),
name: &"name".into(),
layer: super::Layer::Value
})
);
assert_eq!(
expr.find_node(2),
Some(Located::Expression {
expression: &expr,
position: ExpressionPosition::Expression
})
);
assert_eq!(
expr.find_node(3),
Some(Located::Expression {
expression: &expr,
position: ExpressionPosition::Expression
})
);
}
#[test]
fn find_node_fn() {
let statement = compile_expression("fn() { 1 }");
let expr = get_bare_expression(&statement);
let int = TypedExpr::Int {
location: SrcSpan { start: 7, end: 8 },
value: "1".into(),
int_value: 1.into(),
type_: type_::int(),
};
assert_eq!(
expr.find_node(0),
Some(Located::Expression {
expression: expr,
position: ExpressionPosition::Expression
})
);
assert_eq!(
expr.find_node(6),
Some(Located::Expression {
expression: expr,
position: ExpressionPosition::Expression
})
);
assert_eq!(
expr.find_node(7),
Some(Located::Expression {
expression: &int,
position: ExpressionPosition::Expression
})
);
assert_eq!(
expr.find_node(8),
Some(Located::Expression {
expression: &int,
position: ExpressionPosition::Expression
})
);
assert_eq!(
expr.find_node(9),
Some(Located::Expression {
expression: expr,
position: ExpressionPosition::Expression
})
);
assert_eq!(
expr.find_node(10),
Some(Located::Expression {
expression: expr,
position: ExpressionPosition::Expression
})
);
}
#[test]
fn find_node_call() {
let statement = compile_expression("fn(_, _) { 1 }(1, 2)");
let expr = get_bare_expression(&statement);
let return_ = TypedExpr::Int {
location: SrcSpan { start: 11, end: 12 },
value: "1".into(),
int_value: 1.into(),
type_: type_::int(),
};
let arg1 = TypedExpr::Int {
location: SrcSpan { start: 15, end: 16 },
value: "1".into(),
int_value: 1.into(),
type_: type_::int(),
};
let arg2 = TypedExpr::Int {
location: SrcSpan { start: 18, end: 19 },
value: "2".into(),
int_value: 2.into(),
type_: type_::int(),
};
let TypedExpr::Call {
fun: called_function,
arguments: function_arguments,
..
} = expr
else {
panic!("Expression was not a function call");
};
assert_eq!(
expr.find_node(11),
Some(Located::Expression {
expression: &return_,
position: ExpressionPosition::Expression
})
);
assert_eq!(
expr.find_node(15),
Some(Located::Expression {
expression: &arg1,
position: ExpressionPosition::Expression
})
);
assert_eq!(
expr.find_node(16),
Some(Located::Expression {
expression: &arg1,
position: ExpressionPosition::ArgumentOrLabel {
called_function,
function_arguments
}
})
);
assert_eq!(
expr.find_node(17),
Some(Located::Expression {
expression: expr,
position: ExpressionPosition::Expression
})
);
assert_eq!(
expr.find_node(18),
Some(Located::Expression {
expression: &arg2,
position: ExpressionPosition::Expression
})
);
assert_eq!(
expr.find_node(19),
Some(Located::Expression {
expression: &arg2,
position: ExpressionPosition::ArgumentOrLabel {
called_function,
function_arguments
}
})
);
assert_eq!(
expr.find_node(20),
Some(Located::Expression {
expression: expr,
position: ExpressionPosition::Expression
})
);
}
#[test]
fn find_node_record_access() {
let statement = compile_expression(r#"Cat("Nubi", 3).name"#);
let access = get_bare_expression(&statement);
let string = TypedExpr::String {
location: SrcSpan { start: 4, end: 10 },
value: "Nubi".into(),
type_: type_::string(),
};
let int = TypedExpr::Int {
location: SrcSpan { start: 12, end: 13 },
value: "3".into(),
int_value: 3.into(),
type_: type_::int(),
};
assert_eq!(
access.find_node(4),
Some(Located::Expression {
expression: &string,
position: ExpressionPosition::Expression
})
);
assert_eq!(
access.find_node(9),
Some(Located::Expression {
expression: &string,
position: ExpressionPosition::Expression
})
);
assert_eq!(
access.find_node(12),
Some(Located::Expression {
expression: &int,
position: ExpressionPosition::Expression
})
);
assert_eq!(
access.find_node(15),
Some(Located::Expression {
expression: access,
position: ExpressionPosition::Expression
})
);
assert_eq!(
access.find_node(18),
Some(Located::Expression {
expression: access,
position: ExpressionPosition::Expression
})
);
assert_eq!(
access.find_node(19),
Some(Located::Expression {
expression: access,
position: ExpressionPosition::Expression
})
);
}
#[test]
fn find_node_record_update() {
let statement = compile_expression(r#"Cat(..Cat("Nubi", 3), age: 4)"#);
let update = get_bare_expression(&statement);
let cat = TypedExpr::Var {
location: SrcSpan { start: 0, end: 3 },
constructor: ValueConstructor {
publicity: Publicity::Public,
deprecation: Deprecation::NotDeprecated,
variant: ValueConstructorVariant::Record {
name: "Cat".into(),
arity: 2,
field_map: Some(FieldMap {
arity: 2,
fields: [(EcoString::from("age"), 1), (EcoString::from("name"), 0)].into(),
}),
location: SrcSpan { start: 12, end: 15 },
module: "mymod".into(),
variants_count: 1,
variant_index: 0,
documentation: Some("wibble".into()),
},
type_: type_::fn_(
vec![type_::string(), type_::int()],
type_::named("mypackage", "mymod", "Cat", Publicity::Public, vec![]),
),
},
name: "Cat".into(),
};
let int = TypedExpr::Int {
location: SrcSpan { start: 27, end: 28 },
value: "4".into(),
int_value: 4.into(),
type_: type_::int(),
};
assert_eq!(
update.find_node(0),
Some(Located::Expression {
expression: &cat,
position: ExpressionPosition::Expression
})
);
assert_eq!(
update.find_node(3),
Some(Located::Expression {
expression: &cat,
position: ExpressionPosition::Expression
})
);
assert_eq!(
update.find_node(27),
Some(Located::Expression {
expression: &int,
position: ExpressionPosition::Expression
})
);
assert_eq!(
update.find_node(28),
Some(Located::Expression {
expression: &int,
position: ExpressionPosition::Expression
})
);
assert_eq!(
update.find_node(29),
Some(Located::Expression {
expression: update,
position: ExpressionPosition::Expression
})
);
}
#[test]
fn find_node_case() {
let statement = compile_expression(
r#"
case 1, 2 {
_, _ -> 3
}
"#,
);
let case = get_bare_expression(&statement);
let int1 = TypedExpr::Int {
location: SrcSpan { start: 6, end: 7 },
value: "1".into(),
int_value: 1.into(),
type_: type_::int(),
};
let int2 = TypedExpr::Int {
location: SrcSpan { start: 9, end: 10 },
value: "2".into(),
int_value: 2.into(),
type_: type_::int(),
};
let int3 = TypedExpr::Int {
location: SrcSpan { start: 23, end: 24 },
value: "3".into(),
int_value: 3.into(),
type_: type_::int(),
};
assert_eq!(
case.find_node(1),
Some(Located::Expression {
expression: case,
position: ExpressionPosition::Expression
})
);
assert_eq!(
case.find_node(6),
Some(Located::Expression {
expression: &int1,
position: ExpressionPosition::Expression
})
);
assert_eq!(
case.find_node(9),
Some(Located::Expression {
expression: &int2,
position: ExpressionPosition::Expression
})
);
assert_eq!(
case.find_node(23),
Some(Located::Expression {
expression: &int3,
position: ExpressionPosition::Expression
})
);
assert_eq!(
case.find_node(25),
Some(Located::Expression {
expression: case,
position: ExpressionPosition::Expression
})
);
assert_eq!(
case.find_node(26),
Some(Located::Expression {
expression: case,
position: ExpressionPosition::Expression
})
);
assert_eq!(case.find_node(27), None);
}
#[test]
fn find_node_bool() {
let statement = compile_expression(r#"!True"#);
let negate = get_bare_expression(&statement);
let bool = TypedExpr::Var {
location: SrcSpan { start: 1, end: 5 },
constructor: ValueConstructor {
deprecation: Deprecation::NotDeprecated,
publicity: Publicity::Public,
variant: ValueConstructorVariant::Record {
documentation: None,
variants_count: 2,
name: "True".into(),
arity: 0,
field_map: None,
location: SrcSpan { start: 0, end: 0 },
module: PRELUDE_MODULE_NAME.into(),
variant_index: 0,
},
type_: type_::bool_with_variant(Some(true)),
},
name: "True".into(),
};
assert_eq!(
negate.find_node(0),
Some(Located::Expression {
expression: negate,
position: ExpressionPosition::Expression
})
);
assert_eq!(
negate.find_node(1),
Some(Located::Expression {
expression: &bool,
position: ExpressionPosition::Expression
})
);
assert_eq!(
negate.find_node(2),
Some(Located::Expression {
expression: &bool,
position: ExpressionPosition::Expression
})
);
assert_eq!(
negate.find_node(3),
Some(Located::Expression {
expression: &bool,
position: ExpressionPosition::Expression
})
);
assert_eq!(
negate.find_node(4),
Some(Located::Expression {
expression: &bool,
position: ExpressionPosition::Expression
})
);
assert_eq!(
negate.find_node(5),
Some(Located::Expression {
expression: &bool,
position: ExpressionPosition::Expression
})
);
}
#[test]
fn find_node_statement_fn() {
let module = compile_module(
r#"
pub fn main() {
Nil
}
"#,
);
assert!(module.find_node(0).is_none());
assert!(module.find_node(1).is_none());
// The fn
assert!(module.find_node(2).is_some());
assert!(module.find_node(24).is_some());
assert!(module.find_node(25).is_some());
assert!(module.find_node(26).is_none());
}
#[test]
fn find_node_statement_import() {
let module = compile_module(
r#"
import gleam
"#,
);
assert!(module.find_node(0).is_none());
// The import
assert!(module.find_node(1).is_some());
assert!(module.find_node(12).is_some());
assert!(module.find_node(13).is_some());
assert!(module.find_node(14).is_none());
}
#[test]
fn find_node_use() {
let use_ = compile_expression(
r#"
use x <- fn(f) { f(1) }
124
"#,
);
assert!(use_.find_node(0).is_none());
assert!(use_.find_node(1).is_some()); // The use
assert!(use_.find_node(23).is_some());
assert!(use_.find_node(26).is_some()); // The int
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/ast/visit.rs | compiler-core/src/ast/visit.rs | //! AST traversal routines, referenced from [`syn::visit`](https://docs.rs/syn/latest/syn/visit/index.html)
//!
//! Each method of the [`Visit`] trait can be overriden to customize the
//! behaviour when visiting the corresponding type of AST node. By default,
//! every method recursively visits the substructure of the node by using the
//! right visitor method.
//!
//! # Example
//!
//! Suppose we would like to collect all function names in a module,
//! we can do the following:
//!
//! ```no_run
//! use gleam_core::ast::{TypedFunction, visit::{self, Visit}};
//!
//! struct FnCollector<'ast> {
//! functions: Vec<&'ast TypedFunction>
//! }
//!
//! impl<'ast> Visit<'ast> for FnCollector<'ast> {
//! fn visit_typed_function(&mut self, fun: &'ast TypedFunction) {
//! self.functions.push(fun);
//!
//! // Use the default behaviour to visit any nested functions
//! visit::visit_typed_function(self, fun);
//! }
//! }
//!
//! fn print_all_module_functions() {
//! let module = todo!("module");
//! let mut fn_collector = FnCollector { functions: vec![] };
//!
//! // This will walk the AST and collect all functions
//! fn_collector.visit_typed_module(module);
//!
//! // Print the collected functions
//! println!("{:#?}", fn_collector.functions);
//! }
//! ```
use crate::{
analyse::Inferred,
ast::{
BitArraySize, RecordBeingUpdated, TypedBitArraySize, TypedConstantBitArraySegment,
TypedDefinitions, TypedTailPattern, typed::InvalidExpression,
},
exhaustiveness::CompiledCase,
parse::LiteralFloatValue,
type_::{
FieldMap, ModuleValueConstructor, PatternConstructor, TypedCallArg, ValueConstructor,
error::VariableOrigin,
},
};
use std::sync::Arc;
use ecow::EcoString;
use num_bigint::BigInt;
use vec1::Vec1;
use crate::type_::Type;
use super::{
AssignName, BinOp, BitArrayOption, CallArg, Pattern, PipelineAssignmentKind, RecordUpdateArg,
SrcSpan, Statement, TodoKind, TypeAst, TypedArg, TypedAssert, TypedAssignment, TypedClause,
TypedClauseGuard, TypedConstant, TypedCustomType, TypedExpr, TypedExprBitArraySegment,
TypedFunction, TypedModule, TypedModuleConstant, TypedPattern, TypedPatternBitArraySegment,
TypedPipelineAssignment, TypedStatement, TypedUse, untyped::FunctionLiteralKind,
};
pub trait Visit<'ast> {
fn visit_typed_module(&mut self, module: &'ast TypedModule) {
visit_typed_module(self, module);
}
fn visit_typed_function(&mut self, fun: &'ast TypedFunction) {
visit_typed_function(self, fun);
}
fn visit_typed_module_constant(&mut self, constant: &'ast TypedModuleConstant) {
visit_typed_module_constant(self, constant);
}
fn visit_typed_custom_type(&mut self, custom_type: &'ast TypedCustomType) {
visit_typed_custom_type(self, custom_type);
}
fn visit_typed_expr(&mut self, expr: &'ast TypedExpr) {
visit_typed_expr(self, expr);
}
fn visit_typed_expr_echo(
&mut self,
location: &'ast SrcSpan,
type_: &'ast Arc<Type>,
expression: &'ast Option<Box<TypedExpr>>,
message: &'ast Option<Box<TypedExpr>>,
) {
visit_typed_expr_echo(self, location, type_, expression, message);
}
fn visit_typed_expr_int(
&mut self,
location: &'ast SrcSpan,
type_: &'ast Arc<Type>,
value: &'ast EcoString,
) {
visit_typed_expr_int(self, location, type_, value);
}
fn visit_typed_expr_float(
&mut self,
location: &'ast SrcSpan,
type_: &'ast Arc<Type>,
value: &'ast EcoString,
) {
visit_typed_expr_float(self, location, type_, value);
}
fn visit_typed_expr_string(
&mut self,
location: &'ast SrcSpan,
type_: &'ast Arc<Type>,
value: &'ast EcoString,
) {
visit_typed_expr_string(self, location, type_, value);
}
fn visit_typed_expr_block(
&mut self,
location: &'ast SrcSpan,
statements: &'ast [TypedStatement],
) {
visit_typed_expr_block(self, location, statements);
}
fn visit_typed_expr_pipeline(
&mut self,
location: &'ast SrcSpan,
first_value: &'ast TypedPipelineAssignment,
assignments: &'ast [(TypedPipelineAssignment, PipelineAssignmentKind)],
finally: &'ast TypedExpr,
finally_kind: &'ast PipelineAssignmentKind,
) {
visit_typed_expr_pipeline(
self,
location,
first_value,
assignments,
finally,
finally_kind,
);
}
fn visit_typed_expr_var(
&mut self,
location: &'ast SrcSpan,
constructor: &'ast ValueConstructor,
name: &'ast EcoString,
) {
visit_typed_expr_var(self, location, constructor, name);
}
fn visit_typed_expr_fn(
&mut self,
location: &'ast SrcSpan,
type_: &'ast Arc<Type>,
kind: &'ast FunctionLiteralKind,
arguments: &'ast [TypedArg],
body: &'ast Vec1<TypedStatement>,
return_annotation: &'ast Option<TypeAst>,
) {
visit_typed_expr_fn(
self,
location,
type_,
kind,
arguments,
body,
return_annotation,
);
}
fn visit_typed_expr_list(
&mut self,
location: &'ast SrcSpan,
type_: &'ast Arc<Type>,
elements: &'ast [TypedExpr],
tail: &'ast Option<Box<TypedExpr>>,
) {
visit_typed_expr_list(self, location, type_, elements, tail);
}
fn visit_typed_expr_call(
&mut self,
location: &'ast SrcSpan,
type_: &'ast Arc<Type>,
fun: &'ast TypedExpr,
arguments: &'ast [TypedCallArg],
) {
visit_typed_expr_call(self, location, type_, fun, arguments);
}
fn visit_typed_expr_bin_op(
&mut self,
location: &'ast SrcSpan,
type_: &'ast Arc<Type>,
name: &'ast BinOp,
name_location: &'ast SrcSpan,
left: &'ast TypedExpr,
right: &'ast TypedExpr,
) {
visit_typed_expr_bin_op(self, location, type_, name, name_location, left, right);
}
fn visit_typed_expr_case(
&mut self,
location: &'ast SrcSpan,
type_: &'ast Arc<Type>,
subjects: &'ast [TypedExpr],
clauses: &'ast [TypedClause],
compiled_case: &'ast CompiledCase,
) {
visit_typed_expr_case(self, location, type_, subjects, clauses, compiled_case);
}
#[allow(clippy::too_many_arguments)]
fn visit_typed_expr_record_access(
&mut self,
location: &'ast SrcSpan,
field_start: &'ast u32,
type_: &'ast Arc<Type>,
label: &'ast EcoString,
index: &'ast u64,
record: &'ast TypedExpr,
documentation: &'ast Option<EcoString>,
) {
visit_typed_expr_record_access(
self,
location,
field_start,
type_,
label,
index,
record,
documentation,
);
}
#[allow(clippy::too_many_arguments)]
fn visit_typed_expr_module_select(
&mut self,
location: &'ast SrcSpan,
field_start: &'ast u32,
type_: &'ast Arc<Type>,
label: &'ast EcoString,
module_name: &'ast EcoString,
module_alias: &'ast EcoString,
constructor: &'ast ModuleValueConstructor,
) {
visit_typed_expr_module_select(
self,
location,
field_start,
type_,
label,
module_name,
module_alias,
constructor,
);
}
fn visit_typed_expr_tuple(
&mut self,
location: &'ast SrcSpan,
type_: &'ast Arc<Type>,
elements: &'ast [TypedExpr],
) {
visit_typed_expr_tuple(self, location, type_, elements);
}
fn visit_typed_expr_tuple_index(
&mut self,
location: &'ast SrcSpan,
type_: &'ast Arc<Type>,
index: &'ast u64,
tuple: &'ast TypedExpr,
) {
visit_typed_expr_tuple_index(self, location, type_, index, tuple);
}
fn visit_typed_expr_todo(
&mut self,
location: &'ast SrcSpan,
message: &'ast Option<Box<TypedExpr>>,
kind: &'ast TodoKind,
type_: &'ast Arc<Type>,
) {
visit_typed_expr_todo(self, location, message, kind, type_);
}
fn visit_typed_expr_panic(
&mut self,
location: &'ast SrcSpan,
message: &'ast Option<Box<TypedExpr>>,
type_: &'ast Arc<Type>,
) {
visit_typed_expr_panic(self, location, message, type_);
}
fn visit_typed_expr_bit_array(
&mut self,
location: &'ast SrcSpan,
type_: &'ast Arc<Type>,
segments: &'ast [TypedExprBitArraySegment],
) {
visit_typed_expr_bit_array(self, location, type_, segments);
}
fn visit_typed_expr_record_update(
&mut self,
location: &'ast SrcSpan,
type_: &'ast Arc<Type>,
record: &'ast Option<Box<TypedAssignment>>,
constructor: &'ast TypedExpr,
arguments: &'ast [TypedCallArg],
) {
visit_typed_expr_record_update(self, location, type_, record, constructor, arguments);
}
fn visit_typed_expr_negate_bool(&mut self, location: &'ast SrcSpan, value: &'ast TypedExpr) {
visit_typed_expr_negate_bool(self, location, value);
}
fn visit_typed_expr_negate_int(&mut self, location: &'ast SrcSpan, value: &'ast TypedExpr) {
visit_typed_expr_negate_int(self, location, value)
}
fn visit_typed_expr_invalid(
&mut self,
location: &'ast SrcSpan,
type_: &'ast Arc<Type>,
extra_information: &'ast Option<InvalidExpression>,
) {
visit_typed_expr_invalid(self, location, type_, extra_information);
}
fn visit_typed_statement(&mut self, statement: &'ast TypedStatement) {
visit_typed_statement(self, statement);
}
fn visit_typed_assignment(&mut self, assignment: &'ast TypedAssignment) {
visit_typed_assignment(self, assignment);
}
fn visit_typed_use(&mut self, use_: &'ast TypedUse) {
visit_typed_use(self, use_);
}
fn visit_typed_assert(&mut self, assert: &'ast TypedAssert) {
visit_typed_assert(self, assert);
}
fn visit_typed_pipeline_assignment(&mut self, assignment: &'ast TypedPipelineAssignment) {
visit_typed_pipeline_assignment(self, assignment);
}
fn visit_typed_call_arg(&mut self, arg: &'ast TypedCallArg) {
visit_typed_call_arg(self, arg);
}
fn visit_typed_clause(&mut self, clause: &'ast TypedClause) {
visit_typed_clause(self, clause);
}
fn visit_typed_clause_guard(&mut self, guard: &'ast TypedClauseGuard) {
visit_typed_clause_guard(self, guard);
}
fn visit_typed_clause_guard_var(
&mut self,
location: &'ast SrcSpan,
name: &'ast EcoString,
type_: &'ast Arc<Type>,
definition_location: &'ast SrcSpan,
) {
visit_typed_clause_guard_var(self, location, name, type_, definition_location);
}
fn visit_typed_clause_guard_tuple_index(
&mut self,
location: &'ast SrcSpan,
index: &'ast u64,
type_: &'ast Arc<Type>,
tuple: &'ast TypedClauseGuard,
) {
visit_typed_clause_guard_tuple_index(self, location, index, type_, tuple)
}
fn visit_typed_clause_guard_field_access(
&mut self,
label_location: &'ast SrcSpan,
index: &'ast Option<u64>,
label: &'ast EcoString,
type_: &'ast Arc<Type>,
container: &'ast TypedClauseGuard,
) {
visit_typed_clause_guard_field_access(self, label_location, index, label, type_, container)
}
fn visit_typed_clause_guard_module_select(
&mut self,
location: &'ast SrcSpan,
type_: &'ast Arc<Type>,
label: &'ast EcoString,
module_name: &'ast EcoString,
module_alias: &'ast EcoString,
literal: &'ast TypedConstant,
) {
visit_typed_clause_guard_module_select(
self,
location,
type_,
label,
module_name,
module_alias,
literal,
)
}
fn visit_typed_expr_bit_array_segment(&mut self, segment: &'ast TypedExprBitArraySegment) {
visit_typed_expr_bit_array_segment(self, segment);
}
fn visit_typed_bit_array_option(&mut self, option: &'ast BitArrayOption<TypedExpr>) {
visit_typed_bit_array_option(self, option);
}
fn visit_typed_pattern(&mut self, pattern: &'ast TypedPattern) {
visit_typed_pattern(self, pattern);
}
fn visit_typed_pattern_int(&mut self, location: &'ast SrcSpan, value: &'ast EcoString) {
visit_typed_pattern_int(self, location, value);
}
fn visit_typed_pattern_float(&mut self, location: &'ast SrcSpan, value: &'ast EcoString) {
visit_typed_pattern_float(self, location, value);
}
fn visit_typed_pattern_string(&mut self, location: &'ast SrcSpan, value: &'ast EcoString) {
visit_typed_pattern_string(self, location, value);
}
fn visit_typed_pattern_variable(
&mut self,
location: &'ast SrcSpan,
name: &'ast EcoString,
type_: &'ast Arc<Type>,
origin: &'ast VariableOrigin,
) {
visit_typed_pattern_variable(self, location, name, type_, origin);
}
fn visit_typed_pattern_bit_array_size(&mut self, size: &'ast TypedBitArraySize) {
visit_typed_pattern_bit_array_size(self, size);
}
fn visit_typed_bit_array_size_int(&mut self, location: &'ast SrcSpan, value: &'ast EcoString) {
visit_typed_bit_array_size_int(self, location, value)
}
fn visit_typed_bit_array_size_variable(
&mut self,
location: &'ast SrcSpan,
name: &'ast EcoString,
constructor: &'ast Option<Box<ValueConstructor>>,
type_: &'ast Arc<Type>,
) {
visit_typed_bit_array_size_variable(self, location, name, constructor, type_)
}
fn visit_typed_pattern_assign(
&mut self,
location: &'ast SrcSpan,
name: &'ast EcoString,
pattern: &'ast TypedPattern,
) {
visit_typed_pattern_assign(self, location, name, pattern);
}
fn visit_typed_pattern_discard(
&mut self,
location: &'ast SrcSpan,
name: &'ast EcoString,
type_: &'ast Arc<Type>,
) {
visit_typed_pattern_discard(self, location, name, type_)
}
fn visit_typed_pattern_list(
&mut self,
location: &'ast SrcSpan,
elements: &'ast Vec<TypedPattern>,
tail: &'ast Option<Box<TypedTailPattern>>,
type_: &'ast Arc<Type>,
) {
visit_typed_pattern_list(self, location, elements, tail, type_);
}
#[allow(clippy::too_many_arguments)]
fn visit_typed_pattern_constructor(
&mut self,
location: &'ast SrcSpan,
name_location: &'ast SrcSpan,
name: &'ast EcoString,
arguments: &'ast Vec<CallArg<TypedPattern>>,
module: &'ast Option<(EcoString, SrcSpan)>,
constructor: &'ast Inferred<PatternConstructor>,
spread: &'ast Option<SrcSpan>,
type_: &'ast Arc<Type>,
) {
visit_typed_pattern_constructor(
self,
location,
name_location,
name,
arguments,
module,
constructor,
spread,
type_,
);
}
fn visit_typed_pattern_call_arg(&mut self, arg: &'ast CallArg<TypedPattern>) {
visit_typed_pattern_call_arg(self, arg);
}
fn visit_typed_pattern_tuple(
&mut self,
location: &'ast SrcSpan,
elements: &'ast Vec<TypedPattern>,
) {
visit_typed_pattern_tuple(self, location, elements);
}
fn visit_typed_pattern_bit_array(
&mut self,
location: &'ast SrcSpan,
segments: &'ast [TypedPatternBitArraySegment],
) {
visit_typed_pattern_bit_array(self, location, segments);
}
fn visit_typed_pattern_bit_array_option(&mut self, option: &'ast BitArrayOption<TypedPattern>) {
visit_typed_pattern_bit_array_option(self, option);
}
fn visit_typed_pattern_string_prefix(
&mut self,
location: &'ast SrcSpan,
left_location: &'ast SrcSpan,
left_side_assignment: &'ast Option<(EcoString, SrcSpan)>,
right_location: &'ast SrcSpan,
left_side_string: &'ast EcoString,
right_side_assignment: &'ast AssignName,
) {
visit_typed_pattern_string_prefix(
self,
location,
left_location,
left_side_assignment,
right_location,
left_side_string,
right_side_assignment,
);
}
fn visit_typed_pattern_invalid(&mut self, location: &'ast SrcSpan, type_: &'ast Arc<Type>) {
visit_typed_pattern_invalid(self, location, type_);
}
fn visit_type_ast(&mut self, node: &'ast TypeAst) {
visit_type_ast(self, node);
}
fn visit_type_ast_constructor(
&mut self,
location: &'ast SrcSpan,
name_location: &'ast SrcSpan,
module: &'ast Option<(EcoString, SrcSpan)>,
name: &'ast EcoString,
arguments: &'ast Vec<TypeAst>,
) {
visit_type_ast_constructor(self, location, name_location, module, name, arguments);
}
fn visit_type_ast_fn(
&mut self,
location: &'ast SrcSpan,
arguments: &'ast Vec<TypeAst>,
return_: &'ast TypeAst,
) {
visit_type_ast_fn(self, location, arguments, return_);
}
fn visit_type_ast_var(&mut self, location: &'ast SrcSpan, name: &'ast EcoString) {
visit_type_ast_var(self, location, name);
}
fn visit_type_ast_tuple(&mut self, location: &'ast SrcSpan, elements: &'ast Vec<TypeAst>) {
visit_type_ast_tuple(self, location, elements);
}
fn visit_type_ast_hole(&mut self, location: &'ast SrcSpan, name: &'ast EcoString) {
visit_type_ast_hole(self, location, name);
}
fn visit_typed_constant(&mut self, constant: &'ast TypedConstant) {
visit_typed_constant(self, constant);
}
fn visit_typed_constant_int(
&mut self,
location: &'ast SrcSpan,
value: &'ast EcoString,
int_value: &'ast BigInt,
) {
visit_typed_constant_int(self, location, value, int_value);
}
fn visit_typed_constant_float(
&mut self,
location: &'ast SrcSpan,
value: &'ast EcoString,
float_value: &'ast LiteralFloatValue,
) {
visit_typed_constant_float(self, location, value, float_value);
}
fn visit_typed_constant_string(&mut self, location: &'ast SrcSpan, value: &'ast EcoString) {
visit_typed_constant_string(self, location, value);
}
fn visit_typed_constant_tuple(
&mut self,
location: &'ast SrcSpan,
elements: &'ast Vec<TypedConstant>,
type_: &'ast Arc<Type>,
) {
visit_typed_constant_tuple(self, location, elements, type_);
}
fn visit_typed_constant_list(
&mut self,
location: &'ast SrcSpan,
elements: &'ast Vec<TypedConstant>,
type_: &'ast Arc<Type>,
) {
visit_typed_constant_list(self, location, elements, type_);
}
#[allow(clippy::too_many_arguments)]
fn visit_typed_constant_record(
&mut self,
location: &'ast SrcSpan,
module: &'ast Option<(EcoString, SrcSpan)>,
name: &'ast EcoString,
arguments: &'ast Vec<CallArg<TypedConstant>>,
tag: &'ast EcoString,
type_: &'ast Arc<Type>,
field_map: &'ast Inferred<FieldMap>,
record_constructor: &'ast Option<Box<ValueConstructor>>,
) {
visit_typed_constant_record(
self,
location,
module,
name,
arguments,
tag,
type_,
field_map,
record_constructor,
)
}
#[allow(clippy::too_many_arguments)]
fn visit_typed_constant_record_update(
&mut self,
location: &'ast SrcSpan,
constructor_location: &'ast SrcSpan,
module: &'ast Option<(EcoString, SrcSpan)>,
name: &'ast EcoString,
record: &'ast RecordBeingUpdated<TypedConstant>,
arguments: &'ast [RecordUpdateArg<TypedConstant>],
tag: &'ast EcoString,
type_: &'ast Arc<Type>,
field_map: &'ast Inferred<FieldMap>,
) {
visit_typed_constant_record_update(
self,
location,
constructor_location,
module,
name,
record,
arguments,
tag,
type_,
field_map,
)
}
fn visit_typed_constant_bit_array(
&mut self,
location: &'ast SrcSpan,
segments: &'ast [TypedConstantBitArraySegment],
) {
visit_typed_constant_bit_array(self, location, segments);
}
fn visit_typed_constant_var(
&mut self,
location: &'ast SrcSpan,
module: &'ast Option<(EcoString, SrcSpan)>,
name: &'ast EcoString,
constructor: &'ast Option<Box<ValueConstructor>>,
type_: &'ast Arc<Type>,
) {
visit_typed_constant_var(self, location, module, name, constructor, type_);
}
fn visit_typed_constant_string_concatenation(
&mut self,
location: &'ast SrcSpan,
left: &'ast TypedConstant,
right: &'ast TypedConstant,
) {
visit_typed_constant_string_concatenation(self, location, left, right);
}
fn visit_typed_constant_invalid(
&mut self,
location: &'ast SrcSpan,
type_: &'ast Arc<Type>,
extra_information: &'ast Option<InvalidExpression>,
) {
visit_typed_constant_invalid(self, location, type_, extra_information);
}
}
fn visit_typed_constant_invalid<'a, V: Visit<'a> + ?Sized>(
_v: &mut V,
_location: &'a SrcSpan,
_type_: &'a Type,
_extra_information: &'a Option<InvalidExpression>,
) {
// No further traversal needed for constant invalid expressions
}
fn visit_typed_constant_string_concatenation<'a, V: Visit<'a> + ?Sized>(
v: &mut V,
_location: &'a SrcSpan,
left: &'a TypedConstant,
right: &'a TypedConstant,
) {
v.visit_typed_constant(left);
v.visit_typed_constant(right);
}
pub fn visit_typed_constant_var<'a, V: Visit<'a> + ?Sized>(
_v: &mut V,
_location: &'a SrcSpan,
_module: &'a Option<(EcoString, SrcSpan)>,
_name: &'a EcoString,
_constructor: &'a Option<Box<ValueConstructor>>,
_type_: &'a Arc<Type>,
) {
// No further traversal needed for constant vars
}
fn visit_typed_constant_bit_array<'a, V: Visit<'a> + ?Sized>(
_v: &mut V,
_location: &'a SrcSpan,
_segments: &'a [TypedConstantBitArraySegment],
) {
// TODO
}
#[allow(clippy::too_many_arguments)]
pub fn visit_typed_constant_record<'a, V: Visit<'a> + ?Sized>(
v: &mut V,
_location: &'a SrcSpan,
_module: &'a Option<(EcoString, SrcSpan)>,
_name: &'a EcoString,
arguments: &'a Vec<CallArg<TypedConstant>>,
_tag: &'a EcoString,
_type_: &'a Arc<Type>,
_field_map: &'a Inferred<FieldMap>,
_record_constructor: &'a Option<Box<ValueConstructor>>,
) {
for argument in arguments {
v.visit_typed_constant(&argument.value)
}
}
#[allow(clippy::too_many_arguments)]
fn visit_typed_constant_record_update<'a, V: Visit<'a> + ?Sized>(
v: &mut V,
_location: &'a SrcSpan,
_constructor_location: &'a SrcSpan,
_module: &'a Option<(EcoString, SrcSpan)>,
_name: &'a EcoString,
record: &'a RecordBeingUpdated<TypedConstant>,
arguments: &'a [RecordUpdateArg<TypedConstant>],
_tag: &'a EcoString,
_type_: &'a Arc<Type>,
_field_map: &'a Inferred<FieldMap>,
) {
v.visit_typed_constant(&record.base);
for argument in arguments {
v.visit_typed_constant(&argument.value);
}
}
fn visit_typed_constant_list<'a, V: Visit<'a> + ?Sized>(
v: &mut V,
_location: &'a SrcSpan,
elements: &'a Vec<TypedConstant>,
_type_: &'a Arc<Type>,
) {
for element in elements {
v.visit_typed_constant(element)
}
}
fn visit_typed_constant_tuple<'a, V: Visit<'a> + ?Sized>(
v: &mut V,
_location: &'a SrcSpan,
elements: &'a Vec<TypedConstant>,
_type_: &'a Arc<Type>,
) {
for element in elements {
v.visit_typed_constant(element)
}
}
fn visit_typed_constant_string<'a, V: Visit<'a> + ?Sized>(
_v: &mut V,
_location: &'a SrcSpan,
_value: &'a EcoString,
) {
// No further traversal needed for constant strings
}
fn visit_typed_constant_float<'a, V: Visit<'a> + ?Sized>(
_v: &mut V,
_location: &'a SrcSpan,
_value: &'a EcoString,
_float_value: &'a LiteralFloatValue,
) {
// No further traversal needed for constant floats
}
fn visit_typed_constant_int<'a, V: Visit<'a> + ?Sized>(
_v: &mut V,
_location: &'a SrcSpan,
_value: &'a EcoString,
_int_value: &'a BigInt,
) {
// No further traversal needed for constant ints
}
pub fn visit_typed_module<'a, V>(v: &mut V, module: &'a TypedModule)
where
V: Visit<'a> + ?Sized,
{
let TypedDefinitions {
imports: _, // TODO
constants,
custom_types,
type_aliases: _, // TODO
functions,
} = &module.definitions;
for constant in constants {
v.visit_typed_module_constant(constant);
}
for custom_type in custom_types {
v.visit_typed_custom_type(custom_type);
}
for function in functions {
v.visit_typed_function(function);
}
}
pub fn visit_typed_function<'a, V>(v: &mut V, fun: &'a TypedFunction)
where
V: Visit<'a> + ?Sized,
{
for argument in fun.arguments.iter() {
if let Some(annotation) = &argument.annotation {
v.visit_type_ast(annotation);
}
}
if let Some(annotation) = &fun.return_annotation {
v.visit_type_ast(annotation);
}
for statement in &fun.body {
v.visit_typed_statement(statement);
}
}
pub fn visit_type_ast<'a, V>(v: &mut V, node: &'a TypeAst)
where
V: Visit<'a> + ?Sized,
{
match node {
TypeAst::Constructor(super::TypeAstConstructor {
location,
name_location,
arguments,
module,
name,
start_parentheses: _,
}) => {
v.visit_type_ast_constructor(location, name_location, module, name, arguments);
}
TypeAst::Fn(super::TypeAstFn {
location,
arguments,
return_,
}) => {
v.visit_type_ast_fn(location, arguments, return_);
}
TypeAst::Var(super::TypeAstVar { location, name }) => {
v.visit_type_ast_var(location, name);
}
TypeAst::Tuple(super::TypeAstTuple { location, elements }) => {
v.visit_type_ast_tuple(location, elements);
}
TypeAst::Hole(super::TypeAstHole { location, name }) => {
v.visit_type_ast_hole(location, name);
}
}
}
pub fn visit_type_ast_constructor<'a, V>(
v: &mut V,
_location: &'a SrcSpan,
_name_location: &'a SrcSpan,
_module: &'a Option<(EcoString, SrcSpan)>,
_name: &'a EcoString,
arguments: &'a Vec<TypeAst>,
) where
V: Visit<'a> + ?Sized,
{
for argument in arguments {
v.visit_type_ast(argument);
}
}
pub fn visit_type_ast_fn<'a, V>(
v: &mut V,
_location: &'a SrcSpan,
arguments: &'a Vec<TypeAst>,
return_: &'a TypeAst,
) where
V: Visit<'a> + ?Sized,
{
for argument in arguments {
v.visit_type_ast(argument);
}
v.visit_type_ast(return_);
}
pub fn visit_type_ast_var<'a, V>(_v: &mut V, _location: &'a SrcSpan, _name: &'a EcoString)
where
V: Visit<'a> + ?Sized,
{
// No further traversal needed for variables
}
pub fn visit_type_ast_tuple<'a, V>(v: &mut V, _location: &'a SrcSpan, elements: &'a Vec<TypeAst>)
where
V: Visit<'a> + ?Sized,
{
for element in elements {
v.visit_type_ast(element);
}
}
pub fn visit_type_ast_hole<'a, V>(_v: &mut V, _location: &'a SrcSpan, _name: &'a EcoString)
where
V: Visit<'a> + ?Sized,
{
// No further traversal needed for holes
}
pub fn visit_typed_module_constant<'a, V>(v: &mut V, constant: &'a TypedModuleConstant)
where
V: Visit<'a> + ?Sized,
{
v.visit_typed_constant(&constant.value);
}
pub fn visit_typed_constant<'a, V: Visit<'a> + ?Sized>(v: &mut V, constant: &'a TypedConstant) {
match constant {
super::Constant::Int {
location,
value,
int_value,
} => v.visit_typed_constant_int(location, value, int_value),
super::Constant::Float {
location,
value,
float_value,
} => v.visit_typed_constant_float(location, value, float_value),
super::Constant::String { location, value } => {
v.visit_typed_constant_string(location, value)
}
super::Constant::Tuple {
location,
elements,
type_,
} => v.visit_typed_constant_tuple(location, elements, type_),
super::Constant::List {
location,
elements,
type_,
} => v.visit_typed_constant_list(location, elements, type_),
super::Constant::Record {
location,
module,
name,
arguments,
tag,
type_,
field_map,
record_constructor,
} => v.visit_typed_constant_record(
location,
module,
name,
arguments,
tag,
type_,
field_map,
record_constructor,
),
super::Constant::RecordUpdate {
location,
constructor_location,
module,
name,
record,
arguments,
tag,
type_,
field_map,
} => v.visit_typed_constant_record_update(
location,
constructor_location,
module,
name,
record,
arguments,
tag,
type_,
field_map,
),
super::Constant::BitArray { location, segments } => {
v.visit_typed_constant_bit_array(location, segments)
}
super::Constant::Var {
location,
module,
name,
constructor,
type_,
} => v.visit_typed_constant_var(location, module, name, constructor, type_),
super::Constant::StringConcatenation {
location,
left,
right,
} => v.visit_typed_constant_string_concatenation(location, left, right),
super::Constant::Invalid {
location,
type_,
extra_information,
} => v.visit_typed_constant_invalid(location, type_, extra_information),
}
}
pub fn visit_typed_custom_type<'a, V>(v: &mut V, custom_type: &'a TypedCustomType)
where
V: Visit<'a> + ?Sized,
{
for record in &custom_type.constructors {
for argument in &record.arguments {
v.visit_type_ast(&argument.ast);
}
}
}
pub fn visit_typed_expr<'a, V>(v: &mut V, node: &'a TypedExpr)
where
V: Visit<'a> + ?Sized,
{
match node {
TypedExpr::Int {
location,
type_,
value,
int_value: _,
} => v.visit_typed_expr_int(location, type_, value),
TypedExpr::Float {
location,
type_,
value,
float_value: _,
} => v.visit_typed_expr_float(location, type_, value),
TypedExpr::String {
location,
type_,
value,
} => v.visit_typed_expr_string(location, type_, value),
TypedExpr::Block {
location,
statements,
} => v.visit_typed_expr_block(location, statements),
TypedExpr::Pipeline {
location,
first_value,
assignments,
finally,
finally_kind,
} => v.visit_typed_expr_pipeline(location, first_value, assignments, finally, finally_kind),
TypedExpr::Var {
location,
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | true |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/ast/untyped.rs | compiler-core/src/ast/untyped.rs | use vec1::Vec1;
use crate::parse::LiteralFloatValue;
use super::*;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UntypedExpr {
Int {
location: SrcSpan,
value: EcoString,
int_value: BigInt,
},
Float {
location: SrcSpan,
value: EcoString,
float_value: LiteralFloatValue,
},
String {
location: SrcSpan,
value: EcoString,
},
Block {
location: SrcSpan,
statements: Vec1<UntypedStatement>,
},
Var {
location: SrcSpan,
name: EcoString,
},
// TODO: create new variant for captures specifically
Fn {
/// For anonymous functions, this is the location of the entire function including the end of the body.
/// For named functions, this is the location of the function head.
location: SrcSpan,
kind: FunctionLiteralKind,
/// The byte location of the end of the function head before the opening bracket
end_of_head_byte_index: u32,
arguments: Vec<UntypedArg>,
body: Vec1<UntypedStatement>,
return_annotation: Option<TypeAst>,
},
List {
location: SrcSpan,
elements: Vec<Self>,
tail: Option<Box<Self>>,
},
Call {
location: SrcSpan,
fun: Box<Self>,
arguments: Vec<CallArg<Self>>,
},
BinOp {
location: SrcSpan,
name: BinOp,
name_location: SrcSpan,
left: Box<Self>,
right: Box<Self>,
},
PipeLine {
expressions: Vec1<Self>,
},
Case {
location: SrcSpan,
subjects: Vec<Self>,
// None if the case expression is missing a body.
clauses: Option<Vec<Clause<Self, (), ()>>>,
},
FieldAccess {
// This is the location of the whole record and field
// user.name
// ^^^^^^^^^
location: SrcSpan,
// This is the location of just the field access (ignoring the `.`)
// user.name
// ^^^^
label_location: SrcSpan,
label: EcoString,
container: Box<Self>,
},
Tuple {
location: SrcSpan,
elements: Vec<Self>,
},
TupleIndex {
location: SrcSpan,
index: u64,
tuple: Box<Self>,
},
Todo {
kind: TodoKind,
location: SrcSpan,
message: Option<Box<Self>>,
},
Panic {
location: SrcSpan,
message: Option<Box<Self>>,
},
Echo {
location: SrcSpan,
/// This is the position where the echo keyword ends:
/// ```gleam
/// echo wibble
/// // ^ ends here!
/// ```
keyword_end: u32,
expression: Option<Box<Self>>,
message: Option<Box<Self>>,
},
BitArray {
location: SrcSpan,
segments: Vec<UntypedExprBitArraySegment>,
},
RecordUpdate {
location: SrcSpan,
constructor: Box<Self>,
record: RecordBeingUpdated<UntypedExpr>,
arguments: Vec<UntypedRecordUpdateArg>,
},
NegateBool {
location: SrcSpan,
value: Box<Self>,
},
NegateInt {
location: SrcSpan,
value: Box<Self>,
},
}
impl UntypedExpr {
pub fn location(&self) -> SrcSpan {
match self {
Self::PipeLine { expressions, .. } => expressions
.first()
.location()
.merge(&expressions.last().location()),
Self::Fn { location, .. }
| Self::Var { location, .. }
| Self::Int { location, .. }
| Self::Todo { location, .. }
| Self::Echo { location, .. }
| Self::Case { location, .. }
| Self::Call { location, .. }
| Self::List { location, .. }
| Self::Float { location, .. }
| Self::Block { location, .. }
| Self::BinOp { location, .. }
| Self::Tuple { location, .. }
| Self::Panic { location, .. }
| Self::String { location, .. }
| Self::BitArray { location, .. }
| Self::NegateInt { location, .. }
| Self::NegateBool { location, .. }
| Self::TupleIndex { location, .. }
| Self::FieldAccess { location, .. }
| Self::RecordUpdate { location, .. } => *location,
}
}
pub fn start_byte_index(&self) -> u32 {
match self {
Self::Block { location, .. } => location.start,
Self::PipeLine { expressions, .. } => expressions.first().start_byte_index(),
Self::Int { .. }
| Self::Float { .. }
| Self::String { .. }
| Self::Var { .. }
| Self::Fn { .. }
| Self::List { .. }
| Self::Call { .. }
| Self::BinOp { .. }
| Self::Case { .. }
| Self::FieldAccess { .. }
| Self::Tuple { .. }
| Self::TupleIndex { .. }
| Self::Todo { .. }
| Self::Panic { .. }
| Self::Echo { .. }
| Self::BitArray { .. }
| Self::RecordUpdate { .. }
| Self::NegateBool { .. }
| Self::NegateInt { .. } => self.location().start,
}
}
pub fn bin_op_precedence(&self) -> u8 {
match self {
Self::BinOp { name, .. } => name.precedence(),
Self::PipeLine { .. } => 5,
Self::Int { .. }
| Self::Float { .. }
| Self::String { .. }
| Self::Block { .. }
| Self::Var { .. }
| Self::Fn { .. }
| Self::List { .. }
| Self::Call { .. }
| Self::Case { .. }
| Self::FieldAccess { .. }
| Self::Tuple { .. }
| Self::TupleIndex { .. }
| Self::Todo { .. }
| Self::Panic { .. }
| Self::Echo { .. }
| Self::BitArray { .. }
| Self::RecordUpdate { .. }
| Self::NegateBool { .. }
| Self::NegateInt { .. } => u8::MAX,
}
}
pub fn bin_op_name(&self) -> Option<&BinOp> {
if let UntypedExpr::BinOp { name, .. } = self {
Some(name)
} else {
None
}
}
pub fn can_have_multiple_per_line(&self) -> bool {
match self {
UntypedExpr::Int { .. }
| UntypedExpr::Float { .. }
| UntypedExpr::String { .. }
| UntypedExpr::Var { .. } => true,
UntypedExpr::NegateBool { value, .. }
| UntypedExpr::NegateInt { value, .. }
| UntypedExpr::FieldAccess {
container: value, ..
} => value.can_have_multiple_per_line(),
UntypedExpr::Block { .. }
| UntypedExpr::Fn { .. }
| UntypedExpr::List { .. }
| UntypedExpr::Call { .. }
| UntypedExpr::BinOp { .. }
| UntypedExpr::PipeLine { .. }
| UntypedExpr::Case { .. }
| UntypedExpr::Tuple { .. }
| UntypedExpr::TupleIndex { .. }
| UntypedExpr::Todo { .. }
| UntypedExpr::Panic { .. }
| UntypedExpr::Echo { .. }
| UntypedExpr::BitArray { .. }
| UntypedExpr::RecordUpdate { .. } => false,
}
}
pub fn is_tuple(&self) -> bool {
matches!(self, UntypedExpr::Tuple { .. })
}
/// Returns `true` if the untyped expr is [`Call`].
///
/// [`Call`]: UntypedExpr::Call
#[must_use]
pub fn is_call(&self) -> bool {
matches!(self, Self::Call { .. })
}
#[must_use]
pub fn is_binop(&self) -> bool {
matches!(self, Self::BinOp { .. })
}
#[must_use]
pub fn is_pipeline(&self) -> bool {
matches!(self, Self::PipeLine { .. })
}
#[must_use]
pub fn is_todo(&self) -> bool {
matches!(self, Self::Todo { .. })
}
#[must_use]
pub fn is_panic(&self) -> bool {
matches!(self, Self::Panic { .. })
}
}
impl HasLocation for UntypedExpr {
fn location(&self) -> SrcSpan {
self.location()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FunctionLiteralKind {
Capture { hole: SrcSpan },
Anonymous { head: SrcSpan },
Use { location: SrcSpan },
}
impl FunctionLiteralKind {
pub fn is_capture(&self) -> bool {
match self {
FunctionLiteralKind::Capture { .. } => true,
FunctionLiteralKind::Anonymous { .. } | FunctionLiteralKind::Use { .. } => false,
}
}
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/ast/constant.rs | compiler-core/src/ast/constant.rs | use super::*;
use crate::analyse::Inferred;
use crate::type_::{FieldMap, HasType};
pub type TypedConstant = Constant<Arc<Type>, EcoString>;
pub type UntypedConstant = Constant<(), ()>;
// TODO: remove RecordTag paramter
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Constant<T, RecordTag> {
Int {
location: SrcSpan,
value: EcoString,
int_value: BigInt,
},
Float {
location: SrcSpan,
value: EcoString,
float_value: LiteralFloatValue,
},
String {
location: SrcSpan,
value: EcoString,
},
Tuple {
location: SrcSpan,
elements: Vec<Self>,
type_: T,
},
List {
location: SrcSpan,
elements: Vec<Self>,
type_: T,
},
Record {
location: SrcSpan,
module: Option<(EcoString, SrcSpan)>,
name: EcoString,
arguments: Vec<CallArg<Self>>,
tag: RecordTag,
type_: T,
field_map: Inferred<FieldMap>,
record_constructor: Option<Box<ValueConstructor>>,
},
RecordUpdate {
location: SrcSpan,
constructor_location: SrcSpan,
module: Option<(EcoString, SrcSpan)>,
name: EcoString,
record: RecordBeingUpdated<Self>,
arguments: Vec<RecordUpdateArg<Self>>,
tag: RecordTag,
type_: T,
field_map: Inferred<FieldMap>,
},
BitArray {
location: SrcSpan,
segments: Vec<BitArraySegment<Self, T>>,
},
Var {
location: SrcSpan,
module: Option<(EcoString, SrcSpan)>,
name: EcoString,
constructor: Option<Box<ValueConstructor>>,
type_: T,
},
StringConcatenation {
location: SrcSpan,
left: Box<Self>,
right: Box<Self>,
},
/// A placeholder constant used to allow module analysis to continue
/// even when there are type errors. Should never end up in generated code.
Invalid {
location: SrcSpan,
type_: T,
/// Extra information about the invalid expression, useful for providing
/// addition help or information, such as code actions to fix invalid
/// states.
extra_information: Option<InvalidExpression>,
},
}
impl TypedConstant {
pub fn type_(&self) -> Arc<Type> {
match self {
Constant::Int { .. } => type_::int(),
Constant::Float { .. } => type_::float(),
Constant::String { .. } | Constant::StringConcatenation { .. } => type_::string(),
Constant::BitArray { .. } => type_::bit_array(),
Constant::List { type_, .. }
| Constant::Tuple { type_, .. }
| Constant::Record { type_, .. }
| Constant::RecordUpdate { type_, .. }
| Constant::Var { type_, .. }
| Constant::Invalid { type_, .. } => type_.clone(),
}
}
pub fn find_node(&self, byte_index: u32) -> Option<Located<'_>> {
if !self.location().contains(byte_index) {
return None;
}
Some(match self {
Constant::Int { .. }
| Constant::Float { .. }
| Constant::String { .. }
| Constant::Var { .. }
| Constant::Invalid { .. } => Located::Constant(self),
Constant::Tuple { elements, .. } | Constant::List { elements, .. } => elements
.iter()
.find_map(|element| element.find_node(byte_index))
.unwrap_or(Located::Constant(self)),
Constant::Record { arguments, .. } => arguments
.iter()
.find_map(|argument| argument.find_node(byte_index))
.unwrap_or(Located::Constant(self)),
Constant::RecordUpdate {
record, arguments, ..
} => record
.base
.find_node(byte_index)
.or_else(|| {
arguments
.iter()
.find_map(|arg| arg.value.find_node(byte_index))
})
.unwrap_or(Located::Constant(self)),
Constant::BitArray { segments, .. } => segments
.iter()
.find_map(|segment| segment.find_node(byte_index))
.unwrap_or(Located::Constant(self)),
Constant::StringConcatenation { left, right, .. } => left
.find_node(byte_index)
.or_else(|| right.find_node(byte_index))
.unwrap_or(Located::Constant(self)),
})
}
pub fn definition_location(&self) -> Option<DefinitionLocation> {
match self {
Constant::Int { .. }
| Constant::Float { .. }
| Constant::String { .. }
| Constant::Tuple { .. }
| Constant::List { .. }
| Constant::BitArray { .. }
| Constant::StringConcatenation { .. }
| Constant::Invalid { .. } => None,
Constant::Record {
record_constructor: value_constructor,
..
}
| Constant::Var {
constructor: value_constructor,
..
} => value_constructor
.as_ref()
.map(|constructor| constructor.definition_location()),
Constant::RecordUpdate { .. } => None,
}
}
pub(crate) fn referenced_variables(&self) -> im::HashSet<&EcoString> {
match self {
Constant::Var { name, .. } => im::hashset![name],
Constant::Invalid { .. }
| Constant::Int { .. }
| Constant::Float { .. }
| Constant::String { .. } => im::hashset![],
Constant::List { elements, .. } | Constant::Tuple { elements, .. } => elements
.iter()
.map(|element| element.referenced_variables())
.fold(im::hashset![], im::HashSet::union),
Constant::Record { arguments, .. } => arguments
.iter()
.map(|argument| argument.value.referenced_variables())
.fold(im::hashset![], im::HashSet::union),
Constant::RecordUpdate {
record, arguments, ..
} => record.base.referenced_variables().union(
arguments
.iter()
.map(|arg| arg.value.referenced_variables())
.fold(im::hashset![], im::HashSet::union),
),
Constant::BitArray { segments, .. } => segments
.iter()
.map(|segment| {
segment
.options
.iter()
.map(|option| option.referenced_variables())
.fold(segment.value.referenced_variables(), im::HashSet::union)
})
.fold(im::hashset![], im::HashSet::union),
Constant::StringConcatenation { left, right, .. } => left
.referenced_variables()
.union(right.referenced_variables()),
}
}
pub(crate) fn syntactically_eq(&self, other: &Self) -> bool {
match (self, other) {
(Constant::Int { int_value: n, .. }, Constant::Int { int_value: m, .. }) => n == m,
(Constant::Int { .. }, _) => false,
(Constant::Float { float_value: n, .. }, Constant::Float { float_value: m, .. }) => {
n == m
}
(Constant::Float { .. }, _) => false,
(
Constant::String { value, .. },
Constant::String {
value: other_value, ..
},
) => value == other_value,
(Constant::String { .. }, _) => false,
(
Constant::Tuple { elements, .. },
Constant::Tuple {
elements: other_elements,
..
},
) => pairwise_all(elements, other_elements, |(one, other)| {
one.syntactically_eq(other)
}),
(Constant::Tuple { .. }, _) => false,
(
Constant::List { elements, .. },
Constant::List {
elements: other_elements,
..
},
) => pairwise_all(elements, other_elements, |(one, other)| {
one.syntactically_eq(other)
}),
(Constant::List { .. }, _) => false,
(
Constant::Record {
module,
name,
arguments,
..
},
Constant::Record {
module: other_module,
name: other_name,
arguments: other_arguments,
..
},
) => {
let modules_are_equal = match (module, other_module) {
(None, None) => true,
(None, Some(_)) | (Some(_), None) => false,
(Some((one, _)), Some((other, _))) => one == other,
};
modules_are_equal
&& name == other_name
&& pairwise_all(arguments, other_arguments, |(one, other)| {
one.label == other.label && one.value.syntactically_eq(&other.value)
})
}
(Constant::Record { .. }, _) => false,
(
Constant::RecordUpdate {
module,
name,
record,
arguments,
..
},
Constant::RecordUpdate {
module: other_module,
name: other_name,
record: other_record,
arguments: other_arguments,
..
},
) => {
let modules_are_equal = match (module, other_module) {
(None, None) => true,
(None, Some(_)) | (Some(_), None) => false,
(Some((one, _)), Some((other, _))) => one == other,
};
modules_are_equal
&& name == other_name
&& record.base.syntactically_eq(&other_record.base)
&& pairwise_all(arguments, other_arguments, |(one, other)| {
one.label == other.label && one.value.syntactically_eq(&other.value)
})
}
(Constant::RecordUpdate { .. }, _) => false,
(
Constant::BitArray { segments, .. },
Constant::BitArray {
segments: other_segments,
..
},
) => pairwise_all(segments, other_segments, |(one, other)| {
one.syntactically_eq(other)
}),
(Constant::BitArray { .. }, _) => false,
(
Constant::Var { module, name, .. },
Constant::Var {
module: other_module,
name: other_name,
..
},
) => {
let modules_are_equal = match (module, other_module) {
(None, None) => true,
(None, Some(_)) | (Some(_), None) => false,
(Some((one, _)), Some((other, _))) => one == other,
};
modules_are_equal && name == other_name
}
(Constant::Var { .. }, _) => false,
(
Constant::StringConcatenation { left, right, .. },
Constant::StringConcatenation {
left: other_left,
right: other_right,
..
},
) => left.syntactically_eq(other_left) && right.syntactically_eq(other_right),
(Constant::StringConcatenation { .. }, _) => false,
(Constant::Invalid { .. }, _) => false,
}
}
}
impl HasType for TypedConstant {
fn type_(&self) -> Arc<Type> {
self.type_()
}
}
impl<A, B> Constant<A, B> {
pub fn location(&self) -> SrcSpan {
match self {
Constant::Int { location, .. }
| Constant::List { location, .. }
| Constant::Float { location, .. }
| Constant::Tuple { location, .. }
| Constant::String { location, .. }
| Constant::Record { location, .. }
| Constant::RecordUpdate { location, .. }
| Constant::BitArray { location, .. }
| Constant::Var { location, .. }
| Constant::Invalid { location, .. }
| Constant::StringConcatenation { location, .. } => *location,
}
}
#[must_use]
pub fn can_have_multiple_per_line(&self) -> bool {
match self {
Constant::Int { .. }
| Constant::Float { .. }
| Constant::String { .. }
| Constant::Var { .. } => true,
Constant::Tuple { .. }
| Constant::List { .. }
| Constant::Record { .. }
| Constant::RecordUpdate { .. }
| Constant::BitArray { .. }
| Constant::StringConcatenation { .. }
| Constant::Invalid { .. } => false,
}
}
}
impl<A, B> HasLocation for Constant<A, B> {
fn location(&self) -> SrcSpan {
self.location()
}
}
impl<A, B> bit_array::GetLiteralValue for Constant<A, B> {
fn as_int_literal(&self) -> Option<BigInt> {
if let Constant::Int { int_value, .. } = self {
Some(int_value.clone())
} else {
None
}
}
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/ast/typed.rs | compiler-core/src/ast/typed.rs | use std::sync::OnceLock;
use type_::{FieldMap, TypedCallArg};
use super::*;
use crate::{
build::ExpressionPosition,
exhaustiveness::CompiledCase,
parse::LiteralFloatValue,
type_::{HasType, Type, ValueConstructorVariant, bool},
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TypedExpr {
Int {
location: SrcSpan,
type_: Arc<Type>,
value: EcoString,
int_value: BigInt,
},
Float {
location: SrcSpan,
type_: Arc<Type>,
value: EcoString,
float_value: LiteralFloatValue,
},
String {
location: SrcSpan,
type_: Arc<Type>,
value: EcoString,
},
Block {
location: SrcSpan,
statements: Vec1<TypedStatement>,
},
/// A chain of pipe expressions.
/// By this point the type checker has expanded it into a series of
/// assignments and function calls, but we still have a Pipeline AST node as
/// even though it is identical to `Block` we want to use different
/// locations when showing it in error messages, etc.
Pipeline {
location: SrcSpan,
first_value: TypedPipelineAssignment,
assignments: Vec<(TypedPipelineAssignment, PipelineAssignmentKind)>,
finally: Box<Self>,
finally_kind: PipelineAssignmentKind,
},
Var {
location: SrcSpan,
constructor: ValueConstructor,
name: EcoString,
},
Fn {
location: SrcSpan,
type_: Arc<Type>,
kind: FunctionLiteralKind,
arguments: Vec<TypedArg>,
body: Vec1<TypedStatement>,
return_annotation: Option<TypeAst>,
purity: Purity,
},
List {
location: SrcSpan,
type_: Arc<Type>,
elements: Vec<Self>,
tail: Option<Box<Self>>,
},
Call {
location: SrcSpan,
type_: Arc<Type>,
fun: Box<Self>,
arguments: Vec<CallArg<Self>>,
},
BinOp {
location: SrcSpan,
type_: Arc<Type>,
name: BinOp,
name_location: SrcSpan,
left: Box<Self>,
right: Box<Self>,
},
Case {
location: SrcSpan,
type_: Arc<Type>,
subjects: Vec<Self>,
clauses: Vec<Clause<Self, Arc<Type>, EcoString>>,
compiled_case: CompiledCase,
},
RecordAccess {
location: SrcSpan,
field_start: u32,
type_: Arc<Type>,
label: EcoString,
index: u64,
record: Box<Self>,
documentation: Option<EcoString>,
},
/// Generated internally for accessing unlabelled fields of a custom type,
/// such as for record updates.
PositionalAccess {
location: SrcSpan,
type_: Arc<Type>,
index: u64,
record: Box<Self>,
},
ModuleSelect {
location: SrcSpan,
field_start: u32,
type_: Arc<Type>,
label: EcoString,
module_name: EcoString,
module_alias: EcoString,
constructor: ModuleValueConstructor,
},
Tuple {
location: SrcSpan,
type_: Arc<Type>,
elements: Vec<Self>,
},
TupleIndex {
location: SrcSpan,
type_: Arc<Type>,
index: u64,
tuple: Box<Self>,
},
Todo {
location: SrcSpan,
message: Option<Box<Self>>,
kind: TodoKind,
type_: Arc<Type>,
},
Panic {
location: SrcSpan,
message: Option<Box<Self>>,
type_: Arc<Type>,
},
Echo {
location: SrcSpan,
type_: Arc<Type>,
expression: Option<Box<Self>>,
message: Option<Box<Self>>,
},
BitArray {
location: SrcSpan,
type_: Arc<Type>,
segments: Vec<TypedExprBitArraySegment>,
},
/// A record update gets desugared to a block expression of the form
///
/// {
/// let _record = record
/// Constructor(explicit_arg: explicit_value(), implicit_arg: _record.implicit_arg)
/// }
///
/// We still keep a separate `RecordUpdate` AST node for the same reasons as
/// we do for pipelines.
RecordUpdate {
location: SrcSpan,
type_: Arc<Type>,
/// If the record is an expression that is not a variable we will need to assign to a
/// variable so it can be referred multiple times.
record_assignment: Option<Box<TypedAssignment>>,
constructor: Box<Self>,
arguments: Vec<CallArg<Self>>,
},
NegateBool {
location: SrcSpan,
value: Box<Self>,
},
NegateInt {
location: SrcSpan,
value: Box<Self>,
},
/// A placeholder expression used to allow module analysis to continue
/// even when there are type errors. Should never end up in generated code.
Invalid {
location: SrcSpan,
type_: Arc<Type>,
/// Extra information about the invalid expression, useful for providing
/// addition help or information, such as code actions to fix invalid
/// states.
extra_information: Option<InvalidExpression>,
},
}
impl TypedExpr {
pub fn is_println(&self) -> bool {
let fun = if let TypedExpr::Call { fun, arguments, .. } = self
&& arguments.len() == 1
{
fun.as_ref()
} else {
return false;
};
if let TypedExpr::ModuleSelect {
label, module_name, ..
} = fun
{
label == "println" && module_name == "gleam/io"
} else {
false
}
}
pub fn find_node(&self, byte_index: u32) -> Option<Located<'_>> {
match self {
Self::Var { .. }
| Self::Int { .. }
| Self::Float { .. }
| Self::String { .. }
| Self::Invalid { .. }
| Self::PositionalAccess { .. } => self.self_if_contains_location(byte_index),
Self::ModuleSelect {
location,
field_start,
module_name,
..
} => {
// We want to return the `ModuleSelect` only when we're hovering
// over the selected field, not on the module part.
let field_span = SrcSpan {
start: *field_start,
end: location.end,
};
// We subtract 1 so the location doesn't include the `.` character.
let module_span = SrcSpan::new(location.start, field_start - 1);
if field_span.contains(byte_index) {
Some(self.into())
} else if module_span.contains(byte_index) {
Some(Located::ModuleName {
location: module_span,
name: module_name,
layer: Layer::Value,
})
} else {
None
}
}
Self::Echo {
expression,
message,
..
} => expression
.as_ref()
.and_then(|expression| expression.find_node(byte_index))
.or_else(|| {
message
.as_ref()
.and_then(|message| message.find_node(byte_index))
})
.or_else(|| self.self_if_contains_location(byte_index)),
Self::Panic { message, .. } => message
.as_ref()
.and_then(|message| message.find_node(byte_index))
.or_else(|| self.self_if_contains_location(byte_index)),
Self::Todo { kind, message, .. } => match kind {
TodoKind::Keyword => message
.as_ref()
.and_then(|message| message.find_node(byte_index))
.or_else(|| self.self_if_contains_location(byte_index)),
// We don't want to match on todos that were implicitly inserted
// by the compiler as it would result in confusing suggestions
// from the LSP.
TodoKind::EmptyFunction { .. } | TodoKind::EmptyBlock | TodoKind::IncompleteUse => {
None
}
},
Self::Pipeline {
first_value,
assignments,
finally,
..
} => first_value
.find_node(byte_index)
.or_else(|| {
assignments
.iter()
.find_map(|(e, _)| e.find_node(byte_index))
})
.or_else(|| finally.find_node(byte_index)),
// Exit the search and return None if during iteration a statement
// is found with a start index beyond the index under search.
Self::Block { statements, .. } => {
for statement in statements {
if statement.location().start > byte_index {
break;
}
if let Some(located) = statement.find_node(byte_index) {
return Some(located);
}
}
None
}
// Exit the search and return the encompassing type (e.g., list or tuple)
// if during iteration, an element is encountered with a start index
// beyond the index under search.
Self::Tuple {
elements: expressions,
..
} => {
for expression in expressions {
if expression.location().start > byte_index {
break;
}
if let Some(located) = expression.find_node(byte_index) {
return Some(located);
}
}
self.self_if_contains_location(byte_index)
}
Self::List {
elements: expressions,
tail,
..
} => {
for expression in expressions {
if expression.location().start > byte_index {
break;
}
if let Some(located) = expression.find_node(byte_index) {
return Some(located);
}
}
if let Some(tail) = tail
&& let Some(node) = tail.find_node(byte_index)
{
return Some(node);
}
self.self_if_contains_location(byte_index)
}
Self::NegateBool { value, .. } | Self::NegateInt { value, .. } => value
.find_node(byte_index)
.or_else(|| self.self_if_contains_location(byte_index)),
Self::Fn {
body, arguments, ..
} => arguments
.iter()
.find_map(|arg| arg.find_node(byte_index))
.or_else(|| body.iter().find_map(|s| s.find_node(byte_index)))
.or_else(|| self.self_if_contains_location(byte_index)),
Self::Call { fun, arguments, .. } => arguments
.iter()
.find_map(|argument| argument.find_node(byte_index, fun, arguments))
.or_else(|| fun.find_node(byte_index))
.or_else(|| self.self_if_contains_location(byte_index)),
Self::BinOp { left, right, .. } => left
.find_node(byte_index)
.or_else(|| right.find_node(byte_index)),
Self::Case {
subjects, clauses, ..
} => subjects
.iter()
.find_map(|subject| subject.find_node(byte_index))
.or_else(|| clauses.iter().find_map(|c| c.find_node(byte_index)))
.or_else(|| self.self_if_contains_location(byte_index)),
Self::RecordAccess {
record: expression, ..
}
| Self::TupleIndex {
tuple: expression, ..
} => expression
.find_node(byte_index)
.or_else(|| self.self_if_contains_location(byte_index)),
Self::BitArray { segments, .. } => segments
.iter()
.find_map(|arg| arg.find_node(byte_index))
.or_else(|| self.self_if_contains_location(byte_index)),
Self::RecordUpdate {
record_assignment,
constructor,
arguments,
..
} => arguments
.iter()
.filter(|argument| argument.implicit.is_none())
.find_map(|argument| argument.find_node(byte_index, constructor, arguments))
.or_else(|| constructor.find_node(byte_index))
.or_else(|| {
record_assignment
.as_ref()
.and_then(|assignment| assignment.find_node(byte_index))
})
.or_else(|| self.self_if_contains_location(byte_index)),
}
}
pub fn find_statement(&self, byte_index: u32) -> Option<&TypedStatement> {
match self {
Self::Var { .. }
| Self::Int { .. }
| Self::Float { .. }
| Self::String { .. }
| Self::ModuleSelect { .. }
| Self::Invalid { .. }
| Self::PositionalAccess { .. } => None,
Self::Pipeline {
first_value,
assignments,
finally,
..
} => first_value
.find_statement(byte_index)
.or_else(|| {
assignments
.iter()
.find_map(|(e, _)| e.find_statement(byte_index))
})
.or_else(|| finally.find_statement(byte_index)),
// Exit the search and return None if during iteration a statement
// is found with a start index beyond the index under search.
Self::Block { statements, .. } => {
for statement in statements {
if statement.location().start > byte_index {
break;
}
if let Some(located) = statement.find_statement(byte_index) {
return Some(located);
}
}
None
}
// Exit the search and return the encompassing type (e.g., list or tuple)
// if during iteration, an element is encountered with a start index
// beyond the index under search.
Self::Tuple {
elements: expressions,
..
} => {
for expression in expressions {
if expression.location().start > byte_index {
break;
}
if let Some(located) = expression.find_statement(byte_index) {
return Some(located);
}
}
None
}
Self::List {
elements: expressions,
tail,
..
} => {
for expression in expressions {
if expression.location().start > byte_index {
break;
}
if let Some(located) = expression.find_statement(byte_index) {
return Some(located);
}
}
if let Some(tail) = tail
&& let Some(node) = tail.find_statement(byte_index)
{
return Some(node);
}
None
}
Self::NegateBool { value, .. } | Self::NegateInt { value, .. } => {
value.find_statement(byte_index)
}
Self::Fn { body, .. } => body.iter().find_map(|s| s.find_statement(byte_index)),
Self::Call { fun, arguments, .. } => arguments
.iter()
.find_map(|argument| argument.find_statement(byte_index))
.or_else(|| fun.find_statement(byte_index)),
Self::BinOp { left, right, .. } => left
.find_statement(byte_index)
.or_else(|| right.find_statement(byte_index)),
Self::Case {
subjects, clauses, ..
} => subjects
.iter()
.find_map(|subject| subject.find_statement(byte_index))
.or_else(|| {
clauses
.iter()
.find_map(|c| c.then.find_statement(byte_index))
}),
Self::RecordAccess {
record: expression, ..
}
| Self::TupleIndex {
tuple: expression, ..
} => expression.find_statement(byte_index),
Self::Echo {
expression,
message,
..
} => expression
.as_ref()
.and_then(|expression| expression.find_statement(byte_index))
.or_else(|| {
message
.as_ref()
.and_then(|message| message.find_statement(byte_index))
}),
Self::Todo { message, kind, .. } => match kind {
TodoKind::EmptyFunction { .. } | TodoKind::IncompleteUse | TodoKind::EmptyBlock => {
None
}
TodoKind::Keyword => message
.as_ref()
.and_then(|message| message.find_statement(byte_index)),
},
Self::Panic { message, .. } => message
.as_ref()
.and_then(|message| message.find_statement(byte_index)),
Self::BitArray { segments, .. } => segments
.iter()
.find_map(|arg| arg.value.find_statement(byte_index)),
Self::RecordUpdate {
record_assignment,
arguments,
..
} => arguments
.iter()
.filter(|arg| arg.implicit.is_none())
.find_map(|arg| arg.find_statement(byte_index))
.or_else(|| {
record_assignment
.as_ref()
.and_then(|r| r.value.find_statement(byte_index))
}),
}
}
fn self_if_contains_location(&self, byte_index: u32) -> Option<Located<'_>> {
if self.location().contains(byte_index) {
Some(self.into())
} else {
None
}
}
pub fn is_non_zero_compile_time_number(&self) -> bool {
match self {
Self::Int { int_value, .. } => int_value != &BigInt::ZERO,
Self::Float { value, .. } => is_non_zero_number(value),
Self::String { .. }
| Self::Block { .. }
| Self::Pipeline { .. }
| Self::Var { .. }
| Self::Fn { .. }
| Self::List { .. }
| Self::Call { .. }
| Self::BinOp { .. }
| Self::Case { .. }
| Self::RecordAccess { .. }
| Self::PositionalAccess { .. }
| Self::ModuleSelect { .. }
| Self::Tuple { .. }
| Self::TupleIndex { .. }
| Self::Todo { .. }
| Self::Panic { .. }
| Self::Echo { .. }
| Self::BitArray { .. }
| Self::RecordUpdate { .. }
| Self::NegateBool { .. }
| Self::NegateInt { .. }
| Self::Invalid { .. } => false,
}
}
pub fn is_zero_compile_time_number(&self) -> bool {
match self {
Self::Int { int_value, .. } => int_value == &BigInt::ZERO,
Self::Float { value, .. } => !is_non_zero_number(value),
Self::String { .. }
| Self::Block { .. }
| Self::Pipeline { .. }
| Self::Var { .. }
| Self::Fn { .. }
| Self::List { .. }
| Self::Call { .. }
| Self::BinOp { .. }
| Self::Case { .. }
| Self::RecordAccess { .. }
| Self::PositionalAccess { .. }
| Self::ModuleSelect { .. }
| Self::Tuple { .. }
| Self::TupleIndex { .. }
| Self::Todo { .. }
| Self::Panic { .. }
| Self::Echo { .. }
| Self::BitArray { .. }
| Self::RecordUpdate { .. }
| Self::NegateBool { .. }
| Self::NegateInt { .. }
| Self::Invalid { .. } => false,
}
}
pub fn location(&self) -> SrcSpan {
match self {
Self::Fn { location, .. }
| Self::Int { location, .. }
| Self::Var { location, .. }
| Self::Todo { location, .. }
| Self::Echo { location, .. }
| Self::Case { location, .. }
| Self::Call { location, .. }
| Self::List { location, .. }
| Self::Float { location, .. }
| Self::BinOp { location, .. }
| Self::Tuple { location, .. }
| Self::Panic { location, .. }
| Self::Block { location, .. }
| Self::String { location, .. }
| Self::NegateBool { location, .. }
| Self::NegateInt { location, .. }
| Self::Pipeline { location, .. }
| Self::BitArray { location, .. }
| Self::TupleIndex { location, .. }
| Self::ModuleSelect { location, .. }
| Self::RecordAccess { location, .. }
| Self::PositionalAccess { location, .. }
| Self::RecordUpdate { location, .. }
| Self::Invalid { location, .. } => *location,
}
}
pub fn type_defining_location(&self) -> SrcSpan {
match self {
Self::Fn { location, .. }
| Self::Int { location, .. }
| Self::Var { location, .. }
| Self::Todo { location, .. }
| Self::Echo { location, .. }
| Self::Case { location, .. }
| Self::Call { location, .. }
| Self::List { location, .. }
| Self::Float { location, .. }
| Self::BinOp { location, .. }
| Self::Tuple { location, .. }
| Self::String { location, .. }
| Self::Panic { location, .. }
| Self::NegateBool { location, .. }
| Self::NegateInt { location, .. }
| Self::Pipeline { location, .. }
| Self::BitArray { location, .. }
| Self::TupleIndex { location, .. }
| Self::ModuleSelect { location, .. }
| Self::RecordAccess { location, .. }
| Self::PositionalAccess { location, .. }
| Self::RecordUpdate { location, .. }
| Self::Invalid { location, .. } => *location,
Self::Block { statements, .. } => statements.last().location(),
}
}
pub fn definition_location(&self) -> Option<DefinitionLocation> {
match self {
TypedExpr::Fn { .. }
| TypedExpr::Int { .. }
| TypedExpr::List { .. }
| TypedExpr::Call { .. }
| TypedExpr::Case { .. }
| TypedExpr::Todo { .. }
| TypedExpr::Echo { .. }
| TypedExpr::Panic { .. }
| TypedExpr::BinOp { .. }
| TypedExpr::Float { .. }
| TypedExpr::Tuple { .. }
| TypedExpr::NegateBool { .. }
| TypedExpr::NegateInt { .. }
| TypedExpr::String { .. }
| TypedExpr::Block { .. }
| TypedExpr::Pipeline { .. }
| TypedExpr::BitArray { .. }
| TypedExpr::TupleIndex { .. }
| TypedExpr::RecordAccess { .. }
| TypedExpr::PositionalAccess { .. }
| Self::Invalid { .. } => None,
// TODO: test
// TODO: definition
TypedExpr::RecordUpdate { .. } => None,
// TODO: test
TypedExpr::ModuleSelect {
module_name,
constructor,
..
} => Some(DefinitionLocation {
module: Some(module_name.clone()),
span: constructor.location(),
}),
// TODO: test
TypedExpr::Var { constructor, .. } => Some(constructor.definition_location()),
}
}
pub fn type_(&self) -> Arc<Type> {
match self {
Self::NegateBool { .. } => bool(),
Self::NegateInt { value, .. } => value.type_(),
Self::Var { constructor, .. } => constructor.type_.clone(),
Self::Fn { type_, .. }
| Self::Int { type_, .. }
| Self::Todo { type_, .. }
| Self::Echo { type_, .. }
| Self::Case { type_, .. }
| Self::List { type_, .. }
| Self::Call { type_, .. }
| Self::Float { type_, .. }
| Self::Panic { type_, .. }
| Self::BinOp { type_, .. }
| Self::Tuple { type_, .. }
| Self::String { type_, .. }
| Self::BitArray { type_, .. }
| Self::TupleIndex { type_, .. }
| Self::ModuleSelect { type_, .. }
| Self::RecordAccess { type_, .. }
| Self::PositionalAccess { type_, .. }
| Self::RecordUpdate { type_, .. }
| Self::Invalid { type_, .. } => type_.clone(),
Self::Pipeline { finally, .. } => finally.type_(),
Self::Block { statements, .. } => statements.last().type_(),
}
}
pub fn is_literal(&self) -> bool {
match self {
Self::Int { .. } | Self::Float { .. } | Self::String { .. } => true,
Self::List { elements, .. } | Self::Tuple { elements, .. } => {
elements.iter().all(|value| value.is_literal())
}
Self::BitArray { segments, .. } => {
segments.iter().all(|segment| segment.value.is_literal())
}
// Calls are literals if they are records and all the arguemnts are also literals.
Self::Call { fun, arguments, .. } => {
fun.is_record_literal()
&& arguments.iter().all(|argument| argument.value.is_literal())
}
// Variables are literals if they are record constructors that take no arguments.
Self::Var {
constructor:
ValueConstructor {
variant: ValueConstructorVariant::Record { arity: 0, .. },
..
},
..
} => true,
Self::Block { .. }
| Self::Pipeline { .. }
| Self::Var { .. }
| Self::Fn { .. }
| Self::BinOp { .. }
| Self::Case { .. }
| Self::RecordAccess { .. }
| Self::PositionalAccess { .. }
| Self::ModuleSelect { .. }
| Self::TupleIndex { .. }
| Self::Todo { .. }
| Self::Panic { .. }
| Self::Echo { .. }
| Self::RecordUpdate { .. }
| Self::NegateBool { .. }
| Self::NegateInt { .. }
| Self::Invalid { .. } => false,
}
}
pub fn is_known_bool(&self) -> bool {
match self {
TypedExpr::BinOp {
left, right, name, ..
} if name.is_bool_operator() => left.is_known_bool() && right.is_known_bool(),
TypedExpr::NegateBool { value, .. } => value.is_known_bool(),
TypedExpr::Int { .. }
| TypedExpr::Float { .. }
| TypedExpr::String { .. }
| TypedExpr::Block { .. }
| TypedExpr::Pipeline { .. }
| TypedExpr::Var { .. }
| TypedExpr::Fn { .. }
| TypedExpr::List { .. }
| TypedExpr::Call { .. }
| TypedExpr::BinOp { .. }
| TypedExpr::Case { .. }
| TypedExpr::RecordAccess { .. }
| TypedExpr::PositionalAccess { .. }
| TypedExpr::ModuleSelect { .. }
| TypedExpr::Tuple { .. }
| TypedExpr::TupleIndex { .. }
| TypedExpr::Todo { .. }
| TypedExpr::Panic { .. }
| TypedExpr::Echo { .. }
| TypedExpr::BitArray { .. }
| TypedExpr::RecordUpdate { .. }
| TypedExpr::NegateInt { .. }
| TypedExpr::Invalid { .. } => self.is_literal(),
}
}
pub fn is_literal_string(&self) -> bool {
matches!(self, Self::String { .. })
}
/// Returns `true` if the typed expr is [`Var`].
///
/// [`Var`]: TypedExpr::Var
#[must_use]
pub fn is_var(&self) -> bool {
matches!(self, Self::Var { .. })
}
pub fn get_documentation(&self) -> Option<&str> {
match self {
TypedExpr::Var { constructor, .. } => constructor.get_documentation(),
TypedExpr::ModuleSelect { constructor, .. } => constructor.get_documentation(),
TypedExpr::RecordAccess { documentation, .. } => documentation.as_deref(),
TypedExpr::Int { .. }
| TypedExpr::Float { .. }
| TypedExpr::String { .. }
| TypedExpr::Block { .. }
| TypedExpr::Pipeline { .. }
| TypedExpr::Fn { .. }
| TypedExpr::List { .. }
| TypedExpr::Call { .. }
| TypedExpr::BinOp { .. }
| TypedExpr::Case { .. }
| TypedExpr::Tuple { .. }
| TypedExpr::TupleIndex { .. }
| TypedExpr::Todo { .. }
| TypedExpr::Echo { .. }
| TypedExpr::Panic { .. }
| TypedExpr::BitArray { .. }
| TypedExpr::RecordUpdate { .. }
| TypedExpr::NegateBool { .. }
| TypedExpr::NegateInt { .. }
| TypedExpr::PositionalAccess { .. }
| TypedExpr::Invalid { .. } => None,
}
}
/// Returns `true` if the typed expr is [`Case`].
///
/// [`Case`]: TypedExpr::Case
#[must_use]
pub fn is_case(&self) -> bool {
matches!(self, Self::Case { .. })
}
/// Returns `true` if the typed expr is [`Pipeline`].
///
/// [`Pipeline`]: TypedExpr::Pipeline
#[must_use]
pub fn is_pipeline(&self) -> bool {
matches!(self, Self::Pipeline { .. })
}
pub fn is_pure_value_constructor(&self) -> bool {
match self {
TypedExpr::Int { .. }
| TypedExpr::Float { .. }
| TypedExpr::String { .. }
| TypedExpr::List { .. }
| TypedExpr::Tuple { .. }
| TypedExpr::BitArray { .. }
| TypedExpr::Var { .. }
| TypedExpr::BinOp { .. }
| TypedExpr::RecordAccess { .. }
| TypedExpr::PositionalAccess { .. }
| TypedExpr::TupleIndex { .. }
| TypedExpr::RecordUpdate { .. }
| TypedExpr::Fn { .. } => true,
TypedExpr::NegateBool { value, .. } | TypedExpr::NegateInt { value, .. } => {
value.is_pure_value_constructor()
}
// Just selecting a value from a module never has any effects. The
// selected thing might be a function but it has no side effects as
// long as it's not called!
TypedExpr::ModuleSelect { .. } => true,
// A pipeline is a pure value constructor if its last step is a record builder,
// or a call to a pure function. For example:
// - `wibble() |> wobble() |> Ok`
// - `"hello" |> fn(s) { s <> " world!" }`
TypedExpr::Pipeline {
first_value,
assignments,
finally,
..
} => {
first_value.value.is_pure_value_constructor()
&& assignments
.iter()
.all(|(assignment, _)| assignment.value.is_pure_value_constructor())
&& finally.is_pure_value_constructor()
}
TypedExpr::Call { fun, arguments, .. } => {
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | true |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests.rs | compiler-core/src/javascript/tests.rs | use crate::{
analyse::TargetSupport,
build::{Origin, Target},
config::PackageConfig,
inline,
javascript::*,
uid::UniqueIdGenerator,
warning::{TypeWarningEmitter, WarningEmitter},
};
use camino::{Utf8Path, Utf8PathBuf};
mod assert;
mod assignments;
mod bit_arrays;
mod blocks;
mod bools;
mod case;
mod case_clause_guards;
mod consts;
mod custom_types;
mod echo;
mod externals;
mod functions;
mod generics;
mod inlining;
mod lists;
mod modules;
mod numbers;
mod panic;
mod prelude;
mod records;
mod recursion;
mod results;
mod strings;
mod todo;
mod tuples;
mod type_alias;
mod use_;
pub static CURRENT_PACKAGE: &str = "thepackage";
#[macro_export]
macro_rules! assert_js {
($(($name:literal, $module_src:literal)),+, $src:literal $(,)?) => {
let compiled =
$crate::javascript::tests::compile_js($src, vec![$(($crate::javascript::tests::CURRENT_PACKAGE, $name, $module_src)),*]);
let mut output = String::from("----- SOURCE CODE\n");
for (name, src) in [$(($name, $module_src)),*] {
output.push_str(&format!("-- {name}.gleam\n{src}\n\n"));
}
output.push_str(&format!("-- main.gleam\n{}\n\n----- COMPILED JAVASCRIPT\n{compiled}", $src));
insta::assert_snapshot!(insta::internals::AutoName, output, $src);
};
($(($dep_package:expr, $dep_name:expr, $dep_src:expr)),+, $src:literal $(,)?) => {{
let compiled =
$crate::javascript::tests::compile_js($src, vec![$(($dep_package, $dep_name, $dep_src)),*]);
let output = format!(
"----- SOURCE CODE\n{}\n\n----- COMPILED JAVASCRIPT\n{}",
$src, compiled
);
insta::assert_snapshot!(insta::internals::AutoName, output, $src);
}};
(($dep_package:expr, $dep_name:expr, $dep_src:expr), $src:expr, $js:expr $(,)?) => {{
let output =
$crate::javascript::tests::compile_js($src, Some(($dep_package, $dep_name, $dep_src)));
assert_eq!(($src, output), ($src, $js.to_string()));
}};
($src:expr $(,)?) => {{
let compiled =
$crate::javascript::tests::compile_js($src, vec![]);
let output = format!(
"----- SOURCE CODE\n{}\n\n----- COMPILED JAVASCRIPT\n{}",
$src, compiled
);
insta::assert_snapshot!(insta::internals::AutoName, output, $src);
}};
($src:expr, $js:expr $(,)?) => {{
let output =
$crate::javascript::tests::compile_js($src, vec![]);
assert_eq!(($src, output), ($src, $js.to_string()));
}};
}
#[macro_export]
macro_rules! assert_ts_def {
(($dep_1_package:expr, $dep_1_name:expr, $dep_1_src:expr), ($dep_2_package:expr, $dep_2_name:expr, $dep_2_src:expr), $src:expr $(,)?) => {{
let compiled = $crate::javascript::tests::compile_ts(
$src,
vec![
($dep_1_package, $dep_1_name, $dep_1_src),
($dep_2_package, $dep_2_name, $dep_2_src),
],
);
let output = format!(
"----- SOURCE CODE\n{}\n\n----- TYPESCRIPT DEFINITIONS\n{}",
$src, compiled
);
insta::assert_snapshot!(insta::internals::AutoName, output, $src);
}};
(($dep_package:expr, $dep_name:expr, $dep_src:expr), $src:expr $(,)?) => {{
let compiled =
$crate::javascript::tests::compile_ts($src, vec![($dep_package, $dep_name, $dep_src)]);
let output = format!(
"----- SOURCE CODE\n{}\n\n----- TYPESCRIPT DEFINITIONS\n{}",
$src, compiled
);
insta::assert_snapshot!(insta::internals::AutoName, output, $src);
}};
($src:expr $(,)?) => {{
let compiled = $crate::javascript::tests::compile_ts($src, vec![]);
let output = format!(
"----- SOURCE CODE\n{}\n\n----- TYPESCRIPT DEFINITIONS\n{}",
$src, compiled
);
insta::assert_snapshot!(insta::internals::AutoName, output, $src);
}};
}
pub fn compile(src: &str, deps: Vec<(&str, &str, &str)>) -> TypedModule {
let mut modules = im::HashMap::new();
let ids = UniqueIdGenerator::new();
// DUPE: preludeinsertion
// TODO: Currently we do this here and also in the tests. It would be better
// to have one place where we create all this required state for use in each
// place.
let _ = modules.insert(
PRELUDE_MODULE_NAME.into(),
crate::type_::build_prelude(&ids),
);
let mut direct_dependencies = HashMap::from_iter(vec![]);
deps.iter().for_each(|(dep_package, dep_name, dep_src)| {
let mut dep_config = PackageConfig::default();
dep_config.name = (*dep_package).into();
let parsed = crate::parse::parse_module(
Utf8PathBuf::from("test/path"),
dep_src,
&WarningEmitter::null(),
)
.expect("dep syntax error");
let mut ast = parsed.module;
ast.name = (*dep_name).into();
let line_numbers = LineNumbers::new(dep_src);
let dep = crate::analyse::ModuleAnalyzerConstructor::<()> {
target: Target::JavaScript,
ids: &ids,
origin: Origin::Src,
importable_modules: &modules,
warnings: &TypeWarningEmitter::null(),
direct_dependencies: &HashMap::new(),
dev_dependencies: &std::collections::HashSet::new(),
target_support: TargetSupport::Enforced,
package_config: &dep_config,
}
.infer_module(ast, line_numbers, "".into())
.expect("should successfully infer");
let _ = modules.insert((*dep_name).into(), dep.type_info);
let _ = direct_dependencies.insert((*dep_package).into(), ());
});
let parsed =
crate::parse::parse_module(Utf8PathBuf::from("test/path"), src, &WarningEmitter::null())
.expect("syntax error");
let mut ast = parsed.module;
ast.name = "my/mod".into();
let line_numbers = LineNumbers::new(src);
let mut config = PackageConfig::default();
config.name = "thepackage".into();
let module = crate::analyse::ModuleAnalyzerConstructor::<()> {
target: Target::JavaScript,
ids: &ids,
origin: Origin::Src,
importable_modules: &modules,
warnings: &TypeWarningEmitter::null(),
direct_dependencies: &direct_dependencies,
dev_dependencies: &std::collections::HashSet::new(),
target_support: TargetSupport::NotEnforced,
package_config: &config,
}
.infer_module(ast, line_numbers, "src/module.gleam".into())
.expect("should successfully infer");
inline::module(module, &modules)
}
pub fn compile_js(src: &str, deps: Vec<(&str, &str, &str)>) -> String {
let ast = compile(src, deps);
let line_numbers = LineNumbers::new(src);
let stdlib_package = StdlibPackage::Present;
let output = module(ModuleConfig {
module: &ast,
line_numbers: &line_numbers,
src: &"".into(),
typescript: TypeScriptDeclarations::None,
stdlib_package,
path: Utf8Path::new("src/module.gleam"),
project_root: "project/root".into(),
});
output.replace(
std::include_str!("../../templates/echo.mjs"),
"// ...omitted code from `templates/echo.mjs`...",
)
}
pub fn compile_ts(src: &str, deps: Vec<(&str, &str, &str)>) -> String {
let ast = compile(src, deps);
ts_declaration(&ast)
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/typescript.rs | compiler-core/src/javascript/typescript.rs | //! This module is responsible for generating TypeScript type declaration files.
//! This code is run during the code generation phase along side the normal
//! Javascript code emission. Here we walk through the typed AST and translate
//! the Gleam statements into their TypeScript equivalent. Unlike the Javascript
//! code generation, the TypeScript generation only needs to look at the module
//! statements and not the expressions that may be _inside_ those statements.
//! This is due to the TypeScript declarations only caring about inputs and outputs
//! rather than _how_ those outputs are generated.
//!
//! ## Links
//! <https://www.typescriptlang.org/>
//! <https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html>
use crate::ast::{
AssignName, Publicity, TypedCustomType, TypedFunction, TypedModuleConstant, TypedTypeAlias,
};
use crate::javascript::import::Member;
use crate::type_::{PRELUDE_MODULE_NAME, RecordAccessor, is_prelude_module};
use crate::{
ast::{TypedModule, TypedRecordConstructor},
docvec,
javascript::JavaScriptCodegenTarget,
pretty::{Document, Documentable, break_},
type_::{Type, TypeVar},
};
use ecow::{EcoString, eco_format};
use itertools::Itertools;
use std::{collections::HashMap, ops::Deref, sync::Arc};
use super::{INDENT, concat, import::Imports, join, line, lines, wrap_arguments};
/// When rendering a type variable to an TypeScript type spec we need all type
/// variables with the same id to end up with the same name in the generated
/// TypeScript. This function converts a usize into base 26 A-Z for this purpose.
fn id_to_type_var(id: u64) -> Document<'static> {
if id < 26 {
return std::iter::once(
std::char::from_u32((id % 26 + 65) as u32).expect("id_to_type_var 0"),
)
.collect::<EcoString>()
.to_doc();
}
let mut name = vec![];
let mut last_char = id;
while last_char >= 26 {
name.push(std::char::from_u32((last_char % 26 + 65) as u32).expect("id_to_type_var 1"));
last_char /= 26;
}
name.push(std::char::from_u32((last_char % 26 + 64) as u32).expect("id_to_type_var 2"));
name.reverse();
name.into_iter().collect::<EcoString>().to_doc()
}
fn name_with_generics<'a>(
name: Document<'a>,
types: impl IntoIterator<Item = &'a Arc<Type>>,
) -> Document<'a> {
let generic_usages = collect_generic_usages(HashMap::new(), types);
let generic_names: Vec<Document<'_>> = generic_usages
.keys()
.map(|id| id_to_type_var(*id))
.collect();
docvec![
name,
if generic_names.is_empty() {
super::nil()
} else {
wrap_generic_arguments(generic_names)
},
]
}
/// A generic can either be rendered as an actual type variable such as `A` or `B`,
/// or it can be rendered as `any` depending on how many usages it has. If it
/// has only 1 usage it is an `any` type. If it has more than 1 usage it is a
/// TS generic. This function gathers usages for this determination.
///
/// Examples:
/// fn(a) -> String // `a` is `any`
/// `fn()` -> Result(a, b) // `a` and `b` are `any`
/// fn(a) -> a // `a` is a generic
fn collect_generic_usages<'a>(
mut ids: HashMap<u64, u64>,
types: impl IntoIterator<Item = &'a Arc<Type>>,
) -> HashMap<u64, u64> {
for type_ in types {
generic_ids(type_, &mut ids);
}
ids
}
fn generic_ids(type_: &Type, ids: &mut HashMap<u64, u64>) {
match type_ {
Type::Var { type_ } => match type_.borrow().deref() {
TypeVar::Unbound { id, .. } | TypeVar::Generic { id, .. } => {
let count = ids.entry(*id).or_insert(0);
*count += 1;
}
TypeVar::Link { type_ } => generic_ids(type_, ids),
},
Type::Named { arguments, .. } => {
for argument in arguments {
generic_ids(argument, ids)
}
}
Type::Fn { arguments, return_ } => {
for argument in arguments {
generic_ids(argument, ids)
}
generic_ids(return_, ids);
}
Type::Tuple { elements } => {
for element in elements {
generic_ids(element, ids)
}
}
}
}
/// Prints a Gleam tuple in the TypeScript equivalent syntax
///
fn tuple<'a>(elements: impl IntoIterator<Item = Document<'a>>) -> Document<'a> {
break_("", "")
.append(join(elements, break_(",", ", ")))
.nest(INDENT)
.append(break_("", ""))
.surround("[", "]")
.group()
}
fn wrap_generic_arguments<'a, I>(arguments: I) -> Document<'a>
where
I: IntoIterator<Item = Document<'a>>,
{
break_("", "")
.append(join(arguments, break_(",", ", ")))
.nest(INDENT)
.append(break_("", ""))
.surround("<", ">")
.group()
}
/// Returns a name that can be used as a TypeScript type name. If there is a
/// naming clash a '_' will be appended.
///
fn ts_safe_type_name(mut name: String) -> EcoString {
if matches!(
name.as_str(),
"any"
| "boolean"
| "constructor"
| "declare"
| "get"
| "module"
| "require"
| "number"
| "set"
| "string"
| "symbol"
| "type"
| "from"
| "of"
) {
name.push('_');
EcoString::from(name)
} else {
super::maybe_escape_identifier_string(&name)
}
}
/// The `TypeScriptGenerator` contains the logic of how to convert Gleam's typed
/// AST into the equivalent TypeScript type declaration file.
///
#[derive(Debug)]
pub struct TypeScriptGenerator<'a> {
module: &'a TypedModule,
aliased_module_names: HashMap<&'a str, &'a str>,
tracker: UsageTracker,
current_module_name_segments_count: usize,
}
impl<'a> TypeScriptGenerator<'a> {
pub fn new(module: &'a TypedModule) -> Self {
let current_module_name_segments_count = module.name.split('/').count();
Self {
module,
aliased_module_names: HashMap::new(),
tracker: UsageTracker::default(),
current_module_name_segments_count,
}
}
pub fn compile(&mut self) -> Document<'a> {
let mut imports = self.collect_imports();
let statements = self.definitions(&mut imports);
// Two lines between each statement
let mut statements = Itertools::intersperse(statements.into_iter(), lines(2)).collect_vec();
// Put it all together
if self.prelude_used() {
let path = self.import_path(&self.module.type_info.package, PRELUDE_MODULE_NAME);
imports.register_module(path, ["_".into()], []);
}
if imports.is_empty() && statements.is_empty() {
docvec!["export {}", line()]
} else if imports.is_empty() {
statements.push(line());
statements.to_doc()
} else if statements.is_empty() {
imports.into_doc(JavaScriptCodegenTarget::TypeScriptDeclarations)
} else {
docvec![
imports.into_doc(JavaScriptCodegenTarget::TypeScriptDeclarations),
line(),
statements,
line()
]
}
}
fn collect_imports(&mut self) -> Imports<'a> {
let mut imports = Imports::new();
for function in &self.module.definitions.functions {
for argument in &function.arguments {
self.collect_imports_for_type(&argument.type_, &mut imports);
}
self.collect_imports_for_type(&function.return_type, &mut imports);
}
for type_alias in &self.module.definitions.type_aliases {
self.collect_imports_for_type(&type_alias.type_, &mut imports);
}
for custom_type in &self.module.definitions.custom_types {
for type_ in &custom_type.typed_parameters {
self.collect_imports_for_type(type_, &mut imports);
}
for constructor in &custom_type.constructors {
for argument in &constructor.arguments {
self.collect_imports_for_type(&argument.type_, &mut imports);
}
}
}
for constant in &self.module.definitions.constants {
self.collect_imports_for_type(&constant.type_, &mut imports);
}
for import in &self.module.definitions.imports {
match &import.as_name {
Some((AssignName::Variable(name), _)) => {
let _ = self.aliased_module_names.insert(&import.module, name);
}
Some((AssignName::Discard(_), _)) | None => (),
}
}
imports
}
/// Recurses through a type and any types it references, registering all of their imports.
///
fn collect_imports_for_type<'b>(&mut self, type_: &'b Type, imports: &mut Imports<'a>) {
match &type_ {
Type::Named {
package,
module,
arguments,
..
} => {
let is_prelude = module == "gleam" && package.is_empty();
let is_current_module = *module == self.module.name;
if !is_prelude && !is_current_module {
self.register_import(imports, package, module);
}
for argument in arguments {
self.collect_imports_for_type(argument, imports);
}
}
Type::Fn { arguments, return_ } => {
for argument in arguments {
self.collect_imports_for_type(argument, imports);
}
self.collect_imports_for_type(return_, imports);
}
Type::Tuple { elements } => {
for element in elements {
self.collect_imports_for_type(element, imports);
}
}
Type::Var { type_ } => {
if let TypeVar::Link { type_ } = type_
.as_ref()
.try_borrow()
.expect("borrow type after inference")
.deref()
{
self.collect_imports_for_type(type_, imports);
}
}
}
}
/// Registers an import of an external module so that it can be added to
/// the top of the generated Document. The module names are prefixed with a
/// "$" symbol to prevent any clashes with other Gleam names that may be
/// used in this module.
///
fn register_import<'b>(
&mut self,
imports: &mut Imports<'a>,
package: &'b str,
module: &'b str,
) {
let path = self.import_path(package, module);
imports.register_module(path, [self.module_name(module)], []);
}
/// Calculates the path of where to import an external module from
///
fn import_path<'b>(&self, package: &'b str, module: &'b str) -> EcoString {
// DUPE: current_module_name_segments_count
// TODO: strip shared prefixed between current module and imported
// module to avoid descending and climbing back out again
if package == self.module.type_info.package || package.is_empty() {
// Same package
match self.current_module_name_segments_count {
1 => eco_format!("./{module}.d.mts"),
_ => {
let prefix = "../".repeat(self.current_module_name_segments_count - 1);
eco_format!("{prefix}{module}.d.mts")
}
}
} else {
// Different package
let prefix = "../".repeat(self.current_module_name_segments_count);
eco_format!("{prefix}{package}/{module}.d.mts")
}
}
fn definitions(&mut self, imports: &mut Imports<'_>) -> Vec<Document<'a>> {
let mut documents = vec![];
for custom_type in &self.module.definitions.custom_types {
if let Some(mut new_documents) = self.custom_type_definition(custom_type, imports) {
documents.append(&mut new_documents);
}
}
for type_alias in &self.module.definitions.type_aliases {
if let Some(document) = self.type_alias(type_alias) {
documents.push(document);
}
}
for constant in &self.module.definitions.constants {
if let Some(document) = self.module_constant(constant) {
documents.push(document);
}
}
for function in &self.module.definitions.functions {
if let Some(document) = self.module_function(function) {
documents.push(document);
}
}
documents
}
fn type_alias(&mut self, type_alias: &TypedTypeAlias) -> Option<Document<'a>> {
if !type_alias.publicity.is_importable() {
return None;
}
Some(docvec![
"export type ",
ts_safe_type_name(type_alias.alias.to_string()),
" = ",
self.print_type(&type_alias.type_),
";"
])
}
/// Converts a Gleam custom type definition into the TypeScript equivalent.
/// In Gleam, all custom types have one to many concrete constructors. This
/// function first converts the constructors into TypeScript then finally
/// emits a union type to represent the TypeScript type itself. Because in
/// Gleam constructors can have the same name as the custom type, here we
/// append a "$" symbol to the emitted TypeScript type to prevent those
/// naming classes.
///
fn custom_type_definition(
&mut self,
custom_type: &'a TypedCustomType,
imports: &mut Imports<'_>,
) -> Option<Vec<Document<'a>>> {
let TypedCustomType {
name,
publicity,
constructors,
opaque,
typed_parameters,
external_javascript,
..
} = custom_type;
// Constructors for opaque and private types are not exported
let constructor_publicity = if publicity.is_private() || *opaque {
Publicity::Private
} else {
Publicity::Public
};
let type_name = name_with_generics(eco_format!("{name}$").to_doc(), typed_parameters);
let mut definitions = constructors
.iter()
.map(|constructor| {
self.variant_definition(
constructor,
constructor_publicity,
name,
&type_name,
typed_parameters,
)
})
.collect_vec();
let definition = if constructors.is_empty() {
if let Some((module, external_name, _location)) = external_javascript {
let member = Member {
name: external_name.to_doc(),
alias: Some(eco_format!("{name}$").to_doc()),
};
imports.register_export(eco_format!("{name}$"));
imports.register_module(module.clone(), [], [member]);
return Some(Vec::new());
} else {
"any".to_doc()
}
} else {
let constructors = constructors.iter().map(|x| {
name_with_generics(
super::maybe_escape_identifier(&x.name).to_doc(),
x.arguments.iter().map(|a| &a.type_),
)
});
join(constructors, break_("| ", " | "))
};
let head = if publicity.is_private() {
"type "
} else {
"export type "
};
definitions.push(docvec![head, type_name.clone(), " = ", definition, ";",]);
// Generate getters for fields shared between variants
if let Some(accessors_map) = self.module.type_info.accessors.get(name)
&& !accessors_map.shared_accessors.is_empty()
// Don't bother generating shared getters when there's only one variant,
// since the specific accessors can always be uses instead.
&& constructors.len() != 1
// Only generate accessors for the API if the constructors are public
&& constructor_publicity.is_public()
{
definitions.push(self.shared_custom_type_fields(
name,
&type_name,
typed_parameters,
&accessors_map.shared_accessors,
));
}
Some(definitions)
}
fn variant_definition(
&mut self,
constructor: &'a TypedRecordConstructor,
publicity: Publicity,
type_name: &'a str,
type_name_with_generics: &Document<'a>,
type_parameters: &'a [Arc<Type>],
) -> Document<'a> {
self.set_prelude_used();
let class_definition = self.variant_class_definition(constructor, publicity);
// If the custom type is private or opaque, we don't need to generate API
// functions for it.
if publicity.is_private() {
return class_definition;
}
let constructor_definition = self.variant_constructor_definition(
constructor,
type_name,
type_name_with_generics,
type_parameters,
);
let variant_check_definition = self.variant_check_definition(
constructor,
type_name,
type_name_with_generics,
type_parameters,
);
let fields_definition = self.variant_fields_definition(
constructor,
type_name,
type_name_with_generics,
type_parameters,
);
docvec![
class_definition,
line(),
constructor_definition,
line(),
variant_check_definition,
fields_definition,
]
}
fn variant_class_definition(
&mut self,
constructor: &'a TypedRecordConstructor,
publicity: Publicity,
) -> Document<'a> {
let head = docvec![
if publicity.is_public() {
"export ".to_doc()
} else {
"declare ".to_doc()
},
"class ",
name_with_generics(
super::maybe_escape_identifier(&constructor.name).to_doc(),
constructor.arguments.iter().map(|a| &a.type_)
),
" extends _.CustomType {"
];
if constructor.arguments.is_empty() {
return head.append("}");
};
let class_body = docvec![
line(),
"/** @deprecated */",
line(),
// First add the constructor
"constructor",
wrap_arguments(
constructor
.arguments
.iter()
.enumerate()
.map(|(i, argument)| {
let name = argument
.label
.as_ref()
.map(|(_, s)| super::maybe_escape_identifier(s))
.unwrap_or_else(|| eco_format!("argument${i}"))
.to_doc();
docvec![
name,
": ",
self.do_print_force_generic_param(&argument.type_)
]
})
),
";",
line(),
// Then add each field to the class
join(
constructor.arguments.iter().enumerate().map(|(i, arg)| {
let name = arg
.label
.as_ref()
.map(|(_, s)| super::maybe_escape_identifier(s))
.unwrap_or_else(|| eco_format!("{i}"))
.to_doc();
docvec![
"/** @deprecated */",
line(),
name,
": ",
self.do_print_force_generic_param(&arg.type_),
";"
]
}),
line(),
),
]
.nest(INDENT);
docvec![head, class_body, line(), "}"]
}
fn variant_constructor_definition(
&mut self,
constructor: &'a TypedRecordConstructor,
type_name: &'a str,
type_name_with_generics: &Document<'a>,
type_parameters: &'a [Arc<Type>],
) -> Document<'a> {
let mut arguments = Vec::new();
for (index, parameter) in constructor.arguments.iter().enumerate() {
let name = if let Some((_, label)) = ¶meter.label {
super::maybe_escape_identifier(label)
} else {
eco_format!("${index}")
};
arguments.push(docvec![
name,
": ",
self.do_print_force_generic_param(¶meter.type_)
])
}
let function_name = eco_format!(
"{type_name}${variant_name}",
variant_name = constructor.name
)
.to_doc();
let has_arguments = !arguments.is_empty();
docvec![
"export function ",
name_with_generics(function_name, type_parameters),
"(",
docvec![break_("", ""), join(arguments, break_(",", ", ")),].nest(INDENT),
break_(if has_arguments { "," } else { "" }, ""),
"): ",
type_name_with_generics.clone(),
";"
]
.group()
}
fn variant_check_definition(
&self,
constructor: &'a TypedRecordConstructor,
type_name: &'a str,
type_name_with_generics: &Document<'a>,
type_parameters: &'a [Arc<Type>],
) -> Document<'a> {
let function_name = eco_format!(
"{type_name}$is{variant_name}",
variant_name = constructor.name
)
.to_doc();
docvec![
"export function ",
name_with_generics(function_name, type_parameters),
"(",
docvec![break_("", "",), "value: ", type_name_with_generics.clone(),].nest(INDENT),
break_(",", ""),
"): boolean;",
]
.group()
}
fn variant_fields_definition(
&mut self,
constructor: &'a TypedRecordConstructor,
type_name: &'a str,
type_name_with_generics: &Document<'a>,
type_parameters: &'a [Arc<Type>],
) -> Document<'a> {
let mut functions = Vec::new();
for (index, argument) in constructor.arguments.iter().enumerate() {
// Always generate the accessor for the value at this index. Although
// this is not necessary when a label is present, we want to make sure
// that adding a label to a record isn't a breaking change. For this
// reason, we need to generate an index getter even when a label is
// present to ensure consistent behaviour between labelled and unlabelled
// field access.
let function_name = eco_format!(
"{type_name}${variant_name}${index}",
variant_name = constructor.name
)
.to_doc();
functions.push(
docvec![
line(),
"export function ",
name_with_generics(function_name, type_parameters),
"(",
docvec![break_("", "",), "value: ", type_name_with_generics.clone(),]
.nest(INDENT),
break_(",", ""),
"): ",
self.do_print_force_generic_param(&argument.type_),
";",
]
.group(),
);
// If the argument is labelled, also generate a getter for the labelled
// argument.
if let Some((_, label)) = &argument.label {
let function_name = eco_format!(
"{type_name}${variant_name}${label}",
variant_name = constructor.name
)
.to_doc();
functions.push(
docvec![
line(),
"export function ",
name_with_generics(function_name, type_parameters),
"(",
docvec![break_("", "",), "value: ", type_name_with_generics.clone(),]
.nest(INDENT),
break_(",", ""),
"): ",
self.do_print_force_generic_param(&argument.type_),
";",
]
.group(),
);
}
}
concat(functions)
}
fn shared_custom_type_fields(
&mut self,
type_name: &'a str,
type_name_with_generics: &Document<'a>,
type_parameters: &'a [Arc<Type>],
shared_accessors: &HashMap<EcoString, RecordAccessor>,
) -> Document<'a> {
let accessors = shared_accessors
.iter()
.sorted_by_key(|(name, _)| *name)
.map(|(field, accessor)| {
let function_name = eco_format!("{type_name}${field}").to_doc();
docvec![
"export function ",
name_with_generics(function_name, type_parameters),
"(",
docvec![break_("", "",), "value: ", type_name_with_generics.clone(),]
.nest(INDENT),
break_(",", ""),
"): ",
self.do_print_force_generic_param(&accessor.type_),
";"
]
.group()
});
join(accessors, line())
}
fn module_constant(&mut self, constant: &TypedModuleConstant) -> Option<Document<'a>> {
if !constant.publicity.is_importable() {
return None;
}
Some(docvec![
"export const ",
super::maybe_escape_identifier(&constant.name),
": ",
self.print_type(&constant.value.type_()),
";",
])
}
fn module_function(&mut self, function: &'a TypedFunction) -> Option<Document<'a>> {
let TypedFunction {
name: Some((_, name)),
arguments,
publicity,
return_type,
..
} = function
else {
return None;
};
if !publicity.is_importable() {
return None;
}
let generic_usages = collect_generic_usages(
HashMap::new(),
std::iter::once(return_type).chain(arguments.iter().map(|a| &a.type_)),
);
let generic_names: Vec<Document<'_>> = generic_usages
.iter()
.filter(|(_id, use_count)| **use_count > 1)
.sorted_by_key(|x| x.0)
.map(|(id, _use_count)| id_to_type_var(*id))
.collect();
Some(docvec![
"export function ",
super::maybe_escape_identifier(name),
if generic_names.is_empty() {
super::nil()
} else {
wrap_generic_arguments(generic_names)
},
wrap_arguments(arguments.iter().enumerate().map(|(i, argument)| {
match argument.get_variable_name() {
None => {
docvec![
"x",
i,
": ",
self.print_type_with_generic_usages(&argument.type_, &generic_usages)
]
}
Some(name) => docvec![
super::maybe_escape_identifier(name),
": ",
self.print_type_with_generic_usages(&argument.type_, &generic_usages)
],
}
}),),
": ",
self.print_type_with_generic_usages(return_type, &generic_usages),
";",
])
}
/// Converts a Gleam type into a TypeScript type string
///
pub fn print_type(&mut self, type_: &Type) -> Document<'static> {
self.do_print(type_, None)
}
/// Helper function for generating a TypeScript type string after collecting
/// all of the generics used in a statement
///
pub fn print_type_with_generic_usages(
&mut self,
type_: &Type,
generic_usages: &HashMap<u64, u64>,
) -> Document<'static> {
self.do_print(type_, Some(generic_usages))
}
/// Get the locally used name for a module. Either the last segment, or the
/// alias if one was given when imported.
///
fn module_name(&self, name: &str) -> EcoString {
// The prelude is always `_`
if name.is_empty() {
return "_".into();
}
let name = match self.aliased_module_names.get(name) {
Some(name) => name,
None => name.split('/').next_back().expect("Non empty module path"),
};
eco_format!("${name}")
}
fn do_print(
&mut self,
type_: &Type,
generic_usages: Option<&HashMap<u64, u64>>,
) -> Document<'static> {
match type_ {
Type::Var { type_ } => self.print_var(&type_.borrow(), generic_usages, false),
Type::Named {
name,
module,
arguments,
..
} if is_prelude_module(module) => {
self.print_prelude_type(name, arguments, generic_usages)
}
Type::Named {
name,
arguments,
module,
..
} => self.print_type_app(name, arguments, module, generic_usages),
Type::Fn { arguments, return_ } => self.print_fn(arguments, return_, generic_usages),
Type::Tuple { elements } => tuple(
elements
.iter()
.map(|element| self.do_print(element, generic_usages)),
),
}
}
fn do_print_force_generic_param(&mut self, type_: &Type) -> Document<'static> {
match type_ {
Type::Var { type_ } => self.print_var(&type_.borrow(), None, true),
Type::Named {
name,
module,
arguments,
..
} if is_prelude_module(module) => self.print_prelude_type(name, arguments, None),
Type::Named {
name,
arguments,
module,
..
} => self.print_type_app(name, arguments, module, None),
Type::Fn { arguments, return_ } => self.print_fn(arguments, return_, None),
Type::Tuple { elements } => {
tuple(elements.iter().map(|element| self.do_print(element, None)))
}
}
}
fn print_var(
&mut self,
type_: &TypeVar,
generic_usages: Option<&HashMap<u64, u64>>,
force_generic_id: bool,
) -> Document<'static> {
match type_ {
TypeVar::Unbound { id } | TypeVar::Generic { id } => match &generic_usages {
Some(usages) => match usages.get(id) {
Some(&0) => super::nil(),
Some(&1) => "any".to_doc(),
_ => id_to_type_var(*id),
},
None => {
if force_generic_id {
id_to_type_var(*id)
} else {
"any".to_doc()
}
}
},
TypeVar::Link { type_ } => self.do_print(type_, generic_usages),
}
}
/// Prints a type coming from the Gleam prelude module. These are often the
/// low level types the rest of the type system are built up from. If there
/// is no built-in TypeScript equivalent, the type is prefixed with "_."
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | true |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/decision.rs | compiler-core/src/javascript/decision.rs | use super::{
INDENT, bit_array_segment_int_value_to_bytes,
expression::{self, Generator, Ordering, float, float_from_value},
};
use crate::{
ast::{AssignmentKind, Endianness, SrcSpan, TypedClause, TypedExpr, TypedPattern},
docvec,
exhaustiveness::{
BitArrayMatchedValue, BitArrayTest, Body, BoundValue, CompiledCase, Decision,
FallbackCheck, MatchTest, Offset, ReadAction, ReadSize, ReadType, RuntimeCheck,
SizeOperator, SizeTest, Variable, VariableUsage,
},
format::break_block,
javascript::{
expression::{eco_string_int, string},
maybe_escape_property,
},
pretty::{Document, Documentable, break_, concat, join, line, nil},
strings::{convert_string_escape_chars, length_utf16},
};
use ecow::{EcoString, eco_format};
use itertools::Itertools;
use num_bigint::BigInt;
use std::{collections::HashMap, sync::OnceLock};
pub static ASSIGNMENT_VAR: &str = "$";
pub fn case<'a>(
compiled_case: &'a CompiledCase,
clauses: &'a [TypedClause],
subjects: &'a [TypedExpr],
expression_generator: &mut Generator<'_, 'a>,
) -> Document<'a> {
let mut variables = Variables::new(expression_generator, VariableAssignment::Declare);
let assignments = variables.assign_case_subjects(compiled_case, subjects);
let decision = CasePrinter {
variables,
assignments: &assignments,
kind: DecisionKind::Case { clauses },
}
.decision(&compiled_case.tree);
docvec![assignments_to_doc(assignments), decision.into_doc()].force_break()
}
/// The generated code for a decision tree.
enum CaseBody<'a> {
/// A JavaScript `if`` statement by itself. This can be merged with any
/// preceding `else` statements to form an `else if` construct.
If {
check: Document<'a>,
body: Document<'a>,
},
/// A sequence of statements. This must be wrapped as the body of an `if` or
/// `else` statement.
Statements(Document<'a>),
/// A JavaScript `if` statement followed by a single `else` clause. In some
/// cases this can be flattened to reduce the size of the generated decision
/// tree.
IfElse {
check: Document<'a>,
if_body: Document<'a>,
else_body: Document<'a>,
/// The decision in the tree that is used to generate the code for the
/// `else` clause of this statement. If this is the same as another `if`-
/// `else` statement, the two can be merged into one.
fallback_decision: &'a Decision,
},
/// A JavaScript `if` statement followed by more than one `else` clause. This
/// can sometimes be merged with preceding `else` statements in the same way
/// that `if` can.
IfElseChain(Document<'a>),
}
impl<'a> CaseBody<'a> {
fn into_doc(self) -> Document<'a> {
match self {
CaseBody::If { check, body } => docvec![
"if (",
break_("", "")
.append(check)
.nest(INDENT)
.append(break_("", ""))
.group(),
") ",
break_block(body)
],
// If we have some code like the following:
// ```javascript
// if (some_condition) {
//
// } else {
// fallback()
// }
// ```
//
// Here, the body of the `if` statement is empty. This can happen
// sometimes when generating decision trees for `let assert`.
//
// Instead, we can write this more concisely:
// ```javascript
// if (!some_condition) {
// fallback()
// }
// ```
CaseBody::IfElse {
check,
if_body,
else_body,
..
} if if_body.is_empty() => docvec![
"if (!(",
break_("", "")
.append(check)
.nest(INDENT)
.append(break_("", ""))
.group(),
")) ",
else_body,
],
CaseBody::IfElse {
check,
if_body,
else_body,
..
} => docvec![
"if (",
break_("", "")
.append(check)
.nest(INDENT)
.append(break_("", ""))
.group(),
") ",
break_block(if_body),
" else ",
else_body,
],
CaseBody::Statements(document) | CaseBody::IfElseChain(document) => document,
}
}
/// Convert this value into the required document to put directly after an
/// `else` keyword.
fn document_after_else(self) -> Document<'a> {
match self {
// `if` and `if-else` statements can come directly after an `else` keyword
CaseBody::If { .. } | CaseBody::IfElse { .. } => self.into_doc(),
CaseBody::IfElseChain(document) => document,
// Lists of statements must be wrapped in a block
CaseBody::Statements(document) => break_block(document),
}
}
fn is_empty(&self) -> bool {
match self {
CaseBody::If { .. } | CaseBody::IfElse { .. } => false,
CaseBody::Statements(document) | CaseBody::IfElseChain(document) => document.is_empty(),
}
}
}
struct CasePrinter<'module, 'generator, 'a, 'assignments> {
variables: Variables<'generator, 'module, 'a>,
assignments: &'assignments Vec<SubjectAssignment<'a>>,
kind: DecisionKind<'a>,
}
/// Information specific to the different kinds of decision trees: `case`
/// expressions and `let assert` statements.
enum DecisionKind<'a> {
Case {
clauses: &'a [TypedClause],
},
LetAssert {
kind: &'a AssignmentKind<TypedExpr>,
subject_location: SrcSpan,
pattern_location: SrcSpan,
subject: EcoString,
},
}
enum BodyExpression<'a> {
/// This happens when a case expression branch returns the same value that
/// is being matched on. So instead of rebuilding it from scratch we can
/// return the case subject directly. For example:
/// `Ok(1) -> Ok(1)`
/// `a -> a`
/// `[1, ..rest] -> [1, ..rest]`
///
Variable(Document<'a>),
/// This happens when a case expression has a complex body that is not just
/// returning the matched subject. For example:
/// `Ok(1) -> Ok(2)`
/// `_ -> [1, 2, 3]`
/// `1 -> "wibble"`
///
Expressions(Document<'a>),
}
/// Code generation for decision trees can look a bit daunting at a first glance
/// so let's go over the big idea to hopefully make it easier to understand why
/// the code is organised the way it is :)
///
/// > It might be helpful to go over the `exhaustiveness` module first and get
/// > familiar with the structure of the decision tree!
///
/// A decision tree has nodes that perform checks on pattern variables until
/// it reaches a body with an expression to run. This will be turned into a
/// series of if-else checks.
///
/// While on the surface it might sound pretty straightforward, the code generation
/// needs to take care of a couple of tricky aspects: when a check succeeds it's
/// not just allowing us to move to the next check, but it also introduces new
/// variables in the scope that we can reference. Let's look at an example:
///
/// ```gleam
/// case value {
/// [1, ..rest] -> rest
/// _ -> []
/// }
/// ```
///
/// Here we will first need to check that the list is not empty:
///
/// ```js
/// if (value instanceOf $NonEmptyList) {
/// // ...
/// } else {
/// return [];
/// }
/// ```
///
/// Once that check succeeds we know that now we can access two new values: the
/// first element of the list and the rest of the list! So we need to keep track
/// of that in case further checks need to use those values; and in the example
/// above they actually do! The second check we need to perform will be on the
/// first item of the list, so we need to actually create a variable for it:
///
/// ```js
/// if (value instanceOf $NonEmptyList) {
/// let $ = value.head;
/// if ($ === 1) {
/// // ...
/// } else {
/// // ...
/// }
/// } else {
/// return [];
/// }
/// ```
///
/// So, as we're generating code for each check and move further down the decision
/// tree, we will have to keep track of all the variables that we've discovered
/// after each successful check.
///
/// In order to do that we'll be using a `Variables` data structure to hold all
/// this information about the current scope.
///
impl<'a> CasePrinter<'_, '_, 'a, '_> {
fn decision(&mut self, decision: &'a Decision) -> CaseBody<'a> {
match decision {
Decision::Fail => {
if let DecisionKind::LetAssert {
kind,
subject_location,
pattern_location,
subject,
} = &self.kind
{
CaseBody::Statements(self.assignment_no_match(
subject.to_doc(),
kind,
*subject_location,
*pattern_location,
))
} else {
unreachable!("Invalid decision tree reached code generation")
}
}
Decision::Run { body } => {
let bindings = self.variables.bindings_doc(&body.bindings);
let body = self.body_expression(body.clause_index);
let body = match body {
BodyExpression::Variable(variable) => variable,
BodyExpression::Expressions(body) => join_with_line(bindings, body),
};
CaseBody::Statements(body)
}
Decision::Switch {
var,
choices,
fallback,
fallback_check,
} => self.switch(var, choices, fallback, fallback_check),
Decision::Guard {
guard,
if_true,
if_false,
} => self.decision_guard(*guard, if_true, if_false),
}
}
fn body_expression(&mut self, clause_index: usize) -> BodyExpression<'a> {
// If we are not in a `case` expression, there is no additional code to
// execute when a branch matches; we only assign variables bound in the
// pattern.
let DecisionKind::Case { clauses } = &self.kind else {
return BodyExpression::Expressions(nil());
};
let clause = &clauses.get(clause_index).expect("invalid clause index");
let body = &clause.then;
if let Some(subject_index) = clause.returned_subject() {
let variable = self
.assignments
.get(subject_index)
.expect("case with no subjects")
.name();
BodyExpression::Variable(
self.variables
.expression_generator
.wrap_return(variable.to_doc()),
)
} else {
BodyExpression::Expressions(
self.variables
.expression_generator
.expression_flattening_blocks(body),
)
}
}
fn switch(
&mut self,
var: &'a Variable,
choices: &'a [(RuntimeCheck, Decision)],
fallback: &'a Decision,
fallback_check: &'a FallbackCheck,
) -> CaseBody<'a> {
// If there's just a single choice we can just generate the code for
// it: no need to do any checking, we know it must match!
if choices.is_empty() {
// However, if the choice had an associated check (that is, it was
// not just a simple catch all) we need to keep track of all the
// variables brought into scope by the (always) successfull check.
if let FallbackCheck::RuntimeCheck { check } = fallback_check {
self.variables.record_check_assignments(var, check);
}
return self.decision(fallback);
}
// Otherwise we'll have to generate a series of if-else to check which
// pattern is going to match!
let mut assignments = vec![];
if !self.variables.is_bound_in_scope(var) {
// If the variable we need to perform a check on is not already bound
// in scope we will be binding it to a new made up name. This way we
// can also reference this exact name in further checks instead of
// recomputing the value each time.
let name = self.variables.next_local_var(&ASSIGNMENT_VAR.into());
let value = self.variables.get_value(var);
self.variables.bind(name.clone(), var);
assignments.push(let_doc(name, value.to_doc()))
};
let mut if_ = CaseBody::Statements(nil());
for (i, (check, decision)) in choices.iter().enumerate() {
self.variables.record_check_assignments(var, check);
// For each check we generate:
// - the document to perform such check
// - the body to run if the check is successful
// - the assignments we need to bring all the bit array segments
// referenced by this check
let (check_doc, body, mut segment_assignments) = self.inside_new_scope(|this| {
let segment_assignments = this.variables.bit_array_segment_assignments(check);
let check_doc = this.variables.runtime_check(var, check);
let body = this.decision(decision);
(check_doc, body, segment_assignments)
});
assignments.append(&mut segment_assignments);
let (check_doc, body) = match body {
// If we have a statement like this:
// ```javascript
// if (x) {
// if (y) {
// ...
// }
// }
// ```
//
// We can transform it into:
// ```javascript
// if (x && y) {
// ...
// }
// ```
CaseBody::If { check, body } => {
(docvec![check_doc, break_(" &&", " && "), check], body)
}
// The following code is a pretty common pattern in the code
// generated by decision trees:
//
// ```javascript
// if (something) {
// if (something_else) {
// do_thing()
// } else {
// do_fallback()
// }
// } else {
// do_fallback()
// }
// ```
//
// Here, the `do_fallback()` branch is repeated, which we want
// to avoid if possible. In this case, we can transform the above
// code into the following:
//
// ```javascript
// if (something && something_else) {
// do_thing()
// } else {
// do_fallback()
// }
// ```
//
// This only works if both `else` branches run the same code,
// otherwise we would be losing information.
// It also only works if the inner statement has only a single
// `else` clause, and not multiple `else if`s.
CaseBody::IfElse {
check,
if_body,
fallback_decision: decision,
..
} if decision == fallback => {
(docvec![check_doc, break_(" &&", " && "), check], if_body)
}
if_else @ CaseBody::IfElse { .. } => (check_doc, if_else.into_doc()),
CaseBody::Statements(document) | CaseBody::IfElseChain(document) => {
(check_doc, document)
}
};
if_ = match if_ {
// The first statement will always be an `if`
_ if i == 0 => CaseBody::If {
check: check_doc,
body,
},
// If this is the second check, the `if` becomes `else if`
CaseBody::If { .. } | CaseBody::IfElse { .. } => CaseBody::IfElseChain(docvec![
if_.into_doc(),
" else if (",
break_("", "")
.append(check_doc)
.nest(INDENT)
.append(break_("", ""))
.group(),
") ",
break_block(body)
]),
CaseBody::IfElseChain(document) | CaseBody::Statements(document) => {
CaseBody::IfElseChain(docvec![
document,
" else if (",
break_("", "")
.append(check_doc)
.nest(INDENT)
.append(break_("", ""))
.group(),
") ",
break_block(body)
])
}
};
}
// In case there's some new variables we can extract after the
// successful final check we store those. But we don't need to perform
// the check itself: the type system ensures that, if we ever get here,
// the check is going to match no matter what!
if let FallbackCheck::RuntimeCheck { check } = fallback_check {
self.variables.record_check_assignments(var, check);
}
let else_body = self.inside_new_scope(|this| this.decision(fallback));
let document = if else_body.is_empty() {
if_
} else if let CaseBody::If {
check,
body: if_body,
} = if_
{
CaseBody::IfElse {
check,
if_body,
else_body: else_body.document_after_else(),
fallback_decision: fallback,
}
} else {
CaseBody::IfElseChain(docvec![
if_.into_doc(),
" else ",
else_body.document_after_else()
])
};
if assignments.is_empty() {
document
} else {
CaseBody::Statements(join_with_line(
join(assignments, line()),
document.into_doc(),
))
}
}
fn inside_new_scope<A, F>(&mut self, run: F) -> A
where
F: Fn(&mut Self) -> A,
{
// Since we use reassignment for `let assert`, we can't reset the scope
// as it loses data about the assigned variables.
let old_scope = match &self.kind {
DecisionKind::Case { .. } => self
.variables
.expression_generator
.current_scope_vars
.clone(),
DecisionKind::LetAssert { .. } => Default::default(),
};
let old_names = self.variables.scoped_variable_names.clone();
let old_segments = self.variables.segment_values.clone();
let old_segment_names = self.variables.scoped_segment_names.clone();
let output = run(self);
match &self.kind {
DecisionKind::Case { .. } => {
self.variables.expression_generator.current_scope_vars = old_scope
}
DecisionKind::LetAssert { .. } => {}
}
self.variables.scoped_variable_names = old_names;
self.variables.segment_values = old_segments;
self.variables.scoped_segment_names = old_segment_names;
output
}
fn decision_guard(
&mut self,
guard: usize,
if_true: &'a Body,
if_false: &'a Decision,
) -> CaseBody<'a> {
let DecisionKind::Case { clauses } = &self.kind else {
unreachable!("Guards cannot appear in let assert decision trees")
};
let guard = clauses
.get(guard)
.expect("invalid clause index")
.guard
.as_ref()
.expect("missing guard");
// Before generating the if-else condition we want to generate all the
// assignments that will be needed by the guard condition so we can rest
// assured they are in scope and the guard check can use those.
let guard_variables = guard.referenced_variables();
let (check_bindings, if_true_bindings): (Vec<_>, Vec<_>) = if_true
.bindings
.iter()
.partition(|(variable, _)| guard_variables.contains(variable));
let (check_bindings, check, if_true) = self.inside_new_scope(|this| {
// check_bindings and if_true generation have to be in this scope so that pattern-bound
// variables used in guards don't leak into other case branches (if_false).
let check_bindings = this.variables.bindings_ref_doc(&check_bindings);
let check = this.variables.expression_generator.guard(guard);
// All the other bindings that are not needed by the guard check will
// end up directly in the body of the if clause.
let if_true_bindings = this.variables.bindings_ref_doc(&if_true_bindings);
let if_true_body = this.body_expression(if_true.clause_index);
let if_true = match if_true_body {
BodyExpression::Variable(variable) => variable,
BodyExpression::Expressions(if_true_body) => {
join_with_line(if_true_bindings, if_true_body)
}
};
(check_bindings, check, if_true)
});
let if_false_body = self.inside_new_scope(|this| this.decision(if_false));
// We can now piece everything together into a case body!
let if_ = if if_false_body.is_empty() {
CaseBody::If {
check,
body: if_true,
}
} else {
CaseBody::IfElse {
check,
if_body: if_true,
else_body: if_false_body.document_after_else(),
fallback_decision: if_false,
}
};
if check_bindings.is_empty() {
if_
} else {
CaseBody::Statements(join_with_line(check_bindings, if_.into_doc()))
}
}
fn assignment_no_match(
&mut self,
subject: Document<'a>,
kind: &'a AssignmentKind<TypedExpr>,
subject_location: SrcSpan,
pattern_location: SrcSpan,
) -> Document<'a> {
let AssignmentKind::Assert {
location, message, ..
} = kind
else {
unreachable!("inexhaustive let made it to code generation");
};
let generator = &mut self.variables.expression_generator;
let message = match message {
None => string("Pattern match failed, no pattern matched the value."),
Some(message) => generator
.not_in_tail_position(Some(Ordering::Strict), |this| this.wrap_expression(message)),
};
generator.throw_error(
"let_assert",
&message,
*location,
[
("value", subject),
("start", location.start.to_doc()),
("end", subject_location.end.to_doc()),
("pattern_start", pattern_location.start.to_doc()),
("pattern_end", pattern_location.end.to_doc()),
],
)
}
}
pub fn let_<'a>(
compiled_case: &'a CompiledCase,
subject: &'a TypedExpr,
kind: &'a AssignmentKind<TypedExpr>,
expression_generator: &mut Generator<'_, 'a>,
pattern: &'a TypedPattern,
) -> Document<'a> {
let _ = pattern;
let scope_position = expression_generator.scope_position.clone();
let mut variables = Variables::new(expression_generator, VariableAssignment::Reassign);
let assignment = variables.assign_let_subject(compiled_case, subject);
let assignment_name = assignment.name();
let assignments = vec![assignment];
let decision = CasePrinter {
variables,
assignments: &assignments,
kind: DecisionKind::LetAssert {
kind,
subject_location: subject.location(),
pattern_location: pattern.location(),
subject: assignment_name.clone(),
},
}
.decision(&compiled_case.tree);
// When we generate `let assert` statements, we want to produce code like
// this:
// ```javascript
// let some_var;
// let other_var;
// if (condition_to_check_pattern) {
// some_var = x;
// other_var = y;
// }
// ```
// This generates the code for binding the initial variables before the
// check so the scoping of them is correct.
//
// We must generate this after we generate the code for the decision tree
// itself as we might be re-binding variables which are used in the checks
// to determine whether the pattern matches or not.
let beginning_assignments = pattern.bound_variables().into_iter().map(|bound_variable| {
docvec![
"let ",
expression_generator.local_var(&bound_variable.name()),
";",
line()
]
});
let doc = docvec![
assignments_to_doc(assignments),
concat(beginning_assignments),
decision.into_doc()
];
match scope_position {
expression::Position::Expression(_) | expression::Position::Statement => doc,
expression::Position::Tail => docvec![doc, line(), "return ", assignment_name, ";"],
expression::Position::Assign(variable) => {
docvec![doc, line(), variable, " = ", assignment_name, ";"]
}
}
}
enum VariableAssignment {
Declare,
Reassign,
}
/// This is a useful piece of state that is kept separate from the generator
/// itself so we can reuse it both with `case`s and `let`s without rewriting
/// everything from scratch.
///
struct Variables<'generator, 'module, 'a> {
expression_generator: &'generator mut Generator<'module, 'a>,
/// Whether to bind variables using `let` as we do in `case` expressions,
/// or to reassign them as we do in `let assert` statements.
variable_assignment: VariableAssignment,
/// All the pattern variables will be assigned a specific value: being bound
/// to a constructor field, tuple element and so on. Pattern variables never
/// end up in the generated code but we replace them with their actual value.
/// We store those values as `EcoString`s in this map; the key is the pattern
/// variable's unique id.
///
variable_values: HashMap<usize, EcoString>,
/// The same happens for bit array segments. Unlike pattern variables, we
/// identify those using their names and store their value as a `Document`.
segment_values: HashMap<EcoString, Document<'a>>,
/// When we discover new variables after a runtime check we don't immediately
/// generate assignments for each of them, because that could lead to wasted
/// work. Let's consider the following check:
///
/// ```txt
/// a is Wibble(3, c, 1) -> c
/// a is _ -> 1
/// ```
///
/// If we generated variables for it as soon as we enter its corresponding
/// branch we would find ourselves with this piece of code:
///
/// ```js
/// if (a instanceof Wibble) {
/// let a$0 = wibble.0;
/// let a$1 = wibble.1;
/// let a$2 = wibble.2;
///
/// // and now we go on checking these new variables
/// }
/// ```
///
/// However, by extracting all the fields immediately we might end up doing
/// wasted work: as soon as we find out that `a$0 != 3` we don't even need
/// to check the other fields, we know the pattern can't match! So we
/// extracted two fields we're not even checking.
///
/// To avoid this situation, we only bind a variable to a name right before
/// we're checking it so we're sure we're never generating useless bindings.
/// The previous example would become something like this:
///
/// ```js
/// if (a instanceof Wibble) {
/// let a$0 = wibble.0;
/// if (a$0 === 3) {
/// let a$2 = wibble.2
/// // further checks
/// } else {
/// return 1;
/// }
/// }
/// ```
///
/// In this map we store the name a variable is bound to in the current
/// scope. For example here we know that `wibble.0` is bound to the name
/// `a$0`.
///
scoped_variable_names: HashMap<usize, EcoString>,
/// Once again, this is the same as `scoped_variable_names` with the
/// difference that a segment is identified by its name.
///
scoped_segment_names: HashMap<EcoString, EcoString>,
}
impl<'generator, 'module, 'a> Variables<'generator, 'module, 'a> {
fn new(
expression_generator: &'generator mut Generator<'module, 'a>,
variable_assignment: VariableAssignment,
) -> Self {
Variables {
expression_generator,
variable_assignment,
variable_values: HashMap::new(),
scoped_variable_names: HashMap::new(),
segment_values: HashMap::new(),
scoped_segment_names: HashMap::new(),
}
}
/// Give a unique name to each of the subjects of a case expression and keep
/// track of each of those names in case it needs to be referenced later.
///
fn assign_case_subjects(
&mut self,
compiled_case: &'a CompiledCase,
subjects: &'a [TypedExpr],
) -> Vec<SubjectAssignment<'a>> {
let assignments = subjects
.iter()
.map(|subject| assign_subject(self.expression_generator, subject, Ordering::Strict))
.collect_vec();
for (variable, assignment) in compiled_case
.subject_variables
.iter()
.zip(assignments.iter())
{
// We need to record the fact that each subject corresponds to a
// pattern variable.
self.set_value(variable, assignment.name());
self.bind(assignment.name(), variable);
}
assignments
}
/// Give a unique name to the subject of a let expression (if it needs one
/// and it's not already a variable) and keep track of that name in case it
/// needs to be referenced later.
///
fn assign_let_subject(
&mut self,
compiled_case: &'a CompiledCase,
subject: &'a TypedExpr,
) -> SubjectAssignment<'a> {
let variable = compiled_case
.subject_variables
.first()
.expect("decision tree with no subjects");
let assignment = assign_subject(self.expression_generator, subject, Ordering::Loose);
self.set_value(variable, assignment.name());
self.bind(assignment.name(), variable);
assignment
}
fn local_var(&mut self, name: &EcoString) -> EcoString {
self.expression_generator.local_var(name)
}
fn next_local_var(&mut self, name: &EcoString) -> EcoString {
self.expression_generator.next_local_var(name)
}
/// Records that a given pattern `variable` has been assigned a runtime
/// `value`. For example if we had something like this:
///
/// ```txt
/// a is Wibble(1, b) -> todo
/// ```
///
/// After a successful `is Wibble` check, we know we'd end up with two
/// additional checks that look like this:
///
/// ```txt
/// a0 is 1, a1 is b -> todo
/// ```
///
/// But what's the runtime value of `a0` and `a1`? To get those we'd have to
/// extract the two fields from `a`, so they would have a value that looks
/// like this: `a[0]` and `a[1]`; these values are set with this `set_value`
/// function as we discover them.
///
fn set_value(&mut self, variable: &Variable, value: EcoString) {
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | true |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/expression.rs | compiler-core/src/javascript/expression.rs | use num_bigint::BigInt;
use vec1::Vec1;
use super::{decision::ASSIGNMENT_VAR, *};
use crate::{
ast::*,
exhaustiveness::StringEncoding,
line_numbers::LineNumbers,
pretty::*,
type_::{
ModuleValueConstructor, Type, TypedCallArg, ValueConstructor, ValueConstructorVariant,
},
};
use std::sync::Arc;
#[derive(Debug, Clone)]
pub enum Position {
/// We are compiling the last expression in a function, meaning that it should
/// use `return` to return the value it produces from the function.
Tail,
/// We are inside a function, but the value of this expression isn't being
/// used, so we don't need to do anything with the returned value.
Statement,
/// The value of this expression needs to be used inside another expression,
/// so we need to use the value that is returned by this expression.
Expression(Ordering),
/// We are compiling an expression inside a block, meaning we must assign
/// to the `_block` variable at the end of the scope, because blocks are not
/// expressions in JS.
/// Since JS doesn't have variable shadowing, we must store the name of the
/// variable being used, which will include the incrementing counter.
/// For example, `block$2`
Assign(EcoString),
}
impl Position {
/// Returns `true` if the position is [`Tail`].
///
/// [`Tail`]: Position::Tail
#[must_use]
pub fn is_tail(&self) -> bool {
matches!(self, Self::Tail)
}
#[must_use]
pub fn ordering(&self) -> Ordering {
match self {
Self::Expression(ordering) => *ordering,
Self::Tail | Self::Assign(_) | Self::Statement => Ordering::Loose,
}
}
}
#[derive(Debug, Clone, Copy)]
/// Determines whether we can lift blocks into statement level instead of using
/// immediately invoked function expressions. Consider the following piece of code:
///
/// ```gleam
/// some_function(function_with_side_effect(), {
/// let a = 10
/// other_function_with_side_effects(a)
/// })
/// ```
/// Here, if we lift the block that is the second argument of the function, we
/// would end up running `other_function_with_side_effects` before
/// `function_with_side_effects`. This would be invalid, as code in Gleam should be
/// evaluated left-to-right, top-to-bottom. In this case, the ordering would be
/// `Strict`, indicating that we cannot lift the block.
///
/// However, in this example:
///
/// ```gleam
/// let value = !{
/// let value = False
/// some_function_with_side_effect()
/// value
/// }
/// ```
/// The only expression is the block, meaning it can be safely lifted without
/// changing the evaluation order of the program. So the ordering is `Loose`.
///
pub enum Ordering {
Strict,
Loose,
}
/// Tracking where the current function is a module function or an anonymous function.
#[derive(Debug)]
enum CurrentFunction {
/// The current function is a module function
///
/// ```gleam
/// pub fn main() -> Nil {
/// // we are here
/// }
/// ```
Module,
/// The current function is a module function, but one of its arguments shadows
/// the reference to itself so it cannot recurse.
///
/// ```gleam
/// pub fn main(main: fn() -> Nil) -> Nil {
/// // we are here
/// }
/// ```
ModuleWithShadowingArgument,
/// The current function is an anonymous function
///
/// ```gleam
/// pub fn main() -> Nil {
/// fn() {
/// // we are here
/// }
/// }
/// ```
Anonymous,
}
impl CurrentFunction {
#[inline]
fn can_recurse(&self) -> bool {
match self {
CurrentFunction::Module => true,
CurrentFunction::ModuleWithShadowingArgument => false,
CurrentFunction::Anonymous => false,
}
}
}
#[derive(Debug)]
pub(crate) struct Generator<'module, 'ast> {
module_name: EcoString,
src_path: EcoString,
line_numbers: &'module LineNumbers,
function_name: EcoString,
function_arguments: Vec<Option<&'module EcoString>>,
current_function: CurrentFunction,
pub current_scope_vars: im::HashMap<EcoString, usize>,
pub function_position: Position,
pub scope_position: Position,
// We register whether these features are used within an expression so that
// the module generator can output a suitable function if it is needed.
pub tracker: &'module mut UsageTracker,
// We track whether tail call recursion is used so that we can render a loop
// at the top level of the function to use in place of pushing new stack
// frames.
pub tail_recursion_used: bool,
/// Statements to be compiled when lifting blocks into statement scope.
/// For example, when compiling the following code:
/// ```gleam
/// let a = {
/// let b = 1
/// b + 1
/// }
/// ```
/// There will be 2 items in `statement_level`: The first will be `let _block;`
/// The second will be the generated code for the block being assigned to `a`.
/// This lets use return `_block` as the value that the block evaluated to,
/// while still including the necessary code in the output at the right place.
///
/// Once the `let` statement has compiled its value, it will add anything accumulated
/// in `statement_level` to the generated code, so it will result in:
///
/// ```javascript
/// let _block;
/// {...}
/// let a = _block;
/// ```
///
statement_level: Vec<Document<'ast>>,
/// This will be true if we've generated a `let assert` statement that we know
/// is guaranteed to throw.
/// This means we can stop code generation for all the following statements
/// in the same block!
pub let_assert_always_panics: bool,
}
impl<'module, 'a> Generator<'module, 'a> {
#[allow(clippy::too_many_arguments)] // TODO: FIXME
pub fn new(
module_name: EcoString,
src_path: EcoString,
line_numbers: &'module LineNumbers,
function_name: EcoString,
function_arguments: Vec<Option<&'module EcoString>>,
tracker: &'module mut UsageTracker,
mut current_scope_vars: im::HashMap<EcoString, usize>,
) -> Self {
let mut current_function = CurrentFunction::Module;
for &name in function_arguments.iter().flatten() {
// Initialise the function arguments
let _ = current_scope_vars.insert(name.clone(), 0);
// If any of the function arguments shadow the current function then
// recursion is no longer possible.
if function_name.as_ref() == name {
current_function = CurrentFunction::ModuleWithShadowingArgument;
}
}
Self {
tracker,
module_name,
src_path,
line_numbers,
function_name,
function_arguments,
tail_recursion_used: false,
current_scope_vars,
current_function,
function_position: Position::Tail,
scope_position: Position::Tail,
statement_level: Vec::new(),
let_assert_always_panics: false,
}
}
pub fn local_var(&mut self, name: &EcoString) -> EcoString {
match self.current_scope_vars.get(name) {
None => {
let _ = self.current_scope_vars.insert(name.clone(), 0);
maybe_escape_identifier(name)
}
Some(0) => maybe_escape_identifier(name),
Some(n) if name == "$" => eco_format!("${n}"),
Some(n) => eco_format!("{name}${n}"),
}
}
pub fn next_local_var(&mut self, name: &EcoString) -> EcoString {
let next = self.current_scope_vars.get(name).map_or(0, |i| i + 1);
let _ = self.current_scope_vars.insert(name.clone(), next);
self.local_var(name)
}
pub fn function_body(
&mut self,
body: &'a [TypedStatement],
arguments: &'a [TypedArg],
) -> Document<'a> {
let body = self.statements(body);
if self.tail_recursion_used {
self.tail_call_loop(body, arguments)
} else {
body
}
}
fn tail_call_loop(&mut self, body: Document<'a>, arguments: &'a [TypedArg]) -> Document<'a> {
let loop_assignments = concat(arguments.iter().flat_map(Arg::get_variable_name).map(
|name| {
let var = maybe_escape_identifier(name);
docvec!["let ", var, " = loop$", name, ";", line()]
},
));
docvec![
"while (true) {",
docvec![line(), loop_assignments, body].nest(INDENT),
line(),
"}"
]
}
fn statement(&mut self, statement: &'a TypedStatement) -> Document<'a> {
let expression_doc = match statement {
Statement::Expression(expression) => self.expression(expression),
Statement::Assignment(assignment) => self.assignment(assignment),
Statement::Use(use_) => self.expression(&use_.call),
Statement::Assert(assert) => self.assert(assert),
};
self.add_statement_level(expression_doc)
}
fn add_statement_level(&mut self, expression: Document<'a>) -> Document<'a> {
if self.statement_level.is_empty() {
expression
} else {
let mut statements = std::mem::take(&mut self.statement_level);
statements.push(expression);
join(statements, line())
}
}
pub fn expression(&mut self, expression: &'a TypedExpr) -> Document<'a> {
let document = match expression {
TypedExpr::String { value, .. } => string(value),
TypedExpr::Int { value, .. } => int(value),
TypedExpr::Float { float_value, .. } => float_from_value(float_value.value()),
TypedExpr::List { elements, tail, .. } => {
self.not_in_tail_position(Some(Ordering::Strict), |this| match tail {
Some(tail) => {
this.tracker.prepend_used = true;
let tail = this.wrap_expression(tail);
prepend(
elements.iter().map(|element| this.wrap_expression(element)),
tail,
)
}
None => {
this.tracker.list_used = true;
list(elements.iter().map(|element| this.wrap_expression(element)))
}
})
}
TypedExpr::Tuple { elements, .. } => self.tuple(elements),
TypedExpr::TupleIndex { tuple, index, .. } => self.tuple_index(tuple, *index),
TypedExpr::Case {
subjects,
clauses,
compiled_case,
..
} => decision::case(compiled_case, clauses, subjects, self),
TypedExpr::Call { fun, arguments, .. } => self.call(fun, arguments),
TypedExpr::Fn {
arguments, body, ..
} => self.fn_(arguments, body),
TypedExpr::RecordAccess { record, label, .. } => self.record_access(record, label),
TypedExpr::PositionalAccess { record, index, .. } => {
self.positional_access(record, *index)
}
TypedExpr::RecordUpdate {
record_assignment,
constructor,
arguments,
..
} => self.record_update(record_assignment, constructor, arguments),
TypedExpr::Var {
name, constructor, ..
} => self.variable(name, constructor),
TypedExpr::Pipeline {
first_value,
assignments,
finally,
..
} => self.pipeline(first_value, assignments.as_slice(), finally),
TypedExpr::Block { statements, .. } => self.block(statements),
TypedExpr::BinOp {
name, left, right, ..
} => self.bin_op(name, left, right),
TypedExpr::Todo {
message, location, ..
} => self.todo(message.as_ref().map(|m| &**m), location),
TypedExpr::Panic {
location, message, ..
} => self.panic(location, message.as_ref().map(|m| &**m)),
TypedExpr::BitArray { segments, .. } => self.bit_array(segments),
TypedExpr::ModuleSelect {
module_alias,
label,
constructor,
..
} => self.module_select(module_alias, label, constructor),
TypedExpr::NegateBool { value, .. } => self.negate_with("!", value),
TypedExpr::NegateInt { value, .. } => self.negate_with("- ", value),
TypedExpr::Echo {
expression,
message,
location,
..
} => {
let expression = expression
.as_ref()
.expect("echo with no expression outside of pipe");
let expresion_doc =
self.not_in_tail_position(None, |this| this.wrap_expression(expression));
self.echo(expresion_doc, message.as_deref(), location)
}
TypedExpr::Invalid { .. } => {
panic!("invalid expressions should not reach code generation")
}
};
if expression.handles_own_return() {
document
} else {
self.wrap_return(document)
}
}
fn negate_with(&mut self, with: &'static str, value: &'a TypedExpr) -> Document<'a> {
self.not_in_tail_position(None, |this| docvec![with, this.wrap_expression(value)])
}
fn bit_array(&mut self, segments: &'a [TypedExprBitArraySegment]) -> Document<'a> {
self.tracker.bit_array_literal_used = true;
// Collect all the values used in segments.
let segments_array = array(segments.iter().map(|segment| {
let value = self.not_in_tail_position(Some(Ordering::Strict), |this| {
this.wrap_expression(&segment.value)
});
let details = self.bit_array_segment_details(segment);
match details.type_ {
BitArraySegmentType::BitArray => {
if segment.size().is_some() {
self.tracker.bit_array_slice_used = true;
docvec!["bitArraySlice(", value, ", 0, ", details.size, ")"]
} else {
value
}
}
BitArraySegmentType::Int => match (details.size_value, segment.value.as_ref()) {
(Some(size_value), TypedExpr::Int { int_value, .. })
if size_value <= SAFE_INT_SEGMENT_MAX_SIZE.into()
&& (&size_value % BigInt::from(8) == BigInt::ZERO) =>
{
let bytes = bit_array_segment_int_value_to_bytes(
int_value.clone(),
size_value,
segment.endianness(),
);
u8_slice(&bytes)
}
(Some(size_value), _) if size_value == 8.into() => value,
(Some(size_value), _) if size_value <= 0.into() => nil(),
_ => {
self.tracker.sized_integer_segment_used = true;
let size = details.size;
let is_big = bool(segment.endianness().is_big());
docvec!["sizedInt(", value, ", ", size, ", ", is_big, ")"]
}
},
BitArraySegmentType::Float => {
self.tracker.float_bit_array_segment_used = true;
let size = details.size;
let is_big = bool(details.endianness.is_big());
docvec!["sizedFloat(", value, ", ", size, ", ", is_big, ")"]
}
BitArraySegmentType::String(StringEncoding::Utf8) => {
self.tracker.string_bit_array_segment_used = true;
docvec!["stringBits(", value, ")"]
}
BitArraySegmentType::String(StringEncoding::Utf16) => {
self.tracker.string_utf16_bit_array_segment_used = true;
let is_big = bool(details.endianness.is_big());
docvec!["stringToUtf16(", value, ", ", is_big, ")"]
}
BitArraySegmentType::String(StringEncoding::Utf32) => {
self.tracker.string_utf32_bit_array_segment_used = true;
let is_big = bool(details.endianness.is_big());
docvec!["stringToUtf32(", value, ", ", is_big, ")"]
}
BitArraySegmentType::UtfCodepoint(StringEncoding::Utf8) => {
self.tracker.codepoint_bit_array_segment_used = true;
docvec!["codepointBits(", value, ")"]
}
BitArraySegmentType::UtfCodepoint(StringEncoding::Utf16) => {
self.tracker.codepoint_utf16_bit_array_segment_used = true;
let is_big = bool(details.endianness.is_big());
docvec!["codepointToUtf16(", value, ", ", is_big, ")"]
}
BitArraySegmentType::UtfCodepoint(StringEncoding::Utf32) => {
self.tracker.codepoint_utf32_bit_array_segment_used = true;
let is_big = bool(details.endianness.is_big());
docvec!["codepointToUtf32(", value, ", ", is_big, ")"]
}
}
}));
docvec!["toBitArray(", segments_array, ")"]
}
fn bit_array_segment_details(
&mut self,
segment: &'a TypedExprBitArraySegment,
) -> BitArraySegmentDetails<'a> {
let size = segment.size();
let unit = segment.unit();
let (size_value, size) = match size {
Some(TypedExpr::Int { int_value, .. }) => {
let size_value = int_value * unit;
let size = eco_format!("{}", size_value).to_doc();
(Some(size_value), size)
}
Some(size) => {
let mut size = self.not_in_tail_position(Some(Ordering::Strict), |this| {
this.wrap_expression(size)
});
if unit != 1 {
size = size.group().append(" * ".to_doc().append(unit.to_doc()));
}
(None, size)
}
None => {
let size_value: usize = if segment.type_.is_int() { 8 } else { 64 };
(Some(BigInt::from(size_value)), docvec![size_value])
}
};
let type_ = BitArraySegmentType::from_segment(segment);
BitArraySegmentDetails {
type_,
size,
size_value,
endianness: segment.endianness(),
}
}
pub fn wrap_return(&mut self, document: Document<'a>) -> Document<'a> {
match &self.scope_position {
Position::Tail => docvec!["return ", document, ";"],
Position::Expression(_) | Position::Statement => document,
Position::Assign(name) => docvec![name.clone(), " = ", document, ";"],
}
}
pub fn not_in_tail_position<CompileFn, Output>(
&mut self,
// If ordering is None, it is inherited from the parent scope.
// It will be None in cases like `!x`, where `x` can be lifted
// only if the ordering is already loose.
ordering: Option<Ordering>,
compile: CompileFn,
) -> Output
where
CompileFn: Fn(&mut Self) -> Output,
{
let new_ordering = ordering.unwrap_or(self.scope_position.ordering());
let function_position = std::mem::replace(
&mut self.function_position,
Position::Expression(new_ordering),
);
let scope_position =
std::mem::replace(&mut self.scope_position, Position::Expression(new_ordering));
let result = compile(self);
self.function_position = function_position;
self.scope_position = scope_position;
result
}
/// Use the `_block` variable if the expression is JS statement.
pub fn wrap_expression(&mut self, expression: &'a TypedExpr) -> Document<'a> {
match (expression, &self.scope_position) {
(_, Position::Tail | Position::Assign(_)) => self.expression(expression),
(
TypedExpr::Panic { .. }
| TypedExpr::Todo { .. }
| TypedExpr::Case { .. }
| TypedExpr::Pipeline { .. }
| TypedExpr::RecordUpdate {
// Record updates that assign a variable generate multiple statements
record_assignment: Some(_),
..
},
Position::Expression(Ordering::Loose),
) => self.wrap_block(|this| this.expression(expression)),
(
TypedExpr::Panic { .. }
| TypedExpr::Todo { .. }
| TypedExpr::Case { .. }
| TypedExpr::Pipeline { .. }
| TypedExpr::RecordUpdate {
// Record updates that assign a variable generate multiple statements
record_assignment: Some(_),
..
},
Position::Expression(Ordering::Strict),
) => self.immediately_invoked_function_expression(expression, |this, expr| {
this.expression(expr)
}),
_ => self.expression(expression),
}
}
/// Wrap an expression using the `_block` variable if required due to being
/// a JS statement, or in parens if required due to being an operator or
/// a function literal.
pub fn child_expression(&mut self, expression: &'a TypedExpr) -> Document<'a> {
match expression {
TypedExpr::BinOp { name, .. } if name.is_operator_to_wrap() => {}
TypedExpr::Fn { .. } => {}
TypedExpr::Int { .. }
| TypedExpr::Float { .. }
| TypedExpr::String { .. }
| TypedExpr::Block { .. }
| TypedExpr::Pipeline { .. }
| TypedExpr::Var { .. }
| TypedExpr::List { .. }
| TypedExpr::Call { .. }
| TypedExpr::BinOp { .. }
| TypedExpr::Case { .. }
| TypedExpr::RecordAccess { .. }
| TypedExpr::PositionalAccess { .. }
| TypedExpr::ModuleSelect { .. }
| TypedExpr::Tuple { .. }
| TypedExpr::TupleIndex { .. }
| TypedExpr::Todo { .. }
| TypedExpr::Panic { .. }
| TypedExpr::Echo { .. }
| TypedExpr::BitArray { .. }
| TypedExpr::RecordUpdate { .. }
| TypedExpr::NegateBool { .. }
| TypedExpr::NegateInt { .. }
| TypedExpr::Invalid { .. } => return self.wrap_expression(expression),
}
let document = self.expression(expression);
match &self.scope_position {
// Here the document is a return statement: `return <expr>;`
// or an assignment: `_block = <expr>;`
Position::Tail | Position::Assign(_) | Position::Statement => document,
Position::Expression(_) => docvec!["(", document, ")"],
}
}
/// Wrap an expression in an immediately invoked function expression
fn immediately_invoked_function_expression<T, ToDoc>(
&mut self,
statements: &'a T,
to_doc: ToDoc,
) -> Document<'a>
where
ToDoc: FnOnce(&mut Self, &'a T) -> Document<'a>,
{
// Save initial state
let scope_position = std::mem::replace(&mut self.scope_position, Position::Tail);
let statement_level = std::mem::take(&mut self.statement_level);
// Set state for in this iife
let current_scope_vars = self.current_scope_vars.clone();
// Generate the expression
let result = to_doc(self, statements);
let doc = self.add_statement_level(result);
let doc = immediately_invoked_function_expression_document(doc);
// Reset
self.current_scope_vars = current_scope_vars;
self.scope_position = scope_position;
self.statement_level = statement_level;
self.wrap_return(doc)
}
fn wrap_block<CompileFn>(&mut self, compile: CompileFn) -> Document<'a>
where
CompileFn: Fn(&mut Self) -> Document<'a>,
{
let block_variable = self.next_local_var(&BLOCK_VARIABLE.into());
// Save initial state
let scope_position = std::mem::replace(
&mut self.scope_position,
Position::Assign(block_variable.clone()),
);
let function_position = std::mem::replace(
&mut self.function_position,
Position::Expression(Ordering::Strict),
);
// Generate the expression
let statement_doc = compile(self);
// Reset
self.scope_position = scope_position;
self.function_position = function_position;
self.statement_level
.push(docvec!["let ", block_variable.clone(), ";"]);
self.statement_level.push(statement_doc);
self.wrap_return(block_variable.to_doc())
}
fn variable(&mut self, name: &'a EcoString, constructor: &'a ValueConstructor) -> Document<'a> {
match &constructor.variant {
ValueConstructorVariant::Record { arity, .. } => {
let type_ = constructor.type_.clone();
let tracker = &mut self.tracker;
record_constructor(type_, None, name, *arity, tracker)
}
ValueConstructorVariant::ModuleFn { .. }
| ValueConstructorVariant::ModuleConstant { .. }
| ValueConstructorVariant::LocalVariable { .. } => self.local_var(name).to_doc(),
}
}
fn pipeline(
&mut self,
first_value: &'a TypedPipelineAssignment,
assignments: &'a [(TypedPipelineAssignment, PipelineAssignmentKind)],
finally: &'a TypedExpr,
) -> Document<'a> {
let count = assignments.len();
let mut documents = Vec::with_capacity((count + 2) * 2);
let all_assignments = std::iter::once(first_value)
.chain(assignments.iter().map(|(assignment, _kind)| assignment));
let mut latest_local_var: Option<EcoString> = None;
for assignment in all_assignments {
// An echo in a pipeline won't result in an assignment, instead it
// just prints the previous variable assigned in the pipeline.
if let TypedExpr::Echo {
expression: None,
message,
location,
..
} = assignment.value.as_ref()
{
documents.push(self.not_in_tail_position(Some(Ordering::Strict), |this| {
let var = latest_local_var
.as_ref()
.expect("echo with no previous step in a pipe");
this.echo(var.to_doc(), message.as_deref(), location)
}))
} else {
// Otherwise we assign the intermediate pipe value to a variable.
let assignment_document = self
.not_in_tail_position(Some(Ordering::Strict), |this| {
this.simple_variable_assignment(&assignment.name, &assignment.value)
});
documents.push(self.add_statement_level(assignment_document));
latest_local_var = Some(self.local_var(&assignment.name));
}
documents.push(line());
}
if let TypedExpr::Echo {
expression: None,
message,
location,
..
} = finally
{
let var = latest_local_var.expect("echo with no previous step in a pipe");
documents.push(self.echo(var.to_doc(), message.as_deref(), location));
} else {
let finally = self.expression(finally);
documents.push(self.add_statement_level(finally))
}
documents.to_doc().force_break()
}
pub(crate) fn expression_flattening_blocks(
&mut self,
expression: &'a TypedExpr,
) -> Document<'a> {
if let TypedExpr::Block { statements, .. } = expression {
self.statements(statements)
} else {
let expression_document = self.expression(expression);
self.add_statement_level(expression_document)
}
}
fn block(&mut self, statements: &'a Vec1<TypedStatement>) -> Document<'a> {
if statements.len() == 1 {
match statements.first() {
Statement::Expression(expression) => return self.child_expression(expression),
Statement::Assignment(assignment) => match &assignment.kind {
AssignmentKind::Let | AssignmentKind::Generated => {
return self.child_expression(&assignment.value);
}
// We can't just return the right-hand side of a `let assert`
// assignment; we still need to check that the pattern matches.
AssignmentKind::Assert { .. } => {}
},
Statement::Use(use_) => return self.child_expression(&use_.call),
// Similar to `let assert`, we can't immediately return the value
// that is asserted; we have to actually perform the assertion.
Statement::Assert(_) => {}
}
}
match &self.scope_position {
Position::Tail | Position::Assign(_) | Position::Statement => {
self.block_document(statements)
}
Position::Expression(Ordering::Strict) => self
.immediately_invoked_function_expression(statements, |this, statements| {
this.statements(statements)
}),
Position::Expression(Ordering::Loose) => self.wrap_block(|this| {
// Save previous scope
let current_scope_vars = this.current_scope_vars.clone();
let document = this.block_document(statements);
// Restore previous state
this.current_scope_vars = current_scope_vars;
document
}),
}
}
fn block_document(&mut self, statements: &'a Vec1<TypedStatement>) -> Document<'a> {
let statements = self.statements(statements);
docvec!["{", docvec![line(), statements].nest(INDENT), line(), "}"]
}
fn statements(&mut self, statements: &'a [TypedStatement]) -> Document<'a> {
// If there are any statements that need to be printed at statement level, that's
// for an outer scope so we don't want to print them inside this one.
let statement_level = std::mem::take(&mut self.statement_level);
let count = statements.len();
let mut documents = Vec::with_capacity(count * 3);
for (i, statement) in statements.iter().enumerate() {
if i + 1 < count {
let function_position =
std::mem::replace(&mut self.function_position, Position::Statement);
let scope_position =
std::mem::replace(&mut self.scope_position, Position::Statement);
documents.push(self.statement(statement));
self.function_position = function_position;
self.scope_position = scope_position;
if requires_semicolon(statement) {
documents.push(";".to_doc());
}
documents.push(line());
} else {
documents.push(self.statement(statement));
}
// If we've generated code for a statement that always throws, we
// can skip code generation for all the following ones.
if self.let_assert_always_panics {
self.let_assert_always_panics = false;
break;
}
}
self.statement_level = statement_level;
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | true |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/import.rs | compiler-core/src/javascript/import.rs | use std::collections::{HashMap, HashSet};
use ecow::EcoString;
use itertools::Itertools;
use crate::{
docvec,
javascript::{INDENT, JavaScriptCodegenTarget},
pretty::{Document, Documentable, break_, concat, join, line},
};
/// A collection of JavaScript import statements from Gleam imports and from
/// external functions, to be rendered into a JavaScript module.
///
#[derive(Debug, Default)]
pub(crate) struct Imports<'a> {
imports: HashMap<EcoString, Import<'a>>,
exports: HashSet<EcoString>,
}
impl<'a> Imports<'a> {
pub fn new() -> Self {
Self::default()
}
pub fn register_export(&mut self, export: EcoString) {
let _ = self.exports.insert(export);
}
pub fn register_module(
&mut self,
path: EcoString,
aliases: impl IntoIterator<Item = EcoString>,
unqualified_imports: impl IntoIterator<Item = Member<'a>>,
) {
let import = self
.imports
.entry(path.clone())
.or_insert_with(|| Import::new(path.clone()));
import.aliases.extend(aliases);
import.unqualified.extend(unqualified_imports)
}
pub fn into_doc(self, codegen_target: JavaScriptCodegenTarget) -> Document<'a> {
let imports = concat(
self.imports
.into_values()
.sorted_by(|a, b| a.path.cmp(&b.path))
.map(|import| Import::into_doc(import, codegen_target)),
);
if self.exports.is_empty() {
imports
} else {
let names = join(
self.exports
.into_iter()
.sorted()
.map(|string| string.to_doc()),
break_(",", ", "),
);
let names = docvec![
docvec![break_("", " "), names].nest(INDENT),
break_(",", " ")
]
.group();
let export_keyword = match codegen_target {
JavaScriptCodegenTarget::JavaScript => "export {",
JavaScriptCodegenTarget::TypeScriptDeclarations => "export type {",
};
imports
.append(line())
.append(export_keyword)
.append(names)
.append("};")
.append(line())
}
}
pub fn is_empty(&self) -> bool {
self.imports.is_empty() && self.exports.is_empty()
}
}
#[derive(Debug)]
struct Import<'a> {
path: EcoString,
aliases: HashSet<EcoString>,
unqualified: Vec<Member<'a>>,
}
impl<'a> Import<'a> {
fn new(path: EcoString) -> Self {
Self {
path,
aliases: Default::default(),
unqualified: Default::default(),
}
}
pub fn into_doc(self, codegen_target: JavaScriptCodegenTarget) -> Document<'a> {
let path = self.path.to_doc();
let import_modifier = if codegen_target == JavaScriptCodegenTarget::TypeScriptDeclarations {
"type "
} else {
""
};
let alias_imports = concat(self.aliases.into_iter().sorted().map(|alias| {
docvec![
"import ",
import_modifier,
"* as ",
alias,
" from \"",
path.clone(),
r#"";"#,
line()
]
}));
if self.unqualified.is_empty() {
alias_imports
} else {
let members = self.unqualified.into_iter().map(Member::into_doc);
let members = join(members, break_(",", ", "));
let members = docvec![
docvec![break_("", " "), members].nest(INDENT),
break_(",", " ")
]
.group();
docvec![
alias_imports,
"import ",
import_modifier,
"{",
members,
"} from \"",
path,
r#"";"#,
line()
]
}
}
}
#[derive(Debug)]
pub struct Member<'a> {
pub name: Document<'a>,
pub alias: Option<Document<'a>>,
}
impl<'a> Member<'a> {
fn into_doc(self) -> Document<'a> {
match self.alias {
None => self.name,
Some(alias) => docvec![self.name, " as ", alias],
}
}
}
#[test]
fn into_doc() {
let mut imports = Imports::new();
imports.register_module("./gleam/empty".into(), [], []);
imports.register_module(
"./multiple/times".into(),
["wibble".into(), "wobble".into()],
[],
);
imports.register_module("./multiple/times".into(), ["wubble".into()], []);
imports.register_module(
"./multiple/times".into(),
[],
[Member {
name: "one".to_doc(),
alias: None,
}],
);
imports.register_module(
"./other".into(),
[],
[
Member {
name: "one".to_doc(),
alias: None,
},
Member {
name: "one".to_doc(),
alias: Some("onee".to_doc()),
},
Member {
name: "two".to_doc(),
alias: Some("twoo".to_doc()),
},
],
);
imports.register_module(
"./other".into(),
[],
[
Member {
name: "three".to_doc(),
alias: None,
},
Member {
name: "four".to_doc(),
alias: None,
},
],
);
imports.register_module(
"./zzz".into(),
[],
[
Member {
name: "one".to_doc(),
alias: None,
},
Member {
name: "two".to_doc(),
alias: None,
},
],
);
assert_eq!(
line()
.append(imports.into_doc(JavaScriptCodegenTarget::JavaScript))
.to_pretty_string(40),
r#"
import * as wibble from "./multiple/times";
import * as wobble from "./multiple/times";
import * as wubble from "./multiple/times";
import { one } from "./multiple/times";
import {
one,
one as onee,
two as twoo,
three,
four,
} from "./other";
import { one, two } from "./zzz";
"#
.to_string()
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/consts.rs | compiler-core/src/javascript/tests/consts.rs | use crate::assert_js;
#[test]
fn custom_type_constructor_imported_and_aliased() {
assert_js!(
("package", "other_module", "pub type T { A }"),
r#"import other_module.{A as B}
pub const local = B
"#,
);
}
#[test]
fn imported_aliased_ok() {
assert_js!(
r#"import gleam.{Ok as Y}
pub type X {
Ok
}
pub const y = Y
"#,
);
}
#[test]
fn imported_ok() {
assert_js!(
r#"import gleam
pub type X {
Ok
}
pub const y = gleam.Ok
"#,
);
}
#[test]
fn constant_constructor_gets_pure_annotation() {
assert_js!(
r#"
pub type X {
X(Int, List(String))
}
pub const x = X(1, ["1"])
pub const y = X(1, [])
"#
);
}
#[test]
fn constant_list_with_constructors_gets_pure_annotation() {
assert_js!(
r#"
pub type X {
X(Int, List(String))
}
pub const x = [X(1, ["1"])]
pub const y = [X(1, ["1"])]
"#
);
}
#[test]
fn constant_tuple_with_constructors_gets_pure_annotation() {
assert_js!(
r#"
pub type X {
X(Int, List(String))
}
pub const x = #(X(1, ["1"]))
pub const y = #(X(1, ["1"]))
"#
);
}
#[test]
fn literal_int_does_not_get_constant_annotation() {
assert_js!("pub const a = 1");
}
#[test]
fn literal_float_does_not_get_constant_annotation() {
assert_js!("pub const a = 1.1");
}
#[test]
fn literal_string_does_not_get_constant_annotation() {
assert_js!("pub const a = \"1\"");
}
#[test]
fn literal_bool_does_not_get_constant_annotation() {
assert_js!(
"
pub const a = True
pub const b = False
"
);
}
#[test]
fn literal_list_does_not_get_constant_annotation() {
assert_js!("pub const a = [1, 2, 3]");
}
#[test]
fn literal_tuple_does_not_get_constant_annotation() {
assert_js!("pub const a = #(1, 2, 3)");
}
#[test]
fn literal_nil_does_not_get_constant_annotation() {
assert_js!("pub const a = Nil");
}
// https://github.com/lpil/decode/pull/6
#[test]
fn constructor_function_in_constant() {
assert_js!("pub const a = Ok");
}
#[test]
fn constants_get_their_own_jsdoc_comment() {
assert_js!(
"
/// 11 is clearly the best number!
pub const jaks_favourite_number = 11
"
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/assert.rs | compiler-core/src/javascript/tests/assert.rs | use crate::assert_js;
#[test]
fn assert_variable() {
assert_js!(
"
pub fn main() {
let x = True
assert x
}
"
);
}
#[test]
fn assert_literal() {
assert_js!(
"
pub fn main() {
assert False
}
"
);
}
#[test]
fn assert_binary_operation() {
assert_js!(
"
pub fn main() {
let x = True
assert x || False
}
"
);
}
#[test]
fn assert_binary_operation2() {
assert_js!(
"
pub fn eq(a, b) {
assert a == b
}
"
);
}
#[test]
fn assert_binary_operation3() {
assert_js!(
"
pub fn assert_answer(x) {
assert x == 42
}
"
);
}
#[test]
fn assert_function_call() {
assert_js!(
"
fn bool() {
True
}
pub fn main() {
assert bool()
}
"
);
}
#[test]
fn assert_function_call2() {
assert_js!(
"
fn and(a, b) {
a && b
}
pub fn go(x) {
assert and(True, x)
}
"
);
}
#[test]
fn assert_nested_function_call() {
assert_js!(
"
fn and(x, y) {
x && y
}
pub fn main() {
assert and(and(True, False), True)
}
"
);
}
#[test]
fn assert_binary_operator_with_side_effects() {
assert_js!(
"
fn wibble(a, b) {
let result = a + b
result == 10
}
pub fn go(x) {
assert True && wibble(1, 4)
}
"
);
}
#[test]
fn assert_binary_operator_with_side_effects2() {
assert_js!(
"
fn wibble(a, b) {
let result = a + b
result == 10
}
pub fn go(x) {
assert wibble(5, 5) && wibble(4, 6)
}
"
);
}
#[test]
fn assert_with_message() {
assert_js!(
r#"
pub fn main() {
assert True as "This shouldn't fail"
}
"#
);
}
#[test]
fn assert_with_block_message() {
assert_js!(
r#"
fn identity(a) {
a
}
pub fn main() {
assert identity(True) as {
let message = identity("This shouldn't fail")
message
}
}
"#
);
}
#[test]
fn assert_nil_always_throws() {
assert_js!(
r#"
pub fn go(x: Nil) {
let assert Nil = x
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/4643
#[test]
fn assert_with_pipe_on_right() {
assert_js!(
"
fn add(a, b) { a + b }
pub fn main() {
assert 3 == 1 |> add(2)
}
"
);
}
#[test]
fn prova() {
assert_js!(
"
pub fn main() {
assert Ok([]) == Ok([] |> id)
}
fn id(x) { x }
"
)
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/use_.rs | compiler-core/src/javascript/tests/use_.rs | use crate::assert_js;
#[test]
fn arity_1() {
assert_js!(
r#"
pub fn main() {
use <- pair()
123
}
fn pair(f) {
let x = f()
#(x, x)
}
"#,
)
}
#[test]
fn arity_2() {
assert_js!(
r#"
pub fn main() {
use <- pair(1.0)
123
}
fn pair(x, f) {
let y = f()
#(x, y)
}
"#,
)
}
#[test]
fn arity_3() {
assert_js!(
r#"
pub fn main() {
use <- trip(1.0, "")
123
}
fn trip(x, y, f) {
let z = f()
#(x, y, z)
}
"#,
)
}
#[test]
fn no_callback_body() {
assert_js!(
r#"
pub fn main() {
let thingy = fn(f) { f() }
use <- thingy()
}
"#
);
}
#[test]
fn patterns() {
assert_js!(
r#"
pub fn main() {
use Box(x) <- apply(Box(1))
x
}
type Box(a) {
Box(a)
}
fn apply(arg, fun) {
fun(arg)
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/prelude.rs | compiler-core/src/javascript/tests/prelude.rs | use crate::{assert_js, assert_ts_def};
#[test]
fn qualified_ok() {
assert_js!(
r#"import gleam
pub fn go() { gleam.Ok(1) }
"#,
);
}
#[test]
fn qualified_ok_typescript() {
assert_ts_def!(
r#"import gleam
pub fn go() { gleam.Ok(1) }
"#,
);
}
#[test]
fn qualified_error() {
assert_js!(
r#"import gleam
pub fn go() { gleam.Error(1) }
"#,
);
}
#[test]
fn qualified_nil() {
assert_js!(
r#"import gleam
pub fn go() { gleam.Nil }
"#,
);
}
#[test]
fn qualified_nil_typescript() {
assert_ts_def!(
r#"import gleam
pub fn go() { gleam.Nil }
"#,
);
}
// https://github.com/gleam-lang/gleam/issues/4756
#[test]
fn qualified_prelude_value_does_not_conflict_with_local_value() {
assert_js!(
"
import gleam
pub type Result(a, e) {
Ok(a)
Error(e)
}
pub fn main() {
gleam.Ok(10)
}
",
);
}
#[test]
fn qualified_prelude_value_does_not_conflict_with_local_value_constant() {
assert_js!(
r#"
import gleam
pub type Result(a, e) {
Ok(a)
Error(e)
}
pub const error = gleam.Error("Bad")
"#,
);
}
#[test]
fn qualified_prelude_value_does_not_conflict_with_local_value_pattern() {
assert_js!(
r#"
import gleam
pub type Result(a, e) {
Ok(a)
Error(e)
}
pub fn go(x) {
case x {
gleam.Ok(x) -> x
gleam.Error(_) -> 0
}
}
"#,
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/case.rs | compiler-core/src/javascript/tests/case.rs | use crate::assert_js;
#[test]
fn case_on_error() {
assert_js!(
r#"
fn a_result() { Error(1) }
pub fn main() {
case a_result() {
Error(_) -> 1
_ -> 2
}
}"#
);
}
#[test]
fn tuple_and_guard() {
assert_js!(
r#"
pub fn go(x) {
case #(1, 2) {
#(1, a) if a == 2 -> 1
#(_, _) -> 2
}
}
"#,
)
}
#[test]
fn guard_variable_only_brought_into_scope_when_needed() {
assert_js!(
r#"
pub fn go(x) {
case x {
// We want `a` to be defined before the guard check, and
// `b` to be defined only if the predicate on a matches!
[a, b] if a == 1 -> a + b
_ -> 2
}
}
"#
)
}
// https://github.com/gleam-lang/gleam/issues/4221
#[test]
fn guard_variable_only_brought_into_scope_when_needed_1() {
assert_js!(
r#"
pub fn main() {
case 1 {
i if i == 1 -> True
i if i < 2 -> True
_ -> False
}
}
"#
)
}
// https://github.com/gleam-lang/gleam/issues/1187
#[test]
fn pointless() {
assert_js!(
r#"
pub fn go(x) {
case x {
_ -> x
}
}
"#,
)
}
// https://github.com/gleam-lang/gleam/issues/1188
#[test]
fn following_todo() {
assert_js!(
r#"
pub fn go(x) {
case x {
True -> todo
_ -> 1
}
}
"#,
)
}
#[test]
fn multi_subject_catch_all() {
assert_js!(
r#"
pub fn go(x, y) {
case x, y {
True, True -> 1
_, _ -> 0
}
}
"#,
)
}
#[test]
fn multi_subject_or() {
assert_js!(
r#"
pub fn go(x, y) {
case x, y {
True, _ | _, True -> 1
_, _ -> 0
}
}
"#,
)
}
#[test]
fn multi_subject_no_catch_all() {
assert_js!(
r#"
pub fn go(x, y) {
case x, y {
True, _ -> 1
_, True -> 2
False, False -> 0
}
}
"#,
)
}
#[test]
fn multi_subject_subject_assignments() {
assert_js!(
r#"
pub fn go() {
case True, False {
True, True -> 1
_, _ -> 0
}
}
"#,
)
}
#[test]
fn assignment() {
assert_js!(
r#"
pub fn go(x) {
let y = case x {
True -> 1
_ -> 0
}
y
}
"#,
)
}
#[test]
fn preassign_assignment() {
assert_js!(
r#"
pub fn go(x) {
let y = case x() {
True -> 1
_ -> 0
}
y
}
"#,
)
}
// https://github.com/gleam-lang/gleam/issues/1237
#[test]
fn pipe() {
assert_js!(
r#"
pub fn go(x, f) {
case x |> f {
0 -> 1
_ -> 2
}
}
"#,
)
}
#[test]
fn result() {
assert_js!(
r#"
pub fn go(x) {
case x {
Ok(_) -> 1
Error(_) -> 0
}
}
"#,
)
}
// https://github.com/gleam-lang/gleam/issues/1506
#[test]
fn called_case() {
assert_js!(
r#"
pub fn go(x, y) {
case x {
0 -> y
_ -> y
}()
}
"#,
)
}
// https://github.com/gleam-lang/gleam/issues/1978
#[test]
fn case_local_var_in_tuple() {
assert_js!(
r#"
pub fn go(x, y) {
let z = False
case True {
x if #(x, z) == #(True, False) -> x
_ -> False
}
}
"#,
)
}
// https://github.com/gleam-lang/gleam/issues/2665
#[test]
fn case_branches_guards_are_wrapped_in_parentheses() {
assert_js!(
r#"
pub fn anything() -> a {
case [] {
[a] if False || True -> a
_ -> anything()
}
}
"#,
)
}
// https://github.com/gleam-lang/gleam/issues/2759
#[test]
fn nested_string_prefix_match() {
assert_js!(
r#"
pub fn main() {
case Ok(["a", "b c", "d"]) {
Ok(["a", "b " <> _, "d"]) -> 1
_ -> 1
}
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2759
#[test]
fn nested_string_prefix_match_that_would_crash_on_js() {
assert_js!(
r#"
pub fn main() {
case Ok(["b c", "d"]) {
Ok(["b " <> _, "d"]) -> 1
_ -> 1
}
}
"#
);
}
#[test]
fn slicing_is_handled_properly_with_multiple_branches() {
assert_js!(
r#"
pub fn main() {
case "12345" {
"0" <> rest -> rest
"123" <> rest -> rest
_ -> ""
}
}
"#
)
}
// https://github.com/gleam-lang/gleam/issues/3379
#[test]
fn single_clause_variables() {
assert_js!(
r#"
pub fn main() {
let text = "first defined"
case "defined again" {
text -> Nil
}
let text = "a third time"
}
"#
)
}
// https://github.com/gleam-lang/gleam/issues/3379
#[test]
fn single_clause_variables_assigned() {
assert_js!(
r#"
pub fn main() {
let text = "first defined"
let other = case "defined again" {
text -> Nil
}
let text = "a third time"
}
"#
)
}
// https://github.com/gleam-lang/gleam/issues/3894
#[test]
fn nested_string_prefix_assignment() {
assert_js!(
r#"
type Wibble {
Wibble(wobble: String)
}
pub fn main() {
let tmp = Wibble(wobble: "wibble")
case tmp {
Wibble(wobble: "w" as wibble <> rest) -> wibble <> rest
_ -> panic
}
}
"#
)
}
#[test]
fn deeply_nested_string_prefix_assignment() {
assert_js!(
r#"
type Wibble {
Wibble(Wobble)
}
type Wobble {
Wobble(wabble: Wabble)
}
type Wabble {
Wabble(tuple: #(Int, String))
}
pub fn main() {
let tmp = Wibble(Wobble(Wabble(#(42, "wibble"))))
case tmp {
Wibble(Wobble(Wabble(#(_int, "w" as wibble <> rest)))) -> wibble <> rest
_ -> panic
}
}
"#
)
}
// https://github.com/gleam-lang/gleam/issues/4383
#[test]
fn record_update_in_pipeline_in_case_clause() {
assert_js!(
"
pub type Wibble {
Wibble(wibble: Int, wobble: Int)
}
fn identity(x) {
x
}
pub fn go(x) {
case x {
Wibble(1, _) -> Wibble(..x, wibble: 4) |> identity
Wibble(_, 3) -> Wibble(..x, wobble: 10) |> identity
_ -> panic
}
}
"
);
}
#[test]
fn pattern_matching_on_aliased_result_constructor() {
assert_js!(
"
import gleam.{Error as E, Ok as O}
pub fn go(x) {
case x {
E(_) -> 1
O(_) -> 2
}
}
"
);
}
#[test]
fn list_with_guard() {
assert_js!(
"
pub fn go(x) {
case x {
[] -> 0
[first, ..] if first < 10 -> first * 2
[first, ..] -> first
}
}
"
);
}
#[test]
fn list_with_guard_no_binding() {
assert_js!(
"
pub fn go(x) {
case x {
[] -> 0
[first, ..] if 1 < 10 -> first * 2
[first, ..] -> first
}
}
"
);
}
#[test]
fn case_building_simple_value_matched_by_pattern() {
assert_js!(
"pub fn go(x) {
case x {
1 -> 2
n -> n
}
}"
)
}
#[test]
fn case_building_list_matched_by_pattern() {
assert_js!(
"pub fn go(x) {
case x {
[] -> []
[a, b] -> [a, b]
[1, ..rest] -> [1, ..rest]
_ -> x
}
}"
)
}
#[test]
fn case_building_record_matched_by_pattern() {
assert_js!(
"pub fn go(x) {
case x {
Ok(1) -> Ok(1)
Ok(n) -> Ok(n)
Error(_) -> Error(Nil)
}
}"
)
}
#[test]
fn case_building_record_with_select_matched_by_pattern() {
assert_js!(
"
import gleam
pub fn go(x) {
case x {
Ok(1) -> gleam.Ok(1)
_ -> Error(Nil)
}
}"
)
}
#[test]
fn case_building_record_with_select_matched_by_pattern_2() {
assert_js!(
"
import gleam
pub fn go(x) {
case x {
gleam.Ok(1) -> gleam.Ok(1)
_ -> Error(Nil)
}
}"
)
}
#[test]
fn case_building_record_with_select_matched_by_pattern_3() {
assert_js!(
"
import gleam
pub fn go(x) {
case x {
gleam.Ok(1) -> Ok(1)
_ -> Error(Nil)
}
}"
)
}
#[test]
fn case_building_matched_string_1() {
assert_js!(
r#"
import gleam
pub fn go(x) {
case x {
"a" <> rest -> "a" <> rest
_ -> ""
}
}"#
)
}
#[test]
fn case_building_matched_string_2() {
assert_js!(
r#"
import gleam
pub fn go(x) {
case x {
"a" as a <> rest -> a <> rest
_ -> ""
}
}"#
)
}
#[test]
fn case_building_matched_value_wrapped_in_block() {
assert_js!(
r#"
import gleam
pub fn go(x) {
case x {
1 -> { 1 }
_ -> 2
}
}"#
)
}
#[test]
fn case_building_matched_value_alias() {
assert_js!(
r#"
import gleam
pub fn go(x) {
case x {
Ok(_) as a -> a
Error(Nil) -> Error(Nil)
}
}"#
)
}
#[test]
fn case_building_matched_value_alias_2() {
assert_js!(
r#"
import gleam
pub fn go(x) {
case x {
Ok(1) as a -> Ok(1)
Ok(_) -> Ok(2)
Error(Nil) -> Error(Nil)
}
}"#
)
}
#[test]
fn case_building_matched_value_alias_3() {
assert_js!(
r#"
import gleam
pub fn go(x) {
case x {
Ok(1 as a) -> Ok(a)
Ok(_) -> Ok(2)
Error(Nil) -> Error(Nil)
}
}"#
)
}
#[test]
fn case_building_matched_no_variant_record() {
assert_js!(
r#"
pub fn go(x) {
case x {
Ok(Nil) -> Ok(Nil)
_ -> Error(Nil)
}
}"#
)
}
#[test]
fn case_building_matched_no_variant_record_2() {
assert_js!(
r#"
import gleam
pub fn go(x) {
case x {
Ok(gleam.Nil) -> Ok(Nil)
_ -> Error(Nil)
}
}"#
)
}
#[test]
fn case_building_matched_no_variant_record_3() {
assert_js!(
r#"
import gleam
pub fn go(x) {
case x {
Ok(Nil) -> Ok(gleam.Nil)
_ -> Error(Nil)
}
}"#
)
}
#[test]
fn case_building_matched_no_variant_record_4() {
assert_js!(
r#"
import gleam
pub fn go(x) {
case x {
Ok(gleam.Nil) -> Ok(gleam.Nil)
_ -> Error(Nil)
}
}"#
)
}
#[test]
fn case_building_record_with_labels_matched_by_pattern_1() {
assert_js!(
"
pub type Wibble {
Wibble(int: Int, string: String)
Wobble(Int)
}
pub fn go(x) {
case x {
Wibble(1, s) -> Wibble(1, s)
_ -> Wobble(1)
}
}"
)
}
#[test]
fn case_building_record_with_labels_matched_by_pattern_2() {
assert_js!(
"
pub type Wibble {
Wibble(int: Int, string: String)
Wobble(Int)
}
pub fn go(x) {
case x {
Wibble(string:, int:) -> Wibble(string:, int:)
_ -> Wobble(1)
}
}"
)
}
#[test]
fn case_building_record_with_labels_matched_by_pattern_3() {
assert_js!(
"
pub type Wibble {
Wibble(int: Int, string: String)
Wobble(Int)
}
pub fn go(x) {
case x {
// This should not be optimised away!
Wibble(string:, int:) -> Wibble(string:, int: 1)
_ -> Wobble(1)
}
}"
)
}
#[test]
fn case_building_record_with_labels_matched_by_pattern_4() {
assert_js!(
"
pub type Wibble {
Wibble(int: Int, string: String)
Wobble(Int)
}
pub fn go(x) {
case x {
Wibble(string:, int:) -> Wibble(int:, string:)
_ -> Wobble(1)
}
}"
)
}
#[test]
fn case_building_record_with_labels_matched_by_pattern_5() {
assert_js!(
"
pub type Wibble {
Wibble(int: Int, string: String)
Wobble(Int)
}
pub fn go(x) {
case x {
Wibble(string:, int: 1) -> Wibble(1, string:)
_ -> Wobble(1)
}
}"
)
}
#[test]
fn case_building_record_with_labels_matched_by_pattern_6() {
assert_js!(
"
pub type Wibble {
Wibble(int: Int, string: String)
Wobble(Int)
}
pub fn go(x) {
case x {
Wibble(1, string:) -> Wibble(string:, int: 1)
_ -> Wobble(1)
}
}"
)
}
#[test]
fn case_with_multiple_subjects_building_simple_value_matched_by_pattern() {
assert_js!(
"pub fn go(x) {
case x, x + 1 {
1, _ -> 2
_, n -> n
}
}"
)
}
#[test]
fn case_with_multiple_subjects_building_list_matched_by_pattern() {
assert_js!(
"pub fn go(n, x) {
case n, x {
1, [] -> []
_, [a, b] -> [a, b]
3, [1, ..rest] -> [1, ..rest]
_, _ -> x
}
}"
)
}
#[test]
fn case_with_multiple_subjects_building_record_matched_by_pattern() {
assert_js!(
"pub fn go(x, y) {
case x, y {
Ok(1), Error(_) -> Ok(1)
Error(_), Ok(n) -> Ok(n)
_, _ -> Error(Nil)
}
}"
)
}
#[test]
fn case_with_multiple_subjects_building_same_value_as_two_subjects_one_is_picked() {
assert_js!(
"
import gleam
pub fn go(x, y) {
case x, y {
gleam.Ok(1), Ok(1) -> Ok(1)
_, Error(Nil) -> Error(Nil)
_, _ -> Error(Nil)
}
}"
)
}
#[test]
fn interfering_string_pattern_fails_if_succeeding() {
assert_js!(
r#"
pub fn wibble(bits) {
case bits {
<<"aaa", 0, _:bits>> -> 1
// If the first one fails, we know this one won't match, so it won't appear
// in the final else branch!
<<_, "aa", 1, _:bits>> -> 2
_ -> 3
}
}"#
);
}
#[test]
fn interfering_string_pattern_succeeds_if_succeeding() {
assert_js!(
r#"
pub fn wibble(bits) {
case bits {
<<"aaa", 0, _:bits>> -> 1
// If the first one succeeds, so will the second check, so it won't be
// performed twice inside the first if branch!
<<"aaa", 1, _:bits>> -> 2
_ -> 3
}
}"#
);
}
#[test]
fn interfering_string_pattern_fails_if_failing() {
assert_js!(
r#"
pub fn wibble(bits) {
case bits {
<<"aaaa", 0, _:bits>> -> 1
// If the first one fails we know this one will fail as well, so it won't
// appear in the final else branch.
<<_, "aaabbb", 1, _:bits>> -> 2
_ -> 3
}
}"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/case_clause_guards.rs | compiler-core/src/javascript/tests/case_clause_guards.rs | use crate::assert_js;
#[test]
fn referencing_pattern_var() {
assert_js!(
r#"pub fn main(xs) {
case xs {
#(x) if x -> 1
_ -> 0
}
}
"#,
);
}
#[test]
fn rebound_var() {
assert_js!(
r#"pub fn main() {
let x = False
let x = True
case x {
_ if x -> 1
_ -> 0
}
}
"#,
);
}
#[test]
fn bitarray_with_var() {
assert_js!(
r#"pub fn main() {
case 5 {
z if <<z>> == <<z>> -> Nil
_ -> Nil
}
}
"#,
)
}
// https://github.com/gleam-lang/gleam/issues/3004
#[test]
fn keyword_var() {
assert_js!(
r#"
pub const function = 5
pub const do = 10
pub fn main() {
let class = 5
let while = 10
let var = 7
case var {
_ if class == while -> True
_ if [class] == [5] -> True
function if #(function) == #(5) -> False
_ if do == function -> True
while if while > 5 -> False
class -> False
}
}
"#,
);
}
#[test]
fn operator_wrapping_right() {
assert_js!(
r#"pub fn main(xs, y: Bool, z: Bool) {
case xs {
#(x) if x == { y == z } -> 1
_ -> 0
}
}
"#,
);
}
#[test]
fn operator_wrapping_left() {
assert_js!(
r#"pub fn main(xs, y: Bool, z: Bool) {
case xs {
#(x) if { x == y } == z -> 1
_ -> 0
}
}
"#,
);
}
#[test]
fn eq_scalar() {
assert_js!(
r#"pub fn main(xs, y: Int) {
case xs {
#(x) if x == y -> 1
_ -> 0
}
}
"#,
);
}
#[test]
fn not_eq_scalar() {
assert_js!(
r#"pub fn main(xs, y: Int) {
case xs {
#(x) if x != y -> 1
_ -> 0
}
}
"#,
);
}
#[test]
fn tuple_index() {
assert_js!(
r#"pub fn main(x, xs: #(Bool, Bool, Bool)) {
case x {
_ if xs.2 -> 1
_ -> 0
}
}
"#,
);
}
#[test]
fn not_eq_complex() {
assert_js!(
r#"pub fn main(xs, y) {
case xs {
#(x) if xs != y -> x
_ -> 0
}
}
"#,
);
}
#[test]
fn eq_complex() {
assert_js!(
r#"pub fn main(xs, y) {
case xs {
#(x) if xs == y -> x
_ -> 0
}
}
"#,
);
}
#[test]
fn constant() {
assert_js!(
r#"pub fn main(xs) {
case xs {
#(x) if x == 1 -> x
_ -> 0
}
}
"#,
);
}
#[test]
fn alternative_patterns() {
assert_js!(
r#"pub fn main(xs) {
case xs {
1 | 2 -> 0
_ -> 1
}
}
"#,
);
}
#[test]
fn alternative_patterns_list() {
assert_js!(
r#"pub fn main(xs) -> Int {
case xs {
[1] | [1, 2] -> 0
_ -> 1
}
}
"#,
);
}
#[test]
fn alternative_patterns_assignment() {
assert_js!(
r#"pub fn main(xs) -> Int {
case xs {
[x] | [_, x] -> x
_ -> 1
}
}
"#,
);
}
#[test]
fn alternative_patterns_guard() {
assert_js!(
r#"pub fn main(xs) -> Int {
case xs {
[x] | [_, x] if x == 1 -> x
_ -> 0
}
}
"#,
);
}
#[test]
fn field_access() {
assert_js!(
r#"
pub type Person {
Person(username: String, name: String, age: Int)
}
pub fn main() {
let given_name = "jack"
let raiden = Person("raiden", "jack", 31)
case given_name {
name if name == raiden.name -> "It's jack"
_ -> "It's not jack"
}
}
"#
)
}
#[test]
fn nested_record_access() {
assert_js!(
r#"
pub type A {
A(b: B)
}
pub type B {
B(c: C)
}
pub type C {
C(d: Bool)
}
pub fn a(a: A) {
case a {
_ if a.b.c.d -> 1
_ -> 0
}
}
"#
);
}
#[test]
fn module_string_access() {
assert_js!(
(
"package",
"hero",
r#"
pub const ironman = "Tony Stark"
"#
),
r#"
import hero
pub fn main() {
let name = "Tony Stark"
case name {
n if n == hero.ironman -> True
_ -> False
}
}
"#
);
}
#[test]
fn module_list_access() {
assert_js!(
(
"package",
"hero",
r#"
pub const heroes = ["Tony Stark", "Bruce Wayne"]
"#
),
r#"
import hero
pub fn main() {
let names = ["Tony Stark", "Bruce Wayne"]
case names {
n if n == hero.heroes -> True
_ -> False
}
}
"#
);
}
#[test]
fn module_tuple_access() {
assert_js!(
(
"package",
"hero",
r#"
pub const hero = #("ironman", "Tony Stark")
"#
),
r#"
import hero
pub fn main() {
let name = "Tony Stark"
case name {
n if n == hero.hero.1 -> True
_ -> False
}
}
"#
);
}
#[test]
fn module_access() {
assert_js!(
(
"package",
"hero",
r#"
pub type Hero {
Hero(name: String)
}
pub const ironman = Hero("Tony Stark")
"#
),
r#"
import hero
pub fn main() {
let name = "Tony Stark"
case name {
n if n == hero.ironman.name -> True
_ -> False
}
}
"#
);
}
#[test]
fn module_access_submodule() {
assert_js!(
(
"package",
"hero/submodule",
r#"
pub type Hero {
Hero(name: String)
}
pub const ironman = Hero("Tony Stark")
"#
),
r#"
import hero/submodule
pub fn main() {
let name = "Tony Stark"
case name {
n if n == submodule.ironman.name -> True
_ -> False
}
}
"#
);
}
#[test]
fn module_access_aliased() {
assert_js!(
(
"package",
"hero/submodule",
r#"
pub type Hero {
Hero(name: String)
}
pub const ironman = Hero("Tony Stark")
"#
),
r#"
import hero/submodule as myhero
pub fn main() {
let name = "Tony Stark"
case name {
n if n == myhero.ironman.name -> True
_ -> False
}
}
"#
);
}
#[test]
fn module_nested_access() {
assert_js!(
(
"package",
"hero",
r#"
pub type Person {
Person(name: String)
}
pub type Hero {
Hero(secret_identity: Person)
}
const bruce = Person("Bruce Wayne")
pub const batman = Hero(bruce)
"#
),
r#"
import hero
pub fn main() {
let name = "Bruce Wayne"
case name {
n if n == hero.batman.secret_identity.name -> True
_ -> False
}
}
"#
);
}
#[test]
fn not() {
assert_js!(
r#"pub fn main(x, y) {
case x {
_ if !y -> 0
_ -> 1
}
}
"#,
);
}
#[test]
fn not_two() {
assert_js!(
r#"pub fn main(x, y) {
case x {
_ if !y && !x -> 0
_ -> 1
}
}
"#,
);
}
#[test]
fn custom_type_constructor_imported_and_aliased() {
assert_js!(
("package", "other_module", "pub type T { A }"),
r#"import other_module.{A as B}
pub fn func() {
case B {
x if x == B -> True
_ -> False
}
}
"#,
);
}
#[test]
fn imported_aliased_ok() {
assert_js!(
r#"import gleam.{Ok as Y}
pub type X {
Ok
}
pub fn func() {
case Y {
y if y == Y -> True
_ -> False
}
}
"#,
);
}
#[test]
fn imported_ok() {
assert_js!(
r#"import gleam
pub type X {
Ok
}
pub fn func(x) {
case gleam.Ok {
_ if [] == [ gleam.Ok ] -> True
_ -> False
}
}
"#,
);
}
// Variant of https://github.com/lpil/decode/pull/6
#[test]
fn constructor_function_in_guard() {
assert_js!(
r#"pub fn func(x) {
case [] {
_ if [] == [ Ok ] -> True
_ -> False
}
}
"#,
);
}
// https://github.com/gleam-lang/gleam/issues/4241
#[test]
fn int_division() {
assert_js!(
r#"
pub fn main() {
case 5 / 2 {
x if x == 5 / 2 -> True
_ -> False
}
}
"#,
);
}
// https://github.com/gleam-lang/gleam/issues/4241
#[test]
fn float_division() {
assert_js!(
r#"
pub fn main() {
case 5.1 /. 0.0 {
x if x == 5.1 /. 0.0 -> True
_ -> False
}
}
"#,
);
}
// https://github.com/gleam-lang/gleam/issues/4241
#[test]
fn int_remainder() {
assert_js!(
r#"
pub fn main() {
case 4 % 0 {
x if x == 4 % 0 -> True
_ -> False
}
}
"#,
);
}
// https://github.com/gleam-lang/gleam/issues/5094
#[test]
fn guard_pattern_does_not_shadow_outer_scope() {
assert_js!(
r#"
pub type Option(a) {
Some(a)
None
}
pub type Container {
Container(x: Option(Int))
}
pub fn main() {
let x: Option(Int) = Some(42)
case Some(1) {
Some(x) if x < 0 -> Container(None)
_ -> {
Container(x:)
}
}
}
"#,
);
}
// https://github.com/gleam-lang/gleam/issues/5214
#[test]
fn bit_array_referencing_shadowed_variable() {
assert_js!(
"
pub fn main() {
let a = 1
let a = 2
case Nil {
_ if <<a>> == <<1>> -> False
_ if <<a>> == <<2>> -> True
_ -> False
}
}
"
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/modules.rs | compiler-core/src/javascript/tests/modules.rs | use crate::assert_js;
use crate::javascript::tests::CURRENT_PACKAGE;
#[test]
fn empty_module() {
// Renders an export statement to ensure it's an ESModule
assert_js!("", "export {}\n");
}
#[test]
fn unqualified_fn_call() {
assert_js!(
("rocket_ship", r#"pub fn launch() { 1 }"#),
r#"import rocket_ship.{launch}
pub fn go() { launch() }
"#,
);
}
#[test]
fn aliased_unqualified_fn_call() {
assert_js!(
("rocket_ship", r#"pub fn launch() { 1 }"#),
r#"import rocket_ship.{launch as boom_time}
pub fn go() { boom_time() }
"#,
);
}
#[test]
fn multiple_unqualified_fn_call() {
assert_js!(
(
CURRENT_PACKAGE,
"rocket_ship",
r#"
pub fn a() { 1 }
pub fn b() { 2 }"#
),
r#"import rocket_ship.{a,b as bb}
pub fn go() { a() + bb() }
"#,
);
}
#[test]
fn constant() {
assert_js!(
("rocket_ship", r#"pub const x = 1"#),
r#"
import rocket_ship
pub fn go() { rocket_ship.x }
"#,
);
}
#[test]
fn alias_aliased_constant() {
assert_js!(
("rocket_ship", r#"pub const x = 1"#),
r#"
import rocket_ship.{ x as y }
pub const z = y
"#,
);
}
#[test]
fn renamed_module() {
assert_js!(
("x", r#"pub const v = 1"#),
r#"
import x as y
pub const z = y.v
"#,
);
}
#[test]
fn nested_module_constant() {
assert_js!(
(
CURRENT_PACKAGE,
"rocket_ship/launcher",
r#"pub const x = 1"#
),
r#"
import rocket_ship/launcher
pub fn go() { launcher.x }
"#,
);
}
#[test]
fn alias_constant() {
assert_js!(
("rocket_ship", r#"pub const x = 1"#),
r#"
import rocket_ship as boop
pub fn go() { boop.x }
"#,
);
}
#[test]
fn alias_fn_call() {
assert_js!(
("rocket_ship", r#"pub fn go() { 1 }"#),
r#"
import rocket_ship as boop
pub fn go() { boop.go() }
"#,
);
}
#[test]
fn nested_fn_call() {
assert_js!(
("one/two", r#"pub fn go() { 1 }"#),
r#"import one/two
pub fn go() { two.go() }"#,
);
}
#[test]
fn nested_nested_fn_call() {
assert_js!(
("one/two/three", r#"pub fn go() { 1 }"#),
r#"import one/two/three
pub fn go() { three.go() }"#,
);
}
#[test]
fn different_package_import() {
assert_js!(
("other_package", "one", r#"pub fn go() { 1 }"#),
r#"import one
pub fn go() { one.go() }
"#,
);
}
#[test]
fn nested_same_package() {
assert_js!(
("one/two/three", r#"pub fn go() { 1 }"#),
r#"import one/two/three
pub fn go() { three.go() }
"#,
);
}
#[test]
fn discarded_duplicate_import() {
assert_js!(
("esa/rocket_ship", r#"pub fn go() { 1 }"#),
("nasa/rocket_ship", r#"pub fn go() { 1 }"#),
r#"
import esa/rocket_ship
import nasa/rocket_ship as _nasa_rocket
pub fn go() { rocket_ship.go() }
"#
);
}
#[test]
fn discarded_duplicate_import_with_unqualified() {
assert_js!(
("esa/rocket_ship", r#"pub fn go() { 1 }"#),
("nasa/rocket_ship", r#"pub fn go() { 1 }"#),
r#"
import esa/rocket_ship
import nasa/rocket_ship.{go} as _nasa_rocket
pub fn esa_go() { rocket_ship.go() }
pub fn nasa_go() { go() }
"#
);
}
#[test]
fn import_with_keyword() {
assert_js!(
(
CURRENT_PACKAGE,
"rocket_ship",
r#"
pub const class = 1
pub const in = 2
"#
),
r#"
import rocket_ship.{class, in as while}
pub fn main() {
#(class, while)
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/3004
#[test]
fn constant_module_access_with_keyword() {
assert_js!(
("rocket_ship", r#"pub const class = 1"#),
r#"
import rocket_ship
pub const variable = rocket_ship.class
"#,
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/results.rs | compiler-core/src/javascript/tests/results.rs | use crate::assert_js;
#[test]
fn ok() {
assert_js!(r#"pub fn main() { Ok(1) }"#);
}
#[test]
fn error() {
assert_js!(r#"pub fn main() { Error(1) }"#);
}
#[test]
fn ok_fn() {
assert_js!(r#"pub fn main() { Ok }"#);
}
#[test]
fn error_fn() {
assert_js!(r#"pub fn main() { Error }"#);
}
#[test]
fn qualified_ok() {
assert_js!(
r#"import gleam
pub fn main() { gleam.Ok(1) }"#
);
}
#[test]
fn qualified_error() {
assert_js!(
r#"import gleam
pub fn main() { gleam.Error(1) }"#
);
}
#[test]
fn qualified_ok_fn() {
assert_js!(
r#"import gleam
pub fn main() { gleam.Ok }"#
);
}
#[test]
fn qualified_error_fn() {
assert_js!(
r#"import gleam
pub fn main() { gleam.Error }"#
);
}
#[test]
fn aliased_ok() {
assert_js!(
r#"import gleam.{Ok as Thing}
pub fn main() { Thing(1) }"#
);
}
#[test]
fn aliased_error() {
assert_js!(
r#"import gleam.{Error as Thing}
pub fn main() { Thing(1) }"#
);
}
#[test]
fn aliased_ok_fn() {
assert_js!(
r#"import gleam.{Ok as Thing}
pub fn main() { Thing }"#
);
}
#[test]
fn aliased_error_fn() {
assert_js!(
r#"import gleam.{Error as Thing}
pub fn main() { Thing }"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/externals.rs | compiler-core/src/javascript/tests/externals.rs | use crate::{assert_js, assert_module_error, assert_ts_def};
#[test]
fn type_() {
assert_js!(r#"pub type Thing"#,);
}
#[test]
fn module_fn() {
assert_js!(
r#"
@external(javascript, "utils", "inspect")
fn show(x: anything) -> Nil"#,
);
}
#[test]
fn at_namespace_module() {
assert_js!(
r#"
@external(javascript, "@namespace/package", "inspect")
fn show(x: anything) -> Nil"#,
);
}
#[test]
fn pub_module_fn() {
assert_js!(
r#"
@external(javascript, "utils", "inspect")
pub fn show(x: anything) -> Nil"#,
);
}
#[test]
fn pub_module_fn_typescript() {
assert_ts_def!(
r#"
@external(javascript, "utils", "inspect")
pub fn show(x: anything) -> Nil"#,
);
}
#[test]
fn same_name_external() {
assert_js!(
r#"
@external(javascript, "thingy", "fetch")
pub fn fetch(request: Nil) -> Nil"#,
);
}
#[test]
fn same_module_multiple_imports() {
assert_js!(
r#"
@external(javascript, "./the/module.mjs", "one")
pub fn one() -> Nil
@external(javascript, "./the/module.mjs", "two")
pub fn two() -> Nil
"#,
);
}
#[test]
fn duplicate_import() {
assert_js!(
r#"
@external(javascript, "./the/module.mjs", "dup")
pub fn one() -> Nil
@external(javascript, "./the/module.mjs", "dup")
pub fn two() -> Nil
"#,
);
}
#[test]
fn name_to_escape() {
assert_js!(
r#"
@external(javascript, "./the/module.mjs", "one")
pub fn class() -> Nil
"#,
);
}
#[test]
fn external_type_typescript() {
assert_ts_def!(
r#"pub type Queue(a)
@external(javascript, "queue", "new")
pub fn new() -> Queue(a)
"#,
);
}
// https://github.com/gleam-lang/gleam/issues/1636
#[test]
fn external_fn_escaping() {
assert_js!(
r#"
@external(javascript, "./ffi.js", "then")
pub fn then(a: a) -> b"#,
);
}
// https://github.com/gleam-lang/gleam/issues/1954
#[test]
fn pipe_variable_shadow() {
assert_js!(
r#"
@external(javascript, "module", "string")
fn name() -> String
pub fn main() {
let name = name()
name
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2090
#[test]
fn tf_type_name_usage() {
assert_ts_def!(
r#"
pub type TESTitem
@external(javascript, "it", "one")
pub fn one(a: TESTitem) -> TESTitem
"#
);
}
#[test]
fn attribute_erlang() {
assert_js!(
r#"
@external(erlang, "one", "one_erl")
pub fn one(x: Int) -> Int {
todo
}
pub fn main() {
one(1)
}
"#
);
}
#[test]
fn attribute_javascript() {
assert_js!(
r#"
@external(javascript, "./one.mjs", "oneJs")
pub fn one(x: Int) -> Int {
todo
}
pub fn main() {
one(1)
}
"#
);
}
#[test]
fn erlang_and_javascript() {
assert_js!(
r#"
@external(erlang, "one", "one")
@external(javascript, "./one.mjs", "oneJs")
pub fn one(x: Int) -> Int {
todo
}
pub fn main() {
one(1)
}
"#
);
}
#[test]
fn private_attribute_erlang() {
assert_js!(
r#"
@external(erlang, "one", "one_erl")
fn one(x: Int) -> Int {
todo
}
pub fn main() {
one(1)
}
"#
);
}
#[test]
fn private_attribute_javascript() {
assert_js!(
r#"
@external(javascript, "./one.mjs", "oneJs")
fn one(x: Int) -> Int {
todo
}
pub fn main() {
one(1)
}
"#
);
}
#[test]
fn private_erlang_and_javascript() {
assert_js!(
r#"
@external(erlang, "one", "one")
@external(javascript, "./one.mjs", "oneJs")
fn one(x: Int) -> Int {
todo
}
pub fn main() {
one(1)
}
"#
);
}
#[test]
fn no_body() {
assert_js!(
r#"
@external(javascript, "one", "one")
pub fn one(x: Int) -> Int
"#
);
}
#[test]
fn no_module() {
assert_module_error!(
r#"
@external(javascript, "", "one")
pub fn one(x: Int) -> Int {
1
}
"#
);
}
#[test]
fn inline_function() {
assert_module_error!(
r#"
@external(javascript, "blah", "(x => x)")
pub fn one(x: Int) -> Int {
1
}
"#
);
}
#[test]
fn erlang_only() {
assert_js!(
r#"
pub fn should_be_generated(x: Int) -> Int {
x
}
@external(erlang, "one", "one")
pub fn should_not_be_generated(x: Int) -> Int
"#
);
}
#[test]
fn both_externals_no_valid_impl() {
assert_js!(
r#"
@external(javascript, "one", "one")
pub fn js() -> Nil
@external(erlang, "one", "one")
pub fn erl() -> Nil
pub fn should_not_be_generated() {
js()
erl()
}
"#
);
}
#[test]
fn discarded_names_in_external_are_passed_correctly() {
assert_js!(
r#"
@external(javascript, "wibble", "wobble")
pub fn woo(_ignored: a) -> Nil
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/lists.rs | compiler-core/src/javascript/tests/lists.rs | use crate::{assert_js, assert_ts_def};
#[test]
fn list_literals() {
assert_js!(
r#"
pub fn go(x) {
[]
[1]
[1, 2]
[1, 2, ..x]
}
"#,
);
}
#[test]
fn long_list_literals() {
assert_js!(
r#"
pub fn go() {
[111111111111111111111111111111111111111111111111111111111111111111111111]
[11111111111111111111111111111111111111111111, 1111111111111111111111111111111111111111111]
}
"#,
);
}
#[test]
fn multi_line_list_literals() {
assert_js!(
r#"
pub fn go(x) {
[{True 1}]
}
"#,
);
}
#[test]
fn list_constants() {
assert_js!(
r#"
pub const a = []
pub const b = [1, 2, 3]
"#,
);
}
#[test]
fn list_constants_typescript() {
assert_ts_def!(
r#"
pub const a = []
pub const b = [1, 2, 3]
"#,
);
}
#[test]
fn list_destructuring() {
assert_js!(
r#"
pub fn go(x, y) {
let assert [] = x
let assert [a] = x
let assert [1, 2] = x
let assert [_, #(3, b)] = y
let assert [head, ..tail] = y
}
"#,
);
}
#[test]
fn equality() {
assert_js!(
r#"
pub fn go() {
[] == [1]
[] != [1]
}
"#,
);
}
#[test]
fn case() {
assert_js!(
r#"
pub fn go(xs) {
case xs {
[] -> 0
[_] -> 1
[_, _] -> 2
_ -> 9999
}
}
"#,
);
}
// https://github.com/gleam-lang/gleam/issues/2904
#[test]
fn tight_empty_list() {
assert_js!(
r#"
pub fn go(func) {
let huuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuge_variable = []
}
"#,
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/assignments.rs | compiler-core/src/javascript/tests/assignments.rs | use crate::{assert_js, assert_ts_def};
#[test]
fn tuple_matching() {
assert_js!(
r#"
pub fn go(x) {
let assert #(1, 2) = x
}
"#,
)
}
#[test]
fn assert() {
assert_js!(r#"pub fn go(x) { let assert 1 = x }"#,);
}
#[test]
fn assert1() {
assert_js!(r#"pub fn go(x) { let assert #(1, 2) = x }"#,);
}
#[test]
fn nested_binding() {
assert_js!(
r#"
pub fn go(x) {
let assert #(a, #(b, c, 2) as t, _, 1) = x
}
"#,
)
}
#[test]
fn variable_renaming() {
assert_js!(
r#"
pub fn go(x, wibble) {
let a = 1
wibble(a)
let a = 2
wibble(a)
let assert #(a, 3) = x
let b = a
wibble(b)
let c = {
let a = a
#(a, b)
}
wibble(a)
// make sure arguments are counted in initial state
let x = c
x
}
"#,
)
}
#[test]
fn constant_assignments() {
assert_js!(
r#"
const a = True
pub fn go() {
a
let a = 10
a + 20
}
fn second() {
let a = 10
a + 20
}
"#,
);
}
#[test]
fn returning_literal_subject() {
assert_js!(r#"pub fn go(x) { let assert 1 = x + 1 }"#,);
}
#[test]
fn rebound_argument() {
assert_js!(
r#"pub fn main(x) {
let x = False
x
}
"#,
);
}
#[test]
fn rebound_function() {
assert_js!(
r#"pub fn x() {
Nil
}
pub fn main() {
let x = False
x
}
"#,
);
}
#[test]
fn rebound_function_and_arg() {
assert_js!(
r#"pub fn x() {
Nil
}
pub fn main(x) {
let x = False
x
}
"#,
);
}
#[test]
fn variable_used_in_pattern_and_assignment() {
assert_js!(
r#"pub fn main(x) {
let #(x) = #(x)
x
}
"#,
);
}
// https://github.com/gleam-lang/gleam/issues/1253
#[test]
fn correct_variable_renaming_in_assigned_functions() {
assert_js!(
r#"
pub fn debug(x) {
let x = x
fn(x) { x + 1 }
}
"#,
);
}
#[test]
fn module_const_var() {
assert_js!(
r#"
pub const int = 42
pub const int_alias = int
pub fn use_int_alias() { int_alias }
pub const compound: #(Int, Int) = #(int, int_alias)
pub fn use_compound() { compound.0 + compound.1 }
"#
);
}
#[test]
fn module_const_var1() {
assert_ts_def!(
r#"
pub const int = 42
pub const int_alias = int
pub const compound: #(Int, Int) = #(int, int_alias)
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2443
#[test]
fn let_assert_string_prefix() {
assert_js!(
r#"
pub fn main() {
let assert "Game " <> id = "Game 1"
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/3894
#[test]
fn let_assert_nested_string_prefix() {
assert_js!(
r#"
type Wibble {
Wibble(wibble: String)
}
pub fn main() {
let assert Wibble(wibble: "w" as prefix <> rest) = Wibble("wibble")
prefix <> rest
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2931
#[test]
fn keyword_assignment() {
assert_js!(
r#"
pub fn main() {
let class = 10
let debugger = 50
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/3004
#[test]
fn escaped_variables_in_constants() {
assert_js!(
r#"
pub const class = 5
pub const something = class
"#
);
}
#[test]
fn message() {
assert_js!(
r#"
pub fn unwrap_or_panic(value) {
let assert Ok(inner) = value as "Oops, there was an error"
inner
}
"#
);
}
#[test]
fn variable_message() {
assert_js!(
r#"
pub fn expect(value, message) {
let assert Ok(inner) = value as message
inner
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/4471
#[test]
fn case_message() {
assert_js!(
r#"
pub fn expect(value, message) {
let assert Ok(inner) = value as case message {
Ok(message) -> message
Error(_) -> "No message provided"
}
inner
}
"#
);
}
#[test]
fn assert_that_always_succeeds() {
assert_js!(
r#"
type Wibble {
Wibble(Int)
}
pub fn go() {
let assert Wibble(n) = Wibble(1)
n
}
"#,
);
}
#[test]
fn assert_that_always_fails() {
assert_js!(
r#"
type Wibble {
Wibble(Int)
Wobble(Int)
}
pub fn go() {
let assert Wobble(n) = Wibble(1)
n
}
"#,
);
}
#[test]
fn catch_all_assert() {
assert_js!(
r#"
type Wibble {
Wibble(Int)
Wobble(Int)
}
pub fn go() {
let assert _ = Wibble(1)
1
}
"#,
);
}
#[test]
fn assert_with_multiple_variants() {
assert_js!(
r#"
type Wibble {
Wibble(Int)
Wobble(Int)
Woo(Int)
}
pub fn go() {
let assert Wobble(n) = todo
n
}
"#,
);
}
#[test]
fn use_discard_assignment() {
assert_js!(
r#"
type Wibble {
Wibble(Int)
Wobble(Int)
Woo(Int)
}
fn fun(f) { f(Wibble(1)) }
pub fn go() {
use _ <- fun
1
}
"#,
);
}
#[test]
fn use_matching_assignment() {
assert_js!(
r#"
fn fun(f) { f(#(2, 4)) }
pub fn go() {
use #(_, n) <- fun
n
}
"#,
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/panic.rs | compiler-core/src/javascript/tests/panic.rs | use crate::{assert_js, assert_ts_def};
#[test]
fn bare() {
assert_js!(
r#"
pub fn go() {
panic
}
"#,
);
}
#[test]
fn panic_as() {
assert_js!(
r#"
pub fn go() {
let x = "wibble"
panic as x
}
"#,
);
}
#[test]
fn bare_typescript() {
assert_ts_def!(
r#"
pub fn go() {
panic
}
"#,
);
}
#[test]
fn as_expression() {
assert_js!(
r#"
pub fn go(f) {
let boop = panic
f(panic)
}
"#,
);
}
#[test]
fn pipe() {
assert_js!(
r#"
pub fn go(f) {
f |> panic
}
"#,
);
}
#[test]
fn sequence() {
assert_js!(
r#"
pub fn go(at_the_disco) {
panic
at_the_disco
}
"#,
);
}
#[test]
fn case() {
assert_js!(
r#"
pub fn go(x) {
case x {
_ -> panic
}
}
"#,
);
}
// https://github.com/gleam-lang/gleam/issues/4471
#[test]
fn case_message() {
assert_js!(
r#"
pub fn crash(message) {
panic as case message {
Ok(message) -> message
Error(_) -> "No message provided"
}
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/functions.rs | compiler-core/src/javascript/tests/functions.rs | use crate::{assert_js, assert_ts_def};
#[test]
fn exported_functions() {
assert_js!(
r#"
pub fn add(x, y) {
x + y
}"#,
);
}
#[test]
fn calling_functions() {
assert_js!(
r#"
pub fn twice(f: fn(t) -> t, x: t) -> t {
f(f(x))
}
pub fn add_one(x: Int) -> Int {
x + 1
}
pub fn add_two(x: Int) -> Int {
twice(add_one, x)
}
pub fn take_two(x: Int) -> Int {
twice(fn(y) {y - 1}, x)
}
"#,
);
}
#[test]
fn function_formatting() {
assert_js!(
r#"
pub fn add(the_first_variable_that_should_be_added, the_second_variable_that_should_be_added) {
the_first_variable_that_should_be_added + the_second_variable_that_should_be_added
}"#,
);
}
#[test]
fn function_formatting1() {
assert_js!(
r#"
pub fn this_function_really_does_have_a_ludicrously_unfeasibly_long_name_for_a_function(x, y) {
x + y
}"#,
);
}
#[test]
fn function_formatting2() {
assert_js!(
r#"
pub fn add(x, y) {
x + y
}
pub fn long() {
add(1, add(1, add(1, add(1, add(1, add(1, add(1, add(1, add(1, add(1, add(1, add(1, add(1, add(1, add(1, 1)))))))))))))))
}"#,
);
}
#[test]
fn function_formatting3() {
assert_js!(
r#"
pub fn math(x, y) {
fn() {
x + y
x - y
2 * x
}
}"#,
);
}
#[test]
fn function_formatting_typescript() {
assert_ts_def!(
r#"
pub fn add(the_first_variable_that_should_be_added, the_second_variable_that_should_be_added) {
the_first_variable_that_should_be_added + the_second_variable_that_should_be_added
}"#,
);
}
#[test]
fn function_formatting_typescript1() {
assert_ts_def!(
r#"
pub fn this_function_really_does_have_a_ludicrously_unfeasibly_long_name_for_a_function(x, y) {
x + y
}"#,
);
}
#[test]
fn tail_call() {
assert_js!(
r#"
pub fn count(xs, n) {
case xs {
[] -> n
[_, ..xs] -> count(xs, n + 1)
}
}
"#,
);
}
#[test]
fn tail_call_doesnt_clobber_tail_position_tracking() {
assert_js!(
r#"
pub fn loop(indentation) {
case indentation > 0 {
True -> loop(indentation - 1)
False -> Nil
}
}
"#,
);
}
#[test]
fn pipe_last() {
assert_js!(
r#"fn id(x) { x }
pub fn main() {
1
|> id
}
"#,
);
}
#[test]
fn calling_fn_literal() {
assert_js!(
r#"pub fn main() {
fn(x) { x }(1)
}
"#,
);
}
// Don't mistake calling a function with the same name as the current function
// as tail recursion
#[test]
fn shadowing_current() {
assert_js!(
r#"pub fn main() {
let main = fn() { 0 }
main()
}
"#,
);
}
#[test]
fn recursion_with_discards() {
assert_js!(
r#"pub fn main(f, _) {
f()
main(f, 1)
}
"#,
);
}
#[test]
fn no_recur_in_anon_fn() {
assert_js!(
r#"pub fn main() {
fn() { main() }
1
}
"#,
);
}
#[test]
fn case_in_call() {
assert_js!(
r#"pub fn main(f, x) {
f(case x {
1 -> 2
_ -> 0
})
}
"#,
);
}
#[test]
fn reserved_word_fn() {
assert_js!(
r#"pub fn class() {
Nil
}
"#,
);
}
#[test]
fn reserved_word_imported() {
assert_js!(
("for", "pub fn class() { 1 }"),
r#"import for.{class}
pub fn export() {
class()
}
"#,
);
}
#[test]
fn reserved_word_imported_alias() {
assert_js!(
("for", "pub fn class() { 1 }"),
r#"import for.{class as while} as function
pub fn export() {
let delete = function.class
while()
}
"#,
);
}
#[test]
fn reserved_word_const() {
assert_js!(
r#"const in = 1
pub fn export() {
in
}
"#,
);
}
// https://github.com/gleam-lang/gleam/issues/1208
#[test]
fn reserved_word_argument() {
assert_js!(
r#"pub fn main(with) {
with
}
"#,
);
}
// https://github.com/gleam-lang/gleam/issues/1186
#[test]
fn multiple_discard() {
assert_js!(
r#"pub fn main(_, _, _) {
1
}
"#,
);
}
#[test]
fn keyword_in_recursive_function() {
assert_js!(
r#"pub fn main(with: Int) -> Nil {
main(with - 1)
}
"#,
);
}
#[test]
fn reserved_word_in_function_arguments() {
assert_js!(
r#"pub fn main(arguments, eval) {
#(arguments, eval)
}
"#,
);
}
#[test]
fn let_last() {
assert_js!(
r#"pub fn main() {
let x = 1
}
"#,
);
}
#[test]
fn assert_last() {
assert_js!(
r#"pub fn main() {
let assert x = 1
}
"#,
);
}
#[test]
fn fn_return_fn_typescript() {
assert_ts_def!(
r#"pub fn main(f: fn(Int) -> Int) {
let func = fn(x, y) { f(x) + f(y) }
func
}
"#,
);
}
// https://github.com/gleam-lang/gleam/issues/1637
#[test]
fn variable_rewriting_in_anon_fn_with_matching_parameter() {
assert_js!(
r#"pub fn bad() {
fn(state) {
let state = state
state
}
}
"#,
);
}
// https://github.com/gleam-lang/gleam/issues/1637
#[test]
fn variable_rewriting_in_anon_fn_with_matching_parameter_in_case() {
assert_js!(
r#"pub fn bad() {
fn(state) {
let state = case Nil {
_ -> state
}
state
}
}
"#,
);
}
// https://github.com/gleam-lang/gleam/issues/1508
#[test]
fn pipe_variable_rebinding() {
assert_js!(
"
pub fn main() {
let version = 1 |> version()
version
}
pub fn version(n) {
Ok(1)
}"
)
}
#[test]
fn pipe_shadow_import() {
assert_js!(
("wibble", "pub fn println(x: String) { }"),
r#"
import wibble.{println}
pub fn main() {
let println =
"oh dear"
|> println
println
}"#
);
}
#[test]
fn module_const_fn() {
assert_js!(
r#"
pub fn int_identity(i: Int) -> Int { i }
pub const int_identity_alias: fn(Int) -> Int = int_identity
pub fn use_int_identity_alias() { int_identity_alias(42) }
pub const compound: #(fn(Int) -> Int, fn(Int) -> Int) = #(int_identity, int_identity_alias)
pub fn use_compound() { compound.0(compound.1(42)) }"#
);
}
#[test]
fn module_const_fn1() {
assert_ts_def!(
r#"
pub fn int_identity(i: Int) -> Int { i }
pub const int_identity_alias: fn(Int) -> Int = int_identity
pub const compound: #(fn(Int) -> Int, fn(Int) -> Int) =
#(int_identity, int_identity_alias)"#
)
}
// https://github.com/gleam-lang/gleam/issues/2399
#[test]
fn bad_comma() {
assert_js!(
r#"
fn function_with_a_long_name_that_is_intended_to_sit_right_on_the_limit() {
Nil
}
fn identity(x) {
x
}
pub fn main() {
function_with_a_long_name_that_is_intended_to_sit_right_on_the_limit()
|> identity
}
"#
)
}
// https://github.com/gleam-lang/gleam/issues/2518
#[test]
fn function_literals_get_properly_wrapped_1() {
assert_js!(
r#"pub fn main() {
fn(n) { n + 1 }(10)
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2518
#[test]
fn function_literals_get_properly_wrapped_2() {
assert_js!(
r#"pub fn main() {
{ fn(n) { n + 1 } }(10)
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2518
#[test]
fn function_literals_get_properly_wrapped_3() {
assert_js!(
r#"pub fn main() {
{ let a = fn(n) { n + 1 } }(10)
}
"#
);
}
#[test]
fn labelled_argument_ordering() {
// https://github.com/gleam-lang/gleam/issues/3671
assert_js!(
"
type A { A }
type B { B }
type C { C }
type D { D }
fn wibble(a a: A, b b: B, c c: C, d d: D) {
Nil
}
pub fn main() {
wibble(A, C, D, b: B)
wibble(A, C, D, b: B)
wibble(B, C, D, a: A)
wibble(B, C, a: A, d: D)
wibble(B, C, d: D, a: A)
wibble(B, D, a: A, c: C)
wibble(B, D, c: C, a: A)
wibble(C, D, b: B, a: A)
}
"
);
}
// During the implementation of https://github.com/gleam-lang/gleam/pull/4337,
// a bug was found where this code would compile incorrectly.
#[test]
fn two_pipes_in_a_row() {
assert_js!(
"
pub type Function(a) {
Function(fn() -> a)
}
pub fn main() {
[fn() { 1 } |> Function, fn() { 2 } |> Function]
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/4472
#[test]
fn pipe_into_block() {
assert_js!(
"
fn side_effects(x) { x }
pub fn main() {
1
|> side_effects
|> {
side_effects(2)
side_effects
}
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/4472
#[test]
fn pipe_with_block_in_the_middle() {
assert_js!(
"
fn side_effects(x) { x }
pub fn main() {
1
|> side_effects
|> {
side_effects(2)
side_effects
}
|> side_effects
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/4533
#[test]
fn immediately_invoked_function_expressions_include_statement_level() {
assert_js!(
"
fn identity(x) { x }
pub type Wibble {
Wibble(a: Int, b: Int)
}
pub fn main() {
let w = Wibble(1, 2)
identity(Wibble(..w |> identity, b: 4)) |> identity
}
"
);
}
#[test]
fn public_function_gets_jsdoc() {
assert_js!(
"
/// Hello! This is the documentation of the `main`
/// function.
///
pub fn main() { 1 }
"
);
}
#[test]
fn internal_function_gets_ignored_jsdoc() {
assert_js!(
"
/// Hello! This is the documentation of the `main`
/// function, which is internal!
///
@internal
pub fn main() { 1 }
"
);
}
#[test]
fn star_slash_in_jsdoc() {
assert_js!(
"
/// */
///
pub fn main() { 1 }
"
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/recursion.rs | compiler-core/src/javascript/tests/recursion.rs | use crate::assert_js;
#[test]
fn tco() {
assert_js!(
r#"
pub fn main(x) {
case x {
0 -> Nil
_ -> main(x - 1)
}
}
"#
);
}
#[test]
fn tco_case_block() {
assert_js!(
r#"
pub fn main(x) {
case x {
0 -> Nil
_ -> {
let y = x
main(y - 1)
}
}
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/1779
#[test]
fn not_tco_due_to_assignment() {
assert_js!(
r#"
pub fn main(x) {
let z = {
let y = x
main(y - 1)
}
z
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2400
#[test]
fn shadowing_so_not_recursive() {
// This funtion is calling an argument with the same name as itself, so it is not recursive
assert_js!(
r#"
pub fn map(map) {
map()
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/todo.rs | compiler-core/src/javascript/tests/todo.rs | use crate::{assert_js, assert_ts_def};
#[test]
fn without_message() {
assert_js!(
r#"
pub fn go() {
todo
}
"#,
);
}
#[test]
fn without_message_typescript() {
assert_ts_def!(
r#"
pub fn go() {
todo
}
"#,
);
}
#[test]
fn with_message() {
assert_js!(
r#"
pub fn go() {
todo as "I should do this"
}
"#,
);
}
#[test]
fn with_message_expr() {
assert_js!(
r#"
pub fn go() {
let x = "I should " <> "do this"
todo as x
}
"#,
);
}
// https://github.com/gleam-lang/gleam/issues/1238
#[test]
fn as_expression() {
assert_js!(
r#"
pub fn go(f) {
let boop = todo as "I should do this"
f(todo as "Boom")
}
"#,
);
}
// https://github.com/gleam-lang/gleam/issues/4471
#[test]
fn case_message() {
assert_js!(
r#"
pub fn unimplemented(message) {
panic as case message {
Ok(message) -> message
Error(_) -> "No message provided"
}
}
"#
);
}
#[test]
fn inside_fn() {
assert_js!(
r#"
pub fn main() {
fn() { todo }
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/echo.rs | compiler-core/src/javascript/tests/echo.rs | use crate::assert_js;
#[test]
pub fn echo_with_a_simple_expression() {
assert_js!(
r#"
pub fn main() {
echo 1
}
"#
);
}
#[test]
pub fn echo_with_a_simple_expression_and_a_message() {
assert_js!(
r#"
pub fn main() {
echo 1 as "hello!"
}
"#
);
}
#[test]
pub fn echo_with_complex_expression_as_a_message() {
assert_js!(
r#"
pub fn main() {
echo 1 as case name() {
"Giacomo" -> "hello Jak!"
_ -> "hello!"
}
}
fn name() { "Giacomo" }
"#
);
}
#[test]
pub fn echo_evaluates_printed_value_before_message() {
assert_js!(
r#"
pub fn main() {
echo name() as case name() {
"Giacomo" -> "hello Jak!"
_ -> "hello!"
}
}
fn name() { "Giacomo" }
"#
);
}
#[test]
pub fn echo_with_a_block_as_a_message() {
assert_js!(
r#"
pub fn main() {
echo 1 as {
let name = "Giacomo"
"Hello, " <> name
}
}
"#
);
}
#[test]
pub fn multiple_echos_inside_expression() {
assert_js!(
r#"
pub fn main() {
echo 1
echo 2
}
"#
);
}
#[test]
pub fn echo_with_a_case_expression() {
assert_js!(
r#"
pub fn main() {
echo case 1 {
_ -> 2
}
}
"#
);
}
#[test]
pub fn echo_with_a_panic() {
assert_js!(
r#"
pub fn main() {
echo panic
}
"#
);
}
#[test]
pub fn echo_with_a_function_call() {
assert_js!(
r#"
pub fn main() {
echo wibble(1, 2)
}
fn wibble(n: Int, m: Int) { n + m }
"#
);
}
#[test]
pub fn echo_with_a_function_call_and_a_message() {
assert_js!(
r#"
pub fn main() {
echo wibble(1, 2) as message()
}
fn wibble(n: Int, m: Int) { n + m }
fn message() { "Hello!" }
"#
);
}
#[test]
pub fn echo_with_a_block() {
assert_js!(
r#"
pub fn main() {
echo {
Nil
1
}
}
"#
);
}
#[test]
pub fn echo_in_a_pipeline() {
assert_js!(
r#"
pub fn main() {
[1, 2, 3]
|> echo
|> wibble
}
pub fn wibble(n) { n }
"#
)
}
#[test]
pub fn echo_in_a_pipeline_with_message() {
assert_js!(
r#"
pub fn main() {
[1, 2, 3]
|> echo as "message!!"
|> wibble
}
pub fn wibble(n) { n }
"#
)
}
#[test]
pub fn multiple_echos_in_a_pipeline() {
assert_js!(
r#"
pub fn main() {
[1, 2, 3]
|> echo
|> wibble
|> echo
|> wibble
|> echo
}
pub fn wibble(n) { n }
"#
)
}
#[test]
pub fn module_named_inspect() {
assert_js!(
("other", "other/inspect", "pub const x = Nil"),
r#"
import other/inspect
pub fn main() {
echo inspect.x
}
"#
)
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/generics.rs | compiler-core/src/javascript/tests/generics.rs | use crate::assert_ts_def;
#[test]
fn fn_generics_typescript() {
assert_ts_def!(
r#"pub fn identity(a) -> a {
a
}
"#,
);
}
#[test]
fn record_generics_typescript() {
assert_ts_def!(
r#"pub type Animal(t) {
Cat(type_: t)
Dog(type_: t)
}
pub fn main() {
Cat(type_: 6)
}
"#,
);
}
#[test]
fn tuple_generics_typescript() {
assert_ts_def!(
r#"pub fn make_tuple(x: t) -> #(Int, t, Int) {
#(0, x, 1)
}
"#,
);
}
#[test]
fn result_typescript() {
assert_ts_def!(
r#"pub fn map(result, fun) {
case result {
Ok(a) -> Ok(fun(a))
Error(e) -> Error(e)
}
}"#,
);
}
#[test]
fn task_typescript() {
assert_ts_def!(
r#"pub type Promise(value)
pub type Task(a) = fn() -> Promise(a)"#,
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/numbers.rs | compiler-core/src/javascript/tests/numbers.rs | use crate::{assert_js, assert_js_module_error};
#[test]
fn int_literals() {
assert_js!(
r#"
pub fn go() {
1
2
-3
4001
0b00001111
0o17
0xF
1_000
}
"#,
);
}
#[test]
fn float_literals() {
assert_js!(
r#"
pub fn go() {
1.5
2.0
-0.1
1.
}
"#,
);
}
#[test]
fn float_scientific_literals() {
assert_js!(
r#"
pub fn go() {
0.01e-1
0.01e-0
-10.01e-1
-10.01e-0
-100.001e-523
-100.001e-123_456_789
}
"#,
);
}
#[test]
fn int_operators() {
assert_js!(
r#"
pub fn go() {
1 + 1 // => 2
5 - 1 // => 4
5 / 2 // => 2
3 * 3 // => 9
5 % 2 // => 1
2 > 1 // => True
2 < 1 // => False
2 >= 1 // => True
2 <= 1 // => False
}
"#,
);
}
#[test]
fn int_divide_complex_expr() {
assert_js!(
r#"
pub fn go() {
case 1 >= 0 {
True -> 2
False -> 4
} / 2
}
"#,
);
}
#[test]
fn int_mod_complex_expr() {
assert_js!(
r#"
pub fn go() {
case 1 >= 0 {
True -> 2
False -> 4
} % 2
}
"#,
);
}
#[test]
fn float_operators() {
assert_js!(
r#"
pub fn go() {
1.0 +. 1.4 // => 2.4
5.0 -. 1.5 // => 3.5
5.0 /. 2.0 // => 2.5
3.0 *. 3.1 // => 9.3
2.0 >. 1.0 // => True
2.0 <. 1.0 // => False
2.0 >=. 1.0 // => True
2.0 <=. 1.0 // => False
}
"#,
);
}
#[test]
fn float_divide_complex_expr() {
assert_js!(
r#"
pub fn go() {
case 1.0 >=. 0.0 {
True -> 2.0
False -> 4.0
} /. 2.0
}
"#,
);
}
#[test]
fn wide_float_div() {
assert_js!(
r#"
pub fn go() {
111111111111111111111111111111. /. 22222222222222222222222222222222222.
}
"#,
);
}
#[test]
fn int_patterns() {
assert_js!(
r#"
pub fn go(x) {
let assert 4 = x
}
"#,
);
}
#[test]
fn int_equality() {
assert_js!(
r#"
pub fn go() {
1 != 2
1 == 2
}
"#,
);
}
#[test]
fn int_equality1() {
assert_js!(
r#"
pub fn go(y) {
let x = 1
x == y
}
"#,
);
}
#[test]
fn float_equality() {
assert_js!(
r#"
pub fn go() {
1.0 != 2.0
1.0 == 2.0
}
"#,
);
}
#[test]
fn float_equality1() {
assert_js!(
r#"
pub fn go(y) {
let x = 1.0
x == y
}
"#,
);
}
#[test]
fn operator_precedence() {
assert_js!(
r#"
pub fn go() {
2.4 *. { 3.5 +. 6.0 }
}
"#,
)
}
#[test]
fn remainder() {
assert_js!(
r#"
pub fn go() {
5 % 0 // => 0
}
"#,
);
}
#[test]
fn int_negation() {
assert_js!(
r#"
pub fn go() {
let a = 3
let b = -a
}
"#,
);
}
#[test]
fn repeated_int_negation() {
assert_js!(
r#"
pub fn go() {
let a = 3
let b = --a
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2412
#[test]
fn preceeding_zeros_int() {
assert_js!(
r#"
pub fn main() {
09_179
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2412
#[test]
fn preceeding_zeros_float() {
assert_js!(
r#"
pub fn main() {
09_179.1
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2412
#[test]
fn preceeding_zeros_int_const() {
assert_js!(
r#"
pub const x = 09_179
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2412
#[test]
fn preceeding_zeros_float_const() {
assert_js!(
r#"
pub const x = 09_179.1
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2412
#[test]
fn preceeding_zeros_int_pattern() {
assert_js!(
r#"
pub fn main(x) {
let assert 09_179 = x
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2412
#[test]
fn preceeding_zeros_float_pattern() {
assert_js!(
r#"
pub fn main(x) {
let assert 09_179.1 = x
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/4459
#[test]
fn underscore_after_hexadecimal_prefix() {
assert_js!(
"
pub fn main() {
0x_12_34
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/4459
#[test]
fn underscore_after_octal_prefix() {
assert_js!(
"
pub fn main() {
0o_12_34
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/4459
#[test]
fn underscore_after_binary_prefix() {
assert_js!(
"
pub fn main() {
0b_10_01
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/4481
#[test]
fn underscore_after_zero_after_hex_prefix() {
assert_js!(
"
pub fn main() {
0x0_1_2_3
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/4481
#[test]
fn underscore_after_zero_after_octal_prefix() {
assert_js!(
"
pub fn main() {
0o0_1_2_3
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/4481
#[test]
fn underscore_after_zero_after_binary_prefix() {
assert_js!(
"
pub fn main() {
0b0_1_0_1
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/4481
#[test]
fn underscore_after_zero() {
assert_js!(
"
pub fn main() {
0_1_2_3
}
"
);
}
#[test]
fn zero_after_underscore_after_hex_prefix() {
assert_js!(
"
pub fn main() {
0x_0_1_2_3
}
"
);
}
#[test]
fn zero_after_underscore_after_octal_prefix() {
assert_js!(
"
pub fn main() {
0o_0_1_2_3
}
"
);
}
#[test]
fn zero_after_underscore_after_binary_prefix() {
assert_js!(
"
pub fn main() {
0b_0_1_0_1
}
"
);
}
#[test]
fn underscore_after_decimal_point() {
assert_js!(
"
pub fn main() {
0._1
}
"
);
}
#[test]
fn underscore_after_decimal_point_case_statement() {
assert_js!(
"
pub fn main(x) {
case x {
0._1 -> \"wobble\"
_ -> \"wibble\"
}
}
"
);
}
#[test]
fn inf_float_case_statement() {
assert_js_module_error!(
"
pub fn main(x) {
case x {
100.001e123_456_789 -> \"wobble\"
_ -> \"wibble\"
}
}
"
);
}
#[test]
fn division_inf_by_inf_float() {
assert_js_module_error!(
"
pub fn main(x) {
-100.001e123_456_789 /. 100.001e123_456_789
}
"
);
}
#[test]
fn division_by_zero_float() {
assert_js!(
"pub fn main() {
1.1 /. 0.0
}"
)
}
#[test]
fn division_by_non_zero_float() {
assert_js!(
"pub fn main() {
1.1 /. 2.3
}"
)
}
#[test]
fn complex_division_by_non_zero_float() {
assert_js!(
"pub fn main() {
{ 1.1 +. 2.0 } /. 2.3
}"
)
}
#[test]
fn division_by_zero_int() {
assert_js!(
"pub fn main() {
1 / 0
}"
)
}
#[test]
fn division_by_non_zero_int() {
assert_js!(
"pub fn main() {
1 / 2
}"
)
}
#[test]
fn complex_division_by_non_zero_int() {
assert_js!(
"pub fn main() {
{ 1 + 2 } / 3
}"
)
}
#[test]
fn remainder_by_zero_int() {
assert_js!(
"pub fn main() {
1 % 0
}"
)
}
#[test]
fn remainder_by_non_zero_int() {
assert_js!(
"pub fn main() {
1 % 2
}"
)
}
#[test]
fn complex_remainder_by_non_zero_int() {
assert_js!(
"pub fn main() {
{ 1 + 2 } % 3
}"
)
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/records.rs | compiler-core/src/javascript/tests/records.rs | use crate::assert_js;
#[test]
fn record_accessors() {
// We can use record accessors for types with only one constructor
assert_js!(
r#"
pub type Person { Person(name: String, age: Int) }
pub fn get_age(person: Person) { person.age }
pub fn get_name(person: Person) { person.name }
"#
);
}
#[test]
fn record_accessor_multiple_variants() {
// We can access fields on custom types with multiple variants
assert_js!(
"
pub type Person {
Teacher(name: String, title: String)
Student(name: String, age: Int)
}
pub fn get_name(person: Person) { person.name }"
);
}
#[test]
fn record_accessor_multiple_variants_positions_other_than_first() {
// We can access fields on custom types with multiple variants
// In positions other than the 1st field
assert_js!(
"
pub type Person {
Teacher(name: String, age: Int, title: String)
Student(name: String, age: Int)
}
pub fn get_name(person: Person) { person.name }
pub fn get_age(person: Person) { person.age }"
);
}
#[test]
fn record_accessor_multiple_with_first_position_different_types() {
// We can access fields on custom types with multiple variants
// In positions other than the 1st field
assert_js!(
"
pub type Person {
Teacher(name: Nil, age: Int)
Student(name: String, age: Int)
}
pub fn get_age(person: Person) { person.age }"
);
}
#[test]
fn record_accessor_multiple_variants_parameterised_types() {
// We can access fields on custom types with multiple variants
// In positions other than the 1st field
assert_js!(
"
pub type Person {
Teacher(name: String, age: List(Int), title: String)
Student(name: String, age: List(Int))
}
pub fn get_name(person: Person) { person.name }
pub fn get_age(person: Person) { person.age }"
);
}
// https://github.com/gleam-lang/gleam/issues/4603
#[test]
fn field_named_x0() {
assert_js!(
"
pub type Wibble {
Wibble(Int, x0: String)
}
"
);
}
#[test]
fn field_named_then_is_escaped() {
assert_js!(
"
pub type Wibble {
Wibble(then: fn() -> Int)
}
"
);
}
#[test]
fn field_named_constructor_is_escaped() {
assert_js!(
"
pub type Wibble {
Wibble(constructor: fn() -> Wibble)
}
"
);
}
#[test]
fn field_named_prototype_is_escaped() {
assert_js!(
"
pub type Wibble {
Wibble(prototype: String)
}
"
);
}
#[test]
fn const_record_update_generic_respecialization() {
assert_js!(
"
pub type Box(a) {
Box(name: String, value: a)
}
pub const base = Box(\"score\", 50)
pub const updated = Box(..base, value: \"Hello\")
pub fn main() {
#(base, updated)
}
",
);
}
#[test]
fn record_update_with_unlabelled_fields() {
assert_js!(
r#"
pub type Wibble {
Wibble(Int, Float, b: Bool, s: String)
}
pub fn main() {
let record = Wibble(1, 3.14, True, "Hello")
Wibble(..record, b: False)
}
"#
);
}
#[test]
fn constant_record_update_with_unlabelled_fields() {
assert_js!(
r#"
pub type Wibble {
Wibble(Int, Float, b: Bool, s: String)
}
pub const record = Wibble(1, 3.14, True, "Hello")
pub const updated = Wibble(..record, b: False)
pub fn main() {
updated
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/strings.rs | compiler-core/src/javascript/tests/strings.rs | use crate::assert_js;
#[test]
fn unicode1() {
assert_js!(
r#"
pub fn emoji() -> String {
"\u{1f600}"
}
"#,
);
}
#[test]
fn unicode2() {
assert_js!(
r#"
pub fn y_with_dieresis() -> String {
"\u{0308}y"
}
"#,
);
}
#[test]
fn ascii_as_unicode_escape_sequence() {
assert_js!(
r#"
pub fn y() -> String {
"\u{79}"
}
"#,
)
}
#[test]
fn unicode_escape_sequence_6_digits() {
assert_js!(
r#"
pub fn unicode_escape_sequence_6_digits() -> String {
"\u{10abcd}"
}
"#,
);
}
#[test]
fn string_literals() {
assert_js!(
r#"
pub fn go() {
"Hello, Gleam!"
}
"#,
);
}
#[test]
fn string_patterns() {
assert_js!(
r#"
pub fn go(x) {
let assert "Hello" = x
}
"#,
);
}
#[test]
fn equality() {
assert_js!(
r#"
pub fn go(a) {
a == "ok"
a != "ok"
a == a
}
"#,
);
}
#[test]
fn case() {
assert_js!(
r#"
pub fn go(a) {
case a {
"" -> 0
"one" -> 1
"two" -> 2
_ -> 3
}
}
"#,
);
}
#[test]
fn string_concat() {
assert_js!(
r#"
pub fn go() {
"Hello, " <> "Joe"
}
"#,
);
}
#[test]
fn string_prefix() {
assert_js!(
r#"
pub fn go(x) {
case x {
"Hello, " <> name -> name
_ -> "Unknown"
}
}
"#,
);
}
#[test]
fn string_prefix_utf16() {
assert_js!(
r#"
pub fn go(x) {
case "Θ wibble wobble" {
"Θ" <> rest -> rest
_ -> ""
}
case "🫥 is neutral dotted" {
"🫥" <> rest -> rest
_ -> ""
}
case "🇺🇸 is a cluster" {
"🇺🇸" <> rest -> rest
_ -> ""
}
case "\" is a an escaped quote" {
"\"" <> rest -> rest
_ -> ""
}
case "\\ is a an escaped backslash" {
"\\" <> rest -> rest
_ -> ""
}
}
"#,
);
}
#[test]
fn discard_concat_rest_pattern() {
// We can discard the right hand side, it parses and type checks ok
assert_js!(
r#"
pub fn go(x) {
case x {
"Hello, " <> _ -> Nil
_ -> Nil
}
}
"#,
);
}
#[test]
fn string_prefix_assignment() {
assert_js!(
r#"
pub fn go(x) {
case x {
"Hello, " as greeting <> name -> greeting
_ -> "Unknown"
}
}
"#,
)
}
#[test]
fn string_prefix_assignment_with_utf_escape_sequence() {
assert_js!(
r#"
pub fn go(x) {
case x {
"\u{0032} " as greeting <> name -> greeting
"\u{0007ff} " as greeting <> name -> greeting
"\u{00ffff} " as greeting <> name -> greeting
"\u{10ffff} " as greeting <> name -> greeting
_ -> "Unknown"
}
}
"#,
)
}
#[test]
fn string_prefix_shadowing() {
assert_js!(
r#"
pub fn go(x) {
case x {
"Hello, " as x <> name -> x
_ -> "Unknown"
}
}
"#,
)
}
// https://github.com/gleam-lang/gleam/issues/2471
#[test]
fn string_prefix_assignment_with_multiple_subjects() {
assert_js!(
r#"
pub fn go(x) {
case x {
"1" as prefix <> _ | "11" as prefix <> _ -> prefix
_ -> "Unknown"
}
}
"#,
)
}
#[test]
fn const_concat() {
assert_js!(
r#"
pub const cute = "cute"
pub const cute_bee = cute <> "bee"
pub fn main() {
cute_bee
}
"#
);
}
#[test]
fn const_concat_multiple() {
assert_js!(
r#"
pub const cute = "cute"
pub const cute_bee = cute <> "bee"
pub const cute_cute_bee_buzz = cute <> cute_bee <> "buzz"
pub fn main() {
cute_cute_bee_buzz
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/bools.rs | compiler-core/src/javascript/tests/bools.rs | use crate::{assert_js, assert_ts_def};
#[test]
fn expressions() {
assert_js!(
r#"
pub fn go() {
True
False
Nil
}
"#
);
}
#[test]
fn constants() {
assert_js!(
r#"
pub const a = True
pub const b = False
pub const c = Nil
"#,
);
}
#[test]
fn constants_typescript() {
assert_ts_def!(
r#"
pub const a = True
pub const b = False
pub const c = Nil
"#,
);
}
#[test]
fn operators() {
assert_js!(
r#"
pub fn go() {
True && True
False || False
}
"#,
);
}
#[test]
fn assigning() {
assert_js!(
r#"
pub fn go(x, y) {
let assert True = x
let assert False = x
let assert Nil = y
}
"#,
);
}
// https://github.com/gleam-lang/gleam/issues/1112
// differentiate between prelude constructors and custom type constructors
#[test]
fn shadowed_bools_and_nil() {
assert_js!(
r#"
pub type True { True False Nil }
pub fn go(x, y) {
let assert True = x
let assert False = x
let assert Nil = y
}
"#,
);
}
#[test]
fn shadowed_bools_and_nil_typescript() {
assert_ts_def!(
r#"
pub type True { True False Nil }
pub fn go(x, y) {
let assert True = x
let assert False = x
let assert Nil = y
}
"#,
);
}
#[test]
fn equality() {
assert_js!(
r#"
pub fn go(a, b) {
a == True
a != True
a == False
a != False
a == a
a != a
b == Nil
b != Nil
b == b
}
"#,
);
}
#[test]
fn case() {
assert_js!(
r#"
pub fn go(a) {
case a {
True -> 1
False -> 0
}
}
"#,
);
}
#[test]
fn nil_case() {
assert_js!(
r#"
pub fn go(a) {
case a {
Nil -> 0
}
}
"#,
);
}
#[test]
fn negation() {
assert_js!(
"pub fn negate(x) {
!x
}"
);
}
#[test]
fn negation_block() {
assert_js!(
"pub fn negate(x) {
!{
123
x
}
}"
);
}
#[test]
fn binop_panic_right() {
assert_js!(
"pub fn negate(x) {
x && panic
}"
);
}
#[test]
fn binop_panic_left() {
assert_js!(
"pub fn negate(x) {
panic && x
}"
);
}
#[test]
fn binop_todo_right() {
assert_js!(
"pub fn negate(x) {
x && todo
}"
);
}
#[test]
fn binop_todo_left() {
assert_js!(
"pub fn negate(x) {
todo && x
}"
);
}
#[test]
fn negate_panic() {
assert_js!(
"pub fn negate(x) {
!panic
}"
);
}
#[test]
fn negate_todo() {
assert_js!(
"pub fn negate(x) {
!todo
}"
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/blocks.rs | compiler-core/src/javascript/tests/blocks.rs | use crate::assert_js;
#[test]
fn block() {
assert_js!(
r#"
pub fn go() {
let x = {
1
2
}
x
}
"#,
);
}
#[test]
fn nested_simple_blocks() {
assert_js!(
r#"
pub fn go() {
let x = {
{
3
}
}
x
}
"#,
);
}
#[test]
fn nested_multiexpr_blocks() {
assert_js!(
r#"
pub fn go() {
let x = {
1
{
2
3
}
}
x
}
"#,
);
}
#[test]
fn nested_multiexpr_blocks_with_pipe() {
assert_js!(
r#"
pub fn add1(a) {
a + 1
}
pub fn go() {
let x = {
1
{
2
3 |> add1
} |> add1
}
x
}
"#,
);
}
#[test]
fn nested_multiexpr_non_ending_blocks() {
assert_js!(
r#"
pub fn go() {
let x = {
1
{
2
3
}
4
}
x
}
"#,
);
}
#[test]
fn nested_multiexpr_blocks_with_case() {
assert_js!(
r#"
pub fn go() {
let x = {
1
{
2
case True {
_ -> 3
}
}
}
x
}
"#,
);
}
#[test]
fn sequences() {
assert_js!(
r#"
pub fn go() {
"one"
"two"
"three"
}
"#,
);
}
#[test]
fn left_operator_sequence() {
assert_js!(
r#"
pub fn go() {
1 == {
1
2
}
}
"#,
);
}
#[test]
fn right_operator_sequence() {
assert_js!(
r#"
pub fn go() {
{
1
2
} == 1
}
"#,
);
}
#[test]
fn concat_blocks() {
assert_js!(
r#"
pub fn main(f, a, b) {
{
a
|> f
} <> {
b
|> f
}
}
"#,
);
}
#[test]
fn blocks_returning_functions() {
assert_js!(
r#"
pub fn b() {
{
fn(cb) { cb(1) }
}
{
fn(cb) { cb(2) }
}
3
}
"#
);
}
#[test]
fn blocks_returning_use() {
assert_js!(
r#"
pub fn b() {
{
use a <- fn(cb) { cb(1) }
a
}
{
use b <- fn(cb) { cb(2) }
b
}
3
}
"#
);
}
#[test]
fn block_with_parenthesised_expression_returning_from_function() {
assert_js!(
r#"
pub fn b() {
{
1 + 2
}
}
"#
);
}
#[test]
fn block_in_tail_position_is_not_an_iife() {
assert_js!(
r#"
pub fn b() {
let x = 1
{
Nil
x + 1
}
}
"#
);
}
#[test]
fn block_in_tail_position_shadowing_variables() {
assert_js!(
r#"
pub fn b() {
let x = 1
{
let x = 2
x + 1
}
}
"#
);
}
#[test]
fn block_in_tail_position_with_just_an_assignment() {
assert_js!(
r#"
pub fn b() {
let x = 1
{
let x = x
}
}
"#
);
}
#[test]
fn shadowed_variable_in_nested_scope() {
assert_js!(
"
pub fn main() {
{
let x = 1
let _ = {
let x = 2
x
}
x
}
}
"
)
}
// https://github.com/gleam-lang/gleam/issues/4393
#[test]
fn let_assert_only_statement_in_block() {
assert_js!(
"
pub fn main() {
{
let assert Ok(1) = Error(Nil)
}
}
"
)
}
// https://github.com/gleam-lang/gleam/issues/4394
#[test]
fn assignment_last_in_block() {
assert_js!(
"
pub fn main() {
let a = {
let b = 1
let c = b + 1
}
a
}
"
)
}
// https://github.com/gleam-lang/gleam/issues/4394
#[test]
fn pattern_assignment_last_in_block() {
assert_js!(
"
pub fn main() {
let a = {
let b = #(1, 2)
let #(x, y) = b
}
a
}
"
)
}
// https://github.com/gleam-lang/gleam/issues/4395
#[test]
fn let_assert_message_no_lifted() {
assert_js!(
r#"
fn side_effects(x) {
// Some side effects
x
}
pub fn main() {
let assert Error(Nil) = side_effects(Ok(10))
as {
let message = side_effects("some message")
message
}
}
"#
)
}
#[test]
fn blocks_whose_values_are_unused_do_not_generate_assignments() {
// There's no point generating `_block` assignments here, as the values
// would be unused.
assert_js!(
"
pub fn main() {
{
let x = 10
echo x
}
{
let a = 1
let b = 2
a + b
}
Nil
}
"
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/tuples.rs | compiler-core/src/javascript/tests/tuples.rs | use crate::{assert_js, assert_ts_def};
#[test]
fn tuple() {
assert_js!(
r#"
pub fn go() {
#("1", "2", "3")
}
"#,
);
}
#[test]
fn tuple1() {
assert_js!(
r#"
pub fn go() {
#(
"1111111111111111111111111111111",
#("1111111111111111111111111111111", "2", "3"),
"3",
)
}
"#,
);
}
#[test]
fn tuple_typescript() {
assert_ts_def!(
r#"
pub fn go() {
#("1", "2", "3")
}
"#,
);
}
#[test]
fn tuple_access() {
assert_js!(
r#"
pub fn go() {
#(1, 2).0
}
"#,
)
}
#[test]
fn tuple_with_block_element() {
assert_js!(
r#"
pub fn go() {
#(
"1",
{
"2"
"3"
},
)
}
"#,
);
}
#[test]
fn tuple_with_block_element1() {
assert_js!(
r#"
pub fn go() {
#(
"1111111111111111111111111111111",
#("1111111111111111111111111111111", "2", "3"),
"3",
)
}
"#,
);
}
#[test]
fn constant_tuples() {
assert_js!(
r#"
pub const a = "Hello"
pub const b = 1
pub const c = 2.0
pub const e = #("bob", "dug")
"#,
);
}
#[test]
fn constant_tuples1() {
assert_js!(
r#"
pub const e = #(
"loooooooooooooong", "loooooooooooong", "loooooooooooooong",
"loooooooooooooong", "loooooooooooong", "loooooooooooooong",
)
"#
);
}
#[test]
fn tuple_formatting_typescript() {
assert_ts_def!(
r#"
pub const e = #(
"a", "a", "a", "a", "a", "a", "a",
"a", "a", "a", "a", "a", "a", "a",
"a", "a", "a", "a", "a", "a", "a",
)
"#
);
}
#[test]
fn case() {
assert_js!(
r#"
pub fn go(a) {
case a {
#(2, a) -> a
#(1, 1) -> 1
#(a, b) -> a + b
}
}
"#
);
}
#[test]
fn nested_pattern() {
assert_js!(
r#"
pub fn go(x) {
case x {
#(2, #(a, b)) -> a + b
_ -> 1
}
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/custom_types.rs | compiler-core/src/javascript/tests/custom_types.rs | use crate::javascript::tests::CURRENT_PACKAGE;
use crate::{assert_js, assert_ts_def};
#[test]
fn zero_arity_literal() {
assert_js!(
r#"
pub type Mine {
This
ThatOneIsAMuchMuchMuchMuchMuchMuchMuchMuchMuchMuchMuchMuchLongerVariant
}
pub fn go() {
This
ThatOneIsAMuchMuchMuchMuchMuchMuchMuchMuchMuchMuchMuchMuchLongerVariant
}
"#,
);
}
#[test]
fn zero_arity_const() {
assert_js!(
r#"
pub type Mine {
This
ThatOneIsAMuchMuchMuchMuchMuchMuchMuchMuchMuchMuchMuchMuchLongerVariant
}
pub const this = This
pub const that = ThatOneIsAMuchMuchMuchMuchMuchMuchMuchMuchMuchMuchMuchMuchLongerVariant
"#,
);
}
#[test]
fn zero_arity_imported() {
assert_js!(
("other", r#"pub type One { Two }"#),
r#"import other
pub fn main() {
other.Two
}"#,
);
}
#[test]
fn zero_arity_imported_typscript() {
assert_ts_def!(
(CURRENT_PACKAGE, "other", r#"pub type One { Two }"#),
r#"import other
pub fn main() {
other.Two
}"#,
);
}
#[test]
fn zero_arity_imported_unqualified() {
assert_js!(
("other", r#"pub type One { Two }"#),
r#"import other.{Two}
pub fn main() {
Two
}"#,
);
}
#[test]
fn zero_arity_imported_unqualified_typescript() {
assert_ts_def!(
(CURRENT_PACKAGE, "other", r#"pub type One { Two }"#),
r#"import other.{Two}
pub fn main() {
Two
}"#,
);
}
#[test]
fn zero_arity_imported_unqualified_aliased() {
assert_js!(
("other", r#"pub type One { Two }"#),
r#"import other.{Two as Three}
pub fn main() {
Three
}"#
);
}
#[test]
fn zero_arity_imported_unqualified_aliased_typescript() {
assert_ts_def!(
(CURRENT_PACKAGE, "other", r#"pub type One { Two }"#),
r#"import other.{Two as Three}
pub fn main() {
Three
}"#
);
}
#[test]
fn const_zero_arity_imported() {
assert_js!(
("other", r#"pub type One { Two }"#),
r#"import other
pub const x = other.Two
"#,
);
}
#[test]
fn const_zero_arity_imported_unqualified() {
assert_js!(
("other", r#"pub type One { Two }"#),
r#"import other.{Two}
pub const a = Two
"#,
);
}
#[test]
fn const_with_fields() {
assert_js!(
r#"
pub type Mine {
Mine(a: Int, b: Int)
}
pub const labels = Mine(b: 2, a: 1)
pub const no_labels = Mine(3, 4)
"#,
);
}
#[test]
fn const_with_fields_typescript() {
assert_ts_def!(
r#"
pub type Mine {
Mine(a: Int, b: Int)
}
pub const labels = Mine(b: 2, a: 1)
pub const no_labels = Mine(3, 4)
"#,
);
}
#[test]
fn unnamed_fields() {
assert_js!(
r#"
pub type Ip {
Ip(String)
}
pub const local = Ip("0.0.0.0")
pub fn build(x) {
x("1.2.3.4")
}
pub fn go() {
build(Ip)
Ip("5.6.7.8")
}
pub fn destructure(x) {
let Ip(raw) = x
raw
}
"#,
);
}
#[test]
fn unnamed_fields_typescript() {
assert_ts_def!(
r#"
pub type Ip{
Ip(String)
}
pub const local = Ip("0.0.0.0")
"#,
);
}
#[test]
fn long_name_variant_without_labels() {
assert_js!(
r#"
pub type TypeWithALongNameAndSeveralArguments{
TypeWithALongNameAndSeveralArguments(String, String, String, String, String)
}
pub fn go() {
TypeWithALongNameAndSeveralArguments
}
"#,
);
}
#[test]
fn long_name_variant_mixed_labels_typescript() {
assert_ts_def!(
r#"
pub type TypeWithALongNameAndSeveralArguments{
TypeWithALongNameAndSeveralArguments(String, String, String, a: String, b: String)
}
pub const local = TypeWithALongNameAndSeveralArguments("one", "two", "three", "four", "five")
"#,
);
}
#[test]
fn custom_type_with_named_fields() {
assert_js!(
r#"
pub type Cat {
Cat(name: String, cuteness: Int)
}
pub type Box {
Box(occupant: Cat)
}
pub const felix = Cat("Felix", 12)
pub const tom = Cat(cuteness: 1, name: "Tom")
pub fn go() {
Cat("Nubi", 1)
Cat(2, name: "Nubi")
Cat(cuteness: 3, name: "Nubi")
}
pub fn update(cat) {
Cat(..cat, name: "Sid")
Cat(..cat, name: "Bartholemew Wonder Puss the Fourth !!!!!!!!!!!!!!!!")
Cat(..new_cat(), name: "Molly")
let box = Box(occupant: cat)
Cat(..box.occupant, cuteness: box.occupant.cuteness + 1)
}
pub fn access(cat: Cat) {
cat.cuteness
}
pub fn new_cat() {
Cat(name: "Beau", cuteness: 11)
}
"#,
);
}
#[test]
fn destructure_custom_type_with_named_fields() {
assert_js!(
r#"
pub type Cat {
Cat(name: String, cuteness: Int)
}
pub fn go(cat) {
let Cat(x, y) = cat
let Cat(name: x, ..) = cat
let assert Cat(cuteness: 4, name: x) = cat
x
}
"#,
)
}
#[test]
fn destructure_custom_type_with_mixed_fields_first_unlabelled() {
assert_js!(
r#"
pub type Cat {
Cat(String, cuteness: Int)
}
pub fn go(cat) {
let Cat(x, y) = cat
let Cat(cuteness: y, ..) = cat
let Cat(x, cuteness: y) = cat
x
}
"#,
)
}
#[test]
fn nested_pattern_with_labels() {
assert_js!(
r#"pub type Box(x) { Box(a: Int, b: x) }
pub fn go(x) {
case x {
Box(a: _, b: Box(a: a, b: b)) -> a + b
_ -> 1
}
}
"#,
);
}
#[test]
fn imported_no_label() {
assert_js!(
("other", r#"pub type One { Two(Int) }"#),
r#"import other
pub fn main() {
other.Two(1)
}"#,
);
}
#[test]
fn imported_ignoring_label() {
assert_js!(
("other", r#"pub type One { Two(field: Int) }"#),
r#"import other
pub fn main() {
other.Two(1)
}"#,
);
}
#[test]
fn imported_using_label() {
assert_js!(
("other", r#"pub type One { Two(field: Int) }"#),
r#"import other
pub fn main() {
other.Two(field: 1)
}"#,
);
}
#[test]
fn imported_multiple_fields() {
assert_js!(
("other", r#"pub type One { Two(a: Int, b: Int, c: Int) }"#),
r#"import other
pub fn main() {
other.Two(b: 2, c: 3, a: 1)
}"#,
);
}
#[test]
fn unqualified_imported_no_label() {
assert_js!(
("other", r#"pub type One { Two(Int) }"#),
r#"import other.{Two}
pub fn main() {
Two(1)
}"#,
);
}
#[test]
fn unqualified_imported_no_label_typescript() {
assert_ts_def!(
(CURRENT_PACKAGE, "other", r#"pub type One { Two(Int) }"#),
r#"import other.{Two}
pub fn main() {
Two(1)
}"#,
);
}
#[test]
fn unqualified_imported_ignoring_label() {
assert_js!(
("other", r#"pub type One { Two(field: Int) }"#),
r#"import other.{Two}
pub fn main() {
Two(1)
}"#,
);
}
#[test]
fn unqualified_imported_using_label() {
assert_js!(
("other", r#"pub type One { Two(field: Int) }"#),
r#"import other.{Two}
pub fn main() {
Two(field: 1)
}"#,
);
}
#[test]
fn unqualified_imported_multiple_fields() {
assert_js!(
("other", r#"pub type One { Two(a: Int, b: Int, c: Int) }"#),
r#"import other.{Two}
pub fn main() {
Two(b: 2, c: 3, a: 1)
}"#,
);
}
#[test]
fn constructor_as_value() {
assert_js!(
("other", r#"pub type One { Two(a: Int, b: Int, c: Int) }"#),
r#"import other
pub fn main() {
other.Two
}"#,
);
}
#[test]
fn unqualified_constructor_as_value() {
assert_js!(
("other", r#"pub type One { Two(a: Int, b: Int, c: Int) }"#),
r#"import other.{Two}
pub fn main() {
Two
}"#,
);
}
#[test]
fn const_imported_no_label() {
assert_js!(
("other", r#"pub type One { Two(Int) }"#),
r#"import other
pub const main = other.Two(1)
"#,
);
}
#[test]
fn const_imported_ignoring_label() {
assert_js!(
("other", r#"pub type One { Two(field: Int) }"#),
r#"import other
pub const main = other.Two(1)
"#,
);
}
#[test]
fn const_imported_using_label() {
assert_js!(
("other", r#"pub type One { Two(field: Int) }"#),
r#"import other
pub const main = other.Two(field: 1)
"#,
);
}
#[test]
fn const_imported_multiple_fields() {
assert_js!(
("other", r#"pub type One { Two(a: Int, b: Int, c: Int) }"#),
r#"import other
pub const main = other.Two(b: 2, c: 3, a: 1)
"#,
);
}
#[test]
fn const_unqualified_imported_no_label() {
assert_js!(
("other", r#"pub type One { Two(Int) }"#),
r#"import other.{Two}
pub const main = Two(1)
"#,
);
}
#[test]
fn const_unqualified_imported_ignoring_label() {
assert_js!(
("other", r#"pub type One { Two(field: Int) }"#),
r#"import other.{Two}
pub const main = Two(1)
"#,
);
}
#[test]
fn const_unqualified_imported_using_label() {
assert_js!(
("other", r#"pub type One { Two(field: Int) }"#),
r#"import other.{Two}
pub const main = Two(field: 1)
"#,
);
}
#[test]
fn const_unqualified_imported_multiple_fields() {
assert_js!(
("other", r#"pub type One { Two(a: Int, b: Int, c: Int) }"#),
r#"import other.{Two}
pub const main = Two(b: 2, c: 3, a: 1)
"#,
);
}
#[test]
fn imported_pattern() {
assert_js!(
("other", r#"pub type One { Two(a: Int, b: Int, c: Int) }"#),
r#"import other.{Two}
pub fn main(x) {
case x {
Two(a: 1, ..) -> 1
other.Two(b: 2, c: c, ..) -> c
_ -> 3
}
}
"#,
);
}
#[test]
fn keyword_label_name() {
assert_js!(
r#"pub type Thing {
Thing(in: Int, class: Nil)
}
"#,
);
}
#[test]
fn qualified() {
assert_js!(
("other", r#"pub type One { One }"#),
r#"import other
pub fn main() {
other.One
}
"#,
);
}
#[test]
fn unapplied_record_constructors_typescript() {
assert_ts_def!(
r#"pub type Cat { Cat(name: String) }
pub fn return_unapplied_cat() {
Cat
}
"#
);
}
#[test]
fn opaque_types_typescript() {
assert_ts_def!(
r#"pub opaque type Animal {
Cat(goes_outside: Bool)
Dog(plays_fetch: Bool)
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/1650
#[test]
fn types_must_be_rendered_before_functions() {
assert_js!(
r#"
pub fn one() { One }
pub type One { One }
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2386
#[test]
fn new_type_import_syntax() {
assert_js!(
("package", "a", r#"pub type A { A }"#),
r#"
import a.{type A, A}
pub fn main() {
A
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/3813
#[test]
fn record_with_field_named_constructor() {
assert_js!(
r#"
pub type Thing {
Thing(constructor: Nil)
}
pub fn main() {
let a = Thing(constructor: Nil)
let b = Thing(..a, constructor: Nil)
b.constructor
}
"#
);
}
#[test]
fn record_with_field_named_then() {
assert_js!(
r#"
pub type Thing {
Thing(then: Nil)
}
pub fn main() {
let a = Thing(then: Nil)
let b = Thing(..a, then: Nil)
b.then
}
"#
);
}
#[test]
fn record_access_in_guard_with_reserved_field_name() {
assert_js!(
r#"
pub type Thing {
Thing(constructor: Nil)
}
pub fn main() {
let a = Thing(constructor: Nil)
case Nil {
Nil if a.constructor == Nil -> a.constructor
_ -> Nil
}
}
"#
);
}
#[test]
fn record_access_in_pattern_with_reserved_field_name() {
assert_js!(
r#"
pub type Thing {
Thing(constructor: Nil)
}
pub fn main() {
let a = Thing(constructor: Nil)
let Thing(constructor: ctor) = a
case a {
a if a.constructor == ctor -> Nil
Thing(constructor:) if ctor == constructor -> Nil
_ -> Nil
}
}
"#
);
}
#[test]
fn constructors_get_their_own_jsdoc() {
assert_js!(
r#"
pub type Wibble {
/// Wibbling!!
Wibble(field: Int)
/// Wobbling!!
Wobble(field: Int)
}
"#
);
}
#[test]
fn singleton_record_equality() {
assert_js!(
r#"
pub type Wibble {
Wibble
Wobble
}
pub fn is_wibble(w: Wibble) -> Bool {
w == Wibble
}
"#,
);
}
#[test]
fn singleton_record_inequality() {
assert_js!(
r#"
pub type Wibble {
Wibble
Wobble
}
pub fn is_not_wibble(w: Wibble) -> Bool {
w != Wibble
}
"#,
);
}
#[test]
fn singleton_record_reverse_order() {
assert_js!(
r#"
pub type Wibble {
Wibble
Wobble
}
pub fn is_wibble_reverse(w: Wibble) -> Bool {
Wibble == w
}
"#,
);
}
#[test]
fn non_singleton_record_equality() {
assert_js!(
r#"
pub type Person {
Person(name: String, age: Int)
}
pub fn same_person(p1: Person, p2: Person) -> Bool {
p1 == p2
}
"#,
);
}
#[test]
fn multiple_singleton_constructors() {
assert_js!(
r#"
pub type Status {
Loading
Success
Error
}
pub fn is_loading(s: Status) -> Bool {
s == Loading
}
pub fn is_success(s: Status) -> Bool {
s == Success
}
"#,
);
}
#[test]
fn mixed_singleton_and_non_singleton() {
assert_js!(
r#"
pub type Result {
Ok(value: Int)
Error
}
pub fn is_error(r: Result) -> Bool {
r == Error
}
"#,
);
}
#[test]
fn singleton_in_case_guard() {
assert_js!(
r#"
pub type State {
Active
Inactive
}
pub fn process(s: State) -> String {
case s {
state if state == Active -> "active"
_ -> "inactive"
}
}
"#,
);
}
#[test]
fn equality_with_non_singleton_variant() {
assert_js!(
r#"
pub type Thing {
Variant
Other(String)
}
pub fn check_other(x: Thing) -> Bool {
x == Other("hello")
}
"#,
);
}
#[test]
fn guard_equality_with_non_singleton_variant() {
assert_js!(
r#"
pub type Thing {
Variant
Other(String)
}
pub fn process(e: Thing) -> String {
case e {
value if value == Other("hello") -> "match"
_ -> "no match"
}
}
"#,
);
}
#[test]
fn variant_defined_in_another_module_qualified_expression() {
assert_js!(
(
"other_module",
r#"pub type Thingy { Variant OtherVariant }"#
),
r#"
import other_module
pub fn check(x) -> Bool {
x == other_module.Variant
}
"#,
);
}
#[test]
fn variant_defined_in_another_module_unqualified_expression() {
assert_js!(
("other_module", r#"pub type Thingy { Variant Other(Int) }"#),
r#"
import other_module.{Variant}
pub fn check(x) -> Bool {
x == Variant
}
"#,
);
}
#[test]
fn variant_defined_in_another_module_aliased_expression() {
assert_js!(
("other_module", r#"pub type Thingy { Variant Other(Int) }"#),
r#"
import other_module.{Variant as Aliased}
pub fn check(x) -> Bool {
x == Aliased
}
"#,
);
}
#[test]
fn variant_defined_in_another_module_qualified_clause_guard() {
assert_js!(
("other_module", r#"pub type Thingy { Variant Other(Int) }"#),
r#"
import other_module
pub fn process(e) -> String {
case e {
value if value == other_module.Variant -> "match"
_ -> "no match"
}
}
"#,
);
}
#[test]
fn variant_defined_in_another_module_unqualified_clause_guard() {
assert_js!(
("other_module", r#"pub type Thingy { Variant Other(Int) }"#),
r#"
import other_module.{Variant}
pub fn process(e) -> String {
case e {
value if value == Variant -> "match"
_ -> "no match"
}
}
"#,
);
}
#[test]
fn variant_defined_in_another_module_aliased_clause_guard() {
assert_js!(
("other_module", r#"pub type Thingy { Variant Other(Int) }"#),
r#"
import other_module.{Variant as Aliased}
pub fn process(e) -> String {
case e {
value if value == Aliased -> "match"
_ -> "no match"
}
}
"#,
);
}
#[test]
fn external_annotation() {
assert_ts_def!(
r#"
@external(javascript, "./gleam_stdlib.d.ts", "Dict")
pub type Dict(key, value)
"#
);
}
#[test]
fn external_annotated_type_used_in_function() {
assert_ts_def!(
r#"
@external(javascript, "./gleam_stdlib.d.ts", "Dict")
pub type Dict(key, value)
@external(javascript, "./gleam_stdlib.mjs", "get")
pub fn get(dict: Dict(key, value), key: key) -> Result(value, Nil)
"#
);
}
// https://github.com/gleam-lang/gleam/issues/5127
#[test]
fn unused_opaque_constructor_is_generated_correctly() {
assert_ts_def!(
"
type Wibble {
Wibble
}
pub opaque type Wobble {
Wobble(Wibble)
}
"
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/type_alias.rs | compiler-core/src/javascript/tests/type_alias.rs | use crate::assert_ts_def;
#[test]
fn type_alias() {
assert_ts_def!(
r#"
pub type Headers = List(#(String, String))
"#,
);
}
#[test]
fn private_type_in_opaque_type() {
assert_ts_def!(
r#"
type PrivateType {
PrivateType
}
pub opaque type OpaqueType {
OpaqueType(PrivateType)
}
"#,
);
}
#[test]
fn import_indirect_type_alias() {
assert_ts_def!(
(
"wibble",
"wibble",
r#"
pub type Wibble {
Wibble(Int)
}
"#
),
(
"wobble",
"wobble",
r#"
import wibble
pub type Wobble = wibble.Wibble
"#
),
r#"
import wobble
pub fn main(x: wobble.Wobble) {
Nil
}
"#,
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/bit_arrays.rs | compiler-core/src/javascript/tests/bit_arrays.rs | use hexpm::version::Version;
use pubgrub::Range;
use crate::{
assert_js, assert_js_no_warnings_with_gleam_version, assert_js_warnings_with_gleam_version,
assert_ts_def,
};
#[test]
fn empty() {
assert_js!(
r#"
pub fn go() {
<<>>
}
"#,
);
}
#[test]
fn one() {
assert_js!(
r#"
pub fn go() {
<<256>>
}
"#,
);
}
#[test]
fn two() {
assert_js!(
r#"
pub fn go() {
<<256, 4>>
}
"#,
);
}
#[test]
fn integer() {
assert_js!(
r#"
pub fn go() {
<<256:int>>
}
"#,
);
}
#[test]
fn float() {
assert_js!(
r#"
pub fn go() {
<<1.1:float>>
}
"#,
);
}
#[test]
fn float_big_endian() {
assert_js!(
r#"
pub fn go() {
<<1.1:float-big>>
}
"#,
);
}
#[test]
fn float_little_endian() {
assert_js!(
r#"
pub fn go() {
<<1.1:float-little>>
}
"#,
);
}
#[test]
fn float_sized() {
assert_js!(
r#"
pub fn go() {
<<1.1:float-32>>
}
"#,
);
}
#[test]
fn float_sized_big_endian() {
assert_js!(
r#"
pub fn go() {
<<1.1:float-32-big>>
}
"#,
);
}
#[test]
fn float_sized_little_endian() {
assert_js!(
r#"
pub fn go() {
<<1.1:float-32-little>>
}
"#,
);
}
#[test]
fn sized_constant_value() {
assert_js!(
r#"
pub fn go() {
<<256:64>>
}
"#,
);
}
#[test]
fn sized_dynamic_value() {
assert_js!(
r#"
pub fn go(i: Int) {
<<i:64>>
}
"#,
);
}
#[test]
fn sized_constant_value_positive_overflow() {
assert_js!(
r#"
pub fn go() {
<<80_000:16>>
}
"#,
);
}
#[test]
fn sized_constant_value_negative_overflow() {
assert_js!(
r#"
pub fn go() {
<<-80_000:16>>
}
"#,
);
}
#[test]
fn sized_constant_value_max_size_for_compile_time_evaluation() {
assert_js!(
r#"
pub fn go() {
<<-1:48>>
}
"#,
);
}
#[test]
fn sized_big_endian_constant_value() {
assert_js!(
r#"
pub fn go() {
<<256:16-big>>
}
"#,
);
}
#[test]
fn sized_big_endian_dynamic_value() {
assert_js!(
r#"
pub fn go(i: Int) {
<<i:16-big>>
}
"#,
);
}
#[test]
fn sized_little_endian_constant_value() {
assert_js!(
r#"
pub fn go() {
<<256:16-little>>
}
"#,
);
}
#[test]
fn sized_little_endian_dynamic_value() {
assert_js!(
r#"
pub fn go(i: Int) {
<<i:16-little>>
}
"#,
);
}
#[test]
fn explicit_sized_constant_value() {
assert_js!(
r#"
pub fn go() {
<<256:size(32)>>
}
"#,
);
}
#[test]
fn explicit_sized_dynamic_value() {
assert_js!(
r#"
pub fn go(i: Int) {
<<i:size(32)>>
}
"#,
);
}
#[test]
fn variable_sized() {
assert_js!(
r#"
pub fn go(x, y) {
<<x:size(y)>>
}
"#,
);
}
#[test]
fn variable() {
assert_js!(
r#"
pub fn go(x) {
<<256, 4, x>>
}
"#,
);
}
#[test]
fn utf8() {
assert_js!(
r#"
pub fn go(x) {
<<256, 4, x, "Gleam":utf8>>
}
"#,
);
}
#[test]
fn match_utf8_with_escape_chars() {
assert_js!(
r#"
pub fn go(x) {
let assert <<"\"\\\r\n\t\f\u{1f600}">> = x
}
"#,
);
}
#[test]
fn match_utf8() {
assert_js!(
r#"
pub fn go(x) {
let assert <<"Gleam 👍":utf8>> = x
}
"#,
);
}
#[test]
fn match_case_utf8_with_escape_chars() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<"\"\\\r\n\t\f\u{1f600}">> -> 1
_ -> 2
}
}
"#,
);
}
#[test]
fn match_case_utf8() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<"Gleam 👍":utf8>> -> 1
_ -> 2
}
}
"#,
);
}
#[test]
fn utf8_codepoint() {
assert_js!(
r#"
pub fn go(x) {
<<x:utf8_codepoint, "Gleam":utf8>>
}
"#,
);
}
#[test]
fn utf8_codepoint_typescript() {
assert_ts_def!(
r#"
pub fn go(x) {
<<x:utf8_codepoint, "Gleam":utf8>>
}
"#,
);
}
#[test]
fn bit_string() {
assert_js!(
r#"
pub fn go(x) {
<<x:bits>>
}
"#,
);
}
#[test]
fn bits() {
assert_js!(
r#"
pub fn go(x) {
<<x:bits>>
}
"#,
);
}
#[test]
fn bit_array_sliced() {
assert_js!(
r#"
pub fn go(x) {
<<<<0xAB>>:bits-4>>
}
"#,
);
}
#[test]
fn bit_array_dynamic_slice() {
assert_js!(
r#"
pub fn go(x) {
let i = 4
<<<<0xAB>>:bits-size(i)>>
}
"#,
);
}
#[test]
fn bit_string_typescript() {
assert_ts_def!(
r#"
pub fn go(x) {
<<x:bits>>
}
"#,
);
}
#[test]
fn bits_typescript() {
assert_ts_def!(
r#"
pub fn go(x) {
<<x:bits>>
}
"#,
);
}
#[test]
fn empty_match() {
assert_js!(
r#"
pub fn go(x) {
let assert <<>> = x
}
"#,
);
}
#[test]
fn case_empty_match() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<>> -> 1
_ -> 2
}
}
"#,
);
}
#[test]
fn match_bytes() {
assert_js!(
r#"
pub fn go(x) {
let assert <<1, y>> = x
}
"#,
);
}
#[test]
fn case_match_bytes() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<1, y>> -> y
_ -> 1
}
}
"#,
);
}
#[test]
fn match_sized() {
assert_js!(
r#"
pub fn go(x) {
let assert <<a:16, b:8>> = x
}
"#,
);
}
#[test]
fn case_match_sized() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<a:16, b:8>> -> a + b
_ -> 1
}
}
"#,
);
}
#[test]
fn match_sized_unaligned() {
assert_js!(
r#"
pub fn go(x) {
let assert <<a:17, b:7>> = x
}
"#,
);
}
#[test]
fn case_match_sized_unaligned() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<a:17, b:7>> -> b * 2
_ -> 1
}
}
"#,
);
}
#[test]
fn match_sized_constant_pattern() {
assert_js!(
r#"
pub fn go(x) {
let assert <<1234:16, 123:8>> = x
}
"#,
);
}
#[test]
fn case_match_sized_constant_pattern() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<1234:16, 123:8>> -> 1
_ -> 2
}
}
"#,
);
}
#[test]
fn match_unsigned() {
assert_js!(
r#"
pub fn go(x) {
let assert <<a:unsigned>> = x
}
"#,
);
}
#[test]
fn case_match_unsigned() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<a:unsigned>> -> a
_ -> 1
}
}
"#,
);
}
#[test]
fn match_unsigned_constant_pattern() {
assert_js!(
r#"
pub fn go(x) {
let assert <<-2:unsigned>> = x
}
"#,
);
}
#[test]
fn case_match_unsigned_constant_pattern() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<-2:unsigned>> -> 1
_ -> 2
}
}
"#,
);
}
#[test]
fn match_signed() {
assert_js!(
r#"
pub fn go(x) {
let assert <<a:signed>> = x
}
"#,
);
}
#[test]
fn case_match_signed() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<a:signed>> -> a
_ -> 1
}
}
"#,
);
}
#[test]
fn match_signed_constant_pattern() {
assert_js!(
r#"
pub fn go(x) {
let assert <<-1:signed>> = x
}
"#,
);
}
#[test]
fn case_match_signed_constant_pattern() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<-1:signed>> -> 1
_ -> 2
}
}
"#,
);
}
#[test]
fn match_sized_big_endian() {
assert_js!(
r#"
pub fn go(x) {
let assert <<a:16-big>> = x
}
"#,
);
}
#[test]
fn case_match_sized_big_endian() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<a:16-big>> -> a
_ -> 1
}
}
"#,
);
}
#[test]
fn match_sized_big_endian_constant_pattern() {
assert_js!(
r#"
pub fn go(x) {
let assert <<1234:16-big>> = x
}
"#,
);
}
#[test]
fn case_match_sized_big_endian_constant_pattern() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<1234:16-big>> -> 1
_ -> 2
}
}
"#,
);
}
#[test]
fn match_sized_little_endian() {
assert_js!(
r#"
pub fn go(x) {
let assert <<a:16-little>> = x
}
"#,
);
}
#[test]
fn case_match_sized_little_endian() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<a:16-little>> -> a
_ -> 1
}
}
"#,
);
}
#[test]
fn match_sized_little_endian_constant_pattern() {
assert_js!(
r#"
pub fn go(x) {
let assert <<1234:16-little>> = x
}
"#,
);
}
#[test]
fn case_match_sized_little_endian_constant_pattern() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<1234:16-little>> -> 1
_ -> 2
}
}
"#,
);
}
#[test]
fn match_sized_big_endian_unsigned() {
assert_js!(
r#"
pub fn go(x) {
let assert <<a:16-big-unsigned>> = x
}
"#,
);
}
#[test]
fn case_match_sized_big_endian_unsigned() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<a:16-big-unsigned>> -> a
_ -> 1
}
}
"#,
);
}
#[test]
fn match_sized_big_endian_unsigned_constant_pattern() {
assert_js!(
r#"
pub fn go(x) {
let assert <<1234:16-big-unsigned>> = x
}
"#,
);
}
#[test]
fn case_match_sized_big_endian_unsigned_constant_pattern() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<1234:16-big-unsigned>> -> 1
_ -> 2
}
}
"#,
);
}
#[test]
fn match_sized_big_endian_signed() {
assert_js!(
r#"
pub fn go(x) {
let assert <<a:16-big-signed>> = x
}
"#,
);
}
#[test]
fn case_match_sized_big_endian_signed() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<a:16-big-signed>> -> a
_ -> 1
}
}
"#,
);
}
#[test]
fn match_sized_big_endian_signed_constant_pattern() {
assert_js!(
r#"
pub fn go(x) {
let assert <<1234:16-big-signed>> = x
}
"#,
);
}
#[test]
fn case_match_sized_big_endian_signed_constant_pattern() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<1234:16-big-signed>> -> 1
_ -> 2
}
}
"#,
);
}
#[test]
fn match_sized_little_endian_unsigned() {
assert_js!(
r#"
pub fn go(x) {
let assert <<a:16-little-unsigned>> = x
}
"#,
);
}
#[test]
fn case_match_sized_little_endian_unsigned() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<a:16-little-unsigned>> -> a
_ -> 1
}
}
"#,
);
}
#[test]
fn match_sized_little_endian_unsigned_constant_pattern() {
assert_js!(
r#"
pub fn go(x) {
let assert <<1234:16-little-unsigned>> = x
}
"#,
);
}
#[test]
fn case_match_sized_little_endian_unsigned_constant_pattern() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<1234:16-little-unsigned>> -> 1
_ -> 2
}
}
"#,
);
}
#[test]
fn match_sized_little_endian_signed() {
assert_js!(
r#"
pub fn go(x) {
let assert <<a:16-little-signed>> = x
}
"#,
);
}
#[test]
fn case_match_sized_little_endian_signed() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<a:16-little-signed>> -> a
_ -> 1
}
}
"#,
);
}
#[test]
fn match_sized_little_endian_signed_constant_pattern() {
assert_js!(
r#"
pub fn go(x) {
let assert <<1234:16-little-signed>> = x
}
"#,
);
}
#[test]
fn case_match_sized_little_endian_signed_constant_pattern() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<1234:16-little-signed>> -> 1
_ -> 2
}
}
"#,
);
}
#[test]
fn match_dynamic_size() {
assert_js!(
r#"
pub fn go(x) {
let n = 16
let assert <<a:size(n)>> = x
}
"#
);
}
#[test]
fn case_match_dynamic_size() {
assert_js!(
r#"
pub fn go(x) {
let n = 16
case x {
<<a:size(n)>> -> a
_ -> 1
}
}
"#
);
}
#[test]
fn match_dynamic_size_with_other_segments() {
assert_js!(
r#"
pub fn go(x) {
let n = 16
let m = 32
let assert <<first:size(8), a:size(n), b:size(m), rest:bits>> = x
}
"#
);
}
#[test]
fn case_match_dynamic_size_with_other_segments() {
assert_js!(
r#"
pub fn go(x) {
let n = 16
let m = 32
case x {
<<first:size(8), a:size(n), b:size(m), rest:bits>> -> first + a + b
_ -> 1
}
}
"#
);
}
#[test]
fn match_dynamic_size_shadowed_variable() {
assert_js!(
r#"
pub fn go(x) {
let n = 16
let n = 5
let assert <<a:size(n)>> = x
}
"#
);
}
#[test]
fn case_match_dynamic_size_shadowed_variable() {
assert_js!(
r#"
pub fn go(x) {
let n = 16
let n = 5
case x {
<<a:size(n)>> -> a
_ -> 1
}
}
"#
);
}
#[test]
fn match_dynamic_size_literal_value() {
assert_js!(
r#"
pub fn go(x) {
let n = 8
let assert <<a:size(n), 0b010101:size(8)>> = x
}
"#
);
}
#[test]
fn case_match_dynamic_size_literal_value() {
assert_js!(
r#"
pub fn go(x) {
let n = 8
case x {
<<a:size(n), 0b010101:size(8)>> -> a
_ -> 1
}
}
"#
);
}
#[test]
fn match_dynamic_bits_size() {
assert_js!(
r#"
pub fn go(x) {
let n = 16
let assert <<a:bits-size(n)>> = x
}
"#
);
}
#[test]
fn case_match_dynamic_bits_size() {
assert_js!(
r#"
pub fn go(x) {
let n = 16
case x {
<<a:bits-size(n)>> -> a
_ -> x
}
}
"#
);
}
#[test]
fn match_dynamic_bytes_size() {
assert_js!(
r#"
pub fn go(x) {
let n = 3
let assert <<a:bytes-size(n)>> = x
}
"#
);
}
#[test]
fn case_match_dynamic_bytes_size() {
assert_js!(
r#"
pub fn go(x) {
let n = 3
case x {
<<a:bytes-size(n)>> -> a
_ -> x
}
}
"#
);
}
#[test]
fn discard_sized() {
assert_js!(
r#"
pub fn go(x) {
let assert <<_:16, _:8>> = x
let assert <<_:16-little-signed, _:8>> = x
}
"#,
);
}
#[test]
fn case_discard_sized() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<_:16, _:8>> -> 1
_ -> 2
}
case x {
<<_:16-little-signed, _:8>> -> 1
_ -> 2
}
}
"#,
);
}
#[test]
fn match_sized_value() {
assert_js!(
r#"
pub fn go(x) {
let assert <<i:16>> = x
}
"#,
);
}
#[test]
fn case_match_sized_value() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<i:16>> -> i
_ -> 1
}
}
"#,
);
}
#[test]
fn match_sized_value_constant_pattern() {
assert_js!(
r#"
pub fn go(x) {
let assert <<258:16>> = x
}
"#,
);
}
#[test]
fn case_match_sized_value_constant_pattern() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<258:16>> -> 1
_ -> 2
}
}
"#,
);
}
#[test]
fn match_float() {
assert_js!(
r#"
pub fn go(x) {
let assert <<a:float, b:int>> = x
}
"#,
);
}
#[test]
fn case_match_float() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<a:float, b:int>> -> #(a, b)
_ -> #(1.1, 2)
}
}
"#,
);
}
#[test]
fn match_float_big_endian() {
assert_js!(
r#"
pub fn go(x) {
let assert <<a:float-big, b:int>> = x
}
"#,
);
}
#[test]
fn case_match_float_big_endian() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<a:float-big, b:int>> -> #(a, b)
_ -> #(1.1, 1)
}
}
"#,
);
}
#[test]
fn match_float_little_endian() {
assert_js!(
r#"
pub fn go(x) {
let assert <<a:float-little, b:int>> = x
}
"#,
);
}
#[test]
fn case_match_float_little_endian() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<a:float-little, b:int>> -> #(a, b)
_ -> #(1.1, 2)
}
}
"#,
);
}
#[test]
fn match_float_sized() {
assert_js!(
r#"
pub fn go(x) {
let assert <<a:float-32, b:int>> = x
}
"#,
);
}
#[test]
fn case_match_float_sized() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<a:float-32, b:int>> -> #(a, b)
_ -> #(1.1, 2)
}
}
"#,
);
}
#[test]
fn match_float_sized_big_endian() {
assert_js!(
r#"
pub fn go(x) {
let assert <<a:float-32-big, b:int>> = x
}
"#,
);
}
#[test]
fn case_match_float_sized_big_endian() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<a:float-32-big, b:int>> -> #(a, b)
_ -> #(1.1, 2)
}
}
"#,
);
}
#[test]
fn match_float_sized_little_endian() {
assert_js!(
r#"
pub fn go(x) {
let assert <<a:float-32-little, b:int>> = x
}
"#,
);
}
#[test]
fn case_match_float_sized_little_endian() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<a:float-32-little, b:int>> -> #(a, b)
_ -> #(1.1, 2)
}
}
"#,
);
}
#[test]
fn match_literal_float() {
assert_js!(
r#"
pub fn go(x) {
let assert <<1.4, b:int>> = x
}
"#,
);
}
#[test]
fn case_match_literal_float() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<1.4, b:int>> -> 1
_ -> 2
}
}
"#,
);
}
#[test]
fn match_literal_unaligned_float() {
assert_js!(
r#"
pub fn go(x) {
let n = 1
let assert <<_:size(n), 1.1, _:bits>> = x
}
"#,
);
}
#[test]
fn case_match_literal_unaligned_float() {
assert_js!(
r#"
pub fn go(x) {
let n = 1
case x {
<<_:size(n), 1.1, _:int>> -> 1
_ -> 2
}
}
"#,
);
}
#[test]
fn match_literal_aligned_float() {
assert_js!(
r#"
pub fn go(x) {
let assert <<_, 1.1, _:bits>> = x
}
"#,
);
}
#[test]
fn case_match_literal_aligned_float() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<_, 1.1, _:int>> -> 1
_ -> 2
}
}
"#,
);
}
#[test]
fn match_float_16_bit() {
assert_js!(
r#"
pub fn go(x) {
let assert <<a:float-size(16)>> = x
}
"#
);
}
#[test]
fn case_match_float_16_bit() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<a:float-size(16)>> -> a
_ -> 1.1
}
}
"#
);
}
#[test]
fn match_rest() {
assert_js!(
r#"
pub fn go(x) {
let assert <<_, b:bytes>> = <<1,2,3>>
}
"#,
);
}
#[test]
fn case_match_rest() {
assert_js!(
r#"
pub fn go(x) {
case <<1, 2, 3>> {
<<_, b:bytes>> -> b
_ -> x
}
}
"#,
);
}
#[test]
fn match_bytes_with_size() {
assert_js!(
r#"
pub fn go(x) {
let assert <<f:bytes-2>> = <<1, 2>>
}
"#,
);
}
#[test]
fn case_match_bytes_with_size() {
assert_js!(
r#"
pub fn go(x) {
case <<1, 2>> {
<<f:bytes-2>> -> f
_ -> x
}
}
"#,
);
}
#[test]
fn match_bits_with_size() {
assert_js!(
r#"
pub fn go(x) {
let assert <<_:4, f:bits-2, _:1>> = <<0x77:7>>
}
"#,
);
}
#[test]
fn case_match_bits_with_size() {
assert_js!(
r#"
pub fn go(x) {
case <<0x77:7>> {
<<_:4, f:bits-2, _:1>> -> f
_ -> x
}
}
"#,
);
}
#[test]
fn match_rest_bytes() {
assert_js!(
r#"
pub fn go(x) {
let assert <<_, b:bytes>> = <<1,2,3>>
}
"#,
);
}
#[test]
fn case_match_rest_bytes() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<_, b:bytes>> -> b
_ -> x
}
}
"#,
);
}
#[test]
fn match_rest_bits() {
assert_js!(
r#"
pub fn go(x) {
let assert <<_, b:bits>> = <<1,2,3>>
}
"#,
);
}
#[test]
fn case_match_rest_bits() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<_, b:bits>> -> b
_ -> x
}
}
"#,
);
}
#[test]
fn match_rest_bits_unaligned() {
assert_js!(
r#"
pub fn go(x) {
let assert <<_:5, b:bits>> = <<1,2,3>>
}
"#,
);
}
#[test]
fn case_match_rest_bits_unaligned() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<_:5, b:bits>> -> b
_ -> x
}
}
"#,
);
}
#[test]
fn match_binary_size() {
assert_js!(
r#"
pub fn go(x) {
let assert <<_, a:2-bytes>> = x
let assert <<_, b:bytes-size(2)>> = x
}
"#,
);
}
#[test]
fn case_match_binary_size() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<_, a:2-bytes>> -> a
_ -> x
}
case x {
<<_, b:bytes-size(2)>> -> b
_ -> x
}
}
"#,
);
}
#[test]
fn unaligned_int_expression_requires_v1_9() {
assert_js_warnings_with_gleam_version!(
Range::higher_than(Version::new(1, 8, 0)),
"
pub fn main() {
<<0:1>>
}
",
);
}
#[test]
fn bits_expression_does_not_require_v1_9() {
assert_js_no_warnings_with_gleam_version!(
Range::higher_than(Version::new(1, 8, 0)),
"
pub fn main() {
<<<<0>>:bits>>
}
",
);
}
#[test]
fn sized_bits_expression_requires_v1_9() {
assert_js_warnings_with_gleam_version!(
Range::higher_than(Version::new(1, 8, 0)),
"
pub fn main() {
<<<<0>>:bits-5>>
}
",
);
}
#[test]
fn unaligned_int_pattern_requires_v1_9() {
assert_js_warnings_with_gleam_version!(
Range::higher_than(Version::new(1, 8, 0)),
"
pub fn main() {
let assert <<_:3>> = <<0>>
}
",
);
}
#[test]
fn bits_pattern_requires_v1_9() {
assert_js_warnings_with_gleam_version!(
Range::higher_than(Version::new(1, 8, 0)),
"
pub fn main() {
let assert <<_:bits>> = <<0>>
}
",
);
}
#[test]
fn bytes_pattern_with_odd_size_does_not_require_v1_9() {
assert_js_no_warnings_with_gleam_version!(
Range::higher_than(Version::new(1, 8, 0)),
"
pub fn main() {
let assert <<_:bytes-3>> = <<0, 1, 2>>
}
",
);
}
#[test]
fn sized_bits_expression_with_javascript_external_does_not_require_v1_9() {
assert_js_no_warnings_with_gleam_version!(
Range::higher_than(Version::new(1, 8, 0)),
r#"
@external(javascript, "test.mjs", "go")
pub fn go() -> BitArray {
<<0:size(5)>>
}
"#,
);
}
#[test]
fn bits_pattern_with_javascript_external_does_not_require_v1_9() {
assert_js_no_warnings_with_gleam_version!(
Range::higher_than(Version::new(1, 8, 0)),
r#"
@external(javascript, "test.mjs", "go")
pub fn go() -> BitArray {
let <<a:bits>> = <<>>
a
}
"#,
);
}
#[test]
fn as_module_const() {
assert_js!(
r#"
pub const data = <<
0x1,
2,
2:size(16),
0x4:size(32),
-1:32,
"Gleam":utf8,
4.2:float,
4.2:32-float,
<<0xFA>>:bits-6,
-1:64,
<<
<<1, 2, 3>>:bits,
"Gleam":utf8,
1024
>>:bits
>>
"#
)
}
#[test]
fn bit_array_literal_string_constant_is_treated_as_utf8() {
assert_js!(r#"pub const a = <<"hello", " ", "world">>"#);
}
#[test]
fn bit_array_literal_string_is_treated_as_utf8() {
assert_js!(
r#"
pub fn main() {
<<"hello", " ", "world">>
}"#
);
}
#[test]
fn bit_array_literal_string_pattern_is_treated_as_utf8() {
assert_js!(
r#"
pub fn main() {
case <<>> {
<<"a", "b", _:bytes>> -> 1
_ -> 2
}
}"#
);
}
#[test]
fn with_unit() {
assert_js!(
r#"
pub fn main() {
<<1:size(2)-unit(2), 2:size(3)-unit(4)>>
}
"#,
);
}
#[test]
fn dynamic_size_with_unit() {
assert_js!(
r#"
pub fn main() {
let size = 3
<<1:size(size)-unit(2)>>
}
"#,
);
}
#[test]
fn pattern_with_unit() {
assert_js!(
r#"
pub fn go(x) {
let assert <<1:size(2)-unit(2), 2:size(3)-unit(4)>> = x
}
"#,
);
}
#[test]
fn case_pattern_with_unit() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<1:size(2)-unit(2), 2:size(3)-unit(4)>> -> 1
_ -> 2
}
}
"#,
);
}
#[test]
fn dynamic_size_pattern_with_unit() {
assert_js!(
r#"
pub fn go(x) {
let size = 3
let assert <<1:size(size)-unit(2)>> = x
}
"#,
);
}
#[test]
fn case_dynamic_size_pattern_with_unit() {
assert_js!(
r#"
pub fn go(x) {
let size = 3
case x {
<<1:size(size)-unit(2)>> -> 1
_ -> 2
}
}
"#,
);
}
#[test]
fn case_dynamic_size_float_pattern_with_unit() {
assert_js!(
r#"
pub fn go(x) {
let size = 3
case x {
<<1.3:size(size)-unit(2)>> -> 1
_ -> 2
}
}
"#,
);
}
#[test]
fn case_with_remaining_bytes_after_constant_size() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<_, _, _:bytes>> -> 1
_ -> 2
}
}
"#,
);
}
#[test]
fn case_with_remaining_bytes_after_variable_size() {
assert_js!(
r#"
pub fn go(x) {
let n = 1
case x {
<<_:size(n), _, _:bytes>> -> 1
_ -> 2
}
}
"#,
);
}
#[test]
fn case_with_remaining_bytes_after_variable_size_2() {
assert_js!(
r#"
pub fn go(x) {
let n = 1
case x {
<<m:size(n), _:size(m), _:bytes>> -> 1
_ -> 2
}
}
"#,
);
}
#[test]
fn case_is_byte_aligned() {
assert_js!(
r#"
pub fn is_byte_aligned(x) {
case x {
<<_:bytes>> -> True
_ -> False
}
}
"#,
);
}
#[test]
fn alternative_patterns_with_variable_size() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<_, n, rest:size(n)>> |
<<n, _, rest:size(n)>> -> True
_ -> False
}
}
"#,
);
}
#[test]
fn variable_sized_segment() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<n, rest:size(n)>> -> 1
_ -> 2
}
}
"#
)
}
#[test]
fn segments_shadowing_each_other() {
assert_js!(
r#"
pub fn go(x) {
let n = 1
case x {
<<n, rest:size(n)>> -> 1
_ -> 2
}
}
"#
)
}
#[test]
fn negative_size_pattern() {
assert_js!(
r#"
pub fn go(x) {
let n = -10
case x {
<<int:size(n)>> -> int
_ -> 2
}
}
"#
)
}
#[test]
fn negative_size_pattern_2() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<n:signed, int:size(n)>> -> int
_ -> 2
}
}
"#
)
}
// https://github.com/gleam-lang/gleam/issues/3375
#[test]
fn bit_array_assignment_int() {
assert_js!(
"
pub fn main() {
let assert <<1 as a>> = <<1>>
a
}
"
);
}
#[test]
fn case_bit_array_assignment_int() {
assert_js!(
"
pub fn go(x) {
case x {
<<1 as n>>
| <<2 as n, _:bytes>> -> n
_ -> 1
}
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/3375
#[test]
fn bit_array_assignment_float() {
assert_js!(
"
pub fn main() {
let assert <<3.14 as pi:float>> = <<3.14>>
pi
}
"
);
}
#[test]
fn case_bit_array_assignment_float() {
assert_js!(
"
pub fn go(x) {
case x {
<<3.14 as pi:float>>
| <<1.1 as pi:float, _:bytes>> -> pi
_ -> 1.1
}
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/3375
#[test]
fn bit_array_assignment_string() {
assert_js!(
r#"
pub fn main() {
let assert <<"Hello, world!" as message:utf8>> = <<"Hello, world!">>
message
}
"#
);
}
#[test]
fn case_bit_array_assignment_string() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<"Hello" as message>>
| <<"Jak" as message, _:bytes>> -> message
_ -> "wibble"
}
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/3375
#[test]
fn bit_array_assignment_discard() {
assert_js!(
r#"
pub fn main() {
let assert <<_ as number>> = <<10>>
number
}
"#
);
}
#[test]
fn case_bit_array_assignment_discard() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<_ as n>>
| <<_ as n, _:bytes>> -> n
_ -> 1
}
}
"#
);
}
#[test]
fn utf16() {
assert_js!(
r#"
pub fn main() {
<<"Hello, world!":utf16>>
}
"#
);
}
#[test]
fn utf16_codepoint() {
assert_js!(
r#"
fn codepoint() -> UtfCodepoint { todo }
pub fn main() {
let my_codepoint = codepoint()
<<my_codepoint:utf16_codepoint>>
}
"#
);
}
#[test]
fn utf32() {
assert_js!(
r#"
pub fn main() {
<<"Hello, world!":utf32>>
}
"#
);
}
#[test]
fn utf32_codepoint() {
assert_js!(
r#"
fn codepoint() -> UtfCodepoint { todo }
pub fn main() {
let my_codepoint = codepoint()
<<my_codepoint:utf32_codepoint>>
}
"#
);
}
#[test]
fn const_utf16() {
assert_js!(
r#"
pub const message = <<"Hello, world!":utf16>>
"#
);
}
#[test]
fn const_utf32() {
assert_js!(
r#"
pub const message = <<"Hello, world!":utf32>>
"#
);
}
#[test]
fn pattern_match_utf16() {
assert_js!(
r#"
pub fn go(x) {
let assert <<"Hello":utf16, _rest:bytes>> = x
}
"#
);
}
#[test]
fn pattern_match_utf32() {
assert_js!(
r#"
pub fn go(x) {
let assert <<"Hello":utf32, _rest:bytes>> = x
}
"#
);
}
#[test]
fn utf16_little_endian() {
assert_js!(
r#"
pub fn main() {
<<"Hello, world!":utf16-little>>
}
"#
);
}
#[test]
fn utf32_little_endian() {
assert_js!(
r#"
pub fn main() {
<<"Hello, world!":utf32-little>>
}
"#
);
}
#[test]
fn pattern_match_utf16_little_endian() {
assert_js!(
r#"
pub fn go(x) {
let assert <<"Hello":utf16-little, _rest:bytes>> = x
}
"#
);
}
#[test]
fn pattern_match_utf32_little_endian() {
assert_js!(
r#"
pub fn go(x) {
let assert <<"Hello":utf32-little, _rest:bytes>> = x
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/4630
#[test]
fn tuple_bit_array() {
assert_js!(
"
pub fn go(x) {
let assert #(<<>>) = x
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/4630
#[test]
fn tuple_bit_array_case() {
assert_js!(
"
pub fn go(x) {
case x {
#(<<>>) -> 1
_ -> 2
}
}
"
);
}
#[test]
fn tuple_multiple_bit_arrays() {
assert_js!(
"
pub fn go(x) {
let assert #(<<>>, <<1>>, <<2, 3>>) = x
}
"
);
}
#[test]
fn tuple_multiple_bit_arrays_case() {
assert_js!(
"
pub fn go(x) {
case x {
#(<<>>, <<1>>, <<2, 3>>) -> True
_ -> False
}
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/4637
#[test]
fn pattern_matching_on_32_float_plus_infinity_still_reachable() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<_:32-float>> -> "Float"
<<0x7f800000:32>> -> "+Infinity"
_ -> "Other"
}
}
"#
);
}
#[test]
fn pattern_matching_on_32_float_plus_infinity_still_reachable_2() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<_:32-float>> -> "Float"
<<0x7f80:16, 0x0000:16>> -> "+Infinity"
_ -> "Other"
}
}
"#
);
}
#[test]
fn pattern_matching_on_32_float_minus_infinity_still_reachable() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<_:32-float>> -> "Float"
<<0xff800000:32>> -> "-Infinity"
_ -> "Other"
}
}
"#
);
}
#[test]
fn pattern_matching_on_32_float_minus_infinity_still_reachable_2() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<_:32-float>> -> "Float"
<<0xff80:16, 0x0000:16>> -> "-Infinity"
_ -> "Other"
}
}
"#
);
}
#[test]
fn pattern_matching_on_32_float_nan_still_reachable() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<_:32-float>> -> "Float"
<<0x7fc00000:32>> -> "NaN"
_ -> "Other"
}
}
"#
);
}
#[test]
fn pattern_matching_on_32_float_nan_still_reachable_2() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<_:32-float>> -> "Float"
<<0x7fc0:16, 0x0000:16>> -> "NaN"
_ -> "Other"
}
}
"#
);
}
#[test]
fn pattern_matching_on_64_float_plus_infinity_still_reachable() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<_:64-float>> -> "Float"
<<0x7ff0000000000000:64>> -> "+Infinity"
_ -> "Other"
}
}
"#
);
}
#[test]
fn pattern_matching_on_64_float_plus_infinity_still_reachable_2() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<_:64-float>> -> "Float"
<<0x7ff00000:32, 0x00000000:32>> -> "+Infinity"
_ -> "Other"
}
}
"#
);
}
#[test]
fn pattern_matching_on_64_float_minus_infinity_still_reachable() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<_:64-float>> -> "Float"
<<0xfff0000000000000:64>> -> "-Infinity"
_ -> "Other"
}
}
"#
);
}
#[test]
fn pattern_matching_on_64_float_minus_infinity_still_reachable_2() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<_:64-float>> -> "Float"
<<0xfff00000:32, 0x00000000:32>> -> "-Infinity"
_ -> "Other"
}
}
"#
);
}
#[test]
fn pattern_matching_on_64_float_nan_still_reachable() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<_:64-float>> -> "Float"
<<0x7ff8000000000000:64>> -> "NaN"
_ -> "Other"
}
}
"#
);
}
#[test]
fn pattern_matching_on_64_float_nan_still_reachable_2() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<_:64-float>> -> "Float"
<<0x7ff80000:32, 0x00000000:32>> -> "NaN"
_ -> "Other"
}
}
"#
);
}
#[test]
fn pattern_matching_on_64_float_int_is_still_reachable() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<_:64-float>> -> "Float"
<<_:64-int>> -> "Int"
_ -> "Other"
}
}
"#
);
}
#[test]
fn pattern_matching_on_64_float_float_is_unreachable() {
assert_js!(
r#"
pub fn go(x) {
case x {
<<_:64-float>> -> "Float"
<<_:64-float>> -> "unreachable"
_ -> "Other"
}
}
"#
);
}
#[test]
fn unit_with_bits_option() {
assert_js!(
"
pub fn go(x) {
<<x:bits-size(4)-unit(8)>>
}
"
);
}
#[test]
fn unit_with_bits_option_constant() {
assert_js!(
"
pub const bits = <<1, 2, 3>>
pub const more_bits = <<bits:bits-size(3)-unit(8)>>
"
);
}
#[test]
fn operator_in_size_for_bit_array_segment() {
assert_js!(
"
pub fn go(x) {
<<x:bits-size(4 + 1)>>
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/4712
#[test]
fn multiple_variable_size_segments() {
assert_js!(
"
pub fn main() {
let assert <<a, b:size(a), c:size(b)>> = <<1, 2, 3, 4>>
a + b + c
}
"
);
}
#[test]
fn utf16_codepoint_little_endian() {
assert_js!(
"
pub fn go(codepoint) {
<<codepoint:utf16_codepoint-little>>
}
"
);
}
#[test]
fn utf32_codepoint_little_endian() {
assert_js!(
"
pub fn go(codepoint) {
<<codepoint:utf32_codepoint-little>>
}
"
);
}
#[test]
fn operator_in_pattern_size() {
assert_js!(
"
pub fn main() {
let assert <<len, payload:size(len * 8)>> = <<>>
}
"
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | true |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/javascript/tests/inlining.rs | compiler-core/src/javascript/tests/inlining.rs | use crate::assert_js;
const BOOL_MODULE: &str = "
pub fn guard(
when condition: Bool,
return value: a,
otherwise callback: fn() -> a,
) -> a {
case condition {
True -> value
False -> callback()
}
}
pub fn lazy_guard(
when condition: Bool,
return consequence: fn() -> a,
otherwise alternative: fn() -> a,
) -> a {
case condition {
True -> consequence()
False -> alternative()
}
}
";
const RESULT_MODULE: &str = "
pub fn try(result: Result(a, e), apply f: fn(a) -> Result(b, e)) -> Result(b, e) {
case result {
Ok(value) -> f(value)
Error(error) -> Error(error)
}
}
pub fn map(over result: Result(a, e), with f: fn(a) -> b) -> Result(b, e) {
case result {
Ok(value) -> Ok(f(value))
Error(error) -> Error(error)
}
}
";
#[test]
fn inline_higher_order_function() {
assert_js!(
("gleam_stdlib", "gleam/result", RESULT_MODULE),
"
import gleam/result
pub fn main() {
result.map(over: Ok(10), with: double)
}
fn double(x) { x + x }
"
);
}
#[test]
fn inline_higher_order_function_with_capture() {
assert_js!(
("gleam_stdlib", "gleam/result", RESULT_MODULE),
"
import gleam/result
pub fn main() {
result.try(Ok(10), divide(_, 2))
}
fn divide(a: Int, b: Int) -> Result(Int, Nil) {
case a % b {
0 -> Ok(a / b)
_ -> Error(Nil)
}
}
"
);
}
#[test]
fn inline_higher_order_function_anonymous() {
assert_js!(
("gleam_stdlib", "gleam/result", RESULT_MODULE),
"
import gleam/result
pub fn main() {
result.try(Ok(10), fn(value) {
Ok({ value + 2 } * 4)
})
}
"
);
}
#[test]
fn inline_function_which_calls_other_function() {
// This function calls `result.try`, meaning this must be inlined twice to
// achieve the desired result.
assert_js!(
("gleam_stdlib", "gleam/result", RESULT_MODULE),
(
"gleam_stdlib",
"testing",
"
import gleam/result.{try}
pub fn always_inline(result, f) -> Result(b, e) {
try(result, f)
}
"
),
"
import testing
pub fn main() {
testing.always_inline(Ok(10), Error)
}
"
);
}
#[test]
fn inline_function_with_use() {
assert_js!(
("gleam_stdlib", "gleam/bool", BOOL_MODULE),
"
import gleam/bool
pub fn divide(a, b) {
use <- bool.guard(when: b == 0, return: 0)
a / b
}
"
);
}
#[test]
fn inline_function_with_use_and_anonymous() {
assert_js!(
("gleam_stdlib", "gleam/bool", BOOL_MODULE),
r#"
import gleam/bool
pub fn divide(a, b) {
use <- bool.lazy_guard(b == 0, fn() { panic as "Cannot divide by 0" })
a / b
}
"#
);
}
#[test]
fn inline_function_with_use_becomes_tail_recursive() {
assert_js!(
("gleam_stdlib", "gleam/bool", BOOL_MODULE),
"
import gleam/bool
pub fn count(from: Int, to: Int) -> Int {
use <- bool.guard(when: from >= to, return: from)
echo from
count(from + 1, to)
}
"
);
}
#[test]
fn do_not_inline_parameters_used_more_than_once() {
// Since the `something` parameter is used more than once in the body of the
// function, it should not be inlined, and should be assigned once at the
// beginning of the function.
assert_js!(
(
"gleam_stdlib",
"testing",
"
pub fn always_inline(something) {
case something {
True -> something
False -> False
}
}
"
),
"
import testing
pub fn main() {
testing.always_inline(True)
}
"
);
}
#[test]
fn do_not_inline_parameters_that_have_side_effects() {
assert_js!(
("gleam_stdlib", "gleam/result", RESULT_MODULE),
r#"
import gleam/result
pub fn main() {
result.map(Ok(10), do_side_effects())
}
fn do_side_effects() {
let function = fn(x) { x + 1 }
panic as "Side effects"
function
}
"#
);
}
#[test]
fn inline_anonymous_function_call() {
assert_js!(
"
pub fn main() {
fn(a, b) { #(a, b) }(42, False)
}
"
);
}
#[test]
fn inline_anonymous_function_in_pipe() {
assert_js!(
"
pub fn main() {
1 |> fn(x) { x + 1 } |> fn(y) { y * y }
}
"
);
}
#[test]
fn inline_function_capture_in_pipe() {
// The function capture is desugared to an anonymous function, so it should
// be turned into a direct call to `add`
assert_js!(
"
pub fn main() {
1 |> add(4, _)
}
fn add(a, b) { a + b }
"
);
}
#[test]
fn inlining_works_through_blocks() {
assert_js!(
"
pub fn main() {
{ fn(x) { Ok(x + 1) } }(41)
}
"
);
}
#[test]
fn blocks_get_preserved_when_needed() {
assert_js!(
"
pub fn main() {
{ 4 |> make_adder }(6)
}
fn make_adder(a) {
fn(b) { a + b }
}
"
);
}
#[test]
fn blocks_get_preserved_when_needed2() {
assert_js!(
"
pub fn main() {
fn(x) { 1 + x }(2) * 3
}
"
);
}
#[test]
fn parameters_from_nested_functions_are_correctly_inlined() {
assert_js!(
("gleam_stdlib", "gleam/result", RESULT_MODULE),
"
import gleam/result
pub fn halve_all(a, b, c) {
use x <- result.try(divide(a, 2))
use y <- result.try(divide(b, 2))
use z <- result.map(divide(c, 2))
#(x, y, z)
}
fn divide(a, b) {
case a % b {
0 -> Ok(a / b)
_ -> Error(Nil)
}
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/4852
#[test]
fn inlining_works_properly_with_record_updates() {
assert_js!(
("gleam_stdlib", "gleam/result", RESULT_MODULE),
"
import gleam/result
pub type Wibble {
Wibble(a: Int, b: Int)
}
pub fn main() {
let w = Wibble(1, 2)
use b <- result.map(Ok(3))
Wibble(..w, b:)
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/4877
#[test]
fn inline_shadowed_variable() {
assert_js!(
"
pub fn main() {
let a = 10
let b = 20
fn(x) {
let a = 7
x + a
}(a + b)
a
}
"
);
}
#[test]
fn inline_variable_shadowing_parameter() {
assert_js!(
"
pub fn sum(a, b) {
fn(x) {
let a = 7
x + a
}(a + b)
a
}
"
);
}
#[test]
fn inline_shadowed_variable_nested() {
assert_js!(
"
pub fn sum(a, b) {
fn(x) {
let a = 7
fn(y) {
let a = 10
y - a
}(x + a)
a
}(a + b)
a
}
"
);
}
#[test]
fn inline_variable_shadowed_in_case_pattern() {
assert_js!(
"
pub fn sum() {
let a = 10
let b = 20
fn(x) {
case 7, 8 {
a, b -> a + b + x
}
}(a + b)
a + b
}
"
);
}
#[test]
fn inline_variable_shadowing_case_pattern() {
assert_js!(
"
pub fn sum() {
case 1, 2 {
a, b -> fn(x) {
let a = 7
x + a
}(a + b)
}
}
"
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests.rs | compiler-core/src/erlang/tests.rs | use std::time::SystemTime;
use camino::Utf8PathBuf;
use crate::analyse::TargetSupport;
use crate::config::PackageConfig;
use crate::type_::PRELUDE_MODULE_NAME;
use crate::warning::WarningEmitter;
use crate::{build, inline};
use crate::{
build::{Origin, Target},
erlang::module,
line_numbers::LineNumbers,
uid::UniqueIdGenerator,
warning::TypeWarningEmitter,
};
use camino::Utf8Path;
mod assert;
mod bit_arrays;
mod case;
mod conditional_compilation;
mod consts;
mod custom_types;
mod documentation;
mod echo;
mod external_fn;
mod functions;
mod guards;
mod inlining;
mod let_assert;
mod numbers;
mod panic;
mod patterns;
mod pipes;
mod records;
mod reserved;
mod strings;
mod todo;
mod type_params;
mod use_;
mod variables;
pub fn compile_test_project(
src: &str,
src_path: &str,
dependencies: Vec<(&str, &str, &str)>,
) -> String {
let mut modules = im::HashMap::new();
let ids = UniqueIdGenerator::new();
// DUPE: preludeinsertion
// TODO: Currently we do this here and also in the tests. It would be better
// to have one place where we create all this required state for use in each
// place.
let _ = modules.insert(
PRELUDE_MODULE_NAME.into(),
crate::type_::build_prelude(&ids),
);
let mut direct_dependencies = std::collections::HashMap::from_iter(vec![]);
for (dep_package, dep_name, dep_src) in dependencies {
let mut dep_config = PackageConfig::default();
dep_config.name = dep_package.into();
let parsed = crate::parse::parse_module(
Utf8PathBuf::from("test/path"),
dep_src,
&WarningEmitter::null(),
)
.expect("dep syntax error");
let mut ast = parsed.module;
ast.name = dep_name.into();
let line_numbers = LineNumbers::new(dep_src);
let dep = crate::analyse::ModuleAnalyzerConstructor::<()> {
target: Target::Erlang,
ids: &ids,
origin: Origin::Src,
importable_modules: &modules,
warnings: &TypeWarningEmitter::null(),
direct_dependencies: &std::collections::HashMap::new(),
dev_dependencies: &std::collections::HashSet::new(),
target_support: TargetSupport::NotEnforced,
package_config: &dep_config,
}
.infer_module(ast, line_numbers, "".into())
.expect("should successfully infer dep Erlang");
let _ = modules.insert(dep_name.into(), dep.type_info);
let _ = direct_dependencies.insert(dep_package.into(), ());
}
let path = Utf8PathBuf::from(src_path);
let parsed = crate::parse::parse_module(path.clone(), src, &WarningEmitter::null())
.expect("syntax error");
let mut config = PackageConfig::default();
config.name = "thepackage".into();
let mut ast = parsed.module;
ast.name = "my/mod".into();
let line_numbers = LineNumbers::new(src);
let ast = crate::analyse::ModuleAnalyzerConstructor::<()> {
target: Target::Erlang,
ids: &ids,
origin: Origin::Src,
importable_modules: &modules,
warnings: &TypeWarningEmitter::null(),
direct_dependencies: &direct_dependencies,
dev_dependencies: &std::collections::HashSet::new(),
target_support: TargetSupport::NotEnforced,
package_config: &config,
}
.infer_module(ast, line_numbers, path.clone())
.expect("should successfully infer root Erlang");
let ast = inline::module(ast, &modules);
// After building everything we still need to attach the module comments, to
// do that we're reusing the `attach_doc_and_module_comments` that's used
// for the real thing. We just have to make a placeholder module wrapping
// the parsed ast and call the function!
let mut built_module = build::Module {
name: "my/mod".into(),
code: src.into(),
mtime: SystemTime::UNIX_EPOCH,
input_path: path,
origin: Origin::Src,
ast,
extra: parsed.extra,
dependencies: vec![],
};
let root = Utf8Path::new("/root");
built_module.attach_doc_and_module_comments();
let line_numbers = LineNumbers::new(src);
module(&built_module.ast, &line_numbers, root)
.unwrap()
.replace(
std::include_str!("../../templates/echo.erl"),
"% ...omitted code from `templates/echo.erl`...",
)
}
#[macro_export]
macro_rules! assert_erl {
($(($dep_package:expr, $dep_name:expr, $dep_src:expr)),+, $src:literal $(,)?) => {{
let compiled = $crate::erlang::tests::compile_test_project(
$src,
"/root/project/test/my/mod.gleam",
vec![$(($dep_package, $dep_name, $dep_src)),*],
);
let output = format!(
"----- SOURCE CODE\n{}\n\n----- COMPILED ERLANG\n{}",
$src, compiled
);
insta::assert_snapshot!(insta::internals::AutoName, output, $src);
}};
($src:expr $(,)?) => {{
let compiled = $crate::erlang::tests::compile_test_project(
$src,
"/root/project/test/my/mod.gleam",
Vec::new(),
);
let output = format!(
"----- SOURCE CODE\n{}\n\n----- COMPILED ERLANG\n{}",
$src, compiled,
);
insta::assert_snapshot!(insta::internals::AutoName, output, $src);
}};
}
#[test]
fn integration_test() {
assert_erl!(
r#"pub fn go() {
let x = #(100000000000000000, #(2000000000, 3000000000000, 40000000000), 50000, 6000000000)
x
}"#
);
}
#[test]
fn integration_test0_1() {
assert_erl!(
r#"pub fn go() {
let y = 1
let y = 2
y
}"#
);
}
#[test]
fn integration_test0_2() {
// hex, octal, and binary literals
assert_erl!(
r#"pub fn go() {
let fifteen = 0xF
let nine = 0o11
let ten = 0b1010
fifteen
}"#
);
}
#[test]
fn integration_test0_3() {
assert_erl!(
r#"pub fn go() {
let y = 1
let y = 2
y
}"#
);
}
#[test]
fn integration_test1() {
assert_erl!(r#"pub fn t() { True }"#);
}
#[test]
fn integration_test1_1() {
assert_erl!(
r#"pub type Money { Pound(Int) }
pub fn pound(x) { Pound(x) }"#
);
}
#[test]
fn integration_test1_2() {
assert_erl!(r#"pub fn loop() { loop() }"#);
}
#[test]
fn integration_test1_4() {
assert_erl!(
r#"fn inc(x) { x + 1 }
pub fn go() { 1 |> inc |> inc |> inc }"#
);
}
#[test]
fn integration_test1_5() {
assert_erl!(
r#"fn add(x, y) { x + y }
pub fn go() { 1 |> add(_, 1) |> add(2, _) |> add(_, 3) }"#
);
}
#[test]
fn integration_test1_6() {
assert_erl!(
r#"pub fn and(x, y) { x && y }
pub fn or(x, y) { x || y }
pub fn remainder(x, y) { x % y }
pub fn fdiv(x, y) { x /. y }
"#
);
}
#[test]
fn integration_test2() {
assert_erl!(
r#"pub fn second(list) { case list { [x, y] -> y z -> 1 } }
pub fn tail(list) { case list { [x, ..xs] -> xs z -> list } }
"#
);
}
#[test]
fn integration_test5() {
assert_erl!(
"pub fn tail(list) {
case list {
[x, ..] -> x
_ -> 0
}
}"
);
}
#[test]
fn integration_test6() {
assert_erl!(r#"pub fn x() { let x = 1 let x = x + 1 x }"#);
}
#[test]
fn integration_test8() {
// Translation of Float-specific BinOp into variable-type Erlang term comparison.
assert_erl!(r#"pub fn x() { 1. <. 2.3 }"#);
}
#[test]
fn integration_test9() {
// Custom type creation
assert_erl!(
r#"pub type Pair(x, y) { Pair(x: x, y: y) } pub fn x() { Pair(1, 2) Pair(3., 4.) }"#
);
}
#[test]
fn integration_test10() {
assert_erl!(
r#"pub type Null { Null }
pub fn x() { Null }"#
);
}
#[test]
fn integration_test3() {
assert_erl!(
r#"pub type Point { Point(x: Int, y: Int) }
pub fn y() { fn() { Point }()(4, 6) }"#
);
}
#[test]
fn integration_test11() {
assert_erl!(
r#"pub type Point { Point(x: Int, y: Int) }
pub fn x() { Point(x: 4, y: 6) Point(y: 1, x: 9) }"#
);
}
#[test]
fn integration_test12() {
assert_erl!(
r#"pub type Point { Point(x: Int, y: Int) }
pub fn x(y) { let Point(a, b) = y a }"#
);
}
//https://github.com/gleam-lang/gleam/issues/1106
#[test]
fn integration_test13() {
assert_erl!(
r#"pub type State{ Start(Int) End(Int) }
pub fn build(constructor : fn(Int) -> a) -> a { constructor(1) }
pub fn main() { build(End) }"#
);
}
#[test]
fn integration_test16() {
assert_erl!(
r#"fn go(x xx, y yy) { xx }
pub fn x() { go(x: 1, y: 2) go(y: 3, x: 4) }"#
);
}
#[test]
fn integration_test17() {
// https://github.com/gleam-lang/gleam/issues/289
assert_erl!(
r#"
pub type User { User(id: Int, name: String, age: Int) }
pub fn create_user(user_id) { User(age: 22, id: user_id, name: "") }
"#
);
}
#[test]
fn integration_test18() {
assert_erl!(r#"pub fn run() { case 1, 2 { a, b -> a } }"#);
}
#[test]
fn integration_test19() {
assert_erl!(
r#"pub type X { X(x: Int, y: Float) }
pub fn x() { X(x: 1, y: 2.) X(y: 3., x: 4) }"#
);
}
#[test]
fn integration_test20() {
assert_erl!(
r#"
pub fn go(a) {
let a = a + 1
a
}
"#
);
}
#[test]
fn integration_test21() {
assert_erl!(
r#"
pub fn go(a) {
let a = 1
a
}
"#
);
}
#[test]
fn integration_test22() {
// https://github.com/gleam-lang/gleam/issues/358
assert_erl!(
r#"
pub fn factory(f, i) {
f(i)
}
pub type Box {
Box(i: Int)
}
pub fn main() {
factory(Box, 0)
}
"#
);
}
#[test]
fn integration_test23() {
// https://github.com/gleam-lang/gleam/issues/384
assert_erl!(
r#"
pub fn main(args) {
case args {
_ -> {
let a = 1
a
}
}
let a = 2
a
}
"#
);
}
#[test]
fn binop_parens() {
// Parentheses are added for binop subexpressions
assert_erl!(
r#"
pub fn main() {
let a = 2 * {3 + 1} / 2
let b = 5 + 3 / 3 * 2 - 6 * 4
b
}
"#
);
}
#[test]
fn field_access_function_call() {
// Parentheses are added when calling functions returned by record access
assert_erl!(
r#"
pub type FnBox {
FnBox(f: fn(Int) -> Int)
}
pub fn main() {
let b = FnBox(f: fn(x) { x })
b.f(5)
}
"#
);
}
#[test]
fn field_access_function_call1() {
// Parentheses are added when calling functions returned by tuple access
assert_erl!(
r#"
pub fn main() {
let t = #(fn(x) { x })
t.0(5)
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/777
#[test]
fn block_assignment() {
assert_erl!(
r#"
pub fn main() {
let x = {
1
2
}
x
}
"#
);
}
#[test]
fn recursive_type() {
// TODO: we should be able to generalise `id` and we should be
// able to handle recursive types. Either of these type features
// would make this module type check OK.
assert_erl!(
r#"
fn id(x) {
x
}
pub fn main() {
id(id)
}
"#
);
}
#[test]
fn tuple_access_in_guard() {
assert_erl!(
r#"
pub fn main() {
let key = 10
let x = [#(10, 2), #(1, 2)]
case x {
[first, ..rest] if first.0 == key -> "ok"
_ -> "ko"
}
}
"#
);
}
#[test]
fn variable_name_underscores_preserved() {
assert_erl!(
"pub fn a(name_: String) -> String {
let name__ = name_
let name = name__
let one_1 = 1
let one1 = one_1
name
}"
);
}
#[test]
fn allowed_string_escapes() {
assert_erl!(r#"pub fn a() { "\n" "\r" "\t" "\\" "\"" "\\^" }"#);
}
// https://github.com/gleam-lang/gleam/issues/1006
#[test]
fn keyword_constructors() {
assert_erl!("pub type X { Div }");
}
// https://github.com/gleam-lang/gleam/issues/1006
#[test]
fn keyword_constructors1() {
assert_erl!("pub type X { Fun(Int) }");
}
#[test]
fn discard_in_assert() {
assert_erl!(
"pub fn x(y) {
let assert Ok(_) = y
1
}"
);
}
// https://github.com/gleam-lang/gleam/issues/1424
#[test]
fn operator_pipe_right_hand_side() {
assert_erl!(
"fn id(x) {
x
}
pub fn bool_expr(x, y) {
y || x |> id
}"
);
}
#[test]
fn negation() {
assert_erl!(
"pub fn negate(x) {
!x
}"
)
}
#[test]
fn negation_block() {
assert_erl!(
"pub fn negate(x) {
!{
123
x
}
}"
)
}
// https://github.com/gleam-lang/gleam/issues/1655
#[test]
fn tail_maybe_expr_block() {
assert_erl!(
"pub fn a() {
let fake_tap = fn(x) { x }
let b = [99]
[
1,
2,
..b
|> fake_tap
]
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/1587
#[test]
fn guard_variable_rewriting() {
assert_erl!(
"pub fn main() {
case 1.0 {
a if a <. 0.0 -> {
let a = a
a
}
_ -> 0.0
}
}
"
)
}
// https://github.com/gleam-lang/gleam/issues/1816
#[test]
fn function_argument_shadowing() {
assert_erl!(
"pub fn main(a) {
Box
}
pub type Box {
Box(Int)
}
"
)
}
// https://github.com/gleam-lang/gleam/issues/2156
#[test]
fn dynamic() {
assert_erl!("pub type Dynamic")
}
// https://github.com/gleam-lang/gleam/issues/2166
#[test]
fn inline_const_pattern_option() {
assert_erl!(
"pub fn main() {
let fifteen = 15
let x = <<5:size(sixteen)>>
case x {
<<5:size(sixteen)>> -> <<5:size(sixteen)>>
<<6:size(fifteen)>> -> <<5:size(fifteen)>>
_ -> <<>>
}
}
pub const sixteen = 16"
)
}
// https://github.com/gleam-lang/gleam/issues/2349
#[test]
fn positive_zero() {
assert_erl!(
"
pub fn main() {
0.0
}
"
)
}
// https://github.com/gleam-lang/gleam/issues/3073
#[test]
fn scientific_notation() {
assert_erl!(
"
pub fn main() {
1.0e6
1.e6
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/3304
#[test]
fn type_named_else() {
assert_erl!(
"
pub type Else {
Else
}
pub fn main() {
Else
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/3382
#[test]
fn type_named_module_info() {
assert_erl!(
"
pub type ModuleInfo {
ModuleInfo
}
pub fn main() {
ModuleInfo
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/3382
#[test]
fn function_named_module_info() {
assert_erl!(
"
pub fn module_info() {
1
}
pub fn main() {
module_info()
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/3382
#[test]
fn function_named_module_info_imported() {
assert_erl!(
(
"some_module",
"some_module",
"
pub fn module_info() {
1
}
"
),
"
import some_module
pub fn main() {
some_module.module_info()
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/3382
#[test]
fn function_named_module_info_imported_qualified() {
assert_erl!(
(
"some_module",
"some_module",
"
pub fn module_info() {
1
}
"
),
"
import some_module.{module_info}
pub fn main() {
module_info()
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/3382
#[test]
fn constant_named_module_info() {
assert_erl!(
"
pub const module_info = 1
pub fn main() {
module_info
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/3382
#[test]
fn constant_named_module_info_imported() {
assert_erl!(
(
"some_module",
"some_module",
"
pub const module_info = 1
"
),
"
import some_module
pub fn main() {
some_module.module_info
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/3382
#[test]
fn constant_named_module_info_imported_qualified() {
assert_erl!(
(
"some_module",
"some_module",
"
pub const module_info = 1
"
),
"
import some_module.{module_info}
pub fn main() {
module_info
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/3382
#[test]
fn constant_named_module_info_with_function_inside() {
assert_erl!(
"
pub fn function() {
1
}
pub const module_info = function
pub fn main() {
module_info()
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/3382
#[test]
fn constant_named_module_info_with_function_inside_imported() {
assert_erl!(
(
"some_module",
"some_module",
"
pub fn function() {
1
}
pub const module_info = function
"
),
"
import some_module
pub fn main() {
some_module.module_info()
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/3382
#[test]
fn constant_named_module_info_with_function_inside_imported_qualified() {
assert_erl!(
(
"some_module",
"some_module",
"
pub fn function() {
1
}
pub const module_info = function
"
),
"
import some_module.{module_info}
pub fn main() {
module_info()
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/3382
#[test]
fn function_named_module_info_in_constant() {
assert_erl!(
"
pub fn module_info() {
1
}
pub const constant = module_info
pub fn main() {
constant()
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/3382
#[test]
fn function_named_module_info_in_constant_imported() {
assert_erl!(
(
"some_module",
"some_module",
"
pub fn module_info() {
1
}
pub const constant = module_info
"
),
"
import some_module
pub fn main() {
some_module.constant()
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/3382
#[test]
fn function_named_module_info_in_constant_imported_qualified() {
assert_erl!(
(
"some_module",
"some_module",
"
pub fn module_info() {
1
}
pub const constant = module_info
"
),
"
import some_module.{constant}
pub fn main() {
constant()
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/3648
#[test]
fn windows_file_escaping_bug() {
let src = "pub fn main() { Nil }";
let path = "C:\\root\\project\\test\\my\\mod.gleam";
let output = compile_test_project(src, path, Vec::new());
insta::assert_snapshot!(insta::internals::AutoName, output, src);
}
// https://github.com/gleam-lang/gleam/issues/3315
#[test]
fn bit_pattern_shadowing() {
assert_erl!(
"
pub fn main() {
let code = <<\"hello world\":utf8>>
let pre = 1
case code {
<<pre:bytes-size(pre), _:bytes>> -> pre
_ -> panic
}
} "
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/pattern.rs | compiler-core/src/erlang/pattern.rs | use ecow::eco_format;
use crate::analyse::Inferred;
use super::*;
pub(super) struct PatternPrinter<'a, 'env> {
pub environment: &'env mut Env<'a>,
pub variables: Vec<&'a str>,
pub guards: Vec<Document<'a>>,
/// In case we're dealing with string patterns, we might have something like
/// this: `"a" as letter <> rest`. In this case we want to compile it to
/// `<<"a"/utf8, rest/binary>>` and then bind a variable to `"a"`.
/// This way it's easier for the erlang compiler to optimise the pattern
/// matching.
///
/// Here we store a list of gleam variable name to its name used in the
/// Erlang code and its literal value.
pub assignments: Vec<StringPatternAssignment<'a>>,
}
/// This is used to hold data about string patterns with an alias like:
/// `"a" as letter <> _`
pub struct StringPatternAssignment<'a> {
/// The name assigned to the pattern in the Gleam code:
///
/// ```gleam
/// "a" as letter <> _
/// // ^^^^^^ This one
/// ```
///
pub gleam_name: EcoString,
/// The name we're using for that same variable in the generated Erlang
/// code, could have numbers added to it to make sure it's unique, like
/// `Letter@1`.
///
pub erlang_name: Document<'a>,
/// The document representing the literal value of that variable. For
/// example, if we had this pattern `"a" <> letter` it's literal value in
/// Erlang is going to be a document with the following string
/// `<<"a"/utf8>>`.
///
pub literal_value: Document<'a>,
}
impl<'a> StringPatternAssignment<'a> {
pub fn to_assignment_doc(&self) -> Document<'a> {
docvec![self.erlang_name.clone(), " = ", self.literal_value.clone()]
}
}
impl<'a, 'env> PatternPrinter<'a, 'env> {
pub(super) fn new(environment: &'env mut Env<'a>) -> Self {
Self {
environment,
variables: vec![],
guards: vec![],
assignments: vec![],
}
}
pub(super) fn reset_variables(&mut self) {
self.variables = vec![];
}
pub(super) fn print(&mut self, pattern: &'a TypedPattern) -> Document<'a> {
match pattern {
Pattern::Assign { name, pattern, .. } => {
self.variables.push(name);
self.print(pattern)
.append(" = ")
.append(self.environment.next_local_var_name(name))
}
Pattern::List { elements, tail, .. } => self.pattern_list(elements, tail.as_deref()),
Pattern::Discard { .. } => "_".to_doc(),
Pattern::BitArraySize(size) => match size {
BitArraySize::Int { .. }
| BitArraySize::Variable { .. }
| BitArraySize::Block { .. } => self.bit_array_size(size),
BitArraySize::BinaryOperator { .. } => self.bit_array_size(size).surround("(", ")"),
},
Pattern::Variable { name, .. } => {
self.variables.push(name);
self.environment.next_local_var_name(name)
}
Pattern::Int { value, .. } => int(value),
Pattern::Float { value, .. } => float(value),
Pattern::String { value, .. } => string(value),
Pattern::Constructor {
arguments,
constructor: Inferred::Known(PatternConstructor { name, .. }),
..
} => self.tag_tuple_pattern(name, arguments),
Pattern::Constructor {
constructor: Inferred::Unknown,
..
} => {
panic!("Erlang generation performed with uninferred pattern constructor")
}
Pattern::Tuple { elements, .. } => {
tuple(elements.iter().map(|pattern| self.print(pattern)))
}
Pattern::BitArray { segments, .. } => bit_array(
segments
.iter()
.map(|s| self.pattern_segment(&s.value, &s.options)),
),
Pattern::StringPrefix {
left_side_string,
right_side_assignment,
left_side_assignment,
..
} => {
let right = match right_side_assignment {
AssignName::Variable(right) => {
self.variables.push(right);
self.environment.next_local_var_name(right)
}
AssignName::Discard(_) => "_".to_doc(),
};
if let Some((left_name, _)) = left_side_assignment {
// "wibble" as prefix <> rest
// ^^^^^^^^^ In case the left prefix of the pattern matching is given an alias
// we bind it to a local variable so that it can be correctly
// referenced inside the case branch.
//
// So we will end up with something that looks like this:
//
// <<"wibble"/binary, Rest/binary>> ->
// Prefix = "wibble",
// ...
//
self.variables.push(left_name);
self.assignments.push(StringPatternAssignment {
gleam_name: left_name.clone(),
erlang_name: self.environment.next_local_var_name(left_name),
literal_value: string(left_side_string),
});
}
docvec![
"<<\"",
string_inner(left_side_string),
"\"/utf8",
", ",
right,
"/binary>>"
]
}
Pattern::Invalid { .. } => panic!("invalid patterns should not reach code generation"),
}
}
fn bit_array_size(&mut self, size: &'a TypedBitArraySize) -> Document<'a> {
match size {
BitArraySize::Int { value, .. } => int(value),
BitArraySize::Block { inner, .. } => self.bit_array_size(inner).surround("(", ")"),
BitArraySize::Variable {
name, constructor, ..
} => {
let variant = &constructor
.as_ref()
.expect("Constructor not found for variable usage")
.variant;
match variant {
ValueConstructorVariant::ModuleConstant { literal, .. } => {
const_inline(literal, self.environment)
}
ValueConstructorVariant::LocalVariable { .. }
| ValueConstructorVariant::ModuleFn { .. }
| ValueConstructorVariant::Record { .. } => {
self.environment.local_var_name(name)
}
}
}
BitArraySize::BinaryOperator {
operator,
left,
right,
..
} => {
let operator = match operator {
IntOperator::Add => " + ",
IntOperator::Subtract => " - ",
IntOperator::Multiply => " * ",
IntOperator::Divide => {
return self.bit_array_size_divide(left, right, "div");
}
IntOperator::Remainder => {
return self.bit_array_size_divide(left, right, "rem");
}
};
docvec![
self.bit_array_size(left),
operator,
self.bit_array_size(right)
]
}
}
}
fn bit_array_size_divide(
&mut self,
left: &'a TypedBitArraySize,
right: &'a TypedBitArraySize,
operator: &'static str,
) -> Document<'a> {
if right.non_zero_compile_time_number() {
return self.bit_array_size_operator(left, operator, right);
}
let left = self.bit_array_size(left);
let right = self.bit_array_size(right);
let denominator = self.environment.next_local_var_name("gleam@denominator");
let clauses = docvec![
line(),
"0 -> 0;",
line(),
denominator.clone(),
" -> ",
binop_documents(left, operator, denominator)
];
docvec!["case ", right, " of", clauses.nest(INDENT), line(), "end"]
}
fn bit_array_size_operator(
&mut self,
left: &'a TypedBitArraySize,
operator: &'static str,
right: &'a TypedBitArraySize,
) -> Document<'a> {
let left = if let BitArraySize::BinaryOperator { .. } = left {
self.bit_array_size(left).surround("(", ")")
} else {
self.bit_array_size(left)
};
let right = if let BitArraySize::BinaryOperator { .. } = right {
self.bit_array_size(right).surround("(", ")")
} else {
self.bit_array_size(right)
};
binop_documents(left, operator, right)
}
fn tag_tuple_pattern(
&mut self,
name: &'a str,
arguments: &'a [CallArg<TypedPattern>],
) -> Document<'a> {
if arguments.is_empty() {
atom_string(to_snake_case(name))
} else {
tuple(
[atom_string(to_snake_case(name))]
.into_iter()
.chain(arguments.iter().map(|argument| self.print(&argument.value))),
)
}
}
fn pattern_list(
&mut self,
elements: &'a [TypedPattern],
tail: Option<&'a TypedTailPattern>,
) -> Document<'a> {
let elements = join(
elements.iter().map(|element| self.print(element)),
break_(",", ", "),
);
let tail = tail.map(|tail| self.print(&tail.pattern));
list(elements, tail)
}
fn pattern_segment(
&mut self,
value: &'a TypedPattern,
options: &'a [BitArrayOption<TypedPattern>],
) -> Document<'a> {
let pattern_is_a_string_literal = matches!(value, Pattern::String { .. });
let pattern_is_a_discard = matches!(value, Pattern::Discard { .. });
let create_document = |this: &mut PatternPrinter<'a, 'env>| match value {
Pattern::String { value, .. } => string_inner(value).surround("\"", "\""),
Pattern::Discard { .. }
| Pattern::Variable { .. }
| Pattern::Int { .. }
| Pattern::Float { .. } => this.print(value),
Pattern::Assign { name, pattern, .. } => {
this.variables.push(name);
let variable_name = this.environment.next_local_var_name(name);
match pattern.as_ref() {
// In Erlang, assignment patterns inside bit arrays are not allowed. So instead of
// generating `<<1 = A>>`, we use guards, and generate `<<A>> when A =:= 1`.
Pattern::Int { value, .. } => {
this.guards
.push(docvec![variable_name.clone(), " =:= ", int(value)]);
variable_name
}
Pattern::Float { value, .. } => {
this.guards
.push(docvec![variable_name.clone(), " =:= ", float(value)]);
variable_name
}
// Here we do the same as for floats and ints, but we must calculate the size of
// the string first, so we can correctly match the bit array segment then compare
// it afterwards.
Pattern::String { value, .. } => {
this.guards
.push(docvec![variable_name.clone(), " =:= ", string(value)]);
docvec![variable_name, ":", string_length_utf8_bytes(value)]
}
// Doing a pattern such as `<<_ as a>>` is the same as just `<<a>>`, so we treat it
// as such.
Pattern::Discard { .. } => variable_name,
// Any other pattern is invalid as a bit array segment. We already handle the case
// of `<<a as b>>` in the type-checker, and assignment patterns cannot be nested.
Pattern::Variable { .. }
| Pattern::BitArraySize(_)
| Pattern::Assign { .. }
| Pattern::List { .. }
| Pattern::Constructor { .. }
| Pattern::Tuple { .. }
| Pattern::BitArray { .. }
| Pattern::StringPrefix { .. }
| Pattern::Invalid { .. } => panic!("Pattern segment match not recognised"),
}
}
Pattern::BitArraySize(_)
| Pattern::List { .. }
| Pattern::Constructor { .. }
| Pattern::Tuple { .. }
| Pattern::BitArray { .. }
| Pattern::StringPrefix { .. }
| Pattern::Invalid { .. } => panic!("Pattern segment match not recognised"),
};
let size = |value: &'a TypedPattern, this: &mut PatternPrinter<'a, 'env>| {
Some(":".to_doc().append(this.print(value)))
};
let unit = |value: &'a u8| Some(eco_format!("unit:{value}").to_doc());
bit_array_segment(
create_document,
options,
size,
unit,
pattern_is_a_string_literal,
pattern_is_a_discard,
self,
)
}
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests/consts.rs | compiler-core/src/erlang/tests/consts.rs | use crate::assert_erl;
// https://github.com/gleam-lang/gleam/issues/2163
#[test]
fn record_constructor() {
assert_erl!(
r#"
pub type X {
X(Int)
}
pub const z = X
pub fn main() {
z
}"#
);
}
// https://github.com/gleam-lang/gleam/issues/2163
#[test]
fn record_constructor_in_tuple() {
assert_erl!(
r#"
pub type X {
X(Int)
}
pub const z = #(X)
pub fn main() {
z
}"#
);
}
// https://github.com/gleam-lang/gleam/issues/2179
#[test]
fn const_type_variable() {
assert_erl!(
r#"
fn identity(a: a) -> a {
a
}
const id: fn(a) -> a = identity
"#
);
}
#[test]
fn const_generalise() {
assert_erl!(
r#"
fn identity(a: a) -> a {
a
}
const id = identity
pub fn main(){
let num = id(1)
let word = id("Word")
}"#
);
}
#[test]
fn pub_const_equal_to_private_function() {
assert_erl!(
r#"
fn identity(a) {
a
}
pub const id = identity
"#
);
}
#[test]
fn pub_const_equal_to_record_with_private_function_field() {
assert_erl!(
r#"
fn identity(a) {
a
}
pub type Mapper(b) {
Mapper(fn(b) -> b)
}
pub const id_mapper = Mapper(identity)
"#
);
}
#[test]
fn pub_const_equal_to_record_with_nested_private_function_field() {
assert_erl!(
r#"
fn identity(a) {
a
}
pub type Mapper(b) {
Mapper(fn(b) -> b)
}
pub type Funcs(b) {
Funcs(mapper: Mapper(b))
}
pub const id_mapper = Funcs(Mapper(identity))
"#
);
}
#[test]
fn use_unqualified_pub_const_equal_to_private_function() {
assert_erl!(
r#"
fn identity(a) {
a
}
pub const id = identity
"#
);
}
#[test]
fn use_unqualified_pub_const_equal_to_record_with_private_function_field() {
assert_erl!(
r#"
fn identity(a) {
a
}
pub type Mapper(b) {
Mapper(fn(b) -> b)
}
pub const id_mapper = Mapper(identity)
"#
);
}
#[test]
fn use_qualified_pub_const_equal_to_record_with_private_function_field() {
assert_erl!(
r#"
fn identity(a) {
a
}
pub type Mapper(b) {
Mapper(fn(b) -> b)
}
pub const id_mapper = Mapper(identity)
"#
);
}
#[test]
fn use_private_in_internal() {
assert_erl!(
r#"
fn identity(a) {
a
}
pub type Mapper(b) {
Mapper(fn(b) -> b)
}
@internal
pub const id_mapper = Mapper(identity)
"#
);
}
#[test]
fn use_private_in_list() {
assert_erl!(
r#"
fn identity(a) {
a
}
pub const funcs = [identity]
"#
)
}
#[test]
fn use_private_in_tuple() {
assert_erl!(
r#"
fn identity(a) {
a
}
pub const funcs = #(identity)
"#
)
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests/reserved.rs | compiler-core/src/erlang/tests/reserved.rs | use crate::assert_erl;
#[test]
fn build_in_erlang_type_escaping() {
assert_erl!("pub type Map");
}
#[test]
fn escape_erlang_reserved_keywords_in_type_names() {
// list of all reserved words in erlang
// http://erlang.org/documentation/doc-5.8/doc/reference_manual/introduction.html
assert_erl!(
r#"pub type After { TestAfter }
pub type And { TestAnd }
pub type Andalso { TestAndAlso }
pub type Band { TestBAnd }
pub type Begin { TestBegin }
pub type Bnot { TestBNot }
pub type Bor { TestBOr }
pub type Bsl { TestBsl }
pub type Bsr { TestBsr }
pub type Bxor { TestBXor }
pub type Case { TestCase }
pub type Catch { TestCatch }
pub type Cond { TestCond }
pub type Div { TestDiv }
pub type End { TestEnd }
pub type Fun { TestFun }
pub type If { TestIf }
pub type Let { TestLet }
pub type Maybe { TestMaybe }
pub type Not { TestNot }
pub type Of { TestOf }
pub type Or { TestOr }
pub type Orelse { TestOrElse }
pub type Query { TestQuery }
pub type Receive { TestReceive }
pub type Rem { TestRem }
pub type Try { TestTry }
pub type When { TestWhen }
pub type Xor { TestXor }"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests/documentation.rs | compiler-core/src/erlang/tests/documentation.rs | use crate::assert_erl;
#[test]
fn function_with_documentation() {
assert_erl!(
r#"
/// Function doc!
pub fn documented() { 1 }"#
);
}
#[test]
fn function_with_multiline_documentation() {
assert_erl!(
r#"
/// Function doc!
/// Hello!!
///
pub fn documented() { 1 }"#
);
}
#[test]
fn quotes_in_documentation_are_escaped() {
assert_erl!(
r#"
/// "hello"
pub fn documented() { 1 }"#
);
}
#[test]
fn backslashes_in_documentation_are_escaped() {
assert_erl!(
r#"
/// \hello\
pub fn documented() { 1 }"#
);
}
#[test]
fn single_line_module_comment() {
assert_erl!(
r#"
//// Hello! This is a single line module comment.
pub fn main() { 1 }"#
);
}
#[test]
fn multi_line_module_comment() {
assert_erl!(
r#"
//// Hello! This is a multi-
//// line module comment.
////
pub fn main() { 1 }"#
);
}
#[test]
fn double_quotes_are_escaped_in_module_comment() {
assert_erl!(
r#"
//// "quotes!"
pub fn main() { 1 }"#
);
}
#[test]
fn backslashes_are_escaped_in_module_comment() {
assert_erl!(
r#"
//// \backslashes!\
pub fn main() { 1 }"#
);
}
#[test]
fn internal_function_has_no_documentation() {
assert_erl!(
r#"
/// hidden!
@internal
pub fn main() { 1 }"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests/assert.rs | compiler-core/src/erlang/tests/assert.rs | use crate::assert_erl;
#[test]
fn assert_variable() {
assert_erl!(
"
pub fn main() {
let x = True
assert x
}
"
);
}
#[test]
fn assert_literal() {
assert_erl!(
"
pub fn main() {
assert False
}
"
);
}
#[test]
fn assert_binary_operation() {
assert_erl!(
"
pub fn main() {
let x = True
assert x || False
}
"
);
}
#[test]
fn assert_binary_operation2() {
assert_erl!(
"
pub fn eq(a, b) {
assert a == b
}
"
);
}
#[test]
fn assert_binary_operation3() {
assert_erl!(
"
pub fn assert_answer(x) {
assert x == 42
}
"
);
}
#[test]
fn assert_function_call() {
assert_erl!(
"
fn bool() {
True
}
pub fn main() {
assert bool()
}
"
);
}
#[test]
fn assert_function_call2() {
assert_erl!(
"
fn and(a, b) {
a && b
}
pub fn go(x) {
assert and(True, x)
}
"
);
}
#[test]
fn assert_nested_function_call() {
assert_erl!(
"
fn and(x, y) {
x && y
}
pub fn main() {
assert and(and(True, False), True)
}
"
);
}
#[test]
fn assert_binary_operator_with_side_effects() {
assert_erl!(
"
fn wibble(a, b) {
let result = a + b
result == 10
}
pub fn go(x) {
assert True && wibble(1, 4)
}
"
);
}
#[test]
fn assert_binary_operator_with_side_effects2() {
assert_erl!(
"
fn wibble(a, b) {
let result = a + b
result == 10
}
pub fn go(x) {
assert wibble(5, 5) && wibble(4, 6)
}
"
);
}
#[test]
fn assert_with_message() {
assert_erl!(
r#"
pub fn main() {
assert True as "This shouldn't fail"
}
"#
);
}
#[test]
fn assert_with_block_message() {
assert_erl!(
r#"
fn identity(a) {
a
}
pub fn main() {
assert identity(True) as {
let message = identity("This shouldn't fail")
message
}
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests/variables.rs | compiler-core/src/erlang/tests/variables.rs | use crate::assert_erl;
#[test]
fn shadow_let() {
// https://github.com/gleam-lang/gleam/issues/333
assert_erl!(
r#"
pub fn go(a) {
case a {
99 -> {
let a = a
1
}
_ -> a
}
}"#
);
}
#[test]
fn shadow_param() {
// https://github.com/gleam-lang/gleam/issues/772
assert_erl!(
"pub fn main(board) {
fn(board) { board }
board
}"
);
}
#[test]
fn shadow_and_call() {
// https://github.com/gleam-lang/gleam/issues/762
assert_erl!(
r#"
pub fn main(x) {
fn(x) { x }(x)
}
"#
);
}
#[test]
fn shadow_pipe() {
assert_erl!(
r#"
pub fn main(x) {
x
|> fn(x) { x }
}
"#
);
}
#[test]
fn discarded() {
// https://github.com/gleam-lang/gleam/issues/788
assert_erl!(
r#"pub fn go() {
let _r = 1
let _r = 2
Nil
}"#
);
}
#[test]
fn anon_external_fun_name_escaping() {
// https://github.com/gleam-lang/gleam/issues/1418
assert_erl!(
r#"
@external(erlang, "one.two", "three.four")
fn func() -> Nil
pub fn main() {
func
}"#
);
}
#[test]
fn module_const_vars() {
assert_erl!(
"const int = 42
const int_alias = int
pub fn use_int_alias() { int_alias }
fn int_identity(i: Int) { i }
const int_identity_alias: fn(Int) -> Int = int_identity
pub fn use_int_identity_alias() { int_identity_alias(42) }
const compound: #(Int, fn(Int) -> Int, fn(Int) -> Int) = #(int, int_identity, int_identity_alias)
pub fn use_compound() { compound.1(compound.0) }
"
)
}
#[test]
fn blocks_are_scopes() {
assert_erl!(
"
pub fn main() {
let x = 1
{
let x = 2
}
x
}
"
)
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests/external_fn.rs | compiler-core/src/erlang/tests/external_fn.rs | use crate::{assert_erl, assert_js_module_error, assert_module_error};
#[test]
fn integration_test1_3() {
assert_erl!(
r#"
@external(erlang, "Elixir.MyApp", "run")
pub fn run() -> Int
"#
);
}
#[test]
fn integration_test7() {
assert_erl!(
r#"
@external(erlang, "try", "and")
pub fn receive() -> Int
pub fn catch(x) { receive() }
"#
);
}
#[test]
fn private_external_function_calls() {
// Private external function calls are inlined
assert_erl!(
r#"
@external(erlang, "m", "f")
fn go(x x: Int, y y: Int) -> Int
pub fn x() { go(x: 1, y: 2) go(y: 3, x: 4) }"#
);
}
#[test]
fn public_local_function_calls() {
// Public external function calls are inlined but the wrapper function is
// also printed in the erlang output and exported
assert_erl!(
r#"
@external(erlang, "m", "f")
pub fn go(x x: Int, y y: Int) -> Int
pub fn x() { go(x: 1, y: 2) go(y: 3, x: 4) }
"#
);
}
#[test]
fn private_local_function_references() {
// Private external function references are inlined
assert_erl!(
r#"
@external(erlang, "m", "f")
fn go(x: Int, y: Int) -> Int
pub fn x() { go }
"#
);
}
#[test]
fn inlining_external_functions_from_another_module() {
assert_erl!(
(
"lib",
"atom",
r#"
pub type Atom
@external(erlang, "erlang", "binary_to_atom")
pub fn make(x: String) -> Atom
"#
),
r#"import atom
pub fn main() {
atom.make("ok")
}
"#
);
}
#[test]
fn unqualified_inlining_external_functions_from_another_module() {
assert_erl!(
(
"lib",
"atom",
r#"
pub type Atom
@external(erlang, "erlang", "binary_to_atom")
pub fn make(x: String) -> Atom
"#
),
"import atom.{make}
pub fn main() {
make(\"ok\")
}
"
);
}
#[test]
fn reference_to_imported_elixir_external_fn() {
assert_erl!(
(
"lib",
"my_app",
r#"
@external(erlang, "Elixir.MyApp", "run")
pub fn run() -> Int
"#
),
r#"import my_app
pub fn main() {
let x = my_app.run
id(my_app.run)
}
fn id(x) { x }
"#
);
}
#[test]
fn unqualified_reference_to_imported_elixir_external_fn() {
assert_erl!(
(
"lib",
"my_app",
r#"
@external(erlang, "Elixir.MyApp", "run")
pub fn run() -> Int
"#
),
r#"import my_app.{run}
pub fn main() {
let x = run
id(run)
}
fn id(x) { x }
"#
);
}
#[test]
fn attribute_erlang() {
assert_erl!(
r#"
@external(erlang, "one", "one")
pub fn one(x: Int) -> Int {
todo
}
"#
);
}
#[test]
fn attribute_javascript() {
assert_erl!(
r#"
@external(javascript, "./one.mjs", "one")
pub fn one(x: Int) -> Int {
todo
}
"#
);
}
#[test]
fn erlang_and_javascript() {
assert_erl!(
r#"
@external(erlang, "one", "one")
@external(javascript, "./one.mjs", "one")
pub fn one(x: Int) -> Int {
todo
}
"#
);
}
#[test]
fn no_type_annotation_for_parameter() {
assert_module_error!(
r#"
@external(erlang, "one", "one")
pub fn one(x: Int, y) -> Int {
todo
}
"#
);
}
#[test]
fn no_type_annotation_for_return() {
assert_module_error!(
r#"
@external(erlang, "one", "one")
pub fn one(x: Int) {
todo
}
"#
);
}
#[test]
fn hole_parameter_erlang() {
assert_module_error!(
r#"
@external(erlang, "one", "one")
pub fn one(x: List(_)) -> Int {
todo
}
"#
);
}
#[test]
fn hole_return_erlang() {
assert_module_error!(
r#"
@external(erlang, "one", "one")
pub fn one(x: List(Int)) -> List(_) {
todo
}
"#
);
}
#[test]
fn hole_parameter_javascript() {
assert_module_error!(
r#"
@external(javascript, "one", "one")
pub fn one(x: List(_)) -> Int {
todo
}
"#
);
}
#[test]
fn hole_return_javascript() {
assert_module_error!(
r#"
@external(javascript, "one", "one")
pub fn one(x: List(Int)) -> List(_) {
todo
}
"#
);
}
#[test]
fn no_body() {
assert_erl!(
r#"
@external(erlang, "one", "one")
pub fn one(x: Int) -> Int
"#
);
}
#[test]
fn no_body_or_implementation() {
assert_module_error!(
r#"
pub fn one(x: Int) -> Float
"#
);
}
#[test]
fn private() {
assert_erl!(
r#"
pub fn main() {
do()
}
@external(erlang, "library", "main")
fn do() -> Int
"#
);
}
#[test]
fn elixir() {
assert_erl!(
r#"
pub fn main() {
#(do, do())
}
@external(erlang, "Elixir.String", "main")
fn do() -> Int
"#
);
}
#[test]
fn public_elixir() {
assert_erl!(
r#"
@external(erlang, "Elixir.String", "main")
pub fn do() -> Int
"#
);
}
#[test]
fn javascript_only() {
assert_erl!(
r#"
pub fn should_be_generated(x: Int) -> Int {
x
}
@external(javascript, "one", "one")
pub fn should_not_be_generated(x: Int) -> Int
"#
);
}
#[test]
fn javascript_only_indirect() {
assert_erl!(
r#"
pub fn should_be_generated(x: Int) -> Int {
x
}
@external(javascript, "one", "one")
pub fn should_not_be_generated(x: Int) -> Int
pub fn also_should_not_be_generated() {
should_not_be_generated(1)
|> should_be_generated
}
"#
);
}
#[test]
fn both_externals_no_valid_impl() {
assert_erl!(
r#"
@external(javascript, "one", "one")
pub fn js() -> Nil
@external(erlang, "one", "one")
pub fn erl() -> Nil
pub fn should_not_be_generated() {
js()
erl()
}
"#
);
}
#[test]
fn no_gleam_impl_no_annotations_function_fault_tolerance() {
// A function not having annotations when required does not stop analysis.
assert_module_error!(
r#"
@external(erlang, "one", "two")
pub fn no_impl()
pub type X = UnknownType
"#
);
}
#[test]
fn no_target_supported_function_fault_tolerance() {
// A function not supporting the current target does not stop analysis.
assert_js_module_error!(
r#"
// This will error for having no support on this platform
@external(erlang, "one", "two")
pub fn no_impl() -> Int
pub fn main() {
// This will due to no_impl not having an appropriate implementation for the
// target, NOT because it doesn't exist. The analyser should still know about
// it, even though it is invalid.
no_impl()
}
"#
);
}
#[test]
fn discarded_arg_in_external_are_passed_correctly() {
assert_erl!(
r#"
@external(erlang, "wibble", "wobble")
pub fn woo(_a: a) -> Nil
"#
);
}
#[test]
fn multiple_discarded_args_in_external_are_passed_correctly() {
assert_erl!(
r#"
@external(erlang, "wibble", "wobble")
pub fn woo(_: a, _: b) -> Nil
"#
);
}
#[test]
fn multiple_discarded_args_in_external_are_passed_correctly_2() {
assert_erl!(
r#"
@external(erlang, "wibble", "wobble")
pub fn woo(__: a, _two: b) -> Nil
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests/use_.rs | compiler-core/src/erlang/tests/use_.rs | use crate::assert_erl;
#[test]
fn arity_1() {
assert_erl!(
r#"
pub fn main() {
use <- pair()
123
}
fn pair(f) {
let x = f()
#(x, x)
}
"#,
)
}
#[test]
fn arity_2() {
assert_erl!(
r#"
pub fn main() {
use <- pair(1.0)
123
}
fn pair(x, f) {
let y = f()
#(x, y)
}
"#,
)
}
#[test]
fn arity_3() {
assert_erl!(
r#"
pub fn main() {
use <- trip(1.0, "")
123
}
fn trip(x, y, f) {
let z = f()
#(x, y, z)
}
"#,
)
}
#[test]
fn no_callback_body() {
assert_erl!(
r#"
pub fn main() {
let thingy = fn(f) { f() }
use <- thingy()
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/1863
#[test]
fn pipeline_that_returns_fn() {
assert_erl!(
r#"
pub fn main() {
use <- 1 |> add
1
}
pub fn add(x) {
fn(f) { f() + x }
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests/prelude.rs | compiler-core/src/erlang/tests/prelude.rs | use crate::assert_erl;
#[test]
fn qualified_prelude() {
assert_erl!(
"import gleam
pub type X { X(gleam.Int) }
"
);
assert_erl!(
"import gleam
pub fn x() { gleam.Ok(1) }
"
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests/case.rs | compiler-core/src/erlang/tests/case.rs | use crate::assert_erl;
// https://github.com/gleam-lang/gleam/issues/1675
#[test]
fn alternative_pattern_variable_rewriting() {
assert_erl!(
"
pub fn myfun(mt) {
case mt {
1 | _ ->
1
|> Ok
}
1
|> Ok
}
"
)
}
// https://github.com/gleam-lang/gleam/issues/2349
#[test]
fn positive_zero_pattern() {
assert_erl!(
"
pub fn main(x) {
case x {
0.0 -> 1
_ -> 2
}
}
"
)
}
// https://github.com/gleam-lang/gleam/issues/2349
#[test]
fn negative_zero_pattern() {
assert_erl!(
"
pub fn main(x) {
case x {
-0.0 -> 1
_ -> 2
}
}
"
)
}
#[test]
fn not() {
assert_erl!(
r#"pub fn main(x, y) {
case x {
_ if !y -> 0
_ -> 1
}
}
"#,
);
}
#[test]
fn not_two() {
assert_erl!(
r#"pub fn main(x, y) {
case x {
_ if !y && !x -> 0
_ -> 1
}
}
"#,
);
}
// https://github.com/gleam-lang/gleam/issues/2657
#[test]
fn spread_empty_list() {
assert_erl!(
r#"
pub fn main() {
case [] {
[..] -> 1
}
}
"#,
);
}
// https://github.com/gleam-lang/gleam/issues/2657
#[test]
fn spread_empty_list_assigning() {
assert_erl!(
r#"
pub fn main() {
case [] {
[..rest] -> rest
}
}
"#,
);
}
// https://github.com/gleam-lang/gleam/issues/5055
#[test]
fn alternative_patter_with_string_alias() {
assert_erl!(
r#"
pub fn main(x) {
case x {
"a" as letter <> _ | "b" as letter <> _ -> letter
_ -> "wibble"
}
}
"#,
);
}
// https://github.com/gleam-lang/gleam/issues/5115
#[test]
fn aliased_string_prefix_pattern_referenced_in_guard() {
assert_erl!(
r#"
pub fn main(x) {
case x {
"a" as letter <> _ if letter == x -> letter
_ -> "wibble"
}
}
"#,
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests/guards.rs | compiler-core/src/erlang/tests/guards.rs | use crate::assert_erl;
#[test]
fn clause_guards() {
// Clause guards
assert_erl!(
r#"
pub fn main(args) {
case args {
x if x == args -> 1
_ -> 0
}
}
"#
);
}
#[test]
fn clause_guards_1() {
assert_erl!(
r#"
pub fn main(args) {
case args {
x if {x != x} == {args == args} -> 1
_ -> 0
}
}
"#
);
}
#[test]
fn clause_guards_2() {
assert_erl!(
r#"
pub fn main(args) {
case args {
x if x && x || x == x && x -> 1
_ -> 0
}
}
"#
);
}
#[test]
fn clause_guards_3() {
assert_erl!(
r#"
pub fn main() {
case 1, 0 {
x, y if x > y -> 1
_, _ -> 0
}
}
"#
);
}
#[test]
fn clause_guards_4() {
assert_erl!(
r#"
pub fn main() {
case 1, 0 {
x, y if x >= y -> 1
_, _ -> 0
}
}
"#
);
}
#[test]
fn clause_guards_5() {
assert_erl!(
r#"
pub fn main() {
case 1, 0 {
x, y if x < y -> 1
_, _ -> 0
}
}
"#
);
}
#[test]
fn clause_guards_6() {
assert_erl!(
r#"
pub fn main() {
case 1, 0 {
x, y if x <= y -> 1
_, _ -> 0
}
}
"#
);
}
#[test]
fn clause_guards_7() {
assert_erl!(
r#"
pub fn main() {
case 1.0, 0.1 {
x, y if x >. y -> 1
_, _ -> 0
}
}
"#
);
}
#[test]
fn clause_guards_8() {
assert_erl!(
r#"
pub fn main() {
case 1.0, 0.1 {
x, y if x >=. y -> 1
_, _ -> 0
}
}
"#
);
}
#[test]
fn clause_guards_9() {
assert_erl!(
r#"
pub fn main() {
let x = 0.123
case x {
99.9854 -> 1
_ -> 0
}
}
"#
);
}
#[test]
fn clause_guards_10() {
assert_erl!(
r#"
pub fn main() {
let x = 0.123
case x {
_ if x == 3.14 -> 1
_ -> 0
}
}
"#
);
}
#[test]
fn clause_guards20() {
assert_erl!(
r#"
pub fn main() {
let x = 0.123
case x {
_ if 0.123 <. x -> 1
_ -> 0
}
}
"#
);
}
#[test]
fn clause_guards21() {
assert_erl!(
r#"
pub fn main(x) {
case x {
_ if x == [1, 2, 3] -> 1
_ -> 0
}
}
"#
);
}
#[test]
fn clause_guards22() {
assert_erl!(
r#"
pub fn main() {
let x = 0
case x {
0 -> 1
_ -> 0
}
}
"#
);
}
#[test]
fn clause_guards23() {
// Tuple literals in guards
assert_erl!(
r#"
pub fn main() {
let x = #(1, 2, 3)
case x {
_ if x == #(1, 2, 3) -> 1
_ -> 0
}
}
"#
);
}
#[test]
fn clause_guards24() {
assert_erl!(
r#"
pub fn main() {
let x = #(1, 2, 3)
case x {
_ if x == #(1, 2, 3) -> 1
_ if x == #(2, 3, 4) -> 2
_ -> 0
}
}
"#
);
}
#[test]
fn clause_guards25() {
// Int literals in guards
assert_erl!(
r#"
pub fn main() {
let x = 0
case x {
_ if x == 0 -> 1
_ -> 0
}
}
"#
);
}
#[test]
fn clause_guards26() {
assert_erl!(
r#"
pub fn main() {
let x = 0
case x {
_ if 0 < x -> 1
_ -> 0
}
}
"#
);
}
#[test]
fn clause_guards27() {
// String literals in guards
assert_erl!(
r#"
pub fn main() {
case "test" {
x if x == "test" -> 1
_ -> 0
}
}
"#
);
}
#[test]
fn clause_guards28() {
// Record literals in guards
assert_erl!(
r#"
type Test { Test(x: Int, y: Float) }
pub fn main() {
let x = Test(1, 3.0)
case x {
_ if x == Test(1, 1.0) -> 1
_ if x == Test(y: 2.0, x: 2) -> 2
_ if x != Test(2, 3.0) -> 2
_ -> 0
}
}
"#
);
}
#[test]
fn clause_guards29() {
// Float vars in guards
assert_erl!(
r#"
pub fn main() {
case 0.1, 1.0 {
x, y if x <. y -> 1
_, _ -> 0
}
}
"#
);
}
#[test]
fn clause_guards30() {
assert_erl!(
r#"
pub fn main() {
case 0.1, 1.0 {
x, y if x <=. y -> 1
_, _ -> 0
}
}
"#
);
}
#[test]
fn clause_guards31() {
assert_erl!(
r#"
pub fn main(args) {
case args {
[x] | [x, _] if x -> 1
_ -> 0
}
}
"#
);
}
#[test]
fn constants_in_guards() {
assert_erl!(
r#"
pub const string_value = "constant value"
pub const float_value = 3.14
pub const int_value = 42
pub const tuple_value = #(1, 2.0, "3")
pub const list_value = [1, 2, 3]
pub fn main(arg) {
let _ = list_value
case arg {
#(w, x, y, z) if w == tuple_value && x == string_value && y >. float_value && z == int_value -> 1
_ -> 0
}
}
"#
);
}
#[test]
fn constants_in_guards1() {
assert_erl!(
r#"
pub const list = [1, 2, 3]
pub fn main(arg) {
case arg {
_ if arg == list -> 1
_ -> 0
}
}
"#
);
}
#[test]
fn only_guards() {
assert_erl!(
r#"
pub const string_value = "constant value"
pub fn main(arg) {
case arg {
_ if arg == string_value -> 1
_ -> 0
}
}
"#
);
}
#[test]
fn only_guards1() {
assert_erl!(
r#"
pub const bits = <<1, "ok":utf8, 3, 4:50>>
pub fn main(arg) {
case arg {
_ if arg == bits -> 1
_ -> 0
}
}
"#
);
}
#[test]
fn only_guards2() {
assert_erl!(
r#"
pub const constant = #(1, 2.0)
pub fn main(arg) {
case arg {
_ if arg == constant -> 1
_ -> 0
}
}
"#
);
}
#[test]
fn only_guards3() {
assert_erl!(
r#"
pub const float_value = 3.14
pub fn main(arg) {
case arg {
_ if arg >. float_value -> 1
_ -> 0
}
}
"#
);
}
#[test]
fn field_access() {
assert_erl!(
r#"
pub type Person {
Person(username: String, name: String, age: Int)
}
pub fn main() {
let given_name = "jack"
let raiden = Person("raiden", "jack", 31)
case given_name {
name if name == raiden.name -> "It's jack"
_ -> "It's not jack"
}
}
"#
)
}
#[test]
fn nested_record_access() {
assert_erl!(
r#"
pub type A {
A(b: B)
}
pub type B {
B(c: C)
}
pub type C {
C(d: Bool)
}
pub fn a(a: A) {
case a {
_ if a.b.c.d -> 1
_ -> 0
}
}
"#
);
}
#[test]
fn module_string_access() {
assert_erl!(
(
"package",
"hero",
r#"
pub const ironman = "Tony Stark"
"#
),
r#"
import hero
pub fn main() {
let name = "Tony Stark"
case name {
n if n == hero.ironman -> True
_ -> False
}
}
"#
);
}
#[test]
fn module_list_access() {
assert_erl!(
(
"package",
"hero",
r#"
pub const heroes = ["Tony Stark", "Bruce Wayne"]
"#
),
r#"
import hero
pub fn main() {
let names = ["Tony Stark", "Bruce Wayne"]
case names {
n if n == hero.heroes -> True
_ -> False
}
}
"#
);
}
#[test]
fn module_tuple_access() {
assert_erl!(
(
"package",
"hero",
r#"
pub const hero = #("ironman", "Tony Stark")
"#
),
r#"
import hero
pub fn main() {
let name = "Tony Stark"
case name {
n if n == hero.hero.1 -> True
_ -> False
}
}
"#
);
}
#[test]
fn module_access() {
assert_erl!(
(
"package",
"hero",
r#"
pub type Hero {
Hero(name: String)
}
pub const ironman = Hero("Tony Stark")
"#
),
r#"
import hero
pub fn main() {
let name = "Tony Stark"
case name {
n if n == hero.ironman.name -> True
_ -> False
}
}
"#
);
}
#[test]
fn module_nested_access() {
assert_erl!(
(
"package",
"hero",
r#"
pub type Person {
Person(name: String)
}
pub type Hero {
Hero(secret_identity: Person)
}
const bruce = Person("Bruce Wayne")
pub const batman = Hero(bruce)
"#
),
r#"
import hero
pub fn main() {
let name = "Bruce Wayne"
case name {
n if n == hero.batman.secret_identity.name -> True
_ -> False
}
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests/let_assert.rs | compiler-core/src/erlang/tests/let_assert.rs | use crate::assert_erl;
#[test]
fn one_var() {
// One var
assert_erl!(
r#"pub fn go() {
let assert Ok(y) = Ok(1)
y
}"#
);
}
#[test]
fn more_than_one_var() {
// More vars
assert_erl!(
r#"pub fn go(x) {
let assert [1, a, b, c] = x
[a, b, c]
}"#
);
}
#[test]
fn pattern_let() {
// Pattern::Let
assert_erl!(
r#"pub fn go(x) {
let assert [1 as a, b, c] = x
[a, b, c]
}"#
);
}
#[test]
fn variable_rewrites() {
// Following asserts use appropriate variable rewrites
assert_erl!(
r#"pub fn go() {
let assert Ok(y) = Ok(1)
let assert Ok(y) = Ok(1)
y
}"#
);
}
#[test]
fn message() {
assert_erl!(
r#"
pub fn unwrap_or_panic(value) {
let assert Ok(inner) = value as "Oops, there was an error"
inner
}
"#
);
}
#[test]
fn variable_message() {
assert_erl!(
r#"
pub fn expect(value, message) {
let assert Ok(inner) = value as message
inner
}
"#
);
}
#[test]
fn just_variable() {
assert_erl!(
r#"pub fn go() {
let assert x = Ok(1)
x
}"#
);
}
#[test]
fn tuple_pattern() {
assert_erl!(
r#"pub fn go() {
let assert #(a, b, c) = #(1, 2, 3)
a + b + c
}"#
);
}
#[test]
fn int_pattern() {
assert_erl!(
r#"pub fn go() {
let assert 1 = 2
}"#
);
}
#[test]
fn float_pattern() {
assert_erl!(
r#"pub fn go() {
let assert 1.5 = 5.1
}"#
);
}
#[test]
fn string_pattern() {
assert_erl!(
r#"pub fn go() {
let assert "Hello!" = "Hel" <> "lo!"
}"#
);
}
#[test]
fn assignment_pattern() {
assert_erl!(
r#"pub fn go() {
let assert 123 as x = 123
x
}"#
);
}
#[test]
fn discard_pattern() {
assert_erl!(
r#"pub fn go() {
let assert _ = 123
}"#
);
}
#[test]
fn list_pattern() {
assert_erl!(
r#"pub fn go() {
let assert [1, x, 3] = [1, 2, 3]
x
}"#
);
}
#[test]
fn list_pattern_with_multiple_variables() {
assert_erl!(
r#"pub fn go() {
let assert [a, b, c] = [1, 2, 3]
a + b + c
}"#
);
}
#[test]
fn constructor_pattern() {
assert_erl!(
r#"pub fn go() {
let assert Ok(x) = Error(Nil)
x
}"#
);
}
#[test]
fn constructor_pattern_with_multiple_variables() {
assert_erl!(
r#"
pub type Wibble {
Wibble(Int, Float)
}
pub fn go() {
let assert Wibble(x, 2.0 as y) = Wibble(1, 2.0)
x
}"#
);
}
#[test]
fn bit_array_pattern() {
assert_erl!(
r#"pub fn go() {
let assert <<a:2, b:3, c:3>> = <<123>>
a + b + c
}"#
);
}
#[test]
fn string_prefix_pattern() {
assert_erl!(
r#"pub fn go() {
let assert "Hello " <> name = "Hello John"
name
}"#
);
}
#[test]
fn string_prefix_pattern_with_prefix_binding() {
assert_erl!(
r#"pub fn go() {
let assert "Hello " as greeting <> name = "Hello John"
#(greeting, name)
}"#
);
}
#[test]
fn let_assert_at_end_of_block() {
assert_erl!(
r#"
pub fn go() {
let result = Ok(10)
let x = {
let assert Ok(_) = result
}
x
}"#
);
}
// https://github.com/gleam-lang/gleam/issues/4145
#[test]
fn reference_earlier_segment() {
assert_erl!(
"
pub fn main() {
let assert <<length, bytes:size(length)-unit(8)>> = <<3, 1, 2, 3>>
bytes
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/3375
#[test]
fn bit_array_assignment_int() {
assert_erl!(
"
pub fn main() {
let assert <<1 as a>> = <<1>>
a
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/3375
#[test]
fn bit_array_assignment_float() {
assert_erl!(
"
pub fn main() {
let assert <<3.14 as pi:float>> = <<3.14>>
pi
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/3375
#[test]
fn bit_array_assignment_string() {
assert_erl!(
r#"
pub fn main() {
let assert <<"Hello, world!" as message:utf8>> = <<"Hello, world!">>
message
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/3375
#[test]
fn bit_array_assignment_discard() {
assert_erl!(
r#"
pub fn main() {
let assert <<_ as number>> = <<10>>
number
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/4924
#[test]
fn let_assert_should_not_use_redefined_variable() {
assert_erl!(
r#"
fn split_once(x: String, y: String) -> Result(#(String, String), String) {
Ok(#(x, y))
}
pub fn main() {
let string = "Hello, world!"
let assert Ok(#(prefix, string)) = split_once(string, "\n")
as { "Failed to split: " <> string }
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests/panic.rs | compiler-core/src/erlang/tests/panic.rs | use crate::assert_erl;
#[test]
fn panic_as() {
assert_erl!(
r#"
pub fn main() {
panic as "wibble"
}
"#
);
}
#[test]
fn plain() {
assert_erl!(
r#"
pub fn main() {
panic
}
"#
);
}
#[test]
fn panic_as_function() {
assert_erl!(
r#"
pub fn retstring() {
"wibble"
}
pub fn main() {
panic as { retstring() <> "wobble" }
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2176
#[test]
fn piped() {
assert_erl!(
r#"
pub fn main() {
"lets"
|> panic
}
"#
);
}
#[test]
fn piped_chain() {
assert_erl!(
r#"
pub fn main() {
"lets"
|> panic as "pipe"
|> panic as "other panic"
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests/functions.rs | compiler-core/src/erlang/tests/functions.rs | use crate::assert_erl;
#[test]
fn function_as_value() {
assert_erl!(
r#"
fn other() {
Nil
}
pub fn main() {
other
}
"#
);
}
#[test]
fn nested_imported_function_as_value() {
assert_erl!(
("package", "some/other", "pub fn wibble() { Nil }"),
r#"
import some/other
pub fn main() {
other.wibble
}
"#
);
}
#[test]
fn nested_unqualified_imported_function_as_value() {
assert_erl!(
("package", "some/other", "pub fn wibble() { Nil }"),
r#"
import some/other.{wibble}
pub fn main() {
wibble
}
"#
);
}
#[test]
fn nested_aliased_imported_function_as_value() {
assert_erl!(
("package", "some/other", "pub fn wibble() { Nil }"),
r#"
import some/other.{wibble as wobble}
pub fn main() {
wobble
}
"#
);
}
#[test]
fn function_called() {
assert_erl!(
r#"
pub fn main() {
main()
}
"#
);
}
#[test]
fn nested_imported_function_called() {
assert_erl!(
("package", "some/other", "pub fn wibble() { Nil }"),
r#"
import some/other
pub fn main() {
other.wibble()
}
"#
);
}
#[test]
fn nested_unqualified_imported_function_called() {
assert_erl!(
("package", "some/other", "pub fn wibble() { Nil }"),
r#"
import some/other.{wibble}
pub fn main() {
wibble()
}
"#
);
}
#[test]
fn nested_aliased_imported_function_called() {
assert_erl!(
("package", "some/other", "pub fn wibble() { Nil }"),
r#"
import some/other.{wibble as wobble}
pub fn main() {
wobble()
}
"#
);
}
#[test]
fn labelled_argument_ordering() {
// https://github.com/gleam-lang/gleam/issues/3671
assert_erl!(
"
type A { A }
type B { B }
type C { C }
type D { D }
fn wibble(a a: A, b b: B, c c: C, d d: D) {
Nil
}
pub fn main() {
wibble(A, C, D, b: B)
wibble(A, C, D, b: B)
wibble(B, C, D, a: A)
wibble(B, C, a: A, d: D)
wibble(B, C, d: D, a: A)
wibble(B, D, a: A, c: C)
wibble(B, D, c: C, a: A)
wibble(C, D, b: B, a: A)
}
"
);
}
#[test]
fn unused_private_functions() {
assert_erl!(
r#"
pub fn main() -> Int {
used()
}
fn used() -> Int {
123
}
fn unused1() -> Int {
unused2()
}
fn unused2() -> Int {
used()
}
fn unused3() -> Int {
used()
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests/todo.rs | compiler-core/src/erlang/tests/todo.rs | use crate::assert_erl;
#[test]
fn plain() {
assert_erl!(
r#"
pub fn main() {
todo
}
"#
);
}
#[test]
fn todo_as() {
assert_erl!(
r#"
pub fn main() {
todo as "wibble"
}
"#
);
}
#[test]
fn named() {
assert_erl!(
r#"
pub fn main() {
todo as "testing"
}
"#
);
}
#[test]
fn todo_as_function() {
assert_erl!(
r#"
pub fn retstring() {
"wibble"
}
pub fn main() {
todo as { retstring() <> "wobble" }
}
"#
);
}
#[test]
fn piped() {
assert_erl!(
r#"
pub fn main() {
"lets"
|> todo as "pipe"
|> todo as "other todo"
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests/echo.rs | compiler-core/src/erlang/tests/echo.rs | use crate::assert_erl;
#[test]
pub fn echo_with_a_simple_expression() {
assert_erl!(
r#"
pub fn main() {
echo 1
}
"#
);
}
#[test]
pub fn echo_with_a_simple_expression_and_a_message() {
assert_erl!(
r#"
pub fn main() {
echo 1 as "hello!"
}
"#
);
}
#[test]
pub fn echo_with_complex_expression_as_a_message() {
assert_erl!(
r#"
pub fn main() {
echo 1 as case name() {
"Giacomo" -> "hello Jak!"
_ -> "hello!"
}
}
fn name() { "Giacomo" }
"#
);
}
#[test]
pub fn multiple_echos_inside_expression() {
assert_erl!(
r#"
pub fn main() {
echo 1
echo 2
}
"#
);
}
#[test]
pub fn echo_with_a_case_expression() {
assert_erl!(
r#"
pub fn main() {
echo case 1 {
_ -> 2
}
}
"#
);
}
#[test]
pub fn echo_with_a_panic() {
assert_erl!(
r#"
pub fn main() {
echo panic
}
"#
);
}
#[test]
pub fn echo_with_a_function_call() {
assert_erl!(
r#"
pub fn main() {
echo wibble(1, 2)
}
fn wibble(n: Int, m: Int) { n + m }
"#
);
}
#[test]
pub fn echo_with_a_function_call_and_a_message() {
assert_erl!(
r#"
pub fn main() {
echo wibble(1, 2) as message()
}
fn wibble(n: Int, m: Int) { n + m }
fn message() { "Hello!" }
"#
);
}
#[test]
pub fn echo_with_a_block() {
assert_erl!(
r#"
pub fn main() {
echo {
Nil
1
}
}
"#
);
}
#[test]
pub fn echo_in_a_pipeline() {
assert_erl!(
r#"
pub fn main() {
[1, 2, 3]
|> echo
|> wibble
}
pub fn wibble(n) { n }
"#
)
}
#[test]
pub fn echo_in_a_pipeline_with_message() {
assert_erl!(
r#"
pub fn main() {
[1, 2, 3]
|> echo as "message!!"
|> wibble
}
pub fn wibble(n) { n }
"#
)
}
#[test]
pub fn multiple_echos_in_a_pipeline() {
assert_erl!(
r#"
pub fn main() {
[1, 2, 3]
|> echo
|> wibble
|> echo
|> wibble
|> echo
}
pub fn wibble(n) { n }
"#
)
}
#[test]
pub fn pipeline_printed_by_echo_is_wrapped_in_begin_end_block() {
assert_erl!(
r#"
pub fn main() {
echo
123
|> wibble
|> wibble
}
pub fn wibble(n) { n }
"#
)
}
#[test]
pub fn record_update_printed_by_echo_is_wrapped_in_begin_end_block() {
assert_erl!(
r#"
pub type Wobble { Wobble(id: Int, name: String) }
pub fn main() {
let wobble = Wobble(1, "wobble")
echo Wobble(..wobble, id: 1)
}
"#
)
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests/type_params.rs | compiler-core/src/erlang/tests/type_params.rs | use crate::assert_erl;
#[test]
fn result_type_inferred_count_once() {
assert_erl!(
"
pub fn wibble() {
let assert Ok(_) = wobble()
}
pub type Wobble(a) {
Wobble
}
pub fn wobble() -> Result(a, Wobble(a)) {
todo
}
"
);
}
#[test]
fn result_type_count_once() {
assert_erl!(
"
pub fn wibble() -> Result(a, a) {
todo
}
"
);
}
#[test]
fn nested_result_type_count_once() {
assert_erl!(
"
pub fn wibble() -> Result(a, Result(a, b)) {
todo
}
"
);
}
#[test]
fn custom_type_nested_result_type_count_once() {
assert_erl!(
"
pub type Wibble(a) {
Oops
}
pub fn wibble() -> Result(a, Wibble(a)) {
todo
}
"
);
}
#[test]
fn tuple_type_params_count_twice() {
assert_erl!(
"
pub fn wibble() -> #(a, b) {
todo
}
"
);
}
#[test]
fn custom_type_named_args_count_once() {
assert_erl!(
"
pub type Wibble(a, b) {
Wibble(a, b)
}
pub fn wibble() -> Wibble(a, a) {
todo
}
"
);
}
#[test]
fn custom_type_nested_named_args_count_once() {
assert_erl!(
"
pub type Wibble(a, b) {
Wibble(a, b)
}
pub fn wibble() -> Wibble(a, Wibble(a, b)) {
todo
}
"
);
}
#[test]
fn custom_type_tuple_type_params_count_twice() {
assert_erl!(
"
pub type Wibble(a, b) {
Wibble(a, b)
}
pub fn wibble() -> #(a, Wibble(a, b)) {
todo
}
"
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests/pipes.rs | compiler-core/src/erlang/tests/pipes.rs | use crate::assert_erl;
#[test]
fn clever_pipe_rewriting() {
// a |> b
assert_erl!(
r#"
pub fn apply(f: fn(a) -> b, a: a) { a |> f }
"#
);
}
#[test]
fn clever_pipe_rewriting1() {
// a |> b(c)
assert_erl!(
r#"
pub fn apply(f: fn(a, Int) -> b, a: a) { a |> f(1) }
"#
);
}
// https://github.com/gleam-lang/gleam/issues/952
#[test]
fn block_expr_into_pipe() {
assert_erl!(
r#"fn id(a) { a }
pub fn main() {
{
let x = 1
x
}
|> id
}"#
);
}
#[test]
fn pipe_in_list() {
assert_erl!(
"pub fn x(f) {
[
1 |> f
]
}"
);
}
#[test]
fn pipe_in_tuple() {
assert_erl!(
"pub fn x(f) {
#(
1 |> f
)
}"
);
}
#[test]
fn pipe_in_case_subject() {
assert_erl!(
"pub fn x(f) {
case 1 |> f {
x -> x
}
}"
);
}
// https://github.com/gleam-lang/gleam/issues/1379
#[test]
fn pipe_in_record_update() {
assert_erl!(
"pub type X {
X(a: Int, b: Int)
}
fn id(x) {
x
}
pub fn main(x) {
X(..x, a: 1 |> id)
}"
);
}
// https://github.com/gleam-lang/gleam/issues/1385
#[test]
fn pipe_in_eq() {
assert_erl!(
"fn id(x) {
x
}
pub fn main() {
1 == 1 |> id
}"
);
}
// https://github.com/gleam-lang/gleam/issues/1863
#[test]
fn call_pipeline_result() {
assert_erl!(
r#"
pub fn main() {
{ 1 |> add }(1)
}
pub fn add(x) {
fn(y) { x + y }
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/1931
#[test]
fn pipe_in_call() {
assert_erl!(
r#"
pub fn main() {
123
|> two(
1 |> two(2),
_,
)
}
pub fn two(a, b) {
a
}
"#
);
}
#[test]
fn multiple_pipes() {
assert_erl!(
"
pub fn main() {
1 |> x |> x
2 |> x |> x
}
fn x(x) { x }
"
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests/conditional_compilation.rs | compiler-core/src/erlang/tests/conditional_compilation.rs | use crate::assert_erl;
#[test]
fn excluded_attribute_syntax() {
assert_erl!(
"@target(javascript)
pub fn main() { 1 }
"
);
}
#[test]
fn included_attribute_syntax() {
assert_erl!(
"@target(erlang)
pub fn main() { 1 }
"
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests/numbers.rs | compiler-core/src/erlang/tests/numbers.rs | use crate::assert_erl;
#[test]
fn numbers_with_underscores() {
assert_erl!(
r#"
pub fn main() {
100_000
100_000.00101
}
"#
);
}
#[test]
fn numbers_with_underscores1() {
assert_erl!(
r#"
const i = 100_000
const f = 100_000.00101
pub fn main() {
i
f
}
"#
);
}
#[test]
fn numbers_with_underscores2() {
assert_erl!(
r#"
pub fn main() {
let assert 100_000 = 1
let assert 100_000.00101 = 1.
1
}
"#
);
}
#[test]
fn numbers_with_scientific_notation() {
assert_erl!(
r#"
const i = 100.001e223
const j = -100.001e-223
pub fn main() {
i
j
}
"#
);
}
#[test]
fn int_negation() {
assert_erl!(
r#"
pub fn main() {
let a = 3
let b = -a
}
"#
);
}
#[test]
fn repeated_int_negation() {
assert_erl!(
r#"
pub fn main() {
let a = 3
let b = --a
}
"#
);
}
// https://github.com/gleam-lang/gleam/issues/2356
#[test]
fn zero_b_in_hex() {
assert_erl!(
r#"
pub fn main() {
0xffe0bb
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests/patterns.rs | compiler-core/src/erlang/tests/patterns.rs | use crate::assert_erl;
#[test]
fn alternative_patterns() {
// reassigning name in alternative patterns
assert_erl!(
r#"
pub fn main() {
let duplicate_name = 1
case 1 {
1 | 2 -> {
let duplicate_name = duplicate_name + 1
duplicate_name
}
_ -> 0
}
}"#
);
}
#[test]
fn alternative_patterns1() {
// Alternative patterns with a clause containing vars
assert_erl!(
r#"
pub fn main() {
case Ok(1) {
Ok(duplicate_name) | Error(duplicate_name) -> duplicate_name
}
}"#
);
}
#[test]
fn alternative_patterns2() {
// Alternative patterns with a guard clause containing vars
assert_erl!(
r#"
pub fn main() {
let duplicate_name = 1
case 1 {
1 | 2 if duplicate_name == 1 -> duplicate_name
_ -> 0
}
}"#
);
}
#[test]
fn alternative_patterns3() {
assert_erl!(
r#"
pub const constant = Ok(1)
pub fn main(arg) {
let _ = constant
case arg {
_ if arg == constant -> 1
_ -> 0
}
}
"#
);
}
#[test]
fn pattern_as() {
assert_erl!(
"pub fn a(x) {
case x {
Ok(1 as y) -> 1
_ -> 0
}
}"
);
}
#[test]
fn string_prefix_as_pattern_with_multiple_subjects() {
assert_erl!(
"pub fn a(x) {
case x, x {
_, \"a\" as a <> _ -> a
_, _ -> \"a\"
}
}"
);
}
#[test]
fn string_prefix_as_pattern_with_multiple_subjects_and_guard() {
assert_erl!(
"pub fn a(x) {
case x, x {
_, \"a\" as a <> rest if rest == \"a\" -> a
_, _ -> \"a\"
}
}"
);
}
#[test]
fn string_prefix_as_pattern_with_list() {
assert_erl!(
"pub fn a(x) {
case x {
[\"a\" as a <> _, \"b\" as b <> _] -> a <> b
_ -> \"\"
}
}"
);
}
#[test]
fn string_prefix_as_pattern_with_assertion() {
assert_erl!(
"pub fn a(x) {
let assert \"a\" as a <> rest = \"wibble\"
a
}"
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests/records.rs | compiler-core/src/erlang/tests/records.rs | use crate::assert_erl;
use crate::erlang::*;
use crate::type_;
#[test]
fn basic() {
insta::assert_snapshot!(record_definition(
"PetCat",
&[
("name", type_::tuple(vec![])),
("is_cute", type_::tuple(vec![]))
]
));
}
#[test]
fn reserve_words() {
// Reserved words are escaped in record names and fields
insta::assert_snapshot!(record_definition(
"div",
&[
("receive", type_::int()),
("catch", type_::tuple(vec![])),
("unreserved", type_::tuple(vec![]))
]
));
}
#[test]
fn type_vars() {
// Type vars are printed as `any()` because records don't support generics
insta::assert_snapshot!(record_definition(
"PetCat",
&[
("name", type_::generic_var(1)),
("is_cute", type_::unbound_var(1)),
("linked", type_::link(type_::int()))
]
));
}
#[test]
fn module_types() {
// Types are printed with module qualifiers
let module_name = "name".into();
insta::assert_snapshot!(record_definition(
"PetCat",
&[(
"name",
Arc::new(Type::Named {
publicity: Publicity::Public,
package: "package".into(),
module: module_name,
name: "my_type".into(),
arguments: vec![],
inferred_variant: None,
})
)]
));
}
#[test]
fn long_definition_formatting() {
// Long definition formatting
insta::assert_snapshot!(record_definition(
"PetCat",
&[
("name", type_::generic_var(1)),
("is_cute", type_::unbound_var(1)),
("linked", type_::link(type_::int())),
(
"whatever",
type_::list(type_::tuple(vec![
type_::nil(),
type_::list(type_::tuple(vec![type_::nil(), type_::nil(), type_::nil()])),
type_::nil(),
type_::list(type_::tuple(vec![type_::nil(), type_::nil(), type_::nil()])),
type_::nil(),
type_::list(type_::tuple(vec![type_::nil(), type_::nil(), type_::nil()])),
]))
),
]
));
}
#[test]
fn record_accessors() {
// We can use record accessors for types with only one constructor
assert_erl!(
r#"
pub type Person { Person(name: String, age: Int) }
pub fn get_age(person: Person) { person.age }
pub fn get_name(person: Person) { person.name }
"#
);
}
#[test]
fn record_accessor_multiple_variants() {
// We can access fields on custom types with multiple variants
assert_erl!(
"
pub type Person {
Teacher(name: String, title: String)
Student(name: String, age: Int)
}
pub fn get_name(person: Person) { person.name }"
);
}
#[test]
fn record_accessor_multiple_variants_positions_other_than_first() {
// We can access fields on custom types with multiple variants
// In positions other than the 1st field
assert_erl!(
"
pub type Person {
Teacher(name: String, age: Int, title: String)
Student(name: String, age: Int)
}
pub fn get_name(person: Person) { person.name }
pub fn get_age(person: Person) { person.age }"
);
}
#[test]
fn record_accessor_multiple_variants_parameterised_types() {
// We can access fields on custom types with multiple variants
// In positions other than the 1st field
assert_erl!(
"
pub type Person {
Teacher(name: String, age: List(Int), title: String)
Student(name: String, age: List(Int))
}
pub fn get_name(person: Person) { person.name }
pub fn get_age(person: Person) { person.age }"
);
}
#[test]
fn record_accessor_multiple_with_first_position_different_types() {
// We can access fields on custom types with multiple variants
// In positions other than the 1st field
assert_erl!(
"
pub type Person {
Teacher(name: Nil, age: Int)
Student(name: String, age: Int)
}
pub fn get_age(person: Person) { person.age }"
);
}
#[test]
fn record_spread() {
// Test binding to a record field with the spread operator
assert_erl!(
r#"
pub type Triple {
Triple(a: Int, b: Int, c: Int)
}
pub fn main() {
let triple = Triple(1,2,3)
let Triple(the_a, ..) = triple
the_a
}
"#
);
}
#[test]
fn record_spread1() {
// Test binding to a record field with the spread operator
// Test binding to a record field with the spread operator and a labelled argument
assert_erl!(
r#"
pub type Triple {
Triple(a: Int, b: Int, c: Int)
}
pub fn main() {
let triple = Triple(1,2,3)
let Triple(b: the_b, ..) = triple
the_b
}
"#
);
}
#[test]
fn record_spread2() {
// Test binding to a record field with the spread operator with both a labelled argument and a positional argument
assert_erl!(
r#"
pub type Triple {
Triple(a: Int, b: Int, c: Int)
}
pub fn main() {
let triple = Triple(1,2,3)
let Triple(the_a, c: the_c, ..) = triple
the_c
}
"#
);
}
#[test]
fn record_spread3() {
// Test binding to a record field with the spread operator in a match
assert_erl!(
r#"
pub type Triple {
Triple(a: Int, b: Int, c: Int)
}
pub fn main() {
let triple = Triple(1,2,3)
case triple {
Triple(b: the_b, ..) -> the_b
}
}
"#
);
}
#[test]
fn record_updates() {
// Record updates
assert_erl!(
r#"
pub type Person { Person(name: String, age: Int) }
pub fn main() {
let p = Person("Quinn", 27)
let new_p = Person(..p, age: 28)
new_p
}
"#
);
}
#[test]
fn record_updates1() {
// Record updates with field accesses
assert_erl!(
r#"
pub type Person { Person(name: String, age: Int) }
pub fn main() {
let p = Person("Quinn", 27)
let new_p = Person(..p, age: p.age + 1)
new_p
}
"#
);
}
#[test]
fn record_updates2() {
// Record updates with multiple fields
assert_erl!(
r#"
pub type Person { Person(name: String, age: Int) }
pub fn main() {
let p = Person("Quinn", 27)
let new_p = Person(..p, age: 28, name: "Riley")
new_p
}
"#
);
}
#[test]
fn record_updates3() {
// Record updates when record is returned from function
assert_erl!(
r#"
pub type Person { Person(name: String, age: Int) }
pub fn main() {
let new_p = Person(..return_person(), age: 28)
new_p
}
fn return_person() {
Person("Quinn", 27)
}
"#
);
}
#[test]
fn record_updates4() {
// Record updates when record is field on another record
assert_erl!(
r#"
pub type Car { Car(make: String, model: String, driver: Person) }
pub type Person { Person(name: String, age: Int) }
pub fn main() {
let car = Car(make: "Amphicar", model: "Model 770", driver: Person(name: "John Doe", age: 27))
let new_p = Person(..car.driver, age: 28)
new_p
}
"#
);
}
#[test]
fn record_constants() {
assert_erl!(
"pub type Test { A }
const some_test = A
pub fn a() { A }"
);
}
// https://github.com/gleam-lang/gleam/issues/1698
#[test]
fn pipe_update_subject() {
assert_erl!(
"pub type Thing {
Thing(a: Int, b: Int)
}
pub fn identity(x) { x }
pub fn main() {
let thing = Thing(1, 2)
Thing(..thing |> identity, b: 1000)
}"
);
}
// https://github.com/gleam-lang/gleam/issues/1698
#[test]
fn record_access_block() {
assert_erl!(
"pub type Thing {
Thing(a: Int, b: Int)
}
pub fn main() {
{
let thing = Thing(1, 2)
thing
}.a
}"
);
}
// https://github.com/gleam-lang/gleam/issues/1981
#[test]
fn imported_qualified_constructor_as_fn_name_escape() {
assert_erl!(
("other_package", "other_module", "pub type Let { Let(Int) }"),
"import other_module
pub fn main() {
other_module.Let
}"
);
}
#[test]
fn nested_record_update() {
assert_erl!(
"pub type Wibble {
Wibble(a: Int, b: Wobble, c: Int)
}
pub type Wobble {
Wobble(a: Int, b: Int)
}
pub fn main() {
let base = Wibble(1, Wobble(2, 3), 4)
Wibble(..base, b: Wobble(..base.b, b: 5))
}"
);
}
#[test]
fn nested_record_update_with_blocks() {
assert_erl!(
"pub type A { A(b: B) }
pub type B { B(c: C) }
pub type C { C(val: Int) }
pub fn main(a: A) {
A(..a, b: {
B(..a.b, c: {
C(..a.b.c, val: 0)
})
})
}"
)
}
#[test]
fn private_unused_records() {
assert_erl!(
"type A { A(inner: Int) }
type B { B(String) }
type C { C(Int) }
pub fn main(x: Int) -> Int {
let a = A(x)
a.inner
}
"
)
}
#[test]
fn const_record_update_generic_respecialization() {
assert_erl!(
"
pub type Box(a) {
Box(name: String, value: a)
}
pub const base = Box(\"score\", 50)
pub const updated = Box(..base, value: \"Hello\")
pub fn main() {
#(base, updated)
}
",
);
}
#[test]
fn record_update_with_unlabelled_fields() {
assert_erl!(
r#"
pub type Wibble {
Wibble(Int, Float, b: Bool, s: String)
}
pub fn main() {
let record = Wibble(1, 3.14, True, "Hello")
Wibble(..record, b: False)
}
"#
);
}
#[test]
fn constant_record_update_with_unlabelled_fields() {
assert_erl!(
r#"
pub type Wibble {
Wibble(Int, Float, b: Bool, s: String)
}
pub const record = Wibble(1, 3.14, True, "Hello")
pub const updated = Wibble(..record, b: False)
pub fn main() {
updated
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests/strings.rs | compiler-core/src/erlang/tests/strings.rs | use crate::assert_erl;
#[test]
fn unicode1() {
assert_erl!(
r#"
pub fn emoji() -> String {
"\u{1f600}"
}
"#,
);
}
#[test]
fn unicode2() {
assert_erl!(
r#"
pub fn y_with_dieresis() -> String {
"\u{0308}y"
}
"#,
);
}
#[test]
fn unicode_concat1() {
assert_erl!(
r#"
pub fn main(x) -> String {
x <> "\u{0308}"
}
"#,
);
}
#[test]
fn unicode_concat2() {
assert_erl!(
r#"
pub fn main(x) -> String {
x <> "\\u{0308}"
}
"#,
);
}
#[test]
fn unicode_concat3() {
assert_erl!(
r#"
pub fn main(x) -> String {
x <> "\\\u{0308}"
}
"#,
);
}
#[test]
fn not_unicode_escape_sequence() {
// '\u'-s must be converted to '\x' in the Erlang codegen.
// but '\\u'-s mustn't.
assert_erl!(
r#"
pub fn not_unicode_escape_sequence() -> String {
"\\u{03a9}"
}
"#,
);
}
#[test]
fn not_unicode_escape_sequence2() {
assert_erl!(
r#"
pub fn not_unicode_escape_sequence() -> String {
"\\\\u{03a9}"
}
"#,
);
}
#[test]
fn unicode3() {
assert_erl!(
r#"
pub fn y_with_dieresis_with_slash() -> String {
"\\\u{0308}y"
}
"#,
);
}
#[test]
fn unicode_escape_sequence_6_digits() {
assert_erl!(
r#"
pub fn unicode_escape_sequence_6_digits() -> String {
"\u{10abcd}"
}
"#,
);
}
#[test]
fn ascii_as_unicode_escape_sequence() {
assert_erl!(
r#"
pub fn y() -> String {
"\u{79}"
}
"#,
)
}
#[test]
fn concat() {
assert_erl!(
r#"
pub fn go(x, y) {
x <> y
}
"#,
);
}
#[test]
fn concat_3_variables() {
assert_erl!(
r#"
pub fn go(x, y, z) {
x <> y <> z
}
"#,
);
}
#[test]
fn string_prefix() {
assert_erl!(
r#"
pub fn go(x) {
case x {
"Hello, " <> name -> name
_ -> "Unknown"
}
}
"#,
);
}
#[test]
fn string_prefix_assignment() {
assert_erl!(
r#"
pub fn go(x) {
case x {
"Hello, " as greeting <> name -> greeting
_ -> "Unknown"
}
}
"#,
)
}
#[test]
fn string_prefix_assignment_with_guard() {
assert_erl!(
r#"
pub fn go(x) {
case x {
"Hello, " as greeting <> name if name == "Dude" -> greeting <> "Mate"
"Hello, " as greeting <> name -> greeting
_ -> "Unknown"
}
}
"#,
)
}
// https://github.com/gleam-lang/gleam/issues/3126
#[test]
fn string_prefix_assignment_with_escape_sequences() {
assert_erl!(
r#"
pub fn go(x) {
let _ = case x {
"\f" as start <> rest -> "test"
"\n" as start <> rest -> "test"
"\r" as start <> rest -> "test"
"\t" as start <> rest -> "test"
"\"" as start <> rest -> "test"
"\\" as start <> rest -> "test"
"\f \n \r \t \" \\" as start <> rest -> "control chars with prefix assignment"
"\u{9}" as start <> rest -> "test"
"\u{000009}" as start <> rest -> "test"
"\u{21}" as start <> rest -> "test"
"\u{100}" as start <> rest -> "test"
"\u{1000}" as start <> rest -> "test"
"\u{1F600}" as start <> rest -> "test"
"\u{1f600}" as start <> rest -> "test"
"\u{01F600}" as start <> rest -> "test"
"\u{01f600}" as start <> rest -> "test"
"\u{9} \u{000009} \u{21} \u{100} \u{1000} \u{1F600} \u{01F600}" as start <> rest -> "test"
_ -> "Unknown"
}
}
"#,
)
}
#[test]
fn string_prefix_with_escape_sequences() {
assert_erl!(
r#"
pub fn go(x) {
let _ = case x {
"\f" <> rest -> "test"
"\n" <> rest -> "test"
"\r" <> rest -> "test"
"\t" <> rest -> "test"
"\"" <> rest -> "test"
"\\" <> rest -> "test"
"\f \n \r \t \" \\" <> rest -> "control chars with prefix assignment"
"\u{9}" <> rest -> "test"
"\u{000009}" <> rest -> "test"
"\u{21}" <> rest -> "test"
"\u{100}" <> rest -> "test"
"\u{1000}" <> rest -> "test"
"\u{1F600}" <> rest -> "test"
"\u{1f600}" <> rest -> "test"
"\u{01F600}" <> rest -> "test"
"\u{01f600}" <> rest -> "test"
"\u{9} \u{000009} \u{21} \u{100} \u{1000} \u{1F600} \u{01F600}" <> rest -> "test"
_ -> "Unknown"
}
}
"#,
)
}
#[test]
fn string_prefix_assignment_not_unicode_escape_sequence() {
assert_erl!(
r#"
pub fn go(x) {
let _ = case x {
"\\u{9}" as start <> rest -> "test"
"\\u{000009}" as start <> rest -> "test"
"\\u{21}" as start <> rest -> "test"
"\\u{100}" as start <> rest -> "test"
"\\u{1000}" as start <> rest -> "test"
"\\u{1F600}" as start <> rest -> "test"
"\\u{1f600}" as start <> rest -> "test"
"\\u{01F600}" as start <> rest -> "test"
"\\u{01f600}" as start <> rest -> "test"
"\\u{9} \\u{000009} \\u{21} \\u{100} \\u{1000} \\u{1F600} \\u{01F600}" as start <> rest -> "test"
_ -> "Unknown"
}
}
"#,
)
}
#[test]
fn string_prefix_not_unicode_escape_sequence() {
assert_erl!(
r#"
pub fn go(x) {
let _ = case x {
"\\u{9}" <> rest -> "test"
"\\u{000009}" <> rest -> "test"
"\\u{21}" <> rest -> "test"
"\\u{100}" <> rest -> "test"
"\\u{1000}" <> rest -> "test"
"\\u{1F600}" <> rest -> "test"
"\\u{1f600}" <> rest -> "test"
"\\u{01F600}" <> rest -> "test"
"\\u{01f600}" <> rest -> "test"
"\\u{9} \\u{000009} \\u{21} \\u{100} \\u{1000} \\u{1F600} \\u{01F600}" <> rest -> "test"
_ -> "Unknown"
}
}
"#,
)
}
// https://github.com/gleam-lang/gleam/issues/2471
#[test]
fn string_prefix_assignment_with_multiple_subjects() {
assert_erl!(
r#"
pub fn go(x) {
case x {
"1" as digit <> _ | "2" as digit <> _ -> digit
_ -> "Unknown"
}
}
"#,
)
}
#[test]
fn string_prefix_shadowing() {
assert_erl!(
r#"
pub fn go(x) {
case x {
"Hello, " as x <> name -> x
_ -> "Unknown"
}
}
"#,
)
}
#[test]
fn rest_variable_rewriting() {
// This test checks that the variable on the right hand side of <> has
// it's name written correctly when it shadows an existing variable
assert_erl!(
r#"
pub fn go(x) {
case x {
"Hello, " <> x -> x
_ -> "Unknown"
}
}
"#,
);
}
#[test]
fn discard_concat_rest_pattern() {
// We can discard the right hand side, it parses and type checks ok
assert_erl!(
r#"
pub fn go(x) {
case x {
"Hello, " <> _ -> Nil
_ -> Nil
}
}
"#,
);
}
#[test]
fn string_of_number_concat() {
assert_erl!(
r#"
pub fn go(x) {
x <> "1"
}
"#,
);
}
#[test]
fn concat_function_call() {
assert_erl!(
r#"
fn x() {
""
}
pub fn go() {
x() <> x()
}
"#,
);
}
#[test]
fn concat_constant() {
assert_erl!(
r#"
const a = "Hello, "
const b = "Joe!"
pub fn go() {
a <> b
}
"#,
);
}
#[test]
fn concat_constant_fn() {
assert_erl!(
r#"
const cs = s
fn s() {
"s"
}
pub fn go() {
cs() <> cs()
}
"#,
);
}
#[test]
fn pipe_concat() {
assert_erl!(
r#"
fn id(x) {
x
}
pub fn main() {
{ "" |> id } <> { "" |> id }
}
"#,
);
}
#[test]
fn assert_string_prefix() {
assert_erl!(
r#"
pub fn main(x) {
let assert "m-" <> rest = x
rest
}
"#,
);
}
#[test]
fn assert_string_prefix_discar() {
assert_erl!(
r#"
pub fn main(x) {
let assert "m-" <> _ = x
}
"#,
);
}
#[test]
fn assert_const_concat() {
assert_erl!(
r#"
const cute = "cute"
const cute_bee = cute <> "bee"
pub fn main() {
cute_bee
}
"#
);
}
#[test]
fn assert_const_concat_many_strings() {
assert_erl!(
r#"
const big_concat = "a" <> "b" <> "c" <> "d" <> "e" <> "f" <> "g" <> "h" <> "i" <> "j" <> "k" <> "l" <> "m" <> "n" <> "o" <> "p" <> "q" <> "r" <> "s" <> "t" <> "u" <> "v" <> "w" <> "x" <> "y" <> "z"
pub fn main() {
big_concat
}
"#
);
}
#[test]
fn assert_const_concat_many_strings_in_list() {
assert_erl!(
r#"
const big_concat_list = ["a" <> "b" <> "c" <> "d" <> "e" <> "f" <> "g" <> "h" <> "i" <> "j" <> "k" <> "l" <> "m" <> "n" <> "o" <> "p" <> "q" <> "r" <> "s" <> "t" <> "u" <> "v" <> "w" <> "x" <> "y" <> "z"]
pub fn main() {
big_concat_list
}
"#
);
}
#[test]
fn assert_const_concat_other_const_concat() {
assert_erl!(
r#"
const cute_bee = "cute" <> "bee"
const cute_cute_bee_buzz = cute_bee <> "buzz"
pub fn main() {
cute_cute_bee_buzz
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests/custom_types.rs | compiler-core/src/erlang/tests/custom_types.rs | use crate::assert_erl;
#[test]
fn phantom() {
assert_erl!("pub type Map(k, v)");
}
#[test]
fn annotated_external_type() {
assert_erl!(
r#"
@external(erlang, "gleam_stdlib", "dict")
pub type Dict(key, value)
"#
);
}
#[test]
fn annotated_external_type_used_in_function() {
assert_erl!(
r#"
@external(erlang, "gleam_stdlib", "dict")
pub type Dict(key, value)
@external(erlang, "maps", "get")
pub fn get(dict: Dict(key, value), key: key) -> Result(value, Nil)
"#
);
}
// https://github.com/gleam-lang/gleam/issues/5127
#[test]
fn unused_opaque_constructor_is_generated_correctly() {
assert_erl!(
"
type Wibble {
Wibble
}
pub opaque type Wobble {
Wobble(Wibble)
}
"
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests/bit_arrays.rs | compiler-core/src/erlang/tests/bit_arrays.rs | use crate::assert_erl;
#[test]
fn bit_array() {
assert_erl!(
r#"pub fn main() {
let a = 1
let simple = <<1, a>>
let complex = <<4:int-big, 5.0:little-float, 6:native-int>>
let assert <<7:2, 8:size(3), b:bytes-size(4)>> = <<1>>
let assert <<c:8-unit(1), d:bytes-size(2)-unit(2)>> = <<1>>
simple
}
"#
);
}
#[test]
fn bit_array_float() {
assert_erl!(
r#"pub fn main() {
let b = 16
let floats = <<1.0:16-float, 5.0:float-32, 6.0:float-64-little, 1.0:float-size(b)>>
let assert <<1.0:16-float, 5.0:float-32, 6.0:float-64-little, 1.0:float-size(b)>> = floats
}"#
);
}
#[test]
fn bit_array1() {
assert_erl!(
r#"pub fn x() { 2 }
pub fn main() {
let a = -1
let b = <<a:unit(2)-size(a * 2), a:size(3 + x())-unit(1)>>
b
}
"#
);
}
#[test]
fn bit_array2() {
assert_erl!(
r#"pub fn main() {
let a = 1
let assert <<b, 1>> = <<1, a>>
b
}
"#
);
}
#[test]
fn bit_array3() {
assert_erl!(
r#"pub fn main() {
let a = <<"test":utf8>>
let assert <<b:utf8_codepoint, "st":utf8>> = a
b
}
"#
);
}
#[test]
fn bit_array4() {
assert_erl!(
r#"fn x() { 1 }
pub fn main() {
let a = <<x():int>>
a
}
"#
);
}
#[test]
fn bit_array5() {
assert_erl!(
r#"const bit_size = 8
pub fn main() {
let a = <<10:size(bit_size)>>
a
}
"#
);
}
#[test]
fn bit_array_discard() {
// https://github.com/gleam-lang/gleam/issues/704
assert_erl!(
r#"
pub fn bit_array_discard(x) -> Bool {
case x {
<<_:utf8, rest:bytes>> -> True
_ -> False
}
}
"#
);
}
#[test]
fn bit_array_discard1() {
assert_erl!(
r#"
pub fn bit_array_discard(x) -> Bool {
case x {
<<_discardme:utf8, rest:bytes>> -> True
_ -> False
}
}
"#
);
}
#[test]
fn bit_array_declare_and_use_var() {
assert_erl!(
r#"pub fn go(x) {
let assert <<name_size:8, name:bytes-size(name_size)>> = x
name
}"#
);
}
// https://github.com/gleam-lang/gleam/issues/3050
#[test]
fn unicode_bit_array_1() {
assert_erl!(
r#"
pub fn main() {
let emoji = "\u{1F600}"
let arr = <<emoji:utf8>>
}"#
);
}
#[test]
fn unicode_bit_array_2() {
assert_erl!(
r#"
pub fn main() {
let arr = <<"\u{1F600}":utf8>>
}"#
);
}
#[test]
fn bit_array_literal_string_constant_is_treated_as_utf8() {
assert_erl!(
r#"
const a = <<"hello", " ", "world">>
pub fn main() { a }
"#
);
}
#[test]
fn bit_array_literal_string_is_treated_as_utf8() {
assert_erl!(
r#"
pub fn main() {
<<"hello", " ", "world">>
}"#
);
}
#[test]
fn bit_array_literal_string_pattern_is_treated_as_utf8() {
assert_erl!(
r#"
pub fn main() {
case <<>> {
<<"a", "b", _:bits>> -> 1
_ -> 2
}
}"#
);
}
#[test]
fn discard_utf8_pattern() {
assert_erl!(
r#"
pub fn main() {
let assert <<_:utf8, rest:bits>> = <<>>
}"#
);
}
// https://github.com/gleam-lang/gleam/issues/3944
#[test]
fn pipe_size_segment() {
assert_erl!(
"
pub fn main() {
<<0xAE:size(5 |> identity)>>
}
fn identity(x) {
x
}
"
);
}
#[test]
fn utf16_codepoint_little_endian() {
assert_erl!(
"
pub fn go(codepoint) {
<<codepoint:utf16_codepoint-little>>
}
"
);
}
#[test]
fn utf32_codepoint_little_endian() {
assert_erl!(
"
pub fn go(codepoint) {
<<codepoint:utf32_codepoint-little>>
}
"
);
}
#[test]
fn pattern_match_utf16_codepoint_little_endian() {
assert_erl!(
"
pub fn go(x) {
let assert <<codepoint:utf16_codepoint-little>> = x
codepoint
}
"
);
}
#[test]
fn pattern_match_utf32_codepoint_little_endian() {
assert_erl!(
"
pub fn go(x) {
let assert <<codepoint:utf32_codepoint-little>> = x
codepoint
}
"
);
}
#[test]
fn operator_in_pattern_size() {
assert_erl!(
"
pub fn main() {
let assert <<len, payload:size(len * 8 - 8)>> = <<>>
}
"
);
}
#[test]
fn operator_in_pattern_size2() {
assert_erl!(
"
pub fn main() {
let assert <<len, payload:size(len / 8 - 1)>> = <<>>
}
"
);
}
#[test]
fn operator_in_pattern_size3() {
assert_erl!(
"
pub fn main() {
let additional = 10
let assert <<len, payload:size(len + additional * 8)>> = <<>>
}
"
);
}
#[test]
fn block_in_pattern_size() {
assert_erl!(
"
pub fn main() {
let assert <<len, payload:size({ len - 1 } * 8)>> = <<>>
}
"
);
}
#[test]
fn non_byte_aligned_size_calculation() {
assert_erl!(
"
pub fn main() {
case <<>> {
<<a:1, b:3, c:size(b - 2)>> -> c + b
_ -> 1
}
}
"
);
}
#[test]
fn unicode_character_encoding_in_bit_array_pattern_segment() {
assert_erl!(
r#"
pub fn main() -> Nil {
let wibble = <<"\u{00A9}wibble":utf8>>
let _bits = case wibble {
<<"\u{00A9}":utf8, rest: bits>> -> rest
_ -> wibble
}
Nil
}
"#
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/src/erlang/tests/inlining.rs | compiler-core/src/erlang/tests/inlining.rs | use crate::assert_erl;
const BOOL_MODULE: &str = "
pub fn guard(
when condition: Bool,
return value: a,
otherwise callback: fn() -> a,
) -> a {
case condition {
True -> value
False -> callback()
}
}
pub fn lazy_guard(
when condition: Bool,
return consequence: fn() -> a,
otherwise alternative: fn() -> a,
) -> a {
case condition {
True -> consequence()
False -> alternative()
}
}
";
const RESULT_MODULE: &str = "
pub fn try(result: Result(a, e), apply f: fn(a) -> Result(b, e)) -> Result(b, e) {
case result {
Ok(value) -> f(value)
Error(error) -> Error(error)
}
}
pub fn map(over result: Result(a, e), with f: fn(a) -> b) -> Result(b, e) {
case result {
Ok(value) -> Ok(f(value))
Error(error) -> Error(error)
}
}
";
#[test]
fn inline_higher_order_function() {
assert_erl!(
("gleam_stdlib", "gleam/result", RESULT_MODULE),
"
import gleam/result
pub fn main() {
result.map(over: Ok(10), with: double)
}
fn double(x) { x + x }
"
);
}
#[test]
fn inline_higher_order_function_with_capture() {
assert_erl!(
("gleam_stdlib", "gleam/result", RESULT_MODULE),
"
import gleam/result
pub fn main() {
result.try(Ok(10), divide(_, 2))
}
fn divide(a: Int, b: Int) -> Result(Int, Nil) {
case a % b {
0 -> Ok(a / b)
_ -> Error(Nil)
}
}
"
);
}
#[test]
fn inline_higher_order_function_anonymous() {
assert_erl!(
("gleam_stdlib", "gleam/result", RESULT_MODULE),
"
import gleam/result
pub fn main() {
result.try(Ok(10), fn(value) {
Ok({ value + 2 } * 4)
})
}
"
);
}
#[test]
fn inline_function_which_calls_other_function() {
// This function calls `result.try`, meaning this must be inlined twice to
// achieve the desired result.
assert_erl!(
("gleam_stdlib", "gleam/result", RESULT_MODULE),
(
"gleam_stdlib",
"testing",
"
import gleam/result.{try}
pub fn always_inline(result, f) -> Result(b, e) {
try(result, f)
}
"
),
"
import testing
pub fn main() {
testing.always_inline(Ok(10), Error)
}
"
);
}
#[test]
fn inline_function_with_use() {
assert_erl!(
("gleam_stdlib", "gleam/bool", BOOL_MODULE),
"
import gleam/bool
pub fn divide(a, b) {
use <- bool.guard(when: b == 0, return: 0)
a / b
}
"
);
}
#[test]
fn inline_function_with_use_and_anonymous() {
assert_erl!(
("gleam_stdlib", "gleam/bool", BOOL_MODULE),
r#"
import gleam/bool
pub fn divide(a, b) {
use <- bool.lazy_guard(b == 0, fn() { panic as "Cannot divide by 0" })
a / b
}
"#
);
}
#[test]
fn inline_function_with_use_becomes_tail_recursive() {
assert_erl!(
("gleam_stdlib", "gleam/bool", BOOL_MODULE),
"
import gleam/bool
pub fn count(from: Int, to: Int) -> Int {
use <- bool.guard(when: from >= to, return: from)
echo from
count(from + 1, to)
}
"
);
}
#[test]
fn do_not_inline_parameters_used_more_than_once() {
// Since the `something` parameter is used more than once in the body of the
// function, it should not be inlined, and should be assigned once at the
// beginning of the function.
assert_erl!(
(
"gleam_stdlib",
"testing",
"
pub fn always_inline(something) {
case something {
True -> something
False -> False
}
}
"
),
"
import testing
pub fn main() {
testing.always_inline(True)
}
"
);
}
#[test]
fn do_not_inline_parameters_that_have_side_effects() {
assert_erl!(
("gleam_stdlib", "gleam/result", RESULT_MODULE),
r#"
import gleam/result
pub fn main() {
result.map(Ok(10), do_side_effects())
}
fn do_side_effects() {
let function = fn(x) { x + 1 }
panic as "Side effects"
function
}
"#
);
}
#[test]
fn inline_anonymous_function_call() {
assert_erl!(
"
pub fn main() {
fn(a, b) { #(a, b) }(42, False)
}
"
);
}
#[test]
fn inline_anonymous_function_in_pipe() {
assert_erl!(
"
pub fn main() {
1 |> fn(x) { x + 1 } |> fn(y) { y * y }
}
"
);
}
#[test]
fn inline_function_capture_in_pipe() {
// The function capture is desugared to an anonymous function, so it should
// be turned into a direct call to `add`
assert_erl!(
"
pub fn main() {
1 |> add(4, _)
}
fn add(a, b) { a + b }
"
);
}
#[test]
fn inlining_works_through_blocks() {
assert_erl!(
"
pub fn main() {
{ fn(x) { Ok(x + 1) } }(41)
}
"
);
}
#[test]
fn blocks_get_preserved_when_needed() {
assert_erl!(
"
pub fn main() {
{ 4 |> make_adder }(6)
}
fn make_adder(a) {
fn(b) { a + b }
}
"
);
}
#[test]
fn blocks_get_preserved_when_needed2() {
assert_erl!(
"
pub fn main() {
fn(x) { 1 + x }(2) * 3
}
"
);
}
#[test]
fn parameters_from_nested_functions_are_correctly_inlined() {
assert_erl!(
("gleam_stdlib", "gleam/result", RESULT_MODULE),
"
import gleam/result
pub fn halve_all(a, b, c) {
use x <- result.try(divide(a, 2))
use y <- result.try(divide(b, 2))
use z <- result.map(divide(c, 2))
#(x, y, z)
}
fn divide(a, b) {
case a % b {
0 -> Ok(a / b)
_ -> Error(Nil)
}
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/4852
#[test]
fn inlining_works_properly_with_record_updates() {
assert_erl!(
("gleam_stdlib", "gleam/result", RESULT_MODULE),
"
import gleam/result
pub type Wibble {
Wibble(a: Int, b: Int)
}
pub fn main() {
let w = Wibble(1, 2)
use b <- result.map(Ok(3))
Wibble(..w, b:)
}
"
);
}
// https://github.com/gleam-lang/gleam/issues/4877
#[test]
fn inline_shadowed_variable() {
assert_erl!(
"
pub fn main() {
let a = 10
let b = 20
fn(x) {
let a = 7
x + a
}(a + b)
a
}
"
);
}
#[test]
fn inline_variable_shadowing_parameter() {
assert_erl!(
"
pub fn sum(a, b) {
fn(x) {
let a = 7
x + a
}(a + b)
a
}
"
);
}
#[test]
fn inline_shadowed_variable_nested() {
assert_erl!(
"
pub fn sum(a, b) {
fn(x) {
let a = 7
fn(y) {
let a = 10
y - a
}(x + a)
a
}(a + b)
a
}
"
);
}
#[test]
fn inline_variable_shadowed_in_case_pattern() {
assert_erl!(
"
pub fn sum() {
let a = 10
let b = 20
fn(x) {
case 7, 8 {
a, b -> a + b + x
}
}(a + b)
a + b
}
"
);
}
#[test]
fn inline_variable_shadowing_case_pattern() {
assert_erl!(
"
pub fn sum() {
case 1, 2 {
a, b -> fn(x) {
let a = 7
x + a
}(a + b)
}
}
"
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/compiler-core/generated/schema_capnp.rs | compiler-core/generated/schema_capnp.rs | // @generated by the capnpc-rust plugin to the Cap'n Proto schema compiler.
// DO NOT EDIT.
// source: schema.capnp
pub mod property { /* Value */
#[derive(Copy, Clone)]
pub struct Owned<Value> {
_phantom: ::core::marker::PhantomData<Value>
}
impl <Value> ::capnp::introspect::Introspect for Owned <Value> where Value: ::capnp::traits::Owned { fn introspect() -> ::capnp::introspect::Type { ::capnp::introspect::TypeVariant::Struct(::capnp::introspect::RawBrandedStructSchema { generic: &_private::RAW_SCHEMA, field_types: _private::get_field_types::<Value>, annotation_types: _private::get_annotation_types::<Value> }).into() } }
impl <Value> ::capnp::traits::Owned for Owned <Value> where Value: ::capnp::traits::Owned { type Reader<'a> = Reader<'a, Value>; type Builder<'a> = Builder<'a, Value>; }
impl <Value> ::capnp::traits::OwnedStruct for Owned <Value> where Value: ::capnp::traits::Owned { type Reader<'a> = Reader<'a, Value>; type Builder<'a> = Builder<'a, Value>; }
impl <Value> ::capnp::traits::Pipelined for Owned<Value> where Value: ::capnp::traits::Owned { type Pipeline = Pipeline<Value>; }
pub struct Reader<'a,Value> where Value: ::capnp::traits::Owned {
reader: ::capnp::private::layout::StructReader<'a>,
_phantom: ::core::marker::PhantomData<Value>
}
impl <Value> ::core::marker::Copy for Reader<'_,Value> where Value: ::capnp::traits::Owned {}
impl <Value> ::core::clone::Clone for Reader<'_,Value> where Value: ::capnp::traits::Owned {
fn clone(&self) -> Self { *self }
}
impl <Value> ::capnp::traits::HasTypeId for Reader<'_,Value> where Value: ::capnp::traits::Owned {
const TYPE_ID: u64 = _private::TYPE_ID;
}
impl <'a,Value> ::core::convert::From<::capnp::private::layout::StructReader<'a>> for Reader<'a,Value> where Value: ::capnp::traits::Owned {
fn from(reader: ::capnp::private::layout::StructReader<'a>) -> Self {
Self { reader, _phantom: ::core::marker::PhantomData, }
}
}
impl <'a,Value> ::core::convert::From<Reader<'a,Value>> for ::capnp::dynamic_value::Reader<'a> where Value: ::capnp::traits::Owned {
fn from(reader: Reader<'a,Value>) -> Self {
Self::Struct(::capnp::dynamic_struct::Reader::new(reader.reader, ::capnp::schema::StructSchema::new(::capnp::introspect::RawBrandedStructSchema { generic: &_private::RAW_SCHEMA, field_types: _private::get_field_types::<Value>, annotation_types: _private::get_annotation_types::<Value>})))
}
}
impl <Value> ::core::fmt::Debug for Reader<'_,Value> where Value: ::capnp::traits::Owned {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::result::Result<(), ::core::fmt::Error> {
core::fmt::Debug::fmt(&::core::convert::Into::<::capnp::dynamic_value::Reader<'_>>::into(*self), f)
}
}
impl <'a,Value> ::capnp::traits::FromPointerReader<'a> for Reader<'a,Value> where Value: ::capnp::traits::Owned {
fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>, default: ::core::option::Option<&'a [::capnp::Word]>) -> ::capnp::Result<Self> {
::core::result::Result::Ok(reader.get_struct(default)?.into())
}
}
impl <'a,Value> ::capnp::traits::IntoInternalStructReader<'a> for Reader<'a,Value> where Value: ::capnp::traits::Owned {
fn into_internal_struct_reader(self) -> ::capnp::private::layout::StructReader<'a> {
self.reader
}
}
impl <'a,Value> ::capnp::traits::Imbue<'a> for Reader<'a,Value> where Value: ::capnp::traits::Owned {
fn imbue(&mut self, cap_table: &'a ::capnp::private::layout::CapTable) {
self.reader.imbue(::capnp::private::layout::CapTableReader::Plain(cap_table))
}
}
impl <'a,Value> Reader<'a,Value> where Value: ::capnp::traits::Owned {
pub fn reborrow(&self) -> Reader<'_,Value> {
Self { .. *self }
}
pub fn total_size(&self) -> ::capnp::Result<::capnp::MessageSize> {
self.reader.total_size()
}
#[inline]
pub fn get_key(self) -> ::capnp::Result<::capnp::text::Reader<'a>> {
::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(0), ::core::option::Option::None)
}
#[inline]
pub fn has_key(&self) -> bool {
!self.reader.get_pointer_field(0).is_null()
}
#[inline]
pub fn get_value(self) -> ::capnp::Result<<Value as ::capnp::traits::Owned>::Reader<'a>> {
::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(1), ::core::option::Option::None)
}
#[inline]
pub fn has_value(&self) -> bool {
!self.reader.get_pointer_field(1).is_null()
}
}
pub struct Builder<'a,Value> where Value: ::capnp::traits::Owned {
builder: ::capnp::private::layout::StructBuilder<'a>,
_phantom: ::core::marker::PhantomData<Value>
}
impl <Value> ::capnp::traits::HasStructSize for Builder<'_,Value> where Value: ::capnp::traits::Owned {
const STRUCT_SIZE: ::capnp::private::layout::StructSize = ::capnp::private::layout::StructSize { data: 0, pointers: 2 };
}
impl <Value> ::capnp::traits::HasTypeId for Builder<'_,Value> where Value: ::capnp::traits::Owned {
const TYPE_ID: u64 = _private::TYPE_ID;
}
impl <'a,Value> ::core::convert::From<::capnp::private::layout::StructBuilder<'a>> for Builder<'a,Value> where Value: ::capnp::traits::Owned {
fn from(builder: ::capnp::private::layout::StructBuilder<'a>) -> Self {
Self { builder, _phantom: ::core::marker::PhantomData, }
}
}
impl <'a,Value> ::core::convert::From<Builder<'a,Value>> for ::capnp::dynamic_value::Builder<'a> where Value: ::capnp::traits::Owned {
fn from(builder: Builder<'a,Value>) -> Self {
Self::Struct(::capnp::dynamic_struct::Builder::new(builder.builder, ::capnp::schema::StructSchema::new(::capnp::introspect::RawBrandedStructSchema { generic: &_private::RAW_SCHEMA, field_types: _private::get_field_types::<Value>, annotation_types: _private::get_annotation_types::<Value>})))
}
}
impl <'a,Value> ::capnp::traits::ImbueMut<'a> for Builder<'a,Value> where Value: ::capnp::traits::Owned {
fn imbue_mut(&mut self, cap_table: &'a mut ::capnp::private::layout::CapTable) {
self.builder.imbue(::capnp::private::layout::CapTableBuilder::Plain(cap_table))
}
}
impl <'a,Value> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a,Value> where Value: ::capnp::traits::Owned {
fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size: u32) -> Self {
builder.init_struct(<Self as ::capnp::traits::HasStructSize>::STRUCT_SIZE).into()
}
fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, default: ::core::option::Option<&'a [::capnp::Word]>) -> ::capnp::Result<Self> {
::core::result::Result::Ok(builder.get_struct(<Self as ::capnp::traits::HasStructSize>::STRUCT_SIZE, default)?.into())
}
}
impl <Value> ::capnp::traits::SetterInput<Owned<Value>> for Reader<'_,Value> where Value: ::capnp::traits::Owned {
fn set_pointer_builder(mut pointer: ::capnp::private::layout::PointerBuilder<'_>, value: Self, canonicalize: bool) -> ::capnp::Result<()> { pointer.set_struct(&value.reader, canonicalize) }
}
impl <'a,Value> Builder<'a,Value> where Value: ::capnp::traits::Owned {
pub fn into_reader(self) -> Reader<'a,Value> {
self.builder.into_reader().into()
}
pub fn reborrow(&mut self) -> Builder<'_,Value> {
Builder { builder: self.builder.reborrow(), ..*self }
}
pub fn reborrow_as_reader(&self) -> Reader<'_,Value> {
self.builder.as_reader().into()
}
pub fn total_size(&self) -> ::capnp::Result<::capnp::MessageSize> {
self.builder.as_reader().total_size()
}
#[inline]
pub fn get_key(self) -> ::capnp::Result<::capnp::text::Builder<'a>> {
::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(0), ::core::option::Option::None)
}
#[inline]
pub fn set_key(&mut self, value: impl ::capnp::traits::SetterInput<::capnp::text::Owned>) {
::capnp::traits::SetterInput::set_pointer_builder(self.builder.reborrow().get_pointer_field(0), value, false).unwrap()
}
#[inline]
pub fn init_key(self, size: u32) -> ::capnp::text::Builder<'a> {
self.builder.get_pointer_field(0).init_text(size)
}
#[inline]
pub fn has_key(&self) -> bool {
!self.builder.is_pointer_field_null(0)
}
#[inline]
pub fn get_value(self) -> ::capnp::Result<<Value as ::capnp::traits::Owned>::Builder<'a>> {
::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(1), ::core::option::Option::None)
}
#[inline]
pub fn initn_value(self, length: u32) -> <Value as ::capnp::traits::Owned>::Builder<'a> {
::capnp::any_pointer::Builder::new(self.builder.get_pointer_field(1)).initn_as(length)
}
#[inline]
pub fn set_value(&mut self, value: impl ::capnp::traits::SetterInput<Value>) -> ::capnp::Result<()> {
::capnp::traits::SetterInput::set_pointer_builder(self.builder.reborrow().get_pointer_field(1), value, false)
}
#[inline]
pub fn init_value(self, ) -> <Value as ::capnp::traits::Owned>::Builder<'a> {
::capnp::any_pointer::Builder::new(self.builder.get_pointer_field(1)).init_as()
}
#[inline]
pub fn has_value(&self) -> bool {
!self.builder.is_pointer_field_null(1)
}
}
pub struct Pipeline<Value> {
_typeless: ::capnp::any_pointer::Pipeline,
_phantom: ::core::marker::PhantomData<Value>
}
impl<Value> ::capnp::capability::FromTypelessPipeline for Pipeline<Value> {
fn new(typeless: ::capnp::any_pointer::Pipeline) -> Self {
Self { _typeless: typeless, _phantom: ::core::marker::PhantomData, }
}
}
impl<Value> Pipeline<Value> where Value: ::capnp::traits::Pipelined, <Value as ::capnp::traits::Pipelined>::Pipeline: ::capnp::capability::FromTypelessPipeline {
pub fn get_value(&self) -> <Value as ::capnp::traits::Pipelined>::Pipeline {
::capnp::capability::FromTypelessPipeline::new(self._typeless.get_pointer_field(1))
}
}
mod _private {
pub static ENCODED_NODE: [::capnp::Word; 50] = [
::capnp::word(0, 0, 0, 0, 5, 0, 6, 0),
::capnp::word(106, 29, 126, 201, 93, 118, 154, 200),
::capnp::word(13, 0, 0, 0, 1, 0, 0, 0),
::capnp::word(190, 237, 188, 253, 156, 169, 51, 181),
::capnp::word(2, 0, 7, 0, 0, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 1, 0, 0, 0),
::capnp::word(21, 0, 0, 0, 178, 0, 0, 0),
::capnp::word(29, 0, 0, 0, 7, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(25, 0, 0, 0, 119, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(141, 0, 0, 0, 15, 0, 0, 0),
::capnp::word(115, 99, 104, 101, 109, 97, 46, 99),
::capnp::word(97, 112, 110, 112, 58, 80, 114, 111),
::capnp::word(112, 101, 114, 116, 121, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 1, 0, 1, 0),
::capnp::word(8, 0, 0, 0, 3, 0, 4, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(0, 0, 1, 0, 0, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(41, 0, 0, 0, 34, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(36, 0, 0, 0, 3, 0, 1, 0),
::capnp::word(48, 0, 0, 0, 2, 0, 1, 0),
::capnp::word(1, 0, 0, 0, 1, 0, 0, 0),
::capnp::word(0, 0, 1, 0, 1, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(45, 0, 0, 0, 50, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(40, 0, 0, 0, 3, 0, 1, 0),
::capnp::word(52, 0, 0, 0, 2, 0, 1, 0),
::capnp::word(107, 101, 121, 0, 0, 0, 0, 0),
::capnp::word(12, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(12, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(118, 97, 108, 117, 101, 0, 0, 0),
::capnp::word(18, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(1, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(106, 29, 126, 201, 93, 118, 154, 200),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(18, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(4, 0, 0, 0, 0, 0, 1, 0),
::capnp::word(1, 0, 0, 0, 50, 0, 0, 0),
::capnp::word(86, 97, 108, 117, 101, 0, 0, 0),
];
pub fn get_field_types<Value>(index: u16) -> ::capnp::introspect::Type where Value: ::capnp::traits::Owned {
match index {
0 => <::capnp::text::Owned as ::capnp::introspect::Introspect>::introspect(),
1 => <Value as ::capnp::introspect::Introspect>::introspect(),
_ => ::capnp::introspect::panic_invalid_field_index(index),
}
}
pub fn get_annotation_types<Value>(child_index: Option<u16>, index: u32) -> ::capnp::introspect::Type where Value: ::capnp::traits::Owned {
::capnp::introspect::panic_invalid_annotation_indices(child_index, index)
}
pub static RAW_SCHEMA: ::capnp::introspect::RawStructSchema = ::capnp::introspect::RawStructSchema {
encoded_node: &ENCODED_NODE,
nonunion_members: NONUNION_MEMBERS,
members_by_discriminant: MEMBERS_BY_DISCRIMINANT,
members_by_name: MEMBERS_BY_NAME,
};
pub static NONUNION_MEMBERS : &[u16] = &[0,1];
pub static MEMBERS_BY_DISCRIMINANT : &[u16] = &[];
pub static MEMBERS_BY_NAME : &[u16] = &[0,1];
pub const TYPE_ID: u64 = 0xc89a_765d_c97e_1d6a;
}
}
pub mod option { /* Value */
pub use self::Which::{None,Some};
#[derive(Copy, Clone)]
pub struct Owned<Value> {
_phantom: ::core::marker::PhantomData<Value>
}
impl <Value> ::capnp::introspect::Introspect for Owned <Value> where Value: ::capnp::traits::Owned { fn introspect() -> ::capnp::introspect::Type { ::capnp::introspect::TypeVariant::Struct(::capnp::introspect::RawBrandedStructSchema { generic: &_private::RAW_SCHEMA, field_types: _private::get_field_types::<Value>, annotation_types: _private::get_annotation_types::<Value> }).into() } }
impl <Value> ::capnp::traits::Owned for Owned <Value> where Value: ::capnp::traits::Owned { type Reader<'a> = Reader<'a, Value>; type Builder<'a> = Builder<'a, Value>; }
impl <Value> ::capnp::traits::OwnedStruct for Owned <Value> where Value: ::capnp::traits::Owned { type Reader<'a> = Reader<'a, Value>; type Builder<'a> = Builder<'a, Value>; }
impl <Value> ::capnp::traits::Pipelined for Owned<Value> where Value: ::capnp::traits::Owned { type Pipeline = Pipeline<Value>; }
pub struct Reader<'a,Value> where Value: ::capnp::traits::Owned {
reader: ::capnp::private::layout::StructReader<'a>,
_phantom: ::core::marker::PhantomData<Value>
}
impl <Value> ::core::marker::Copy for Reader<'_,Value> where Value: ::capnp::traits::Owned {}
impl <Value> ::core::clone::Clone for Reader<'_,Value> where Value: ::capnp::traits::Owned {
fn clone(&self) -> Self { *self }
}
impl <Value> ::capnp::traits::HasTypeId for Reader<'_,Value> where Value: ::capnp::traits::Owned {
const TYPE_ID: u64 = _private::TYPE_ID;
}
impl <'a,Value> ::core::convert::From<::capnp::private::layout::StructReader<'a>> for Reader<'a,Value> where Value: ::capnp::traits::Owned {
fn from(reader: ::capnp::private::layout::StructReader<'a>) -> Self {
Self { reader, _phantom: ::core::marker::PhantomData, }
}
}
impl <'a,Value> ::core::convert::From<Reader<'a,Value>> for ::capnp::dynamic_value::Reader<'a> where Value: ::capnp::traits::Owned {
fn from(reader: Reader<'a,Value>) -> Self {
Self::Struct(::capnp::dynamic_struct::Reader::new(reader.reader, ::capnp::schema::StructSchema::new(::capnp::introspect::RawBrandedStructSchema { generic: &_private::RAW_SCHEMA, field_types: _private::get_field_types::<Value>, annotation_types: _private::get_annotation_types::<Value>})))
}
}
impl <Value> ::core::fmt::Debug for Reader<'_,Value> where Value: ::capnp::traits::Owned {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::result::Result<(), ::core::fmt::Error> {
core::fmt::Debug::fmt(&::core::convert::Into::<::capnp::dynamic_value::Reader<'_>>::into(*self), f)
}
}
impl <'a,Value> ::capnp::traits::FromPointerReader<'a> for Reader<'a,Value> where Value: ::capnp::traits::Owned {
fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>, default: ::core::option::Option<&'a [::capnp::Word]>) -> ::capnp::Result<Self> {
::core::result::Result::Ok(reader.get_struct(default)?.into())
}
}
impl <'a,Value> ::capnp::traits::IntoInternalStructReader<'a> for Reader<'a,Value> where Value: ::capnp::traits::Owned {
fn into_internal_struct_reader(self) -> ::capnp::private::layout::StructReader<'a> {
self.reader
}
}
impl <'a,Value> ::capnp::traits::Imbue<'a> for Reader<'a,Value> where Value: ::capnp::traits::Owned {
fn imbue(&mut self, cap_table: &'a ::capnp::private::layout::CapTable) {
self.reader.imbue(::capnp::private::layout::CapTableReader::Plain(cap_table))
}
}
impl <'a,Value> Reader<'a,Value> where Value: ::capnp::traits::Owned {
pub fn reborrow(&self) -> Reader<'_,Value> {
Self { .. *self }
}
pub fn total_size(&self) -> ::capnp::Result<::capnp::MessageSize> {
self.reader.total_size()
}
#[inline]
pub fn has_some(&self) -> bool {
if self.reader.get_data_field::<u16>(0) != 1 { return false; }
!self.reader.get_pointer_field(0).is_null()
}
#[inline]
pub fn which(self) -> ::core::result::Result<WhichReader<'a,Value>, ::capnp::NotInSchema> {
match self.reader.get_data_field::<u16>(0) {
0 => {
::core::result::Result::Ok(None(
()
))
}
1 => {
::core::result::Result::Ok(Some(
::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(0), ::core::option::Option::None)
))
}
x => ::core::result::Result::Err(::capnp::NotInSchema(x))
}
}
}
pub struct Builder<'a,Value> where Value: ::capnp::traits::Owned {
builder: ::capnp::private::layout::StructBuilder<'a>,
_phantom: ::core::marker::PhantomData<Value>
}
impl <Value> ::capnp::traits::HasStructSize for Builder<'_,Value> where Value: ::capnp::traits::Owned {
const STRUCT_SIZE: ::capnp::private::layout::StructSize = ::capnp::private::layout::StructSize { data: 1, pointers: 1 };
}
impl <Value> ::capnp::traits::HasTypeId for Builder<'_,Value> where Value: ::capnp::traits::Owned {
const TYPE_ID: u64 = _private::TYPE_ID;
}
impl <'a,Value> ::core::convert::From<::capnp::private::layout::StructBuilder<'a>> for Builder<'a,Value> where Value: ::capnp::traits::Owned {
fn from(builder: ::capnp::private::layout::StructBuilder<'a>) -> Self {
Self { builder, _phantom: ::core::marker::PhantomData, }
}
}
impl <'a,Value> ::core::convert::From<Builder<'a,Value>> for ::capnp::dynamic_value::Builder<'a> where Value: ::capnp::traits::Owned {
fn from(builder: Builder<'a,Value>) -> Self {
Self::Struct(::capnp::dynamic_struct::Builder::new(builder.builder, ::capnp::schema::StructSchema::new(::capnp::introspect::RawBrandedStructSchema { generic: &_private::RAW_SCHEMA, field_types: _private::get_field_types::<Value>, annotation_types: _private::get_annotation_types::<Value>})))
}
}
impl <'a,Value> ::capnp::traits::ImbueMut<'a> for Builder<'a,Value> where Value: ::capnp::traits::Owned {
fn imbue_mut(&mut self, cap_table: &'a mut ::capnp::private::layout::CapTable) {
self.builder.imbue(::capnp::private::layout::CapTableBuilder::Plain(cap_table))
}
}
impl <'a,Value> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a,Value> where Value: ::capnp::traits::Owned {
fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size: u32) -> Self {
builder.init_struct(<Self as ::capnp::traits::HasStructSize>::STRUCT_SIZE).into()
}
fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, default: ::core::option::Option<&'a [::capnp::Word]>) -> ::capnp::Result<Self> {
::core::result::Result::Ok(builder.get_struct(<Self as ::capnp::traits::HasStructSize>::STRUCT_SIZE, default)?.into())
}
}
impl <Value> ::capnp::traits::SetterInput<Owned<Value>> for Reader<'_,Value> where Value: ::capnp::traits::Owned {
fn set_pointer_builder(mut pointer: ::capnp::private::layout::PointerBuilder<'_>, value: Self, canonicalize: bool) -> ::capnp::Result<()> { pointer.set_struct(&value.reader, canonicalize) }
}
impl <'a,Value> Builder<'a,Value> where Value: ::capnp::traits::Owned {
pub fn into_reader(self) -> Reader<'a,Value> {
self.builder.into_reader().into()
}
pub fn reborrow(&mut self) -> Builder<'_,Value> {
Builder { builder: self.builder.reborrow(), ..*self }
}
pub fn reborrow_as_reader(&self) -> Reader<'_,Value> {
self.builder.as_reader().into()
}
pub fn total_size(&self) -> ::capnp::Result<::capnp::MessageSize> {
self.builder.as_reader().total_size()
}
#[inline]
pub fn set_none(&mut self, _value: ()) {
self.builder.set_data_field::<u16>(0, 0);
}
#[inline]
pub fn initn_some(self, length: u32) -> <Value as ::capnp::traits::Owned>::Builder<'a> {
self.builder.set_data_field::<u16>(0, 1);
::capnp::any_pointer::Builder::new(self.builder.get_pointer_field(0)).initn_as(length)
}
#[inline]
pub fn set_some(&mut self, value: impl ::capnp::traits::SetterInput<Value>) -> ::capnp::Result<()> {
self.builder.set_data_field::<u16>(0, 1);
::capnp::traits::SetterInput::set_pointer_builder(self.builder.reborrow().get_pointer_field(0), value, false)
}
#[inline]
pub fn init_some(self, ) -> <Value as ::capnp::traits::Owned>::Builder<'a> {
self.builder.set_data_field::<u16>(0, 1);
::capnp::any_pointer::Builder::new(self.builder.get_pointer_field(0)).init_as()
}
#[inline]
pub fn has_some(&self) -> bool {
if self.builder.get_data_field::<u16>(0) != 1 { return false; }
!self.builder.is_pointer_field_null(0)
}
#[inline]
pub fn which(self) -> ::core::result::Result<WhichBuilder<'a,Value>, ::capnp::NotInSchema> {
match self.builder.get_data_field::<u16>(0) {
0 => {
::core::result::Result::Ok(None(
()
))
}
1 => {
::core::result::Result::Ok(Some(
::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(0), ::core::option::Option::None)
))
}
x => ::core::result::Result::Err(::capnp::NotInSchema(x))
}
}
}
pub struct Pipeline<Value> {
_typeless: ::capnp::any_pointer::Pipeline,
_phantom: ::core::marker::PhantomData<Value>
}
impl<Value> ::capnp::capability::FromTypelessPipeline for Pipeline<Value> {
fn new(typeless: ::capnp::any_pointer::Pipeline) -> Self {
Self { _typeless: typeless, _phantom: ::core::marker::PhantomData, }
}
}
impl<Value> Pipeline<Value> where Value: ::capnp::traits::Pipelined, <Value as ::capnp::traits::Pipelined>::Pipeline: ::capnp::capability::FromTypelessPipeline {
}
mod _private {
pub static ENCODED_NODE: [::capnp::Word; 50] = [
::capnp::word(0, 0, 0, 0, 5, 0, 6, 0),
::capnp::word(253, 203, 85, 217, 186, 138, 221, 238),
::capnp::word(13, 0, 0, 0, 1, 0, 1, 0),
::capnp::word(190, 237, 188, 253, 156, 169, 51, 181),
::capnp::word(1, 0, 7, 0, 0, 0, 2, 0),
::capnp::word(0, 0, 0, 0, 1, 0, 0, 0),
::capnp::word(21, 0, 0, 0, 162, 0, 0, 0),
::capnp::word(29, 0, 0, 0, 7, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(25, 0, 0, 0, 119, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(141, 0, 0, 0, 15, 0, 0, 0),
::capnp::word(115, 99, 104, 101, 109, 97, 46, 99),
::capnp::word(97, 112, 110, 112, 58, 79, 112, 116),
::capnp::word(105, 111, 110, 0, 0, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 1, 0, 1, 0),
::capnp::word(8, 0, 0, 0, 3, 0, 4, 0),
::capnp::word(0, 0, 255, 255, 0, 0, 0, 0),
::capnp::word(0, 0, 1, 0, 0, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(41, 0, 0, 0, 42, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(36, 0, 0, 0, 3, 0, 1, 0),
::capnp::word(48, 0, 0, 0, 2, 0, 1, 0),
::capnp::word(1, 0, 254, 255, 0, 0, 0, 0),
::capnp::word(0, 0, 1, 0, 1, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(45, 0, 0, 0, 42, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(40, 0, 0, 0, 3, 0, 1, 0),
::capnp::word(52, 0, 0, 0, 2, 0, 1, 0),
::capnp::word(110, 111, 110, 101, 0, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(115, 111, 109, 101, 0, 0, 0, 0),
::capnp::word(18, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(1, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(253, 203, 85, 217, 186, 138, 221, 238),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(18, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(0, 0, 0, 0, 0, 0, 0, 0),
::capnp::word(4, 0, 0, 0, 0, 0, 1, 0),
::capnp::word(1, 0, 0, 0, 50, 0, 0, 0),
::capnp::word(86, 97, 108, 117, 101, 0, 0, 0),
];
pub fn get_field_types<Value>(index: u16) -> ::capnp::introspect::Type where Value: ::capnp::traits::Owned {
match index {
0 => <() as ::capnp::introspect::Introspect>::introspect(),
1 => <Value as ::capnp::introspect::Introspect>::introspect(),
_ => ::capnp::introspect::panic_invalid_field_index(index),
}
}
pub fn get_annotation_types<Value>(child_index: Option<u16>, index: u32) -> ::capnp::introspect::Type where Value: ::capnp::traits::Owned {
::capnp::introspect::panic_invalid_annotation_indices(child_index, index)
}
pub static RAW_SCHEMA: ::capnp::introspect::RawStructSchema = ::capnp::introspect::RawStructSchema {
encoded_node: &ENCODED_NODE,
nonunion_members: NONUNION_MEMBERS,
members_by_discriminant: MEMBERS_BY_DISCRIMINANT,
members_by_name: MEMBERS_BY_NAME,
};
pub static NONUNION_MEMBERS : &[u16] = &[];
pub static MEMBERS_BY_DISCRIMINANT : &[u16] = &[0,1];
pub static MEMBERS_BY_NAME : &[u16] = &[0,1];
pub const TYPE_ID: u64 = 0xeedd_8aba_d955_cbfd;
}
pub enum Which<A0> {
None(()),
Some(A0),
}
pub type WhichReader<'a,Value> = Which<::capnp::Result<<Value as ::capnp::traits::Owned>::Reader<'a>>>;
pub type WhichBuilder<'a,Value> = Which<::capnp::Result<<Value as ::capnp::traits::Owned>::Builder<'a>>>;
}
pub mod module {
#[derive(Copy, Clone)]
pub struct Owned(());
impl ::capnp::introspect::Introspect for Owned { fn introspect() -> ::capnp::introspect::Type { ::capnp::introspect::TypeVariant::Struct(::capnp::introspect::RawBrandedStructSchema { generic: &_private::RAW_SCHEMA, field_types: _private::get_field_types, annotation_types: _private::get_annotation_types }).into() } }
impl ::capnp::traits::Owned for Owned { type Reader<'a> = Reader<'a>; type Builder<'a> = Builder<'a>; }
impl ::capnp::traits::OwnedStruct for Owned { type Reader<'a> = Reader<'a>; type Builder<'a> = Builder<'a>; }
impl ::capnp::traits::Pipelined for Owned { type Pipeline = Pipeline; }
pub struct Reader<'a> { reader: ::capnp::private::layout::StructReader<'a> }
impl <> ::core::marker::Copy for Reader<'_,> {}
impl <> ::core::clone::Clone for Reader<'_,> {
fn clone(&self) -> Self { *self }
}
impl <> ::capnp::traits::HasTypeId for Reader<'_,> {
const TYPE_ID: u64 = _private::TYPE_ID;
}
impl <'a,> ::core::convert::From<::capnp::private::layout::StructReader<'a>> for Reader<'a,> {
fn from(reader: ::capnp::private::layout::StructReader<'a>) -> Self {
Self { reader, }
}
}
impl <'a,> ::core::convert::From<Reader<'a,>> for ::capnp::dynamic_value::Reader<'a> {
fn from(reader: Reader<'a,>) -> Self {
Self::Struct(::capnp::dynamic_struct::Reader::new(reader.reader, ::capnp::schema::StructSchema::new(::capnp::introspect::RawBrandedStructSchema { generic: &_private::RAW_SCHEMA, field_types: _private::get_field_types::<>, annotation_types: _private::get_annotation_types::<>})))
}
}
impl <> ::core::fmt::Debug for Reader<'_,> {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::result::Result<(), ::core::fmt::Error> {
core::fmt::Debug::fmt(&::core::convert::Into::<::capnp::dynamic_value::Reader<'_>>::into(*self), f)
}
}
impl <'a,> ::capnp::traits::FromPointerReader<'a> for Reader<'a,> {
fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>, default: ::core::option::Option<&'a [::capnp::Word]>) -> ::capnp::Result<Self> {
::core::result::Result::Ok(reader.get_struct(default)?.into())
}
}
impl <'a,> ::capnp::traits::IntoInternalStructReader<'a> for Reader<'a,> {
fn into_internal_struct_reader(self) -> ::capnp::private::layout::StructReader<'a> {
self.reader
}
}
impl <'a,> ::capnp::traits::Imbue<'a> for Reader<'a,> {
fn imbue(&mut self, cap_table: &'a ::capnp::private::layout::CapTable) {
self.reader.imbue(::capnp::private::layout::CapTableReader::Plain(cap_table))
}
}
impl <'a,> Reader<'a,> {
pub fn reborrow(&self) -> Reader<'_,> {
Self { .. *self }
}
pub fn total_size(&self) -> ::capnp::Result<::capnp::MessageSize> {
self.reader.total_size()
}
#[inline]
pub fn get_name(self) -> ::capnp::Result<::capnp::text::Reader<'a>> {
::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(0), ::core::option::Option::None)
}
#[inline]
pub fn has_name(&self) -> bool {
!self.reader.get_pointer_field(0).is_null()
}
#[inline]
pub fn get_types(self) -> ::capnp::Result<::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned<crate::schema_capnp::type_constructor::Owned>>> {
::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(1), ::core::option::Option::None)
}
#[inline]
pub fn has_types(&self) -> bool {
!self.reader.get_pointer_field(1).is_null()
}
#[inline]
pub fn get_values(self) -> ::capnp::Result<::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned<crate::schema_capnp::value_constructor::Owned>>> {
::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(2), ::core::option::Option::None)
}
#[inline]
pub fn has_values(&self) -> bool {
!self.reader.get_pointer_field(2).is_null()
}
#[inline]
pub fn get_accessors(self) -> ::capnp::Result<::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned<crate::schema_capnp::accessors_map::Owned>>> {
::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(3), ::core::option::Option::None)
}
#[inline]
pub fn has_accessors(&self) -> bool {
!self.reader.get_pointer_field(3).is_null()
}
#[inline]
pub fn get_package(self) -> ::capnp::Result<::capnp::text::Reader<'a>> {
::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(4), ::core::option::Option::None)
}
#[inline]
pub fn has_package(&self) -> bool {
!self.reader.get_pointer_field(4).is_null()
}
#[inline]
pub fn get_types_constructors(self) -> ::capnp::Result<::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned<crate::schema_capnp::types_variant_constructors::Owned>>> {
::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(5), ::core::option::Option::None)
}
#[inline]
pub fn has_types_constructors(&self) -> bool {
!self.reader.get_pointer_field(5).is_null()
}
#[inline]
pub fn get_line_numbers(self) -> ::capnp::Result<crate::schema_capnp::line_numbers::Reader<'a>> {
::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(6), ::core::option::Option::None)
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | true |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/test-package-compiler/build.rs | test-package-compiler/build.rs | use std::path::PathBuf;
pub fn main() {
println!("cargo:rerun-if-changed=cases");
let mut module = "//! This file is generated by build.rs
//! Do not edit it directly, instead add new test cases to ./cases
"
.to_string();
let cases = PathBuf::from("./cases");
let mut names: Vec<_> = std::fs::read_dir(&cases)
.unwrap()
.map(|entry| entry.unwrap().file_name().into_string().unwrap())
.collect();
names.sort();
for name in names {
let path = cases.join(&name);
let path = path.to_str().unwrap().replace('\\', "/");
module.push_str(&format!(
r#"
#[rustfmt::skip]
#[test]
fn {name}() {{
let output = crate::prepare("{path}");
insta::assert_snapshot!(
"{name}",
output,
"{path}",
);
}}
"#
));
}
let out = PathBuf::from("./src/generated_tests.rs");
std::fs::write(out, module).unwrap();
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/test-package-compiler/src/lib.rs | test-package-compiler/src/lib.rs | #[cfg(test)]
mod generated_tests;
use camino::Utf8PathBuf;
use gleam_core::{
build::{
ErlangAppCodegenConfiguration, Mode, NullTelemetry, Outcome, StaleTracker, Target,
TargetCodegenConfiguration,
},
config::PackageConfig,
io::{FileSystemReader, FileSystemWriter},
warning::{VectorWarningEmitterIO, WarningEmitter},
};
use std::{
collections::{HashMap, HashSet},
rc::Rc,
};
pub fn prepare(path: &str) -> String {
let root = Utf8PathBuf::from(path).canonicalize_utf8().unwrap();
let toml = std::fs::read_to_string(root.join("gleam.toml")).unwrap();
let config: PackageConfig = toml::from_str(&toml).unwrap();
let target = match config.target {
Target::Erlang => TargetCodegenConfiguration::Erlang {
app_file: Some(ErlangAppCodegenConfiguration {
include_dev_deps: true,
package_name_overrides: HashMap::new(),
}),
},
Target::JavaScript => TargetCodegenConfiguration::JavaScript {
emit_typescript_definitions: config.javascript.typescript_declarations,
prelude_location: Utf8PathBuf::from("../prelude.mjs"),
},
};
let ids = gleam_core::uid::UniqueIdGenerator::new();
let mut modules = im::HashMap::new();
let warnings = VectorWarningEmitterIO::default();
let warning_emitter = WarningEmitter::new(Rc::new(warnings.clone()));
let filesystem = test_helpers_rs::to_in_memory_filesystem(&root);
let initial_files = filesystem.files();
let root = Utf8PathBuf::from("");
let out = Utf8PathBuf::from("/out/lib/the_package");
let lib = Utf8PathBuf::from("/out/lib");
let mut compiler = gleam_core::build::PackageCompiler::new(
&config,
Mode::Dev,
&root,
&out,
&lib,
&target,
ids,
filesystem.clone(),
);
compiler.write_entrypoint = false;
compiler.write_metadata = true;
compiler.compile_beam_bytecode = false;
compiler.copy_native_files = false;
let result = compiler.compile(
&warning_emitter,
&mut modules,
&mut im::HashMap::new(),
&mut StaleTracker::default(),
&mut HashSet::new(),
&NullTelemetry,
);
match result {
Outcome::Ok(_) => {
for path in initial_files {
if filesystem.is_file(&path) {
filesystem.delete_file(&path).unwrap();
}
}
let files = filesystem.into_contents();
let warnings = warnings.take();
test_helpers_rs::TestCompileOutput { files, warnings }.as_overview_text()
}
Outcome::TotalFailure(error) | Outcome::PartialFailure(_, error) => {
test_helpers_rs::normalise_diagnostic(&error.pretty_string())
}
}
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
gleam-lang/gleam | https://github.com/gleam-lang/gleam/blob/f424547f02e621f1c5f28749786e05eda7feb098/test-package-compiler/src/generated_tests.rs | test-package-compiler/src/generated_tests.rs | //! This file is generated by build.rs
//! Do not edit it directly, instead add new test cases to ./cases
#[rustfmt::skip]
#[test]
fn alias_unqualified_import() {
let output = crate::prepare("./cases/alias_unqualified_import");
insta::assert_snapshot!(
"alias_unqualified_import",
output,
"./cases/alias_unqualified_import",
);
}
#[rustfmt::skip]
#[test]
fn dev_importing_test() {
let output = crate::prepare("./cases/dev_importing_test");
insta::assert_snapshot!(
"dev_importing_test",
output,
"./cases/dev_importing_test",
);
}
#[rustfmt::skip]
#[test]
fn duplicate_module() {
let output = crate::prepare("./cases/duplicate_module");
insta::assert_snapshot!(
"duplicate_module",
output,
"./cases/duplicate_module",
);
}
#[rustfmt::skip]
#[test]
fn duplicate_module_dev() {
let output = crate::prepare("./cases/duplicate_module_dev");
insta::assert_snapshot!(
"duplicate_module_dev",
output,
"./cases/duplicate_module_dev",
);
}
#[rustfmt::skip]
#[test]
fn duplicate_module_test_dev() {
let output = crate::prepare("./cases/duplicate_module_test_dev");
insta::assert_snapshot!(
"duplicate_module_test_dev",
output,
"./cases/duplicate_module_test_dev",
);
}
#[rustfmt::skip]
#[test]
fn empty_module_warning() {
let output = crate::prepare("./cases/empty_module_warning");
insta::assert_snapshot!(
"empty_module_warning",
output,
"./cases/empty_module_warning",
);
}
#[rustfmt::skip]
#[test]
fn erlang_app_generation() {
let output = crate::prepare("./cases/erlang_app_generation");
insta::assert_snapshot!(
"erlang_app_generation",
output,
"./cases/erlang_app_generation",
);
}
#[rustfmt::skip]
#[test]
fn erlang_app_generation_with_argument() {
let output = crate::prepare("./cases/erlang_app_generation_with_argument");
insta::assert_snapshot!(
"erlang_app_generation_with_argument",
output,
"./cases/erlang_app_generation_with_argument",
);
}
#[rustfmt::skip]
#[test]
fn erlang_bug_752() {
let output = crate::prepare("./cases/erlang_bug_752");
insta::assert_snapshot!(
"erlang_bug_752",
output,
"./cases/erlang_bug_752",
);
}
#[rustfmt::skip]
#[test]
fn erlang_empty() {
let output = crate::prepare("./cases/erlang_empty");
insta::assert_snapshot!(
"erlang_empty",
output,
"./cases/erlang_empty",
);
}
#[rustfmt::skip]
#[test]
fn erlang_escape_names() {
let output = crate::prepare("./cases/erlang_escape_names");
insta::assert_snapshot!(
"erlang_escape_names",
output,
"./cases/erlang_escape_names",
);
}
#[rustfmt::skip]
#[test]
fn erlang_import() {
let output = crate::prepare("./cases/erlang_import");
insta::assert_snapshot!(
"erlang_import",
output,
"./cases/erlang_import",
);
}
#[rustfmt::skip]
#[test]
fn erlang_import_shadowing_prelude() {
let output = crate::prepare("./cases/erlang_import_shadowing_prelude");
insta::assert_snapshot!(
"erlang_import_shadowing_prelude",
output,
"./cases/erlang_import_shadowing_prelude",
);
}
#[rustfmt::skip]
#[test]
fn erlang_nested() {
let output = crate::prepare("./cases/erlang_nested");
insta::assert_snapshot!(
"erlang_nested",
output,
"./cases/erlang_nested",
);
}
#[rustfmt::skip]
#[test]
fn erlang_nested_qualified_constant() {
let output = crate::prepare("./cases/erlang_nested_qualified_constant");
insta::assert_snapshot!(
"erlang_nested_qualified_constant",
output,
"./cases/erlang_nested_qualified_constant",
);
}
#[rustfmt::skip]
#[test]
fn hello_joe() {
let output = crate::prepare("./cases/hello_joe");
insta::assert_snapshot!(
"hello_joe",
output,
"./cases/hello_joe",
);
}
#[rustfmt::skip]
#[test]
fn import_cycle() {
let output = crate::prepare("./cases/import_cycle");
insta::assert_snapshot!(
"import_cycle",
output,
"./cases/import_cycle",
);
}
#[rustfmt::skip]
#[test]
fn import_cycle_multi() {
let output = crate::prepare("./cases/import_cycle_multi");
insta::assert_snapshot!(
"import_cycle_multi",
output,
"./cases/import_cycle_multi",
);
}
#[rustfmt::skip]
#[test]
fn import_shadowed_name_warning() {
let output = crate::prepare("./cases/import_shadowed_name_warning");
insta::assert_snapshot!(
"import_shadowed_name_warning",
output,
"./cases/import_shadowed_name_warning",
);
}
#[rustfmt::skip]
#[test]
fn imported_constants() {
let output = crate::prepare("./cases/imported_constants");
insta::assert_snapshot!(
"imported_constants",
output,
"./cases/imported_constants",
);
}
#[rustfmt::skip]
#[test]
fn imported_external_fns() {
let output = crate::prepare("./cases/imported_external_fns");
insta::assert_snapshot!(
"imported_external_fns",
output,
"./cases/imported_external_fns",
);
}
#[rustfmt::skip]
#[test]
fn imported_record_constructors() {
let output = crate::prepare("./cases/imported_record_constructors");
insta::assert_snapshot!(
"imported_record_constructors",
output,
"./cases/imported_record_constructors",
);
}
#[rustfmt::skip]
#[test]
fn javascript_d_ts() {
let output = crate::prepare("./cases/javascript_d_ts");
insta::assert_snapshot!(
"javascript_d_ts",
output,
"./cases/javascript_d_ts",
);
}
#[rustfmt::skip]
#[test]
fn javascript_empty() {
let output = crate::prepare("./cases/javascript_empty");
insta::assert_snapshot!(
"javascript_empty",
output,
"./cases/javascript_empty",
);
}
#[rustfmt::skip]
#[test]
fn javascript_import() {
let output = crate::prepare("./cases/javascript_import");
insta::assert_snapshot!(
"javascript_import",
output,
"./cases/javascript_import",
);
}
#[rustfmt::skip]
#[test]
fn not_overwriting_erlang_module() {
let output = crate::prepare("./cases/not_overwriting_erlang_module");
insta::assert_snapshot!(
"not_overwriting_erlang_module",
output,
"./cases/not_overwriting_erlang_module",
);
}
#[rustfmt::skip]
#[test]
fn opaque_type_accessor() {
let output = crate::prepare("./cases/opaque_type_accessor");
insta::assert_snapshot!(
"opaque_type_accessor",
output,
"./cases/opaque_type_accessor",
);
}
#[rustfmt::skip]
#[test]
fn opaque_type_destructure() {
let output = crate::prepare("./cases/opaque_type_destructure");
insta::assert_snapshot!(
"opaque_type_destructure",
output,
"./cases/opaque_type_destructure",
);
}
#[rustfmt::skip]
#[test]
fn overwriting_erlang_module() {
let output = crate::prepare("./cases/overwriting_erlang_module");
insta::assert_snapshot!(
"overwriting_erlang_module",
output,
"./cases/overwriting_erlang_module",
);
}
#[rustfmt::skip]
#[test]
fn src_importing_dev() {
let output = crate::prepare("./cases/src_importing_dev");
insta::assert_snapshot!(
"src_importing_dev",
output,
"./cases/src_importing_dev",
);
}
#[rustfmt::skip]
#[test]
fn src_importing_test() {
let output = crate::prepare("./cases/src_importing_test");
insta::assert_snapshot!(
"src_importing_test",
output,
"./cases/src_importing_test",
);
}
#[rustfmt::skip]
#[test]
fn unknown_module_field_in_constant() {
let output = crate::prepare("./cases/unknown_module_field_in_constant");
insta::assert_snapshot!(
"unknown_module_field_in_constant",
output,
"./cases/unknown_module_field_in_constant",
);
}
#[rustfmt::skip]
#[test]
fn unknown_module_field_in_expression() {
let output = crate::prepare("./cases/unknown_module_field_in_expression");
insta::assert_snapshot!(
"unknown_module_field_in_expression",
output,
"./cases/unknown_module_field_in_expression",
);
}
#[rustfmt::skip]
#[test]
fn unknown_module_field_in_import() {
let output = crate::prepare("./cases/unknown_module_field_in_import");
insta::assert_snapshot!(
"unknown_module_field_in_import",
output,
"./cases/unknown_module_field_in_import",
);
}
#[rustfmt::skip]
#[test]
fn variable_or_module() {
let output = crate::prepare("./cases/variable_or_module");
insta::assert_snapshot!(
"variable_or_module",
output,
"./cases/variable_or_module",
);
}
| rust | Apache-2.0 | f424547f02e621f1c5f28749786e05eda7feb098 | 2026-01-04T15:40:22.554517Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/config.rs | src/config.rs | use super::banner::BANNER;
use anyhow::{anyhow, Error, Result};
use serde::{Deserialize, Serialize};
use std::{
fs,
io::{stdin, Write},
path::{Path, PathBuf},
};
const DEFAULT_PORT: u16 = 8888;
const FILE_NAME: &str = "client.yml";
const CONFIG_DIR: &str = ".config";
const APP_CONFIG_DIR: &str = "spotify-tui";
const TOKEN_CACHE_FILE: &str = ".spotify_token_cache.json";
#[derive(Default, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ClientConfig {
pub client_id: String,
pub client_secret: String,
pub device_id: Option<String>,
// FIXME: port should be defined in `user_config` not in here
pub port: Option<u16>,
}
pub struct ConfigPaths {
pub config_file_path: PathBuf,
pub token_cache_path: PathBuf,
}
impl ClientConfig {
pub fn new() -> ClientConfig {
ClientConfig {
client_id: "".to_string(),
client_secret: "".to_string(),
device_id: None,
port: None,
}
}
pub fn get_redirect_uri(&self) -> String {
format!("http://localhost:{}/callback", self.get_port())
}
pub fn get_port(&self) -> u16 {
self.port.unwrap_or(DEFAULT_PORT)
}
pub fn get_or_build_paths(&self) -> Result<ConfigPaths> {
match dirs::home_dir() {
Some(home) => {
let path = Path::new(&home);
let home_config_dir = path.join(CONFIG_DIR);
let app_config_dir = home_config_dir.join(APP_CONFIG_DIR);
if !home_config_dir.exists() {
fs::create_dir(&home_config_dir)?;
}
if !app_config_dir.exists() {
fs::create_dir(&app_config_dir)?;
}
let config_file_path = &app_config_dir.join(FILE_NAME);
let token_cache_path = &app_config_dir.join(TOKEN_CACHE_FILE);
let paths = ConfigPaths {
config_file_path: config_file_path.to_path_buf(),
token_cache_path: token_cache_path.to_path_buf(),
};
Ok(paths)
}
None => Err(anyhow!("No $HOME directory found for client config")),
}
}
pub fn set_device_id(&mut self, device_id: String) -> Result<()> {
let paths = self.get_or_build_paths()?;
let config_string = fs::read_to_string(&paths.config_file_path)?;
let mut config_yml: ClientConfig = serde_yaml::from_str(&config_string)?;
self.device_id = Some(device_id.clone());
config_yml.device_id = Some(device_id);
let new_config = serde_yaml::to_string(&config_yml)?;
let mut config_file = fs::File::create(&paths.config_file_path)?;
write!(config_file, "{}", new_config)?;
Ok(())
}
pub fn load_config(&mut self) -> Result<()> {
let paths = self.get_or_build_paths()?;
if paths.config_file_path.exists() {
let config_string = fs::read_to_string(&paths.config_file_path)?;
let config_yml: ClientConfig = serde_yaml::from_str(&config_string)?;
self.client_id = config_yml.client_id;
self.client_secret = config_yml.client_secret;
self.device_id = config_yml.device_id;
self.port = config_yml.port;
Ok(())
} else {
println!("{}", BANNER);
println!(
"Config will be saved to {}",
paths.config_file_path.display()
);
println!("\nHow to get setup:\n");
let instructions = [
"Go to the Spotify dashboard - https://developer.spotify.com/dashboard/applications",
"Click `Create a Client ID` and create an app",
"Now click `Edit Settings`",
&format!(
"Add `http://localhost:{}/callback` to the Redirect URIs",
DEFAULT_PORT
),
"You are now ready to authenticate with Spotify!",
];
let mut number = 1;
for item in instructions.iter() {
println!(" {}. {}", number, item);
number += 1;
}
let client_id = ClientConfig::get_client_key_from_input("Client ID")?;
let client_secret = ClientConfig::get_client_key_from_input("Client Secret")?;
let mut port = String::new();
println!("\nEnter port of redirect uri (default {}): ", DEFAULT_PORT);
stdin().read_line(&mut port)?;
let port = port.trim().parse::<u16>().unwrap_or(DEFAULT_PORT);
let config_yml = ClientConfig {
client_id,
client_secret,
device_id: None,
port: Some(port),
};
let content_yml = serde_yaml::to_string(&config_yml)?;
let mut new_config = fs::File::create(&paths.config_file_path)?;
write!(new_config, "{}", content_yml)?;
self.client_id = config_yml.client_id;
self.client_secret = config_yml.client_secret;
self.device_id = config_yml.device_id;
self.port = config_yml.port;
Ok(())
}
}
fn get_client_key_from_input(type_label: &'static str) -> Result<String> {
let mut client_key = String::new();
const MAX_RETRIES: u8 = 5;
let mut num_retries = 0;
loop {
println!("\nEnter your {}: ", type_label);
stdin().read_line(&mut client_key)?;
client_key = client_key.trim().to_string();
match ClientConfig::validate_client_key(&client_key) {
Ok(_) => return Ok(client_key),
Err(error_string) => {
println!("{}", error_string);
client_key.clear();
num_retries += 1;
if num_retries == MAX_RETRIES {
return Err(Error::from(std::io::Error::new(
std::io::ErrorKind::Other,
format!("Maximum retries ({}) exceeded.", MAX_RETRIES),
)));
}
}
};
}
}
fn validate_client_key(key: &str) -> Result<()> {
const EXPECTED_LEN: usize = 32;
if key.len() != EXPECTED_LEN {
Err(Error::from(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("invalid length: {} (must be {})", key.len(), EXPECTED_LEN,),
)))
} else if !key.chars().all(|c| c.is_digit(16)) {
Err(Error::from(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"invalid character found (must be hex digits)",
)))
} else {
Ok(())
}
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/app.rs | src/app.rs | use super::user_config::UserConfig;
use crate::network::IoEvent;
use anyhow::anyhow;
use rspotify::{
model::{
album::{FullAlbum, SavedAlbum, SimplifiedAlbum},
artist::FullArtist,
audio::AudioAnalysis,
context::CurrentlyPlaybackContext,
device::DevicePayload,
page::{CursorBasedPage, Page},
playing::PlayHistory,
playlist::{PlaylistTrack, SimplifiedPlaylist},
show::{FullShow, Show, SimplifiedEpisode, SimplifiedShow},
track::{FullTrack, SavedTrack, SimplifiedTrack},
user::PrivateUser,
PlayingItem,
},
senum::Country,
};
use std::str::FromStr;
use std::sync::mpsc::Sender;
use std::{
cmp::{max, min},
collections::HashSet,
time::{Instant, SystemTime},
};
use tui::layout::Rect;
use arboard::Clipboard;
pub const LIBRARY_OPTIONS: [&str; 6] = [
"Made For You",
"Recently Played",
"Liked Songs",
"Albums",
"Artists",
"Podcasts",
];
const DEFAULT_ROUTE: Route = Route {
id: RouteId::Home,
active_block: ActiveBlock::Empty,
hovered_block: ActiveBlock::Library,
};
#[derive(Clone)]
pub struct ScrollableResultPages<T> {
index: usize,
pub pages: Vec<T>,
}
impl<T> ScrollableResultPages<T> {
pub fn new() -> ScrollableResultPages<T> {
ScrollableResultPages {
index: 0,
pages: vec![],
}
}
pub fn get_results(&self, at_index: Option<usize>) -> Option<&T> {
self.pages.get(at_index.unwrap_or(self.index))
}
pub fn get_mut_results(&mut self, at_index: Option<usize>) -> Option<&mut T> {
self.pages.get_mut(at_index.unwrap_or(self.index))
}
pub fn add_pages(&mut self, new_pages: T) {
self.pages.push(new_pages);
// Whenever a new page is added, set the active index to the end of the vector
self.index = self.pages.len() - 1;
}
}
#[derive(Default)]
pub struct SpotifyResultAndSelectedIndex<T> {
pub index: usize,
pub result: T,
}
#[derive(Clone)]
pub struct Library {
pub selected_index: usize,
pub saved_tracks: ScrollableResultPages<Page<SavedTrack>>,
pub made_for_you_playlists: ScrollableResultPages<Page<SimplifiedPlaylist>>,
pub saved_albums: ScrollableResultPages<Page<SavedAlbum>>,
pub saved_shows: ScrollableResultPages<Page<Show>>,
pub saved_artists: ScrollableResultPages<CursorBasedPage<FullArtist>>,
pub show_episodes: ScrollableResultPages<Page<SimplifiedEpisode>>,
}
#[derive(PartialEq, Debug)]
pub enum SearchResultBlock {
AlbumSearch,
SongSearch,
ArtistSearch,
PlaylistSearch,
ShowSearch,
Empty,
}
#[derive(PartialEq, Debug, Clone)]
pub enum ArtistBlock {
TopTracks,
Albums,
RelatedArtists,
Empty,
}
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum DialogContext {
PlaylistWindow,
PlaylistSearch,
}
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum ActiveBlock {
Analysis,
PlayBar,
AlbumTracks,
AlbumList,
ArtistBlock,
Empty,
Error,
HelpMenu,
Home,
Input,
Library,
MyPlaylists,
Podcasts,
EpisodeTable,
RecentlyPlayed,
SearchResultBlock,
SelectDevice,
TrackTable,
MadeForYou,
Artists,
BasicView,
Dialog(DialogContext),
}
#[derive(Clone, PartialEq, Debug)]
pub enum RouteId {
Analysis,
AlbumTracks,
AlbumList,
Artist,
BasicView,
Error,
Home,
RecentlyPlayed,
Search,
SelectedDevice,
TrackTable,
MadeForYou,
Artists,
Podcasts,
PodcastEpisodes,
Recommendations,
Dialog,
}
#[derive(Debug)]
pub struct Route {
pub id: RouteId,
pub active_block: ActiveBlock,
pub hovered_block: ActiveBlock,
}
// Is it possible to compose enums?
#[derive(PartialEq, Debug)]
pub enum TrackTableContext {
MyPlaylists,
AlbumSearch,
PlaylistSearch,
SavedTracks,
RecommendedTracks,
MadeForYou,
}
// Is it possible to compose enums?
#[derive(Clone, PartialEq, Debug, Copy)]
pub enum AlbumTableContext {
Simplified,
Full,
}
#[derive(Clone, PartialEq, Debug, Copy)]
pub enum EpisodeTableContext {
Simplified,
Full,
}
#[derive(Clone, PartialEq, Debug)]
pub enum RecommendationsContext {
Artist,
Song,
}
pub struct SearchResult {
pub albums: Option<Page<SimplifiedAlbum>>,
pub artists: Option<Page<FullArtist>>,
pub playlists: Option<Page<SimplifiedPlaylist>>,
pub tracks: Option<Page<FullTrack>>,
pub shows: Option<Page<SimplifiedShow>>,
pub selected_album_index: Option<usize>,
pub selected_artists_index: Option<usize>,
pub selected_playlists_index: Option<usize>,
pub selected_tracks_index: Option<usize>,
pub selected_shows_index: Option<usize>,
pub hovered_block: SearchResultBlock,
pub selected_block: SearchResultBlock,
}
#[derive(Default)]
pub struct TrackTable {
pub tracks: Vec<FullTrack>,
pub selected_index: usize,
pub context: Option<TrackTableContext>,
}
#[derive(Clone)]
pub struct SelectedShow {
pub show: SimplifiedShow,
}
#[derive(Clone)]
pub struct SelectedFullShow {
pub show: FullShow,
}
#[derive(Clone)]
pub struct SelectedAlbum {
pub album: SimplifiedAlbum,
pub tracks: Page<SimplifiedTrack>,
pub selected_index: usize,
}
#[derive(Clone)]
pub struct SelectedFullAlbum {
pub album: FullAlbum,
pub selected_index: usize,
}
#[derive(Clone)]
pub struct Artist {
pub artist_name: String,
pub albums: Page<SimplifiedAlbum>,
pub related_artists: Vec<FullArtist>,
pub top_tracks: Vec<FullTrack>,
pub selected_album_index: usize,
pub selected_related_artist_index: usize,
pub selected_top_track_index: usize,
pub artist_hovered_block: ArtistBlock,
pub artist_selected_block: ArtistBlock,
}
pub struct App {
pub instant_since_last_current_playback_poll: Instant,
navigation_stack: Vec<Route>,
pub audio_analysis: Option<AudioAnalysis>,
pub home_scroll: u16,
pub user_config: UserConfig,
pub artists: Vec<FullArtist>,
pub artist: Option<Artist>,
pub album_table_context: AlbumTableContext,
pub saved_album_tracks_index: usize,
pub api_error: String,
pub current_playback_context: Option<CurrentlyPlaybackContext>,
pub devices: Option<DevicePayload>,
// Inputs:
// input is the string for input;
// input_idx is the index of the cursor in terms of character;
// input_cursor_position is the sum of the width of characters preceding the cursor.
// Reason for this complication is due to non-ASCII characters, they may
// take more than 1 bytes to store and more than 1 character width to display.
pub input: Vec<char>,
pub input_idx: usize,
pub input_cursor_position: u16,
pub liked_song_ids_set: HashSet<String>,
pub followed_artist_ids_set: HashSet<String>,
pub saved_album_ids_set: HashSet<String>,
pub saved_show_ids_set: HashSet<String>,
pub large_search_limit: u32,
pub library: Library,
pub playlist_offset: u32,
pub made_for_you_offset: u32,
pub playlist_tracks: Option<Page<PlaylistTrack>>,
pub made_for_you_tracks: Option<Page<PlaylistTrack>>,
pub playlists: Option<Page<SimplifiedPlaylist>>,
pub recently_played: SpotifyResultAndSelectedIndex<Option<CursorBasedPage<PlayHistory>>>,
pub recommended_tracks: Vec<FullTrack>,
pub recommendations_seed: String,
pub recommendations_context: Option<RecommendationsContext>,
pub search_results: SearchResult,
pub selected_album_simplified: Option<SelectedAlbum>,
pub selected_album_full: Option<SelectedFullAlbum>,
pub selected_device_index: Option<usize>,
pub selected_playlist_index: Option<usize>,
pub active_playlist_index: Option<usize>,
pub size: Rect,
pub small_search_limit: u32,
pub song_progress_ms: u128,
pub seek_ms: Option<u128>,
pub track_table: TrackTable,
pub episode_table_context: EpisodeTableContext,
pub selected_show_simplified: Option<SelectedShow>,
pub selected_show_full: Option<SelectedFullShow>,
pub user: Option<PrivateUser>,
pub album_list_index: usize,
pub made_for_you_index: usize,
pub artists_list_index: usize,
pub clipboard: Option<Clipboard>,
pub shows_list_index: usize,
pub episode_list_index: usize,
pub help_docs_size: u32,
pub help_menu_page: u32,
pub help_menu_max_lines: u32,
pub help_menu_offset: u32,
pub is_loading: bool,
io_tx: Option<Sender<IoEvent>>,
pub is_fetching_current_playback: bool,
pub spotify_token_expiry: SystemTime,
pub dialog: Option<String>,
pub confirm: bool,
}
impl Default for App {
fn default() -> Self {
App {
audio_analysis: None,
album_table_context: AlbumTableContext::Full,
album_list_index: 0,
made_for_you_index: 0,
artists_list_index: 0,
shows_list_index: 0,
episode_list_index: 0,
artists: vec![],
artist: None,
user_config: UserConfig::new(),
saved_album_tracks_index: 0,
recently_played: Default::default(),
size: Rect::default(),
selected_album_simplified: None,
selected_album_full: None,
home_scroll: 0,
library: Library {
saved_tracks: ScrollableResultPages::new(),
made_for_you_playlists: ScrollableResultPages::new(),
saved_albums: ScrollableResultPages::new(),
saved_shows: ScrollableResultPages::new(),
saved_artists: ScrollableResultPages::new(),
show_episodes: ScrollableResultPages::new(),
selected_index: 0,
},
liked_song_ids_set: HashSet::new(),
followed_artist_ids_set: HashSet::new(),
saved_album_ids_set: HashSet::new(),
saved_show_ids_set: HashSet::new(),
navigation_stack: vec![DEFAULT_ROUTE],
large_search_limit: 20,
small_search_limit: 4,
api_error: String::new(),
current_playback_context: None,
devices: None,
input: vec![],
input_idx: 0,
input_cursor_position: 0,
playlist_offset: 0,
made_for_you_offset: 0,
playlist_tracks: None,
made_for_you_tracks: None,
playlists: None,
recommended_tracks: vec![],
recommendations_context: None,
recommendations_seed: "".to_string(),
search_results: SearchResult {
hovered_block: SearchResultBlock::SongSearch,
selected_block: SearchResultBlock::Empty,
albums: None,
artists: None,
playlists: None,
shows: None,
selected_album_index: None,
selected_artists_index: None,
selected_playlists_index: None,
selected_tracks_index: None,
selected_shows_index: None,
tracks: None,
},
song_progress_ms: 0,
seek_ms: None,
selected_device_index: None,
selected_playlist_index: None,
active_playlist_index: None,
track_table: Default::default(),
episode_table_context: EpisodeTableContext::Full,
selected_show_simplified: None,
selected_show_full: None,
user: None,
instant_since_last_current_playback_poll: Instant::now(),
clipboard: Clipboard::new().ok(),
help_docs_size: 0,
help_menu_page: 0,
help_menu_max_lines: 0,
help_menu_offset: 0,
is_loading: false,
io_tx: None,
is_fetching_current_playback: false,
spotify_token_expiry: SystemTime::now(),
dialog: None,
confirm: false,
}
}
}
impl App {
pub fn new(
io_tx: Sender<IoEvent>,
user_config: UserConfig,
spotify_token_expiry: SystemTime,
) -> App {
App {
io_tx: Some(io_tx),
user_config,
spotify_token_expiry,
..App::default()
}
}
// Send a network event to the network thread
pub fn dispatch(&mut self, action: IoEvent) {
// `is_loading` will be set to false again after the async action has finished in network.rs
self.is_loading = true;
if let Some(io_tx) = &self.io_tx {
if let Err(e) = io_tx.send(action) {
self.is_loading = false;
println!("Error from dispatch {}", e);
// TODO: handle error
};
}
}
fn apply_seek(&mut self, seek_ms: u32) {
if let Some(CurrentlyPlaybackContext {
item: Some(item), ..
}) = &self.current_playback_context
{
let duration_ms = match item {
PlayingItem::Track(track) => track.duration_ms,
PlayingItem::Episode(episode) => episode.duration_ms,
};
let event = if seek_ms < duration_ms {
IoEvent::Seek(seek_ms)
} else {
IoEvent::NextTrack
};
self.dispatch(event);
}
}
fn poll_current_playback(&mut self) {
// Poll every 5 seconds
let poll_interval_ms = 5_000;
let elapsed = self
.instant_since_last_current_playback_poll
.elapsed()
.as_millis();
if !self.is_fetching_current_playback && elapsed >= poll_interval_ms {
self.is_fetching_current_playback = true;
// Trigger the seek if the user has set a new position
match self.seek_ms {
Some(seek_ms) => self.apply_seek(seek_ms as u32),
None => self.dispatch(IoEvent::GetCurrentPlayback),
}
}
}
pub fn update_on_tick(&mut self) {
self.poll_current_playback();
if let Some(CurrentlyPlaybackContext {
item: Some(item),
progress_ms: Some(progress_ms),
is_playing,
..
}) = &self.current_playback_context
{
// Update progress even when the song is not playing,
// because seeking is possible while paused
let elapsed = if *is_playing {
self
.instant_since_last_current_playback_poll
.elapsed()
.as_millis()
} else {
0u128
} + u128::from(*progress_ms);
let duration_ms = match item {
PlayingItem::Track(track) => track.duration_ms,
PlayingItem::Episode(episode) => episode.duration_ms,
};
if elapsed < u128::from(duration_ms) {
self.song_progress_ms = elapsed;
} else {
self.song_progress_ms = duration_ms.into();
}
}
}
pub fn seek_forwards(&mut self) {
if let Some(CurrentlyPlaybackContext {
item: Some(item), ..
}) = &self.current_playback_context
{
let duration_ms = match item {
PlayingItem::Track(track) => track.duration_ms,
PlayingItem::Episode(episode) => episode.duration_ms,
};
let old_progress = match self.seek_ms {
Some(seek_ms) => seek_ms,
None => self.song_progress_ms,
};
let new_progress = min(
old_progress as u32 + self.user_config.behavior.seek_milliseconds,
duration_ms,
);
self.seek_ms = Some(new_progress as u128);
}
}
pub fn seek_backwards(&mut self) {
let old_progress = match self.seek_ms {
Some(seek_ms) => seek_ms,
None => self.song_progress_ms,
};
let new_progress = if old_progress as u32 > self.user_config.behavior.seek_milliseconds {
old_progress as u32 - self.user_config.behavior.seek_milliseconds
} else {
0u32
};
self.seek_ms = Some(new_progress as u128);
}
pub fn get_recommendations_for_seed(
&mut self,
seed_artists: Option<Vec<String>>,
seed_tracks: Option<Vec<String>>,
first_track: Option<FullTrack>,
) {
let user_country = self.get_user_country();
self.dispatch(IoEvent::GetRecommendationsForSeed(
seed_artists,
seed_tracks,
Box::new(first_track),
user_country,
));
}
pub fn get_recommendations_for_track_id(&mut self, id: String) {
let user_country = self.get_user_country();
self.dispatch(IoEvent::GetRecommendationsForTrackId(id, user_country));
}
pub fn increase_volume(&mut self) {
if let Some(context) = self.current_playback_context.clone() {
let current_volume = context.device.volume_percent as u8;
let next_volume = min(
current_volume + self.user_config.behavior.volume_increment,
100,
);
if next_volume != current_volume {
self.dispatch(IoEvent::ChangeVolume(next_volume));
}
}
}
pub fn decrease_volume(&mut self) {
if let Some(context) = self.current_playback_context.clone() {
let current_volume = context.device.volume_percent as i8;
let next_volume = max(
current_volume - self.user_config.behavior.volume_increment as i8,
0,
);
if next_volume != current_volume {
self.dispatch(IoEvent::ChangeVolume(next_volume as u8));
}
}
}
pub fn handle_error(&mut self, e: anyhow::Error) {
self.push_navigation_stack(RouteId::Error, ActiveBlock::Error);
self.api_error = e.to_string();
}
pub fn toggle_playback(&mut self) {
if let Some(CurrentlyPlaybackContext {
is_playing: true, ..
}) = &self.current_playback_context
{
self.dispatch(IoEvent::PausePlayback);
} else {
// When no offset or uris are passed, spotify will resume current playback
self.dispatch(IoEvent::StartPlayback(None, None, None));
}
}
pub fn previous_track(&mut self) {
if self.song_progress_ms >= 3_000 {
self.dispatch(IoEvent::Seek(0));
} else {
self.dispatch(IoEvent::PreviousTrack);
}
}
// The navigation_stack actually only controls the large block to the right of `library` and
// `playlists`
pub fn push_navigation_stack(&mut self, next_route_id: RouteId, next_active_block: ActiveBlock) {
if !self
.navigation_stack
.last()
.map(|last_route| last_route.id == next_route_id)
.unwrap_or(false)
{
self.navigation_stack.push(Route {
id: next_route_id,
active_block: next_active_block,
hovered_block: next_active_block,
});
}
}
pub fn pop_navigation_stack(&mut self) -> Option<Route> {
if self.navigation_stack.len() == 1 {
None
} else {
self.navigation_stack.pop()
}
}
pub fn get_current_route(&self) -> &Route {
// if for some reason there is no route return the default
self.navigation_stack.last().unwrap_or(&DEFAULT_ROUTE)
}
fn get_current_route_mut(&mut self) -> &mut Route {
self.navigation_stack.last_mut().unwrap()
}
pub fn set_current_route_state(
&mut self,
active_block: Option<ActiveBlock>,
hovered_block: Option<ActiveBlock>,
) {
let mut current_route = self.get_current_route_mut();
if let Some(active_block) = active_block {
current_route.active_block = active_block;
}
if let Some(hovered_block) = hovered_block {
current_route.hovered_block = hovered_block;
}
}
pub fn copy_song_url(&mut self) {
let clipboard = match &mut self.clipboard {
Some(ctx) => ctx,
None => return,
};
if let Some(CurrentlyPlaybackContext {
item: Some(item), ..
}) = &self.current_playback_context
{
match item {
PlayingItem::Track(track) => {
if let Err(e) = clipboard.set_text(format!(
"https://open.spotify.com/track/{}",
track.id.to_owned().unwrap_or_default()
)) {
self.handle_error(anyhow!("failed to set clipboard content: {}", e));
}
}
PlayingItem::Episode(episode) => {
if let Err(e) = clipboard.set_text(format!(
"https://open.spotify.com/episode/{}",
episode.id.to_owned()
)) {
self.handle_error(anyhow!("failed to set clipboard content: {}", e));
}
}
}
}
}
pub fn copy_album_url(&mut self) {
let clipboard = match &mut self.clipboard {
Some(ctx) => ctx,
None => return,
};
if let Some(CurrentlyPlaybackContext {
item: Some(item), ..
}) = &self.current_playback_context
{
match item {
PlayingItem::Track(track) => {
if let Err(e) = clipboard.set_text(format!(
"https://open.spotify.com/album/{}",
track.album.id.to_owned().unwrap_or_default()
)) {
self.handle_error(anyhow!("failed to set clipboard content: {}", e));
}
}
PlayingItem::Episode(episode) => {
if let Err(e) = clipboard.set_text(format!(
"https://open.spotify.com/show/{}",
episode.show.id.to_owned()
)) {
self.handle_error(anyhow!("failed to set clipboard content: {}", e));
}
}
}
}
}
pub fn set_saved_tracks_to_table(&mut self, saved_track_page: &Page<SavedTrack>) {
self.dispatch(IoEvent::SetTracksToTable(
saved_track_page
.items
.clone()
.into_iter()
.map(|item| item.track)
.collect::<Vec<FullTrack>>(),
));
}
pub fn set_saved_artists_to_table(&mut self, saved_artists_page: &CursorBasedPage<FullArtist>) {
self.dispatch(IoEvent::SetArtistsToTable(
saved_artists_page
.items
.clone()
.into_iter()
.collect::<Vec<FullArtist>>(),
))
}
pub fn get_current_user_saved_artists_next(&mut self) {
match self
.library
.saved_artists
.get_results(Some(self.library.saved_artists.index + 1))
.cloned()
{
Some(saved_artists) => {
self.set_saved_artists_to_table(&saved_artists);
self.library.saved_artists.index += 1
}
None => {
if let Some(saved_artists) = &self.library.saved_artists.clone().get_results(None) {
if let Some(last_artist) = saved_artists.items.last() {
self.dispatch(IoEvent::GetFollowedArtists(Some(last_artist.id.clone())));
}
}
}
}
}
pub fn get_current_user_saved_artists_previous(&mut self) {
if self.library.saved_artists.index > 0 {
self.library.saved_artists.index -= 1;
}
if let Some(saved_artists) = &self.library.saved_artists.get_results(None).cloned() {
self.set_saved_artists_to_table(saved_artists);
}
}
pub fn get_current_user_saved_tracks_next(&mut self) {
// Before fetching the next tracks, check if we have already fetched them
match self
.library
.saved_tracks
.get_results(Some(self.library.saved_tracks.index + 1))
.cloned()
{
Some(saved_tracks) => {
self.set_saved_tracks_to_table(&saved_tracks);
self.library.saved_tracks.index += 1
}
None => {
if let Some(saved_tracks) = &self.library.saved_tracks.get_results(None) {
let offset = Some(saved_tracks.offset + saved_tracks.limit);
self.dispatch(IoEvent::GetCurrentSavedTracks(offset));
}
}
}
}
pub fn get_current_user_saved_tracks_previous(&mut self) {
if self.library.saved_tracks.index > 0 {
self.library.saved_tracks.index -= 1;
}
if let Some(saved_tracks) = &self.library.saved_tracks.get_results(None).cloned() {
self.set_saved_tracks_to_table(saved_tracks);
}
}
pub fn shuffle(&mut self) {
if let Some(context) = &self.current_playback_context.clone() {
self.dispatch(IoEvent::Shuffle(context.shuffle_state));
};
}
pub fn get_current_user_saved_albums_next(&mut self) {
match self
.library
.saved_albums
.get_results(Some(self.library.saved_albums.index + 1))
.cloned()
{
Some(_) => self.library.saved_albums.index += 1,
None => {
if let Some(saved_albums) = &self.library.saved_albums.get_results(None) {
let offset = Some(saved_albums.offset + saved_albums.limit);
self.dispatch(IoEvent::GetCurrentUserSavedAlbums(offset));
}
}
}
}
pub fn get_current_user_saved_albums_previous(&mut self) {
if self.library.saved_albums.index > 0 {
self.library.saved_albums.index -= 1;
}
}
pub fn current_user_saved_album_delete(&mut self, block: ActiveBlock) {
match block {
ActiveBlock::SearchResultBlock => {
if let Some(albums) = &self.search_results.albums {
if let Some(selected_index) = self.search_results.selected_album_index {
let selected_album = &albums.items[selected_index];
if let Some(album_id) = selected_album.id.clone() {
self.dispatch(IoEvent::CurrentUserSavedAlbumDelete(album_id));
}
}
}
}
ActiveBlock::AlbumList => {
if let Some(albums) = self.library.saved_albums.get_results(None) {
if let Some(selected_album) = albums.items.get(self.album_list_index) {
let album_id = selected_album.album.id.clone();
self.dispatch(IoEvent::CurrentUserSavedAlbumDelete(album_id));
}
}
}
ActiveBlock::ArtistBlock => {
if let Some(artist) = &self.artist {
if let Some(selected_album) = artist.albums.items.get(artist.selected_album_index) {
if let Some(album_id) = selected_album.id.clone() {
self.dispatch(IoEvent::CurrentUserSavedAlbumDelete(album_id));
}
}
}
}
_ => (),
}
}
pub fn current_user_saved_album_add(&mut self, block: ActiveBlock) {
match block {
ActiveBlock::SearchResultBlock => {
if let Some(albums) = &self.search_results.albums {
if let Some(selected_index) = self.search_results.selected_album_index {
let selected_album = &albums.items[selected_index];
if let Some(album_id) = selected_album.id.clone() {
self.dispatch(IoEvent::CurrentUserSavedAlbumAdd(album_id));
}
}
}
}
ActiveBlock::ArtistBlock => {
if let Some(artist) = &self.artist {
if let Some(selected_album) = artist.albums.items.get(artist.selected_album_index) {
if let Some(album_id) = selected_album.id.clone() {
self.dispatch(IoEvent::CurrentUserSavedAlbumAdd(album_id));
}
}
}
}
_ => (),
}
}
pub fn get_current_user_saved_shows_next(&mut self) {
match self
.library
.saved_shows
.get_results(Some(self.library.saved_shows.index + 1))
.cloned()
{
Some(_) => self.library.saved_shows.index += 1,
None => {
if let Some(saved_shows) = &self.library.saved_shows.get_results(None) {
let offset = Some(saved_shows.offset + saved_shows.limit);
self.dispatch(IoEvent::GetCurrentUserSavedShows(offset));
}
}
}
}
pub fn get_current_user_saved_shows_previous(&mut self) {
if self.library.saved_shows.index > 0 {
self.library.saved_shows.index -= 1;
}
}
pub fn get_episode_table_next(&mut self, show_id: String) {
match self
.library
.show_episodes
.get_results(Some(self.library.show_episodes.index + 1))
.cloned()
{
Some(_) => self.library.show_episodes.index += 1,
None => {
if let Some(show_episodes) = &self.library.show_episodes.get_results(None) {
let offset = Some(show_episodes.offset + show_episodes.limit);
self.dispatch(IoEvent::GetCurrentShowEpisodes(show_id, offset));
}
}
}
}
pub fn get_episode_table_previous(&mut self) {
if self.library.show_episodes.index > 0 {
self.library.show_episodes.index -= 1;
}
}
pub fn user_unfollow_artists(&mut self, block: ActiveBlock) {
match block {
ActiveBlock::SearchResultBlock => {
if let Some(artists) = &self.search_results.artists {
if let Some(selected_index) = self.search_results.selected_artists_index {
let selected_artist: &FullArtist = &artists.items[selected_index];
let artist_id = selected_artist.id.clone();
self.dispatch(IoEvent::UserUnfollowArtists(vec![artist_id]));
}
}
}
ActiveBlock::AlbumList => {
if let Some(artists) = self.library.saved_artists.get_results(None) {
if let Some(selected_artist) = artists.items.get(self.artists_list_index) {
let artist_id = selected_artist.id.clone();
self.dispatch(IoEvent::UserUnfollowArtists(vec![artist_id]));
}
}
}
ActiveBlock::ArtistBlock => {
if let Some(artist) = &self.artist {
let selected_artis = &artist.related_artists[artist.selected_related_artist_index];
let artist_id = selected_artis.id.clone();
self.dispatch(IoEvent::UserUnfollowArtists(vec![artist_id]));
}
}
_ => (),
};
}
pub fn user_follow_artists(&mut self, block: ActiveBlock) {
match block {
ActiveBlock::SearchResultBlock => {
if let Some(artists) = &self.search_results.artists {
if let Some(selected_index) = self.search_results.selected_artists_index {
let selected_artist: &FullArtist = &artists.items[selected_index];
let artist_id = selected_artist.id.clone();
self.dispatch(IoEvent::UserFollowArtists(vec![artist_id]));
}
}
}
ActiveBlock::ArtistBlock => {
if let Some(artist) = &self.artist {
let selected_artis = &artist.related_artists[artist.selected_related_artist_index];
let artist_id = selected_artis.id.clone();
self.dispatch(IoEvent::UserFollowArtists(vec![artist_id]));
}
}
_ => (),
}
}
pub fn user_follow_playlist(&mut self) {
if let SearchResult {
playlists: Some(ref playlists),
selected_playlists_index: Some(selected_index),
..
} = self.search_results
{
let selected_playlist: &SimplifiedPlaylist = &playlists.items[selected_index];
let selected_id = selected_playlist.id.clone();
let selected_public = selected_playlist.public;
let selected_owner_id = selected_playlist.owner.id.clone();
self.dispatch(IoEvent::UserFollowPlaylist(
selected_owner_id,
selected_id,
selected_public,
));
}
}
pub fn user_unfollow_playlist(&mut self) {
if let (Some(playlists), Some(selected_index), Some(user)) =
(&self.playlists, self.selected_playlist_index, &self.user)
{
let selected_playlist = &playlists.items[selected_index];
let selected_id = selected_playlist.id.clone();
let user_id = user.id.clone();
self.dispatch(IoEvent::UserUnfollowPlaylist(user_id, selected_id))
}
}
pub fn user_unfollow_playlist_search_result(&mut self) {
if let (Some(playlists), Some(selected_index), Some(user)) = (
&self.search_results.playlists,
self.search_results.selected_playlists_index,
&self.user,
) {
let selected_playlist = &playlists.items[selected_index];
let selected_id = selected_playlist.id.clone();
let user_id = user.id.clone();
self.dispatch(IoEvent::UserUnfollowPlaylist(user_id, selected_id))
}
}
pub fn user_follow_show(&mut self, block: ActiveBlock) {
match block {
ActiveBlock::SearchResultBlock => {
if let Some(shows) = &self.search_results.shows {
if let Some(selected_index) = self.search_results.selected_shows_index {
if let Some(show_id) = shows.items.get(selected_index).map(|item| item.id.clone()) {
self.dispatch(IoEvent::CurrentUserSavedShowAdd(show_id));
}
}
}
}
ActiveBlock::EpisodeTable => match self.episode_table_context {
EpisodeTableContext::Full => {
if let Some(selected_episode) = self.selected_show_full.clone() {
let show_id = selected_episode.show.id;
self.dispatch(IoEvent::CurrentUserSavedShowAdd(show_id));
}
}
EpisodeTableContext::Simplified => {
if let Some(selected_episode) = self.selected_show_simplified.clone() {
let show_id = selected_episode.show.id;
self.dispatch(IoEvent::CurrentUserSavedShowAdd(show_id));
}
}
},
_ => (),
}
}
pub fn user_unfollow_show(&mut self, block: ActiveBlock) {
match block {
ActiveBlock::Podcasts => {
if let Some(shows) = self.library.saved_shows.get_results(None) {
if let Some(selected_show) = shows.items.get(self.shows_list_index) {
let show_id = selected_show.show.id.clone();
self.dispatch(IoEvent::CurrentUserSavedShowDelete(show_id));
}
}
}
ActiveBlock::SearchResultBlock => {
if let Some(shows) = &self.search_results.shows {
if let Some(selected_index) = self.search_results.selected_shows_index {
let show_id = shows.items[selected_index].id.to_owned();
self.dispatch(IoEvent::CurrentUserSavedShowDelete(show_id));
}
}
}
ActiveBlock::EpisodeTable => match self.episode_table_context {
EpisodeTableContext::Full => {
if let Some(selected_episode) = self.selected_show_full.clone() {
let show_id = selected_episode.show.id;
self.dispatch(IoEvent::CurrentUserSavedShowDelete(show_id));
}
}
EpisodeTableContext::Simplified => {
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | true |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/banner.rs | src/banner.rs | pub const BANNER: &str = "
_________ ____ / /_(_) __/_ __ / /___ __(_)
/ ___/ __ \\/ __ \\/ __/ / /_/ / / /_____/ __/ / / / /
(__ ) /_/ / /_/ / /_/ / __/ /_/ /_____/ /_/ /_/ / /
/____/ .___/\\____/\\__/_/_/ \\__, / \\__/\\__,_/_/
/_/ /____/
";
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/network.rs | src/network.rs | use crate::app::{
ActiveBlock, AlbumTableContext, App, Artist, ArtistBlock, EpisodeTableContext, RouteId,
ScrollableResultPages, SelectedAlbum, SelectedFullAlbum, SelectedFullShow, SelectedShow,
TrackTableContext,
};
use crate::config::ClientConfig;
use anyhow::anyhow;
use rspotify::{
client::Spotify,
model::{
album::SimplifiedAlbum,
artist::FullArtist,
offset::for_position,
page::Page,
playlist::{PlaylistTrack, SimplifiedPlaylist},
recommend::Recommendations,
search::SearchResult,
show::SimplifiedShow,
track::FullTrack,
PlayingItem,
},
oauth2::{SpotifyClientCredentials, SpotifyOAuth, TokenInfo},
senum::{AdditionalType, Country, RepeatState, SearchType},
util::get_token,
};
use serde_json::{map::Map, Value};
use std::{
sync::Arc,
time::{Duration, Instant, SystemTime},
};
use tokio::sync::Mutex;
use tokio::try_join;
#[derive(Debug)]
pub enum IoEvent {
GetCurrentPlayback,
RefreshAuthentication,
GetPlaylists,
GetDevices,
GetSearchResults(String, Option<Country>),
SetTracksToTable(Vec<FullTrack>),
GetMadeForYouPlaylistTracks(String, u32),
GetPlaylistTracks(String, u32),
GetCurrentSavedTracks(Option<u32>),
StartPlayback(Option<String>, Option<Vec<String>>, Option<usize>),
UpdateSearchLimits(u32, u32),
Seek(u32),
NextTrack,
PreviousTrack,
Shuffle(bool),
Repeat(RepeatState),
PausePlayback,
ChangeVolume(u8),
GetArtist(String, String, Option<Country>),
GetAlbumTracks(Box<SimplifiedAlbum>),
GetRecommendationsForSeed(
Option<Vec<String>>,
Option<Vec<String>>,
Box<Option<FullTrack>>,
Option<Country>,
),
GetCurrentUserSavedAlbums(Option<u32>),
CurrentUserSavedAlbumsContains(Vec<String>),
CurrentUserSavedAlbumDelete(String),
CurrentUserSavedAlbumAdd(String),
UserUnfollowArtists(Vec<String>),
UserFollowArtists(Vec<String>),
UserFollowPlaylist(String, String, Option<bool>),
UserUnfollowPlaylist(String, String),
MadeForYouSearchAndAdd(String, Option<Country>),
GetAudioAnalysis(String),
GetUser,
ToggleSaveTrack(String),
GetRecommendationsForTrackId(String, Option<Country>),
GetRecentlyPlayed,
GetFollowedArtists(Option<String>),
SetArtistsToTable(Vec<FullArtist>),
UserArtistFollowCheck(Vec<String>),
GetAlbum(String),
TransferPlaybackToDevice(String),
GetAlbumForTrack(String),
CurrentUserSavedTracksContains(Vec<String>),
GetCurrentUserSavedShows(Option<u32>),
CurrentUserSavedShowsContains(Vec<String>),
CurrentUserSavedShowDelete(String),
CurrentUserSavedShowAdd(String),
GetShowEpisodes(Box<SimplifiedShow>),
GetShow(String),
GetCurrentShowEpisodes(String, Option<u32>),
AddItemToQueue(String),
}
pub fn get_spotify(token_info: TokenInfo) -> (Spotify, SystemTime) {
let token_expiry = {
if let Some(expires_at) = token_info.expires_at {
SystemTime::UNIX_EPOCH
+ Duration::from_secs(expires_at as u64)
// Set 10 seconds early
- Duration::from_secs(10)
} else {
SystemTime::now()
}
};
let client_credential = SpotifyClientCredentials::default()
.token_info(token_info)
.build();
let spotify = Spotify::default()
.client_credentials_manager(client_credential)
.build();
(spotify, token_expiry)
}
#[derive(Clone)]
pub struct Network<'a> {
oauth: SpotifyOAuth,
pub spotify: Spotify,
large_search_limit: u32,
small_search_limit: u32,
pub client_config: ClientConfig,
pub app: &'a Arc<Mutex<App>>,
}
impl<'a> Network<'a> {
pub fn new(
oauth: SpotifyOAuth,
spotify: Spotify,
client_config: ClientConfig,
app: &'a Arc<Mutex<App>>,
) -> Self {
Network {
oauth,
spotify,
large_search_limit: 20,
small_search_limit: 4,
client_config,
app,
}
}
#[allow(clippy::cognitive_complexity)]
pub async fn handle_network_event(&mut self, io_event: IoEvent) {
match io_event {
IoEvent::RefreshAuthentication => {
self.refresh_authentication().await;
}
IoEvent::GetPlaylists => {
self.get_current_user_playlists().await;
}
IoEvent::GetUser => {
self.get_user().await;
}
IoEvent::GetDevices => {
self.get_devices().await;
}
IoEvent::GetCurrentPlayback => {
self.get_current_playback().await;
}
IoEvent::SetTracksToTable(full_tracks) => {
self.set_tracks_to_table(full_tracks).await;
}
IoEvent::GetSearchResults(search_term, country) => {
self.get_search_results(search_term, country).await;
}
IoEvent::GetMadeForYouPlaylistTracks(playlist_id, made_for_you_offset) => {
self
.get_made_for_you_playlist_tracks(playlist_id, made_for_you_offset)
.await;
}
IoEvent::GetPlaylistTracks(playlist_id, playlist_offset) => {
self.get_playlist_tracks(playlist_id, playlist_offset).await;
}
IoEvent::GetCurrentSavedTracks(offset) => {
self.get_current_user_saved_tracks(offset).await;
}
IoEvent::StartPlayback(context_uri, uris, offset) => {
self.start_playback(context_uri, uris, offset).await;
}
IoEvent::UpdateSearchLimits(large_search_limit, small_search_limit) => {
self.large_search_limit = large_search_limit;
self.small_search_limit = small_search_limit;
}
IoEvent::Seek(position_ms) => {
self.seek(position_ms).await;
}
IoEvent::NextTrack => {
self.next_track().await;
}
IoEvent::PreviousTrack => {
self.previous_track().await;
}
IoEvent::Repeat(repeat_state) => {
self.repeat(repeat_state).await;
}
IoEvent::PausePlayback => {
self.pause_playback().await;
}
IoEvent::ChangeVolume(volume) => {
self.change_volume(volume).await;
}
IoEvent::GetArtist(artist_id, input_artist_name, country) => {
self.get_artist(artist_id, input_artist_name, country).await;
}
IoEvent::GetAlbumTracks(album) => {
self.get_album_tracks(album).await;
}
IoEvent::GetRecommendationsForSeed(seed_artists, seed_tracks, first_track, country) => {
self
.get_recommendations_for_seed(seed_artists, seed_tracks, first_track, country)
.await;
}
IoEvent::GetCurrentUserSavedAlbums(offset) => {
self.get_current_user_saved_albums(offset).await;
}
IoEvent::CurrentUserSavedAlbumsContains(album_ids) => {
self.current_user_saved_albums_contains(album_ids).await;
}
IoEvent::CurrentUserSavedAlbumDelete(album_id) => {
self.current_user_saved_album_delete(album_id).await;
}
IoEvent::CurrentUserSavedAlbumAdd(album_id) => {
self.current_user_saved_album_add(album_id).await;
}
IoEvent::UserUnfollowArtists(artist_ids) => {
self.user_unfollow_artists(artist_ids).await;
}
IoEvent::UserFollowArtists(artist_ids) => {
self.user_follow_artists(artist_ids).await;
}
IoEvent::UserFollowPlaylist(playlist_owner_id, playlist_id, is_public) => {
self
.user_follow_playlist(playlist_owner_id, playlist_id, is_public)
.await;
}
IoEvent::UserUnfollowPlaylist(user_id, playlist_id) => {
self.user_unfollow_playlist(user_id, playlist_id).await;
}
IoEvent::MadeForYouSearchAndAdd(search_term, country) => {
self.made_for_you_search_and_add(search_term, country).await;
}
IoEvent::GetAudioAnalysis(uri) => {
self.get_audio_analysis(uri).await;
}
IoEvent::ToggleSaveTrack(track_id) => {
self.toggle_save_track(track_id).await;
}
IoEvent::GetRecommendationsForTrackId(track_id, country) => {
self
.get_recommendations_for_track_id(track_id, country)
.await;
}
IoEvent::GetRecentlyPlayed => {
self.get_recently_played().await;
}
IoEvent::GetFollowedArtists(after) => {
self.get_followed_artists(after).await;
}
IoEvent::SetArtistsToTable(full_artists) => {
self.set_artists_to_table(full_artists).await;
}
IoEvent::UserArtistFollowCheck(artist_ids) => {
self.user_artist_check_follow(artist_ids).await;
}
IoEvent::GetAlbum(album_id) => {
self.get_album(album_id).await;
}
IoEvent::TransferPlaybackToDevice(device_id) => {
self.transfert_playback_to_device(device_id).await;
}
IoEvent::GetAlbumForTrack(track_id) => {
self.get_album_for_track(track_id).await;
}
IoEvent::Shuffle(shuffle_state) => {
self.shuffle(shuffle_state).await;
}
IoEvent::CurrentUserSavedTracksContains(track_ids) => {
self.current_user_saved_tracks_contains(track_ids).await;
}
IoEvent::GetCurrentUserSavedShows(offset) => {
self.get_current_user_saved_shows(offset).await;
}
IoEvent::CurrentUserSavedShowsContains(show_ids) => {
self.current_user_saved_shows_contains(show_ids).await;
}
IoEvent::CurrentUserSavedShowDelete(show_id) => {
self.current_user_saved_shows_delete(show_id).await;
}
IoEvent::CurrentUserSavedShowAdd(show_id) => {
self.current_user_saved_shows_add(show_id).await;
}
IoEvent::GetShowEpisodes(show) => {
self.get_show_episodes(show).await;
}
IoEvent::GetShow(show_id) => {
self.get_show(show_id).await;
}
IoEvent::GetCurrentShowEpisodes(show_id, offset) => {
self.get_current_show_episodes(show_id, offset).await;
}
IoEvent::AddItemToQueue(item) => {
self.add_item_to_queue(item).await;
}
};
let mut app = self.app.lock().await;
app.is_loading = false;
}
async fn handle_error(&mut self, e: anyhow::Error) {
let mut app = self.app.lock().await;
app.handle_error(e);
}
async fn get_user(&mut self) {
match self.spotify.current_user().await {
Ok(user) => {
let mut app = self.app.lock().await;
app.user = Some(user);
}
Err(e) => {
self.handle_error(anyhow!(e)).await;
}
}
}
async fn get_devices(&mut self) {
if let Ok(result) = self.spotify.device().await {
let mut app = self.app.lock().await;
app.push_navigation_stack(RouteId::SelectedDevice, ActiveBlock::SelectDevice);
if !result.devices.is_empty() {
app.devices = Some(result);
// Select the first device in the list
app.selected_device_index = Some(0);
}
}
}
async fn get_current_playback(&mut self) {
let context = self
.spotify
.current_playback(
None,
Some(vec![AdditionalType::Episode, AdditionalType::Track]),
)
.await;
match context {
Ok(Some(c)) => {
let mut app = self.app.lock().await;
app.current_playback_context = Some(c.clone());
app.instant_since_last_current_playback_poll = Instant::now();
if let Some(item) = c.item {
match item {
PlayingItem::Track(track) => {
if let Some(track_id) = track.id {
app.dispatch(IoEvent::CurrentUserSavedTracksContains(vec![track_id]));
};
}
PlayingItem::Episode(_episode) => { /*should map this to following the podcast show*/ }
}
};
}
Ok(None) => {
let mut app = self.app.lock().await;
app.instant_since_last_current_playback_poll = Instant::now();
}
Err(e) => {
self.handle_error(anyhow!(e)).await;
}
}
let mut app = self.app.lock().await;
app.seek_ms.take();
app.is_fetching_current_playback = false;
}
async fn current_user_saved_tracks_contains(&mut self, ids: Vec<String>) {
match self.spotify.current_user_saved_tracks_contains(&ids).await {
Ok(is_saved_vec) => {
let mut app = self.app.lock().await;
for (i, id) in ids.iter().enumerate() {
if let Some(is_liked) = is_saved_vec.get(i) {
if *is_liked {
app.liked_song_ids_set.insert(id.to_string());
} else {
// The song is not liked, so check if it should be removed
if app.liked_song_ids_set.contains(id) {
app.liked_song_ids_set.remove(id);
}
}
};
}
}
Err(e) => {
self.handle_error(anyhow!(e)).await;
}
}
}
async fn get_playlist_tracks(&mut self, playlist_id: String, playlist_offset: u32) {
if let Ok(playlist_tracks) = self
.spotify
.user_playlist_tracks(
"spotify",
&playlist_id,
None,
Some(self.large_search_limit),
Some(playlist_offset),
None,
)
.await
{
self.set_playlist_tracks_to_table(&playlist_tracks).await;
let mut app = self.app.lock().await;
app.playlist_tracks = Some(playlist_tracks);
app.push_navigation_stack(RouteId::TrackTable, ActiveBlock::TrackTable);
};
}
async fn set_playlist_tracks_to_table(&mut self, playlist_track_page: &Page<PlaylistTrack>) {
self
.set_tracks_to_table(
playlist_track_page
.items
.clone()
.into_iter()
.filter_map(|item| item.track)
.collect::<Vec<FullTrack>>(),
)
.await;
}
async fn set_tracks_to_table(&mut self, tracks: Vec<FullTrack>) {
let mut app = self.app.lock().await;
app.track_table.tracks = tracks.clone();
// Send this event round (don't block here)
app.dispatch(IoEvent::CurrentUserSavedTracksContains(
tracks
.into_iter()
.filter_map(|item| item.id)
.collect::<Vec<String>>(),
));
}
async fn set_artists_to_table(&mut self, artists: Vec<FullArtist>) {
let mut app = self.app.lock().await;
app.artists = artists;
}
async fn get_made_for_you_playlist_tracks(
&mut self,
playlist_id: String,
made_for_you_offset: u32,
) {
if let Ok(made_for_you_tracks) = self
.spotify
.user_playlist_tracks(
"spotify",
&playlist_id,
None,
Some(self.large_search_limit),
Some(made_for_you_offset),
None,
)
.await
{
self
.set_playlist_tracks_to_table(&made_for_you_tracks)
.await;
let mut app = self.app.lock().await;
app.made_for_you_tracks = Some(made_for_you_tracks);
if app.get_current_route().id != RouteId::TrackTable {
app.push_navigation_stack(RouteId::TrackTable, ActiveBlock::TrackTable);
}
}
}
async fn get_current_user_saved_shows(&mut self, offset: Option<u32>) {
match self
.spotify
.get_saved_show(self.large_search_limit, offset)
.await
{
Ok(saved_shows) => {
// not to show a blank page
if !saved_shows.items.is_empty() {
let mut app = self.app.lock().await;
app.library.saved_shows.add_pages(saved_shows);
}
}
Err(e) => {
self.handle_error(anyhow!(e)).await;
}
}
}
async fn current_user_saved_shows_contains(&mut self, show_ids: Vec<String>) {
if let Ok(are_followed) = self
.spotify
.check_users_saved_shows(show_ids.to_owned())
.await
{
let mut app = self.app.lock().await;
show_ids.iter().enumerate().for_each(|(i, id)| {
if are_followed[i] {
app.saved_show_ids_set.insert(id.to_owned());
} else {
app.saved_show_ids_set.remove(id);
}
})
}
}
async fn get_show_episodes(&mut self, show: Box<SimplifiedShow>) {
match self
.spotify
.get_shows_episodes(show.id.clone(), self.large_search_limit, 0, None)
.await
{
Ok(episodes) => {
if !episodes.items.is_empty() {
let mut app = self.app.lock().await;
app.library.show_episodes = ScrollableResultPages::new();
app.library.show_episodes.add_pages(episodes);
app.selected_show_simplified = Some(SelectedShow { show: *show });
app.episode_table_context = EpisodeTableContext::Simplified;
app.push_navigation_stack(RouteId::PodcastEpisodes, ActiveBlock::EpisodeTable);
}
}
Err(e) => {
self.handle_error(anyhow!(e)).await;
}
}
}
async fn get_show(&mut self, show_id: String) {
match self.spotify.get_a_show(show_id, None).await {
Ok(show) => {
let selected_show = SelectedFullShow { show };
let mut app = self.app.lock().await;
app.selected_show_full = Some(selected_show);
app.episode_table_context = EpisodeTableContext::Full;
app.push_navigation_stack(RouteId::PodcastEpisodes, ActiveBlock::EpisodeTable);
}
Err(e) => {
self.handle_error(anyhow!(e)).await;
}
}
}
async fn get_current_show_episodes(&mut self, show_id: String, offset: Option<u32>) {
match self
.spotify
.get_shows_episodes(show_id, self.large_search_limit, offset, None)
.await
{
Ok(episodes) => {
if !episodes.items.is_empty() {
let mut app = self.app.lock().await;
app.library.show_episodes.add_pages(episodes);
}
}
Err(e) => {
self.handle_error(anyhow!(e)).await;
}
}
}
async fn get_search_results(&mut self, search_term: String, country: Option<Country>) {
let search_track = self.spotify.search(
&search_term,
SearchType::Track,
self.small_search_limit,
0,
country,
None,
);
let search_artist = self.spotify.search(
&search_term,
SearchType::Artist,
self.small_search_limit,
0,
country,
None,
);
let search_album = self.spotify.search(
&search_term,
SearchType::Album,
self.small_search_limit,
0,
country,
None,
);
let search_playlist = self.spotify.search(
&search_term,
SearchType::Playlist,
self.small_search_limit,
0,
country,
None,
);
let search_show = self.spotify.search(
&search_term,
SearchType::Show,
self.small_search_limit,
0,
country,
None,
);
// Run the futures concurrently
match try_join!(
search_track,
search_artist,
search_album,
search_playlist,
search_show
) {
Ok((
SearchResult::Tracks(track_results),
SearchResult::Artists(artist_results),
SearchResult::Albums(album_results),
SearchResult::Playlists(playlist_results),
SearchResult::Shows(show_results),
)) => {
let mut app = self.app.lock().await;
let artist_ids = album_results
.items
.iter()
.filter_map(|item| item.id.to_owned())
.collect();
// Check if these artists are followed
app.dispatch(IoEvent::UserArtistFollowCheck(artist_ids));
let album_ids = album_results
.items
.iter()
.filter_map(|album| album.id.to_owned())
.collect();
// Check if these albums are saved
app.dispatch(IoEvent::CurrentUserSavedAlbumsContains(album_ids));
let show_ids = show_results
.items
.iter()
.map(|show| show.id.to_owned())
.collect();
// check if these shows are saved
app.dispatch(IoEvent::CurrentUserSavedShowsContains(show_ids));
app.search_results.tracks = Some(track_results);
app.search_results.artists = Some(artist_results);
app.search_results.albums = Some(album_results);
app.search_results.playlists = Some(playlist_results);
app.search_results.shows = Some(show_results);
}
Err(e) => {
self.handle_error(anyhow!(e)).await;
}
_ => {}
};
}
async fn get_current_user_saved_tracks(&mut self, offset: Option<u32>) {
match self
.spotify
.current_user_saved_tracks(self.large_search_limit, offset)
.await
{
Ok(saved_tracks) => {
let mut app = self.app.lock().await;
app.track_table.tracks = saved_tracks
.items
.clone()
.into_iter()
.map(|item| item.track)
.collect::<Vec<FullTrack>>();
saved_tracks.items.iter().for_each(|item| {
if let Some(track_id) = &item.track.id {
app.liked_song_ids_set.insert(track_id.to_string());
}
});
app.library.saved_tracks.add_pages(saved_tracks);
app.track_table.context = Some(TrackTableContext::SavedTracks);
}
Err(e) => {
self.handle_error(anyhow!(e)).await;
}
}
}
async fn start_playback(
&mut self,
context_uri: Option<String>,
uris: Option<Vec<String>>,
offset: Option<usize>,
) {
let (uris, context_uri) = if context_uri.is_some() {
(None, context_uri)
} else if uris.is_some() {
(uris, None)
} else {
(None, None)
};
let offset = offset.and_then(|o| for_position(o as u32));
let result = match &self.client_config.device_id {
Some(device_id) => {
match self
.spotify
.start_playback(
Some(device_id.to_string()),
context_uri.clone(),
uris.clone(),
offset.clone(),
None,
)
.await
{
Ok(()) => Ok(()),
Err(e) => Err(anyhow!(e)),
}
}
None => Err(anyhow!("No device_id selected")),
};
match result {
Ok(()) => {
let mut app = self.app.lock().await;
app.song_progress_ms = 0;
app.dispatch(IoEvent::GetCurrentPlayback);
}
Err(e) => {
self.handle_error(e).await;
}
}
}
async fn seek(&mut self, position_ms: u32) {
if let Some(device_id) = &self.client_config.device_id {
match self
.spotify
.seek_track(position_ms, Some(device_id.to_string()))
.await
{
Ok(()) => {
// Wait between seek and status query.
// Without it, the Spotify API may return the old progress.
tokio::time::delay_for(Duration::from_millis(1000)).await;
self.get_current_playback().await;
}
Err(e) => {
self.handle_error(anyhow!(e)).await;
}
};
}
}
async fn next_track(&mut self) {
match self
.spotify
.next_track(self.client_config.device_id.clone())
.await
{
Ok(()) => {
self.get_current_playback().await;
}
Err(e) => {
self.handle_error(anyhow!(e)).await;
}
};
}
async fn previous_track(&mut self) {
match self
.spotify
.previous_track(self.client_config.device_id.clone())
.await
{
Ok(()) => {
self.get_current_playback().await;
}
Err(e) => {
self.handle_error(anyhow!(e)).await;
}
};
}
async fn shuffle(&mut self, shuffle_state: bool) {
match self
.spotify
.shuffle(!shuffle_state, self.client_config.device_id.clone())
.await
{
Ok(()) => {
// Update the UI eagerly (otherwise the UI will wait until the next 5 second interval
// due to polling playback context)
let mut app = self.app.lock().await;
if let Some(current_playback_context) = &mut app.current_playback_context {
current_playback_context.shuffle_state = !shuffle_state;
};
}
Err(e) => {
self.handle_error(anyhow!(e)).await;
}
};
}
async fn repeat(&mut self, repeat_state: RepeatState) {
let next_repeat_state = match repeat_state {
RepeatState::Off => RepeatState::Context,
RepeatState::Context => RepeatState::Track,
RepeatState::Track => RepeatState::Off,
};
match self
.spotify
.repeat(next_repeat_state, self.client_config.device_id.clone())
.await
{
Ok(()) => {
let mut app = self.app.lock().await;
if let Some(current_playback_context) = &mut app.current_playback_context {
current_playback_context.repeat_state = next_repeat_state;
};
}
Err(e) => {
self.handle_error(anyhow!(e)).await;
}
};
}
async fn pause_playback(&mut self) {
match self
.spotify
.pause_playback(self.client_config.device_id.clone())
.await
{
Ok(()) => {
self.get_current_playback().await;
}
Err(e) => {
self.handle_error(anyhow!(e)).await;
}
};
}
async fn change_volume(&mut self, volume_percent: u8) {
match self
.spotify
.volume(volume_percent, self.client_config.device_id.clone())
.await
{
Ok(()) => {
let mut app = self.app.lock().await;
if let Some(current_playback_context) = &mut app.current_playback_context {
current_playback_context.device.volume_percent = volume_percent.into();
};
}
Err(e) => {
self.handle_error(anyhow!(e)).await;
}
};
}
async fn get_artist(
&mut self,
artist_id: String,
input_artist_name: String,
country: Option<Country>,
) {
let albums = self.spotify.artist_albums(
&artist_id,
None,
country,
Some(self.large_search_limit),
Some(0),
);
let artist_name = if input_artist_name.is_empty() {
self
.spotify
.artist(&artist_id)
.await
.map(|full_artist| full_artist.name)
.unwrap_or_default()
} else {
input_artist_name
};
let top_tracks = self.spotify.artist_top_tracks(&artist_id, country);
let related_artist = self.spotify.artist_related_artists(&artist_id);
if let Ok((albums, top_tracks, related_artist)) = try_join!(albums, top_tracks, related_artist)
{
let mut app = self.app.lock().await;
app.dispatch(IoEvent::CurrentUserSavedAlbumsContains(
albums
.items
.iter()
.filter_map(|item| item.id.to_owned())
.collect(),
));
app.artist = Some(Artist {
artist_name,
albums,
related_artists: related_artist.artists,
top_tracks: top_tracks.tracks,
selected_album_index: 0,
selected_related_artist_index: 0,
selected_top_track_index: 0,
artist_hovered_block: ArtistBlock::TopTracks,
artist_selected_block: ArtistBlock::Empty,
});
}
}
async fn get_album_tracks(&mut self, album: Box<SimplifiedAlbum>) {
if let Some(album_id) = &album.id {
match self
.spotify
.album_track(&album_id.clone(), self.large_search_limit, 0)
.await
{
Ok(tracks) => {
let track_ids = tracks
.items
.iter()
.filter_map(|item| item.id.clone())
.collect::<Vec<String>>();
let mut app = self.app.lock().await;
app.selected_album_simplified = Some(SelectedAlbum {
album: *album,
tracks,
selected_index: 0,
});
app.album_table_context = AlbumTableContext::Simplified;
app.push_navigation_stack(RouteId::AlbumTracks, ActiveBlock::AlbumTracks);
app.dispatch(IoEvent::CurrentUserSavedTracksContains(track_ids));
}
Err(e) => {
self.handle_error(anyhow!(e)).await;
}
}
}
}
async fn get_recommendations_for_seed(
&mut self,
seed_artists: Option<Vec<String>>,
seed_tracks: Option<Vec<String>>,
first_track: Box<Option<FullTrack>>,
country: Option<Country>,
) {
let empty_payload: Map<String, Value> = Map::new();
match self
.spotify
.recommendations(
seed_artists, // artists
None, // genres
seed_tracks, // tracks
self.large_search_limit, // adjust playlist to screen size
country, // country
&empty_payload, // payload
)
.await
{
Ok(result) => {
if let Some(mut recommended_tracks) = self.extract_recommended_tracks(&result).await {
//custom first track
if let Some(track) = *first_track {
recommended_tracks.insert(0, track);
}
let track_ids = recommended_tracks
.iter()
.map(|x| x.uri.clone())
.collect::<Vec<String>>();
self.set_tracks_to_table(recommended_tracks.clone()).await;
let mut app = self.app.lock().await;
app.recommended_tracks = recommended_tracks;
app.track_table.context = Some(TrackTableContext::RecommendedTracks);
if app.get_current_route().id != RouteId::Recommendations {
app.push_navigation_stack(RouteId::Recommendations, ActiveBlock::TrackTable);
};
app.dispatch(IoEvent::StartPlayback(None, Some(track_ids), Some(0)));
}
}
Err(e) => {
self.handle_error(anyhow!(e)).await;
}
}
}
async fn extract_recommended_tracks(
&mut self,
recommendations: &Recommendations,
) -> Option<Vec<FullTrack>> {
let tracks = recommendations
.clone()
.tracks
.into_iter()
.map(|item| item.uri)
.collect::<Vec<String>>();
if let Ok(result) = self
.spotify
.tracks(tracks.iter().map(|x| &x[..]).collect::<Vec<&str>>(), None)
.await
{
return Some(result.tracks);
}
None
}
async fn get_recommendations_for_track_id(&mut self, id: String, country: Option<Country>) {
if let Ok(track) = self.spotify.track(&id).await {
let track_id_list = track.id.as_ref().map(|id| vec![id.to_string()]);
self
.get_recommendations_for_seed(None, track_id_list, Box::new(Some(track)), country)
.await;
}
}
async fn toggle_save_track(&mut self, track_id: String) {
match self
.spotify
.current_user_saved_tracks_contains(&[track_id.clone()])
.await
{
Ok(saved) => {
if saved.first() == Some(&true) {
match self
.spotify
.current_user_saved_tracks_delete(&[track_id.clone()])
.await
{
Ok(()) => {
let mut app = self.app.lock().await;
app.liked_song_ids_set.remove(&track_id);
}
Err(e) => {
self.handle_error(anyhow!(e)).await;
}
}
} else {
match self
.spotify
.current_user_saved_tracks_add(&[track_id.clone()])
.await
{
Ok(()) => {
// TODO: This should ideally use the same logic as `self.current_user_saved_tracks_contains`
let mut app = self.app.lock().await;
app.liked_song_ids_set.insert(track_id);
}
Err(e) => {
self.handle_error(anyhow!(e)).await;
}
}
}
}
Err(e) => {
self.handle_error(anyhow!(e)).await;
}
};
}
async fn get_followed_artists(&mut self, after: Option<String>) {
match self
.spotify
.current_user_followed_artists(self.large_search_limit, after)
.await
{
Ok(saved_artists) => {
let mut app = self.app.lock().await;
app.artists = saved_artists.artists.items.to_owned();
app.library.saved_artists.add_pages(saved_artists.artists);
}
Err(e) => {
self.handle_error(anyhow!(e)).await;
}
};
}
async fn user_artist_check_follow(&mut self, artist_ids: Vec<String>) {
if let Ok(are_followed) = self.spotify.user_artist_check_follow(&artist_ids).await {
let mut app = self.app.lock().await;
artist_ids.iter().enumerate().for_each(|(i, id)| {
if are_followed[i] {
app.followed_artist_ids_set.insert(id.to_owned());
} else {
app.followed_artist_ids_set.remove(id);
}
});
}
}
async fn get_current_user_saved_albums(&mut self, offset: Option<u32>) {
match self
.spotify
.current_user_saved_albums(self.large_search_limit, offset)
.await
{
Ok(saved_albums) => {
// not to show a blank page
if !saved_albums.items.is_empty() {
let mut app = self.app.lock().await;
app.library.saved_albums.add_pages(saved_albums);
}
}
Err(e) => {
self.handle_error(anyhow!(e)).await;
}
};
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | true |
Rigellute/spotify-tui | https://github.com/Rigellute/spotify-tui/blob/c4dcf6b9fd8318017acbdd7ec005955e26cf2794/src/user_config.rs | src/user_config.rs | use crate::event::Key;
use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use std::{
fs,
path::{Path, PathBuf},
};
use tui::style::Color;
const FILE_NAME: &str = "config.yml";
const CONFIG_DIR: &str = ".config";
const APP_CONFIG_DIR: &str = "spotify-tui";
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct UserTheme {
pub active: Option<String>,
pub banner: Option<String>,
pub error_border: Option<String>,
pub error_text: Option<String>,
pub hint: Option<String>,
pub hovered: Option<String>,
pub inactive: Option<String>,
pub playbar_background: Option<String>,
pub playbar_progress: Option<String>,
pub playbar_progress_text: Option<String>,
pub playbar_text: Option<String>,
pub selected: Option<String>,
pub text: Option<String>,
pub header: Option<String>,
}
#[derive(Copy, Clone, Debug)]
pub struct Theme {
pub analysis_bar: Color,
pub analysis_bar_text: Color,
pub active: Color,
pub banner: Color,
pub error_border: Color,
pub error_text: Color,
pub hint: Color,
pub hovered: Color,
pub inactive: Color,
pub playbar_background: Color,
pub playbar_progress: Color,
pub playbar_progress_text: Color,
pub playbar_text: Color,
pub selected: Color,
pub text: Color,
pub header: Color,
}
impl Default for Theme {
fn default() -> Self {
Theme {
analysis_bar: Color::LightCyan,
analysis_bar_text: Color::Reset,
active: Color::Cyan,
banner: Color::LightCyan,
error_border: Color::Red,
error_text: Color::LightRed,
hint: Color::Yellow,
hovered: Color::Magenta,
inactive: Color::Gray,
playbar_background: Color::Black,
playbar_progress: Color::LightCyan,
playbar_progress_text: Color::LightCyan,
playbar_text: Color::Reset,
selected: Color::LightCyan,
text: Color::Reset,
header: Color::Reset,
}
}
}
fn parse_key(key: String) -> Result<Key> {
fn get_single_char(string: &str) -> char {
match string.chars().next() {
Some(c) => c,
None => panic!(),
}
}
match key.len() {
1 => Ok(Key::Char(get_single_char(key.as_str()))),
_ => {
let sections: Vec<&str> = key.split('-').collect();
if sections.len() > 2 {
return Err(anyhow!(
"Shortcut can only have 2 keys, \"{}\" has {}",
key,
sections.len()
));
}
match sections[0].to_lowercase().as_str() {
"ctrl" => Ok(Key::Ctrl(get_single_char(sections[1]))),
"alt" => Ok(Key::Alt(get_single_char(sections[1]))),
"left" => Ok(Key::Left),
"right" => Ok(Key::Right),
"up" => Ok(Key::Up),
"down" => Ok(Key::Down),
"backspace" | "delete" => Ok(Key::Backspace),
"del" => Ok(Key::Delete),
"esc" | "escape" => Ok(Key::Esc),
"pageup" => Ok(Key::PageUp),
"pagedown" => Ok(Key::PageDown),
"space" => Ok(Key::Char(' ')),
_ => Err(anyhow!("The key \"{}\" is unknown.", sections[0])),
}
}
}
}
fn check_reserved_keys(key: Key) -> Result<()> {
let reserved = [
Key::Char('h'),
Key::Char('j'),
Key::Char('k'),
Key::Char('l'),
Key::Char('H'),
Key::Char('M'),
Key::Char('L'),
Key::Up,
Key::Down,
Key::Left,
Key::Right,
Key::Backspace,
Key::Enter,
];
for item in reserved.iter() {
if key == *item {
// TODO: Add pretty print for key
return Err(anyhow!(
"The key {:?} is reserved and cannot be remapped",
key
));
}
}
Ok(())
}
#[derive(Clone)]
pub struct UserConfigPaths {
pub config_file_path: PathBuf,
}
#[derive(Default, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct KeyBindingsString {
back: Option<String>,
next_page: Option<String>,
previous_page: Option<String>,
jump_to_start: Option<String>,
jump_to_end: Option<String>,
jump_to_album: Option<String>,
jump_to_artist_album: Option<String>,
jump_to_context: Option<String>,
manage_devices: Option<String>,
decrease_volume: Option<String>,
increase_volume: Option<String>,
toggle_playback: Option<String>,
seek_backwards: Option<String>,
seek_forwards: Option<String>,
next_track: Option<String>,
previous_track: Option<String>,
help: Option<String>,
shuffle: Option<String>,
repeat: Option<String>,
search: Option<String>,
submit: Option<String>,
copy_song_url: Option<String>,
copy_album_url: Option<String>,
audio_analysis: Option<String>,
basic_view: Option<String>,
add_item_to_queue: Option<String>,
}
#[derive(Clone)]
pub struct KeyBindings {
pub back: Key,
pub next_page: Key,
pub previous_page: Key,
pub jump_to_start: Key,
pub jump_to_end: Key,
pub jump_to_album: Key,
pub jump_to_artist_album: Key,
pub jump_to_context: Key,
pub manage_devices: Key,
pub decrease_volume: Key,
pub increase_volume: Key,
pub toggle_playback: Key,
pub seek_backwards: Key,
pub seek_forwards: Key,
pub next_track: Key,
pub previous_track: Key,
pub help: Key,
pub shuffle: Key,
pub repeat: Key,
pub search: Key,
pub submit: Key,
pub copy_song_url: Key,
pub copy_album_url: Key,
pub audio_analysis: Key,
pub basic_view: Key,
pub add_item_to_queue: Key,
}
#[derive(Default, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BehaviorConfigString {
pub seek_milliseconds: Option<u32>,
pub volume_increment: Option<u8>,
pub tick_rate_milliseconds: Option<u64>,
pub enable_text_emphasis: Option<bool>,
pub show_loading_indicator: Option<bool>,
pub enforce_wide_search_bar: Option<bool>,
pub liked_icon: Option<String>,
pub shuffle_icon: Option<String>,
pub repeat_track_icon: Option<String>,
pub repeat_context_icon: Option<String>,
pub playing_icon: Option<String>,
pub paused_icon: Option<String>,
pub set_window_title: Option<bool>,
}
#[derive(Clone)]
pub struct BehaviorConfig {
pub seek_milliseconds: u32,
pub volume_increment: u8,
pub tick_rate_milliseconds: u64,
pub enable_text_emphasis: bool,
pub show_loading_indicator: bool,
pub enforce_wide_search_bar: bool,
pub liked_icon: String,
pub shuffle_icon: String,
pub repeat_track_icon: String,
pub repeat_context_icon: String,
pub playing_icon: String,
pub paused_icon: String,
pub set_window_title: bool,
}
#[derive(Default, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UserConfigString {
keybindings: Option<KeyBindingsString>,
behavior: Option<BehaviorConfigString>,
theme: Option<UserTheme>,
}
#[derive(Clone)]
pub struct UserConfig {
pub keys: KeyBindings,
pub theme: Theme,
pub behavior: BehaviorConfig,
pub path_to_config: Option<UserConfigPaths>,
}
impl UserConfig {
pub fn new() -> UserConfig {
UserConfig {
theme: Default::default(),
keys: KeyBindings {
back: Key::Char('q'),
next_page: Key::Ctrl('d'),
previous_page: Key::Ctrl('u'),
jump_to_start: Key::Ctrl('a'),
jump_to_end: Key::Ctrl('e'),
jump_to_album: Key::Char('a'),
jump_to_artist_album: Key::Char('A'),
jump_to_context: Key::Char('o'),
manage_devices: Key::Char('d'),
decrease_volume: Key::Char('-'),
increase_volume: Key::Char('+'),
toggle_playback: Key::Char(' '),
seek_backwards: Key::Char('<'),
seek_forwards: Key::Char('>'),
next_track: Key::Char('n'),
previous_track: Key::Char('p'),
help: Key::Char('?'),
shuffle: Key::Ctrl('s'),
repeat: Key::Ctrl('r'),
search: Key::Char('/'),
submit: Key::Enter,
copy_song_url: Key::Char('c'),
copy_album_url: Key::Char('C'),
audio_analysis: Key::Char('v'),
basic_view: Key::Char('B'),
add_item_to_queue: Key::Char('z'),
},
behavior: BehaviorConfig {
seek_milliseconds: 5 * 1000,
volume_increment: 10,
tick_rate_milliseconds: 250,
enable_text_emphasis: true,
show_loading_indicator: true,
enforce_wide_search_bar: false,
liked_icon: "♥".to_string(),
shuffle_icon: "🔀".to_string(),
repeat_track_icon: "🔂".to_string(),
repeat_context_icon: "🔁".to_string(),
playing_icon: "▶".to_string(),
paused_icon: "⏸".to_string(),
set_window_title: true,
},
path_to_config: None,
}
}
pub fn get_or_build_paths(&mut self) -> Result<()> {
match dirs::home_dir() {
Some(home) => {
let path = Path::new(&home);
let home_config_dir = path.join(CONFIG_DIR);
let app_config_dir = home_config_dir.join(APP_CONFIG_DIR);
if !home_config_dir.exists() {
fs::create_dir(&home_config_dir)?;
}
if !app_config_dir.exists() {
fs::create_dir(&app_config_dir)?;
}
let config_file_path = &app_config_dir.join(FILE_NAME);
let paths = UserConfigPaths {
config_file_path: config_file_path.to_path_buf(),
};
self.path_to_config = Some(paths);
Ok(())
}
None => Err(anyhow!("No $HOME directory found for client config")),
}
}
pub fn load_keybindings(&mut self, keybindings: KeyBindingsString) -> Result<()> {
macro_rules! to_keys {
($name: ident) => {
if let Some(key_string) = keybindings.$name {
self.keys.$name = parse_key(key_string)?;
check_reserved_keys(self.keys.$name)?;
}
};
}
to_keys!(back);
to_keys!(next_page);
to_keys!(previous_page);
to_keys!(jump_to_start);
to_keys!(jump_to_end);
to_keys!(jump_to_album);
to_keys!(jump_to_artist_album);
to_keys!(jump_to_context);
to_keys!(manage_devices);
to_keys!(decrease_volume);
to_keys!(increase_volume);
to_keys!(toggle_playback);
to_keys!(seek_backwards);
to_keys!(seek_forwards);
to_keys!(next_track);
to_keys!(previous_track);
to_keys!(help);
to_keys!(shuffle);
to_keys!(repeat);
to_keys!(search);
to_keys!(submit);
to_keys!(copy_song_url);
to_keys!(copy_album_url);
to_keys!(audio_analysis);
to_keys!(basic_view);
to_keys!(add_item_to_queue);
Ok(())
}
pub fn load_theme(&mut self, theme: UserTheme) -> Result<()> {
macro_rules! to_theme_item {
($name: ident) => {
if let Some(theme_item) = theme.$name {
self.theme.$name = parse_theme_item(&theme_item)?;
}
};
}
to_theme_item!(active);
to_theme_item!(banner);
to_theme_item!(error_border);
to_theme_item!(error_text);
to_theme_item!(hint);
to_theme_item!(hovered);
to_theme_item!(inactive);
to_theme_item!(playbar_background);
to_theme_item!(playbar_progress);
to_theme_item!(playbar_progress_text);
to_theme_item!(playbar_text);
to_theme_item!(selected);
to_theme_item!(text);
to_theme_item!(header);
Ok(())
}
pub fn load_behaviorconfig(&mut self, behavior_config: BehaviorConfigString) -> Result<()> {
if let Some(behavior_string) = behavior_config.seek_milliseconds {
self.behavior.seek_milliseconds = behavior_string;
}
if let Some(behavior_string) = behavior_config.volume_increment {
if behavior_string > 100 {
return Err(anyhow!(
"Volume increment must be between 0 and 100, is {}",
behavior_string,
));
}
self.behavior.volume_increment = behavior_string;
}
if let Some(tick_rate) = behavior_config.tick_rate_milliseconds {
if tick_rate >= 1000 {
return Err(anyhow!("Tick rate must be below 1000"));
} else {
self.behavior.tick_rate_milliseconds = tick_rate;
}
}
if let Some(text_emphasis) = behavior_config.enable_text_emphasis {
self.behavior.enable_text_emphasis = text_emphasis;
}
if let Some(loading_indicator) = behavior_config.show_loading_indicator {
self.behavior.show_loading_indicator = loading_indicator;
}
if let Some(wide_search_bar) = behavior_config.enforce_wide_search_bar {
self.behavior.enforce_wide_search_bar = wide_search_bar;
}
if let Some(liked_icon) = behavior_config.liked_icon {
self.behavior.liked_icon = liked_icon;
}
if let Some(paused_icon) = behavior_config.paused_icon {
self.behavior.paused_icon = paused_icon;
}
if let Some(playing_icon) = behavior_config.playing_icon {
self.behavior.playing_icon = playing_icon;
}
if let Some(shuffle_icon) = behavior_config.shuffle_icon {
self.behavior.shuffle_icon = shuffle_icon;
}
if let Some(repeat_track_icon) = behavior_config.repeat_track_icon {
self.behavior.repeat_track_icon = repeat_track_icon;
}
if let Some(repeat_context_icon) = behavior_config.repeat_context_icon {
self.behavior.repeat_context_icon = repeat_context_icon;
}
if let Some(set_window_title) = behavior_config.set_window_title {
self.behavior.set_window_title = set_window_title;
}
Ok(())
}
pub fn load_config(&mut self) -> Result<()> {
let paths = match &self.path_to_config {
Some(path) => path,
None => {
self.get_or_build_paths()?;
self.path_to_config.as_ref().unwrap()
}
};
if paths.config_file_path.exists() {
let config_string = fs::read_to_string(&paths.config_file_path)?;
// serde fails if file is empty
if config_string.trim().is_empty() {
return Ok(());
}
let config_yml: UserConfigString = serde_yaml::from_str(&config_string)?;
if let Some(keybindings) = config_yml.keybindings.clone() {
self.load_keybindings(keybindings)?;
}
if let Some(behavior) = config_yml.behavior {
self.load_behaviorconfig(behavior)?;
}
if let Some(theme) = config_yml.theme {
self.load_theme(theme)?;
}
Ok(())
} else {
Ok(())
}
}
pub fn padded_liked_icon(&self) -> String {
format!("{} ", &self.behavior.liked_icon)
}
}
fn parse_theme_item(theme_item: &str) -> Result<Color> {
let color = match theme_item {
"Reset" => Color::Reset,
"Black" => Color::Black,
"Red" => Color::Red,
"Green" => Color::Green,
"Yellow" => Color::Yellow,
"Blue" => Color::Blue,
"Magenta" => Color::Magenta,
"Cyan" => Color::Cyan,
"Gray" => Color::Gray,
"DarkGray" => Color::DarkGray,
"LightRed" => Color::LightRed,
"LightGreen" => Color::LightGreen,
"LightYellow" => Color::LightYellow,
"LightBlue" => Color::LightBlue,
"LightMagenta" => Color::LightMagenta,
"LightCyan" => Color::LightCyan,
"White" => Color::White,
_ => {
let colors = theme_item.split(',').collect::<Vec<&str>>();
if let (Some(r), Some(g), Some(b)) = (colors.get(0), colors.get(1), colors.get(2)) {
Color::Rgb(
r.trim().parse::<u8>()?,
g.trim().parse::<u8>()?,
b.trim().parse::<u8>()?,
)
} else {
println!("Unexpected color {}", theme_item);
Color::Black
}
}
};
Ok(color)
}
#[cfg(test)]
mod tests {
#[test]
fn test_parse_key() {
use super::parse_key;
use crate::event::Key;
assert_eq!(parse_key(String::from("j")).unwrap(), Key::Char('j'));
assert_eq!(parse_key(String::from("J")).unwrap(), Key::Char('J'));
assert_eq!(parse_key(String::from("ctrl-j")).unwrap(), Key::Ctrl('j'));
assert_eq!(parse_key(String::from("ctrl-J")).unwrap(), Key::Ctrl('J'));
assert_eq!(parse_key(String::from("-")).unwrap(), Key::Char('-'));
assert_eq!(parse_key(String::from("esc")).unwrap(), Key::Esc);
assert_eq!(parse_key(String::from("del")).unwrap(), Key::Delete);
}
#[test]
fn parse_theme_item_test() {
use super::parse_theme_item;
use tui::style::Color;
assert_eq!(parse_theme_item("Reset").unwrap(), Color::Reset);
assert_eq!(parse_theme_item("Black").unwrap(), Color::Black);
assert_eq!(parse_theme_item("Red").unwrap(), Color::Red);
assert_eq!(parse_theme_item("Green").unwrap(), Color::Green);
assert_eq!(parse_theme_item("Yellow").unwrap(), Color::Yellow);
assert_eq!(parse_theme_item("Blue").unwrap(), Color::Blue);
assert_eq!(parse_theme_item("Magenta").unwrap(), Color::Magenta);
assert_eq!(parse_theme_item("Cyan").unwrap(), Color::Cyan);
assert_eq!(parse_theme_item("Gray").unwrap(), Color::Gray);
assert_eq!(parse_theme_item("DarkGray").unwrap(), Color::DarkGray);
assert_eq!(parse_theme_item("LightRed").unwrap(), Color::LightRed);
assert_eq!(parse_theme_item("LightGreen").unwrap(), Color::LightGreen);
assert_eq!(parse_theme_item("LightYellow").unwrap(), Color::LightYellow);
assert_eq!(parse_theme_item("LightBlue").unwrap(), Color::LightBlue);
assert_eq!(
parse_theme_item("LightMagenta").unwrap(),
Color::LightMagenta
);
assert_eq!(parse_theme_item("LightCyan").unwrap(), Color::LightCyan);
assert_eq!(parse_theme_item("White").unwrap(), Color::White);
assert_eq!(
parse_theme_item("23, 43, 45").unwrap(),
Color::Rgb(23, 43, 45)
);
}
#[test]
fn test_reserved_key() {
use super::check_reserved_keys;
use crate::event::Key;
assert!(
check_reserved_keys(Key::Enter).is_err(),
"Enter key should be reserved"
);
}
}
| rust | MIT | c4dcf6b9fd8318017acbdd7ec005955e26cf2794 | 2026-01-04T15:43:14.194500Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.