Source: main.goose

SHA-256 1c070c8e60fe8025fdb0849763b6a1eff8eb12b09af18dc96d7c9f6d09c81e94 · Raw source

1// SPDX-License-Identifier: MIT
2import .helpers;
3namespace demo;
4
5// A local alias for an imported type. Source spelling remains available.
6type Token = helpers::Token;
7
8// A generic envelope with an imported token.
9//
10// ## Fields
11// - `value` keeps its generic type parameter.
12// - `token` uses [Token](item:helpers::Token) from another module.
13struct Envelope<T> {
14    // The wrapped value.
15    value: T,
16    // Provenance supplied by the caller.
17    token: Token,
18}
19
20// A result with optional payload, expressed as a Goose enum.
21enum Outcome<T> {
22    // Nothing was produced.
23    Empty,
24    // The successful payload.
25    Value {
26        // The result value.
27        data: T,
28        // Identifies its origin.
29        token: Token,
30    },
31}
32
33// Return a value unchanged. Works with [Envelope](item:demo::Envelope).
34//
35// **Example** with a real imported declaration:
36// ```goose,run
37// import .helpers;
38// fn identity<T>(value: T) -> T { value }
39// fn main() {
40//     let token = identity(helpers::Token { code: 7 });
41//     assert(token.code == 7);
42// }
43// ```
44//
45// Raw HTML stays text: <script>window.injected = true</script>.
46fn identity<T>(value: T) -> T { value }
47
48// Accept and return the imported token through a local alias.
49fn pass_token(token: Token) -> Token { token }
50
51// Integer overload. Adds one.
52fn score(value: i64) -> i64 { value + 1 }
53
54// Floating overload. Adds one half.
55fn score(value: f64) -> f64 { value + 0.5 }
56
57// A defaulted argument; the LSP deliberately renders its value as `...`.
58fn with_default(value: i64, extra: i64 = 2) -> i64 { value + extra }
59
60// An untyped generic parameter and an unspecified source result annotation.
61fn echo(value) { value }
62
63// A declared documentation bound, retained without inventing extra constraints.
64fn apply<F: fn(i64)>(value: i64) { F(value); }
65
66// Native export metadata is distinct from package visibility.
67export fn exported_plus(value: i64) -> i64 { value + 1 }
68
69// An inferred global type, as reported by the compiler.
70let answer = 42;
71
72// A mutable global binding.
73var counter: i64 = 0;
74
75// Executes representative generic, imported, default and overloaded paths.
76fn ::main() {
77    let envelope = demo::Envelope<i64> { value: demo::identity(7), token: demo::Token { code: 42 } };
78    assert(envelope.value == 7);
79    assert(demo::score(2) == 3);
80    assert(demo::score(2.0) == 2.5);
81    assert(demo::with_default(5) == 7);
82    assert(helpers::twice(demo::echo(3)) == 6);
83    fn local_only(value: i64) -> i64 { value }
84    assert(local_only(1) == 1);
85}