### Metacall Setup and Build Commands Source: https://github.com/valelang/vale/blob/master/docs/Metacall.md Commands to install Metacall dependencies, clone the Metacall repository, build Metacall with C and Rust loader support, and install it. ```bash sudo apt install git cmake build-essential git clone https://github.com/metacall/core.git cd core tools/metacall-environment.sh rust c source ~/.bashrc mkdir build cd build cmake -DOPTION_BUILD_LOADERS_C=ON -DOPTION_BUILD_LOADERS_RS=ON .. make -j12 sudo HOME="$HOME" make install ``` -------------------------------- ### Install Compiler Prerequisites on macOS Source: https://github.com/valelang/vale/blob/master/build-compiler.md Installs necessary dependencies and prepares the build environment for the Vale compiler on macOS. It clones the Vale repository and runs a setup script, followed by sourcing the zshrc configuration. ```shell git clone --single-branch --branch master https://github.com/ValeLang/Vale Vale/scripts/mac/install-compiler-prereqs.sh ~/BootstrappingValeCompiler source ~/.zshrc cd Vale ./scripts/mac/build-compiler.sh ~/BootstrappingValeCompiler --test=all ./scripts/VERSION ``` -------------------------------- ### Vale Impl Syntax Examples Source: https://github.com/valelang/vale/blob/master/docs/virtuals/Impls.md Demonstrates the syntax for implementing interfaces in the Vale programming language. These examples illustrate generic implementations and specific type implementations. ```vale impl MyInterface for MyStruct where T impl ISomething; impl ISpaceship for Serenity; ``` -------------------------------- ### Vale Compiler Build Command Examples for Dependencies Source: https://github.com/valelang/vale/blob/master/docs/Metacall.md Illustrative command-line examples demonstrating how the Vale compiler might handle dependencies on libraries from other languages, such as Rust. These examples show potential syntax for specifying Rust or Cargo dependencies. ```Shell valec build rocketvale=. --rs_dep=~/Rocket valec build rocketvale=. --cargo_dep=rocket@0.5.0-rc.2 ``` -------------------------------- ### Install Compiler Prerequisites on Ubuntu Source: https://github.com/valelang/vale/blob/master/build-compiler.md Installs necessary system packages and LLVM for building the Vale compiler on Ubuntu. It clones the Vale repository and runs a script to set up dependencies. Requires root privileges. ```shell sudo apt install -y git git clone --single-branch --branch master https://github.com/ValeLang/Vale # Add the -j and -s flags to the below command to also install Java and SBT from external APT repositories Vale/scripts/ubuntu/install-compiler-prereqs.sh -l LLVMForVale -b BootstrappingValeCompiler cd Vale ./scripts/ubuntu/build-compiler.sh "$PWD/../LLVMForVale/clang+llvm-13.0.1-x86_64-linux-gnu-ubuntu-18.04" "$PWD/../BootstrappingValeCompiler" --test=all ./scripts/VERSION ``` -------------------------------- ### Running the Metacall Example Source: https://github.com/valelang/vale/blob/master/docs/Metacall.md Command to execute the compiled C program, which in turn calls the Rust library via Metacall, demonstrating inter-language communication. ```bash LD_LIBRARY_PATH=/usr/local/lib ./a.out ./rust/target/debug/librocketvale.rlib ``` -------------------------------- ### Vale Code Example: Function and Main Structure Source: https://github.com/valelang/vale/blob/master/docs/hgm/HGMv11,12.md This Vale code snippet demonstrates function definition and a main execution block with conditional and loop structures. It includes examples of variable declarations, type conversions, and basic I/O operations. The 'stringify' function converts an integer to a string, and 'main' reads an integer, processes it through conditional logic and a loop, and prints boolean results. ```vale fn stringify(i int) str { s2 = str(i); ret s2; } fn main() { x = stdinReadInt(); if (x < 20) { while (x < 10) { s1 = stringify(x); n = len(s1); b = n < 3; printf(b); mut x = x + 1; } } else { z = x * 2; q = z / 2; println(q); } } ``` -------------------------------- ### Calculate Function Stack Sizes Example Source: https://github.com/valelang/vale/blob/master/docs/concurrency/VirtualThreadsPrototype.md This example demonstrates how to calculate the stack space required for different functions, including normal, recursive, and virtual calls. It outlines the components of a stack frame and provides a case study with specific byte calculations for each function in a given program. ```vale func triple(x int) int { return x * 3; } func factorial(z int) { if z < 2 { return 1; } else { return z * factorial(z - 1); } } interface IShip { func launch(self &IShip); } struct Spaceship { } im IShip for Spaceship; func launch(self &Spaceship) { println("Launching!"); } exported func main() { x = 2; z = triple(x); // Normal call f = factorial(x); // Recursive call if f < 10 { ship = ^Spaceship(); // Heap allocate a Spaceship ship.launch(); // Virtual call } } ``` -------------------------------- ### Vale Borrowing vs. Moving Example Source: https://github.com/valelang/vale/blob/master/docs/notes/ArchitectureNotes.md Demonstrates the distinction between borrowing and consuming (moving) in Vale, using collection methods like 'shout' (borrowing) and 'drain' (consuming). ```vale myList..shout() myList.map({_.shout()}) myList.drain({_.kill()}) ``` -------------------------------- ### Vale: Basic Function Signature Example Source: https://github.com/valelang/vale/blob/master/docs/regions/Regions.md A simple Vale function signature with two generic parameters, T and Y, used as examples for discussing implicit region rune placement. ```vale func moo(a T, b Y) ``` -------------------------------- ### Vale: Example AST Nodes for Region Specification Source: https://github.com/valelang/vale/blob/master/docs/regions/Regions.md Shows example AST (Abstract Syntax Tree) node types in Vale, such as ConstantIntSE and CallSE, which would be annotated to specify their result region. This is part of a strategy to manage regions at the expression level. ```vale ConstantIntSE CallSE ``` -------------------------------- ### Prefetching Iterator Optimization Example (Java) Source: https://github.com/valelang/vale/blob/master/docs/notes/StandardLibrary.md Illustrates how a prefetching iterator can optimize loops by prefetching elements from the next page while processing the current one. This example shows the conceptual transformation from a non-prefetching loop to a prefetching loop for SegmentedList and PageList. ```java for (int p = 0; p < numPages; p++) { thisPage = ... // Non-prefetching loop: for (int i = 0; i < numPerPage - L; i++) { // run body on thisPage[i] } nextPage = ... // Prefetching loop: for (int i = 0; i < L; i++) { // prefetch nextPage[i] // run body on thisPage[numPerPage - L + i] } } ``` -------------------------------- ### Vale Interface Definition Source: https://github.com/valelang/vale/blob/master/docs/concurrency/VirtualThreads.md Defines a 'Ship' interface with methods for launching, firing, and flying. This serves as an example for demonstrating how preambles are handled in Vale, particularly for virtual functions. ```vale interface Ship { fn launch(&self); fn fire(&self); fn fly(&self); } ``` -------------------------------- ### Illustrating Case Struct Resolution Logic in Vale Source: https://github.com/valelang/vale/blob/master/docs/Generics.md Provides a conceptual example of how a function match works within a case struct context in Vale. It shows a `launch` function being called on a virtual `ILaunchable` interface, with a specific match case for a `Ship` struct, demonstrating the need for bound checking. ```Vale func launch(virtual self &ILaunchable) { self match { borky &Ship => bork(fwd) } } ``` -------------------------------- ### Vale Main Function Example with Reference Alias Source: https://github.com/valelang/vale/blob/master/docs/hgm/HGMv16,17,18.md Demonstrates obtaining an initial borrow reference to a 'Ship' object and then passing its components to the 'fire' function. This highlights a scenario where a single tether can be conceptually split, leading to potential issues with immutability assumptions. ```vale fn main() { ... myShip &Ship = getShip(...); // original tether fire(myShip.engine, myShip.weapon); } ``` -------------------------------- ### Vale Concept Printer Interface Example Source: https://github.com/valelang/vale/blob/master/docs/Environments.md Defines a 'Printer' concept interface in Vale with a single special method '__call'. This example is used to illustrate a scenario where an interface needs to express specific internal methods, potentially required for advanced use cases like closure conformance. ```vale concept Printer { fn __call(x: #X) Str; } ``` -------------------------------- ### Vale: Pure Function Merging Example Source: https://github.com/valelang/vale/blob/master/docs/regions/Regions.md This Vale code demonstrates pure function merging, where lifetimes of parameters from different call sites are merged for the callee. It shows a `bork` function calling a `zork` function, illustrating how region runes can be merged. The example includes a struct `Ship` and two pure functions, `zork` and `bork`, along with an exported `main` function. ```vale struct Ship { fuel int; } pure func zork(a &m'Ship, b &m'Ship) int { 42 } pure func bork(x &r'Ship) int { return zork(x, &Ship(28)); } exported func main() int { return bork(&Ship(42)); } ``` -------------------------------- ### Vale Destructor Statement Example Source: https://github.com/valelang/vale/blob/master/docs/notes/ArchitectureNotes.md Illustrates a potential syntax for defining destructors in Vale, focusing on the 'dest' keyword. This is presented as an alternative to implicit consumption. ```vale dest moo; moo.blah() to move; blah(moo) to move; ``` -------------------------------- ### Merging Function Bounds (MFBFDP) Example Source: https://github.com/valelang/vale/blob/master/docs/Generics.md Shows a scenario where a function inherits bounds (like 'drop') from multiple sources. The compiler previously faced ambiguity and substitution issues when registering these bounds. The solution involves standardizing bound names to avoid conflicts. ```vale struct A where func drop(T)void { x T; } struct B where func drop(T)void { x T; } func myFunc(a &A, b &B) { ... } ``` -------------------------------- ### Vale Function: makeBoard Example Source: https://github.com/valelang/vale/blob/master/docs/hgm/HGMv24.md This Vale function demonstrates the creation of a 2D boolean array. It highlights a potential issue where using a non-owning reference with the `push` operation could trigger a generation check, as the compiler might not guarantee the lifetime of the reference. This example serves as a basis for discussing memory safety optimizations. ```vale func makeBoard(rand_seed int) [][]bool { rows = [][]bool(20); foreach row_i in 0..20 { row = []bool(20); foreach col_i in 0..20 { random_bool = true; row.push(random_bool); // making this & could cause a gen check. hmm. } rows.push(row); // same here. } return rows; } ``` -------------------------------- ### Vale Conflicting Generic Type Parameters Example Source: https://github.com/valelang/vale/blob/master/docs/Generics.md An example function 'bork' in Vale that demonstrates a potential conflict when generic type parameters T and Y are introduced and constrained to be equal, highlighting the need for incremental placeholder resolution. ```vale func bork(a T) Y where T = Y { return a; } ``` -------------------------------- ### Vale: Function Returning a Borrow Reference Source: https://github.com/valelang/vale/blob/master/docs/hgm/HGM Pointers and Borrows.md Demonstrates a Vale function `foo` that takes a borrow reference `x` of type `X` and returns a borrow reference to `X`. This is a core example used in edge cases related to reference management. ```vale fn foo(x &X) &X { x } ``` -------------------------------- ### Vale: Explicit Hard Tethering Syntax Examples Source: https://github.com/valelang/vale/blob/master/docs/hgm/HGMv22.md Illustrates two proposed syntaxes for explicitly tethering an object in Vale, ensuring its liveness. The first uses a `liv` keyword for variables, while the second uses an optional `liv` keyword before the variable type. This is contrasted with the default behavior which does not tether. ```vale `liv x = something.get(blah); // tethers` vs `let x = something.get(blah); // doesnt tether` or perhaps an optional keyword: `x liv = something.get(blah); // tethers` vs `x = something.get(blah); // doesnt tether` ``` -------------------------------- ### Vale: Main Function with List Operations Source: https://github.com/valelang/vale/blob/master/docs/Catalyst.md This example demonstrates the usage of the 'List' struct within a 'main' function in Vale. It includes creating a list of 'Ship' objects, adding elements to it, and accessing elements by their index. This illustrates basic list manipulation and interaction with custom structs. ```vale struct Ship { hp int; } func main() { list = List(); list.add(Ship(42)); list.add(Ship(43)); println(list.get(0).hp); } ``` -------------------------------- ### Monomorphizer Example with HashMap in Vale Source: https://github.com/valelang/vale/blob/master/docs/Generics.md This snippet illustrates a problem encountered by the monomorphizer when instantiating generic types. The example involves a `HashMap` struct with a generic bound on its hasher and a `moo` function. The bug arises during the instantiation process, specifically when `moo` is called on a `HashMap` instance, requiring careful handling of generic constraints. ```vale struct IntHasher { } func __call(this &IntHasher, x int) int { return x; } #!DeriveStructDrop struct HashMap where func(&H, int)int { hasher H; } func moo(self &HashMap) { // Nothing needed in here to cause the bug } exported func main() int { m = HashMap(IntHasher()); moo(&m); destruct m; return 9; } ``` -------------------------------- ### Build LLVM on Windows using CMake Source: https://github.com/valelang/vale/blob/master/build-compiler.md Builds the LLVM compiler infrastructure on Windows using CMake and Visual Studio. This process is resource-intensive and requires specific Visual Studio command prompt environments. It configures, builds, and installs LLVM. ```shell cd C:\llvm-project-llvmorg-13.0.1 mkdir build cd build cmake "C:\llvm-project-llvmorg-13.0.1\llvm" -D "CMAKE_INSTALL_PREFIX=C:\llvm-project-llvmorg-13.0.1\build" -D CMAKE_BUILD_TYPE=Release -G "Visual Studio 17 2022" -Thost=x64 -A x64 cmake --build . cmake --build . --target install ``` -------------------------------- ### HashMap Instantiation with Bounds in Vale Source: https://github.com/valelang/vale/blob/master/docs/Generics.md This example demonstrates a potential issue with incorporating bounds from return types in Vale. It shows how a HashMap instantiation might fail if the return type's bounds are not correctly satisfied by the arguments provided at the call site. The code highlights the challenge of ensuring all necessary function requirements, like `drop(H)`, are met. ```vale func HashMap(hasher H, equator E) HashMap { return HashMap(hasher, equator, 0); } ``` -------------------------------- ### Vale Concept Interface Declaration Example Source: https://github.com/valelang/vale/blob/master/docs/Environments.md Shows the declaration of a 'concept' interface in Vale, where all associated functions must be defined within the interface's declaration. This approach aims to simplify the contract by ensuring functions are localized. ```vale concept IRulexTR { fn resultType() ITemplataType; } ``` -------------------------------- ### Vale Concept Example Source: https://github.com/valelang/vale/blob/master/docs/FasterCompileTimes.md Demonstrates how Vale handles concepts, allowing generic functions to be constrained by method requirements without explicit interface implementation. The compiler checks for the presence of required methods. ```vale interface Addable { fn +(a T, b T) T; } fn triple>(a T) { ret a + a + a; } struct Vec2 imm { x int; y int; } fn +(a Vec2, b Vec2) { Vec2(a.x + b.x, a.y + b.y) } fn main() { q = triple(Vec2(5, 6)); // Compiler checks existence of + method for Vec2 // q is Vec2(15, 18) } ``` -------------------------------- ### Vale Interface Evaluation Function Example Source: https://github.com/valelang/vale/blob/master/docs/Environments.md Presents a Vale function 'eval' that takes a state and an abstract interface reference. It demonstrates how different rule types (EqualsTR, ConformsTR, etc.) are evaluated by calling specific handler functions, showcasing conditional logic based on rule types. ```vale fn eval(state: &!State, rule: abstract &IRulexTR) IEvalResult { if :EqualsTR => evaluateEqualsRule(state, r) if :ConformsTR => evaluateConformsRule(state, r) if :OrTR => evaluateOrRule(state, r) if :ComponentsTR => evaluateComponentsRule(state, r) if :TemplexTR => evaluateTemplex(state, templex) if :CallTR => evaluateRuleCall(state, r) } ``` -------------------------------- ### Coercing Calls And Lookups (CCAL) Example Source: https://github.com/valelang/vale/blob/master/docs/Generics.md Illustrates a compiler challenge in resolving generic type parameters for structs when faced with potential type coercions. It highlights the ambiguity between interpreting a type as a 'kind' or a 'coord' and the dependencies between lookup and call resolutions. ```vale struct Moo { bork T; } struct Bork { x Moo; } ``` -------------------------------- ### Vale Instantiator Code Lowering Example Source: https://github.com/valelang/vale/blob/master/docs/InstantiatorRegions.md Demonstrates how Vale's instantiator transforms code during the typing and instantiator phases, particularly how ownership and region mutability are represented. It shows the transition from initial declarations to the instantiator's representation, including changes within pure blocks. ```vale func main() { // main' \ ship Ship = ...; \ // Typing phase: own main'Ship \ // Instantiator: own Ship \ list List<&Ship> = ...; \ // Typing phase: own main'List<&main'Ship, main'> \ // Instantiator: own List, mut'> \ pure { // p1' \ z = &list; \ // Typing phase: &main'List<&main'Ship, main'> \ // Instantiator: imm&List, mut'> \ listOfImms List<&main'List<&main'Ship>> = ...; \ // Typing phase: own p1'List<&main'List<&main'Ship, main'>, p1'> \ // Instantiator: own List, mut'>, mut'> \ } \ } ``` -------------------------------- ### Generic Function in Vale Source: https://github.com/valelang/vale/blob/master/docs/Generics.md A generic function 'get' that accepts a list of any type 'T' and an index 'i', returning an element of type 'T'. This demonstrates basic generic type parameter usage in Vale. ```vale func get(list List, i int) T { result = list.array[i]; return result; } ``` -------------------------------- ### Vale Code Example: List Iteration with Conditional Logic Source: https://github.com/valelang/vale/blob/master/docs/hgm/HGMv11,12.md This Vale code snippet illustrates iterating over a list of 'Spaceship' objects and conditionally executing different functions based on a comparison. The 'doThings' function takes a list of 'Spaceship' as input and iterates through each 'x'. Inside the loop, an if-else statement checks if 'x' is less than 10, calling either 'doSomeThing' or 'doOtherThing' accordingly. This highlights the 'Reserve Multiple' optimization strategy. ```vale fn doThings(myList &List) { each x in myList { if x < 10 { doSomeThing(); } else { doOtherThing(); } } } ``` -------------------------------- ### Vale: len Function with Explicit Region Parameter Separation Source: https://github.com/valelang/vale/blob/master/docs/regions/Regions.md This example reformulates the `len` function's signature to explicitly separate the region parameter `r'` from other generic parameters. This clarifies the distinction between region parameters and other type parameters. ```vale pure func len[r' imm]( self r' &RHashMap) int { return self.size; } ``` -------------------------------- ### Vale Function Declaration with Implicit Default Region Source: https://github.com/valelang/vale/blob/master/docs/regions/Regions.md Illustrates how implicit regions are handled in Vale function declarations. The example shows a basic 'main' function and its expanded form with explicit region annotations, highlighting the 'm' region for mutability and read-write access. ```vale func main(args m'[]str) m'{ list = m'List(0); println(list.len()); } ``` -------------------------------- ### Vale Generic Function with Rune Return Type Source: https://github.com/valelang/vale/blob/master/docs/Generics.md Shows a generic function `moo` that takes an argument `x` of type `T` and returns a `Some`. This example is used to explain how runes specified manually (like `T` in the return type) need to be looked up from the current environment. ```vale fn moo(x T) Some { Some(x) } ``` -------------------------------- ### Vale: Translating Impl Bound Argument Names Source: https://github.com/valelang/vale/blob/master/docs/Generics.md Highlights a common issue in Vale's monomorphization where bound arguments from an implementation are brought over with their original impl placeholders, causing resolution errors. The example shows the need to translate these names to match the context of the dispatching function. ```vale odis{impl:98}<^len.odis{impl:98}$0>(&MyOption<^len.odis{impl:98}$0>).case erroneous bound arg: MySome.bound:drop:66<>(^impl:98$0) -> drop(int) correct bound arg translation needed for: MySome.bound:drop:66<>(^len.odis{impl:98}$0) ``` -------------------------------- ### Vale Macro-Derived Sibling Function with Full Context Source: https://github.com/valelang/vale/blob/master/docs/Generics.md Illustrates how macro-derived functions in Vale, such as 'drop' for sealed interfaces, require the full context of the original definition. This includes generic parameters, concept functions, and rune types. The example shows that a derived function needs these elements to be correctly defined and compiled, rather than a simplified version. ```vale sealed interface Opt where func drop(T)void { } struct Some where func drop(T)void { x T; } impl Opt for Some where func drop(T)void; ``` ```vale func drop(this Opt) void where func drop(T)void { [x] = this; } ``` -------------------------------- ### Substitution of Bounds in Dot Access (SBITAFD) in Vale Source: https://github.com/valelang/vale/blob/master/docs/Generics.md This example showcases the 'Substitute Bounds In Things Accessed From Dots' (SBITAFD) mechanism in Vale. It demonstrates how accessing fields via dot notation, like `self.table`, triggers a substitution of type parameters. For instance, `HashMapNode` is transformed into `HashMapNode`, rephrasing the type in terms of the current context's placeholders and ensuring instantiation bounds are correctly managed. ```vale #!DeriveStructDrop struct HashMapNode { key X; } #!DeriveStructDrop struct HashMap { table! Array>; } func keys(self &HashMap) { self.table.len(); } exported func main() int { m = HashMap([]HashMapNode(0)); m.keys(); [arr] = m; [] = arr; return 1337; } ``` -------------------------------- ### Compile and Run a Vale Program Source: https://github.com/valelang/vale/blob/master/README.md This snippet demonstrates how to compile and run a simple 'Hello, World!' program written in Vale. It assumes you have the Vale compiler downloaded and in your PATH. The compilation step creates an executable, which is then run. ```vale exported func main() { println("Hello world!"); } ``` ```bash ./valec build mymod=hello.vale --output_dir target ./target/main ``` -------------------------------- ### Reachability Analysis for Call Rules (OIRCRR) Example Source: https://github.com/valelang/vale/blob/master/docs/Generics.md Demonstrates a bug where a call site incorrectly includes bounds for generic parameters that the called function definition does not actually expect. The fix involves analyzing the CallSR rules of the target function to determine which reachable functions are truly necessary. ```vale func Spork>(Bork)Spork> ``` ```vale func Spork(a T) Spork { construct>(a) } ``` -------------------------------- ### Vale Ambiguous Function Call with Exported Function Source: https://github.com/valelang/vale/blob/master/docs/Generics.md Presents a Vale code example where an exported function calls another function ('moo') with ambiguous parameters. The snippet demonstrates the problem of selecting the correct function when multiple definitions exist. The text suggests that forcing such calls into runes might be a fragile solution. ```vale func moo(i int, b bool) str { return "hello"; } exported func main() str where func moo(int, bool)str { return moo(5, true); } ``` -------------------------------- ### Vale Interface and Struct with Drop Function Source: https://github.com/valelang/vale/blob/master/docs/Generics.md Shows Vale interface and struct definitions that include a 'drop' function constraint. This example highlights a compilation scenario involving itables where resolving overridden functions can lead to ambiguities due to conjured prototypes and environments. The analysis suggests that in such cases, no information should be passed downwards to avoid conflicts. ```vale interface MyInterface where func drop(T)void { } struct MyStruct where func drop(T)void { ... } impl MyInterface for MyStruct where func drop(T)void; ``` ```vale #!DeriveInterfaceDrop interface MyInterface where func drop(T)void { } virtual func drop(self MyInterface); #!DeriveStructDrop struct MyStruct where func drop(T)void { ... } func drop(self MyInterface); impl MyInterface for MyStruct where func drop(T)void; ``` -------------------------------- ### Vale Lang: Identifying Independent Generic Parameters (Milano Case) Source: https://github.com/valelang/vale/blob/master/docs/Generics.md Explains the process of identifying 'independent' generic parameters, using the `Milano` struct's implementation of `ISpaceship` as an example. This involves solving the implementation given only the interface's generic parameters to find any remaining unconstrained generic types. ```vale impl ISpaceship for Milano; // Given an ISpaceship, we solve the impl: // impl ISpaceship for Milano; // Here, ZZ is an 'independent' rune. ``` -------------------------------- ### Compile Vale Program with Module Mappings Source: https://github.com/valelang/vale/blob/master/scripts/all/valec-help-build.txt Compiles a Vale program, specifying the location of modules. The 'hello' module's source is in './samples/helloworld' and the 'stdlib' module's source is in './stdlib/src'. This command requires the valec executable to be in the system's PATH. ```bash valec build hello=./samples/helloworld ``` -------------------------------- ### Scope Tether Bit Manipulation Example Source: https://github.com/valelang/vale/blob/master/docs/hgm/HGMv21.md Illustrates how scope tether bits can be used to detect references within an object. This example shows a bitwise multiplication to check for tethers on specific bits, demonstrating a technique for efficient reference checking. ```text For example, if we had a borrow ref to the Spaceship, it might be [0x120, 8, 1] and if we wanted: * A borrow ref to the contained .engine which is 32 bytes forward, we'd add 32 to the objptr, and also 32 to the offset so it points to the same place it did. * A borrow ref to the contained .nav which is 40 bytes forward and has the next scope tether, we'd add 40 to the objptr, 40 to the offset, and **left-shift the mask by 1.** This actually makes it a bit easier to detect when there are any references anywhere inside something. If we're about to change something whose tether is at 0b000001000, and wanted to check that nobody has tethers on bits 0b0000111000, we just need to multiply the first by 0b111 (aka 7). ``` -------------------------------- ### Build Options for Valelang Compiler Source: https://github.com/valelang/vale/blob/master/scripts/all/valec-help-build.txt Demonstrates various build options for the valec compiler. These include specifying the output directory, executable name, generating LLVM IR, overriding memory regions, enabling census for compiler debugging, and verbose output. ```bash valec build --output_dir ./bin -o myprogram --llvm_ir --region_override unsafe --census --verbose ``` -------------------------------- ### RocketValeMetacall Project Build Steps Source: https://github.com/valelang/vale/blob/master/docs/Metacall.md Commands to clone the RocketValeMetacall project, build its Rust native library, and then build its C interface using Metacall. ```bash cd https://github.com/Verdagon/RocketValeMetacall.git cd RocketValeMetacall cd ~/RocketValeMetacall/src/native/rust cargo build cd ~/RocketValeMetacall/src/native gcc -I/usr/local/include -L/usr/local/lib -lmetacall metacaller.c ``` -------------------------------- ### Build Vale Compiler on Windows Source: https://github.com/valelang/vale/blob/master/build-compiler.md Builds the Vale compiler on Windows after LLVM has been successfully built or downloaded. It clones the Vale repository and executes a batch script with paths to the LLVM build and an old Vale compiler for bootstrapping. ```shell git clone https://github.com/ValeLang/Vale --single-branch --branch master cd Vale .\scripts\windows\build-compiler.bat C:\llvm\llvm-project-llvmorg-13.0.1 C:\OldValeCompiler --test=all ./scripts/VERSION ``` -------------------------------- ### Vale Hammer Boxing Hint for Inlining Source: https://github.com/valelang/vale/blob/master/docs/notes/ArchitectureNotes.md Details how Hammer can provide hints to Midas for inlining small types when converting to LLVM, aiming for performance similar to Rust's approach. ```vale struct { %Marine* } // instead of %MarineBox ``` -------------------------------- ### Define Backend Executable and Source Files (CMake) Source: https://github.com/valelang/vale/blob/master/Backend/CMakeLists.txt Defines the main 'backend' executable and lists all C++ source files, organized into logical directories. This command specifies the compilation units for the project. ```cmake add_executable(backend src/vale.cpp src/globalstate.cpp src/metal/ast.cpp src/metal/readjson.cpp src/metal/types.cpp src/translatetype.cpp src/valeopts.cpp src/mainFunction.cpp src/externs.cpp src/utils/counters.cpp src/utils/structlt.cpp src/function/function.cpp src/function/boundary.cpp src/function/expression.cpp src/function/expressions/call.cpp src/function/expressions/interfacecall.cpp src/function/expressions/construct.cpp src/function/expressions/destructure.cpp src/function/expressions/block.cpp src/function/expressions/discard.cpp src/function/expressions/mutabilify.cpp src/function/expressions/externs.cpp src/function/expressions/if.cpp src/function/expressions/constantstr.cpp src/function/expressions/precheckborrow.cpp src/function/expressions/localload.cpp src/function/expressions/while.cpp src/function/expressions/newimmruntimesizearray.cpp src/function/expressions/newmutruntimesizearray.cpp src/function/expressions/staticarrayfromcallable.cpp src/function/expressions/newarrayfromvalues.cpp src/function/expressions/shared/elements.cpp src/function/expressions/shared/members.cpp src/function/expressions/shared/shared.cpp src/utils/branch.cpp src/utils/call.cpp src/function/expressions/shared/string.cpp src/region/common/heap.cpp src/region/common/controlblock.cpp src/region/urefstructlt.cpp src/function/expressions/shared/ref.cpp src/region/common/common.cpp src/region/common/defaultlayout/structs.cpp src/region/common/defaultlayout/structsrouter.cpp src/region/rcimm/rcimm.cpp src/region/common/lgtweaks/lgtweaks.cpp src/region/common/wrcweaks/wrcweaks.cpp src/region/common/hgm/hgm.cpp src/region/common/fatweaks/fatweaks.cpp src/region/resilientv3/resilientv3.cpp src/region/naiverc/naiverc.cpp src/region/unsafe/unsafe.cpp src/region/linear/linear.cpp src/region/linear/linearstructs.cpp src/region/regions.cpp src/fileio.cpp src/options.cpp src/mainFunction.cpp src/externs.cpp src/determinism/determinism.cpp src/determinism/determinism.h src/utils/definefunction.cpp src/utils/definefunction.h src/utils/flags.cpp src/utils/flags.h src/simplehash/cppsimplehashmap.cpp src/simplehash/cppsimplehashmap.h src/simplehash/llvmsimplehashmap.cpp src/simplehash/llvmsimplehashmap.h src/utils/llvm.cpp src/utils/llvm.h src/utils/structlt.h src/region/safe/safe.cpp src/region/safe-fastest/safefastest.cpp src/region/common/migration.h src/region/common/migration.cpp src/region/iregion.cpp src/utils/randomgeneration.cpp) ``` -------------------------------- ### Vale Movechecker SoftLoad and Nulling Source: https://github.com/valelang/vale/blob/master/docs/notes/ArchitectureNotes.md Illustrates the behavior of 'move-SoftLoad' in Vale, where owning lookups are nullified after being moved, and subsequent lookups must be checked. ```vale move-SoftLoad(owning_lookup); // After move-SoftLoad, subsequent lookups must be checked. ``` -------------------------------- ### C Program to Call Rust createDir Function Source: https://github.com/valelang/vale/blob/master/docs/notes/StandardLibrary.md A simple C program demonstrating how to call the Rust `createDir` function, which is compiled as a static library. ```c extern void createDir(char *p); int main(void) { createDir("Created from Rust stdlib!"); return 0; } ``` -------------------------------- ### Vale: Main Function Demonstrating Reference Handling (Edge Case 1) Source: https://github.com/valelang/vale/blob/master/docs/hgm/HGM Pointers and Borrows.md A main function in Vale that initializes a `Ship` object, passes a borrow reference to it through `foo`, and then calls `bork`. This scenario tests the handling of returned borrow references when the original variable is about to be de-allocated (`unlet`). ```vale fn main() { x = Ship(7); bork(foo(&x), unlet x); } ``` -------------------------------- ### Vale: Concurrent Launch Wrapper Function Source: https://github.com/valelang/vale/blob/master/docs/concurrency/VirtualThreads.md This function demonstrates how to wrap the original 'launch' function with stack space reservation and release logic for concurrent execution. It's designed to be called by 'launch__route'. ```vale fn launch__concurrent(&self) { reserve_stack_space(184); launch(self); release_stack_space(184); } ``` -------------------------------- ### Recursive Struct Declaration in Vale Source: https://github.com/valelang/vale/blob/master/docs/HigherTypingPass.md Illustrates the structure of a recursive type `MyList` in Vale, showing how it internally uses `MyOption` and itself. This example highlights the need for forward declarations due to potential recursion. ```vale struct MyList imm { value: #T; next: MyOption>; } struct MyList #M where(#N = MyOption>, #M = imm) { value: #T; next: #N; } ``` -------------------------------- ### Vale: Member Access Region Transformation Source: https://github.com/valelang/vale/blob/master/docs/regions/Regions.md Demonstrates the region transformation needed when accessing members of a struct. The example shows how accessing 's.engine' requires translating the region from 'Ship.self'' to 'main.self''. ```vale func main() { s = Ship(Engine(7)); e = s.engine; println(e); } ``` -------------------------------- ### Vale Lang: Conceptual Lowering of Abstract Functions to Match-Dispatch Source: https://github.com/valelang/vale/blob/master/docs/Generics.md Illustrates the conceptual lowering of the abstract `launch` function into concrete, virtual functions that use match-dispatch. This process maps different concrete types (`Serenity`, `Firefly`, `Milano`) to their respective `launch` implementations, handling complex generic parameter mappings. ```vale func launch(virtual self &ISpaceship, bork X) where exists drop(X)void { self match { serenity &Serenity => launch(serenity, bork) firefly &Firefly => launch(firefly, bork) milano &Milano => launch(milano, bork) } } func launch(virtual self &ISpaceship, bork int) { self match { raza &Raza => launch(raza, bork) } } func launch(virtual self &ISpaceship, bork X) where exists drop(X)void { self match { enterprise &Enterprise => launch(enterprise, bork) } } ``` -------------------------------- ### LLVM Integration and Include Directories (CMake) Source: https://github.com/valelang/vale/blob/master/Backend/CMakeLists.txt Finds the LLVM 16 configuration, adds LLVM definitions, and includes LLVM and project-specific source directories. This prepares the build environment for using LLVM components. ```cmake find_package(LLVM 16 REQUIRED CONFIG) add_definitions(${LLVM_DEFINITIONS}) include_directories( ${LLVM_INCLUDE_DIRS} "${CMAKE_SOURCE_DIR}/src/" ) ``` -------------------------------- ### Vale: Unstackify within if-statement example Source: https://github.com/valelang/vale/blob/master/docs/Environments, Templatas, and Parent Entries.md Illustrates a scenario in Vale where an 'if' statement contains code that triggers an unstackify operation. It highlights the undesirable effect of this unstackify propagating to the parent environment. ```vale m = Marine(10); if (something) { drop(m); return 7; } ``` -------------------------------- ### Vale 'match' Rule Directional Variants Source: https://github.com/valelang/vale/blob/master/docs/virtuals/Impls.md Shows directional variations of the 'match' rule in Vale, depending on whether the evaluation starts from a struct or an interface. This approach aims to improve matching efficiency and prevent stack overflows. ```vale // Starting from a struct: // 1. I = MyInterface // 2. S = match(MyStruct) // 3. (T < ISomething) = true // Starting from an interface: // 1. I = match(MyInterface) // 2. S = MyStruct // 3. (T < ISomething) = true ``` -------------------------------- ### Vale Lambda Instantiation for Function Overloading (UINIT) Source: https://github.com/valelang/vale/blob/master/docs/Generics.md Shows how Vale handles lambdas by generating multiple FunctionTs/FunctionHeaderTs based on their usage with different types. This allows a single lambda expression to be effectively overloaded for various parameter types. ```vale lam = x => println(x); lam(3); lam(true); // This manifests two FunctionTs/FunctionHeaderTs: // 1. For line 2, with one parameter (int) and one template arg (int). // 2. For line 3, with one parameter (bool) and one template arg (bool). ``` -------------------------------- ### Finding Override Function Signature in Vale Source: https://github.com/valelang/vale/blob/master/docs/Generics.md Demonstrates how Valelang resolves an override function signature in Vale. It shows the target signature being looked for (`launch(Raza, int)`) and the corresponding override function found (`func launch(self Raza, bork int) where exists drop(P)void;`), highlighting the process of matching function declarations based on types and bounds. ```Vale launch(Raza, int) func launch(self Raza, bork int) where exists drop(P)void; ``` -------------------------------- ### Vale: Structs and Pure Blocks Example Source: https://github.com/valelang/vale/blob/master/docs/InstantiatorRegions.md Demonstrates how a pure block affects the mutability of struct members within a Vale function. It highlights issues where the mutability of outer scope variables might be incorrectly inferred inside a pure block. ```vale struct Engine { fuel int; } struct Spaceship { engine Engine; } exported func main(s &Spaceship) int { pure block { s.engine.fuel } } ``` -------------------------------- ### Vale V14: Inline Array Element Example Source: https://github.com/valelang/vale/blob/master/docs/hgm/HGMv14,15.md Demonstrates how Vale V14 optimizes vector operations by avoiding generation increments when elements are added and removed in succession. This is safe because the type of the element is known to remain consistent. ```vale myVec = Vec(); myVec.add(Spaceship(10)); myVec.add(Spaceship(20)); myVec.pop(); myVec.add(Spaceship(30)); myVec.pop(); myVec.add(Spaceship(40)); myVec.pop(); ``` -------------------------------- ### Rust FFI for Directory Creation Source: https://github.com/valelang/vale/blob/master/docs/notes/StandardLibrary.md A Rust library function designed to be called from other languages (like C or Vale) to create a directory. It returns a usize indicating success (0) or failure (1). ```rust use std::fs; use std::ffi::CStr; use std::os::raw::c_char; #[no_mangle] pub extern "C" fn createDir(path: *const c_char) -> usize { let slice = unsafe { CStr::from_ptr(path) }; let create_dir_result = fs::create_dir(slice.to_str().unwrap()); match create_dir_result { Ok(result) => 0, Err(error) => 1, } } ``` -------------------------------- ### Vale Abstract Function Declaration Example Source: https://github.com/valelang/vale/blob/master/docs/Environments.md Demonstrates an abstract function declaration in Vale that handles different reference types. This function defines behavior for 'StructRef2' and 'InterfaceRef2'. It highlights the use of external abstract functions, which are noted to be applicable only to sealed interfaces. ```vale def lookup(citizenRef: abstract CitizenRef2): CitizenDefinition2 = { if :StructRef2 => lookupStruct(citizenRef) if :InterfaceRef2 => lookupInterface(citizenRef) } ``` -------------------------------- ### Vale Declarations for Deterministic File Operations Source: https://github.com/valelang/vale/blob/master/docs/notes/PerfectReplayabilityNotes.md Demonstrates how to declare functions and structures in Vale for deterministic file operations, using annotations like '#Mapped' and '#Deterministic'. This allows for consistent handling of file descriptors across different runs. ```vale exported func OpenFile(filepath str) int; exported func ReadFile(fd int) str; exported func CloseFile(fd int); ``` ```vale #Mapped exported struct FileDescriptor { fd int; } #Deterministic exported func OpenFile(filepath str) ^FileDescriptor; #Deterministic exported func ReadFile(fd &FileDescriptor) str; #Deterministic exported func CloseFile(fd ^FileDescriptor); ``` -------------------------------- ### Environment Access for Call Site Solving in Vale Source: https://github.com/valelang/vale/blob/master/docs/Generics.md Illustrates the need for callees to access the caller's environment for bounds checking, but not for actual function retrieval. Actual functions should be obtained from the environments of the types being passed as arguments. ```Vale func xoo(x X) void where func drop(X)void { zoo(x); } func zoo(z Z) void where func drop(Z)void { ... } // When solving zoo(x), zoo requires func drop(Z)void // which only exists in xoo's environment. ``` -------------------------------- ### Example of Mutability Change in Pure Block (Vale) Source: https://github.com/valelang/vale/blob/master/docs/InstantiatorRegions.md This snippet demonstrates how a variable's perceived mutability can change within a 'pure' block in Vale. It highlights a potential issue where the type of 'ship' appears to change, which could confuse the backend compiler. ```vale struct Ship { hp int; } func main() { ship = Ship(42); // ship is a coord (mut main)'Ship<(mut main)'> pure { // ship is a coord (imm main)'Ship<(imm main)'> println(ship.hp); } } ``` -------------------------------- ### Rust Cargo.toml Configuration for Staticlib Source: https://github.com/valelang/vale/blob/master/docs/notes/StandardLibrary.md Configuration for a Rust project's `Cargo.toml` file to build it as a static library, enabling it to be called by other languages. ```toml [lib] crate-type = ["staticlib"] ```