### Run Pivot Lang Compiler in a Docker Container Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/tutorial/installation.md Starts a Docker container that provides an environment to use the Pivot Lang compiler. This is a convenient way to get started without direct installation on the host system. ```bash docker run -it --rm registry.cn-hangzhou.aliyuncs.com/pivot_lang/pivot_lang:latest /bin/bash ``` -------------------------------- ### Install Pivot Lang Compiler on Linux using APT Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/tutorial/installation.md Installs the Pivot Lang compiler on Ubuntu 20.04 LTS and 22.04 LTS (amd64 architecture) using apt. This involves adding the Pivot Lang apt repository and its GPG key, followed by the installation command. ```bash sudo apt update sudo apt install wget gnupg wget -O - https://pivotlang.tech/apt/public.key | sudo apt-key add - ``` ```bash sudo touch chmod +777 /etc/apt/sources.list.d/pl.list sudo chmod +777 /etc/apt/sources.list.d/pl.list sudo echo "deb [arch=amd64] https://pivotlang.tech/apt/repo focal main # deb-src [arch=amd64] https://pivotlang.tech/apt/repo focal main deb [arch=amd64] https://pivotlang.tech/apt/repo jammy main # deb-src [arch=amd64] https://pivotlang.tech/apt/repo jammy main">/etc/apt/sources.list.d/pl.list sudo apt update ``` ```bash sudo apt install pivot-lang ``` -------------------------------- ### Install Pivot Lang Compiler on macOS using Homebrew Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/tutorial/installation.md Installs the Pivot Lang compiler on macOS using the Homebrew package manager. This involves adding the pivot-studio tap and then installing the pivot-lang formula. ```bash brew tap pivot-studio/tap brew install pivot-lang ``` -------------------------------- ### Install Pivot Lang Compiler on Windows using Scoop Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/tutorial/installation.md Installs the Pivot Lang compiler on Windows using the scoop package manager. Requires scoop to be installed and the pivot bucket to be added. The compiler supports x64 architecture and depends on the MSVC environment. ```powershell scoop bucket add pivot https://github.com/Pivot-Studio/scoop scoop install plc ``` -------------------------------- ### Rust Node and Root Setup for Evacuation Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/systemlib/immix.md Demonstrates the setup of a Rust program with a Node struct and a root variable. It highlights the importance of adding all potential roots to the GC's root set when evacuation is enabled to prevent runtime errors due to incorrect pointer references. ```rust struct Node { next: *mut Node, data: u32, } fn main() { let mut root = Node { next: null_mut(), data: 0, }; let stack_ptr = &mut root as * mut u8; add_root(stack_ptr); } fn add_sub_ndoe(root: *mut Node) { let mut node = Node { next: null_mut(), data: 0, }; root.next = &mut node; } ``` -------------------------------- ### Stack Map Generation Workflow Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/systemlib/stackmap.md Illustrates the process of generating stack map data, starting from the compiler frontend inserting GC root instructions and generating initialization code, through LLVM's target code generation, to the Immix plugin generating and writing the stack map data to the target file's data segment. ```Mermaid graph LR; subgraph Front[编译器前端] A[插入gcroot指令] B[生成stackmap初始化代码] A-->B end B-->C subgraph Back[LLVM] C[目标代码生成] D[生成原始stackmap数据] C-->D end D-->E subgraph Plugin[Immix 插件] E[生成stackmap] F[写入目标代码数据段] E-->F end ``` -------------------------------- ### Rust Complex Object Vtable Implementation Example Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/systemlib/immix.md Illustrates a sample implementation of a vtable function for a complex object in Rust, demonstrating how it calls specific visitor functions for its fields. ```rust fn vtable_complex_obj1(&self, mark_ptr: VisitFunc, mark_complex: VisitFunc, mark_trait: VisitFunc){ mark_ptr(self.PointerField) mark_complex(self.ComplexField) } ``` -------------------------------- ### Rust Complex Field Vtable Implementation Example Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/systemlib/immix.md Provides an example of a vtable function for a complex field within a complex object, showing how it invokes the appropriate visitor functions for its own members. ```rust fn vtable_complex_field(&self, mark_ptr: VisitFunc, mark_complex: VisitFunc, mark_trait: VisitFunc){ mark_ptr(self.PointerField) } ``` -------------------------------- ### Evacuation Algorithm Concept (Mermaid) Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/systemlib/eva.md Illustrates the process of evacuating objects from one memory region to another, showing the state before and after evacuation. This helps visualize how memory gets reorganized. ```mermaid graph TD; subgraph 驱逐之前 A B end subgraph A[内存区域1] Obj1 Empty1 Obj2 Empty2 end subgraph B[内存区域2] Empty3 Empty4 end Obj1-.驱逐.->Empty3 Obj2-.驱逐.->Empty4 subgraph 驱逐之后 C D end subgraph C[内存区域1] Empty5 G[Empty1] Empty6 H[Empty2] end subgraph D[内存区域2] E[Obj1] F[Obj2] end 驱逐之前-->驱逐之后 ``` -------------------------------- ### LLVM IR GC Root Registration Example (Conceptual) Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/systemlib/eva.md This snippet conceptually represents the requirement in LLVM IR for heap variables to have corresponding stack allocas registered as GC roots. This ensures that the garbage collector can correctly update pointers to these variables. ```llvm ; Assuming 'p' is a pointer to a heap-allocated object ; and it's an independently existing heap variable. ; Need to ensure 'p' is loaded from a registered stack alloca. ; Example: Allocate stack space and register it as a GC root. %stack_ptr = alloca ptr, align 8 ; Allocate space for the pointer call void @register_gc_root(ptr %stack_ptr) ; Register this stack slot as a GC root ; When 'p' is used, it should be loaded from %stack_ptr. %p = load ptr, ptr %stack_ptr, align 8 ``` -------------------------------- ### Tokenizing PivotLang with `tag_token` Source: https://github.com/pivot-studio/pivot-lang/blob/master/src/nomparser/README.md This example shows how to read tokens in PivotLang using `tag_token` instead of the generic `tag`. This is important for correctly identifying language-specific tokens during parsing. ```rust use nom::IResult; use crate::token::{tag_token, Token}; fn parse_token<'a>(input: &'a str) -> IResult<&'a str, Token> { tag_token(input) } ``` -------------------------------- ### Implement Trait Method for External Struct (Extension Method) Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/method.md Shows how to implement a trait's method for a struct that is not defined in the current package, a concept known as an extension method. This example implements the `Eq` trait for slices `[T]` where `T` also implements `Eq`. ```Pivot-Lang pub trait Eq { fn eq(r:*S) bool; } impl > Eq<[T]> for [T] { fn eq(r:*[T]) bool { if arr_len(*self) != arr_len(*r) { return false; } for let i = 0; i < arr_len(*self); i = i + 1 { if !(*self)[i].eq(&(*r)[i]) { return false; } } return true; } } ``` -------------------------------- ### Explicit Type Conversion with Union Types in Rust Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/union.md Demonstrates explicit type conversion in Pivot Lang (shown with Rust syntax example) using the `as` keyword. This is used when converting a Union type to a potentially narrower type. ```rust let h = c as i128?; ``` -------------------------------- ### Forced Type Conversion with Union Types in Rust Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/union.md Illustrates forced type conversion in Pivot Lang (shown with Rust syntax example) using the `as ... !` syntax. This is used for conversions where the target type is guaranteed to be present within the Union. ```rust let i = c!; ``` -------------------------------- ### Implicit Type Conversion with Union Types in Rust Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/union.md Explains implicit type conversion in Pivot Lang (shown with Rust syntax example) where a value can be assigned to a Union type variable if the Union type includes the value's type. ```rust let c: A = a; ``` -------------------------------- ### Stack Map Initialization and Usage Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/systemlib/stackmap.md Explains the `gc_init` function provided by Immix GC for loading and processing stack map data. It details how the compiler generates initialization functions for each module and how these are called automatically in the main function to set up the GC. ```Implicit The `gc_init` function reads stack map data, iterates through it, and generates a hash table for fast lookup of safepoint addresses. The hash table maps safepoint addresses to the GC root information for the corresponding function. ``` -------------------------------- ### Immix GC Overview and Architecture Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/systemlib/immix.md Provides an overview of the immix GC, highlighting its parallel capabilities and referencing key resources for its implementation. It details the GC's architectural components: Global Allocator (GA), Thread Local Allocator (TLA), and Collector, explaining their roles in memory management and garbage collection. ```markdown 此页面仍在编写中,此GC是我们基于[immix GC论文](https://www.cs.utexas.edu/users/speedway/DaCapo/papers/immix-pldi-2008.pdf)实现的,大部分的实现细节都与论文一致,对于一些论文没提到的细节我们自行进行了实现,参考了很多别的GC项目。该GC是一个支持多线程使用的、基于StackMap的,半精确mark-region 非并发(Concurrency) 并行(Parallelism) gc。 **gc的并发(Concurrency)与并行(Parallelism)** gc中并发和并行是两个不同的术语,并发gc指的是能够在应用不暂停的基础上进行回收的gc,而并行gc指的是gc在回收的时候能够使用多个线程同时进行工作。一个gc可以既是并行的也是并发的,我们的immix gc目前只具备并行能力 这里有一些创建该gc过程中我们主要参考的资料,列表如下: - [immix gc论文](https://www.cs.utexas.edu/users/speedway/DaCapo/papers/immix-pldi-2008.pdf) - [playxe 的 immixcons(immix gc的一个rust实现,回收存在bug)-- 很多底层内存相关代码是参考该gc完成的,还有在函数头中加入自定义遍历函数的做法](https://github.com/playXE/libimmixcons) - [给scala-native使用的一个immix gc的C实现](https://github.com/scala-native/immix) - [康奈尔大学CS6120课程关于immix gc的博客,可以帮助快速理解论文的基本思路](https://www.cs.cornell.edu/courses/cs6120/2019fa/blog/immix/) 本gc是为pl __定制的__,虽然理论上能被其他项目使用,但是对外部项目的支持 __并不是主要目标__ pl的组件包含一个全局的`GlobalAllocator`,然后每个`mutator`线程会包含一个独属于该线程的`Collector`,每个`Collector`中包含一个 `ThreadLocalAllocator`。在线程使用gc相关功能的时候,该线程对应的`Collector`会自动被创建,直到线程结束或者 用户手动调用销毁api。 **部分immix gc术语介绍** **mutator** mutator指使用gc的用户程序,在有些文档里也被指代为gc的client **block** block是immix中全局分配器分配的基础单位,每个block的大小为32KB **line** line是block中的基本单位,每个line长度为128B,每个block中包含256个line **Global Allocator** 全局分配器,简称GA,分配内存以block为单位 **Thread Local Allocator** 线程本地分配器,简称TLA,分配内存以line为单位,在自身的block中分配,如果没有可用的block,会向全局分配器申请 **Collector** 线程本地的回收器,在每次gc开始的时候会运行标记和驱逐算法,然后通知Thread Local Allocator进行清扫 **Evacuation** 驱逐算法,是一种反碎片化机制 Immix GC由于分配以line为单位,在内存利用率上稍有不足,但是其算法保证了极其优秀的内存局部性,配合TLA、GA的设计也大大 减少了线程间的竞争。 ``` -------------------------------- ### Using 'alloca' for Heap Allocation Replacement Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/blogs/performance_optimization.md Illustrates the concept of using 'alloca' to replace heap allocations, a technique inspired by languages like Go, to reduce the number of heap allocations. This approach requires custom LLVM passes and leveraging analysis passes like 'CaptureTracking'. ```llvm use `alloca` to replace some heap allocations ``` ```llvm analysis pass named `CaptureTracking` which can help you to determine whether a heap pointer can be safely replaced with `alloca` ``` -------------------------------- ### Read-Write Barrier Performance (Mermaid) Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/systemlib/eva.md Visualizes the overhead introduced by read-write barriers in a garbage collection context. It shows how accessing an object might require checking for forward pointers, potentially slowing down operations. ```mermaid graph LR; subgraph load指针 S1[stack_pointer]--load-->B[Space1] B-.发现B中是forward pointer,继续load.->A1[Space2] end subgraph 修正 S2[stack_pointer]-->A2[Space2] B2[Space1]-->A2[Space2] end load指针-->修正 ``` -------------------------------- ### Adding Project Dependencies in Kagari.toml Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/module.md Shows how to declare dependencies on other local PivotLang projects within the `Kagari.toml` configuration file using the `[deps]` section and specifying the path to the dependent project. ```toml [deps] sub3 = { path = "sub2" } ``` -------------------------------- ### GC Safepoint Explanation Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/systemlib/stackmap.md Explains the concept of GC safepoints, their role in synchronizing mutator threads for garbage collection, and how they are utilized within the Immix GC implementation. It also introduces helper functions like `thread_stuck_start`, `thread_stuck_end`, and `no_gc_thread` for managing thread behavior during GC. ```Markdown `thread_stuck_start` and `thread_stuck_end`, used to mark periods where a thread is engaged in long-running tasks that should not be interrupted by GC. During these periods, the thread must not allocate new memory, or it will panic. `no_gc_thread` informs the GC that the current thread does not require GC functionality and will not allocate corresponding ThreadLocalAllocator. ``` -------------------------------- ### Specific and Wildcard Imports in PivotLang Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/module.md Illustrates two ways to import symbols from a module: importing a specific function or importing all symbols from a module using a wildcard. ```pivot-lang use mod1::func1; // 单独引入 use mod2::*; // 全引入 ``` -------------------------------- ### Importing Modules in PivotLang Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/module.md Demonstrates how to import other modules within a PivotLang project. It shows importing specific files and files within subdirectories, and how to call functions from these imported modules. ```pivot-lang use mod1; use sub::mod; fn main() void { mod1::func(); mod::func(); return; } ``` -------------------------------- ### Run All Tests Source: https://github.com/pivot-studio/pivot-lang/blob/master/CONTRIBUTING.md Executes all tests within the project to ensure code correctness and stability. This command is crucial for verifying that changes have not introduced regressions. ```rust cargo test --all ``` -------------------------------- ### Using External Project Modules in PivotLang Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/module.md Demonstrates how to import and use modules from a project that has been added as a dependency in `Kagari.toml`. The imported modules are accessed under the namespace defined in the `[deps]` configuration. ```pivot-lang use sub3::lib; fn main() void { lib::func(); return; } ``` -------------------------------- ### Run Rustfmt Source: https://github.com/pivot-studio/pivot-lang/blob/master/CONTRIBUTING.md Ensures consistent Rust code formatting by running the stable version of rustfmt. This is a standard practice for maintaining code readability and consistency in Rust projects. ```rust cargo +stable fmt ``` -------------------------------- ### Struct Definition and Generic Handling in PivotLang Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/compiler/generic.md Illustrates the process of defining a struct with generic types, adding symbols, and generating LLVM code. It details the steps from defining the struct signature to emitting its definition and handling generic parameters. ```mermaid graph TD DefStruct-->StructAddSymbol-->StructDef-->NodeEmit subgraph DefStruct Def("Struct X< T >{y:T}") end subgraph StructAddSymbol subgraph SetUpGenericMap subgraph PLType::STType GenericMap Fields end subgraph PLType::Generic CurrentType end None EmptyVec("vec![]") CurrentType-->None Fields-->EmptyVec GenericMap--T-->PLType::Generic end %% GenLLVMCode subgraph GenLLVMCode Code("生成占位符,不带泛型签名,A = type {}") end AddType("ctx.add_type(X)") SetUpGenericMap-->GenLLVMCode-->AddType end subgraph StructDef AddGeneric("将泛型T加入ctx中泛型表") GetType("ctx.get_type(X)") FieldGetType subgraph EmitStructDef AddGeneric-->GetType--X-->FieldGetType--fields-->GenVtable end end subgraph NodeEmit HightLight end ``` ```mermaid graph TD subgraph StructInit Init("A{x:1+3}") end ``` ```mermaid graph TD subgraph TypeNameNode GenericParam subgraph ExidNode ModName subgraph VarNode ID end end end subgraph API ExidNode--Mod1::Struct1-->GetOriginType-->HasGenericParam{HasGenericParam}--yes-->GetGenericType HasGenericParam--no-->RET GenericParam--"i64,bool"-->GetGenericType-->SetUpGeneric SetUpGeneric-->GenericInfer SetUpGeneric-->FieldRecursiveEq subgraph GetType GenericInfer end subgraph EqOrInfer FieldRecursiveEq end GenericInfer--"Mod1::Struct1{i64|bool}"-->RET FieldRecursiveEq-->RET end ``` -------------------------------- ### Define and Call a Basic Method in Pivot-Lang Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/method.md Demonstrates the fundamental way to define a method within an `impl` block for a struct in Pivot-Lang and how to call it using the receiver type and method name. ```Pivot-Lang let a = A{}; a.method(); ``` -------------------------------- ### Pivot Lang 变量定义和赋值 Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/basic.md 使用'let'关键字定义变量,并可以直接赋值。编译器可以自动推导出变量类型,也可以显式声明类型。 ```Pivot Lang let x = 1; let test: i8 = 1; ``` -------------------------------- ### Parse Pivot-Lang Source Code to AST (Rust) Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/compiler/parser.md This Rust function, 'parse', is the top-level entry point for the Pivot-Lang parser. It takes the source code as input and utilizes the 'nom' library to perform recursive descent parsing, ultimately converting the source into an Abstract Syntax Tree (AST) root node. It is a core component for understanding and processing Pivot-Lang code. ```rust pub fn parse(input: &str) -> ParseResult { // Placeholder for the actual parsing logic using nom // This function would typically call other parser combinators // to break down the input string according to the Pivot-Lang grammar. // Example: // let (remaining_input, ast_node) = parse_top_level_rule(input)?; // Ok((remaining_input, ast_node)) unimplemented!("Parsing logic not yet implemented"); } ``` -------------------------------- ### Pivot Lang 跳过当前循环 Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/basic.md 使用'continue'关键字跳过当前循环的剩余部分,并进入下一次迭代。 ```Pivot Lang if i == 3 {i = 5;continue;} ``` -------------------------------- ### Pivot Lang 运算 Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/basic.md 支持基本的算术运算(加减乘除)、位运算(与或非异或左移右移)和取反运算。 ```Pivot Lang test = -test; let test2: i8 = test + 1; let b = test | 1; ``` -------------------------------- ### LLVM Metadata for Custom Allocation in Pivot Lang Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/blogs/performance_optimization.md Demonstrates how to add metadata to a custom allocation function in Pivot Lang to enable LLVM optimizations. This helps LLVM recognize and potentially optimize away certain memory allocations. ```llvm add metadata `allockind("alloc")` to your custom allocate function ``` -------------------------------- ### Pivot Lang 函数定义 Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/basic.md 使用'fn'关键字定义函数,函数可以有返回值,也可以没有。示例展示了无返回值和返回i64类型的函数定义。 ```Pivot Lang pub fn test_warn() void pub fn test_vm_link() i64 ``` -------------------------------- ### Preprocessing Source Code (PivotLang) Source: https://github.com/pivot-studio/pivot-lang/blob/master/src/nomparser/README.md This snippet demonstrates preprocessing PivotLang source code by removing leading and trailing whitespace using the `delspace` function. It's crucial for ensuring accurate parsing. ```rust use nom::{bytes::complete::tag, character::complete::space0, IResult}; fn delspace<'a>(input: &'a str) -> IResult<&'a str, &'a str> { let (input, _) = space0(input)?; let (input, content) = nom::error::escaped_transform(nom::character::complete::anychar, '\\', nom::character::complete::hex_digit)( input, )?; let (input, _) = space0(input)?; Ok((input, content)) } ``` -------------------------------- ### Global Allocator (GA) Memory Allocation Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/systemlib/immix.md Details the Global Allocator's role in managing memory by allocating blocks of 32KB. It explains how GA acquires memory from the OS, divides it into blocks, and uses a 'current' pointer for allocation. The GA also maintains a 'free' array for recycled blocks. ```markdown GA是全局的,一个应用程序中只会有一个,负责分配block。在GA被初始化的时候,会向操作系统申请一大 块连续的内存,然后将其切分为block,每个block的大小为32KB。GA有一个`current`指针,指向 目前GA分配到的位置。当GA需要分配新block的时候,GA会返回当前`current`指针指向的内存空间, 并且将`current`指针向后移动一个block的距离。 GA同时维护一个`free`动态数组,用于存储已经被回收的block,当GA需要分配新block的时候,会先从`free`数组中 尝试取出一个block,如果`free`数组为空,才会分配新的block。 **潜在的优化点:** 使用bitmap来记录block的使用情况,这样可以减少动态数组的开销 **如果GA在分配新block的时候,发现`current`指针已经超出了初始申请的内存空间,会导致程序panic。这个行为应该在未来被改善** ``` -------------------------------- ### Pivot Lang: 向数组添加元素 Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/array.md 展示了如何使用`.push()`方法向Pivot Lang数组的末尾添加新元素。 ```pivot array.push(4); array.push(5); ``` -------------------------------- ### Thread Local Allocator (TLA) Small Object Allocation Strategy Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/systemlib/immix.md Describes the Thread Local Allocator's strategy for allocating small objects (less than line size). It outlines a flow using recycle blocks, new block requests, and managing block availability, including moving fully utilized blocks to an unavailable state. ```mermaid graph TD; A[分配内存]-->B{有recycle block?} B--是-->C[从recycle block中分配line] B--否-->D{申请新block} D--成功-->E[新block加入recycle block] D--失败-->I[panic] E-->C C-->F{block用完?} F--是-->G[移入unavailable block] F--否-->H[返回分配空间的指针] G-->H ``` -------------------------------- ### Pivot Lang 循环 Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/basic.md 使用'while'和'for'关键字进行循环。'for'循环支持初始化、条件和迭代语句。 ```Pivot Lang while i < 7 {...} for let i = 0; i <= 10; i = i + 1 {...} ``` -------------------------------- ### `if let ... impl ...` Equivalent Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/operator/tyops.md Provides an equivalent representation of the `if let ... impl ...` syntax using `impl ?` and `impl !` for trait implementation checks. ```plang trait TestTrait { fn test(); } struct TestStruct{}; impl TestTrait for TestStruct { fn test() { println("test"); } } fn test(x: T) T { if x impl TestTrait? { let y = x impl TestTrait!; y.test(); } return x; } ``` -------------------------------- ### Stack Map Format Definition Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/systemlib/stackmap.md Defines the binary format of the stack map data, including header, function information, safepoint addresses, and root offsets. This format is crucial for the GC to interpret stack information. ```Rust Header { i64 : Stack Map Version (current version is 1) i32 : function 数量 } // 这里要对齐 Functions[NumFunctions] { u64 : Function Address i32 : Stack Size(单位是8字节) i32 : 需要压栈的函数变量数量(不同平台不一样,大部分平台前6个参数会用寄存器传) i32 : root数量 i32 : safe point数量 SafePoints[NumSafePoints] { u64: 地址 } Roots[NumRoots] { i32: root的偏移(相对栈指针) i32: root的类型 } } Global { i32: global root数量 // 对齐 Roots[NumRoots] { u64 : 地址 } } ``` -------------------------------- ### Pivot Lang 函数调用 Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/basic.md 直接使用函数名即可调用函数。 ```Pivot Lang test_vm(); ``` -------------------------------- ### Pivot Lang 条件判断 Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/basic.md 使用'if'和'else'关键字进行条件判断。 ```Pivot Lang if i == 3 {...} ``` -------------------------------- ### Thread Local Allocator (TLA) Medium and Large Object Allocation Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/systemlib/immix.md Explains the TLA's allocation strategy for medium (larger than line size, smaller than block size/4) and large objects (larger than block size/4). Medium objects use a simplified approach to mitigate fragmentation and allocation time, while large objects use a distinct big object allocator with a mark-free algorithm. ```markdown **中对象、大对象分配策略** 中对象存在一个问题,就是如果他采用小对象的分配策略,在recycle block中分配line,那么分配过程中可能跳过 很多的小hole,而TLA的分配器在recycle block中分配的时候是**不回头**的,这样可能会导致: - 内存碎片增加 - 分配时间变长 因此,中对象分配的时候只会找recycle block中的第一个hole,如果这个hole装不下它,TLA会直接申请新的block来分配该对象, 并且将这个block加入到recycle block中。 大对象分配不使用mark region算法,它使用特殊的bigobject allocator来分配,是传统的mark free算法。 因为程序中小对象的数量远远大于中对象和大对象,所以TLA的分配器会优先优化小对象分配,以增加性能 ``` -------------------------------- ### `as` Operator: Basic Type Conversion Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/operator/tyops.md Demonstrates the `as` operator for converting between basic integer types. This conversion is always successful but may lead to data loss or precision issues. ```plang let a: i64 = 1; let b: i32 = a as i32; ``` -------------------------------- ### Pivot Lang 指针操作 Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/basic.md 使用'&'获取变量地址,使用'*'获取指针指向的值。可以修改指针指向的值。 ```Pivot Lang let b = &a; *b = 100; ``` -------------------------------- ### Forward Pointer Mechanism (Mermaid) Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/systemlib/eva.md Depicts the use of forward pointers in evacuation. When an object is moved, a forward pointer is left in its original location, pointing to the new location. This aids in updating references. ```mermaid graph LR; subgraph 驱逐之前 S[stack_pointer]-->A[Space1] A-.驱逐.->B1[Space2] end subgraph 驱逐之后 S1[stack_pointer]-->B[Space1] B-->A1[Space2] end 驱逐之前-->驱逐之后 ``` -------------------------------- ### `if let ... as ...`: Safe Generic Type Conversion Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/operator/tyops.md Demonstrates safe conversion of a generic type to `i64` using the `if let ... as ...` syntax. Returns the converted value if successful, otherwise a default value. ```plang fn test(x: T) i64 { if let y = x as i64 { return y; } return -1; } ``` -------------------------------- ### Accessing Stack Map Data Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/systemlib/stackmap.md Describes how application code can access the generated stack map information embedded within each target file's data segment. It outlines the naming convention for the global variables that provide access to this data. ```Implicit The stack map information is generated into the data segment of each target file. Applications can access this data through global variables with the naming convention: `_GC_MAP_$source_file_name`, where `$source_file_name` is the source file name recorded in the LLVM module. ``` -------------------------------- ### Export Rust Function with `is_runtime` Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/systemlib/vm.md Demonstrates how to export a Rust function for use in Pivot Lang using the `#[is_runtime]` attribute. The function can then be declared and called in Pivot Lang. ```rust #[is_runtime] fn printi64ln(i: i64) { println!("{}", i); } ``` ```pivot-lang fn printi64ln(i: i64) void fn main() void { printi64ln(1) return } ``` -------------------------------- ### Pivot Lang 逻辑运算 Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/basic.md 支持基本的逻辑运算,包括与(&&)、或(||)和非(!)。 ```Pivot Lang let x = (false && true_with_panic()) || (true || !true_with_panic()); ``` -------------------------------- ### Pivot Lang 跳出循环 Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/basic.md 使用'break'关键字跳出循环。 ```Pivot Lang if i == 5 {break;} ``` -------------------------------- ### Rust Vtable Function Signatures for GC Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/systemlib/immix.md Defines the type aliases for the visitor functions used in the garbage collection's precise object traversal. These signatures are crucial for the compiler-generated vtable functions. ```rust pub type VisitFunc = unsafe fn(&Collector, *mut u8); // vtable的签名,第一个函数是mark_ptr,第二个函数是mark_complex,第三个函数是mark_trait pub type VtableFunc = fn(*mut u8, &Collector, VisitFunc, VisitFunc, VisitFunc); ``` -------------------------------- ### Reference Update Issue (Mermaid) Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/systemlib/eva.md Illustrates a common memory safety problem where references are not correctly updated after objects are evacuated. This can lead to invalid memory accesses if a pointer still points to the old location. ```mermaid graph LR; subgraph 驱逐之前 S[stack_pointer1]-->A[Space1] S2[stack_pointer2]-->A[Space1] A-.驱逐.->B1[Space2] end subgraph 驱逐并且修正之后 S1[stack_pointer1]-->A1[Space2] S3[stack_pointer2]-->B2[Space1] end 驱逐之前-->驱逐并且修正之后 ``` -------------------------------- ### Pivot Lang: 创建和初始化数组 Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/array.md 演示了如何在Pivot Lang中创建不同类型的数组,包括直接初始化和从切片创建。还展示了如何访问和修改数组的元素。 ```pivot let a1:[i64] = [1]; let array = arr::from_slice([1, 2, 3]); let b = a1[0]; a1[0] = 100; ``` -------------------------------- ### Pivot Lang: 修改数组元素 Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/array.md 演示了如何使用`.set()`方法修改Pivot Lang数组中指定索引的元素值。 ```pivot array.set(2, 100); ``` -------------------------------- ### Pivot Lang: 遍历数组元素 Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/array.md 展示了如何使用`.iter()`获取数组迭代器,并通过循环遍历数组中的每个元素。 ```pivot let iter = array.iter(); for let i = iter.next(); i is i64; i = iter.next() { // 处理元素i } ``` -------------------------------- ### Define Methods on Union Types in Pivot Lang Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/union.md Demonstrates how to define methods on a generic Union type in Pivot Lang. This allows associated functions to operate on values held by the Union type. ```pivot impl A { fn name() void { let f = (*self) as f32!; f = 100.0; return; } } ``` -------------------------------- ### Use Union Types with Variables in Pivot Lang Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/union.md Illustrates how to declare and assign values to variables using Union types in Pivot Lang. This shows the flexibility of holding different types through a single variable declaration. ```pivot let c: A = a; let aa: B = d; let ff: D = ≫ ``` -------------------------------- ### Export Struct Methods with `is_runtime` Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/systemlib/vm.md Shows how to export methods of a Rust struct for use in Pivot Lang. The exported function name follows the pattern `{structname}__{fnname}`. Methods can use receivers and modifiers like `pub`. ```rust struct MyStruct; #[is_runtime("struct")] impl MyStruct { pub fn myfunc1() { // ... } } ``` -------------------------------- ### Pivot Lang: 访问数组元素 Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/array.md 展示了如何使用`.get()`方法安全地访问Pivot Lang数组中指定索引的元素。 ```pivot let a2 = array.get(2); ``` -------------------------------- ### Union Type as Function Return in Pivot Lang Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/union.md Shows how a Union type can be used as the return type for a function in Pivot Lang. This enables functions to return values of multiple possible types. ```pivot fn test_ret_union() Option { return 101; } ``` -------------------------------- ### Handling Syntax Errors with `ErrorNode` in PivotLang Source: https://github.com/pivot-studio/pivot-lang/blob/master/src/nomparser/README.md This snippet illustrates the expected behavior for handling syntax errors in PivotLang parsers. Instead of returning an error that would cause a panic, parsers should generate an `ErrorNode` to represent the syntax issue gracefully. ```rust use nom::IResult; use crate::ast::Node; fn parse_expression<'a>(input: &'a str) -> IResult<&'a str, Node> { // If parsing fails, return an ErrorNode instead of an error // Example: // if let Err(_) = nom_parser(input) { // return Ok((input, Node::ErrorNode("Syntax Error".to_string()))); // } unimplemented!() } ``` -------------------------------- ### Define Union Types in Pivot Lang Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/union.md Demonstrates how to define generic and non-generic Union types in Pivot Lang. Union types allow a variable to hold values of different specified types. ```pivot type A = f32 | T; type B = i32 | A; type D = *i32 | f64; ``` -------------------------------- ### Tuple Deconstruction in Pivot Lang Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/deconstruct.md Demonstrates basic tuple deconstruction in Pivot Lang, assigning elements to variables. It shows explicit type casting and deconstructing single-element tuples. Ensure the number of target elements matches the source elements to avoid errors. ```Pivot Lang let (a, b, c) = (1, 2, 3); (a, b, c): (i32, i32, i32) = (1, 2, 3); (a) = (1,); ``` -------------------------------- ### Pivot Lang: 从数组移除元素 Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/array.md 演示了如何使用`.pop()`方法从Pivot Lang数组的末尾移除最后一个元素,并返回该元素的值。 ```pivot let a5 = array.pop(); ``` -------------------------------- ### `if let ... impl ...`: Safe Trait Implementation Check Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/operator/tyops.md Shows the `if let ... impl ...` syntax for safely checking if a generic type implements a specific trait. Executes a block of code if the trait is implemented. ```plang trait TestTrait { fn test(); } struct TestStruct{}; impl TestTrait for TestStruct { fn test() { println("test"); } } fn test(x: T) T { if let y = x impl TestTrait { y.test(); } return x; } ``` -------------------------------- ### Union Type as Function Parameter in Pivot Lang Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/union.md Illustrates using a Union type as a parameter for a generic function in Pivot Lang. This enables functions to accept arguments of various specified types. ```pivot fn generic(a: Option) void { let c = a as R!; a = c; return; } ``` -------------------------------- ### `as` Operator: Union Type Conversion (Safe) Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/operator/tyops.md Illustrates converting a subtype to a union type using `as`, which is guaranteed to succeed. Also shows converting a union type back to a subtype using `?` (optional) or `!` (forced). ```plang struct ST{}; type Test = T | ST; let a: i64 = 1; let b = a as Test; let c: i64 = b as i64!; let d: Option = b as i64?; ``` -------------------------------- ### `impl` Operator: Trait Implementation Check (Forced) Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/operator/tyops.md Demonstrates the `impl` operator for checking trait implementation. The `!` suffix forces the check, causing a runtime error if the trait is not implemented. ```plang trait TestTrait { fn test(); } struct TestStruct{}; impl TestTrait for TestStruct { fn test() { println("test"); } } fn test(x: T) T { let y = x impl TestTrait?; let z = x impl TestTrait!; z.test(); return x; } ``` -------------------------------- ### `as` Operator: Generic Type Conversion (Forced) Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/operator/tyops.md Shows forced conversion of a generic type to `i64` using `as!`. This conversion occurs at compile time and results in a runtime error if it fails. ```plang fn test(x: T) i64 { let y = x as i64!; return x; } ``` -------------------------------- ### `is` Operator: Basic Type Checking Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/operator/tyops.md Explains the `is` operator for checking if a variable's type matches a specified type. Returns a boolean value. ```plang let a: i64 = 1; let b = a is i64; ``` -------------------------------- ### `is` Operator: Generic Type Checking Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/operator/tyops.md Illustrates using the `is` operator within a generic function to check the type of the generic parameter `T` at runtime. ```plang fn test(x: T) T { if x is i64 { doSth(); } return x; } ``` -------------------------------- ### Struct Deconstruction in Pivot Lang Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/deconstruct.md Illustrates struct deconstruction in Pivot Lang, requiring field names for extraction. It also shows how to omit field names when the variable name matches the field name, and how to deconstruct only specific fields from a struct. ```Pivot Lang struct Point { x: i32; y: i32; } let { x:xx, y:yy } = Point { x: 1, y: 2 }; ``` ```Pivot Lang struct Point { x: i32; y: i32; } let { x, y } = Point { x: 1, y: 2 }; // 省略字段名 let yy:i32; { x, y:yy } = Point { x: 1, y: 2 }; ``` ```Pivot Lang struct Point { x: i32; y: i32; } let { x } = Point { x: 1, y: 2 }; // 只解构 x 字段 ``` -------------------------------- ### `is` Operator: Union Type Checking Source: https://github.com/pivot-studio/pivot-lang/blob/master/book/src/references/operator/tyops.md Shows how the `is` operator can be used to check if a variable, potentially holding a union type, is of a specific subtype. ```plang struct ST{}; type Test = T | ST; let a: i64 = 1; let b = a as Test; let c = b is i64; ```