demo.odin 58 KB

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