### Install wasm-pack Source: https://github.com/gleam-lang/gleam/blob/main/compiler-wasm/README.md Install the wasm-pack build tool using Cargo or Homebrew. ```sh cargo install wasm-pack ``` -------------------------------- ### Install default_readme package Source: https://github.com/gleam-lang/gleam/blob/main/test/publishing_default_readme/README.md Use the Gleam CLI to add the package to your project. ```sh gleam add default_readme@1 ``` -------------------------------- ### Gleam Deps Tree Examples Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.8.md Provides examples of `gleam deps tree` output for different scenarios, including listing the full tree, focusing on a specific package, and inverting the tree direction. ```markdown $ gleam deps tree project_a v1.0.0 ├── package_b v0.52.0 └── package_c v1.2.0 └── package_b v0.52.0 $ gleam deps tree --package package_c package_c v1.2.0 └── package_b v0.52.0 $ gleam deps tree --invert package_b package_b v0.52.0 ├── package_c v1.2.0 │ └── project_a v1.0.0 └── project_a v1.0.0 ``` -------------------------------- ### Install test_community_packages Source: https://github.com/gleam-lang/gleam/blob/main/test-community-packages/README.md Use the Gleam CLI to add the package to your project. ```sh gleam add test_community_packages ``` -------------------------------- ### Configure Erlang/OTP Settings Source: https://context7.com/gleam-lang/gleam/llms.txt Set application start modules, arguments, and extra OTP applications for Erlang targets. ```toml [erlang] # OTP application start module application_start_module = "my_project/application" # Start argument for the application application_start_argument = "[]" # Extra OTP applications to include extra_applications = ["inets", "ssl", "crypto"] ``` -------------------------------- ### Gleam Language Server Import Folding Example Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.15.md Demonstrates the folding range support for contiguous import blocks in Gleam. ```gleam import gleam/int ``` -------------------------------- ### Build Tool Dependency Update Output Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.12.md Example output from the gleam update command showing available major version upgrades. ```text $ gleam update Resolving versions The following dependencies have new major versions available: gleam_http 1.7.0 -> 4.0.0 gleam_json 1.0.1 -> 3.0.1 lustre 3.1.4 -> 5.1.1 ``` -------------------------------- ### Gleam Language Server Autocompletion Example Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.15.md Demonstrates how the language server provides smarter autocompletions for fully qualifying types, preventing invalid code generation. ```gleam pub fn payload() -> js|Json // ^ typing the module name ``` -------------------------------- ### Public type alias documentation Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.13.md Example showing how the build tool now displays public type aliases instead of internal representations in generated documentation. ```gleam import my_package/internal pub type ExternalAlias = internal.InternalRepresentation pub fn do_thing() -> ExternalAlias { ... } ``` ```gleam pub fn do_thing() -> @internal InternalRepresentation ``` ```gleam pub fn do_thing() -> ExternalAlias ``` -------------------------------- ### Run Language Integration Tests Source: https://github.com/gleam-lang/gleam/blob/main/CONTRIBUTING.md Execute the language integration tests. This requires recent stable versions of Rust, Erlang, and NodeJS to be installed. ```sh make language-test ``` -------------------------------- ### Build Tool Dependency Resolution Error Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.12.md Example of the error message displayed when version resolution fails during dependency management. ```text $ gleam add wisp@1 Resolving versions error: Dependency resolution failed There's no compatible version of `gleam_otp`: - You require wisp >= 1.0.0 and < 2.0.0 - wisp requires mist >= 1.2.0 and < 5.0.0 - mist requires gleam_otp >= 0.9.0 and < 1.0.0 - You require lustre >= 5.2.1 and < 6.0.0 - lustre requires gleam_otp >= 1.0.0 and < 2.0.0 There's no compatible version of `gleam_json`: - You require wisp >= 1.0.0 and < 2.0.0 - wisp requires gleam_json >= 3.0.0 and < 4.0.0 - You require gleam_json >= 2.3.0 and < 3.0.0 ``` -------------------------------- ### Watch Compiler Tests with Watchexec Source: https://github.com/gleam-lang/gleam/blob/main/CONTRIBUTING.md Continuously run compiler tests automatically when files change. This requires the 'watchexec' tool to be installed. ```sh make test-watch ``` -------------------------------- ### Transfer ownership implementation in Elixir Source: https://github.com/gleam-lang/gleam/blob/main/hexpm/CONTRIBUTING.md Example of an existing Elixir function used to transfer package ownership, serving as a reference for API interaction patterns. ```elixir defp transfer_owner(organization, package, owner) do auth = Mix.Tasks.Hex.auth_info(:write) Hex.Shell.info("Transferring ownership to #{owner} for #{package}") case Hex.API.Package.Owner.add(organization, package, owner, "full", true, auth) do {:ok, {code, _body, _headers}} when code in 200..299 -> :ok other -> Hex.Shell.error("Transferring ownership failed") Hex.Utils.print_error_result(other) end end ``` -------------------------------- ### Gleam Record Argument Labeling Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.12.md Example of a record construction that triggers an error message suggesting missing labels. ```gleam pub type Pokemon { Pokemon(id: Int, name: String, moves: List(String)) } pub fn best_pokemon() { Pokemon(198, name: "murkrow") } ``` -------------------------------- ### Autocomplete suggestions for labels Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.11.md The language server provides autocomplete suggestions for labels even after part of the label has been typed. This example demonstrates autocompletion for the `Person` type constructor. ```gleam pub type Person { Person(name: String, number: Int) } pub fn main() { Person(n|) } ``` -------------------------------- ### Unexpected token error message Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.3.md Example of an error message indicating a keyword conflict in a constructor argument. ```text 3 │ A(type: String) │ ^^^^ I was not expecting this Found the keyword `type`, expected one of: - `)` - a constructor argument name ``` -------------------------------- ### Run Compiler Tests with Cargo Source: https://github.com/gleam-lang/gleam/blob/main/CONTRIBUTING.md Execute the compiler tests using Cargo. This requires a recent stable version of Rust to be installed. ```sh cargo test ``` -------------------------------- ### Compiler Type Mismatch Error Example Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.8.md Illustrates a type mismatch error where a `String` is found but a `Result(a, Nil)` is expected, with a suggestion to wrap the value in `Ok`. ```txt error: Type mismatch ┌─ /main.gleam:7:3 │ 7 │ "Hello!" │ ^^^^^^^^ Did you mean to wrap this in an `Ok`? Expected type: Result(a, Nil) Found type: String ``` -------------------------------- ### Gleam Language Server Module Rename Example Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.15.md Illustrates the module renaming functionality. Renaming a module when hovering over its import statement or name/alias updates all its usages. ```gleam import lustre/element import lustre/element/html import lustre/event fn view(model: Int) -> element.Element(Msg) { // ^ Renaming module to `el` here let count = int.to_string(model) html.div([], [ html.button([event.on_click(Incr)], [element.text(" + ")]), html.p([], [element.text(count)]), html.button([event.on_click(Decr)], [element.text(" - ")]), ]) } ``` ```gleam import lustre/element as el import lustre/element/html import lustre/event fn view(model: Int) -> el.Element(Msg) { let count = int.to_string(model) html.div([], [ html.button([event.on_click(Incr)], [el.text(" + ")]), html.p([], [el.text(count)]), html.button([event.on_click(Decr)], [el.text(" - ")]), ]) } ``` -------------------------------- ### Optimise bit array pattern matching Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.13.md Example of using interference based pruning for efficient network protocol parsing. ```gleam pub fn parser_headers(headers: BitArray, bytes: Int) -> Headers { case headers { <<"CONTENT_LENGTH" as header, 0, value:size(bytes), 0, rest:bytes>> | <<"QUERY_STRING" as header, 0, value:size(bytes), 0, rest:bytes>> | <<"REQUEST_URI" as header, 0, value:size(bytes), 0, rest:bytes>> // ... | <<"REDIRECT_STATUS" as header, 0, value:size(bytes), 0, rest:bytes>> | <<"SCRIPT_NAME" as header, 0, value:size(bytes), 0, rest:bytes>> -> [#(header, value), ..parse_headers(rest)] } } ``` -------------------------------- ### Generate Function in Other Modules Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.13.md The 'Generate function' code action now supports creating functions in different modules. This example shows generating a function in `maths.gleam`. ```gleam // maths.gleam pub fn add(a: Int, b: Int) -> Int { a + b } ``` -------------------------------- ### Extract Constant Code Action Example Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.15.md Demonstrates the correct placement of a new constant when using the 'Extract constant' code action, especially when the function includes documentation. Previously, it was placed below the doc comment; now it's correctly placed above. ```gleam /// Wibble does some wobbling pub fn wibble() { let x = "wobble" // ^ Trigger "Extract constant" here x } ``` ```gleam /// Wibble does some wobbling const x = "wobble" pub fn wibble() { x } ``` ```gleam const x = "wobble" /// Wibble does some wobbling pub fn wibble() { x } ``` -------------------------------- ### Run Gleam Tests in Docker Sandbox Source: https://github.com/gleam-lang/gleam/blob/main/CONTRIBUTING.md Execute the language integration tests within a Docker sandbox environment. This is useful if Rust or Cargo are not installed locally. Mounts the current directory into the container. ```sh docker run -v $(pwd):/opt/app -it -w /opt/app rust:latest bash ``` -------------------------------- ### Language Server: Use Shorthand Labels Code Action Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.4.md The language server can suggest a code action to automatically use shorthand labels in record construction or pattern matching when the variable name matches the label name. This example demonstrates the conversion. ```gleam case date { Day(day: day, month: month, year: year) -> todo } ``` ```gleam case date { Day(day:, month:, year:) -> todo } ``` -------------------------------- ### Compiler Unknown Variable Error Example Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.8.md Shows an error message when an unknown type is used as a variable name, clarifying that a custom type variant constructor is out of scope. ```txt error: Unknown variable ┌─ /src/one/two.gleam:4:3 │ 4 │ X │ ^ The custom type variant constructor `X` is not in scope here. ``` -------------------------------- ### JavaScript FFI for Gleam Custom Types Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.13.md Provides an example of how to interact with Gleam custom types from JavaScript using the generated public API. This includes constructing types, checking variants, accessing fields, and handling shared fields. ```gleam pub type Person { Teacher(name: String, subject: String) Student(name: String, age: Int) } ``` ```javascript import {...} from "./person.mjs"; // Constructing custom types let teacher = Person$Teacher("Joe Armstrong", "Computer Science"); let student = Person$Student("Louis Pilfold"); let randomPerson = Math.random() > 0.5 ? teacher : student; // Checking variants let randomIsTeacher = Person$isTeacher(randomPerson); // Getting fields let teacherSubject = Person$Teacher$subject(teacher); // The `name` field is shared so can be accessed from either variant let personName = Person$name(randomPerson); ``` -------------------------------- ### Generate Documentation Source: https://context7.com/gleam-lang/gleam/llms.txt Build local documentation or publish it to HexDocs. ```bash # Build documentation locally gleam docs build # Build and open in browser gleam docs build --open # Publish documentation to HexDocs gleam docs publish # Remove documentation from HexDocs gleam docs remove --package my_package --version 1.0.0 ``` -------------------------------- ### Improved Error Message for Invalid Record Constructors in Gleam Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.4.md Shows an example of an improved compiler error message for invalid record constructors, providing a restructured example of the intended syntax. This aids users transitioning from other languages. ```gleam pub type User { name: String } ``` ```text error: Syntax error ┌─ /src/parse/error.gleam:3:5 │ 3 │ name: String, │ ^^^^ I was not expecting this Each custom type variant must have a constructor: pub type User { User( name: String, ) } ``` -------------------------------- ### Run Gleam Project Source: https://github.com/gleam-lang/gleam/blob/main/test/project_deno/README.md Execute the Gleam project using the Deno runtime. ```shell gleam run ``` -------------------------------- ### Redundant function capture warning Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.3.md Example of the compiler warning when a function capture is redundant in a pipeline. ```text warning: Redundant function capture ┌─ /src/warning/wrn.gleam:5:17 │ 5 │ 1 |> wibble(_, 2) |> wibble(2) │ ^ You can safely remove this This function capture is redundant since the value is already piped as the first argument of this call. See: https://tour.gleam.run/functions/pipelines/ ``` -------------------------------- ### Inexhaustive pattern match error Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.5.md Example of an inexhaustive pattern match that triggers a qualified error message. ```gleam import gleam/option pub fn main() { let an_option = option.Some("wibble!") case an_option { option.None -> "missing" } } ``` ```txt error: Inexhaustive patterns ┌─ /Users/giacomocavalieri/Desktop/prova/src/prova.gleam:5:3 │ 5 │ ╭ case an_option { 6 │ │ option.None -> "missing" 7 │ │ } │ ╰───^ This case expression does not have a pattern for all possible values. If it is run on one of the values without a pattern then it will crash. The missing patterns are: option.Some(_) ``` -------------------------------- ### Initialize default_readme usage Source: https://github.com/gleam-lang/gleam/blob/main/test/publishing_default_readme/README.md Basic module import and main function structure for using the package. ```gleam import default_readme pub fn main() -> Nil { // TODO: An example of the project in use } ``` -------------------------------- ### Run project and tests Source: https://github.com/gleam-lang/gleam/blob/main/test/publishing_default_readme/README.md Standard CLI commands for executing the project and running the test suite. ```sh gleam run # Run the project gleam test # Run the tests ``` -------------------------------- ### Gleam Import Syntax Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.15.md Demonstrates a new, more concise way to import modules in Gleam. ```gleam import gleam/list import gleam/string ``` ```gleam import gleam/int ... ``` -------------------------------- ### Unsupported JavaScript feature error Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.3.md Example of the error message when using non-byte aligned arrays in JavaScript compilation. ```text error: Unsupported feature for compilation target ┌─ /src/test/gleam_test.gleam:6:5 │ 6 │ <<1:size(5)>> │ ^^^^^^^^^ Non byte aligned array is not supported for JavaScript compilation. ``` -------------------------------- ### Invalid list pattern matching error Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.3.md Example of the compiler error message when attempting to match on the end of a list. ```text error: Syntax error ┌─ /src/parse/error.gleam:4:14 │ 4 │ [..rest, last] -> 1 │ ^^^^^^ I wasn't expecting elements after this Lists are immutable and singly-linked, so to match on the end of a list would require the whole list to be traversed. This would be slow, so there is no built-in syntax for it. Pattern match on the start of the list instead. ``` -------------------------------- ### Create a New Gleam Project Source: https://context7.com/gleam-lang/gleam/llms.txt Initialize a new project with specific templates, git settings, or custom naming conventions. ```bash # Create a new Erlang-targeted project (default) gleam new my_project # Create a new JavaScript-targeted project gleam new my_project --template javascript # Create a project without git initialization gleam new my_project --skip-git # Create with a specific name different from directory gleam new my_app --name my_custom_name ``` -------------------------------- ### Run and Test Gleam Project Source: https://github.com/gleam-lang/gleam/blob/main/test/project_javascript/README.md Execute the project or run the test suite using the Gleam CLI. ```sh gleam run gleam test ``` -------------------------------- ### Export Build Artifacts Source: https://context7.com/gleam-lang/gleam/llms.txt Generate deployment-ready artifacts, preludes, or interface definitions. ```bash # Export Erlang release for deployment gleam export erlang-shipment # Export package as Hex tarball gleam export hex-tarball # Export JavaScript prelude gleam export javascript-prelude # Export TypeScript prelude gleam export typescript-prelude # Export package interface as JSON gleam export package-interface --out interface.json ``` -------------------------------- ### Run project development commands Source: https://github.com/gleam-lang/gleam/blob/main/test-community-packages/README.md Common CLI commands for running, testing, and interacting with the project. ```sh gleam run # Run the project gleam test # Run the tests gleam shell # Run an Erlang shell ``` -------------------------------- ### Build Gleam Projects Source: https://context7.com/gleam-lang/gleam/llms.txt Compile source files and dependencies with options for target specification, warning handling, and output verbosity. ```bash # Build the project gleam build # Build with specific target gleam build --target erlang gleam build --target javascript # Build treating warnings as errors gleam build --warnings-as-errors # Build without progress output gleam build --no-print-progress ``` -------------------------------- ### Go to definition from alternative patterns in Gleam Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.13.md Illustrates the ability to trigger language server actions like 'Go to definition' from alternative patterns within a case statement. ```gleam case wibble { Wibble | Wobble -> 0 // ^- Previously you could not trigger actions from here } ``` -------------------------------- ### Upgrade Rust Toolchain Source: https://github.com/gleam-lang/gleam/blob/main/CONTRIBUTING.md Upgrade your local Rust installation to the latest stable version. This can resolve CI failures related to linting or compilation issues. ```sh rustup upgrade stable ``` -------------------------------- ### Run Gleam Projects Source: https://context7.com/gleam-lang/gleam/llms.txt Execute the main module or specific modules, with support for different JavaScript runtimes and argument passing. ```bash # Run the main module gleam run # Run with a specific target gleam run --target javascript # Run with specific runtime (JavaScript only) gleam run --target javascript --runtime node gleam run --target javascript --runtime deno gleam run --target javascript --runtime bun # Run a specific module gleam run --module my_module # Pass arguments to the program gleam run -- arg1 arg2 arg3 ``` -------------------------------- ### Configure gleam.toml Source: https://context7.com/gleam-lang/gleam/llms.txt Define project metadata, dependencies, and build targets in the project configuration file. ```toml name = "my_project" version = "1.0.0" gleam = ">= 1.0.0" description = "A sample Gleam project" licences = ["Apache-2.0", "MIT"] target = "erlang" # Repository information for documentation links repository = { type = "github", user = "username", repo = "my_project" } # Additional links for documentation links = [ { title = "Home page", href = "https://example.com" }, { title = "Documentation", href = "https://hexdocs.pm/my_project" } ] # Dependencies from Hex [dependencies] gleam_stdlib = ">= 0.34.0 and < 2.0.0" gleam_json = ">= 1.0.0 and < 2.0.0" # Development-only dependencies [dev_dependencies] gleeunit = ">= 1.0.0 and < 2.0.0" ``` -------------------------------- ### Test Gleam Project Source: https://github.com/gleam-lang/gleam/blob/main/test/project_deno/README.md Run tests for the Gleam project using the Deno runtime. ```shell gleam test ``` -------------------------------- ### Initialize Gleam Configuration Source: https://github.com/gleam-lang/gleam/blob/main/compiler-core/templates/documentation_layout.html Defines the configuration object for theme and prewrap settings, including update logic and callbacks for DOM manipulation. ```javascript "use strict"; /* gleamConfig format: * // object with one or more options * {option: { * // array of values * values: [{ * // this value * value: "off", * // optional button label * label: "default", * // optional array of icons * icons: ["star", "toggle-left", ...], * }, ...], * * // value update function * update: () => {...}, * * // optional callback function * callback: (value) => {...}, * }, ...}; */ window.unnest = '{{ unnest }}'; const gleamConfig = { theme: { values: (() => { const dark = { value: "dark", label: "Switch to light mode", icons: ["moon"], }; const light = { value: "light", label: "Switch to dark mode", icons: ["sun"], }; return ( window.matchMedia("(prefers-color-scheme: dark)").matches ? [dark, light] : [light, dark] ).map((item, index) => { item.icons.push(`toggle-${0 === index ? "left" : "right"}`); return item; }); })(), update: () => "light" === Gleam.getProperty("theme") ? "dark" : "light", callback: function(value) { const syntaxThemes = { dark: "atom-one-dark", light: "atom-one-light", }; const syntaxTheme = document.querySelector("#syntax-theme"); const hrefParts = syntaxTheme.href.match( /^(.*?)([^/\\#?]+?)((?:\.min)?\.css.*)$/i ); if (syntaxThemes[value] !== hrefParts[2]) { hrefParts[2] = syntaxThemes[value]; hrefParts.shift(); syntaxTheme.href = hrefParts.join(""); } }, }, prewrap: { values: [ { value: "off", label: "Switch to line-wrapped snippets", icons: ["more-horizontal", "toggle-left"], }, { value: "on", label: "Switch to non-wrapped snippets", icons: ["more-vertical", "toggle-right"], }, ], update: () => "off" === Gleam.getProperty("prewrap") ? "on" : "off", }, }; ``` -------------------------------- ### Render module-qualified types in documentation Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.11.md Documentation now includes module qualifiers for types, with hover-over support to display the full module path. ```gleam import gleam/dynamic/decode pub fn something_decoder() -> decode.Decoder(Something) { ... } ``` ```gleam pub fn something_decoder() -> decode.Decoder(Something) ``` ```txt gleam/dynamic/decode.{type Decoder} ``` -------------------------------- ### Gleam Deps Tree Usage Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.8.md Demonstrates the usage of the `gleam deps tree` command for listing project dependencies. ```markdown Usage: gleam deps tree [OPTIONS] Options: -p, --package Package to be used as the root of the tree -i, --invert Invert the tree direction and focus on the given package -h, --help Print help ``` -------------------------------- ### Render Project Version Selector Source: https://github.com/gleam-lang/gleam/blob/main/compiler-core/templates/documentation_layout.html Dynamically populates the project version dropdown menu based on available version nodes. ```javascript "use strict"; if ("undefined" !== typeof versionNodes) { const currentVersion = "v{{ project_version }}"; if (! versionNodes.find(element => element.version === currentVersion)) { versionNodes.unshift({ version: currentVersion, url: "#" }); } document.querySelector("#project-version").innerHTML = versionNodes.reduce( (acc, element) => { const status = currentVersion === element.version ? "selected disabled" : ""; return ` ${acc} `; }, `
`; } ``` -------------------------------- ### Run and Review Snapshot Tests Source: https://github.com/gleam-lang/gleam/blob/main/docs/compiler/README.md Commands to execute the test suite and interactively review snapshot changes. ```sh # Run the tests make test # Interactively verify changes to the snapshots cargo insta review ``` -------------------------------- ### Configure Project Dependencies Source: https://context7.com/gleam-lang/gleam/llms.txt Define external git repositories or local file paths for project dependencies in the configuration file. ```toml [dependencies] my_lib = { git = "https://github.com/user/my_lib.git", ref = "main" } ``` ```toml [dependencies] local_lib = { path = "../local_lib" } ``` -------------------------------- ### Formatter: Previous Doc Comment Merging Behavior Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.4.md This example illustrates the previous behavior of the Gleam formatter, where documentation comments would be merged together, ignoring intervening regular comments. ```gleam // a commented definition // fn wibble() {} /// This doc comment will be ignored! /// Wibble's documentation. fn wibble() { todo } ``` -------------------------------- ### Build WASM Library Source: https://github.com/gleam-lang/gleam/blob/main/compiler-wasm/README.md Build the WebAssembly library for web targets using wasm-pack. ```sh wasm-pack build --release --target web ``` -------------------------------- ### Gleam Compiler: If Expression Error Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.5.md The Gleam compiler now provides a helpful error message when an `if` expression is used instead of a `case` expression. This guides users towards the correct conditional syntax. ```gleam pub fn main() { let a = if wibble { 1 } } ``` -------------------------------- ### Publish Gleam Packages Source: https://context7.com/gleam-lang/gleam/llms.txt Upload project releases to the Hex package repository. ```bash # Publish package gleam publish # Publish with automatic yes to prompts gleam publish --yes # Replace existing release gleam publish --replace ``` -------------------------------- ### Configure Documentation and Internal Modules Source: https://context7.com/gleam-lang/gleam/llms.txt Specify documentation pages and hide internal modules from generated documentation. ```toml [documentation] pages = [ { title = "Guide", path = "guide.html", source = "./docs/guide.md" } ] # Internal modules (hidden from docs) internal_modules = ["my_project/internal", "my_project/internal/*"] ``` -------------------------------- ### Generate new variant from incorrect code Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.11.md A code action is available to automatically generate a new variant for a type when an incorrect value is used. This example shows adding `UserPressedButton` to the `Msg` type. ```gleam pub type Msg { ServerSentResponse(Json) } pub fn view() -> Element(Msg) { div([], [ button([on_click(UserPressedButton)], [text("Press me!")]) // ^^^^^^^^^^^^^^^^^ This doesn't exist yet! ]) } ``` ```gleam pub type Msg { ServerSentResponse(Json) UserPressedButton } ``` -------------------------------- ### Formatter: Preserve Doc Comment Placement Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.4.md The formatter now preserves the original placement of documentation comments relative to regular comments, preventing them from being merged. This example shows code that remains unchanged by the formatter. ```gleam /// This doc comment will be ignored! // a commented definition // fn wibble() {} /// Wibble's documentation. fn wibble() { todo } ``` -------------------------------- ### Bit Array Pattern Matching with Calculations Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.12.md Shows the use of calculations within size options for bit array patterns. ```gleam let assert <> = some_bit_array ``` -------------------------------- ### Remove Redundant Tuple in Case Expression Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.3.md This example shows how the language server can suggest simplifying a case expression by removing redundant tuple syntax. It transforms a tuple pattern into a direct pattern match. ```gleam case #(a, b) { #(1, 2) -> todo _ -> todo } ``` ```gleam case a, b { 1, 2 -> todo _, _ -> todo } ``` -------------------------------- ### Create Release Tarball Source: https://github.com/gleam-lang/gleam/blob/main/compiler-wasm/README.md Create a compressed tarball of the built package for release. ```sh tar -C pkg/ -czvf gleam-v1.1.0-browser.tar.gz . ``` -------------------------------- ### Improved Git Dependency Error Message in Gleam Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.14.md Shows the new, more informative error message when attempting to build Git dependencies without Git installed. Previously, a generic shell command failure was shown. ```txt error: Program not found The program `git` was not found. Is it installed? Documentation for installing Git can be viewed here: https://git-scm.com/book/en/v2/Getting-Started-Installing-Git ``` -------------------------------- ### Language Server: Rename Variable Code Action Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.4.md The language server suggests a code action to rename variables, types, and functions to comply with Gleam naming conventions. This example shows a variable before and after the suggested rename. ```gleam let myNumber = 10 ``` ```gleam let my_number = 10 ``` -------------------------------- ### Implement Pattern Matching and Case Expressions Source: https://context7.com/gleam-lang/gleam/llms.txt Use exhaustive pattern matching, guards, and destructuring to handle control flow. ```gleam // Basic case expression pub fn describe_number(n: Int) -> String { case n { 0 -> "zero" 1 -> "one" 2 -> "two" _ -> "many" } } // Pattern matching on custom types pub fn get_value(result: Result(a, e)) -> Option(a) { case result { Ok(value) -> Some(value) Error(_) -> None } } // Multiple patterns (OR patterns) pub fn is_weekend(day: String) -> Bool { case day { "Saturday" | "Sunday" -> True _ -> False } } // Pattern matching on lists pub fn first(list: List(a)) -> Option(a) { case list { [] -> None [head, ..] -> Some(head) } } // Destructuring in patterns pub fn sum_pair(pair: #(Int, Int)) -> Int { case pair { #(a, b) -> a + b } } // Guards in case expressions pub fn categorize(n: Int) -> String { case n { x if x < 0 -> "negative" x if x == 0 -> "zero" x if x > 0 && x < 10 -> "small positive" _ -> "large positive" } } // Let assert for patterns that must match pub fn unwrap(result: Result(a, e)) -> a { let assert Ok(value) = result value } // Pattern matching with variable binding pub fn describe_list(list: List(Int)) -> String { case list { [] -> "empty" [x] -> "single element: " <> int.to_string(x) [x, y] -> "two elements" [head, ..tail] -> "starts with " <> int.to_string(head) } } ``` -------------------------------- ### Gleam Record Update Syntax Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.12.md Demonstrates the record update syntax in Gleam and the resulting optimized Erlang code generation. ```gleam pub fn main() -> Nil { let trainer = Trainer(name: "Ash", badges: 0) battle(Trainer(..trainer, badges: 1)) } ``` ```erlang -spec main() -> nil. main() -> Trainer = {trainer, 0, <<"Ash"/utf8>>}, battle( begin _record = Trainer, {trainer, 1, erlang:element(3, _record)} end ). ``` ```erlang -spec main() -> nil. main() -> Trainer = {trainer, 0, <<"Ash"/utf8>>}, battle({trainer, 1, erlang:element(3, Trainer)}). ``` -------------------------------- ### List prefix syntax error Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.12.md Using the list prefix syntax with multiple lists is not supported and triggers a syntax error. ```gleam pub fn main() -> Nil { let xs = [1, 2, 3] let ys = [5, 6, 7] [1, ..xs, ..ys] } ``` ```txt error: Syntax error ┌─ /src/parse/error.gleam:5:13 │ 5 │ [1, ..xs, ..ys] │ -- ^^ I wasn't expecting a second list here │ │ │ You're using a list here Lists are immutable and singly-linked, so to join two or more lists all the elements of the lists would need to be copied into a new list. This would be slow, so there is no built-in syntax for it. ``` -------------------------------- ### Initialize Gleam Search Functionality Source: https://github.com/gleam-lang/gleam/blob/main/compiler-core/templates/documentation_layout.html This JavaScript code initializes the search functionality for the Gleam documentation website. It fetches search data and then calls `window.Gleam.initSearch` to set up the search interface. Ensure the `fetch` request targets the correct search data endpoint. ```javascript document.querySelectorAll("pre code").forEach((elem) => { if (elem.className === "") { elem.classList.add("gleam"); } }); hljs.configure({ cssSelector: 'pre code:not(.hljs-ignore)' }) hljs.highlightAll(); fetch("{{ unnest }}/search-data.json?v={{ rendering_timestamp }}") .then(response => response.json()) .then(data => window.Gleam.initSearch(data)); ``` -------------------------------- ### Import and use test_community_packages Source: https://github.com/gleam-lang/gleam/blob/main/test-community-packages/README.md Basic template for importing the package in a Gleam project. ```gleam import test_community_packages pub fn main() { // TODO: An example of the project in use } ``` -------------------------------- ### Initialize Options on Load Source: https://github.com/gleam-lang/gleam/blob/main/compiler-core/templates/documentation_layout.html Iterates through the gleamConfig object to apply stored localStorage settings to the document body classes. ```javascript "use strict"; /* Initialise options before any content loads */ void function() { for (const property in gleamConfig) { const name = `Gleam.${property}`; let value; try { value = localStorage.getItem(name); if (value.startsWith('"') && value.endsWith('"')) { localStorage.setItem(name, value.slice(1, value.length - 1)); } } catch (_error) {} const defaultValue = gleamConfig[property].values[0].value; try { value = localStorage.getItem(name); } catch(_error) {} if (-1 < [null, undefined].indexOf(value)) { value = defaultValue; } const bodyClasses = document.body.classList; bodyClasses.remove(`${property}-${defaultValue}`); bodyClasses.add(`${property}-${value}`); try { gleamConfig[property].callback(value); } catch(_error) {} } }(); ``` -------------------------------- ### Configure Git dependencies Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.9.md Define dependencies using a Git repository URL and a specific reference. ```toml [dependencies] gleam_stdlib = { git = "https://github.com/gleam-lang/stdlib.git", ref = "957b83b" } ``` -------------------------------- ### Gleam Compilation Flow Diagram Source: https://github.com/gleam-lang/gleam/blob/main/docs/compiler/README.md A textual representation of the Gleam compilation process, illustrating the transformation from source code to Erlang or JavaScript output. ```txt Gleam source code .cache binaries ▼ ▼ ┌────────────────────┐ ┌───────────────────────┐ │ Parser │ │ Metadata deserializer │ └────────────────────┘ └───────────────────────┘ │ │ Untyped AST Module metadata └─────────┐ ┌────────┘ │ ▼ ▼ │ ┌─────────────────────┐ │ │ Dependency sorter │ │ └─────────────────────┘ │ │ │ Untyped AST │ (sorted by deps) │ ▼ │ ┌───────────────────┐ │ │ Type checker │◄─────┘ └───────────────────┘ │ ┌────── Typed AST ──────┐ ▼ ▼ ┌────────────────────┐ ┌─────────────────────┐ │ Code generator │ │ Metadata serializer │ └────────────────────┘ └─────────────────────┘ │ │ │ ▼ Erlang or JavaScript .cache binaries printing algebra ▼ ┌────────────────────┐ │ Pretty printer │ └────────────────────┘ │ ▼ Erlang or JavaScript source code ``` -------------------------------- ### Configure repository path in gleam.toml Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.6.md Specify a sub-path for the repository in the configuration file to ensure correct source links in generated documentation. ```toml [repository] type = "github" user = "gleam-lang" repo = "gleam" path = "packages/my_package" ``` -------------------------------- ### Run Gleam Tests Source: https://context7.com/gleam-lang/gleam/llms.txt Execute project tests with target-specific configurations and filtering options. ```bash # Run tests gleam test # Run tests with specific target gleam test --target erlang gleam test --target javascript # Run tests with arguments gleam test -- --filter "my_test" ``` -------------------------------- ### HTTP Server Configuration in Gleam Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.14.md Defines production-ready HTTP server configuration, including port, TLS usage, and log level. Requires prior definition of base HTTP configuration. ```gleam pub const prod_http_config = HttpConfig( ..base_http_config, port: 80, use_tls: True, log_level: Warn, ) ``` -------------------------------- ### Gleam Language Server String Prefix Pattern References Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.15.md Shows how to find references and rename variables within string prefix patterns in case statements. Trigger 'Find references' or 'Rename' from the highlighted parts. ```gleam case wibble { "1" as digit <> rest -> digit <> rest // ^^^^^ ^^^^ // You can now trigger "Find references" and "Rename" from here } ``` -------------------------------- ### Gleam Function Signature Helper Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.15.md Illustrates how the function signature helper now displays original generic names for unbound arguments, improving clarity in the editor. ```gleam pub fn wibble(x: something, y: fn() -> something, z: anything) { Nil } pub fn main() { wibble( ) // ↑ } ``` ```gleam wibble(something, fn() -> something, anything) ``` ```gleam wibble(a, fn() -> a, b) -> Nil ``` -------------------------------- ### Manage Gleam Dependencies Source: https://context7.com/gleam-lang/gleam/llms.txt Add, remove, update, and inspect project dependencies via the Hex package repository. ```bash # Add a package dependency gleam add gleam_stdlib # Add a specific version gleam add gleam_json@2 # Add as dev dependency gleam add --dev gleeunit # Remove a dependency gleam remove gleam_json # Update all dependencies gleam update # Update specific packages gleam update gleam_stdlib gleam_json # List all dependencies gleam deps list # Show dependency tree gleam deps tree # Check for outdated dependencies gleam deps outdated # Download dependencies gleam deps download ``` -------------------------------- ### Language Server: Convert `let assert` to Case Expression Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.4.md The language server provides a code action to convert `let assert` statements into equivalent case expressions. This is useful for handling pattern matching results more explicitly. ```gleam let assert Ok(value) = get_result() ``` ```gleam let value = case get_result() { Ok(value) -> value _ -> panic } ``` -------------------------------- ### Define Functions and Variables Source: https://context7.com/gleam-lang/gleam/llms.txt Implement public/private functions with type annotations, labeled arguments, and immutable variable bindings. ```gleam // Public function with type annotations pub fn greet(name: String) -> String { "Hello, " <> name <> "!" } // Private function (default) fn add(a: Int, b: Int) -> Int { a + b } // Function with labeled arguments pub fn create_user(name name: String, age age: Int) -> User { User(name: name, age: age) } // Calling with labeled arguments let user = create_user(name: "Alice", age: 30) let user = create_user(age: 25, name: "Bob") // Order doesn't matter // Variable binding (immutable) let x = 5 let y = x + 10 // Variable shadowing let x = 1 let x = x + 1 // x is now 2 // Anonymous functions let double = fn(x) { x * 2 } let result = double(5) // 10 // Function capture with placeholder let add_five = add(5, _) let result = add_five(3) // 8 ``` -------------------------------- ### Check for Outdated Dependencies in Gleam Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.14.md Lists dependencies that have newer versions available. Displays the package name, current version, and the latest available version. ```sh $ gleam deps outdated Package Current Latest ------- ------- ------ wibble 1.4.0 1.4.1 wobble 1.0.1 2.3.0 ``` -------------------------------- ### Use Label Shorthand for Function Arguments in Gleam Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.4.md Demonstrates the shorthand syntax for labelled arguments when the variable name matches the label. This reduces verbosity in function calls. ```gleam pub fn date(day day: Int, month month: Month, year year: Year) -> Date { todo } pub fn main() { let day = 11 let month = October let year = 1998 date(year:, month:, day:) // This is the same as writing // date(year: year, month: month, day: day) } ``` -------------------------------- ### Unknown module import hint Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.5.md The compiler suggests imports when a module is missing but matches a known library. ```gleam pub fn main() { io.println("Hello, world!") } ``` ```txt error: Unknown module ┌─ /src/file.gleam:2:3 │ 2 │ io.println("Hello, world!") │ ^^ No module has been found with the name `io`. Hint: Did you mean to import `gleam/io`? ``` ```gleam pub fn main() { io.non_existent() } ``` -------------------------------- ### Language Server: Import Unused Modules Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.5.md The language server can automatically add necessary `import` statements for modules referenced in existing code, simplifying module management. ```gleam pub fn main() { io.println("Hello, world!") } ``` ```gleam import gleam/io pub fn main() { io.println("Hello, world!") } ``` -------------------------------- ### Use Label Shorthand for Pattern Matching in Gleam Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.4.md Illustrates the shorthand syntax for labelled pattern variables in case expressions. This simplifies binding record fields to variables with matching names. ```gleam pub type Date Date(day: Int, month: Month, year: Year) } pub fn main() { case Date(11, October, 1998) { Date(year:, month:, day:) -> todo // This is the same as writing // Date(year: year, month: month, day: day) -> todo } } ``` -------------------------------- ### Define constants and manage modules Source: https://context7.com/gleam-lang/gleam/llms.txt Organize code using modules and define compile-time constants. Supports qualified, unqualified, and aliased imports. ```gleam // Module-level constants const max_retries = 3 const api_base_url = "https://api.example.com" const default_timeout = 5000 // Public constants pub const version = "1.0.0" // Constant lists and tuples const allowed_methods = ["GET", "POST", "PUT", "DELETE"] const origin = #(0, 0) // Constant records (custom types) pub type Config { Config(timeout: Int, retries: Int) } const default_config = Config(timeout: 5000, retries: 3) // Importing from other modules import gleam/io import gleam/list import gleam/string.{concat, uppercase} // Unqualified imports // Aliased imports import gleam/dynamic as dyn import long/module/path as short // Using qualified access pub fn main() { io.println("Hello!") let items = list.map([1, 2, 3], fn(x) { x * 2 }) let text = string.uppercase("hello") text } ``` -------------------------------- ### Debug and validate code with assertions and echo Source: https://context7.com/gleam-lang/gleam/llms.txt Use echo for quick inspection of values during execution. Assertions and panic are used to enforce invariants and handle unreachable code paths. ```gleam // Echo for debugging (prints and returns value) pub fn debug_example() { let x = 5 let y = echo x // Prints "5" to stderr, y = 5 let result = [1, 2, 3] |> list.map(fn(n) { n * 2 }) |> echo // Prints "[2, 4, 6]", returns the list result } // Assertions pub fn assertion_examples() { // Assert equality assert 1 + 1 == 2 // Assert with pattern matching let result = Ok(42) let assert Ok(value) = result // value = 42 // Assert in case (panics if no match) let assert [first, ..] = [1, 2, 3] // first = 1 first } // Todo for unfinished code pub fn unfinished_function() -> Int { todo as "Implement this later" } // Panic for unreachable code pub fn impossible_case(x: Int) -> String { case x { 1 -> "one" 2 -> "two" _ -> panic as "This should never happen" } } ``` -------------------------------- ### String Concatenation in Gleam Case Guards Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.15.md Demonstrates how to use string concatenation within case expression guards for pattern matching. Ensure the comparison logic is correctly implemented. ```gleam case message { #(version, action) if version <> ":" <> action == "v1:delete" -> handle_delete() _ -> ignore() } ``` -------------------------------- ### Add custom message to echo Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.12.md Use the as keyword to provide a label for echo output. ```gleam pub fn main() { echo 11 as "lucky number" } ``` ```txt /src/module.gleam:2 lucky number 11 ``` -------------------------------- ### Pattern match on variable code action Source: https://github.com/gleam-lang/gleam/blob/main/changelog/v1.12.md Demonstrates the transformation applied when triggering the pattern match code action on a use variable. ```gleam pub type User { User(id: Int, name: String) } pub fn main() { use user <- result.try(load_user()) // ^^^^ Triggering the code action here todo } ``` ```gleam pub type User { User(id: Int, name: String) } pub fn main() { use user <- result.try(load_user()) let User(id:, name:) = user todo } ```