demo.odin 61 KB

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