demo.odin 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  1. package main
  2. import "core:fmt"
  3. import "core:strconv"
  4. import "core:mem"
  5. import "core:bits"
  6. import "core:hash"
  7. import "core:math"
  8. import "core:math/rand"
  9. import "core:os"
  10. import "core:sort"
  11. import "core:strings"
  12. import "core:types"
  13. import "core:unicode/utf16"
  14. import "core:unicode/utf8"
  15. import "core:c"
  16. import "core:runtime"
  17. when os.OS == "windows" {
  18. import "core:atomics"
  19. import "core:sync"
  20. import "core:thread"
  21. import "core:sys/win32"
  22. }
  23. @(link_name="general_stuff")
  24. general_stuff :: proc() {
  25. fmt.println("# general_stuff");
  26. { // `do` for inline statements rather than block
  27. foo :: proc() do fmt.println("Foo!");
  28. if false do foo();
  29. for false do foo();
  30. when false do foo();
  31. if false do foo();
  32. else do foo();
  33. }
  34. { // Removal of `++` and `--` (again)
  35. x: int;
  36. x += 1;
  37. x -= 1;
  38. }
  39. { // Casting syntaxes
  40. i := i32(137);
  41. ptr := &i;
  42. _ = (^f32)(ptr);
  43. // ^f32(ptr) == ^(f32(ptr))
  44. _ = cast(^f32)ptr;
  45. _ = (^f32)(ptr)^;
  46. _ = (cast(^f32)ptr)^;
  47. // Questions: Should there be two ways to do it?
  48. }
  49. /*
  50. * Remove *_val_of built-in procedures
  51. * size_of, align_of, offset_of
  52. * type_of, type_info_of
  53. */
  54. { // `expand_to_tuple` built-in procedure
  55. Foo :: struct {
  56. x: int,
  57. b: bool,
  58. }
  59. f := Foo{137, true};
  60. x, b := expand_to_tuple(f);
  61. fmt.println(f);
  62. fmt.println(x, b);
  63. fmt.println(expand_to_tuple(f));
  64. }
  65. {
  66. // .. open range
  67. for in 0..2 {} // 0, 1, 2
  68. }
  69. { // Multiple sized booleans
  70. x0: bool; // default
  71. x1: b8 = true;
  72. x2: b16 = false;
  73. x3: b32 = true;
  74. x4: b64 = false;
  75. fmt.printf("x0: %T = %v;\n", x0, x0);
  76. fmt.printf("x1: %T = %v;\n", x1, x1);
  77. fmt.printf("x2: %T = %v;\n", x2, x2);
  78. fmt.printf("x3: %T = %v;\n", x3, x3);
  79. fmt.printf("x4: %T = %v;\n", x4, x4);
  80. // Having specific sized booleans is very useful when dealing with foreign code
  81. // and to enforce specific alignment for a boolean, especially within a struct
  82. }
  83. { // `distinct` types
  84. // Originally, all type declarations would create a distinct type unless #type_alias was present.
  85. // Now the behaviour has been reversed. All type declarations create a type alias unless `distinct` is present.
  86. // If the type expression is `struct`, `union`, `enum`, `proc`, or `bit_field`, the types will always been distinct.
  87. Int32 :: i32;
  88. #assert(Int32 == i32);
  89. My_Int32 :: distinct i32;
  90. #assert(My_Int32 != i32);
  91. My_Struct :: struct{x: int};
  92. #assert(My_Struct != struct{x: int});
  93. }
  94. }
  95. union_type :: proc() {
  96. fmt.println("\n# union_type");
  97. {
  98. val: union{int, bool};
  99. val = 137;
  100. if i, ok := val.(int); ok {
  101. fmt.println(i);
  102. }
  103. val = true;
  104. fmt.println(val);
  105. val = nil;
  106. switch v in val {
  107. case int: fmt.println("int", v);
  108. case bool: fmt.println("bool", v);
  109. case: fmt.println("nil");
  110. }
  111. }
  112. {
  113. // There is a duality between `any` and `union`
  114. // An `any` has a pointer to the data and allows for any type (open)
  115. // A `union` has as binary blob to store the data and allows only certain types (closed)
  116. // The following code is with `any` but has the same syntax
  117. val: any;
  118. val = 137;
  119. if i, ok := val.(int); ok {
  120. fmt.println(i);
  121. }
  122. val = true;
  123. fmt.println(val);
  124. val = nil;
  125. switch v in val {
  126. case int: fmt.println("int", v);
  127. case bool: fmt.println("bool", v);
  128. case: fmt.println("nil");
  129. }
  130. }
  131. Vector3 :: struct {x, y, z: f32};
  132. Quaternion :: struct {x, y, z, w: f32};
  133. // More realistic examples
  134. {
  135. // NOTE(bill): For the above basic examples, you may not have any
  136. // particular use for it. However, my main use for them is not for these
  137. // simple cases. My main use is for hierarchical types. Many prefer
  138. // subtyping, embedding the base data into the derived types. Below is
  139. // an example of this for a basic game Entity.
  140. Entity :: struct {
  141. id: u64,
  142. name: string,
  143. position: Vector3,
  144. orientation: Quaternion,
  145. derived: any,
  146. }
  147. Frog :: struct {
  148. using entity: Entity,
  149. jump_height: f32,
  150. }
  151. Monster :: struct {
  152. using entity: Entity,
  153. is_robot: bool,
  154. is_zombie: bool,
  155. }
  156. // See `parametric_polymorphism` procedure for details
  157. new_entity :: proc(T: type) -> ^Entity {
  158. t := new(T);
  159. t.derived = t^;
  160. return t;
  161. }
  162. entity := new_entity(Monster);
  163. switch e in entity.derived {
  164. case Frog:
  165. fmt.println("Ribbit");
  166. case Monster:
  167. if e.is_robot do fmt.println("Robotic");
  168. if e.is_zombie do fmt.println("Grrrr!");
  169. }
  170. }
  171. {
  172. // NOTE(bill): A union can be used to achieve something similar. Instead
  173. // of embedding the base data into the derived types, the derived data
  174. // in embedded into the base type. Below is the same example of the
  175. // basic game Entity but using an union.
  176. Entity :: struct {
  177. id: u64,
  178. name: string,
  179. position: Vector3,
  180. orientation: Quaternion,
  181. derived: union {Frog, Monster},
  182. }
  183. Frog :: struct {
  184. using entity: ^Entity,
  185. jump_height: f32,
  186. }
  187. Monster :: struct {
  188. using entity: ^Entity,
  189. is_robot: bool,
  190. is_zombie: bool,
  191. }
  192. // See `parametric_polymorphism` procedure for details
  193. new_entity :: proc(T: type) -> ^Entity {
  194. t := new(Entity);
  195. t.derived = T{entity = t};
  196. return t;
  197. }
  198. entity := new_entity(Monster);
  199. switch e in entity.derived {
  200. case Frog:
  201. fmt.println("Ribbit");
  202. case Monster:
  203. if e.is_robot do fmt.println("Robotic");
  204. if e.is_zombie do fmt.println("Grrrr!");
  205. }
  206. // NOTE(bill): As you can see, the usage code has not changed, only its
  207. // memory layout. Both approaches have their own advantages but they can
  208. // be used together to achieve different results. The subtyping approach
  209. // can allow for a greater control of the memory layout and memory
  210. // allocation, e.g. storing the derivatives together. However, this is
  211. // also its disadvantage. You must either preallocate arrays for each
  212. // derivative separation (which can be easily missed) or preallocate a
  213. // bunch of "raw" memory; determining the maximum size of the derived
  214. // types would require the aid of metaprogramming. Unions solve this
  215. // particular problem as the data is stored with the base data.
  216. // Therefore, it is possible to preallocate, e.g. [100]Entity.
  217. // It should be noted that the union approach can have the same memory
  218. // layout as the any and with the same type restrictions by using a
  219. // pointer type for the derivatives.
  220. /*
  221. Entity :: struct {
  222. ..
  223. derived: union{^Frog, ^Monster},
  224. }
  225. Frog :: struct {
  226. using entity: Entity,
  227. ..
  228. }
  229. Monster :: struct {
  230. using entity: Entity,
  231. ..
  232. }
  233. new_entity :: proc(T: type) -> ^Entity {
  234. t := new(T);
  235. t.derived = t;
  236. return t;
  237. }
  238. */
  239. }
  240. }
  241. parametric_polymorphism :: proc() {
  242. fmt.println("# parametric_polymorphism");
  243. print_value :: proc(value: $T) {
  244. fmt.printf("print_value: %T %v\n", value, value);
  245. }
  246. v1: int = 1;
  247. v2: f32 = 2.1;
  248. v3: f64 = 3.14;
  249. v4: string = "message";
  250. print_value(v1);
  251. print_value(v2);
  252. print_value(v3);
  253. print_value(v4);
  254. fmt.println();
  255. add :: proc(p, q: $T) -> T {
  256. x: T = p + q;
  257. return x;
  258. }
  259. a := add(3, 4);
  260. fmt.printf("a: %T = %v\n", a, a);
  261. b := add(3.2, 4.3);
  262. fmt.printf("b: %T = %v\n", b, b);
  263. // This is how `new` is implemented
  264. alloc_type :: proc(T: type) -> ^T {
  265. t := cast(^T)alloc(size_of(T), align_of(T));
  266. t^ = T{}; // Use default initialization value
  267. return t;
  268. }
  269. copy_slice :: proc(dst, src: []$T) -> int {
  270. n := min(len(dst), len(src));
  271. if n > 0 {
  272. mem.copy(&dst[0], &src[0], n*size_of(T));
  273. }
  274. return n;
  275. }
  276. double_params :: proc(a: $A, b: $B) -> A {
  277. return a + A(b);
  278. }
  279. fmt.println(double_params(12, 1.345));
  280. { // Polymorphic Types and Type Specialization
  281. Table_Slot :: struct(Key, Value: type) {
  282. occupied: bool,
  283. hash: u32,
  284. key: Key,
  285. value: Value,
  286. }
  287. TABLE_SIZE_MIN :: 32;
  288. Table :: struct(Key, Value: type) {
  289. count: int,
  290. allocator: mem.Allocator,
  291. slots: []Table_Slot(Key, Value),
  292. }
  293. // Only allow types that are specializations of a (polymorphic) slice
  294. make_slice :: proc(T: type/[]$E, len: int) -> T {
  295. return make(T, len);
  296. }
  297. // Only allow types that are specializations of `Table`
  298. allocate :: proc(table: ^$T/Table, capacity: int) {
  299. c := context;
  300. if table.allocator.procedure != nil do c.allocator = table.allocator;
  301. context = c;
  302. table.slots = make_slice(type_of(table.slots), max(capacity, TABLE_SIZE_MIN));
  303. }
  304. expand :: proc(table: ^$T/Table) {
  305. c := context;
  306. if table.allocator.procedure != nil do c.allocator = table.allocator;
  307. context = c;
  308. old_slots := table.slots;
  309. defer delete(old_slots);
  310. cap := max(2*len(table.slots), TABLE_SIZE_MIN);
  311. allocate(table, cap);
  312. for s in old_slots do if s.occupied {
  313. put(table, s.key, s.value);
  314. }
  315. }
  316. // Polymorphic determination of a polymorphic struct
  317. // put :: proc(table: ^$T/Table, key: T.Key, value: T.Value) {
  318. put :: proc(table: ^Table($Key, $Value), key: Key, value: Value) {
  319. hash := get_hash(key); // Ad-hoc method which would fail in a different scope
  320. index := find_index(table, key, hash);
  321. if index < 0 {
  322. if f64(table.count) >= 0.75*f64(len(table.slots)) {
  323. expand(table);
  324. }
  325. assert(table.count <= len(table.slots));
  326. hash := get_hash(key);
  327. index = int(hash % u32(len(table.slots)));
  328. for table.slots[index].occupied {
  329. if index += 1; index >= len(table.slots) {
  330. index = 0;
  331. }
  332. }
  333. table.count += 1;
  334. }
  335. slot := &table.slots[index];
  336. slot.occupied = true;
  337. slot.hash = hash;
  338. slot.key = key;
  339. slot.value = value;
  340. }
  341. // find :: proc(table: ^$T/Table, key: T.Key) -> (T.Value, bool) {
  342. find :: proc(table: ^Table($Key, $Value), key: Key) -> (Value, bool) {
  343. hash := get_hash(key);
  344. index := find_index(table, key, hash);
  345. if index < 0 {
  346. return Value{}, false;
  347. }
  348. return table.slots[index].value, true;
  349. }
  350. find_index :: proc(table: ^Table($Key, $Value), key: Key, hash: u32) -> int {
  351. if len(table.slots) <= 0 do return -1;
  352. index := int(hash % u32(len(table.slots)));
  353. for table.slots[index].occupied {
  354. if table.slots[index].hash == hash {
  355. if table.slots[index].key == key {
  356. return index;
  357. }
  358. }
  359. if index += 1; index >= len(table.slots) {
  360. index = 0;
  361. }
  362. }
  363. return -1;
  364. }
  365. get_hash :: proc(s: string) -> u32 { // fnv32a
  366. h: u32 = 0x811c9dc5;
  367. for i in 0..len(s)-1 {
  368. h = (h ~ u32(s[i])) * 0x01000193;
  369. }
  370. return h;
  371. }
  372. table: Table(string, int);
  373. for i in 0..36 do put(&table, "Hellope", i);
  374. for i in 0..42 do put(&table, "World!", i);
  375. found, _ := find(&table, "Hellope");
  376. fmt.printf("`found` is %v\n", found);
  377. found, _ = find(&table, "World!");
  378. fmt.printf("`found` is %v\n", found);
  379. // I would not personally design a hash table like this in production
  380. // but this is a nice basic example
  381. // A better approach would either use a `u64` or equivalent for the key
  382. // and let the user specify the hashing function or make the user store
  383. // the hashing procedure with the table
  384. }
  385. }
  386. prefix_table := [?]string{
  387. "White",
  388. "Red",
  389. "Green",
  390. "Blue",
  391. "Octarine",
  392. "Black",
  393. };
  394. threading_example :: proc() {
  395. when os.OS == "windows" {
  396. fmt.println("# threading_example");
  397. unordered_remove :: proc(array: ^[dynamic]$T, index: int, loc := #caller_location) {
  398. runtime.bounds_check_error_loc(loc, index, len(array));
  399. array[index] = array[len(array)-1];
  400. pop(array);
  401. }
  402. ordered_remove :: proc(array: ^[dynamic]$T, index: int, loc := #caller_location) {
  403. runtime.bounds_check_error_loc(loc, index, len(array));
  404. copy(array[index:], array[index+1:]);
  405. pop(array);
  406. }
  407. worker_proc :: proc(t: ^thread.Thread) -> int {
  408. for iteration in 1..5 {
  409. fmt.printf("Thread %d is on iteration %d\n", t.user_index, iteration);
  410. fmt.printf("`%s`: iteration %d\n", prefix_table[t.user_index], iteration);
  411. // win32.sleep(1);
  412. }
  413. return 0;
  414. }
  415. threads := make([dynamic]^thread.Thread, 0, len(prefix_table));
  416. defer delete(threads);
  417. for in prefix_table {
  418. if t := thread.create(worker_proc); t != nil {
  419. t.init_context = context;
  420. t.use_init_context = true;
  421. t.user_index = len(threads);
  422. append(&threads, t);
  423. thread.start(t);
  424. }
  425. }
  426. for len(threads) > 0 {
  427. for i := 0; i < len(threads); /**/ {
  428. if t := threads[i]; thread.is_done(t) {
  429. fmt.printf("Thread %d is done\n", t.user_index);
  430. thread.destroy(t);
  431. ordered_remove(&threads, i);
  432. } else {
  433. i += 1;
  434. }
  435. }
  436. }
  437. }
  438. }
  439. array_programming :: proc() {
  440. fmt.println("# array_programming");
  441. {
  442. a := [3]f32{1, 2, 3};
  443. b := [3]f32{5, 6, 7};
  444. c := a * b;
  445. d := a + b;
  446. e := 1 + (c - d) / 2;
  447. fmt.printf("%.1f\n", e); // [0.5, 3.0, 6.5]
  448. }
  449. {
  450. a := [3]f32{1, 2, 3};
  451. b := swizzle(a, 2, 1, 0);
  452. assert(b == [3]f32{3, 2, 1});
  453. c := swizzle(a, 0, 0);
  454. assert(c == [2]f32{1, 1});
  455. assert(c == 1);
  456. }
  457. {
  458. Vector3 :: distinct [3]f32;
  459. a := Vector3{1, 2, 3};
  460. b := Vector3{5, 6, 7};
  461. c := (a * b)/2 + 1;
  462. d := c.x + c.y + c.z;
  463. fmt.printf("%.1f\n", d); // 22.0
  464. cross :: proc(a, b: Vector3) -> Vector3 {
  465. i := swizzle(a, 1, 2, 0) * swizzle(b, 2, 0, 1);
  466. j := swizzle(a, 2, 0, 1) * swizzle(b, 1, 2, 0);
  467. return i - j;
  468. }
  469. blah :: proc(a: Vector3) -> f32 {
  470. return a.x + a.y + a.z;
  471. }
  472. x := cross(a, b);
  473. fmt.println(x);
  474. fmt.println(blah(x));
  475. }
  476. }
  477. named_proc_return_parameters :: proc() {
  478. fmt.println("# named proc return parameters");
  479. foo0 :: proc() -> int {
  480. return 123;
  481. }
  482. foo1 :: proc() -> (a: int) {
  483. a = 123;
  484. return;
  485. }
  486. foo2 :: proc() -> (a, b: int) {
  487. // Named return values act like variables within the scope
  488. a = 321;
  489. b = 567;
  490. return b, a;
  491. }
  492. fmt.println("foo0 =", foo0()); // 123
  493. fmt.println("foo1 =", foo1()); // 123
  494. fmt.println("foo2 =", foo2()); // 567 321
  495. }
  496. using_enum :: proc() {
  497. fmt.println("# using enum");
  498. using Foo :: enum {A, B, C};
  499. f0 := A;
  500. f1 := B;
  501. f2 := C;
  502. fmt.println(f0, f1, f2);
  503. fmt.println(len(Foo));
  504. // Non-comparsion operations are not allowed with enum
  505. // You must convert to an integer if you want to do this
  506. // x := f0 + f1;
  507. y := int(f0) + int(f1);
  508. }
  509. explicit_procedure_overloading :: proc() {
  510. fmt.println("# explicit procedure overloading");
  511. add_ints :: proc(a, b: int) -> int {
  512. x := a + b;
  513. fmt.println("add_ints", x);
  514. return x;
  515. }
  516. add_floats :: proc(a, b: f32) -> f32 {
  517. x := a + b;
  518. fmt.println("add_floats", x);
  519. return x;
  520. }
  521. add_numbers :: proc(a: int, b: f32, c: u8) -> int {
  522. x := int(a) + int(b) + int(c);
  523. fmt.println("add_numbers", x);
  524. return x;
  525. }
  526. add :: proc[add_ints, add_floats, add_numbers];
  527. add(int(1), int(2));
  528. add(f32(1), f32(2));
  529. add(int(1), f32(2), u8(3));
  530. add(1, 2); // untyped ints coerce to int tighter than f32
  531. add(1.0, 2.0); // untyped floats coerce to f32 tighter than int
  532. add(1, 2, 3); // three parameters
  533. // Ambiguous answers
  534. // add(1.0, 2);
  535. // add(1, 2.0);
  536. }
  537. complete_switch :: proc() {
  538. fmt.println("# complete_switch");
  539. { // enum
  540. using Foo :: enum {
  541. A,
  542. B,
  543. C,
  544. D,
  545. }
  546. b := Foo.B;
  547. f := Foo.A;
  548. #complete switch f {
  549. case A: fmt.println("A");
  550. case B: fmt.println("B");
  551. case C: fmt.println("C");
  552. case D: fmt.println("D");
  553. case: fmt.println("?");
  554. }
  555. }
  556. { // union
  557. Foo :: union {int, bool};
  558. f: Foo = 123;
  559. #complete switch in f {
  560. case int: fmt.println("int");
  561. case bool: fmt.println("bool");
  562. case:
  563. }
  564. }
  565. }
  566. cstring_example :: proc() {
  567. W :: "Hellope";
  568. X :: cstring(W);
  569. Y :: string(X);
  570. w := W;
  571. x: cstring = X;
  572. y: string = Y;
  573. z := string(x);
  574. fmt.println(x, y, z);
  575. fmt.println(len(x), len(y), len(z));
  576. fmt.println(len(W), len(X), len(Y));
  577. // IMPORTANT NOTE for cstring variables
  578. // len(cstring) is O(N)
  579. // cast(cstring)string is O(N)
  580. }
  581. deprecated_attribute :: proc() {
  582. @(deprecated="Use foo_v2 instead")
  583. foo_v1 :: proc(x: int) {
  584. fmt.println("foo_v1");
  585. }
  586. foo_v2 :: proc(x: int) {
  587. fmt.println("foo_v2");
  588. }
  589. // NOTE: Uncomment to see the warning messages
  590. // foo_v1(1);
  591. }
  592. bit_set_type :: proc() {
  593. {
  594. using Day :: enum {
  595. Sunday,
  596. Monday,
  597. Tuesday,
  598. Wednesday,
  599. Thursday,
  600. Friday,
  601. Saturday,
  602. }
  603. Days :: distinct bit_set[Day];
  604. WEEKEND :: Days{Sunday, Saturday};
  605. d: Days;
  606. d = {Sunday, Monday};
  607. x := Tuesday;
  608. e := d | WEEKEND;
  609. e |= {Monday};
  610. fmt.println(d, e);
  611. ok := Saturday in e; // `in` is only allowed for `map` and `bit_set` types
  612. fmt.println(ok);
  613. if Saturday in e {
  614. fmt.println("Saturday in", e);
  615. }
  616. X :: Saturday in WEEKEND; // Constant evaluation
  617. fmt.println(X);
  618. }
  619. {
  620. x: bit_set['A'..'Z'];
  621. assert(size_of(x) == size_of(u32));
  622. y: bit_set[0..8; u16];
  623. fmt.println(typeid_of(type_of(x))); // bit_set[A..Z]
  624. fmt.println(typeid_of(type_of(y))); // bit_set[0..8]
  625. incl(&x, 'F');
  626. assert('F' in x);
  627. excl(&x, 'F');
  628. assert(!('F' in x));
  629. y |= {1, 4, 2};
  630. assert(2 in y);
  631. }
  632. }
  633. main :: proc() {
  634. when false {
  635. general_stuff();
  636. union_type();
  637. parametric_polymorphism();
  638. threading_example();
  639. array_programming();
  640. named_proc_return_parameters();
  641. using_enum();
  642. explicit_procedure_overloading();
  643. complete_switch();
  644. cstring_example();
  645. deprecated_attribute();
  646. bit_set_type();
  647. }
  648. }