### Hylo IR - Loop Function Example Source: https://github.com/hylo-lang/hylo/blob/main/Docs/DefiniteInitialization.md Illustrates a simple loop structure in Hylo IR, showcasing basic blocks (bb0, bb1, bb2, bb3), variable allocation, function calls, conditional branching, and deallocation. This serves as a concrete example for understanding the block selection algorithm. ```hylo @lowered fun foo(let &Bool) -> Void { bb0(%0 : &Bool): %1 = alloc_stack Bool, binding="y" %2 = borrow [let] %0 %3 = call [let, let] @Hylo.Bool.Copy, %2 %4 = borrow [set] %1 store %3, %4 branch bb1 bb1(): %5 = borrow [let] %1, 0 cond_branch %5, bb2, bb3 bb2(): %6 = record Bool, i1(0x0) %7 = borrow [set] %1 store %6, %7 branch bb1 bb3(): dealloc_stack %1 return void } ``` -------------------------------- ### Val: Basic 'Hello, World!' Program Source: https://github.com/hylo-lang/hylo/wiki/The-Basics Demonstrates the basic structure of a Val program, starting with the 'main' function and printing a string to the terminal. This is the entry point for all Val programs. ```val fun main() { print("Hello, World!") } ``` -------------------------------- ### Hylo Generic Signature Example Source: https://github.com/hylo-lang/hylo/blob/main/Docs/GenericEnvironments.md Illustrates a generic signature in Hylo and the step-by-step process of deriving facts from its constraints when read from left to right. ```hylo ``` -------------------------------- ### Configure Project with CMake and Ninja Source: https://github.com/hylo-lang/hylo/blob/main/README.md Configures the Hylo project for building with CMake and Ninja. Requires specifying a build directory, build type, and the path to the LLVM installation. Optionally enables testing. ```bash cmake -D CMAKE_BUILD_TYPE= \ -D LLVM_DIR=/lib/cmake/llvm \ -G Ninja -S . -B ``` ```bash cmake --build ``` ```bash ctest --parallel --test-dir ``` -------------------------------- ### Hylo Post-Hoc Specializable Algorithm Example Source: https://github.com/hylo-lang/hylo/blob/main/Docs/GenericDispatch.md Illustrates a pattern for defining a specializable algorithm post-hoc in Hylo. It shows a default implementation and a specialized implementation based on additional trait requirements. ```hylo trait SomeAlgorithm { fun some_algorithm() } conformance T: SomeAlgorithm where T: P { fun some_algorithm() { ... } // default implementation } specialization T: SomeAlgorithm { fun some_algorithm() { ... } // specialized implementation } ``` -------------------------------- ### Generate Xcode Project with CMake Source: https://github.com/hylo-lang/hylo/blob/main/README.md Generates an Xcode project file for the Hylo project using CMake. Requires specifying the LLVM installation path and optionally enables testing. ```bash cmake -D LLVM_DIR=/lib/cmake/llvm \ -G Xcode -S . -B ``` -------------------------------- ### Hylo Trait Conformance and Specialization Examples Source: https://github.com/hylo-lang/hylo/blob/main/Docs/GenericDispatch.md Demonstrates Hylo's syntax for defining traits, generic types, conformances, and attempting disallowed specialization. It highlights limitations in defining specific implementations based on constraints. ```hylo trait P { type Q // Requirement with empty default implementation fun f() {} } type X { } // X conforms to P for all Ts. conformance X: P { type Q = T // Specific implementation for X for any T fun f() { print("hi") } } // X conforms to P differently when T is Equatable conformance X: P where T: Equatable { // Disallowed fun f() { print("bye") } } // Specialized implementation of f for P when P.Q is Equatable specialization P where Q: Equatable { // Disallowed fun f() { print("why?") } } ``` -------------------------------- ### Hylo IR: Allocating Stack Memory Source: https://github.com/hylo-lang/hylo/blob/main/Docs/DefiniteInitialization.md Example of allocating memory on the stack in Hylo's intermediate representation (IR). This operation results in a root memory location and an empty path. ```hylo %0 = alloc_stack T // results in (%0.0, []) ``` -------------------------------- ### Hylo Module Compilation Example Source: https://github.com/hylo-lang/hylo/blob/main/Docs/Compiler/CLI.md Demonstrates compiling multiple Hylo source files as separate modules and linking them into an executable. This requires defining modules with specific directory structures. ```swift // In `Sources/Hello/Hello.hylo` import Greetings public fun main() { greet("World") } ``` ```swift // In `Sources/Greetings/Greetings.hylo` public fun greet(_ name: String) { print("Hello, ${name}!") } ``` ```bash hc --modules Sources/Hello Sources/Greet -o hello ``` -------------------------------- ### Val: Single-line and Multi-line Comments Source: https://github.com/hylo-lang/hylo/wiki/The-Basics Shows how to add comments to Val code for documentation. Single-line comments start with '//', and multi-line comments are enclosed in '/* ... */'. Comments are not executed. ```val /* This comment is written over two lines. */ fun main() { // This comment is written on a single-line. print("Hello, World!") } ``` -------------------------------- ### CMake Project Setup for Hylo Source: https://github.com/hylo-lang/hylo/blob/main/CMakeLists.txt This snippet defines the basic project structure and metadata using CMake. It specifies the minimum required CMake version, project name, version, description, homepage URL, and the programming languages to be used (C, CXX, Swift). It also enables testing and sets the macOS deployment target. ```cmake cmake_minimum_required(VERSION 3.30) project(Hylo VERSION 0.1.0 DESCRIPTION "The Hylo programming language" HOMEPAGE_URL "https://hylo-lang.org" LANGUAGES C CXX Swift ) enable_testing() include(CTest) set(CMAKE_OSX_DEPLOYMENT_TARGET "13.0") ``` -------------------------------- ### Hylo Traits and Generic Types Example Source: https://github.com/hylo-lang/hylo/blob/main/Docs/GenericDispatch.md Demonstrates the definition of traits like Equatable, Hashable, and Iterator, along with generic types such as Repeat. It shows how traits can refine other traits and how generic type parameters can have conformance bounds. This example also illustrates associated type requirements and default implementations within traits. ```hylo trait Equatable { fun infix== (_ other: Self) -> Bool } trait Hashable: Equatable { fun hash(into: inout Hasher) } trait Iterator: Deinitializable { type Element: Movable fun next() inout -> Optional fun is_homogeneous() inout -> Bool where Element: Equatable { if let first = &self.next() { while let x = &self.next() { if x != first { return } } } return true } } type Repeat: Iterator { var count: Int let element_value: T type Element = T fun next() inout -> Optional { return if count == 0 { nil } else { count -= 1 return .some(element_value) } } fun is_homogeneous() inout -> Bool where Element: Equatable { true } } type Repeat { var count: Int let element_value: T } conformance Repeat: Iterator { type Element = T fun next() inout -> Optional fun is_homogeneous() inout -> Bool where Element: Equatable { true } } extension Iterator { fun next_two() inout -> Optional<(Element, Element)> { if let first = &self.next(), let second = &self.next() { return Optional((first, second)) } else return nil } } ``` -------------------------------- ### Hylo IR: Borrowing from Memory Source: https://github.com/hylo-lang/hylo/blob/main/Docs/DefiniteInitialization.md Example of borrowing from a memory location in Hylo's IR. This operation specifies the borrow mode (e.g., 'set') and results in a root location along with a path of abstract offsets. ```hylo %1 = borrow [set] %0, 0, 1 // results in (%0.0, [0, 1]) ``` -------------------------------- ### Hylo Subscript and Function Example Source: https://github.com/hylo-lang/hylo/blob/main/Docs/Subscripts.md Demonstrates a simple subscript 'sum' and a function 'foo' that utilizes it in Hylo. The 'sum' subscript takes two integers and returns their sum. The 'foo' function calls 'sum' and prints the result. ```hylo subscript sum(_ x: Int, _ y: Int): Int { x + y } fun foo(a: Int, b: Int) { let x = sum(a, b) print(x) } ``` -------------------------------- ### Hylo Metatype Stack Allocation Optimization Source: https://github.com/hylo-lang/hylo/blob/main/Docs/MiscNotes.md Illustrates an optimization in Hylo where stack allocations of metatypes are transformed into global references. This example shows the transformation from an initial stack allocation to a direct global address. ```Hylo %i0.0#0: &Metatype = alloc_stack Metatype store Int, %i0.0#0 %i0.2#0: &Metatype = borrow [let] %i0.0#0 ``` ```Hylo %i0.0#0: &Metatype = global_addr Int.metatype %i0.2#0: &Metatype = borrow [let] %i0.0#0 ``` -------------------------------- ### Initialize Product Types with Default and User-Defined Constructors in Hylo Source: https://github.com/hylo-lang/hylo/wiki/Types This example shows the declaration of a product type 'Rectangle' and how to call its default constructor. It also presents a user-defined constructor that takes different parameters, overriding the default behavior. ```Hylo type Vector2 { var x: Double var y: Double new(x: Double, y: Double) { self.x = x self.y = y } } type Rectangle { val origin: Vector2 val dimensions: Vector2 } fun main() { // Calls the constructor of 'Rectangle' val p0 = Rectangle(origin: Vector2(0, 0), dimensions: Vector2(2, 1)) } ``` ```Hylo type Rectangle { val origin: Vector2 val dimensions: Vector2 // A user-defined constructor. new (centeredAt center: Vector2, dimensions: Vector2) { self.origin = Vector2( x: center.x - dimensions.x * 0.5, y: center.y - dimensions.y * 0.5) self.dimensions = dimensions } } ``` -------------------------------- ### Assigning Local Functions to Variables in Val Source: https://github.com/hylo-lang/hylo/wiki/Functions Shows how functions in Val are first-class citizens and can be assigned to constants or variables. This example assigns a local function to a constant and then calls it. ```val fun main() { val x = 42 fun constant() -> Int { ret x } val f = constant print(f()) // Prints 42 } ``` -------------------------------- ### Hylo Emit Raw AST Example Source: https://github.com/hylo-lang/hylo/blob/main/Docs/Compiler/CLI.md Compiles a Hylo source file and emits the Abstract Syntax Tree (AST) before type checking to a JSON file. This allows inspection of the initial parsed structure. ```bash hc --emit raw-ast -o main.json main.hylo ``` -------------------------------- ### Hylo: Inconsistent Generic Constraint Example Source: https://github.com/hylo-lang/hylo/blob/main/Docs/GenericEnvironments.md This Hylo code snippet presents a generic function `bar` with conflicting constraints (`T: Collection`, `T == Bool`). It serves as an example of an inconsistent environment where blame assignment is ambiguous, posing a challenge for the type checking process. ```hylo fun bar() { ... } ``` -------------------------------- ### Hylo Function Initialization State Tracking Source: https://github.com/hylo-lang/hylo/blob/main/Docs/LocalBindings.md Illustrates definite initialization tracking in Hylo at the IR level. This example shows a function 'add' with two 'let' parameters. It highlights how arguments passed to the function reside in memory, while the result of an operation can reside in a register. ```ir @lowered fun add(let Int, let Int) -> sink Int { bb0(%0 : &Int, %1 : &Int): %2 = start_borrow [let] %0 %3 = start_borrow [let] %1 %4 = call [let, let, let] @Hylo.Int.infix+, %2, %3 return %4 } ``` -------------------------------- ### Hylo: Extending Existing Types Source: https://github.com/hylo-lang/hylo/wiki/Types Demonstrates how to extend existing types with new declarations and conformances, even if the original type declaration cannot be modified. The first example extends the built-in `Int` type to conform to `Serializable`. The second example extends a type alias `Shape` with a computed property `area`. ```hylo extn Int: Serializable { fun serialize() -> String { ret self.stringified } } ``` ```hylo type Shape = Rectangle | Circle extn Shape { val area: Double { get { if self is Rectangle { ret dimensions.x * dimensions.y } else if self is Circle { ret Double.pi * radius * radius } } } } ``` -------------------------------- ### Hylo Type Inference Tracing Example Source: https://github.com/hylo-lang/hylo/blob/main/Docs/Compiler/CLI.md Enables tracing of type inference requests at a specific line number within a Hylo source file. This is useful for debugging type-related issues. ```bash hc --typecheck --trace-inference main.hylo:16 main.hylo ``` -------------------------------- ### Hylo Trait Refinements and Conformance Examples Source: https://github.com/hylo-lang/hylo/blob/main/Docs/GenericDispatch.md Illustrates various aspects of Hylo traits and conformances, including trait refinement, associated type requirements, and default implementations. It also shows explicit conformances for types and conditional conformances based on type bounds. ```hylo trait Equatable { fun equals(_: Self) -> Bool // method requirement } trait Hashable: Equatable { // trait refinement fun hash(into: inout Hasher) } trait Iterator { type Element // associated type requirement fun next() inout -> Optional } trait Sequence { type Traversal: Iterator fun traversal() -> Traversal fun nth(_ n_: Int) -> Optional { var i = iterator() for n in 0.. Iter fun equals(_: Other) -> Bool where Self.Element == Other.Element, // type equality bound Self.Element: Equatable // requirement with default implementation fun nth(_ n_: Int) -> Optional { var i = iterator() for n in 0.. Bool { return self.a == other.a } } type Y { var a: T } conformance Y: Equatable where T: Equatable { // conditional (bounded) conformance fun equals(_ other: Y)-> Bool { return self.a.equals(other.a) // use of trait requirement available via to bound } } ``` -------------------------------- ### Hylo Generic Signature Example Source: https://github.com/hylo-lang/hylo/blob/main/Docs/GenericEnvironments.md Demonstrates a generic signature in Hylo with a generic parameter 'T' constrained to conform to 'Collection' and an associated type 'Element' equal to 'Int'. This signature is used to create a corresponding generic environment. ```hylo fun f(x: X) {} ``` -------------------------------- ### Extracting Future Result with a Function in Val Source: https://github.com/hylo-lang/hylo/wiki/Asynchrony Demonstrates how futures can be passed as arguments to functions. This example defines a generic function `extract` that takes an `async` type and returns its awaited result. This showcases futures as first-class citizens. ```val fun extract(resultOf future: async A) -> A { ret await future } val future = async someTask() val result = extract(resultOf: future) ``` -------------------------------- ### Hylo: 'let' Binding with Conditional Initialization Source: https://github.com/hylo-lang/hylo/blob/main/Docs/LocalBindings.md Shows a Hylo 'let' binding whose initialization depends on a conditional expression. This example highlights how Hylo IR handles potential storage allocation for 'let' bindings based on initializer types (lvalue/rvalue) and control flow. ```hylo public fun main() { let bar = if condition { 1 } else { 2 } } ``` ```hylo public fun main() { var foo = 42 let bar = if condition { foo } else { 42 } _ = bar.copy() } ``` ```ir @lowered fun main() -> Void { bb0: %0 = record Hylo.Int, i64(0x2a) %1 = alloc_stack Hylo.Int, binding="foo" %2 = start_borrow [set] %0 store %2, %0 %3 = alloc_stack Hylo.Option %4 = start_borrow [let] @condition, 0 %5 = call [let, let] @Builtin.i1_copy, %4 cond_branch %5, bb1, bb2 bb1: %6 = record Hylo.Optional.Nil %7 = union Hylo.Option, %6 %8 = start_borrow [set] %3 store %7, %8 %9 = start_borrow [let] %0, binding="bar" branch bb3, %9 bb2: %10 = record Hylo.Int, i64(0x2a) %11 = record Hylo.Optional.Some, %10 %12 = union Hylo.Option, %11 %13 = start_borrow [set] %3 store %12, %13 %14 = start_borrow [let] %3, 1, binding="bar" branch bb3, %14 bb3(%15 : &Int): %16 = start_borrow [let] %15 %17 = call [let, let] Hylo.Int.copy, %16 deinit %17 dealloc_stack %3 dealloc_stack %0 } ``` -------------------------------- ### Hylo Specialized Conformance for Overlapping Types Source: https://github.com/hylo-lang/hylo/blob/main/Docs/GenericDispatch.md Presents an example of a specialized conformance `Y: Equatable` that overlaps with a more general conformance `Y: Equatable`. This requires dynamic lookup of the appropriate witness table at runtime to ensure the most specific implementation is used. ```hylo conformance Y: Equatable { fun equals(_ other: Self) -> Bool { return true // All Ys are equal } } ``` -------------------------------- ### Swift Example: Accessing Type Size via Metatype Source: https://github.com/hylo-lang/hylo/blob/main/Docs/Compiler/MetatypeLowering.md Demonstrates how to use a metatype in Swift to query runtime information, specifically the memory size of the Int type. It highlights the use of '.layout.size' for accessing layout properties. ```swift public fun main() { print(Int.layout.size) } ``` -------------------------------- ### Hylo Function Example with Context Merging Source: https://github.com/hylo-lang/hylo/blob/main/Docs/DefiniteInitialization.md This Hylo code snippet demonstrates a function that conditionally initializes a local variable 'x'. The context merging process is explained in relation to detecting potential uninitialized variable access when the variable is used after a conditional branch. ```Hylo @lowered fun foo(let &Bool) -> Int { bb0(%0 : &Bool): %1 = alloc_stack Int, binding="x" %2 = borrow [let] %0, 0 cond_branch %2, bb1, bb2: bb1(): %3 = record Bool, i64(0x2a) %4 = borrow [set] %0 store %3, %4 branch bb2 bb2(): %5 = load %1 dealloc_stack %1 return %5 } ``` -------------------------------- ### Hylo: Using Views as Types for Constraints Source: https://github.com/hylo-lang/hylo/wiki/Types Demonstrates how to use views as type annotations to express constraints on existential types. The example shows declaring types that conform to a `Serializable` view and assigning values of different conforming types to a variable annotated with the `Serializable` view. ```hylo type Vector2: Serializable { /* ... */ } type Vector3: Serializable { /* ... */ } fun main() { var x: Serializable = Vector3(x: 0.4, y: 0.7, z: -1.9) x = Vector2(x: 0.5, y: 1.7) print(x.serialize) // Prints Vector2(x: 0.5, y: 1.7) } ``` -------------------------------- ### Hylo: Referring to Conforming Type with Self Source: https://github.com/hylo-lang/hylo/wiki/Types Explains how to use `Self` within a view declaration to refer to the concrete type that conforms to the view. The example shows the `Orderable` view, which requires a less-than operator `<` that compares an instance with another instance of the same concrete type, ensuring type safety. ```hylo view Orderable { func < (_: Self) -> Bool } ``` -------------------------------- ### Hylo function returning a tuple for multiple values Source: https://github.com/hylo-lang/hylo/wiki/Functions Explains how Hylo functions can return tuples to emulate multiple return values. The example shows a function returning a tuple of two integers, which are then destructured into separate variables in the caller. ```hylo fun dup(_ x: Int) -> (Int, Int) { ret (a: x, b: x) } fun main() { val (x, y) = dup(8) } ``` -------------------------------- ### Hylo Generics and Static Invisibility Example Source: https://github.com/hylo-lang/hylo/blob/main/Docs/GenericDispatch.md Shows a scenario where a generic function `f` calls another generic function `f1`. Due to separate compilation, `f` might not know about specific instantiations like `Y`, leading to dynamic lookup of witness tables for traits like `Equatable`. ```hylo fun f1(_ w: U) -> Bool { return w.equals(w) } fun f(_ x: T) -> Bool { return f1( Y(x) ) } fun g() { let a = Y(false) print(a.equals(a)) print(f(3)) } ``` -------------------------------- ### Hylo 'inout' Binding Example Source: https://github.com/hylo-lang/hylo/blob/main/Docs/LocalBindings.md Demonstrates the usage of 'inout' bindings in Hylo. 'inout' bindings are always represented as borrowed access at the IR level and do not have storage. This snippet shows a variable 'foo' being declared and then an 'inout' binding 'bar' referencing 'foo'. ```hylo public fun main() { var foo = 42 inout bar = &foo } ``` ```ir @lowered fun main() -> Void { bb0: %0 = record Hylo.Int, i64(0x2a) %1 = alloc_stack Hylo.Int, binding="foo" %2 = start_borrow [set] %0 store %0, %2 %3 = start_borrow [inout] %0, binding="bar" dealloc_stack %0 } ``` -------------------------------- ### Hylo: Generic Function Constraint Assumption Example Source: https://github.com/hylo-lang/hylo/blob/main/Docs/GenericEnvironments.md This Hylo code snippet illustrates a scenario where a generic function `foo` has constraints (`T: Collection`, `T.Element == Int`) that must be assumed rather than checked. This highlights a limitation of the current solver, which is not designed to handle such assumptions. ```hylo fun foo() { ... } ``` -------------------------------- ### Hylo: Generic Function Type Inference Example Source: https://github.com/hylo-lang/hylo/blob/main/Docs/GenericEnvironments.md This Hylo code snippet demonstrates type inference for a generic function `id`. It shows how a type variable `T` with a `Movable` constraint can be unified with a concrete type `Int`, and how external evidence (`Int: Movable`) is used to satisfy the constraint. ```hylo public fun main() { fun id(_ v: sink T) -> T { v } let x: Int = 1 let y = id(x) } ``` -------------------------------- ### Conform Counter Type to Iterator View in Hylo Source: https://github.com/hylo-lang/hylo/wiki/Generics Demonstrates how a concrete type 'Counter' conforms to the 'Iterator' view by providing a specific type for 'Element' (Int) and implementing the 'next' method. This example shows a simple counter that yields integers until a specified end. ```hylo type Counter: Iterator { type Element = Int var current: Int val end: Int mut fun next() -> Maybe { if current >= end { ret Nil() } else { val i = current ¤t += 1 ret i } } } ``` -------------------------------- ### Move pkgconfig file to system directory Source: https://github.com/hylo-lang/hylo/blob/main/README.md Moves the generated 'llvm.pc' file to '/usr/local/lib/pkgconfig/', a standard location searched by 'pkg_config'. This is necessary for integration with tools like Xcode. ```bash sudo mkdir -p /usr/local/lib/pkgconfig && sudo mv llvm.pc /usr/local/lib/pkgconfig/ ``` -------------------------------- ### C++ Threading Example Demonstrating Semantic Difference Source: https://github.com/hylo-lang/hylo/blob/main/Docs/Performance.org Illustrates a C++ multithreaded scenario involving a mutex and shared variable 's'. This example demonstrates why a compiler cannot always optimize 'f' to 'g' due to potential data races and semantic differences in C++ regarding shared mutable state. ```C++ #include int main() { std::mutex m; int s = 0; std::jthread t1([&] { const bool b = m.try_lock(); f( b, 2, s ); if( b ) m.unlock(); }); std::jthread t2([&] { const bool b = m.try_lock(); f( b, 3, s ); if( b ) m.unlock(); }); } ``` -------------------------------- ### Generate pkgconfig file with Bash Source: https://github.com/hylo-lang/hylo/blob/main/README.md This script generates a 'pkgconfig' file required for Swift Package Manager builds. It takes the desired output file path as an argument and prints the file's content. On Windows, it specifies how to use the bash executable included with Git. ```bash ./Tools/make-pkgconfig.sh ./llvm.pc ``` ```bash C:\Program Files\Git\bin\bash ./Tools/make-pkgconfig.sh ./llvm.pc ``` -------------------------------- ### Hylo: Basic Function with Let Bindings Source: https://github.com/hylo-lang/hylo/blob/main/Docs/LocalBindings.md Demonstrates a simple Hylo function introducing 'let' bindings for multiple values. It shows how individual bindings can be declared together but initialized and managed separately. ```hylo public fun foo() -> Int { let (one, two): { Int, Int } one = 1 two = 2 print(one) return two } ``` -------------------------------- ### Val: Sequential Statements Execution Source: https://github.com/hylo-lang/hylo/wiki/The-Basics Illustrates how statements are executed sequentially in Val. Each print statement is on a new line, showing the basic execution flow. Semicolons can be used to separate statements explicitly. ```val fun main() { print("Hello,") print("World!") } ``` -------------------------------- ### Hylo Compiler Pipeline Emission Options Source: https://github.com/hylo-lang/hylo/blob/main/README.md These are command-line options used to control the Hylo compiler's output at various stages of its pipeline. They range from generating an Abstract Syntax Tree (AST) to producing executable binaries. The `--emit binary` option is the default. ```bash --emit raw-ast --typecheck --emit raw-ir --emit ir --emit llvm --emit intel-asm --emit binary ``` -------------------------------- ### Configure PKG_CONFIG_PATH environment variable Source: https://github.com/hylo-lang/hylo/blob/main/README.md Sets the PKG_CONFIG_PATH environment variable to the current directory, making the generated 'llvm.pc' file visible to command-line tools. This is a common step for build system configuration. ```bash export PKG_CONFIG_PATH=$PWD ``` -------------------------------- ### Test Hylo compiler with Swift Package Manager Source: https://github.com/hylo-lang/hylo/blob/main/README.md Runs the tests for the Hylo compiler in release mode and in parallel using Swift Package Manager. This command is used to verify the correctness of the compiler. ```bash swift test -c release --parallel ``` -------------------------------- ### Define and Implement a View Requirement Source: https://github.com/hylo-lang/hylo/wiki/Types Demonstrates the definition of a 'view' in Val, which specifies a set of required methods or properties. It also shows how a type can conform to a view by providing the necessary implementation. ```val view Serializable { fun serialize() -> String } view Stringifiable { val stringified: String } type Vector2: Serializable { var x: Double var y: Double fun serialize() -> String { ret "Vector2(x: " + x.stringified + ", y: " + y.stringified + ")" } } ``` -------------------------------- ### Build Hylo project with Swift Package Manager Source: https://github.com/hylo-lang/hylo/blob/main/README.md Builds the Hylo project in release mode using Swift Package Manager. This command generates an executable named 'hc' located in the '.build/release' directory. ```bash swift build -c release ``` -------------------------------- ### Overload Constructors for Multiple Initialization Methods in Hylo Source: https://github.com/hylo-lang/hylo/wiki/Types This snippet demonstrates constructor overloading in Hylo. By defining multiple 'new' methods with different parameter lists, developers can offer various ways to create and initialize instances of a type. ```Hylo type Circle { /* ... */ } type Rectangle { val origin: Vector2 val dimensions: Vector2 // A user-defined constructor. new (centeredAt center: Vector2, dimensions: Vector2) { /* ... */ } // Another user-defined constructor. new (enclosing circle: Circle) { /* ... */ } } ``` -------------------------------- ### Defining Hylo Libraries with CMake Source: https://github.com/hylo-lang/hylo/blob/main/Sources/CMakeLists.txt These snippets define various library targets within the Hylo project using the `add_hylo_library` command. Each library represents a distinct component of the compiler (e.g., Driver, FrontEnd, IR) and lists its own dependencies. ```cmake add_hylo_library(Driver DEPENDENCIES CodeGenLLVM FrontEnd IR StandardLibrary ArgumentParser # TODO: why is this needed? Collections) add_hylo_library(FrontEnd DEPENDENCIES BigInt OrderedCollections Durian Utils) add_hylo_library(IR DEPENDENCIES FrontEnd Utils) add_hylo_library(CodeGenLLVM DEPENDENCIES FrontEnd IR Utils SwiftyLLVM PATH CodeGen/LLVM) add_hylo_library(Utils DEPENDENCIES BigInt DequeModule Algorithms) add_hylo_library(StandardLibrary DEPENDENCIES FrontEnd Utils PATH ../StandardLibrary) ``` -------------------------------- ### Hylo: View Inheritance and Composition Source: https://github.com/hylo-lang/hylo/wiki/Types Illustrates view inheritance and composition in Hylo. The first part shows how views can inherit from others to aggregate requirements, defining a `Persistent` view that inherits from `Serializable` and `Deserializable`. The second part demonstrates anonymous composition using the `&` operator and the concept of an empty composition represented by the `Any` type alias. ```hylo view Deserializable { new deserialize(from: String) {} } view Persistent: Serializable, Deserializable { fun save(to: String) fun load(from: String) } ``` ```hylo val doc: Serializable & Deserializable ``` ```hylo var something: Any = (fst: 1, snd: "two") something = 4.2 print(something as! Double) ``` -------------------------------- ### Hylo Program Structure for Continuations Source: https://github.com/hylo-lang/hylo/blob/main/Docs/Subscripts.md Illustrates a Hylo program's structure and its lowered form, highlighting control flow and projection operations. This helps in understanding the scope and termination requirements of continuations. ```swift public fun main() { var s = [1, 2, 3, 4] while condition() { let t = s[0] let u = t print(t) print(u) } print(s) } ``` ```hylo fun main() -> Void { b0: ... branch loop.head loop.head: ... cond_branch %b, loop.body, loop.tail loop.body: ... %t = project @Buffer.[], %x0, %x1 ... %u = project @Buffer.[], %x2, %x3 ... end_project %t ... end_project %u ... branch loop.head loop.tail: ... %x4 = call @print, %s } ``` -------------------------------- ### Hylo: Unsafe Cast Operator `as!` Source: https://github.com/hylo-lang/hylo/wiki/Types Illustrates the unsafe cast operator `as!` in Hylo. This operator forces a type conversion and will cause a runtime error if the conversion is illegal. The example shows successful casts where the runtime type matches the target type. ```hylo type Shape = Rectangle | Circle fun main() { val a: Shape = Circle(origin: Vector2(x: 0, y: 0), radius: 2.3) // This operation succeeds because 'a' has indeed the type 'Circle'. // The constant 'b' has the type 'Circle'. val b = a as! Circle // This operation succeeds because 'a' does not have the type 'Rectangle'. val c = a as! Rectangle } ``` -------------------------------- ### Hylo IR - Pair Projection Lowering Source: https://github.com/hylo-lang/hylo/blob/main/Docs/DefiniteInitialization.md Demonstrates the lowering of a Hylo code snippet that creates a projection from a pair. It shows the IR instructions involved in memory allocation, borrowing, and the start_subscript operation, illustrating how tuple access is represented at the IR level. ```hylo %0 = alloc_stack ... %5 = borrow [inout] %0, 0 %6 = borrow [inout] %0, 0 %7, %8 = start_subscript [inout] [let, inout, inout] @min, %5, %6 ``` -------------------------------- ### Add Hylo Test Suite: DriverTests Source: https://github.com/hylo-lang/hylo/blob/main/Tests/CMakeLists.txt Creates a Hylo test suite named 'DriverTests' for the 'Driver' module. Dependencies include 'TestUtils', 'Durian', and 'SwiftyLLVM'. ```cmake add_hylo_test_of(Driver NAMED DriverTests DEPENDENCIES TestUtils # TODO: why are these needed? Durian SwiftyLLVM) ``` -------------------------------- ### C++ Example for Non-Optimizable Loop Condition Source: https://github.com/hylo-lang/hylo/blob/main/Docs/Performance.org Demonstrates a C++ scenario where the compiler cannot optimize the loop condition in function 'f'. This is because the global 'flag' variable can be modified within the 'g' function, making the value of 'b' unpredictable during the loop. ```C++ bool flag; int g(int a) { flag = !flag; return a+1; } int f( const std::vector& v, const bool &b ) { /*...*/ } int main() { f( {1, 2, 3}, flag ); } ``` -------------------------------- ### Hylo: 'var' Binding with Storage Allocation Source: https://github.com/hylo-lang/hylo/blob/main/Docs/LocalBindings.md Illustrates a 'var' binding in Hylo, which is guaranteed to have storage. The code snippet shows the IR translation, including 'alloc_stack' for storage and 'store' for initialization. ```hylo public fun main() { var foo = 42 } ``` ```ir @lowered fun main() -> Void { bb0: %0 = record Hylo.Int, i64(0x2a) %1 = alloc_stack Hylo.Int, binding="foo" %2 = start_borrow [set] %0 store %0, %2 dealloc_stack %0 } ``` -------------------------------- ### Add Hylo Library: TestUtils Source: https://github.com/hylo-lang/hylo/blob/main/Tests/CMakeLists.txt Defines a Hylo library named 'TestUtils'. It has dependencies on 'FrontEnd', 'Driver', 'Utils', 'SwiftXCTest', and 'SwiftyLLVM'. The source code for this library is located in '../Sources/TestUtils'. ```cmake add_hylo_library(TestUtils DEPENDENCIES FrontEnd Driver Utils SwiftXCTest # TODO: why is this needed? SwiftyLLVM PATH ../Sources/TestUtils ) ``` -------------------------------- ### Creating a Basic Future in Val Source: https://github.com/hylo-lang/hylo/wiki/Asynchrony Demonstrates how to create a future from an expression by prefixing it with the `async` keyword. Futures represent computations that will be completed eventually, not necessarily synchronously. The `someTask()` function is assumed to be an existing asynchronous task. ```val val future = async someTask() ``` -------------------------------- ### Val: Variable Declaration and Assignment Source: https://github.com/hylo-lang/hylo/wiki/The-Basics Demonstrates how to declare mutable variables using 'var' and assign values using the '=' operator in Val. Variables can be reassigned. ```val fun main() { var count = 1 count = 2 } ``` -------------------------------- ### Hylo Static Selection: Witness Table Passing Source: https://github.com/hylo-lang/hylo/blob/main/Docs/GenericDispatch.md Demonstrates Hylo's static selection mechanism where witness tables are passed along in generic function calls. This avoids redundant table creation and resolves ambiguities statically. ```hylo fun is_really_equal(_ x: T, _ y: T) -> Bool { return x == y } fun is_equal(_ x: T, _ y: T) -> Bool { // implicit witness parameter for `T: Equatable` passed along return is_really_equal(x, y) } let yes = is_equal(1, 1) // New witness table for `Int: Equatable` needed. ``` -------------------------------- ### Creating a Custom Target for Compiler Version Output Source: https://github.com/hylo-lang/hylo/blob/main/Sources/CMakeLists.txt This CMake snippet defines a custom target named `output_compiler_version`. This target, when built, executes the Hylo compiler executable (`hc`) with the `--version` argument, useful for verifying the compiler's build and version information. ```cmake add_custom_target(output_compiler_version "$" --version DEPENDS hc VERBATIM) ``` -------------------------------- ### Define and Access Tuple Properties Source: https://github.com/hylo-lang/hylo/wiki/Types Illustrates the creation and usage of tuples in Val, including defining labeled and unlabeled tuples, assigning values, and accessing elements using dot notation with labels or positional indices. ```val val pair: (fst: Int, snd: Int) = (fst: 4, snd: 2) val pair: (fst: Int, snd: Int) = (4, 2) val pair: (fst: Int, snd: Int) = (4, 2) print(pair.fst) // Prints 4 print(pair.1) // Prints 2 ``` -------------------------------- ### Hylo Immutable Array Projection with Mutable Slice Source: https://github.com/hylo-lang/hylo/blob/main/Docs/RemoteParts.md Demonstrates accessing a mutable slice from an immutable array. The example shows that even though the original array is immutable, the subscript's ability to yield a mutable slice (`var Slice`) allows modification through the slice. ```hylo public fun main() { let array = [1,2,2] inout part = &array[0] // This part is projected inout; type error because `array` is immutbale var slice = array[in: 1 ..< 10] // Okay, even if `array` is immutable, because of the var on the output type of the projection print(array) } ``` -------------------------------- ### Marking Unimplemented Features in Hylo Source: https://github.com/hylo-lang/hylo/blob/main/CONVENTIONS.md Use the UNIMPLEMENTED() macro to mark API stubs for features not yet implemented. It's recommended to include a description of the feature and the associated issue number. This aids in tracking development progress and ensures clarity for contributors. ```swift UNIMPLEMENTED("description of feature #issue-number") ``` -------------------------------- ### Hylo Separate Compilation and Generic Dispatch Source: https://github.com/hylo-lang/hylo/blob/main/Docs/GenericDispatch.md Illustrates how separate compilation restricts operations on generic parameters to their declared bounds. This example shows a function `f` that accepts a generic type `T` constrained to `Equatable`. Attempting to use a `Hashable` method on `x` within `f` results in a compile-time error, even if `f` is called with a `Hashable` type, because the generic bound only guarantees `Equatable`. ```hylo conformance X: Hashable { public fun hash(into: inout Hasher) } fun f(_ x: T) { x.equals(x) // OK var h = Hasher() x.hash(into: &h) // Error: no 'hash' method on 'x'. } f(X()) ``` -------------------------------- ### Defining Hylo Executables with CMake Source: https://github.com/hylo-lang/hylo/blob/main/Sources/CMakeLists.txt This section shows how to define executable targets for the Hylo compiler (`hc`) and the demangling tool (`hylo-demangle`) using the custom `add_hylo_executable` command. It specifies their dependencies on other libraries and modules. ```cmake add_hylo_executable(hc DEPENDENCIES Driver # TODO: why are these needed? Durian SwiftyLLVM) add_hylo_executable(hylo-demangle DEPENDENCIES IR # TODO: why are these needed? Durian SwiftyLLVM Collections) set_target_properties(hylo-demangle PROPERTIES Swift_MODULE_NAME HyloDemangle) ``` -------------------------------- ### Add Hylo Test Suite: HyloTests Source: https://github.com/hylo-lang/hylo/blob/main/Tests/CMakeLists.txt Sets up a Hylo test suite named 'HyloTests' for the 'FrontEnd' module. Key dependencies are 'IR', 'TestUtils', 'StandardLibrary', and 'Utils', 'Algorithms'. ```cmake add_hylo_test_of(FrontEnd NAMED HyloTests DEPENDENCIES IR TestUtils StandardLibrary Utils Algorithms) ``` -------------------------------- ### Configuring MSVC Runtime Library for Swift Compilation Source: https://github.com/hylo-lang/hylo/blob/main/Sources/CMakeLists.txt This configuration sets the MSVC runtime library for Swift compilation. It ensures compatibility with the LLVM build process by specifying the MultiThreadedDLL option for the C runtime library. ```cmake set(CMAKE_Swift_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY MultiThreadedDLL) set(CMAKE_MSVC_RUNTIME_LIBRARY MultiThreadedDLL) ``` -------------------------------- ### Add Hylo Test Suite: EndToEndTests Source: https://github.com/hylo-lang/hylo/blob/main/Tests/CMakeLists.txt Configures a Hylo test suite named 'EndToEndTests' for the 'Driver' module. This test suite depends on 'TestUtils', 'Durian', and 'SwiftyLLVM'. ```cmake add_hylo_test_of(Driver NAMED EndToEndTests DEPENDENCIES TestUtils # TODO: why are these needed? Durian SwiftyLLVM) ``` -------------------------------- ### Finding Swift Packages with CMake Source: https://github.com/hylo-lang/hylo/blob/main/Sources/CMakeLists.txt This snippet demonstrates how to use CMake's `find_package` command to locate and utilize external Swift packages. These packages are essential dependencies for the Hylo compiler and related tools. ```cmake find_package(SwiftArgumentParser) find_package(SwiftCollections) find_package(SwiftAlgorithms) find_package(Durian) find_package(BigInt) find_package(Swifty-LLVM) ``` -------------------------------- ### Composing Asynchronous Operations with Futures in Val Source: https://github.com/hylo-lang/hylo/wiki/Asynchrony Illustrates chaining asynchronous operations using futures and `reduce`. Each step in the reduction asynchronously computes the next state by awaiting the previous partial task and applying an action. This allows for sequential composition of asynchronous tasks. ```val var state = ... type Action = State -> State val actions: [Action] = ... val task = actions.reduce( async state, fun (partialTask: async State, action: Action) -> async State { async { val s = await partialTask; ret async action(s) } }) // Wait for all actions to have been executed. state = await task ``` -------------------------------- ### Access and Modify Product Type Properties in Hylo Source: https://github.com/hylo-lang/hylo/wiki/Types Demonstrates creating an instance of Vector2, modifying its properties using dot syntax, and accessing a property for output. This illustrates basic data manipulation with product types. ```val // Creates a vector. var vec = Vector2(x: 4.2, y: 2.3) // Modify the x-component of the vector. vec.x = 2.6 // Prints the y-component of the vector. print(vec.y) ``` -------------------------------- ### Declare a basic function in Hylo Source: https://github.com/hylo-lang/hylo/wiki/Functions Demonstrates the syntax for declaring a function in Hylo, including its name, parameters with types, and return type. The function body contains statements enclosed in braces. ```hylo fun min(lhs: Int, rhs: Int) -> Int { if lhs < rhs { ret lhs } else { ret rhs } } ```