demo.odin 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012
  1. package main
  2. import "core:fmt"
  3. import "core:mem"
  4. import "core:os"
  5. import "core:thread"
  6. import "core:time"
  7. import "core:reflect"
  8. import "core:runtime"
  9. import "intrinsics"
  10. /*
  11. The Odin programming language is fast, concise, readable, pragmatic and open sourced.
  12. It is designed with the intent of replacing C with the following goals:
  13. * simplicity
  14. * high performance
  15. * built for modern systems
  16. * joy of programming
  17. # Installing Odin
  18. Getting Started - https://odin-lang.org/docs/install/
  19. Instructions for downloading and install the Odin compiler and libraries.
  20. # Learning Odin
  21. Overview of Odin - https://odin-lang.org/docs/overview/
  22. An overview of the Odin programming language.
  23. Frequently Asked Questions (FAQ) - https://odin-lang.org/docs/faq/
  24. Answers to common questions about Odin.
  25. */
  26. the_basics :: proc() {
  27. fmt.println("\n# the basics");
  28. { // The Basics
  29. fmt.println("Hellope");
  30. // Lexical elements and literals
  31. // A comment
  32. my_integer_variable: int; // A comment for documentaton
  33. // Multi-line comments begin with /* and end with */. Multi-line comments can
  34. // also be nested (unlike in C):
  35. /*
  36. You can have any text or code here and
  37. have it be commented.
  38. /*
  39. NOTE: comments can be nested!
  40. */
  41. */
  42. // String literals are enclosed in double quotes and character literals in single quotes.
  43. // Special characters are escaped with a backslash \
  44. some_string := "This is a string";
  45. _ = 'A'; // unicode codepoint literal
  46. _ = '\n';
  47. _ = "C:\\Windows\\notepad.exe";
  48. // Raw string literals are enclosed with single back ticks
  49. _ = `C:\Windows\notepad.exe`;
  50. // The length of a string in bytes can be found using the built-in `len` procedure:
  51. _ = len("Foo");
  52. _ = len(some_string);
  53. // Numbers
  54. // Numerical literals are written similar to most other programming languages.
  55. // A useful feature in Odin is that underscores are allowed for better
  56. // readability: 1_000_000_000 (one billion). A number that contains a dot is a
  57. // floating point literal: 1.0e9 (one billion). If a number literal is suffixed
  58. // with i, is an imaginary number literal: 2i (2 multiply the square root of -1).
  59. // Binary literals are prefixed with 0b, octal literals with 0o, and hexadecimal
  60. // literals 0x. A leading zero does not produce an octal constant (unlike C).
  61. // In Odin, if a numeric constant can be represented by a type without
  62. // precision loss, it will automatically convert to that type.
  63. x: int = 1.0; // A float literal but it can be represented by an integer without precision loss
  64. // Constant literals are “untyped” which means that they can implicitly convert to a type.
  65. y: int; // `y` is typed of type `int`
  66. y = 1; // `1` is an untyped integer literal which can implicitly convert to `int`
  67. z: f64; // `z` is typed of type `f64` (64-bit floating point number)
  68. z = 1; // `1` is an untyped integer literal which can be implicitly converted to `f64`
  69. // No need for any suffixes or decimal places like in other languages
  70. // CONSTANTS JUST WORK!!!
  71. // Assignment statements
  72. h: int = 123; // declares a new variable `h` with type `int` and assigns a value to it
  73. h = 637; // assigns a new value to `h`
  74. // `=` is the assignment operator
  75. // You can assign multiple variables with it:
  76. a, b := 1, "hello"; // declares `a` and `b` and infers the types from the assignments
  77. b, a = "byte", 0;
  78. // Note: `:=` is two tokens, `:` and `=`. The following are equivalent,
  79. /*
  80. i: int = 123;
  81. i: = 123;
  82. i := 123;
  83. */
  84. // Constant declarations
  85. // Constants are entities (symbols) which have an assigned value.
  86. // The constant’s value cannot be changed.
  87. // The constant’s value must be able to be evaluated at compile time:
  88. X :: "what"; // constant `X` has the untyped string value "what"
  89. // Constants can be explicitly typed like a variable declaration:
  90. Y : int : 123;
  91. Z :: Y + 7; // constant computations are possible
  92. _ = my_integer_variable;
  93. _ = x;
  94. }
  95. }
  96. control_flow :: proc() {
  97. fmt.println("\n# control flow");
  98. { // Control flow
  99. // For loop
  100. // Odin has only one loop statement, the `for` loop
  101. // Basic for loop
  102. for i := 0; i < 10; i += 1 {
  103. fmt.println(i);
  104. }
  105. // NOTE: Unlike other languages like C, there are no parentheses `( )` surrounding the three components.
  106. // Braces `{ }` or a `do` are always required
  107. for i := 0; i < 10; i += 1 { }
  108. // for i := 0; i < 10; i += 1 do fmt.print();
  109. // The initial and post statements are optional
  110. i := 0;
  111. for ; i < 10; {
  112. i += 1;
  113. }
  114. // These semicolons can be dropped. This `for` loop is equivalent to C's `while` loop
  115. i = 0;
  116. for i < 10 {
  117. i += 1;
  118. }
  119. // If the condition is omitted, an infinite loop is produced:
  120. for {
  121. break;
  122. }
  123. // Range-based for loop
  124. // The basic for loop
  125. for j := 0; j < 10; j += 1 {
  126. fmt.println(j);
  127. }
  128. // can also be written
  129. for j in 0..<10 {
  130. fmt.println(j);
  131. }
  132. for j in 0..9 {
  133. fmt.println(j);
  134. }
  135. // Certain built-in types can be iterated over
  136. some_string := "Hello, 世界";
  137. for character in some_string { // Strings are assumed to be UTF-8
  138. fmt.println(character);
  139. }
  140. some_array := [3]int{1, 4, 9};
  141. for value in some_array {
  142. fmt.println(value);
  143. }
  144. some_slice := []int{1, 4, 9};
  145. for value in some_slice {
  146. fmt.println(value);
  147. }
  148. some_dynamic_array := [dynamic]int{1, 4, 9};
  149. defer delete(some_dynamic_array);
  150. for value in some_dynamic_array {
  151. fmt.println(value);
  152. }
  153. some_map := map[string]int{"A" = 1, "C" = 9, "B" = 4};
  154. defer delete(some_map);
  155. for key in some_map {
  156. fmt.println(key);
  157. }
  158. // Alternatively a second index value can be added
  159. for character, index in some_string {
  160. fmt.println(index, character);
  161. }
  162. for value, index in some_array {
  163. fmt.println(index, value);
  164. }
  165. for value, index in some_slice {
  166. fmt.println(index, value);
  167. }
  168. for value, index in some_dynamic_array {
  169. fmt.println(index, value);
  170. }
  171. for key, value in some_map {
  172. fmt.println(key, value);
  173. }
  174. // The iterated values are copies and cannot be written to.
  175. // The following idiom is useful for iterating over a container in a by-reference manner:
  176. for _, idx in some_slice {
  177. some_slice[idx] = (idx+1)*(idx+1);
  178. }
  179. // If statements
  180. x := 123;
  181. if x >= 0 {
  182. fmt.println("x is positive");
  183. }
  184. if y := -34; y < 0 {
  185. fmt.println("y is negative");
  186. }
  187. if y := 123; y < 0 {
  188. fmt.println("y is negative");
  189. } else if y == 0 {
  190. fmt.println("y is zero");
  191. } else {
  192. fmt.println("y is positive");
  193. }
  194. // Switch statement
  195. // A switch statement is another way to write a sequence of if-else statements.
  196. // In Odin, the default case is denoted as a case without any expression.
  197. switch arch := ODIN_ARCH; arch {
  198. case "386":
  199. fmt.println("32-bit");
  200. case "amd64":
  201. fmt.println("64-bit");
  202. case: // default
  203. fmt.println("Unsupported architecture");
  204. }
  205. // Odin’s `switch` is like one in C or C++, except that Odin only runs the selected case.
  206. // This means that a `break` statement is not needed at the end of each case.
  207. // Another important difference is that the case values need not be integers nor constants.
  208. // To achieve a C-like fall through into the next case block, the keyword `fallthrough` can be used.
  209. one_angry_dwarf :: proc() -> int {
  210. fmt.println("one_angry_dwarf was called");
  211. return 1;
  212. }
  213. switch j := 0; j {
  214. case 0:
  215. case one_angry_dwarf():
  216. }
  217. // A switch statement without a condition is the same as `switch true`.
  218. // This can be used to write a clean and long if-else chain and have the
  219. // ability to break if needed
  220. switch {
  221. case x < 0:
  222. fmt.println("x is negative");
  223. case x == 0:
  224. fmt.println("x is zero");
  225. case:
  226. fmt.println("x is positive");
  227. }
  228. // A `switch` statement can also use ranges like a range-based loop:
  229. switch c := 'j'; c {
  230. case 'A'..'Z', 'a'..'z', '0'..'9':
  231. fmt.println("c is alphanumeric");
  232. }
  233. switch x {
  234. case 0..<10:
  235. fmt.println("units");
  236. case 10..<13:
  237. fmt.println("pre-teens");
  238. case 13..<20:
  239. fmt.println("teens");
  240. case 20..<30:
  241. fmt.println("twenties");
  242. }
  243. }
  244. { // Defer statement
  245. // A defer statement defers the execution of a statement until the end of
  246. // the scope it is in.
  247. // The following will print 4 then 234:
  248. {
  249. x := 123;
  250. defer fmt.println(x);
  251. {
  252. defer x = 4;
  253. x = 2;
  254. }
  255. fmt.println(x);
  256. x = 234;
  257. }
  258. // You can defer an entire block too:
  259. {
  260. bar :: proc() {}
  261. defer {
  262. fmt.println("1");
  263. fmt.println("2");
  264. }
  265. cond := false;
  266. defer if cond {
  267. bar();
  268. }
  269. }
  270. // Defer statements are executed in the reverse order that they were declared:
  271. {
  272. defer fmt.println("1");
  273. defer fmt.println("2");
  274. defer fmt.println("3");
  275. }
  276. // Will print 3, 2, and then 1.
  277. if false {
  278. f, err := os.open("my_file.txt");
  279. if err != 0 {
  280. // handle error
  281. }
  282. defer os.close(f);
  283. // rest of code
  284. }
  285. }
  286. { // When statement
  287. /*
  288. The when statement is almost identical to the if statement but with some differences:
  289. * Each condition must be a constant expression as a when
  290. statement is evaluated at compile time.
  291. * The statements within a branch do not create a new scope
  292. * The compiler checks the semantics and code only for statements
  293. that belong to the first condition that is true
  294. * An initial statement is not allowed in a when statement
  295. * when statements are allowed at file scope
  296. */
  297. // Example
  298. when ODIN_ARCH == "386" {
  299. fmt.println("32 bit");
  300. } else when ODIN_ARCH == "amd64" {
  301. fmt.println("64 bit");
  302. } else {
  303. fmt.println("Unsupported architecture");
  304. }
  305. // The when statement is very useful for writing platform specific code.
  306. // This is akin to the #if construct in C’s preprocessor however, in Odin,
  307. // it is type checked.
  308. }
  309. { // Branch statements
  310. cond, cond1, cond2 := false, false, false;
  311. one_step :: proc() { fmt.println("one_step"); }
  312. beyond :: proc() { fmt.println("beyond"); }
  313. // Break statement
  314. for cond {
  315. switch {
  316. case:
  317. if cond {
  318. break; // break out of the `switch` statement
  319. }
  320. }
  321. break; // break out of the `for` statement
  322. }
  323. loop: for cond1 {
  324. for cond2 {
  325. break loop; // leaves both loops
  326. }
  327. }
  328. // Continue statement
  329. for cond {
  330. if cond2 {
  331. continue;
  332. }
  333. fmt.println("Hellope");
  334. }
  335. // Fallthrough statement
  336. // Odin’s switch is like one in C or C++, except that Odin only runs the selected
  337. // case. This means that a break statement is not needed at the end of each case.
  338. // Another important difference is that the case values need not be integers nor
  339. // constants.
  340. // fallthrough can be used to explicitly fall through into the next case block:
  341. switch i := 0; i {
  342. case 0:
  343. one_step();
  344. fallthrough;
  345. case 1:
  346. beyond();
  347. }
  348. }
  349. }
  350. named_proc_return_parameters :: proc() {
  351. fmt.println("\n# named proc return parameters");
  352. foo0 :: proc() -> int {
  353. return 123;
  354. }
  355. foo1 :: proc() -> (a: int) {
  356. a = 123;
  357. return;
  358. }
  359. foo2 :: proc() -> (a, b: int) {
  360. // Named return values act like variables within the scope
  361. a = 321;
  362. b = 567;
  363. return b, a;
  364. }
  365. fmt.println("foo0 =", foo0()); // 123
  366. fmt.println("foo1 =", foo1()); // 123
  367. fmt.println("foo2 =", foo2()); // 567 321
  368. }
  369. explicit_procedure_overloading :: proc() {
  370. fmt.println("\n# explicit procedure overloading");
  371. add_ints :: proc(a, b: int) -> int {
  372. x := a + b;
  373. fmt.println("add_ints", x);
  374. return x;
  375. }
  376. add_floats :: proc(a, b: f32) -> f32 {
  377. x := a + b;
  378. fmt.println("add_floats", x);
  379. return x;
  380. }
  381. add_numbers :: proc(a: int, b: f32, c: u8) -> int {
  382. x := int(a) + int(b) + int(c);
  383. fmt.println("add_numbers", x);
  384. return x;
  385. }
  386. add :: proc{add_ints, add_floats, add_numbers};
  387. add(int(1), int(2));
  388. add(f32(1), f32(2));
  389. add(int(1), f32(2), u8(3));
  390. add(1, 2); // untyped ints coerce to int tighter than f32
  391. add(1.0, 2.0); // untyped floats coerce to f32 tighter than int
  392. add(1, 2, 3); // three parameters
  393. // Ambiguous answers
  394. // add(1.0, 2);
  395. // add(1, 2.0);
  396. }
  397. struct_type :: proc() {
  398. fmt.println("\n# struct type");
  399. // A struct is a record type in Odin. It is a collection of fields.
  400. // Struct fields are accessed by using a dot:
  401. {
  402. Vector2 :: struct {
  403. x: f32,
  404. y: f32,
  405. };
  406. v := Vector2{1, 2};
  407. v.x = 4;
  408. fmt.println(v.x);
  409. // Struct fields can be accessed through a struct pointer:
  410. v = Vector2{1, 2};
  411. p := &v;
  412. p.x = 1335;
  413. fmt.println(v);
  414. // We could write p^.x, however, it is to nice abstract the ability
  415. // to not explicitly dereference the pointer. This is very useful when
  416. // refactoring code to use a pointer rather than a value, and vice versa.
  417. }
  418. {
  419. // A struct literal can be denoted by providing the struct’s type
  420. // followed by {}. A struct literal must either provide all the
  421. // arguments or none:
  422. Vector3 :: struct {
  423. x, y, z: f32,
  424. };
  425. v: Vector3;
  426. v = Vector3{}; // Zero value
  427. v = Vector3{1, 4, 9};
  428. // You can list just a subset of the fields if you specify the
  429. // field by name (the order of the named fields does not matter):
  430. v = Vector3{z=1, y=2};
  431. assert(v.x == 0);
  432. assert(v.y == 2);
  433. assert(v.z == 1);
  434. }
  435. {
  436. // Structs can tagged with different memory layout and alignment requirements:
  437. a :: struct #align 4 {}; // align to 4 bytes
  438. b :: struct #packed {}; // remove padding between fields
  439. c :: struct #raw_union {}; // all fields share the same offset (0). This is the same as C's union
  440. }
  441. }
  442. union_type :: proc() {
  443. fmt.println("\n# union type");
  444. {
  445. val: union{int, bool};
  446. val = 137;
  447. if i, ok := val.(int); ok {
  448. fmt.println(i);
  449. }
  450. val = true;
  451. fmt.println(val);
  452. val = nil;
  453. switch v in val {
  454. case int: fmt.println("int", v);
  455. case bool: fmt.println("bool", v);
  456. case: fmt.println("nil");
  457. }
  458. }
  459. {
  460. // There is a duality between `any` and `union`
  461. // An `any` has a pointer to the data and allows for any type (open)
  462. // A `union` has as binary blob to store the data and allows only certain types (closed)
  463. // The following code is with `any` but has the same syntax
  464. val: any;
  465. val = 137;
  466. if i, ok := val.(int); ok {
  467. fmt.println(i);
  468. }
  469. val = true;
  470. fmt.println(val);
  471. val = nil;
  472. switch v in val {
  473. case int: fmt.println("int", v);
  474. case bool: fmt.println("bool", v);
  475. case: fmt.println("nil");
  476. }
  477. }
  478. Vector3 :: distinct [3]f32;
  479. Quaternion :: distinct quaternion128;
  480. // More realistic examples
  481. {
  482. // NOTE(bill): For the above basic examples, you may not have any
  483. // particular use for it. However, my main use for them is not for these
  484. // simple cases. My main use is for hierarchical types. Many prefer
  485. // subtyping, embedding the base data into the derived types. Below is
  486. // an example of this for a basic game Entity.
  487. Entity :: struct {
  488. id: u64,
  489. name: string,
  490. position: Vector3,
  491. orientation: Quaternion,
  492. derived: any,
  493. };
  494. Frog :: struct {
  495. using entity: Entity,
  496. jump_height: f32,
  497. };
  498. Monster :: struct {
  499. using entity: Entity,
  500. is_robot: bool,
  501. is_zombie: bool,
  502. };
  503. // See `parametric_polymorphism` procedure for details
  504. new_entity :: proc($T: typeid) -> ^Entity {
  505. t := new(T);
  506. t.derived = t^;
  507. return t;
  508. }
  509. entity := new_entity(Monster);
  510. switch e in entity.derived {
  511. case Frog:
  512. fmt.println("Ribbit");
  513. case Monster:
  514. if e.is_robot { fmt.println("Robotic"); }
  515. if e.is_zombie { fmt.println("Grrrr!"); }
  516. fmt.println("I'm a monster");
  517. }
  518. }
  519. {
  520. // NOTE(bill): A union can be used to achieve something similar. Instead
  521. // of embedding the base data into the derived types, the derived data
  522. // in embedded into the base type. Below is the same example of the
  523. // basic game Entity but using an union.
  524. Entity :: struct {
  525. id: u64,
  526. name: string,
  527. position: Vector3,
  528. orientation: Quaternion,
  529. derived: union {Frog, Monster},
  530. };
  531. Frog :: struct {
  532. using entity: ^Entity,
  533. jump_height: f32,
  534. };
  535. Monster :: struct {
  536. using entity: ^Entity,
  537. is_robot: bool,
  538. is_zombie: bool,
  539. };
  540. // See `parametric_polymorphism` procedure for details
  541. new_entity :: proc($T: typeid) -> ^Entity {
  542. t := new(Entity);
  543. t.derived = T{entity = t};
  544. return t;
  545. }
  546. entity := new_entity(Monster);
  547. switch e in entity.derived {
  548. case Frog:
  549. fmt.println("Ribbit");
  550. case Monster:
  551. if e.is_robot { fmt.println("Robotic"); }
  552. if e.is_zombie { fmt.println("Grrrr!"); }
  553. }
  554. // NOTE(bill): As you can see, the usage code has not changed, only its
  555. // memory layout. Both approaches have their own advantages but they can
  556. // be used together to achieve different results. The subtyping approach
  557. // can allow for a greater control of the memory layout and memory
  558. // allocation, e.g. storing the derivatives together. However, this is
  559. // also its disadvantage. You must either preallocate arrays for each
  560. // derivative separation (which can be easily missed) or preallocate a
  561. // bunch of "raw" memory; determining the maximum size of the derived
  562. // types would require the aid of metaprogramming. Unions solve this
  563. // particular problem as the data is stored with the base data.
  564. // Therefore, it is possible to preallocate, e.g. [100]Entity.
  565. // It should be noted that the union approach can have the same memory
  566. // layout as the any and with the same type restrictions by using a
  567. // pointer type for the derivatives.
  568. /*
  569. Entity :: struct {
  570. ...
  571. derived: union{^Frog, ^Monster},
  572. }
  573. Frog :: struct {
  574. using entity: Entity,
  575. ...
  576. }
  577. Monster :: struct {
  578. using entity: Entity,
  579. ...
  580. }
  581. new_entity :: proc(T: type) -> ^Entity {
  582. t := new(T);
  583. t.derived = t;
  584. return t;
  585. }
  586. */
  587. }
  588. }
  589. using_statement :: proc() {
  590. fmt.println("\n# using statement");
  591. // using can used to bring entities declared in a scope/namespace
  592. // into the current scope. This can be applied to import names, struct
  593. // fields, procedure fields, and struct values.
  594. Vector3 :: struct{x, y, z: f32};
  595. {
  596. Entity :: struct {
  597. position: Vector3,
  598. orientation: quaternion128,
  599. };
  600. // It can used like this:
  601. foo0 :: proc(entity: ^Entity) {
  602. fmt.println(entity.position.x, entity.position.y, entity.position.z);
  603. }
  604. // The entity members can be brought into the procedure scope by using it:
  605. foo1 :: proc(entity: ^Entity) {
  606. using entity;
  607. fmt.println(position.x, position.y, position.z);
  608. }
  609. // The using can be applied to the parameter directly:
  610. foo2 :: proc(using entity: ^Entity) {
  611. fmt.println(position.x, position.y, position.z);
  612. }
  613. // It can also be applied to sub-fields:
  614. foo3 :: proc(entity: ^Entity) {
  615. using entity.position;
  616. fmt.println(x, y, z);
  617. }
  618. }
  619. {
  620. // We can also apply the using statement to the struct fields directly,
  621. // making all the fields of position appear as if they on Entity itself:
  622. Entity :: struct {
  623. using position: Vector3,
  624. orientation: quaternion128,
  625. };
  626. foo :: proc(entity: ^Entity) {
  627. fmt.println(entity.x, entity.y, entity.z);
  628. }
  629. // Subtype polymorphism
  630. // It is possible to get subtype polymorphism, similar to inheritance-like
  631. // functionality in C++, but without the requirement of vtables or unknown
  632. // struct layout:
  633. Colour :: struct {r, g, b, a: u8};
  634. Frog :: struct {
  635. ribbit_volume: f32,
  636. using entity: Entity,
  637. colour: Colour,
  638. };
  639. frog: Frog;
  640. // Both work
  641. foo(&frog.entity);
  642. foo(&frog);
  643. frog.x = 123;
  644. // Note: using can be applied to arbitrarily many things, which allows
  645. // the ability to have multiple subtype polymorphism (but also its issues).
  646. // Note: using’d fields can still be referred by name.
  647. }
  648. { // using on an enum declaration
  649. using Foo :: enum {A, B, C};
  650. f0 := A;
  651. f1 := B;
  652. f2 := C;
  653. fmt.println(f0, f1, f2);
  654. fmt.println(len(Foo));
  655. }
  656. }
  657. implicit_context_system :: proc() {
  658. fmt.println("\n# implicit context system");
  659. // In each scope, there is an implicit value named context. This
  660. // context variable is local to each scope and is implicitly passed
  661. // by pointer to any procedure call in that scope (if the procedure
  662. // has the Odin calling convention).
  663. // The main purpose of the implicit context system is for the ability
  664. // to intercept third-party code and libraries and modify their
  665. // functionality. One such case is modifying how a library allocates
  666. // something or logs something. In C, this was usually achieved with
  667. // the library defining macros which could be overridden so that the
  668. // user could define what he wanted. However, not many libraries
  669. // supported this in many languages by default which meant intercepting
  670. // third-party code to see what it does and to change how it does it is
  671. // not possible.
  672. c := context; // copy the current scope's context
  673. context.user_index = 456;
  674. {
  675. context.allocator = my_custom_allocator();
  676. context.user_index = 123;
  677. what_a_fool_believes(); // the `context` for this scope is implicitly passed to `what_a_fool_believes`
  678. }
  679. // `context` value is local to the scope it is in
  680. assert(context.user_index == 456);
  681. what_a_fool_believes :: proc() {
  682. c := context; // this `context` is the same as the parent procedure that it was called from
  683. // From this example, context.user_index == 123
  684. // An context.allocator is assigned to the return value of `my_custom_allocator()`
  685. assert(context.user_index == 123);
  686. // The memory management procedure use the `context.allocator` by
  687. // default unless explicitly specified otherwise
  688. china_grove := new(int);
  689. free(china_grove);
  690. _ = c;
  691. }
  692. my_custom_allocator :: mem.nil_allocator;
  693. _ = c;
  694. // By default, the context value has default values for its parameters which is
  695. // decided in the package runtime. What the defaults are are compiler specific.
  696. // To see what the implicit context value contains, please see the following
  697. // definition in package runtime.
  698. }
  699. parametric_polymorphism :: proc() {
  700. fmt.println("\n# parametric polymorphism");
  701. print_value :: proc(value: $T) {
  702. fmt.printf("print_value: %T %v\n", value, value);
  703. }
  704. v1: int = 1;
  705. v2: f32 = 2.1;
  706. v3: f64 = 3.14;
  707. v4: string = "message";
  708. print_value(v1);
  709. print_value(v2);
  710. print_value(v3);
  711. print_value(v4);
  712. fmt.println();
  713. add :: proc(p, q: $T) -> T {
  714. x: T = p + q;
  715. return x;
  716. }
  717. a := add(3, 4);
  718. fmt.printf("a: %T = %v\n", a, a);
  719. b := add(3.2, 4.3);
  720. fmt.printf("b: %T = %v\n", b, b);
  721. // This is how `new` is implemented
  722. alloc_type :: proc($T: typeid) -> ^T {
  723. t := cast(^T)alloc(size_of(T), align_of(T));
  724. t^ = T{}; // Use default initialization value
  725. return t;
  726. }
  727. copy_slice :: proc(dst, src: []$T) -> int {
  728. n := min(len(dst), len(src));
  729. if n > 0 {
  730. mem.copy(&dst[0], &src[0], n*size_of(T));
  731. }
  732. return n;
  733. }
  734. double_params :: proc(a: $A, b: $B) -> A {
  735. return a + A(b);
  736. }
  737. fmt.println(double_params(12, 1.345));
  738. { // Polymorphic Types and Type Specialization
  739. Table_Slot :: struct(Key, Value: typeid) {
  740. occupied: bool,
  741. hash: u32,
  742. key: Key,
  743. value: Value,
  744. };
  745. TABLE_SIZE_MIN :: 32;
  746. Table :: struct(Key, Value: typeid) {
  747. count: int,
  748. allocator: mem.Allocator,
  749. slots: []Table_Slot(Key, Value),
  750. };
  751. // Only allow types that are specializations of a (polymorphic) slice
  752. make_slice :: proc($T: typeid/[]$E, len: int) -> T {
  753. return make(T, len);
  754. }
  755. // Only allow types that are specializations of `Table`
  756. allocate :: proc(table: ^$T/Table, capacity: int) {
  757. c := context;
  758. if table.allocator.procedure != nil {
  759. c.allocator = table.allocator;
  760. }
  761. context = c;
  762. table.slots = make_slice(type_of(table.slots), max(capacity, TABLE_SIZE_MIN));
  763. }
  764. expand :: proc(table: ^$T/Table) {
  765. c := context;
  766. if table.allocator.procedure != nil {
  767. c.allocator = table.allocator;
  768. }
  769. context = c;
  770. old_slots := table.slots;
  771. defer delete(old_slots);
  772. cap := max(2*len(table.slots), TABLE_SIZE_MIN);
  773. allocate(table, cap);
  774. for s in old_slots {
  775. if s.occupied {
  776. put(table, s.key, s.value);
  777. }
  778. }
  779. }
  780. // Polymorphic determination of a polymorphic struct
  781. // put :: proc(table: ^$T/Table, key: T.Key, value: T.Value) {
  782. put :: proc(table: ^Table($Key, $Value), key: Key, value: Value) {
  783. hash := get_hash(key); // Ad-hoc method which would fail in a different scope
  784. index := find_index(table, key, hash);
  785. if index < 0 {
  786. if f64(table.count) >= 0.75*f64(len(table.slots)) {
  787. expand(table);
  788. }
  789. assert(table.count <= len(table.slots));
  790. index = int(hash % u32(len(table.slots)));
  791. for table.slots[index].occupied {
  792. if index += 1; index >= len(table.slots) {
  793. index = 0;
  794. }
  795. }
  796. table.count += 1;
  797. }
  798. slot := &table.slots[index];
  799. slot.occupied = true;
  800. slot.hash = hash;
  801. slot.key = key;
  802. slot.value = value;
  803. }
  804. // find :: proc(table: ^$T/Table, key: T.Key) -> (T.Value, bool) {
  805. find :: proc(table: ^Table($Key, $Value), key: Key) -> (Value, bool) {
  806. hash := get_hash(key);
  807. index := find_index(table, key, hash);
  808. if index < 0 {
  809. return Value{}, false;
  810. }
  811. return table.slots[index].value, true;
  812. }
  813. find_index :: proc(table: ^Table($Key, $Value), key: Key, hash: u32) -> int {
  814. if len(table.slots) <= 0 {
  815. return -1;
  816. }
  817. index := int(hash % u32(len(table.slots)));
  818. for table.slots[index].occupied {
  819. if table.slots[index].hash == hash {
  820. if table.slots[index].key == key {
  821. return index;
  822. }
  823. }
  824. if index += 1; index >= len(table.slots) {
  825. index = 0;
  826. }
  827. }
  828. return -1;
  829. }
  830. get_hash :: proc(s: string) -> u32 { // fnv32a
  831. h: u32 = 0x811c9dc5;
  832. for i in 0..<len(s) {
  833. h = (h ~ u32(s[i])) * 0x01000193;
  834. }
  835. return h;
  836. }
  837. table: Table(string, int);
  838. for i in 0..36 { put(&table, "Hellope", i); }
  839. for i in 0..42 { put(&table, "World!", i); }
  840. found, _ := find(&table, "Hellope");
  841. fmt.printf("`found` is %v\n", found);
  842. found, _ = find(&table, "World!");
  843. fmt.printf("`found` is %v\n", found);
  844. // I would not personally design a hash table like this in production
  845. // but this is a nice basic example
  846. // A better approach would either use a `u64` or equivalent for the key
  847. // and let the user specify the hashing function or make the user store
  848. // the hashing procedure with the table
  849. }
  850. { // Parametric polymorphic union
  851. Error :: enum {
  852. Foo0,
  853. Foo1,
  854. Foo2,
  855. Foo3,
  856. };
  857. Para_Union :: union(T: typeid) {T, Error};
  858. r: Para_Union(int);
  859. fmt.println(typeid_of(type_of(r)));
  860. fmt.println(r);
  861. r = 123;
  862. fmt.println(r);
  863. r = Error.Foo0; // r = .Foo0; is allow too, see implicit selector expressions below
  864. fmt.println(r);
  865. }
  866. { // Polymorphic names
  867. foo :: proc($N: $I, $T: typeid) -> (res: [N]T) {
  868. // `N` is the constant value passed
  869. // `I` is the type of N
  870. // `T` is the type passed
  871. fmt.printf("Generating an array of type %v from the value %v of type %v\n",
  872. typeid_of(type_of(res)), N, typeid_of(I));
  873. for i in 0..<N {
  874. res[i] = T(i*i);
  875. }
  876. return;
  877. }
  878. T :: int;
  879. array := foo(4, T);
  880. for v, i in array {
  881. assert(v == T(i*i));
  882. }
  883. // Matrix multiplication
  884. mul :: proc(a: [$M][$N]$T, b: [N][$P]T) -> (c: [M][P]T) {
  885. for i in 0..<M {
  886. for j in 0..<P {
  887. for k in 0..<N {
  888. c[i][j] += a[i][k] * b[k][j];
  889. }
  890. }
  891. }
  892. return;
  893. }
  894. x := [2][3]f32{
  895. {1, 2, 3},
  896. {3, 2, 1},
  897. };
  898. y := [3][2]f32{
  899. {0, 8},
  900. {6, 2},
  901. {8, 4},
  902. };
  903. z := mul(x, y);
  904. assert(z == {{36, 24}, {20, 32}});
  905. }
  906. }
  907. prefix_table := [?]string{
  908. "White",
  909. "Red",
  910. "Green",
  911. "Blue",
  912. "Octarine",
  913. "Black",
  914. };
  915. threading_example :: proc() {
  916. if ODIN_OS == "darwin" {
  917. // TODO: Fix threads on darwin/macOS
  918. return;
  919. }
  920. fmt.println("\n# threading_example");
  921. { // Basic Threads
  922. fmt.println("\n## Basic Threads");
  923. worker_proc :: proc(t: ^thread.Thread) {
  924. for iteration in 1..5 {
  925. fmt.printf("Thread %d is on iteration %d\n", t.user_index, iteration);
  926. fmt.printf("`%s`: iteration %d\n", prefix_table[t.user_index], iteration);
  927. time.sleep(1 * time.Millisecond);
  928. }
  929. }
  930. threads := make([dynamic]^thread.Thread, 0, len(prefix_table));
  931. defer delete(threads);
  932. for in prefix_table {
  933. if t := thread.create(worker_proc); t != nil {
  934. t.init_context = context;
  935. t.user_index = len(threads);
  936. append(&threads, t);
  937. thread.start(t);
  938. }
  939. }
  940. for len(threads) > 0 {
  941. for i := 0; i < len(threads); /**/ {
  942. if t := threads[i]; thread.is_done(t) {
  943. fmt.printf("Thread %d is done\n", t.user_index);
  944. thread.destroy(t);
  945. ordered_remove(&threads, i);
  946. } else {
  947. i += 1;
  948. }
  949. }
  950. }
  951. }
  952. { // Thread Pool
  953. fmt.println("\n## Thread Pool");
  954. task_proc :: proc(t: ^thread.Task) {
  955. index := t.user_index % len(prefix_table);
  956. for iteration in 1..5 {
  957. fmt.printf("Worker Task %d is on iteration %d\n", t.user_index, iteration);
  958. fmt.printf("`%s`: iteration %d\n", prefix_table[index], iteration);
  959. time.sleep(1 * time.Millisecond);
  960. }
  961. }
  962. pool: thread.Pool;
  963. thread.pool_init(pool=&pool, thread_count=3);
  964. defer thread.pool_destroy(&pool);
  965. for i in 0..<30 {
  966. thread.pool_add_task(pool=&pool, procedure=task_proc, data=nil, user_index=i);
  967. }
  968. thread.pool_start(&pool);
  969. thread.pool_wait_and_process(&pool);
  970. }
  971. }
  972. array_programming :: proc() {
  973. fmt.println("\n# array programming");
  974. {
  975. a := [3]f32{1, 2, 3};
  976. b := [3]f32{5, 6, 7};
  977. c := a * b;
  978. d := a + b;
  979. e := 1 + (c - d) / 2;
  980. fmt.printf("%.1f\n", e); // [0.5, 3.0, 6.5]
  981. }
  982. {
  983. a := [3]f32{1, 2, 3};
  984. b := swizzle(a, 2, 1, 0);
  985. assert(b == [3]f32{3, 2, 1});
  986. c := swizzle(a, 0, 0);
  987. assert(c == [2]f32{1, 1});
  988. assert(c == 1);
  989. }
  990. {
  991. Vector3 :: distinct [3]f32;
  992. a := Vector3{1, 2, 3};
  993. b := Vector3{5, 6, 7};
  994. c := (a * b)/2 + 1;
  995. d := c.x + c.y + c.z;
  996. fmt.printf("%.1f\n", d); // 22.0
  997. cross :: proc(a, b: Vector3) -> Vector3 {
  998. i := swizzle(a, 1, 2, 0) * swizzle(b, 2, 0, 1);
  999. j := swizzle(a, 2, 0, 1) * swizzle(b, 1, 2, 0);
  1000. return i - j;
  1001. }
  1002. blah :: proc(a: Vector3) -> f32 {
  1003. return a.x + a.y + a.z;
  1004. }
  1005. x := cross(a, b);
  1006. fmt.println(x);
  1007. fmt.println(blah(x));
  1008. }
  1009. }
  1010. map_type :: proc() {
  1011. fmt.println("\n# map type");
  1012. m := make(map[string]int);
  1013. defer delete(m);
  1014. m["Bob"] = 2;
  1015. m["Ted"] = 5;
  1016. fmt.println(m["Bob"]);
  1017. delete_key(&m, "Ted");
  1018. // If an element of a key does not exist, the zero value of the
  1019. // element will be returned. To check to see if an element exists
  1020. // can be done in two ways:
  1021. elem, ok := m["Bob"];
  1022. exists := "Bob" in m;
  1023. _, _ = elem, ok;
  1024. _ = exists;
  1025. }
  1026. implicit_selector_expression :: proc() {
  1027. fmt.println("\n# implicit selector expression");
  1028. Foo :: enum {A, B, C};
  1029. f: Foo;
  1030. f = Foo.A;
  1031. f = .A;
  1032. BAR :: bit_set[Foo]{.B, .C};
  1033. switch f {
  1034. case .A:
  1035. fmt.println("HITHER");
  1036. case .B:
  1037. fmt.println("NEVER");
  1038. case .C:
  1039. fmt.println("FOREVER");
  1040. }
  1041. my_map := make(map[Foo]int);
  1042. defer delete(my_map);
  1043. my_map[.A] = 123;
  1044. my_map[Foo.B] = 345;
  1045. fmt.println(my_map[.A] + my_map[Foo.B] + my_map[.C]);
  1046. }
  1047. partial_switch :: proc() {
  1048. fmt.println("\n# partial_switch");
  1049. { // enum
  1050. Foo :: enum {
  1051. A,
  1052. B,
  1053. C,
  1054. D,
  1055. };
  1056. f := Foo.A;
  1057. switch f {
  1058. case .A: fmt.println("A");
  1059. case .B: fmt.println("B");
  1060. case .C: fmt.println("C");
  1061. case .D: fmt.println("D");
  1062. case: fmt.println("?");
  1063. }
  1064. #partial switch f {
  1065. case .A: fmt.println("A");
  1066. case .D: fmt.println("D");
  1067. }
  1068. }
  1069. { // union
  1070. Foo :: union {int, bool};
  1071. f: Foo = 123;
  1072. switch in f {
  1073. case int: fmt.println("int");
  1074. case bool: fmt.println("bool");
  1075. case:
  1076. }
  1077. #partial switch in f {
  1078. case bool: fmt.println("bool");
  1079. }
  1080. }
  1081. }
  1082. cstring_example :: proc() {
  1083. fmt.println("\n# cstring_example");
  1084. W :: "Hellope";
  1085. X :: cstring(W);
  1086. Y :: string(X);
  1087. w := W;
  1088. _ = w;
  1089. x: cstring = X;
  1090. y: string = Y;
  1091. z := string(x);
  1092. fmt.println(x, y, z);
  1093. fmt.println(len(x), len(y), len(z));
  1094. fmt.println(len(W), len(X), len(Y));
  1095. // IMPORTANT NOTE for cstring variables
  1096. // len(cstring) is O(N)
  1097. // cast(string)cstring is O(N)
  1098. }
  1099. bit_set_type :: proc() {
  1100. fmt.println("\n# bit_set type");
  1101. {
  1102. using Day :: enum {
  1103. Sunday,
  1104. Monday,
  1105. Tuesday,
  1106. Wednesday,
  1107. Thursday,
  1108. Friday,
  1109. Saturday,
  1110. };
  1111. Days :: distinct bit_set[Day];
  1112. WEEKEND :: Days{Sunday, Saturday};
  1113. d: Days;
  1114. d = {Sunday, Monday};
  1115. e := d | WEEKEND;
  1116. e |= {Monday};
  1117. fmt.println(d, e);
  1118. ok := Saturday in e; // `in` is only allowed for `map` and `bit_set` types
  1119. fmt.println(ok);
  1120. if Saturday in e {
  1121. fmt.println("Saturday in", e);
  1122. }
  1123. X :: Saturday in WEEKEND; // Constant evaluation
  1124. fmt.println(X);
  1125. fmt.println("Cardinality:", card(e));
  1126. }
  1127. {
  1128. x: bit_set['A'..'Z'];
  1129. #assert(size_of(x) == size_of(u32));
  1130. y: bit_set[0..8; u16];
  1131. fmt.println(typeid_of(type_of(x))); // bit_set[A..Z]
  1132. fmt.println(typeid_of(type_of(y))); // bit_set[0..8; u16]
  1133. incl(&x, 'F');
  1134. assert('F' in x);
  1135. excl(&x, 'F');
  1136. assert('F' not_in x);
  1137. y |= {1, 4, 2};
  1138. assert(2 in y);
  1139. }
  1140. {
  1141. Letters :: bit_set['A'..'Z'];
  1142. a := Letters{'A', 'B'};
  1143. b := Letters{'A', 'B', 'C', 'D', 'F'};
  1144. c := Letters{'A', 'B'};
  1145. assert(a <= b); // 'a' is a subset of 'b'
  1146. assert(b >= a); // 'b' is a superset of 'a'
  1147. assert(a < b); // 'a' is a strict subset of 'b'
  1148. assert(b > a); // 'b' is a strict superset of 'a'
  1149. assert(!(a < c)); // 'a' is a not strict subset of 'c'
  1150. assert(!(c > a)); // 'c' is a not strict superset of 'a'
  1151. }
  1152. }
  1153. deferred_procedure_associations :: proc() {
  1154. fmt.println("\n# deferred procedure associations");
  1155. @(deferred_out=closure)
  1156. open :: proc(s: string) -> bool {
  1157. fmt.println(s);
  1158. return true;
  1159. }
  1160. closure :: proc(ok: bool) {
  1161. fmt.println("Goodbye?", ok);
  1162. }
  1163. if open("Welcome") {
  1164. fmt.println("Something in the middle, mate.");
  1165. }
  1166. }
  1167. reflection :: proc() {
  1168. fmt.println("\n# reflection");
  1169. Foo :: struct {
  1170. x: int `tag1`,
  1171. y: string `json:"y_field"`,
  1172. z: bool, // no tag
  1173. };
  1174. id := typeid_of(Foo);
  1175. names := reflect.struct_field_names(id);
  1176. types := reflect.struct_field_types(id);
  1177. tags := reflect.struct_field_tags(id);
  1178. assert(len(names) == len(types) && len(names) == len(tags));
  1179. fmt.println("Foo :: struct {");
  1180. for tag, i in tags {
  1181. name, type := names[i], types[i];
  1182. if tag != "" {
  1183. fmt.printf("\t%s: %T `%s`,\n", name, type, tag);
  1184. } else {
  1185. fmt.printf("\t%s: %T,\n", name, type);
  1186. }
  1187. }
  1188. fmt.println("}");
  1189. for tag, i in tags {
  1190. if val, ok := reflect.struct_tag_lookup(tag, "json"); ok {
  1191. fmt.printf("json: %s -> %s\n", names[i], val);
  1192. }
  1193. }
  1194. }
  1195. quaternions :: proc() {
  1196. // Not just an April Fool's Joke any more, but a fully working thing!
  1197. fmt.println("\n# quaternions");
  1198. { // Quaternion operations
  1199. q := 1 + 2i + 3j + 4k;
  1200. r := quaternion(5, 6, 7, 8);
  1201. t := q * r;
  1202. fmt.printf("(%v) * (%v) = %v\n", q, r, t);
  1203. v := q / r;
  1204. fmt.printf("(%v) / (%v) = %v\n", q, r, v);
  1205. u := q + r;
  1206. fmt.printf("(%v) + (%v) = %v\n", q, r, u);
  1207. s := q - r;
  1208. fmt.printf("(%v) - (%v) = %v\n", q, r, s);
  1209. }
  1210. { // The quaternion types
  1211. q128: quaternion128; // 4xf32
  1212. q256: quaternion256; // 4xf64
  1213. q128 = quaternion(1, 0, 0, 0);
  1214. q256 = 1; // quaternion(1, 0, 0, 0);
  1215. }
  1216. { // Built-in procedures
  1217. q := 1 + 2i + 3j + 4k;
  1218. fmt.println("q =", q);
  1219. fmt.println("real(q) =", real(q));
  1220. fmt.println("imag(q) =", imag(q));
  1221. fmt.println("jmag(q) =", jmag(q));
  1222. fmt.println("kmag(q) =", kmag(q));
  1223. fmt.println("conj(q) =", conj(q));
  1224. fmt.println("abs(q) =", abs(q));
  1225. }
  1226. { // Conversion of a complex type to a quaternion type
  1227. c := 1 + 2i;
  1228. q := quaternion256(c);
  1229. fmt.println(c);
  1230. fmt.println(q);
  1231. }
  1232. { // Memory layout of Quaternions
  1233. q := 1 + 2i + 3j + 4k;
  1234. a := transmute([4]f64)q;
  1235. fmt.println("Quaternion memory layout: xyzw/(ijkr)");
  1236. fmt.println(q); // 1.000+2.000i+3.000j+4.000k
  1237. fmt.println(a); // [2.000, 3.000, 4.000, 1.000]
  1238. }
  1239. }
  1240. unroll_for_statement :: proc() {
  1241. fmt.println("\n#'#unroll for' statements");
  1242. // '#unroll for' works the same as if the 'inline' prefix did not
  1243. // exist but these ranged loops are explicitly unrolled which can
  1244. // be very very useful for certain optimizations
  1245. fmt.println("Ranges");
  1246. #unroll for x, i in 1..<4 {
  1247. fmt.println(x, i);
  1248. }
  1249. fmt.println("Strings");
  1250. #unroll for r, i in "Hello, 世界" {
  1251. fmt.println(r, i);
  1252. }
  1253. fmt.println("Arrays");
  1254. #unroll for elem, idx in ([4]int{1, 4, 9, 16}) {
  1255. fmt.println(elem, idx);
  1256. }
  1257. Foo_Enum :: enum {
  1258. A = 1,
  1259. B,
  1260. C = 6,
  1261. D,
  1262. };
  1263. fmt.println("Enum types");
  1264. #unroll for elem, idx in Foo_Enum {
  1265. fmt.println(elem, idx);
  1266. }
  1267. }
  1268. where_clauses :: proc() {
  1269. fmt.println("\n#procedure 'where' clauses");
  1270. { // Sanity checks
  1271. simple_sanity_check :: proc(x: [2]int)
  1272. where len(x) > 1,
  1273. type_of(x) == [2]int {
  1274. fmt.println(x);
  1275. }
  1276. }
  1277. { // Parametric polymorphism checks
  1278. cross_2d :: proc(a, b: $T/[2]$E) -> E
  1279. where intrinsics.type_is_numeric(E) {
  1280. return a.x*b.y - a.y*b.x;
  1281. }
  1282. cross_3d :: proc(a, b: $T/[3]$E) -> T
  1283. where intrinsics.type_is_numeric(E) {
  1284. x := a.y*b.z - a.z*b.y;
  1285. y := a.z*b.x - a.x*b.z;
  1286. z := a.x*b.y - a.y*b.z;
  1287. return T{x, y, z};
  1288. }
  1289. a := [2]int{1, 2};
  1290. b := [2]int{5, -3};
  1291. fmt.println(cross_2d(a, b));
  1292. x := [3]f32{1, 4, 9};
  1293. y := [3]f32{-5, 0, 3};
  1294. fmt.println(cross_3d(x, y));
  1295. // Failure case
  1296. // i := [2]bool{true, false};
  1297. // j := [2]bool{false, true};
  1298. // fmt.println(cross_2d(i, j));
  1299. }
  1300. { // Procedure groups usage
  1301. foo :: proc(x: [$N]int) -> bool
  1302. where N > 2 {
  1303. fmt.println(#procedure, "was called with the parameter", x);
  1304. return true;
  1305. }
  1306. bar :: proc(x: [$N]int) -> bool
  1307. where 0 < N,
  1308. N <= 2 {
  1309. fmt.println(#procedure, "was called with the parameter", x);
  1310. return false;
  1311. }
  1312. baz :: proc{foo, bar};
  1313. x := [3]int{1, 2, 3};
  1314. y := [2]int{4, 9};
  1315. ok_x := baz(x);
  1316. ok_y := baz(y);
  1317. assert(ok_x == true);
  1318. assert(ok_y == false);
  1319. }
  1320. { // Record types
  1321. Foo :: struct(T: typeid, N: int)
  1322. where intrinsics.type_is_integer(T),
  1323. N > 2 {
  1324. x: [N]T,
  1325. y: [N-2]T,
  1326. };
  1327. T :: i32;
  1328. N :: 5;
  1329. f: Foo(T, N);
  1330. #assert(size_of(f) == (N+N-2)*size_of(T));
  1331. }
  1332. }
  1333. when ODIN_OS == "windows" {
  1334. foreign import kernel32 "system:kernel32.lib"
  1335. }
  1336. foreign_system :: proc() {
  1337. fmt.println("\n#foreign system");
  1338. when ODIN_OS == "windows" {
  1339. // It is sometimes necessarily to interface with foreign code,
  1340. // such as a C library. In Odin, this is achieved through the
  1341. // foreign system. You can “import” a library into the code
  1342. // using the same semantics as a normal import declaration.
  1343. // This foreign import declaration will create a
  1344. // “foreign import name” which can then be used to associate
  1345. // entities within a foreign block.
  1346. foreign kernel32 {
  1347. ExitProcess :: proc "stdcall" (exit_code: u32) ---
  1348. }
  1349. // Foreign procedure declarations have the cdecl/c calling
  1350. // convention by default unless specified otherwise. Due to
  1351. // foreign procedures do not have a body declared within this
  1352. // code, you need append the --- symbol to the end to distinguish
  1353. // it as a procedure literal without a body and not a procedure type.
  1354. // The attributes system can be used to change specific properties
  1355. // of entities declared within a block:
  1356. @(default_calling_convention = "std")
  1357. foreign kernel32 {
  1358. @(link_name="GetLastError") get_last_error :: proc() -> i32 ---
  1359. }
  1360. // Example using the link_prefix attribute
  1361. @(default_calling_convention = "std")
  1362. @(link_prefix = "Get")
  1363. foreign kernel32 {
  1364. LastError :: proc() -> i32 ---
  1365. }
  1366. }
  1367. }
  1368. ranged_fields_for_array_compound_literals :: proc() {
  1369. fmt.println("\n#ranged fields for array compound literals");
  1370. { // Normal Array Literal
  1371. foo := [?]int{1, 4, 9, 16};
  1372. fmt.println(foo);
  1373. }
  1374. { // Indexed
  1375. foo := [?]int{
  1376. 3 = 16,
  1377. 1 = 4,
  1378. 2 = 9,
  1379. 0 = 1,
  1380. };
  1381. fmt.println(foo);
  1382. }
  1383. { // Ranges
  1384. i := 2;
  1385. foo := [?]int {
  1386. 0 = 123,
  1387. 5..9 = 54,
  1388. 10..<16 = i*3 + (i-1)*2,
  1389. };
  1390. #assert(len(foo) == 16);
  1391. fmt.println(foo); // [123, 0, 0, 0, 0, 54, 54, 54, 54, 54, 8, 8, 8, 8, 8]
  1392. }
  1393. { // Slice and Dynamic Array support
  1394. i := 2;
  1395. foo_slice := []int {
  1396. 0 = 123,
  1397. 5..9 = 54,
  1398. 10..<16 = i*3 + (i-1)*2,
  1399. };
  1400. assert(len(foo_slice) == 16);
  1401. fmt.println(foo_slice); // [123, 0, 0, 0, 0, 54, 54, 54, 54, 54, 8, 8, 8, 8, 8]
  1402. foo_dynamic_array := [dynamic]int {
  1403. 0 = 123,
  1404. 5..9 = 54,
  1405. 10..<16 = i*3 + (i-1)*2,
  1406. };
  1407. assert(len(foo_dynamic_array) == 16);
  1408. fmt.println(foo_dynamic_array); // [123, 0, 0, 0, 0, 54, 54, 54, 54, 54, 8, 8, 8, 8, 8]
  1409. }
  1410. }
  1411. deprecated_attribute :: proc() {
  1412. @(deprecated="Use foo_v2 instead")
  1413. foo_v1 :: proc(x: int) {
  1414. fmt.println("foo_v1");
  1415. }
  1416. foo_v2 :: proc(x: int) {
  1417. fmt.println("foo_v2");
  1418. }
  1419. // NOTE: Uncomment to see the warning messages
  1420. // foo_v1(1);
  1421. }
  1422. range_statements_with_multiple_return_values :: proc() {
  1423. // IMPORTANT NOTE(bill, 2019-11-02): This feature is subject to be changed/removed
  1424. fmt.println("\n#range statements with multiple return values");
  1425. My_Iterator :: struct {
  1426. index: int,
  1427. data: []i32,
  1428. };
  1429. make_my_iterator :: proc(data: []i32) -> My_Iterator {
  1430. return My_Iterator{data = data};
  1431. }
  1432. my_iterator :: proc(it: ^My_Iterator) -> (val: i32, idx: int, cond: bool) {
  1433. if cond = it.index < len(it.data); cond {
  1434. val = it.data[it.index];
  1435. idx = it.index;
  1436. it.index += 1;
  1437. }
  1438. return;
  1439. }
  1440. data := make([]i32, 6);
  1441. for _, i in data {
  1442. data[i] = i32(i*i);
  1443. }
  1444. {
  1445. it := make_my_iterator(data);
  1446. for val in my_iterator(&it) {
  1447. fmt.println(val);
  1448. }
  1449. }
  1450. {
  1451. it := make_my_iterator(data);
  1452. for val, idx in my_iterator(&it) {
  1453. fmt.println(val, idx);
  1454. }
  1455. }
  1456. {
  1457. it := make_my_iterator(data);
  1458. for {
  1459. val, _, cond := my_iterator(&it);
  1460. if !cond {
  1461. break;
  1462. }
  1463. fmt.println(val);
  1464. }
  1465. }
  1466. }
  1467. soa_struct_layout :: proc() {
  1468. // IMPORTANT NOTE(bill, 2019-11-03): This feature is subject to be changed/removed
  1469. // NOTE(bill): Most likely #soa [N]T
  1470. fmt.println("\n#SOA Struct Layout");
  1471. {
  1472. Vector3 :: struct {x, y, z: f32};
  1473. N :: 2;
  1474. v_aos: [N]Vector3;
  1475. v_aos[0].x = 1;
  1476. v_aos[0].y = 4;
  1477. v_aos[0].z = 9;
  1478. fmt.println(len(v_aos));
  1479. fmt.println(v_aos[0]);
  1480. fmt.println(v_aos[0].x);
  1481. fmt.println(&v_aos[0].x);
  1482. v_aos[1] = {0, 3, 4};
  1483. v_aos[1].x = 2;
  1484. fmt.println(v_aos[1]);
  1485. fmt.println(v_aos);
  1486. v_soa: #soa[N]Vector3;
  1487. v_soa[0].x = 1;
  1488. v_soa[0].y = 4;
  1489. v_soa[0].z = 9;
  1490. // Same syntax as AOS and treat as if it was an array
  1491. fmt.println(len(v_soa));
  1492. fmt.println(v_soa[0]);
  1493. fmt.println(v_soa[0].x);
  1494. fmt.println(&v_soa[0].x);
  1495. v_soa[1] = {0, 3, 4};
  1496. v_soa[1].x = 2;
  1497. fmt.println(v_soa[1]);
  1498. // Can use SOA syntax if necessary
  1499. v_soa.x[0] = 1;
  1500. v_soa.y[0] = 4;
  1501. v_soa.z[0] = 9;
  1502. fmt.println(v_soa.x[0]);
  1503. // Same pointer addresses with both syntaxes
  1504. assert(&v_soa[0].x == &v_soa.x[0]);
  1505. // Same fmt printing
  1506. fmt.println(v_aos);
  1507. fmt.println(v_soa);
  1508. }
  1509. {
  1510. // Works with arrays of length <= 4 which have the implicit fields xyzw/rgba
  1511. Vector3 :: distinct [3]f32;
  1512. N :: 2;
  1513. v_aos: [N]Vector3;
  1514. v_aos[0].x = 1;
  1515. v_aos[0].y = 4;
  1516. v_aos[0].z = 9;
  1517. v_soa: #soa[N]Vector3;
  1518. v_soa[0].x = 1;
  1519. v_soa[0].y = 4;
  1520. v_soa[0].z = 9;
  1521. }
  1522. {
  1523. // SOA Slices
  1524. // Vector3 :: struct {x, y, z: f32};
  1525. Vector3 :: struct {x: i8, y: i16, z: f32};
  1526. N :: 3;
  1527. v: #soa[N]Vector3;
  1528. v[0].x = 1;
  1529. v[0].y = 4;
  1530. v[0].z = 9;
  1531. s: #soa[]Vector3;
  1532. s = v[:];
  1533. assert(len(s) == N);
  1534. fmt.println(s);
  1535. fmt.println(s[0].x);
  1536. a := s[1:2];
  1537. assert(len(a) == 1);
  1538. fmt.println(a);
  1539. d: #soa[dynamic]Vector3;
  1540. append_soa(&d, Vector3{1, 2, 3}, Vector3{4, 5, 9}, Vector3{-4, -4, 3});
  1541. fmt.println(d);
  1542. fmt.println(len(d));
  1543. fmt.println(cap(d));
  1544. fmt.println(d[:]);
  1545. }
  1546. }
  1547. constant_literal_expressions :: proc() {
  1548. fmt.println("\n#constant literal expressions");
  1549. Bar :: struct {x, y: f32};
  1550. Foo :: struct {a, b: int, using c: Bar};
  1551. FOO_CONST :: Foo{b = 2, a = 1, c = {3, 4}};
  1552. fmt.println(FOO_CONST.a);
  1553. fmt.println(FOO_CONST.b);
  1554. fmt.println(FOO_CONST.c);
  1555. fmt.println(FOO_CONST.c.x);
  1556. fmt.println(FOO_CONST.c.y);
  1557. fmt.println(FOO_CONST.x); // using works as expected
  1558. fmt.println(FOO_CONST.y);
  1559. fmt.println("-------");
  1560. ARRAY_CONST :: [3]int{1 = 4, 2 = 9, 0 = 1};
  1561. fmt.println(ARRAY_CONST[0]);
  1562. fmt.println(ARRAY_CONST[1]);
  1563. fmt.println(ARRAY_CONST[2]);
  1564. fmt.println("-------");
  1565. FOO_ARRAY_DEFAULTS :: [3]Foo{{}, {}, {}};
  1566. fmt.println(FOO_ARRAY_DEFAULTS[2].x);
  1567. fmt.println("-------");
  1568. Baz :: enum{A=5, B, C, D};
  1569. ENUM_ARRAY_CONST :: [Baz]int{.A .. .C = 1, .D = 16};
  1570. fmt.println(ENUM_ARRAY_CONST[.A]);
  1571. fmt.println(ENUM_ARRAY_CONST[.B]);
  1572. fmt.println(ENUM_ARRAY_CONST[.C]);
  1573. fmt.println(ENUM_ARRAY_CONST[.D]);
  1574. fmt.println("-------");
  1575. Partial_Baz :: enum{A=5, B, C, D=16};
  1576. #assert(len(Partial_Baz) < len(#partial [Partial_Baz]int));
  1577. PARTIAL_ENUM_ARRAY_CONST :: #partial [Partial_Baz]int{.A .. .C = 1, .D = 16};
  1578. fmt.println(PARTIAL_ENUM_ARRAY_CONST[.A]);
  1579. fmt.println(PARTIAL_ENUM_ARRAY_CONST[.B]);
  1580. fmt.println(PARTIAL_ENUM_ARRAY_CONST[.C]);
  1581. fmt.println(PARTIAL_ENUM_ARRAY_CONST[.D]);
  1582. fmt.println("-------");
  1583. STRING_CONST :: "Hellope!";
  1584. fmt.println(STRING_CONST[0]);
  1585. fmt.println(STRING_CONST[2]);
  1586. fmt.println(STRING_CONST[3]);
  1587. fmt.println(STRING_CONST[0:5]);
  1588. fmt.println(STRING_CONST[3:][:4]);
  1589. }
  1590. union_maybe :: proc() {
  1591. fmt.println("\n#union #maybe");
  1592. Maybe :: union(T: typeid) #maybe {T};
  1593. i: Maybe(u8);
  1594. p: Maybe(^u8); // No tag is stored for pointers, nil is the sentinel value
  1595. #assert(size_of(i) == size_of(u8) + size_of(u8));
  1596. #assert(size_of(p) == size_of(^u8));
  1597. i = 123;
  1598. x := i.?;
  1599. y, y_ok := p.?;
  1600. p = &x;
  1601. z, z_ok := p.?;
  1602. fmt.println(i, p);
  1603. fmt.println(x, &x);
  1604. fmt.println(y, y_ok);
  1605. fmt.println(z, z_ok);
  1606. }
  1607. dummy_procedure :: proc() {
  1608. fmt.println("dummy_procedure");
  1609. }
  1610. explicit_context_definition :: proc "c" () {
  1611. // Try commenting the following statement out below
  1612. context = runtime.default_context();
  1613. fmt.println("\n#explicit context definition");
  1614. dummy_procedure();
  1615. }
  1616. relative_data_types :: proc() {
  1617. fmt.println("\n#relative data types");
  1618. x: int = 123;
  1619. ptr: #relative(i16) ^int;
  1620. ptr = &x;
  1621. fmt.println(ptr^);
  1622. arr := [3]int{1, 2, 3};
  1623. s := arr[:];
  1624. rel_slice: #relative(i16) []int;
  1625. rel_slice = s;
  1626. fmt.println(rel_slice);
  1627. fmt.println(rel_slice[:]);
  1628. fmt.println(rel_slice[1]);
  1629. }
  1630. main :: proc() {
  1631. when true {
  1632. the_basics();
  1633. control_flow();
  1634. named_proc_return_parameters();
  1635. explicit_procedure_overloading();
  1636. struct_type();
  1637. union_type();
  1638. using_statement();
  1639. implicit_context_system();
  1640. parametric_polymorphism();
  1641. array_programming();
  1642. map_type();
  1643. implicit_selector_expression();
  1644. partial_switch();
  1645. cstring_example();
  1646. bit_set_type();
  1647. deferred_procedure_associations();
  1648. reflection();
  1649. quaternions();
  1650. unroll_for_statement();
  1651. where_clauses();
  1652. foreign_system();
  1653. ranged_fields_for_array_compound_literals();
  1654. deprecated_attribute();
  1655. range_statements_with_multiple_return_values();
  1656. threading_example();
  1657. soa_struct_layout();
  1658. constant_literal_expressions();
  1659. union_maybe();
  1660. explicit_context_definition();
  1661. relative_data_types();
  1662. }
  1663. }