demo.odin 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  1. package main
  2. import "core:fmt"
  3. import "core:mem"
  4. import "core:os"
  5. import "core:reflect"
  6. import "intrinsics"
  7. when os.OS == "windows" {
  8. import "core:thread"
  9. }
  10. /*
  11. The Odin programming language is fast, concise, readable, pragmatic and open sourced. It is designed with the intent of replacing C with the following goals:
  12. * simplicity
  13. * high performance
  14. * built for modern systems
  15. * joy of programming
  16. # Installing Odin
  17. Getting Started - https://odin-lang.org/docs/install/
  18. Instructions for downloading and install the Odin compiler and libraries.
  19. # Learning Odin
  20. Overview of Odin - https://odin-lang.org/docs/overview/
  21. An overview of the Odin programming language.
  22. Frequently Asked Questions (FAQ) - https://odin-lang.org/docs/faq/
  23. Answers to common questions about Odin.
  24. */
  25. @(link_name="extra_general_stuff")
  26. extra_general_stuff :: proc() {
  27. fmt.println("# extra_general_stuff");
  28. { // `do` for inline statements rather than block
  29. foo :: proc() do fmt.println("Foo!");
  30. if false do foo();
  31. for false do foo();
  32. when false do foo();
  33. if false do foo();
  34. else do foo();
  35. }
  36. { // Removal of `++` and `--` (again)
  37. x: int;
  38. x += 1;
  39. x -= 1;
  40. }
  41. { // Casting syntaxes
  42. i := i32(137);
  43. ptr := &i;
  44. _ = (^f32)(ptr); // Call-based syntax
  45. // ^f32(ptr) == ^(f32(ptr))
  46. _ = cast(^f32)ptr; // Operator-based syntax
  47. _ = (^f32)(ptr)^;
  48. _ = (cast(^f32)ptr)^;
  49. }
  50. /*
  51. * Remove *_val_of built-in procedures
  52. * size_of, align_of, offset_of
  53. * type_of, type_info_of, typeid_of
  54. */
  55. { // `expand_to_tuple` built-in procedure
  56. Foo :: struct {
  57. x: int,
  58. b: bool,
  59. };
  60. f := Foo{137, true};
  61. x, b := expand_to_tuple(f);
  62. fmt.println(f);
  63. fmt.println(x, b);
  64. fmt.println(expand_to_tuple(f));
  65. }
  66. {
  67. // .. open range
  68. // ..< half-closed range
  69. for in 0..2 {} // 0, 1, 2
  70. for in 0..<2 {} // 0, 1
  71. }
  72. { // Multiple sized booleans
  73. x0: bool; // default
  74. x1: b8 = true;
  75. x2: b16 = false;
  76. x3: b32 = true;
  77. x4: b64 = false;
  78. fmt.printf("x0: %T = %v;\n", x0, x0);
  79. fmt.printf("x1: %T = %v;\n", x1, x1);
  80. fmt.printf("x2: %T = %v;\n", x2, x2);
  81. fmt.printf("x3: %T = %v;\n", x3, x3);
  82. fmt.printf("x4: %T = %v;\n", x4, x4);
  83. // Having specific sized booleans is very useful when dealing with foreign code
  84. // and to enforce specific alignment for a boolean, especially within a struct
  85. }
  86. { // `distinct` types
  87. // Originally, all type declarations would create a distinct type unless #type_alias was present.
  88. // Now the behaviour has been reversed. All type declarations create a type alias unless `distinct` is present.
  89. // If the type expression is `struct`, `union`, `enum`, `proc`, or `bit_field`, the types will always been distinct.
  90. Int32 :: i32;
  91. #assert(Int32 == i32);
  92. My_Int32 :: distinct i32;
  93. #assert(My_Int32 != i32);
  94. My_Struct :: struct{x: int};
  95. #assert(My_Struct != struct{x: int});
  96. My_Struct2 :: My_Struct;
  97. #assert(My_Struct2 == My_Struct);
  98. }
  99. {
  100. X :: 123;
  101. when #defined(X) {
  102. fmt.println("X is defined");
  103. } else {
  104. fmt.println("X is not defined");
  105. }
  106. when #defined(Y) {
  107. fmt.println("Y is defined");
  108. } else {
  109. fmt.println("Y is not defined");
  110. }
  111. }
  112. { // Labelled control blocks
  113. block: {
  114. if true {
  115. fmt.println("break block;");
  116. break block;
  117. }
  118. }
  119. {
  120. branch: if true {
  121. fmt.println("break branch;");
  122. break branch;
  123. }
  124. }
  125. {
  126. loop: for true {
  127. fmt.println("break loop;");
  128. break loop;
  129. }
  130. }
  131. {
  132. cases: switch {
  133. case:
  134. fmt.println("break cases;");
  135. break cases;
  136. }
  137. }
  138. }
  139. }
  140. union_type :: proc() {
  141. fmt.println("\n# union_type");
  142. {
  143. val: union{int, bool};
  144. val = 137;
  145. if i, ok := val.(int); ok {
  146. fmt.println(i);
  147. }
  148. val = true;
  149. fmt.println(val);
  150. val = nil;
  151. switch v in val {
  152. case int: fmt.println("int", v);
  153. case bool: fmt.println("bool", v);
  154. case: fmt.println("nil");
  155. }
  156. }
  157. {
  158. // There is a duality between `any` and `union`
  159. // An `any` has a pointer to the data and allows for any type (open)
  160. // A `union` has as binary blob to store the data and allows only certain types (closed)
  161. // The following code is with `any` but has the same syntax
  162. val: any;
  163. val = 137;
  164. if i, ok := val.(int); ok {
  165. fmt.println(i);
  166. }
  167. val = true;
  168. fmt.println(val);
  169. val = nil;
  170. switch v in val {
  171. case int: fmt.println("int", v);
  172. case bool: fmt.println("bool", v);
  173. case: fmt.println("nil");
  174. }
  175. }
  176. Vector3 :: distinct [3]f32;
  177. Quaternion :: distinct quaternion128;
  178. // More realistic examples
  179. {
  180. // NOTE(bill): For the above basic examples, you may not have any
  181. // particular use for it. However, my main use for them is not for these
  182. // simple cases. My main use is for hierarchical types. Many prefer
  183. // subtyping, embedding the base data into the derived types. Below is
  184. // an example of this for a basic game Entity.
  185. Entity :: struct {
  186. id: u64,
  187. name: string,
  188. position: Vector3,
  189. orientation: Quaternion,
  190. derived: any,
  191. };
  192. Frog :: struct {
  193. using entity: Entity,
  194. jump_height: f32,
  195. };
  196. Monster :: struct {
  197. using entity: Entity,
  198. is_robot: bool,
  199. is_zombie: bool,
  200. };
  201. // See `parametric_polymorphism` procedure for details
  202. new_entity :: proc($T: typeid) -> ^Entity {
  203. t := new(T);
  204. t.derived = t^;
  205. return t;
  206. }
  207. entity := new_entity(Monster);
  208. switch e in entity.derived {
  209. case Frog:
  210. fmt.println("Ribbit");
  211. case Monster:
  212. if e.is_robot do fmt.println("Robotic");
  213. if e.is_zombie do fmt.println("Grrrr!");
  214. fmt.println("I'm a monster");
  215. }
  216. }
  217. {
  218. // NOTE(bill): A union can be used to achieve something similar. Instead
  219. // of embedding the base data into the derived types, the derived data
  220. // in embedded into the base type. Below is the same example of the
  221. // basic game Entity but using an union.
  222. Entity :: struct {
  223. id: u64,
  224. name: string,
  225. position: Vector3,
  226. orientation: Quaternion,
  227. derived: union {Frog, Monster},
  228. };
  229. Frog :: struct {
  230. using entity: ^Entity,
  231. jump_height: f32,
  232. };
  233. Monster :: struct {
  234. using entity: ^Entity,
  235. is_robot: bool,
  236. is_zombie: bool,
  237. };
  238. // See `parametric_polymorphism` procedure for details
  239. new_entity :: proc($T: typeid) -> ^Entity {
  240. t := new(Entity);
  241. t.derived = T{entity = t};
  242. return t;
  243. }
  244. entity := new_entity(Monster);
  245. switch e in entity.derived {
  246. case Frog:
  247. fmt.println("Ribbit");
  248. case Monster:
  249. if e.is_robot do fmt.println("Robotic");
  250. if e.is_zombie do fmt.println("Grrrr!");
  251. }
  252. // NOTE(bill): As you can see, the usage code has not changed, only its
  253. // memory layout. Both approaches have their own advantages but they can
  254. // be used together to achieve different results. The subtyping approach
  255. // can allow for a greater control of the memory layout and memory
  256. // allocation, e.g. storing the derivatives together. However, this is
  257. // also its disadvantage. You must either preallocate arrays for each
  258. // derivative separation (which can be easily missed) or preallocate a
  259. // bunch of "raw" memory; determining the maximum size of the derived
  260. // types would require the aid of metaprogramming. Unions solve this
  261. // particular problem as the data is stored with the base data.
  262. // Therefore, it is possible to preallocate, e.g. [100]Entity.
  263. // It should be noted that the union approach can have the same memory
  264. // layout as the any and with the same type restrictions by using a
  265. // pointer type for the derivatives.
  266. /*
  267. Entity :: struct {
  268. ...
  269. derived: union{^Frog, ^Monster},
  270. }
  271. Frog :: struct {
  272. using entity: Entity,
  273. ...
  274. }
  275. Monster :: struct {
  276. using entity: Entity,
  277. ...
  278. }
  279. new_entity :: proc(T: type) -> ^Entity {
  280. t := new(T);
  281. t.derived = t;
  282. return t;
  283. }
  284. */
  285. }
  286. }
  287. parametric_polymorphism :: proc() {
  288. fmt.println("\n# parametric_polymorphism");
  289. print_value :: proc(value: $T) {
  290. fmt.printf("print_value: %T %v\n", value, value);
  291. }
  292. v1: int = 1;
  293. v2: f32 = 2.1;
  294. v3: f64 = 3.14;
  295. v4: string = "message";
  296. print_value(v1);
  297. print_value(v2);
  298. print_value(v3);
  299. print_value(v4);
  300. fmt.println();
  301. add :: proc(p, q: $T) -> T {
  302. x: T = p + q;
  303. return x;
  304. }
  305. a := add(3, 4);
  306. fmt.printf("a: %T = %v\n", a, a);
  307. b := add(3.2, 4.3);
  308. fmt.printf("b: %T = %v\n", b, b);
  309. // This is how `new` is implemented
  310. alloc_type :: proc($T: typeid) -> ^T {
  311. t := cast(^T)alloc(size_of(T), align_of(T));
  312. t^ = T{}; // Use default initialization value
  313. return t;
  314. }
  315. copy_slice :: proc(dst, src: []$T) -> int {
  316. n := min(len(dst), len(src));
  317. if n > 0 {
  318. mem.copy(&dst[0], &src[0], n*size_of(T));
  319. }
  320. return n;
  321. }
  322. double_params :: proc(a: $A, b: $B) -> A {
  323. return a + A(b);
  324. }
  325. fmt.println(double_params(12, 1.345));
  326. { // Polymorphic Types and Type Specialization
  327. Table_Slot :: struct(Key, Value: typeid) {
  328. occupied: bool,
  329. hash: u32,
  330. key: Key,
  331. value: Value,
  332. };
  333. TABLE_SIZE_MIN :: 32;
  334. Table :: struct(Key, Value: typeid) {
  335. count: int,
  336. allocator: mem.Allocator,
  337. slots: []Table_Slot(Key, Value),
  338. };
  339. // Only allow types that are specializations of a (polymorphic) slice
  340. make_slice :: proc($T: typeid/[]$E, len: int) -> T {
  341. return make(T, len);
  342. }
  343. // Only allow types that are specializations of `Table`
  344. allocate :: proc(table: ^$T/Table, capacity: int) {
  345. c := context;
  346. if table.allocator.procedure != nil do c.allocator = table.allocator;
  347. context = c;
  348. table.slots = make_slice(type_of(table.slots), max(capacity, TABLE_SIZE_MIN));
  349. }
  350. expand :: proc(table: ^$T/Table) {
  351. c := context;
  352. if table.allocator.procedure != nil do c.allocator = table.allocator;
  353. context = c;
  354. old_slots := table.slots;
  355. defer delete(old_slots);
  356. cap := max(2*len(table.slots), TABLE_SIZE_MIN);
  357. allocate(table, cap);
  358. for s in old_slots do if s.occupied {
  359. put(table, s.key, s.value);
  360. }
  361. }
  362. // Polymorphic determination of a polymorphic struct
  363. // put :: proc(table: ^$T/Table, key: T.Key, value: T.Value) {
  364. put :: proc(table: ^Table($Key, $Value), key: Key, value: Value) {
  365. hash := get_hash(key); // Ad-hoc method which would fail in a different scope
  366. index := find_index(table, key, hash);
  367. if index < 0 {
  368. if f64(table.count) >= 0.75*f64(len(table.slots)) {
  369. expand(table);
  370. }
  371. assert(table.count <= len(table.slots));
  372. index = int(hash % u32(len(table.slots)));
  373. for table.slots[index].occupied {
  374. if index += 1; index >= len(table.slots) {
  375. index = 0;
  376. }
  377. }
  378. table.count += 1;
  379. }
  380. slot := &table.slots[index];
  381. slot.occupied = true;
  382. slot.hash = hash;
  383. slot.key = key;
  384. slot.value = value;
  385. }
  386. // find :: proc(table: ^$T/Table, key: T.Key) -> (T.Value, bool) {
  387. find :: proc(table: ^Table($Key, $Value), key: Key) -> (Value, bool) {
  388. hash := get_hash(key);
  389. index := find_index(table, key, hash);
  390. if index < 0 {
  391. return Value{}, false;
  392. }
  393. return table.slots[index].value, true;
  394. }
  395. find_index :: proc(table: ^Table($Key, $Value), key: Key, hash: u32) -> int {
  396. if len(table.slots) <= 0 do return -1;
  397. index := int(hash % u32(len(table.slots)));
  398. for table.slots[index].occupied {
  399. if table.slots[index].hash == hash {
  400. if table.slots[index].key == key {
  401. return index;
  402. }
  403. }
  404. if index += 1; index >= len(table.slots) {
  405. index = 0;
  406. }
  407. }
  408. return -1;
  409. }
  410. get_hash :: proc(s: string) -> u32 { // fnv32a
  411. h: u32 = 0x811c9dc5;
  412. for i in 0..<len(s) {
  413. h = (h ~ u32(s[i])) * 0x01000193;
  414. }
  415. return h;
  416. }
  417. table: Table(string, int);
  418. for i in 0..36 do put(&table, "Hellope", i);
  419. for i in 0..42 do put(&table, "World!", i);
  420. found, _ := find(&table, "Hellope");
  421. fmt.printf("`found` is %v\n", found);
  422. found, _ = find(&table, "World!");
  423. fmt.printf("`found` is %v\n", found);
  424. // I would not personally design a hash table like this in production
  425. // but this is a nice basic example
  426. // A better approach would either use a `u64` or equivalent for the key
  427. // and let the user specify the hashing function or make the user store
  428. // the hashing procedure with the table
  429. }
  430. { // Parametric polymorphic union
  431. Error :: enum {
  432. Foo0,
  433. Foo1,
  434. Foo2,
  435. Foo3,
  436. };
  437. Para_Union :: union(T: typeid) {T, Error};
  438. r: Para_Union(int);
  439. fmt.println(typeid_of(type_of(r)));
  440. fmt.println(r);
  441. r = 123;
  442. fmt.println(r);
  443. r = Error.Foo0; // r = .Foo0; is allow too, see implicit selector expressions below
  444. fmt.println(r);
  445. }
  446. { // Polymorphic names
  447. foo :: proc($N: $I, $T: typeid) -> (res: [N]T) {
  448. // `N` is the constant value passed
  449. // `I` is the type of N
  450. // `T` is the type passed
  451. fmt.printf("Generating an array of type %v from the value %v of type %v\n",
  452. typeid_of(type_of(res)), N, typeid_of(I));
  453. for i in 0..<N {
  454. res[i] = T(i*i);
  455. }
  456. return;
  457. }
  458. T :: int;
  459. array := foo(4, T);
  460. for v, i in array {
  461. assert(v == T(i*i));
  462. }
  463. // Matrix multiplication
  464. mul :: proc(a: [$M][$N]$T, b: [N][$P]T) -> (c: [M][P]T) {
  465. for i in 0..<M {
  466. for j in 0..<P {
  467. for k in 0..<N {
  468. c[i][j] += a[i][k] * b[k][j];
  469. }
  470. }
  471. }
  472. return;
  473. }
  474. x := [2][3]f32{
  475. {1, 2, 3},
  476. {3, 2, 1},
  477. };
  478. y := [3][2]f32{
  479. {0, 8},
  480. {6, 2},
  481. {8, 4},
  482. };
  483. z := mul(x, y);
  484. assert(z == {{36, 24}, {20, 32}});
  485. }
  486. }
  487. prefix_table := [?]string{
  488. "White",
  489. "Red",
  490. "Green",
  491. "Blue",
  492. "Octarine",
  493. "Black",
  494. };
  495. threading_example :: proc() {
  496. when os.OS == "windows" {
  497. fmt.println("\n# threading_example");
  498. worker_proc :: proc(t: ^thread.Thread) -> int {
  499. for iteration in 1..5 {
  500. fmt.printf("Thread %d is on iteration %d\n", t.user_index, iteration);
  501. fmt.printf("`%s`: iteration %d\n", prefix_table[t.user_index], iteration);
  502. // win32.sleep(1);
  503. }
  504. return 0;
  505. }
  506. threads := make([dynamic]^thread.Thread, 0, len(prefix_table));
  507. defer delete(threads);
  508. for in prefix_table {
  509. if t := thread.create(worker_proc); t != nil {
  510. t.init_context = context;
  511. t.use_init_context = true;
  512. t.user_index = len(threads);
  513. append(&threads, t);
  514. thread.start(t);
  515. }
  516. }
  517. for len(threads) > 0 {
  518. for i := 0; i < len(threads); /**/ {
  519. if t := threads[i]; thread.is_done(t) {
  520. fmt.printf("Thread %d is done\n", t.user_index);
  521. thread.destroy(t);
  522. ordered_remove(&threads, i);
  523. } else {
  524. i += 1;
  525. }
  526. }
  527. }
  528. }
  529. }
  530. array_programming :: proc() {
  531. fmt.println("\n# array_programming");
  532. {
  533. a := [3]f32{1, 2, 3};
  534. b := [3]f32{5, 6, 7};
  535. c := a * b;
  536. d := a + b;
  537. e := 1 + (c - d) / 2;
  538. fmt.printf("%.1f\n", e); // [0.5, 3.0, 6.5]
  539. }
  540. {
  541. a := [3]f32{1, 2, 3};
  542. b := swizzle(a, 2, 1, 0);
  543. assert(b == [3]f32{3, 2, 1});
  544. c := swizzle(a, 0, 0);
  545. assert(c == [2]f32{1, 1});
  546. assert(c == 1);
  547. }
  548. {
  549. Vector3 :: distinct [3]f32;
  550. a := Vector3{1, 2, 3};
  551. b := Vector3{5, 6, 7};
  552. c := (a * b)/2 + 1;
  553. d := c.x + c.y + c.z;
  554. fmt.printf("%.1f\n", d); // 22.0
  555. cross :: proc(a, b: Vector3) -> Vector3 {
  556. i := swizzle(a, 1, 2, 0) * swizzle(b, 2, 0, 1);
  557. j := swizzle(a, 2, 0, 1) * swizzle(b, 1, 2, 0);
  558. return i - j;
  559. }
  560. blah :: proc(a: Vector3) -> f32 {
  561. return a.x + a.y + a.z;
  562. }
  563. x := cross(a, b);
  564. fmt.println(x);
  565. fmt.println(blah(x));
  566. }
  567. }
  568. named_proc_return_parameters :: proc() {
  569. fmt.println("\n# named proc return parameters");
  570. foo0 :: proc() -> int {
  571. return 123;
  572. }
  573. foo1 :: proc() -> (a: int) {
  574. a = 123;
  575. return;
  576. }
  577. foo2 :: proc() -> (a, b: int) {
  578. // Named return values act like variables within the scope
  579. a = 321;
  580. b = 567;
  581. return b, a;
  582. }
  583. fmt.println("foo0 =", foo0()); // 123
  584. fmt.println("foo1 =", foo1()); // 123
  585. fmt.println("foo2 =", foo2()); // 567 321
  586. }
  587. using_enum :: proc() {
  588. fmt.println("\n# using enum");
  589. using Foo :: enum {A, B, C};
  590. f0 := A;
  591. f1 := B;
  592. f2 := C;
  593. fmt.println(f0, f1, f2);
  594. fmt.println(len(Foo));
  595. }
  596. map_type :: proc() {
  597. fmt.println("\n# map type");
  598. // enums of type u16, u32, i16 & i32 also work
  599. Enum_u8 :: enum u8 {
  600. A = 0,
  601. B = 1 << 8 - 1,
  602. };
  603. Enum_u64 :: enum u64 {
  604. A = 0,
  605. B = 1 << 64 - 1,
  606. };
  607. Enum_i8 :: enum i8 {
  608. A = 0,
  609. B = -(1 << 7),
  610. };
  611. Enum_i64 :: enum i64 {
  612. A = 0,
  613. B = -(1 << 63),
  614. };
  615. map_u8: map[Enum_u8]u8;
  616. map_u8[Enum_u8.A] = u8(Enum_u8.B);
  617. assert(map_u8[Enum_u8.A] == u8(Enum_u8.B));
  618. fmt.println(map_u8);
  619. map_u64: map[Enum_u64]u64;
  620. map_u64[Enum_u64.A] = u64(Enum_u64.B);
  621. assert(map_u64[Enum_u64.A] == u64(Enum_u64.B));
  622. fmt.println(map_u64);
  623. map_i8: map[Enum_i8]i8;
  624. map_i8[Enum_i8.A] = i8(Enum_i8.B);
  625. assert(map_i8[Enum_i8.A] == i8(Enum_i8.B));
  626. fmt.println(map_i8);
  627. map_i64: map[Enum_i64]i64;
  628. map_i64[Enum_i64.A] = i64(Enum_i64.B);
  629. assert(map_i64[Enum_i64.A] == i64(Enum_i64.B));
  630. fmt.println(map_i64);
  631. demo_struct :: struct {
  632. member: Enum_i64,
  633. };
  634. map_string: map[string]demo_struct;
  635. map_string["Hellope!"] = demo_struct{Enum_i64.B};
  636. assert(map_string["Hellope!"].member == Enum_i64.B);
  637. assert("Hellope?" notin map_string);
  638. fmt.println(map_string);
  639. fmt.println("Hellope! in map_string:", "Hellope!" in map_string);
  640. fmt.println("Hellope? in map_string:", "Hellope?" in map_string);
  641. }
  642. implicit_selector_expression :: proc() {
  643. fmt.println("\n# implicit selector expression");
  644. Foo :: enum {A, B, C};
  645. f: Foo;
  646. f = .A;
  647. BAR :: bit_set[Foo]{.B, .C};
  648. switch f {
  649. case .A:
  650. fmt.println("HERE");
  651. case .B:
  652. fmt.println("NEVER");
  653. case .C:
  654. fmt.println("FOREVER");
  655. }
  656. my_map := make(map[Foo]int);
  657. defer delete(my_map);
  658. my_map[.A] = 123;
  659. my_map[Foo.B] = 345;
  660. fmt.println(my_map[.A] + my_map[Foo.B] + my_map[.C]);
  661. }
  662. explicit_procedure_overloading :: proc() {
  663. fmt.println("\n# explicit procedure overloading");
  664. add_ints :: proc(a, b: int) -> int {
  665. x := a + b;
  666. fmt.println("add_ints", x);
  667. return x;
  668. }
  669. add_floats :: proc(a, b: f32) -> f32 {
  670. x := a + b;
  671. fmt.println("add_floats", x);
  672. return x;
  673. }
  674. add_numbers :: proc(a: int, b: f32, c: u8) -> int {
  675. x := int(a) + int(b) + int(c);
  676. fmt.println("add_numbers", x);
  677. return x;
  678. }
  679. add :: proc{add_ints, add_floats, add_numbers};
  680. add(int(1), int(2));
  681. add(f32(1), f32(2));
  682. add(int(1), f32(2), u8(3));
  683. add(1, 2); // untyped ints coerce to int tighter than f32
  684. add(1.0, 2.0); // untyped floats coerce to f32 tighter than int
  685. add(1, 2, 3); // three parameters
  686. // Ambiguous answers
  687. // add(1.0, 2);
  688. // add(1, 2.0);
  689. }
  690. complete_switch :: proc() {
  691. fmt.println("\n# complete_switch");
  692. { // enum
  693. using Foo :: enum {
  694. A,
  695. B,
  696. C,
  697. D,
  698. };
  699. b := Foo.B;
  700. f := Foo.A;
  701. #complete switch f {
  702. case A: fmt.println("A");
  703. case B: fmt.println("B");
  704. case C: fmt.println("C");
  705. case D: fmt.println("D");
  706. case: fmt.println("?");
  707. }
  708. _ = b;
  709. }
  710. { // union
  711. Foo :: union {int, bool};
  712. f: Foo = 123;
  713. #complete switch in f {
  714. case int: fmt.println("int");
  715. case bool: fmt.println("bool");
  716. case:
  717. }
  718. }
  719. }
  720. cstring_example :: proc() {
  721. fmt.println("\n# cstring_example");
  722. W :: "Hellope";
  723. X :: cstring(W);
  724. Y :: string(X);
  725. w := W;
  726. _ = w;
  727. x: cstring = X;
  728. y: string = Y;
  729. z := string(x);
  730. fmt.println(x, y, z);
  731. fmt.println(len(x), len(y), len(z));
  732. fmt.println(len(W), len(X), len(Y));
  733. // IMPORTANT NOTE for cstring variables
  734. // len(cstring) is O(N)
  735. // cast(string)cstring is O(N)
  736. }
  737. deprecated_attribute :: proc() {
  738. @(deprecated="Use foo_v2 instead")
  739. foo_v1 :: proc(x: int) {
  740. fmt.println("foo_v1");
  741. }
  742. foo_v2 :: proc(x: int) {
  743. fmt.println("foo_v2");
  744. }
  745. // NOTE: Uncomment to see the warning messages
  746. // foo_v1(1);
  747. }
  748. bit_set_type :: proc() {
  749. fmt.println("\n# bit_set_type");
  750. {
  751. using Day :: enum {
  752. Sunday,
  753. Monday,
  754. Tuesday,
  755. Wednesday,
  756. Thursday,
  757. Friday,
  758. Saturday,
  759. };
  760. Days :: distinct bit_set[Day];
  761. WEEKEND :: Days{Sunday, Saturday};
  762. d: Days;
  763. d = {Sunday, Monday};
  764. e := d | WEEKEND;
  765. e |= {Monday};
  766. fmt.println(d, e);
  767. ok := Saturday in e; // `in` is only allowed for `map` and `bit_set` types
  768. fmt.println(ok);
  769. if Saturday in e {
  770. fmt.println("Saturday in", e);
  771. }
  772. X :: Saturday in WEEKEND; // Constant evaluation
  773. fmt.println(X);
  774. fmt.println("Cardinality:", card(e));
  775. }
  776. {
  777. x: bit_set['A'..'Z'];
  778. #assert(size_of(x) == size_of(u32));
  779. y: bit_set[0..8; u16];
  780. fmt.println(typeid_of(type_of(x))); // bit_set[A..Z]
  781. fmt.println(typeid_of(type_of(y))); // bit_set[0..8; u16]
  782. incl(&x, 'F');
  783. assert('F' in x);
  784. excl(&x, 'F');
  785. assert('F' notin x);
  786. y |= {1, 4, 2};
  787. assert(2 in y);
  788. }
  789. {
  790. Letters :: bit_set['A'..'Z'];
  791. a := Letters{'A', 'B'};
  792. b := Letters{'A', 'B', 'C', 'D', 'F'};
  793. c := Letters{'A', 'B'};
  794. assert(a <= b); // 'a' is a subset of 'b'
  795. assert(b >= a); // 'b' is a superset of 'a'
  796. assert(a < b); // 'a' is a strict subset of 'b'
  797. assert(b > a); // 'b' is a strict superset of 'a'
  798. assert(!(a < c)); // 'a' is a not strict subset of 'c'
  799. assert(!(c > a)); // 'c' is a not strict superset of 'a'
  800. }
  801. }
  802. diverging_procedures :: proc() {
  803. fmt.println("\n# diverging_procedures");
  804. // Diverging procedures may never return
  805. foo :: proc() -> ! {
  806. fmt.println("I'm a diverging procedure");
  807. }
  808. foo();
  809. }
  810. deferred_procedure_associations :: proc() {
  811. fmt.println("\n# deferred_procedure_associations");
  812. @(deferred_out=closure)
  813. open :: proc(s: string) -> bool {
  814. fmt.println(s);
  815. return true;
  816. }
  817. closure :: proc(ok: bool) {
  818. fmt.println("Goodbye?", ok);
  819. }
  820. if open("Welcome") {
  821. fmt.println("Something in the middle, mate.");
  822. }
  823. }
  824. reflection :: proc() {
  825. fmt.println("\n# reflection");
  826. Foo :: struct {
  827. x: int `tag1`,
  828. y: string `json:"y_field"`,
  829. z: bool, // no tag
  830. };
  831. id := typeid_of(Foo);
  832. names := reflect.struct_field_names(id);
  833. types := reflect.struct_field_types(id);
  834. tags := reflect.struct_field_tags(id);
  835. assert(len(names) == len(types) && len(names) == len(tags));
  836. fmt.println("Foo :: struct {");
  837. for tag, i in tags {
  838. name, type := names[i], types[i];
  839. if tag != "" {
  840. fmt.printf("\t%s: %T `%s`,\n", name, type, tag);
  841. } else {
  842. fmt.printf("\t%s: %T,\n", name, type);
  843. }
  844. }
  845. fmt.println("}");
  846. for tag, i in tags {
  847. if val, ok := reflect.struct_tag_lookup(tag, "json"); ok {
  848. fmt.printf("json: %s -> %s\n", names[i], val);
  849. }
  850. }
  851. }
  852. quaternions :: proc() {
  853. fmt.println("\n# quaternions");
  854. { // Quaternion operations
  855. q := 1 + 2i + 3j + 4k;
  856. r := quaternion(5, 6, 7, 8);
  857. t := q * r;
  858. fmt.printf("(%v) * (%v) = %v\n", q, r, t);
  859. v := q / r;
  860. fmt.printf("(%v) / (%v) = %v\n", q, r, v);
  861. u := q + r;
  862. fmt.printf("(%v) + (%v) = %v\n", q, r, u);
  863. s := q - r;
  864. fmt.printf("(%v) - (%v) = %v\n", q, r, s);
  865. }
  866. { // The quaternion types
  867. q128: quaternion128; // 4xf32
  868. q256: quaternion256; // 4xf64
  869. q128 = quaternion(1, 0, 0, 0);
  870. q256 = 1; // quaternion(1, 0, 0, 0);
  871. }
  872. { // Built-in procedures
  873. q := 1 + 2i + 3j + 4k;
  874. fmt.println("q =", q);
  875. fmt.println("real(q) =", real(q));
  876. fmt.println("imag(q) =", imag(q));
  877. fmt.println("jmag(q) =", jmag(q));
  878. fmt.println("kmag(q) =", kmag(q));
  879. fmt.println("conj(q) =", conj(q));
  880. fmt.println("abs(q) =", abs(q));
  881. }
  882. { // Conversion of a complex type to a quaternion type
  883. c := 1 + 2i;
  884. q := quaternion256(c);
  885. fmt.println(c);
  886. fmt.println(q);
  887. }
  888. { // Memory layout of Quaternions
  889. q := 1 + 2i + 3j + 4k;
  890. a := transmute([4]f64)q;
  891. fmt.println("Quaternion memory layout: xyzw/(ijkr)");
  892. fmt.println(q); // 1.000+2.000i+3.000j+4.000k
  893. fmt.println(a); // [2.000, 3.000, 4.000, 1.000]
  894. }
  895. }
  896. inline_for_statement :: proc() {
  897. fmt.println("\n#inline for statements");
  898. // 'inline for' works the same as if the 'inline' prefix did not
  899. // exist but these ranged loops are explicitly unrolled which can
  900. // be very very useful for certain optimizations
  901. fmt.println("Ranges");
  902. inline for x, i in 1..<4 {
  903. fmt.println(x, i);
  904. }
  905. fmt.println("Strings");
  906. inline for r, i in "Hello, 世界" {
  907. fmt.println(r, i);
  908. }
  909. fmt.println("Arrays");
  910. inline for elem, idx in ([4]int{1, 4, 9, 16}) {
  911. fmt.println(elem, idx);
  912. }
  913. Foo_Enum :: enum {
  914. A = 1,
  915. B,
  916. C = 6,
  917. D,
  918. };
  919. fmt.println("Enum types");
  920. inline for elem, idx in Foo_Enum {
  921. fmt.println(elem, idx);
  922. }
  923. }
  924. where_clauses :: proc() {
  925. fmt.println("\n#procedure 'where' clauses");
  926. { // Sanity checks
  927. simple_sanity_check :: proc(x: [2]int)
  928. where len(x) > 1,
  929. type_of(x) == [2]int {
  930. fmt.println(x);
  931. }
  932. }
  933. { // Parametric polymorphism checks
  934. cross_2d :: proc(a, b: $T/[2]$E) -> E
  935. where intrinsics.type_is_numeric(E) {
  936. return a.x*b.y - a.y*b.x;
  937. }
  938. cross_3d :: proc(a, b: $T/[3]$E) -> T
  939. where intrinsics.type_is_numeric(E) {
  940. x := a.y*b.z - a.z*b.y;
  941. y := a.z*b.x - a.x*b.z;
  942. z := a.x*b.y - a.y*b.z;
  943. return T{x, y, z};
  944. }
  945. a := [2]int{1, 2};
  946. b := [2]int{5, -3};
  947. fmt.println(cross_2d(a, b));
  948. x := [3]f32{1, 4, 9};
  949. y := [3]f32{-5, 0, 3};
  950. fmt.println(cross_3d(x, y));
  951. // Failure case
  952. // i := [2]bool{true, false};
  953. // j := [2]bool{false, true};
  954. // fmt.println(cross_2d(i, j));
  955. }
  956. { // Procedure groups usage
  957. foo :: proc(x: [$N]int) -> bool
  958. where N > 2 {
  959. fmt.println(#procedure, "was called with the parameter", x);
  960. return true;
  961. }
  962. bar :: proc(x: [$N]int) -> bool
  963. where 0 < N,
  964. N <= 2 {
  965. fmt.println(#procedure, "was called with the parameter", x);
  966. return false;
  967. }
  968. baz :: proc{foo, bar};
  969. x := [3]int{1, 2, 3};
  970. y := [2]int{4, 9};
  971. ok_x := baz(x);
  972. ok_y := baz(y);
  973. assert(ok_x == true);
  974. assert(ok_y == false);
  975. }
  976. { // Record types
  977. Foo :: struct(T: typeid, N: int)
  978. where intrinsics.type_is_integer(T),
  979. N > 2 {
  980. x: [N]T,
  981. y: [N-2]T,
  982. };
  983. T :: i32;
  984. N :: 5;
  985. f: Foo(T, N);
  986. #assert(size_of(f) == (N+N-2)*size_of(T));
  987. }
  988. }
  989. ranged_fields_for_array_compound_literals :: proc() {
  990. fmt.println("\n#ranged fields for array compound literals");
  991. { // Normal Array Literal
  992. foo := [?]int{1, 4, 9, 16};
  993. fmt.println(foo);
  994. }
  995. { // Indexed
  996. foo := [?]int{
  997. 3 = 16,
  998. 1 = 4,
  999. 2 = 9,
  1000. 0 = 1,
  1001. };
  1002. fmt.println(foo);
  1003. }
  1004. { // Ranges
  1005. i := 2;
  1006. foo := [?]int {
  1007. 0 = 123,
  1008. 5..9 = 54,
  1009. 10..<16 = i*3 + (i-1)*2,
  1010. };
  1011. #assert(len(foo) == 16);
  1012. fmt.println(foo); // [123, 0, 0, 0, 0, 54, 54, 54, 54, 54, 8, 8, 8, 8, 8]
  1013. }
  1014. { // Slice and Dynamic Array support
  1015. i := 2;
  1016. foo_slice := []int {
  1017. 0 = 123,
  1018. 5..9 = 54,
  1019. 10..<16 = i*3 + (i-1)*2,
  1020. };
  1021. assert(len(foo_slice) == 16);
  1022. fmt.println(foo_slice); // [123, 0, 0, 0, 0, 54, 54, 54, 54, 54, 8, 8, 8, 8, 8]
  1023. foo_dynamic_array := [dynamic]int {
  1024. 0 = 123,
  1025. 5..9 = 54,
  1026. 10..<16 = i*3 + (i-1)*2,
  1027. };
  1028. assert(len(foo_dynamic_array) == 16);
  1029. fmt.println(foo_dynamic_array); // [123, 0, 0, 0, 0, 54, 54, 54, 54, 54, 8, 8, 8, 8, 8]
  1030. }
  1031. }
  1032. main :: proc() {
  1033. when true {
  1034. extra_general_stuff();
  1035. union_type();
  1036. parametric_polymorphism();
  1037. threading_example();
  1038. array_programming();
  1039. named_proc_return_parameters();
  1040. using_enum();
  1041. map_type();
  1042. implicit_selector_expression();
  1043. explicit_procedure_overloading();
  1044. complete_switch();
  1045. cstring_example();
  1046. deprecated_attribute();
  1047. bit_set_type();
  1048. diverging_procedures();
  1049. deferred_procedure_associations();
  1050. reflection();
  1051. quaternions();
  1052. inline_for_statement();
  1053. where_clauses();
  1054. ranged_fields_for_array_compound_literals();
  1055. }
  1056. }