odin.ok (76078B)
1 // vim: set ft=odin sw=4 ts=8 et: 2 3 // START_INDENT 4 5 #+vet !using-stmt !using-param 6 #+feature dynamic-literals using-stmt 7 package main 8 9 import "core:fmt" 10 import "core:mem" 11 import "core:os" 12 import "core:thread" 13 import "core:time" 14 import "core:reflect" 15 import "base:runtime" 16 import "base:intrinsics" 17 import "core:math/big" 18 import "core:math/rand" 19 20 /* 21 Odin is a general-purpose programming language with distinct typing built 22 for high performance, modern systems and data-oriented programming. 23 24 Odin is the C alternative for the Joy of Programming. 25 26 # Installing Odin 27 Getting Started - https://odin-lang.org/docs/install/ 28 Instructions for downloading and install the Odin compiler and libraries. 29 30 # Learning Odin 31 Getting Started - https://odin-lang.org/docs/install/ 32 Getting Started with Odin. Downloading, installing, and getting your 33 first program to compile and run. 34 Overview of Odin - https://odin-lang.org/docs/overview/ 35 An overview of the Odin programming language and its features. 36 Frequently Asked Questions (FAQ) - https://odin-lang.org/docs/faq/ 37 Answers to common questions about Odin. 38 Packages - https://pkg.odin-lang.org/ 39 Documentation for all the official packages part of the 40 core and vendor library collections. 41 Nightly Builds - https://odin-lang.org/docs/nightly/ 42 Get the latest nightly builds of Odin. 43 More Odin Examples - https://github.com/odin-lang/examples 44 This repository contains examples of how certain things can be accomplished 45 in idiomatic Odin, allowing you learn its semantics, as well as how to use 46 parts of the core and vendor package collections. 47 */ 48 49 the_basics :: proc() { 50 fmt.println("\n# the basics") 51 52 { // The Basics 53 54 // os.args holds the path to the current executable and any arguments passed to it. 55 if len(os.args) == 1 { 56 fmt.printf("Hellope from %v.\n", os.args[0]) 57 } else if len(os.args) > 2 { 58 fmt.printf("%v, %v! from %v.\n", os.args[1], os.args[2], os.args[0]) 59 } 60 61 // Lexical elements and literals 62 // A comment 63 64 my_integer_variable: int // A comment for documentaton 65 66 // Multi-line comments begin with /* and end with */. Multi-line comments can 67 // also be nested (unlike in C): 68 /* 69 You can have any text or code here and 70 have it be commented. 71 /* 72 NOTE: comments can be nested! 73 */ 74 */ 75 76 // String literals are enclosed in double quotes and character literals in single quotes. 77 // Special characters are escaped with a backslash \ 78 79 some_string := "This is a string" 80 _ = 'A' // unicode codepoint literal 81 _ = '\n' 82 _ = "C:\\Windows\\notepad.exe" 83 // Raw string literals are enclosed with single back ticks 84 _ = `C:\Windows\notepad.exe` 85 86 // The length of a string in bytes can be found using the built-in `len` procedure: 87 _ = len("Foo") 88 _ = len(some_string) 89 90 91 // Numbers 92 93 // Numerical literals are written similar to most other programming languages. 94 // A useful feature in Odin is that underscores are allowed for better 95 // readability: 1_000_000_000 (one billion). A number that contains a dot is a 96 // floating point literal: 1.0e9 (one billion). If a number literal is suffixed 97 // with i, is an imaginary number literal: 2i (2 multiply the square root of -1). 98 99 // Binary literals are prefixed with 0b, octal literals with 0o, and hexadecimal 100 // literals 0x. A leading zero does not produce an octal constant (unlike C). 101 102 // In Odin, if a numeric constant can be represented by a type without 103 // precision loss, it will automatically convert to that type. 104 105 x: int = 1.0 // A float literal but it can be represented by an integer without precision loss 106 // Constant literals are “untyped” which means that they can implicitly convert to a type. 107 108 y: int // `y` is typed of type `int` 109 y = 1 // `1` is an untyped integer literal which can implicitly convert to `int` 110 111 z: f64 // `z` is typed of type `f64` (64-bit floating point number) 112 z = 1 // `1` is an untyped integer literal which can be implicitly converted to `f64` 113 // No need for any suffixes or decimal places like in other languages 114 // (with the exception of negative zero, which must be given as `-0.0`) 115 // CONSTANTS JUST WORK!!! 116 117 118 // Assignment statements 119 h: int = 123 // declares a new variable `h` with type `int` and assigns a value to it 120 h = 637 // assigns a new value to `h` 121 122 // `=` is the assignment operator 123 124 // You can assign multiple variables with it: 125 a, b := 1, "hello" // declares `a` and `b` and infers the types from the assignments 126 b, a = "byte", 0 127 128 // Note: `:=` is two tokens, `:` and `=`. The following are equivalent, 129 /* 130 i: int = 123 131 i: = 123 132 i := 123 133 */ 134 135 // Constant declarations 136 // Constants are entities (symbols) which have an assigned value. 137 // The constant’s value cannot be changed. 138 // The constant’s value must be able to be evaluated at compile time: 139 X :: "what" // constant `X` has the untyped string value "what" 140 141 // Constants can be explicitly typed like a variable declaration: 142 Y : int : 123 143 Z :: Y + 7 // constant computations are possible 144 145 _ = my_integer_variable 146 _ = x 147 } 148 } 149 150 control_flow :: proc() { 151 fmt.println("\n# control flow") 152 { // Control flow 153 // For loop 154 // Odin has only one loop statement, the `for` loop 155 156 // Basic for loop 157 for i := 0; i < 10; i += 1 { 158 fmt.println(i) 159 } 160 161 // NOTE: Unlike other languages like C, there are no parentheses `( )` surrounding the three components. 162 // Braces `{ }` or a `do` are always required 163 for i := 0; i < 10; i += 1 { } 164 // for i := 0; i < 10; i += 1 do fmt.print() 165 166 // The initial and post statements are optional 167 i := 0 168 for ; i < 10; { 169 i += 1 170 } 171 172 // These semicolons can be dropped. This `for` loop is equivalent to C's `while` loop 173 i = 0 174 for i < 10 { 175 i += 1 176 } 177 178 // If the condition is omitted, an infinite loop is produced: 179 for { 180 break 181 } 182 183 // Range-based for loop 184 // The basic for loop 185 for j := 0; j < 10; j += 1 { 186 fmt.println(j) 187 } 188 // can also be written 189 for j in 0..<10 { 190 fmt.println(j) 191 } 192 for j in 0..=9 { 193 fmt.println(j) 194 } 195 196 // Certain built-in types can be iterated over 197 some_string := "Hello, 世界" 198 for character in some_string { // Strings are assumed to be UTF-8 199 fmt.println(character) 200 } 201 202 some_array := [3]int{1, 4, 9} 203 for value in some_array { 204 fmt.println(value) 205 } 206 207 some_slice := []int{1, 4, 9} 208 for value in some_slice { 209 fmt.println(value) 210 } 211 212 some_dynamic_array := [dynamic]int{1, 4, 9} 213 defer delete(some_dynamic_array) 214 for value in some_dynamic_array { 215 fmt.println(value) 216 } 217 218 219 some_map := map[string]int{"A" = 1, "C" = 9, "B" = 4} 220 defer delete(some_map) 221 for key in some_map { 222 fmt.println(key) 223 } 224 225 // Alternatively a second index value can be added 226 for character, index in some_string { 227 fmt.println(index, character) 228 } 229 for value, index in some_array { 230 fmt.println(index, value) 231 } 232 for value, index in some_slice { 233 fmt.println(index, value) 234 } 235 for value, index in some_dynamic_array { 236 fmt.println(index, value) 237 } 238 for key, value in some_map { 239 fmt.println(key, value) 240 } 241 242 // The iterated values are copies and cannot be written to. 243 // The following idiom is useful for iterating over a container in a by-reference manner: 244 for _, idx in some_slice { 245 some_slice[idx] = (idx+1)*(idx+1) 246 } 247 248 249 // If statements 250 x := 123 251 if x >= 0 { 252 fmt.println("x is positive") 253 } 254 255 if y := -34; y < 0 { 256 fmt.println("y is negative") 257 } 258 259 if y := 123; y < 0 { 260 fmt.println("y is negative") 261 } else if y == 0 { 262 fmt.println("y is zero") 263 } else { 264 fmt.println("y is positive") 265 } 266 267 // Switch statement 268 // A switch statement is another way to write a sequence of if-else statements. 269 // In Odin, the default case is denoted as a case without any expression. 270 271 #partial switch arch := ODIN_ARCH; arch { 272 case .i386: 273 fmt.println("32-bit") 274 case .amd64: 275 fmt.println("64-bit") 276 case: // default 277 fmt.println("Unsupported architecture") 278 } 279 280 // Odin’s `switch` is like one in C or C++, except that Odin only runs the selected case. 281 // This means that a `break` statement is not needed at the end of each case. 282 // Another important difference is that the case values need not be integers nor constants. 283 284 // To achieve a C-like fall through into the next case block, the keyword `fallthrough` can be used. 285 one_angry_dwarf :: proc() -> int { 286 fmt.println("one_angry_dwarf was called") 287 return 1 288 } 289 290 switch j := 0; j { 291 case 0: 292 case one_angry_dwarf(): 293 } 294 295 // A switch statement without a condition is the same as `switch true`. 296 // This can be used to write a clean and long if-else chain and have the 297 // ability to break if needed 298 299 switch { 300 case x < 0: 301 fmt.println("x is negative") 302 case x == 0: 303 fmt.println("x is zero") 304 case: 305 fmt.println("x is positive") 306 } 307 308 // A `switch` statement can also use ranges like a range-based loop: 309 switch c := 'j'; c { 310 case 'A'..='Z', 'a'..='z', '0'..='9': 311 fmt.println("c is alphanumeric") 312 } 313 314 switch x { 315 case 0..<10: 316 fmt.println("units") 317 case 10..<13: 318 fmt.println("pre-teens") 319 case 13..<20: 320 fmt.println("teens") 321 case 20..<30: 322 fmt.println("twenties") 323 } 324 } 325 326 { // Defer statement 327 // A defer statement defers the execution of a statement until the end of 328 // the scope it is in. 329 330 // The following will print 4 then 234: 331 { 332 x := 123 333 defer fmt.println(x) 334 { 335 defer x = 4 336 x = 2 337 } 338 fmt.println(x) 339 340 x = 234 341 } 342 343 // You can defer an entire block too: 344 { 345 bar :: proc() {} 346 347 defer { 348 fmt.println("1") 349 fmt.println("2") 350 } 351 352 cond := false 353 defer if cond { 354 bar() 355 } 356 } 357 358 // Defer statements are executed in the reverse order that they were declared: 359 { 360 defer fmt.println("1") 361 defer fmt.println("2") 362 defer fmt.println("3") 363 } 364 // Will print 3, 2, and then 1. 365 366 if false { 367 f, err := os.open("my_file.txt") 368 if err != nil { 369 // handle error 370 } 371 defer os.close(f) 372 // rest of code 373 } 374 } 375 376 { // When statement 377 /* 378 The when statement is almost identical to the if statement but with some differences: 379 380 * Each condition must be a constant expression as a when 381 statement is evaluated at compile time. 382 * The statements within a branch do not create a new scope 383 * The compiler checks the semantics and code only for statements 384 that belong to the first condition that is true 385 * An initial statement is not allowed in a when statement 386 * when statements are allowed at file scope 387 */ 388 389 // Example 390 when ODIN_ARCH == .i386 { 391 fmt.println("32 bit") 392 } else when ODIN_ARCH == .amd64 { 393 fmt.println("64 bit") 394 } else { 395 fmt.println("Unknown architecture") 396 } 397 // The when statement is very useful for writing platform specific code. 398 // This is akin to the #if construct in C’s preprocessor however, in Odin, 399 // it is type checked. 400 } 401 402 { // Branch statements 403 cond, cond1, cond2 := false, false, false 404 one_step :: proc() { fmt.println("one_step") } 405 beyond :: proc() { fmt.println("beyond") } 406 407 // Break statement 408 for cond { 409 switch { 410 case: 411 if cond { 412 break // break out of the `switch` statement 413 } 414 } 415 416 break // break out of the `for` statement 417 } 418 419 loop: for cond1 { 420 for cond2 { 421 break loop // leaves both loops 422 } 423 } 424 425 // Continue statement 426 for cond { 427 if cond2 { 428 continue 429 } 430 fmt.println("Hellope") 431 } 432 433 // Fallthrough statement 434 435 // Odin’s switch is like one in C or C++, except that Odin only runs the selected 436 // case. This means that a break statement is not needed at the end of each case. 437 // Another important difference is that the case values need not be integers nor 438 // constants. 439 440 // fallthrough can be used to explicitly fall through into the next case block: 441 442 switch i := 0; i { 443 case 0: 444 one_step() 445 fallthrough 446 case 1: 447 beyond() 448 } 449 } 450 } 451 452 453 named_proc_return_parameters :: proc() { 454 fmt.println("\n# named proc return parameters") 455 456 foo0 :: proc() -> int { 457 return 123 458 } 459 foo1 :: proc() -> (a: int) { 460 a = 123 461 return 462 } 463 foo2 :: proc() -> (a, b: int) { 464 // Named return values act like variables within the scope 465 a = 321 466 b = 567 467 return b, a 468 } 469 fmt.println("foo0 =", foo0()) // 123 470 fmt.println("foo1 =", foo1()) // 123 471 fmt.println("foo2 =", foo2()) // 567 321 472 } 473 474 variadic_procedures :: proc() { 475 fmt.println("\n# variadic procedures") 476 sum :: proc(nums: ..int, init_value:= 0) -> (result: int) { 477 result = init_value 478 for n in nums { 479 result += n 480 } 481 return 482 } 483 fmt.println("sum(()) =", sum()) 484 fmt.println("sum(1, 2) =", sum(1, 2)) 485 fmt.println("sum(1, 2, 3, 4, 5) =", sum(1, 2, 3, 4, 5)) 486 fmt.println("sum(1, 2, 3, 4, 5, init_value = 5) =", sum(1, 2, 3, 4, 5, init_value = 5)) 487 488 // pass a slice as varargs 489 odds := []int{1, 3, 5} 490 fmt.println("odds =", odds) 491 fmt.println("sum(..odds) =", sum(..odds)) 492 fmt.println("sum(..odds, init_value = 5) =", sum(..odds, init_value = 5)) 493 } 494 495 496 explicit_procedure_overloading :: proc() { 497 fmt.println("\n# explicit procedure overloading") 498 499 add_ints :: proc(a, b: int) -> int { 500 x := a + b 501 fmt.println("add_ints", x) 502 return x 503 } 504 add_floats :: proc(a, b: f32) -> f32 { 505 x := a + b 506 fmt.println("add_floats", x) 507 return x 508 } 509 add_numbers :: proc(a: int, b: f32, c: u8) -> int { 510 x := int(a) + int(b) + int(c) 511 fmt.println("add_numbers", x) 512 return x 513 } 514 515 add :: proc{add_ints, add_floats, add_numbers} 516 517 add(int(1), int(2)) 518 add(f32(1), f32(2)) 519 add(int(1), f32(2), u8(3)) 520 521 add(1, 2) // untyped ints coerce to int tighter than f32 522 add(1.0, 2.0) // untyped floats coerce to f32 tighter than int 523 add(1, 2, 3) // three parameters 524 525 // Ambiguous answers 526 // add(1.0, 2) 527 // add(1, 2.0) 528 } 529 530 struct_type :: proc() { 531 fmt.println("\n# struct type") 532 // A struct is a record type in Odin. It is a collection of fields. 533 // Struct fields are accessed by using a dot: 534 { 535 Vector2 :: struct { 536 x: f32, 537 y: f32, 538 } 539 v := Vector2{1, 2} 540 v.x = 4 541 fmt.println(v.x) 542 543 // Struct fields can be accessed through a struct pointer: 544 545 v = Vector2{1, 2} 546 p := &v 547 p.x = 1335 548 fmt.println(v) 549 550 // We could write p^.x, however, it is nice to abstract the ability 551 // to not explicitly dereference the pointer. This is very useful when 552 // refactoring code to use a pointer rather than a value, and vice versa. 553 } 554 { 555 // A struct literal can be denoted by providing the struct’s type 556 // followed by {}. A struct literal must either provide all the 557 // arguments or none: 558 Vector3 :: struct { 559 x, y, z: f32, 560 } 561 v: Vector3 562 v = Vector3{} // Zero value 563 v = Vector3{1, 4, 9} 564 565 // You can list just a subset of the fields if you specify the 566 // field by name (the order of the named fields does not matter): 567 v = Vector3{z=1, y=2} 568 assert(v.x == 0) 569 assert(v.y == 2) 570 assert(v.z == 1) 571 } 572 { 573 // Structs can tagged with different memory layout and alignment requirements: 574 575 a :: struct #align(4) {} // align to 4 bytes 576 b :: struct #packed {} // remove padding between fields 577 c :: struct #raw_union {} // all fields share the same offset (0). This is the same as C's union 578 } 579 580 } 581 582 583 union_type :: proc() { 584 fmt.println("\n# union type") 585 { 586 val: union{int, bool} 587 val = 137 588 if i, ok := val.(int); ok { 589 fmt.println(i) 590 } 591 val = true 592 fmt.println(val) 593 594 val = nil 595 596 switch v in val { 597 case int: fmt.println("int", v) 598 case bool: fmt.println("bool", v) 599 case: fmt.println("nil") 600 } 601 } 602 { 603 // There is a duality between `any` and `union` 604 // An `any` has a pointer to the data and allows for any type (open) 605 // A `union` has as binary blob to store the data and allows only certain types (closed) 606 // The following code is with `any` but has the same syntax 607 val: any 608 val = 137 609 if i, ok := val.(int); ok { 610 fmt.println(i) 611 } 612 val = true 613 fmt.println(val) 614 615 val = nil 616 617 switch v in val { 618 case int: fmt.println("int", v) 619 case bool: fmt.println("bool", v) 620 case: fmt.println("nil") 621 } 622 } 623 624 Vector3 :: distinct [3]f32 625 Quaternion :: distinct quaternion128 626 627 // More realistic examples 628 { 629 // NOTE(bill): For the above basic examples, you may not have any 630 // particular use for it. However, my main use for them is not for these 631 // simple cases. My main use is for hierarchical types. Many prefer 632 // subtyping, embedding the base data into the derived types. Below is 633 // an example of this for a basic game Entity. 634 635 Entity :: struct { 636 id: u64, 637 name: string, 638 position: Vector3, 639 orientation: Quaternion, 640 641 derived: any, 642 } 643 644 Frog :: struct { 645 using entity: Entity, 646 jump_height: f32, 647 } 648 649 Monster :: struct { 650 using entity: Entity, 651 is_robot: bool, 652 is_zombie: bool, 653 } 654 655 // See `parametric_polymorphism` procedure for details 656 new_entity :: proc($T: typeid) -> ^Entity { 657 t := new(T) 658 t.derived = t^ 659 return t 660 } 661 662 entity := new_entity(Monster) 663 664 switch e in entity.derived { 665 case Frog: 666 fmt.println("Ribbit") 667 case Monster: 668 if e.is_robot { fmt.println("Robotic") } 669 if e.is_zombie { fmt.println("Grrrr!") } 670 fmt.println("I'm a monster") 671 } 672 } 673 674 { 675 // NOTE(bill): A union can be used to achieve something similar. Instead 676 // of embedding the base data into the derived types, the derived data 677 // in embedded into the base type. Below is the same example of the 678 // basic game Entity but using an union. 679 680 Entity :: struct { 681 id: u64, 682 name: string, 683 position: Vector3, 684 orientation: Quaternion, 685 686 derived: union {Frog, Monster}, 687 } 688 689 Frog :: struct { 690 using entity: ^Entity, 691 jump_height: f32, 692 } 693 694 Monster :: struct { 695 using entity: ^Entity, 696 is_robot: bool, 697 is_zombie: bool, 698 } 699 700 // See `parametric_polymorphism` procedure for details 701 new_entity :: proc($T: typeid) -> ^Entity { 702 t := new(Entity) 703 t.derived = T{entity = t} 704 return t 705 } 706 707 entity := new_entity(Monster) 708 709 switch e in entity.derived { 710 case Frog: 711 fmt.println("Ribbit") 712 case Monster: 713 if e.is_robot { fmt.println("Robotic") } 714 if e.is_zombie { fmt.println("Grrrr!") } 715 } 716 717 // NOTE(bill): As you can see, the usage code has not changed, only its 718 // memory layout. Both approaches have their own advantages but they can 719 // be used together to achieve different results. The subtyping approach 720 // can allow for a greater control of the memory layout and memory 721 // allocation, e.g. storing the derivatives together. However, this is 722 // also its disadvantage. You must either preallocate arrays for each 723 // derivative separation (which can be easily missed) or preallocate a 724 // bunch of "raw" memory; determining the maximum size of the derived 725 // types would require the aid of metaprogramming. Unions solve this 726 // particular problem as the data is stored with the base data. 727 // Therefore, it is possible to preallocate, e.g. [100]Entity. 728 729 // It should be noted that the union approach can have the same memory 730 // layout as the any and with the same type restrictions by using a 731 // pointer type for the derivatives. 732 733 /* 734 Entity :: struct { 735 ... 736 derived: union{^Frog, ^Monster}, 737 } 738 739 Frog :: struct { 740 using entity: Entity, 741 ... 742 } 743 Monster :: struct { 744 using entity: Entity, 745 ... 746 747 } 748 new_entity :: proc(T: type) -> ^Entity { 749 t := new(T) 750 t.derived = t 751 return t 752 } 753 */ 754 } 755 } 756 757 using_statement :: proc() { 758 // IMPORTANT NOTE: `using` as a statement is an opt-in feature which can be abled 759 // by adding `#+feature using-stmt` to be beginning of the file 760 // 761 // `using` as a struct field modifier remains available always 762 763 fmt.println("\n# using statement") 764 // using can used to bring entities declared in a scope/namespace 765 // into the current scope. This can be applied to import names, struct 766 // fields, procedure fields, and struct values. 767 768 Vector3 :: struct{x, y, z: f32} 769 { 770 Entity :: struct { 771 position: Vector3, 772 orientation: quaternion128, 773 } 774 775 // It can used like this: 776 foo0 :: proc(entity: ^Entity) { 777 fmt.println(entity.position.x, entity.position.y, entity.position.z) 778 } 779 780 // The entity members can be brought into the procedure scope by using it: 781 foo1 :: proc(entity: ^Entity) { 782 using entity 783 fmt.println(position.x, position.y, position.z) 784 } 785 786 // The using can be applied to the parameter directly: 787 foo2 :: proc(using entity: ^Entity) { 788 fmt.println(position.x, position.y, position.z) 789 } 790 791 // It can also be applied to sub-fields: 792 foo3 :: proc(entity: ^Entity) { 793 using entity.position 794 fmt.println(x, y, z) 795 } 796 } 797 { 798 // We can also apply the using statement to the struct fields directly, 799 // making all the fields of position appear as if they on Entity itself: 800 Entity :: struct { 801 using position: Vector3, 802 orientation: quaternion128, 803 } 804 foo :: proc(entity: ^Entity) { 805 fmt.println(entity.x, entity.y, entity.z) 806 } 807 808 809 // Subtype polymorphism 810 // It is possible to get subtype polymorphism, similar to inheritance-like 811 // functionality in C++, but without the requirement of vtables or unknown 812 // struct layout: 813 814 Colour :: struct {r, g, b, a: u8} 815 Frog :: struct { 816 ribbit_volume: f32, 817 using entity: Entity, 818 colour: Colour, 819 } 820 821 frog: Frog 822 // Both work 823 foo(&frog.entity) 824 foo(&frog) 825 frog.x = 123 826 827 // Note: using can be applied to arbitrarily many things, which allows 828 // the ability to have multiple subtype polymorphism (but also its issues). 829 830 // Note: using’d fields can still be referred by name. 831 } 832 } 833 834 835 implicit_context_system :: proc() { 836 fmt.println("\n# implicit context system") 837 // In each scope, there is an implicit value named context. This 838 // context variable is local to each scope and is implicitly passed 839 // by pointer to any procedure call in that scope (if the procedure 840 // has the Odin calling convention). 841 842 // The main purpose of the implicit context system is for the ability 843 // to intercept third-party code and libraries and modify their 844 // functionality. One such case is modifying how a library allocates 845 // something or logs something. In C, this was usually achieved with 846 // the library defining macros which could be overridden so that the 847 // user could define what he wanted. However, not many libraries 848 // supported this in many languages by default which meant intercepting 849 // third-party code to see what it does and to change how it does it is 850 // not possible. 851 852 c := context // copy the current scope's context 853 854 context.user_index = 456 855 { 856 context.allocator = my_custom_allocator() 857 context.user_index = 123 858 what_a_fool_believes() // the `context` for this scope is implicitly passed to `what_a_fool_believes` 859 } 860 861 // `context` value is local to the scope it is in 862 assert(context.user_index == 456) 863 864 what_a_fool_believes :: proc() { 865 c := context // this `context` is the same as the parent procedure that it was called from 866 // From this example, context.user_index == 123 867 // A context.allocator is assigned to the return value of `my_custom_allocator()` 868 assert(context.user_index == 123) 869 870 // The memory management procedure use the `context.allocator` by 871 // default unless explicitly specified otherwise 872 china_grove := new(int) 873 free(china_grove) 874 875 _ = c 876 } 877 878 my_custom_allocator :: mem.nil_allocator 879 _ = c 880 881 // By default, the context value has default values for its parameters which is 882 // decided in the package runtime. What the defaults are are compiler specific. 883 884 // To see what the implicit context value contains, please see the following 885 // definition in package runtime. 886 } 887 888 parametric_polymorphism :: proc() { 889 fmt.println("\n# parametric polymorphism") 890 891 print_value :: proc(value: $T) { 892 fmt.printf("print_value: %T %v\n", value, value) 893 } 894 895 v1: int = 1 896 v2: f32 = 2.1 897 v3: f64 = 3.14 898 v4: string = "message" 899 900 print_value(v1) 901 print_value(v2) 902 print_value(v3) 903 print_value(v4) 904 905 fmt.println() 906 907 add :: proc(p, q: $T) -> T { 908 x: T = p + q 909 return x 910 } 911 912 a := add(3, 4) 913 fmt.printf("a: %T = %v\n", a, a) 914 915 b := add(3.2, 4.3) 916 fmt.printf("b: %T = %v\n", b, b) 917 918 // This is how `new` is implemented 919 alloc_type :: proc($T: typeid) -> ^T { 920 t := cast(^T)mem.alloc(size_of(T), align_of(T)) 921 t^ = T{} // Use default initialization value 922 return t 923 } 924 925 copy_slice :: proc(dst, src: []$T) -> int { 926 n := min(len(dst), len(src)) 927 if n > 0 { 928 mem.copy(&dst[0], &src[0], n*size_of(T)) 929 } 930 return n 931 } 932 933 double_params :: proc(a: $A, b: $B) -> A { 934 return a + A(b) 935 } 936 937 fmt.println(double_params(12, 1.345)) 938 939 940 941 { // Polymorphic Types and Type Specialization 942 Table_Slot :: struct($Key, $Value: typeid) { 943 occupied: bool, 944 hash: u32, 945 key: Key, 946 value: Value, 947 } 948 TABLE_SIZE_MIN :: 32 949 Table :: struct($Key, $Value: typeid) { 950 count: int, 951 allocator: mem.Allocator, 952 slots: []Table_Slot(Key, Value), 953 } 954 955 // Only allow types that are specializations of a (polymorphic) slice 956 make_slice :: proc($T: typeid/[]$E, len: int) -> T { 957 return make(T, len) 958 } 959 960 // Only allow types that are specializations of `Table` 961 allocate :: proc(table: ^$T/Table, capacity: int) { 962 c := context 963 if table.allocator.procedure != nil { 964 c.allocator = table.allocator 965 } 966 context = c 967 968 table.slots = make_slice(type_of(table.slots), max(capacity, TABLE_SIZE_MIN)) 969 } 970 971 expand :: proc(table: ^$T/Table) { 972 c := context 973 if table.allocator.procedure != nil { 974 c.allocator = table.allocator 975 } 976 context = c 977 978 old_slots := table.slots 979 defer delete(old_slots) 980 981 cap := max(2*len(table.slots), TABLE_SIZE_MIN) 982 allocate(table, cap) 983 984 for s in old_slots { 985 if s.occupied { 986 put(table, s.key, s.value) 987 } 988 } 989 } 990 991 // Polymorphic determination of a polymorphic struct 992 // put :: proc(table: ^$T/Table, key: T.Key, value: T.Value) { 993 put :: proc(table: ^Table($Key, $Value), key: Key, value: Value) { 994 hash := get_hash(key) // Ad-hoc method which would fail in a different scope 995 index := find_index(table, key, hash) 996 if index < 0 { 997 if f64(table.count) >= 0.75*f64(len(table.slots)) { 998 expand(table) 999 } 1000 assert(table.count <= len(table.slots)) 1001 1002 index = int(hash % u32(len(table.slots))) 1003 1004 for table.slots[index].occupied { 1005 if index += 1; index >= len(table.slots) { 1006 index = 0 1007 } 1008 } 1009 1010 table.count += 1 1011 } 1012 1013 slot := &table.slots[index] 1014 slot.occupied = true 1015 slot.hash = hash 1016 slot.key = key 1017 slot.value = value 1018 } 1019 1020 1021 // find :: proc(table: ^$T/Table, key: T.Key) -> (T.Value, bool) { 1022 find :: proc(table: ^Table($Key, $Value), key: Key) -> (Value, bool) { 1023 hash := get_hash(key) 1024 index := find_index(table, key, hash) 1025 if index < 0 { 1026 return Value{}, false 1027 } 1028 return table.slots[index].value, true 1029 } 1030 1031 find_index :: proc(table: ^Table($Key, $Value), key: Key, hash: u32) -> int { 1032 if len(table.slots) <= 0 { 1033 return -1 1034 } 1035 1036 index := int(hash % u32(len(table.slots))) 1037 for table.slots[index].occupied { 1038 if table.slots[index].hash == hash { 1039 if table.slots[index].key == key { 1040 return index 1041 } 1042 } 1043 1044 if index += 1; index >= len(table.slots) { 1045 index = 0 1046 } 1047 } 1048 1049 return -1 1050 } 1051 1052 get_hash :: proc(s: string) -> u32 { // fnv32a 1053 h: u32 = 0x811c9dc5 1054 for i in 0..<len(s) { 1055 h = (h ~ u32(s[i])) * 0x01000193 1056 } 1057 return h 1058 } 1059 1060 1061 table: Table(string, int) 1062 1063 for i in 0..=36 { put(&table, "Hellope", i) } 1064 for i in 0..=42 { put(&table, "World!", i) } 1065 1066 found, _ := find(&table, "Hellope") 1067 fmt.printf("`found` is %v\n", found) 1068 1069 found, _ = find(&table, "World!") 1070 fmt.printf("`found` is %v\n", found) 1071 1072 // I would not personally design a hash table like this in production 1073 // but this is a nice basic example 1074 // A better approach would either use a `u64` or equivalent for the key 1075 // and let the user specify the hashing function or make the user store 1076 // the hashing procedure with the table 1077 } 1078 1079 { // Parametric polymorphic union 1080 Error :: enum { 1081 Foo0, 1082 Foo1, 1083 Foo2, 1084 Foo3, 1085 } 1086 Para_Union :: union($T: typeid) {T, Error} 1087 r: Para_Union(int) 1088 fmt.println(typeid_of(type_of(r))) 1089 1090 fmt.println(r) 1091 r = 123 1092 fmt.println(r) 1093 r = Error.Foo0 // r = .Foo0 is allow too, see implicit selector expressions below 1094 fmt.println(r) 1095 } 1096 1097 { // Polymorphic names 1098 foo :: proc($N: $I, $T: typeid) -> (res: [N]T) { 1099 // `N` is the constant value passed 1100 // `I` is the type of N 1101 // `T` is the type passed 1102 fmt.printf("Generating an array of type %v from the value %v of type %v\n", 1103 typeid_of(type_of(res)), N, typeid_of(I)) 1104 for i in 0..<N { 1105 res[i] = T(i*i) 1106 } 1107 return 1108 } 1109 1110 T :: int 1111 array := foo(4, T) 1112 for v, i in array { 1113 assert(v == T(i*i)) 1114 } 1115 1116 // Matrix multiplication 1117 mul :: proc(a: [$M][$N]$T, b: [N][$P]T) -> (c: [M][P]T) { 1118 for i in 0..<M { 1119 for j in 0..<P { 1120 for k in 0..<N { 1121 c[i][j] += a[i][k] * b[k][j] 1122 } 1123 } 1124 } 1125 return 1126 } 1127 1128 x := [2][3]f32{ 1129 {1, 2, 3}, 1130 {3, 2, 1}, 1131 } 1132 y := [3][2]f32{ 1133 {0, 8}, 1134 {6, 2}, 1135 {8, 4}, 1136 } 1137 z := mul(x, y) 1138 assert(z == {{36, 24}, {20, 32}}) 1139 } 1140 } 1141 1142 1143 prefix_table := [?]string{ 1144 "White", 1145 "Red", 1146 "Green", 1147 "Blue", 1148 "Octarine", 1149 "Black", 1150 } 1151 1152 print_mutex := b64(false) 1153 1154 @(disabled=!thread.IS_SUPPORTED) 1155 threading_example :: proc() { 1156 fmt.println("\n# threading_example") 1157 1158 did_acquire :: proc(m: ^b64) -> (acquired: bool) { 1159 res, ok := intrinsics.atomic_compare_exchange_strong(m, false, true) 1160 return ok && res == false 1161 } 1162 1163 { // Basic Threads 1164 fmt.println("\n## Basic Threads") 1165 worker_proc :: proc(t: ^thread.Thread) { 1166 for iteration in 1..=5 { 1167 fmt.printf("Thread %d is on iteration %d\n", t.user_index, iteration) 1168 fmt.printf("`%s`: iteration %d\n", prefix_table[t.user_index], iteration) 1169 time.sleep(1 * time.Millisecond) 1170 } 1171 } 1172 1173 threads := make([dynamic]^thread.Thread, 0, len(prefix_table)) 1174 defer delete(threads) 1175 1176 for _ in prefix_table { 1177 if t := thread.create(worker_proc); t != nil { 1178 t.init_context = context 1179 t.user_index = len(threads) 1180 append(&threads, t) 1181 thread.start(t) 1182 } 1183 } 1184 1185 for len(threads) > 0 { 1186 for i := 0; i < len(threads); /**/ { 1187 if t := threads[i]; thread.is_done(t) { 1188 fmt.printf("Thread %d is done\n", t.user_index) 1189 thread.destroy(t) 1190 1191 ordered_remove(&threads, i) 1192 } else { 1193 i += 1 1194 } 1195 } 1196 } 1197 } 1198 1199 { // Thread Pool 1200 fmt.println("\n## Thread Pool") 1201 task_proc :: proc(t: thread.Task) { 1202 index := t.user_index % len(prefix_table) 1203 for iteration in 1..=5 { 1204 for !did_acquire(&print_mutex) { thread.yield() } // Allow one thread to print at a time. 1205 1206 fmt.printf("Worker Task %d is on iteration %d\n", t.user_index, iteration) 1207 fmt.printf("`%s`: iteration %d\n", prefix_table[index], iteration) 1208 1209 print_mutex = false 1210 1211 time.sleep(1 * time.Millisecond) 1212 } 1213 } 1214 1215 N :: 3 1216 1217 pool: thread.Pool 1218 thread.pool_init(&pool, allocator=context.allocator, thread_count=N) 1219 defer thread.pool_destroy(&pool) 1220 1221 1222 for i in 0..<30 { 1223 // be mindful of the allocator used for tasks. The allocator needs to be thread safe, or be owned by the task for exclusive use 1224 thread.pool_add_task(&pool, allocator=context.allocator, procedure=task_proc, data=nil, user_index=i) 1225 } 1226 1227 thread.pool_start(&pool) 1228 thread.pool_finish(&pool) 1229 } 1230 } 1231 1232 1233 array_programming :: proc() { 1234 fmt.println("\n# array programming") 1235 { 1236 a := [3]f32{1, 2, 3} 1237 b := [3]f32{5, 6, 7} 1238 c := a * b 1239 d := a + b 1240 e := 1 + (c - d) / 2 1241 fmt.printf("%.1f\n", e) // [0.5, 3.0, 6.5] 1242 } 1243 1244 { 1245 a := [3]f32{1, 2, 3} 1246 b := swizzle(a, 2, 1, 0) 1247 assert(b == [3]f32{3, 2, 1}) 1248 1249 c := swizzle(a, 0, 0) 1250 assert(c == [2]f32{1, 1}) 1251 assert(c == 1) 1252 } 1253 1254 { 1255 Vector3 :: distinct [3]f32 1256 a := Vector3{1, 2, 3} 1257 b := Vector3{5, 6, 7} 1258 c := (a * b)/2 + 1 1259 d := c.x + c.y + c.z 1260 fmt.printf("%.1f\n", d) // 22.0 1261 1262 cross :: proc(a, b: Vector3) -> Vector3 { 1263 i := swizzle(a, 1, 2, 0) * swizzle(b, 2, 0, 1) 1264 j := swizzle(a, 2, 0, 1) * swizzle(b, 1, 2, 0) 1265 return i - j 1266 } 1267 1268 cross_shorter :: proc(a, b: Vector3) -> Vector3 { 1269 i := a.yzx * b.zxy 1270 j := a.zxy * b.yzx 1271 return i - j 1272 } 1273 1274 blah :: proc(a: Vector3) -> f32 { 1275 return a.x + a.y + a.z 1276 } 1277 1278 x := cross(a, b) 1279 fmt.println(x) 1280 fmt.println(blah(x)) 1281 } 1282 } 1283 1284 map_type :: proc() { 1285 fmt.println("\n# map type") 1286 1287 m := make(map[string]int) 1288 defer delete(m) 1289 1290 m["Bob"] = 2 1291 m["Ted"] = 5 1292 fmt.println(m["Bob"]) 1293 1294 delete_key(&m, "Ted") 1295 1296 // If an element of a key does not exist, the zero value of the 1297 // element will be returned. To check to see if an element exists 1298 // can be done in two ways: 1299 elem, ok := m["Bob"] 1300 exists := "Bob" in m 1301 _, _ = elem, ok 1302 _ = exists 1303 } 1304 1305 implicit_selector_expression :: proc() { 1306 fmt.println("\n# implicit selector expression") 1307 1308 Foo :: enum {A, B, C} 1309 1310 f: Foo 1311 f = Foo.A 1312 f = .A 1313 1314 BAR :: bit_set[Foo]{.B, .C} 1315 1316 switch f { 1317 case .A: 1318 fmt.println("HITHER") 1319 case .B: 1320 if true do fmt.println("NEVER") 1321 case .C: 1322 fmt.println("FOREVER") 1323 } 1324 1325 my_map := make(map[Foo]int) 1326 defer delete(my_map) 1327 1328 my_map[.A] = 123 1329 my_map[Foo.B] = 345 1330 1331 fmt.println(my_map[.A] + my_map[Foo.B] + my_map[.C]) 1332 } 1333 1334 1335 partial_switch :: proc() { 1336 fmt.println("\n# partial_switch") 1337 { // enum 1338 Foo :: enum { 1339 A, 1340 B, 1341 C, 1342 D, 1343 } 1344 1345 f := Foo.A 1346 switch f { 1347 case .A: fmt.println("A") 1348 case .B: fmt.println("B") 1349 case .C: fmt.println("C") 1350 case .D: fmt.println("D") 1351 case: fmt.println("?") 1352 } 1353 1354 #partial switch f { 1355 case .A: fmt.println("A") 1356 case .D: fmt.println("D") 1357 } 1358 } 1359 { // union 1360 Foo :: union {int, bool} 1361 f: Foo = 123 1362 switch _ in f { 1363 case int: fmt.println("int") 1364 case bool: fmt.println("bool") 1365 case: 1366 } 1367 1368 #partial switch _ in f { 1369 case bool: fmt.println("bool") 1370 } 1371 } 1372 } 1373 1374 cstring_example :: proc() { 1375 fmt.println("\n# cstring_example") 1376 1377 W :: "Hellope" 1378 X :: cstring(W) 1379 Y :: string(X) 1380 1381 w := W 1382 _ = w 1383 x: cstring = X 1384 y: string = Y 1385 z := string(x) 1386 fmt.println(x, y, z) 1387 fmt.println(len(x), len(y), len(z)) 1388 fmt.println(len(W), len(X), len(Y)) 1389 // IMPORTANT NOTE for cstring variables 1390 // len(cstring) is O(N) 1391 // cast(string)cstring is O(N) 1392 } 1393 1394 bit_set_type :: proc() { 1395 fmt.println("\n# bit_set type") 1396 1397 { 1398 Day :: enum { 1399 Sunday, 1400 Monday, 1401 Tuesday, 1402 Wednesday, 1403 Thursday, 1404 Friday, 1405 Saturday, 1406 } 1407 1408 Days :: distinct bit_set[Day] 1409 WEEKEND :: Days{.Sunday, .Saturday} 1410 1411 d: Days 1412 d = {.Sunday, .Monday} 1413 e := d + WEEKEND 1414 e += {.Monday} 1415 fmt.println(d, e) 1416 1417 ok := .Saturday in e // `in` is only allowed for `map` and `bit_set` types 1418 fmt.println(ok) 1419 if .Saturday in e { 1420 fmt.println("Saturday in", e) 1421 } 1422 X :: .Saturday in WEEKEND // Constant evaluation 1423 fmt.println(X) 1424 fmt.println("Cardinality:", card(e)) 1425 } 1426 { 1427 x: bit_set['A'..='Z'] 1428 #assert(size_of(x) == size_of(u32)) 1429 y: bit_set[0..=8; u16] 1430 fmt.println(typeid_of(type_of(x))) // bit_set[A..=Z] 1431 fmt.println(typeid_of(type_of(y))) // bit_set[0..=8; u16] 1432 1433 x += {'F'} 1434 assert('F' in x) 1435 x -= {'F'} 1436 assert('F' not_in x) 1437 1438 y += {1, 4, 2} 1439 assert(2 in y) 1440 } 1441 { 1442 Letters :: bit_set['A'..='Z'] 1443 a := Letters{'A', 'B'} 1444 b := Letters{'A', 'B', 'C', 'D', 'F'} 1445 c := Letters{'A', 'B'} 1446 1447 assert(a <= b) // 'a' is a subset of 'b' 1448 assert(b >= a) // 'b' is a superset of 'a' 1449 assert(a < b) // 'a' is a strict subset of 'b' 1450 assert(b > a) // 'b' is a strict superset of 'a' 1451 1452 assert(!(a < c)) // 'a' is a not strict subset of 'c' 1453 assert(!(c > a)) // 'c' is a not strict superset of 'a' 1454 } 1455 } 1456 1457 deferred_procedure_associations :: proc() { 1458 fmt.println("\n# deferred procedure associations") 1459 1460 @(deferred_out=closure) 1461 open :: proc(s: string) -> bool { 1462 fmt.println(s) 1463 return true 1464 } 1465 1466 closure :: proc(ok: bool) { 1467 fmt.println("Goodbye?", ok) 1468 } 1469 1470 if open("Welcome") { 1471 fmt.println("Something in the middle, mate.") 1472 } 1473 } 1474 1475 reflection :: proc() { 1476 fmt.println("\n# reflection") 1477 1478 Foo :: struct { 1479 x: int `tag1`, 1480 y: string `json:"y_field"`, 1481 z: bool, // no tag 1482 } 1483 1484 id := typeid_of(Foo) 1485 names := reflect.struct_field_names(id) 1486 types := reflect.struct_field_types(id) 1487 tags := reflect.struct_field_tags(id) 1488 1489 assert(len(names) == len(types) && len(names) == len(tags)) 1490 1491 fmt.println("Foo :: struct {") 1492 for tag, i in tags { 1493 name, type := names[i], types[i] 1494 if tag != "" { 1495 fmt.printf("\t%s: %T `%s`,\n", name, type, tag) 1496 } else { 1497 fmt.printf("\t%s: %T,\n", name, type) 1498 } 1499 } 1500 fmt.println("}") 1501 1502 1503 for tag, i in tags { 1504 if val, ok := reflect.struct_tag_lookup(tag, "json"); ok { 1505 fmt.printf("json: %s -> %s\n", names[i], val) 1506 } 1507 } 1508 } 1509 1510 quaternions :: proc() { 1511 // Not just an April Fool's Joke any more, but a fully working thing! 1512 fmt.println("\n# quaternions") 1513 1514 { // Quaternion operations 1515 q := 1 + 2i + 3j + 4k 1516 r := quaternion(real=5, imag=6, jmag=7, kmag=8) 1517 t := q * r 1518 fmt.printf("(%v) * (%v) = %v\n", q, r, t) 1519 v := q / r 1520 fmt.printf("(%v) / (%v) = %v\n", q, r, v) 1521 u := q + r 1522 fmt.printf("(%v) + (%v) = %v\n", q, r, u) 1523 s := q - r 1524 fmt.printf("(%v) - (%v) = %v\n", q, r, s) 1525 } 1526 { // The quaternion types 1527 q128: quaternion128 // 4xf32 1528 q256: quaternion256 // 4xf64 1529 q128 = quaternion(w=1, x=0, y=0, z=0) 1530 q256 = 1 // quaternion(x=0, y=0, z=0, w=1) 1531 1532 // NOTE: The internal memory layout of a quaternion is xyzw 1533 } 1534 { // Built-in procedures 1535 q := 1 + 2i + 3j + 4k 1536 fmt.println("q =", q) 1537 fmt.println("real(q) =", real(q)) 1538 fmt.println("imag(q) =", imag(q)) 1539 fmt.println("jmag(q) =", jmag(q)) 1540 fmt.println("kmag(q) =", kmag(q)) 1541 fmt.println("conj(q) =", conj(q)) 1542 fmt.println("abs(q) =", abs(q)) 1543 } 1544 { // Conversion of a complex type to a quaternion type 1545 c := 1 + 2i 1546 q := quaternion256(c) 1547 fmt.println(c) 1548 fmt.println(q) 1549 } 1550 { // Memory layout of Quaternions 1551 q := 1 + 2i + 3j + 4k 1552 a := transmute([4]f64)q 1553 fmt.println("Quaternion memory layout: xyzw/(ijkr)") 1554 fmt.println(q) // 1.000+2.000i+3.000j+4.000k 1555 fmt.println(a) // [2.000, 3.000, 4.000, 1.000] 1556 } 1557 } 1558 1559 unroll_for_statement :: proc() { 1560 fmt.println("\n#'#unroll for' statements") 1561 1562 // '#unroll for' works the same as if the 'inline' prefix did not 1563 // exist but these ranged loops are explicitly unrolled which can 1564 // be very very useful for certain optimizations 1565 1566 fmt.println("Ranges") 1567 #unroll for x, i in 1..<4 { 1568 fmt.println(x, i) 1569 } 1570 1571 fmt.println("Strings") 1572 #unroll for r, i in "Hello, 世界" { 1573 fmt.println(r, i) 1574 } 1575 1576 fmt.println("Arrays") 1577 #unroll for elem, idx in ([4]int{1, 4, 9, 16}) { 1578 fmt.println(elem, idx) 1579 } 1580 1581 1582 Foo_Enum :: enum { 1583 A = 1, 1584 B, 1585 C = 6, 1586 D, 1587 } 1588 fmt.println("Enum types") 1589 #unroll for elem, idx in Foo_Enum { 1590 fmt.println(elem, idx) 1591 } 1592 } 1593 1594 where_clauses :: proc() { 1595 fmt.println("\n#procedure 'where' clauses") 1596 1597 { // Sanity checks 1598 simple_sanity_check :: proc(x: [2]int) 1599 where len(x) > 1, 1600 type_of(x) == [2]int { 1601 fmt.println(x) 1602 } 1603 } 1604 { // Parametric polymorphism checks 1605 cross_2d :: proc(a, b: $T/[2]$E) -> E 1606 where intrinsics.type_is_numeric(E) { 1607 return a.x*b.y - a.y*b.x 1608 } 1609 cross_3d :: proc(a, b: $T/[3]$E) -> T 1610 where intrinsics.type_is_numeric(E) { 1611 x := a.y*b.z - a.z*b.y 1612 y := a.z*b.x - a.x*b.z 1613 z := a.x*b.y - a.y*b.x 1614 return T{x, y, z} 1615 } 1616 1617 a := [2]int{1, 2} 1618 b := [2]int{5, -3} 1619 fmt.println(cross_2d(a, b)) 1620 1621 x := [3]f32{1, 4, 9} 1622 y := [3]f32{-5, 0, 3} 1623 fmt.println(cross_3d(x, y)) 1624 1625 // Failure case 1626 // i := [2]bool{true, false} 1627 // j := [2]bool{false, true} 1628 // fmt.println(cross_2d(i, j)) 1629 1630 } 1631 1632 { // Procedure groups usage 1633 foo :: proc(x: [$N]int) -> bool 1634 where N > 2 { 1635 fmt.println(#procedure, "was called with the parameter", x) 1636 return true 1637 } 1638 1639 bar :: proc(x: [$N]int) -> bool 1640 where 0 < N, 1641 N <= 2 { 1642 fmt.println(#procedure, "was called with the parameter", x) 1643 return false 1644 } 1645 1646 baz :: proc{foo, bar} 1647 1648 x := [3]int{1, 2, 3} 1649 y := [2]int{4, 9} 1650 ok_x := baz(x) 1651 ok_y := baz(y) 1652 assert(ok_x == true) 1653 assert(ok_y == false) 1654 } 1655 1656 { // Record types 1657 Foo :: struct($T: typeid, $N: int) 1658 where intrinsics.type_is_integer(T), 1659 N > 2 { 1660 x: [N]T, 1661 y: [N-2]T, 1662 } 1663 1664 T :: i32 1665 N :: 5 1666 f: Foo(T, N) 1667 #assert(size_of(f) == (N+N-2)*size_of(T)) 1668 } 1669 } 1670 1671 1672 when ODIN_OS == .Windows { 1673 foreign import kernel32 "system:kernel32.lib" 1674 } 1675 1676 foreign_system :: proc() { 1677 fmt.println("\n#foreign system") 1678 when ODIN_OS == .Windows { 1679 // It is sometimes necessarily to interface with foreign code, 1680 // such as a C library. In Odin, this is achieved through the 1681 // foreign system. You can “import” a library into the code 1682 // using the same semantics as a normal import declaration. 1683 1684 // This foreign import declaration will create a 1685 // “foreign import name” which can then be used to associate 1686 // entities within a foreign block. 1687 1688 foreign kernel32 { 1689 ExitProcess :: proc "stdcall" (exit_code: u32) --- 1690 } 1691 1692 // Foreign procedure declarations have the cdecl/c calling 1693 // convention by default unless specified otherwise. Due to 1694 // foreign procedures do not have a body declared within this 1695 // code, you need append the --- symbol to the end to distinguish 1696 // it as a procedure literal without a body and not a procedure type. 1697 1698 // The attributes system can be used to change specific properties 1699 // of entities declared within a block: 1700 1701 @(default_calling_convention = "std") 1702 foreign kernel32 { 1703 @(link_name="GetLastError") get_last_error :: proc() -> i32 --- 1704 } 1705 1706 // Example using the link_prefix attribute 1707 @(default_calling_convention = "std") 1708 @(link_prefix = "Get") 1709 foreign kernel32 { 1710 LastError :: proc() -> i32 --- 1711 } 1712 } 1713 } 1714 1715 ranged_fields_for_array_compound_literals :: proc() { 1716 fmt.println("\n#ranged fields for array compound literals") 1717 { // Normal Array Literal 1718 foo := [?]int{1, 4, 9, 16} 1719 fmt.println(foo) 1720 } 1721 { // Indexed 1722 foo := [?]int{ 1723 3 = 16, 1724 1 = 4, 1725 2 = 9, 1726 0 = 1, 1727 } 1728 fmt.println(foo) 1729 } 1730 { // Ranges 1731 i := 2 1732 foo := [?]int { 1733 0 = 123, 1734 5..=9 = 54, 1735 10..<16 = i*3 + (i-1)*2, 1736 } 1737 #assert(len(foo) == 16) 1738 fmt.println(foo) // [123, 0, 0, 0, 0, 54, 54, 54, 54, 54, 8, 8, 8, 8, 8] 1739 } 1740 { // Slice and Dynamic Array support 1741 i := 2 1742 foo_slice := []int { 1743 0 = 123, 1744 5..=9 = 54, 1745 10..<16 = i*3 + (i-1)*2, 1746 } 1747 assert(len(foo_slice) == 16) 1748 fmt.println(foo_slice) // [123, 0, 0, 0, 0, 54, 54, 54, 54, 54, 8, 8, 8, 8, 8] 1749 1750 foo_dynamic_array := [dynamic]int { 1751 0 = 123, 1752 5..=9 = 54, 1753 10..<16 = i*3 + (i-1)*2, 1754 } 1755 assert(len(foo_dynamic_array) == 16) 1756 fmt.println(foo_dynamic_array) // [123, 0, 0, 0, 0, 54, 54, 54, 54, 54, 8, 8, 8, 8, 8] 1757 } 1758 } 1759 1760 deprecated_attribute :: proc() { 1761 @(deprecated="Use foo_v2 instead") 1762 foo_v1 :: proc(x: int) { 1763 fmt.println("foo_v1") 1764 } 1765 foo_v2 :: proc(x: int) { 1766 fmt.println("foo_v2") 1767 } 1768 1769 // NOTE: Uncomment to see the warning messages 1770 // foo_v1(1) 1771 } 1772 1773 range_statements_with_multiple_return_values :: proc() { 1774 fmt.println("\n#range statements with multiple return values") 1775 My_Iterator :: struct { 1776 index: int, 1777 data: []i32, 1778 } 1779 make_my_iterator :: proc(data: []i32) -> My_Iterator { 1780 return My_Iterator{data = data} 1781 } 1782 my_iterator :: proc(it: ^My_Iterator) -> (val: i32, idx: int, cond: bool) { 1783 if cond = it.index < len(it.data); cond { 1784 val = it.data[it.index] 1785 idx = it.index 1786 it.index += 1 1787 } 1788 return 1789 } 1790 1791 data := make([]i32, 6) 1792 for _, i in data { 1793 data[i] = i32(i*i) 1794 } 1795 1796 { // Manual Style 1797 it := make_my_iterator(data) 1798 for { 1799 val, _, cond := my_iterator(&it) 1800 if !cond { 1801 break 1802 } 1803 fmt.println(val) 1804 } 1805 } 1806 { // or_break 1807 it := make_my_iterator(data) 1808 loop: for { 1809 val, _ := my_iterator(&it) or_break loop 1810 fmt.println(val) 1811 } 1812 } 1813 { // first value 1814 it := make_my_iterator(data) 1815 for val in my_iterator(&it) { 1816 fmt.println(val) 1817 } 1818 } 1819 { // first and second value 1820 it := make_my_iterator(data) 1821 for val, idx in my_iterator(&it) { 1822 fmt.println(val, idx) 1823 } 1824 } 1825 } 1826 1827 1828 soa_struct_layout :: proc() { 1829 fmt.println("\n#SOA Struct Layout") 1830 1831 { 1832 Vector3 :: struct {x, y, z: f32} 1833 1834 N :: 2 1835 v_aos: [N]Vector3 1836 v_aos[0].x = 1 1837 v_aos[0].y = 4 1838 v_aos[0].z = 9 1839 1840 fmt.println(len(v_aos)) 1841 fmt.println(v_aos[0]) 1842 fmt.println(v_aos[0].x) 1843 fmt.println(&v_aos[0].x) 1844 1845 v_aos[1] = {0, 3, 4} 1846 v_aos[1].x = 2 1847 fmt.println(v_aos[1]) 1848 fmt.println(v_aos) 1849 1850 v_soa: #soa[N]Vector3 1851 1852 v_soa[0].x = 1 1853 v_soa[0].y = 4 1854 v_soa[0].z = 9 1855 1856 1857 // Same syntax as AOS and treat as if it was an array 1858 fmt.println(len(v_soa)) 1859 fmt.println(v_soa[0]) 1860 fmt.println(v_soa[0].x) 1861 fmt.println(&v_soa[0].x) 1862 v_soa[1] = {0, 3, 4} 1863 v_soa[1].x = 2 1864 fmt.println(v_soa[1]) 1865 1866 // Can use SOA syntax if necessary 1867 v_soa.x[0] = 1 1868 v_soa.y[0] = 4 1869 v_soa.z[0] = 9 1870 fmt.println(v_soa.x[0]) 1871 1872 // Same pointer addresses with both syntaxes 1873 assert(&v_soa[0].x == &v_soa.x[0]) 1874 1875 1876 // Same fmt printing 1877 fmt.println(v_aos) 1878 fmt.println(v_soa) 1879 } 1880 { 1881 // Works with arrays of length <= 4 which have the implicit fields xyzw/rgba 1882 Vector3 :: distinct [3]f32 1883 1884 N :: 2 1885 v_aos: [N]Vector3 1886 v_aos[0].x = 1 1887 v_aos[0].y = 4 1888 v_aos[0].z = 9 1889 1890 v_soa: #soa[N]Vector3 1891 1892 v_soa[0].x = 1 1893 v_soa[0].y = 4 1894 v_soa[0].z = 9 1895 } 1896 { 1897 // SOA Slices 1898 // Vector3 :: struct {x, y, z: f32} 1899 Vector3 :: struct {x: i8, y: i16, z: f32} 1900 1901 N :: 3 1902 v: #soa[N]Vector3 1903 v[0].x = 1 1904 v[0].y = 4 1905 v[0].z = 9 1906 1907 s: #soa[]Vector3 1908 s = v[:] 1909 assert(len(s) == N) 1910 fmt.println(s) 1911 fmt.println(s[0].x) 1912 1913 a := s[1:2] 1914 assert(len(a) == 1) 1915 fmt.println(a) 1916 1917 d: #soa[dynamic]Vector3 1918 1919 append_soa(&d, Vector3{1, 2, 3}, Vector3{4, 5, 9}, Vector3{-4, -4, 3}) 1920 fmt.println(d) 1921 fmt.println(len(d)) 1922 fmt.println(cap(d)) 1923 fmt.println(d[:]) 1924 } 1925 { // soa_zip and soa_unzip 1926 fmt.println("\nsoa_zip and soa_unzip") 1927 1928 x := []i32{1, 3, 9} 1929 y := []f32{2, 4, 16} 1930 z := []b32{true, false, true} 1931 1932 // produce an #soa slice the normal slices passed 1933 s := soa_zip(a=x, b=y, c=z) 1934 1935 // iterate over the #soa slice 1936 for v, i in s { 1937 fmt.println(v, i) // exactly the same as s[i] 1938 // NOTE: 'v' is NOT a temporary value but has a specialized addressing mode 1939 // which means that when accessing v.a etc, it does the correct transformation 1940 // internally: 1941 // s[i].a === s.a[i] 1942 fmt.println(v.a, v.b, v.c) 1943 } 1944 1945 // Recover the slices from the #soa slice 1946 a, b, c := soa_unzip(s) 1947 fmt.println(a, b, c) 1948 } 1949 } 1950 1951 constant_literal_expressions :: proc() { 1952 fmt.println("\n#constant literal expressions") 1953 1954 Bar :: struct {x, y: f32} 1955 Foo :: struct {a, b: int, using c: Bar} 1956 1957 FOO_CONST :: Foo{b = 2, a = 1, c = {3, 4}} 1958 1959 1960 fmt.println(FOO_CONST.a) 1961 fmt.println(FOO_CONST.b) 1962 fmt.println(FOO_CONST.c) 1963 fmt.println(FOO_CONST.c.x) 1964 fmt.println(FOO_CONST.c.y) 1965 fmt.println(FOO_CONST.x) // using works as expected 1966 fmt.println(FOO_CONST.y) 1967 1968 fmt.println("-------") 1969 1970 ARRAY_CONST :: [3]int{1 = 4, 2 = 9, 0 = 1} 1971 1972 fmt.println(ARRAY_CONST[0]) 1973 fmt.println(ARRAY_CONST[1]) 1974 fmt.println(ARRAY_CONST[2]) 1975 1976 fmt.println("-------") 1977 1978 FOO_ARRAY_DEFAULTS :: [3]Foo{{}, {}, {}} 1979 fmt.println(FOO_ARRAY_DEFAULTS[2].x) 1980 1981 fmt.println("-------") 1982 1983 Baz :: enum{A=5, B, C, D} 1984 ENUM_ARRAY_CONST :: [Baz]int{.A ..= .C = 1, .D = 16} 1985 1986 fmt.println(ENUM_ARRAY_CONST[.A]) 1987 fmt.println(ENUM_ARRAY_CONST[.B]) 1988 fmt.println(ENUM_ARRAY_CONST[.C]) 1989 fmt.println(ENUM_ARRAY_CONST[.D]) 1990 1991 fmt.println("-------") 1992 1993 Sparse_Baz :: enum{A=5, B, C, D=16} 1994 #assert(len(Sparse_Baz) < len(#sparse[Sparse_Baz]int)) 1995 SPARSE_ENUM_ARRAY_CONST :: #sparse[Sparse_Baz]int{.A ..= .C = 1, .D = 16} 1996 1997 fmt.println(SPARSE_ENUM_ARRAY_CONST[.A]) 1998 fmt.println(SPARSE_ENUM_ARRAY_CONST[.B]) 1999 fmt.println(SPARSE_ENUM_ARRAY_CONST[.C]) 2000 fmt.println(SPARSE_ENUM_ARRAY_CONST[.D]) 2001 2002 fmt.println("-------") 2003 2004 2005 STRING_CONST :: "Hellope!" 2006 2007 fmt.println(STRING_CONST[0]) 2008 fmt.println(STRING_CONST[2]) 2009 fmt.println(STRING_CONST[3]) 2010 2011 fmt.println(STRING_CONST[0:5]) 2012 fmt.println(STRING_CONST[3:][:4]) 2013 } 2014 2015 union_maybe :: proc() { 2016 fmt.println("\n#union based maybe") 2017 2018 // NOTE: This is already built-in, and this is just a reimplementation to explain the behaviour 2019 Maybe :: union($T: typeid) {T} 2020 2021 i: Maybe(u8) 2022 p: Maybe(^u8) // No tag is stored for pointers, nil is the sentinel value 2023 2024 // Tag size will be as small as needed for the number of variants 2025 #assert(size_of(i) == size_of(u8) + size_of(u8)) 2026 // No need to store a tag here, the `nil` state is shared with the variant's `nil` 2027 #assert(size_of(p) == size_of(^u8)) 2028 2029 i = 123 2030 x := i.? 2031 y, y_ok := p.? 2032 p = &x 2033 z, z_ok := p.? 2034 2035 fmt.println(i, p) 2036 fmt.println(x, &x) 2037 fmt.println(y, y_ok) 2038 fmt.println(z, z_ok) 2039 } 2040 2041 dummy_procedure :: proc() { 2042 fmt.println("dummy_procedure") 2043 } 2044 2045 explicit_context_definition :: proc "c" () { 2046 // Try commenting the following statement out below 2047 context = runtime.default_context() 2048 2049 fmt.println("\n#explicit context definition") 2050 dummy_procedure() 2051 } 2052 2053 or_else_operator :: proc() { 2054 fmt.println("\n#'or_else'") 2055 { 2056 m: map[string]int 2057 i: int 2058 ok: bool 2059 2060 if i, ok = m["hellope"]; !ok { 2061 i = 123 2062 } 2063 // The above can be mapped to 'or_else' 2064 i = m["hellope"] or_else 123 2065 2066 assert(i == 123) 2067 } 2068 { 2069 // 'or_else' can be used with type assertions too, as they 2070 // have optional ok semantics 2071 v: union{int, f64} 2072 i: int 2073 i = v.(int) or_else 123 2074 i = v.? or_else 123 // Type inference magic 2075 assert(i == 123) 2076 2077 m: Maybe(int) 2078 i = m.? or_else 456 2079 assert(i == 456) 2080 } 2081 } 2082 2083 or_return_operator :: proc() { 2084 fmt.println("\n#'or_return'") 2085 // The concept of 'or_return' will work by popping off the end value in a multiple 2086 // valued expression and checking whether it was not 'nil' or 'false', and if so, 2087 // set the end return value to value if possible. If the procedure only has one 2088 // return value, it will do a simple return. If the procedure had multiple return 2089 // values, 'or_return' will require that all parameters be named so that the end 2090 // value could be assigned to by name and then an empty return could be called. 2091 2092 Error :: enum { 2093 None, 2094 Something_Bad, 2095 Something_Worse, 2096 The_Worst, 2097 Your_Mum, 2098 } 2099 2100 caller_1 :: proc() -> Error { 2101 return .None 2102 } 2103 2104 caller_2 :: proc() -> (int, Error) { 2105 return 123, .None 2106 } 2107 caller_3 :: proc() -> (int, int, Error) { 2108 return 123, 345, .None 2109 } 2110 2111 foo_1 :: proc() -> Error { 2112 // This can be a common idiom in many code bases 2113 n0, err := caller_2() 2114 if err != nil { 2115 return err 2116 } 2117 2118 // The above idiom can be transformed into the following 2119 n1 := caller_2() or_return 2120 2121 2122 // And if the expression is 1-valued, it can be used like this 2123 caller_1() or_return 2124 // which is functionally equivalent to 2125 if err1 := caller_1(); err1 != nil { 2126 return err1 2127 } 2128 2129 // Multiple return values still work with 'or_return' as it only 2130 // pops off the end value in the multi-valued expression 2131 n0, n1 = caller_3() or_return 2132 2133 return .None 2134 } 2135 foo_2 :: proc() -> (n: int, err: Error) { 2136 // It is more common that your procedure returns multiple values 2137 // If 'or_return' is used within a procedure multiple parameters (2+), 2138 // then all the parameters must be named so that the remaining parameters 2139 // so that a bare 'return' statement can be used 2140 2141 // This can be a common idiom in many code bases 2142 x: int 2143 x, err = caller_2() 2144 if err != nil { 2145 return 2146 } 2147 2148 // The above idiom can be transformed into the following 2149 y := caller_2() or_return 2150 _ = y 2151 2152 // And if the expression is 1-valued, it can be used like this 2153 caller_1() or_return 2154 2155 // which is functionally equivalent to 2156 if err1 := caller_1(); err1 != nil { 2157 err = err1 2158 return 2159 } 2160 2161 // If using a non-bare 'return' statement is required, setting the return values 2162 // using the normal idiom is a better choice and clearer to read. 2163 if z, zerr := caller_2(); zerr != nil { 2164 return -345 * z, zerr 2165 } 2166 2167 defer if err != nil { 2168 fmt.println("Error in", #procedure, ":" , err) 2169 } 2170 2171 n = 123 2172 return 2173 } 2174 2175 foo_1() 2176 foo_2() 2177 } 2178 2179 2180 or_break_and_or_continue_operators :: proc() { 2181 fmt.println("\n#'or_break' and 'or_continue'") 2182 // The concept of 'or_break' and 'or_continue' is very similar to that of 'or_return'. 2183 // The difference is that unlike 'or_return', the value does not get returned from 2184 // the current procedure but rather discarded if it is 'false' or not 'nil', and then 2185 // the specified branch (i.e. break or continue). 2186 // The or branch expression can be labelled if a specific statement needs to be used. 2187 2188 Error :: enum { 2189 None, 2190 Something_Bad, 2191 Something_Worse, 2192 The_Worst, 2193 Your_Mum, 2194 } 2195 2196 caller_1 :: proc() -> Error { 2197 return .Something_Bad 2198 } 2199 2200 caller_2 :: proc() -> (int, Error) { 2201 return 123, .Something_Worse 2202 } 2203 caller_3 :: proc() -> (int, int, Error) { 2204 return 123, 345, .None 2205 } 2206 2207 for { // common approach 2208 err := caller_1() 2209 if err != nil { 2210 break 2211 } 2212 } 2213 for { // or_break approach 2214 caller_1() or_break 2215 } 2216 2217 for { // or_break approach with multiple values 2218 n := caller_2() or_break 2219 _ = n 2220 } 2221 2222 loop: for { // or_break approach with named label 2223 n := caller_2() or_break loop 2224 _ = n 2225 } 2226 2227 for { // or_continue 2228 x, y := caller_3() or_continue 2229 _, _ = x, y 2230 2231 break 2232 } 2233 2234 continue_loop: for { // or_continue with named label 2235 x, y := caller_3() or_continue continue_loop 2236 _, _ = x, y 2237 2238 break 2239 } 2240 2241 } 2242 2243 arbitrary_precision_mathematics :: proc() { 2244 fmt.println("\n# core:math/big") 2245 2246 print_bigint :: proc(name: string, a: ^big.Int, base := i8(10), print_name := true, newline := true, print_extra_info := true) { 2247 big.assert_if_nil(a) 2248 2249 as, err := big.itoa(a, base) 2250 defer delete(as) 2251 2252 cb := big.internal_count_bits(a) 2253 if print_name { 2254 fmt.print(name) 2255 } 2256 if err != nil { 2257 fmt.printf(" (Error: %v) ", err) 2258 } 2259 fmt.printf(as) 2260 if print_extra_info { 2261 fmt.printf(" (base: %v, bits: %v, digits: %v)", base, cb, a.used) 2262 } 2263 if newline { 2264 fmt.println() 2265 } 2266 } 2267 2268 a, b, c, d, e, f, res := &big.Int{}, &big.Int{}, &big.Int{}, &big.Int{}, &big.Int{}, &big.Int{}, &big.Int{} 2269 defer big.destroy(a, b, c, d, e, f, res) 2270 2271 // Set the context RNG to something that does not require 2272 // cryptographic entropy (not supported on all targets). 2273 context.random_generator = rand.xoshiro256_random_generator() 2274 2275 // How many bits should the random prime be? 2276 bits := 64 2277 // Number of Rabin-Miller trials, -1 for automatic. 2278 trials := -1 2279 2280 // Default prime generation flags 2281 flags := big.Primality_Flags{} 2282 2283 err := big.internal_random_prime(a, bits, trials, flags) 2284 if err != nil { 2285 fmt.printf("Error %v while generating random prime.\n", err) 2286 } else { 2287 print_bigint("Random Prime A: ", a, 10) 2288 fmt.printf("Random number iterations until prime found: %v\n", big.RANDOM_PRIME_ITERATIONS_USED) 2289 } 2290 2291 // If we want to pack this Int into a buffer of u32, how many do we need? 2292 count := big.internal_int_pack_count(a, u32) 2293 buf := make([]u32, count) 2294 defer delete(buf) 2295 2296 written: int 2297 written, err = big.internal_int_pack(a, buf) 2298 fmt.printf("\nPacked into u32 buf: %v | err: %v | written: %v\n", buf, err, written) 2299 2300 // If we want to pack this Int into a buffer of bytes of which only the bottom 6 bits are used, how many do we need? 2301 nails := 2 2302 2303 count = big.internal_int_pack_count(a, u8, nails) 2304 byte_buf := make([]u8, count) 2305 defer delete(byte_buf) 2306 2307 written, err = big.internal_int_pack(a, byte_buf, nails) 2308 fmt.printf("\nPacked into buf of 6-bit bytes: %v | err: %v | written: %v\n", byte_buf, err, written) 2309 2310 2311 2312 // Pick another random big Int, not necesssarily prime. 2313 err = big.random(b, 2048) 2314 print_bigint("\n2048 bit random number: ", b) 2315 2316 // Calculate GCD + LCM in one fell swoop 2317 big.gcd_lcm(c, d, a, b) 2318 2319 print_bigint("\nGCD of random prime A and random number B: ", c) 2320 print_bigint("\nLCM of random prime A and random number B (in base 36): ", d, 36) 2321 } 2322 2323 matrix_type :: proc() { 2324 fmt.println("\n# matrix type") 2325 // A matrix is a mathematical type built into Odin. It is a regular array of numbers, 2326 // arranged in rows and columns 2327 2328 { 2329 // The following represents a matrix that has 2 rows and 3 columns 2330 m: matrix[2, 3]f32 2331 2332 m = matrix[2, 3]f32{ 2333 1, 9, -13, 2334 20, 5, -6, 2335 } 2336 2337 // Element types of integers, float, and complex numbers are supported by matrices. 2338 // There is no support for booleans, quaternions, or any compound type. 2339 2340 // Indexing a matrix can be used with the matrix indexing syntax 2341 // This mirrors other type usages: type on the left, usage on the right 2342 2343 elem := m[1, 2] // row 1, column 2 2344 assert(elem == -6) 2345 2346 2347 // Scalars act as if they are scaled identity matrices 2348 // and can be assigned to matrices as them 2349 b := matrix[2, 2]f32{} 2350 f := f32(3) 2351 b = f 2352 2353 fmt.println("b", b) 2354 fmt.println("b == f", b == f) 2355 2356 } 2357 2358 { // Matrices support multiplication between matrices 2359 a := matrix[2, 3]f32{ 2360 2, 3, 1, 2361 4, 5, 0, 2362 } 2363 2364 b := matrix[3, 2]f32{ 2365 1, 2, 2366 3, 4, 2367 5, 6, 2368 } 2369 2370 fmt.println("a", a) 2371 fmt.println("b", b) 2372 2373 c := a * b 2374 #assert(type_of(c) == matrix[2, 2]f32) 2375 fmt.println("c = a * b", c) 2376 } 2377 2378 { // Matrices support multiplication between matrices and arrays 2379 m := matrix[4, 4]f32{ 2380 1, 2, 3, 4, 2381 5, 5, 4, 2, 2382 0, 1, 3, 0, 2383 0, 1, 4, 1, 2384 } 2385 2386 v := [4]f32{1, 5, 4, 3} 2387 2388 // treating 'v' as a column vector 2389 fmt.println("m * v", m * v) 2390 2391 // treating 'v' as a row vector 2392 fmt.println("v * m", v * m) 2393 2394 // Support with non-square matrices 2395 s := matrix[2, 4]f32{ // [4][2]f32 2396 2, 4, 3, 1, 2397 7, 8, 6, 5, 2398 } 2399 2400 w := [2]f32{1, 2} 2401 r: [4]f32 = w * s 2402 fmt.println("r", r) 2403 } 2404 2405 { // Component-wise operations 2406 // if the element type supports it 2407 // Not support for '/', '%', or '%%' operations 2408 2409 a := matrix[2, 2]i32{ 2410 1, 2, 2411 3, 4, 2412 } 2413 2414 b := matrix[2, 2]i32{ 2415 -5, 1, 2416 9, -7, 2417 } 2418 2419 c0 := a + b 2420 c1 := a - b 2421 c2 := a & b 2422 c3 := a | b 2423 c4 := a ~ b 2424 c5 := a &~ b 2425 2426 // component-wise multiplication 2427 // since a * b would be a standard matrix multiplication 2428 c6 := intrinsics.hadamard_product(a, b) 2429 2430 2431 fmt.println("a + b", c0) 2432 fmt.println("a - b", c1) 2433 fmt.println("a & b", c2) 2434 fmt.println("a | b", c3) 2435 fmt.println("a ~ b", c4) 2436 fmt.println("a &~ b", c5) 2437 fmt.println("hadamard_product(a, b)", c6) 2438 } 2439 2440 { // Submatrix casting square matrices 2441 // Casting a square matrix to another square matrix with same element type 2442 // is supported. 2443 // If the cast is to a smaller matrix type, the top-left submatrix is taken. 2444 // If the cast is to a larger matrix type, the matrix is extended with zeros 2445 // everywhere and ones in the diagonal for the unfilled elements of the 2446 // extended matrix. 2447 2448 mat2 :: distinct matrix[2, 2]f32 2449 mat4 :: distinct matrix[4, 4]f32 2450 2451 m2 := mat2{ 2452 1, 3, 2453 2, 4, 2454 } 2455 2456 m4 := mat4(m2) 2457 assert(m4[2, 2] == 1) 2458 assert(m4[3, 3] == 1) 2459 fmt.printf("m2 %#v\n", m2) 2460 fmt.println("m4", m4) 2461 fmt.println("mat2(m4)", mat2(m4)) 2462 assert(mat2(m4) == m2) 2463 2464 b4 := mat4{ 2465 1, 2, 0, 0, 2466 3, 4, 0, 0, 2467 5, 0, 6, 0, 2468 0, 7, 0, 8, 2469 } 2470 fmt.println("b4", intrinsics.matrix_flatten(b4)) 2471 } 2472 2473 { // Casting non-square matrices 2474 // Casting a matrix to another matrix is allowed as long as they share 2475 // the same element type and the number of elements (rows*columns). 2476 // Matrices in Odin are stored in column-major order, which means 2477 // the casts will preserve this element order. 2478 2479 mat2x4 :: distinct matrix[2, 4]f32 2480 mat4x2 :: distinct matrix[4, 2]f32 2481 2482 x := mat2x4{ 2483 1, 3, 5, 7, 2484 2, 4, 6, 8, 2485 } 2486 2487 y := mat4x2(x) 2488 fmt.println("x", x) 2489 fmt.println("y", y) 2490 } 2491 2492 // TECHNICAL INFORMATION: the internal representation of a matrix in Odin is stored 2493 // in column-major format 2494 // e.g. matrix[2, 3]f32 is internally [3][2]f32 (with different a alignment requirement) 2495 // Column-major is used in order to utilize (SIMD) vector instructions effectively on 2496 // modern hardware, if possible. 2497 // 2498 // Unlike normal arrays, matrices try to maximize alignment to allow for the (SIMD) vectorization 2499 // properties whilst keeping zero padding (either between columns or at the end of the type). 2500 // 2501 // Zero padding is a compromise for use with third-party libraries, instead of optimizing for performance. 2502 // Padding between columns was not taken even if that would have allowed each column to be loaded 2503 // individually into a SIMD register with the correct alignment properties. 2504 // 2505 // Currently, matrices are limited to a maximum of 16 elements (rows*columns), and a minimum of 1 element. 2506 // This is because matrices are stored as values (not a reference type), and thus operations on them will 2507 // be stored on the stack. Restricting the maximum element count minimizing the possibility of stack overflows. 2508 2509 // 'intrinsics' Procedures (Compiler Level) 2510 // transpose(m) 2511 // transposes a matrix 2512 // outer_product(a, b) 2513 // takes two array-like data types and returns the outer product 2514 // of the values in a matrix 2515 // hadamard_product(a, b) 2516 // component-wise multiplication of two matrices of the same type 2517 // matrix_flatten(m) 2518 // converts the matrix into a flatten array of elements 2519 // in column-major order 2520 // Example: 2521 // m := matrix[2, 2]f32{ 2522 // x0, x1, 2523 // y0, y1, 2524 // } 2525 // array: [4]f32 = matrix_flatten(m) 2526 // assert(array == {x0, y0, x1, y1}) 2527 // conj(x) 2528 // conjugates the elements of a matrix for complex element types only 2529 2530 // Procedures in "core:math/linalg" and related (Runtime Level) (all square matrix procedures) 2531 // determinant(m) 2532 // adjugate(m) 2533 // inverse(m) 2534 // inverse_transpose(m) 2535 // hermitian_adjoint(m) 2536 // trace(m) 2537 // matrix_minor(m) 2538 } 2539 2540 bit_field_type :: proc() { 2541 fmt.println("\n# bit_field type") 2542 // A `bit_field` is a record type in Odin that is akin to a bit-packed struct. 2543 // IMPORTNAT NOTE: `bit_field` is NOT equivalent to `bit_set` as it has different sematics and use cases. 2544 2545 { 2546 // `bit_field` fields are accessed by using a dot: 2547 Foo :: bit_field u16 { // backing type must be an integer or array of integers 2548 x: i32 | 3, // signed integers will be signed extended on use 2549 y: u16 | 2 + 3, // general expressions 2550 z: My_Enum | SOME_CONSTANT, // ability to define the bit-width elsewhere 2551 w: bool | 2 when SOME_CONSTANT > 10 else 1, 2552 } 2553 2554 v := Foo{} 2555 v.x = 3 // truncates the value to fit into 3 bits 2556 fmt.println(v.x) // accessing will convert `v.x` to an `i32` and do an appropriate sign extension 2557 2558 2559 My_Enum :: enum u8 {A, B, C, D} 2560 SOME_CONSTANT :: 7 2561 } 2562 2563 { 2564 // A `bit_field` is different from a struct in that you must specify the backing type. 2565 // This backing type must be an integer or a fixed-length array of integers. 2566 // This is useful if there needs to be a specific alignment or access pattern for the record. 2567 2568 Bar :: bit_field u32 {} 2569 Baz :: bit_field [4]u8 {} 2570 } 2571 2572 // IMPORTANT NOTES: 2573 // * If _all_ of the fields in a bit_field are 1-bit in size and they are all booleans, 2574 // please consider using a `bit_set` instead. 2575 // * Odin's `bit_field` and C's bit-fields might not be compatible 2576 // * Odin's `bit_field`s have a well defined layout (Least-Significant-Bit) 2577 // * C's bit-fields on `struct`s are undefined and are not portable across targets and compilers 2578 // * A `bit_field`'s field type can only be one of the following: 2579 // * Integer 2580 // * Boolean 2581 // * Enum 2582 } 2583 2584 main :: proc() { 2585 /* 2586 For More Odin Examples - https://github.com/odin-lang/examples 2587 This repository contains examples of how certain things can be accomplished 2588 in idiomatic Odin, allowing you learn its semantics, as well as how to use 2589 parts of the core and vendor package collections. 2590 */ 2591 2592 when true { 2593 the_basics() 2594 control_flow() 2595 named_proc_return_parameters() 2596 variadic_procedures() 2597 explicit_procedure_overloading() 2598 struct_type() 2599 union_type() 2600 using_statement() 2601 implicit_context_system() 2602 parametric_polymorphism() 2603 threading_example() 2604 array_programming() 2605 map_type() 2606 implicit_selector_expression() 2607 partial_switch() 2608 cstring_example() 2609 bit_set_type() 2610 deferred_procedure_associations() 2611 reflection() 2612 quaternions() 2613 unroll_for_statement() 2614 where_clauses() 2615 foreign_system() 2616 ranged_fields_for_array_compound_literals() 2617 deprecated_attribute() 2618 range_statements_with_multiple_return_values() 2619 soa_struct_layout() 2620 constant_literal_expressions() 2621 union_maybe() 2622 explicit_context_definition() 2623 or_else_operator() 2624 or_return_operator() 2625 or_break_and_or_continue_operators() 2626 arbitrary_precision_mathematics() 2627 matrix_type() 2628 bit_field_type() 2629 } 2630 } 2631 // END_INDENT