demo.odin 60 KB

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