Compare commits

...

801 Commits

Author SHA1 Message Date
gingerBill 784c48c9e3 Redefine how union tag size is calculated to match alignment of the union 2018-11-29 23:00:16 +00:00
gingerBill 008d8f25c8 Fix assertion on union assignment in compound literal 2018-11-29 22:50:08 +00:00
gingerBill 7ffcf34dca Modify how custom alignment is printed for LLVM IR 2018-11-29 22:47:08 +00:00
gingerBill f3a4904f21 Hack: union compound literal fix 2018-11-29 22:23:30 +00:00
gingerBill 3aec78b1d4 Lock on possible race condition in parser 2018-11-29 20:27:48 +00:00
gingerBill a3e6e8d304 Allow single field struct #raw_union 2018-11-29 19:46:45 +00:00
gingerBill a747c03f29 Fix #complete switch on pointers to unions #286 2018-11-29 18:36:45 +00:00
gingerBill 2301ae157c Fix recursive loop bug for is_type_polymorphic 2018-11-28 16:47:20 +00:00
gingerBill d3c7d6d485 Fix #284 2018-11-26 10:55:15 +00:00
gingerBill 9b063ad9a3 Fix poly proc determination by cloning the signature node 2018-11-25 17:57:49 +00:00
gingerBill c2f9bf489e Fix debug information for entities without an associated identifier 2018-11-25 17:31:53 +00:00
gingerBill e496b95881 Subset and superset operators for bit_set: < <= > >= 2018-11-25 16:19:17 +00:00
gingerBill 444f4f446a -vet flag to do basic vetting of code 2018-11-25 14:14:58 +00:00
gingerBill 41ad896f3f Update README.md 2018-11-25 11:21:11 +00:00
gingerBill 0a4b88f9a6 Fix Issue with referencing a polymorphic struct in another package referencing itself #283 2018-11-25 10:35:49 +00:00
gingerBill 4c2f03b1f2 Fix compile time bounds check test 2018-11-23 10:38:17 +00:00
gingerBill 52dcaeb1e9 Fix transmute with cstring and integers 2018-11-22 20:59:24 +00:00
gingerBill f96fbc94c8 v0.9.0 Release 2018-11-22 10:25:01 +00:00
gingerBill bb62bed981 Remove assert that should have never been there 2018-11-22 09:53:08 +00:00
gingerBill bc6b8c5332 Remove dead code 2018-11-22 09:52:25 +00:00
gingerBill 6ab6447791 Fix is_type_polymorphic infinite recursion bug 2018-11-22 09:41:08 +00:00
gingerBill f61c4715c1 Allow opaque to be polymorphic 2018-11-17 10:08:06 +00:00
gingerBill 3061bc8478 Fix error with polymorphic structs #279 2018-11-17 10:05:35 +00:00
gingerBill d035d48c8e Fix issue #280 2018-11-17 09:45:52 +00:00
gingerBill b55b1ffe14 opaque keyword and type 2018-11-11 17:08:30 +00:00
gingerBill 620d5d34f7 Fix issue with complication of -debug that is caused sometimes due to lambda procedures. 2018-11-11 11:44:55 +00:00
gingerBill f9654b6c36 Fix package usage with when on import #278 2018-11-07 16:11:14 +00:00
gingerBill 6659ceb551 Allow comparisons of cstring; Add resize 2018-10-31 10:04:30 +00:00
gingerBill 5aa591d884 Fix debug info issue 2018-10-29 22:16:43 +00:00
gingerBill efe91b1f91 Disable debug info for bit fields 2018-10-29 18:10:44 +00:00
gingerBill 7c99884afb Fix CompositeType for zero length arrays 2018-10-29 12:52:41 +00:00
gingerBill dfd7a194ed Fix big int shifts of 0 2018-10-28 09:32:59 +00:00
gingerBill 2ddb27869b Built-in procedure #defined 2018-10-27 18:44:28 +01:00
gingerBill 5c608b01ba Place optimization level flag in condition again; -memcpyopt -die only in non-debug builds 2018-10-24 10:19:01 +01:00
gingerBill 2bd85e764e Merge pull request #260 from lachsinc/master
[WIP] Provide llvm with more debug info (for Visual Studio debugger support)
2018-10-24 09:40:05 +01:00
gingerBill 822e4894f2 Minor logic change for reserved package names 2018-10-20 21:19:40 +01:00
gingerBill ce2e23849e Fix context initialization 2018-10-20 16:34:56 +01:00
gingerBill 099995e7dd Add basics for context-based Logger 2018-10-20 13:02:30 +01:00
gingerBill 72f4186b21 Fix atomic.odin 2018-10-20 12:55:48 +01:00
gingerBill 3742d9e7e9 Move atomic intrinsics to the new built-in package intrinsics 2018-10-20 10:44:02 +01:00
gingerBill 4ac1218bf8 sync atomics "wrapper" procedures 2018-10-17 21:43:05 +01:00
gingerBill b171cc41e6 __atomic_* "intrinsics" using LLVM instructions 2018-10-17 21:16:01 +01:00
gingerBill efc3a9e69d Merge pull request #274 from hazeycode/fix/245
Use name of source file as output_name
2018-10-17 15:29:56 +01:00
gingerBill 307c58d908 Fix compilation error #272 2018-10-17 15:27:36 +01:00
Chris Heyes ae02e9c34a Use name of source file as output_name 2018-10-16 23:56:19 +01:00
Chris Heyes 139fa55c27 Merge pull request #1 from hazeycode/fix/272
Fix syntax error in core/os/os_linux.odin
2018-10-16 19:30:02 +01:00
Chris Heyes 562bb6e4c4 Fix syntax error in core/os/os_linux.odin 2018-10-15 21:24:42 +01:00
gingerBill ef2931d4a5 Remove AstTypeType 2018-10-13 14:07:00 +01:00
gingerBill 2d4aa2be6d Remove type as being a keyword 2018-10-13 14:04:34 +01:00
gingerBill 42b42db675 Add unimplemented and unreachable procedures; make os.exit a diverging procedure 2018-10-13 13:19:52 +01:00
gingerBill 73e9dbbf8c switch on typeid with type cases 2018-10-13 11:07:56 +01:00
gingerBill 0971a59493 Update runtime printing code 2018-10-11 18:19:29 +01:00
gingerBill 627c91124a Merge pull request #271 from Breush/267-bugfix-linux-heap-alloc-zero
Fixed heap alloc not allowing empty structs on Linux
2018-10-09 21:49:14 +01:00
Alexis Breust 4eba717281 Fixed heap alloc not allowing empty structs on Linux - Fixes #267 2018-10-09 08:34:48 +02:00
gingerBill 9623e5e032 Merge pull request #270 from Breush/263-bugfix-leading-zeros-count
Replaced __builtin_clz by long long version
2018-10-08 09:39:43 +01:00
Alexis Breust 805cc48f03 Replaced __builtin_clz by long long version - Fixes #268 2018-10-08 08:23:50 +02:00
lachsinc d894fb3708 Cleanup comments. 2018-10-06 09:09:12 +10:00
lachsinc b6ca913cff Cleanup hack as all types appear to be handled!.. 2018-10-06 08:58:39 +10:00
lachsinc 39db428603 Add complex debug info. 2018-10-05 17:10:58 +10:00
lachsinc 992502f03b Add debug info for proc ptrs. 2018-10-05 16:49:48 +10:00
lachsinc edc3a9392a Cleanup. 2018-10-05 15:03:13 +10:00
lachsinc f881ebd007 Cleanup unused AllProcs. 2018-10-05 14:51:08 +10:00
lachsinc 11ea03d2e8 Tuple debug info (untested). Generated locals now flow through debug info. 2018-10-05 14:33:39 +10:00
lachsinc 99b4d59f44 Add arg # for proc param locals. 2018-10-05 12:57:06 +10:00
lachsinc dfeefc5179 Fix dgb.declare using different location to it's associated instructions. 2018-10-05 12:46:53 +10:00
lachsinc ab46406f4d Fix debug info for unnamed aggregate types. 2018-10-05 12:27:36 +10:00
lachsinc 48ad147818 Cleanup; Move enums/globals di inside CompileUnit. Minor comment cleanup. 2018-10-04 14:09:17 +10:00
lachsinc 79d49f1955 Lexical block debug info. 2018-10-04 13:43:52 +10:00
lachsinc 1ccc8700e4 bit_set / bit_field debug info. 2018-10-02 10:06:48 +10:00
lachsinc f38d70a235 Cleanup. 2018-10-01 01:21:15 +10:00
lachsinc b37b7a0f72 Cleanup. 2018-10-01 01:10:22 +10:00
lachsinc f8d7f42208 Minor cleanup. 2018-10-01 00:17:42 +10:00
lachsinc db0756a119 Stepping working. Cleanup. 2018-10-01 00:02:41 +10:00
gingerBill 1a4e25f141 Prefix runtime procedures 2018-09-29 21:09:19 +01:00
lachsinc 79ade6ac7b Add various debug location stuff. 2018-09-30 04:47:21 +10:00
lachsinc ecce1d9974 Add debug location stack. 2018-09-30 04:24:24 +10:00
gingerBill 834308d8ce Fix using import override "bug" 2018-09-29 13:07:46 +01:00
lachsinc 9e73189d63 Tagged union debug info. Aggregate type fixes (unions inside structs etc.). 2018-09-27 21:50:57 +10:00
lachsinc 11bddf270c Cleanup debug info 'name' stuff. 2018-09-27 18:34:59 +10:00
lachsinc 0818a272e2 Cleanup hardcoded bytes to bits 2018-09-27 17:55:37 +10:00
lachsinc 9750b1162a Cleanup. 2018-09-27 01:34:15 +10:00
lachsinc 3106aaaa3d Fix pointers to all things debug info. Cleanup param order. Make scope/file optional for relevent types. 2018-09-27 00:02:35 +10:00
lachsinc d31d4c9bd6 (Basic) Map debug info support. Minor slice fix. 2018-09-26 07:51:16 +10:00
lachsinc 6993777d36 Slices. Fix dynamic array data ptr size. 2018-09-26 06:04:33 +10:00
lachsinc 54c044ee09 Add support for any. Fix rawptr debug type. 2018-09-26 05:43:58 +10:00
lachsinc 2e5cecf9e6 Cleanup dynamic array/string bloat. 2018-09-26 04:01:16 +10:00
lachsinc 7acb49eefb Cleanup comments/todos. 2018-09-26 02:17:05 +10:00
lachsinc 0f6c1f3482 Add debug info for globals. Misc debug info cleanup. 2018-09-26 02:01:03 +10:00
lachsinc 1ee0fe7457 Add DebugInfoArray as separate debug info type. Minor cleanup of various debug infos. 2018-09-25 21:24:15 +10:00
gingerBill 1a18481d8b Fix context assignment with selector expressions 2018-09-24 12:04:26 +01:00
gingerBill 28c61c0f5d Merge branch 'master' of https://github.com/odin-lang/Odin 2018-09-24 10:22:33 +01:00
gingerBill 597fb452b1 Minor fixes 2018-09-24 10:22:22 +01:00
lachsinc 5961a63880 Expose dynamic array data/len/cap debug info. Minor cleanup of odin string debug info. 2018-09-19 13:16:56 +10:00
lachsinc cce5e595e5 String debug info. Minor cleanup of derived / composite debug info output. 2018-09-19 01:52:08 +10:00
lachsinc e7d72f6848 Static array debug info. Temporary dynamic array debug info (pointer to data, no len/cap info provided yet). 2018-09-18 23:21:44 +10:00
lachsinc 7dcad45e0d Add proper procedure type support (return types and param proc signature) 2018-09-18 21:28:28 +10:00
lachsinc 3772ea6ae1 Enum debug info support. 2018-09-18 20:12:36 +10:00
lachsinc 2cc2eb1ec0 Fix stepping/jumping between procedures/files. 2018-09-18 18:10:03 +10:00
lachsinc 8a789e33b0 Remove llc/opt hack. XX.bc now contains useful debug info thanks to removal of optimization flags in debug builds. 2018-09-18 14:17:43 +10:00
lachsinc 2f86f8f8e0 Provide llvm ir with more debug info (for Visual Studio debugger support). 2018-09-18 10:50:56 +10:00
gingerBill 02f9a27f46 Merge pull request #264 from lunaticLipid/master
Remove reference to the runtime package within itself
2018-09-16 22:26:34 +01:00
Lipid 6cb605a025 Remove reference to the runtime package within itself 2018-09-16 08:19:33 +02:00
gingerBill 9f3e42e4ef Fix delete_key #262 2018-09-15 11:21:02 +01:00
gingerBill 71d987bd2e Fix runtime proc names; Change calling convention of context parameter 2018-09-15 10:46:46 +01:00
gingerBill 637899467c Merge branch 'master' of https://github.com/odin-lang/Odin 2018-09-15 10:14:40 +01:00
gingerBill 5bdb424c6b context.allocator = a; Remove __ from runtime procs; improve division for complex numbers 2018-09-15 10:14:24 +01:00
gingerBill c62cfddb9c Merge pull request #263 from hasenj/master
fix macos thread_count value
2018-09-14 17:48:34 +01:00
Hasen Judy 14a4c28f8f fix macos thread_count value 2018-09-15 01:46:50 +09:00
gingerBill f1e1814ff9 Syntactic sugar for anonymous enum within a bit set 2018-09-11 12:10:32 +01:00
gingerBill b468cf141b Fix are_types_identical for bit_set 2018-09-11 11:14:46 +01:00
gingerBill 787ea1feba Fix polymorphic constant parameters for procedures 2018-09-11 11:09:42 +01:00
gingerBill 91477e9e69 Allow for optional ok for return 2018-09-11 10:55:30 +01:00
gingerBill cfd0dfd2bf Remove assertion from constant parameter 2018-09-10 21:56:16 +01:00
gingerBill 46b1868185 Constant polymorphic names 2018-09-10 14:21:19 +01:00
gingerBill 4c4de1d6c4 Fix cloning of auto_cast Ast 2018-09-10 08:50:20 +01:00
gingerBill c8b30de771 Update compiler flags for build.bat 2018-09-09 15:06:04 +01:00
gingerBill 4f3837f0e6 Procedure inlining on call site 2018-09-09 14:46:28 +01:00
gingerBill 76848e8807 Disallow inline for recursive procedures 2018-09-09 13:58:23 +01:00
gingerBill 12902821d6 Make diverging procedure types different from ones without a return type 2018-09-09 13:48:33 +01:00
gingerBill f5549f6bde Make panic a diverging procedure 2018-09-08 12:17:16 +01:00
gingerBill 3825eab989 Diverging procedures proc() -> ! (no return) 2018-09-08 12:16:03 +01:00
gingerBill 3cd6ae311d Parametric polymorphic union type 2018-09-08 12:02:25 +01:00
gingerBill 26cfc0257d Fix array_ordered_remove typo 2018-09-08 10:44:18 +01:00
Ginger Bill 1d31eabb6e Fix minor parsing issue for polymorphic identifiers 2018-09-04 13:47:24 +01:00
Joshua Mark Manton 8cd2797b2e Fixed core library bugs after recent changes. (#257)
* Fix `delete_map` calling `delete_dynamic_array` instead of `delete_slice for its hashes.

* Removed print statements from `__dynamic_map_rehash`
2018-09-02 22:18:32 +02:00
gingerBill 11f5236434 Add $T: typeid/[]$E; Deprecate T: type/[]$E
`type` as a keyword will soon be removed in favour of polymorphic names (identifiers) in procedures
2018-09-02 16:33:54 +01:00
gingerBill 220485a2d2 typeid as keyword (ready to implement polymorphic name parameters) 2018-09-02 15:56:36 +01:00
gingerBill eb274cf316 Remove test code 2018-08-30 19:33:16 +01:00
gingerBill aa542980ce Change memory layout of map to be 3 words smaller 2018-08-30 19:14:10 +01:00
gingerBill e0240c186f Rename buffer entity 2018-08-30 12:53:07 +01:00
gingerBill ae58502a21 Make free_all built-in 2018-08-30 12:21:16 +01:00
gingerBill 6a3697279c Place assertf and printf to package fmt 2018-08-30 12:10:16 +01:00
gingerBill c19ec5d65d Fix delete for dynamic array and map 2018-08-30 12:00:51 +01:00
gingerBill 15dca449c9 Add assertf and panicf 2018-08-30 11:46:57 +01:00
gingerBill dda985f49d Add extra nil check for assert and panic 2018-08-30 11:16:06 +01:00
gingerBill 12256beeb2 Prevent other parameters being the default value 2018-08-30 11:12:57 +01:00
gingerBill 0858ae2024 Add utf8_to_ucs2 for package win32 so that the wide procedures can used by default 2018-08-30 10:59:46 +01:00
gingerBill 6c18864291 Add default_assertion_failure_proc to the minimum dependency build 2018-08-29 21:15:11 +01:00
gingerBill ae57284912 Add Assertion_Failure_Proc to context 2018-08-29 21:10:13 +01:00
gingerBill 001837e6bb Temporary allocator for context 2018-08-29 19:55:55 +01:00
gingerBill 28523f17e2 Add default allocator to allocation related procedures e.g. alloc, free, delete, make 2018-08-28 20:14:56 +01:00
gingerBill ae2af8315e Allow for default parameters that are non-constant entities, but not any non-constant expression 2018-08-28 20:03:27 +01:00
gingerBill adbb3bb75f Add -lld flag for using "bin\lld-link.exe" on Windows 2018-08-28 19:28:34 +01:00
gingerBill 6181c4edb3 Update 2018-08-28 19:26:05 +01:00
gingerBill 830c194da5 Allow enums for array lengths 2018-08-26 18:23:17 +01:00
gingerBill 1830c1e57c Allow bitwise operation on enums 2018-08-26 18:05:59 +01:00
gingerBill e5735af6d6 Disable for in over cstring 2018-08-26 15:10:23 +01:00
gingerBill a6b0ae71b2 Remove assert 2018-08-26 10:56:33 +01:00
gingerBill 3365baee8f runtime.Typeid_Bit_Field layout to store more information into the typeid 2018-08-25 12:11:48 +01:00
gingerBill cc88dd0b71 Allow for variadic min max procs
Request #252
2018-08-25 11:12:52 +01:00
gingerBill f050bfe872 Fix comparisons with union 2018-08-25 10:39:19 +01:00
gingerBill ab71acc3a5 Disable abs for arrays #254 2018-08-25 10:27:44 +01:00
gingerBill 0a85d1af6b Improve error messages for using on fields 2018-08-24 22:28:00 +01:00
gingerBill 68adadb01a Allow using in structs on arrays with count <= 4 2018-08-24 22:12:30 +01:00
gingerBill d56f458d11 Fix file scope #assert 2018-08-24 17:42:13 +01:00
gingerBill a65eadee63 Fix for in enum iteration 2018-08-22 18:56:41 +01:00
gingerBill 16dfae62bc Allow casting to and from rawptr and cstring #249 2018-08-22 15:19:04 +01:00
gingerBill fe680a8b1f Fix default return values #250 2018-08-22 15:17:29 +01:00
gingerBill 54fe9f3eb1 Improve min dep for min/max/abs/clamp 2018-08-21 21:43:38 +01:00
gingerBill cbc6c2666b Improve proc group scoring algorithm 2018-08-21 14:11:18 +01:00
gingerBill a4d0ac1802 Merge branch 'master' of https://github.com/odin-lang/Odin 2018-08-20 19:20:44 +01:00
gingerBill 0dc29a7208 Implement suggestions from #247 2018-08-20 19:20:28 +01:00
gingerBill a9321bc73f Update README.md 2018-08-20 10:27:48 +01:00
gingerBill e3f0ab7c3d Parallelize parser on *nix 2018-08-19 10:58:57 +01:00
gingerBill 5643ea1ba2 Fix typo 2018-08-19 10:56:23 +01:00
gingerBill 3b6523fbd9 Fix gbMutex for *nix 2018-08-19 10:34:31 +01:00
gingerBill ffc4f01470 All enums in array indices 2018-08-17 19:38:15 +01:00
gingerBill e326f41d16 Fix demo 2018-08-17 15:26:29 +01:00
gingerBill 1d0ac72e4a Disable non-comparison operations for enum (use bit_set for flags) 2018-08-17 15:24:44 +01:00
gingerBill b216e44870 Add underlying type for bit_set 2018-08-17 15:11:41 +01:00
gingerBill 7d39b26cf4 Minor refactor 2018-08-16 20:52:46 +01:00
gingerBill 884d5fed9f bit_set['A'..'Z'], bit_set[0..8] 2018-08-16 15:16:57 +01:00
gingerBill ec84188597 Fix typos in parser 2018-08-16 10:30:44 +01:00
gingerBill 85ac95f81b Constant evaluation for in expression for bit_sets 2018-08-16 00:07:26 +01:00
gingerBill 042550cf87 Fix default value bug 2018-08-15 19:36:32 +01:00
gingerBill b3ebff715a Fix defer ir bug 2018-08-15 15:44:41 +01:00
gingerBill 1ee60663bb Fix issue #244 with constant array comparisons 2018-08-14 19:43:36 +01:00
gingerBill 59da98d3f0 Improve type hinting for compound literals 2018-08-14 19:39:28 +01:00
gingerBill 2d41a42f61 Cleaning type hinting for assignments 2018-08-14 19:33:42 +01:00
gingerBill e1e4a916a5 Fix demo and improve type hinting 2018-08-14 19:29:31 +01:00
gingerBill 71f94bff76 Minor sanity features for bit_set 2018-08-14 19:22:48 +01:00
gingerBill c7d6467cfa Fix assigning issue for bit sets 2018-08-14 18:43:47 +01:00
gingerBill 79a3c0b36c Fix bit_set range 2018-08-14 18:35:14 +01:00
gingerBill 966249c10a bit_set constants 2018-08-14 18:32:34 +01:00
gingerBill acc010cba5 Add bit_set type 2018-08-14 17:07:56 +01:00
gingerBill 89f4e7a8db -no-crt flag for windows amd64 2018-08-13 01:22:14 +01:00
gingerBill 55f4eabecd Fix map addressing mode bug 2018-08-10 18:22:37 +01:00
gingerBill d0fc9aa069 Allow for '\"' 2018-08-10 17:48:29 +01:00
gingerBill 8be9b5082c Fix default make parameters for dynamic arrays 2018-08-09 18:15:49 +01:00
gingerBill 708907df31 auto_cast for named parameters 2018-08-09 17:59:18 +01:00
gingerBill 70586b1cf8 auto_cast prefix for procedure parameters 2018-08-09 17:58:11 +01:00
gingerBill 877a78d6ba Fix make error messages 2018-08-08 23:07:51 +01:00
gingerBill 3928614326 Merge pull request #241 from thebirk/fix-sh-main-not-found
Fixed 'sh: main: command not found' error on linux.
2018-08-08 22:41:42 +01:00
thebirk 5e5f5bfa8d Fixed 'sh: main: command not found' error on linux. 2018-08-08 17:48:17 +02:00
gingerBill 3a1a7b40f9 Add runtime messages for make for the len/cap parameters 2018-08-08 13:04:40 +01:00
gingerBill 835d7dcab2 make as a user-level procedure rather than a built-in procedure 2018-08-08 13:04:40 +01:00
gingerBill 28816dc491 Fix parenthesis warning on clang 2018-08-08 13:04:40 +01:00
gingerBill ccdc3438be Refactor handle_parameter_value code 2018-08-06 00:26:38 +01:00
gingerBill 60711dd355 Refactor default parameter values 2018-08-05 23:57:34 +01:00
gingerBill fad3947e26 Add *with_allocator procedures to mem 2018-08-05 23:40:19 +01:00
gingerBill d8e5b2d1a4 Fix cstring cast operation 2018-08-05 19:07:03 +01:00
gingerBill 2d26ad0226 Remove opengl package 2018-08-05 19:01:15 +01:00
gingerBill 45d3c6c0d3 Fix cstring to string conversion 2018-08-05 18:58:35 +01:00
gingerBill c6bffd7c35 Change build.bat to use release_mode=1 by default 2018-08-05 10:37:09 +01:00
gingerBill 462d81430c Fix map runtime issue regarding erasing a key 2018-08-05 10:31:20 +01:00
gingerBill d3cada5bd6 Change rules for how context and defer interact 2018-08-04 23:46:46 +01:00
gingerBill cdbf831a7a Replace context <- c {} with context = c;. context assignments are scope based 2018-08-04 23:14:55 +01:00
gingerBill 0718f14774 Reduce number of range and slice operators #239
Replace .. and ... with : and ..
2018-08-01 21:34:59 +01:00
gingerBill a6fe656f21 foreign import x {"foo.lib", "bar.lib"} 2018-07-29 20:56:09 +01:00
gingerBill dc5da7933a Add older demos 2018-07-29 11:36:24 +01:00
gingerBill 96fc9138d4 Do using Foo :: enum at the type_decl stage 2018-07-29 11:29:20 +01:00
gingerBill 6512a3e5f2 using Foo :: enum {A, B, C}; len(Foo) 2018-07-29 10:50:15 +01:00
gingerBill 49f2124df0 Support larger integer literals to work with the new BigInt system 2018-07-29 10:22:17 +01:00
gingerBill a11d6e696a expand_to_tuple for fixed arrays 2018-07-28 20:56:27 +01:00
gingerBill 1705ba8069 Fix typos 2018-07-28 19:44:00 +01:00
gingerBill 8d2c4a78a1 Merge pull request #238 from odin-lang/big-int
Big int
2018-07-28 18:39:15 +01:00
gingerBill 8504ff920b Correctly handle bitwise operations for negative BigInt 2018-07-28 18:36:45 +01:00
gingerBill e34a9e6185 Fix big_int_shr 2018-07-28 00:48:36 +01:00
gingerBill c3c7834246 BigInt support in the constant system 2018-07-28 00:41:31 +01:00
gingerBill 1ab40d8600 Merge pull request #237 from lunaticLipid/master
Add mat3_mul and generic transpose to math.odin
2018-07-17 08:25:21 +01:00
Lipid 92ce02dab0 Fix indent characters 2018-07-16 20:30:49 +02:00
Lipid 8abe9ef507 Add mat3_mul and generic transpose to math.odin 2018-07-16 20:27:29 +02:00
gingerBill d0e04bf569 Merge pull request #236 from hasenj/master
Fix build errors on osx
2018-07-14 19:39:11 +01:00
Hasen Judy b92599879a free -> delete in os_osx and os_linux 2018-07-13 11:25:46 -06:00
gingerBill 0e91298fd1 Rename free to delete for non pointer types 2018-07-08 11:03:56 +01:00
gingerBill e515220694 Improve array arithmetic inlining 2018-07-08 10:15:46 +01:00
gingerBill a55683d287 Remove allocator parameters in ir.cpp 2018-07-07 11:29:45 +01:00
gingerBill fa4e95105f Loop array arithmetic on large arrays 2018-07-07 11:13:20 +01:00
gingerBill 1e01085ef7 Merge branch 'master' of https://github.com/odin-lang/Odin 2018-07-07 08:12:48 +01:00
gingerBill 04a1f869b5 Fix when statements within a foreign block 2018-07-07 08:11:31 +01:00
Morten Vassvik e04ba7530d Updated makefile to run demo package instead of demo.odin 2018-07-05 15:48:55 +02:00
Morten Vassvik ea055f1465 Surrounded explicit link paths (.a and .so) and the exe path for 'odin run' in quotes, so that it works in paths containing characters that must be escaped (like spaces) 2018-07-05 15:46:11 +02:00
Morten Vassvik 3b2c867817 Replaced CLOCK_PROCESS_CPUTIME_ID with CLOCK_MONOTONIC in calls to clock_gettime and clock_getres to make timings on calling external executables accurate instead of showing them taking negligible time on linux. 2018-07-04 21:04:48 +02:00
gingerBill 3de23eb0bf Merge pull request #233 from zangent/master
Make macOS builds work again
2018-07-02 08:57:22 +01:00
Zachary Pierson 5de3b07e2b Made os_osx.odin use the new-style runtime.args__ and added read_directory for macOS 2018-07-02 02:50:08 -05:00
gingerBill c0ca4d4635 Uncomment code 2018-07-01 18:31:31 +01:00
gingerBill efe4b71bae Fix build.sh 2018-07-01 17:17:31 +01:00
gingerBill bc37bd5429 Merge branch 'packages' of https://github.com/odin-lang/Odin into packages 2018-07-01 17:14:43 +01:00
gingerBill 5f20e04259 Fix on *nix 2018-07-01 17:14:22 +01:00
gingerBill 9bef5ec01a Fix anonymous procedures 2018-07-01 16:21:32 +01:00
gingerBill cdf873542b Add read_directory for linux 2018-06-21 08:39:52 +01:00
gingerBill 4742690dec Fix is_excluded_target_filename 2018-06-21 08:39:07 +01:00
gingerBill 3a16f1e854 Minor style change 2018-06-17 22:25:28 +01:00
gingerBill 877400dd12 Scope to use flags rathers than booleans 2018-06-17 22:22:30 +01:00
gingerBill a4e3201113 Minor cleanup for builtin scope/pkg 2018-06-17 22:07:27 +01:00
gingerBill a99cc2fd70 Clean up import lookup code 2018-06-17 21:50:40 +01:00
gingerBill 5fe4c33d0e Allow importation of core:builtin to get built-in entities 2018-06-17 21:46:37 +01:00
gingerBill 4d9d38cc28 Move TypeAndValue to Ast from Map 2018-06-17 16:35:22 +01:00
gingerBill 5b71ffd4f9 Rename clone_ast_node to clone_ast 2018-06-17 11:03:26 +01:00
gingerBill c2ca24a486 Big renaming: AstNode to Ast 2018-06-17 10:58:59 +01:00
gingerBill e5aff6fd6d Minimize AstNode size 2018-06-17 10:48:50 +01:00
gingerBill 3eb8aa8268 Modify CommentGroup parsing 2018-06-17 10:29:20 +01:00
gingerBill 6d1c32eb77 Add escape code for ESC \e 2018-06-15 23:13:26 +01:00
gingerBill ba776a3c9f Fix bitwise not for signed integers 2018-06-15 23:01:12 +01:00
gingerBill cd7e260f4e Fix cyclic polymorphic procedure usage and improve its error message 2018-06-15 22:49:06 +01:00
gingerBill ba67e474d3 Make source code compile with 32 bit (but not build 32 bit code) 2018-06-15 21:46:03 +01:00
gingerBill b92a8c513e Modify how build settings are handled 2018-06-15 21:38:22 +01:00
gingerBill 13572aeef0 Fix gb.h 2018-06-15 20:26:39 +01:00
gingerBill 5081ea1a0c Fix type aliasing comparison; Fix gb_utf8_decode 2018-06-15 19:59:35 +01:00
gingerBill e9e7ce2606 Allow .allocator for dynamic arrays; Add mem.Pool 2018-06-12 19:10:14 +01:00
gingerBill 915dcb0c28 Fix min dependency check 2018-06-11 22:57:40 +01:00
gingerBill 8236c6d4b7 Allow for base enum type with an enum declaration 2018-06-11 22:50:13 +01:00
gingerBill 555fe37ad8 Remove the need for a look ahead 2018-06-11 18:06:58 +01:00
gingerBill 881f667558 Change how context <- is parsed to remove the need for a look-ahead 2018-06-11 18:02:04 +01:00
gingerBill 0a99595efe Remove using in stuff 2018-06-11 17:34:57 +01:00
gingerBill 268491b224 Use global arena for AstNode allocations 2018-06-09 19:53:06 +01:00
gingerBill 49ea9ed722 Entity aliasing clean up 2018-06-09 10:08:17 +01:00
gingerBill d7108416c9 Remove dead code 2018-06-07 23:52:13 +01:00
gingerBill b136630856 Fix type info generation for empty structs 2018-06-07 23:24:37 +01:00
gingerBill fa6f31186a Merge pull request #228 from shuaDev/shwadev-packages
Fix some core lib errors on packages branch
2018-06-03 21:09:57 +01:00
gingerBill b027b1d60f Fix min type info for polymorphic procedures and named types 2018-06-03 21:09:08 +01:00
Joshua Mark Manton 7ed1d931cb fix quick_sort_proc calling quick_sort instead of recursively calling itself 2018-06-03 11:27:57 -07:00
Joshua Mark Manton 2570296b01 fix core opengl ODIN_OS reference and pointer math stuff 2018-06-03 11:25:46 -07:00
Joshua Mark Manton f0a4526250 Fix alloc.odin using old raw file 2018-06-03 11:22:42 -07:00
gingerBill c39332c7e7 Revert name mangling 2018-06-03 19:18:47 +01:00
gingerBill 3f4b6b22dc Change our IR name mangling rules 2018-06-03 17:55:13 +01:00
gingerBill e0549df03e Fix minor possible issue 2018-06-03 17:44:10 +01:00
gingerBill e46662a546 Rename os.default_allocator to os.heap_allocator 2018-06-03 16:40:58 +01:00
gingerBill 360a74e2fe Merge pull request #226 from BrettRToomey/packages
Dsymutil fixes
2018-06-03 16:35:43 +01:00
Brett R. Toomey 597c4591bc Merge branch 'packages' of github.com:odin-lang/Odin into packages 2018-06-03 17:13:11 +02:00
Brett R. Toomey 80833ed703 Dsymutil fixes for macOS 2018-06-03 17:12:30 +02:00
gingerBill 106302189c Use gbString for opt_flags 2018-06-03 16:09:24 +01:00
gingerBill 05c5f98e8e Add -debug-compile parameter for llc 2018-06-03 15:55:14 +01:00
gingerBill d556fa2cd8 Remove special shared scope for runtime stuff 2018-06-03 15:06:40 +01:00
gingerBill 9bd7f023b2 Split up init_preload into specific parts 2018-06-03 11:38:02 +01:00
gingerBill 398109ac84 Remove need for __llvm_core 2018-06-03 10:51:43 +01:00
gingerBill 12b870ba66 Use const & for Array<AstNode *> parameters 2018-06-03 10:30:31 +01:00
gingerBill 6202fb8373 Re-allow when statements at the file scope 2018-06-02 19:44:34 +01:00
gingerBill ced818ad54 Remove dead code from checker 2018-06-02 11:58:35 +01:00
gingerBill ccbb6df749 Handle multiple +build package tags with '!' (nots) 2018-05-28 21:25:08 +01:00
gingerBill 6eb505a677 Comment based build tags for packages (basic and temporary) 2018-05-28 20:59:06 +01:00
gingerBill 619783ca1b Remove clutter parameters and begin parallelizing the type checker 2018-05-28 18:46:39 +01:00
gingerBill 642aa0bc4b Refactor: use CheckerContext rather than Checker in type checking part 2018-05-28 15:57:53 +01:00
gingerBill 45b3067068 Remove tmp_allocator from Checker 2018-05-28 14:15:08 +01:00
gingerBill b7858a66b9 Parallelize per file rather than per package 2018-05-28 12:06:50 +01:00
gingerBill 4e203feaf4 Change import lookup 2018-05-27 23:46:08 +01:00
gingerBill a513b47780 Remove unused packages 2018-05-27 23:33:10 +01:00
gingerBill 547a2831c7 Clean up name mangling by using unique package names per project 2018-05-27 22:09:11 +01:00
gingerBill 5c52ffe24e Reorganize runtime package 2018-05-27 21:22:25 +01:00
gingerBill a5763d6fee Err on empty directory packages 2018-05-27 14:12:10 +01:00
gingerBill 95482c554d Fix build.bat 2018-05-27 13:53:46 +01:00
gingerBill 10758710d4 Fix demo.odin 2018-05-27 13:53:19 +01:00
gingerBill 86cf9383ea Fix delayed assert collection 2018-05-27 13:49:55 +01:00
gingerBill 307977d4cf Remove dead code 2018-05-27 13:30:18 +01:00
gingerBill 1beff539d7 Single file "main" file 2018-05-27 13:22:24 +01:00
gingerBill df578d6ec5 Allow for either .odin file or directory as the initial start 2018-05-27 11:40:27 +01:00
gingerBill 6aae381e83 Move ODIN_* platform constants to core:os 2018-05-27 11:03:46 +01:00
gingerBill 7ee9051a56 IR now builds with the new package system 2018-05-27 10:49:14 +01:00
gingerBill eb11edabe0 Add file scopes for the packages 2018-05-27 00:10:38 +01:00
gingerBill c067b90403 Add basic package support (no IR support yet) 2018-05-26 23:12:55 +01:00
gingerBill 5b6770f3d2 Parse directories to be packages 2018-05-21 20:47:52 +01:00
gingerBill 718b80ba39 Fix demo for removing default struct values 2018-05-20 17:39:49 +01:00
gingerBill 4d052d5119 Remove code relating to default struct values 2018-05-20 17:31:46 +01:00
gingerBill 7e4c643401 Disable default struct field values; Update README.md 2018-05-20 16:00:39 +01:00
gingerBill e920338f21 Remove old dependency 2018-05-20 08:58:48 +01:00
gingerBill af2048570c Merge pull request #222 from shuaDev/master
added compiler command for only parsing and typechecking
2018-05-17 10:33:23 +01:00
Joshua Mark Manton 1ee4f849cb now return 1 if there were errors 2018-05-17 02:08:04 -07:00
Joshua Mark Manton 703393fc63 whitespace 2018-05-16 23:08:01 -07:00
Joshua Mark Manton 81420ab246 removed unneeded block 2018-05-16 23:07:27 -07:00
Joshua Mark Manton c94d19718b added compiler command for only parsing and typechecking 2018-05-16 23:03:05 -07:00
gingerBill e25c72ecdd Fix #219 and #220 2018-05-14 17:05:52 +01:00
gingerBill 780b81a59f Allow for NO_DEFAULT_STRUCT_VALUES
(will decide later if I want them or not)
2018-05-13 21:09:49 +01:00
gingerBill 9f1dda701d Comment out test 2018-05-13 18:43:21 +01:00
gingerBill e597a8d72e Fix issues with exact integer bounds and remove dead code 2018-05-13 17:38:35 +01:00
gingerBill de9a4b5164 Disable pointer arithmetic 2018-05-13 16:10:02 +01:00
gingerBill 319aca3101 Merge pull request #218 from hasenj/osx-timing
Fix timing on macos
2018-05-13 11:45:05 +01:00
Hasen Judy 9dc2c01aaa Fix timing on macos 2018-05-13 19:33:08 +09:00
gingerBill 6164672421 Change FreeAll to Free_All 2018-05-13 10:14:32 +01:00
gingerBill 61906613b0 Add typeid to Type_Info struct 2018-05-13 10:09:21 +01:00
gingerBill 3b48fa8e7d Fix default initialized values for globals (#217) 2018-05-12 21:22:39 +01:00
gingerBill 324b7d65e7 Use __type_info_of internally 2018-05-12 20:17:12 +01:00
gingerBill 373a60b9ef type_info_of allows typeid; typeid_of allows ^Type_Info; Otherwise only allow type 2018-05-12 19:54:16 +01:00
gingerBill 2ef22e86e0 Make any use typeid rather than ^Type_Info 2018-05-12 18:40:49 +01:00
gingerBill 830f4f540f typeid 2018-05-12 17:39:04 +01:00
gingerBill 56ff5496bc Minimal Type Info Dependency handling 2018-05-12 16:53:44 +01:00
gingerBill 20fbece14c Change semantics for distinctness for pointers, arrays, dynamic arrays, and maps. 2018-05-12 10:47:32 +01:00
gingerBill 9fbfd86cde Add log to math.odin 2018-05-12 10:46:00 +01:00
gingerBill 7547bc66cf Complete remove all non required preload stuff from min dep and only use what is used. 2018-05-12 10:38:40 +01:00
gingerBill 18a9fa7355 Improve minimal dependency system 2018-05-12 10:27:55 +01:00
gingerBill b32af841c5 Merge branch 'master' of https://github.com/odin-lang/Odin 2018-05-06 15:31:32 +01:00
gingerBill 66b4252931 Fix #210 2018-05-06 15:31:18 +01:00
gingerBill 2c95eaa418 Merge pull request #216 from lunaticLipid/master
Fix copy-and-forget in math.odin
2018-05-02 19:40:59 +01:00
Lipid 7382f52dc9 Fix copy-and-forget in math.odin 2018-05-02 18:04:50 +02:00
gingerBill 49dd299999 Merge pull request #204 from ThisDrunkDane/master
Added more function to windows.odin
2018-04-14 19:45:00 +01:00
Mikkel Hjortshoej e391b05513 Merge branch 'master' of github.com:ThisDrunkDane/Odin 2018-04-13 22:39:17 +02:00
Mikkel Hjortshoej 2de62910fc Added more function to windows.odin 2018-04-13 22:38:58 +02:00
gingerBill fc77b5b4ac Try to fix internal compiler error in #208 2018-04-10 21:03:51 +01:00
gingerBill a83d916fad Fix immutable context to any assignment #214 2018-04-10 20:51:44 +01:00
gingerBill e71a641379 Fix internal compiler error trigger for issue #212 2018-04-10 20:46:32 +01:00
gingerBill e2eca45188 Fix race condition caused by parallelized parser: #211 2018-04-10 20:35:05 +01:00
gingerBill 4d78540658 Fix #210 2018-04-10 20:20:33 +01:00
gingerBill b83c3f265b Fix #209 #assert bug 2018-04-10 20:18:16 +01:00
gingerBill 30f5a3bb93 Move cycle checking to much earlier on in the semantic stage 2018-03-23 20:48:30 +00:00
gingerBill 2e1e1e6034 Type caching 2018-03-23 16:35:41 +00:00
gingerBill 991479fbf9 Remove allocator parameter to types.cpp functions 2018-03-23 16:01:23 +00:00
gingerBill 5660f98cc3 Merge branch 'master' of https://github.com/odin-lang/Odin 2018-03-23 15:23:31 +00:00
gingerBill 5bf0f9d630 Fix type cycle bug 2018-03-23 15:23:14 +00:00
Mikkel Hjortshoej 15b72119eb Added more function to windows.odin 2018-03-21 19:30:27 +01:00
gingerBill dc30e7a200 Merge pull request #201 from nakst/master
update essence bindings
2018-03-11 20:52:58 +00:00
Nakst db2293144a update essence bindings 2018-03-10 21:33:59 +00:00
gingerBill 5016f45429 Merge pull request #200 from nakst/master
fix compile warnings on linux
2018-03-10 20:50:46 +00:00
Nakst 9fa4aa40b7 fix compile warnings on linux 2018-03-10 20:29:43 +00:00
gingerBill 52f60c706a Merge pull request #199 from ThisDrunkDane/resource
Resource Compiler calling
2018-03-10 13:42:25 +00:00
gingerBill fff4ead96a Fix gb_alloc_str_len 2018-03-07 20:36:15 +00:00
Mikkel Hjortshoej 3574341b6b Missing .rc error message 2018-03-05 13:10:01 +01:00
Mikkel Hjortshoej cbabc80d92 Calls rc.exe if -resource specified 2018-03-05 11:46:50 +01:00
gingerBill f4cf88c2ca Move os_*.odin files to os/ 2018-03-04 11:38:49 +00:00
gingerBill 6db95b554f __args__: []cstring 2018-03-04 11:25:23 +00:00
gingerBill 105de7705a Add unselector_expr 2018-03-04 11:06:59 +00:00
gingerBill 584dffea14 Remove dead code; fix referencing of a type assertion in a selector expression 2018-03-04 09:25:02 +00:00
gingerBill 41b6d215bb Fix using determination order 2018-03-03 20:07:12 +00:00
gingerBill 9274f29ca9 deprecated attribute for procedure declarations 2018-03-03 11:16:48 +00:00
gingerBill 08c87e57f8 Remove cwd in odin run for Linux 2018-03-03 10:26:25 +00:00
gingerBill b21cdd5037 Merge branch 'master' of https://github.com/odin-lang/Odin 2018-03-03 10:25:13 +00:00
gingerBill 63ab8b2418 Make irGen.output_base use full path rather than relative 2018-03-03 10:23:27 +00:00
Morten Vassvik cb7a343caf Fixed '_alloc_command_line_arguments()' in os_linux.odin to use the new cstrings, and made 'odin run' use the full executable path. 2018-03-01 12:58:57 +01:00
gingerBill 40542e6e26 Fix comparison against nil for cstring 2018-02-28 12:01:26 +00:00
gingerBill 9da05dd4cb Update core library with cstring 2018-02-28 11:44:41 +00:00
gingerBill ae9da0abfb Merge branch 'master' of https://github.com/odin-lang/Odin 2018-02-28 11:20:31 +00:00
gingerBill d3ea334e7a cstring 2018-02-28 11:20:11 +00:00
gingerBill d76132a3fb Merge pull request #198 from ThisDrunkDane/terminate_thread
Added terminate_thread to thread.odin
2018-02-26 10:06:08 +00:00
gingerBill 223c473cf6 Demo fix 2018-02-25 20:57:34 +00:00
gingerBill fd57cfa1ae Fix build_settings.cpp 2018-02-25 20:52:06 +00:00
gingerBill f23bd2dc27 Revert demo 2018-02-25 20:46:32 +00:00
gingerBill 69062ba3ab More code tidying with Array 2018-02-25 20:24:38 +00:00
gingerBill e75563cb32 Minor code rearrangement 2018-02-25 19:42:12 +00:00
gingerBill d63885a495 array_make 2018-02-25 19:23:52 +00:00
gingerBill f28a34fa99 Use Array<irValue *> in ir.cpp 2018-02-25 15:31:00 +00:00
gingerBill a1e8de4e00 Fix ir_emit_slice_bounds_check 2018-02-25 15:11:20 +00:00
gingerBill d247ba4751 Hexadecimal floats for "perfect values" 0h42f60000 == 123; use bit_cast in compiler 2018-02-25 15:09:16 +00:00
gingerBill 27b7dc336a Change parsing for floats and disallow x.0 2018-02-25 14:36:41 +00:00
gingerBill 60a7c68aa6 Minor code reorganization 2018-02-25 14:23:45 +00:00
Mikkel Hjortshoej 78c103e62c Merge branch 'terminate_thread' of github.com:ThisDrunkDane/Odin into terminate_thread 2018-02-25 14:57:22 +01:00
Mikkel Hjortshoej ffec1c77f2 Added terminate_thread to thread.odin 2018-02-25 14:56:50 +01:00
gingerBill 5357181484 Multithreaded parser (windows only) 2018-02-25 13:45:44 +00:00
Mikkel Hjortshoej 33ddb3ad4d Added terminate_thread to thread.odin 2018-02-25 14:38:55 +01:00
gingerBill 1cd453db14 Remove unneeded disabled warnings for MSVC 2018-02-25 12:29:48 +00:00
gingerBill 3b5932699c Fix #assert in opengl.odin 2018-02-25 12:14:35 +00:00
gingerBill bada81159d Add #no_bounds_check to __dynamic_map_* procedures 2018-02-25 12:13:45 +00:00
gingerBill 652da98c70 Fix slice bounds checking 2018-02-25 12:10:19 +00:00
gingerBill e14e2c3b4d -out and generate executable in the current working directory 2018-02-25 11:49:44 +00:00
gingerBill f96a897821 Make switch in f { valid 2018-02-25 10:55:18 +00:00
gingerBill b74ae77745 Merge pull request #197 from bpunsky/context-bug-fix
Context bug fix
2018-02-25 00:13:02 +00:00
Brendan Punsky 564226be02 fixed issues with uninitialized contexts
also, `any_to_bytes` I think, and maybe some bindings in `core:sys/windows.odin`
2018-02-24 18:58:22 -05:00
Brendan Punsky f6c45fc68a Merge remote-tracking branch 'origin/master' 2018-02-24 14:29:30 -05:00
gingerBill 35ba5771a5 Replace compile_assert with #assert 2018-02-24 19:03:29 +00:00
gingerBill b2461f7192 Fix issue #195 2018-02-24 18:19:11 +00:00
Brendan Punsky 60a54f404b Auto stash before merge of "master" and "origin/master" 2018-02-22 20:11:17 -05:00
gingerBill 921f261377 Fix os.args on Windows #143 2018-02-22 21:34:09 +00:00
gingerBill d70a555c1c Fix issue #192 2018-02-22 21:24:38 +00:00
gingerBill 4c339360e9 auto_cast 2018-02-18 15:14:13 +00:00
gingerBill 731dad480d Fix issue regarding nullptr Type * 2018-02-18 14:37:58 +00:00
gingerBill a0f2357cb3 Minor fix to demo 2018-02-17 19:40:33 +00:00
gingerBill e86ac75e9c Merge branch 'master' of https://github.com/odin-lang/Odin 2018-02-17 19:24:15 +00:00
gingerBill f51de2e488 Disallow #complete switch ranges 2018-02-17 19:24:02 +00:00
gingerBill 5efefdcf16 Merge pull request #189 from ThisDrunkDane/master
Pretty readme header
2018-02-17 19:16:51 +00:00
gingerBill cabb2bb992 Commit 1000 🎉🎂 2018-02-17 19:15:58 +00:00
gingerBill d560f6c920 Fix compile time issue regarding switch ranges 2018-02-17 19:05:14 +00:00
gingerBill 21432ba96e Clean up range code for switch 2018-02-17 18:34:14 +00:00
gingerBill c341597657 Remove constant from switch for strings 2018-02-17 18:22:43 +00:00
Mikkel Hjortshøj 2a1420d4e7 Update README.md 2018-02-17 15:03:26 +01:00
Mikkel Hjortshoej 28d88f6af4 rounded logo 2018-02-17 15:03:16 +01:00
gingerBill c4d2d287fc #complete switch; Removal of dyncall 2018-02-17 11:54:08 +00:00
gingerBill 6a85546b76 Fix #187 2018-02-14 21:46:39 +00:00
gingerBill 2e92d0c821 Remove old procedures 2018-02-13 22:05:25 +00:00
gingerBill a499a3aa5e Merge pull request #184 from ThisDrunkDane/master
Added widechar versions of functions, plus cursor functions
2018-02-13 22:02:43 +00:00
gingerBill 23ab3c4713 Replace [...] with [?] 2018-02-13 21:59:49 +00:00
gingerBill da300aa9c3 Fix enum #export does not work with export #185 2018-02-13 18:01:42 +00:00
ThisDrunkDane e225158a6f Merge branch 'master' of https://github.com/odin-lang/Odin 2018-02-12 06:07:15 +01:00
gingerBill 2ce55783d2 Fix make 2018-02-11 23:47:46 +00:00
gingerBill 14eeee40b2 Update demo.odin 2018-02-11 11:16:17 +00:00
gingerBill 038dea9202 v0.8.1
Fix initialization values for variables
2018-02-11 11:15:53 +00:00
gingerBill 0ae3484171 Fix zero value initialization in IR 2018-02-11 11:13:52 +00:00
gingerBill 54976c3249 v0.8.0 2018-02-09 18:03:06 +00:00
Mikkel Hjortshoej 4c06b44315 Merge branch 'master' of github.com:odin-lang/odin 2018-02-07 21:23:28 +01:00
Mikkel Hjortshoej 678b58e0b1 Added widechar versions of functions, plus cursor functions 2018-02-07 21:17:59 +01:00
gingerBill 8f913c656c Fix error reporting for assignment to a built-in procedure (#183) 2018-02-07 18:55:01 +00:00
gingerBill 001b48a5c6 Change local variable alignment to 16 bytes for the time being 2018-02-05 23:27:18 +00:00
gingerBill 54929a1b92 Minor context fix 2018-02-05 23:09:34 +00:00
gingerBill 92780e2683 distinct keyword for type declarations 2018-02-05 22:46:30 +00:00
gingerBill 2891988d3b Add extra check to ir_emit_zero_init 2018-02-05 22:26:22 +00:00
gingerBill c1728914c6 Fix typos #type_alias 2018-02-04 21:34:45 +00:00
gingerBill ed2f49e8d2 Remove dead code; Fix issue regarding order of evaluation of function parameters (in C++) depending on the compiler (clang vs gcc vs msvc) 2018-02-04 20:07:05 +00:00
gingerBill 8a76a370a9 Merge pull request #182 from ThisDrunkDane/master
Functions, structs and constants related to getting file notifications
2018-02-04 19:49:04 +00:00
Mikkel Hjortshoej 1160fd4331 functions, structs and constants related to getting file notifications 2018-02-03 21:56:15 +01:00
gingerBill 0134c38759 Fix issue #181 2018-02-03 10:32:47 +00:00
gingerBill d079095517 Fix bug #179 2018-02-03 10:27:33 +00:00
gingerBill 028d628e9f Add extra zero init for IR 2018-01-31 18:27:08 +00:00
gingerBill 5e4b62acfe Fix literal 2018-01-28 15:59:37 +00:00
gingerBill 9366fa8e95 Simplify printing for float and complex types 2018-01-28 15:58:34 +00:00
gingerBill 369db3a8e3 Add __print_type to runtime 2018-01-28 15:55:37 +00:00
gingerBill 8c360b2a3c Reduce type info data size in IR 2018-01-28 15:43:58 +00:00
gingerBill b66e7bed45 Improve min-dep for Type Info 2018-01-28 15:37:15 +00:00
gingerBill e919482aa8 Add ir_emit_store_union_variant to reduce alloca use 2018-01-28 15:09:07 +00:00
gingerBill dce45e7d58 Add ODIN_DEBUG 2018-01-28 14:42:22 +00:00
gingerBill 1a0877e965 Fix minimum dependency generation for foreign entities 2018-01-28 14:39:18 +00:00
gingerBill 0361a18551 Remove old math constants 2018-01-28 11:59:28 +00:00
gingerBill 83d90f1463 Extra check for type_info cycle checking 2018-01-28 09:51:52 +00:00
gingerBill f661ae9d09 Fix issue with proc group cycles #176 2018-01-28 09:19:23 +00:00
gingerBill bee4cb57f2 Fix printf bug #177 2018-01-28 09:13:29 +00:00
gingerBill 53b670b889 Merge branch 'master' of https://github.com/odin-lang/Odin 2018-01-28 08:59:31 +00:00
gingerBill e2600a3e44 Fix #178 2018-01-28 08:59:10 +00:00
gingerBill 25101b2ae0 Merge pull request #175 from ThisDrunkDane/windows.odin-adds
More file handling functions
2018-01-25 14:02:32 +00:00
Mikkel Hjortshoej 4e7867fcc1 More file handling functions 2018-01-25 00:00:34 +01:00
gingerBill 101ee64165 Merge pull request #174 from ThisDrunkDane/windows.odin-adds
Added stuff to windows.odin
2018-01-24 09:41:09 +00:00
Mikkel Hjortshoej 4c3e65791e added stuff to windows.odin 2018-01-24 07:26:29 +01:00
gingerBill a9c8031b61 Fix sync_windows.odin 2018-01-21 21:21:57 +00:00
gingerBill afb3033913 Change thread.odin to use a rawptr rather than any 2018-01-21 21:19:03 +00:00
gingerBill 2ad26640a2 Revert back to gb_memmove 2018-01-21 19:30:05 +00:00
gingerBill 2c0b08145f Fix nested defer blocks 2018-01-21 19:26:55 +00:00
gingerBill aa9c9eda9e Fix boolean casting 2018-01-21 18:41:21 +00:00
gingerBill 1353d61894 Minor parsing change 2018-01-21 16:45:29 +00:00
gingerBill 88ba6d8015 enum #export 2018-01-21 14:30:48 +00:00
gingerBill 8b288a2072 Reimplement opt stage 2018-01-20 16:16:59 +00:00
gingerBill 4e90644527 Remove timing for llvm-opt 2018-01-20 16:15:05 +00:00
gingerBill 6651b65373 Remove need for opt 2018-01-20 16:13:36 +00:00
gingerBill 705352099f Remove #endif 2018-01-20 16:10:26 +00:00
gingerBill 2e28c9d793 Cache type size/align; Improve speed of ir_print.cpp 2018-01-20 15:12:44 +00:00
gingerBill 2fe660a1d7 Fix empty union IR bug 2018-01-19 17:11:28 +00:00
gingerBill b03ce0e9b4 Modify implicit semicolon rules 2018-01-18 17:28:07 +00:00
gingerBill 386f5f596d Change to HeapAlloc et al on Windows 2018-01-18 13:11:51 +00:00
gingerBill add53228b2 -no-bounds-check 2018-01-18 12:22:27 +00:00
gingerBill d90008cc52 Add basic debug information needed for stepping over code 2018-01-18 12:12:18 +00:00
gingerBill dbf8f9ab38 Add extra comments for clarity 2018-01-17 21:22:45 +00:00
gingerBill 81a99cf67b Debug fix target triple and procedure positioning 2018-01-17 20:57:54 +00:00
gingerBill 876af6fb02 Modify boolean conversion in IR 2018-01-17 19:27:13 +00:00
gingerBill b3734a5f77 Add math/rand.odin 2018-01-17 19:09:22 +00:00
gingerBill 419ab6f00c Named return value act as variables; Code reorganization 2018-01-17 19:07:38 +00:00
gingerBill 5558b55e9f Fix ir_emit_store for booleans 2018-01-17 14:06:06 +00:00
gingerBill 4b14d608f4 Update sys/windows.odin to use Bool :: b32; rather than i32 2018-01-17 14:02:19 +00:00
gingerBill 9428d86f2b Specific sized booleans: b8, b16, b32, b64 2018-01-17 14:00:49 +00:00
gingerBill ddebf0daf2 Merge branch 'master' of https://github.com/odin-lang/Odin 2018-01-17 13:16:59 +00:00
gingerBill 3a44c62ecf Remove old "macro" parsing code 2018-01-17 13:16:43 +00:00
gingerBill 184efd4f49 Update demo for using in 2018-01-13 22:42:05 +00:00
gingerBill 6b3c4cc379 Remove u128 and i128 2018-01-13 22:26:37 +00:00
gingerBill 0b137e087c Fix mem.odin #173 2018-01-12 11:44:09 +00:00
gingerBill 37790c13a0 Fix issue #170 2018-01-10 21:17:09 +00:00
gingerBill 82057f08ce Fix issue #172 2018-01-10 21:13:20 +00:00
gingerBill 1553421e1a Fix typo in error 2018-01-01 22:15:43 +00:00
gingerBill f3ea109e6f Fix min/max for floats 2018-01-01 11:41:32 +00:00
gingerBill 90dbfe7660 Fix issue #167 regarding abs, min, and, max for floats 2017-12-27 20:35:50 +00:00
gingerBill 125bad3154 Fix 'llvm bool' emit store 2017-12-23 09:46:28 +00:00
gingerBill 30c83d6c81 Fix map internals 2017-12-23 09:30:40 +00:00
gingerBill 4f12c118a5 Fix Type info bug for 'llvm bool' 2017-12-23 09:06:49 +00:00
gingerBill 423775d50e Merge branch 'master' of https://github.com/odin-lang/Odin 2017-12-22 18:14:50 +00:00
gingerBill 860a5c3e86 "Fix" LLVM boolean bug (more like a bodge) 2017-12-22 18:14:35 +00:00
gingerBill 649e02f209 Add basic example to README.md 2017-12-22 11:29:33 +00:00
gingerBill b449305cc1 Fix free_map 2017-12-21 21:05:53 +00:00
gingerBill 49bee6bad0 Fix free_map 2017-12-21 21:01:28 +00:00
gingerBill ac277a1cce Revert map to be a value type and not a reference type
(Implement code for "const ref" parameters)
2017-12-21 20:59:23 +00:00
gingerBill a17310a83c Fix len, cap, comparison against nil for map 2017-12-18 20:43:02 +00:00
gingerBill b509946b13 Fix fallthrough within a nested block 2017-12-17 21:55:20 +00:00
gingerBill a69ea58388 map is internally backed by a pointer (i.e. a "reference type") 2017-12-17 19:25:35 +00:00
gingerBill 30530d058c Remove struct #ordered 2017-12-17 14:53:40 +00:00
gingerBill 436928d06a Fix "using in import" 2017-12-17 12:12:24 +00:00
gingerBill 32a502d14e using x in bar; 2017-12-17 11:44:26 +00:00
gingerBill 0d665c637f using in importation statements 2017-12-17 11:17:54 +00:00
gingerBill 1b6a14ac39 Fix lhs < rhs bug (#164) 2017-12-14 19:56:32 +00:00
gingerBill 367013f589 Change Map and PtrSet grow rate 2017-12-12 23:39:20 +00:00
gingerBill c980a30bad Merge branch 'checker-optimizations' into explicit-overloading
# Conflicts:
#	examples/demo.odin
2017-12-12 21:22:46 +00:00
gingerBill 78b459590c Print nil for nil procedures in fmt.odin 2017-12-12 21:21:55 +00:00
gingerBill 054e241033 Localize checker data 2017-12-12 20:23:36 +00:00
gingerBill f7e9649be4 Disable struct field reordering (for the time being) 2017-12-12 18:21:40 +00:00
gingerBill fd1f6ec75c Merge branch 'master' into explicit-overloading 2017-12-11 11:13:22 +00:00
gingerBill 6b0d7cb26c Fix issue #162 regarding empty unions 2017-12-11 11:08:02 +00:00
gingerBill 3aea08df78 Change how abs, min, max, and clamp are implemented for floats 2017-12-11 11:06:43 +00:00
gingerBill 3c6f90e552 Fix proc groups from import names 2017-12-10 11:35:11 +00:00
gingerBill 3703ca4df4 Explicit procedure group; Remove implicit procedure overloading 2017-12-09 18:11:36 +00:00
gingerBill 41b8281c73 Set type of a procedure grouping to nullptr 2017-12-06 11:13:00 +00:00
gingerBill acd1f83bd0 Fix procedure groupings 2017-12-06 11:11:53 +00:00
gingerBill ba8371104d Set procedure grouping type to t_invalid 2017-12-06 11:01:52 +00:00
gingerBill 991682e9fd Fix write_entire_file 2017-12-06 10:58:02 +00:00
gingerBill f0de994059 Make core library use procedure groupings rather than normal overloading 2017-12-04 22:01:51 +00:00
gingerBill ebb2a9812c Merge pull request #160 from thebirk/patch-1
Added skip for Entity_ProcedureGrouping
2017-12-04 15:07:09 +00:00
Aleksander Birkeland 265c05927f Added skip for Entity_ProcedureGrouping 2017-12-04 16:05:42 +01:00
gingerBill 05ad38ae2d Fix procedure grouping 2017-12-03 23:19:25 +00:00
gingerBill 596a2c8355 Procedure grouping foo :: proc[foo16, foo32]; 2017-12-03 23:03:40 +00:00
gingerBill 9f52b2c283 Update demo.odin 2017-12-03 22:28:54 +00:00
gingerBill 8035a407a6 Remove dead code 2017-12-03 20:59:48 +00:00
gingerBill 97760c3fa4 Fix union_tag_size; Fix constant array of array literal printing with scalar contents 2017-12-03 20:49:19 +00:00
gingerBill d75291097e &x.(type) 2017-11-30 23:09:21 +00:00
gingerBill db632b7e22 buffer_from_slice 2017-11-30 20:42:16 +00:00
gingerBill 1a75dfe075 Remove vector type (will be replaced by something else in the future) 2017-11-30 20:34:42 +00:00
gingerBill e00d88d82e Fix issue #157 2017-11-30 19:53:40 +00:00
gingerBill 04cce1826b Fix map IR bug 2017-11-28 23:46:01 +00:00
gingerBill cc28cda053 Fix issue #156 2017-11-28 22:49:34 +00:00
gingerBill cfabc0e61f Remove using in arrays; Remove _ non-exported struct fields
Start determining slow parts of the compiler
2017-11-28 22:12:33 +00:00
gingerBill 91b534d128 Fix transmute 2017-11-27 23:00:23 +00:00
gingerBill 3268f43340 Update ABI for basic types 2017-11-27 20:37:09 +00:00
gingerBill 05e374934d Change proc ABI for Odin specific types 2017-11-27 20:18:06 +00:00
gingerBill 3e1ff0ec67 Update fmt for runes; Add strings.contains_rune 2017-11-26 23:54:23 +00:00
gingerBill 65945dac09 Fix comparison against nil for slices 2017-11-26 22:49:31 +00:00
gingerBill 1608da2dc8 for key, val in some_map {}; for val, idx in some_array {} 2017-11-26 18:56:47 +00:00
gingerBill c340827381 Remove old slice procedures 2017-11-26 18:38:46 +00:00
gingerBill 74fa7ca25d New slice memory layout (ptr+len); byte 2017-11-26 18:36:46 +00:00
gingerBill 5a9223afda nil_allocator; Fix IR type checking assert; append_string 2017-11-26 15:25:45 +00:00
gingerBill febcd73323 Fix merge from essence cross compile #154 2017-11-26 11:11:29 +00:00
gingerBill df06236076 Merge pull request #154 from nakst/master
essence cross compile
2017-11-26 11:10:13 +00:00
Nakst b0d3fbba47 essence cross compile 2017-11-26 11:03:11 +00:00
gingerBill adb6c7637e Fix 'fallthrough' 2017-11-25 11:16:23 +00:00
gingerBill 425f83b17d Merge pull request #150 from zangent/master
Changed `string_has_extension` to `string_ends_with` and fix macOS target triple
2017-11-21 22:33:39 +00:00
gingerBill 976415ff9d Fix key lookup of pointer to map 2017-11-21 22:32:41 +00:00
Zachary Pierson 4d7fb3e8d6 Changed string_has_extension to string_ends_with.
Fixed macOS target triple.
2017-11-21 16:16:53 -06:00
gingerBill bcca3bf322 Remove target triple from windows 2017-11-19 16:55:24 +00:00
gingerBill 74aaa3408f Fix debug symbol generation 2017-11-19 16:45:12 +00:00
gingerBill 2a5beee88c Remove /SYMBOLS flag 2017-11-19 15:11:07 +00:00
gingerBill cec9f7abfe Add -debug command (still in development) 2017-11-19 15:06:56 +00:00
gingerBill 284a9cd4c3 Update usage text 2017-11-19 09:57:37 +00:00
gingerBill 5955c101d4 Update version 2017-11-19 09:56:51 +00:00
gingerBill f80b910ba3 Set version number to v0.7.1 2017-11-19 09:50:22 +00:00
gingerBill 2b0521347b Begin with on debugging symbol; fix version number 0.7.0 2017-11-19 09:49:55 +00:00
gingerBill 0c06a8d154 Fix issue #146 regarding polymorphic type parameters 2017-11-18 20:56:53 +00:00
gingerBill b0e3a4e276 build_dll replace with -build-mode=dll 2017-11-17 20:21:58 +00:00
gingerBill b651466630 Add ptr_to_bytes 2017-11-16 19:01:57 +00:00
gingerBill 24c09c9201 Allow for printf style assert and panic 2017-11-16 18:57:03 +00:00
gingerBill e48346a9ee Disable negation of unsigned constants (Issue: #145) 2017-11-15 21:25:16 +00:00
gingerBill 9bd8bdaa5a Disable all cyclic importations 2017-11-13 23:53:01 +00:00
gingerBill a137699d95 Add optional truncate parameter to write_entire_file (#144) 2017-11-13 20:35:21 +00:00
gingerBill f6a56c2f82 Remove #const; Minor fixes 2017-11-12 20:15:17 +00:00
gingerBill dffa791607 In error messages, remove with '; Fix error messages for switch` 2017-11-12 19:00:48 +00:00
gingerBill 5ce6555721 Allow for default arguments after a variadic parameter 2017-11-12 17:55:16 +00:00
gingerBill 53b3ad186f Fix untyped type IR bug 2017-11-10 22:37:38 +00:00
gingerBill 82c1c5b3fe Merge pull request #142 from zangent/master
Added static linking for macOS, too. There's literally %number% of us!
2017-11-10 22:14:40 +00:00
Zachary Pierson 6d880bc3bb Added static linking for macOS. Also fixed the build.sh. Thanks, vass :/ 2017-11-10 16:11:55 -06:00
gingerBill 40281d595d Fix parsing errors for variadic signatures 2017-11-10 22:03:05 +00:00
gingerBill 85fab55e57 Fix make 2017-11-10 21:43:37 +00:00
gingerBill 1d2eb8055e Merge pull request #140 from vassvik/master
Fixed foreign import for linux. Modified .gitignore to ignore temp files and files in shared/. Added a Makefile for linux
2017-11-10 21:17:16 +00:00
vassvik 9e0b69312b Fixed foreign import for linux. Modified .gitignore to ignore temp files and files in shared/. Added a Makefile for linux 2017-11-10 21:31:13 +01:00
gingerBill bbddbba340 Fix cast to uintptr 2017-11-10 18:56:47 +00:00
gingerBill 0d01a6f552 Fix issue #139 2017-11-10 18:24:49 +00:00
gingerBill ae3672608d Fix link_name overriding 2017-11-09 23:36:10 +00:00
gingerBill e5c39fb2a9 Fix opening file without close; Minor fixes 2017-11-09 22:58:44 +00:00
gingerBill eb4b3f5976 Change push allocator system; update core libraries 2017-11-09 22:48:00 +00:00
gingerBill dbb070524f Allow nil in a ternary statement 2017-11-09 21:10:08 +00:00
gingerBill 36b0b50ba4 Amend allocation procedures with caller location; Compound literals missing type can determine type in certain cases. 2017-11-09 20:51:13 +00:00
gingerBill ac46b2053d Remove unnecessary IR bound checks 2017-11-08 22:14:07 +00:00
gingerBill 0ffcccdae5 Add Source_Code_Location parameter Allocator_Proc (#138) 2017-11-08 22:05:51 +00:00
gingerBill 4777bd607e Fix issue #137 2017-11-08 22:02:15 +00:00
gingerBill 39e9b50482 Remove debug code 2017-11-07 23:09:05 +00:00
gingerBill 30adb9c770 Fix issue #134 2017-11-07 23:05:39 +00:00
gingerBill b1d1497f4b Fix array of array arithmetic 2017-11-07 23:02:53 +00:00
gingerBill 9df3a94d33 Fix cyclic type checking bug 2017-11-05 23:38:09 +00:00
gingerBill d4f335d068 Fix fmt.odin %#v fancy printing 2017-11-05 19:47:18 +00:00
gingerBill 74341b9b74 Fix IR generation issue 2017-11-05 19:37:46 +00:00
gingerBill 66ee2cb6ed #const value procedure parameters; $N for polymorphic array lengths 2017-11-05 18:26:24 +00:00
gingerBill 1d4881cbbe Add array programming 2017-11-05 14:22:18 +00:00
gingerBill 04b917a60a More code clean up 2017-11-04 10:53:47 +00:00
gingerBill e6c99cd289 Cleanup attribute handling 2017-11-04 10:26:56 +00:00
gingerBill 6bc5584add Fix fmt printing uintptr type 2017-11-04 00:16:54 +00:00
gingerBill 121f0185d6 Custom thread local models 2017-11-03 23:46:42 +00:00
gingerBill e7999f8450 Foreign context cleanup 2017-11-03 23:20:30 +00:00
gingerBill 0b29e42adb link_prefix; thread_local; fix link_name for file-scope variables 2017-11-03 23:11:06 +00:00
gingerBill fcc8b89e6b Fix issue #130; allow conversion from any pointer to uintptr and vice versa 2017-11-02 22:34:09 +00:00
gingerBill 529d1c78c7 Fix issue #131 2017-11-02 22:30:12 +00:00
gingerBill 414486829a Add string_set.cpp; Code clean up 2017-10-30 20:26:05 +00:00
gingerBill 3e05be8eb8 @(default_calling_convention = ...) for foreign blocks 2017-10-29 18:09:05 +00:00
gingerBill ae24a8e5ae Fix pointer arithmetic; remove suffix #tags for proc types 2017-10-29 17:00:54 +00:00
gingerBill d2588f9d1d Infix proc calling convention proc "std" (...) 2017-10-29 16:44:44 +00:00
gingerBill 1eb9994d88 Attributes; @(link_name="foo") 2017-10-29 15:46:23 +00:00
gingerBill a43b89f36e #alias type declarations; core library additions; _global import name for the global scope 2017-10-29 11:35:21 +00:00
gingerBill 0ed34af19d Fix importation of empty file (issue #128) 2017-10-18 22:52:42 +01:00
gingerBill 71729c2855 Add anonymous using import names with an underscore (#127)
`using import _ "foo.odin"`
2017-10-18 22:29:14 +01:00
gingerBill 6c8c430c2a Fix enum iteration (issue #126) 2017-10-18 22:26:04 +01:00
gingerBill 57b97ad0bd Fix issue #124 2017-10-15 23:30:55 +01:00
gingerBill 56f7a859df Refactor code to remove entity flag for export 2017-10-15 16:16:16 +01:00
gingerBill e5e14b9947 Remove name mangling for foreign export variables 2017-10-15 16:11:34 +01:00
gingerBill 3d8bf36a30 foreign export block
```
foreign export {
    my_i32: i32;
    my_foo :: proc() -> i32 {
        return 123;
    }
}
```
2017-10-15 16:05:42 +01:00
gingerBill 85f7c2d040 Change foreign_library to foreign import 2017-10-15 15:21:56 +01:00
gingerBill 26ea8f6dcb Syntax: Replace foreign_system_library "kernel.lib" to foreign_library "system:kernel.lib"; Remove keyword: foreign_system_library 2017-10-15 12:11:33 +01:00
gingerBill e05fe1837d Fix minimal dependency generation for polymorphic structs (related to issue #121) 2017-10-15 11:21:48 +01:00
gingerBill 94762b56f6 Fix issue #122 2017-10-15 10:14:17 +01:00
gingerBill b3b688fa50 Fix issue #123 2017-10-15 10:09:50 +01:00
Ginger Bill 5eaa8de8f9 Fix issue with #118 2017-10-12 21:01:16 +01:00
Ginger Bill 26d3c54aff Fix issue #119
This may need better error messages
2017-10-12 20:52:19 +01:00
Ginger Bill 349a62121c Fix issue #120 2017-10-12 20:32:44 +01:00
Ginger Bill bbb0e14633 Fix using import to work correctly 2017-10-12 20:28:32 +01:00
Ginger Bill 42312d9def Fix typos in c.odin 2017-10-10 23:43:31 +01:00
Ginger Bill 065d0e4ee3 Fix string_to_enum_value 2017-10-09 22:56:48 +01:00
Ginger Bill b772ad7094 Fix issue #116 2017-10-09 17:58:12 +01:00
Ginger Bill 444d366c39 Fix issue #115 2017-10-09 17:56:26 +01:00
Ginger Bill 8e4233b86a Correct union size 2017-10-08 15:19:01 +01:00
Ginger Bill 6424966b7a Union tag stored as an integer 2017-10-08 15:16:13 +01:00
Ginger Bill 4e42d7df43 Minor code reorganization 2017-10-08 12:27:03 +01:00
Ginger Bill 580ee5cc4a Fix using on import names 2017-10-08 11:08:15 +01:00
Ginger Bill 56a98a483f Better error messages for import cycles 2017-10-08 10:58:16 +01:00
Ginger Bill df7a4eda8a Allow for cyclic import but disallow cyclic using import and export 2017-10-07 11:37:43 +01:00
Ginger Bill 91cc0b282a Fix issue #114 2017-10-04 18:57:27 +01:00
Ginger Bill 01d8aea4df Disallow procedures literals as default values in anonymous struct types 2017-10-01 21:44:55 +01:00
Ginger Bill ee904060c5 Disallow anonymous structs with procedures as default values 2017-10-01 21:22:39 +01:00
Ginger Bill afb5538e83 Default procedure values for proc 2017-10-01 20:27:02 +01:00
Ginger Bill 1f24f105cc "Constant" procedure values for default values in structs 2017-10-01 20:10:13 +01:00
Ginger Bill 8f39ebbe5a Procedure literals for default values in structs 2017-10-01 20:01:00 +01:00
Ginger Bill c1e720a49b match to switch; Optional semicolons after "import" statements 2017-10-01 17:09:57 +01:00
Ginger Bill f38c8875b2 Fix issue #104 2017-10-01 14:29:54 +01:00
Ginger Bill e7e51f53ce Fix cyclic polymorphic struct bug #111 2017-10-01 14:10:31 +01:00
Ginger Bill 5259de5872 Reserve the link_name main 2017-09-30 11:28:17 +01:00
Ginger Bill e2b9c87aa8 Wrap entry point main around the C style main in the IR 2017-09-30 11:20:35 +01:00
Ginger Bill 8c7cf0dbb0 Fix union array bug (Issue #112) 2017-09-29 21:35:59 +01:00
Ginger Bill e6e9375b09 Remove http_test.odin 2017-09-29 21:20:39 +01:00
Ginger Bill c6096f9205 Revert to demo.odin 2017-09-29 21:11:51 +01:00
Ginger Bill 11614c2649 Fix old_demos; Fix when bug; Fix enum .names 2017-09-29 21:11:16 +01:00
Ginger Bill 793bc8c585 Fix issue #89 2017-09-25 23:08:22 +01:00
Ginger Bill 335e88b738 Fix issue #106 2017-09-25 23:06:04 +01:00
Ginger Bill b77ea94976 Fix issue #108 2017-09-25 22:59:59 +01:00
Ginger Bill ae17a51c0d Fix issue #109 2017-09-25 22:53:59 +01:00
gingerBill ee7a83f124 Merge pull request #110 from ThisDrunkDane/invalid-token-print-pos
Print position of the invalid token found during parsing.
2017-09-25 22:51:41 +01:00
Mikkel Hjortshoej 67ac551a2f The position that the invalid token was found at is printed 2017-09-25 21:42:23 +02:00
Ginger Bill 572ac616c1 Prevent statements after branch statements. 2017-09-24 14:58:15 +01:00
Ginger Bill 96bf6a5bcb Fix cyclic importation error printing 2017-09-23 20:47:02 +01:00
Ginger Bill c43d66c286 Use comma for struct field separators (disallow nesting) 2017-09-21 23:18:28 +01:00
Ginger Bill 95fb5fa46c Fix #export proc tag 2017-09-21 22:32:24 +01:00
Ginger Bill d614913c11 Fix decimal.odin, again 2017-09-20 23:17:33 +01:00
Ginger Bill 3bfaac0844 Fix decimal.odin assignment bug 2017-09-20 22:59:46 +01:00
Ginger Bill 14d0cbf6d7 Fix load order of files (again) 2017-09-20 21:42:42 +01:00
Ginger Bill 61a163d773 Fix crash with build_dll (Issue #100) 2017-09-20 21:00:40 +01:00
Ginger Bill 3a644dad78 Fix issue #101 2017-09-20 20:45:40 +01:00
Ginger Bill d2c1c719bd Fix file load order and allow when statements at file scope 2017-09-20 20:38:32 +01:00
Ginger Bill 333db4dc94 Fix issues #95 and #96 2017-09-13 22:20:27 +01:00
Ginger Bill cbcf4b6071 Fix issue #94 2017-09-11 22:49:26 +01:00
Ginger Bill e6e0aba8c3 Remove when suffixes; Implement file scope when statement, evaluated in source order 2017-09-10 15:17:37 +01:00
Ginger Bill 85097a9958 Fix global variable initialization IR bug 2017-09-10 13:50:11 +01:00
Ginger Bill 7791c343c4 Allow for multiple library collections; Store AstFile as pointer 2017-09-10 13:26:14 +01:00
Ginger Bill 3bd762591a Fix path_is_directory for *nix 2017-09-07 21:33:37 +01:00
Ginger Bill 8e3b77aba8 Library collections 2017-09-07 20:55:59 +01:00
Ginger Bill 36e3a02f67 Fix bit_field type information 2017-09-02 22:54:11 +01:00
Ginger Bill 566a242ba3 Fix issue #92 2017-09-02 10:06:44 +01:00
Ginger Bill 1e3b3c107c IR Fix for UnionTagValue 2017-08-28 23:04:48 +01:00
Ginger Bill 2ac33285c1 Remove metagen.odin 2017-08-27 23:28:20 +01:00
Ginger Bill 7cb8016df3 Add examples 2017-08-27 23:27:12 +01:00
Ginger Bill cf3c5a878a export declarations 2017-08-27 19:36:43 +01:00
Ginger Bill 2d20bde495 Remove () grouping for foreign_library 2017-08-27 19:24:30 +01:00
Ginger Bill b9e347ef50 Replace import_load with using import . 2017-08-27 17:03:27 +01:00
Ginger Bill 6707c8750e Import cycle checking 2017-08-27 14:42:19 +01:00
Ginger Bill e5502c13ee Restrict global variables to not allow tuples 2017-08-20 19:35:52 +01:00
Ginger Bill f30d2e43ea Add priority_queue.cpp and ptr_set.cpp 2017-08-20 18:39:09 +01:00
Ginger Bill 6c73f9d3fd Global variable dependency initialization ordering
Fuck graph theory
2017-08-20 18:28:21 +01:00
Ginger Bill 1161aa829d Fix mem.Arena 2017-08-13 22:20:44 +01:00
Ginger Bill 01519f2fd5 Fix push_allocator 2017-08-13 22:09:26 +01:00
Ginger Bill 33aad3a8ce Merge branch 'master' of https://github.com/gingerBill/Odin 2017-08-12 20:04:58 +01:00
Ginger Bill 4262c125c5 Fix struct #packed alignment calculation 2017-08-12 20:04:35 +01:00
Ginger Bill a09d5959ef Fix issues with OSX 2017-08-11 12:47:07 +01:00
Ginger Bill d7bd3f8402 Fix compilation issues on OSX 2017-08-11 00:16:57 +01:00
Ginger Bill 0fff6a2b74 Fix i128 division 2017-08-10 23:46:12 +01:00
Ginger Bill f4c0405221 Fix inline #raw_union bug in issue #87 2017-08-08 21:27:42 +01:00
Ginger Bill 49d337c830 v0.6.2; Use Ada_Case for types 2017-08-03 21:21:56 +01:00
Ginger Bill 294092979e Update build.bat 2017-08-01 21:38:06 +01:00
Ginger Bill c454ede184 v0.6.1a 2017-08-01 17:30:26 +01:00
Ginger Bill d854c5003c Fix minor errors for *nix 2017-08-01 17:28:49 +01:00
Ginger Bill 66d8776b83 v0.6.1 2017-08-01 15:18:37 +01:00
Ginger Bill ba6ecf35cf Disable threading on *nix for the time being 2017-08-01 15:09:43 +01:00
Ginger Bill 10cc9cf661 Add mutexes to string buffer allocator uses 2017-08-01 14:24:40 +01:00
Ginger Bill 2db971eedd Use pthread mutex 2017-08-01 13:49:12 +01:00
Ginger Bill 1775e80b41 HACK: Ignore Mutex check 2017-07-31 23:18:21 +01:00
Ginger Bill e4a93619db Update gb.h 2017-07-31 12:17:53 +01:00
Ginger Bill 4d14b3bcb4 Update remove_temp_files 2017-07-31 12:15:20 +01:00
Ginger Bill 9f4f5f9346 Add -keep-temp-files option 2017-07-31 12:06:04 +01:00
Ginger Bill 0fae31fb54 Extra type safety; Fix typos 2017-07-31 11:36:00 +01:00
Ginger Bill 8987a6630c v0.6.0 2017-07-30 22:26:22 +01:00
Ginger Bill 10ff8e0426 Fix ir for TypeInfo.Map 2017-07-30 20:17:25 +01:00
Ginger Bill a0ae02168a Update add_type_info_type to ignore polymorphic types 2017-07-30 20:13:23 +01:00
Ginger Bill a3c1ac2030 Speed up llvm ir printing; Use CRITICAL_SECTION for Mutex on windows 2017-07-30 19:47:37 +01:00
Ginger Bill 629b248f53 Parallelization of the Parser
~66% reduction (unoptimized build)
~30% reduction (optimized build)
2017-07-30 19:01:02 +01:00
Ginger Bill 62a72f0163 transmute(type)x; Minor code clean up 2017-07-30 14:52:42 +01:00
Ginger Bill 655931f0ea Minor Simplification of threading demo 2017-07-29 15:18:36 +01:00
Ginger Bill ca36fabfc0 Remove dead code for the "fixed" map idea 2017-07-29 14:43:42 +01:00
Ginger Bill 7bd62481ad Fix nil assignment to unions 2017-07-29 14:23:34 +01:00
Ginger Bill fbd27d7c45 Fix map internal type generation 2017-07-29 13:56:45 +01:00
Ginger Bill 3546391311 Merge branch 'master' of https://github.com/gingerBill/Odin 2017-07-29 13:01:28 +01:00
Ginger Bill 24c812115e Remove empty union check on array types; Fix overflowing error printing 2017-07-29 13:01:17 +01:00
gingerBill 28be0ad69b Fix IR print bug for empty structs; 2017-07-28 11:35:01 +01:00
gingerBill f0980c0a98 Fix import name exportation bug; Fix procedure type printing 2017-07-24 07:57:09 +01:00
Ginger Bill 1df4aa90ce Fix struct parameter bugs 2017-07-21 15:25:58 +01:00
Ginger Bill 6b3cf051f8 Fix math.odin, again 2017-07-21 12:39:05 +01:00
Ginger Bill 4ecd6e592b Fix missing semicolons in math.odin 2017-07-21 10:37:49 +01:00
Ginger Bill dbddec33c8 Internal changes; thread.odin for windows only 2017-07-20 23:57:56 +01:00
Ginger Bill 401a5955a4 Fix minor check on vector types 2017-07-20 19:55:54 +01:00
Ginger Bill 9a3b4167bb Fix polymorphic element types usage; Empty union as opaque type 2017-07-20 19:40:51 +01:00
Ginger Bill 13bc6eeea4 Make fields et al an Array rather than a raw pointer 2017-07-20 15:32:34 +01:00
Ginger Bill 2da18b6d33 Change internals from Record to Struct 2017-07-20 15:23:13 +01:00
Ginger Bill 6d37ed12d2 Update internals of a Union and Tuple 2017-07-20 15:17:04 +01:00
Ginger Bill eab23cd5b7 Fix parsing bug with procedure types in return values 2017-07-19 22:34:50 +01:00
Ginger Bill d233706a2d Fix minor parsing bug with procedure return types 2017-07-19 22:17:57 +01:00
Ginger Bill f1ab17ed4e type_info_of; enum_value_to_string and string_to_enum_value 2017-07-19 14:01:56 +01:00
Ginger Bill 6113164211 Change union layout to store type info rather than an integer; ternary expression for types with constant condition 2017-07-19 12:15:21 +01:00
Ginger Bill 4db462a703 Fix copy 2017-07-18 20:39:53 +01:00
Ginger Bill a22c6d6c0c Fix parsing error for compound literals 2017-07-18 19:57:30 +01:00
Ginger Bill 59fb7b020a Merge raw_union into struct as a memory layout tag #raw_union 2017-07-18 19:24:45 +01:00
Ginger Bill 65f079ebc4 Remove atomic, ++, and -- 2017-07-18 18:58:41 +01:00
Ginger Bill d16aa79492 General specialization for polymorphic parameters 2017-07-18 18:05:41 +01:00
Ginger Bill 5af0acc4af Disallow default struct values for any; new_clone 2017-07-18 16:02:01 +01:00
Ginger Bill a459364de3 Ignore missing default values for struct literals at the end 2017-07-18 15:32:34 +01:00
Ginger Bill 277ef1a68f Allow undefined --- as a struct field default value. 2017-07-18 15:09:24 +01:00
Ginger Bill 193c7c82c8 Default struct field values 2017-07-18 14:56:07 +01:00
Ginger Bill f7d8ba408c Fix some preload bugs. 2017-07-18 11:42:16 +01:00
Ginger Bill 9a8759efef Polymorphic type specialization for procedures 2017-07-17 15:08:36 +01:00
Ginger Bill 054948e701 Basic procedure type parameter specialization 2017-07-16 15:00:16 +01:00
Ginger Bill 1c5ddd65b4 Rudimentary support for parametric polymorphic types 2017-07-13 22:35:00 +01:00
Ginger Bill b8697fb4ed Change precedence order for types e.g. ^T(x) == ^(T(x)) 2017-07-13 16:20:07 +01:00
Ginger Bill 03570275c1 Fix issue #78 and have a better error message. 2017-07-13 11:35:01 +01:00
Ginger Bill b5587f1937 Fix aliasing of overloaded procedures from other scopes 2017-07-11 20:54:38 +01:00
Ginger Bill c4c6975f1b cast(Type)expr; Fix overloaded procedure determination on assignment 2017-07-11 14:40:27 +01:00
Ginger Bill 0be0fb2a57 Nested when statements within records 2017-07-10 23:47:22 +01:00
Ginger Bill 115e6e7f9e Update demo for both subtyping and union based Entity 2017-07-10 23:28:53 +01:00
Ginger Bill 3868a9a0f0 Clean up _preload.odin types 2017-07-10 23:15:41 +01:00
Ginger Bill ba5050ac7c Compiler Internal Changes: TypeRecord_Union -> Type_Union 2017-07-10 22:59:23 +01:00
Ginger Bill d936ca1ea0 Compiler internal change: TypeRecord_Enum -> Type_Enum 2017-07-10 22:42:58 +01:00
Ginger Bill fd8c4d58bb union type allow for any types and removes common fields 2017-07-10 22:32:21 +01:00
Ginger Bill ce4b7b8b7d Nested record declarations 2017-07-10 20:39:42 +01:00
Ginger Bill 069a47220e Make record semicolon syntax more consistent 2017-07-10 14:52:58 +01:00
Ginger Bill 66e4aaffc5 Use semicolons as field delimiters in records 2017-07-10 13:49:50 +01:00
Ginger Bill 81336b58cb "Fix" printing of embedded any to prevent recursion 2017-07-10 10:37:51 +01:00
Ginger Bill b201670f7a Fix _preload.odin; Add for in without parameters; Change sync.Mutex for windows 2017-07-08 23:13:57 +01:00
Ginger Bill 4b051a0d3b .. half closed range; ... open range; ... variadic syntax 2017-07-07 23:42:43 +01:00
Ginger Bill 45353465a6 Add sort.odin 2017-07-07 22:26:55 +01:00
Ginger Bill c63cb98019 Fix else do 2017-07-07 17:50:45 +01:00
Ginger Bill 773cf5ca08 Add -show-timings; Clean up polymorphic procedure code a bit 2017-07-07 15:26:49 +01:00
Ginger Bill 2db03cb4a5 Fix aprint* bug; NULL -> nullptr; Better error messages for overloaded functions 2017-07-06 22:43:55 +01:00
Ginger Bill eed873c6ec Add free for maps (a previous oversight) 2017-07-05 13:51:25 +01:00
Ginger Bill 3d2d461867 Replace many built-in procedures with user-level procedures 2017-07-04 23:52:00 +01:00
Ginger Bill 36392d658e Fix demo.odin 2017-07-04 22:43:38 +01:00
Ginger Bill 82696179e8 Merge branch 'master' of https://github.com/gingerBill/Odin 2017-07-04 22:42:41 +01:00
Ginger Bill 188bc28f6a Allow for overloading of polymorphic procedures 2017-07-04 22:42:25 +01:00
Ginger Bill 240da5c8e0 Allow aliasing of aliases 2017-07-04 16:06:08 +01:00
Ginger Bill 689a0c0b49 *_of as keyords; Allow constant aliasing for user/built-in procedures, import names, and library names 2017-07-04 11:23:48 +01:00
Ginger Bill bc16b290ba Disable polymorphic overloading in the global scope
TODO: Figure out why it does not work in the global scope
2017-07-02 22:08:39 +01:00
Ginger Bill 96d32680fe Allow overloading of polymorphic procedures 2017-07-02 10:45:22 +01:00
Ginger Bill d782b3d21d Fix do on for loops 2017-07-01 11:53:01 +01:00
Ginger Bill ed089b44b9 do keyword for inline statements instead of blocks 2017-07-01 11:38:44 +01:00
Ginger Bill 33f4af2e19 Fix demo 2017-06-29 21:01:07 +01:00
Ginger Bill 69f7382eec Implicit parametric polymorphic procedures 2017-06-29 20:56:18 +01:00
Ginger Bill 7e3293fc20 Fix odin version printing 2017-06-29 16:08:30 +01:00
Ginger Bill e4a8283327 Remove Type
What was I thinking?!
2017-06-29 15:48:07 +01:00
Ginger Bill 001baf4419 Add Type -- Runtime type for comparing types (similar to TypeInfo but simpler) 2017-06-29 15:13:41 +01:00
Ginger Bill d167290b28 Make AstNodeIdent a struct wrapping its Token 2017-06-29 12:11:50 +01:00
Ginger Bill f4879d4723 Update procedure names and extend demo.odin 2017-06-29 11:25:05 +01:00
Ginger Bill fd81c06c35 Remove var and const keywords; Fix default parameter syntax 2017-06-28 23:55:40 +01:00
Ginger Bill 94afcec757 :: style procedure declarations; remove old parsing code 2017-06-28 23:47:06 +01:00
Ginger Bill 4f28e9e1fb Remove type prefix declarations 2017-06-28 23:23:10 +01:00
Ginger Bill 0622509807 Disable var and const declarations 2017-06-28 23:17:20 +01:00
Ginger Bill 9ca2246bac Basic allowance for := and :: 2017-06-28 22:38:04 +01:00
Ginger Bill 647e2cafd7 Fix expand_to_tuple 2017-06-27 22:47:19 +01:00
154 changed files with 39565 additions and 30648 deletions
+10
View File
@@ -257,7 +257,17 @@ paket-files/
builds/
bin/
*.exe
*.obj
*.pdb
# - Linux/MacOS
odin
odin.dSYM
# shared collection
shared/
# temp files
* .ll
*.bc
+1 -1
View File
@@ -1,4 +1,4 @@
Copyright (c) 2016 Ginger Bill. All rights reserved.
Copyright (c) 2016-2017 Ginger Bill. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
+24
View File
@@ -0,0 +1,24 @@
DISABLED_WARNINGS=-Wno-switch -Wno-writable-strings -Wno-tautological-compare -Wno-macro-redefined #-Wno-pointer-sign -Wno-tautological-constant-out-of-range-compare
LDFLAGS=-pthread -ldl -lm -lstdc++
CFLAGS=-std=c++11
CC=clang
OS=$(shell uname)
ifeq ($(OS), DARWIN)
LDFLAGS=$(LDFLAGS) -liconv
endif
all: debug demo
demo:
./odin run examples/demo
debug:
$(CC) src/main.cpp $(DISABLED_WARNINGS) $(CFLAGS) -g $(LDFLAGS) -o odin
release:
$(CC) src/main.cpp $(DISABLED_WARNINGS) $(CFLAGS) -O3 -march=native $(LDFLAGS) -o odin
+52 -24
View File
@@ -1,4 +1,19 @@
<img src="misc/logo-slim.png" alt="Odin logo" height="74">
<p align="center">
<img src="misc/logo-slim.png" alt="Odin logo" height="120">
<br/>
A fast, concise, readable, pragmatic and open sourced programming language.
<br/>
<br/>
<a href="https://github.com/odin-lang/odin/releases/latest">
<img src="https://img.shields.io/github/release/odin-lang/odin.svg">
</a>
<a href="https://github.com/odin-lang/odin/releases/latest">
<img src="https://img.shields.io/badge/platforms-Windows%20|%20Linux%20|%20macOS-green.svg">
</a>
<a href="https://github.com/odin-lang/odin/blob/master/LICENSE">
<img src="https://img.shields.io/github/license/odin-lang/odin.svg">
</a>
</p>
# The Odin Programming Language
@@ -11,6 +26,32 @@ The Odin programming language is fast, concise, readable, pragmatic and open sou
Website: [https://odin.handmade.network/](https://odin.handmade.network/)
```go
package main
import "core:fmt"
main :: proc() {
program := "+ + * 😃 - /";
accumulator := 0;
for token in program {
switch token {
case '+': accumulator += 1;
case '-': accumulator -= 1;
case '*': accumulator *= 2;
case '/': accumulator /= 2;
case '😃': accumulator *= accumulator;
case: // Ignore everything else
}
}
fmt.printf("The program \"%s\" calculates the value %d\n",
program, accumulator);
}
```
## Demonstrations:
* First Talk & Demo
- [Talk](https://youtu.be/TMCkT-uASaE?t=338)
@@ -22,13 +63,21 @@ Website: [https://odin.handmade.network/](https://odin.handmade.network/)
* [when, for & procedure overloading](https://www.youtube.com/watch?v=OzeOekzyZK8)
* [Context Types, Unexported Entities, Labelled Branches](https://www.youtube.com/watch?v=CkHVwT1Qk-g)
* [Bit Fields, i128 & u128, Syntax Changes](https://www.youtube.com/watch?v=NlTutcLyF64)
* [Default and Named Arguments; Explicit Parametric Polymorphism](https://www.youtube.com/watch?v=-XQZE6S6zUU)
* [Loadsachanges](https://www.youtube.com/watch?v=ar0vFMoMtrI)
## Documentation
* [Tutorial](https://odin.handmade.network/wiki/3329-odin_tutorial)
* [Frequently Asked Questions](https://github.com/odin-lang/Odin/wiki/Frequently-Asked-Questions-(FAQ))
## Requirements to build and run
Please read the [Getting Started Guide](https://github.com/odin-lang/Odin/wiki#getting-started-with-odin).
- Windows
* x86-64
* MSVC 2015 installed (C++11 support)
* [LLVM binaries](https://github.com/gingerBill/Odin/releases/tag/llvm-4.0-windows) for `opt.exe` and `llc.exe`
* MSVC 2010 installed (C++11 support)
* [LLVM binaries](https://github.com/odin-lang/Odin/releases/tag/llvm-windows) for `opt.exe`, `llc.exe`, and `lld-link.exe`
* Requires MSVC's link.exe as the linker
* run `vcvarsall.bat` to setup the path
@@ -47,24 +96,3 @@ Website: [https://odin.handmade.network/](https://odin.handmade.network/)
* This is still highly in development and the language's design is quite volatile.
* Syntax is not fixed.
## Roadmap
Not in any particular order and not be implemented
* Compile Time Execution (CTE)
- More metaprogramming madness
- Compiler as a library
- AST inspection and modification
* CTE-based build system
* Replace LLVM backend with my own custom backend
* Improve SSA design to accommodate for lowering to a "bytecode"
* SSA optimizations
* Documentation Generator for "Entities"
* Multiple Architecture support
* Debug Information
- pdb format too
* Command Line Tooling
* Compiler Internals:
- Big numbers library
- Multithreading for performance increase
+7 -10
View File
@@ -4,28 +4,26 @@
set exe_name=odin.exe
:: Debug = 0, Release = 1
set release_mode=0
set compiler_flags= -nologo -Oi -TP -fp:fast -fp:except- -Gm- -MP -FC -GS- -EHsc- -GR-
set release_mode=1
set compiler_flags= -nologo -Oi -TP -fp:precise -Gm- -MP -FC -GS- -EHsc- -GR-
if %release_mode% EQU 0 ( rem Debug
set compiler_flags=%compiler_flags% -Od -MDd -Z7
rem -DDISPLAY_TIMING
) else ( rem Release
set compiler_flags=%compiler_flags% -O2 -MT -Z7
set compiler_flags=%compiler_flags% -O2 -MT -Z7 -DNO_ARRAY_BOUNDS_CHECK
)
set compiler_warnings= ^
-W4 -WX ^
-wd4100 -wd4101 -wd4127 -wd4189 ^
-wd4201 -wd4204 -wd4244 ^
-wd4306 ^
-wd4201 -wd4204 ^
-wd4456 -wd4457 -wd4480 ^
-wd4505 -wd4512 -wd4550
-wd4512
set compiler_includes=
set libs= ^
kernel32.lib
rem "src\dyncall\lib\*.lib"
set linker_flags= -incremental:no -opt:ref -subsystem:console
@@ -38,14 +36,13 @@ if %release_mode% EQU 0 ( rem Debug
set compiler_settings=%compiler_includes% %compiler_flags% %compiler_warnings%
set linker_settings=%libs% %linker_flags%
del *.pdb > NUL 2> NUL
del *.ilk > NUL 2> NUL
cl %compiler_settings% "src\main.cpp" ^
/link %linker_settings% -OUT:%exe_name% ^
&& odin run code/demo.odin -opt=0
rem && odin docs core/fmt.odin
&& odin run examples/demo/demo.odin
del *.obj > NUL 2> NUL
+10 -6
View File
@@ -1,15 +1,21 @@
#!/bin/bash
release_mode=0
release_mode=$1
warnings_to_disable="-std=c++11 -g -Wno-switch -Wno-pointer-sign -Wno-tautological-constant-out-of-range-compare -Wno-tautological-compare -Wno-macro-redefined -Wno-writable-strings"
warnings_to_disable="-std=c++11 -Wno-switch -Wno-pointer-sign -Wno-tautological-constant-out-of-range-compare -Wno-tautological-compare -Wno-macro-redefined -Wno-writable-strings"
libraries="-pthread -ldl -lm -lstdc++"
other_args=""
compiler="clang"
if [ -z "$release_mode" ]; then release_mode="0"; fi
if [ "$release_mode" -eq "0" ]; then
other_args="${other_args} -g -fno-inline-functions"
other_args="${other_args} -g"
fi
if [ "$release_mode" -eq "1" ]; then
other_args="${other_args} -O3 -march=native"
fi
if [[ "$(uname)" == "Darwin" ]]; then
# Set compiler to clang on MacOS
@@ -19,6 +25,4 @@ if [[ "$(uname)" == "Darwin" ]]; then
other_args="${other_args} -liconv"
fi
${compiler} src/main.cpp ${warnings_to_disable} ${libraries} ${other_args} -o odin
./odin run code/demo.odin
${compiler} src/main.cpp ${warnings_to_disable} ${libraries} ${other_args} -o odin && ./odin run examples/demo/demo.odin
-433
View File
@@ -1,433 +0,0 @@
import "fmt.odin";
proc general_stuff() {
// Complex numbers
var a = 3 + 4i;
var b: complex64 = 3 + 4i;
var c: complex128 = 3 + 4i;
var d = complex(2, 3);
var e = a / conj(a);
fmt.println("(3+4i)/(3-4i) =", e);
fmt.println(real(e), "+", imag(e), "i");
// C-style variadic procedures
foreign __llvm_core {
// The variadic part allows for extra type checking too which C does not provide
proc c_printf(fmt: ^u8, #c_vararg args: ..any) -> i32 #link_name "printf";
}
type Foo struct {
x: int,
y: f32,
z: string,
}
var foo = Foo{123, 0.513, "A string"};
var x, y, z = expand_to_tuple(foo);
fmt.println(x, y, z);
// By default, all variables are zeroed
// This can be overridden with the "uninitialized value"
// This is similar to `nil` but applied to everything
var undef_int: int = ---;
// Context system is now implemented using Implicit Parameter Passing (IPP)
// The previous implementation was Thread Local Storage (TLS)
// IPP has the advantage that it works on systems without TLS and that you can
// link the context to the stack frame and thus look at previous contexts
//
// It does mean that a pointer is implicitly passed procedures with the default
// Odin calling convention (#cc_odin)
// This can be overridden with something like #cc_contextless or #cc_c if performance
// is worried about
}
proc foreign_blocks() {
// See sys/windows.odin
}
proc default_arguments() {
proc hello(a: int = 9, b: int = 9) {
fmt.printf("a is %d; b is %d\n", a, b);
}
fmt.println("\nTesting default arguments:");
hello(1, 2);
hello(1);
hello();
}
proc named_arguments() {
type Colour enum {
Red,
Orange,
Yellow,
Green,
Blue,
Octarine,
};
using Colour;
proc make_character(name, catch_phrase: string, favorite_color, least_favorite_color: Colour) {
fmt.println();
fmt.printf("My name is %v and I like %v. %v\n", name, favorite_color, catch_phrase);
}
make_character("Frank", "¡Ay, caramba!", Blue, Green);
// As the procedures have more and more parameters, it is very easy
// to get many of the arguments in the wrong order especialy if the
// types are the same
make_character("¡Ay, caramba!", "Frank", Green, Blue);
// Named arguments help to disambiguate this problem
make_character(catch_phrase = "¡Ay, caramba!", name = "Frank",
least_favorite_color = Green, favorite_color = Blue);
// The named arguments can be specifed in any order.
make_character(favorite_color = Octarine, catch_phrase = "U wot m8!",
least_favorite_color = Green, name = "Dennis");
// NOTE: You cannot mix named arguments with normal values
/*
make_character("Dennis",
favorite_color = Octarine, catch_phrase = "U wot m8!",
least_favorite_color = Green);
*/
// Named arguments can also aid with default arguments
proc numerous_things(s : string, a = 1, b = 2, c = 3.14,
d = "The Best String!", e = false, f = 10.3/3.1, g = false) {
var g_str = g ? "true" : "false";
fmt.printf("How many?! %s: %v\n", s, g_str);
}
numerous_things("First");
numerous_things(s = "Second", g = true);
// Default values can be placed anywhere, not just at the end like in other languages
proc weird(pre: string, mid: int = 0, post: string) {
fmt.println(pre, mid, post);
}
weird("How many things", 42, "huh?");
weird(pre = "Prefix", post = "Pat");
}
proc default_return_values() {
proc foo(x: int) -> (first: string = "Hellope", second = "world!") {
match x {
case 0: return;
case 1: return "Goodbye";
case 2: return "Goodbye", "cruel world...";
case 3: return second = "cruel world...", first = "Goodbye";
}
return second = "my old friend.";
}
fmt.printf("%s %s\n", foo(0));
fmt.printf("%s %s\n", foo(1));
fmt.printf("%s %s\n", foo(2));
fmt.printf("%s %s\n", foo(3));
fmt.printf("%s %s\n", foo(4));
fmt.println();
// A more "real" example
type Error enum {
None,
WhyTheNumberThree,
TenIsTooBig,
};
type Entity struct {
name: string,
id: u32,
}
proc some_thing(input: int) -> (result: ^Entity = nil, err = Error.None) {
match {
case input == 3: return err = Error.WhyTheNumberThree;
case input >= 10: return err = Error.TenIsTooBig;
}
var e = new(Entity);
e.id = u32(input);
return result = e;
}
}
proc call_location() {
proc amazing(n: int, using loc = #caller_location) {
fmt.printf("%s(%d:%d) just asked to do something amazing.\n",
fully_pathed_filename, line, column);
fmt.printf("Normal -> %d\n", n);
fmt.printf("Amazing -> %d\n", n+1);
fmt.println();
}
var loc = #location(main);
fmt.println("`main` is located at", loc);
fmt.println("This line is located at", #location());
fmt.println();
amazing(3);
amazing(4, #location(call_location));
// See _preload.odin for the implementations of `assert` and `panic`
}
proc explicit_parametric_polymorphic_procedures() {
// This is how `new` is actually implemented, see _preload.odin
proc alloc_type(T: type) -> ^T {
return ^T(alloc(size_of(T), align_of(T)));
}
var int_ptr = alloc_type(int);
defer free(int_ptr);
int_ptr^ = 137;
fmt.println(int_ptr, int_ptr^);
// Named arguments work too!
var another_ptr = alloc_type(T = f32);
defer free(another_ptr);
proc add(T: type, args: ..T) -> T {
var res: T;
for arg in args {
res += arg;
}
return res;
}
fmt.println("add =", add(int, 1, 2, 3, 4, 5, 6));
proc swap(T: type, a, b: ^T) {
var tmp = a^;
a^ = b^;
b^ = tmp;
}
var a, b: int = 3, 4;
fmt.println("Pre-swap:", a, b);
swap(int, &a, &b);
fmt.println("Post-swap:", a, b);
a, b = b, a; // Or use this syntax for this silly example case
// A more complicated example using subtyping
// Something like this could be used in a game
type Vector2 struct {x, y: f32};
type Entity struct {
using position: Vector2,
flags: u64,
id: u64,
batch_index: u32,
slot_index: u32,
portable_id: u32,
derived: any,
}
type Rock struct {
using entity: ^Entity,
heavy: bool,
}
type Door struct {
using entity: ^Entity,
open: bool,
}
type Monster struct {
using entity: ^Entity,
is_robot: bool,
is_zombie: bool,
}
type EntityManager struct {
batches: [dynamic]^EntityBatch,
next_portable_id: u32,
}
const ENTITIES_PER_BATCH = 16;
type EntityBatch struct {
data: [ENTITIES_PER_BATCH]Entity,
occupied: [ENTITIES_PER_BATCH]bool,
batch_index: u32,
}
proc use_empty_slot(manager: ^EntityManager, batch: ^EntityBatch) -> ^Entity {
for ok, i in batch.occupied {
if ok -> continue;
batch.occupied[i] = true;
var e = &batch.data[i];
e.batch_index = u32(batch.batch_index);
e.slot_index = u32(i);
e.portable_id = manager.next_portable_id;
manager.next_portable_id++;
return e;
}
return nil;
}
proc gen_new_entity(manager: ^EntityManager) -> ^Entity {
for b in manager.batches {
var e = use_empty_slot(manager, b);
if e != nil -> return e;
}
var new_batch = new(EntityBatch);
append(manager.batches, new_batch);
new_batch.batch_index = u32(len(manager.batches)-1);
return use_empty_slot(manager, new_batch);
}
proc new_entity(manager: ^EntityManager, Type: type, x, y: int) -> ^Type {
var result = new(Type);
result.entity = gen_new_entity(manager);
result.derived.data = result;
result.derived.type_info = type_info(Type);
result.position.x = f32(x);
result.position.y = f32(y);
return result;
}
var manager: EntityManager;
var entities: [dynamic]^Entity;
var rock = new_entity(&manager, Rock, 3, 5);
// Named arguments work too!
var door = new_entity(manager = &manager, Type = Door, x = 3, y = 6);
// And named arguments can be any order
var monster = new_entity(
y = 1,
x = 2,
manager = &manager,
Type = Monster,
);
append(entities, rock, door, monster);
// An alternative to `union`s
for entity in entities {
match e in entity.derived {
case Rock: fmt.println("Rock", e.portable_id);
case Door: fmt.println("Door", e.portable_id);
case Monster: fmt.println("Monster", e.portable_id);
}
}
}
proc main() {
general_stuff();
foreign_blocks();
default_arguments();
named_arguments();
default_return_values();
call_location();
explicit_parametric_polymorphic_procedures();
// Command line argument(s)!
// -opt=0,1,2,3
/*************/
/* Questions */
/*************/
/*
I'm questioning if I should change the declaration syntax back to Jai-like
as I've found solutions to the problems I had with it before.
Should I change back to Jai-like declarations or keep with the Pascal-like?
Jai-like
x: int;
x: int = 123;
x := 123;
foo : int : 123;
foo :: 123;
MyInt :: int;
BarType :: proc();
bar :: proc() {
}
foreign lib {
foreign_bar :: proc() ---;
}
Pascal-like
var x: int;
var x: int = 123;
var x = 123;
const foo: int = 123;
const foo = 123;
type MyInt int;
type BarType proc();
proc bar() {
}
foreign lib {
proc foreign_bar();
}
*/
}
/*
proc main() {
var program = "+ + * - /";
var accumulator = 0;
for token in program {
match token {
case '+': accumulator += 1;
case '-': accumulator -= 1;
case '*': accumulator *= 2;
case '/': accumulator /= 2;
case: // Ignore everything else
}
}
fmt.printf("The program \"%s\" calculates the value %d\n",
program, accumulator);
}
*/
-222
View File
@@ -1,222 +0,0 @@
import win32 "sys/windows.odin" when ODIN_OS == "windows";
import wgl "sys/wgl.odin" when ODIN_OS == "windows";
import "fmt.odin";
import "math.odin";
import "os.odin";
import gl "opengl.odin";
const TWO_HEARTS = '💕';
var win32_perf_count_freq = win32.get_query_performance_frequency();
proc time_now() -> f64 {
assert(win32_perf_count_freq != 0);
var counter: i64;
win32.query_performance_counter(&counter);
return f64(counter) / f64(win32_perf_count_freq);
}
proc win32_print_last_error() {
var err_code = win32.get_last_error();
if err_code != 0 {
fmt.println("get_last_error: ", err_code);
}
}
// Yuk!
proc to_c_string(s: string) -> []u8 {
var c_str = make([]u8, len(s)+1);
copy(c_str, []u8(s));
c_str[len(s)] = 0;
return c_str;
}
type Window struct {
width, height: int,
wc: win32.WndClassExA,
dc: win32.Hdc,
hwnd: win32.Hwnd,
opengl_context, rc: wgl.Hglrc,
c_title: []u8,
}
proc make_window(title: string, msg, height: int, window_proc: win32.WndProc) -> (Window, bool) {
using win32;
var w: Window;
w.width, w.height = msg, height;
var class_name = "Win32-Odin-Window\x00";
var c_class_name = &class_name[0];
if title[len(title)-1] != 0 {
w.c_title = to_c_string(title);
} else {
w.c_title = []u8(title);
}
var instance = get_module_handle_a(nil);
w.wc = WndClassExA{
size = size_of(WndClassExA),
style = CS_VREDRAW | CS_HREDRAW,
instance = Hinstance(instance),
class_name = c_class_name,
wnd_proc = window_proc,
};
if register_class_ex_a(&w.wc) == 0 {
win32_print_last_error();
return w, false;
}
w.hwnd = create_window_ex_a(0,
c_class_name, &w.c_title[0],
WS_VISIBLE | WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX,
CW_USEDEFAULT, CW_USEDEFAULT,
i32(w.width), i32(w.height),
nil, nil, instance, nil);
if w.hwnd == nil {
win32_print_last_error();
return w, false;
}
w.dc = get_dc(w.hwnd);
{
var pfd = PixelFormatDescriptor{
size = size_of(PixelFormatDescriptor),
version = 1,
flags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
pixel_type = PFD_TYPE_RGBA,
color_bits = 32,
alpha_bits = 8,
depth_bits = 24,
stencil_bits = 8,
layer_type = PFD_MAIN_PLANE,
};
set_pixel_format(w.dc, choose_pixel_format(w.dc, &pfd), nil);
w.opengl_context = wgl.create_context(w.dc);
wgl.make_current(w.dc, w.opengl_context);
var attribs = [8]i32{
wgl.CONTEXT_MAJOR_VERSION_ARB, 2,
wgl.CONTEXT_MINOR_VERSION_ARB, 1,
wgl.CONTEXT_PROFILE_MASK_ARB, wgl.CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB,
0, // NOTE(bill): tells the proc that this is the end of attribs
};
var wgl_str = "wglCreateContextAttribsARB\x00";
var wglCreateContextAttribsARB = wgl.CreateContextAttribsARBType(wgl.get_proc_address(&wgl_str[0]));
w.rc = wglCreateContextAttribsARB(w.dc, nil, &attribs[0]);
wgl.make_current(w.dc, w.rc);
swap_buffers(w.dc);
}
return w, true;
}
proc destroy_window(w: ^Window) {
free(w.c_title);
}
proc display_window(w: ^Window) {
win32.swap_buffers(w.dc);
}
proc run() {
using math;
proc win32_proc(hwnd: win32.Hwnd, msg: u32, wparam: win32.Wparam, lparam: win32.Lparam) -> win32.Lresult #no_inline {
using win32;
if msg == WM_DESTROY || msg == WM_CLOSE || msg == WM_QUIT {
os.exit(0);
return 0;
}
return def_window_proc_a(hwnd, msg, wparam, lparam);
}
var window, window_success = make_window("Odin Language Demo", 854, 480, win32.WndProc(win32_proc));
if !window_success {
return;
}
defer destroy_window(&window);
gl.init();
using win32;
var prev_time = time_now();
var running = true;
var pos = Vec2{100, 100};
for running {
var curr_time = time_now();
var dt = f32(curr_time - prev_time);
prev_time = curr_time;
var msg: Msg;
for peek_message_a(&msg, nil, 0, 0, PM_REMOVE) > 0 {
if msg.message == WM_QUIT {
running = false;
}
translate_message(&msg);
dispatch_message_a(&msg);
}
if is_key_down(KeyCode.Escape) {
running = false;
}
{
const SPEED = 500;
var v: Vec2;
if is_key_down(KeyCode.Right) { v[0] += 1; }
if is_key_down(KeyCode.Left) { v[0] -= 1; }
if is_key_down(KeyCode.Up) { v[1] += 1; }
if is_key_down(KeyCode.Down) { v[1] -= 1; }
v = norm(v);
pos += v * Vec2{SPEED * dt};
}
gl.ClearColor(0.5, 0.7, 1.0, 1.0);
gl.Clear(gl.COLOR_BUFFER_BIT);
gl.LoadIdentity();
gl.Ortho(0, f64(window.width),
0, f64(window.height), 0, 1);
proc draw_rect(x, y, w, h: f32) {
gl.Begin(gl.TRIANGLES);
defer gl.End();
gl.Color3f(1, 0, 0); gl.Vertex3f(x, y, 0);
gl.Color3f(0, 1, 0); gl.Vertex3f(x+w, y, 0);
gl.Color3f(0, 0, 1); gl.Vertex3f(x+w, y+h, 0);
gl.Color3f(0, 0, 1); gl.Vertex3f(x+w, y+h, 0);
gl.Color3f(1, 1, 0); gl.Vertex3f(x, y+h, 0);
gl.Color3f(1, 0, 0); gl.Vertex3f(x, y, 0);
}
draw_rect(pos.x, pos.y, 50, 50);
display_window(&window);
var ms_to_sleep = i32(16 - 1000*dt);
if ms_to_sleep > 0 {
win32.sleep(ms_to_sleep);
}
}
}
proc main() {
run();
}
-184
View File
@@ -1,184 +0,0 @@
import "fmt.odin";
foreign_system_library ws2 "Ws2_32.lib" when ODIN_OS == "windows";
type SOCKET uint;
const INVALID_SOCKET = ~SOCKET(0);
type AF enum i32 {
UNSPEC = 0, // unspecified
UNIX = 1, // local to host (pipes, portals)
INET = 2, // internetwork: UDP, TCP, etc.
IMPLINK = 3, // arpanet imp addresses
PUP = 4, // pup protocols: e.g. BSP
CHAOS = 5, // mit CHAOS protocols
NS = 6, // XEROX NS protocols
ISO = 7, // ISO protocols
OSI = ISO, // OSI is ISO
ECMA = 8, // european computer manufacturers
DATAKIT = 9, // datakit protocols
CCITT = 10, // CCITT protocols, X.25 etc
SNA = 11, // IBM SNA
DECnet = 12, // DECnet
DLI = 13, // Direct data link interface
LAT = 14, // LAT
HYLINK = 15, // NSC Hyperchannel
APPLETALK = 16, // AppleTalk
ROUTE = 17, // Internal Routing Protocol
LINK = 18, // Link layer interface
XTP = 19, // eXpress Transfer Protocol (no AF)
COIP = 20, // connection-oriented IP, aka ST II
CNT = 21, // Computer Network Technology
RTIP = 22, // Help Identify RTIP packets
IPX = 23, // Novell Internet Protocol
SIP = 24, // Simple Internet Protocol
PIP = 25, // Help Identify PIP packets
MAX = 26,
};
const (
SOCK_STREAM = 1;
SOCKET_ERROR = -1;
IPPROTO_TCP = 6;
AI_PASSIVE = 0x0020;
SOMAXCONN = 128;
)
const (
SD_RECEIVE = 0;
SD_SEND = 1;
SD_BOTH = 2;
)
const WSADESCRIPTION_LEN = 256;
const WSASYS_STATUS_LEN = 128;
type WSADATA struct #ordered {
version: i16,
high_version: i16,
// NOTE(bill): This is x64 ordering
max_sockets: u16,
max_udp_dg: u16,
vendor_info: ^u8,
description: [WSADESCRIPTION_LEN+1]u8,
system_status: [WSASYS_STATUS_LEN+1]u8,
}
type addrinfo struct #ordered {
flags: i32,
family: i32,
socktype: i32,
protocol: i32,
addrlen: uint,
canonname: ^u8,
addr: ^sockaddr,
next: ^addrinfo,
}
type sockaddr struct #ordered {
family: u16,
data: [14]u8,
}
foreign ws2 {
proc WSAStartup (version_requested: i16, data: ^WSADATA) -> i32;
proc WSACleanup () -> i32;
proc getaddrinfo (node_name, service_name: ^u8, hints: ^addrinfo, result: ^^addrinfo) -> i32;
proc freeaddrinfo (ai: ^addrinfo);
proc socket (af, type_, protocol: i32) -> SOCKET;
proc closesocket (s: SOCKET) -> i32;
proc bind (s: SOCKET, name: ^sockaddr, name_len: i32) -> i32;
proc listen (s: SOCKET, back_log: i32) -> i32;
proc accept (s: SOCKET, addr: ^sockaddr, addr_len: i32) -> SOCKET;
proc recv (s: SOCKET, buf: ^u8, len: i32, flags: i32) -> i32;
proc send (s: SOCKET, buf: ^u8, len: i32, flags: i32) -> i32;
proc shutdown (s: SOCKET, how: i32) -> i32;
proc WSAGetLastError() -> i32;
}
proc to_c_string(s: string) -> ^u8 {
var c_str = make([]u8, len(s)+1);
copy(c_str, []u8(s));
c_str[len(s)] = 0;
return &c_str[0];
}
proc run() {
var (
wsa: WSADATA;
res: ^addrinfo = nil;
hints: addrinfo;
s, client: SOCKET;
)
if WSAStartup(2 | (2 << 8), &wsa) != 0 {
fmt.println("WSAStartup failed: ", WSAGetLastError());
return;
}
defer WSACleanup();
hints.family = i32(AF.INET);
hints.socktype = SOCK_STREAM;
hints.protocol = IPPROTO_TCP;
hints.flags = AI_PASSIVE;
if getaddrinfo(nil, to_c_string("8080"), &hints, &res) != 0 {
fmt.println("getaddrinfo failed: ", WSAGetLastError());
return;
}
defer freeaddrinfo(res);
s = socket(res.family, res.socktype, res.protocol);
if s == INVALID_SOCKET {
fmt.println("socket failed: ", WSAGetLastError());
return;
}
defer closesocket(s);
bind(s, res.addr, i32(res.addrlen));
listen(s, SOMAXCONN);
client = accept(s, nil, 0);
if client == INVALID_SOCKET {
fmt.println("socket failed: ", WSAGetLastError());
return;
}
defer closesocket(client);
var html =
`HTTP/1.1 200 OK
Connection: close
Content-type: text/html
<html>
<head>
<title>Demo Title</title>
</head>
<body>
<h1 style="color: orange;">Odin Server Demo</h1>
</body>
</html>
`;
var buf: [1024]u8;
for {
var bytes = recv(client, &buf[0], i32(len(buf)), 0);
if bytes > 0 {
// fmt.println(string(buf[0..<bytes]))
var bytes_sent = send(client, &html[0], i32(len(html)-1), 0);
if bytes_sent == SOCKET_ERROR {
fmt.println("send failed: ", WSAGetLastError());
return;
}
break;
} else if bytes == 0 {
fmt.println("Connection closing...");
break;
} else {
fmt.println("recv failed: ", WSAGetLastError());
return;
}
}
shutdown(client, SD_SEND);
}
-498
View File
@@ -1,498 +0,0 @@
import (
win32 "sys/windows.odin";
"fmt.odin";
"os.odin";
"mem.odin";
)
const (
CANVAS_WIDTH = 128;
CANVAS_HEIGHT = 128;
CANVAS_SCALE = 3;
FRAME_TIME = 1.0/30.0;
WINDOW_TITLE = "Punity\x00";
)
const _ = compile_assert(CANVAS_WIDTH % 16 == 0);
const (
WINDOW_WIDTH = CANVAS_WIDTH * CANVAS_SCALE;
WINDOW_HEIGHT = CANVAS_HEIGHT * CANVAS_SCALE;
)
const (
STACK_CAPACITY = 1<<20;
STORAGE_CAPACITY = 1<<20;
DRAW_LIST_RESERVE = 128;
MAX_KEYS = 256;
)
type Core struct {
stack: ^Bank,
storage: ^Bank,
running: bool,
key_modifiers: u32,
key_states: [MAX_KEYS]u8,
key_deltas: [MAX_KEYS]u8,
perf_frame,
perf_frame_inner,
perf_step,
perf_audio,
perf_blit,
perf_blit_cvt,
perf_blit_gdi: Perf_Span,
frame: i64,
canvas: Canvas,
draw_list: ^Draw_List,
}
type Perf_Span struct {
stamp: f64,
delta: f32,
}
type Bank struct {
memory: []u8,
cursor: int,
}
type Bank_State struct {
state: Bank,
bank: ^Bank,
}
type Color raw_union {
using channels: struct{a, b, g, r: u8},
rgba: u32,
}
type Palette struct {
colors: [256]Color,
colors_count: u8,
}
type Rect raw_union {
using minmax: struct {min_x, min_y, max_x, max_y: int},
using pos: struct {left, top, right, bottom: int},
e: [4]int,
}
type Bitmap struct {
pixels: []u8,
width: int,
height: int,
}
type Font struct {
using bitmap: Bitmap,
char_width: int,
char_height: int,
}
type Canvas struct {
using bitmap: ^Bitmap,
palette: Palette,
translate_x: int,
translate_y: int,
clip: Rect,
font: ^Font,
}
type DrawFlag enum {
NONE = 0,
FLIP_H = 1<<0,
FLIP_V = 1<<1,
MASK = 1<<2,
}
type Draw_Item struct {}
type Draw_List struct {
items: []Draw_Item,
}
type Key enum {
ModShift = 0x0001,
ModControl = 0x0002,
ModAlt = 0x0004,
ModSuper = 0x0008,
Unknown =-1,
Invalid =-2,
Lbutton = 1,
Rbutton = 2,
Cancel = 3,
Mbutton = 4,
Back = 8,
Tab = 9,
Clear = 12,
Return = 13,
Shift = 16,
Control = 17,
Menu = 18,
Pause = 19,
Capital = 20,
Kana = 0x15,
Hangeul = 0x15,
Hangul = 0x15,
Junja = 0x17,
Final = 0x18,
Hanja = 0x19,
Kanji = 0x19,
Escape = 0x1B,
Convert = 0x1C,
NonConvert = 0x1D,
Accept = 0x1E,
ModeChange = 0x1F,
Space = 32,
Prior = 33,
Next = 34,
End = 35,
Home = 36,
Left = 37,
Up = 38,
Right = 39,
Down = 40,
Select = 41,
Print = 42,
Exec = 43,
Snapshot = 44,
Insert = 45,
Delete = 46,
Help = 47,
Lwin = 0x5B,
Rwin = 0x5C,
Apps = 0x5D,
Sleep = 0x5F,
Numpad0 = 0x60,
Numpad1 = 0x61,
Numpad2 = 0x62,
Numpad3 = 0x63,
Numpad4 = 0x64,
Numpad5 = 0x65,
Numpad6 = 0x66,
Numpad7 = 0x67,
Numpad8 = 0x68,
Numpad9 = 0x69,
Multiply = 0x6A,
Add = 0x6B,
Separator = 0x6C,
Subtract = 0x6D,
Decimal = 0x6E,
Divide = 0x6F,
F1 = 0x70,
F2 = 0x71,
F3 = 0x72,
F4 = 0x73,
F5 = 0x74,
F6 = 0x75,
F7 = 0x76,
F8 = 0x77,
F9 = 0x78,
F10 = 0x79,
F11 = 0x7A,
F12 = 0x7B,
F13 = 0x7C,
F14 = 0x7D,
F15 = 0x7E,
F16 = 0x7F,
F17 = 0x80,
F18 = 0x81,
F19 = 0x82,
F20 = 0x83,
F21 = 0x84,
F22 = 0x85,
F23 = 0x86,
F24 = 0x87,
Numlock = 0x90,
Scroll = 0x91,
Lshift = 0xA0,
Rshift = 0xA1,
Lcontrol = 0xA2,
Rcontrol = 0xA3,
Lmenu = 0xA4,
Rmenu = 0xA5,
Apostrophe = 39, /* ' */
Comma = 44, /* , */
Minus = 45, /* - */
Period = 46, /* . */
Slash = 47, /* / */
Num0 = 48,
Num1 = 49,
Num2 = 50,
Num3 = 51,
Num4 = 52,
Num5 = 53,
Num6 = 54,
Num7 = 55,
Num8 = 56,
Num9 = 57,
Semicolon = 59, /* ; */
Equal = 61, /* = */
A = 65,
B = 66,
C = 67,
D = 68,
E = 69,
F = 70,
G = 71,
H = 72,
I = 73,
J = 74,
K = 75,
L = 76,
M = 77,
N = 78,
O = 79,
P = 80,
Q = 81,
R = 82,
S = 83,
T = 84,
U = 85,
V = 86,
W = 87,
X = 88,
Y = 89,
Z = 90,
LeftBracket = 91, /* [ */
Backslash = 92, /* \ */
RightBracket = 93, /* ] */
GraveAccent = 96, /* ` */
};
proc key_down(k: Key) -> bool {
return _core.key_states[k] != 0;
}
proc key_pressed(k: Key) -> bool {
return (_core.key_deltas[k] != 0) && key_down(k);
}
let win32_perf_count_freq = win32.get_query_performance_frequency();
proc time_now() -> f64 {
assert(win32_perf_count_freq != 0);
var counter: i64;
win32.query_performance_counter(&counter);
return f64(counter) / f64(win32_perf_count_freq);
}
var _core: Core;
proc run(user_init, user_step: proc(c: ^Core)) {
using win32;
_core.running = true;
proc win32_proc(hwnd: win32.Hwnd, msg: u32, wparam: win32.Wparam, lparam: win32.Lparam) -> win32.Lresult #no_inline #cc_c {
proc win32_app_key_mods() -> u32 {
var mods: u32 = 0;
if is_key_down(KeyCode.Shift) {
mods |= u32(Key.ModShift);
}
if is_key_down(KeyCode.Control) {
mods |= u32(Key.ModControl);
}
if is_key_down(KeyCode.Menu) {
mods |= u32(Key.ModAlt);
}
if is_key_down(KeyCode.Lwin) || is_key_down(KeyCode.Rwin) {
mods |= u32(Key.ModSuper);
}
return mods;
}
match msg {
case WM_KEYDOWN:
_core.key_modifiers = win32_app_key_mods();
if wparam < MAX_KEYS {
_core.key_states[wparam] = 1;
_core.key_deltas[wparam] = 1;
}
return 0;
case WM_KEYUP:
_core.key_modifiers = win32_app_key_mods();
if wparam < MAX_KEYS {
_core.key_states[wparam] = 0;
_core.key_deltas[wparam] = 1;
}
return 0;
case WM_CLOSE:
post_quit_message(0);
_core.running = false;
return 0;
}
return def_window_proc_a(hwnd, msg, wparam, lparam);
}
var class_name = "Punity\x00";
var window_class = WndClassExA{
class_name = &class_name[0],
size = size_of(WndClassExA),
style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC,
instance = Hinstance(get_module_handle_a(nil)),
wnd_proc = win32_proc,
// wnd_proc = DefWindowProcA,
background = Hbrush(get_stock_object(BLACK_BRUSH)),
};
if register_class_ex_a(&window_class) == 0 {
fmt.fprintln(os.stderr, "register_class_ex_a failed");
return;
}
var screen_width = get_system_metrics(SM_CXSCREEN);
var screen_height = get_system_metrics(SM_CYSCREEN);
var rc: Rect;
rc.left = (screen_width - WINDOW_WIDTH) / 2;
rc.top = (screen_height - WINDOW_HEIGHT) / 2;
rc.right = rc.left + WINDOW_WIDTH;
rc.bottom = rc.top + WINDOW_HEIGHT;
var style: u32 = WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
assert(adjust_window_rect(&rc, style, 0) != 0);
var wt = WINDOW_TITLE;
var win32_window = create_window_ex_a(0,
window_class.class_name,
&wt[0],
style,
rc.left, rc.top,
rc.right-rc.left, rc.bottom-rc.top,
nil, nil, window_class.instance,
nil);
if win32_window == nil {
fmt.fprintln(os.stderr, "create_window_ex_a failed");
return;
}
var window_bmi: BitmapInfo;
window_bmi.size = size_of(BitmapInfoHeader);
window_bmi.width = CANVAS_WIDTH;
window_bmi.height = CANVAS_HEIGHT;
window_bmi.planes = 1;
window_bmi.bit_count = 32;
window_bmi.compression = BI_RGB;
user_init(&_core);
show_window(win32_window, SW_SHOW);
var window_buffer = make([]u32, CANVAS_WIDTH * CANVAS_HEIGHT);
defer free(window_buffer);
for _, i in window_buffer {
window_buffer[i] = 0xff00ff;
}
var (
dt: f64;
prev_time = time_now();
curr_time = time_now();
total_time : f64 = 0;
offset_x = 0;
offset_y = 0;
)
var message: Msg;
for _core.running {
curr_time = time_now();
dt = curr_time - prev_time;
prev_time = curr_time;
total_time += dt;
offset_x += 1;
offset_y += 2;
{
var buf: [128]u8;
var s = fmt.bprintf(buf[..], "Punity: %.4f ms\x00", dt*1000);
win32.set_window_text_a(win32_window, &s[0]);
}
for var y = 0; y < CANVAS_HEIGHT; y++ {
for var x = 0; x < CANVAS_WIDTH; x++ {
var g = (x % 32) * 8;
var b = (y % 32) * 8;
window_buffer[x + y*CANVAS_WIDTH] = u32(g << 8 | b);
}
}
mem.zero(&_core.key_deltas[0], size_of(_core.key_deltas));
for peek_message_a(&message, nil, 0, 0, PM_REMOVE) != 0 {
if message.message == WM_QUIT {
_core.running = false;
}
translate_message(&message);
dispatch_message_a(&message);
}
user_step(&_core);
var dc = get_dc(win32_window);
stretch_dibits(dc,
0, 0, CANVAS_WIDTH * CANVAS_SCALE, CANVAS_HEIGHT * CANVAS_SCALE,
0, 0, CANVAS_WIDTH, CANVAS_HEIGHT,
&window_buffer[0],
&window_bmi,
DIB_RGB_COLORS,
SRCCOPY);
release_dc(win32_window, dc);
{
var delta = time_now() - prev_time;
var ms = i32((FRAME_TIME - delta) * 1000);
if ms > 0 {
win32.sleep(ms);
}
}
_core.frame++;
}
}
proc main() {
proc user_init(c: ^Core) {
}
proc user_step(c: ^Core) {
}
run(user_init, user_step);
}
-814
View File
@@ -1,814 +0,0 @@
#shared_global_scope;
import (
"os.odin";
"fmt.odin";
"utf8.odin";
"raw.odin";
)
// Naming Conventions:
// In general, PascalCase for types and snake_case for values
//
// Import Name: snake_case (but prefer single word)
// Types: PascalCase
// Union Variants: PascalCase
// Enum Values: PascalCase
// Procedures: snake_case
// Local Variables: snake_case
// Constant Variables: SCREAMING_SNAKE_CASE
// IMPORTANT NOTE(bill): `type_info` cannot be used within a
// #shared_global_scope due to the internals of the compiler.
// This could change at a later date if the all these data structures are
// implemented within the compiler rather than in this "preload" file
// IMPORTANT NOTE(bill): Do not change the order of any of this data
// The compiler relies upon this _exact_ order
type (
TypeInfoEnumValue raw_union {
f: f64,
i: i128,
}
// NOTE(bill): This must match the compiler's
CallingConvention enum {
Invalid = 0,
Odin = 1,
Contextless = 2,
C = 3,
Std = 4,
Fast = 5,
}
TypeInfoRecord struct #ordered {
types: []^TypeInfo,
names: []string,
offsets: []int, // offsets may not be used in tuples
usings: []bool, // usings may not be used in tuples
packed: bool,
ordered: bool,
custom_align: bool,
}
TypeInfo union {
size: int,
align: int,
Named{name: string, base: ^TypeInfo},
Integer{signed: bool},
Rune{},
Float{},
Complex{},
String{},
Boolean{},
Any{},
Pointer{
elem: ^TypeInfo, // nil -> rawptr
},
Atomic{elem: ^TypeInfo},
Procedure{
params: ^TypeInfo, // TypeInfo.Tuple
results: ^TypeInfo, // TypeInfo.Tuple
variadic: bool,
convention: CallingConvention,
},
Array{
elem: ^TypeInfo,
elem_size: int,
count: int,
},
DynamicArray{elem: ^TypeInfo, elem_size: int},
Slice {elem: ^TypeInfo, elem_size: int},
Vector {elem: ^TypeInfo, elem_size, count: int},
Tuple {using record: TypeInfoRecord}, // Only really used for procedures
Struct {using record: TypeInfoRecord},
RawUnion {using record: TypeInfoRecord},
Union{
common_fields: struct {
types: []^TypeInfo,
names: []string,
offsets: []int, // offsets may not be used in tuples
},
variant_names: []string,
variant_types: []^TypeInfo,
},
Enum{
base: ^TypeInfo,
names: []string,
values: []TypeInfoEnumValue,
},
Map{
key: ^TypeInfo,
value: ^TypeInfo,
generated_struct: ^TypeInfo,
count: int, // == 0 if dynamic
},
BitField{
names: []string,
bits: []i32,
offsets: []i32,
},
}
)
// NOTE(bill): only the ones that are needed (not all types)
// This will be set by the compiler
var (
__type_table: []TypeInfo;
__argv__: ^^u8;
__argc__: i32;
)
proc type_info_base(info: ^TypeInfo) -> ^TypeInfo {
if info == nil -> return nil;
var base = info;
match i in base {
case TypeInfo.Named:
base = i.base;
}
return base;
}
proc type_info_base_without_enum(info: ^TypeInfo) -> ^TypeInfo {
if info == nil -> return nil;
var base = info;
match i in base {
case TypeInfo.Named:
base = i.base;
case TypeInfo.Enum:
base = i.base;
}
return base;
}
foreign __llvm_core {
proc assume (cond: bool) #link_name "llvm.assume";
proc __debug_trap () #link_name "llvm.debugtrap";
proc __trap () #link_name "llvm.trap";
proc read_cycle_counter() -> u64 #link_name "llvm.readcyclecounter";
}
// IMPORTANT NOTE(bill): Must be in this order (as the compiler relies upon it)
type (
AllocatorMode enum u8 {
Alloc,
Free,
FreeAll,
Resize,
}
AllocatorProc proc(allocator_data: rawptr, mode: AllocatorMode,
size, alignment: int,
old_memory: rawptr, old_size: int, flags: u64 = 0) -> rawptr;
Allocator struct #ordered {
procedure: AllocatorProc,
data: rawptr,
}
Context struct #ordered {
thread_id: int,
allocator: Allocator,
user_data: rawptr,
user_index: int,
}
)
// #thread_local var __context: Context;
type SourceCodeLocation struct {
fully_pathed_filename: string,
line, column: i64,
procedure: string,
}
proc make_source_code_location(file: string, line, column: i64, procedure: string) -> SourceCodeLocation #cc_contextless #inline {
return SourceCodeLocation{file, line, column, procedure};
}
const DEFAULT_ALIGNMENT = align_of([vector 4]f32);
proc __init_context_from_ptr(c: ^Context, other: ^Context) #cc_contextless {
if c == nil -> return;
c^ = other^;
if c.allocator.procedure == nil {
c.allocator = default_allocator();
}
if c.thread_id == 0 {
c.thread_id = os.current_thread_id();
}
}
proc __init_context(c: ^Context) #cc_contextless {
if c == nil -> return;
if c.allocator.procedure == nil {
c.allocator = default_allocator();
}
if c.thread_id == 0 {
c.thread_id = os.current_thread_id();
}
}
/*
proc __check_context() {
__init_context(&__context);
}
*/
proc alloc(size: int, alignment: int = DEFAULT_ALIGNMENT) -> rawptr #inline {
// __check_context();
var a = context.allocator;
return a.procedure(a.data, AllocatorMode.Alloc, size, alignment, nil, 0, 0);
}
proc free_ptr_with_allocator(a: Allocator, ptr: rawptr) #inline {
if ptr == nil {
return;
}
if a.procedure == nil {
return;
}
a.procedure(a.data, AllocatorMode.Free, 0, 0, ptr, 0, 0);
}
proc free_ptr(ptr: rawptr) #inline {
// __check_context();
free_ptr_with_allocator(context.allocator, ptr);
}
proc free_all() #inline {
// __check_context();
var a = context.allocator;
a.procedure(a.data, AllocatorMode.FreeAll, 0, 0, nil, 0, 0);
}
proc resize(ptr: rawptr, old_size, new_size: int, alignment: int = DEFAULT_ALIGNMENT) -> rawptr #inline {
// __check_context();
var a = context.allocator;
return a.procedure(a.data, AllocatorMode.Resize, new_size, alignment, ptr, old_size, 0);
}
proc new(T: type) -> ^T #inline {
return ^T(alloc(size_of(T), align_of(T)));
}
proc default_resize_align(old_memory: rawptr, old_size, new_size, alignment: int) -> rawptr {
if old_memory == nil {
return alloc(new_size, alignment);
}
if new_size == 0 {
free(old_memory);
return nil;
}
if new_size == old_size {
return old_memory;
}
var new_memory = alloc(new_size, alignment);
if new_memory == nil {
return nil;
}
__mem_copy(new_memory, old_memory, min(old_size, new_size));;
free(old_memory);
return new_memory;
}
proc default_allocator_proc(allocator_data: rawptr, mode: AllocatorMode,
size, alignment: int,
old_memory: rawptr, old_size: int, flags: u64) -> rawptr {
using AllocatorMode;
match mode {
case Alloc:
return os.heap_alloc(size);
case Free:
os.heap_free(old_memory);
return nil;
case FreeAll:
// NOTE(bill): Does nothing
case Resize:
var ptr = os.heap_resize(old_memory, size);
assert(ptr != nil);
return ptr;
}
return nil;
}
proc default_allocator() -> Allocator {
return Allocator{
procedure = default_allocator_proc,
data = nil,
};
}
proc assert(condition: bool, message = "", using location = #caller_location) -> bool #cc_contextless {
if !condition {
if len(message) > 0 {
fmt.printf("%s(%d:%d) Runtime assertion: %s\n", fully_pathed_filename, line, column, message);
} else {
fmt.printf("%s(%d:%d) Runtime assertion\n", fully_pathed_filename, line, column);
}
__debug_trap();
}
return condition;
}
proc panic(message = "", using location = #caller_location) #cc_contextless {
if len(message) > 0 {
fmt.printf("%s(%d:%d) Panic: %s\n", fully_pathed_filename, line, column, message);
} else {
fmt.printf("%s(%d:%d) Panic\n", fully_pathed_filename, line, column);
}
__debug_trap();
}
proc __string_eq(a, b: string) -> bool #cc_contextless {
if len(a) != len(b) {
return false;
}
if len(a) == 0 {
return true;
}
if &a[0] == &b[0] {
return true;
}
return __string_cmp(a, b) == 0;
}
proc __string_cmp(a, b: string) -> int #cc_contextless {
return __mem_compare(&a[0], &b[0], min(len(a), len(b)));
}
proc __string_ne(a, b: string) -> bool #cc_contextless #inline { return !__string_eq(a, b); }
proc __string_lt(a, b: string) -> bool #cc_contextless #inline { return __string_cmp(a, b) < 0; }
proc __string_gt(a, b: string) -> bool #cc_contextless #inline { return __string_cmp(a, b) > 0; }
proc __string_le(a, b: string) -> bool #cc_contextless #inline { return __string_cmp(a, b) <= 0; }
proc __string_ge(a, b: string) -> bool #cc_contextless #inline { return __string_cmp(a, b) >= 0; }
proc __complex64_eq (a, b: complex64) -> bool #cc_contextless #inline { return real(a) == real(b) && imag(a) == imag(b); }
proc __complex64_ne (a, b: complex64) -> bool #cc_contextless #inline { return real(a) != real(b) || imag(a) != imag(b); }
proc __complex128_eq(a, b: complex128) -> bool #cc_contextless #inline { return real(a) == real(b) && imag(a) == imag(b); }
proc __complex128_ne(a, b: complex128) -> bool #cc_contextless #inline { return real(a) != real(b) || imag(a) != imag(b); }
proc __bounds_check_error(file: string, line, column: int, index, count: int) #cc_contextless {
if 0 <= index && index < count {
return;
}
fmt.fprintf(os.stderr, "%s(%d:%d) Index %d is out of bounds range 0..<%d\n",
file, line, column, index, count);
__debug_trap();
}
proc __slice_expr_error(file: string, line, column: int, low, high, max: int) #cc_contextless {
if 0 <= low && low <= high && high <= max {
return;
}
fmt.fprintf(os.stderr, "%s(%d:%d) Invalid slice indices: [%d..<%d..<%d]\n",
file, line, column, low, high, max);
__debug_trap();
}
proc __substring_expr_error(file: string, line, column: int, low, high: int) #cc_contextless {
if 0 <= low && low <= high {
return;
}
fmt.fprintf(os.stderr, "%s(%d:%d) Invalid substring indices: [%d..<%d]\n",
file, line, column, low, high);
__debug_trap();
}
proc __type_assertion_check(ok: bool, file: string, line, column: int, from, to: ^TypeInfo) #cc_contextless {
if !ok {
fmt.fprintf(os.stderr, "%s(%d:%d) Invalid type_assertion from %T to %T\n",
file, line, column, from, to);
__debug_trap();
}
}
proc __string_decode_rune(s: string) -> (rune, int) #cc_contextless #inline {
return utf8.decode_rune(s);
}
proc __mem_set(data: rawptr, value: i32, len: int) -> rawptr #cc_contextless {
when size_of(rawptr) == 8 {
foreign __llvm_core proc llvm_memset_64bit(dst: rawptr, val: u8, len: int, align: i32, is_volatile: bool) #link_name "llvm.memset.p0i8.i64";
llvm_memset_64bit(data, u8(value), len, 1, false);
return data;
} else {
foreign __llvm_core proc llvm_memset_32bit(dst: rawptr, val: u8, len: int, align: i32, is_volatile: bool) #link_name "llvm.memset.p0i8.i32";
llvm_memset_32bit(data, u8(value), len, 1, false);
return data;
}
}
proc __mem_zero(data: rawptr, len: int) -> rawptr #cc_contextless {
return __mem_set(data, 0, len);
}
proc __mem_copy(dst, src: rawptr, len: int) -> rawptr #cc_contextless {
// NOTE(bill): This _must_ be implemented like C's memmove
when size_of(rawptr) == 8 {
foreign __llvm_core proc llvm_memmove_64bit(dst, src: rawptr, len: int, align: i32, is_volatile: bool) #link_name "llvm.memmove.p0i8.p0i8.i64";
llvm_memmove_64bit(dst, src, len, 1, false);
return dst;
} else {
foreign __llvm_core proc llvm_memmove_32bit(dst, src: rawptr, len: int, align: i32, is_volatile: bool) #link_name "llvm.memmove.p0i8.p0i8.i32";
llvm_memmove_32bit(dst, src, len, 1, false);
return dst;
}
}
proc __mem_copy_non_overlapping(dst, src: rawptr, len: int) -> rawptr #cc_contextless {
// NOTE(bill): This _must_ be implemented like C's memcpy
when size_of(rawptr) == 8 {
foreign __llvm_core proc llvm_memcpy_64bit(dst, src: rawptr, len: int, align: i32, is_volatile: bool) #link_name "llvm.memcpy.p0i8.p0i8.i64";
llvm_memcpy_64bit(dst, src, len, 1, false);
return dst;
} else {
foreign __llvm_core proc llvm_memcpy_32bit(dst, src: rawptr, len: int, align: i32, is_volatile: bool) #link_name "llvm.memcpy.p0i8.p0i8.i32";
llvm_memcpy_32bit(dst, src, len, 1, false);
return dst;
}
}
proc __mem_compare(a, b: ^u8, n: int) -> int #cc_contextless {
for i in 0..<n {
match {
case (a+i)^ < (b+i)^:
return -1;
case (a+i)^ > (b+i)^:
return +1;
}
}
return 0;
}
foreign __llvm_core {
proc __sqrt_f32(x: f32) -> f32 #link_name "llvm.sqrt.f32";
proc __sqrt_f64(x: f64) -> f64 #link_name "llvm.sqrt.f64";
}
proc __abs_complex64(x: complex64) -> f32 #inline #cc_contextless {
var r, i = real(x), imag(x);
return __sqrt_f32(r*r + i*i);
}
proc __abs_complex128(x: complex128) -> f64 #inline #cc_contextless {
var r, i = real(x), imag(x);
return __sqrt_f64(r*r + i*i);
}
proc __dynamic_array_make(array_: rawptr, elem_size, elem_align: int, len, cap: int) {
var array = ^raw.DynamicArray(array_);
// __check_context();
array.allocator = context.allocator;
assert(array.allocator.procedure != nil);
if cap > 0 {
__dynamic_array_reserve(array_, elem_size, elem_align, cap);
array.len = len;
}
}
proc __dynamic_array_reserve(array_: rawptr, elem_size, elem_align: int, cap: int) -> bool {
var array = ^raw.DynamicArray(array_);
if cap <= array.cap -> return true;
// __check_context();
if array.allocator.procedure == nil {
array.allocator = context.allocator;
}
assert(array.allocator.procedure != nil);
var old_size = array.cap * elem_size;
var new_size = cap * elem_size;
var allocator = array.allocator;
var new_data = allocator.procedure(allocator.data, AllocatorMode.Resize, new_size, elem_align, array.data, old_size, 0);
if new_data == nil -> return false;
array.data = new_data;
array.cap = cap;
return true;
}
proc __dynamic_array_resize(array_: rawptr, elem_size, elem_align: int, len: int) -> bool {
var array = ^raw.DynamicArray(array_);
var ok = __dynamic_array_reserve(array_, elem_size, elem_align, len);
if ok -> array.len = len;
return ok;
}
proc __dynamic_array_append(array_: rawptr, elem_size, elem_align: int,
items: rawptr, item_count: int) -> int {
var array = ^raw.DynamicArray(array_);
if item_count <= 0 || items == nil {
return array.len;
}
var ok = true;
if array.cap <= array.len+item_count {
var cap = 2 * array.cap + max(8, item_count);
ok = __dynamic_array_reserve(array, elem_size, elem_align, cap);
}
// TODO(bill): Better error handling for failed reservation
if !ok -> return array.len;
var data = ^u8(array.data);
assert(data != nil);
__mem_copy(data + (elem_size*array.len), items, elem_size * item_count);
array.len += item_count;
return array.len;
}
proc __dynamic_array_append_nothing(array_: rawptr, elem_size, elem_align: int) -> int {
var array = ^raw.DynamicArray(array_);
var ok = true;
if array.cap <= array.len+1 {
var cap = 2 * array.cap + max(8, 1);
ok = __dynamic_array_reserve(array, elem_size, elem_align, cap);
}
// TODO(bill): Better error handling for failed reservation
if !ok -> return array.len;
var data = ^u8(array.data);
assert(data != nil);
__mem_zero(data + (elem_size*array.len), elem_size);
array.len++;
return array.len;
}
proc __slice_append(slice_: rawptr, elem_size, elem_align: int,
items: rawptr, item_count: int) -> int {
var slice = ^raw.Slice(slice_);
if item_count <= 0 || items == nil {
return slice.len;
}
item_count = min(slice.cap-slice.len, item_count);
if item_count > 0 {
var data = ^u8(slice.data);
assert(data != nil);
__mem_copy(data + (elem_size*slice.len), items, elem_size * item_count);
slice.len += item_count;
}
return slice.len;
}
// Map stuff
proc __default_hash(data: []u8) -> u128 {
proc fnv128a(data: []u8) -> u128 {
var h: u128 = 0x6c62272e07bb014262b821756295c58d;
for b in data {
h = (h ~ u128(b)) * 0x1000000000000000000013b;
}
return h;
}
return fnv128a(data);
}
proc __default_hash_string(s: string) -> u128 {
return __default_hash([]u8(s));
}
const __INITIAL_MAP_CAP = 16;
type (
__MapKey struct #ordered {
hash: u128,
str: string,
}
__MapFindResult struct #ordered {
hash_index: int,
entry_prev: int,
entry_index: int,
}
__MapEntryHeader struct #ordered {
key: __MapKey,
next: int,
/*
value: Value_Type,
*/
}
__MapHeader struct #ordered {
m: ^raw.DynamicMap,
is_key_string: bool,
entry_size: int,
entry_align: int,
value_offset: int,
value_size: int,
}
)
proc __dynamic_map_reserve(using header: __MapHeader, cap: int) {
__dynamic_array_reserve(&m.hashes, size_of(int), align_of(int), cap);
__dynamic_array_reserve(&m.entries, entry_size, entry_align, cap);
}
proc __dynamic_map_rehash(using header: __MapHeader, new_count: int) {
var new_header: __MapHeader = header;
var nm: raw.DynamicMap;
new_header.m = &nm;
var header_hashes = ^raw.DynamicArray(&header.m.hashes);
var nm_hashes = ^raw.DynamicArray(&nm.hashes);
__dynamic_array_resize(nm_hashes, size_of(int), align_of(int), new_count);
__dynamic_array_reserve(&nm.entries, entry_size, entry_align, m.entries.len);
for i in 0..<new_count -> nm.hashes[i] = -1;
for var i = 0; i < m.entries.len; i++ {
if len(nm.hashes) == 0 {
__dynamic_map_grow(new_header);
}
var entry_header = __dynamic_map_get_entry(header, i);
var data = ^u8(entry_header);
var fr = __dynamic_map_find(new_header, entry_header.key);
var j = __dynamic_map_add_entry(new_header, entry_header.key);
if fr.entry_prev < 0 {
nm.hashes[fr.hash_index] = j;
} else {
var e = __dynamic_map_get_entry(new_header, fr.entry_prev);
e.next = j;
}
var e = __dynamic_map_get_entry(new_header, j);
e.next = fr.entry_index;
var ndata = ^u8(e);
__mem_copy(ndata+value_offset, data+value_offset, value_size);
if __dynamic_map_full(new_header) {
__dynamic_map_grow(new_header);
}
}
free_ptr_with_allocator(header_hashes.allocator, header_hashes.data);
free_ptr_with_allocator(header.m.entries.allocator, header.m.entries.data);
header.m^ = nm;
}
proc __dynamic_map_get(h: __MapHeader, key: __MapKey) -> rawptr {
var index = __dynamic_map_find(h, key).entry_index;
if index >= 0 {
var data = ^u8(__dynamic_map_get_entry(h, index));
var val = data + h.value_offset;
return val;
}
return nil;
}
proc __dynamic_map_set(using h: __MapHeader, key: __MapKey, value: rawptr) {
var index: int;
assert(value != nil);
if len(m.hashes) == 0 {
__dynamic_map_reserve(h, __INITIAL_MAP_CAP);
__dynamic_map_grow(h);
}
var fr = __dynamic_map_find(h, key);
if fr.entry_index >= 0 {
index = fr.entry_index;
} else {
index = __dynamic_map_add_entry(h, key);
if fr.entry_prev >= 0 {
var entry = __dynamic_map_get_entry(h, fr.entry_prev);
entry.next = index;
} else {
m.hashes[fr.hash_index] = index;
}
}
{
var e = __dynamic_map_get_entry(h, index);
e.key = key;
var val = ^u8(e) + value_offset;
__mem_copy(val, value, value_size);
}
if __dynamic_map_full(h) {
__dynamic_map_grow(h);
}
}
proc __dynamic_map_grow(using h: __MapHeader) {
var new_count = max(2*m.entries.cap + 8, __INITIAL_MAP_CAP);
__dynamic_map_rehash(h, new_count);
}
proc __dynamic_map_full(using h: __MapHeader) -> bool {
return int(0.75 * f64(len(m.hashes))) <= m.entries.cap;
}
proc __dynamic_map_hash_equal(h: __MapHeader, a, b: __MapKey) -> bool {
if a.hash == b.hash {
if h.is_key_string -> return a.str == b.str;
return true;
}
return false;
}
proc __dynamic_map_find(using h: __MapHeader, key: __MapKey) -> __MapFindResult {
var fr = __MapFindResult{-1, -1, -1};
if len(m.hashes) > 0 {
fr.hash_index = int(key.hash % u128(len(m.hashes)));
fr.entry_index = m.hashes[fr.hash_index];
for fr.entry_index >= 0 {
var entry = __dynamic_map_get_entry(h, fr.entry_index);
if __dynamic_map_hash_equal(h, entry.key, key) {
return fr;
}
fr.entry_prev = fr.entry_index;
fr.entry_index = entry.next;
}
}
return fr;
}
proc __dynamic_map_add_entry(using h: __MapHeader, key: __MapKey) -> int {
var prev = m.entries.len;
var c = __dynamic_array_append_nothing(&m.entries, entry_size, entry_align);
if c != prev {
var end = __dynamic_map_get_entry(h, c-1);
end.key = key;
end.next = -1;
}
return prev;
}
proc __dynamic_map_delete(using h: __MapHeader, key: __MapKey) {
var fr = __dynamic_map_find(h, key);
if fr.entry_index >= 0 {
__dynamic_map_erase(h, fr);
}
}
proc __dynamic_map_get_entry(using h: __MapHeader, index: int) -> ^__MapEntryHeader {
var data = ^u8(m.entries.data) + index*entry_size;
return ^__MapEntryHeader(data);
}
proc __dynamic_map_erase(using h: __MapHeader, fr: __MapFindResult) {
if fr.entry_prev < 0 {
m.hashes[fr.hash_index] = __dynamic_map_get_entry(h, fr.entry_index).next;
} else {
__dynamic_map_get_entry(h, fr.entry_prev).next = __dynamic_map_get_entry(h, fr.entry_index).next;
}
if fr.entry_index == m.entries.len-1 {
m.entries.len--;
}
__mem_copy(__dynamic_map_get_entry(h, fr.entry_index), __dynamic_map_get_entry(h, m.entries.len-1), entry_size);
var last = __dynamic_map_find(h, __dynamic_map_get_entry(h, fr.entry_index).key);
if last.entry_prev >= 0 {
__dynamic_map_get_entry(h, last.entry_prev).next = fr.entry_index;
} else {
m.hashes[last.hash_index] = fr.entry_index;
}
}
-227
View File
@@ -1,227 +0,0 @@
#shared_global_scope;
proc __multi3(a, b: u128) -> u128 #cc_c #link_name "__multi3" {
const bits_in_dword_2 = size_of(i64) * 4;
const lower_mask = u128(~u64(0) >> bits_in_dword_2);
when ODIN_ENDIAN == "bit" {
type TWords raw_union {
all: u128,
using _: struct {lo, hi: u64},
};
} else {
type TWords raw_union {
all: u128,
using _: struct {hi, lo: u64},
};
}
var r: TWords;
var t: u64;
r.lo = u64(a & lower_mask) * u64(b & lower_mask);
t = r.lo >> bits_in_dword_2;
r.lo &= u64(lower_mask);
t += u64(a >> bits_in_dword_2) * u64(b & lower_mask);
r.lo += u64(t & u64(lower_mask)) << bits_in_dword_2;
r.hi = t >> bits_in_dword_2;
t = r.lo >> bits_in_dword_2;
r.lo &= u64(lower_mask);
t += u64(b >> bits_in_dword_2) * u64(a & lower_mask);
r.lo += u64(t & u64(lower_mask)) << bits_in_dword_2;
r.hi += t >> bits_in_dword_2;
r.hi += u64(a >> bits_in_dword_2) * u64(b >> bits_in_dword_2);
return r.all;
}
proc __u128_mod(a, b: u128) -> u128 #cc_c #link_name "__umodti3" {
var r: u128;
__u128_quo_mod(a, b, &r);
return r;
}
proc __u128_quo(a, b: u128) -> u128 #cc_c #link_name "__udivti3" {
return __u128_quo_mod(a, b, nil);
}
proc __i128_mod(a, b: i128) -> i128 #cc_c #link_name "__modti3" {
var r: i128;
__i128_quo_mod(a, b, &r);
return r;
}
proc __i128_quo(a, b: i128) -> i128 #cc_c #link_name "__divti3" {
return __i128_quo_mod(a, b, nil);
}
proc __i128_quo_mod(a, b: i128, rem: ^i128) -> (quo: i128) #cc_c #link_name "__divmodti4" {
var s: i128;
s = b >> 127;
b = (b~s) - s;
s = a >> 127;
b = (a~s) - s;
var uquo: u128;
var urem = __u128_quo_mod(transmute(u128, a), transmute(u128, b), &uquo);
var iquo = transmute(i128, uquo);
var irem = transmute(i128, urem);
iquo = (iquo~s) - s;
irem = (irem~s) - s;
if rem != nil { rem^ = irem; }
return iquo;
}
proc __u128_quo_mod(a, b: u128, rem: ^u128) -> (quo: u128) #cc_c #link_name "__udivmodti4" {
var alo, ahi = u64(a), u64(a>>64);
var blo, bhi = u64(b), u64(b>>64);
if b == 0 {
if rem != nil { rem^ = 0; }
return u128(alo/blo);
}
var r, d, x, q: u128 = a, b, 1, 0;
for r >= d && (d>>127)&1 == 0 {
x <<= 1;
d <<= 1;
}
for x != 0 {
if r >= d {
r -= d;
q |= x;
}
x >>= 1;
d >>= 1;
}
if rem != nil { rem^ = r; }
return q;
}
/*
proc __f16_to_f32(f: f16) -> f32 #cc_c #no_inline #link_name "__gnu_h2f_ieee" {
when true {
// Source: https://fgiesen.wordpress.com/2012/03/28/half-to-float-done-quic/
const FP32 = raw_union {u: u32, f: f32};
magic, was_infnan: FP32;
magic.u = (254-15) << 23;
was_infnan.u = (127+16) << 23;
hu := transmute(u16, f);
o := FP32{};
o.u = u32(hu & 0x7fff) << 13);
o.f *= magic.f;
if o.f >= was_infnan.f {
o.u |= 255 << 23;
}
o.u |= u32(hu & 0x8000) << 16;
return o.f;
} else {
return 0;
}
}
proc __f32_to_f16(f_: f32) -> f16 #cc_c #no_inline #link_name "__gnu_f2h_ieee" {
when false {
// Source: https://gist.github.com/rygorous/2156668
const FP16 = raw_union {u: u16, f: f16};
const FP32 = raw_union {u: u32, f: f32};
f32infty, f16infty, magic: FP32;
f32infty.u = 255<<23;
f16infty.u = 31<<23;
magic.u = 15<<23;
const sign_mask = u32(0x80000000);
const round_mask = ~u32(0x0fff);
f := transmute(FP32, f_);
o: FP16;
sign := f.u & sign_mask;
f.u ~= sign;
// NOTE all the integer compares in this function can be safely
// compiled into signed compares since all operands are below
// 0x80000000. Important if you want fast straight SSE2 code
// (since there's no unsigned PCMPGTD).
if f.u >= f32infty.u { // Inf or NaN (all exponent bits set)
o.u = f.u > f32infty.u ? 0x7e00 : 0x7c00; // NaN->qNaN and Inf->Inf
} else { // (De)normalized number or zero
f.u &= round_mask;
f.f *= magic.f;
f.u -= round_mask;
if f.u > f16infty.u {
f.u = f16infty.u; // Clamp to signed infinity if overflowed
}
o.u = u16(f.u >> 13); // Take the bits!
}
o.u |= u16(sign >> 16);
return o.f;
} else {
f := transmute(u32, f_);
h: u16;
hs, he, hf: u16;
fs := (f >> 31) & 1;
fe := (f >> 23) & 0b1111_1111;
ff := (f >> 0) & 0b0111_1111_1111_1111_1111_1111;
add_one := false;
if (fe == 0) {
he = 0;
} else if (fe == 255) {
he = 31;
hf = ff != 0 ? 0x200 : 0;
} else {
ne := fe - 127 + 15;
if ne >= 31 {
he = 31;
} else if ne <= 0 {
if (14-ne) <= 24 {
mant := ff | 0x800000;
hf = u16(mant >> (14-ne));
if (mant >> (13-ne)) & 1 != 0 {
add_one = true;
}
}
} else {
he = u16(ne);
hf = u16(ff >> 13);
if ff&0x1000 != 0 {
add_one = true;
}
}
}
hs = u16(hs);
h |= (he&0b0001_1111)<<10;
h |= (hf&0b0011_1111_1111);
if add_one {
h++;
}
h |= (hs&1) << 15;
return transmute(f16, h);
}
}
proc __f64_to_f16(f: f64) -> f16 #cc_c #no_inline #link_name "__truncdfhf2" {
return __f32_to_f16(f32(f));
}
proc __f16_to_f64(f: f16) -> f64 #cc_c #no_inline {
return f64(__f16_to_f32(f));
}
*/
-100
View File
@@ -1,100 +0,0 @@
// TODO(bill): Use assembly instead here to implement atomics
// Inline vs external file?
import win32 "sys/windows.odin" when ODIN_OS == "windows";
var _ = compile_assert(ODIN_ARCH == "amd64"); // TODO(bill): x86 version
proc yield_thread() { win32.mm_pause(); }
proc mfence () { win32.read_write_barrier(); }
proc sfence () { win32.write_barrier(); }
proc lfence () { win32.read_barrier(); }
proc load(a: ^i32) -> i32 {
return a^;
}
proc store(a: ^i32, value: i32) {
a^ = value;
}
proc compare_exchange(a: ^i32, expected, desired: i32) -> i32 {
return win32.interlocked_compare_exchange(a, desired, expected);
}
proc exchanged(a: ^i32, desired: i32) -> i32 {
return win32.interlocked_exchange(a, desired);
}
proc fetch_add(a: ^i32, operand: i32) -> i32 {
return win32.interlocked_exchange_add(a, operand);
}
proc fetch_and(a: ^i32, operand: i32) -> i32 {
return win32.interlocked_and(a, operand);
}
proc fetch_or(a: ^i32, operand: i32) -> i32 {
return win32.interlocked_or(a, operand);
}
proc spin_lock(a: ^i32, time_out: int) -> bool { // NOTE(bill) time_out = -1 as default
var old_value = compare_exchange(a, 1, 0);
var counter = 0;
for old_value != 0 && (time_out < 0 || counter < time_out) {
counter++;
yield_thread();
old_value = compare_exchange(a, 1, 0);
mfence();
}
return old_value == 0;
}
proc spin_unlock(a: ^i32) {
store(a, 0);
mfence();
}
proc try_acquire_lock(a: ^i32) -> bool {
yield_thread();
var old_value = compare_exchange(a, 1, 0);
mfence();
return old_value == 0;
}
proc load(a: ^i64) -> i64 {
return a^;
}
proc store(a: ^i64, value: i64) {
a^ = value;
}
proc compare_exchange(a: ^i64, expected, desired: i64) -> i64 {
return win32.interlocked_compare_exchange64(a, desired, expected);
}
proc exchanged(a: ^i64, desired: i64) -> i64 {
return win32.interlocked_exchange64(a, desired);
}
proc fetch_add(a: ^i64, operand: i64) -> i64 {
return win32.interlocked_exchange_add64(a, operand);
}
proc fetch_and(a: ^i64, operand: i64) -> i64 {
return win32.interlocked_and64(a, operand);
}
proc fetch_or(a: ^i64, operand: i64) -> i64 {
return win32.interlocked_or64(a, operand);
}
proc spin_lock(a: ^i64, time_out: int) -> bool { // NOTE(bill) time_out = -1 as default
var old_value = compare_exchange(a, 1, 0);
var counter = 0;
for old_value != 0 && (time_out < 0 || counter < time_out) {
counter++;
yield_thread();
old_value = compare_exchange(a, 1, 0);
mfence();
}
return old_value == 0;
}
proc spin_unlock(a: ^i64) {
store(a, 0);
mfence();
}
proc try_acquire_lock(a: ^i64) -> bool {
yield_thread();
var old_value = compare_exchange(a, 1, 0);
mfence();
return old_value == 0;
}
-287
View File
@@ -1,287 +0,0 @@
const (
U8_MIN = u8(0);
U16_MIN = u16(0);
U32_MIN = u32(0);
U64_MIN = u64(0);
U128_MIN = u128(0);
I8_MIN = i8(-0x80);
I16_MIN = i16(-0x8000);
I32_MIN = i32(-0x8000_0000);
I64_MIN = i64(-0x8000_0000_0000_0000);
I128_MIN = i128(-0x8000_0000_0000_0000_0000_0000_0000_0000);
U8_MAX = ~u8(0);
U16_MAX = ~u16(0);
U32_MAX = ~u32(0);
U64_MAX = ~u64(0);
U128_MAX = ~u128(0);
I8_MAX = i8(0x7f);
I16_MAX = i16(0x7fff);
I32_MAX = i32(0x7fff_ffff);
I64_MAX = i64(0x7fff_ffff_ffff_ffff);
I128_MAX = i128(0x7fff_ffff_ffff_ffff_ffff_ffff_ffff_ffff);
)
proc count_ones(i: u8) -> u8 { foreign __llvm_core proc __llvm_ctpop(u8) -> u8 #link_name "llvm.ctpop.i8"; return __llvm_ctpop(i); }
proc count_ones(i: i8) -> i8 { foreign __llvm_core proc __llvm_ctpop(i8) -> i8 #link_name "llvm.ctpop.i8"; return __llvm_ctpop(i); }
proc count_ones(i: u16) -> u16 { foreign __llvm_core proc __llvm_ctpop(u16) -> u16 #link_name "llvm.ctpop.i16"; return __llvm_ctpop(i); }
proc count_ones(i: i16) -> i16 { foreign __llvm_core proc __llvm_ctpop(i16) -> i16 #link_name "llvm.ctpop.i16"; return __llvm_ctpop(i); }
proc count_ones(i: u32) -> u32 { foreign __llvm_core proc __llvm_ctpop(u32) -> u32 #link_name "llvm.ctpop.i32"; return __llvm_ctpop(i); }
proc count_ones(i: i32) -> i32 { foreign __llvm_core proc __llvm_ctpop(i32) -> i32 #link_name "llvm.ctpop.i32"; return __llvm_ctpop(i); }
proc count_ones(i: u64) -> u64 { foreign __llvm_core proc __llvm_ctpop(u64) -> u64 #link_name "llvm.ctpop.i64"; return __llvm_ctpop(i); }
proc count_ones(i: i64) -> i64 { foreign __llvm_core proc __llvm_ctpop(i64) -> i64 #link_name "llvm.ctpop.i64"; return __llvm_ctpop(i); }
proc count_ones(i: u128) -> u128 { foreign __llvm_core proc __llvm_ctpop(u128) -> u128 #link_name "llvm.ctpop.i128";return __llvm_ctpop(i); }
proc count_ones(i: i128) -> i128 { foreign __llvm_core proc __llvm_ctpop(i128) -> i128 #link_name "llvm.ctpop.i128";return __llvm_ctpop(i); }
proc count_ones(i: uint) -> uint { when size_of(uint) == size_of(u32) { return uint(count_ones(u32(i))); } else { return uint(count_ones(u64(i))); } }
proc count_ones(i: int) -> int { when size_of(int) == size_of(i32) { return int(count_ones(i32(i))); } else { return int(count_ones(i64(i))); } }
proc count_zeros(i: u8) -> u8 { return 8 - count_ones(i); }
proc count_zeros(i: i8) -> i8 { return 8 - count_ones(i); }
proc count_zeros(i: u16) -> u16 { return 16 - count_ones(i); }
proc count_zeros(i: i16) -> i16 { return 16 - count_ones(i); }
proc count_zeros(i: u32) -> u32 { return 32 - count_ones(i); }
proc count_zeros(i: i32) -> i32 { return 32 - count_ones(i); }
proc count_zeros(i: u64) -> u64 { return 64 - count_ones(i); }
proc count_zeros(i: i64) -> i64 { return 64 - count_ones(i); }
proc count_zeros(i: u128) -> u128 { return 128 - count_ones(i); }
proc count_zeros(i: i128) -> i128 { return 128 - count_ones(i); }
proc count_zeros(i: uint) -> uint { return 8*size_of(uint) - count_ones(i); }
proc count_zeros(i: int) -> int { return 8*size_of(int) - count_ones(i); }
proc rotate_left(i: u8, s: uint) -> u8 { return (i << s)|(i >> (8*size_of(u8) - s)); }
proc rotate_left(i: i8, s: uint) -> i8 { return (i << s)|(i >> (8*size_of(i8) - s)); }
proc rotate_left(i: u16, s: uint) -> u16 { return (i << s)|(i >> (8*size_of(u16) - s)); }
proc rotate_left(i: i16, s: uint) -> i16 { return (i << s)|(i >> (8*size_of(i16) - s)); }
proc rotate_left(i: u32, s: uint) -> u32 { return (i << s)|(i >> (8*size_of(u32) - s)); }
proc rotate_left(i: i32, s: uint) -> i32 { return (i << s)|(i >> (8*size_of(i32) - s)); }
proc rotate_left(i: u64, s: uint) -> u64 { return (i << s)|(i >> (8*size_of(u64) - s)); }
proc rotate_left(i: i64, s: uint) -> i64 { return (i << s)|(i >> (8*size_of(i64) - s)); }
proc rotate_left(i: u128, s: uint) -> u128 { return (i << s)|(i >> (8*size_of(u128) - s)); }
proc rotate_left(i: i128, s: uint) -> i128 { return (i << s)|(i >> (8*size_of(i128) - s)); }
proc rotate_left(i: uint, s: uint) -> uint { when size_of(uint) == size_of(u32) { return uint(rotate_left(u32(i), s)); } else { return uint(rotate_left(u64(i), s)); } }
proc rotate_left(i: int, s: uint) -> int { when size_of(int) == size_of(i32) { return int(rotate_left(i32(i), s)); } else { return int(rotate_left(i64(i), s)); } }
proc rotate_right(i: u8, s: uint) -> u8 { return (i >> s)|(i << (8*size_of(u8) - s)); }
proc rotate_right(i: i8, s: uint) -> i8 { return (i >> s)|(i << (8*size_of(i8) - s)); }
proc rotate_right(i: u16, s: uint) -> u16 { return (i >> s)|(i << (8*size_of(u16) - s)); }
proc rotate_right(i: i16, s: uint) -> i16 { return (i >> s)|(i << (8*size_of(i16) - s)); }
proc rotate_right(i: u32, s: uint) -> u32 { return (i >> s)|(i << (8*size_of(u32) - s)); }
proc rotate_right(i: i32, s: uint) -> i32 { return (i >> s)|(i << (8*size_of(i32) - s)); }
proc rotate_right(i: u64, s: uint) -> u64 { return (i >> s)|(i << (8*size_of(u64) - s)); }
proc rotate_right(i: i64, s: uint) -> i64 { return (i >> s)|(i << (8*size_of(i64) - s)); }
proc rotate_right(i: u128, s: uint) -> u128 { return (i >> s)|(i << (8*size_of(u128) - s)); }
proc rotate_right(i: i128, s: uint) -> i128 { return (i >> s)|(i << (8*size_of(i128) - s)); }
proc rotate_right(i: uint, s: uint) -> uint { when size_of(uint) == size_of(u32) { return uint(rotate_right(u32(i), s)); } else { return uint(rotate_right(u64(i), s)); } }
proc rotate_right(i: int, s: uint) -> int { when size_of(int) == size_of(i32) { return int(rotate_right(i32(i), s)); } else { return int(rotate_right(i64(i), s)); } }
proc leading_zeros(i: u8) -> u8 { foreign __llvm_core proc __llvm_ctlz(u8, bool) -> u8 #link_name "llvm.ctlz.i8"; return __llvm_ctlz(i, false); }
proc leading_zeros(i: i8) -> i8 { foreign __llvm_core proc __llvm_ctlz(i8, bool) -> i8 #link_name "llvm.ctlz.i8"; return __llvm_ctlz(i, false); }
proc leading_zeros(i: u16) -> u16 { foreign __llvm_core proc __llvm_ctlz(u16, bool) -> u16 #link_name "llvm.ctlz.i16"; return __llvm_ctlz(i, false); }
proc leading_zeros(i: i16) -> i16 { foreign __llvm_core proc __llvm_ctlz(i16, bool) -> i16 #link_name "llvm.ctlz.i16"; return __llvm_ctlz(i, false); }
proc leading_zeros(i: u32) -> u32 { foreign __llvm_core proc __llvm_ctlz(u32, bool) -> u32 #link_name "llvm.ctlz.i32"; return __llvm_ctlz(i, false); }
proc leading_zeros(i: i32) -> i32 { foreign __llvm_core proc __llvm_ctlz(i32, bool) -> i32 #link_name "llvm.ctlz.i32"; return __llvm_ctlz(i, false); }
proc leading_zeros(i: u64) -> u64 { foreign __llvm_core proc __llvm_ctlz(u64, bool) -> u64 #link_name "llvm.ctlz.i64"; return __llvm_ctlz(i, false); }
proc leading_zeros(i: i64) -> i64 { foreign __llvm_core proc __llvm_ctlz(i64, bool) -> i64 #link_name "llvm.ctlz.i64"; return __llvm_ctlz(i, false); }
proc leading_zeros(i: u128) -> u128 { foreign __llvm_core proc __llvm_ctlz(u128, bool) -> u128 #link_name "llvm.ctlz.i128";return __llvm_ctlz(i, false); }
proc leading_zeros(i: i128) -> i128 { foreign __llvm_core proc __llvm_ctlz(i128, bool) -> i128 #link_name "llvm.ctlz.i128";return __llvm_ctlz(i, false); }
proc leading_zeros(i: uint) -> uint { when size_of(uint) == size_of(u32) { return uint(leading_zeros(u32(i))); } else { return uint(leading_zeros(u64(i))); } }
proc leading_zeros(i: int) -> int { when size_of(int) == size_of(i32) { return int(leading_zeros(i32(i))); } else { return int(leading_zeros(i64(i))); } }
proc trailing_zeros(i: u8) -> u8 { foreign __llvm_core proc __llvm_cttz(u8, bool) -> u8 #link_name "llvm.cttz.i8"; return __llvm_cttz(i, false); }
proc trailing_zeros(i: i8) -> i8 { foreign __llvm_core proc __llvm_cttz(i8, bool) -> i8 #link_name "llvm.cttz.i8"; return __llvm_cttz(i, false); }
proc trailing_zeros(i: u16) -> u16 { foreign __llvm_core proc __llvm_cttz(u16, bool) -> u16 #link_name "llvm.cttz.i16"; return __llvm_cttz(i, false); }
proc trailing_zeros(i: i16) -> i16 { foreign __llvm_core proc __llvm_cttz(i16, bool) -> i16 #link_name "llvm.cttz.i16"; return __llvm_cttz(i, false); }
proc trailing_zeros(i: u32) -> u32 { foreign __llvm_core proc __llvm_cttz(u32, bool) -> u32 #link_name "llvm.cttz.i32"; return __llvm_cttz(i, false); }
proc trailing_zeros(i: i32) -> i32 { foreign __llvm_core proc __llvm_cttz(i32, bool) -> i32 #link_name "llvm.cttz.i32"; return __llvm_cttz(i, false); }
proc trailing_zeros(i: u64) -> u64 { foreign __llvm_core proc __llvm_cttz(u64, bool) -> u64 #link_name "llvm.cttz.i64"; return __llvm_cttz(i, false); }
proc trailing_zeros(i: i64) -> i64 { foreign __llvm_core proc __llvm_cttz(i64, bool) -> i64 #link_name "llvm.cttz.i64"; return __llvm_cttz(i, false); }
proc trailing_zeros(i: u128) -> u128 { foreign __llvm_core proc __llvm_cttz(u128, bool) -> u128 #link_name "llvm.cttz.i128";return __llvm_cttz(i, false); }
proc trailing_zeros(i: i128) -> i128 { foreign __llvm_core proc __llvm_cttz(i128, bool) -> i128 #link_name "llvm.cttz.i128";return __llvm_cttz(i, false); }
proc trailing_zeros(i: uint) -> uint { when size_of(uint) == size_of(u32) { return uint(trailing_zeros(u32(i))); } else { return uint(trailing_zeros(u64(i))); } }
proc trailing_zeros(i: int) -> int { when size_of(int) == size_of(i32) { return int(trailing_zeros(i32(i))); } else { return int(trailing_zeros(i64(i))); } }
proc reverse_bits(i: u8) -> u8 { foreign __llvm_core proc __llvm_bitreverse(u8) -> u8 #link_name "llvm.bitreverse.i8"; return __llvm_bitreverse(i); }
proc reverse_bits(i: i8) -> i8 { foreign __llvm_core proc __llvm_bitreverse(i8) -> i8 #link_name "llvm.bitreverse.i8"; return __llvm_bitreverse(i); }
proc reverse_bits(i: u16) -> u16 { foreign __llvm_core proc __llvm_bitreverse(u16) -> u16 #link_name "llvm.bitreverse.i16"; return __llvm_bitreverse(i); }
proc reverse_bits(i: i16) -> i16 { foreign __llvm_core proc __llvm_bitreverse(i16) -> i16 #link_name "llvm.bitreverse.i16"; return __llvm_bitreverse(i); }
proc reverse_bits(i: u32) -> u32 { foreign __llvm_core proc __llvm_bitreverse(u32) -> u32 #link_name "llvm.bitreverse.i32"; return __llvm_bitreverse(i); }
proc reverse_bits(i: i32) -> i32 { foreign __llvm_core proc __llvm_bitreverse(i32) -> i32 #link_name "llvm.bitreverse.i32"; return __llvm_bitreverse(i); }
proc reverse_bits(i: u64) -> u64 { foreign __llvm_core proc __llvm_bitreverse(u64) -> u64 #link_name "llvm.bitreverse.i64"; return __llvm_bitreverse(i); }
proc reverse_bits(i: i64) -> i64 { foreign __llvm_core proc __llvm_bitreverse(i64) -> i64 #link_name "llvm.bitreverse.i64"; return __llvm_bitreverse(i); }
proc reverse_bits(i: u128) -> u128 { foreign __llvm_core proc __llvm_bitreverse(u128) -> u128 #link_name "llvm.bitreverse.i128";return __llvm_bitreverse(i); }
proc reverse_bits(i: i128) -> i128 { foreign __llvm_core proc __llvm_bitreverse(i128) -> i128 #link_name "llvm.bitreverse.i128";return __llvm_bitreverse(i); }
proc reverse_bits(i: uint) -> uint { when size_of(uint) == size_of(u32) { return uint(reverse_bits(u32(i))); } else { return uint(reverse_bits(u64(i))); } }
proc reverse_bits(i: int) -> int { when size_of(int) == size_of(i32) { return int(reverse_bits(i32(i))); } else { return int(reverse_bits(i64(i))); } }
foreign __llvm_core {
proc byte_swap(u16) -> u16 #link_name "llvm.bswap.i16";
proc byte_swap(i16) -> i16 #link_name "llvm.bswap.i16";
proc byte_swap(u32) -> u32 #link_name "llvm.bswap.i32";
proc byte_swap(i32) -> i32 #link_name "llvm.bswap.i32";
proc byte_swap(u64) -> u64 #link_name "llvm.bswap.i64";
proc byte_swap(i64) -> i64 #link_name "llvm.bswap.i64";
proc byte_swap(u128) -> u128 #link_name "llvm.bswap.i128";
proc byte_swap(i128) -> i128 #link_name "llvm.bswap.i128";
}
proc byte_swap(i: uint) -> uint { when size_of(uint) == size_of(u32) { return uint(byte_swap(u32(i))); } else { return uint(byte_swap(u64(i))); } }
proc byte_swap(i: int) -> int { when size_of(int) == size_of(i32) { return int(byte_swap(i32(i))); } else { return int(byte_swap(i64(i))); } }
proc from_be(i: u8) -> u8 { return i; }
proc from_be(i: i8) -> i8 { return i; }
proc from_be(i: u16) -> u16 { when ODIN_ENDIAN == "big" { return i; } else { return byte_swap(i); } }
proc from_be(i: i16) -> i16 { when ODIN_ENDIAN == "big" { return i; } else { return byte_swap(i); } }
proc from_be(i: u32) -> u32 { when ODIN_ENDIAN == "big" { return i; } else { return byte_swap(i); } }
proc from_be(i: i32) -> i32 { when ODIN_ENDIAN == "big" { return i; } else { return byte_swap(i); } }
proc from_be(i: u64) -> u64 { when ODIN_ENDIAN == "big" { return i; } else { return byte_swap(i); } }
proc from_be(i: i64) -> i64 { when ODIN_ENDIAN == "big" { return i; } else { return byte_swap(i); } }
proc from_be(i: u128) -> u128 { when ODIN_ENDIAN == "big" { return i; } else { return byte_swap(i); } }
proc from_be(i: i128) -> i128 { when ODIN_ENDIAN == "big" { return i; } else { return byte_swap(i); } }
proc from_be(i: uint) -> uint { when ODIN_ENDIAN == "big" { return i; } else { return byte_swap(i); } }
proc from_be(i: int) -> int { when ODIN_ENDIAN == "big" { return i; } else { return byte_swap(i); } }
proc from_le(i: u8) -> u8 { return i; }
proc from_le(i: i8) -> i8 { return i; }
proc from_le(i: u16) -> u16 { when ODIN_ENDIAN == "little" { return i; } else { return byte_swap(i); } }
proc from_le(i: i16) -> i16 { when ODIN_ENDIAN == "little" { return i; } else { return byte_swap(i); } }
proc from_le(i: u32) -> u32 { when ODIN_ENDIAN == "little" { return i; } else { return byte_swap(i); } }
proc from_le(i: i32) -> i32 { when ODIN_ENDIAN == "little" { return i; } else { return byte_swap(i); } }
proc from_le(i: u64) -> u64 { when ODIN_ENDIAN == "little" { return i; } else { return byte_swap(i); } }
proc from_le(i: i64) -> i64 { when ODIN_ENDIAN == "little" { return i; } else { return byte_swap(i); } }
proc from_le(i: u128) -> u128 { when ODIN_ENDIAN == "little" { return i; } else { return byte_swap(i); } }
proc from_le(i: i128) -> i128 { when ODIN_ENDIAN == "little" { return i; } else { return byte_swap(i); } }
proc from_le(i: uint) -> uint { when ODIN_ENDIAN == "little" { return i; } else { return byte_swap(i); } }
proc from_le(i: int) -> int { when ODIN_ENDIAN == "little" { return i; } else { return byte_swap(i); } }
proc to_be(i: u8) -> u8 { return i; }
proc to_be(i: i8) -> i8 { return i; }
proc to_be(i: u16) -> u16 { when ODIN_ENDIAN == "big" { return i; } else { return byte_swap(i); } }
proc to_be(i: i16) -> i16 { when ODIN_ENDIAN == "big" { return i; } else { return byte_swap(i); } }
proc to_be(i: u32) -> u32 { when ODIN_ENDIAN == "big" { return i; } else { return byte_swap(i); } }
proc to_be(i: i32) -> i32 { when ODIN_ENDIAN == "big" { return i; } else { return byte_swap(i); } }
proc to_be(i: u64) -> u64 { when ODIN_ENDIAN == "big" { return i; } else { return byte_swap(i); } }
proc to_be(i: i64) -> i64 { when ODIN_ENDIAN == "big" { return i; } else { return byte_swap(i); } }
proc to_be(i: u128) -> u128 { when ODIN_ENDIAN == "big" { return i; } else { return byte_swap(i); } }
proc to_be(i: i128) -> i128 { when ODIN_ENDIAN == "big" { return i; } else { return byte_swap(i); } }
proc to_be(i: uint) -> uint { when ODIN_ENDIAN == "big" { return i; } else { return byte_swap(i); } }
proc to_be(i: int) -> int { when ODIN_ENDIAN == "big" { return i; } else { return byte_swap(i); } }
proc to_le(i: u8) -> u8 { return i; }
proc to_le(i: i8) -> i8 { return i; }
proc to_le(i: u16) -> u16 { when ODIN_ENDIAN == "little" { return i; } else { return byte_swap(i); } }
proc to_le(i: i16) -> i16 { when ODIN_ENDIAN == "little" { return i; } else { return byte_swap(i); } }
proc to_le(i: u32) -> u32 { when ODIN_ENDIAN == "little" { return i; } else { return byte_swap(i); } }
proc to_le(i: i32) -> i32 { when ODIN_ENDIAN == "little" { return i; } else { return byte_swap(i); } }
proc to_le(i: u64) -> u64 { when ODIN_ENDIAN == "little" { return i; } else { return byte_swap(i); } }
proc to_le(i: i64) -> i64 { when ODIN_ENDIAN == "little" { return i; } else { return byte_swap(i); } }
proc to_le(i: u128) -> u128 { when ODIN_ENDIAN == "little" { return i; } else { return byte_swap(i); } }
proc to_le(i: i128) -> i128 { when ODIN_ENDIAN == "little" { return i; } else { return byte_swap(i); } }
proc to_le(i: uint) -> uint { when ODIN_ENDIAN == "little" { return i; } else { return byte_swap(i); } }
proc to_le(i: int) -> int { when ODIN_ENDIAN == "little" { return i; } else { return byte_swap(i); } }
proc overflowing_add(lhs, rhs: u8) -> (u8, bool) { foreign __llvm_core proc op(u8, u8) -> (u8, bool) #link_name "llvm.uadd.with.overflow.i8"; return op(lhs, rhs); }
proc overflowing_add(lhs, rhs: i8) -> (i8, bool) { foreign __llvm_core proc op(i8, i8) -> (i8, bool) #link_name "llvm.sadd.with.overflow.i8"; return op(lhs, rhs); }
proc overflowing_add(lhs, rhs: u16) -> (u16, bool) { foreign __llvm_core proc op(u16, u16) -> (u16, bool) #link_name "llvm.uadd.with.overflow.i16"; return op(lhs, rhs); }
proc overflowing_add(lhs, rhs: i16) -> (i16, bool) { foreign __llvm_core proc op(i16, i16) -> (i16, bool) #link_name "llvm.sadd.with.overflow.i16"; return op(lhs, rhs); }
proc overflowing_add(lhs, rhs: u32) -> (u32, bool) { foreign __llvm_core proc op(u32, u32) -> (u32, bool) #link_name "llvm.uadd.with.overflow.i32"; return op(lhs, rhs); }
proc overflowing_add(lhs, rhs: i32) -> (i32, bool) { foreign __llvm_core proc op(i32, i32) -> (i32, bool) #link_name "llvm.sadd.with.overflow.i32"; return op(lhs, rhs); }
proc overflowing_add(lhs, rhs: u64) -> (u64, bool) { foreign __llvm_core proc op(u64, u64) -> (u64, bool) #link_name "llvm.uadd.with.overflow.i64"; return op(lhs, rhs); }
proc overflowing_add(lhs, rhs: i64) -> (i64, bool) { foreign __llvm_core proc op(i64, i64) -> (i64, bool) #link_name "llvm.sadd.with.overflow.i64"; return op(lhs, rhs); }
proc overflowing_add(lhs, rhs: u128) -> (u128, bool) { foreign __llvm_core proc op(u128, u128) -> (u128, bool) #link_name "llvm.uadd.with.overflow.i128"; return op(lhs, rhs); }
proc overflowing_add(lhs, rhs: i128) -> (i128, bool) { foreign __llvm_core proc op(i128, i128) -> (i128, bool) #link_name "llvm.sadd.with.overflow.i128"; return op(lhs, rhs); }
proc overflowing_add(lhs, rhs: uint) -> (uint, bool) {
when size_of(uint) == size_of(u32) {
var x, ok = overflowing_add(u32(lhs), u32(rhs));
return uint(x), ok;
} else {
var x, ok = overflowing_add(u64(lhs), u64(rhs));
return uint(x), ok;
}
}
proc overflowing_add(lhs, rhs: int) -> (int, bool) {
when size_of(int) == size_of(i32) {
var x, ok = overflowing_add(i32(lhs), i32(rhs));
return int(x), ok;
} else {
var x, ok = overflowing_add(i64(lhs), i64(rhs));
return int(x), ok;
}
}
proc overflowing_sub(lhs, rhs: u8) -> (u8, bool) { foreign __llvm_core proc op(u8, u8) -> (u8, bool) #link_name "llvm.usub.with.overflow.i8"; return op(lhs, rhs); }
proc overflowing_sub(lhs, rhs: i8) -> (i8, bool) { foreign __llvm_core proc op(i8, i8) -> (i8, bool) #link_name "llvm.ssub.with.overflow.i8"; return op(lhs, rhs); }
proc overflowing_sub(lhs, rhs: u16) -> (u16, bool) { foreign __llvm_core proc op(u16, u16) -> (u16, bool) #link_name "llvm.usub.with.overflow.i16"; return op(lhs, rhs); }
proc overflowing_sub(lhs, rhs: i16) -> (i16, bool) { foreign __llvm_core proc op(i16, i16) -> (i16, bool) #link_name "llvm.ssub.with.overflow.i16"; return op(lhs, rhs); }
proc overflowing_sub(lhs, rhs: u32) -> (u32, bool) { foreign __llvm_core proc op(u32, u32) -> (u32, bool) #link_name "llvm.usub.with.overflow.i32"; return op(lhs, rhs); }
proc overflowing_sub(lhs, rhs: i32) -> (i32, bool) { foreign __llvm_core proc op(i32, i32) -> (i32, bool) #link_name "llvm.ssub.with.overflow.i32"; return op(lhs, rhs); }
proc overflowing_sub(lhs, rhs: u64) -> (u64, bool) { foreign __llvm_core proc op(u64, u64) -> (u64, bool) #link_name "llvm.usub.with.overflow.i64"; return op(lhs, rhs); }
proc overflowing_sub(lhs, rhs: i64) -> (i64, bool) { foreign __llvm_core proc op(i64, i64) -> (i64, bool) #link_name "llvm.ssub.with.overflow.i64"; return op(lhs, rhs); }
proc overflowing_sub(lhs, rhs: u128) -> (u128, bool) { foreign __llvm_core proc op(u128, u128) -> (u128, bool) #link_name "llvm.usub.with.overflow.i128"; return op(lhs, rhs); }
proc overflowing_sub(lhs, rhs: i128) -> (i128, bool) { foreign __llvm_core proc op(i128, i128) -> (i128, bool) #link_name "llvm.ssub.with.overflow.i128"; return op(lhs, rhs); }
proc overflowing_sub(lhs, rhs: uint) -> (uint, bool) {
when size_of(uint) == size_of(u32) {
var x, ok = overflowing_sub(u32(lhs), u32(rhs));
return uint(x), ok;
} else {
var x, ok = overflowing_sub(u64(lhs), u64(rhs));
return uint(x), ok;
}
}
proc overflowing_sub(lhs, rhs: int) -> (int, bool) {
when size_of(int) == size_of(i32) {
var x, ok = overflowing_sub(i32(lhs), i32(rhs));
return int(x), ok;
} else {
var x, ok = overflowing_sub(i64(lhs), i64(rhs));
return int(x), ok;
}
}
proc overflowing_mul(lhs, rhs: u8) -> (u8, bool) { foreign __llvm_core proc op(u8, u8) -> (u8, bool) #link_name "llvm.umul.with.overflow.i8"; return op(lhs, rhs); }
proc overflowing_mul(lhs, rhs: i8) -> (i8, bool) { foreign __llvm_core proc op(i8, i8) -> (i8, bool) #link_name "llvm.smul.with.overflow.i8"; return op(lhs, rhs); }
proc overflowing_mul(lhs, rhs: u16) -> (u16, bool) { foreign __llvm_core proc op(u16, u16) -> (u16, bool) #link_name "llvm.umul.with.overflow.i16"; return op(lhs, rhs); }
proc overflowing_mul(lhs, rhs: i16) -> (i16, bool) { foreign __llvm_core proc op(i16, i16) -> (i16, bool) #link_name "llvm.smul.with.overflow.i16"; return op(lhs, rhs); }
proc overflowing_mul(lhs, rhs: u32) -> (u32, bool) { foreign __llvm_core proc op(u32, u32) -> (u32, bool) #link_name "llvm.umul.with.overflow.i32"; return op(lhs, rhs); }
proc overflowing_mul(lhs, rhs: i32) -> (i32, bool) { foreign __llvm_core proc op(i32, i32) -> (i32, bool) #link_name "llvm.smul.with.overflow.i32"; return op(lhs, rhs); }
proc overflowing_mul(lhs, rhs: u64) -> (u64, bool) { foreign __llvm_core proc op(u64, u64) -> (u64, bool) #link_name "llvm.umul.with.overflow.i64"; return op(lhs, rhs); }
proc overflowing_mul(lhs, rhs: i64) -> (i64, bool) { foreign __llvm_core proc op(i64, i64) -> (i64, bool) #link_name "llvm.smul.with.overflow.i64"; return op(lhs, rhs); }
proc overflowing_mul(lhs, rhs: u128) -> (u128, bool) { foreign __llvm_core proc op(u128, u128) -> (u128, bool) #link_name "llvm.umul.with.overflow.i128"; return op(lhs, rhs); }
proc overflowing_mul(lhs, rhs: i128) -> (i128, bool) { foreign __llvm_core proc op(i128, i128) -> (i128, bool) #link_name "llvm.smul.with.overflow.i128"; return op(lhs, rhs); }
proc overflowing_mul(lhs, rhs: uint) -> (uint, bool) {
when size_of(uint) == size_of(u32) {
var x, ok = overflowing_mul(u32(lhs), u32(rhs));
return uint(x), ok;
} else {
var x, ok = overflowing_mul(u64(lhs), u64(rhs));
return uint(x), ok;
}
}
proc overflowing_mul(lhs, rhs: int) -> (int, bool) {
when size_of(int) == size_of(i32) {
var x, ok = overflowing_mul(i32(lhs), i32(rhs));
return int(x), ok;
} else {
var x, ok = overflowing_mul(i64(lhs), i64(rhs));
return int(x), ok;
}
}
proc is_power_of_two(i: u8) -> bool { return i > 0 && (i & (i-1)) == 0; }
proc is_power_of_two(i: i8) -> bool { return i > 0 && (i & (i-1)) == 0; }
proc is_power_of_two(i: u16) -> bool { return i > 0 && (i & (i-1)) == 0; }
proc is_power_of_two(i: i16) -> bool { return i > 0 && (i & (i-1)) == 0; }
proc is_power_of_two(i: u32) -> bool { return i > 0 && (i & (i-1)) == 0; }
proc is_power_of_two(i: i32) -> bool { return i > 0 && (i & (i-1)) == 0; }
proc is_power_of_two(i: u64) -> bool { return i > 0 && (i & (i-1)) == 0; }
proc is_power_of_two(i: i64) -> bool { return i > 0 && (i & (i-1)) == 0; }
proc is_power_of_two(i: u128) -> bool { return i > 0 && (i & (i-1)) == 0; }
proc is_power_of_two(i: i128) -> bool { return i > 0 && (i & (i-1)) == 0; }
proc is_power_of_two(i: uint) -> bool { return i > 0 && (i & (i-1)) == 0; }
proc is_power_of_two(i: int) -> bool { return i > 0 && (i & (i-1)) == 0; }
+253
View File
@@ -0,0 +1,253 @@
package bits
import "core:os"
U8_MIN :: 0;
U16_MIN :: 0;
U32_MIN :: 0;
U64_MIN :: 0;
U8_MAX :: 1 << 8 - 1;
U16_MAX :: 1 << 16 - 1;
U32_MAX :: 1 << 32 - 1;
U64_MAX :: 1 << 64 - 1;
I8_MIN :: - 1 << 7;
I16_MIN :: - 1 << 15;
I32_MIN :: - 1 << 31;
I64_MIN :: - 1 << 63;
I8_MAX :: 1 << 7 - 1;
I16_MAX :: 1 << 15 - 1;
I32_MAX :: 1 << 31 - 1;
I64_MAX :: 1 << 63 - 1;
foreign {
@(link_name="llvm.ctpop.i8") count_ones8 :: proc(i: u8) -> u8 ---
@(link_name="llvm.ctpop.i16") count_ones16 :: proc(i: u16) -> u16 ---
@(link_name="llvm.ctpop.i32") count_ones32 :: proc(i: u32) -> u32 ---
@(link_name="llvm.ctpop.i64") count_ones64 :: proc(i: u64) -> u64 ---
@(link_name="llvm.ctlz.i8") leading_zeros8 :: proc(i: u8, is_zero_undef := false) -> u8 ---
@(link_name="llvm.ctlz.i16") leading_zeros16 :: proc(i: u16, is_zero_undef := false) -> u16 ---
@(link_name="llvm.ctlz.i32") leading_zeros32 :: proc(i: u32, is_zero_undef := false) -> u32 ---
@(link_name="llvm.ctlz.i64") leading_zeros64 :: proc(i: u64, is_zero_undef := false) -> u64 ---
@(link_name="llvm.cttz.i8") trailing_zeros8 :: proc(i: u8, is_zero_undef := false) -> u8 ---
@(link_name="llvm.cttz.i16") trailing_zeros16 :: proc(i: u16, is_zero_undef := false) -> u16 ---
@(link_name="llvm.cttz.i32") trailing_zeros32 :: proc(i: u32, is_zero_undef := false) -> u32 ---
@(link_name="llvm.cttz.i64") trailing_zeros64 :: proc(i: u64, is_zero_undef := false) -> u64 ---
@(link_name="llvm.bitreverse.i8") reverse_bits8 :: proc(i: u8) -> u8 ---
@(link_name="llvm.bitreverse.i16") reverse_bits16 :: proc(i: u16) -> u16 ---
@(link_name="llvm.bitreverse.i32") reverse_bits32 :: proc(i: u32) -> u32 ---
@(link_name="llvm.bitreverse.i64") reverse_bits64 :: proc(i: u64) -> u64 ---
@(link_name="llvm.bswap.i16") byte_swap_u16 :: proc(u16) -> u16 ---
@(link_name="llvm.bswap.i32") byte_swap_u32 :: proc(u32) -> u32 ---
@(link_name="llvm.bswap.i64") byte_swap_u64 :: proc(u64) -> u64 ---
@(link_name="llvm.bswap.i16") byte_swap_i16 :: proc(i16) -> i16 ---
@(link_name="llvm.bswap.i32") byte_swap_i32 :: proc(i32) -> i32 ---
@(link_name="llvm.bswap.i64") byte_swap_i64 :: proc(i64) -> i64 ---
}
byte_swap_uint :: proc(i: uint) -> uint {
when size_of(uint) == size_of(u32) {
return uint(byte_swap_u32(u32(i)));
} else {
return uint(byte_swap_u64(u64(i)));
}
}
byte_swap_int :: proc(i: int) -> int {
when size_of(int) == size_of(i32) {
return int(byte_swap_i32(i32(i)));
} else {
return int(byte_swap_i64(i64(i)));
}
}
byte_swap :: proc[
byte_swap_u16,
byte_swap_u32,
byte_swap_u64,
byte_swap_i16,
byte_swap_i32,
byte_swap_i64,
byte_swap_uint,
byte_swap_int,
];
count_zeros8 :: proc(i: u8) -> u8 { return 8 - count_ones8(i); }
count_zeros16 :: proc(i: u16) -> u16 { return 16 - count_ones16(i); }
count_zeros32 :: proc(i: u32) -> u32 { return 32 - count_ones32(i); }
count_zeros64 :: proc(i: u64) -> u64 { return 64 - count_ones64(i); }
rotate_left8 :: proc(i: u8, s: uint) -> u8 { return (i << s)|(i >> (8*size_of(u8) - s)); }
rotate_left16 :: proc(i: u16, s: uint) -> u16 { return (i << s)|(i >> (8*size_of(u16) - s)); }
rotate_left32 :: proc(i: u32, s: uint) -> u32 { return (i << s)|(i >> (8*size_of(u32) - s)); }
rotate_left64 :: proc(i: u64, s: uint) -> u64 { return (i << s)|(i >> (8*size_of(u64) - s)); }
rotate_right8 :: proc(i: u8, s: uint) -> u8 { return (i >> s)|(i << (8*size_of(u8) - s)); }
rotate_right16 :: proc(i: u16, s: uint) -> u16 { return (i >> s)|(i << (8*size_of(u16) - s)); }
rotate_right32 :: proc(i: u32, s: uint) -> u32 { return (i >> s)|(i << (8*size_of(u32) - s)); }
rotate_right64 :: proc(i: u64, s: uint) -> u64 { return (i >> s)|(i << (8*size_of(u64) - s)); }
from_be_u8 :: proc(i: u8) -> u8 { return i; }
from_be_u16 :: proc(i: u16) -> u16 { when os.ENDIAN == "big" { return i; } else { return byte_swap(i); } }
from_be_u32 :: proc(i: u32) -> u32 { when os.ENDIAN == "big" { return i; } else { return byte_swap(i); } }
from_be_u64 :: proc(i: u64) -> u64 { when os.ENDIAN == "big" { return i; } else { return byte_swap(i); } }
from_be_uint :: proc(i: uint) -> uint { when os.ENDIAN == "big" { return i; } else { return byte_swap(i); } }
from_le_u8 :: proc(i: u8) -> u8 { return i; }
from_le_u16 :: proc(i: u16) -> u16 { when os.ENDIAN == "little" { return i; } else { return byte_swap(i); } }
from_le_u32 :: proc(i: u32) -> u32 { when os.ENDIAN == "little" { return i; } else { return byte_swap(i); } }
from_le_u64 :: proc(i: u64) -> u64 { when os.ENDIAN == "little" { return i; } else { return byte_swap(i); } }
from_le_uint :: proc(i: uint) -> uint { when os.ENDIAN == "little" { return i; } else { return byte_swap(i); } }
to_be_u8 :: proc(i: u8) -> u8 { return i; }
to_be_u16 :: proc(i: u16) -> u16 { when os.ENDIAN == "big" { return i; } else { return byte_swap(i); } }
to_be_u32 :: proc(i: u32) -> u32 { when os.ENDIAN == "big" { return i; } else { return byte_swap(i); } }
to_be_u64 :: proc(i: u64) -> u64 { when os.ENDIAN == "big" { return i; } else { return byte_swap(i); } }
to_be_uint :: proc(i: uint) -> uint { when os.ENDIAN == "big" { return i; } else { return byte_swap(i); } }
to_le_u8 :: proc(i: u8) -> u8 { return i; }
to_le_u16 :: proc(i: u16) -> u16 { when os.ENDIAN == "little" { return i; } else { return byte_swap(i); } }
to_le_u32 :: proc(i: u32) -> u32 { when os.ENDIAN == "little" { return i; } else { return byte_swap(i); } }
to_le_u64 :: proc(i: u64) -> u64 { when os.ENDIAN == "little" { return i; } else { return byte_swap(i); } }
to_le_uint :: proc(i: uint) -> uint { when os.ENDIAN == "little" { return i; } else { return byte_swap(i); } }
foreign {
@(link_name="llvm.uadd.with.overflow.i8") overflowing_add_u8 :: proc(lhs, rhs: u8) -> (u8, bool) ---
@(link_name="llvm.sadd.with.overflow.i8") overflowing_add_i8 :: proc(lhs, rhs: i8) -> (i8, bool) ---
@(link_name="llvm.uadd.with.overflow.i16") overflowing_add_u16 :: proc(lhs, rhs: u16) -> (u16, bool) ---
@(link_name="llvm.sadd.with.overflow.i16") overflowing_add_i16 :: proc(lhs, rhs: i16) -> (i16, bool) ---
@(link_name="llvm.uadd.with.overflow.i32") overflowing_add_u32 :: proc(lhs, rhs: u32) -> (u32, bool) ---
@(link_name="llvm.sadd.with.overflow.i32") overflowing_add_i32 :: proc(lhs, rhs: i32) -> (i32, bool) ---
@(link_name="llvm.uadd.with.overflow.i64") overflowing_add_u64 :: proc(lhs, rhs: u64) -> (u64, bool) ---
@(link_name="llvm.sadd.with.overflow.i64") overflowing_add_i64 :: proc(lhs, rhs: i64) -> (i64, bool) ---
}
overflowing_add_uint :: proc(lhs, rhs: uint) -> (uint, bool) {
when size_of(uint) == size_of(u32) {
x, ok := overflowing_add_u32(u32(lhs), u32(rhs));
return uint(x), ok;
} else {
x, ok := overflowing_add_u64(u64(lhs), u64(rhs));
return uint(x), ok;
}
}
overflowing_add_int :: proc(lhs, rhs: int) -> (int, bool) {
when size_of(int) == size_of(i32) {
x, ok := overflowing_add_i32(i32(lhs), i32(rhs));
return int(x), ok;
} else {
x, ok := overflowing_add_i64(i64(lhs), i64(rhs));
return int(x), ok;
}
}
overflowing_add :: proc[
overflowing_add_u8, overflowing_add_i8,
overflowing_add_u16, overflowing_add_i16,
overflowing_add_u32, overflowing_add_i32,
overflowing_add_u64, overflowing_add_i64,
overflowing_add_uint, overflowing_add_int,
];
foreign {
@(link_name="llvm.usub.with.overflow.i8") overflowing_sub_u8 :: proc(lhs, rhs: u8) -> (u8, bool) ---
@(link_name="llvm.ssub.with.overflow.i8") overflowing_sub_i8 :: proc(lhs, rhs: i8) -> (i8, bool) ---
@(link_name="llvm.usub.with.overflow.i16") overflowing_sub_u16 :: proc(lhs, rhs: u16) -> (u16, bool) ---
@(link_name="llvm.ssub.with.overflow.i16") overflowing_sub_i16 :: proc(lhs, rhs: i16) -> (i16, bool) ---
@(link_name="llvm.usub.with.overflow.i32") overflowing_sub_u32 :: proc(lhs, rhs: u32) -> (u32, bool) ---
@(link_name="llvm.ssub.with.overflow.i32") overflowing_sub_i32 :: proc(lhs, rhs: i32) -> (i32, bool) ---
@(link_name="llvm.usub.with.overflow.i64") overflowing_sub_u64 :: proc(lhs, rhs: u64) -> (u64, bool) ---
@(link_name="llvm.ssub.with.overflow.i64") overflowing_sub_i64 :: proc(lhs, rhs: i64) -> (i64, bool) ---
}
overflowing_sub_uint :: proc(lhs, rhs: uint) -> (uint, bool) {
when size_of(uint) == size_of(u32) {
x, ok := overflowing_sub_u32(u32(lhs), u32(rhs));
return uint(x), ok;
} else {
x, ok := overflowing_sub_u64(u64(lhs), u64(rhs));
return uint(x), ok;
}
}
overflowing_sub_int :: proc(lhs, rhs: int) -> (int, bool) {
when size_of(int) == size_of(i32) {
x, ok := overflowing_sub_i32(i32(lhs), i32(rhs));
return int(x), ok;
} else {
x, ok := overflowing_sub_i64(i64(lhs), i64(rhs));
return int(x), ok;
}
}
overflowing_sub :: proc[
overflowing_sub_u8, overflowing_sub_i8,
overflowing_sub_u16, overflowing_sub_i16,
overflowing_sub_u32, overflowing_sub_i32,
overflowing_sub_u64, overflowing_sub_i64,
overflowing_sub_uint, overflowing_sub_int,
];
foreign {
@(link_name="llvm.umul.with.overflow.i8") overflowing_mul_u8 :: proc(lhs, rhs: u8) -> (u8, bool) ---
@(link_name="llvm.smul.with.overflow.i8") overflowing_mul_i8 :: proc(lhs, rhs: i8) -> (i8, bool) ---
@(link_name="llvm.umul.with.overflow.i16") overflowing_mul_u16 :: proc(lhs, rhs: u16) -> (u16, bool) ---
@(link_name="llvm.smul.with.overflow.i16") overflowing_mul_i16 :: proc(lhs, rhs: i16) -> (i16, bool) ---
@(link_name="llvm.umul.with.overflow.i32") overflowing_mul_u32 :: proc(lhs, rhs: u32) -> (u32, bool) ---
@(link_name="llvm.smul.with.overflow.i32") overflowing_mul_i32 :: proc(lhs, rhs: i32) -> (i32, bool) ---
@(link_name="llvm.umul.with.overflow.i64") overflowing_mul_u64 :: proc(lhs, rhs: u64) -> (u64, bool) ---
@(link_name="llvm.smul.with.overflow.i64") overflowing_mul_i64 :: proc(lhs, rhs: i64) -> (i64, bool) ---
}
overflowing_mul_uint :: proc(lhs, rhs: uint) -> (uint, bool) {
when size_of(uint) == size_of(u32) {
x, ok := overflowing_mul_u32(u32(lhs), u32(rhs));
return uint(x), ok;
} else {
x, ok := overflowing_mul_u64(u64(lhs), u64(rhs));
return uint(x), ok;
}
}
overflowing_mul_int :: proc(lhs, rhs: int) -> (int, bool) {
when size_of(int) == size_of(i32) {
x, ok := overflowing_mul_i32(i32(lhs), i32(rhs));
return int(x), ok;
} else {
x, ok := overflowing_mul_i64(i64(lhs), i64(rhs));
return int(x), ok;
}
}
overflowing_mul :: proc[
overflowing_mul_u8, overflowing_mul_i8,
overflowing_mul_u16, overflowing_mul_i16,
overflowing_mul_u32, overflowing_mul_i32,
overflowing_mul_u64, overflowing_mul_i64,
overflowing_mul_uint, overflowing_mul_int,
];
is_power_of_two_u8 :: proc(i: u8) -> bool { return i > 0 && (i & (i-1)) == 0; }
is_power_of_two_i8 :: proc(i: i8) -> bool { return i > 0 && (i & (i-1)) == 0; }
is_power_of_two_u16 :: proc(i: u16) -> bool { return i > 0 && (i & (i-1)) == 0; }
is_power_of_two_i16 :: proc(i: i16) -> bool { return i > 0 && (i & (i-1)) == 0; }
is_power_of_two_u32 :: proc(i: u32) -> bool { return i > 0 && (i & (i-1)) == 0; }
is_power_of_two_i32 :: proc(i: i32) -> bool { return i > 0 && (i & (i-1)) == 0; }
is_power_of_two_u64 :: proc(i: u64) -> bool { return i > 0 && (i & (i-1)) == 0; }
is_power_of_two_i64 :: proc(i: i64) -> bool { return i > 0 && (i & (i-1)) == 0; }
is_power_of_two_uint :: proc(i: uint) -> bool { return i > 0 && (i & (i-1)) == 0; }
is_power_of_two_int :: proc(i: int) -> bool { return i > 0 && (i & (i-1)) == 0; }
is_power_of_two :: proc[
is_power_of_two_u8, is_power_of_two_i8,
is_power_of_two_u16, is_power_of_two_i16,
is_power_of_two_u32, is_power_of_two_i32,
is_power_of_two_u64, is_power_of_two_i64,
is_power_of_two_uint, is_power_of_two_int,
]
+34
View File
@@ -0,0 +1,34 @@
package c
import b "core:builtin"
import "core:os"
CHAR_BIT :: 8;
bool :: b.bool;
char :: b.u8;
byte :: b.byte;
schar :: b.i8;
uchar :: b.u8;
short :: b.i16;
ushort :: b.u16;
int :: b.i32;
uint :: b.u32;
long :: (os.OS == "windows" || size_of(b.rawptr) == 4) ? b.i32 : b.i64;
ulong :: (os.OS == "windows" || size_of(b.rawptr) == 4) ? b.u32 : b.u64;
longlong :: b.i64;
ulonglong :: b.u64;
float :: b.f32;
double :: b.f64;
complex_float :: b.complex64;
complex_double :: b.complex128;
#assert(size_of(b.uintptr) == size_of(b.int));
size_t :: b.uint;
ssize_t :: b.int;
ptrdiff_t :: b.int;
uintptr_t :: b.uintptr;
intptr_t :: b.int;
+80 -82
View File
@@ -1,54 +1,54 @@
// #import "fmt.odin";
// Multiple precision decimal numbers
// NOTE: This is only for floating point printing and nothing else
package decimal
type Decimal struct {
digits: [384]u8, // big-endian digits
Decimal :: struct {
digits: [384]byte, // big-endian digits
count: int,
decimal_point: int,
neg, trunc: bool,
}
proc decimal_to_string(buf: []u8, a: ^Decimal) -> string {
proc digit_zero(buf: []u8) -> int {
for _, i in buf -> buf[i] = '0';
decimal_to_string :: proc(buf: []byte, a: ^Decimal) -> string {
digit_zero :: proc(buf: []byte) -> int {
for _, i in buf do buf[i] = '0';
return len(buf);
}
var n = 10 + a.count + abs(a.decimal_point);
n := 10 + a.count + abs(a.decimal_point);
// TODO(bill): make this work with a buffer that's not big enough
assert(len(buf) >= n);
buf = buf[0..<n];
buf = buf[0:n];
if a.count == 0 {
buf[0] = '0';
return string(buf[0..<1]);
return string(buf[0:1]);
}
var w = 0;
w := 0;
if a.decimal_point <= 0 {
buf[w] = '0'; w++;
buf[w] = '.'; w++;
w += digit_zero(buf[w ..< w-a.decimal_point]);
w += copy(buf[w..], a.digits[0..<a.count]);
buf[w] = '0'; w += 1;
buf[w] = '.'; w += 1;
w += digit_zero(buf[w : w-a.decimal_point]);
w += copy(buf[w:], a.digits[0:a.count]);
} else if a.decimal_point < a.count {
w += copy(buf[w..], a.digits[0..<a.decimal_point]);
buf[w] = '.'; w++;
w += copy(buf[w..], a.digits[a.decimal_point ..< a.count]);
w += copy(buf[w:], a.digits[0:a.decimal_point]);
buf[w] = '.'; w += 1;
w += copy(buf[w:], a.digits[a.decimal_point : a.count]);
} else {
w += copy(buf[w..], a.digits[0..<a.count]);
w += digit_zero(buf[w ..< w+a.decimal_point-a.count]);
w += copy(buf[w:], a.digits[0:a.count]);
w += digit_zero(buf[w : w+a.decimal_point-a.count]);
}
return string(buf[0..<w]);
return string(buf[0:w]);
}
// trim trailing zeros
proc trim(a: ^Decimal) {
trim :: proc(a: ^Decimal) {
for a.count > 0 && a.digits[a.count-1] == '0' {
a.count--;
a.count -= 1;
}
if a.count == 0 {
a.decimal_point = 0;
@@ -56,21 +56,21 @@ proc trim(a: ^Decimal) {
}
proc assign(a: ^Decimal, i: u64) {
var buf: [32]u8;
var n = 0;
assign :: proc(a: ^Decimal, i: u64) {
buf: [64]byte;
n := 0;
for i > 0 {
var j = i/10;
j := i/10;
i -= 10*j;
buf[n] = u8('0'+i);
n++;
buf[n] = byte('0'+i);
n += 1;
i = j;
}
a.count = 0;
for n--; n >= 0; n-- {
for n -= 1; n >= 0; n -= 1 {
a.digits[a.count] = buf[n];
a.count++;
a.count += 1;
}
a.decimal_point = a.count;
trim(a);
@@ -78,12 +78,12 @@ proc assign(a: ^Decimal, i: u64) {
proc shift_right(a: ^Decimal, k: uint) {
var r = 0; // read index
var w = 0; // write index
shift_right :: proc(a: ^Decimal, k: uint) {
r := 0; // read index
w := 0; // write index
var n: uint;
for ; n>>k == 0; r++ {
n: uint;
for ; n>>k == 0; r += 1 {
if r >= a.count {
if n == 0 {
// Just in case
@@ -92,32 +92,32 @@ proc shift_right(a: ^Decimal, k: uint) {
}
for n>>k == 0 {
n = n * 10;
r++;
r += 1;
}
break;
}
var c = uint(a.digits[r]);
c := uint(a.digits[r]);
n = n*10 + c - '0';
}
a.decimal_point -= r-1;
var mask: uint = (1<<k) - 1;
mask: uint = (1<<k) - 1;
for ; r < a.count; r++ {
var c = uint(a.digits[r]);
var dig = n>>k;
for ; r < a.count; r += 1 {
c := uint(a.digits[r]);
dig := n>>k;
n &= mask;
a.digits[w] = u8('0' + dig);
w++;
a.digits[w] = byte('0' + dig);
w += 1;
n = n*10 + c - '0';
}
for n > 0 {
var dig = n>>k;
dig := n>>k;
n &= mask;
if w < len(a.digits) {
a.digits[w] = u8('0' + dig);
w++;
a.digits[w] = byte('0' + dig);
w += 1;
} else if dig > 0 {
a.trunc = true;
}
@@ -129,20 +129,20 @@ proc shift_right(a: ^Decimal, k: uint) {
trim(a);
}
proc shift_left(a: ^Decimal, k: uint) {
var delta = int(k/4);
shift_left :: proc(a: ^Decimal, k: uint) {
delta := int(k/4);
var r = a.count; // read index
var w = a.count+delta; // write index
r := a.count; // read index
w := a.count+delta; // write index
var n: uint;
for r--; r >= 0; r-- {
n: uint;
for r -= 1; r >= 0; r -= 1 {
n += (uint(a.digits[r]) - '0') << k;
var quo = n/10;
var rem = n - 10*quo;
w--;
quo := n/10;
rem := n - 10*quo;
w -= 1;
if w < len(a.digits) {
a.digits[w] = u8('0' + rem);
a.digits[w] = byte('0' + rem);
} else if rem != 0 {
a.trunc = true;
}
@@ -150,11 +150,11 @@ proc shift_left(a: ^Decimal, k: uint) {
}
for n > 0 {
var quo = n/10;
var rem = n - 10*quo;
w--;
quo := n/10;
rem := n - 10*quo;
w -= 1;
if 0 <= w && w < len(a.digits) {
a.digits[w] = u8('0' + rem);
a.digits[w] = byte('0' + rem);
} else if rem != 0 {
a.trunc = true;
}
@@ -167,13 +167,11 @@ proc shift_left(a: ^Decimal, k: uint) {
trim(a);
}
proc shift(a: ^Decimal, k: int) {
const (
uint_size = 8*size_of(uint);
max_shift = uint_size-4;
)
shift :: proc(a: ^Decimal, k: int) {
uint_size :: 8*size_of(uint);
max_shift :: uint_size-4;
match {
switch {
case a.count == 0:
// no need to update
case k > 0:
@@ -193,17 +191,17 @@ proc shift(a: ^Decimal, k: int) {
}
}
proc can_round_up(a: ^Decimal, nd: int) -> bool {
can_round_up :: proc(a: ^Decimal, nd: int) -> bool {
if nd < 0 || nd >= a.count { return false ; }
if a.digits[nd] == '5' && nd+1 == a.count {
if a.trunc -> return true;
if a.trunc do return true;
return nd > 0 && (a.digits[nd-1]-'0')%2 != 0;
}
return a.digits[nd] >= '5';
}
proc round(a: ^Decimal, nd: int) {
round :: proc(a: ^Decimal, nd: int) {
if nd < 0 || nd >= a.count { return; }
if can_round_up(a, nd) {
round_up(a, nd);
@@ -212,12 +210,12 @@ proc round(a: ^Decimal, nd: int) {
}
}
proc round_up(a: ^Decimal, nd: int) {
round_up :: proc(a: ^Decimal, nd: int) {
if nd < 0 || nd >= a.count { return; }
for var i = nd-1; i >= 0; i-- {
if var c = a.digits[i]; c < '9' {
a.digits[i]++;
for i := nd-1; i >= 0; i -= 1 {
if c := a.digits[i]; c < '9' {
a.digits[i] += 1;
a.count = i+1;
return;
}
@@ -226,10 +224,10 @@ proc round_up(a: ^Decimal, nd: int) {
// Number is just 9s
a.digits[0] = '1';
a.count = 1;
a.decimal_point++;
a.decimal_point += 1;
}
proc round_down(a: ^Decimal, nd: int) {
round_down :: proc(a: ^Decimal, nd: int) {
if nd < 0 || nd >= a.count { return; }
a.count = nd;
trim(a);
@@ -237,21 +235,21 @@ proc round_down(a: ^Decimal, nd: int) {
// Extract integer part, rounded appropriately. There are no guarantees about overflow.
proc rounded_integer(a: ^Decimal) -> u64 {
rounded_integer :: proc(a: ^Decimal) -> u64 {
if a.decimal_point > 20 {
return 0xffff_ffff_ffff_ffff;
}
var i: int;
var n: u64 = 0;
var m = min(a.decimal_point, a.count);
for i = 0; i < m; i++ {
i: int = 0;
n: u64 = 0;
m := min(a.decimal_point, a.count);
for ; i < m; i += 1 {
n = n*10 + u64(a.digits[i]-'0');
}
for ; i < a.decimal_point; i++ {
for ; i < a.decimal_point; i += 1 {
n *= 10;
}
if can_round_up(a, a.decimal_point) {
n++;
n += 1;
}
return n;
}
-1172
View File
File diff suppressed because it is too large Load Diff
+1448
View File
File diff suppressed because it is too large Load Diff
+62 -58
View File
@@ -1,65 +1,75 @@
proc crc32(data: []u8) -> u32 {
var result = ~u32(0);
package hash
import "core:mem"
adler32 :: proc(data: []byte) -> u32 {
ADLER_CONST :: 65521;
a, b: u32 = 1, 0;
for x in data {
a = (a + u32(x)) % ADLER_CONST;
b = (b + a) % ADLER_CONST;
}
return (b << 16) | a;
}
crc32 :: proc(data: []byte) -> u32 {
result := ~u32(0);
for b in data {
result = result>>8 ~ _crc32_table[(result ~ u32(b)) & 0xff];
}
return ~result;
}
proc crc64(data: []u8) -> u64 {
var result = ~u64(0);
crc64 :: proc(data: []byte) -> u64 {
result := ~u64(0);
for b in data {
result = result>>8 ~ _crc64_table[(result ~ u64(b)) & 0xff];
}
return ~result;
}
proc fnv32(data: []u8) -> u32 {
var h: u32 = 0x811c9dc5;
fnv32 :: proc(data: []byte) -> u32 {
h: u32 = 0x811c9dc5;
for b in data {
h = (h * 0x01000193) ~ u32(b);
}
return h;
}
proc fnv64(data: []u8) -> u64 {
var h: u64 = 0xcbf29ce484222325;
fnv64 :: proc(data: []byte) -> u64 {
h: u64 = 0xcbf29ce484222325;
for b in data {
h = (h * 0x100000001b3) ~ u64(b);
}
return h;
}
proc fnv32a(data: []u8) -> u32 {
var h: u32 = 0x811c9dc5;
fnv32a :: proc(data: []byte) -> u32 {
h: u32 = 0x811c9dc5;
for b in data {
h = (h ~ u32(b)) * 0x01000193;
}
return h;
}
proc fnv64a(data: []u8) -> u64 {
var h: u64 = 0xcbf29ce484222325;
fnv64a :: proc(data: []byte) -> u64 {
h: u64 = 0xcbf29ce484222325;
for b in data {
h = (h ~ u64(b)) * 0x100000001b3;
}
return h;
}
proc murmur32(data: []u8) -> u32 {
const (
c1_32: u32 = 0xcc9e2d51;
c2_32: u32 = 0x1b873593;
)
murmur32 :: proc(data: []byte) -> u32 {
c1_32: u32 : 0xcc9e2d51;
c2_32: u32 : 0x1b873593;
var (
h1: u32 = 0;
nblocks = len(data)/4;
p = &data[0];
p1 = p + 4*nblocks;
)
h1: u32 = 0;
nblocks := len(data)/4;
p := &data[0];
p1 := mem.ptr_offset(p, 4*nblocks);
for ; p < p1; p += 4 {
var k1 = ^u32(p)^;
for ; p < p1; p = mem.ptr_offset(p, 4) {
k1 := (cast(^u32)p)^;
k1 *= c1_32;
k1 = (k1 << 15) | (k1 >> 17);
@@ -70,9 +80,9 @@ proc murmur32(data: []u8) -> u32 {
h1 = h1*5 + 0xe6546b64;
}
var tail = data[nblocks*4 ..];
var k1: u32;
match len(tail)&3 {
tail := data[nblocks*4:];
k1: u32;
switch len(tail)&3 {
case 3:
k1 ~= u32(tail[2]) << 16;
fallthrough;
@@ -98,20 +108,18 @@ proc murmur32(data: []u8) -> u32 {
return h1;
}
proc murmur64(data: []u8) -> u64 {
const SEED = 0x9747b28c;
murmur64 :: proc(data: []byte) -> u64 {
SEED :: 0x9747b28c;
when size_of(int) == 8 {
const (
m = 0xc6a4a7935bd1e995;
r = 47;
)
m :: 0xc6a4a7935bd1e995;
r :: 47;
var h: u64 = SEED ~ (u64(len(data)) * m);
var data64 = slice_ptr(^u64(&data[0]), len(data)/size_of(u64));
h: u64 = SEED ~ (u64(len(data)) * m);
data64 := mem.slice_ptr(cast(^u64)&data[0], len(data)/size_of(u64));
for _, i in data64 {
var k = data64[i];
k := data64[i];
k *= m;
k ~= k>>r;
@@ -121,7 +129,7 @@ proc murmur64(data: []u8) -> u64 {
h *= m;
}
match len(data)&7 {
switch len(data)&7 {
case 7: h ~= u64(data[6]) << 48; fallthrough;
case 6: h ~= u64(data[5]) << 40; fallthrough;
case 5: h ~= u64(data[4]) << 32; fallthrough;
@@ -139,22 +147,18 @@ proc murmur64(data: []u8) -> u64 {
return h;
} else {
const (
m = 0x5bd1e995;
r = 24;
)
m :: 0x5bd1e995;
r :: 24;
var (
h1 = u32(SEED) ~ u32(len(data));
h2 = u32(SEED) >> 32;
data32 = slice_ptr(^u32(&data[0]), len(data)/size_of(u32));
len = len(data);
i = 0;
)
h1 := u32(SEED) ~ u32(len(data));
h2 := u32(SEED) >> 32;
data32 := mem.slice_ptr(cast(^u32)&data[0], len(data)/size_of(u32));
len := len(data);
i := 0;
for len >= 8 {
var k1, k2: u32;
k1 = data32[i]; i++;
k1, k2: u32;
k1 = data32[i]; i += 1;
k1 *= m;
k1 ~= k1>>r;
k1 *= m;
@@ -162,7 +166,7 @@ proc murmur64(data: []u8) -> u64 {
h1 ~= k1;
len -= 4;
k2 = data32[i]; i++;
k2 = data32[i]; i += 1;
k2 *= m;
k2 ~= k2>>r;
k2 *= m;
@@ -172,8 +176,8 @@ proc murmur64(data: []u8) -> u64 {
}
if len >= 4 {
var k1: u32;
k1 = data32[i]; i++;
k1: u32;
k1 = data32[i]; i += 1;
k1 *= m;
k1 ~= k1>>r;
k1 *= m;
@@ -183,8 +187,8 @@ proc murmur64(data: []u8) -> u64 {
}
// TODO(bill): Fix this
#no_bounds_check var data8 = slice_to_bytes(data32[i..])[0..<3];
match len {
#no_bounds_check data8 := mem.slice_to_bytes(data32[i:])[:3];
switch len {
case 3:
h2 ~= u32(data8[2]) << 16;
fallthrough;
@@ -210,7 +214,7 @@ proc murmur64(data: []u8) -> u64 {
}
var _crc32_table = [256]u32{
_crc32_table := [256]u32{
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba,
0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
@@ -276,7 +280,7 @@ var _crc32_table = [256]u32{
0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,
};
var _crc64_table = [256]u64{
_crc64_table := [256]u64{
0x0000000000000000, 0x42f0e1eba9ea3693, 0x85e1c3d753d46d26, 0xc711223cfa3e5bb5,
0x493366450e42ecdf, 0x0bc387aea7a8da4c, 0xccd2a5925d9681f9, 0x8e224479f47cb76a,
0x9266cc8a1c85d9be, 0xd0962d61b56fef2d, 0x17870f5d4f51b498, 0x5577eeb6e6bb820b,
+34
View File
@@ -0,0 +1,34 @@
package log
Level :: enum {
Debug,
Info,
Warning,
Error,
Fatal,
}
Option :: enum {
Level,
Time,
File,
Line,
Procedure,
}
Options :: bit_set[Option];
Logger_Proc :: #type proc(data: rawptr, level: Level, ident, text: string, options: Options, location := #caller_location);
Logger :: struct {
procedure: Logger_Proc,
data: rawptr,
}
nil_logger_proc :: proc(data: rawptr, level: Level, ident, text: string, options: Options, location := #caller_location) {
// Do nothing
}
nil_logger :: proc() -> Logger {
return Logger{nil_logger_proc, nil};
}
-396
View File
@@ -1,396 +0,0 @@
const (
TAU = 6.28318530717958647692528676655900576;
PI = 3.14159265358979323846264338327950288;
ONE_OVER_TAU = 0.636619772367581343075535053490057448;
ONE_OVER_PI = 0.159154943091895335768883763372514362;
E = 2.71828182845904523536;
SQRT_TWO = 1.41421356237309504880168872420969808;
SQRT_THREE = 1.73205080756887729352744634150587236;
SQRT_FIVE = 2.23606797749978969640917366873127623;
LOG_TWO = 0.693147180559945309417232121458176568;
LOG_TEN = 2.30258509299404568401799145468436421;
EPSILON = 1.19209290e-7;
τ = TAU;
π = PI;
)
type (
Vec2 [vector 2]f32;
Vec3 [vector 3]f32;
Vec4 [vector 4]f32;
// Column major
Mat2 [2][2]f32;
Mat3 [3][3]f32;
Mat4 [4][4]f32;
Complex complex64;
)
foreign __llvm_core {
proc sqrt(x: f32) -> f32 #link_name "llvm.sqrt.f32";
proc sqrt(x: f64) -> f64 #link_name "llvm.sqrt.f64";
proc sin (θ: f32) -> f32 #link_name "llvm.sin.f32";
proc sin (θ: f64) -> f64 #link_name "llvm.sin.f64";
proc cos (θ: f32) -> f32 #link_name "llvm.cos.f32";
proc cos (θ: f64) -> f64 #link_name "llvm.cos.f64";
proc pow (x, power: f32) -> f32 #link_name "llvm.pow.f32";
proc pow (x, power: f64) -> f64 #link_name "llvm.pow.f64";
proc fmuladd(a, b, c: f32) -> f32 #link_name "llvm.fmuladd.f32";
proc fmuladd(a, b, c: f64) -> f64 #link_name "llvm.fmuladd.f64";
}
proc tan (θ: f32) -> f32 #inline { return sin(θ)/cos(θ); }
proc tan (θ: f64) -> f64 #inline { return sin(θ)/cos(θ); }
proc lerp (a, b, t: f32) -> (x: f32) { return a*(1-t) + b*t; }
proc lerp (a, b, t: f64) -> (x: f64) { return a*(1-t) + b*t; }
proc unlerp(a, b, x: f32) -> (t: f32) { return (x-a)/(b-a); }
proc unlerp(a, b, x: f64) -> (t: f64) { return (x-a)/(b-a); }
proc sign(x: f32) -> f32 { return x >= 0 ? +1 : -1; }
proc sign(x: f64) -> f64 { return x >= 0 ? +1 : -1; }
proc copy_sign(x, y: f32) -> f32 {
var ix = transmute(u32, x);
var iy = transmute(u32, y);
ix &= 0x7fff_ffff;
ix |= iy & 0x8000_0000;
return transmute(f32, ix);
}
proc copy_sign(x, y: f64) -> f64 {
var ix = transmute(u64, x);
var iy = transmute(u64, y);
ix &= 0x7fff_ffff_ffff_ff;
ix |= iy & 0x8000_0000_0000_0000;
return transmute(f64, ix);
}
proc round (x: f32) -> f32 { return x >= 0 ? floor(x + 0.5) : ceil(x - 0.5); }
proc round (x: f64) -> f64 { return x >= 0 ? floor(x + 0.5) : ceil(x - 0.5); }
proc floor (x: f32) -> f32 { return x >= 0 ? f32(i64(x)) : f32(i64(x-0.5)); } // TODO: Get accurate versions
proc floor (x: f64) -> f64 { return x >= 0 ? f64(i64(x)) : f64(i64(x-0.5)); } // TODO: Get accurate versions
proc ceil (x: f32) -> f32 { return x < 0 ? f32(i64(x)) : f32(i64(x+1)); } // TODO: Get accurate versions
proc ceil (x: f64) -> f64 { return x < 0 ? f64(i64(x)) : f64(i64(x+1)); } // TODO: Get accurate versions
proc remainder(x, y: f32) -> f32 { return x - round(x/y) * y; }
proc remainder(x, y: f64) -> f64 { return x - round(x/y) * y; }
proc mod(x, y: f32) -> f32 {
var result: f32;
y = abs(y);
result = remainder(abs(x), y);
if sign(result) < 0 {
result += y;
}
return copy_sign(result, x);
}
proc mod(x, y: f64) -> f64 {
var result: f64;
y = abs(y);
result = remainder(abs(x), y);
if sign(result) < 0 {
result += y;
}
return copy_sign(result, x);
}
proc to_radians(degrees: f32) -> f32 { return degrees * TAU / 360; }
proc to_degrees(radians: f32) -> f32 { return radians * 360 / TAU; }
proc dot(a, b: Vec2) -> f32 { var c = a*b; return c.x + c.y; }
proc dot(a, b: Vec3) -> f32 { var c = a*b; return c.x + c.y + c.z; }
proc dot(a, b: Vec4) -> f32 { var c = a*b; return c.x + c.y + c.z + c.w; }
proc cross(x, y: Vec3) -> Vec3 {
var a = swizzle(x, 1, 2, 0) * swizzle(y, 2, 0, 1);
var b = swizzle(x, 2, 0, 1) * swizzle(y, 1, 2, 0);
return a - b;
}
proc mag(v: Vec2) -> f32 { return sqrt(dot(v, v)); }
proc mag(v: Vec3) -> f32 { return sqrt(dot(v, v)); }
proc mag(v: Vec4) -> f32 { return sqrt(dot(v, v)); }
proc norm(v: Vec2) -> Vec2 { return v / mag(v); }
proc norm(v: Vec3) -> Vec3 { return v / mag(v); }
proc norm(v: Vec4) -> Vec4 { return v / mag(v); }
proc norm0(v: Vec2) -> Vec2 {
var m = mag(v);
if m == 0 {
return 0;
}
return v / m;
}
proc norm0(v: Vec3) -> Vec3 {
var m = mag(v);
if m == 0 {
return 0;
}
return v / m;
}
proc norm0(v: Vec4) -> Vec4 {
var m = mag(v);
if m == 0 {
return 0;
}
return v / m;
}
proc mat4_identity() -> Mat4 {
return Mat4{
{1, 0, 0, 0},
{0, 1, 0, 0},
{0, 0, 1, 0},
{0, 0, 0, 1},
};
}
proc mat4_transpose(m: Mat4) -> Mat4 {
for j in 0..<4 {
for i in 0..<4 {
m[i][j], m[j][i] = m[j][i], m[i][j];
}
}
return m;
}
proc mul(a, b: Mat4) -> Mat4 {
var c: Mat4;
for j in 0..<4 {
for i in 0..<4 {
c[j][i] = a[0][i]*b[j][0] +
a[1][i]*b[j][1] +
a[2][i]*b[j][2] +
a[3][i]*b[j][3];
}
}
return c;
}
proc mul(m: Mat4, v: Vec4) -> Vec4 {
return Vec4{
m[0][0]*v.x + m[1][0]*v.y + m[2][0]*v.z + m[3][0]*v.w,
m[0][1]*v.x + m[1][1]*v.y + m[2][1]*v.z + m[3][1]*v.w,
m[0][2]*v.x + m[1][2]*v.y + m[2][2]*v.z + m[3][2]*v.w,
m[0][3]*v.x + m[1][3]*v.y + m[2][3]*v.z + m[3][3]*v.w,
};
}
proc inverse(m: Mat4) -> Mat4 {
var o: Mat4;
var (
sf00 = m[2][2] * m[3][3] - m[3][2] * m[2][3];
sf01 = m[2][1] * m[3][3] - m[3][1] * m[2][3];
sf02 = m[2][1] * m[3][2] - m[3][1] * m[2][2];
sf03 = m[2][0] * m[3][3] - m[3][0] * m[2][3];
sf04 = m[2][0] * m[3][2] - m[3][0] * m[2][2];
sf05 = m[2][0] * m[3][1] - m[3][0] * m[2][1];
sf06 = m[1][2] * m[3][3] - m[3][2] * m[1][3];
sf07 = m[1][1] * m[3][3] - m[3][1] * m[1][3];
sf08 = m[1][1] * m[3][2] - m[3][1] * m[1][2];
sf09 = m[1][0] * m[3][3] - m[3][0] * m[1][3];
sf10 = m[1][0] * m[3][2] - m[3][0] * m[1][2];
sf11 = m[1][1] * m[3][3] - m[3][1] * m[1][3];
sf12 = m[1][0] * m[3][1] - m[3][0] * m[1][1];
sf13 = m[1][2] * m[2][3] - m[2][2] * m[1][3];
sf14 = m[1][1] * m[2][3] - m[2][1] * m[1][3];
sf15 = m[1][1] * m[2][2] - m[2][1] * m[1][2];
sf16 = m[1][0] * m[2][3] - m[2][0] * m[1][3];
sf17 = m[1][0] * m[2][2] - m[2][0] * m[1][2];
sf18 = m[1][0] * m[2][1] - m[2][0] * m[1][1];
)
o[0][0] = +(m[1][1] * sf00 - m[1][2] * sf01 + m[1][3] * sf02);
o[0][1] = -(m[1][0] * sf00 - m[1][2] * sf03 + m[1][3] * sf04);
o[0][2] = +(m[1][0] * sf01 - m[1][1] * sf03 + m[1][3] * sf05);
o[0][3] = -(m[1][0] * sf02 - m[1][1] * sf04 + m[1][2] * sf05);
o[1][0] = -(m[0][1] * sf00 - m[0][2] * sf01 + m[0][3] * sf02);
o[1][1] = +(m[0][0] * sf00 - m[0][2] * sf03 + m[0][3] * sf04);
o[1][2] = -(m[0][0] * sf01 - m[0][1] * sf03 + m[0][3] * sf05);
o[1][3] = +(m[0][0] * sf02 - m[0][1] * sf04 + m[0][2] * sf05);
o[2][0] = +(m[0][1] * sf06 - m[0][2] * sf07 + m[0][3] * sf08);
o[2][1] = -(m[0][0] * sf06 - m[0][2] * sf09 + m[0][3] * sf10);
o[2][2] = +(m[0][0] * sf11 - m[0][1] * sf09 + m[0][3] * sf12);
o[2][3] = -(m[0][0] * sf08 - m[0][1] * sf10 + m[0][2] * sf12);
o[3][0] = -(m[0][1] * sf13 - m[0][2] * sf14 + m[0][3] * sf15);
o[3][1] = +(m[0][0] * sf13 - m[0][2] * sf16 + m[0][3] * sf17);
o[3][2] = -(m[0][0] * sf14 - m[0][1] * sf16 + m[0][3] * sf18);
o[3][3] = +(m[0][0] * sf15 - m[0][1] * sf17 + m[0][2] * sf18);
var ood = 1.0 / (m[0][0] * o[0][0] +
m[0][1] * o[0][1] +
m[0][2] * o[0][2] +
m[0][3] * o[0][3]);
o[0][0] *= ood;
o[0][1] *= ood;
o[0][2] *= ood;
o[0][3] *= ood;
o[1][0] *= ood;
o[1][1] *= ood;
o[1][2] *= ood;
o[1][3] *= ood;
o[2][0] *= ood;
o[2][1] *= ood;
o[2][2] *= ood;
o[2][3] *= ood;
o[3][0] *= ood;
o[3][1] *= ood;
o[3][2] *= ood;
o[3][3] *= ood;
return o;
}
proc mat4_translate(v: Vec3) -> Mat4 {
var m = mat4_identity();
m[3][0] = v.x;
m[3][1] = v.y;
m[3][2] = v.z;
m[3][3] = 1;
return m;
}
proc mat4_rotate(v: Vec3, angle_radians: f32) -> Mat4 {
var (
c = cos(angle_radians);
s = sin(angle_radians);
a = norm(v);
t = a * (1-c);
rot = mat4_identity();
)
rot[0][0] = c + t.x*a.x;
rot[0][1] = 0 + t.x*a.y + s*a.z;
rot[0][2] = 0 + t.x*a.z - s*a.y;
rot[0][3] = 0;
rot[1][0] = 0 + t.y*a.x - s*a.z;
rot[1][1] = c + t.y*a.y;
rot[1][2] = 0 + t.y*a.z + s*a.x;
rot[1][3] = 0;
rot[2][0] = 0 + t.z*a.x + s*a.y;
rot[2][1] = 0 + t.z*a.y - s*a.x;
rot[2][2] = c + t.z*a.z;
rot[2][3] = 0;
return rot;
}
proc scale(m: Mat4, v: Vec3) -> Mat4 {
m[0][0] *= v.x;
m[1][1] *= v.y;
m[2][2] *= v.z;
return m;
}
proc scale(m: Mat4, s: f32) -> Mat4 {
m[0][0] *= s;
m[1][1] *= s;
m[2][2] *= s;
return m;
}
proc look_at(eye, centre, up: Vec3) -> Mat4 {
var (
f = norm(centre - eye);
s = norm(cross(f, up));
u = cross(s, f);
)
return Mat4{
{+s.x, +u.x, -f.x, 0},
{+s.y, +u.y, -f.y, 0},
{+s.z, +u.z, -f.z, 0},
{-dot(s, eye), -dot(u, eye), dot(f, eye), 1},
};
}
proc perspective(fovy, aspect, near, far: f32) -> Mat4 {
var (
m: Mat4;
tan_half_fovy = tan(0.5 * fovy);
)
m[0][0] = 1.0 / (aspect*tan_half_fovy);
m[1][1] = 1.0 / (tan_half_fovy);
m[2][2] = -(far + near) / (far - near);
m[2][3] = -1.0;
m[3][2] = -2.0*far*near / (far - near);
return m;
}
proc ortho3d(left, right, bottom, top, near, far: f32) -> Mat4 {
var m = mat4_identity();
m[0][0] = +2.0 / (right - left);
m[1][1] = +2.0 / (top - bottom);
m[2][2] = -2.0 / (far - near);
m[3][0] = -(right + left) / (right - left);
m[3][1] = -(top + bottom) / (top - bottom);
m[3][2] = -(far + near) / (far - near);
return m;
}
const (
F32_DIG = 6;
F32_EPSILON = 1.192092896e-07;
F32_GUARD = 0;
F32_MANT_DIG = 24;
F32_MAX = 3.402823466e+38;
F32_MAX_10_EXP = 38;
F32_MAX_EXP = 128;
F32_MIN = 1.175494351e-38;
F32_MIN_10_EXP = -37;
F32_MIN_EXP = -125;
F32_NORMALIZE = 0;
F32_RADIX = 2;
F32_ROUNDS = 1;
F64_DIG = 15; // # of decimal digits of precision
F64_EPSILON = 2.2204460492503131e-016; // smallest such that 1.0+F64_EPSILON != 1.0
F64_MANT_DIG = 53; // # of bits in mantissa
F64_MAX = 1.7976931348623158e+308; // max value
F64_MAX_10_EXP = 308; // max decimal exponent
F64_MAX_EXP = 1024; // max binary exponent
F64_MIN = 2.2250738585072014e-308; // min positive value
F64_MIN_10_EXP = -307; // min decimal exponent
F64_MIN_EXP = -1021; // min binary exponent
F64_RADIX = 2; // exponent radix
F64_ROUNDS = 1; // addition rounding: near
)
+494
View File
@@ -0,0 +1,494 @@
package math
TAU :: 6.28318530717958647692528676655900576;
PI :: 3.14159265358979323846264338327950288;
E :: 2.71828182845904523536;
SQRT_TWO :: 1.41421356237309504880168872420969808;
SQRT_THREE :: 1.73205080756887729352744634150587236;
SQRT_FIVE :: 2.23606797749978969640917366873127623;
LOG_TWO :: 0.693147180559945309417232121458176568;
LOG_TEN :: 2.30258509299404568401799145468436421;
EPSILON :: 1.19209290e-7;
τ :: TAU;
π :: PI;
Vec2 :: distinct [2]f32;
Vec3 :: distinct [3]f32;
Vec4 :: distinct [4]f32;
// Column major
Mat2 :: distinct [2][2]f32;
Mat3 :: distinct [3][3]f32;
Mat4 :: distinct [4][4]f32;
Quat :: struct {x, y, z, w: f32};
QUAT_IDENTITY := Quat{x = 0, y = 0, z = 0, w = 1};
@(default_calling_convention="c")
foreign _ {
@(link_name="llvm.sqrt.f32")
sqrt_f32 :: proc(x: f32) -> f32 ---;
@(link_name="llvm.sqrt.f64")
sqrt_f64 :: proc(x: f64) -> f64 ---;
@(link_name="llvm.sin.f32")
sin_f32 :: proc(θ: f32) -> f32 ---;
@(link_name="llvm.sin.f64")
sin_f64 :: proc(θ: f64) -> f64 ---;
@(link_name="llvm.cos.f32")
cos_f32 :: proc(θ: f32) -> f32 ---;
@(link_name="llvm.cos.f64")
cos_f64 :: proc(θ: f64) -> f64 ---;
@(link_name="llvm.pow.f32")
pow_f32 :: proc(x, power: f32) -> f32 ---;
@(link_name="llvm.pow.f64")
pow_f64 :: proc(x, power: f64) -> f64 ---;
@(link_name="llvm.fmuladd.f32")
fmuladd_f32 :: proc(a, b, c: f32) -> f32 ---;
@(link_name="llvm.fmuladd.f64")
fmuladd_f64 :: proc(a, b, c: f64) -> f64 ---;
@(link_name="llvm.log.f32")
log_f32 :: proc(x: f32) -> f32 ---;
@(link_name="llvm.log.f64")
log_f64 :: proc(x: f64) -> f64 ---;
}
log :: proc[log_f32, log_f64];
tan_f32 :: proc "c" (θ: f32) -> f32 { return sin(θ)/cos(θ); }
tan_f64 :: proc "c" (θ: f64) -> f64 { return sin(θ)/cos(θ); }
lerp :: proc(a, b: $T, t: $E) -> (x: T) { return a*(1-t) + b*t; }
unlerp_f32 :: proc(a, b, x: f32) -> (t: f32) { return (x-a)/(b-a); }
unlerp_f64 :: proc(a, b, x: f64) -> (t: f64) { return (x-a)/(b-a); }
sign_f32 :: proc(x: f32) -> f32 { return x >= 0 ? +1 : -1; }
sign_f64 :: proc(x: f64) -> f64 { return x >= 0 ? +1 : -1; }
copy_sign_f32 :: proc(x, y: f32) -> f32 {
ix := transmute(u32)x;
iy := transmute(u32)y;
ix &= 0x7fff_ffff;
ix |= iy & 0x8000_0000;
return transmute(f32)ix;
}
copy_sign_f64 :: proc(x, y: f64) -> f64 {
ix := transmute(u64)x;
iy := transmute(u64)y;
ix &= 0x7fff_ffff_ffff_ff;
ix |= iy & 0x8000_0000_0000_0000;
return transmute(f64)ix;
}
sqrt :: proc[sqrt_f32, sqrt_f64];
sin :: proc[sin_f32, sin_f64];
cos :: proc[cos_f32, cos_f64];
tan :: proc[tan_f32, tan_f64];
pow :: proc[pow_f32, pow_f64];
fmuladd :: proc[fmuladd_f32, fmuladd_f64];
sign :: proc[sign_f32, sign_f64];
copy_sign :: proc[copy_sign_f32, copy_sign_f64];
round_f32 :: proc(x: f32) -> f32 { return x >= 0 ? floor(x + 0.5) : ceil(x - 0.5); }
round_f64 :: proc(x: f64) -> f64 { return x >= 0 ? floor(x + 0.5) : ceil(x - 0.5); }
round :: proc[round_f32, round_f64];
floor_f32 :: proc(x: f32) -> f32 { return x >= 0 ? f32(i64(x)) : f32(i64(x-0.5)); } // TODO: Get accurate versions
floor_f64 :: proc(x: f64) -> f64 { return x >= 0 ? f64(i64(x)) : f64(i64(x-0.5)); } // TODO: Get accurate versions
floor :: proc[floor_f32, floor_f64];
ceil_f32 :: proc(x: f32) -> f32 { return x < 0 ? f32(i64(x)) : f32(i64(x+1)); }// TODO: Get accurate versions
ceil_f64 :: proc(x: f64) -> f64 { return x < 0 ? f64(i64(x)) : f64(i64(x+1)); }// TODO: Get accurate versions
ceil :: proc[ceil_f32, ceil_f64];
remainder_f32 :: proc(x, y: f32) -> f32 { return x - round(x/y) * y; }
remainder_f64 :: proc(x, y: f64) -> f64 { return x - round(x/y) * y; }
remainder :: proc[remainder_f32, remainder_f64];
mod_f32 :: proc(x, y: f32) -> f32 {
result: f32;
y = abs(y);
result = remainder(abs(x), y);
if sign(result) < 0 {
result += y;
}
return copy_sign(result, x);
}
mod_f64 :: proc(x, y: f64) -> f64 {
result: f64;
y = abs(y);
result = remainder(abs(x), y);
if sign(result) < 0 {
result += y;
}
return copy_sign(result, x);
}
mod :: proc[mod_f32, mod_f64];
to_radians :: proc(degrees: f32) -> f32 { return degrees * TAU / 360; }
to_degrees :: proc(radians: f32) -> f32 { return radians * 360 / TAU; }
mul :: proc[
mat3_mul,
mat4_mul, mat4_mul_vec4,
quat_mul, quat_mulf,
];
div :: proc[
quat_div, quat_divf,
];
inverse :: proc[mat4_inverse, quat_inverse];
dot :: proc[vec_dot, quat_dot];
cross :: proc[cross2, cross3];
vec_dot :: proc(a, b: $T/[$N]$E) -> E {
res: E;
for i in 0..N-1 {
res += a[i] * b[i];
}
return res;
}
cross2 :: proc(a, b: $T/[2]$E) -> E {
return a[0]*b[1] - a[1]*b[0];
}
cross3 :: proc(a, b: $T/[3]$E) -> T {
i := swizzle(a, 1, 2, 0) * swizzle(b, 2, 0, 1);
j := swizzle(a, 2, 0, 1) * swizzle(b, 1, 2, 0);
return T(i - j);
}
length :: proc(v: $T/[$N]$E) -> E { return sqrt(dot(v, v)); }
norm :: proc(v: $T/[$N]$E) -> T { return v / length(v); }
norm0 :: proc(v: $T/[$N]$E) -> T {
m := length(v);
return m == 0 ? 0 : v/m;
}
identity :: proc($T: typeid/[$N][N]$E) -> T {
m: T;
for i in 0..N-1 do m[i][i] = E(1);
return m;
}
transpose :: proc(m: $M/[$N][N]f32) -> M {
for j in 0..N-1 {
for i in 0..N-1 {
m[i][j], m[j][i] = m[j][i], m[i][j];
}
}
return m;
}
mat3_mul :: proc(a, b: Mat3) -> Mat3 {
c: Mat3;
for j in 0..2 {
for i in 0..2 {
c[j][i] = a[0][i]*b[j][0] +
a[1][i]*b[j][1] +
a[2][i]*b[j][2];
}
}
return c;
}
mat4_mul :: proc(a, b: Mat4) -> Mat4 {
c: Mat4;
for j in 0..3 {
for i in 0..3 {
c[j][i] = a[0][i]*b[j][0] +
a[1][i]*b[j][1] +
a[2][i]*b[j][2] +
a[3][i]*b[j][3];
}
}
return c;
}
mat4_mul_vec4 :: proc(m: Mat4, v: Vec4) -> Vec4 {
return Vec4{
m[0][0]*v[0] + m[1][0]*v[1] + m[2][0]*v[2] + m[3][0]*v[3],
m[0][1]*v[0] + m[1][1]*v[1] + m[2][1]*v[2] + m[3][1]*v[3],
m[0][2]*v[0] + m[1][2]*v[1] + m[2][2]*v[2] + m[3][2]*v[3],
m[0][3]*v[0] + m[1][3]*v[1] + m[2][3]*v[2] + m[3][3]*v[3],
};
}
mat4_inverse :: proc(m: Mat4) -> Mat4 {
o: Mat4;
sf00 := m[2][2] * m[3][3] - m[3][2] * m[2][3];
sf01 := m[2][1] * m[3][3] - m[3][1] * m[2][3];
sf02 := m[2][1] * m[3][2] - m[3][1] * m[2][2];
sf03 := m[2][0] * m[3][3] - m[3][0] * m[2][3];
sf04 := m[2][0] * m[3][2] - m[3][0] * m[2][2];
sf05 := m[2][0] * m[3][1] - m[3][0] * m[2][1];
sf06 := m[1][2] * m[3][3] - m[3][2] * m[1][3];
sf07 := m[1][1] * m[3][3] - m[3][1] * m[1][3];
sf08 := m[1][1] * m[3][2] - m[3][1] * m[1][2];
sf09 := m[1][0] * m[3][3] - m[3][0] * m[1][3];
sf10 := m[1][0] * m[3][2] - m[3][0] * m[1][2];
sf11 := m[1][1] * m[3][3] - m[3][1] * m[1][3];
sf12 := m[1][0] * m[3][1] - m[3][0] * m[1][1];
sf13 := m[1][2] * m[2][3] - m[2][2] * m[1][3];
sf14 := m[1][1] * m[2][3] - m[2][1] * m[1][3];
sf15 := m[1][1] * m[2][2] - m[2][1] * m[1][2];
sf16 := m[1][0] * m[2][3] - m[2][0] * m[1][3];
sf17 := m[1][0] * m[2][2] - m[2][0] * m[1][2];
sf18 := m[1][0] * m[2][1] - m[2][0] * m[1][1];
o[0][0] = +(m[1][1] * sf00 - m[1][2] * sf01 + m[1][3] * sf02);
o[0][1] = -(m[1][0] * sf00 - m[1][2] * sf03 + m[1][3] * sf04);
o[0][2] = +(m[1][0] * sf01 - m[1][1] * sf03 + m[1][3] * sf05);
o[0][3] = -(m[1][0] * sf02 - m[1][1] * sf04 + m[1][2] * sf05);
o[1][0] = -(m[0][1] * sf00 - m[0][2] * sf01 + m[0][3] * sf02);
o[1][1] = +(m[0][0] * sf00 - m[0][2] * sf03 + m[0][3] * sf04);
o[1][2] = -(m[0][0] * sf01 - m[0][1] * sf03 + m[0][3] * sf05);
o[1][3] = +(m[0][0] * sf02 - m[0][1] * sf04 + m[0][2] * sf05);
o[2][0] = +(m[0][1] * sf06 - m[0][2] * sf07 + m[0][3] * sf08);
o[2][1] = -(m[0][0] * sf06 - m[0][2] * sf09 + m[0][3] * sf10);
o[2][2] = +(m[0][0] * sf11 - m[0][1] * sf09 + m[0][3] * sf12);
o[2][3] = -(m[0][0] * sf08 - m[0][1] * sf10 + m[0][2] * sf12);
o[3][0] = -(m[0][1] * sf13 - m[0][2] * sf14 + m[0][3] * sf15);
o[3][1] = +(m[0][0] * sf13 - m[0][2] * sf16 + m[0][3] * sf17);
o[3][2] = -(m[0][0] * sf14 - m[0][1] * sf16 + m[0][3] * sf18);
o[3][3] = +(m[0][0] * sf15 - m[0][1] * sf17 + m[0][2] * sf18);
ood := 1.0 / (m[0][0] * o[0][0] +
m[0][1] * o[0][1] +
m[0][2] * o[0][2] +
m[0][3] * o[0][3]);
o[0][0] *= ood;
o[0][1] *= ood;
o[0][2] *= ood;
o[0][3] *= ood;
o[1][0] *= ood;
o[1][1] *= ood;
o[1][2] *= ood;
o[1][3] *= ood;
o[2][0] *= ood;
o[2][1] *= ood;
o[2][2] *= ood;
o[2][3] *= ood;
o[3][0] *= ood;
o[3][1] *= ood;
o[3][2] *= ood;
o[3][3] *= ood;
return o;
}
mat4_translate :: proc(v: Vec3) -> Mat4 {
m := identity(Mat4);
m[3][0] = v[0];
m[3][1] = v[1];
m[3][2] = v[2];
m[3][3] = 1;
return m;
}
mat4_rotate :: proc(v: Vec3, angle_radians: f32) -> Mat4 {
c := cos(angle_radians);
s := sin(angle_radians);
a := norm(v);
t := a * (1-c);
rot := identity(Mat4);
rot[0][0] = c + t[0]*a[0];
rot[0][1] = 0 + t[0]*a[1] + s*a[2];
rot[0][2] = 0 + t[0]*a[2] - s*a[1];
rot[0][3] = 0;
rot[1][0] = 0 + t[1]*a[0] - s*a[2];
rot[1][1] = c + t[1]*a[1];
rot[1][2] = 0 + t[1]*a[2] + s*a[0];
rot[1][3] = 0;
rot[2][0] = 0 + t[2]*a[0] + s*a[1];
rot[2][1] = 0 + t[2]*a[1] - s*a[0];
rot[2][2] = c + t[2]*a[2];
rot[2][3] = 0;
return rot;
}
scale_vec3 :: proc(m: Mat4, v: Vec3) -> Mat4 {
m[0][0] *= v[0];
m[1][1] *= v[1];
m[2][2] *= v[2];
return m;
}
scale_f32 :: proc(m: Mat4, s: f32) -> Mat4 {
m[0][0] *= s;
m[1][1] *= s;
m[2][2] *= s;
return m;
}
scale :: proc[scale_vec3, scale_f32];
look_at :: proc(eye, centre, up: Vec3) -> Mat4 {
f := norm(centre - eye);
s := norm(cross(f, up));
u := cross(s, f);
return Mat4{
{+s.x, +u.x, -f.x, 0},
{+s.y, +u.y, -f.y, 0},
{+s.z, +u.z, -f.z, 0},
{-dot(s, eye), -dot(u, eye), dot(f, eye), 1},
};
}
perspective :: proc(fovy, aspect, near, far: f32) -> Mat4 {
m: Mat4;
tan_half_fovy := tan(0.5 * fovy);
m[0][0] = 1.0 / (aspect*tan_half_fovy);
m[1][1] = 1.0 / (tan_half_fovy);
m[2][2] = -(far + near) / (far - near);
m[2][3] = -1.0;
m[3][2] = -2.0*far*near / (far - near);
return m;
}
ortho3d :: proc(left, right, bottom, top, near, far: f32) -> Mat4 {
m := identity(Mat4);
m[0][0] = +2.0 / (right - left);
m[1][1] = +2.0 / (top - bottom);
m[2][2] = -2.0 / (far - near);
m[3][0] = -(right + left) / (right - left);
m[3][1] = -(top + bottom) / (top - bottom);
m[3][2] = -(far + near) / (far - near);
return m;
}
// Quaternion operations
conj :: proc(q: Quat) -> Quat {
return Quat{-q.x, -q.y, -q.z, q.w};
}
quat_mul :: proc(q0, q1: Quat) -> Quat {
d: Quat;
d.x = q0.w * q1.x + q0.x * q1.w + q0.y * q1.z - q0.z * q1.y;
d.y = q0.w * q1.y - q0.x * q1.z + q0.y * q1.w + q0.z * q1.x;
d.z = q0.w * q1.z + q0.x * q1.y - q0.y * q1.x + q0.z * q1.w;
d.w = q0.w * q1.w - q0.x * q1.x - q0.y * q1.y - q0.z * q1.z;
return d;
}
quat_mulf :: proc(q: Quat, f: f32) -> Quat { return Quat{q.x*f, q.y*f, q.z*f, q.w*f}; }
quat_divf :: proc(q: Quat, f: f32) -> Quat { return Quat{q.x/f, q.y/f, q.z/f, q.w/f}; }
quat_div :: proc(q0, q1: Quat) -> Quat { return mul(q0, quat_inverse(q1)); }
quat_inverse :: proc(q: Quat) -> Quat { return div(conj(q), dot(q, q)); }
quat_dot :: proc(q0, q1: Quat) -> f32 { return q0.x*q1.x + q0.y*q1.y + q0.z*q1.z + q0.w*q1.w; }
quat_norm :: proc(q: Quat) -> Quat {
m := sqrt(dot(q, q));
return div(q, m);
}
axis_angle :: proc(axis: Vec3, angle_radians: f32) -> Quat {
v := norm(axis) * sin(0.5*angle_radians);
w := cos(0.5*angle_radians);
return Quat{v.x, v.y, v.z, w};
}
euler_angles :: proc(pitch, yaw, roll: f32) -> Quat {
p := axis_angle(Vec3{1, 0, 0}, pitch);
y := axis_angle(Vec3{0, 1, 0}, yaw);
r := axis_angle(Vec3{0, 0, 1}, roll);
return mul(mul(y, p), r);
}
quat_to_mat4 :: proc(q: Quat) -> Mat4 {
a := quat_norm(q);
xx := a.x*a.x; yy := a.y*a.y; zz := a.z*a.z;
xy := a.x*a.y; xz := a.x*a.z; yz := a.y*a.z;
wx := a.w*a.x; wy := a.w*a.y; wz := a.w*a.z;
m := identity(Mat4);
m[0][0] = 1 - 2*(yy + zz);
m[0][1] = 2*(xy + wz);
m[0][2] = 2*(xz - wy);
m[1][0] = 2*(xy - wz);
m[1][1] = 1 - 2*(xx + zz);
m[1][2] = 2*(yz + wx);
m[2][0] = 2*(xz + wy);
m[2][1] = 2*(yz - wx);
m[2][2] = 1 - 2*(xx + yy);
return m;
}
F32_DIG :: 6;
F32_EPSILON :: 1.192092896e-07;
F32_GUARD :: 0;
F32_MANT_DIG :: 24;
F32_MAX :: 3.402823466e+38;
F32_MAX_10_EXP :: 38;
F32_MAX_EXP :: 128;
F32_MIN :: 1.175494351e-38;
F32_MIN_10_EXP :: -37;
F32_MIN_EXP :: -125;
F32_NORMALIZE :: 0;
F32_RADIX :: 2;
F32_ROUNDS :: 1;
F64_DIG :: 15; // # of decimal digits of precision
F64_EPSILON :: 2.2204460492503131e-016; // smallest such that 1.0+F64_EPSILON != 1.0
F64_MANT_DIG :: 53; // # of bits in mantissa
F64_MAX :: 1.7976931348623158e+308; // max value
F64_MAX_10_EXP :: 308; // max decimal exponent
F64_MAX_EXP :: 1024; // max binary exponent
F64_MIN :: 2.2250738585072014e-308; // min positive value
F64_MIN_10_EXP :: -307; // min decimal exponent
F64_MIN_EXP :: -1021; // min binary exponent
F64_RADIX :: 2; // exponent radix
F64_ROUNDS :: 1; // addition rounding: near
+62
View File
@@ -0,0 +1,62 @@
package rand
Rand :: struct {
state: u64,
inc: u64,
}
init :: proc(r: ^Rand, seed: u64 = 8675309) {
r.state = 0;
r.inc = (seed << 1) | 1;
_random(r);
r.state += seed;
_random(r);
}
_random :: proc(r: ^Rand) -> u32 {
old_state := r.state;
r.state = old_state * 6364136223846793005 + (r.inc|1);
xor_shifted := u32(((old_state>>18) ~ old_state) >> 27);
rot := u32(old_state >> 59);
return (xor_shifted >> rot) | (xor_shifted << ((-rot) & 31));
}
uint32 :: proc(r: ^Rand) -> u32 { return _random(r); }
uint64 :: proc(r: ^Rand) -> u64 {
a := u64(_random(r));
b := u64(_random(r));
return (a<<32) | b;
}
int31 :: proc(r: ^Rand) -> i32 { return i32(uint32(r) << 1 >> 1); }
int63 :: proc(r: ^Rand) -> i64 { return i64(uint64(r) << 1 >> 1); }
int31_max :: proc(r: ^Rand, n: i32) -> i32 {
if n <= 0 do panic("Invalid argument to int31_max");
if n&(n-1) == 0 {
return int31(r) & (n-1);
}
max := i32((1<<31) - 1 - (1<<31)&u32(n));
v := int31(r);
for v > max {
v = int31(r);
}
return v % n;
}
int63_max :: proc(r: ^Rand, n: i64) -> i64 {
if n <= 0 do panic("Invalid argument to int63_max");
if n&(n-1) == 0 {
return int63(r) & (n-1);
}
max := i64((1<<63) - 1 - (1<<63)&u64(n));
v := int63(r);
for v > max {
v = int63(r);
}
return v % n;
}
float64 :: proc(r: ^Rand) -> f64 { return f64(int63_max(r, 1<<53)) / (1 << 53); }
float32 :: proc(r: ^Rand) -> f32 { return f32(float64(r)); }
-308
View File
@@ -1,308 +0,0 @@
import (
"fmt.odin";
"os.odin";
)
foreign __llvm_core {
proc swap(b: u16) -> u16 #link_name "llvm.bswap.i16";
proc swap(b: u32) -> u32 #link_name "llvm.bswap.i32";
proc swap(b: u64) -> u64 #link_name "llvm.bswap.i64";
}
proc set(data: rawptr, value: i32, len: int) -> rawptr {
return __mem_set(data, value, len);
}
proc zero(data: rawptr, len: int) -> rawptr {
return __mem_zero(data, len);
}
proc copy(dst, src: rawptr, len: int) -> rawptr {
return __mem_copy(dst, src, len);
}
proc copy_non_overlapping(dst, src: rawptr, len: int) -> rawptr {
return __mem_copy_non_overlapping(dst, src, len);
}
proc compare(a, b: []u8) -> int {
return __mem_compare(&a[0], &b[0], min(len(a), len(b)));
}
proc kilobytes(x: int) -> int #inline { return (x) * 1024; }
proc megabytes(x: int) -> int #inline { return kilobytes(x) * 1024; }
proc gigabytes(x: int) -> int #inline { return megabytes(x) * 1024; }
proc terabytes(x: int) -> int #inline { return gigabytes(x) * 1024; }
proc is_power_of_two(x: int) -> bool {
if x <= 0 {
return false;
}
return (x & (x-1)) == 0;
}
proc align_forward(ptr: rawptr, align: int) -> rawptr {
assert(is_power_of_two(align));
var a = uint(align);
var p = uint(ptr);
var modulo = p & (a-1);
if modulo != 0 {
p += a - modulo;
}
return rawptr(p);
}
type AllocationHeader struct {
size: int,
}
proc allocation_header_fill(header: ^AllocationHeader, data: rawptr, size: int) {
header.size = size;
var ptr = ^int(header+1);
for var i = 0; rawptr(ptr) < data; i++ {
(ptr+i)^ = -1;
}
}
proc allocation_header(data: rawptr) -> ^AllocationHeader {
if data == nil {
return nil;
}
var p = ^int(data);
for (p-1)^ == -1 {
p = (p-1);
}
return ^AllocationHeader(p-1);
}
// Custom allocators
type (
Arena struct {
backing: Allocator,
offset: int,
memory: []u8,
temp_count: int,
}
ArenaTempMemory struct {
arena: ^Arena,
original_count: int,
}
)
proc init_arena_from_memory(using a: ^Arena, data: []u8) {
backing = Allocator{};
memory = data[0..<0];
temp_count = 0;
}
proc init_arena_from_context(using a: ^Arena, size: int) {
backing = context.allocator;
memory = make([]u8, size);
temp_count = 0;
}
proc free_arena(using a: ^Arena) {
if backing.procedure != nil {
push_allocator backing {
free(memory);
memory = nil;
offset = 0;
}
}
}
proc arena_allocator(arena: ^Arena) -> Allocator {
return Allocator{
procedure = arena_allocator_proc,
data = arena,
};
}
proc arena_allocator_proc(allocator_data: rawptr, mode: AllocatorMode,
size, alignment: int,
old_memory: rawptr, old_size: int, flags: u64) -> rawptr {
using AllocatorMode;
var arena = ^Arena(allocator_data);
match mode {
case Alloc:
var total_size = size + alignment;
if arena.offset + total_size > len(arena.memory) {
fmt.fprintln(os.stderr, "Arena out of memory");
return nil;
}
#no_bounds_check var end = &arena.memory[arena.offset];
var ptr = align_forward(end, alignment);
arena.offset += total_size;
return zero(ptr, size);
case Free:
// NOTE(bill): Free all at once
// Use ArenaTempMemory if you want to free a block
case FreeAll:
arena.offset = 0;
case Resize:
return default_resize_align(old_memory, old_size, size, alignment);
}
return nil;
}
proc begin_arena_temp_memory(a: ^Arena) -> ArenaTempMemory {
var tmp: ArenaTempMemory;
tmp.arena = a;
tmp.original_count = len(a.memory);
a.temp_count++;
return tmp;
}
proc end_arena_temp_memory(using tmp: ArenaTempMemory) {
assert(len(arena.memory) >= original_count);
assert(arena.temp_count > 0);
arena.memory = arena.memory[0..<original_count];
arena.temp_count--;
}
proc align_of_type_info(type_info: ^TypeInfo) -> int {
proc prev_pow2(n: i64) -> i64 {
if n <= 0 {
return 0;
}
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n |= n >> 32;
return n - (n >> 1);
}
const WORD_SIZE = size_of(int);
const MAX_ALIGN = size_of([vector 64]f64); // TODO(bill): Should these constants be builtin constants?
using TypeInfo;
match info in type_info {
case Named:
return align_of_type_info(info.base);
case Integer:
return info.size;
case Float:
return info.size;
case String:
return WORD_SIZE;
case Boolean:
return 1;
case Any:
return WORD_SIZE;
case Pointer:
return WORD_SIZE;
case Procedure:
return WORD_SIZE;
case Array:
return align_of_type_info(info.elem);
case DynamicArray:
return WORD_SIZE;
case Slice:
return WORD_SIZE;
case Vector:
var size = size_of_type_info(info.elem);
var count = int(max(prev_pow2(i64(info.count)), 1));
var total = size * count;
return clamp(total, 1, MAX_ALIGN);
case Tuple:
return info.align;
case Struct:
return info.align;
case Union:
return info.align;
case RawUnion:
return info.align;
case Enum:
return align_of_type_info(info.base);
case Map:
return align_of_type_info(info.generated_struct);
}
return 0;
}
proc align_formula(size, align: int) -> int {
var result = size + align-1;
return result - result%align;
}
proc size_of_type_info(type_info: ^TypeInfo) -> int {
const WORD_SIZE = size_of(int);
using TypeInfo;
match info in type_info {
case Named:
return size_of_type_info(info.base);
case Integer:
return info.size;
case Float:
return info.size;
case String:
return 2*WORD_SIZE;
case Boolean:
return 1;
case Any:
return 2*WORD_SIZE;
case Pointer:
return WORD_SIZE;
case Procedure:
return WORD_SIZE;
case Array:
var count = info.count;
if count == 0 {
return 0;
}
var size = size_of_type_info(info.elem);
var align = align_of_type_info(info.elem);
var alignment = align_formula(size, align);
return alignment*(count-1) + size;
case DynamicArray:
return size_of(rawptr) + 2*size_of(int) + size_of(Allocator);
case Slice:
return 2*WORD_SIZE;
case Vector:
var count = info.count;
if count == 0 {
return 0;
}
var size = size_of_type_info(info.elem);
var align = align_of_type_info(info.elem);
var alignment = align_formula(size, align);
return alignment*(count-1) + size;
case Struct:
return info.size;
case Union:
return info.size;
case RawUnion:
return info.size;
case Enum:
return size_of_type_info(info.base);
case Map:
return size_of_type_info(info.generated_struct);
}
return 0;
}
+427
View File
@@ -0,0 +1,427 @@
package mem
import "core:runtime"
DEFAULT_ALIGNMENT :: 2*align_of(rawptr);
Allocator_Mode :: enum byte {
Alloc,
Free,
Free_All,
Resize,
}
Allocator_Proc :: #type proc(allocator_data: rawptr, mode: Allocator_Mode,
size, alignment: int,
old_memory: rawptr, old_size: int, flags: u64 = 0, location := #caller_location) -> rawptr;
Allocator :: struct {
procedure: Allocator_Proc,
data: rawptr,
}
alloc :: inline proc(size: int, alignment: int = DEFAULT_ALIGNMENT, allocator := context.allocator, loc := #caller_location) -> rawptr {
if size == 0 do return nil;
if allocator.procedure == nil do return nil;
return allocator.procedure(allocator.data, Allocator_Mode.Alloc, size, alignment, nil, 0, 0, loc);
}
free :: inline proc(ptr: rawptr, allocator := context.allocator, loc := #caller_location) {
if ptr == nil do return;
if allocator.procedure == nil do return;
allocator.procedure(allocator.data, Allocator_Mode.Free, 0, 0, ptr, 0, 0, loc);
}
free_all :: inline proc(allocator := context.allocator, loc := #caller_location) {
if allocator.procedure != nil {
allocator.procedure(allocator.data, Allocator_Mode.Free_All, 0, 0, nil, 0, 0, loc);
}
}
resize :: inline proc(ptr: rawptr, old_size, new_size: int, alignment: int = DEFAULT_ALIGNMENT, allocator := context.allocator, loc := #caller_location) -> rawptr {
if allocator.procedure == nil {
return nil;
}
if new_size == 0 {
free(ptr, allocator, loc);
return nil;
} else if ptr == nil {
return allocator.procedure(allocator.data, Allocator_Mode.Alloc, new_size, alignment, nil, 0, 0, loc);
}
return allocator.procedure(allocator.data, Allocator_Mode.Resize, new_size, alignment, ptr, old_size, 0, loc);
}
delete_string :: proc(str: string, allocator := context.allocator, loc := #caller_location) {
free(raw_data(str), allocator, loc);
}
delete_cstring :: proc(str: cstring, allocator := context.allocator, loc := #caller_location) {
free((^byte)(str), allocator, loc);
}
delete_dynamic_array :: proc(array: $T/[dynamic]$E, loc := #caller_location) {
free(raw_data(array), array.allocator, loc);
}
delete_slice :: proc(array: $T/[]$E, allocator := context.allocator, loc := #caller_location) {
free(raw_data(array), allocator, loc);
}
delete_map :: proc(m: $T/map[$K]$V, loc := #caller_location) {
raw := transmute(Raw_Map)m;
delete_slice(raw.hashes);
free(raw.entries.data, raw.entries.allocator, loc);
}
delete :: proc[
delete_string,
delete_cstring,
delete_dynamic_array,
delete_slice,
delete_map,
];
new :: inline proc($T: typeid, allocator := context.allocator, loc := #caller_location) -> ^T {
ptr := (^T)(alloc(size_of(T), align_of(T), allocator, loc));
if ptr != nil do ptr^ = T{};
return ptr;
}
new_clone :: inline proc(data: $T, allocator := context.allocator, loc := #caller_location) -> ^T {
ptr := (^T)(alloc(size_of(T), align_of(T), allocator, loc));
if ptr != nil do ptr^ = data;
return ptr;
}
make_slice :: proc($T: typeid/[]$E, auto_cast len: int, allocator := context.allocator, loc := #caller_location) -> T {
runtime.make_slice_error_loc(loc, len);
data := alloc(size_of(E)*len, align_of(E), allocator, loc);
s := Raw_Slice{data, len};
return transmute(T)s;
}
make_dynamic_array :: proc($T: typeid/[dynamic]$E, allocator := context.allocator, loc := #caller_location) -> T {
return make_dynamic_array_len_cap(T, 0, 16, allocator, loc);
}
make_dynamic_array_len :: proc($T: typeid/[dynamic]$E, auto_cast len: int, allocator := context.allocator, loc := #caller_location) -> T {
return make_dynamic_array_len_cap(T, len, len, allocator, loc);
}
make_dynamic_array_len_cap :: proc($T: typeid/[dynamic]$E, auto_cast len: int, auto_cast cap: int, allocator := context.allocator, loc := #caller_location) -> T {
runtime.make_dynamic_array_error_loc(loc, len, cap);
data := alloc(size_of(E)*cap, align_of(E), allocator, loc);
s := Raw_Dynamic_Array{data, len, cap, allocator};
return transmute(T)s;
}
make_map :: proc($T: typeid/map[$K]$E, auto_cast cap: int = 16, allocator := context.allocator, loc := #caller_location) -> T {
runtime.make_map_expr_error_loc(loc, cap);
context.allocator = allocator;
m: T;
reserve_map(&m, cap);
return m;
}
make :: proc[
make_slice,
make_dynamic_array,
make_dynamic_array_len,
make_dynamic_array_len_cap,
make_map,
];
default_resize_align :: proc(old_memory: rawptr, old_size, new_size, alignment: int, allocator := context.allocator, loc := #caller_location) -> rawptr {
if old_memory == nil do return alloc(new_size, alignment, allocator, loc);
if new_size == 0 {
free(old_memory, allocator, loc);
return nil;
}
if new_size == old_size do return old_memory;
new_memory := alloc(new_size, alignment, allocator, loc);
if new_memory == nil do return nil;
copy(new_memory, old_memory, min(old_size, new_size));;
free(old_memory, allocator, loc);
return new_memory;
}
nil_allocator_proc :: proc(allocator_data: rawptr, mode: Allocator_Mode,
size, alignment: int,
old_memory: rawptr, old_size: int, flags: u64 = 0, loc := #caller_location) -> rawptr {
return nil;
}
nil_allocator :: proc() -> Allocator {
return Allocator{
procedure = nil_allocator_proc,
data = nil,
};
}
Scratch_Allocator :: struct {
data: []byte,
curr_offset: int,
prev_offset: int,
backup_allocator: Allocator,
leaked_allocations: [dynamic]rawptr,
}
scratch_allocator_init :: proc(scratch: ^Scratch_Allocator, data: []byte, backup_allocator := context.allocator) {
scratch.data = data;
scratch.curr_offset = 0;
scratch.prev_offset = 0;
scratch.backup_allocator = backup_allocator;
}
scratch_allocator_proc :: proc(allocator_data: rawptr, mode: Allocator_Mode,
size, alignment: int,
old_memory: rawptr, old_size: int, flags: u64 = 0, loc := #caller_location) -> rawptr {
scratch := (^Scratch_Allocator)(allocator_data);
if scratch.data == nil {
DEFAULT_SCRATCH_BACKING_SIZE :: 1<<22;
scratch_allocator_init(scratch, make([]byte, 1<<22));
}
switch mode {
case Allocator_Mode.Alloc:
switch {
case scratch.curr_offset+size <= len(scratch.data):
offset := align_forward_uintptr(uintptr(scratch.curr_offset), uintptr(alignment));
ptr := &scratch.data[offset];
zero(ptr, size);
scratch.prev_offset = int(offset);
scratch.curr_offset = int(offset) + size;
return ptr;
case size <= len(scratch.data):
offset := align_forward_uintptr(uintptr(0), uintptr(alignment));
ptr := &scratch.data[offset];
zero(ptr, size);
scratch.prev_offset = int(offset);
scratch.curr_offset = int(offset) + size;
return ptr;
}
// TODO(bill): Should leaks be notified about? Should probably use a logging system that is built into the context system
a := scratch.backup_allocator;
if a.procedure == nil {
a = context.allocator;
scratch.backup_allocator = a;
}
ptr := alloc(size, alignment, a, loc);
if scratch.leaked_allocations == nil {
scratch.leaked_allocations = make([dynamic]rawptr, a);
}
append(&scratch.leaked_allocations, ptr);
return ptr;
case Allocator_Mode.Free:
last_ptr := rawptr(&scratch.data[scratch.prev_offset]);
if old_memory == last_ptr {
full_size := scratch.curr_offset - scratch.prev_offset;
scratch.curr_offset = scratch.prev_offset;
zero(last_ptr, full_size);
return nil;
}
// NOTE(bill): It's scratch memory, don't worry about freeing
case Allocator_Mode.Free_All:
scratch.curr_offset = 0;
scratch.prev_offset = 0;
for ptr in scratch.leaked_allocations {
free(ptr, scratch.backup_allocator);
}
clear(&scratch.leaked_allocations);
case Allocator_Mode.Resize:
last_ptr := rawptr(&scratch.data[scratch.prev_offset]);
if old_memory == last_ptr && len(scratch.data)-scratch.prev_offset >= size {
scratch.curr_offset = scratch.prev_offset+size;
return old_memory;
}
return scratch_allocator_proc(allocator_data, Allocator_Mode.Alloc, size, alignment, old_memory, old_size, flags, loc);
}
return nil;
}
scratch_allocator :: proc(scratch: ^Scratch_Allocator) -> Allocator {
return Allocator{
procedure = scratch_allocator_proc,
data = scratch,
};
}
Pool :: struct {
block_size: int,
out_band_size: int,
alignment: int,
unused_blocks: [dynamic]rawptr,
used_blocks: [dynamic]rawptr,
out_band_allocations: [dynamic]rawptr,
current_block: rawptr,
current_pos: rawptr,
bytes_left: int,
block_allocator: Allocator,
}
POOL_BLOCK_SIZE_DEFAULT :: 65536;
POOL_OUT_OF_BAND_SIZE_DEFAULT :: 6554;
pool_allocator_proc :: proc(allocator_data: rawptr, mode: Allocator_Mode,
size, alignment: int,
old_memory: rawptr, old_size: int, flags: u64 = 0, loc := #caller_location) -> rawptr {
pool := (^Pool)(allocator_data);
switch mode {
case Allocator_Mode.Alloc:
return pool_alloc(pool, size);
case Allocator_Mode.Free:
panic("Allocator_Mode.Free is not supported for a pool");
case Allocator_Mode.Free_All:
pool_free_all(pool);
case Allocator_Mode.Resize:
panic("Allocator_Mode.Resize is not supported for a pool");
if old_size >= size {
return old_memory;
}
ptr := pool_alloc(pool, size);
copy(ptr, old_memory, old_size);
return ptr;
}
return nil;
}
pool_allocator :: proc(pool: ^Pool) -> Allocator {
return Allocator{
procedure = pool_allocator_proc,
data = pool,
};
}
pool_init :: proc(pool: ^Pool,
block_allocator := Allocator{} , array_allocator := Allocator{},
block_size := POOL_BLOCK_SIZE_DEFAULT, out_band_size := POOL_OUT_OF_BAND_SIZE_DEFAULT,
alignment := 8) {
pool.block_size = block_size;
pool.out_band_size = out_band_size;
pool.alignment = alignment;
if block_allocator.procedure == nil {
block_allocator = context.allocator;
}
if array_allocator.procedure == nil {
array_allocator = context.allocator;
}
pool.block_allocator = block_allocator;
pool.out_band_allocations.allocator = array_allocator;
pool. unused_blocks.allocator = array_allocator;
pool. used_blocks.allocator = array_allocator;
}
pool_destroy :: proc(using pool: ^Pool) {
pool_free_all(pool);
delete(unused_blocks);
delete(used_blocks);
zero(pool, size_of(pool^));
}
pool_alloc :: proc(using pool: ^Pool, bytes: int) -> rawptr {
cycle_new_block :: proc(using pool: ^Pool) {
if block_allocator.procedure == nil {
panic("You must call pool_init on a Pool before using it");
}
if current_block != nil {
append(&used_blocks, current_block);
}
new_block: rawptr;
if len(unused_blocks) > 0 {
new_block = pop(&unused_blocks);
} else {
new_block = block_allocator.procedure(block_allocator.data, Allocator_Mode.Alloc,
block_size, alignment,
nil, 0);
}
bytes_left = block_size;
current_pos = new_block;
current_block = new_block;
}
extra := alignment - (bytes % alignment);
bytes += extra;
if bytes >= out_band_size {
assert(block_allocator.procedure != nil);
memory := block_allocator.procedure(block_allocator.data, Allocator_Mode.Alloc,
block_size, alignment,
nil, 0);
if memory != nil {
append(&out_band_allocations, (^byte)(memory));
}
return memory;
}
if bytes_left < bytes {
cycle_new_block(pool);
if current_block == nil {
return nil;
}
}
memory := current_pos;
current_pos = ptr_offset((^byte)(current_pos), bytes);
bytes_left -= bytes;
return memory;
}
pool_reset :: proc(using pool: ^Pool) {
if current_block != nil {
append(&unused_blocks, current_block);
current_block = nil;
}
for block in used_blocks {
append(&unused_blocks, block);
}
clear(&used_blocks);
for a in out_band_allocations {
free(a, block_allocator);
}
clear(&out_band_allocations);
}
pool_free_all :: proc(using pool: ^Pool) {
pool_reset(pool);
for block in unused_blocks {
free(block, block_allocator);
}
clear(&unused_blocks);
}
+329
View File
@@ -0,0 +1,329 @@
package mem
foreign _ {
@(link_name = "llvm.bswap.i16") swap16 :: proc(b: u16) -> u16 ---;
@(link_name = "llvm.bswap.i32") swap32 :: proc(b: u32) -> u32 ---;
@(link_name = "llvm.bswap.i64") swap64 :: proc(b: u64) -> u64 ---;
}
swap :: proc[swap16, swap32, swap64];
set :: proc "contextless" (data: rawptr, value: byte, len: int) -> rawptr {
if data == nil do return nil;
if len < 0 do return data;
foreign _ {
when size_of(rawptr) == 8 {
@(link_name="llvm.memset.p0i8.i64")
llvm_memset :: proc(dst: rawptr, val: byte, len: int, align: i32, is_volatile: bool) ---;
} else {
@(link_name="llvm.memset.p0i8.i32")
llvm_memset :: proc(dst: rawptr, val: byte, len: int, align: i32, is_volatile: bool) ---;
}
}
llvm_memset(data, byte(value), len, 1, false);
return data;
}
zero :: proc "contextless" (data: rawptr, len: int) -> rawptr {
return set(data, 0, len);
}
zero_slice :: proc "contextless" (data: $T/[]$E) {
if n := len(data); n > 0 {
zero(&data[0], size_of(E)*n);
}
}
copy :: proc "contextless" (dst, src: rawptr, len: int) -> rawptr {
if src == nil do return dst;
// NOTE(bill): This _must_ be implemented like C's memmove
foreign _ {
when size_of(rawptr) == 8 {
@(link_name="llvm.memmove.p0i8.p0i8.i64")
llvm_memmove :: proc(dst, src: rawptr, len: int, align: i32, is_volatile: bool) ---;
} else {
@(link_name="llvm.memmove.p0i8.p0i8.i32")
llvm_memmove :: proc(dst, src: rawptr, len: int, align: i32, is_volatile: bool) ---;
}
}
llvm_memmove(dst, src, len, 1, false);
return dst;
}
copy_non_overlapping :: proc "contextless" (dst, src: rawptr, len: int) -> rawptr {
if src == nil do return dst;
// NOTE(bill): This _must_ be implemented like C's memcpy
foreign _ {
when size_of(rawptr) == 8 {
@(link_name="llvm.memcpy.p0i8.p0i8.i64")
llvm_memcpy :: proc(dst, src: rawptr, len: int, align: i32, is_volatile: bool) ---;
} else {
@(link_name="llvm.memcpy.p0i8.p0i8.i32")
llvm_memcpy :: proc(dst, src: rawptr, len: int, align: i32, is_volatile: bool) ---;
}
}
llvm_memcpy(dst, src, len, 1, false);
return dst;
}
compare :: proc "contextless" (a, b: []byte) -> int {
return compare_byte_ptrs(&a[0], &b[0], min(len(a), len(b)));
}
compare_byte_ptrs :: proc "contextless" (a, b: ^byte, n: int) -> int #no_bounds_check {
ptr_idx :: inline proc(ptr: $P/^$T, n: int) -> T {
return ptr_offset(ptr, n)^;
}
x := slice_ptr(a, n);
y := slice_ptr(b, n);
SU :: size_of(uintptr);
fast := n/SU + 1;
offset := (fast-1)*SU;
curr_block := 0;
if n < SU {
fast = 0;
}
la := slice_ptr((^uintptr)(a), fast);
lb := slice_ptr((^uintptr)(b), fast);
for /**/; curr_block < fast; curr_block += 1 {
if la[curr_block] ~ lb[curr_block] != 0 {
for pos := curr_block*SU; pos < n; pos += 1 {
if x[pos] ~ y[pos] != 0 {
return (int(x[pos]) - int(y[pos])) < 0 ? -1 : +1;
}
}
}
}
for /**/; offset < n; offset += 1 {
if x[offset] ~ y[offset] != 0 {
return (int(x[offset]) - int(y[offset])) < 0 ? -1 : +1;
}
}
return 0;
}
compare_ptrs :: inline proc "contextless" (a, b: rawptr, n: int) -> int {
return compare_byte_ptrs((^byte)(a), (^byte)(b), n);
}
ptr_offset :: proc "contextless" (ptr: $P/^$T, n: int) -> P {
new := int(uintptr(ptr)) + size_of(T)*n;
return P(uintptr(new));
}
ptr_sub :: proc "contextless" (a, b: $P/^$T) -> int {
return (int(uintptr(a)) - int(uintptr(b)))/size_of(T);
}
slice_ptr :: proc "contextless" (ptr: ^$T, len: int) -> []T {
assert(len >= 0);
slice := Raw_Slice{data = ptr, len = len};
return transmute([]T)slice;
}
slice_to_bytes :: proc "contextless" (slice: $E/[]$T) -> []byte {
s := transmute(Raw_Slice)slice;
s.len *= size_of(T);
return transmute([]byte)s;
}
buffer_from_slice :: proc(backing: $T/[]$E) -> [dynamic]E {
s := transmute(Raw_Slice)backing;
d := Raw_Dynamic_Array{
data = s.data,
len = 0,
cap = s.len,
allocator = nil_allocator(),
};
return transmute([dynamic]E)d;
}
ptr_to_bytes :: proc "contextless" (ptr: ^$T, len := 1) -> []byte {
assert(len >= 0);
return transmute([]byte)Raw_Slice{ptr, len*size_of(T)};
}
any_to_bytes :: proc "contextless" (val: any) -> []byte {
ti := type_info_of(val.id);
size := ti != nil ? ti.size : 0;
return transmute([]byte)Raw_Slice{val.data, size};
}
kilobytes :: inline proc "contextless" (x: int) -> int do return (x) * 1024;
megabytes :: inline proc "contextless" (x: int) -> int do return kilobytes(x) * 1024;
gigabytes :: inline proc "contextless" (x: int) -> int do return megabytes(x) * 1024;
terabytes :: inline proc "contextless" (x: int) -> int do return gigabytes(x) * 1024;
is_power_of_two :: proc(x: uintptr) -> bool {
if x <= 0 do return false;
return (x & (x-1)) == 0;
}
align_forward :: proc(ptr: rawptr, align: uintptr) -> rawptr {
assert(is_power_of_two(align));
a := uintptr(align);
p := uintptr(ptr);
modulo := p & (a-1);
if modulo != 0 do p += a - modulo;
return rawptr(p);
}
align_forward_uintptr :: proc(ptr, align: uintptr) -> uintptr {
assert(is_power_of_two(align));
a := uintptr(align);
p := uintptr(ptr);
modulo := p & (a-1);
if modulo != 0 do p += a - modulo;
return uintptr(p);
}
AllocationHeader :: struct {size: int};
allocation_header_fill :: proc(header: ^AllocationHeader, data: rawptr, size: int) {
header.size = size;
ptr := cast(^uint)(ptr_offset(header, 1));
n := ptr_sub(cast(^uint)data, ptr);
for i in 0..n-1 {
ptr_offset(ptr, i)^ = ~uint(0);
}
}
allocation_header :: proc(data: rawptr) -> ^AllocationHeader {
if data == nil do return nil;
p := cast(^uint)data;
for ptr_offset(p, -1)^ == ~uint(0) do p = ptr_offset(p, -1);
return (^AllocationHeader)(ptr_offset(p, -1));
}
Fixed_Byte_Buffer :: distinct [dynamic]byte;
make_fixed_byte_buffer :: proc(backing: []byte) -> Fixed_Byte_Buffer {
s := transmute(Raw_Slice)backing;
d: Raw_Dynamic_Array;
d.data = s.data;
d.len = 0;
d.cap = s.len;
d.allocator = nil_allocator();
return transmute(Fixed_Byte_Buffer)d;
}
// Custom allocators
Arena :: struct {
backing: Allocator,
memory: Fixed_Byte_Buffer,
temp_count: int,
}
Arena_Temp_Memory :: struct {
arena: ^Arena,
original_count: int,
}
init_arena_from_memory :: proc(using a: ^Arena, data: []byte) {
backing = Allocator{};
memory = make_fixed_byte_buffer(data);
temp_count = 0;
}
init_arena_from_context :: proc(using a: ^Arena, size: int) {
backing = context.allocator;
memory = make_fixed_byte_buffer(make([]byte, size));
temp_count = 0;
}
context_from_allocator :: proc(a: Allocator) -> type_of(context) {
context.allocator = a;
return context;
}
destroy_arena :: proc(using a: ^Arena) {
if backing.procedure != nil {
context.allocator = backing;
if memory != nil {
free(&memory[0]);
}
memory = nil;
}
}
arena_allocator :: proc(arena: ^Arena) -> Allocator {
return Allocator{
procedure = arena_allocator_proc,
data = arena,
};
}
arena_allocator_proc :: proc(allocator_data: rawptr, mode: Allocator_Mode,
size, alignment: int,
old_memory: rawptr, old_size: int, flags: u64, location := #caller_location) -> rawptr {
using Allocator_Mode;
arena := cast(^Arena)allocator_data;
switch mode {
case Alloc:
total_size := size + alignment;
if len(arena.memory) + total_size > cap(arena.memory) {
return nil;
}
#no_bounds_check end := &arena.memory[len(arena.memory)];
ptr := align_forward(end, uintptr(alignment));
(^Raw_Slice)(&arena.memory).len += total_size;
return zero(ptr, size);
case Free:
// NOTE(bill): Free all at once
// Use Arena_Temp_Memory if you want to free a block
case Free_All:
(^Raw_Slice)(&arena.memory).len = 0;
case Resize:
return default_resize_align(old_memory, old_size, size, alignment, arena_allocator(arena));
}
return nil;
}
begin_arena_temp_memory :: proc(a: ^Arena) -> Arena_Temp_Memory {
tmp: Arena_Temp_Memory;
tmp.arena = a;
tmp.original_count = len(a.memory);
a.temp_count += 1;
return tmp;
}
end_arena_temp_memory :: proc(using tmp: Arena_Temp_Memory) {
assert(len(arena.memory) >= original_count);
assert(arena.temp_count > 0);
(^Raw_Dynamic_Array)(&arena.memory).len = original_count;
arena.temp_count -= 1;
}
align_formula :: proc(size, align: int) -> int {
result := size + align-1;
return result - result%align;
}
+51
View File
@@ -0,0 +1,51 @@
package mem
Raw_Any :: struct {
data: rawptr,
id: typeid,
}
Raw_String :: struct {
data: ^byte,
len: int,
}
Raw_Cstring :: struct {
data: ^byte,
}
Raw_Slice :: struct {
data: rawptr,
len: int,
}
Raw_Dynamic_Array :: struct {
data: rawptr,
len: int,
cap: int,
allocator: Allocator,
}
Raw_Map :: struct {
hashes: []int,
entries: Raw_Dynamic_Array,
}
make_any :: inline proc(data: rawptr, id: typeid) -> any {
return transmute(any)Raw_Any{data, id};
}
raw_string_data :: inline proc(s: $T/string) -> ^byte {
return (^Raw_String)(&s).data;
}
raw_slice_data :: inline proc(a: $T/[]$E) -> ^E {
return cast(^E)(^Raw_Slice)(&a).data;
}
raw_dynamic_array_data :: inline proc(a: $T/[dynamic]$E) -> ^E {
return cast(^E)(^Raw_Dynamic_Array)(&a).data;
}
raw_data :: proc[raw_string_data, raw_slice_data, raw_dynamic_array_data];
-176
View File
@@ -1,176 +0,0 @@
foreign_system_library (
lib "opengl32.lib" when ODIN_OS == "windows";
lib "gl" when ODIN_OS == "linux";
)
import (
win32 "sys/windows.odin" when ODIN_OS == "windows";
"sys/wgl.odin" when ODIN_OS == "windows";
)
import_load "opengl_constants.odin";
foreign lib {
proc Clear (mask: u32) #link_name "glClear";
proc ClearColor (r, g, b, a: f32) #link_name "glClearColor";
proc Begin (mode: i32) #link_name "glBegin";
proc End () #link_name "glEnd";
proc Finish () #link_name "glFinish";
proc BlendFunc (sfactor, dfactor: i32) #link_name "glBlendFunc";
proc Enable (cap: i32) #link_name "glEnable";
proc Disable (cap: i32) #link_name "glDisable";
proc GenTextures (count: i32, result: ^u32) #link_name "glGenTextures";
proc DeleteTextures(count: i32, result: ^u32) #link_name "glDeleteTextures";
proc TexParameteri (target, pname, param: i32) #link_name "glTexParameteri";
proc TexParameterf (target: i32, pname: i32, param: f32) #link_name "glTexParameterf";
proc BindTexture (target: i32, texture: u32) #link_name "glBindTexture";
proc LoadIdentity () #link_name "glLoadIdentity";
proc Viewport (x, y, width, height: i32) #link_name "glViewport";
proc Ortho (left, right, bottom, top, near, far: f64) #link_name "glOrtho";
proc Color3f (r, g, b: f32) #link_name "glColor3f";
proc Vertex3f (x, y, z: f32) #link_name "glVertex3f";
proc GetError () -> i32 #link_name "glGetError";
proc GetString (name: i32) -> ^u8 #link_name "glGetString";
proc GetIntegerv (name: i32, v: ^i32) #link_name "glGetIntegerv";
proc TexCoord2f (x, y: f32) #link_name "glTexCoord2f";
proc TexImage2D (target, level, internal_format,
width, height, border,
format, type_: i32, pixels: rawptr) #link_name "glTexImage2D";
}
proc _string_data(s: string) -> ^u8 #inline { return &s[0]; }
var _libgl = win32.load_library_a(_string_data("opengl32.dll\x00"));
proc get_proc_address(name: string) -> rawptr {
if name[len(name)-1] == 0 {
name = name[0..<len(name)-1];
}
// NOTE(bill): null terminated
assert((&name[0] + len(name))^ == 0);
var res = wgl.get_proc_address(&name[0]);
if res == nil {
res = win32.get_proc_address(_libgl, &name[0]);
}
return rawptr(res);
}
var (
GenBuffers: proc(count: i32, buffers: ^u32) #cc_c;
GenVertexArrays: proc(count: i32, buffers: ^u32) #cc_c;
GenSamplers: proc(count: i32, buffers: ^u32) #cc_c;
DeleteBuffers: proc(count: i32, buffers: ^u32) #cc_c;
BindBuffer: proc(target: i32, buffer: u32) #cc_c;
BindVertexArray: proc(buffer: u32) #cc_c;
DeleteVertexArrays: proc(count: i32, arrays: ^u32) #cc_c;
BindSampler: proc(position: i32, sampler: u32) #cc_c;
BufferData: proc(target: i32, size: int, data: rawptr, usage: i32) #cc_c;
BufferSubData: proc(target: i32, offset, size: int, data: rawptr) #cc_c;
DrawArrays: proc(mode, first: i32, count: u32) #cc_c;
DrawElements: proc(mode: i32, count: u32, type_: i32, indices: rawptr) #cc_c;
MapBuffer: proc(target, access: i32) -> rawptr #cc_c;
UnmapBuffer: proc(target: i32) #cc_c;
VertexAttribPointer: proc(index: u32, size, type_: i32, normalized: i32, stride: u32, pointer: rawptr) #cc_c;
EnableVertexAttribArray: proc(index: u32) #cc_c;
CreateShader: proc(shader_type: i32) -> u32 #cc_c;
ShaderSource: proc(shader: u32, count: u32, str: ^^u8, length: ^i32) #cc_c;
CompileShader: proc(shader: u32) #cc_c;
CreateProgram: proc() -> u32 #cc_c;
AttachShader: proc(program, shader: u32) #cc_c;
DetachShader: proc(program, shader: u32) #cc_c;
DeleteShader: proc(shader: u32) #cc_c;
LinkProgram: proc(program: u32) #cc_c;
UseProgram: proc(program: u32) #cc_c;
DeleteProgram: proc(program: u32) #cc_c;
GetShaderiv: proc(shader: u32, pname: i32, params: ^i32) #cc_c;
GetProgramiv: proc(program: u32, pname: i32, params: ^i32) #cc_c;
GetShaderInfoLog: proc(shader: u32, max_length: u32, length: ^u32, info_long: ^u8) #cc_c;
GetProgramInfoLog: proc(program: u32, max_length: u32, length: ^u32, info_long: ^u8) #cc_c;
ActiveTexture: proc(texture: i32) #cc_c;
GenerateMipmap: proc(target: i32) #cc_c;
SamplerParameteri: proc(sampler: u32, pname: i32, param: i32) #cc_c;
SamplerParameterf: proc(sampler: u32, pname: i32, param: f32) #cc_c;
SamplerParameteriv: proc(sampler: u32, pname: i32, params: ^i32) #cc_c;
SamplerParameterfv: proc(sampler: u32, pname: i32, params: ^f32) #cc_c;
SamplerParameterIiv: proc(sampler: u32, pname: i32, params: ^i32) #cc_c;
SamplerParameterIuiv: proc(sampler: u32, pname: i32, params: ^u32) #cc_c;
Uniform1i: proc(loc: i32, v0: i32) #cc_c;
Uniform2i: proc(loc: i32, v0, v1: i32) #cc_c;
Uniform3i: proc(loc: i32, v0, v1, v2: i32) #cc_c;
Uniform4i: proc(loc: i32, v0, v1, v2, v3: i32) #cc_c;
Uniform1f: proc(loc: i32, v0: f32) #cc_c;
Uniform2f: proc(loc: i32, v0, v1: f32) #cc_c;
Uniform3f: proc(loc: i32, v0, v1, v2: f32) #cc_c;
Uniform4f: proc(loc: i32, v0, v1, v2, v3: f32) #cc_c;
UniformMatrix4fv: proc(loc: i32, count: u32, transpose: i32, value: ^f32) #cc_c;
GetUniformLocation: proc(program: u32, name: ^u8) -> i32 #cc_c;
)
proc init() {
proc set_proc_address(p: rawptr, name: string) #inline {
var x = ^rawptr(p);
x^ = get_proc_address(name);
}
set_proc_address(&GenBuffers, "glGenBuffers\x00");
set_proc_address(&GenVertexArrays, "glGenVertexArrays\x00");
set_proc_address(&GenSamplers, "glGenSamplers\x00");
set_proc_address(&DeleteBuffers, "glDeleteBuffers\x00");
set_proc_address(&BindBuffer, "glBindBuffer\x00");
set_proc_address(&BindSampler, "glBindSampler\x00");
set_proc_address(&BindVertexArray, "glBindVertexArray\x00");
set_proc_address(&DeleteVertexArrays, "glDeleteVertexArrays\x00");
set_proc_address(&BufferData, "glBufferData\x00");
set_proc_address(&BufferSubData, "glBufferSubData\x00");
set_proc_address(&DrawArrays, "glDrawArrays\x00");
set_proc_address(&DrawElements, "glDrawElements\x00");
set_proc_address(&MapBuffer, "glMapBuffer\x00");
set_proc_address(&UnmapBuffer, "glUnmapBuffer\x00");
set_proc_address(&VertexAttribPointer, "glVertexAttribPointer\x00");
set_proc_address(&EnableVertexAttribArray, "glEnableVertexAttribArray\x00");
set_proc_address(&CreateShader, "glCreateShader\x00");
set_proc_address(&ShaderSource, "glShaderSource\x00");
set_proc_address(&CompileShader, "glCompileShader\x00");
set_proc_address(&CreateProgram, "glCreateProgram\x00");
set_proc_address(&AttachShader, "glAttachShader\x00");
set_proc_address(&DetachShader, "glDetachShader\x00");
set_proc_address(&DeleteShader, "glDeleteShader\x00");
set_proc_address(&LinkProgram, "glLinkProgram\x00");
set_proc_address(&UseProgram, "glUseProgram\x00");
set_proc_address(&DeleteProgram, "glDeleteProgram\x00");
set_proc_address(&GetShaderiv, "glGetShaderiv\x00");
set_proc_address(&GetProgramiv, "glGetProgramiv\x00");
set_proc_address(&GetShaderInfoLog, "glGetShaderInfoLog\x00");
set_proc_address(&GetProgramInfoLog, "glGetProgramInfoLog\x00");
set_proc_address(&ActiveTexture, "glActiveTexture\x00");
set_proc_address(&GenerateMipmap, "glGenerateMipmap\x00");
set_proc_address(&Uniform1i, "glUniform1i\x00");
set_proc_address(&UniformMatrix4fv, "glUniformMatrix4fv\x00");
set_proc_address(&GetUniformLocation, "glGetUniformLocation\x00");
set_proc_address(&SamplerParameteri, "glSamplerParameteri\x00");
set_proc_address(&SamplerParameterf, "glSamplerParameterf\x00");
set_proc_address(&SamplerParameteriv, "glSamplerParameteriv\x00");
set_proc_address(&SamplerParameterfv, "glSamplerParameterfv\x00");
set_proc_address(&SamplerParameterIiv, "glSamplerParameterIiv\x00");
set_proc_address(&SamplerParameterIuiv, "glSamplerParameterIuiv\x00");
}
File diff suppressed because it is too large Load Diff
-49
View File
@@ -1,49 +0,0 @@
import_load (
"os_windows.odin" when ODIN_OS == "windows";
"os_x.odin" when ODIN_OS == "osx";
"os_linux.odin" when ODIN_OS == "linux";
)
proc write_string(fd: Handle, str: string) -> (int, Errno) {
return write(fd, []u8(str));
}
proc read_entire_file(name: string) -> ([]u8, bool) {
var fd, err = open(name, O_RDONLY, 0);
if err != 0 {
return nil, false;
}
defer close(fd);
var length: i64;
if length, err = file_size(fd); err != 0 {
return nil, false;
}
if length == 0 {
return nil, true;
}
var data = make([]u8, length);
if data == nil {
return nil, false;
}
var bytes_read, read_err = read(fd, data);
if read_err != 0 {
free(data);
return nil, false;
}
return data[0..<bytes_read], true;
}
proc write_entire_file(name: string, data: []u8) -> bool {
var fd, err = open(name, O_WRONLY, 0);
if err != 0 {
return false;
}
defer close(fd);
var bytes_written, write_err = write(fd, data);
return write_err != 0;
}
+142
View File
@@ -0,0 +1,142 @@
package os
import "core:mem"
import "core:strconv"
import "core:unicode/utf8"
write_string :: proc(fd: Handle, str: string) -> (int, Errno) {
return write(fd, cast([]byte)str);
}
write_byte :: proc(fd: Handle, b: byte) -> (int, Errno) {
return write(fd, []byte{b});
}
write_rune :: proc(fd: Handle, r: rune) -> (int, Errno) {
if r < utf8.RUNE_SELF {
return write_byte(fd, byte(r));
}
b, n := utf8.encode_rune(r);
return write(fd, b[:n]);
}
write_encoded_rune :: proc(fd: Handle, r: rune) {
write_byte(fd, '\'');
switch r {
case '\a': write_string(fd, "\\a");
case '\b': write_string(fd, "\\b");
case '\e': write_string(fd, "\\e");
case '\f': write_string(fd, "\\f");
case '\n': write_string(fd, "\\n");
case '\r': write_string(fd, "\\r");
case '\t': write_string(fd, "\\t");
case '\v': write_string(fd, "\\v");
case:
if r < 32 {
write_string(fd, "\\x");
b: [2]byte;
s := strconv.append_bits(b[:], u64(r), 16, true, 64, strconv.digits, nil);
switch len(s) {
case 0: write_string(fd, "00");
case 1: write_rune(fd, '0');
case 2: write_string(fd, s);
}
} else {
write_rune(fd, r);
}
}
write_byte(fd, '\'');
}
read_entire_file :: proc(name: string) -> (data: []byte, success: bool) {
fd, err := open(name, O_RDONLY, 0);
if err != 0 {
return nil, false;
}
defer close(fd);
length: i64;
if length, err = file_size(fd); err != 0 {
return nil, false;
}
if length <= 0 {
return nil, true;
}
data = make([]byte, int(length));
if data == nil {
return nil, false;
}
bytes_read, read_err := read(fd, data);
if read_err != 0 {
delete(data);
return nil, false;
}
return data[0:bytes_read], true;
}
write_entire_file :: proc(name: string, data: []byte, truncate := true) -> (success: bool) {
flags: int = O_WRONLY|O_CREATE;
if truncate {
flags |= O_TRUNC;
}
fd, err := open(name, flags, 0);
if err != 0 {
return false;
}
defer close(fd);
_, write_err := write(fd, data);
return write_err == 0;
}
write_ptr :: proc(fd: Handle, data: rawptr, len: int) -> (int, Errno) {
s := transmute([]byte)mem.Raw_Slice{data, len};
return write(fd, s);
}
read_ptr :: proc(fd: Handle, data: rawptr, len: int) -> (int, Errno) {
s := transmute([]byte)mem.Raw_Slice{data, len};
return read(fd, s);
}
heap_allocator_proc :: proc(allocator_data: rawptr, mode: mem.Allocator_Mode,
size, alignment: int,
old_memory: rawptr, old_size: int, flags: u64 = 0, loc := #caller_location) -> rawptr {
using mem.Allocator_Mode;
switch mode {
case Alloc:
return heap_alloc(size);
case Free:
heap_free(old_memory);
return nil;
case Free_All:
// NOTE(bill): Does nothing
case Resize:
if old_memory == nil {
return heap_alloc(size);
}
ptr := heap_resize(old_memory, size);
assert(ptr != nil);
return ptr;
}
return nil;
}
heap_allocator :: proc() -> mem.Allocator {
return mem.Allocator{
procedure = heap_allocator_proc,
data = nil,
};
}
+4
View File
@@ -0,0 +1,4 @@
package os;
ARCH :: "x86";
ENDIAN :: "little";
+4
View File
@@ -0,0 +1,4 @@
package os;
ARCH :: "amd64";
ENDIAN :: "little";
+176
View File
@@ -0,0 +1,176 @@
package os
OS :: "essence";
foreign import api "system:api"
Handle :: distinct int;
Errno :: distinct int;
O_RDONLY :: 0x00001;
O_WRONLY :: 0x00002;
O_RDWR :: 0x00003;
O_CREATE :: 0x00040;
O_EXCL :: 0x00080;
O_TRUNC :: 0x00200;
O_APPEND :: 0x00400;
ERROR_NONE :: Errno(-1);
ERROR_UNKNOWN_OPERATION_FAILURE :: Errno(-7);
ERROR_PATH_NOT_WITHIN_MOUNTED_VOLUME :: Errno(-14);
ERROR_PATH_NOT_FOUND :: Errno(-15);
ERROR_FILE_EXISTS :: Errno(-19);
ERROR_FILE_NOT_FOUND :: Errno(-20);
ERROR_DRIVE_ERROR_FILE_DAMAGED :: Errno(-21);
ERROR_ACCESS_NOT_WITHIN_FILE_BOUNDS :: Errno(-22);
ERROR_ACCESS_DENIED :: Errno(-23);
ERROR_FILE_IN_EXCLUSIVE_USE :: Errno(-24);
ERROR_FILE_CANNOT_GET_EXCLUSIVE_USE :: Errno(-25);
ERROR_INCORRECT_NODE_TYPE :: Errno(-26);
ERROR_EVENT_NOT_SET :: Errno(-27);
ERROR_TIMEOUT_REACHED :: Errno(-29);
ERROR_REQUEST_CLOSED_BEFORE_COMPLETE :: Errno(-30);
ERROR_NO_CHARACTER_AT_COORDINATE :: Errno(-31);
ERROR_FILE_ON_READ_ONLY_VOLUME :: Errno(-32);
ERROR_USER_CANCELED_IO :: Errno(-33);
ERROR_DRIVE_CONTROLLER_REPORTED :: Errno(-35);
ERROR_COULD_NOT_ISSUE_PACKET :: Errno(-36);
ERROR_NOT_IMPLEMENTED :: Errno(1);
OS_Node_Type :: enum i32 {
File = 0,
Directory = 1,
}
OS_Node_Information :: struct {
handle: Handle,
id: [16]byte,
ntype: OS_Node_Type,
size: i64,
// Our additions..
position: i64,
}
foreign api {
@(link_name="OSPrintDirect") OSPrintDirect :: proc(str: ^u8, length: int) ---;
@(link_name="malloc") OSMalloc :: proc(bytes: int) -> rawptr ---;
@(link_name="free") OSFree :: proc(address: rawptr) ---;
@(link_name="OSOpenNode") OSOpenNode :: proc(path: ^u8, path_length: int, flags: u64, information: ^OS_Node_Information) -> Errno ---;
@(link_name="OSResizeFile") OSResizeFile :: proc(handle: Handle, new_size: u64) -> Errno ---;
@(link_name="OSCloseHandle") OSCloseHandle :: proc(handle: Handle) ---;
@(link_name="OSWriteFileSync") OSWriteFileSync :: proc(handle: Handle, offset: i64, size: i64, buffer: rawptr) -> i64 ---;
@(link_name="OSReadFileSync") OSReadFileSync :: proc(handle: Handle, offset: i64, size: i64, buffer: rawptr) -> i64 ---;
@(link_name="realloc") OSRealloc :: proc(address: rawptr, size: int) -> rawptr ---;
@(link_name="OSGetThreadID") OSGetThreadID :: proc(handle: Handle) -> int ---;
@(link_name="OSRefreshNodeInformation") OSRefreshNodeInformation :: proc(information: ^OS_Node_Information) ---;
}
stdin := Handle(-1); // Not implemented
stdout := Handle(0);
stderr := Handle(0);
current_thread_id :: proc "contextless" () -> int {
return OSGetThreadID(Handle(0x1000));
}
heap_alloc :: proc(size: int) -> rawptr {
return OSMalloc(size);
}
heap_free :: proc(address: rawptr) {
OSFree(address);
}
heap_resize :: proc(address: rawptr, new_size: int) -> rawptr {
return OSRealloc(address, new_size);
}
open :: proc(path: string, mode: int = O_RDONLY, perm: u32 = 0) -> (Handle, Errno) {
flags : u64 = 0;
if mode & O_CREATE == O_CREATE {
flags = flags | 0x9000; // Fail if found and create directories leading to the file if they don't exist
} else {
flags = flags | 0x2000; // Fail if not found
}
if mode & O_EXCL == O_EXCL {
flags = flags | 0x111; // Block opening the node for any reason
}
if mode & O_RDONLY == O_RDONLY {
flags = flags | 0x2; // Read access
}
if mode & O_WRONLY == O_WRONLY {
flags = flags | 0x220; // Write and resize access
}
if mode & O_TRUNC == O_TRUNC {
flags = flags | 0x200; // Resize access
}
information := new(OS_Node_Information);
error := OSOpenNode(&path[0], len(path), flags, information);
if error < ERROR_NONE {
free(information);
return 0, error;
}
if mode & O_TRUNC == O_TRUNC {
error := OSResizeFile(information.handle, 0);
if error < ERROR_NONE do return 0, ERROR_UNKNOWN_OPERATION_FAILURE;
}
if mode & O_APPEND == O_APPEND {
information.position = information.size;
} else {
information.position = 0;
}
return Handle(uintptr(information)), ERROR_NONE;
}
close :: proc(fd: Handle) {
information := (^OS_Node_Information)(uintptr(fd));
OSCloseHandle(information.handle);
free(information);
}
file_size :: proc(fd: Handle) -> (i64, Errno) {
x: OS_Node_Information;
OSRefreshNodeInformation(&x);
return x.size, ERROR_NONE;
}
write :: proc(fd: Handle, data: []byte) -> (int, Errno) {
if fd == 0 {
OSPrintDirect(&data[0], len(data));
return len(data), ERROR_NONE;
} else if fd == 1 {
assert(false);
return 0, ERROR_NOT_IMPLEMENTED;
}
information := (^OS_Node_Information)(uintptr(fd));
count := OSWriteFileSync(information.handle, information.position, i64(len(data)), &data[0]);
if count < 0 do return 0, 1;
information.position += count;
return int(count), 0;
}
read :: proc(fd: Handle, data: []byte) -> (int, Errno) {
if (fd == 0 || fd == 1) {
assert(false);
return 0, ERROR_NOT_IMPLEMENTED;
}
information := (^OS_Node_Information)(uintptr(fd));
count := OSReadFileSync(information.handle, information.position, i64(len(data)), &data[0]);
if count < 0 do return 0, ERROR_UNKNOWN_OPERATION_FAILURE;
information.position += count;
return int(count), ERROR_NONE;
}
+281
View File
@@ -0,0 +1,281 @@
package os
foreign import dl "system:dl"
foreign import libc "system:c"
import "core:runtime"
import "core:strings"
OS :: "linux";
Handle :: distinct i32;
File_Time :: distinct u64;
Errno :: distinct i32;
O_RDONLY :: 0x00000;
O_WRONLY :: 0x00001;
O_RDWR :: 0x00002;
O_CREATE :: 0x00040;
O_EXCL :: 0x00080;
O_NOCTTY :: 0x00100;
O_TRUNC :: 0x00200;
O_NONBLOCK :: 0x00800;
O_APPEND :: 0x00400;
O_SYNC :: 0x01000;
O_ASYNC :: 0x02000;
O_CLOEXEC :: 0x80000;
SEEK_SET :: 0;
SEEK_CUR :: 1;
SEEK_END :: 2;
SEEK_DATA :: 3;
SEEK_HOLE :: 4;
SEEK_MAX :: SEEK_HOLE;
// NOTE(zangent): These are OS specific!
// Do not mix these up!
RTLD_LAZY :: 0x001;
RTLD_NOW :: 0x002;
RTLD_BINDING_MASK :: 0x3;
RTLD_GLOBAL :: 0x100;
// "Argv" arguments converted to Odin strings
args := _alloc_command_line_arguments();
_File_Time :: struct {
seconds: i64,
nanoseconds: i32,
reserved: i32,
}
// Translated from
// https://android.googlesource.com/platform/prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.7-4.6/+/jb-dev/sysroot/usr/include/bits/stat.h
// Validity is not guaranteed.
Stat :: struct {
device_id: u64, // ID of device containing file
serial: u64, // File serial number
nlink: u32, // Number of hard links
mode: u32, // Mode of the file
uid: u32, // User ID of the file's owner
gid: u32, // Group ID of the file's group
_padding: i32, // 32 bits of padding
rdev: u64, // Device ID, if device
size: i64, // Size of the file, in bytes
block_size: i64, // Optimal bllocksize for I/O
blocks: i64, // Number of 512-byte blocks allocated
last_access: _File_Time, // Time of last access
modified: _File_Time, // Time of last modification
status_change: _File_Time, // Time of last status change
_reserve1,
_reserve2,
_reserve3: i64,
serial_numbe: u64, // File serial number..? Maybe.
_reserve4: i64,
};
// File type
S_IFMT :: 0170000; // Type of file mask
S_IFIFO :: 0010000; // Named pipe (fifo)
S_IFCHR :: 0020000; // Character special
S_IFDIR :: 0040000; // Directory
S_IFBLK :: 0060000; // Block special
S_IFREG :: 0100000; // Regular
S_IFLNK :: 0120000; // Symbolic link
S_IFSOCK :: 0140000; // Socket
// File mode
// Read, write, execute/search by owner
S_IRWXU :: 0000700; // RWX mask for owner
S_IRUSR :: 0000400; // R for owner
S_IWUSR :: 0000200; // W for owner
S_IXUSR :: 0000100; // X for owner
// Read, write, execute/search by group
S_IRWXG :: 0000070; // RWX mask for group
S_IRGRP :: 0000040; // R for group
S_IWGRP :: 0000020; // W for group
S_IXGRP :: 0000010; // X for group
// Read, write, execute/search by others
S_IRWXO :: 0000007; // RWX mask for other
S_IROTH :: 0000004; // R for other
S_IWOTH :: 0000002; // W for other
S_IXOTH :: 0000001; // X for other
S_ISUID :: 0004000; // Set user id on execution
S_ISGID :: 0002000; // Set group id on execution
S_ISVTX :: 0001000; // Directory restrcted delete
S_ISLNK :: inline proc(m: u32) -> bool do return (m & S_IFMT) == S_IFLNK;
S_ISREG :: inline proc(m: u32) -> bool do return (m & S_IFMT) == S_IFREG;
S_ISDIR :: inline proc(m: u32) -> bool do return (m & S_IFMT) == S_IFDIR;
S_ISCHR :: inline proc(m: u32) -> bool do return (m & S_IFMT) == S_IFCHR;
S_ISBLK :: inline proc(m: u32) -> bool do return (m & S_IFMT) == S_IFBLK;
S_ISFIFO :: inline proc(m: u32) -> bool do return (m & S_IFMT) == S_IFIFO;
S_ISSOCK :: inline proc(m: u32) -> bool do return (m & S_IFMT) == S_IFSOCK;
F_OK :: 0; // Test for file existance
X_OK :: 1; // Test for execute permission
W_OK :: 2; // Test for write permission
R_OK :: 4; // Test for read permission
foreign libc {
@(link_name="open") _unix_open :: proc(path: cstring, mode: int) -> Handle ---;
@(link_name="close") _unix_close :: proc(fd: Handle) -> i32 ---;
@(link_name="read") _unix_read :: proc(fd: Handle, buf: rawptr, size: int) -> int ---;
@(link_name="write") _unix_write :: proc(fd: Handle, buf: rawptr, size: int) -> int ---;
@(link_name="lseek64") _unix_seek :: proc(fd: Handle, offset: i64, whence: i32) -> i64 ---;
@(link_name="gettid") _unix_gettid :: proc() -> u64 ---;
@(link_name="stat") _unix_stat :: proc(path: cstring, stat: ^Stat) -> i32 ---;
@(link_name="access") _unix_access :: proc(path: cstring, mask: int) -> i32 ---;
@(link_name="malloc") _unix_malloc :: proc(size: int) -> rawptr ---;
@(link_name="calloc") _unix_calloc :: proc(num, size: int) -> rawptr ---;
@(link_name="free") _unix_free :: proc(ptr: rawptr) ---;
@(link_name="realloc") _unix_realloc :: proc(ptr: rawptr, size: int) -> rawptr ---;
@(link_name="getenv") _unix_getenv :: proc(cstring) -> cstring ---;
@(link_name="exit") _unix_exit :: proc(status: int) -> ! ---;
}
foreign dl {
@(link_name="dlopen") _unix_dlopen :: proc(filename: cstring, flags: int) -> rawptr ---;
@(link_name="dlsym") _unix_dlsym :: proc(handle: rawptr, symbol: cstring) -> rawptr ---;
@(link_name="dlclose") _unix_dlclose :: proc(handle: rawptr) -> int ---;
@(link_name="dlerror") _unix_dlerror :: proc() -> cstring ---;
}
// TODO(zangent): Change this to just `open` when Bill fixes overloading.
open_simple :: proc(path: string, mode: int) -> (Handle, Errno) {
cstr := strings.new_cstring(path);
handle := _unix_open(cstr, mode);
delete(cstr);
if(handle == -1) {
return 0, 1;
}
return handle, 0;
}
// NOTE(zangent): This is here for compatability reasons. Should this be here?
open :: proc(path: string, mode: int = O_RDONLY, perm: u32 = 0) -> (Handle, Errno) {
return open_simple(path, mode);
}
close :: proc(fd: Handle) {
_unix_close(fd);
}
read :: proc(fd: Handle, data: []byte) -> (int, Errno) {
sz := _unix_read(fd, &data[0], len(data));
return sz, 0;
}
write :: proc(fd: Handle, data: []byte) -> (int, Errno) {
sz := _unix_write(fd, &data[0], len(data));
return sz, 0;
}
seek :: proc(fd: Handle, offset: i64, whence: int) -> (i64, Errno) {
res := _unix_seek(fd, offset, i32(whence));
return res, 0;
}
file_size :: proc(fd: Handle) -> (i64, Errno) {
prev, _ := seek(fd, 0, SEEK_CUR);
size, err := seek(fd, 0, SEEK_END);
seek(fd, prev, SEEK_SET);
return size, err;
}
// NOTE(bill): Uses startup to initialize it
stdin: Handle = 0;
stdout: Handle = 1;
stderr: Handle = 2;
/* TODO(zangent): Implement these!
last_write_time :: proc(fd: Handle) -> File_Time {}
last_write_time_by_name :: proc(name: string) -> File_Time {}
*/
stat :: inline proc(path: string) -> (Stat, int) {
cstr := strings.new_cstring(path);
defer delete(cstr);
s: Stat;
ret_int := _unix_stat(cstr, &s);
return s, int(ret_int);
}
access :: inline proc(path: string, mask: int) -> bool {
cstr := strings.new_cstring(path);
defer delete(cstr);
return _unix_access(cstr, mask) == 0;
}
heap_alloc :: proc(size: int) -> rawptr {
assert(size >= 0);
return _unix_calloc(1, size);
}
heap_resize :: proc(ptr: rawptr, new_size: int) -> rawptr {
return _unix_realloc(ptr, new_size);
}
heap_free :: proc(ptr: rawptr) {
_unix_free(ptr);
}
getenv :: proc(name: string) -> (string, bool) {
path_str := strings.new_cstring(name);
defer delete(path_str);
cstr := _unix_getenv(path_str);
if cstr == nil {
return "", false;
}
return string(cstr), true;
}
exit :: proc(code: int) -> ! {
_unix_exit(code);
}
current_thread_id :: proc "contextless" () -> int {
// return int(_unix_gettid());
return 0;
}
dlopen :: inline proc(filename: string, flags: int) -> rawptr {
cstr := strings.new_cstring(filename);
defer delete(cstr);
handle := _unix_dlopen(cstr, flags);
return handle;
}
dlsym :: inline proc(handle: rawptr, symbol: string) -> rawptr {
assert(handle != nil);
cstr := strings.new_cstring(symbol);
defer delete(cstr);
proc_handle := _unix_dlsym(handle, cstr);
return proc_handle;
}
dlclose :: inline proc(handle: rawptr) -> bool {
assert(handle != nil);
return _unix_dlclose(handle) == 0;
}
dlerror :: proc() -> string {
return string(_unix_dlerror());
}
_alloc_command_line_arguments :: proc() -> []string {
args := make([]string, len(runtime.args__));
for arg, i in runtime.args__ {
args[i] = string(arg);
}
return args;
}
+296
View File
@@ -0,0 +1,296 @@
package os
foreign import dl "system:dl"
foreign import libc "system:c"
import "core:runtime"
import "core:strings"
OS :: "osx";
Handle :: distinct i32;
File_Time :: distinct u64;
Errno :: distinct int;
O_RDONLY :: 0x00000;
O_WRONLY :: 0x00001;
O_RDWR :: 0x00002;
O_CREATE :: 0x00040;
O_EXCL :: 0x00080;
O_NOCTTY :: 0x00100;
O_TRUNC :: 0x00200;
O_NONBLOCK :: 0x00800;
O_APPEND :: 0x00400;
O_SYNC :: 0x01000;
O_ASYNC :: 0x02000;
O_CLOEXEC :: 0x80000;
SEEK_SET :: 0;
SEEK_CUR :: 1;
SEEK_END :: 2;
SEEK_DATA :: 3;
SEEK_HOLE :: 4;
SEEK_MAX :: SEEK_HOLE;
// NOTE(zangent): These are OS specific!
// Do not mix these up!
RTLD_LAZY :: 0x1;
RTLD_NOW :: 0x2;
RTLD_LOCAL :: 0x4;
RTLD_GLOBAL :: 0x8;
RTLD_NODELETE :: 0x80;
RTLD_NOLOAD :: 0x10;
RTLD_FIRST :: 0x100;
// "Argv" arguments converted to Odin strings
args := _alloc_command_line_arguments();
_File_Time :: struct {
seconds: i64,
nanoseconds: i64,
}
Stat :: struct {
device_id: i32, // ID of device containing file
mode: u16, // Mode of the file
nlink: u16, // Number of hard links
serial: u64, // File serial number
uid: u32, // User ID of the file's owner
gid: u32, // Group ID of the file's group
rdev: i32, // Device ID, if device
last_access: File_Time, // Time of last access
modified: File_Time, // Time of last modification
status_change: File_Time, // Time of last status change
created: File_Time, // Time of creation
size: i64, // Size of the file, in bytes
blocks: i64, // Number of blocks allocated for the file
block_size: i32, // Optimal blocksize for I/O
flags: u32, // User-defined flags for the file
gen_num: u32, // File generation number ..?
_spare: i32, // RESERVED
_reserve1,
_reserve2: i64, // RESERVED
};
// File type
S_IFMT :: 0170000; // Type of file mask
S_IFIFO :: 0010000; // Named pipe (fifo)
S_IFCHR :: 0020000; // Character special
S_IFDIR :: 0040000; // Directory
S_IFBLK :: 0060000; // Block special
S_IFREG :: 0100000; // Regular
S_IFLNK :: 0120000; // Symbolic link
S_IFSOCK :: 0140000; // Socket
// File mode
// Read, write, execute/search by owner
S_IRWXU :: 0000700; // RWX mask for owner
S_IRUSR :: 0000400; // R for owner
S_IWUSR :: 0000200; // W for owner
S_IXUSR :: 0000100; // X for owner
// Read, write, execute/search by group
S_IRWXG :: 0000070; // RWX mask for group
S_IRGRP :: 0000040; // R for group
S_IWGRP :: 0000020; // W for group
S_IXGRP :: 0000010; // X for group
// Read, write, execute/search by others
S_IRWXO :: 0000007; // RWX mask for other
S_IROTH :: 0000004; // R for other
S_IWOTH :: 0000002; // W for other
S_IXOTH :: 0000001; // X for other
S_ISUID :: 0004000; // Set user id on execution
S_ISGID :: 0002000; // Set group id on execution
S_ISVTX :: 0001000; // Directory restrcted delete
S_ISLNK :: inline proc(m: u32) -> bool do return (m & S_IFMT) == S_IFLNK;
S_ISREG :: inline proc(m: u32) -> bool do return (m & S_IFMT) == S_IFREG;
S_ISDIR :: inline proc(m: u32) -> bool do return (m & S_IFMT) == S_IFDIR;
S_ISCHR :: inline proc(m: u32) -> bool do return (m & S_IFMT) == S_IFCHR;
S_ISBLK :: inline proc(m: u32) -> bool do return (m & S_IFMT) == S_IFBLK;
S_ISFIFO :: inline proc(m: u32) -> bool do return (m & S_IFMT) == S_IFIFO;
S_ISSOCK :: inline proc(m: u32) -> bool do return (m & S_IFMT) == S_IFSOCK;
R_OK :: 4; // Test for read permission
W_OK :: 2; // Test for write permission
X_OK :: 1; // Test for execute permission
F_OK :: 0; // Test for file existance
foreign libc {
@(link_name="open") _unix_open :: proc(path: cstring, mode: int) -> Handle ---;
@(link_name="close") _unix_close :: proc(handle: Handle) ---;
@(link_name="read") _unix_read :: proc(handle: Handle, buffer: rawptr, count: int) -> int ---;
@(link_name="write") _unix_write :: proc(handle: Handle, buffer: rawptr, count: int) -> int ---;
@(link_name="lseek") _unix_lseek :: proc(fs: Handle, offset: int, whence: int) -> int ---;
@(link_name="gettid") _unix_gettid :: proc() -> u64 ---;
@(link_name="stat") _unix_stat :: proc(path: cstring, stat: ^Stat) -> int ---;
@(link_name="access") _unix_access :: proc(path: cstring, mask: int) -> int ---;
@(link_name="malloc") _unix_malloc :: proc(size: int) -> rawptr ---;
@(link_name="calloc") _unix_calloc :: proc(num, size: int) -> rawptr ---;
@(link_name="free") _unix_free :: proc(ptr: rawptr) ---;
@(link_name="realloc") _unix_realloc :: proc(ptr: rawptr, size: int) -> rawptr ---;
@(link_name="getenv") _unix_getenv :: proc(cstring) -> cstring ---;
@(link_name="exit") _unix_exit :: proc(status: int) ---;
}
foreign dl {
@(link_name="dlopen") _unix_dlopen :: proc(filename: cstring, flags: int) -> rawptr ---;
@(link_name="dlsym") _unix_dlsym :: proc(handle: rawptr, symbol: cstring) -> rawptr ---;
@(link_name="dlclose") _unix_dlclose :: proc(handle: rawptr) -> int ---;
@(link_name="dlerror") _unix_dlerror :: proc() -> cstring ---;
}
// TODO(zangent): Change this to just `open` when Bill fixes overloading.
open_simple :: proc(path: string, mode: int) -> (Handle, Errno) {
cstr := strings.new_cstring(path);
defer delete(cstr);
handle := _unix_open(cstr, mode);
if handle == -1 {
return 0, 1;
}
return handle, 0;
}
// NOTE(zangent): This is here for compatability reasons. Should this be here?
open :: proc(path: string, mode: int = O_RDONLY, perm: u32 = 0) -> (Handle, Errno) {
return open_simple(path, mode);
}
close :: proc(fd: Handle) {
_unix_close(fd);
}
write :: proc(fd: Handle, data: []u8) -> (int, Errno) {
assert(fd != -1);
bytes_written := _unix_write(fd, &data[0], len(data));
if(bytes_written == -1) {
return 0, 1;
}
return bytes_written, 0;
}
read :: proc(fd: Handle, data: []u8) -> (int, Errno) {
assert(fd != -1);
bytes_read := _unix_read(fd, &data[0], len(data));
if bytes_read == -1 {
return 0, 1;
}
return bytes_read, 0;
}
seek :: proc(fd: Handle, offset: i64, whence: int) -> (i64, Errno) {
assert(fd != -1);
final_offset := i64(_unix_lseek(fd, int(offset), whence));
if final_offset == -1 {
return 0, 1;
}
return final_offset, 0;
}
file_size :: proc(fd: Handle) -> (i64, Errno) {
prev, _ := seek(fd, 0, SEEK_CUR);
size, err := seek(fd, 0, SEEK_END);
seek(fd, prev, SEEK_SET);
return i64(size), err;
}
// NOTE(bill): Uses startup to initialize it
stdin: Handle = 0; // get_std_handle(win32.STD_INPUT_HANDLE);
stdout: Handle = 1; // get_std_handle(win32.STD_OUTPUT_HANDLE);
stderr: Handle = 2; // get_std_handle(win32.STD_ERROR_HANDLE);
/* TODO(zangent): Implement these!
last_write_time :: proc(fd: Handle) -> File_Time {}
last_write_time_by_name :: proc(name: string) -> File_Time {}
*/
stat :: inline proc(path: string) -> (Stat, bool) {
s: Stat;
cstr := strings.new_cstring(path);
defer delete(cstr);
ret_int := _unix_stat(cstr, &s);
return s, ret_int==0;
}
access :: inline proc(path: string, mask: int) -> bool {
cstr := strings.new_cstring(path);
defer delete(cstr);
return _unix_access(cstr, mask) == 0;
}
heap_alloc :: inline proc(size: int) -> rawptr {
assert(size > 0);
return _unix_calloc(1, size);
}
heap_resize :: inline proc(ptr: rawptr, new_size: int) -> rawptr {
return _unix_realloc(ptr, new_size);
}
heap_free :: inline proc(ptr: rawptr) {
_unix_free(ptr);
}
getenv :: proc(name: string) -> (string, bool) {
path_str := strings.new_cstring(name);
defer delete(path_str);
cstr := _unix_getenv(path_str);
if cstr == nil {
return "", false;
}
return string(cstr), true;
}
exit :: inline proc(code: int) -> ! {
_unix_exit(code);
}
current_thread_id :: proc "contextless" () -> int {
// return int(_unix_gettid());
return 0;
}
dlopen :: inline proc(filename: string, flags: int) -> rawptr {
cstr := strings.new_cstring(filename);
defer delete(cstr);
handle := _unix_dlopen(cstr, flags);
return handle;
}
dlsym :: inline proc(handle: rawptr, symbol: string) -> rawptr {
assert(handle != nil);
cstr := strings.new_cstring(symbol);
defer delete(cstr);
proc_handle := _unix_dlsym(handle, cstr);
return proc_handle;
}
dlclose :: inline proc(handle: rawptr) -> bool {
assert(handle != nil);
return _unix_dlclose(handle) == 0;
}
dlerror :: proc() -> string {
return string(_unix_dlerror());
}
_alloc_command_line_arguments :: proc() -> []string {
args := make([]string, len(runtime.args__));
for arg, i in runtime.args__ {
args[i] = string(arg);
}
return args;
}
+281
View File
@@ -0,0 +1,281 @@
// +build windows
package os
import "core:sys/win32"
OS :: "windows";
Handle :: distinct uintptr;
File_Time :: distinct u64;
Errno :: distinct int;
INVALID_HANDLE :: ~Handle(0);
O_RDONLY :: 0x00000;
O_WRONLY :: 0x00001;
O_RDWR :: 0x00002;
O_CREATE :: 0x00040;
O_EXCL :: 0x00080;
O_NOCTTY :: 0x00100;
O_TRUNC :: 0x00200;
O_NONBLOCK :: 0x00800;
O_APPEND :: 0x00400;
O_SYNC :: 0x01000;
O_ASYNC :: 0x02000;
O_CLOEXEC :: 0x80000;
ERROR_NONE: Errno : 0;
ERROR_FILE_NOT_FOUND: Errno : 2;
ERROR_PATH_NOT_FOUND: Errno : 3;
ERROR_ACCESS_DENIED: Errno : 5;
ERROR_NO_MORE_FILES: Errno : 18;
ERROR_HANDLE_EOF: Errno : 38;
ERROR_NETNAME_DELETED: Errno : 64;
ERROR_FILE_EXISTS: Errno : 80;
ERROR_BROKEN_PIPE: Errno : 109;
ERROR_BUFFER_OVERFLOW: Errno : 111;
ERROR_INSUFFICIENT_BUFFER: Errno : 122;
ERROR_MOD_NOT_FOUND: Errno : 126;
ERROR_PROC_NOT_FOUND: Errno : 127;
ERROR_DIR_NOT_EMPTY: Errno : 145;
ERROR_ALREADY_EXISTS: Errno : 183;
ERROR_ENVVAR_NOT_FOUND: Errno : 203;
ERROR_MORE_DATA: Errno : 234;
ERROR_OPERATION_ABORTED: Errno : 995;
ERROR_IO_PENDING: Errno : 997;
ERROR_NOT_FOUND: Errno : 1168;
ERROR_PRIVILEGE_NOT_HELD: Errno : 1314;
WSAEACCES: Errno : 10013;
WSAECONNRESET: Errno : 10054;
// Windows reserves errors >= 1<<29 for application use
ERROR_FILE_IS_PIPE: Errno : 1<<29 + 0;
// "Argv" arguments converted to Odin strings
args := _alloc_command_line_arguments();
open :: proc(path: string, mode: int = O_RDONLY, perm: u32 = 0) -> (Handle, Errno) {
if len(path) == 0 do return INVALID_HANDLE, ERROR_FILE_NOT_FOUND;
access: u32;
switch mode & (O_RDONLY|O_WRONLY|O_RDWR) {
case O_RDONLY: access = win32.FILE_GENERIC_READ;
case O_WRONLY: access = win32.FILE_GENERIC_WRITE;
case O_RDWR: access = win32.FILE_GENERIC_READ | win32.FILE_GENERIC_WRITE;
}
if mode&O_CREATE != 0 {
access |= win32.FILE_GENERIC_WRITE;
}
if mode&O_APPEND != 0 {
access &~= win32.FILE_GENERIC_WRITE;
access |= win32.FILE_APPEND_DATA;
}
share_mode := u32(win32.FILE_SHARE_READ|win32.FILE_SHARE_WRITE);
sa: ^win32.Security_Attributes = nil;
sa_inherit := win32.Security_Attributes{length = size_of(win32.Security_Attributes), inherit_handle = true};
if mode&O_CLOEXEC == 0 {
sa = &sa_inherit;
}
create_mode: u32;
switch {
case mode&(O_CREATE|O_EXCL) == (O_CREATE | O_EXCL):
create_mode = win32.CREATE_NEW;
case mode&(O_CREATE|O_TRUNC) == (O_CREATE | O_TRUNC):
create_mode = win32.CREATE_ALWAYS;
case mode&O_CREATE == O_CREATE:
create_mode = win32.OPEN_ALWAYS;
case mode&O_TRUNC == O_TRUNC:
create_mode = win32.TRUNCATE_EXISTING;
case:
create_mode = win32.OPEN_EXISTING;
}
wide_path := win32.utf8_to_wstring(path);
handle := Handle(win32.create_file_w(wide_path, access, share_mode, sa, create_mode, win32.FILE_ATTRIBUTE_NORMAL, nil));
if handle != INVALID_HANDLE do return handle, ERROR_NONE;
err := Errno(win32.get_last_error());
return INVALID_HANDLE, err;
}
close :: proc(fd: Handle) {
win32.close_handle(win32.Handle(fd));
}
write :: proc(fd: Handle, data: []byte) -> (int, Errno) {
if len(data) == 0 do return 0, ERROR_NONE;
single_write_length: i32;
total_write: i64;
length := i64(len(data));
for total_write < length {
remaining := length - total_write;
MAX :: 1<<31-1;
to_write: i32 = min(i32(remaining), MAX);
e := win32.write_file(win32.Handle(fd), &data[total_write], to_write, &single_write_length, nil);
if single_write_length <= 0 || !e {
err := Errno(win32.get_last_error());
return int(total_write), err;
}
total_write += i64(single_write_length);
}
return int(total_write), ERROR_NONE;
}
read :: proc(fd: Handle, data: []byte) -> (int, Errno) {
if len(data) == 0 do return 0, ERROR_NONE;
single_read_length: i32;
total_read: i64;
length := i64(len(data));
for total_read < length {
remaining := length - total_read;
MAX :: 1<<32-1;
to_read: u32 = min(u32(remaining), MAX);
e := win32.read_file(win32.Handle(fd), &data[total_read], to_read, &single_read_length, nil);
if single_read_length <= 0 || !e {
err := Errno(win32.get_last_error());
return int(total_read), err;
}
total_read += i64(single_read_length);
}
return int(total_read), ERROR_NONE;
}
seek :: proc(fd: Handle, offset: i64, whence: int) -> (i64, Errno) {
w: u32;
switch whence {
case 0: w = win32.FILE_BEGIN;
case 1: w = win32.FILE_CURRENT;
case 2: w = win32.FILE_END;
}
hi := i32(offset>>32);
lo := i32(offset);
ft := win32.get_file_type(win32.Handle(fd));
if ft == win32.FILE_TYPE_PIPE do return 0, ERROR_FILE_IS_PIPE;
dw_ptr := win32.set_file_pointer(win32.Handle(fd), lo, &hi, w);
if dw_ptr == win32.INVALID_SET_FILE_POINTER {
err := Errno(win32.get_last_error());
return 0, err;
}
return i64(hi)<<32 + i64(dw_ptr), ERROR_NONE;
}
file_size :: proc(fd: Handle) -> (i64, Errno) {
length: i64;
err: Errno;
if !win32.get_file_size_ex(win32.Handle(fd), &length) {
err = Errno(win32.get_last_error());
}
return length, err;
}
// NOTE(bill): Uses startup to initialize it
stdin := get_std_handle(win32.STD_INPUT_HANDLE);
stdout := get_std_handle(win32.STD_OUTPUT_HANDLE);
stderr := get_std_handle(win32.STD_ERROR_HANDLE);
get_std_handle :: proc(h: int) -> Handle {
fd := win32.get_std_handle(i32(h));
win32.set_handle_information(fd, win32.HANDLE_FLAG_INHERIT, 0);
return Handle(fd);
}
last_write_time :: proc(fd: Handle) -> File_Time {
file_info: win32.By_Handle_File_Information;
win32.get_file_information_by_handle(win32.Handle(fd), &file_info);
lo := File_Time(file_info.last_write_time.lo);
hi := File_Time(file_info.last_write_time.hi);
return lo | hi << 32;
}
last_write_time_by_name :: proc(name: string) -> File_Time {
last_write_time: win32.Filetime;
data: win32.File_Attribute_Data;
wide_path := win32.utf8_to_wstring(name);
if win32.get_file_attributes_ex_w(wide_path, win32.GetFileExInfoStandard, &data) {
last_write_time = data.last_write_time;
}
l := File_Time(last_write_time.lo);
h := File_Time(last_write_time.hi);
return l | h << 32;
}
heap_alloc :: proc(size: int) -> rawptr {
return win32.heap_alloc(win32.get_process_heap(), win32.HEAP_ZERO_MEMORY, size);
}
heap_resize :: proc(ptr: rawptr, new_size: int) -> rawptr {
if new_size == 0 {
heap_free(ptr);
return nil;
}
if ptr == nil do return heap_alloc(new_size);
return win32.heap_realloc(win32.get_process_heap(), win32.HEAP_ZERO_MEMORY, ptr, new_size);
}
heap_free :: proc(ptr: rawptr) {
if ptr == nil do return;
win32.heap_free(win32.get_process_heap(), 0, ptr);
}
exit :: proc(code: int) -> ! {
win32.exit_process(u32(code));
}
current_thread_id :: proc "contextless" () -> int {
return int(win32.get_current_thread_id());
}
_alloc_command_line_arguments :: proc() -> []string {
arg_count: i32;
arg_list_ptr := win32.command_line_to_argv_w(win32.get_command_line_w(), &arg_count);
arg_list := make([]string, int(arg_count));
for _, i in arg_list {
wc_str := (^win32.Wstring)(uintptr(arg_list_ptr) + size_of(win32.Wstring)*uintptr(i))^;
olen := win32.wide_char_to_multi_byte(win32.CP_UTF8, 0, wc_str, -1,
nil, 0, nil, nil);
buf := make([]byte, int(olen));
n := win32.wide_char_to_multi_byte(win32.CP_UTF8, 0, wc_str, -1,
cstring(&buf[0]), olen, nil, nil);
if n > 0 {
n -= 1;
}
arg_list[i] = string(buf[:n]);
}
return arg_list;
}
-281
View File
@@ -1,281 +0,0 @@
foreign_system_library (
dl "dl";
libc "c";
)
import "strings.odin";
type (
Handle i32;
FileTime u64;
Errno i32;
)
const (
O_RDONLY = 0x00000;
O_WRONLY = 0x00001;
O_RDWR = 0x00002;
O_CREAT = 0x00040;
O_EXCL = 0x00080;
O_NOCTTY = 0x00100;
O_TRUNC = 0x00200;
O_NONBLOCK = 0x00800;
O_APPEND = 0x00400;
O_SYNC = 0x01000;
O_ASYNC = 0x02000;
O_CLOEXEC = 0x80000;
)
const (
SEEK_SET = 0;
SEEK_CUR = 1;
SEEK_END = 2;
SEEK_DATA = 3;
SEEK_HOLE = 4;
SEEK_MAX = SEEK_HOLE;
)
const (
// NOTE(zangent): These are OS specific!
// Do not mix these up!
RTLD_LAZY = 0x001;
RTLD_NOW = 0x002;
RTLD_BINDING_MASK = 0x3;
RTLD_GLOBAL = 0x100;
)
// "Argv" arguments converted to Odin strings
var args = _alloc_command_line_arguments();
type _FileTime struct #ordered {
seconds: i64,
nanoseconds: i32,
reserved: i32,
}
// Translated from
// https://android.googlesource.com/platform/prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.7-4.6/+/jb-dev/sysroot/usr/include/bits/stat.h
// Validity is not guaranteed.
type Stat struct #ordered {
device_id: u64, // ID of device containing file
serial: u64, // File serial number
nlink: u32, // Number of hard links
mode: u32, // Mode of the file
uid: u32, // User ID of the file's owner
gid: u32, // Group ID of the file's group
_padding: i32, // 32 bits of padding
rdev: u64, // Device ID, if device
size: i64, // Size of the file, in bytes
block_size: i64, // Optimal bllocksize for I/O
blocks: i64, // Number of 512-byte blocks allocated
last_access: _FileTime, // Time of last access
modified: _FileTime, // Time of last modification
status_change: _FileTime, // Time of last status change
_reserve1,
_reserve2,
_reserve3: i64,
serial_numbe: u64, // File serial number...? Maybe.
_reserve4: i64,
};
// File type
const (
S_IFMT = 0170000; // Type of file mask
S_IFIFO = 0010000; // Named pipe (fifo)
S_IFCHR = 0020000; // Character special
S_IFDIR = 0040000; // Directory
S_IFBLK = 0060000; // Block special
S_IFREG = 0100000; // Regular
S_IFLNK = 0120000; // Symbolic link
S_IFSOCK = 0140000; // Socket
// File mode
// Read, write, execute/search by owner
S_IRWXU = 0000700; // RWX mask for owner
S_IRUSR = 0000400; // R for owner
S_IWUSR = 0000200; // W for owner
S_IXUSR = 0000100; // X for owner
// Read, write, execute/search by group
S_IRWXG = 0000070; // RWX mask for group
S_IRGRP = 0000040; // R for group
S_IWGRP = 0000020; // W for group
S_IXGRP = 0000010; // X for group
// Read, write, execute/search by others
S_IRWXO = 0000007; // RWX mask for other
S_IROTH = 0000004; // R for other
S_IWOTH = 0000002; // W for other
S_IXOTH = 0000001; // X for other
S_ISUID = 0004000; // Set user id on execution
S_ISGID = 0002000; // Set group id on execution
S_ISVTX = 0001000; // Directory restrcted delete
)
proc S_ISLNK (m: u32) -> bool #inline {return (m & S_IFMT) == S_IFLNK; }
proc S_ISREG (m: u32) -> bool #inline {return (m & S_IFMT) == S_IFREG; }
proc S_ISDIR (m: u32) -> bool #inline {return (m & S_IFMT) == S_IFDIR; }
proc S_ISCHR (m: u32) -> bool #inline {return (m & S_IFMT) == S_IFCHR; }
proc S_ISBLK (m: u32) -> bool #inline {return (m & S_IFMT) == S_IFBLK; }
proc S_ISFIFO(m: u32) -> bool #inline {return (m & S_IFMT) == S_IFIFO; }
proc S_ISSOCK(m: u32) -> bool #inline {return (m & S_IFMT) == S_IFSOCK;}
const (
R_OK = 4; // Test for read permission
W_OK = 2; // Test for write permission
X_OK = 1; // Test for execute permission
F_OK = 0; // Test for file existance
)
foreign libc {
proc _unix_open (path: ^u8, mode: int) -> Handle #link_name "open";
proc _unix_close (fd: Handle) -> i32 #link_name "close";
proc _unix_read (fd: Handle, buf: rawptr, size: int) -> int #link_name "read";
proc _unix_write (fd: Handle, buf: rawptr, size: int) -> int #link_name "write";
proc _unix_seek (fd: Handle, offset: i64, whence: i32) -> i64 #link_name "lseek64";
proc _unix_gettid() -> u64 #link_name "gettid";
proc _unix_stat (path: ^u8, stat: ^Stat) -> i32 #link_name "stat";
proc _unix_access(path: ^u8, mask: int) -> i32 #link_name "access";
proc _unix_malloc (size: int) -> rawptr #link_name "malloc";
proc _unix_free (ptr: rawptr) #link_name "free";
proc _unix_realloc(ptr: rawptr, size: int) -> rawptr #link_name "realloc";
proc _unix_getenv (^u8) -> ^u8 #link_name "getenv";
proc _unix_exit(status: int) #link_name "exit";
}
foreign dl {
proc _unix_dlopen (filename: ^u8, flags: int) -> rawptr #link_name "dlopen";
proc _unix_dlsym (handle: rawptr, symbol: ^u8) -> (proc() #cc_c) #link_name "dlsym";
proc _unix_dlclose(handle: rawptr) -> int #link_name "dlclose";
proc _unix_dlerror() -> ^u8 #link_name "dlerror";
}
// TODO(zangent): Change this to just `open` when Bill fixes overloading.
proc open_simple(path: string, mode: int) -> (Handle, Errno) {
var cstr = strings.new_c_string(path);
var handle = _unix_open(cstr, mode);
free(cstr);
if(handle == -1) {
return 0, 1;
}
return handle, 0;
}
// NOTE(zangent): This is here for compatability reasons. Should this be here?
proc open(path: string, mode: int = O_RDONLY, perm: u32 = 0) -> (Handle, Errno) {
return open_simple(path, mode);
}
proc close(fd: Handle) {
_unix_close(fd);
}
proc read(fd: Handle, data: []u8) -> (int, Errno) {
var sz = _unix_read(fd, &data[0], len(data));
return sz, 0;
}
proc write(fd: Handle, data: []u8) -> (int, Errno) {
var sz = _unix_write(fd, &data[0], len(data));
return sz, 0;
}
proc seek(fd: Handle, offset: i64, whence: int) -> (i64, Errno) {
var res = _unix_seek(fd, offset, i32(whence));
return res, 0;
}
proc file_size(fd: Handle) -> (i64, Errno) {
var prev, _ = seek(fd, 0, SEEK_CUR);
var size, err = seek(fd, 0, SEEK_END);
seek(fd, prev, SEEK_SET);
return size, err;
}
// NOTE(bill): Uses startup to initialize it
var (
stdin: Handle = 0;
stdout: Handle = 1;
stderr: Handle = 2;
)
/* TODO(zangent): Implement these!
proc last_write_time(fd: Handle) -> FileTime {}
proc last_write_time_by_name(name: string) -> FileTime {}
*/
proc stat(path: string) -> (Stat, int) #inline {
var s: Stat;
var cstr = strings.new_c_string(path);
defer free(cstr);
var ret_int = _unix_stat(cstr, &s);
return s, int(ret_int);
}
proc access(path: string, mask: int) -> bool #inline {
var cstr = strings.new_c_string(path);
defer free(cstr);
return _unix_access(cstr, mask) == 0;
}
proc heap_alloc(size: int) -> rawptr {
assert(size > 0);
return _unix_malloc(size);
}
proc heap_resize(ptr: rawptr, new_size: int) -> rawptr {
return _unix_realloc(ptr, new_size);
}
proc heap_free(ptr: rawptr) {
_unix_free(ptr);
}
proc getenv(name: string) -> (string, bool) {
var path_str = strings.new_c_string(name);
var cstr: ^u8 = _unix_getenv(path_str);
free(path_str);
if(cstr == nil) {
return "", false;
}
return strings.to_odin_string(cstr), true;
}
proc exit(code: int) {
_unix_exit(code);
}
proc current_thread_id() -> int {
// return int(_unix_gettid());
return 0;
}
proc dlopen(filename: string, flags: int) -> rawptr #inline {
var cstr = strings.new_c_string(filename);
var handle = _unix_dlopen(cstr, flags);
free(cstr);
return handle;
}
proc dlsym(handle: rawptr, symbol: string) -> (proc() #cc_c) #inline {
assert(handle != nil);
var cstr = strings.new_c_string(symbol);
var proc_handle = _unix_dlsym(handle, cstr);
free(cstr);
return proc_handle;
}
proc dlclose(handle: rawptr) -> bool #inline {
assert(handle != nil);
return _unix_dlclose(handle) == 0;
}
proc dlerror() -> string {
return strings.to_odin_string(_unix_dlerror());
}
proc _alloc_command_line_arguments() -> []string {
// TODO(bill):
return nil;
}
-345
View File
@@ -1,345 +0,0 @@
import win32 "sys/windows.odin";
type (
Handle int;
FileTime u64;
)
const INVALID_HANDLE: Handle = -1;
const (
O_RDONLY = 0x00000;
O_WRONLY = 0x00001;
O_RDWR = 0x00002;
O_CREAT = 0x00040;
O_EXCL = 0x00080;
O_NOCTTY = 0x00100;
O_TRUNC = 0x00200;
O_NONBLOCK = 0x00800;
O_APPEND = 0x00400;
O_SYNC = 0x01000;
O_ASYNC = 0x02000;
O_CLOEXEC = 0x80000;
)
type Errno int;
const (
ERROR_NONE: Errno = 0;
ERROR_FILE_NOT_FOUND = 2;
ERROR_PATH_NOT_FOUND = 3;
ERROR_ACCESS_DENIED = 5;
ERROR_NO_MORE_FILES = 18;
ERROR_HANDLE_EOF = 38;
ERROR_NETNAME_DELETED = 64;
ERROR_FILE_EXISTS = 80;
ERROR_BROKEN_PIPE = 109;
ERROR_BUFFER_OVERFLOW = 111;
ERROR_INSUFFICIENT_BUFFER = 122;
ERROR_MOD_NOT_FOUND = 126;
ERROR_PROC_NOT_FOUND = 127;
ERROR_DIR_NOT_EMPTY = 145;
ERROR_ALREADY_EXISTS = 183;
ERROR_ENVVAR_NOT_FOUND = 203;
ERROR_MORE_DATA = 234;
ERROR_OPERATION_ABORTED = 995;
ERROR_IO_PENDING = 997;
ERROR_NOT_FOUND = 1168;
ERROR_PRIVILEGE_NOT_HELD = 1314;
WSAEACCES = 10013;
WSAECONNRESET = 10054;
// Windows reserves errors >= 1<<29 for application use
ERROR_FILE_IS_PIPE = 1<<29 + 0;
)
// "Argv" arguments converted to Odin strings
var args = _alloc_command_line_arguments();
proc open(path: string, mode: int = O_RDONLY, perm: u32 = 0) -> (Handle, Errno) {
if len(path) == 0 {
return INVALID_HANDLE, ERROR_FILE_NOT_FOUND;
}
var access: u32;
match mode & (O_RDONLY|O_WRONLY|O_RDWR) {
case O_RDONLY: access = win32.FILE_GENERIC_READ;
case O_WRONLY: access = win32.FILE_GENERIC_WRITE;
case O_RDWR: access = win32.FILE_GENERIC_READ | win32.FILE_GENERIC_WRITE;
}
if mode&O_CREAT != 0 {
access |= win32.FILE_GENERIC_WRITE;
}
if mode&O_APPEND != 0 {
access &~= win32.FILE_GENERIC_WRITE;
access |= win32.FILE_APPEND_DATA;
}
var share_mode = u32(win32.FILE_SHARE_READ|win32.FILE_SHARE_WRITE);
var sa: ^win32.Security_Attributes = nil;
var sa_inherit = win32.Security_Attributes{length = size_of(win32.Security_Attributes), inherit_handle = 1};
if mode&O_CLOEXEC == 0 {
sa = &sa_inherit;
}
var create_mode: u32;
match {
case mode&(O_CREAT|O_EXCL) == (O_CREAT | O_EXCL):
create_mode = win32.CREATE_NEW;
case mode&(O_CREAT|O_TRUNC) == (O_CREAT | O_TRUNC):
create_mode = win32.CREATE_ALWAYS;
case mode&O_CREAT == O_CREAT:
create_mode = win32.OPEN_ALWAYS;
case mode&O_TRUNC == O_TRUNC:
create_mode = win32.TRUNCATE_EXISTING;
case:
create_mode = win32.OPEN_EXISTING;
}
var buf: [300]u8;
copy(buf[..], []u8(path));
var handle = Handle(win32.create_file_a(&buf[0], access, share_mode, sa, create_mode, win32.FILE_ATTRIBUTE_NORMAL, nil));
if handle != INVALID_HANDLE {
return handle, ERROR_NONE;
}
var err = win32.get_last_error();
return INVALID_HANDLE, Errno(err);
}
proc close(fd: Handle) {
win32.close_handle(win32.Handle(fd));
}
proc write(fd: Handle, data: []u8) -> (int, Errno) {
if len(data) == 0 {
return 0, ERROR_NONE;
}
var single_write_length: i32;
var total_write: i64;
var length = i64(len(data));
for total_write < length {
var remaining = length - total_write;
var to_read: i32;
const MAX = 1<<31-1;
if remaining <= MAX {
to_read = i32(remaining);
} else {
to_read = MAX;
}
var e = win32.write_file(win32.Handle(fd), &data[total_write], to_read, &single_write_length, nil);
if single_write_length <= 0 || e == win32.FALSE {
var err = win32.get_last_error();
return int(total_write), Errno(e);
}
total_write += i64(single_write_length);
}
return int(total_write), ERROR_NONE;
}
proc read(fd: Handle, data: []u8) -> (int, Errno) {
if len(data) == 0 {
return 0, ERROR_NONE;
}
var single_read_length: i32;
var total_read: i64;
var length = i64(len(data));
for total_read < length {
var remaining = length - total_read;
var to_read: u32;
const MAX = 1<<32-1;
if remaining <= MAX {
to_read = u32(remaining);
} else {
to_read = MAX;
}
var e = win32.read_file(win32.Handle(fd), &data[total_read], to_read, &single_read_length, nil);
if single_read_length <= 0 || e == win32.FALSE {
var err = win32.get_last_error();
return int(total_read), Errno(e);
}
total_read += i64(single_read_length);
}
return int(total_read), ERROR_NONE;
}
proc seek(fd: Handle, offset: i64, whence: int) -> (i64, Errno) {
var w: u32;
match whence {
case 0: w = win32.FILE_BEGIN;
case 1: w = win32.FILE_CURRENT;
case 2: w = win32.FILE_END;
}
var hi = i32(offset>>32);
var lo = i32(offset);
var ft = win32.get_file_type(win32.Handle(fd));
if ft == win32.FILE_TYPE_PIPE {
return 0, ERROR_FILE_IS_PIPE;
}
var dw_ptr = win32.set_file_pointer(win32.Handle(fd), lo, &hi, w);
if dw_ptr == win32.INVALID_SET_FILE_POINTER {
var err = win32.get_last_error();
return 0, Errno(err);
}
return i64(hi)<<32 + i64(dw_ptr), ERROR_NONE;
}
proc file_size(fd: Handle) -> (i64, Errno) {
var length: i64;
var err: Errno;
if win32.get_file_size_ex(win32.Handle(fd), &length) == 0 {
err = Errno(win32.get_last_error());
}
return length, err;
}
// NOTE(bill): Uses startup to initialize it
var stdin = get_std_handle(win32.STD_INPUT_HANDLE);
var stdout = get_std_handle(win32.STD_OUTPUT_HANDLE);
var stderr = get_std_handle(win32.STD_ERROR_HANDLE);
proc get_std_handle(h: int) -> Handle {
var fd = win32.get_std_handle(i32(h));
win32.set_handle_information(fd, win32.HANDLE_FLAG_INHERIT, 0);
return Handle(fd);
}
proc last_write_time(fd: Handle) -> FileTime {
var file_info: win32.ByHandleFileInformation;
win32.get_file_information_by_handle(win32.Handle(fd), &file_info);
var lo = FileTime(file_info.last_write_time.lo);
var hi = FileTime(file_info.last_write_time.hi);
return lo | hi << 32;
}
proc last_write_time_by_name(name: string) -> FileTime {
var last_write_time: win32.Filetime;
var data: win32.FileAttributeData;
var buf: [1024]u8;
assert(len(buf) > len(name));
copy(buf[..], []u8(name));
if win32.get_file_attributes_ex_a(&buf[0], win32.GetFileExInfoStandard, &data) != 0 {
last_write_time = data.last_write_time;
}
var l = FileTime(last_write_time.lo);
var h = FileTime(last_write_time.hi);
return l | h << 32;
}
proc heap_alloc(size: int) -> rawptr {
return win32.heap_alloc(win32.get_process_heap(), win32.HEAP_ZERO_MEMORY, size);
}
proc heap_resize(ptr: rawptr, new_size: int) -> rawptr {
if new_size == 0 {
heap_free(ptr);
return nil;
}
if ptr == nil {
return heap_alloc(new_size);
}
return win32.heap_realloc(win32.get_process_heap(), win32.HEAP_ZERO_MEMORY, ptr, new_size);
}
proc heap_free(ptr: rawptr) {
if ptr == nil {
return;
}
win32.heap_free(win32.get_process_heap(), 0, ptr);
}
proc exit(code: int) {
win32.exit_process(u32(code));
}
proc current_thread_id() -> int {
return int(win32.get_current_thread_id());
}
proc _alloc_command_line_arguments() -> []string {
proc alloc_ucs2_to_utf8(wstr: ^u16) -> string {
var wstr_len = 0;
for (wstr+wstr_len)^ != 0 {
wstr_len++;
}
var len = 2*wstr_len-1;
var buf = make([]u8, len+1);
var str = slice_ptr(wstr, wstr_len+1);
var i, j = 0, 0;
for str[j] != 0 {
match {
case str[j] < 0x80:
if i+1 > len {
return "";
}
buf[i] = u8(str[j]); i++;
j++;
case str[j] < 0x800:
if i+2 > len {
return "";
}
buf[i] = u8(0xc0 + (str[j]>>6)); i++;
buf[i] = u8(0x80 + (str[j]&0x3f)); i++;
j++;
case 0xd800 <= str[j] && str[j] < 0xdc00:
if i+4 > len {
return "";
}
var c = rune((str[j] - 0xd800) << 10) + rune((str[j+1]) - 0xdc00) + 0x10000;
buf[i] = u8(0xf0 + (c >> 18)); i++;
buf[i] = u8(0x80 + ((c >> 12) & 0x3f)); i++;
buf[i] = u8(0x80 + ((c >> 6) & 0x3f)); i++;
buf[i] = u8(0x80 + ((c ) & 0x3f)); i++;
j += 2;
case 0xdc00 <= str[j] && str[j] < 0xe000:
return "";
case:
if i+3 > len {
return "";
}
buf[i] = 0xe0 + u8 (str[j] >> 12); i++;
buf[i] = 0x80 + u8((str[j] >> 6) & 0x3f); i++;
buf[i] = 0x80 + u8((str[j] ) & 0x3f); i++;
j++;
}
}
return string(buf[0..<i]);
}
var arg_count: i32;
var arg_list_ptr = win32.command_line_to_argv_w(win32.get_command_line_w(), &arg_count);
var arg_list = make([]string, arg_count);
for _, i in arg_list {
arg_list[i] = alloc_ucs2_to_utf8((arg_list_ptr+i)^);
}
return arg_list;
}
-292
View File
@@ -1,292 +0,0 @@
foreign_system_library (
dl "dl";
libc "c";
)
import "strings.odin";
type (
Handle i32;
FileTime u64;
Errno int;
AddressSize int;
)
const (
O_RDONLY = 0x00000;
O_WRONLY = 0x00001;
O_RDWR = 0x00002;
O_CREAT = 0x00040;
O_EXCL = 0x00080;
O_NOCTTY = 0x00100;
O_TRUNC = 0x00200;
O_NONBLOCK = 0x00800;
O_APPEND = 0x00400;
O_SYNC = 0x01000;
O_ASYNC = 0x02000;
O_CLOEXEC = 0x80000;
)
const (
SEEK_SET = 0;
SEEK_CUR = 1;
SEEK_END = 2;
SEEK_DATA = 3;
SEEK_HOLE = 4;
SEEK_MAX = SEEK_HOLE;
)
const (
// NOTE(zangent): These are OS specific!
// Do not mix these up!
RTLD_LAZY = 0x1;
RTLD_NOW = 0x2;
RTLD_LOCAL = 0x4;
RTLD_GLOBAL = 0x8;
RTLD_NODELETE = 0x80;
RTLD_NOLOAD = 0x10;
RTLD_FIRST = 0x100;
)
var args: [dynamic]string;
type _FileTime struct #ordered {
seconds: i64,
nanoseconds: i64
}
type Stat struct #ordered {
device_id : i32, // ID of device containing file
mode : u16, // Mode of the file
nlink : u16, // Number of hard links
serial : u64, // File serial number
uid : u32, // User ID of the file's owner
gid : u32, // Group ID of the file's group
rdev : i32, // Device ID, if device
last_access : FileTime, // Time of last access
modified : FileTime, // Time of last modification
status_change : FileTime, // Time of last status change
created : FileTime, // Time of creation
size : i64, // Size of the file, in bytes
blocks : i64, // Number of blocks allocated for the file
block_size: i32, // Optimal blocksize for I/O
flags : u32, // User-defined flags for the file
gen_num : u32, // File generation number ...?
_spare : i32, // RESERVED
_reserve1,
_reserve2 : i64, // RESERVED
};
// File type
const (
S_IFMT = 0170000; // Type of file mask
S_IFIFO = 0010000; // Named pipe (fifo)
S_IFCHR = 0020000; // Character special
S_IFDIR = 0040000; // Directory
S_IFBLK = 0060000; // Block special
S_IFREG = 0100000; // Regular
S_IFLNK = 0120000; // Symbolic link
S_IFSOCK = 0140000; // Socket
// File mode
// Read, write, execute/search by owner
S_IRWXU = 0000700; // RWX mask for owner
S_IRUSR = 0000400; // R for owner
S_IWUSR = 0000200; // W for owner
S_IXUSR = 0000100; // X for owner
// Read, write, execute/search by group
S_IRWXG = 0000070; // RWX mask for group
S_IRGRP = 0000040; // R for group
S_IWGRP = 0000020; // W for group
S_IXGRP = 0000010; // X for group
// Read, write, execute/search by others
S_IRWXO = 0000007; // RWX mask for other
S_IROTH = 0000004; // R for other
S_IWOTH = 0000002; // W for other
S_IXOTH = 0000001; // X for other
S_ISUID = 0004000; // Set user id on execution
S_ISGID = 0002000; // Set group id on execution
S_ISVTX = 0001000; // Directory restrcted delete
)
proc S_ISLNK (m: u32) -> bool #inline {return (m & S_IFMT) == S_IFLNK; }
proc S_ISREG (m: u32) -> bool #inline {return (m & S_IFMT) == S_IFREG; }
proc S_ISDIR (m: u32) -> bool #inline {return (m & S_IFMT) == S_IFDIR; }
proc S_ISCHR (m: u32) -> bool #inline {return (m & S_IFMT) == S_IFCHR; }
proc S_ISBLK (m: u32) -> bool #inline {return (m & S_IFMT) == S_IFBLK; }
proc S_ISFIFO(m: u32) -> bool #inline {return (m & S_IFMT) == S_IFIFO; }
proc S_ISSOCK(m: u32) -> bool #inline {return (m & S_IFMT) == S_IFSOCK;}
const (
R_OK = 4; // Test for read permission
W_OK = 2; // Test for write permission
X_OK = 1; // Test for execute permission
F_OK = 0; // Test for file existance
)
foreign libc {
proc unix_open (path: ^u8, mode: int) -> Handle #link_name "open";
proc unix_close (handle: Handle) #link_name "close";
proc unix_read (handle: Handle, buffer: rawptr, count: int) -> AddressSize #link_name "read";
proc unix_write (handle: Handle, buffer: rawptr, count: int) -> AddressSize #link_name "write";
proc unix_lseek (fs: Handle, offset: AddressSize, whence: int) -> AddressSize #link_name "lseek";
proc unix_gettid() -> u64 #link_name "gettid";
proc unix_stat (path: ^u8, stat: ^Stat) -> int #link_name "stat";
proc unix_access(path: ^u8, mask: int) -> int #link_name "access";
proc unix_malloc (size: int) -> rawptr #link_name "malloc";
proc unix_free (ptr: rawptr) #link_name "free";
proc unix_realloc(ptr: rawptr, size: int) -> rawptr #link_name "realloc";
proc unix_getenv (^u8) -> ^u8 #link_name "getenv";
proc unix_exit(status: int) #link_name "exit";
}
foreign dl {
proc unix_dlopen (filename: ^u8, flags: int) -> rawptr #link_name "dlopen";
proc unix_dlsym (handle: rawptr, symbol: ^u8) -> (proc() #cc_c) #link_name "dlsym";
proc unix_dlclose(handle: rawptr) -> int #link_name "dlclose";
proc unix_dlerror() -> ^u8 #link_name "dlerror";
}
// TODO(zangent): Change this to just `open` when Bill fixes overloading.
proc open_simple(path: string, mode: int) -> (Handle, Errno) {
var cstr = strings.new_c_string(path);
var handle = unix_open(cstr, mode);
free(cstr);
if(handle == -1) {
return 0, 1;
}
return handle, 0;
}
// NOTE(zangent): This is here for compatability reasons. Should this be here?
proc open(path: string, mode: int = O_RDONLY, perm: u32 = 0) -> (Handle, Errno) {
return open_simple(path, mode);
}
proc close(fd: Handle) {
unix_close(fd);
}
proc write(fd: Handle, data: []u8) -> (AddressSize, Errno) {
assert(fd != -1);
var bytes_written = unix_write(fd, &data[0], len(data));
if(bytes_written == -1) {
return 0, 1;
}
return bytes_written, 0;
}
proc read(fd: Handle, data: []u8) -> (AddressSize, Errno) {
assert(fd != -1);
var bytes_read = unix_read(fd, &data[0], len(data));
if(bytes_read == -1) {
return 0, 1;
}
return bytes_read, 0;
}
proc seek(fd: Handle, offset: AddressSize, whence: int) -> (AddressSize, Errno) {
assert(fd != -1);
var final_offset = unix_lseek(fd, offset, whence);
if(final_offset == -1) {
return 0, 1;
}
return final_offset, 0;
}
proc file_size(fd: Handle) -> (i64, Errno) {
var prev, _ = seek(fd, 0, SEEK_CUR);
var size, err = seek(fd, 0, SEEK_END);
seek(fd, prev, SEEK_SET);
return size, err;
}
// NOTE(bill): Uses startup to initialize it
var (
stdin: Handle = 0; // get_std_handle(win32.STD_INPUT_HANDLE);
stdout: Handle = 1; // get_std_handle(win32.STD_OUTPUT_HANDLE);
stderr: Handle = 2; // get_std_handle(win32.STD_ERROR_HANDLE);
)
/* TODO(zangent): Implement these!
proc last_write_time(fd: Handle) -> FileTime {}
proc last_write_time_by_name(name: string) -> FileTime {}
*/
proc stat(path: string) -> (Stat, bool) #inline {
var s: Stat;
var cstr = strings.new_c_string(path);
defer free(cstr);
var ret_int = unix_stat(cstr, &s);
return s, ret_int==0;
}
proc access(path: string, mask: int) -> bool #inline {
var cstr = strings.new_c_string(path);
defer free(cstr);
return unix_access(cstr, mask) == 0;
}
proc heap_alloc(size: int) -> rawptr #inline {
assert(size > 0);
return unix_malloc(size);
}
proc heap_resize(ptr: rawptr, new_size: int) -> rawptr #inline {
return unix_realloc(ptr, new_size);
}
proc heap_free(ptr: rawptr) #inline {
unix_free(ptr);
}
proc getenv(name: string) -> (string, bool) {
var path_str = strings.new_c_string(name);
var cstr: ^u8 = unix_getenv(path_str);
free(path_str);
if(cstr == nil) {
return "", false;
}
return strings.to_odin_string(cstr), true;
}
proc exit(code: int) #inline {
unix_exit(code);
}
proc current_thread_id() -> int {
// return cast(int) unix_gettid();
return 0;
}
proc dlopen(filename: string, flags: int) -> rawptr #inline {
var cstr = strings.new_c_string(filename);
var handle = unix_dlopen(cstr, flags);
free(cstr);
return handle;
}
proc dlsym(handle: rawptr, symbol: string) -> (proc() #cc_c) #inline {
assert(handle != nil);
var cstr = strings.new_c_string(symbol);
var proc_handle = unix_dlsym(handle, cstr);
free(cstr);
return proc_handle;
}
proc dlclose(handle: rawptr) -> bool #inline {
assert(handle != nil);
return unix_dlclose(handle) == 0;
}
proc dlerror() -> string {
return strings.to_odin_string(unix_dlerror());
}
-29
View File
@@ -1,29 +0,0 @@
type (
Any struct #ordered {
data: rawptr,
type_info: ^TypeInfo,
};
String struct #ordered {
data: ^u8,
len: int,
};
Slice struct #ordered {
data: rawptr,
len: int,
cap: int,
};
DynamicArray struct #ordered {
data: rawptr,
len: int,
cap: int,
allocator: Allocator,
};
DynamicMap struct #ordered {
hashes: [dynamic]int,
entries: DynamicArray,
};
)
File diff suppressed because it is too large Load Diff
+470
View File
@@ -0,0 +1,470 @@
package runtime
import "core:mem"
import "core:os"
import "core:unicode/utf8"
print_u64 :: proc(fd: os.Handle, u: u64) {
digits := "0123456789";
a: [129]byte;
i := len(a);
b := u64(10);
for u >= b {
i -= 1; a[i] = digits[u % b];
u /= b;
}
i -= 1; a[i] = digits[u % b];
os.write(fd, a[i:]);
}
print_i64 :: proc(fd: os.Handle, u: i64) {
digits := "0123456789";
b :: i64(10);
neg := u < 0;
u = abs(u);
a: [129]byte;
i := len(a);
for u >= b {
i -= 1; a[i] = digits[u % b];
u /= b;
}
i -= 1; a[i] = digits[u % b];
if neg {
i -= 1; a[i] = '-';
}
os.write(fd, a[i:]);
}
print_caller_location :: proc(fd: os.Handle, using loc: Source_Code_Location) {
os.write_string(fd, file_path);
os.write_byte(fd, '(');
print_u64(fd, u64(line));
os.write_byte(fd, ':');
print_u64(fd, u64(column));
os.write_byte(fd, ')');
}
print_typeid :: proc(fd: os.Handle, id: typeid) {
ti := type_info_of(id);
print_type(fd, ti);
}
print_type :: proc(fd: os.Handle, ti: ^Type_Info) {
if ti == nil {
os.write_string(fd, "nil");
return;
}
switch info in ti.variant {
case Type_Info_Named:
os.write_string(fd, info.name);
case Type_Info_Integer:
switch ti.id {
case int: os.write_string(fd, "int");
case uint: os.write_string(fd, "uint");
case uintptr: os.write_string(fd, "uintptr");
case:
os.write_byte(fd, info.signed ? 'i' : 'u');
print_u64(fd, u64(8*ti.size));
}
case Type_Info_Rune:
os.write_string(fd, "rune");
case Type_Info_Float:
os.write_byte(fd, 'f');
print_u64(fd, u64(8*ti.size));
case Type_Info_Complex:
os.write_string(fd, "complex");
print_u64(fd, u64(8*ti.size));
case Type_Info_String:
os.write_string(fd, "string");
case Type_Info_Boolean:
switch ti.id {
case bool: os.write_string(fd, "bool");
case:
os.write_byte(fd, 'b');
print_u64(fd, u64(8*ti.size));
}
case Type_Info_Any:
os.write_string(fd, "any");
case Type_Info_Type_Id:
os.write_string(fd, "typeid");
case Type_Info_Pointer:
if info.elem == nil {
os.write_string(fd, "rawptr");
} else {
os.write_string(fd, "^");
print_type(fd, info.elem);
}
case Type_Info_Procedure:
os.write_string(fd, "proc");
if info.params == nil {
os.write_string(fd, "()");
} else {
t := info.params.variant.(Type_Info_Tuple);
os.write_string(fd, "(");
for t, i in t.types {
if i > 0 do os.write_string(fd, ", ");
print_type(fd, t);
}
os.write_string(fd, ")");
}
if info.results != nil {
os.write_string(fd, " -> ");
print_type(fd, info.results);
}
case Type_Info_Tuple:
count := len(info.names);
if count != 1 do os.write_string(fd, "(");
for name, i in info.names {
if i > 0 do os.write_string(fd, ", ");
t := info.types[i];
if len(name) > 0 {
os.write_string(fd, name);
os.write_string(fd, ": ");
}
print_type(fd, t);
}
if count != 1 do os.write_string(fd, ")");
case Type_Info_Array:
os.write_string(fd, "[");
print_u64(fd, u64(info.count));
os.write_string(fd, "]");
print_type(fd, info.elem);
case Type_Info_Dynamic_Array:
os.write_string(fd, "[dynamic]");
print_type(fd, info.elem);
case Type_Info_Slice:
os.write_string(fd, "[]");
print_type(fd, info.elem);
case Type_Info_Map:
os.write_string(fd, "map[");
print_type(fd, info.key);
os.write_byte(fd, ']');
print_type(fd, info.value);
case Type_Info_Struct:
os.write_string(fd, "struct ");
if info.is_packed do os.write_string(fd, "#packed ");
if info.is_raw_union do os.write_string(fd, "#raw_union ");
if info.custom_align {
os.write_string(fd, "#align ");
print_u64(fd, u64(ti.align));
os.write_byte(fd, ' ');
}
os.write_byte(fd, '{');
for name, i in info.names {
if i > 0 do os.write_string(fd, ", ");
os.write_string(fd, name);
os.write_string(fd, ": ");
print_type(fd, info.types[i]);
}
os.write_byte(fd, '}');
case Type_Info_Union:
os.write_string(fd, "union {");
for variant, i in info.variants {
if i > 0 do os.write_string(fd, ", ");
print_type(fd, variant);
}
os.write_string(fd, "}");
case Type_Info_Enum:
os.write_string(fd, "enum ");
print_type(fd, info.base);
os.write_string(fd, " {");
for name, i in info.names {
if i > 0 do os.write_string(fd, ", ");
os.write_string(fd, name);
}
os.write_string(fd, "}");
case Type_Info_Bit_Field:
os.write_string(fd, "bit_field ");
if ti.align != 1 {
os.write_string(fd, "#align ");
print_u64(fd, u64(ti.align));
os.write_byte(fd, ' ');
}
os.write_string(fd, " {");
for name, i in info.names {
if i > 0 do os.write_string(fd, ", ");
os.write_string(fd, name);
os.write_string(fd, ": ");
print_u64(fd, u64(info.bits[i]));
}
os.write_string(fd, "}");
case Type_Info_Bit_Set:
os.write_string(fd, "bit_set[");
switch elem in type_info_base(info.elem).variant {
case Type_Info_Enum:
print_type(fd, info.elem);
case Type_Info_Rune:
os.write_encoded_rune(fd, rune(info.lower));
os.write_string(fd, "..");
os.write_encoded_rune(fd, rune(info.upper));
case:
print_i64(fd, info.lower);
os.write_string(fd, "..");
print_i64(fd, info.upper);
}
if info.underlying != nil {
os.write_string(fd, "; ");
print_type(fd, info.underlying);
}
os.write_byte(fd, ']');
}
}
string_eq :: proc "contextless" (a, b: string) -> bool {
switch {
case len(a) != len(b): return false;
case len(a) == 0: return true;
case &a[0] == &b[0]: return true;
}
return string_cmp(a, b) == 0;
}
string_cmp :: proc "contextless" (a, b: string) -> int {
return mem.compare_byte_ptrs(&a[0], &b[0], min(len(a), len(b)));
}
string_ne :: inline proc "contextless" (a, b: string) -> bool { return !string_eq(a, b); }
string_lt :: inline proc "contextless" (a, b: string) -> bool { return string_cmp(a, b) < 0; }
string_gt :: inline proc "contextless" (a, b: string) -> bool { return string_cmp(a, b) > 0; }
string_le :: inline proc "contextless" (a, b: string) -> bool { return string_cmp(a, b) <= 0; }
string_ge :: inline proc "contextless" (a, b: string) -> bool { return string_cmp(a, b) >= 0; }
cstring_len :: proc "contextless" (s: cstring) -> int {
n := 0;
for p := (^byte)(s); p != nil && p^ != 0; p = mem.ptr_offset(p, 1) {
n += 1;
}
return n;
}
cstring_to_string :: proc "contextless" (s: cstring) -> string {
if s == nil do return "";
ptr := (^byte)(s);
n := cstring_len(s);
return transmute(string)mem.Raw_String{ptr, n};
}
complex64_eq :: inline proc "contextless" (a, b: complex64) -> bool { return real(a) == real(b) && imag(a) == imag(b); }
complex64_ne :: inline proc "contextless" (a, b: complex64) -> bool { return real(a) != real(b) || imag(a) != imag(b); }
complex128_eq :: inline proc "contextless" (a, b: complex128) -> bool { return real(a) == real(b) && imag(a) == imag(b); }
complex128_ne :: inline proc "contextless" (a, b: complex128) -> bool { return real(a) != real(b) || imag(a) != imag(b); }
bounds_check_error :: proc "contextless" (file: string, line, column: int, index, count: int) {
if 0 <= index && index < count do return;
fd := os.stderr;
print_caller_location(fd, Source_Code_Location{file, line, column, ""});
os.write_string(fd, " Index ");
print_i64(fd, i64(index));
os.write_string(fd, " is out of bounds range 0:");
print_i64(fd, i64(count));
os.write_byte(fd, '\n');
debug_trap();
}
slice_expr_error :: proc "contextless" (file: string, line, column: int, lo, hi: int, len: int) {
if 0 <= lo && lo <= hi && hi <= len do return;
fd := os.stderr;
print_caller_location(fd, Source_Code_Location{file, line, column, ""});
os.write_string(fd, " Invalid slice indices: ");
print_i64(fd, i64(lo));
os.write_string(fd, ":");
print_i64(fd, i64(hi));
os.write_string(fd, ":");
print_i64(fd, i64(len));
os.write_byte(fd, '\n');
debug_trap();
}
dynamic_array_expr_error :: proc "contextless" (file: string, line, column: int, low, high, max: int) {
if 0 <= low && low <= high && high <= max do return;
fd := os.stderr;
print_caller_location(fd, Source_Code_Location{file, line, column, ""});
os.write_string(fd, " Invalid dynamic array values: ");
print_i64(fd, i64(low));
os.write_string(fd, ":");
print_i64(fd, i64(high));
os.write_string(fd, ":");
print_i64(fd, i64(max));
os.write_byte(fd, '\n');
debug_trap();
}
type_assertion_check :: proc "contextless" (ok: bool, file: string, line, column: int, from, to: typeid) {
if ok do return;
fd := os.stderr;
print_caller_location(fd, Source_Code_Location{file, line, column, ""});
os.write_string(fd, " Invalid type assertion from ");
print_typeid(fd, from);
os.write_string(fd, " to ");
print_typeid(fd, to);
os.write_byte(fd, '\n');
debug_trap();
}
string_decode_rune :: inline proc "contextless" (s: string) -> (rune, int) {
return utf8.decode_rune_from_string(s);
}
bounds_check_error_loc :: inline proc "contextless" (using loc := #caller_location, index, count: int) {
bounds_check_error(file_path, int(line), int(column), index, count);
}
slice_expr_error_loc :: inline proc "contextless" (using loc := #caller_location, lo, hi: int, len: int) {
slice_expr_error(file_path, int(line), int(column), lo, hi, len);
}
dynamic_array_expr_error_loc :: inline proc "contextless" (using loc := #caller_location, low, high, max: int) {
dynamic_array_expr_error(file_path, int(line), int(column), low, high, max);
}
make_slice_error_loc :: inline proc "contextless" (using loc := #caller_location, len: int) {
if 0 <= len do return;
fd := os.stderr;
print_caller_location(fd, loc);
os.write_string(fd, " Invalid slice length for make: ");
print_i64(fd, i64(len));
os.write_byte(fd, '\n');
debug_trap();
}
make_dynamic_array_error_loc :: inline proc "contextless" (using loc := #caller_location, len, cap: int) {
if 0 <= len && len <= cap do return;
fd := os.stderr;
print_caller_location(fd, loc);
os.write_string(fd, " Invalid dynamic array parameters for make: ");
print_i64(fd, i64(len));
os.write_byte(fd, ':');
print_i64(fd, i64(cap));
os.write_byte(fd, '\n');
debug_trap();
}
make_map_expr_error_loc :: inline proc "contextless" (using loc := #caller_location, cap: int) {
if 0 <= cap do return;
fd := os.stderr;
print_caller_location(fd, loc);
os.write_string(fd, " Invalid map capacity for make: ");
print_i64(fd, i64(cap));
os.write_byte(fd, '\n');
debug_trap();
}
@(default_calling_convention = "c")
foreign {
@(link_name="llvm.sqrt.f32") _sqrt_f32 :: proc(x: f32) -> f32 ---
@(link_name="llvm.sqrt.f64") _sqrt_f64 :: proc(x: f64) -> f64 ---
}
abs_f32 :: inline proc "contextless" (x: f32) -> f32 {
foreign {
@(link_name="llvm.fabs.f32") _abs :: proc "c" (x: f32) -> f32 ---
}
return _abs(x);
}
abs_f64 :: inline proc "contextless" (x: f64) -> f64 {
foreign {
@(link_name="llvm.fabs.f64") _abs :: proc "c" (x: f64) -> f64 ---
}
return _abs(x);
}
min_f32 :: proc(a, b: f32) -> f32 {
foreign {
@(link_name="llvm.minnum.f32") _min :: proc "c" (a, b: f32) -> f32 ---
}
return _min(a, b);
}
min_f64 :: proc(a, b: f64) -> f64 {
foreign {
@(link_name="llvm.minnum.f64") _min :: proc "c" (a, b: f64) -> f64 ---
}
return _min(a, b);
}
max_f32 :: proc(a, b: f32) -> f32 {
foreign {
@(link_name="llvm.maxnum.f32") _max :: proc "c" (a, b: f32) -> f32 ---
}
return _max(a, b);
}
max_f64 :: proc(a, b: f64) -> f64 {
foreign {
@(link_name="llvm.maxnum.f64") _max :: proc "c" (a, b: f64) -> f64 ---
}
return _max(a, b);
}
abs_complex64 :: inline proc "contextless" (x: complex64) -> f32 {
r, i := real(x), imag(x);
return _sqrt_f32(r*r + i*i);
}
abs_complex128 :: inline proc "contextless" (x: complex128) -> f64 {
r, i := real(x), imag(x);
return _sqrt_f64(r*r + i*i);
}
quo_complex64 :: proc(n, m: complex64) -> complex64 {
e, f: f32;
if abs(real(m)) >= abs(imag(m)) {
ratio := imag(m) / real(m);
denom := real(m) + ratio*imag(m);
e = (real(n) + imag(n)*ratio) / denom;
f = (imag(n) - real(n)*ratio) / denom;
} else {
ratio := real(m) / imag(m);
denom := imag(m) + ratio*real(m);
e = (real(n)*ratio + imag(n)) / denom;
f = (imag(n)*ratio - real(n)) / denom;
}
return complex(e, f);
}
quo_complex128 :: proc(n, m: complex128) -> complex128 {
e, f: f64;
if abs(real(m)) >= abs(imag(m)) {
ratio := imag(m) / real(m);
denom := real(m) + ratio*imag(m);
e = (real(n) + imag(n)*ratio) / denom;
f = (imag(n) - real(n)*ratio) / denom;
} else {
ratio := real(m) / imag(m);
denom := imag(m) + ratio*real(m);
e = (real(n)*ratio + imag(n)) / denom;
f = (imag(n)*ratio - real(n)) / denom;
}
return complex(e, f);
}
+50
View File
@@ -0,0 +1,50 @@
package runtime
foreign import kernel32 "system:Kernel32.lib"
@(link_name="memcpy")
memcpy :: proc "c" (dst, src: rawptr, len: int) -> rawptr {
foreign kernel32 {
RtlCopyMemory :: proc "c" (dst, src: rawptr, len: int) ---
}
RtlCopyMemory(dst, src, len);
return dst;
}
@(link_name="memmove")
memmove :: proc "c" (dst, src: rawptr, len: int) -> rawptr {
foreign kernel32 {
RtlMoveMemory :: proc "c" (dst, src: rawptr, len: int) ---
}
RtlMoveMemory(dst, src, len);
return dst;
}
@(link_name="memset")
memset :: proc "c" (ptr: rawptr, val: i32, len: int) -> rawptr {
foreign kernel32 {
RtlFillMemory :: proc "c" (dst: rawptr, len: int, fill: byte) ---
}
RtlFillMemory(ptr, len, byte(val));
return ptr;
}
// @(link_name="memcmp")
// memcmp :: proc "c" (dst, src: rawptr, len: int) -> i32 {
// if dst == nil || src == nil {
// return 0;
// }
// if dst == src {
// return 0;
// }
// d, s := uintptr(dst), uintptr(src);
// n := uintptr(len);
// for i := uintptr(0); i < n; i += 1 {
// x, y := (^byte)(d+i)^, (^byte)(s+i)^;
// if x != y {
// return x < y ? -1 : +1;
// }
// }
// return 0;
// }
+217
View File
@@ -0,0 +1,217 @@
package sort
import "core:mem"
bubble_sort_proc :: proc(array: $A/[]$T, f: proc(T, T) -> int) {
assert(f != nil);
count := len(array);
init_j, last_j := 0, count-1;
for {
init_swap, prev_swap := -1, -1;
for j in init_j..last_j-1 {
if f(array[j], array[j+1]) > 0 {
array[j], array[j+1] = array[j+1], array[j];
prev_swap = j;
if init_swap == -1 do init_swap = j;
}
}
if prev_swap == -1 do return;
init_j = max(init_swap-1, 0);
last_j = prev_swap;
}
}
bubble_sort :: proc(array: $A/[]$T) {
count := len(array);
init_j, last_j := 0, count-1;
for {
init_swap, prev_swap := -1, -1;
for j in init_j..last_j-1 {
if array[j] > array[j+1] {
array[j], array[j+1] = array[j+1], array[j];
prev_swap = j;
if init_swap == -1 do init_swap = j;
}
}
if prev_swap == -1 do return;
init_j = max(init_swap-1, 0);
last_j = prev_swap;
}
}
quick_sort_proc :: proc(array: $A/[]$T, f: proc(T, T) -> int) {
assert(f != nil);
a := array;
n := len(a);
if n < 2 do return;
p := a[n/2];
i, j := 0, n-1;
loop: for {
for f(a[i], p) < 0 do i += 1;
for f(p, a[j]) < 0 do j -= 1;
if i >= j do break loop;
a[i], a[j] = a[j], a[i];
i += 1;
j -= 1;
}
quick_sort_proc(a[0:i], f);
quick_sort_proc(a[i:n], f);
}
quick_sort :: proc(array: $A/[]$T) {
a := array;
n := len(a);
if n < 2 do return;
p := a[n/2];
i, j := 0, n-1;
loop: for {
for a[i] < p do i += 1;
for p < a[j] do j -= 1;
if i >= j do break loop;
a[i], a[j] = a[j], a[i];
i += 1;
j -= 1;
}
quick_sort(a[0:i]);
quick_sort(a[i:n]);
}
_log2 :: proc(n: int) -> int {
res := 0;
for ; n != 0; n >>= 1 do res += 1;
return res;
}
merge_sort_proc :: proc(array: $A/[]$T, f: proc(T, T) -> int) {
merge_slices :: proc(arr1, arr2, out: A, f: proc(T, T) -> int) {
N1, N2 := len(arr1), len(arr2);
i, j := 0, 0;
for k in 0..N1+N2-1 {
if j == N2 || i < N1 && j < N2 && f(arr1[i], arr2[j]) < 0 {
out[k] = arr1[i];
i += 1;
} else {
out[k] = arr2[j];
j += 1;
}
}
}
assert(f != nil);
arr1 := array;
N := len(arr1);
arr2 := make([]T, N);
defer free(arr2);
a, b, m, M := N/2, N, 1, _log2(N);
for i in 0..M {
for j in 0..a-1 {
k := 2*j*m;
merge_slices(arr1[k:k+m], arr1[k+m:k+m+m], arr2[k:], f);
}
if N-b > m {
k := 2*a*m;
merge_slices(arr1[k:k+m], arr1[k+m : k+m+(N-b)&(m-1)], arr2[k:], f);
} else {
copy(arr2[b:N], arr1[b:N]);
}
arr1, arr2 = arr2, arr1;
m <<= 1;
a >>= 1;
b = a << uint(i) << 2;
}
if M & 1 == 0 do copy(arr2, arr1);
}
merge_sort :: proc(array: $A/[]$T) {
merge_slices :: proc(arr1, arr2, out: A) {
N1, N2 := len(arr1), len(arr2);
i, j := 0, 0;
for k in 0..N1+N2-1 {
if j == N2 || i < N1 && j < N2 && arr1[i] < arr2[j] {
out[k] = arr1[i];
i += 1;
} else {
out[k] = arr2[j];
j += 1;
}
}
}
arr1 := array;
N := len(arr1);
arr2 := make([]T, N);
defer free(arr2);
a, b, m, M := N/2, N, 1, _log2(N);
for i in 0..M {
for j in 0..a-1 {
k := 2*j*m;
merge_slices(arr1[k:k+m], arr1[k+m:k+m+m], arr2[k:]);
}
if N-b > m {
k := 2*a*m;
merge_slices(arr1[k:k+m], arr1[k+m : k+m+(N-b)&(m-1)], arr2[k:]);
} else {
copy(arr2[b:N], arr1[b:N]);
}
arr1, arr2 = arr2, arr1;
m <<= 1;
a >>= 1;
b = a << uint(i) << 2;
}
if M & 1 == 0 do copy(arr2, arr1);
}
compare_ints :: proc(a, b: int) -> int {
switch delta := a - b; {
case delta < 0: return -1;
case delta > 0: return +1;
}
return 0;
}
compare_f32s :: proc(a, b: f32) -> int {
switch delta := a - b; {
case delta < 0: return -1;
case delta > 0: return +1;
}
return 0;
}
compare_f64s :: proc(a, b: f64) -> int {
switch delta := a - b; {
case delta < 0: return -1;
case delta > 0: return +1;
}
return 0;
}
compare_strings :: proc(a, b: string) -> int {
return mem.compare_byte_ptrs(&a[0], &b[0], min(len(a), len(b)));
}
-500
View File
@@ -1,500 +0,0 @@
import . "decimal.odin";
type IntFlag enum {
Prefix = 1<<0,
Plus = 1<<1,
Space = 1<<2,
}
proc parse_bool(s: string) -> (result: bool, ok: bool) {
match s {
case "1", "t", "T", "true", "TRUE", "True":
return true, true;
case "0", "f", "F", "false", "FALSE", "False":
return false, true;
}
return false, false;
}
proc _digit_value(r: rune) -> int {
var ri = int(r);
var v: int = 16;
match r {
case '0'..'9': v = ri-'0';
case 'a'..'z': v = ri-'a'+10;
case 'A'..'Z': v = ri-'A'+10;
}
return v;
}
proc parse_i128(s: string) -> i128 {
var neg = false;
if len(s) > 1 {
match s[0] {
case '-':
neg = true;
s = s[1..];
case '+':
s = s[1..];
}
}
var base: i128 = 10;
if len(s) > 2 && s[0] == '0' {
match s[1] {
case 'b': base = 2; s = s[2..];
case 'o': base = 8; s = s[2..];
case 'd': base = 10; s = s[2..];
case 'z': base = 12; s = s[2..];
case 'x': base = 16; s = s[2..];
}
}
var value: i128;
for r in s {
if r == '_' {
continue;
}
var v = i128(_digit_value(r));
if v >= base {
break;
}
value *= base;
value += v;
}
return neg ? -value : value;
}
proc parse_u128(s: string) -> u128 {
var neg = false;
if len(s) > 1 && s[0] == '+' {
s = s[1..];
}
var base = u128(10);
if len(s) > 2 && s[0] == '0' {
match s[1] {
case 'b': base = 2; s = s[2..];
case 'o': base = 8; s = s[2..];
case 'd': base = 10; s = s[2..];
case 'z': base = 12; s = s[2..];
case 'x': base = 16; s = s[2..];
}
}
var value: u128;
for r in s {
if r == '_' {
continue;
}
var v = u128(_digit_value(r));
if v >= base {
break;
}
value *= base;
value += u128(v);
}
return neg ? -value : value;
}
proc parse_int(s: string) -> int {
return int(parse_i128(s));
}
proc parse_uint(s: string, base: int) -> uint {
return uint(parse_u128(s));
}
proc parse_f64(s: string) -> f64 {
var i = 0;
var sign: f64 = 1;
match s[i] {
case '-': i++; sign = -1;
case '+': i++;
}
var value: f64 = 0;
for ; i < len(s); i++ {
var r = rune(s[i]);
if r == '_' {
continue;
}
var v = _digit_value(r);
if v >= 10 {
break;
}
value *= 10;
value += f64(v);
}
if s[i] == '.' {
var pow10: f64 = 10;
i++;
for ; i < len(s); i++ {
var r = rune(s[i]);
if r == '_' {
continue;
}
var v = _digit_value(r);
if v >= 10 {
break;
}
value += f64(v)/pow10;
pow10 *= 10;
}
}
var frac = false;
var scale: f64 = 1;
if s[i] == 'e' || s[i] == 'E' {
i++;
match s[i] {
case '-': i++; frac = true;
case '+': i++;
}
var exp: u32 = 0;
for ; i < len(s); i++ {
var r = rune(s[i]);
if r == '_' {
continue;
}
var d = u32(_digit_value(r));
if d >= 10 {
break;
}
exp = exp * 10 + d;
}
if exp > 308 { exp = 308; }
for exp >= 50 { scale *= 1e50; exp -= 50; }
for exp >= 8 { scale *= 1e8; exp -= 8; }
for exp > 0 { scale *= 10; exp -= 1; }
}
return sign * (frac ? (value/scale) : (value*scale));
}
proc append_bool(buf: []u8, b: bool) -> string {
var s = b ? "true" : "false";
append(buf, ..[]u8(s));
return string(buf);
}
proc append_uint(buf: []u8, u: u64, base: int) -> string {
return append_bits(buf, u128(u), base, false, 8*size_of(uint), digits, 0);
}
proc append_int(buf: []u8, i: i64, base: int) -> string {
return append_bits(buf, u128(i), base, true, 8*size_of(int), digits, 0);
}
proc itoa(buf: []u8, i: int) -> string { return append_int(buf, i64(i), 10); }
proc append_float(buf: []u8, f: f64, fmt: u8, prec, bit_size: int) -> string {
return string(generic_ftoa(buf, f, fmt, prec, bit_size));
}
type DecimalSlice struct {
digits: []u8,
count: int,
decimal_point: int,
neg: bool,
}
type Float_Info struct {
mantbits: uint,
expbits: uint,
bias: int,
}
var (
_f16_info = Float_Info{10, 5, -15};
_f32_info = Float_Info{23, 8, -127};
_f64_info = Float_Info{52, 11, -1023};
)
proc generic_ftoa(buf: []u8, val: f64, fmt: u8, prec, bit_size: int) -> []u8 {
var bits: u64;
var flt: ^Float_Info;
match bit_size {
case 32:
bits = u64(transmute(u32, f32(val)));
flt = &_f32_info;
case 64:
bits = transmute(u64, val);
flt = &_f64_info;
case:
panic("strconv: invalid bit_size");
}
var neg = bits>>(flt.expbits+flt.mantbits) != 0;
var exp = int(bits>>flt.mantbits) & (1<<flt.expbits - 1);
var mant = bits & (u64(1) << flt.mantbits - 1);
match exp {
case 1<<flt.expbits - 1:
var s: string;
if mant != 0 {
s = "NaN";
} else if neg {
s = "-Inf";
} else {
s = "+Inf";
}
append(buf, ..[]u8(s));
return buf;
case 0: // denormalized
exp++;
case:
mant |= u64(1) << flt.mantbits;
}
exp += flt.bias;
var d_: Decimal;
var d = &d_;
assign(d, mant);
shift(d, exp - int(flt.mantbits));
var digs: DecimalSlice;
var shortest = prec < 0;
if shortest {
round_shortest(d, mant, exp, flt);
digs = DecimalSlice{digits = d.digits[..], count = d.count, decimal_point = d.decimal_point};
match fmt {
case 'e', 'E': prec = digs.count-1;
case 'f', 'F': prec = max(digs.count-digs.decimal_point, 0);
case 'g', 'G': prec = digs.count;
}
} else {
match fmt {
case 'e', 'E': round(d, prec+1);
case 'f', 'F': round(d, d.decimal_point+prec);
case 'g', 'G':
if prec == 0 {
prec = 1;
}
round(d, prec);
}
digs = DecimalSlice{digits = d.digits[..], count = d.count, decimal_point = d.decimal_point};
}
return format_digits(buf, shortest, neg, digs, prec, fmt);
}
proc format_digits(buf: []u8, shortest: bool, neg: bool, digs: DecimalSlice, prec: int, fmt: u8) -> []u8 {
match fmt {
case 'f', 'F':
append(buf, neg ? '-' : '+');
// integer, padded with zeros when needed
if digs.decimal_point > 0 {
var m = min(digs.count, digs.decimal_point);
append(buf, ..digs.digits[0..<m]);
for ; m < digs.decimal_point; m++ {
append(buf, '0');
}
} else {
append(buf, '0');
}
// fractional part
if prec > 0 {
append(buf, '.');
for i in 0..<prec {
var c: u8 = '0';
if var j = digs.decimal_point + i; 0 <= j && j < digs.count {
c = digs.digits[j];
}
append(buf, c);
}
}
return buf;
case 'e', 'E':
panic("strconv: e/E float printing is not yet supported");
return buf; // TODO
case 'g', 'G':
panic("strconv: g/G float printing is not yet supported");
return buf; // TODO
}
var c: [2]u8;
c[0] = '%';
c[1] = fmt;
append(buf, ..c[..]);
return buf;
}
proc round_shortest(d: ^Decimal, mant: u64, exp: int, flt: ^Float_Info) {
if mant == 0 { // If mantissa is zero, the number is zero
d.count = 0;
return;
}
/*
10^(dp-nd) > 2^(exp-mantbits)
log2(10) * (dp-nd) > exp-mantbits
log(2) >~ 0.332
332*(dp-nd) >= 100*(exp-mantbits)
*/
var minexp = flt.bias+1;
if exp > minexp && 332*(d.decimal_point-d.count) >= 100*(exp - int(flt.mantbits)) {
// Number is already its shortest
return;
}
var upper_: Decimal; var upper = &upper_;
assign(upper, 2*mant - 1);
shift(upper, exp - int(flt.mantbits) - 1);
var mantlo: u64;
var explo: int;
if mant > 1<<flt.mantbits || exp == minexp {
mantlo = mant-1;
explo = exp;
} else {
mantlo = 2*mant - 1;
explo = exp-1;
}
var lower_: Decimal; var lower = &lower_;
assign(lower, 2*mantlo + 1);
shift(lower, explo - int(flt.mantbits) - 1);
var inclusive = mant%2 == 0;
for i in 0..<d.count {
var l: u8 = '0'; // lower digit
if i < lower.count {
l = lower.digits[i];
}
var m = d.digits[i]; // middle digit
var u: u8 = '0'; // upper digit
if i < upper.count {
u = upper.digits[i];
}
var ok_round_down = l != m || inclusive && i+1 == lower.count;
var ok_round_up = m != u && (inclusive || m+1 < u || i+1 < upper.count);
if (ok_round_down && ok_round_up) {
round(d, i+1);
return;
}
if (ok_round_down) {
round_down(d, i+1);
return;
}
if (ok_round_up) {
round_up(d, i+1);
return;
}
}
}
const MAX_BASE = 32;
var digits = "0123456789abcdefghijklmnopqrstuvwxyz";
proc is_integer_negative(u: u128, is_signed: bool, bit_size: int) -> (unsigned: u128, neg: bool) {
var neg = false;
if is_signed {
match bit_size {
case 8:
var i = i8(u);
neg = i < 0;
if neg { i = -i; }
u = u128(i);
case 16:
var i = i16(u);
neg = i < 0;
if neg { i = -i; }
u = u128(i);
case 32:
var i = i32(u);
neg = i < 0;
if neg { i = -i; }
u = u128(i);
case 64:
var i = i64(u);
neg = i < 0;
if neg { i = -i; }
u = u128(i);
case 128:
var i = i128(u);
neg = i < 0;
if neg { i = -i; }
u = u128(i);
case:
panic("is_integer_negative: Unknown integer size");
}
}
return u, neg;
}
proc append_bits(buf: []u8, u: u128, base: int, is_signed: bool, bit_size: int, digits: string, flags: IntFlag) -> string {
if base < 2 || base > MAX_BASE {
panic("strconv: illegal base passed to append_bits");
}
var neg: bool;
var a: [129]u8;
var i = len(a);
u, neg = is_integer_negative(u, is_signed, bit_size);
var b = u128(base);
for u >= b {
i--; a[i] = digits[uint(u % b)];
u /= b;
}
i--; a[i] = digits[uint(u % b)];
if flags&IntFlag.Prefix != 0 {
var ok = true;
match base {
case 2: i--; a[i] = 'b';
case 8: i--; a[i] = 'o';
case 10: i--; a[i] = 'd';
case 12: i--; a[i] = 'z';
case 16: i--; a[i] = 'x';
case: ok = false;
}
if ok {
i--; a[i] = '0';
}
}
if neg {
i--; a[i] = '-';
} else if flags&IntFlag.Plus != 0 {
i--; a[i] = '+';
} else if flags&IntFlag.Space != 0 {
i--; a[i] = ' ';
}
append(buf, ..a[i..]);
return string(buf);
}
+506
View File
@@ -0,0 +1,506 @@
package strconv
using import "core:decimal"
Int_Flag :: enum {
Prefix,
Plus,
Space,
}
Int_Flags :: bit_set[Int_Flag];
parse_bool :: proc(s: string) -> (result: bool = false, ok: bool) {
switch s {
case "1", "t", "T", "true", "TRUE", "True":
return true, true;
case "0", "f", "F", "false", "FALSE", "False":
return false, true;
}
return;
}
_digit_value :: proc(r: rune) -> int {
ri := int(r);
v: int = 16;
switch r {
case '0'..'9': v = ri-'0';
case 'a'..'z': v = ri-'a'+10;
case 'A'..'Z': v = ri-'A'+10;
}
return v;
}
parse_i64 :: proc(s: string) -> i64 {
neg := false;
if len(s) > 1 {
switch s[0] {
case '-':
neg = true;
s = s[1:];
case '+':
s = s[1:];
}
}
base: i64 = 10;
if len(s) > 2 && s[0] == '0' {
switch s[1] {
case 'b': base = 2; s = s[2:];
case 'o': base = 8; s = s[2:];
case 'd': base = 10; s = s[2:];
case 'z': base = 12; s = s[2:];
case 'x': base = 16; s = s[2:];
}
}
value: i64;
for r in s {
if r == '_' {
continue;
}
v := i64(_digit_value(r));
if v >= base {
break;
}
value *= base;
value += v;
}
if neg do return -value;
return value;
}
parse_u64 :: proc(s: string) -> u64 {
neg := false;
if len(s) > 1 && s[0] == '+' {
s = s[1:];
}
base := u64(10);
if len(s) > 2 && s[0] == '0' {
switch s[1] {
case 'b': base = 2; s = s[2:];
case 'o': base = 8; s = s[2:];
case 'd': base = 10; s = s[2:];
case 'z': base = 12; s = s[2:];
case 'x': base = 16; s = s[2:];
}
}
value: u64;
for r in s {
if r == '_' do continue;
v := u64(_digit_value(r));
if v >= base do break;
value *= base;
value += u64(v);
}
if neg do return -value;
return value;
}
parse_int :: proc(s: string) -> int {
return int(parse_i64(s));
}
parse_uint :: proc(s: string, base: int) -> uint {
return uint(parse_u64(s));
}
parse_f32 :: proc(s: string) -> f32 {
return f32(parse_f64(s));
}
parse_f64 :: proc(s: string) -> f64 {
if s == "" {
return 0;
}
i := 0;
sign: f64 = 1;
switch s[i] {
case '-': i += 1; sign = -1;
case '+': i += 1;
}
value: f64 = 0;
for ; i < len(s); i += 1 {
r := rune(s[i]);
if r == '_' do continue;
v := _digit_value(r);
if v >= 10 do break;
value *= 10;
value += f64(v);
}
if i < len(s) && s[i] == '.' {
pow10: f64 = 10;
i += 1;
for ; i < len(s); i += 1 {
r := rune(s[i]);
if r == '_' do continue;
v := _digit_value(r);
if v >= 10 do break;
value += f64(v)/pow10;
pow10 *= 10;
}
}
frac := false;
scale: f64 = 1;
if i < len(s) && (s[i] == 'e' || s[i] == 'E') {
i += 1;
if i < len(s) {
switch s[i] {
case '-': i += 1; frac = true;
case '+': i += 1;
}
exp: u32 = 0;
for ; i < len(s); i += 1 {
r := rune(s[i]);
if r == '_' do continue;
d := u32(_digit_value(r));
if d >= 10 do break;
exp = exp * 10 + d;
}
if exp > 308 { exp = 308; }
for exp >= 50 { scale *= 1e50; exp -= 50; }
for exp >= 8 { scale *= 1e8; exp -= 8; }
for exp > 0 { scale *= 10; exp -= 1; }
}
}
if frac do return sign * (value/scale);
return sign * (value*scale);
}
append_bool :: proc(buf: []byte, b: bool) -> string {
n := 0;
if b do n = copy(buf, cast([]byte)"true");
else do n = copy(buf, cast([]byte)"false");
return string(buf[:n]);
}
append_uint :: proc(buf: []byte, u: u64, base: int) -> string {
return append_bits(buf, u64(u), base, false, 8*size_of(uint), digits, nil);
}
append_int :: proc(buf: []byte, i: i64, base: int) -> string {
return append_bits(buf, u64(i), base, true, 8*size_of(int), digits, nil);
}
itoa :: proc(buf: []byte, i: int) -> string do return append_int(buf, i64(i), 10);
append_float :: proc(buf: []byte, f: f64, fmt: byte, prec, bit_size: int) -> string {
return string(generic_ftoa(buf, f, fmt, prec, bit_size));
}
DecimalSlice :: struct {
digits: []byte,
count: int,
decimal_point: int,
neg: bool,
}
FloatInfo :: struct {
mantbits: uint,
expbits: uint,
bias: int,
}
_f16_info := FloatInfo{10, 5, -15};
_f32_info := FloatInfo{23, 8, -127};
_f64_info := FloatInfo{52, 11, -1023};
generic_ftoa :: proc(buf: []byte, val: f64, fmt: byte, prec, bit_size: int) -> []byte {
bits: u64;
flt: ^FloatInfo;
switch bit_size {
case 32:
bits = u64(transmute(u32)f32(val));
flt = &_f32_info;
case 64:
bits = transmute(u64)val;
flt = &_f64_info;
case:
panic("strconv: invalid bit_size");
}
neg := bits>>(flt.expbits+flt.mantbits) != 0;
exp := int(bits>>flt.mantbits) & (1<<flt.expbits - 1);
mant := bits & (u64(1) << flt.mantbits - 1);
switch exp {
case 1<<flt.expbits - 1:
s: string;
if mant != 0 {
s = "NaN";
} else if neg {
s = "-Inf";
} else {
s = "+Inf";
}
n := copy(buf, cast([]byte)s);
return buf[:n];
case 0: // denormalized
exp += 1;
case:
mant |= u64(1) << flt.mantbits;
}
exp += flt.bias;
d_: Decimal;
d := &d_;
assign(d, mant);
shift(d, exp - int(flt.mantbits));
digs: DecimalSlice;
shortest := prec < 0;
if shortest {
round_shortest(d, mant, exp, flt);
digs = DecimalSlice{digits = d.digits[:], count = d.count, decimal_point = d.decimal_point};
switch fmt {
case 'e', 'E': prec = digs.count-1;
case 'f', 'F': prec = max(digs.count-digs.decimal_point, 0);
case 'g', 'G': prec = digs.count;
}
} else {
switch fmt {
case 'e', 'E': round(d, prec+1);
case 'f', 'F': round(d, d.decimal_point+prec);
case 'g', 'G':
if prec == 0 {
prec = 1;
}
round(d, prec);
}
digs = DecimalSlice{digits = d.digits[:], count = d.count, decimal_point = d.decimal_point};
}
return format_digits(buf, shortest, neg, digs, prec, fmt);
}
format_digits :: proc(buf: []byte, shortest: bool, neg: bool, digs: DecimalSlice, prec: int, fmt: byte) -> []byte {
Buffer :: struct {
b: []byte,
n: int,
}
to_bytes :: proc(b: Buffer) -> []byte do return b.b[:b.n];
add_bytes :: proc(buf: ^Buffer, bytes: ..byte) {
buf.n += copy(buf.b[buf.n:], bytes);
}
b := Buffer{b = buf};
switch fmt {
case 'f', 'F':
add_bytes(&b, neg ? '-' : '+');
// integer, padded with zeros when needed
if digs.decimal_point > 0 {
m := min(digs.count, digs.decimal_point);
add_bytes(&b, ..digs.digits[0:m]);
for ; m < digs.decimal_point; m += 1 {
add_bytes(&b, '0');
}
} else {
add_bytes(&b, '0');
}
// fractional part
if prec > 0 {
add_bytes(&b, '.');
for i in 0..prec-1 {
c: byte = '0';
if j := digs.decimal_point + i; 0 <= j && j < digs.count {
c = digs.digits[j];
}
add_bytes(&b, c);
}
}
return to_bytes(b);
case 'e', 'E':
panic("strconv: e/E float printing is not yet supported");
return to_bytes(b); // TODO
case 'g', 'G':
panic("strconv: g/G float printing is not yet supported");
return to_bytes(b); // TODO
case:
add_bytes(&b, '%', fmt);
return to_bytes(b);
}
}
round_shortest :: proc(d: ^Decimal, mant: u64, exp: int, flt: ^FloatInfo) {
if mant == 0 { // If mantissa is zero, the number is zero
d.count = 0;
return;
}
/*
10^(dp-nd) > 2^(exp-mantbits)
log2(10) * (dp-nd) > exp-mantbits
log(2) >~ 0.332
332*(dp-nd) >= 100*(exp-mantbits)
*/
minexp := flt.bias+1;
if exp > minexp && 332*(d.decimal_point-d.count) >= 100*(exp - int(flt.mantbits)) {
// Number is already its shortest
return;
}
upper_: Decimal; upper := &upper_;
assign(upper, 2*mant - 1);
shift(upper, exp - int(flt.mantbits) - 1);
mantlo: u64;
explo: int;
if mant > 1<<flt.mantbits || exp == minexp {
mantlo = mant-1;
explo = exp;
} else {
mantlo = 2*mant - 1;
explo = exp-1;
}
lower_: Decimal; lower := &lower_;
assign(lower, 2*mantlo + 1);
shift(lower, explo - int(flt.mantbits) - 1);
inclusive := mant%2 == 0;
for i in 0..d.count-1 {
l: byte = '0'; // lower digit
if i < lower.count {
l = lower.digits[i];
}
m := d.digits[i]; // middle digit
u: byte = '0'; // upper digit
if i < upper.count {
u = upper.digits[i];
}
ok_round_down := l != m || inclusive && i+1 == lower.count;
ok_round_up := m != u && (inclusive || m+1 < u || i+1 < upper.count);
if ok_round_down && ok_round_up {
round(d, i+1);
return;
}
if ok_round_down {
round_down(d, i+1);
return;
}
if ok_round_up {
round_up(d, i+1);
return;
}
}
}
MAX_BASE :: 32;
digits := "0123456789abcdefghijklmnopqrstuvwxyz";
is_integer_negative :: proc(u: u64, is_signed: bool, bit_size: int) -> (unsigned: u64, neg: bool) {
if is_signed {
switch bit_size {
case 8:
i := i8(u);
neg = i < 0;
u = u64(abs(i64(i)));
case 16:
i := i16(u);
neg = i < 0;
u = u64(abs(i64(i)));
case 32:
i := i32(u);
neg = i < 0;
u = u64(abs(i64(i)));
case 64:
i := i64(u);
neg = i < 0;
u = u64(abs(i64(i)));
case:
panic("is_integer_negative: Unknown integer size");
}
}
return u, neg;
}
append_bits :: proc(buf: []byte, u: u64, base: int, is_signed: bool, bit_size: int, digits: string, flags: Int_Flags) -> string {
if base < 2 || base > MAX_BASE {
panic("strconv: illegal base passed to append_bits");
}
neg: bool;
a: [129]byte;
i := len(a);
u, neg = is_integer_negative(u, is_signed, bit_size);
b := u64(base);
for u >= b {
i-=1; a[i] = digits[u % b];
u /= b;
}
i-=1; a[i] = digits[u % b];
if Int_Flag.Prefix in flags {
ok := true;
switch base {
case 2: i-=1; a[i] = 'b';
case 8: i-=1; a[i] = 'o';
case 10: i-=1; a[i] = 'd';
case 12: i-=1; a[i] = 'z';
case 16: i-=1; a[i] = 'x';
case: ok = false;
}
if ok {
i-=1; a[i] = '0';
}
}
switch {
case neg:
i-=1; a[i] = '-';
case Int_Flag.Plus in flags:
i-=1; a[i] = '+';
case Int_Flag.Space in flags:
i-=1; a[i] = ' ';
}
out := a[i:];
copy(buf, out);
return string(buf[0:len(out)]);
}
-21
View File
@@ -1,21 +0,0 @@
proc new_string(s: string) -> string {
var c = make([]u8, len(s)+1);
copy(c, []u8(s));
c[len(s)] = 0;
return string(c[0..<len(s)]);
}
proc new_c_string(s: string) -> ^u8 {
var c = make([]u8, len(s)+1);
copy(c, []u8(s));
c[len(s)] = 0;
return &c[0];
}
proc to_odin_string(c: ^u8) -> string {
var len = 0;
for (c+len)^ != 0 {
len++;
}
return string(slice_ptr(c, len));
}
+33
View File
@@ -0,0 +1,33 @@
package strings
import "core:mem"
new_string :: proc(s: string) -> string {
c := make([]byte, len(s)+1);
copy(c, cast([]byte)s);
c[len(s)] = 0;
return string(c[:len(s)]);
}
new_cstring :: proc(s: string) -> cstring {
c := make([]byte, len(s)+1);
copy(c, cast([]byte)s);
c[len(s)] = 0;
return cstring(&c[0]);
}
@(deprecated="Please use a standard cast for cstring to string")
to_odin_string :: proc(str: cstring) -> string {
return string(str);
}
string_from_ptr :: proc(ptr: ^byte, len: int) -> string {
return transmute(string)mem.Raw_String{ptr, len};
}
contains_rune :: proc(s: string, r: rune) -> int {
for c, offset in s {
if c == r do return offset;
}
return -1;
}
-4
View File
@@ -1,4 +0,0 @@
import_load (
"sync_windows.odin" when ODIN_OS == "windows";
"sync_linux.odin" when ODIN_OS == "linux";
)
+184
View File
@@ -0,0 +1,184 @@
package sync
import "intrinsics"
Ordering :: enum {
Relaxed, // Monotonic
Release,
Acquire,
Acquire_Release,
Sequentially_Consistent,
}
strongest_failure_ordering :: inline proc "contextless" (order: Ordering) -> Ordering {
using Ordering;
#complete switch order {
case Relaxed: return Relaxed;
case Release: return Relaxed;
case Acquire: return Acquire;
case Acquire_Release: return Acquire;
case Sequentially_Consistent: return Sequentially_Consistent;
}
return Relaxed;
}
fence :: inline proc "contextless" (order: Ordering) {
using Ordering;
#complete switch order {
case Relaxed: panic("there is no such thing as a relaxed fence");
case Release: intrinsics.atomic_fence_rel();
case Acquire: intrinsics.atomic_fence_acq();
case Acquire_Release: intrinsics.atomic_fence_acqrel();
case Sequentially_Consistent: intrinsics.atomic_fence();
case: panic("unknown order");
}
}
atomic_store :: inline proc "contextless" (dst: ^$T, val: T, order: Ordering) {
using Ordering;
#complete switch order {
case Relaxed: intrinsics.atomic_store_relaxed(dst, val);
case Release: intrinsics.atomic_store_rel(dst, val);
case Sequentially_Consistent: intrinsics.atomic_store(dst, val);
case Acquire: panic("there is not such thing as an acquire store");
case Acquire_Release: panic("there is not such thing as an acquire/release store");
case: panic("unknown order");
}
}
atomic_load :: inline proc "contextless" (dst: ^$T, order: Ordering) -> T {
using Ordering;
#complete switch order {
case Relaxed: return intrinsics.atomic_load_relaxed(dst);
case Acquire: return intrinsics.atomic_load_acq(dst);
case Sequentially_Consistent: return intrinsics.atomic_load(dst);
case Release: panic("there is no such thing as a release load");
case Acquire_Release: panic("there is no such thing as an acquire/release load");
}
panic("unknown order");
return T{};
}
atomic_swap :: inline proc "contextless" (dst: ^$T, val: T, order: Ordering) -> T {
using Ordering;
#complete switch order {
case Relaxed: return intrinsics.atomic_xchg_relaxed(dst, val);
case Release: return intrinsics.atomic_xchg_rel(dst, val);
case Acquire: return intrinsics.atomic_xchg_acq(dst, val);
case Acquire_Release: return intrinsics.atomic_xchg_acqrel(dst, val);
case Sequentially_Consistent: return intrinsics.atomic_xchg(dst, val);
}
panic("unknown order");
return T{};
}
atomic_compare_exchange :: inline proc "contextless" (dst: ^$T, old, new: T, success, failure: Ordering) -> (val: T, ok: bool) {
using Ordering;
switch failure {
case Relaxed:
switch success {
case Relaxed: return intrinsics.atomic_cxchg_relaxed(dst, old, new);
case Acquire: return intrinsics.atomic_cxchg_acq_failrelaxed(dst, old, new);
case Acquire_Release: return intrinsics.atomic_cxchg_acqrel_failrelaxed(dst, old, new);
case Sequentially_Consistent: return intrinsics.atomic_cxchg_failrelaxed(dst, old, new);
case: panic("an unknown ordering combination");
}
case Acquire:
switch success {
case Acquire: return intrinsics.atomic_cxchg_acq(dst, old, new);
case: panic("an unknown ordering combination");
}
case Sequentially_Consistent:
switch success {
case Sequentially_Consistent: return intrinsics.atomic_cxchg(dst, old, new);
case: panic("an unknown ordering combination");
}
case Acquire_Release:
panic("there is not such thing as an acquire/release failure ordering");
case Release:
panic("there is not such thing as an release failure ordering");
}
return T{}, false;
}
atomic_add :: inline proc "contextless" (dst: ^$T, val: T, order: Ordering) -> T {
using Ordering;
#complete switch order {
case Relaxed: return intrinsics.atomic_add_relaxed(dst, val);
case Release: return intrinsics.atomic_add_rel(dst, val);
case Acquire: return intrinsics.atomic_add_acq(dst, val);
case Acquire_Release: return intrinsics.atomic_add_acqrel(dst, val);
case Sequentially_Consistent: return intrinsics.atomic_add(dst, val);
}
panic("unknown order");
return T{};
}
atomic_sub :: inline proc "contextless" (dst: ^$T, val: T, order: Ordering) -> T {
using Ordering;
#complete switch order {
case Relaxed: return intrinsics.atomic_sub_relaxed(dst, val);
case Release: return intrinsics.atomic_sub_rel(dst, val);
case Acquire: return intrinsics.atomic_sub_acq(dst, val);
case Acquire_Release: return intrinsics.atomic_sub_acqrel(dst, val);
case Sequentially_Consistent: return intrinsics.atomic_sub(dst, val);
}
panic("unknown order");
return T{};
}
atomic_and :: inline proc "contextless" (dst: ^$T, val: T, order: Ordering) -> T {
using Ordering;
#complete switch order {
case Relaxed: return intrinsics.atomic_and_relaxed(dst, val);
case Release: return intrinsics.atomic_and_rel(dst, val);
case Acquire: return intrinsics.atomic_and_acq(dst, val);
case Acquire_Release: return intrinsics.atomic_and_acqrel(dst, val);
case Sequentially_Consistent: return intrinsics.atomic_and(dst, val);
}
panic("unknown order");
return T{};
}
atomic_nand :: inline proc "contextless" (dst: ^$T, val: T, order: Ordering) -> T {
using Ordering;
#complete switch order {
case Relaxed: return intrinsics.atomic_nand_relaxed(dst, val);
case Release: return intrinsics.atomic_nand_rel(dst, val);
case Acquire: return intrinsics.atomic_nand_acq(dst, val);
case Acquire_Release: return intrinsics.atomic_nand_acqrel(dst, val);
case Sequentially_Consistent: return intrinsics.atomic_nand(dst, val);
}
panic("unknown order");
return T{};
}
atomic_or :: inline proc "contextless" (dst: ^$T, val: T, order: Ordering) -> T {
using Ordering;
#complete switch order {
case Relaxed: return intrinsics.atomic_or_relaxed(dst, val);
case Release: return intrinsics.atomic_or_rel(dst, val);
case Acquire: return intrinsics.atomic_or_acq(dst, val);
case Acquire_Release: return intrinsics.atomic_or_acqrel(dst, val);
case Sequentially_Consistent: return intrinsics.atomic_or(dst, val);
}
panic("unknown order");
return T{};
}
atomic_xor :: inline proc "contextless" (dst: ^$T, val: T, order: Ordering) -> T {
using Ordering;
#complete switch order {
case Relaxed: return intrinsics.atomic_xor_relaxed(dst, val);
case Release: return intrinsics.atomic_xor_rel(dst, val);
case Acquire: return intrinsics.atomic_xor_acq(dst, val);
case Acquire_Release: return intrinsics.atomic_xor_acqrel(dst, val);
case Sequentially_Consistent: return intrinsics.atomic_xor(dst, val);
}
panic("unknown order");
return T{};
}
@@ -1,69 +1,71 @@
import (
"atomics.odin";
"os.odin";
)
package sync
type Semaphore struct {
/*
import "core:atomics"
import "core:os"
Semaphore :: struct {
// _handle: win32.Handle,
}
type Mutex struct {
Mutex :: struct {
_semaphore: Semaphore,
_counter: i32,
_owner: i32,
_recursion: i32,
}
proc current_thread_id() -> i32 {
current_thread_id :: proc() -> i32 {
return i32(os.current_thread_id());
}
proc semaphore_init(s: ^Semaphore) {
semaphore_init :: proc(s: ^Semaphore) {
// s._handle = win32.CreateSemaphoreA(nil, 0, 1<<31-1, nil);
}
proc semaphore_destroy(s: ^Semaphore) {
semaphore_destroy :: proc(s: ^Semaphore) {
// win32.CloseHandle(s._handle);
}
proc semaphore_post(s: ^Semaphore, count: int) {
semaphore_post :: proc(s: ^Semaphore, count: int) {
// win32.ReleaseSemaphore(s._handle, cast(i32)count, nil);
}
proc semaphore_release(s: ^Semaphore) #inline {
semaphore_release :: inline proc(s: ^Semaphore) {
semaphore_post(s, 1);
}
proc semaphore_wait(s: ^Semaphore) {
semaphore_wait :: proc(s: ^Semaphore) {
// win32.WaitForSingleObject(s._handle, win32.INFINITE);
}
proc mutex_init(m: ^Mutex) {
mutex_init :: proc(m: ^Mutex) {
atomics.store(&m._counter, 0);
atomics.store(&m._owner, current_thread_id());
semaphore_init(&m._semaphore);
m._recursion = 0;
}
proc mutex_destroy(m: ^Mutex) {
mutex_destroy :: proc(m: ^Mutex) {
semaphore_destroy(&m._semaphore);
}
proc mutex_lock(m: ^Mutex) {
var thread_id = current_thread_id();
mutex_lock :: proc(m: ^Mutex) {
thread_id := current_thread_id();
if atomics.fetch_add(&m._counter, 1) > 0 {
if thread_id != atomics.load(&m._owner) {
semaphore_wait(&m._semaphore);
}
}
atomics.store(&m._owner, thread_id);
m._recursion++;
m._recursion += 1;
}
proc mutex_try_lock(m: ^Mutex) -> bool {
var thread_id = current_thread_id();
mutex_try_lock :: proc(m: ^Mutex) -> bool {
thread_id := current_thread_id();
if atomics.load(&m._owner) == thread_id {
atomics.fetch_add(&m._counter, 1);
} else {
var expected: i32 = 0;
expected: i32 = 0;
if atomics.load(&m._counter) != 0 {
return false;
}
@@ -72,15 +74,15 @@ proc mutex_try_lock(m: ^Mutex) -> bool {
}
atomics.store(&m._owner, thread_id);
}
m._recursion++;
m._recursion += 1;
return true;
}
proc mutex_unlock(m: ^Mutex) {
var recursion: i32;
var thread_id = current_thread_id();
mutex_unlock :: proc(m: ^Mutex) {
recursion: i32;
thread_id := current_thread_id();
assert(thread_id == atomics.load(&m._owner));
m._recursion--;
m._recursion -= 1;
recursion = m._recursion;
if recursion == 0 {
atomics.store(&m._owner, thread_id);
@@ -93,3 +95,4 @@ proc mutex_unlock(m: ^Mutex) {
}
}
*/
+83
View File
@@ -0,0 +1,83 @@
package sync
import "core:sys/win32"
Semaphore :: struct {
_handle: win32.Handle,
}
Mutex :: struct {
_critical_section: win32.Critical_Section,
}
Condition :: struct {
event: win32.Handle,
}
current_thread_id :: proc() -> i32 {
return i32(win32.get_current_thread_id());
}
semaphore_init :: proc(s: ^Semaphore) {
s._handle = win32.create_semaphore_w(nil, 0, 1<<31-1, nil);
}
semaphore_destroy :: proc(s: ^Semaphore) {
win32.close_handle(s._handle);
}
semaphore_post :: proc(s: ^Semaphore, count: int) {
win32.release_semaphore(s._handle, i32(count), nil);
}
semaphore_release :: inline proc(s: ^Semaphore) {
semaphore_post(s, 1);
}
semaphore_wait :: proc(s: ^Semaphore) {
result := win32.wait_for_single_object(s._handle, win32.INFINITE);
assert(result != win32.WAIT_FAILED);
}
mutex_init :: proc(m: ^Mutex, spin_count := 0) {
win32.initialize_critical_section_and_spin_count(&m._critical_section, u32(spin_count));
}
mutex_destroy :: proc(m: ^Mutex) {
win32.delete_critical_section(&m._critical_section);
}
mutex_lock :: proc(m: ^Mutex) {
win32.enter_critical_section(&m._critical_section);
}
mutex_try_lock :: proc(m: ^Mutex) -> bool {
return bool(win32.try_enter_critical_section(&m._critical_section));
}
mutex_unlock :: proc(m: ^Mutex) {
win32.leave_critical_section(&m._critical_section);
}
condition_init :: proc(using c: ^Condition) {
event = win32.create_event_w(nil, false, false, nil);
assert(event != nil);
}
condition_signal :: proc(using c: ^Condition) {
ok := win32.set_event(event);
assert(bool(ok));
}
condition_wait_for :: proc(using c: ^Condition) {
result := win32.wait_for_single_object(event, win32.INFINITE);
assert(result != win32.WAIT_FAILED);
}
condition_destroy :: proc(using c: ^Condition) {
if event != nil {
win32.close_handle(event);
}
}
-93
View File
@@ -1,93 +0,0 @@
import (
win32 "sys/windows.odin" when ODIN_OS == "windows";
"atomics.odin";
)
type Semaphore struct {
_handle: win32.Handle,
}
type Mutex struct {
_semaphore: Semaphore,
_counter: i32,
_owner: i32,
_recursion: i32,
}
proc current_thread_id() -> i32 {
return i32(win32.get_current_thread_id());
}
proc semaphore_init(s: ^Semaphore) {
s._handle = win32.create_semaphore_a(nil, 0, 1<<31-1, nil);
}
proc semaphore_destroy(s: ^Semaphore) {
win32.close_handle(s._handle);
}
proc semaphore_post(s: ^Semaphore, count: int) {
win32.release_semaphore(s._handle, i32(count), nil);
}
proc semaphore_release(s: ^Semaphore) #inline { semaphore_post(s, 1); }
proc semaphore_wait(s: ^Semaphore) {
win32.wait_for_single_object(s._handle, win32.INFINITE);
}
proc mutex_init(m: ^Mutex) {
atomics.store(&m._counter, 0);
atomics.store(&m._owner, current_thread_id());
semaphore_init(&m._semaphore);
m._recursion = 0;
}
proc mutex_destroy(m: ^Mutex) {
semaphore_destroy(&m._semaphore);
}
proc mutex_lock(m: ^Mutex) {
var thread_id = current_thread_id();
if atomics.fetch_add(&m._counter, 1) > 0 {
if thread_id != atomics.load(&m._owner) {
semaphore_wait(&m._semaphore);
}
}
atomics.store(&m._owner, thread_id);
m._recursion++;
}
proc mutex_try_lock(m: ^Mutex) -> bool {
var thread_id = current_thread_id();
if atomics.load(&m._owner) == thread_id {
atomics.fetch_add(&m._counter, 1);
} else {
var expected: i32 = 0;
if atomics.load(&m._counter) != 0 {
return false;
}
if atomics.compare_exchange(&m._counter, expected, 1) == 0 {
return false;
}
atomics.store(&m._owner, thread_id);
}
m._recursion++;
return true;
}
proc mutex_unlock(m: ^Mutex) {
var recursion: i32;
var thread_id = current_thread_id();
assert(thread_id == atomics.load(&m._owner));
m._recursion--;
recursion = m._recursion;
if recursion == 0 {
atomics.store(&m._owner, thread_id);
}
if atomics.fetch_add(&m._counter, -1) > 1 {
if recursion == 0 {
semaphore_release(&m._semaphore);
}
}
}
+24
View File
@@ -0,0 +1,24 @@
ENTRY(_start)
SECTIONS
{
. = 0x100000;
.text BLOCK(4K) : ALIGN(4K)
{
*(.text)
}
.rodata BLOCK(4K) : ALIGN(4K)
{
*(.rodata)
}
.data BLOCK(4K) : ALIGN(4K)
{
*(.data)
}
.bss BLOCK(4K) : ALIGN(4K)
{
*(COMMON)
*(.bss)
}
}
-90
View File
@@ -1,90 +0,0 @@
foreign_system_library "opengl32.lib" when ODIN_OS == "windows";
import . "windows.odin";
const (
CONTEXT_MAJOR_VERSION_ARB = 0x2091;
CONTEXT_MINOR_VERSION_ARB = 0x2092;
CONTEXT_FLAGS_ARB = 0x2094;
CONTEXT_PROFILE_MASK_ARB = 0x9126;
CONTEXT_FORWARD_COMPATIBLE_BIT_ARB = 0x0002;
CONTEXT_CORE_PROFILE_BIT_ARB = 0x00000001;
CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB = 0x00000002;
)
type (
Hglrc Handle;
ColorRef u32;
LayerPlaneDescriptor struct {
size: u16,
version: u16,
flags: u32,
pixel_type: u8,
color_bits: u8,
red_bits: u8,
red_shift: u8,
green_bits: u8,
green_shift: u8,
blue_bits: u8,
blue_shift: u8,
alpha_bits: u8,
alpha_shift: u8,
accum_bits: u8,
accum_red_bits: u8,
accum_green_bits: u8,
accum_blue_bits: u8,
accum_alpha_bits: u8,
depth_bits: u8,
stencil_bits: u8,
aux_buffers: u8,
layer_type: u8,
reserved: u8,
transparent: ColorRef,
}
PointFloat struct {
x, y: f32,
}
Glyph_MetricsFloat struct {
black_box_x: f32,
black_box_y: f32,
glyph_origin: PointFloat,
cell_inc_x: f32,
cell_inc_y: f32,
}
)
type (
CreateContextAttribsARBType proc(hdc: Hdc, h_share_context: rawptr, attribList: ^i32) -> Hglrc;
ChoosePixelFormatARBType proc(hdc: Hdc, attrib_i_list: ^i32, attrib_f_list: ^f32, max_formats: u32, formats: ^i32, num_formats : ^u32) -> Bool #cc_c;
SwapIntervalEXTType proc(interval: i32) -> bool #cc_c;
GetExtensionsStringARBType proc(Hdc) -> ^u8 #cc_c;
)
var (
create_context_attribs_arb: CreateContextAttribsARBType;
choose_pixel_format_arb: ChoosePixelFormatARBType;
swap_interval_ext: SwapIntervalEXTType;
get_extensions_string_arb: GetExtensionsStringARBType;
)
foreign opengl32 {
proc create_context (hdc: Hdc) -> Hglrc #link_name "wglCreateContext";
proc make_current (hdc: Hdc, hglrc: Hglrc) -> Bool #link_name "wglMakeCurrent";
proc get_proc_address (c_str: ^u8) -> Proc #link_name "wglGetProcAddress";
proc delete_context (hglrc: Hglrc) -> Bool #link_name "wglDeleteContext";
proc copy_context (src, dst: Hglrc, mask: u32) -> Bool #link_name "wglCopyContext";
proc create_layer_context (hdc: Hdc, layer_plane: i32) -> Hglrc #link_name "wglCreateLayerContext";
proc describe_layer_plane (hdc: Hdc, pixel_format, layer_plane: i32, bytes: u32, pd: ^LayerPlaneDescriptor) -> Bool #link_name "wglDescribeLayerPlane";
proc get_current_context () -> Hglrc #link_name "wglGetCurrentContext";
proc get_current_dc () -> Hdc #link_name "wglGetCurrentDC";
proc get_layer_palette_entries(hdc: Hdc, layer_plane, start, entries: i32, cr: ^ColorRef) -> i32 #link_name "wglGetLayerPaletteEntries";
proc realize_layer_palette (hdc: Hdc, layer_plane: i32, realize: Bool) -> Bool #link_name "wglRealizeLayerPalette";
proc set_layer_palette_entries(hdc: Hdc, layer_plane, start, entries: i32, cr: ^ColorRef) -> i32 #link_name "wglSetLayerPaletteEntries";
proc share_lists (hglrc1, hglrc2: Hglrc) -> Bool #link_name "wglShareLists";
proc swap_layer_buffers (hdc: Hdc, planes: u32) -> Bool #link_name "wglSwapLayerBuffers";
proc use_font_bitmaps (hdc: Hdc, first, count, list_base: u32) -> Bool #link_name "wglUseFontBitmaps";
proc use_font_outlines (hdc: Hdc, first, count, list_base: u32, deviation, extrusion: f32, format: i32, gmf: ^Glyph_MetricsFloat) -> Bool #link_name "wglUseFontOutlines";
}
+114
View File
@@ -0,0 +1,114 @@
// +build windows
package win32
foreign import "system:opengl32.lib"
CONTEXT_MAJOR_VERSION_ARB :: 0x2091;
CONTEXT_MINOR_VERSION_ARB :: 0x2092;
CONTEXT_FLAGS_ARB :: 0x2094;
CONTEXT_PROFILE_MASK_ARB :: 0x9126;
CONTEXT_FORWARD_COMPATIBLE_BIT_ARB :: 0x0002;
CONTEXT_CORE_PROFILE_BIT_ARB :: 0x00000001;
CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB :: 0x00000002;
Hglrc :: distinct Handle;
Color_Ref :: distinct u32;
Layer_Plane_Descriptor :: struct {
size: u16,
version: u16,
flags: u32,
pixel_type: u8,
color_bits: u8,
red_bits: u8,
red_shift: u8,
green_bits: u8,
green_shift: u8,
blue_bits: u8,
blue_shift: u8,
alpha_bits: u8,
alpha_shift: u8,
accum_bits: u8,
accum_red_bits: u8,
accum_green_bits: u8,
accum_blue_bits: u8,
accum_alpha_bits: u8,
depth_bits: u8,
stencil_bits: u8,
aux_buffers: u8,
layer_type: u8,
reserved: u8,
transparent: Color_Ref,
}
Point_Float :: struct {x, y: f32};
Glyph_Metrics_Float :: struct {
black_box_x: f32,
black_box_y: f32,
glyph_origin: Point_Float,
cell_inc_x: f32,
cell_inc_y: f32,
}
Create_Context_Attribs_ARB_Type :: #type proc "c" (hdc: Hdc, h_share_context: rawptr, attribList: ^i32) -> Hglrc;
Choose_Pixel_Format_ARB_Type :: #type proc "c" (hdc: Hdc, attrib_i_list: ^i32, attrib_f_list: ^f32, max_formats: u32, formats: ^i32, num_formats : ^u32) -> Bool;
Swap_Interval_EXT_Type :: #type proc "c" (interval: i32) -> bool;
Get_Extensions_String_ARB_Type :: #type proc "c" (Hdc) -> cstring;
// Procedures
create_context_attribs_arb: Create_Context_Attribs_ARB_Type;
choose_pixel_format_arb: Choose_Pixel_Format_ARB_Type;
swap_interval_ext: Swap_Interval_EXT_Type;
get_extensions_string_arb: Get_Extensions_String_ARB_Type;
foreign opengl32 {
@(link_name="wglCreateContext")
create_context :: proc(hdc: Hdc) -> Hglrc ---;
@(link_name="wglMakeCurrent")
make_current :: proc(hdc: Hdc, hglrc: Hglrc) -> Bool ---;
@(link_name="wglGetProcAddress")
get_gl_proc_address :: proc(c_str: cstring) -> rawptr ---;
@(link_name="wglDeleteContext")
delete_context :: proc(hglrc: Hglrc) -> Bool ---;
@(link_name="wglCopyContext")
copy_context :: proc(src, dst: Hglrc, mask: u32) -> Bool ---;
@(link_name="wglCreateLayerContext")
create_layer_context :: proc(hdc: Hdc, layer_plane: i32) -> Hglrc ---;
@(link_name="wglDescribeLayerPlane")
describe_layer_plane :: proc(hdc: Hdc, pixel_format, layer_plane: i32, bytes: u32, pd: ^Layer_Plane_Descriptor) -> Bool ---;
@(link_name="wglGetCurrentContext")
get_current_context :: proc() -> Hglrc ---;
@(link_name="wglGetCurrentDC")
get_current_dc :: proc() -> Hdc ---;
@(link_name="wglGetLayerPaletteEntries")
get_layer_palette_entries :: proc(hdc: Hdc, layer_plane, start, entries: i32, cr: ^Color_Ref) -> i32 ---;
@(link_name="wglRealizeLayerPalette")
realize_layer_palette :: proc(hdc: Hdc, layer_plane: i32, realize: Bool) -> Bool ---;
@(link_name="wglSetLayerPaletteEntries")
set_layer_palette_entries :: proc(hdc: Hdc, layer_plane, start, entries: i32, cr: ^Color_Ref) -> i32 ---;
@(link_name="wglShareLists")
share_lists :: proc(hglrc1, hglrc2: Hglrc) -> Bool ---;
@(link_name="wglSwapLayerBuffers")
swap_layer_buffers :: proc(hdc: Hdc, planes: u32) -> Bool ---;
@(link_name="wglUseFontBitmaps")
use_font_bitmaps :: proc(hdc: Hdc, first, count, list_base: u32) -> Bool ---;
@(link_name="wglUseFontOutlines")
use_font_outlines :: proc(hdc: Hdc, first, count, list_base: u32, deviation, extrusion: f32, format: i32, gmf: ^Glyph_Metrics_Float) -> Bool ---;
}
File diff suppressed because it is too large Load Diff
-700
View File
@@ -1,700 +0,0 @@
foreign_system_library (
"kernel32.lib" when ODIN_OS == "windows";
"user32.lib" when ODIN_OS == "windows";
"gdi32.lib" when ODIN_OS == "windows";
"winmm.lib" when ODIN_OS == "windows";
"shell32.lib" when ODIN_OS == "windows";
)
type (
Handle rawptr;
Hwnd Handle;
Hdc Handle;
Hinstance Handle;
Hicon Handle;
Hcursor Handle;
Hmenu Handle;
Hbrush Handle;
Hgdiobj Handle;
Hmodule Handle;
Hmonitor Handle;
Wparam uint;
Lparam int;
Lresult int;
WndProc proc(Hwnd, u32, Wparam, Lparam) -> Lresult #cc_c;
)
type Bool i32;
const (
FALSE: Bool = 0;
TRUE = 1;
)
type Point struct #ordered {
x, y: i32,
}
type WndClassExA struct #ordered {
size, style: u32,
wnd_proc: WndProc,
cls_extra, wnd_extra: i32,
instance: Hinstance,
icon: Hicon,
cursor: Hcursor,
background: Hbrush,
menu_name, class_name: ^u8,
sm: Hicon,
}
type Msg struct #ordered {
hwnd: Hwnd,
message: u32,
wparam: Wparam,
lparam: Lparam,
time: u32,
pt: Point,
}
type Rect struct #ordered {
left: i32,
top: i32,
right: i32,
bottom: i32,
}
type Filetime struct #ordered {
lo, hi: u32,
}
type Systemtime struct #ordered {
year, month: u16,
day_of_week, day: u16,
hour, minute, second, millisecond: u16,
}
type ByHandleFileInformation struct #ordered {
file_attributes: u32,
creation_time,
last_access_time,
last_write_time: Filetime,
volume_serial_number,
file_size_high,
file_size_low,
number_of_links,
file_index_high,
file_index_low: u32,
}
type FileAttributeData struct #ordered {
file_attributes: u32,
creation_time,
last_access_time,
last_write_time: Filetime,
file_size_high,
file_size_low: u32,
}
type FindData struct #ordered {
file_attributes: u32,
creation_time: Filetime,
last_access_time: Filetime,
last_write_time: Filetime,
file_size_high: u32,
file_size_low: u32,
reserved0: u32,
reserved1: u32,
file_name: [MAX_PATH]u8,
alternate_file_name: [14]u8,
}
type Security_Attributes struct #ordered {
length: u32,
security_descriptor: rawptr,
inherit_handle: Bool,
}
type PixelFormatDescriptor struct #ordered {
size,
version,
flags: u32,
pixel_type,
color_bits,
red_bits,
red_shift,
green_bits,
green_shift,
blue_bits,
blue_shift,
alpha_bits,
alpha_shift,
accum_bits,
accum_red_bits,
accum_green_bits,
accum_blue_bits,
accum_alpha_bits,
depth_bits,
stencil_bits,
aux_buffers,
layer_type,
reserved: u8,
layer_mask,
visible_mask,
damage_mask: u32,
}
type Proc proc() #cc_c;
const (
MAPVK_VK_TO_VSC = 0;
MAPVK_VSC_TO_VK = 1;
MAPVK_VK_TO_CHAR = 2;
MAPVK_VSC_TO_VK_EX = 3;
)
const INVALID_HANDLE = Handle(~int(0));
const (
CS_VREDRAW = 0x0001;
CS_HREDRAW = 0x0002;
CS_OWNDC = 0x0020;
CW_USEDEFAULT = -0x80000000;
WS_OVERLAPPED = 0;
WS_MAXIMIZEBOX = 0x00010000;
WS_MINIMIZEBOX = 0x00020000;
WS_THICKFRAME = 0x00040000;
WS_SYSMENU = 0x00080000;
WS_BORDER = 0x00800000;
WS_CAPTION = 0x00C00000;
WS_VISIBLE = 0x10000000;
WS_POPUP = 0x80000000;
WS_OVERLAPPEDWINDOW = WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_THICKFRAME|WS_MINIMIZEBOX|WS_MAXIMIZEBOX;
WS_POPUPWINDOW = WS_POPUP | WS_BORDER | WS_SYSMENU;
WM_DESTROY = 0x0002;
WM_SIZE = 0x0005;
WM_CLOSE = 0x0010;
WM_ACTIVATEAPP = 0x001C;
WM_QUIT = 0x0012;
WM_KEYDOWN = 0x0100;
WM_KEYUP = 0x0101;
WM_SIZING = 0x0214;
WM_SYSKEYDOWN = 0x0104;
WM_SYSKEYUP = 0x0105;
WM_WINDOWPOSCHANGED = 0x0047;
WM_SETCURSOR = 0x0020;
WM_CHAR = 0x0102;
WM_ACTIVATE = 0x0006;
WM_SETFOCUS = 0x0007;
WM_KILLFOCUS = 0x0008;
WM_USER = 0x0400;
WM_MOUSEWHEEL = 0x020A;
WM_MOUSEMOVE = 0x0200;
WM_LBUTTONDOWN = 0x0201;
WM_LBUTTONUP = 0x0202;
WM_LBUTTONDBLCLK = 0x0203;
WM_RBUTTONDOWN = 0x0204;
WM_RBUTTONUP = 0x0205;
WM_RBUTTONDBLCLK = 0x0206;
WM_MBUTTONDOWN = 0x0207;
WM_MBUTTONUP = 0x0208;
WM_MBUTTONDBLCLK = 0x0209;
PM_NOREMOVE = 0x0000;
PM_REMOVE = 0x0001;
PM_NOYIELD = 0x0002;
BLACK_BRUSH = 4;
SM_CXSCREEN = 0;
SM_CYSCREEN = 1;
SW_SHOW = 5;
)
const COLOR_BACKGROUND = Hbrush(int(1));
const INVALID_SET_FILE_POINTER = ~u32(0);
const HEAP_ZERO_MEMORY = 0x00000008;
const INFINITE = 0xffffffff;
const GWL_STYLE = -16;
const Hwnd_TOP = Hwnd(uint(0));
const BI_RGB = 0;
const DIB_RGB_COLORS = 0x00;
const SRCCOPY: u32 = 0x00cc0020;
const (
MONITOR_DEFAULTTONULL = 0x00000000;
MONITOR_DEFAULTTOPRIMARY = 0x00000001;
MONITOR_DEFAULTTONEAREST = 0x00000002;
)
const (
SWP_FRAMECHANGED = 0x0020;
SWP_NOOWNERZORDER = 0x0200;
SWP_NOZORDER = 0x0004;
SWP_NOSIZE = 0x0001;
SWP_NOMOVE = 0x0002;
)
// Windows OpenGL
const (
PFD_TYPE_RGBA = 0;
PFD_TYPE_COLORINDEX = 1;
PFD_MAIN_PLANE = 0;
PFD_OVERLAY_PLANE = 1;
PFD_UNDERLAY_PLANE = -1;
PFD_DOUBLEBUFFER = 1;
PFD_STEREO = 2;
PFD_DRAW_TO_WINDOW = 4;
PFD_DRAW_TO_BITMAP = 8;
PFD_SUPPORT_GDI = 16;
PFD_SUPPORT_OPENGL = 32;
PFD_GENERIC_FORMAT = 64;
PFD_NEED_PALETTE = 128;
PFD_NEED_SYSTEM_PALETTE = 0x00000100;
PFD_SWAP_EXCHANGE = 0x00000200;
PFD_SWAP_COPY = 0x00000400;
PFD_SWAP_LAYER_BUFFERS = 0x00000800;
PFD_GENERIC_ACCELERATED = 0x00001000;
PFD_DEPTH_DONTCARE = 0x20000000;
PFD_DOUBLEBUFFER_DONTCARE = 0x40000000;
PFD_STEREO_DONTCARE = 0x80000000;
)
type GET_FILEEX_INFO_LEVELS i32;
const (
GetFileExInfoStandard: GET_FILEEX_INFO_LEVELS = 0;
GetFileExMaxInfoLevel = 1;
)
foreign kernel32 {
proc get_last_error () -> i32 #cc_std #link_name "GetLastError";
proc exit_process (exit_code: u32) #cc_std #link_name "ExitProcess";
proc get_module_handle_a(module_name: ^u8) -> Hinstance #cc_std #link_name "GetModuleHandleA";
proc sleep(ms: i32) -> i32 #cc_std #link_name "Sleep";
proc query_performance_frequency(result: ^i64) -> i32 #cc_std #link_name "QueryPerformanceFrequency";
proc query_performance_counter (result: ^i64) -> i32 #cc_std #link_name "QueryPerformanceCounter";
proc output_debug_string_a(c_str: ^u8) #cc_std #link_name "OutputDebugStringA";
proc get_command_line_a () -> ^u8 #cc_std #link_name "GetCommandLineA";
proc get_command_line_w () -> ^u16 #cc_std #link_name "GetCommandLineW";
proc get_system_metrics (index: i32) -> i32 #cc_std #link_name "GetSystemMetrics";
proc get_current_thread_id () -> u32 #cc_std #link_name "GetCurrentThreadId";
proc get_system_time_as_file_time(system_time_as_file_time: ^Filetime) #cc_std #link_name "GetSystemTimeAsFileTime";
proc file_time_to_local_file_time(file_time: ^Filetime, local_file_time: ^Filetime) -> Bool #cc_std #link_name "FileTimeToLocalFileTime";
proc file_time_to_system_time (file_time: ^Filetime, system_time: ^Systemtime) -> Bool #cc_std #link_name "FileTimeToSystemTime";
proc system_time_to_file_time (system_time: ^Systemtime, file_time: ^Filetime) -> Bool #cc_std #link_name "SystemTimeToFileTime";
proc close_handle (h: Handle) -> i32 #cc_std #link_name "CloseHandle";
proc get_std_handle(h: i32) -> Handle #cc_std #link_name "GetStdHandle";
proc create_file_a (filename: ^u8, desired_access, share_mode: u32,
security: rawptr,
creation, flags_and_attribs: u32, template_file: Handle) -> Handle #cc_std #link_name "CreateFileA";
proc read_file (h: Handle, buf: rawptr, to_read: u32, bytes_read: ^i32, overlapped: rawptr) -> Bool #cc_std #link_name "ReadFile";
proc write_file(h: Handle, buf: rawptr, len: i32, written_result: ^i32, overlapped: rawptr) -> Bool #cc_std #link_name "WriteFile";
proc get_file_size_ex (file_handle: Handle, file_size: ^i64) -> Bool #cc_std #link_name "GetFileSizeEx";
proc get_file_attributes_a (filename: ^u8) -> u32 #cc_std #link_name "GetFileAttributesA";
proc get_file_attributes_ex_a (filename: ^u8, info_level_id: GET_FILEEX_INFO_LEVELS, file_info: rawptr) -> Bool #cc_std #link_name "GetFileAttributesExA";
proc get_file_information_by_handle(file_handle: Handle, file_info: ^ByHandleFileInformation) -> Bool #cc_std #link_name "GetFileInformationByHandle";
proc get_file_type (file_handle: Handle) -> u32 #cc_std #link_name "GetFileType";
proc set_file_pointer(file_handle: Handle, distance_to_move: i32, distance_to_move_high: ^i32, move_method: u32) -> u32 #cc_std #link_name "SetFilePointer";
proc set_handle_information(obj: Handle, mask, flags: u32) -> Bool #cc_std #link_name "SetHandleInformation";
proc find_first_file_a(file_name : ^u8, data : ^FindData) -> Handle #cc_std #link_name "FindFirstFileA";
proc find_next_file_a (file : Handle, data : ^FindData) -> Bool #cc_std #link_name "FindNextFileA";
proc find_close (file : Handle) -> Bool #cc_std #link_name "FindClose";
proc heap_alloc (h: Handle, flags: u32, bytes: int) -> rawptr #cc_std #link_name "HeapAlloc";
proc heap_realloc (h: Handle, flags: u32, memory: rawptr, bytes: int) -> rawptr #cc_std #link_name "HeapReAlloc";
proc heap_free (h: Handle, flags: u32, memory: rawptr) -> Bool #cc_std #link_name "HeapFree";
proc get_process_heap() -> Handle #cc_std #link_name "GetProcessHeap";
proc create_semaphore_a (attributes: ^Security_Attributes, initial_count, maximum_count: i32, name: ^u8) -> Handle #cc_std #link_name "CreateSemaphoreA";
proc release_semaphore (semaphore: Handle, release_count: i32, previous_count: ^i32) -> Bool #cc_std #link_name "ReleaseSemaphore";
proc wait_for_single_object(handle: Handle, milliseconds: u32) -> u32 #cc_std #link_name "WaitForSingleObject";
proc interlocked_compare_exchange (dst: ^i32, exchange, comparand: i32) -> i32 #cc_std #link_name "InterlockedCompareExchange";
proc interlocked_exchange (dst: ^i32, desired: i32) -> i32 #cc_std #link_name "InterlockedExchange";
proc interlocked_exchange_add (dst: ^i32, desired: i32) -> i32 #cc_std #link_name "InterlockedExchangeAdd";
proc interlocked_and (dst: ^i32, desired: i32) -> i32 #cc_std #link_name "InterlockedAnd";
proc interlocked_or (dst: ^i32, desired: i32) -> i32 #cc_std #link_name "InterlockedOr";
proc interlocked_compare_exchange64(dst: ^i64, exchange, comparand: i64) -> i64 #cc_std #link_name "InterlockedCompareExchange64";
proc interlocked_exchange64 (dst: ^i64, desired: i64) -> i64 #cc_std #link_name "InterlockedExchange64";
proc interlocked_exchange_add64 (dst: ^i64, desired: i64) -> i64 #cc_std #link_name "InterlockedExchangeAdd64";
proc interlocked_and64 (dst: ^i64, desired: i64) -> i64 #cc_std #link_name "InterlockedAnd64";
proc interlocked_or64 (dst: ^i64, desired: i64) -> i64 #cc_std #link_name "InterlockedOr64";
proc mm_pause () #cc_std #link_name "_mm_pause";
proc read_write_barrier() #cc_std #link_name "ReadWriteBarrier";
proc write_barrier () #cc_std #link_name "WriteBarrier";
proc read_barrier () #cc_std #link_name "ReadBarrier";
proc load_library_a (c_str: ^u8) -> Hmodule #cc_std #link_name "LoadLibraryA";
proc free_library (h: Hmodule) #cc_std #link_name "FreeLibrary";
proc get_proc_address(h: Hmodule, c_str: ^u8) -> Proc #cc_std #link_name "GetProcAddress";
}
foreign user32 {
proc get_desktop_window () -> Hwnd #cc_std #link_name "GetDesktopWindow";
proc show_cursor (show : Bool) #cc_std #link_name "ShowCursor";
proc get_cursor_pos (p: ^Point) -> i32 #cc_std #link_name "GetCursorPos";
proc screen_to_client (h: Hwnd, p: ^Point) -> i32 #cc_std #link_name "ScreenToClient";
proc post_quit_message (exit_code: i32) #cc_std #link_name "PostQuitMessage";
proc set_window_text_a (hwnd: Hwnd, c_string: ^u8) -> Bool #cc_std #link_name "SetWindowTextA";
proc register_class_ex_a (wc: ^WndClassExA) -> i16 #cc_std #link_name "RegisterClassExA";
proc create_window_ex_a (ex_style: u32,
class_name, title: ^u8,
style: u32,
x, y, w, h: i32,
parent: Hwnd, menu: Hmenu, instance: Hinstance,
param: rawptr) -> Hwnd #cc_std #link_name "CreateWindowExA";
proc show_window (hwnd: Hwnd, cmd_show: i32) -> Bool #cc_std #link_name "ShowWindow";
proc translate_message (msg: ^Msg) -> Bool #cc_std #link_name "TranslateMessage";
proc dispatch_message_a (msg: ^Msg) -> Lresult #cc_std #link_name "DispatchMessageA";
proc update_window (hwnd: Hwnd) -> Bool #cc_std #link_name "UpdateWindow";
proc get_message_a (msg: ^Msg, hwnd: Hwnd, msg_filter_min, msg_filter_max : u32) -> Bool #cc_std #link_name "GetMessageA";
proc peek_message_a (msg: ^Msg, hwnd: Hwnd,
msg_filter_min, msg_filter_max, remove_msg: u32) -> Bool #cc_std #link_name "PeekMessageA";
proc post_message (hwnd: Hwnd, msg, wparam, lparam : u32) -> Bool #cc_std #link_name "PostMessageA";
proc def_window_proc_a (hwnd: Hwnd, msg: u32, wparam: Wparam, lparam: Lparam) -> Lresult #cc_std #link_name "DefWindowProcA";
proc adjust_window_rect (rect: ^Rect, style: u32, menu: Bool) -> Bool #cc_std #link_name "AdjustWindowRect";
proc get_active_window () -> Hwnd #cc_std #link_name "GetActiveWindow";
proc destroy_window (wnd: Hwnd) -> Bool #cc_std #link_name "DestroyWindow";
proc describe_pixel_format(dc: Hdc, pixel_format: i32, bytes : u32, pfd: ^PixelFormatDescriptor) -> i32 #cc_std #link_name "DescribePixelFormat";
proc get_monitor_info_a (monitor: Hmonitor, mi: ^MonitorInfo) -> Bool #cc_std #link_name "GetMonitorInfoA";
proc monitor_from_window (wnd: Hwnd, flags : u32) -> Hmonitor #cc_std #link_name "MonitorFromWindow";
proc set_window_pos (wnd: Hwnd, wndInsertAfter: Hwnd, x, y, width, height: i32, flags: u32) #cc_std #link_name "SetWindowPos";
proc get_window_placement (wnd: Hwnd, wndpl: ^WindowPlacement) -> Bool #cc_std #link_name "GetWindowPlacement";
proc set_window_placement (wnd: Hwnd, wndpl: ^WindowPlacement) -> Bool #cc_std #link_name "SetWindowPlacement";
proc get_window_rect (wnd: Hwnd, rect: ^Rect) -> Bool #cc_std #link_name "GetWindowRect";
proc get_window_long_ptr_a(wnd: Hwnd, index: i32) -> i64 #cc_std #link_name "GetWindowLongPtrA";
proc set_window_long_ptr_a(wnd: Hwnd, index: i32, new: i64) -> i64 #cc_std #link_name "SetWindowLongPtrA";
proc get_window_text (wnd: Hwnd, str: ^u8, maxCount: i32) -> i32 #cc_std #link_name "GetWindowText";
proc get_client_rect (hwnd: Hwnd, rect: ^Rect) -> Bool #cc_std #link_name "GetClientRect";
proc get_dc (h: Hwnd) -> Hdc #cc_std #link_name "GetDC";
proc release_dc (wnd: Hwnd, hdc: Hdc) -> i32 #cc_std #link_name "ReleaseDC";
proc map_virtual_key(scancode : u32, map_type : u32) -> u32 #cc_std #link_name "MapVirtualKeyA";
proc get_key_state (v_key: i32) -> i16 #cc_std #link_name "GetKeyState";
proc get_async_key_state(v_key: i32) -> i16 #cc_std #link_name "GetAsyncKeyState";
}
foreign gdi32 {
proc get_stock_object(fn_object: i32) -> Hgdiobj #cc_std #link_name "GetStockObject";
proc stretch_dibits( hdc: Hdc,
x_dst, y_dst, width_dst, height_dst: i32,
x_src, y_src, width_src, header_src: i32,
bits: rawptr, bits_info: ^BitmapInfo,
usage: u32,
rop: u32) -> i32 #cc_std #link_name "StretchDIBits";
proc set_pixel_format (hdc: Hdc, pixel_format: i32, pfd: ^PixelFormatDescriptor) -> Bool #cc_std #link_name "SetPixelFormat";
proc choose_pixel_format(hdc: Hdc, pfd: ^PixelFormatDescriptor) -> i32 #cc_std #link_name "ChoosePixelFormat";
proc swap_buffers (hdc: Hdc) -> Bool #cc_std #link_name "SwapBuffers";
}
foreign shell32 {
proc command_line_to_argv_w(cmd_list: ^u16, num_args: ^i32) -> ^^u16 #cc_std #link_name "CommandLineToArgvW";
}
foreign winmm {
proc time_get_time() -> u32 #cc_std #link_name "timeGetTime";
}
proc get_query_performance_frequency() -> i64 {
var r: i64;
query_performance_frequency(&r);
return r;
}
proc HIWORD(wParam: Wparam) -> u16 { return u16((u32(wParam) >> 16) & 0xffff); }
proc HIWORD(lParam: Lparam) -> u16 { return u16((u32(lParam) >> 16) & 0xffff); }
proc LOWORD(wParam: Wparam) -> u16 { return u16(wParam); }
proc LOWORD(lParam: Lparam) -> u16 { return u16(lParam); }
proc is_key_down(key: KeyCode) -> bool #inline { return get_async_key_state(i32(key)) < 0; }
const (
MAX_PATH = 0x00000104;
HANDLE_FLAG_INHERIT = 1;
HANDLE_FLAG_PROTECT_FROM_CLOSE = 2;
FILE_BEGIN = 0;
FILE_CURRENT = 1;
FILE_END = 2;
FILE_SHARE_READ = 0x00000001;
FILE_SHARE_WRITE = 0x00000002;
FILE_SHARE_DELETE = 0x00000004;
FILE_GENERIC_ALL = 0x10000000;
FILE_GENERIC_EXECUTE = 0x20000000;
FILE_GENERIC_WRITE = 0x40000000;
FILE_GENERIC_READ = 0x80000000;
FILE_APPEND_DATA = 0x0004;
STD_INPUT_HANDLE = -10;
STD_OUTPUT_HANDLE = -11;
STD_ERROR_HANDLE = -12;
CREATE_NEW = 1;
CREATE_ALWAYS = 2;
OPEN_EXISTING = 3;
OPEN_ALWAYS = 4;
TRUNCATE_EXISTING = 5;
INVALID_FILE_ATTRIBUTES = -1;
FILE_ATTRIBUTE_READONLY = 0x00000001;
FILE_ATTRIBUTE_HIDDEN = 0x00000002;
FILE_ATTRIBUTE_SYSTEM = 0x00000004;
FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
FILE_ATTRIBUTE_ARCHIVE = 0x00000020;
FILE_ATTRIBUTE_DEVICE = 0x00000040;
FILE_ATTRIBUTE_NORMAL = 0x00000080;
FILE_ATTRIBUTE_TEMPORARY = 0x00000100;
FILE_ATTRIBUTE_SPARSE_FILE = 0x00000200;
FILE_ATTRIBUTE_REPARSE_Point = 0x00000400;
FILE_ATTRIBUTE_COMPRESSED = 0x00000800;
FILE_ATTRIBUTE_OFFLINE = 0x00001000;
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 0x00002000;
FILE_ATTRIBUTE_ENCRYPTED = 0x00004000;
FILE_TYPE_DISK = 0x0001;
FILE_TYPE_CHAR = 0x0002;
FILE_TYPE_PIPE = 0x0003;
)
type MonitorInfo struct #ordered {
size: u32,
monitor: Rect,
work: Rect,
flags: u32,
}
type WindowPlacement struct #ordered {
length: u32,
flags: u32,
show_cmd: u32,
min_pos: Point,
max_pos: Point,
normal_pos: Rect,
}
type BitmapInfoHeader struct #ordered {
size: u32,
width, height: i32,
planes, bit_count: i16,
compression: u32,
size_image: u32,
x_pels_per_meter: i32,
y_pels_per_meter: i32,
clr_used: u32,
clr_important: u32,
}
type BitmapInfo struct #ordered {
using header: BitmapInfoHeader,
colors: [1]RgbQuad,
}
type RgbQuad struct #ordered { blue, green, red, reserved: u8 }
type KeyCode enum i32 {
Lbutton = 0x01,
Rbutton = 0x02,
Cancel = 0x03,
Mbutton = 0x04,
Back = 0x08,
Tab = 0x09,
Clear = 0x0C,
Return = 0x0D,
Shift = 0x10,
Control = 0x11,
Menu = 0x12,
Pause = 0x13,
Capital = 0x14,
Kana = 0x15,
Hangeul = 0x15,
Hangul = 0x15,
Junja = 0x17,
Final = 0x18,
Hanja = 0x19,
Kanji = 0x19,
Escape = 0x1B,
Convert = 0x1C,
NonConvert = 0x1D,
Accept = 0x1E,
ModeChange = 0x1F,
Space = 0x20,
Prior = 0x21,
Next = 0x22,
End = 0x23,
Home = 0x24,
Left = 0x25,
Up = 0x26,
Right = 0x27,
Down = 0x28,
Select = 0x29,
Print = 0x2A,
Execute = 0x2B,
Snapshot = 0x2C,
Insert = 0x2D,
Delete = 0x2E,
Help = 0x2F,
Num0 = '0',
Num1 = '1',
Num2 = '2',
Num3 = '3',
Num4 = '4',
Num5 = '5',
Num6 = '6',
Num7 = '7',
Num8 = '8',
Num9 = '9',
A = 'A',
B = 'B',
C = 'C',
D = 'D',
E = 'E',
F = 'F',
G = 'G',
H = 'H',
I = 'I',
J = 'J',
K = 'K',
L = 'L',
M = 'M',
N = 'N',
O = 'O',
P = 'P',
Q = 'Q',
R = 'R',
S = 'S',
T = 'T',
U = 'U',
V = 'V',
W = 'W',
X = 'X',
Y = 'Y',
Z = 'Z',
Lwin = 0x5B,
Rwin = 0x5C,
Apps = 0x5D,
Numpad0 = 0x60,
Numpad1 = 0x61,
Numpad2 = 0x62,
Numpad3 = 0x63,
Numpad4 = 0x64,
Numpad5 = 0x65,
Numpad6 = 0x66,
Numpad7 = 0x67,
Numpad8 = 0x68,
Numpad9 = 0x69,
Multiply = 0x6A,
Add = 0x6B,
Separator = 0x6C,
Subtract = 0x6D,
Decimal = 0x6E,
Divide = 0x6F,
F1 = 0x70,
F2 = 0x71,
F3 = 0x72,
F4 = 0x73,
F5 = 0x74,
F6 = 0x75,
F7 = 0x76,
F8 = 0x77,
F9 = 0x78,
F10 = 0x79,
F11 = 0x7A,
F12 = 0x7B,
F13 = 0x7C,
F14 = 0x7D,
F15 = 0x7E,
F16 = 0x7F,
F17 = 0x80,
F18 = 0x81,
F19 = 0x82,
F20 = 0x83,
F21 = 0x84,
F22 = 0x85,
F23 = 0x86,
F24 = 0x87,
Numlock = 0x90,
Scroll = 0x91,
Lshift = 0xA0,
Rshift = 0xA1,
Lcontrol = 0xA2,
Rcontrol = 0xA3,
Lmenu = 0xA4,
Rmenu = 0xA5,
ProcessKey = 0xE5,
Attn = 0xF6,
Crsel = 0xF7,
Exsel = 0xF8,
Ereof = 0xF9,
Play = 0xFA,
Zoom = 0xFB,
Noname = 0xFC,
Pa1 = 0xFD,
OemClear = 0xFE,
}
+75
View File
@@ -0,0 +1,75 @@
package thread
import "core:runtime"
import "core:sys/win32"
Thread_Proc :: #type proc(^Thread) -> int;
Thread_Os_Specific :: struct {
win32_thread: win32.Handle,
win32_thread_id: u32,
}
Thread :: struct {
using specific: Thread_Os_Specific,
procedure: Thread_Proc,
data: rawptr,
user_index: int,
init_context: runtime.Context,
use_init_context: bool,
}
create :: proc(procedure: Thread_Proc) -> ^Thread {
win32_thread_id: u32;
__windows_thread_entry_proc :: proc "c" (t: ^Thread) -> i32 {
c := context;
if t.use_init_context {
c = t.init_context;
}
context = c;
return i32(t.procedure(t));
}
win32_thread_proc := rawptr(__windows_thread_entry_proc);
thread := new(Thread);
win32_thread := win32.create_thread(nil, 0, win32_thread_proc, thread, win32.CREATE_SUSPENDED, &win32_thread_id);
if win32_thread == nil {
free(thread);
return nil;
}
thread.procedure = procedure;
thread.win32_thread = win32_thread;
thread.win32_thread_id = win32_thread_id;
return thread;
}
start :: proc(using thread: ^Thread) {
win32.resume_thread(win32_thread);
}
is_done :: proc(using thread: ^Thread) -> bool {
res := win32.wait_for_single_object(win32_thread, 0);
return res != win32.WAIT_TIMEOUT;
}
join :: proc(using thread: ^Thread) {
win32.wait_for_single_object(win32_thread, win32.INFINITE);
win32.close_handle(win32_thread);
win32_thread = win32.INVALID_HANDLE;
}
destroy :: proc(thread: ^Thread) {
join(thread);
free(thread);
}
terminate :: proc(using thread : ^Thread, exit_code : u32) {
win32.terminate_thread(win32_thread, exit_code);
}
-98
View File
@@ -1,98 +0,0 @@
proc is_signed(info: ^TypeInfo) -> bool {
if info == nil { return false; }
match i in type_info_base(info) {
case TypeInfo.Integer: return i.signed;
case TypeInfo.Float: return true;
}
return false;
}
proc is_integer(info: ^TypeInfo) -> bool {
if info == nil { return false; }
var _, ok = type_info_base(info).(^TypeInfo.Integer);
return ok;
}
proc is_float(info: ^TypeInfo) -> bool {
if info == nil { return false; }
var _, ok = type_info_base(info).(^TypeInfo.Float);
return ok;
}
proc is_complex(info: ^TypeInfo) -> bool {
if info == nil { return false; }
var _, ok = type_info_base(info).(^TypeInfo.Complex);
return ok;
}
proc is_any(info: ^TypeInfo) -> bool {
if info == nil { return false; }
var _, ok = type_info_base(info).(^TypeInfo.Any);
return ok;
}
proc is_string(info: ^TypeInfo) -> bool {
if info == nil { return false; }
var _, ok = type_info_base(info).(^TypeInfo.String);
return ok;
}
proc is_boolean(info: ^TypeInfo) -> bool {
if info == nil { return false; }
var _, ok = type_info_base(info).(^TypeInfo.Boolean);
return ok;
}
proc is_pointer(info: ^TypeInfo) -> bool {
if info == nil { return false; }
var _, ok = type_info_base(info).(^TypeInfo.Pointer);
return ok;
}
proc is_procedure(info: ^TypeInfo) -> bool {
if info == nil { return false; }
var _, ok = type_info_base(info).(^TypeInfo.Procedure);
return ok;
}
proc is_array(info: ^TypeInfo) -> bool {
if info == nil { return false; }
var _, ok = type_info_base(info).(^TypeInfo.Array);
return ok;
}
proc is_dynamic_array(info: ^TypeInfo) -> bool {
if info == nil { return false; }
var _, ok = type_info_base(info).(^TypeInfo.DynamicArray);
return ok;
}
proc is_dynamic_map(info: ^TypeInfo) -> bool {
if info == nil { return false; }
var _, ok = type_info_base(info).(^TypeInfo.Map);
return ok;
}
proc is_slice(info: ^TypeInfo) -> bool {
if info == nil { return false; }
var _, ok = type_info_base(info).(^TypeInfo.Slice);
return ok;
}
proc is_vector(info: ^TypeInfo) -> bool {
if info == nil { return false; }
var _, ok = type_info_base(info).(^TypeInfo.Vector);
return ok;
}
proc is_tuple(info: ^TypeInfo) -> bool {
if info == nil { return false; }
var _, ok = type_info_base(info).(^TypeInfo.Tuple);
return ok;
}
proc is_struct(info: ^TypeInfo) -> bool {
if info == nil { return false; }
var _, ok = type_info_base(info).(^TypeInfo.Struct);
return ok;
}
proc is_union(info: ^TypeInfo) -> bool {
if info == nil { return false; }
var _, ok = type_info_base(info).(^TypeInfo.Union);
return ok;
}
proc is_raw_union(info: ^TypeInfo) -> bool {
if info == nil { return false; }
var _, ok = type_info_base(info).(^TypeInfo.RawUnion);
return ok;
}
proc is_enum(info: ^TypeInfo) -> bool {
if info == nil { return false; }
var _, ok = type_info_base(info).(^TypeInfo.Enum);
return ok;
}
+269
View File
@@ -0,0 +1,269 @@
package types
import rt "core:runtime"
are_types_identical :: proc(a, b: ^rt.Type_Info) -> bool {
if a == b do return true;
if (a == nil && b != nil) ||
(a != nil && b == nil) {
return false;
}
switch {
case a.size != b.size, a.align != b.align:
return false;
}
switch x in a.variant {
case rt.Type_Info_Named:
y, ok := b.variant.(rt.Type_Info_Named);
if !ok do return false;
return x.base == y.base;
case rt.Type_Info_Integer:
y, ok := b.variant.(rt.Type_Info_Integer);
if !ok do return false;
return x.signed == y.signed;
case rt.Type_Info_Rune:
_, ok := b.variant.(rt.Type_Info_Rune);
return ok;
case rt.Type_Info_Float:
_, ok := b.variant.(rt.Type_Info_Float);
return ok;
case rt.Type_Info_Complex:
_, ok := b.variant.(rt.Type_Info_Complex);
return ok;
case rt.Type_Info_String:
_, ok := b.variant.(rt.Type_Info_String);
return ok;
case rt.Type_Info_Boolean:
_, ok := b.variant.(rt.Type_Info_Boolean);
return ok;
case rt.Type_Info_Any:
_, ok := b.variant.(rt.Type_Info_Any);
return ok;
case rt.Type_Info_Pointer:
y, ok := b.variant.(rt.Type_Info_Pointer);
if !ok do return false;
return are_types_identical(x.elem, y.elem);
case rt.Type_Info_Procedure:
y, ok := b.variant.(rt.Type_Info_Procedure);
if !ok do return false;
switch {
case x.variadic != y.variadic,
x.convention != y.convention:
return false;
}
return are_types_identical(x.params, y.params) && are_types_identical(x.results, y.results);
case rt.Type_Info_Array:
y, ok := b.variant.(rt.Type_Info_Array);
if !ok do return false;
if x.count != y.count do return false;
return are_types_identical(x.elem, y.elem);
case rt.Type_Info_Dynamic_Array:
y, ok := b.variant.(rt.Type_Info_Dynamic_Array);
if !ok do return false;
return are_types_identical(x.elem, y.elem);
case rt.Type_Info_Slice:
y, ok := b.variant.(rt.Type_Info_Slice);
if !ok do return false;
return are_types_identical(x.elem, y.elem);
case rt.Type_Info_Tuple:
y, ok := b.variant.(rt.Type_Info_Tuple);
if !ok do return false;
if len(x.types) != len(y.types) do return false;
for _, i in x.types {
xt, yt := x.types[i], y.types[i];
if !are_types_identical(xt, yt) {
return false;
}
}
return true;
case rt.Type_Info_Struct:
y, ok := b.variant.(rt.Type_Info_Struct);
if !ok do return false;
switch {
case len(x.types) != len(y.types),
x.is_packed != y.is_packed,
x.is_raw_union != y.is_raw_union,
x.custom_align != y.custom_align:
return false;
}
for _, i in x.types {
xn, yn := x.names[i], y.names[i];
xt, yt := x.types[i], y.types[i];
if xn != yn do return false;
if !are_types_identical(xt, yt) do return false;
}
return true;
case rt.Type_Info_Union:
y, ok := b.variant.(rt.Type_Info_Union);
if !ok do return false;
if len(x.variants) != len(y.variants) do return false;
for _, i in x.variants {
xv, yv := x.variants[i], y.variants[i];
if !are_types_identical(xv, yv) do return false;
}
return true;
case rt.Type_Info_Enum:
// NOTE(bill): Should be handled above
return false;
case rt.Type_Info_Map:
y, ok := b.variant.(rt.Type_Info_Map);
if !ok do return false;
return are_types_identical(x.key, y.key) && are_types_identical(x.value, y.value);
case rt.Type_Info_Bit_Field:
y, ok := b.variant.(rt.Type_Info_Bit_Field);
if !ok do return false;
if len(x.names) != len(y.names) do return false;
for _, i in x.names {
xb, yb := x.bits[i], y.bits[i];
xo, yo := x.offsets[i], y.offsets[i];
xn, yn := x.names[i], y.names[i];
if xb != yb do return false;
if xo != yo do return false;
if xn != yn do return false;
}
return true;
case rt.Type_Info_Bit_Set:
y, ok := b.variant.(rt.Type_Info_Bit_Set);
if !ok do return false;
return x.elem == y.elem && x.lower == y.lower && x.upper == y.upper;
case rt.Type_Info_Opaque:
y, ok := b.variant.(rt.Type_Info_Opaque);
if !ok do return false;
return x.elem == y.elem;
}
return false;
}
is_signed :: proc(info: ^rt.Type_Info) -> bool {
if info == nil do return false;
switch i in rt.type_info_base(info).variant {
case rt.Type_Info_Integer: return i.signed;
case rt.Type_Info_Float: return true;
}
return false;
}
is_integer :: proc(info: ^rt.Type_Info) -> bool {
if info == nil do return false;
_, ok := rt.type_info_base(info).variant.(rt.Type_Info_Integer);
return ok;
}
is_rune :: proc(info: ^rt.Type_Info) -> bool {
if info == nil do return false;
_, ok := rt.type_info_base(info).variant.(rt.Type_Info_Rune);
return ok;
}
is_float :: proc(info: ^rt.Type_Info) -> bool {
if info == nil do return false;
_, ok := rt.type_info_base(info).variant.(rt.Type_Info_Float);
return ok;
}
is_complex :: proc(info: ^rt.Type_Info) -> bool {
if info == nil do return false;
_, ok := rt.type_info_base(info).variant.(rt.Type_Info_Complex);
return ok;
}
is_any :: proc(info: ^rt.Type_Info) -> bool {
if info == nil do return false;
_, ok := rt.type_info_base(info).variant.(rt.Type_Info_Any);
return ok;
}
is_string :: proc(info: ^rt.Type_Info) -> bool {
if info == nil do return false;
_, ok := rt.type_info_base(info).variant.(rt.Type_Info_String);
return ok;
}
is_boolean :: proc(info: ^rt.Type_Info) -> bool {
if info == nil do return false;
_, ok := rt.type_info_base(info).variant.(rt.Type_Info_Boolean);
return ok;
}
is_pointer :: proc(info: ^rt.Type_Info) -> bool {
if info == nil do return false;
_, ok := rt.type_info_base(info).variant.(rt.Type_Info_Pointer);
return ok;
}
is_procedure :: proc(info: ^rt.Type_Info) -> bool {
if info == nil do return false;
_, ok := rt.type_info_base(info).variant.(rt.Type_Info_Procedure);
return ok;
}
is_array :: proc(info: ^rt.Type_Info) -> bool {
if info == nil do return false;
_, ok := rt.type_info_base(info).variant.(rt.Type_Info_Array);
return ok;
}
is_dynamic_array :: proc(info: ^rt.Type_Info) -> bool {
if info == nil do return false;
_, ok := rt.type_info_base(info).variant.(rt.Type_Info_Dynamic_Array);
return ok;
}
is_dynamic_map :: proc(info: ^rt.Type_Info) -> bool {
if info == nil do return false;
_, ok := rt.type_info_base(info).variant.(rt.Type_Info_Map);
return ok;
}
is_slice :: proc(info: ^rt.Type_Info) -> bool {
if info == nil do return false;
_, ok := rt.type_info_base(info).variant.(rt.Type_Info_Slice);
return ok;
}
is_tuple :: proc(info: ^rt.Type_Info) -> bool {
if info == nil do return false;
_, ok := rt.type_info_base(info).variant.(rt.Type_Info_Tuple);
return ok;
}
is_struct :: proc(info: ^rt.Type_Info) -> bool {
if info == nil do return false;
s, ok := rt.type_info_base(info).variant.(rt.Type_Info_Struct);
return ok && !s.is_raw_union;
}
is_raw_union :: proc(info: ^rt.Type_Info) -> bool {
if info == nil do return false;
s, ok := rt.type_info_base(info).variant.(rt.Type_Info_Struct);
return ok && s.is_raw_union;
}
is_union :: proc(info: ^rt.Type_Info) -> bool {
if info == nil do return false;
_, ok := rt.type_info_base(info).variant.(rt.Type_Info_Union);
return ok;
}
is_enum :: proc(info: ^rt.Type_Info) -> bool {
if info == nil do return false;
_, ok := rt.type_info_base(info).variant.(rt.Type_Info_Enum);
return ok;
}
is_opaque :: proc(info: ^rt.Type_Info) -> bool {
if info == nil do return false;
_, ok := rt.type_info_base(info).variant.(rt.Type_Info_Opaque);
return ok;
}
+81
View File
@@ -0,0 +1,81 @@
package utf16
REPLACEMENT_CHAR :: '\ufffd';
MAX_RUNE :: '\U0010ffff';
_surr1 :: 0xd800;
_surr2 :: 0xdc00;
_surr3 :: 0xe000;
_surr_self :: 0x10000;
is_surrogate :: proc(r: rune) -> bool {
return _surr1 <= r && r < _surr3;
}
decode_surrogate_pair :: proc(r1, r2: rune) -> rune {
if _surr1 <= r1 && r1 < _surr2 && _surr2 <= r2 && r2 < _surr3 {
return (r1-_surr1)<<10 | (r2 - _surr2) + _surr_self;
}
return REPLACEMENT_CHAR;
}
encode_surrogate_pair :: proc(r: rune) -> (r1, r2: rune) {
if r < _surr_self || r > MAX_RUNE {
return REPLACEMENT_CHAR, REPLACEMENT_CHAR;
}
r -= _surr_self;
return _surr1 + (r>>10)&0x3ff, _surr2 + r&0x3ff;
}
encode :: proc(d: []u16, s: []rune) -> int {
n, m := 0, len(d);
loop: for r in s {
switch r {
case 0.._surr1-1, _surr3 .. _surr_self-1:
if m+1 < n do break loop;
d[n] = u16(r);
n += 1;
case _surr_self .. MAX_RUNE:
if m+2 < n do break loop;
r1, r2 := encode_surrogate_pair(r);
d[n] = u16(r1);
d[n+1] = u16(r2);
n += 2;
case:
if m+1 < n do break loop;
d[n] = u16(REPLACEMENT_CHAR);
n += 1;
}
}
return n;
}
encode_string :: proc(d: []u16, s: string) -> int {
n, m := 0, len(d);
loop: for r in s {
switch r {
case 0.._surr1-1, _surr3 .. _surr_self-1:
if m+1 < n do break loop;
d[n] = u16(r);
n += 1;
case _surr_self .. MAX_RUNE:
if m+2 < n do break loop;
r1, r2 := encode_surrogate_pair(r);
d[n] = u16(r1);
d[n+1] = u16(r2);
n += 2;
case:
if m+1 < n do break loop;
d[n] = u16(REPLACEMENT_CHAR);
n += 1;
}
}
return n;
}
+268
View File
@@ -0,0 +1,268 @@
package utf8
RUNE_ERROR :: '\ufffd';
RUNE_SELF :: 0x80;
RUNE_BOM :: 0xfeff;
RUNE_EOF :: ~rune(0);
MAX_RUNE :: '\U0010ffff';
UTF_MAX :: 4;
SURROGATE_MIN :: 0xd800;
SURROGATE_MAX :: 0xdfff;
T1 :: 0b0000_0000;
TX :: 0b1000_0000;
T2 :: 0b1100_0000;
T3 :: 0b1110_0000;
T4 :: 0b1111_0000;
T5 :: 0b1111_1000;
MASKX :: 0b0011_1111;
MASK2 :: 0b0001_1111;
MASK3 :: 0b0000_1111;
MASK4 :: 0b0000_0111;
RUNE1_MAX :: 1<<7 - 1;
RUNE2_MAX :: 1<<11 - 1;
RUNE3_MAX :: 1<<16 - 1;
// The default lowest and highest continuation byte.
LOCB :: 0b1000_0000;
HICB :: 0b1011_1111;
Accept_Range :: struct {lo, hi: u8};
accept_ranges := [5]Accept_Range{
{0x80, 0xbf},
{0xa0, 0xbf},
{0x80, 0x9f},
{0x90, 0xbf},
{0x80, 0x8f},
};
accept_sizes := [256]u8{
0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, // 0x00-0x0f
0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, // 0x10-0x1f
0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, // 0x20-0x2f
0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, // 0x30-0x3f
0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, // 0x40-0x4f
0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, // 0x50-0x5f
0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, // 0x60-0x6f
0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, // 0x70-0x7f
0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, // 0x80-0x8f
0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, // 0x90-0x9f
0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, // 0xa0-0xaf
0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, // 0xb0-0xbf
0xf1, 0xf1, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, // 0xc0-0xcf
0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, // 0xd0-0xdf
0x13, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x23, 0x03, 0x03, // 0xe0-0xef
0x34, 0x04, 0x04, 0x04, 0x44, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, // 0xf0-0xff
};
encode_rune :: proc(r: rune) -> ([4]u8, int) {
buf: [4]u8;
i := u32(r);
mask :: u8(0x3f);
if i <= 1<<7-1 {
buf[0] = u8(r);
return buf, 1;
}
if i <= 1<<11-1 {
buf[0] = 0xc0 | u8(r>>6);
buf[1] = 0x80 | u8(r) & mask;
return buf, 2;
}
// Invalid or Surrogate range
if i > 0x0010ffff ||
(0xd800 <= i && i <= 0xdfff) {
r = 0xfffd;
}
if i <= 1<<16-1 {
buf[0] = 0xe0 | u8(r>>12);
buf[1] = 0x80 | u8(r>>6) & mask;
buf[2] = 0x80 | u8(r) & mask;
return buf, 3;
}
buf[0] = 0xf0 | u8(r>>18);
buf[1] = 0x80 | u8(r>>12) & mask;
buf[2] = 0x80 | u8(r>>6) & mask;
buf[3] = 0x80 | u8(r) & mask;
return buf, 4;
}
decode_rune_from_string :: inline proc(s: string) -> (rune, int) do return decode_rune(cast([]u8)s);
decode_rune :: proc(s: []u8) -> (rune, int) {
n := len(s);
if n < 1 {
return RUNE_ERROR, 0;
}
s0 := s[0];
x := accept_sizes[s0];
if x >= 0xF0 {
mask := rune(x) << 31 >> 31; // NOTE(bill): Create 0x0000 or 0xffff.
return rune(s[0])&~mask | RUNE_ERROR&mask, 1;
}
sz := x & 7;
accept := accept_ranges[x>>4];
if n < int(sz) {
return RUNE_ERROR, 1;
}
b1 := s[1];
if b1 < accept.lo || accept.hi < b1 {
return RUNE_ERROR, 1;
}
if sz == 2 {
return rune(s0&MASK2)<<6 | rune(b1&MASKX), 2;
}
b2 := s[2];
if b2 < LOCB || HICB < b2 {
return RUNE_ERROR, 1;
}
if sz == 3 {
return rune(s0&MASK3)<<12 | rune(b1&MASKX)<<6 | rune(b2&MASKX), 3;
}
b3 := s[3];
if b3 < LOCB || HICB < b3 {
return RUNE_ERROR, 1;
}
return rune(s0&MASK4)<<18 | rune(b1&MASKX)<<12 | rune(b2&MASKX)<<6 | rune(b3&MASKX), 4;
}
decode_last_rune_from_string :: inline proc(s: string) -> (rune, int) do return decode_last_rune(cast([]u8)s);
decode_last_rune :: proc(s: []u8) -> (rune, int) {
r: rune;
size: int;
start, end, limit: int;
end = len(s);
if end == 0 {
return RUNE_ERROR, 0;
}
start = end-1;
r = rune(s[start]);
if r < RUNE_SELF {
return r, 1;
}
limit = max(end - UTF_MAX, 0);
for start-=1; start >= limit; start-=1 {
if rune_start(s[start]) do break;
}
start = max(start, 0);
r, size = decode_rune(s[start:end]);
if start+size != end {
return RUNE_ERROR, 1;
}
return r, size;
}
valid_rune :: proc(r: rune) -> bool {
if r < 0 {
return false;
} else if SURROGATE_MIN <= r && r <= SURROGATE_MAX {
return false;
} else if r > MAX_RUNE {
return false;
}
return true;
}
valid_string :: proc(s: string) -> bool {
n := len(s);
for i := 0; i < n; {
si := s[i];
if si < RUNE_SELF { // ascii
i += 1;
continue;
}
x := accept_sizes[si];
if x == 0xf1 {
return false;
}
size := int(x & 7);
if i+size > n {
return false;
}
ar := accept_ranges[x>>4];
if b := s[i+1]; b < ar.lo || ar.hi < b {
return false;
} else if size == 2 {
// Okay
} else if b := s[i+2]; b < 0x80 || 0xbf < b {
return false;
} else if size == 3 {
// Okay
} else if b := s[i+3]; b < 0x80 || 0xbf < b {
return false;
}
i += size;
}
return true;
}
rune_start :: inline proc(b: u8) -> bool do return b&0xc0 != 0x80;
rune_count_from_string :: inline proc(s: string) -> int do return rune_count(cast([]u8)s);
rune_count :: proc(s: []u8) -> int {
count := 0;
n := len(s);
for i := 0; i < n; {
defer count += 1;
si := s[i];
if si < RUNE_SELF { // ascii
i += 1;
continue;
}
x := accept_sizes[si];
if x == 0xf1 {
i += 1;
continue;
}
size := int(x & 7);
if i+size > n {
i += 1;
continue;
}
ar := accept_ranges[x>>4];
if b := s[i+1]; b < ar.lo || ar.hi < b {
size = 1;
} else if size == 2 {
// Okay
} else if b := s[i+2]; b < 0x80 || 0xbf < b {
size = 1;
} else if size == 3 {
// Okay
} else if b := s[i+3]; b < 0x80 || 0xbf < b {
size = 1;
}
i += size;
}
return count;
}
rune_size :: proc(r: rune) -> int {
switch {
case r < 0: return -1;
case r <= 1<<7 - 1: return 1;
case r <= 1<<11 - 1: return 2;
case SURROGATE_MIN <= r && r <= SURROGATE_MAX: return -1;
case r <= 1<<16 - 1: return 3;
case r <= MAX_RUNE: return 4;
}
return -1;
}
-59
View File
@@ -1,59 +0,0 @@
const (
REPLACEMENT_CHAR = '\uFFFD';
MAX_RUNE = '\U0010FFFF';
_surr1 = 0xd800;
_surr2 = 0xdc00;
_surr3 = 0xe000;
_surr_self = 0x10000;
)
proc is_surrogate(r: rune) -> bool {
return _surr1 <= r && r < _surr3;
}
proc decode_surrogate_pair(r1, r2: rune) -> rune {
if _surr1 <= r1 && r1 < _surr2 && _surr2 <= r2 && r2 < _surr3 {
return (r1-_surr1)<<10 | (r2 - _surr2) + _surr_self;
}
return REPLACEMENT_CHAR;
}
proc encode_surrogate_pair(r: rune) -> (r1, r2: rune) {
if r < _surr_self || r > MAX_RUNE {
return REPLACEMENT_CHAR, REPLACEMENT_CHAR;
}
r -= _surr_self;
return _surr1 + (r>>10)&0x3ff, _surr2 + r&0x3ff;
}
proc encode(d: []u16, s: []rune) {
var n = len(s);
for r in s {
if r >= _surr_self {
n++;
}
}
var max_n = min(len(d), n);
n = 0;
for r in s {
match r {
case 0..<_surr1, _surr3..<_surr_self:
d[n] = u16(r);
n++;
case _surr_self..MAX_RUNE:
var r1, r2 = encode_surrogate_pair(r);
d[n] = u16(r1);
d[n+1] = u16(r2);
n += 2;
case:
d[n] = u16(REPLACEMENT_CHAR);
n++;
}
}
}
-274
View File
@@ -1,274 +0,0 @@
const (
RUNE_ERROR = '\ufffd';
RUNE_SELF = 0x80;
RUNE_BOM = 0xfeff;
RUNE_EOF = ~rune(0);
MAX_RUNE = '\U0010ffff';
UTF_MAX = 4;
SURROGATE_MIN = 0xd800;
SURROGATE_MAX = 0xdfff;
T1 = 0b0000_0000;
TX = 0b1000_0000;
T2 = 0b1100_0000;
T3 = 0b1110_0000;
T4 = 0b1111_0000;
T5 = 0b1111_1000;
MASKX = 0b0011_1111;
MASK2 = 0b0001_1111;
MASK3 = 0b0000_1111;
MASK4 = 0b0000_0111;
RUNE1_MAX = 1<<7 - 1;
RUNE2_MAX = 1<<11 - 1;
RUNE3_MAX = 1<<16 - 1;
// The default lowest and highest continuation byte.
LOCB = 0b1000_0000;
HICB = 0b1011_1111;
)
type AcceptRange struct { lo, hi: u8 }
var (
accept_ranges = [5]AcceptRange{
{0x80, 0xbf},
{0xa0, 0xbf},
{0x80, 0x9f},
{0x90, 0xbf},
{0x80, 0x8f},
};
accept_sizes = [256]u8{
0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, // 0x00-0x0f
0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, // 0x10-0x1f
0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, // 0x20-0x2f
0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, // 0x30-0x3f
0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, // 0x40-0x4f
0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, // 0x50-0x5f
0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, // 0x60-0x6f
0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, // 0x70-0x7f
0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, // 0x80-0x8f
0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, // 0x90-0x9f
0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, // 0xa0-0xaf
0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, // 0xb0-0xbf
0xf1, 0xf1, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, // 0xc0-0xcf
0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, // 0xd0-0xdf
0x13, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x23, 0x03, 0x03, // 0xe0-0xef
0x34, 0x04, 0x04, 0x04, 0x44, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, // 0xf0-0xff
};
)
proc encode_rune(r: rune) -> ([4]u8, int) {
var buf: [4]u8;
var i = u32(r);
const mask: u8 = 0x3f;
if i <= 1<<7-1 {
buf[0] = u8(r);
return buf, 1;
}
if i <= 1<<11-1 {
buf[0] = 0xc0 | u8(r>>6);
buf[1] = 0x80 | u8(r) & mask;
return buf, 2;
}
// Invalid or Surrogate range
if i > 0x0010ffff ||
(0xd800 <= i && i <= 0xdfff) {
r = 0xfffd;
}
if i <= 1<<16-1 {
buf[0] = 0xe0 | u8(r>>12);
buf[1] = 0x80 | u8(r>>6) & mask;
buf[2] = 0x80 | u8(r) & mask;
return buf, 3;
}
buf[0] = 0xf0 | u8(r>>18);
buf[1] = 0x80 | u8(r>>12) & mask;
buf[2] = 0x80 | u8(r>>6) & mask;
buf[3] = 0x80 | u8(r) & mask;
return buf, 4;
}
proc decode_rune(s: string) -> (rune, int) #inline { return decode_rune([]u8(s)); }
proc decode_rune(s: []u8) -> (rune, int) {
var n = len(s);
if n < 1 {
return RUNE_ERROR, 0;
}
var s0 = s[0];
var x = accept_sizes[s0];
if x >= 0xF0 {
var mask = rune(x) << 31 >> 31; // NOTE(bill): Create 0x0000 or 0xffff.
return rune(s[0])&~mask | RUNE_ERROR&mask, 1;
}
var sz = x & 7;
var accept = accept_ranges[x>>4];
if n < int(sz) {
return RUNE_ERROR, 1;
}
var b1 = s[1];
if b1 < accept.lo || accept.hi < b1 {
return RUNE_ERROR, 1;
}
if sz == 2 {
return rune(s0&MASK2)<<6 | rune(b1&MASKX), 2;
}
var b2 = s[2];
if b2 < LOCB || HICB < b2 {
return RUNE_ERROR, 1;
}
if sz == 3 {
return rune(s0&MASK3)<<12 | rune(b1&MASKX)<<6 | rune(b2&MASKX), 3;
}
var b3 = s[3];
if b3 < LOCB || HICB < b3 {
return RUNE_ERROR, 1;
}
return rune(s0&MASK4)<<18 | rune(b1&MASKX)<<12 | rune(b2&MASKX)<<6 | rune(b3&MASKX), 4;
}
proc decode_last_rune(s: string) -> (rune, int) #inline { return decode_last_rune([]u8(s)); }
proc decode_last_rune(s: []u8) -> (rune, int) {
var r: rune;
var size: int;
var start, end, limit: int;
end = len(s);
if end == 0 {
return RUNE_ERROR, 0;
}
start = end-1;
r = rune(s[start]);
if r < RUNE_SELF {
return r, 1;
}
limit = max(end - UTF_MAX, 0);
start--;
for start >= limit {
if rune_start(s[start]) {
break;
}
start--;
}
start = max(start, 0);
r, size = decode_rune(s[start..<end]);
if start+size != end {
return RUNE_ERROR, 1;
}
return r, size;
}
proc valid_rune(r: rune) -> bool {
if r < 0 {
return false;
} else if SURROGATE_MIN <= r && r <= SURROGATE_MAX {
return false;
} else if r > MAX_RUNE {
return false;
}
return true;
}
proc valid_string(s: string) -> bool {
var n = len(s);
for var i = 0; i < n; {
var si = s[i];
if si < RUNE_SELF { // ascii
i++;
continue;
}
var x = accept_sizes[si];
if x == 0xf1 {
return false;
}
var size = int(x & 7);
if i+size > n {
return false;
}
var ar = accept_ranges[x>>4];
if var b = s[i+1]; b < ar.lo || ar.hi < b {
return false;
} else if size == 2 {
// Okay
} else if var b = s[i+2]; b < 0x80 || 0xbf < b {
return false;
} else if size == 3 {
// Okay
} else if var b = s[i+3]; b < 0x80 || 0xbf < b {
return false;
}
i += size;
}
return true;
}
proc rune_start(b: u8) -> bool #inline { return b&0xc0 != 0x80; }
proc rune_count(s: string) -> int #inline { return rune_count([]u8(s)); }
proc rune_count(s: []u8) -> int {
var count = 0;
var n = len(s);
for var i = 0; i < n; {
defer count++;
var si = s[i];
if si < RUNE_SELF { // ascii
i++;
continue;
}
var x = accept_sizes[si];
if x == 0xf1 {
i++;
continue;
}
var size = int(x & 7);
if i+size > n {
i++;
continue;
}
var ar = accept_ranges[x>>4];
if var b = s[i+1]; b < ar.lo || ar.hi < b {
size = 1;
} else if size == 2 {
// Okay
} else if var b = s[i+2]; b < 0x80 || 0xbf < b {
size = 1;
} else if size == 3 {
// Okay
} else if var b = s[i+3]; b < 0x80 || 0xbf < b {
size = 1;
}
i += size;
}
return count;
}
proc rune_size(r: rune) -> int {
match {
case r < 0: return -1;
case r <= 1<<7 - 1: return 1;
case r <= 1<<11 - 1: return 2;
case SURROGATE_MIN <= r && r <= SURROGATE_MAX: return -1;
case r <= 1<<16 - 1: return 3;
case r <= MAX_RUNE: return 4;
}
return -1;
}
+859
View File
@@ -0,0 +1,859 @@
package main
import "core:fmt"
import "core:strconv"
import "core:mem"
import "core:bits"
import "core:hash"
import "core:math"
import "core:math/rand"
import "core:os"
import "core:sort"
import "core:strings"
import "core:types"
import "core:unicode/utf16"
import "core:unicode/utf8"
import "core:c"
import "core:runtime"
when os.OS == "windows" {
import "core:thread"
import "core:sys/win32"
}
@(link_name="general_stuff")
general_stuff :: proc() {
fmt.println("# general_stuff");
{ // `do` for inline statements rather than block
foo :: proc() do fmt.println("Foo!");
if false do foo();
for false do foo();
when false do foo();
if false do foo();
else do foo();
}
{ // Removal of `++` and `--` (again)
x: int;
x += 1;
x -= 1;
}
{ // Casting syntaxes
i := i32(137);
ptr := &i;
_ = (^f32)(ptr);
// ^f32(ptr) == ^(f32(ptr))
_ = cast(^f32)ptr;
_ = (^f32)(ptr)^;
_ = (cast(^f32)ptr)^;
// Questions: Should there be two ways to do it?
}
/*
* Remove *_val_of built-in procedures
* size_of, align_of, offset_of
* type_of, type_info_of
*/
{ // `expand_to_tuple` built-in procedure
Foo :: struct {
x: int,
b: bool,
}
f := Foo{137, true};
x, b := expand_to_tuple(f);
fmt.println(f);
fmt.println(x, b);
fmt.println(expand_to_tuple(f));
}
{
// .. open range
for in 0..2 {} // 0, 1, 2
}
{ // Multiple sized booleans
x0: bool; // default
x1: b8 = true;
x2: b16 = false;
x3: b32 = true;
x4: b64 = false;
fmt.printf("x0: %T = %v;\n", x0, x0);
fmt.printf("x1: %T = %v;\n", x1, x1);
fmt.printf("x2: %T = %v;\n", x2, x2);
fmt.printf("x3: %T = %v;\n", x3, x3);
fmt.printf("x4: %T = %v;\n", x4, x4);
// Having specific sized booleans is very useful when dealing with foreign code
// and to enforce specific alignment for a boolean, especially within a struct
}
{ // `distinct` types
// Originally, all type declarations would create a distinct type unless #type_alias was present.
// Now the behaviour has been reversed. All type declarations create a type alias unless `distinct` is present.
// If the type expression is `struct`, `union`, `enum`, `proc`, or `bit_field`, the types will always been distinct.
Int32 :: i32;
#assert(Int32 == i32);
My_Int32 :: distinct i32;
#assert(My_Int32 != i32);
My_Struct :: struct{x: int};
#assert(My_Struct != struct{x: int});
}
{
X :: 123;
when #defined(X) {
fmt.println("X is defined");
} else {
fmt.println("X is not defined");
}
when #defined(Y) {
fmt.println("Y is defined");
} else {
fmt.println("Y is not defined");
}
}
}
union_type :: proc() {
fmt.println("\n# union_type");
{
val: union{int, bool};
val = 137;
if i, ok := val.(int); ok {
fmt.println(i);
}
val = true;
fmt.println(val);
val = nil;
switch v in val {
case int: fmt.println("int", v);
case bool: fmt.println("bool", v);
case: fmt.println("nil");
}
}
{
// There is a duality between `any` and `union`
// An `any` has a pointer to the data and allows for any type (open)
// A `union` has as binary blob to store the data and allows only certain types (closed)
// The following code is with `any` but has the same syntax
val: any;
val = 137;
if i, ok := val.(int); ok {
fmt.println(i);
}
val = true;
fmt.println(val);
val = nil;
switch v in val {
case int: fmt.println("int", v);
case bool: fmt.println("bool", v);
case: fmt.println("nil");
}
}
Vector3 :: struct {x, y, z: f32};
Quaternion :: struct {x, y, z, w: f32};
// More realistic examples
{
// NOTE(bill): For the above basic examples, you may not have any
// particular use for it. However, my main use for them is not for these
// simple cases. My main use is for hierarchical types. Many prefer
// subtyping, embedding the base data into the derived types. Below is
// an example of this for a basic game Entity.
Entity :: struct {
id: u64,
name: string,
position: Vector3,
orientation: Quaternion,
derived: any,
}
Frog :: struct {
using entity: Entity,
jump_height: f32,
}
Monster :: struct {
using entity: Entity,
is_robot: bool,
is_zombie: bool,
}
// See `parametric_polymorphism` procedure for details
new_entity :: proc($T: typeid) -> ^Entity {
t := new(T);
t.derived = t^;
return t;
}
entity := new_entity(Monster);
switch e in entity.derived {
case Frog:
fmt.println("Ribbit");
case Monster:
if e.is_robot do fmt.println("Robotic");
if e.is_zombie do fmt.println("Grrrr!");
}
}
{
// NOTE(bill): A union can be used to achieve something similar. Instead
// of embedding the base data into the derived types, the derived data
// in embedded into the base type. Below is the same example of the
// basic game Entity but using an union.
Entity :: struct {
id: u64,
name: string,
position: Vector3,
orientation: Quaternion,
derived: union {Frog, Monster},
}
Frog :: struct {
using entity: ^Entity,
jump_height: f32,
}
Monster :: struct {
using entity: ^Entity,
is_robot: bool,
is_zombie: bool,
}
// See `parametric_polymorphism` procedure for details
new_entity :: proc($T: typeid) -> ^Entity {
t := new(Entity);
t.derived = T{entity = t};
return t;
}
entity := new_entity(Monster);
switch e in entity.derived {
case Frog:
fmt.println("Ribbit");
case Monster:
if e.is_robot do fmt.println("Robotic");
if e.is_zombie do fmt.println("Grrrr!");
}
// NOTE(bill): As you can see, the usage code has not changed, only its
// memory layout. Both approaches have their own advantages but they can
// be used together to achieve different results. The subtyping approach
// can allow for a greater control of the memory layout and memory
// allocation, e.g. storing the derivatives together. However, this is
// also its disadvantage. You must either preallocate arrays for each
// derivative separation (which can be easily missed) or preallocate a
// bunch of "raw" memory; determining the maximum size of the derived
// types would require the aid of metaprogramming. Unions solve this
// particular problem as the data is stored with the base data.
// Therefore, it is possible to preallocate, e.g. [100]Entity.
// It should be noted that the union approach can have the same memory
// layout as the any and with the same type restrictions by using a
// pointer type for the derivatives.
/*
Entity :: struct {
..
derived: union{^Frog, ^Monster},
}
Frog :: struct {
using entity: Entity,
..
}
Monster :: struct {
using entity: Entity,
..
}
new_entity :: proc(T: type) -> ^Entity {
t := new(T);
t.derived = t;
return t;
}
*/
}
}
parametric_polymorphism :: proc() {
fmt.println("# parametric_polymorphism");
print_value :: proc(value: $T) {
fmt.printf("print_value: %T %v\n", value, value);
}
v1: int = 1;
v2: f32 = 2.1;
v3: f64 = 3.14;
v4: string = "message";
print_value(v1);
print_value(v2);
print_value(v3);
print_value(v4);
fmt.println();
add :: proc(p, q: $T) -> T {
x: T = p + q;
return x;
}
a := add(3, 4);
fmt.printf("a: %T = %v\n", a, a);
b := add(3.2, 4.3);
fmt.printf("b: %T = %v\n", b, b);
// This is how `new` is implemented
alloc_type :: proc($T: typeid) -> ^T {
t := cast(^T)alloc(size_of(T), align_of(T));
t^ = T{}; // Use default initialization value
return t;
}
copy_slice :: proc(dst, src: []$T) -> int {
n := min(len(dst), len(src));
if n > 0 {
mem.copy(&dst[0], &src[0], n*size_of(T));
}
return n;
}
double_params :: proc(a: $A, b: $B) -> A {
return a + A(b);
}
fmt.println(double_params(12, 1.345));
{ // Polymorphic Types and Type Specialization
Table_Slot :: struct(Key, Value: typeid) {
occupied: bool,
hash: u32,
key: Key,
value: Value,
}
TABLE_SIZE_MIN :: 32;
Table :: struct(Key, Value: typeid) {
count: int,
allocator: mem.Allocator,
slots: []Table_Slot(Key, Value),
}
// Only allow types that are specializations of a (polymorphic) slice
make_slice :: proc($T: typeid/[]$E, len: int) -> T {
return make(T, len);
}
// Only allow types that are specializations of `Table`
allocate :: proc(table: ^$T/Table, capacity: int) {
c := context;
if table.allocator.procedure != nil do c.allocator = table.allocator;
context = c;
table.slots = make_slice(type_of(table.slots), max(capacity, TABLE_SIZE_MIN));
}
expand :: proc(table: ^$T/Table) {
c := context;
if table.allocator.procedure != nil do c.allocator = table.allocator;
context = c;
old_slots := table.slots;
defer delete(old_slots);
cap := max(2*len(table.slots), TABLE_SIZE_MIN);
allocate(table, cap);
for s in old_slots do if s.occupied {
put(table, s.key, s.value);
}
}
// Polymorphic determination of a polymorphic struct
// put :: proc(table: ^$T/Table, key: T.Key, value: T.Value) {
put :: proc(table: ^Table($Key, $Value), key: Key, value: Value) {
hash := get_hash(key); // Ad-hoc method which would fail in a different scope
index := find_index(table, key, hash);
if index < 0 {
if f64(table.count) >= 0.75*f64(len(table.slots)) {
expand(table);
}
assert(table.count <= len(table.slots));
index = int(hash % u32(len(table.slots)));
for table.slots[index].occupied {
if index += 1; index >= len(table.slots) {
index = 0;
}
}
table.count += 1;
}
slot := &table.slots[index];
slot.occupied = true;
slot.hash = hash;
slot.key = key;
slot.value = value;
}
// find :: proc(table: ^$T/Table, key: T.Key) -> (T.Value, bool) {
find :: proc(table: ^Table($Key, $Value), key: Key) -> (Value, bool) {
hash := get_hash(key);
index := find_index(table, key, hash);
if index < 0 {
return Value{}, false;
}
return table.slots[index].value, true;
}
find_index :: proc(table: ^Table($Key, $Value), key: Key, hash: u32) -> int {
if len(table.slots) <= 0 do return -1;
index := int(hash % u32(len(table.slots)));
for table.slots[index].occupied {
if table.slots[index].hash == hash {
if table.slots[index].key == key {
return index;
}
}
if index += 1; index >= len(table.slots) {
index = 0;
}
}
return -1;
}
get_hash :: proc(s: string) -> u32 { // fnv32a
h: u32 = 0x811c9dc5;
for i in 0..len(s)-1 {
h = (h ~ u32(s[i])) * 0x01000193;
}
return h;
}
table: Table(string, int);
for i in 0..36 do put(&table, "Hellope", i);
for i in 0..42 do put(&table, "World!", i);
found, _ := find(&table, "Hellope");
fmt.printf("`found` is %v\n", found);
found, _ = find(&table, "World!");
fmt.printf("`found` is %v\n", found);
// I would not personally design a hash table like this in production
// but this is a nice basic example
// A better approach would either use a `u64` or equivalent for the key
// and let the user specify the hashing function or make the user store
// the hashing procedure with the table
}
{ // Parametric polymorphic union
Error :: enum {
Foo0,
Foo1,
Foo2,
Foo3,
}
Para_Union :: union(T: typeid) {T, Error};
r: Para_Union(int);
fmt.println(typeid_of(type_of(r)));
fmt.println(r);
r = 123;
fmt.println(r);
r = Error.Foo0;
fmt.println(r);
}
{ // Polymorphic names
foo :: proc($N: $I, $T: typeid) -> (res: [N]T) {
// `N` is the constant value passed
// `I` is the type of N
// `T` is the type passed
fmt.printf("Generating an array of type %v from the value %v of type %v\n",
typeid_of(type_of(res)), N, typeid_of(I));
for i in 0..N-1 {
res[i] = i*i;
}
return;
}
T :: int;
array := foo(4, T);
for v, i in array {
assert(v == T(i*i));
}
}
}
prefix_table := [?]string{
"White",
"Red",
"Green",
"Blue",
"Octarine",
"Black",
};
threading_example :: proc() {
when os.OS == "windows" {
fmt.println("# threading_example");
unordered_remove :: proc(array: ^$D/[dynamic]$T, index: int, loc := #caller_location) {
runtime.bounds_check_error_loc(loc, index, len(array));
n := len(array)-1;
if index != n {
array[index] = array[n];
}
pop(array);
}
ordered_remove :: proc(array: ^$D/[dynamic]$T, index: int, loc := #caller_location) {
runtime.bounds_check_error_loc(loc, index, len(array));
copy(array[index:], array[index+1:]);
pop(array);
}
worker_proc :: proc(t: ^thread.Thread) -> int {
for iteration in 1..5 {
fmt.printf("Thread %d is on iteration %d\n", t.user_index, iteration);
fmt.printf("`%s`: iteration %d\n", prefix_table[t.user_index], iteration);
// win32.sleep(1);
}
return 0;
}
threads := make([dynamic]^thread.Thread, 0, len(prefix_table));
defer delete(threads);
for in prefix_table {
if t := thread.create(worker_proc); t != nil {
t.init_context = context;
t.use_init_context = true;
t.user_index = len(threads);
append(&threads, t);
thread.start(t);
}
}
for len(threads) > 0 {
for i := 0; i < len(threads); /**/ {
if t := threads[i]; thread.is_done(t) {
fmt.printf("Thread %d is done\n", t.user_index);
thread.destroy(t);
ordered_remove(&threads, i);
} else {
i += 1;
}
}
}
}
}
array_programming :: proc() {
fmt.println("# array_programming");
{
a := [3]f32{1, 2, 3};
b := [3]f32{5, 6, 7};
c := a * b;
d := a + b;
e := 1 + (c - d) / 2;
fmt.printf("%.1f\n", e); // [0.5, 3.0, 6.5]
}
{
a := [3]f32{1, 2, 3};
b := swizzle(a, 2, 1, 0);
assert(b == [3]f32{3, 2, 1});
c := swizzle(a, 0, 0);
assert(c == [2]f32{1, 1});
assert(c == 1);
}
{
Vector3 :: distinct [3]f32;
a := Vector3{1, 2, 3};
b := Vector3{5, 6, 7};
c := (a * b)/2 + 1;
d := c.x + c.y + c.z;
fmt.printf("%.1f\n", d); // 22.0
cross :: proc(a, b: Vector3) -> Vector3 {
i := swizzle(a, 1, 2, 0) * swizzle(b, 2, 0, 1);
j := swizzle(a, 2, 0, 1) * swizzle(b, 1, 2, 0);
return i - j;
}
blah :: proc(a: Vector3) -> f32 {
return a.x + a.y + a.z;
}
x := cross(a, b);
fmt.println(x);
fmt.println(blah(x));
}
}
named_proc_return_parameters :: proc() {
fmt.println("# named proc return parameters");
foo0 :: proc() -> int {
return 123;
}
foo1 :: proc() -> (a: int) {
a = 123;
return;
}
foo2 :: proc() -> (a, b: int) {
// Named return values act like variables within the scope
a = 321;
b = 567;
return b, a;
}
fmt.println("foo0 =", foo0()); // 123
fmt.println("foo1 =", foo1()); // 123
fmt.println("foo2 =", foo2()); // 567 321
}
using_enum :: proc() {
fmt.println("# using enum");
using Foo :: enum {A, B, C};
f0 := A;
f1 := B;
f2 := C;
fmt.println(f0, f1, f2);
fmt.println(len(Foo));
// Non-comparsion operations are not allowed with enum
// You must convert to an integer if you want to do this
// x := f0 + f1;
y := int(f0) + int(f1);
}
explicit_procedure_overloading :: proc() {
fmt.println("# explicit procedure overloading");
add_ints :: proc(a, b: int) -> int {
x := a + b;
fmt.println("add_ints", x);
return x;
}
add_floats :: proc(a, b: f32) -> f32 {
x := a + b;
fmt.println("add_floats", x);
return x;
}
add_numbers :: proc(a: int, b: f32, c: u8) -> int {
x := int(a) + int(b) + int(c);
fmt.println("add_numbers", x);
return x;
}
add :: proc[add_ints, add_floats, add_numbers];
add(int(1), int(2));
add(f32(1), f32(2));
add(int(1), f32(2), u8(3));
add(1, 2); // untyped ints coerce to int tighter than f32
add(1.0, 2.0); // untyped floats coerce to f32 tighter than int
add(1, 2, 3); // three parameters
// Ambiguous answers
// add(1.0, 2);
// add(1, 2.0);
}
complete_switch :: proc() {
fmt.println("# complete_switch");
{ // enum
using Foo :: enum {
A,
B,
C,
D,
}
b := Foo.B;
f := Foo.A;
#complete switch f {
case A: fmt.println("A");
case B: fmt.println("B");
case C: fmt.println("C");
case D: fmt.println("D");
case: fmt.println("?");
}
}
{ // union
Foo :: union {int, bool};
f: Foo = 123;
#complete switch in f {
case int: fmt.println("int");
case bool: fmt.println("bool");
case:
}
}
}
cstring_example :: proc() {
W :: "Hellope";
X :: cstring(W);
Y :: string(X);
w := W;
x: cstring = X;
y: string = Y;
z := string(x);
fmt.println(x, y, z);
fmt.println(len(x), len(y), len(z));
fmt.println(len(W), len(X), len(Y));
// IMPORTANT NOTE for cstring variables
// len(cstring) is O(N)
// cast(cstring)string is O(N)
}
deprecated_attribute :: proc() {
@(deprecated="Use foo_v2 instead")
foo_v1 :: proc(x: int) {
fmt.println("foo_v1");
}
foo_v2 :: proc(x: int) {
fmt.println("foo_v2");
}
// NOTE: Uncomment to see the warning messages
// foo_v1(1);
}
bit_set_type :: proc() {
{
using Day :: enum {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
}
Days :: distinct bit_set[Day];
WEEKEND :: Days{Sunday, Saturday};
d: Days;
d = {Sunday, Monday};
x := Tuesday;
e := d | WEEKEND;
e |= {Monday};
fmt.println(d, e);
ok := Saturday in e; // `in` is only allowed for `map` and `bit_set` types
fmt.println(ok);
if Saturday in e {
fmt.println("Saturday in", e);
}
X :: Saturday in WEEKEND; // Constant evaluation
fmt.println(X);
}
{
x: bit_set['A'..'Z'];
assert(size_of(x) == size_of(u32));
y: bit_set[0..8; u16];
fmt.println(typeid_of(type_of(x))); // bit_set[A..Z]
fmt.println(typeid_of(type_of(y))); // bit_set[0..8; u16]
incl(&x, 'F');
assert('F' in x);
excl(&x, 'F');
assert(!('F' in x));
y |= {1, 4, 2};
assert(2 in y);
}
{
Letters :: bit_set['A'..'Z'];
a := Letters{'A', 'B'};
b := Letters{'A', 'B', 'C', 'D', 'F'};
c := Letters{'A', 'B'};
assert(a <= b); // 'a' is a subset of 'b'
assert(b >= a); // 'b' is a superset of 'a'
assert(a < b); // 'a' is a strict subset of 'b'
assert(b > a); // 'b' is a strict superset of 'a'
assert(!(a < c)); // 'a' is a not strict subset of 'c'
assert(!(c > a)); // 'c' is a not strict superset of 'a'
}
}
diverging_procedures :: proc() {
// Diverging procedures may never return
foo :: proc() -> ! {
fmt.println("I'm a diverging procedure");
}
foo();
}
main :: proc() {
when true {
general_stuff();
union_type();
parametric_polymorphism();
threading_example();
array_programming();
named_proc_return_parameters();
using_enum();
explicit_procedure_overloading();
complete_switch();
cstring_example();
deprecated_attribute();
bit_set_type();
diverging_procedures();
}
}
@@ -1,9 +1,9 @@
#import "fmt.odin";
#import "os.odin";
#import "mem.odin";
// #import "http_test.odin" as ht;
// #import "game.odin" as game;
// #import "punity.odin" as pn;
import "core:fmt.odin";
import "core:os.odin";
import "core:mem.odin";
// import "http_test.odin" as ht;
// import "game.odin" as game;
// import "punity.odin" as pn;
main :: proc() {
struct_padding();
@@ -160,21 +160,21 @@ type_introspection :: proc() {
info: ^Type_Info;
x: int;
info = type_info(int); // by type
info = type_info_of_val(x); // by value
info = type_info_of(int); // by type
info = type_info_of(x); // by value
// See: runtime.odin
match i in info {
case Type_Info.Integer:
match i in info.variant {
case Type_Info_Integer:
fmt.println("integer!");
case Type_Info.Float:
case Type_Info_Float:
fmt.println("float!");
default:
case:
fmt.println("potato!");
}
// Unsafe cast
integer_info := cast(^Type_Info.Integer)cast(rawptr)info;
integer_info := cast(^Type_Info_Integer)cast(rawptr)info;
}
{
@@ -185,9 +185,9 @@ type_introspection :: proc() {
v2: Vector3;
v3: Vector3;
t1 := type_info_of_val(v1);
t2 := type_info_of_val(v2);
t3 := type_info_of_val(v3);
t1 := type_info_of(v1);
t2 := type_info_of(v2);
t3 := type_info_of(v3);
fmt.println();
fmt.print("Type of v1 is:\n\t", t1);
@@ -262,12 +262,12 @@ crazy_introspection :: proc() {
TOMATO,
}
fruit_ti := type_info(Fruit);
name := (union_cast(^Type_Info.Named)fruit_ti).name; // Unsafe casts
info, _ := union_cast(^Type_Info.Enum)type_info_base(fruit_ti); // Unsafe casts
fruit_ti := type_info_of(Fruit);
name := fruit_ti.variant.(Type_Info_Named).name;
info, _ := type_info_base(fruit_ti).variant.(Type_Info_Enum);
fmt.printf("%s :: enum %T {\n", name, info.base);
for i := 0; i < len(info.values); i++ {
for _, i in info.values {
fmt.printf("\t%s\t= %v,\n", info.names[i], info.values[i]);
}
fmt.printf("}\n");
@@ -328,7 +328,7 @@ miscellany :: proc() {
*/
// assert(false)
// compile_assert(false)
// #assert(false)
// panic("Panic message goes here")
}
@@ -1,7 +1,8 @@
// Demo 002
#load "fmt.odin";
#load "math.odin";
// #load "game.odin"
export "core:fmt.odin";
export "core:math.odin";
export "core:mem.odin";
// export "game.odin"
#thread_local tls_int: int;
@@ -96,9 +97,7 @@ enumerations :: proc() {
variadic_procedures :: proc() {
print_ints :: proc(args: ..int) {
for arg, i in args {
if i > 0 {
print(", ");
}
if i > 0 do print(", ");
print(arg);
}
}
@@ -111,9 +110,7 @@ variadic_procedures :: proc() {
print(prefix);
print(": ");
for arg, i in args {
if i > 0 {
print(", ");
}
if i > 0 do print(", ");
print(arg);
}
}
@@ -147,13 +144,7 @@ new_builtins :: proc() {
// Q: Should this be `free` rather than `free` and should I overload it for slices too?
{
prev_context := context;
defer __context = prev_context;
// Q: Should I add a `push_context` feature to the language?
__context.allocator = default_allocator();
push_allocator default_allocator() {
a := new(int);
defer free(a);
@@ -164,7 +155,7 @@ new_builtins :: proc() {
{
a: int = 123;
b: type_of_val(a) = 321;
b: type_of(a) = 321;
// NOTE(bill): This matches the current naming scheme
// size_of
@@ -180,8 +171,8 @@ new_builtins :: proc() {
{
// Compile time assert
COND :: true;
compile_assert(COND);
// compile_assert(!COND)
#assert(COND);
// #assert(!COND)
// Runtime assert
x := true;
@@ -205,7 +196,7 @@ new_builtins :: proc() {
a: [16]int;
a[1] = 1;
b := ^a;
b := &a;
// Auto pointer deref
// consistent with record members
assert(b[1] == 1);
@@ -255,7 +246,7 @@ match_statement :: proc() {
print("5!\n");
fallthrough; // explicit fallthrough
default:
case:
print("default!\n");
}
@@ -267,7 +258,7 @@ match_statement :: proc() {
// break by default
case TAU:
print("τ!\n");
default:
case:
print("default!\n");
}
@@ -279,7 +270,7 @@ match_statement :: proc() {
// break by default
case "Goodbye":
print("farewell\n");
default:
case:
print("???\n");
}
@@ -302,7 +293,7 @@ match_statement :: proc() {
print("dozens\n");
case a >= 100 && a < 1000:
print("hundreds\n");
default:
case:
print("a fuck ton\n");
}
@@ -334,9 +325,7 @@ Vector3 :: struct {x, y, z: f32}
print_floats :: proc(args: ..f32) {
for arg, i in args {
if i > 0 {
print(", ");
}
if i > 0 do print(", ");
print(arg);
}
println();
@@ -355,7 +344,7 @@ namespacing :: proc() {
Thing :: #type struct {
y: int,
test: bool,
}
};
b: Thing; // Uses this scope's Thing
b.test = true;
@@ -473,10 +462,10 @@ namespacing :: proc() {
}
e := Entity{position = Vector3{1, 2, 3}};
print_pos_1(^e);
print_pos_2(^e);
print_pos_3(^e);
print_pos_4(^e);
print_pos_1(&e);
print_pos_2(&e);
print_pos_3(&e);
print_pos_4(&e);
// This is similar to C++'s `this` pointer that is implicit and only available in methods
}
@@ -574,20 +563,20 @@ subtyping :: proc() {
entity_count := 0;
next_entity :: proc(entities: []Entity, entity_count: ^int) -> ^Entity {
e := ^entities[entity_count^];
entity_count^++;
e := &entities[entity_count^];
entity_count^ += 1;
return e;
}
f: Frog;
f.entity = next_entity(entities[..], ^entity_count);
f.entity = next_entity(entities[..], &entity_count);
f.position = Vector3{3, 4, 6};
using f.position;
print_floats(x, y, z);
}
{
/*{
// Down casting
Entity :: struct {
@@ -609,7 +598,7 @@ subtyping :: proc() {
// NOTE(bill): `down_cast` is unsafe and there are not check are compile time or run time
// Q: Should I completely remove `down_cast` as I added it in about 30 minutes
}
}*/
{
// Multiple "inheritance"/subclassing
@@ -630,7 +619,7 @@ subtyping :: proc() {
tagged_unions :: proc() {
{
EntityKind :: enum {
Entity_Kind :: enum {
INVALID,
FROG,
GIRAFFE,
@@ -638,8 +627,8 @@ tagged_unions :: proc() {
}
Entity :: struct {
kind: EntityKind
using data: raw_union {
kind: Entity_Kind
using data: struct #raw_union {
frog: struct {
jump_height: f32,
colour: u32,
@@ -657,33 +646,31 @@ tagged_unions :: proc() {
}
e: Entity;
e.kind = EntityKind.FROG;
e.kind = Entity_Kind.FROG;
e.frog.jump_height = 12;
f: type_of_val(e.frog);
f: type_of(e.frog);
// But this is very unsafe and extremely cumbersome to write
// In C++, I use macros to alleviate this but it's not a solution
}
{
Entity :: union {
Frog{
jump_height: f32,
colour: u32,
},
Giraffe{
neck_length: f32,
spot_count: int,
},
Helicopter{
blade_count: int,
weight: f32,
pilot_name: string,
},
Frog :: struct {
jump_height: f32,
colour: u32,
}
Giraffe :: struct {
neck_length: f32,
spot_count: int,
}
Helicopter :: struct {
blade_count: int,
weight: f32,
pilot_name: string,
}
Entity :: union {Frog, Giraffe, Helicopter};
using Entity;
f1: Frog = Frog{12, 0xff9900};
f2: Entity = Frog{12, 0xff9900}; // Implicit cast
f3 := cast(Entity)Frog{12, 0xff9900}; // Explicit cast
@@ -703,7 +690,7 @@ tagged_unions :: proc() {
// Requires a pointer to the union
// `x` will be a pointer to type of the case
match x in ^f {
match x in &f {
case Frog:
print("Frog!\n");
print(x.jump_height); nl();
@@ -713,7 +700,7 @@ tagged_unions :: proc() {
print("Giraffe!\n");
case Helicopter:
print("ROFLCOPTER!\n");
default:
case:
print("invalid entity\n");
}
@@ -755,11 +742,11 @@ tagged_unions :: proc() {
AstNode :: struct {};
ExactValue :: struct {};
EntityKind :: enum {
Entity_Kind :: enum {
Invalid,
Constant,
Variable,
UsingVariable,
Using_Variable,
TypeName,
Procedure,
Builtin,
@@ -769,14 +756,14 @@ tagged_unions :: proc() {
Guid :: i64;
Entity :: struct {
kind: EntityKind,
kind: Entity_Kind,
guid: Guid,
scope: ^Scope,
token: Token,
type_: ^Type,
using data: raw_union {
using data: struct #raw_union {
Constant: struct {
value: ExactValue,
},
@@ -786,7 +773,7 @@ tagged_unions :: proc() {
is_field: bool, // Is struct field
anonymous: bool, // Variable is an anonymous
},
UsingVariable: struct {
Using_Variable: struct {
},
TypeName: struct {
},
@@ -813,44 +800,44 @@ tagged_unions :: proc() {
Guid :: i64;
Entity_Base :: struct {
}
Entity :: union {
Constant :: struct {
value: ExactValue,
}
Variable :: struct {
visited: bool, // Cycle detection
used: bool, // Variable is used
is_field: bool, // Is struct field
anonymous: bool, // Variable is an anonymous
}
Using_Variable :: struct {
}
TypeName :: struct {
}
Procedure :: struct {
used: bool,
}
Builtin :: struct {
id: int,
}
Entity :: struct {
guid: Guid,
scope: ^Scope,
token: Token,
type_: ^Type,
Constant{
value: ExactValue,
},
Variable{
visited: bool, // Cycle detection
used: bool, // Variable is used
is_field: bool, // Is struct field
anonymous: bool, // Variable is an anonymous
},
UsingVariable{
},
TypeName{
},
Procedure{
used: bool,
},
Builtin{
id: int,
},
variant: union {Constant, Variable, Using_Variable, TypeName, Procedure, Builtin},
}
using Entity;
e: Entity;
e = Variable{
used = true,
anonymous = false,
e := Entity{
variant = Variable{
used = true,
anonymous = false,
},
};
@@ -863,13 +850,13 @@ tagged_unions :: proc() {
{
// `Raw` unions still have uses, especially for mathematic types
Vector2 :: raw_union {
Vector2 :: struct #raw_union {
using xy_: struct { x, y: f32 },
e: [2]f32,
v: [vector 2]f32,
}
Vector3 :: raw_union {
Vector3 :: struct #raw_union {
using xyz_: struct { x, y, z: f32 },
xy: Vector2,
e: [3]f32,
@@ -1,14 +1,14 @@
#import "fmt.odin";
#import "utf8.odin";
#import "hash.odin";
#import "mem.odin";
import "core:fmt.odin";
import "core:utf8.odin";
import "core:hash.odin";
import "core:mem.odin";
main :: proc() {
{ // New Standard Library stuff
s := "Hello";
fmt.println(s,
utf8.valid_string(s),
hash.murmur64(cast([]byte)s));
hash.murmur64(cast([]u8)s));
// utf8.odin
// hash.odin
@@ -20,10 +20,10 @@ main :: proc() {
{
arena: mem.Arena;
mem.init_arena_from_context(^arena, mem.megabytes(16)); // Uses default allocator
defer mem.free_arena(^arena);
mem.init_arena_from_context(&arena, mem.megabytes(16)); // Uses default allocator
defer mem.destroy_arena(&arena);
push_allocator mem.arena_allocator(^arena) {
push_allocator mem.arena_allocator(&arena) {
x := new(int);
x^ = 1337;
@@ -32,7 +32,7 @@ main :: proc() {
/*
push_allocator x {
...
..
}
is equivalent to:
@@ -42,14 +42,14 @@ main :: proc() {
__context.allocator = x
defer __context.allocator = prev_allocator
...
..
}
*/
// You can also "push" a context
c := context; // Create copy of the allocator
c.allocator = mem.arena_allocator(^arena);
c.allocator = mem.arena_allocator(&arena);
push_context c {
x := new(int);
@@ -1,13 +1,13 @@
#import "fmt.odin";
#import "utf8.odin";
// #import "atomic.odin";
// #import "hash.odin";
// #import "math.odin";
// #import "mem.odin";
// #import "opengl.odin";
// #import "os.odin";
// #import "sync.odin";
// #import win32 "sys/windows.odin";
import "core:fmt.odin";
import "core:utf8.odin";
// import "core:atomic.odin";
// import "core:hash.odin";
// import "core:math.odin";
// import "core:mem.odin";
// import "core:opengl.odin";
// import "core:os.odin";
// import "core:sync.odin";
// import win32 "core:sys/windows.odin";
main :: proc() {
// syntax();
@@ -43,7 +43,7 @@ syntax :: proc() {
Thing2 :: struct {x: f32, y: int, z: ^[]int};
// Slice interals are now just a `ptr+len+cap`
slice: []int; compile_assert(size_of_val(slice) == 3*size_of(int));
slice: []int; #assert(size_of(slice) == 3*size_of(int));
// Helper type - Help the reader understand what it is quicker
My_Int :: #type int;
@@ -90,22 +90,17 @@ Prefix_Type :: struct {x: int, y: f32, z: rawptr};
prefixes :: proc() {
using var: Prefix_Type;
immutable const := Prefix_Type{1, 2, nil};
var.x = 123;
x = 123;
// const.x = 123; // const is immutable
foo :: proc(using immutable pt: Prefix_Type, immutable int_ptr: ^int) {
// int_ptr = nil; // Not valid
// int_ptr^ = 123; // Not valid
foo :: proc(using pt: Prefix_Type) {
}
// Same as C99's `restrict`
bar :: proc(no_alias a, b: ^int) {
bar :: proc(#no_alias a, b: ^int) {
// Assumes a never equals b so it can perform optimizations with that fact
}
@@ -138,14 +133,18 @@ when_statements :: proc() {
foreign_procedures();
}
#foreign_system_library win32_user "user32.lib" when ODIN_OS == "windows";
when ODIN_OS == "windows" {
foreign_system_library win32_user "user32.lib";
}
// NOTE: This is done on purpose for two reasons:
// * Makes it clear where the platform specific stuff is
// * Removes the need to solve the travelling salesman problem when importing files :P
foreign_procedures :: proc() {
ShowWindow :: proc(hwnd: rawptr, cmd_show: i32) -> i32 #foreign win32_user;
show_window :: proc(hwnd: rawptr, cmd_show: i32) -> i32 #foreign win32_user "ShowWindow";
foreign win32_user {
ShowWindow :: proc(hwnd: rawptr, cmd_show: i32) -> i32 ---;
show_window :: proc(hwnd: rawptr, cmd_show: i32) -> i32 #link_name "ShowWindow" ---;
}
// NOTE: If that library doesn't get used, it doesn't get linked with
// NOTE: There is not link checking yet to see if that procedure does come from that library
@@ -203,14 +202,14 @@ loops :: proc() {
fmt.println(val, idx);
}
primes := [..]int{2, 3, 5, 7, 11, 13, 17, 19};
primes := [?]int{2, 3, 5, 7, 11, 13, 17, 19};
for p in primes {
fmt.println(p);
}
// Pointers to arrays, slices, or strings are allowed
for _ in ^primes {
for _ in &primes {
// ignore the value and just iterate across it
}
@@ -219,7 +218,7 @@ loops :: proc() {
name := "你好,世界";
fmt.println(name);
for r in name {
compile_assert(type_of_val(r) == rune);
#assert(type_of(r) == rune);
fmt.printf("%r\n", r);
}
@@ -270,8 +269,8 @@ procedure_overloading :: proc() {
a: i32 = 123;
b: f32;
c: rawptr;
fmt.println(foo(^a));
foo(^b);
fmt.println(foo(&a));
foo(&b);
foo(c);
// foo(nil); // nil could go to numerous types thus the ambiguity
+310
View File
@@ -0,0 +1,310 @@
// import "core:atomic.odin";
import "core:hash.odin";
import "core:mem.odin";
import "core:opengl.odin";
import "core:strconv.odin";
import "core:sync.odin";
import win32 "core:sys/windows.odin";
import "core:fmt.odin";
import "core:os.odin";
import "core:math.odin";
main :: proc() {
when true {
/*
Added:
* Unexported entities and fields using an underscore prefix
- See `sync.odin` and explain
Removed:
* Maybe/option types
* Remove `type` keyword and other "reserved" keywords
* ..< and .. removed and replace with .. (half-closed range)
Changed:
* `#assert` and `assert` return the value of the condition for semantic reasons
* thread_local -> #thread_local
* #include -> #load
* Files only get checked if they are actually used
* match x in y {} // For type match statements
* Version numbering now starts from 0.1.0 and uses the convention:
- major.minor.patch
* Core library additions to Windows specific stuff
*/
{
Fruit :: enum {
APPLE,
BANANA,
COCONUT,
}
fmt.println(Fruit.names);
}
{
A :: struct {x, y: f32};
B :: struct #align 16 {x, y: f32};
fmt.println("align_of(A) =", align_of(A));
fmt.println("align_of(B) =", align_of(B));
}
{
// Removal of ..< and ..
for i in 0..16 {
}
// Is similar to
for i := 0; i < 16; i += 1 {
}
}
{
thing: for i in 0..10 {
for j in i+1..10 {
if j == 2 {
fmt.println(i, j);
continue thing;
}
if j == 3 {
break thing;
}
}
}
// Works with, `for`, `for in`, `match`, `match in`
// NOTE(bill): This solves most of the problems I need `goto` for
}
{
t := type_info_of(int);
match i in t.variant {
case Type_Info_Integer, Type_Info_Float:
fmt.println("It's a number");
}
x: any = 123;
foo: match i in x {
case int, f32:
fmt.println("It's an int or f32");
break foo;
}
}
{
cond := true;
x: int;
if cond {
x = 3;
} else {
x = 4;
}
// Ternary operator
y := cond ? 3 : 4;
FOO :: true ? 123 : 432; // Constant ternary expression
fmt.println("Ternary values:", y, FOO);
}
{
// Slices now store a capacity
buf: [256]u8;
s: []u8;
s = buf[..0]; // == buf[0..0];
fmt.println("count =", len(s));
fmt.println("capacity =", cap(s));
append(&s, 1, 2, 3);
fmt.println(s);
s = buf[1..2..3];
fmt.println("count =", len(s));
fmt.println("capacity =", cap(s));
fmt.println(s);
clear(&s); // Sets count to zero
}
{
Foo :: struct {
x, y, z: f32,
ok: bool,
flags: u32,
}
foo_array: [256]Foo;
foo_as_bytes: []u8 = mem.slice_to_bytes(foo_array[..]);
// Useful for things like
// os.write(handle, foo_as_bytes);
foo_slice := mem.slice_ptr(cast(^Foo)&foo_as_bytes[0], len(foo_as_bytes)/size_of(Foo), cap(foo_as_bytes)/size_of(Foo));
// Question: Should there be a bytes_to_slice procedure or is it clearer to do this even if it is error prone?
// And if so what would the syntax be?
// slice_transmute([]Foo, foo_as_bytes);
}
{
Vec3 :: [vector 3]f32;
x := Vec3{1, 2, 3};
y := Vec3{4, 5, 6};
fmt.println(x < y);
fmt.println(x + y);
fmt.println(x - y);
fmt.println(x * y);
fmt.println(x / y);
for i in x {
fmt.println(i);
}
#assert(size_of([vector 7]bool) >= size_of([7]bool));
#assert(size_of([vector 7]i32) >= size_of([7]i32));
// align_of([vector 7]i32) != align_of([7]i32) // this may be the case
}
{
// fmt.* changes
// bprint* returns `string`
data: [256]u8;
str := fmt.bprintf(data[..], "Hellope %d %s %c", 123, "others", '!');
fmt.println(str);
}
{
x: [dynamic]f64;
reserve(&x, 16);
defer free(x); // `free` is overloaded for numerous types
// Number literals can have underscores in them for readability
append(&x, 2_000_000.500_000, 123, 5, 7); // variadic append
for p, i in x {
if i > 0 { fmt.print(", "); }
fmt.print(p);
}
fmt.println();
}
{
// Dynamic array "literals"
x := [dynamic]f64{2_000_000.500_000, 3, 5, 7};
defer free(x);
fmt.println(x); // fmt.print* supports printing of dynamic types
clear(&x);
fmt.println(x);
}
{
m: map[f32]int;
reserve(&m, 16);
defer free(m);
m[1.0] = 1278;
m[2.0] = 7643;
m[3.0] = 564;
_, ok := m[3.0];
c := m[3.0];
assert(ok && c == 564);
fmt.print("map[");
i := 0;
for val, key in m {
if i > 0 {
fmt.print(", ");
}
fmt.printf("%v=%v", key, val);
i += 1;
}
fmt.println("]");
}
{
m := map[string]u32{
"a" = 56,
"b" = 13453,
"c" = 7654,
};
defer free(m);
c := m["c"];
_, ok := m["c"];
assert(ok && c == 7654);
fmt.println(m);
delete(&m, "c"); // deletes entry with key "c"
_, found := m["c"];
assert(!found);
fmt.println(m);
clear(&m);
fmt.println(m);
// NOTE: Fixed size maps are planned but we have not yet implemented
// them as we have had no need for them as of yet
}
{
Vector3 :: struct{x, y, z: f32};
Quaternion :: struct{x, y, z, w: f32};
// Variants
Frog :: struct {
ribbit_volume: f32,
jump_height: f32,
}
Door :: struct {
openness: f32,
}
Map :: struct {
width, height: f32,
place_positions: []Vector3,
place_names: []string,
}
Entity :: struct {
// Common Fields
id: u64,
name: string,
using position: Vector3,
orientation: Quaternion,
flags: u32,
variant: union { Frog, Door, Map },
}
entity: Entity;
entity.id = 1337;
// implicit conversion from variant to base type
entity.variant = Frog{
ribbit_volume = 0.5,
jump_height = 2.1,
/*other data */
};
entity.name = "Frank";
entity.position = Vector3{1, 4, 9};
match e in entity.variant {
case Frog:
fmt.println("Ribbit");
case Door:
fmt.println("Creak");
case Map:
fmt.println("Rustle");
case:
fmt.println("Just a normal entity");
}
if frog, ok := entity.variant.(Frog); ok {
fmt.printf("The frog jumps %f feet high at %v\n", frog.jump_height, entity.position);
}
// Panics if not the correct type
frog: Frog;
frog = entity.variant.(Frog);
frog, _ = entity.variant.(Frog); // ignore error and force cast
}
}
}
+570
View File
@@ -0,0 +1,570 @@
import "core:fmt.odin"
import "core:strconv.odin"
import "core:mem.odin"
import "core:bits.odin"
import "core:hash.odin"
import "core:math.odin"
import "core:os.odin"
import "core:raw.odin"
import "core:sort.odin"
import "core:strings.odin"
import "core:types.odin"
import "core:utf16.odin"
import "core:utf8.odin"
when ODIN_OS == "windows" {
import "core:atomics.odin"
import "core:opengl.odin"
import "core:thread.odin"
import win32 "core:sys/windows.odin"
}
general_stuff :: proc() {
{ // `do` for inline statmes rather than block
foo :: proc() do fmt.println("Foo!");
if false do foo();
for false do foo();
when false do foo();
if false do foo();
else do foo();
}
{ // Removal of `++` and `--` (again)
x: int;
x += 1;
x -= 1;
}
{ // Casting syntaxes
i := i32(137);
ptr := &i;
fp1 := (^f32)(ptr);
// ^f32(ptr) == ^(f32(ptr))
fp2 := cast(^f32)ptr;
f1 := (^f32)(ptr)^;
f2 := (cast(^f32)ptr)^;
// Questions: Should there be two ways to do it?
}
/*
* Remove *_val_of built-in procedures
* size_of, align_of, offset_of
* type_of, type_info_of
*/
{ // `expand_to_tuple` built-in procedure
Foo :: struct {
x: int,
b: bool,
}
f := Foo{137, true};
x, b := expand_to_tuple(f);
fmt.println(f);
fmt.println(x, b);
fmt.println(expand_to_tuple(f));
}
{
// .. half-closed range
// .. open range
for in 0..2 {} // 0, 1
for in 0..2 {} // 0, 1, 2
}
}
default_struct_values :: proc() {
{
Vector3 :: struct {
x: f32,
y: f32,
z: f32,
}
v: Vector3;
fmt.println(v);
}
{
// Default values must be constants
Vector3 :: struct {
x: f32 = 1,
y: f32 = 4,
z: f32 = 9,
}
v: Vector3;
fmt.println(v);
v = Vector3{};
fmt.println(v);
// Uses the same semantics as a default values in a procedure
v = Vector3{137};
fmt.println(v);
v = Vector3{z = 137};
fmt.println(v);
}
{
Vector3 :: struct {
x := 1.0,
y := 4.0,
z := 9.0,
}
stack_default: Vector3;
stack_literal := Vector3{};
heap_one := new(Vector3); defer free(heap_one);
heap_two := new_clone(Vector3{}); defer free(heap_two);
fmt.println("stack_default - ", stack_default);
fmt.println("stack_literal - ", stack_literal);
fmt.println("heap_one - ", heap_one^);
fmt.println("heap_two - ", heap_two^);
N :: 4;
stack_array: [N]Vector3;
heap_array := new([N]Vector3); defer free(heap_array);
heap_slice := make([]Vector3, N); defer free(heap_slice);
fmt.println("stack_array[1] - ", stack_array[1]);
fmt.println("heap_array[1] - ", heap_array[1]);
fmt.println("heap_slice[1] - ", heap_slice[1]);
}
}
union_type :: proc() {
{
val: union{int, bool};
val = 137;
if i, ok := val.(int); ok {
fmt.println(i);
}
val = true;
fmt.println(val);
val = nil;
switch v in val {
case int: fmt.println("int", v);
case bool: fmt.println("bool", v);
case: fmt.println("nil");
}
}
{
// There is a duality between `any` and `union`
// An `any` has a pointer to the data and allows for any type (open)
// A `union` has as binary blob to store the data and allows only certain types (closed)
// The following code is with `any` but has the same syntax
val: any;
val = 137;
if i, ok := val.(int); ok {
fmt.println(i);
}
val = true;
fmt.println(val);
val = nil;
switch v in val {
case int: fmt.println("int", v);
case bool: fmt.println("bool", v);
case: fmt.println("nil");
}
}
Vector3 :: struct {x, y, z: f32};
Quaternion :: struct {x, y, z: f32, w: f32 = 1};
// More realistic examples
{
// NOTE(bill): For the above basic examples, you may not have any
// particular use for it. However, my main use for them is not for these
// simple cases. My main use is for hierarchical types. Many prefer
// subtyping, embedding the base data into the derived types. Below is
// an example of this for a basic game Entity.
Entity :: struct {
id: u64,
name: string,
position: Vector3,
orientation: Quaternion,
derived: any,
}
Frog :: struct {
using entity: Entity,
jump_height: f32,
}
Monster :: struct {
using entity: Entity,
is_robot: bool,
is_zombie: bool,
}
// See `parametric_polymorphism` procedure for details
new_entity :: proc(T: type) -> ^Entity {
t := new(T);
t.derived = t^;
return t;
}
entity := new_entity(Monster);
switch e in entity.derived {
case Frog:
fmt.println("Ribbit");
case Monster:
if e.is_robot do fmt.println("Robotic");
if e.is_zombie do fmt.println("Grrrr!");
}
}
{
// NOTE(bill): A union can be used to achieve something similar. Instead
// of embedding the base data into the derived types, the derived data
// in embedded into the base type. Below is the same example of the
// basic game Entity but using an union.
Entity :: struct {
id: u64,
name: string,
position: Vector3,
orientation: Quaternion,
derived: union {Frog, Monster},
}
Frog :: struct {
using entity: ^Entity,
jump_height: f32,
}
Monster :: struct {
using entity: ^Entity,
is_robot: bool,
is_zombie: bool,
}
// See `parametric_polymorphism` procedure for details
new_entity :: proc(T: type) -> ^Entity {
t := new(Entity);
t.derived = T{entity = t};
return t;
}
entity := new_entity(Monster);
switch e in entity.derived {
case Frog:
fmt.println("Ribbit");
case Monster:
if e.is_robot do fmt.println("Robotic");
if e.is_zombie do fmt.println("Grrrr!");
}
// NOTE(bill): As you can see, the usage code has not changed, only its
// memory layout. Both approaches have their own advantages but they can
// be used together to achieve different results. The subtyping approach
// can allow for a greater control of the memory layout and memory
// allocation, e.g. storing the derivatives together. However, this is
// also its disadvantage. You must either preallocate arrays for each
// derivative separation (which can be easily missed) or preallocate a
// bunch of "raw" memory; determining the maximum size of the derived
// types would require the aid of metaprogramming. Unions solve this
// particular problem as the data is stored with the base data.
// Therefore, it is possible to preallocate, e.g. [100]Entity.
// It should be noted that the union approach can have the same memory
// layout as the any and with the same type restrictions by using a
// pointer type for the derivatives.
/*
Entity :: struct {
..
derived: union{^Frog, ^Monster};
}
Frog :: struct {
using entity: Entity;
..
}
Monster :: struct {
using entity: Entity;
..
}
new_entity :: proc(T: type) -> ^Entity {
t := new(T);
t.derived = t;
return t;
}
*/
}
}
parametric_polymorphism :: proc() {
print_value :: proc(value: $T) {
fmt.printf("print_value: %T %v\n", value, value);
}
v1: int = 1;
v2: f32 = 2.1;
v3: f64 = 3.14;
v4: string = "message";
print_value(v1);
print_value(v2);
print_value(v3);
print_value(v4);
fmt.println();
add :: proc(p, q: $T) -> T {
x: T = p + q;
return x;
}
a := add(3, 4);
fmt.printf("a: %T = %v\n", a, a);
b := add(3.2, 4.3);
fmt.printf("b: %T = %v\n", b, b);
// This is how `new` is implemented
alloc_type :: proc(T: type) -> ^T {
t := cast(^T)alloc(size_of(T), align_of(T));
t^ = T{}; // Use default initialization value
return t;
}
copy_slice :: proc(dst, src: []$T) -> int {
n := min(len(dst), len(src));
if n > 0 {
mem.copy(&dst[0], &src[0], n*size_of(T));
}
return n;
}
double_params :: proc(a: $A, b: $B) -> A {
return a + A(b);
}
fmt.println(double_params(12, 1.345));
{ // Polymorphic Types and Type Specialization
Table_Slot :: struct(Key, Value: type) {
occupied: bool,
hash: u32,
key: Key,
value: Value,
}
TABLE_SIZE_MIN :: 32;
Table :: struct(Key, Value: type) {
count: int,
allocator: Allocator,
slots: []Table_Slot(Key, Value),
}
// Only allow types that are specializations of a (polymorphic) slice
make_slice :: proc(T: type/[]$E, len: int) -> T {
return make(T, len);
}
// Only allow types that are specializations of `Table`
allocate :: proc(table: ^$T/Table, capacity: int) {
c := context;
if table.allocator.procedure != nil do c.allocator = table.allocator;
push_context c {
table.slots = make_slice(type_of(table.slots), max(capacity, TABLE_SIZE_MIN));
}
}
expand :: proc(table: ^$T/Table) {
c := context;
if table.allocator.procedure != nil do c.allocator = table.allocator;
push_context c {
old_slots := table.slots;
cap := max(2*cap(table.slots), TABLE_SIZE_MIN);
allocate(table, cap);
for s in old_slots do if s.occupied {
put(table, s.key, s.value);
}
free(old_slots);
}
}
// Polymorphic determination of a polymorphic struct
// put :: proc(table: ^$T/Table, key: T.Key, value: T.Value) {
put :: proc(table: ^Table($Key, $Value), key: Key, value: Value) {
hash := get_hash(key); // Ad-hoc method which would fail in a different scope
index := find_index(table, key, hash);
if index < 0 {
if f64(table.count) >= 0.75*f64(cap(table.slots)) {
expand(table);
}
assert(table.count <= cap(table.slots));
hash := get_hash(key);
index = int(hash % u32(cap(table.slots)));
for table.slots[index].occupied {
if index += 1; index >= cap(table.slots) {
index = 0;
}
}
table.count += 1;
}
slot := &table.slots[index];
slot.occupied = true;
slot.hash = hash;
slot.key = key;
slot.value = value;
}
// find :: proc(table: ^$T/Table, key: T.Key) -> (T.Value, bool) {
find :: proc(table: ^Table($Key, $Value), key: Key) -> (Value, bool) {
hash := get_hash(key);
index := find_index(table, key, hash);
if index < 0 {
return Value{}, false;
}
return table.slots[index].value, true;
}
find_index :: proc(table: ^Table($Key, $Value), key: Key, hash: u32) -> int {
if cap(table.slots) <= 0 do return -1;
index := int(hash % u32(cap(table.slots)));
for table.slots[index].occupied {
if table.slots[index].hash == hash {
if table.slots[index].key == key {
return index;
}
}
if index += 1; index >= cap(table.slots) {
index = 0;
}
}
return -1;
}
get_hash :: proc(s: string) -> u32 { // fnv32a
h: u32 = 0x811c9dc5;
for i in 0..len(s) {
h = (h ~ u32(s[i])) * 0x01000193;
}
return h;
}
table: Table(string, int);
for i in 0..36 do put(&table, "Hellope", i);
for i in 0..42 do put(&table, "World!", i);
found, _ := find(&table, "Hellope");
fmt.printf("`found` is %v\n", found);
found, _ = find(&table, "World!");
fmt.printf("`found` is %v\n", found);
// I would not personally design a hash table like this in production
// but this is a nice basic example
// A better approach would either use a `u64` or equivalent for the key
// and let the user specify the hashing function or make the user store
// the hashing procedure with the table
}
}
prefix_table := [?]string{
"White",
"Red",
"Green",
"Blue",
"Octarine",
"Black",
};
threading_example :: proc() {
when ODIN_OS == "windows" {
unordered_remove :: proc(array: ^[]$T, index: int, loc := #caller_location) {
__bounds_check_error_loc(loc, index, len(array));
array[index] = array[len(array)-1];
pop(array);
}
ordered_remove :: proc(array: ^[]$T, index: int, loc := #caller_location) {
__bounds_check_error_loc(loc, index, len(array));
copy(array[index..], array[index+1..]);
pop(array);
}
worker_proc :: proc(t: ^thread.Thread) -> int {
for iteration in 1..5 {
fmt.printf("Thread %d is on iteration %d\n", t.user_index, iteration);
fmt.printf("`%s`: iteration %d\n", prefix_table[t.user_index], iteration);
// win32.sleep(1);
}
return 0;
}
threads := make([]^thread.Thread, 0, len(prefix_table));
defer free(threads);
for i in 0..len(prefix_table) {
if t := thread.create(worker_proc); t != nil {
t.init_context = context;
t.use_init_context = true;
t.user_index = len(threads);
append(&threads, t);
thread.start(t);
}
}
for len(threads) > 0 {
for i := 0; i < len(threads); /**/ {
if t := threads[i]; thread.is_done(t) {
fmt.printf("Thread %d is done\n", t.user_index);
thread.destroy(t);
ordered_remove(&threads, i);
} else {
i += 1;
}
}
}
}
}
main :: proc() {
when false {
fmt.println("\n# general_stuff"); general_stuff();
fmt.println("\n# default_struct_values"); default_struct_values();
fmt.println("\n# union_type"); union_type();
fmt.println("\n# parametric_polymorphism"); parametric_polymorphism();
fmt.println("\n# threading_example"); threading_example();
}
}
+778
View File
@@ -0,0 +1,778 @@
import "core:fmt.odin"
import "core:strconv.odin"
import "core:mem.odin"
import "core:bits.odin"
import "core:hash.odin"
import "core:math.odin"
import "core:math/rand.odin"
import "core:os.odin"
import "core:raw.odin"
import "core:sort.odin"
import "core:strings.odin"
import "core:types.odin"
import "core:utf16.odin"
import "core:utf8.odin"
// File scope `when` statements
when ODIN_OS == "windows" {
import "core:atomics.odin"
import "core:thread.odin"
import win32 "core:sys/windows.odin"
}
@(link_name="general_stuff")
general_stuff :: proc() {
fmt.println("# general_stuff");
{ // `do` for inline statements rather than block
foo :: proc() do fmt.println("Foo!");
if false do foo();
for false do foo();
when false do foo();
if false do foo();
else do foo();
}
{ // Removal of `++` and `--` (again)
x: int;
x += 1;
x -= 1;
}
{ // Casting syntaxes
i := i32(137);
ptr := &i;
_ = (^f32)(ptr);
// ^f32(ptr) == ^(f32(ptr))
_ = cast(^f32)ptr;
_ = (^f32)(ptr)^;
_ = (cast(^f32)ptr)^;
// Questions: Should there be two ways to do it?
}
/*
* Remove *_val_of built-in procedures
* size_of, align_of, offset_of
* type_of, type_info_of
*/
{ // `expand_to_tuple` built-in procedure
Foo :: struct {
x: int,
b: bool,
}
f := Foo{137, true};
x, b := expand_to_tuple(f);
fmt.println(f);
fmt.println(x, b);
fmt.println(expand_to_tuple(f));
}
{
// .. half-closed range
// .. open range
for in 0..2 {} // 0, 1
for in 0..2 {} // 0, 1, 2
}
{ // Multiple sized booleans
x0: bool; // default
x1: b8 = true;
x2: b16 = false;
x3: b32 = true;
x4: b64 = false;
fmt.printf("x1: %T = %v;\n", x1, x1);
fmt.printf("x2: %T = %v;\n", x2, x2);
fmt.printf("x3: %T = %v;\n", x3, x3);
fmt.printf("x4: %T = %v;\n", x4, x4);
// Having specific sized booleans is very useful when dealing with foreign code
// and to enforce specific alignment for a boolean, especially within a struct
}
{ // `distinct` types
// Originally, all type declarations would create a distinct type unless #type_alias was present.
// Now the behaviour has been reversed. All type declarations create a type alias unless `distinct` is present.
// If the type expression is `struct`, `union`, `enum`, `proc`, or `bit_field`, the types will always been distinct.
Int32 :: i32;
#assert(Int32 == i32);
My_Int32 :: distinct i32;
#assert(My_Int32 != i32);
My_Struct :: struct{x: int};
#assert(My_Struct != struct{x: int});
}
}
default_struct_values :: proc() {
fmt.println("# default_struct_values");
{
Vector3 :: struct {
x: f32,
y: f32,
z: f32,
}
v: Vector3;
fmt.println(v);
}
{
// Default values must be constants
Vector3 :: struct {
x: f32 = 1,
y: f32 = 4,
z: f32 = 9,
}
v: Vector3;
fmt.println(v);
v = Vector3{};
fmt.println(v);
// Uses the same semantics as a default values in a procedure
v = Vector3{137};
fmt.println(v);
v = Vector3{z = 137};
fmt.println(v);
}
{
Vector3 :: struct {
x := 1.0,
y := 4.0,
z := 9.0,
}
stack_default: Vector3;
stack_literal := Vector3{};
heap_one := new(Vector3); defer free(heap_one);
heap_two := new_clone(Vector3{}); defer free(heap_two);
fmt.println("stack_default - ", stack_default);
fmt.println("stack_literal - ", stack_literal);
fmt.println("heap_one - ", heap_one^);
fmt.println("heap_two - ", heap_two^);
N :: 4;
stack_array: [N]Vector3;
heap_array := new([N]Vector3); defer free(heap_array);
heap_slice := make([]Vector3, N); defer free(heap_slice);
fmt.println("stack_array[1] - ", stack_array[1]);
fmt.println("heap_array[1] - ", heap_array[1]);
fmt.println("heap_slice[1] - ", heap_slice[1]);
}
}
union_type :: proc() {
fmt.println("\n# union_type");
{
val: union{int, bool};
val = 137;
if i, ok := val.(int); ok {
fmt.println(i);
}
val = true;
fmt.println(val);
val = nil;
switch v in val {
case int: fmt.println("int", v);
case bool: fmt.println("bool", v);
case: fmt.println("nil");
}
}
{
// There is a duality between `any` and `union`
// An `any` has a pointer to the data and allows for any type (open)
// A `union` has as binary blob to store the data and allows only certain types (closed)
// The following code is with `any` but has the same syntax
val: any;
val = 137;
if i, ok := val.(int); ok {
fmt.println(i);
}
val = true;
fmt.println(val);
val = nil;
switch v in val {
case int: fmt.println("int", v);
case bool: fmt.println("bool", v);
case: fmt.println("nil");
}
}
Vector3 :: struct {x, y, z: f32};
Quaternion :: struct {x, y, z: f32, w: f32 = 1};
// More realistic examples
{
// NOTE(bill): For the above basic examples, you may not have any
// particular use for it. However, my main use for them is not for these
// simple cases. My main use is for hierarchical types. Many prefer
// subtyping, embedding the base data into the derived types. Below is
// an example of this for a basic game Entity.
Entity :: struct {
id: u64,
name: string,
position: Vector3,
orientation: Quaternion,
derived: any,
}
Frog :: struct {
using entity: Entity,
jump_height: f32,
}
Monster :: struct {
using entity: Entity,
is_robot: bool,
is_zombie: bool,
}
// See `parametric_polymorphism` procedure for details
new_entity :: proc(T: type) -> ^Entity {
t := new(T);
t.derived = t^;
return t;
}
entity := new_entity(Monster);
switch e in entity.derived {
case Frog:
fmt.println("Ribbit");
case Monster:
if e.is_robot do fmt.println("Robotic");
if e.is_zombie do fmt.println("Grrrr!");
}
}
{
// NOTE(bill): A union can be used to achieve something similar. Instead
// of embedding the base data into the derived types, the derived data
// in embedded into the base type. Below is the same example of the
// basic game Entity but using an union.
Entity :: struct {
id: u64,
name: string,
position: Vector3,
orientation: Quaternion,
derived: union {Frog, Monster},
}
Frog :: struct {
using entity: ^Entity,
jump_height: f32,
}
Monster :: struct {
using entity: ^Entity,
is_robot: bool,
is_zombie: bool,
}
// See `parametric_polymorphism` procedure for details
new_entity :: proc(T: type) -> ^Entity {
t := new(Entity);
t.derived = T{entity = t};
return t;
}
entity := new_entity(Monster);
switch e in entity.derived {
case Frog:
fmt.println("Ribbit");
case Monster:
if e.is_robot do fmt.println("Robotic");
if e.is_zombie do fmt.println("Grrrr!");
}
// NOTE(bill): As you can see, the usage code has not changed, only its
// memory layout. Both approaches have their own advantages but they can
// be used together to achieve different results. The subtyping approach
// can allow for a greater control of the memory layout and memory
// allocation, e.g. storing the derivatives together. However, this is
// also its disadvantage. You must either preallocate arrays for each
// derivative separation (which can be easily missed) or preallocate a
// bunch of "raw" memory; determining the maximum size of the derived
// types would require the aid of metaprogramming. Unions solve this
// particular problem as the data is stored with the base data.
// Therefore, it is possible to preallocate, e.g. [100]Entity.
// It should be noted that the union approach can have the same memory
// layout as the any and with the same type restrictions by using a
// pointer type for the derivatives.
/*
Entity :: struct {
..
derived: union{^Frog, ^Monster},
}
Frog :: struct {
using entity: Entity,
..
}
Monster :: struct {
using entity: Entity,
..
}
new_entity :: proc(T: type) -> ^Entity {
t := new(T);
t.derived = t;
return t;
}
*/
}
}
parametric_polymorphism :: proc() {
fmt.println("# parametric_polymorphism");
print_value :: proc(value: $T) {
fmt.printf("print_value: %T %v\n", value, value);
}
v1: int = 1;
v2: f32 = 2.1;
v3: f64 = 3.14;
v4: string = "message";
print_value(v1);
print_value(v2);
print_value(v3);
print_value(v4);
fmt.println();
add :: proc(p, q: $T) -> T {
x: T = p + q;
return x;
}
a := add(3, 4);
fmt.printf("a: %T = %v\n", a, a);
b := add(3.2, 4.3);
fmt.printf("b: %T = %v\n", b, b);
// This is how `new` is implemented
alloc_type :: proc(T: type) -> ^T {
t := cast(^T)alloc(size_of(T), align_of(T));
t^ = T{}; // Use default initialization value
return t;
}
copy_slice :: proc(dst, src: []$T) -> int {
return mem.copy(&dst[0], &src[0], n*size_of(T));
}
double_params :: proc(a: $A, b: $B) -> A {
return a + A(b);
}
fmt.println(double_params(12, 1.345));
{ // Polymorphic Types and Type Specialization
Table_Slot :: struct(Key, Value: type) {
occupied: bool,
hash: u32,
key: Key,
value: Value,
}
TABLE_SIZE_MIN :: 32;
Table :: struct(Key, Value: type) {
count: int,
allocator: Allocator,
slots: []Table_Slot(Key, Value),
}
// Only allow types that are specializations of a (polymorphic) slice
make_slice :: proc(T: type/[]$E, len: int) -> T {
return make(T, len);
}
// Only allow types that are specializations of `Table`
allocate :: proc(table: ^$T/Table, capacity: int) {
c := context;
if table.allocator.procedure != nil do c.allocator = table.allocator;
context <- c {
table.slots = make_slice(type_of(table.slots), max(capacity, TABLE_SIZE_MIN));
}
}
expand :: proc(table: ^$T/Table) {
c := context;
if table.allocator.procedure != nil do c.allocator = table.allocator;
context <- c {
old_slots := table.slots;
cap := max(2*len(table.slots), TABLE_SIZE_MIN);
allocate(table, cap);
for s in old_slots do if s.occupied {
put(table, s.key, s.value);
}
free(old_slots);
}
}
// Polymorphic determination of a polymorphic struct
// put :: proc(table: ^$T/Table, key: T.Key, value: T.Value) {
put :: proc(table: ^Table($Key, $Value), key: Key, value: Value) {
hash := get_hash(key); // Ad-hoc method which would fail in a different scope
index := find_index(table, key, hash);
if index < 0 {
if f64(table.count) >= 0.75*f64(len(table.slots)) {
expand(table);
}
assert(table.count <= len(table.slots));
hash := get_hash(key);
index = int(hash % u32(len(table.slots)));
for table.slots[index].occupied {
if index += 1; index >= len(table.slots) {
index = 0;
}
}
table.count += 1;
}
slot := &table.slots[index];
slot.occupied = true;
slot.hash = hash;
slot.key = key;
slot.value = value;
}
// find :: proc(table: ^$T/Table, key: T.Key) -> (T.Value, bool) {
find :: proc(table: ^Table($Key, $Value), key: Key) -> (Value, bool) {
hash := get_hash(key);
index := find_index(table, key, hash);
if index < 0 {
return Value{}, false;
}
return table.slots[index].value, true;
}
find_index :: proc(table: ^Table($Key, $Value), key: Key, hash: u32) -> int {
if len(table.slots) <= 0 do return -1;
index := int(hash % u32(len(table.slots)));
for table.slots[index].occupied {
if table.slots[index].hash == hash {
if table.slots[index].key == key {
return index;
}
}
if index += 1; index >= len(table.slots) {
index = 0;
}
}
return -1;
}
get_hash :: proc(s: string) -> u32 { // fnv32a
h: u32 = 0x811c9dc5;
for i in 0..len(s) {
h = (h ~ u32(s[i])) * 0x01000193;
}
return h;
}
table: Table(string, int);
for i in 0..36 do put(&table, "Hellope", i);
for i in 0..42 do put(&table, "World!", i);
found, _ := find(&table, "Hellope");
fmt.printf("`found` is %v\n", found);
found, _ = find(&table, "World!");
fmt.printf("`found` is %v\n", found);
// I would not personally design a hash table like this in production
// but this is a nice basic example
// A better approach would either use a `u64` or equivalent for the key
// and let the user specify the hashing function or make the user store
// the hashing procedure with the table
}
}
prefix_table := [?]string{
"White",
"Red",
"Green",
"Blue",
"Octarine",
"Black",
};
threading_example :: proc() {
when ODIN_OS == "windows" {
fmt.println("# threading_example");
unordered_remove :: proc(array: ^[dynamic]$T, index: int, loc := #caller_location) {
__bounds_check_error_loc(loc, index, len(array));
array[index] = array[len(array)-1];
pop(array);
}
ordered_remove :: proc(array: ^[dynamic]$T, index: int, loc := #caller_location) {
__bounds_check_error_loc(loc, index, len(array));
copy(array[index..], array[index+1..]);
pop(array);
}
worker_proc :: proc(t: ^thread.Thread) -> int {
for iteration in 1..5 {
fmt.printf("Thread %d is on iteration %d\n", t.user_index, iteration);
fmt.printf("`%s`: iteration %d\n", prefix_table[t.user_index], iteration);
// win32.sleep(1);
}
return 0;
}
threads := make([dynamic]^thread.Thread, 0, len(prefix_table));
defer free(threads);
for in prefix_table {
if t := thread.create(worker_proc); t != nil {
t.init_context = context;
t.use_init_context = true;
t.user_index = len(threads);
append(&threads, t);
thread.start(t);
}
}
for len(threads) > 0 {
for i := 0; i < len(threads); /**/ {
if t := threads[i]; thread.is_done(t) {
fmt.printf("Thread %d is done\n", t.user_index);
thread.destroy(t);
ordered_remove(&threads, i);
} else {
i += 1;
}
}
}
}
}
array_programming :: proc() {
fmt.println("# array_programming");
{
a := [3]f32{1, 2, 3};
b := [3]f32{5, 6, 7};
c := a * b;
d := a + b;
e := 1 + (c - d) / 2;
fmt.printf("%.1f\n", e); // [0.5, 3.0, 6.5]
}
{
a := [3]f32{1, 2, 3};
b := swizzle(a, 2, 1, 0);
assert(b == [3]f32{3, 2, 1});
c := swizzle(a, 0, 0);
assert(c == [2]f32{1, 1});
assert(c == 1);
}
{
Vector3 :: distinct [3]f32;
a := Vector3{1, 2, 3};
b := Vector3{5, 6, 7};
c := (a * b)/2 + 1;
d := c.x + c.y + c.z;
fmt.printf("%.1f\n", d); // 22.0
cross :: proc(a, b: Vector3) -> Vector3 {
i := swizzle(a, 1, 2, 0) * swizzle(b, 2, 0, 1);
j := swizzle(a, 2, 0, 1) * swizzle(b, 1, 2, 0);
return i - j;
}
blah :: proc(a: Vector3) -> f32 {
return a.x + a.y + a.z;
}
x := cross(a, b);
fmt.println(x);
fmt.println(blah(x));
}
}
using println in import "core:fmt.odin"
using_in :: proc() {
fmt.println("# using in");
using print in fmt;
println("Hellope1");
print("Hellope2\n");
Foo :: struct {
x, y: int,
b: bool,
}
f: Foo;
f.x, f.y = 123, 321;
println(f);
using x, y in f;
x, y = 456, 654;
println(f);
}
named_proc_return_parameters :: proc() {
fmt.println("# named proc return parameters");
foo0 :: proc() -> int {
return 123;
}
foo1 :: proc() -> (a: int) {
a = 123;
return;
}
foo2 :: proc() -> (a, b: int) {
// Named return values act like variables within the scope
a = 321;
b = 567;
return b, a;
}
fmt.println("foo0 =", foo0()); // 123
fmt.println("foo1 =", foo1()); // 123
fmt.println("foo2 =", foo2()); // 567 321
}
enum_export :: proc() {
fmt.println("# enum #export");
Foo :: enum #export {A, B, C};
f0 := A;
f1 := B;
f2 := C;
fmt.println(f0, f1, f2);
}
explicit_procedure_overloading :: proc() {
fmt.println("# explicit procedure overloading");
add_ints :: proc(a, b: int) -> int {
x := a + b;
fmt.println("add_ints", x);
return x;
}
add_floats :: proc(a, b: f32) -> f32 {
x := a + b;
fmt.println("add_floats", x);
return x;
}
add_numbers :: proc(a: int, b: f32, c: u8) -> int {
x := int(a) + int(b) + int(c);
fmt.println("add_numbers", x);
return x;
}
add :: proc[add_ints, add_floats, add_numbers];
add(int(1), int(2));
add(f32(1), f32(2));
add(int(1), f32(2), u8(3));
add(1, 2); // untyped ints coerce to int tighter than f32
add(1.0, 2.0); // untyped floats coerce to f32 tighter than int
add(1, 2, 3); // three parameters
// Ambiguous answers
// add(1.0, 2);
// add(1, 2.0);
}
complete_switch :: proc() {
fmt.println("# complete_switch");
{ // enum
Foo :: enum #export {
A,
B,
C,
D,
}
b := Foo.B;
f := Foo.A;
#complete switch f {
case A: fmt.println("A");
case B: fmt.println("B");
case C: fmt.println("C");
case D: fmt.println("D");
case: fmt.println("?");
}
}
{ // union
Foo :: union {int, bool};
f: Foo = 123;
#complete switch in f {
case int: fmt.println("int");
case bool: fmt.println("bool");
case:
}
}
}
main :: proc() {
when true {
general_stuff();
default_struct_values();
union_type();
parametric_polymorphism();
threading_example();
array_programming();
using_in();
named_proc_return_parameters();
enum_export();
explicit_procedure_overloading();
complete_switch();
}
}
@@ -46,7 +46,7 @@ memory_copy :: proc(dst, src: rawptr, n: int) #inline {
}
v128b :: type {4}u32
compile_assert(align_of(v128b) == 16)
#assert(align_of(v128b) == 16)
d, s: ^byte = dst, src
+430
View File
@@ -0,0 +1,430 @@
import (
"fmt.odin";
"atomics.odin";
"bits.odin";
"decimal.odin";
"hash.odin";
"math.odin";
"mem.odin";
"opengl.odin";
"os.odin";
"raw.odin";
"strconv.odin";
"strings.odin";
"sync.odin";
"sort.odin";
"types.odin";
"utf8.odin";
"utf16.odin";
/*
*/
)
general_stuff :: proc() {
// Complex numbers
a := 3 + 4i;
b: complex64 = 3 + 4i;
c: complex128 = 3 + 4i;
d := complex(2, 3);
e := a / conj(a);
fmt.println("(3+4i)/(3-4i) =", e);
fmt.println(real(e), "+", imag(e), "i");
// C-style variadic procedures
foreign __llvm_core {
// The variadic part allows for extra type checking too which C does not provide
c_printf :: proc(fmt: ^u8, #c_vararg args: ..any) -> i32 #link_name "printf" ---;
}
str := "%d\n\x00";
// c_printf(&str[0], i32(789456123));
Foo :: struct {
x: int;
y: f32;
z: string;
}
foo := Foo{123, 0.513, "A string"};
x, y, z := expand_to_tuple(foo);
fmt.println(x, y, z);
#assert(type_of(x) == int);
#assert(type_of(y) == f32);
#assert(type_of(z) == string);
// By default, all variables are zeroed
// This can be overridden with the "uninitialized value"
// This is similar to `nil` but applied to everything
undef_int: int = ---;
// Context system is now implemented using Implicit Parameter Passing (IPP)
// The previous implementation was Thread Local Storage (TLS)
// IPP has the advantage that it works on systems without TLS and that you can
// link the context to the stack frame and thus look at previous contexts
//
// It does mean that a pointer is implicitly passed procedures with the default
// Odin calling convention (#cc_odin)
// This can be overridden with something like #cc_contextless or #cc_c if performance
// is worried about
}
foreign_blocks :: proc() {
// See sys/windows.odin
}
default_arguments :: proc() {
hello :: proc(a: int = 9, b: int = 9) do fmt.printf("a is %d; b is %d\n", a, b);
fmt.println("\nTesting default arguments:");
hello(1, 2);
hello(1);
hello();
}
named_arguments :: proc() {
Colour :: enum {
Red,
Orange,
Yellow,
Green,
Blue,
Octarine,
};
using Colour;
make_character :: proc(name, catch_phrase: string, favourite_colour, least_favourite_colour: Colour) {
fmt.println();
fmt.printf("My name is %v and I like %v. %v\n", name, favourite_colour, catch_phrase);
}
make_character("Frank", "¡Ay, caramba!", Blue, Green);
// As the procedures have more and more parameters, it is very easy
// to get many of the arguments in the wrong order especialy if the
// types are the same
make_character("¡Ay, caramba!", "Frank", Green, Blue);
// Named arguments help to disambiguate this problem
make_character(catch_phrase = "¡Ay, caramba!", name = "Frank",
least_favourite_colour = Green, favourite_colour = Blue);
// The named arguments can be specifed in any order.
make_character(favourite_colour = Octarine, catch_phrase = "U wot m8!",
least_favourite_colour = Green, name = "Dennis");
// NOTE: You cannot mix named arguments with normal values
/*
make_character("Dennis",
favourite_colour = Octarine, catch_phrase = "U wot m8!",
least_favourite_colour = Green);
*/
// Named arguments can also aid with default arguments
numerous_things :: proc(s: string, a := 1, b := 2, c := 3.14,
d := "The Best String!", e := false, f := 10.3/3.1, g := false) {
g_str := g ? "true" : "false";
fmt.printf("How many?! %s: %v\n", s, g_str);
}
numerous_things("First");
numerous_things(s = "Second", g = true);
// Default values can be placed anywhere, not just at the end like in other languages
weird :: proc(pre: string, mid: int = 0, post: string) {
fmt.println(pre, mid, post);
}
weird("How many things", 42, "huh?");
weird(pre = "Prefix", post = "Pat");
}
default_return_values :: proc() {
foo :: proc(x: int) -> (first: string = "Hellope", second := "world!") {
match x {
case 0: return;
case 1: return "Goodbye";
case 2: return "Goodbye", "cruel world..";
case 3: return second = "cruel world..", first = "Goodbye";
}
return second = "my old friend.";
}
fmt.printf("%s %s\n", foo(0));
fmt.printf("%s %s\n", foo(1));
fmt.printf("%s %s\n", foo(2));
fmt.printf("%s %s\n", foo(3));
fmt.printf("%s %s\n", foo(4));
fmt.println();
// A more "real" example
Error :: enum {
None,
WhyTheNumberThree,
TenIsTooBig,
};
Entity :: struct {
name: string;
id: u32;
}
some_thing :: proc(input: int) -> (result: ^Entity = nil, err := Error.None) {
match {
case input == 3: return err = Error.WhyTheNumberThree;
case input >= 10: return err = Error.TenIsTooBig;
}
e := new(Entity);
e.id = u32(input);
return result = e;
}
}
call_location :: proc() {
amazing :: proc(n: int, using loc := #caller_location) {
fmt.printf("%s(%d:%d) just asked to do something amazing.\n",
fully_pathed_filename, line, column);
fmt.printf("Normal -> %d\n", n);
fmt.printf("Amazing -> %d\n", n+1);
fmt.println();
}
loc := #location(main);
fmt.println("`main` is located at", loc);
fmt.println("This line is located at", #location());
fmt.println();
amazing(3);
amazing(4, #location(call_location));
// See _preload.odin for the implementations of `assert` and `panic`
}
explicit_parametric_polymorphic_procedures :: proc() {
// This is how `new` is actually implemented, see _preload.odin
alloc_type :: proc(T: type) -> ^T do return cast(^T)alloc(size_of(T), align_of(T));
int_ptr := alloc_type(int);
defer free(int_ptr);
int_ptr^ = 137;
fmt.println(int_ptr, int_ptr^);
// Named arguments work too!
another_ptr := alloc_type(T = f32);
defer free(another_ptr);
add :: proc(T: type, args: ..T) -> T {
res: T;
for arg in args do res += arg;
return res;
}
fmt.println("add =", add(int, 1, 2, 3, 4, 5, 6));
swap :: proc(T: type, a, b: ^T) {
tmp := a^;
a^ = b^;
b^ = tmp;
}
a, b: int = 3, 4;
fmt.println("Pre-swap:", a, b);
swap(int, &a, &b);
fmt.println("Post-swap:", a, b);
a, b = b, a; // Or use this syntax for this silly example case
Vector2 :: struct {x, y: f32;};
{
// A more complicated example using subtyping
// Something like this could be used in a game
Entity :: struct {
using position: Vector2;
flags: u64;
id: u64;
derived: any;
}
Rock :: struct {
using entity: Entity;
heavy: bool;
}
Door :: struct {
using entity: Entity;
open: bool;
}
Monster :: struct {
using entity: Entity;
is_robot: bool;
is_zombie: bool;
}
new_entity :: proc(T: type, x, y: f32) -> ^T {
result := new(T);
result.derived = result^;
result.x = x;
result.y = y;
return result;
}
entities: [dynamic]^Entity;
rock := new_entity(Rock, 3, 5);
// Named arguments work too!
door := new_entity(T = Door, x = 3, y = 6);
// And named arguments can be any order
monster := new_entity(
y = 1,
x = 2,
T = Monster,
);
append(&entities, rock, door, monster);
fmt.println("Subtyping");
for entity in entities {
match e in entity.derived {
case Rock: fmt.println("Rock", e.x, e.y);
case Door: fmt.println("Door", e.x, e.y);
case Monster: fmt.println("Monster", e.x, e.y);
}
}
}
{
Entity :: struct {
using position: Vector2;
flags: u64;
id: u64;
variant: union { Rock, Door, Monster };
}
Rock :: struct {
using entity: ^Entity;
heavy: bool;
}
Door :: struct {
using entity: ^Entity;
open: bool;
}
Monster :: struct {
using entity: ^Entity;
is_robot: bool;
is_zombie: bool;
}
new_entity :: proc(T: type, x, y: f32) -> ^T {
result := new(Entity);
result.variant = T{entity = result};
result.x = x;
result.y = y;
return cast(^T)&result.variant;
}
entities: [dynamic]^Entity;
rock := new_entity(Rock, 3, 5);
// Named arguments work too!
door := new_entity(T = Door, x = 3, y = 6);
// And named arguments can be any order
monster := new_entity(
y = 1,
x = 2,
T = Monster,
);
append(&entities, rock, door, monster);
fmt.println("Union");
for entity in entities {
match e in entity.variant {
case Rock: fmt.println("Rock", e.x, e.y);
case Door: fmt.println("Door", e.x, e.y);
case Monster: fmt.println("Monster", e.x, e.y);
}
}
}
}
implicit_polymorphic_assignment :: proc() {
yep :: proc(p: proc(x: int)) {
p(123);
}
frank :: proc(x: $T) do fmt.println("frank ->", x);
tim :: proc(x, y: $T) do fmt.println("tim ->", x, y);
yep(frank);
// yep(tim);
}
main :: proc() {
/*
foo :: proc(x: i64, y: f32) do fmt.println("#1", x, y);
foo :: proc(x: type, y: f32) do fmt.println("#2", type_info(x), y);
foo :: proc(x: type) do fmt.println("#3", type_info(x));
f :: foo;
f(y = 3785.1546, x = 123);
f(x = int, y = 897.513);
f(x = f32);
general_stuff();
foreign_blocks();
default_arguments();
named_arguments();
default_return_values();
call_location();
explicit_parametric_polymorphic_procedures();
implicit_polymorphic_assignment();
// Command line argument(s)!
// -opt=0,1,2,3
*/
/*
program := "+ + * - /";
accumulator := 0;
for token in program {
match token {
case '+': accumulator += 1;
case '-': accumulator -= 1;
case '*': accumulator *= 2;
case '/': accumulator /= 2;
case: // Ignore everything else
}
}
fmt.printf("The program \"%s\" calculates the value %d\n",
program, accumulator);
*/
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 246 KiB

After

Width:  |  Height:  |  Size: 72 KiB

+136 -29
View File
@@ -10,47 +10,87 @@ struct Array {
isize capacity;
T &operator[](isize index) {
GB_ASSERT_MSG(0 <= index && index < count, "Index out of bounds");
#if !defined(NO_ARRAY_BOUNDS_CHECK)
GB_ASSERT_MSG(0 <= index && index < count, "Index %td is out of bounds ranges 0..<%td", index, count);
#endif
return data[index];
}
T const &operator[](isize index) const {
GB_ASSERT_MSG(0 <= index && index < count, "Index out of bounds");
#if !defined(NO_ARRAY_BOUNDS_CHECK)
GB_ASSERT_MSG(0 <= index && index < count, "Index %td is out of bounds ranges 0..<%td", index, count);
#endif
return data[index];
}
};
template <typename T> void array_init (Array<T> *array, gbAllocator a, isize init_capacity = ARRAY_GROW_FORMULA(0));
template <typename T> void array_init_count (Array<T> *array, gbAllocator a, isize count);
template <typename T> Array<T> array_make (T *data, isize count, isize capacity);
template <typename T> void array_free (Array<T> *array);
template <typename T> void array_add (Array<T> *array, T const &t);
template <typename T> T array_pop (Array<T> *array);
template <typename T> void array_clear (Array<T> *array);
template <typename T> void array_reserve (Array<T> *array, isize capacity);
template <typename T> void array_resize (Array<T> *array, isize count);
template <typename T> void array_set_capacity(Array<T> *array, isize capacity);
template <typename T> void array_init (Array<T> *array, gbAllocator const &a);
template <typename T> void array_init (Array<T> *array, gbAllocator const &a, isize count);
template <typename T> void array_init (Array<T> *array, gbAllocator const &a, isize count, isize capacity);
template <typename T> Array<T> array_make (gbAllocator const &a);
template <typename T> Array<T> array_make (gbAllocator const &a, isize count);
template <typename T> Array<T> array_make (gbAllocator const &a, isize count, isize capacity);
template <typename T> Array<T> array_make_from_ptr (T *data, isize count, isize capacity);
template <typename T> void array_free (Array<T> *array);
template <typename T> void array_add (Array<T> *array, T const &t);
template <typename T> T array_pop (Array<T> *array);
template <typename T> void array_clear (Array<T> *array);
template <typename T> void array_reserve (Array<T> *array, isize capacity);
template <typename T> void array_resize (Array<T> *array, isize count);
template <typename T> void array_set_capacity (Array<T> *array, isize capacity);
template <typename T> Array<T> array_slice (Array<T> const &array, isize lo, isize hi);
template <typename T> void array_ordered_remove (Array<T> *array, isize index);
template <typename T> void array_unordered_remove(Array<T> *array, isize index);
template <typename T>
void array_init(Array<T> *array, gbAllocator a, isize init_capacity) {
array->allocator = a;
array->data = gb_alloc_array(a, T, init_capacity);
array->count = 0;
array->capacity = init_capacity;
void array_copy(Array<T> *array, Array<T> const &data, isize offset) {
gb_memmove(array->data+offset, data.data, gb_size_of(T)*data.count);
}
template <typename T>
void array_copy(Array<T> *array, Array<T> const &data, isize offset, isize count) {
gb_memmove(array->data+offset, data.data, gb_size_of(T)*gb_min(data.count, count));
}
template <typename T>
T *array_end_ptr(Array<T> *array) {
if (array->count > 0) {
return &array->data[array->count-1];
}
return nullptr;
}
template <typename T>
gb_inline void array_init(Array<T> *array, gbAllocator const &a) {
isize cap = ARRAY_GROW_FORMULA(0);
array_init(array, a, 0, cap);
}
template <typename T>
void array_init_count(Array<T> *array, gbAllocator a, isize count) {
gb_inline void array_init(Array<T> *array, gbAllocator const &a, isize count) {
array_init(array, a, count, count);
}
template <typename T>
gb_inline void array_init(Array<T> *array, gbAllocator const &a, isize count, isize capacity) {
array->allocator = a;
array->data = gb_alloc_array(a, T, count);
array->data = nullptr;
if (capacity > 0) {
array->data = gb_alloc_array(a, T, capacity);
}
array->count = count;
array->capacity = count;
array->capacity = capacity;
}
template <typename T>
Array<T> array_make(T *data, isize count, isize capacity) {
gb_inline Array<T> array_make_from_ptr(T *data, isize count, isize capacity) {
Array<T> a = {0};
a.data = data;
a.count = count;
@@ -60,8 +100,39 @@ Array<T> array_make(T *data, isize count, isize capacity) {
template <typename T>
void array_free(Array<T> *array) {
if (array->allocator.proc != NULL) {
gb_inline Array<T> array_make(gbAllocator const &a) {
isize capacity = ARRAY_GROW_FORMULA(0);
Array<T> array = {};
array.allocator = a;
array.data = gb_alloc_array(a, T, capacity);
array.count = 0;
array.capacity = capacity;
return array;
}
template <typename T>
gb_inline Array<T> array_make(gbAllocator const &a, isize count) {
Array<T> array = {};
array.allocator = a;
array.data = gb_alloc_array(a, T, count);
array.count = count;
array.capacity = count;
return array;
}
template <typename T>
gb_inline Array<T> array_make(gbAllocator const &a, isize count, isize capacity) {
Array<T> array = {};
array.allocator = a;
array.data = gb_alloc_array(a, T, capacity);
array.count = count;
array.capacity = capacity;
return array;
}
template <typename T>
gb_inline void array_free(Array<T> *array) {
if (array->allocator.proc != nullptr) {
gb_free(array->allocator, array->data);
}
array->count = 0;
@@ -87,7 +158,7 @@ void array_add(Array<T> *array, T const &t) {
}
template <typename T>
T array_pop(Array<T> *array) {
gb_inline T array_pop(Array<T> *array) {
GB_ASSERT(array->count > 0);
array->count--;
return array->data[array->count];
@@ -123,7 +194,7 @@ void array_set_capacity(Array<T> *array, isize capacity) {
array_resize(array, capacity);
}
T *new_data = NULL;
T *new_data = nullptr;
if (capacity > 0) {
new_data = gb_alloc_array(array->allocator, T, capacity);
gb_memmove(new_data, array->data, gb_size_of(T) * array->capacity);
@@ -133,11 +204,47 @@ void array_set_capacity(Array<T> *array, isize capacity) {
array->capacity = capacity;
}
template <typename T>
gb_inline Array<T> array_slice(Array<T> const &array, isize lo, isize hi) {
GB_ASSERT(0 <= lo && lo <= hi && hi <= array.count);
Array<T> out = {};
isize len = hi-lo;
if (len > 0) {
out.data = array.data+lo;
out.count = len;
out.capacity = len;
}
return out;
}
template <typename T>
void array_ordered_remove(Array<T> *array, isize index) {
GB_ASSERT(0 <= index && index < array->count);
isize bytes = gb_size_of(T) * (array->count-(index+1));
gb_memmove(array->data+index, array->data+index+1, bytes);
array->count -= 1;
}
template <typename T>
void array_unordered_remove(Array<T> *array, isize index) {
GB_ASSERT(0 <= index && index < array->count);
isize n = array->count-1;
if (index != n) {
gb_memmove(array->data+index, array->data+n, gb_size_of(T));
}
array_pop(array);
}
#endif
#if 0
#define Array(Type_) struct { \
gbAllocator allocator; \
gbAllocator const &allocator; \
Type_ * e; \
isize count; \
isize capacity; \
@@ -147,7 +254,7 @@ typedef Array(void) ArrayVoid;
#define array_init_reserve(x_, allocator_, init_capacity_) do { \
void **e = cast(void **)&((x_)->e); \
GB_ASSERT((x_) != NULL); \
GB_ASSERT((x_) != nullptr); \
(x_)->allocator = (allocator_); \
(x_)->count = 0; \
(x_)->capacity = (init_capacity_); \
@@ -156,7 +263,7 @@ typedef Array(void) ArrayVoid;
#define array_init_count(x_, allocator_, init_count_) do { \
void **e = cast(void **)&((x_)->e); \
GB_ASSERT((x_) != NULL); \
GB_ASSERT((x_) != nullptr); \
(x_)->allocator = (allocator_); \
(x_)->count = (init_count_); \
(x_)->capacity = (init_count_); \
@@ -203,7 +310,7 @@ typedef Array(void) ArrayVoid;
void array__set_capacity(void *ptr, isize capacity, isize element_size) {
ArrayVoid *x = cast(ArrayVoid *)ptr;
GB_ASSERT(ptr != NULL);
GB_ASSERT(ptr != nullptr);
GB_ASSERT(element_size > 0);
+1434
View File
File diff suppressed because it is too large Load Diff
+370 -113
View File
@@ -1,3 +1,74 @@
enum TargetOsKind {
TargetOs_Invalid,
TargetOs_windows,
TargetOs_osx,
TargetOs_linux,
TargetOs_essence,
TargetOs_COUNT,
};
enum TargetArchKind {
TargetArch_Invalid,
TargetArch_amd64,
TargetArch_386,
TargetArch_COUNT,
};
enum TargetEndianKind {
TargetEndian_Invalid,
TargetEndian_Little,
TargetEndian_Big,
TargetEndian_COUNT,
};
String target_os_names[TargetOs_COUNT] = {
str_lit(""),
str_lit("windows"),
str_lit("osx"),
str_lit("linux"),
str_lit("essence"),
};
String target_arch_names[TargetArch_COUNT] = {
str_lit(""),
str_lit("amd64"),
str_lit("386"),
};
String target_endian_names[TargetEndian_COUNT] = {
str_lit(""),
str_lit("little"),
str_lit("big"),
};
TargetEndianKind target_endians[TargetArch_COUNT] = {
TargetEndian_Invalid,
TargetEndian_Little,
TargetEndian_Little,
};
String const ODIN_VERSION = str_lit("0.9.0");
String cross_compile_target = str_lit("");
String cross_compile_lib_dir = str_lit("");
struct TargetMetrics {
TargetOsKind os;
TargetArchKind arch;
isize word_size;
isize max_align;
};
// This stores the information for the specify architecture of this build
struct BuildContext {
// Constants
@@ -7,24 +78,167 @@ struct BuildContext {
String ODIN_VENDOR; // compiler vendor
String ODIN_VERSION; // compiler version
String ODIN_ROOT; // Odin ROOT
bool ODIN_DEBUG; // Odin in debug mode
// In bytes
i64 word_size; // Size of a pointer, must be >= 4
i64 max_align; // max alignment, must be >= 1 (and typically >= word_size)
String command;
TargetMetrics metrics;
String out_filepath;
String resource_filepath;
bool has_resource;
String opt_flags;
String llc_flags;
String link_flags;
bool is_dll;
bool generate_docs;
i32 optimization_level;
bool show_timings;
bool keep_temp_files;
bool no_bounds_check;
bool no_output_files;
bool no_crt;
bool use_lld;
bool vet;
gbAffinity affinity;
isize thread_count;
};
gb_global BuildContext build_context = {0};
gb_global TargetMetrics target_windows_386 = {
TargetOs_windows,
TargetArch_386,
4,
8,
};
gb_global TargetMetrics target_windows_amd64 = {
TargetOs_windows,
TargetArch_amd64,
8,
16,
};
gb_global TargetMetrics target_linux_386 = {
TargetOs_linux,
TargetArch_386,
4,
8,
};
gb_global TargetMetrics target_linux_amd64 = {
TargetOs_linux,
TargetArch_amd64,
8,
16,
};
gb_global TargetMetrics target_osx_amd64 = {
TargetOs_osx,
TargetArch_amd64,
8,
16,
};
TargetOsKind get_target_os_from_string(String str) {
for (isize i = 0; i < TargetOs_COUNT; i++) {
if (str_eq_ignore_case(target_os_names[i], str)) {
return cast(TargetOsKind)i;
}
}
return TargetOs_Invalid;
}
TargetArchKind get_target_arch_from_string(String str) {
for (isize i = 0; i < TargetArch_COUNT; i++) {
if (str_eq_ignore_case(target_arch_names[i], str)) {
return cast(TargetArchKind)i;
}
}
return TargetArch_Invalid;
}
bool is_excluded_target_filename(String name) {
String const ext = str_lit(".odin");
String original_name = name;
GB_ASSERT(string_ends_with(name, ext));
name = substring(name, 0, name.len-ext.len);
String str1 = {};
String str2 = {};
isize n = 0;
str1 = name;
n = str1.len;
for (isize i = str1.len-1; i >= 0 && str1[i] != '_'; i--) {
n -= 1;
}
str1 = substring(str1, n, str1.len);
str2 = substring(name, 0, gb_max(n-1, 0));
n = str2.len;
for (isize i = str2.len-1; i >= 0 && str2[i] != '_'; i--) {
n -= 1;
}
str2 = substring(str2, n, str2.len);
if (str1 == name) {
return false;
}
TargetOsKind os1 = get_target_os_from_string(str1);
TargetArchKind arch1 = get_target_arch_from_string(str1);
TargetOsKind os2 = get_target_os_from_string(str2);
TargetArchKind arch2 = get_target_arch_from_string(str2);
if (os1 != TargetOs_Invalid && arch2 != TargetArch_Invalid) {
return os1 != build_context.metrics.os || arch2 != build_context.metrics.arch;
} else if (arch1 != TargetArch_Invalid && os2 != TargetOs_Invalid) {
return arch1 != build_context.metrics.arch || os2 != build_context.metrics.os;
} else if (os1 != TargetOs_Invalid) {
return os1 != build_context.metrics.os;
} else if (arch1 != TargetArch_Invalid) {
return arch1 != build_context.metrics.arch;
}
return false;
}
struct LibraryCollections {
String name;
String path;
};
gb_global Array<LibraryCollections> library_collections = {0};
void add_library_collection(String name, String path) {
// TODO(bill): Check the path is valid and a directory
LibraryCollections lc = {name, string_trim_whitespace(path)};
array_add(&library_collections, lc);
}
bool find_library_collection_path(String name, String *path) {
for_array(i, library_collections) {
if (library_collections[i].name == name) {
if (path) *path = library_collections[i].path;
return true;
}
}
return false;
}
// TODO(bill): OS dependent versions for the BuildContext
@@ -40,7 +254,6 @@ String const NIX_SEPARATOR_STRING = {cast(u8 *)"/", 1};
#if defined(GB_SYSTEM_WINDOWS)
String odin_root_dir(void) {
String path = global_module_path;
Array<wchar_t> path_buf;
isize len, i;
gbTempArenaMemory tmp;
wchar_t *text;
@@ -49,13 +262,13 @@ String odin_root_dir(void) {
return global_module_path;
}
array_init_count(&path_buf, heap_allocator(), 300);
auto path_buf = array_make<wchar_t>(heap_allocator(), 300);
len = 0;
for (;;) {
len = GetModuleFileNameW(NULL, &path_buf[0], path_buf.count);
len = GetModuleFileNameW(nullptr, &path_buf[0], cast(int)path_buf.count);
if (len == 0) {
return make_string(NULL, 0);
return make_string(nullptr, 0);
}
if (len < path_buf.count) {
break;
@@ -64,12 +277,15 @@ String odin_root_dir(void) {
}
len += 1; // NOTE(bill): It needs an extra 1 for some reason
gb_mutex_lock(&string_buffer_mutex);
defer (gb_mutex_unlock(&string_buffer_mutex));
tmp = gb_temp_arena_memory_begin(&string_buffer_arena);
defer (gb_temp_arena_memory_end(tmp));
text = gb_alloc_array(string_buffer_allocator, wchar_t, len+1);
GetModuleFileNameW(NULL, text, len);
GetModuleFileNameW(nullptr, text, cast(int)len);
path = string16_to_string(heap_allocator(), make_string16(text, len));
for (i = path.len-1; i >= 0; i--) {
@@ -83,7 +299,6 @@ String odin_root_dir(void) {
global_module_path = path;
global_module_path_set = true;
gb_temp_arena_memory_end(tmp);
array_free(&path_buf);
@@ -96,7 +311,6 @@ String odin_root_dir(void) {
String odin_root_dir(void) {
String path = global_module_path;
Array<char> path_buf;
isize len, i;
gbTempArenaMemory tmp;
u8 *text;
@@ -105,7 +319,7 @@ String odin_root_dir(void) {
return global_module_path;
}
array_init_count(&path_buf, heap_allocator(), 300);
auto path_buf = array_make<char>(heap_allocator(), 300);
len = 0;
for (;;) {
@@ -119,8 +333,12 @@ String odin_root_dir(void) {
}
}
gb_mutex_lock(&string_buffer_mutex);
defer (gb_mutex_unlock(&string_buffer_mutex));
tmp = gb_temp_arena_memory_begin(&string_buffer_arena);
defer (gb_temp_arena_memory_end(tmp));
text = gb_alloc_array(string_buffer_allocator, u8, len + 1);
gb_memmove(text, &path_buf[0], len);
@@ -136,7 +354,6 @@ String odin_root_dir(void) {
global_module_path = path;
global_module_path_set = true;
gb_temp_arena_memory_end(tmp);
// array_free(&path_buf);
@@ -149,7 +366,6 @@ String odin_root_dir(void) {
String odin_root_dir(void) {
String path = global_module_path;
Array<char> path_buf;
isize len, i;
gbTempArenaMemory tmp;
u8 *text;
@@ -158,7 +374,8 @@ String odin_root_dir(void) {
return global_module_path;
}
array_init_count(&path_buf, heap_allocator(), 300);
auto path_buf = array_make<char>(heap_allocator(), 300);
defer (array_free(&path_buf));
len = 0;
for (;;) {
@@ -168,7 +385,7 @@ String odin_root_dir(void) {
// path without checking this link. Sorry.
len = readlink("/proc/self/exe", &path_buf[0], path_buf.count);
if(len == 0) {
return make_string(NULL, 0);
return make_string(nullptr, 0);
}
if (len < path_buf.count) {
break;
@@ -176,9 +393,14 @@ String odin_root_dir(void) {
array_resize(&path_buf, 2*path_buf.count + 300);
}
gb_mutex_lock(&string_buffer_mutex);
defer (gb_mutex_unlock(&string_buffer_mutex));
tmp = gb_temp_arena_memory_begin(&string_buffer_arena);
defer (gb_temp_arena_memory_end(tmp));
text = gb_alloc_array(string_buffer_allocator, u8, len + 1);
gb_memmove(text, &path_buf[0], len);
path = make_string(text, len);
@@ -193,10 +415,6 @@ String odin_root_dir(void) {
global_module_path = path;
global_module_path_set = true;
gb_temp_arena_memory_end(tmp);
array_free(&path_buf);
return path;
}
#endif
@@ -204,25 +422,32 @@ String odin_root_dir(void) {
#if defined(GB_SYSTEM_WINDOWS)
String path_to_fullpath(gbAllocator a, String s) {
gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&string_buffer_arena);
String16 string16 = string_to_string16(string_buffer_allocator, s);
String result = {0};
String result = {};
gb_mutex_lock(&string_buffer_mutex);
defer (gb_mutex_unlock(&string_buffer_mutex));
DWORD len = GetFullPathNameW(&string16[0], 0, NULL, NULL);
gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&string_buffer_arena);
defer (gb_temp_arena_memory_end(tmp));
String16 string16 = string_to_string16(string_buffer_allocator, s);
DWORD len = GetFullPathNameW(&string16[0], 0, nullptr, nullptr);
if (len != 0) {
wchar_t *text = gb_alloc_array(string_buffer_allocator, wchar_t, len+1);
GetFullPathNameW(&string16[0], len, text, NULL);
GetFullPathNameW(&string16[0], len, text, nullptr);
text[len] = 0;
result = string16_to_string(a, make_string16(text, len));
result = string_trim_whitespace(result);
}
gb_temp_arena_memory_end(tmp);
return result;
}
#elif defined(GB_SYSTEM_OSX) || defined(GB_SYSTEM_UNIX)
String path_to_fullpath(gbAllocator a, String s) {
char *p = realpath(cast(char *)&s[0], 0);
if(p == NULL) return make_string_c("");
char *p;
gb_mutex_lock(&string_buffer_mutex);
p = realpath(cast(char *)s.text, 0);
gb_mutex_unlock(&string_buffer_mutex);
if(p == nullptr) return String{};
return make_string_c(p);
}
#else
@@ -231,130 +456,162 @@ String path_to_fullpath(gbAllocator a, String s) {
String get_fullpath_relative(gbAllocator a, String base_dir, String path) {
String res = {0};
isize str_len = base_dir.len+path.len;
u8 *str = gb_alloc_array(heap_allocator(), u8, str_len+1);
u8 *str = gb_alloc_array(heap_allocator(), u8, base_dir.len+1+path.len+1);
defer (gb_free(heap_allocator(), str));
isize i = 0;
gb_memmove(str+i, &base_dir[0], base_dir.len); i += base_dir.len;
gb_memmove(str+i, &path[0], path.len);
str[str_len] = '\0';
res = path_to_fullpath(a, make_string(str, str_len));
gb_free(heap_allocator(), str);
return res;
gb_memmove(str+i, base_dir.text, base_dir.len); i += base_dir.len;
gb_memmove(str+i, "/", 1); i += 1;
gb_memmove(str+i, path.text, path.len); i += path.len;
str[i] = 0;
String res = make_string(str, i);
res = string_trim_whitespace(res);
return path_to_fullpath(a, res);
}
String get_fullpath_core(gbAllocator a, String path) {
String module_dir = odin_root_dir();
String res = {0};
char core[] = "core/";
isize core_len = gb_size_of(core)-1;
String core = str_lit("core/");
isize str_len = module_dir.len + core_len + path.len;
isize str_len = module_dir.len + core.len + path.len;
u8 *str = gb_alloc_array(heap_allocator(), u8, str_len+1);
defer (gb_free(heap_allocator(), str));
gb_memmove(str, &module_dir[0], module_dir.len);
gb_memmove(str+module_dir.len, core, core_len);
gb_memmove(str+module_dir.len+core_len, &path[0], path.len);
str[str_len] = '\0';
isize i = 0;
gb_memmove(str+i, module_dir.text, module_dir.len); i += module_dir.len;
gb_memmove(str+i, core.text, core.len); i += core.len;
gb_memmove(str+i, path.text, path.len); i += path.len;
str[i] = 0;
res = path_to_fullpath(a, make_string(str, str_len));
gb_free(heap_allocator(), str);
return res;
String res = make_string(str, i);
res = string_trim_whitespace(res);
return path_to_fullpath(a, res);
}
void init_build_context(void) {
BuildContext *bc = &build_context;
bc->ODIN_VENDOR = str_lit("odin");
bc->ODIN_VERSION = str_lit("0.5.0");
bc->ODIN_ROOT = odin_root_dir();
#if defined(GB_SYSTEM_WINDOWS)
bc->ODIN_OS = str_lit("windows");
#elif defined(GB_SYSTEM_OSX)
bc->ODIN_OS = str_lit("osx");
#else
bc->ODIN_OS = str_lit("linux");
#endif
#if defined(GB_ARCH_64_BIT)
bc->ODIN_ARCH = str_lit("amd64");
#else
bc->ODIN_ARCH = str_lit("x86");
#endif
{
u16 x = 1;
bool big = !(*cast(u8 *)&x);
bc->ODIN_ENDIAN = big ? str_lit("big") : str_lit("little");
gb_affinity_init(&bc->affinity);
if (bc->thread_count == 0) {
bc->thread_count = gb_max(bc->affinity.thread_count, 1);
}
bc->ODIN_VENDOR = str_lit("odin");
bc->ODIN_VERSION = ODIN_VERSION;
bc->ODIN_ROOT = odin_root_dir();
TargetMetrics metrics = {};
#if defined(GB_ARCH_64_BIT)
#if defined(GB_SYSTEM_WINDOWS)
metrics = target_windows_amd64;
#elif defined(GB_SYSTEM_OSX)
metrics = target_osx_amd64;
#else
metrics = target_linux_amd64;
#endif
#else
#if defined(GB_SYSTEM_WINDOWS)
metrics = target_windows_386;
#elif defined(GB_SYSTEM_OSX)
#error "Unsupported architecture"
#else
metrics = target_linux_386;
#endif
#endif
if (cross_compile_target.len) {
bc->ODIN_OS = cross_compile_target;
}
GB_ASSERT(metrics.os != TargetOs_Invalid);
GB_ASSERT(metrics.arch != TargetArch_Invalid);
GB_ASSERT(metrics.word_size > 1);
GB_ASSERT(metrics.max_align > 1);
bc->metrics = metrics;
bc->ODIN_OS = target_os_names[metrics.os];
bc->ODIN_ARCH = target_arch_names[metrics.arch];
bc->ODIN_ENDIAN = target_endian_names[target_endians[metrics.arch]];
bc->word_size = metrics.word_size;
bc->max_align = metrics.max_align;
bc->link_flags = str_lit(" ");
bc->opt_flags = str_lit(" ");
gbString llc_flags = gb_string_make_reserve(heap_allocator(), 64);
if (bc->ODIN_DEBUG) {
// llc_flags = gb_string_appendc(llc_flags, "-debug-compile ");
}
// NOTE(zangent): The linker flags to set the build architecture are different
// across OSs. It doesn't make sense to allocate extra data on the heap
// here, so I just #defined the linker flags to keep things concise.
#if defined(GB_SYSTEM_WINDOWS)
#define LINK_FLAG_X64 "/machine:x64"
#define LINK_FLAG_X86 "/machine:x86"
if (bc->metrics.arch == TargetArch_amd64) {
llc_flags = gb_string_appendc(llc_flags, "-march=x86-64 ");
#elif defined(GB_SYSTEM_OSX)
// NOTE(zangent): MacOS systems are x64 only, so ld doesn't have
// an architecture option. All compilation done on MacOS must be x64.
GB_ASSERT(bc->ODIN_ARCH == "amd64");
switch (bc->metrics.os) {
case TargetOs_windows:
bc->link_flags = str_lit("/machine:x64 ");
break;
case TargetOs_osx:
break;
case TargetOs_linux:
bc->link_flags = str_lit("-arch x86-64 ");
break;
}
} else if (bc->metrics.arch == TargetArch_386) {
llc_flags = gb_string_appendc(llc_flags, "-march=x86 ");
#define LINK_FLAG_X64 ""
#define LINK_FLAG_X86 ""
#else
// Linux, but also BSDs and the like.
// NOTE(zangent): When clang is swapped out with ld as the linker,
// the commented flags here should be used. Until then, we'll have
// to use alternative build flags made for clang.
/*
#define LINK_FLAG_X64 "-m elf_x86_64"
#define LINK_FLAG_X86 "-m elf_i386"
*/
#define LINK_FLAG_X64 "-arch x86-64"
#define LINK_FLAG_X86 "-arch x86"
#endif
if (bc->ODIN_ARCH == "amd64") {
bc->word_size = 8;
bc->max_align = 16;
bc->llc_flags = str_lit("-march=x86-64 ");
bc->link_flags = str_lit(LINK_FLAG_X64 " ");
} else if (bc->ODIN_ARCH == "x86") {
bc->word_size = 4;
bc->max_align = 8;
bc->llc_flags = str_lit("-march=x86 ");
bc->link_flags = str_lit(LINK_FLAG_X86 " ");
switch (bc->metrics.os) {
case TargetOs_windows:
bc->link_flags = str_lit("/machine:x86 ");
break;
case TargetOs_osx:
gb_printf_err("Unsupported architecture\n");
gb_exit(1);
break;
case TargetOs_linux:
bc->link_flags = str_lit("-arch x86 ");
break;
}
} else {
gb_printf_err("This current architecture is not supported");
gb_printf_err("Unsupported architecture\n");;
gb_exit(1);
}
bc->llc_flags = make_string_c(llc_flags);
isize opt_max = 1023;
char *opt_flags_string = gb_alloc_array(heap_allocator(), char, opt_max+1);
isize opt_len = 0;
bc->optimization_level = gb_clamp(bc->optimization_level, 0, 3);
gbString opt_flags = gb_string_make_reserve(heap_allocator(), 64);
if (bc->optimization_level != 0) {
opt_len = gb_snprintf(opt_flags_string, opt_max, "-O%d", bc->optimization_level);
} else {
opt_len = gb_snprintf(opt_flags_string, opt_max, "");
opt_flags = gb_string_append_fmt(opt_flags, "-O%d ", bc->optimization_level);
// NOTE(lachsinc): The following options were previously passed during call
// to opt in main.cpp:exec_llvm_opt().
// -die: Dead instruction elimination
// -memcpyopt: MemCpy optimization
}
if (opt_len > 0) {
opt_len--;
if (bc->ODIN_DEBUG == false) {
opt_flags = gb_string_appendc(opt_flags, "-memcpyopt -die ");
}
bc->opt_flags = make_string(cast(u8 *)opt_flags_string, opt_len);
// NOTE(lachsinc): This optimization option was previously required to get
// around an issue in fmt.odin. Thank bp for tracking it down! Leaving for now until the issue
// is resolved and confirmed by Bill. Maybe it should be readded in non-debug builds.
// if (bc->ODIN_DEBUG == false) {
// opt_flags = gb_string_appendc(opt_flags, "-mem2reg ");
// }
bc->opt_flags = make_string_c(opt_flags);
#undef LINK_FLAG_X64
#undef LINK_FLAG_X86
#undef LINK_FLAG_386
}
+649 -241
View File
File diff suppressed because it is too large Load Diff
+3355 -3605
View File
File diff suppressed because it is too large Load Diff
+1059 -1075
View File
File diff suppressed because it is too large Load Diff
+2553
View File
File diff suppressed because it is too large Load Diff
+2781 -1600
View File
File diff suppressed because it is too large Load Diff
+550
View File
@@ -0,0 +1,550 @@
// checker.hpp
struct Type;
struct Entity;
struct Scope;
struct DeclInfo;
struct AstFile;
struct Checker;
struct CheckerInfo;
struct CheckerContext;
enum AddressingMode;
struct TypeAndValue;
// ExprInfo stores information used for "untyped" expressions
struct ExprInfo {
AddressingMode mode;
Type * type;
ExactValue value;
bool is_lhs; // Debug info
};
gb_inline ExprInfo make_expr_info(AddressingMode mode, Type *type, ExactValue value, bool is_lhs) {
ExprInfo ei = {};
ei.mode = mode;
ei.type = type;
ei.value = value;
ei.is_lhs = is_lhs;
return ei;
}
enum ExprKind {
Expr_Expr,
Expr_Stmt,
};
// Statements and Declarations
enum StmtFlag {
Stmt_BreakAllowed = 1<<0,
Stmt_ContinueAllowed = 1<<1,
Stmt_FallthroughAllowed = 1<<2,
Stmt_CheckScopeDecls = 1<<5,
};
enum BuiltinProcPkg {
BuiltinProcPkg_builtin,
BuiltinProcPkg_intrinsics,
};
struct BuiltinProc {
String name;
isize arg_count;
bool variadic;
ExprKind kind;
BuiltinProcPkg pkg;
};
enum BuiltinProcId {
BuiltinProc_Invalid,
BuiltinProc_len,
BuiltinProc_cap,
BuiltinProc_size_of,
BuiltinProc_align_of,
BuiltinProc_offset_of,
BuiltinProc_type_of,
BuiltinProc_type_info_of,
BuiltinProc_typeid_of,
BuiltinProc_swizzle,
BuiltinProc_complex,
BuiltinProc_real,
BuiltinProc_imag,
BuiltinProc_conj,
BuiltinProc_expand_to_tuple,
BuiltinProc_min,
BuiltinProc_max,
BuiltinProc_abs,
BuiltinProc_clamp,
BuiltinProc_DIRECTIVE, // NOTE(bill): This is used for specialized hash-prefixed procedures
// "Intrinsics"
BuiltinProc_atomic_fence,
BuiltinProc_atomic_fence_acq,
BuiltinProc_atomic_fence_rel,
BuiltinProc_atomic_fence_acqrel,
BuiltinProc_atomic_store,
BuiltinProc_atomic_store_rel,
BuiltinProc_atomic_store_relaxed,
BuiltinProc_atomic_store_unordered,
BuiltinProc_atomic_load,
BuiltinProc_atomic_load_acq,
BuiltinProc_atomic_load_relaxed,
BuiltinProc_atomic_load_unordered,
BuiltinProc_atomic_add,
BuiltinProc_atomic_add_acq,
BuiltinProc_atomic_add_rel,
BuiltinProc_atomic_add_acqrel,
BuiltinProc_atomic_add_relaxed,
BuiltinProc_atomic_sub,
BuiltinProc_atomic_sub_acq,
BuiltinProc_atomic_sub_rel,
BuiltinProc_atomic_sub_acqrel,
BuiltinProc_atomic_sub_relaxed,
BuiltinProc_atomic_and,
BuiltinProc_atomic_and_acq,
BuiltinProc_atomic_and_rel,
BuiltinProc_atomic_and_acqrel,
BuiltinProc_atomic_and_relaxed,
BuiltinProc_atomic_nand,
BuiltinProc_atomic_nand_acq,
BuiltinProc_atomic_nand_rel,
BuiltinProc_atomic_nand_acqrel,
BuiltinProc_atomic_nand_relaxed,
BuiltinProc_atomic_or,
BuiltinProc_atomic_or_acq,
BuiltinProc_atomic_or_rel,
BuiltinProc_atomic_or_acqrel,
BuiltinProc_atomic_or_relaxed,
BuiltinProc_atomic_xor,
BuiltinProc_atomic_xor_acq,
BuiltinProc_atomic_xor_rel,
BuiltinProc_atomic_xor_acqrel,
BuiltinProc_atomic_xor_relaxed,
BuiltinProc_atomic_xchg,
BuiltinProc_atomic_xchg_acq,
BuiltinProc_atomic_xchg_rel,
BuiltinProc_atomic_xchg_acqrel,
BuiltinProc_atomic_xchg_relaxed,
BuiltinProc_atomic_cxchg,
BuiltinProc_atomic_cxchg_acq,
BuiltinProc_atomic_cxchg_rel,
BuiltinProc_atomic_cxchg_acqrel,
BuiltinProc_atomic_cxchg_relaxed,
BuiltinProc_atomic_cxchg_failrelaxed,
BuiltinProc_atomic_cxchg_failacq,
BuiltinProc_atomic_cxchg_acq_failrelaxed,
BuiltinProc_atomic_cxchg_acqrel_failrelaxed,
BuiltinProc_atomic_cxchgweak,
BuiltinProc_atomic_cxchgweak_acq,
BuiltinProc_atomic_cxchgweak_rel,
BuiltinProc_atomic_cxchgweak_acqrel,
BuiltinProc_atomic_cxchgweak_relaxed,
BuiltinProc_atomic_cxchgweak_failrelaxed,
BuiltinProc_atomic_cxchgweak_failacq,
BuiltinProc_atomic_cxchgweak_acq_failrelaxed,
BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed,
BuiltinProc_COUNT,
};
gb_global BuiltinProc builtin_procs[BuiltinProc_COUNT] = {
{STR_LIT(""), 0, false, Expr_Stmt, BuiltinProcPkg_builtin},
{STR_LIT("len"), 1, false, Expr_Expr, BuiltinProcPkg_builtin},
{STR_LIT("cap"), 1, false, Expr_Expr, BuiltinProcPkg_builtin},
{STR_LIT("size_of"), 1, false, Expr_Expr, BuiltinProcPkg_builtin},
{STR_LIT("align_of"), 1, false, Expr_Expr, BuiltinProcPkg_builtin},
{STR_LIT("offset_of"), 2, false, Expr_Expr, BuiltinProcPkg_builtin},
{STR_LIT("type_of"), 1, false, Expr_Expr, BuiltinProcPkg_builtin},
{STR_LIT("type_info_of"), 1, false, Expr_Expr, BuiltinProcPkg_builtin},
{STR_LIT("typeid_of"), 1, false, Expr_Expr, BuiltinProcPkg_builtin},
{STR_LIT("swizzle"), 1, true, Expr_Expr, BuiltinProcPkg_builtin},
{STR_LIT("complex"), 2, false, Expr_Expr, BuiltinProcPkg_builtin},
{STR_LIT("real"), 1, false, Expr_Expr, BuiltinProcPkg_builtin},
{STR_LIT("imag"), 1, false, Expr_Expr, BuiltinProcPkg_builtin},
{STR_LIT("conj"), 1, false, Expr_Expr, BuiltinProcPkg_builtin},
{STR_LIT("expand_to_tuple"), 1, false, Expr_Expr, BuiltinProcPkg_builtin},
{STR_LIT("min"), 2, true, Expr_Expr, BuiltinProcPkg_builtin},
{STR_LIT("max"), 2, true, Expr_Expr, BuiltinProcPkg_builtin},
{STR_LIT("abs"), 1, false, Expr_Expr, BuiltinProcPkg_builtin},
{STR_LIT("clamp"), 3, false, Expr_Expr, BuiltinProcPkg_builtin},
{STR_LIT(""), 0, true, Expr_Expr, BuiltinProcPkg_builtin}, // DIRECTIVE
// "Intrinsics"
{STR_LIT("atomic_fence"), 0, false, Expr_Stmt, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_fence_acq"), 0, false, Expr_Stmt, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_fence_rel"), 0, false, Expr_Stmt, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_fence_acqrel"), 0, false, Expr_Stmt, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_store"), 2, false, Expr_Stmt, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_store_rel"), 2, false, Expr_Stmt, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_store_relaxed"), 2, false, Expr_Stmt, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_store_unordered"), 2, false, Expr_Stmt, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_load"), 1, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_load_acq"), 1, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_load_relaxed"), 1, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_load_unordered"), 1, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_add"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_add_acq"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_add_rel"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_add_acqrel"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_add_relaxed"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_sub"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_sub_acq"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_sub_rel"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_sub_acqrel"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_sub_relaxed"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_and"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_and_acq"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_and_rel"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_and_acqrel"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_and_relaxed"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_nand"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_nand_acq"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_nand_rel"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_nand_acqrel"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_nand_relaxed"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_or"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_or_acq"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_or_rel"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_or_acqrel"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_or_relaxed"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_xor"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_xor_acq"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_xor_rel"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_xor_acqrel"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_xor_relaxed"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_xchg"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_xchg_acq"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_xchg_rel"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_xchg_acqrel"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_xchg_relaxed"), 2, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_cxchg"), 3, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_cxchg_acq"), 3, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_cxchg_rel"), 3, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_cxchg_acqrel"), 3, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_cxchg_relaxed"), 3, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_cxchg_failrelaxed"), 3, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_cxchg_failacq"), 3, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_cxchg_acq_failrelaxed"), 3, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_cxchg_acqrel_failrelaxed"), 3, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_cxchgweak"), 3, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_cxchgweak_acq"), 3, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_cxchgweak_rel"), 3, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_cxchgweak_acqrel"), 3, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_cxchgweak_relaxed"), 3, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_cxchgweak_failrelaxed"), 3, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_cxchgweak_failacq"), 3, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_cxchgweak_acq_failrelaxed"), 3, false, Expr_Expr, BuiltinProcPkg_intrinsics},
{STR_LIT("atomic_cxchgweak_acqrel_failrelaxed"), 3, false, Expr_Expr, BuiltinProcPkg_intrinsics},
};
// Operand is used as an intermediate value whilst checking
// Operands store an addressing mode, the expression being evaluated,
// its type and node, and other specific information for certain
// addressing modes
// Its zero-value is a valid "invalid operand"
struct Operand {
AddressingMode mode;
Type * type;
ExactValue value;
Ast * expr;
BuiltinProcId builtin_id;
Entity * proc_group;
};
struct BlockLabel {
String name;
Ast *label; // Ast_Label;
};
struct AttributeContext {
String link_name;
String link_prefix;
isize init_expr_list_count;
String thread_local_model;
String deprecated_message;
};
AttributeContext make_attribute_context(String link_prefix) {
AttributeContext ac = {};
ac.link_prefix = link_prefix;
return ac;
}
#define DECL_ATTRIBUTE_PROC(_name) bool _name(CheckerContext *c, Ast *elem, String name, ExactValue value, AttributeContext *ac)
typedef DECL_ATTRIBUTE_PROC(DeclAttributeProc);
void check_decl_attributes(CheckerContext *c, Array<Ast *> const &attributes, DeclAttributeProc *proc, AttributeContext *ac);
// DeclInfo is used to store information of certain declarations to allow for "any order" usage
struct DeclInfo {
DeclInfo * parent; // NOTE(bill): only used for procedure literals at the moment
Scope * scope;
Entity *entity;
Ast * type_expr;
Ast * init_expr;
Array<Ast *> attributes;
Ast * proc_lit; // Ast_ProcLit
Type * gen_proc_type; // Precalculated
bool is_using;
PtrSet<Entity *> deps;
PtrSet<Type *> type_info_deps;
Array<BlockLabel> labels;
};
// ProcInfo stores the information needed for checking a procedure
struct ProcInfo {
AstFile * file;
Token token;
DeclInfo *decl;
Type * type; // Type_Procedure
Ast * body; // Ast_BlockStmt
u64 tags;
bool generated_from_polymorphic;
Ast * poly_def_node;
};
enum ScopeFlag {
ScopeFlag_Pkg = 1<<1,
ScopeFlag_Global = 1<<2,
ScopeFlag_File = 1<<3,
ScopeFlag_Init = 1<<4,
ScopeFlag_Proc = 1<<5,
ScopeFlag_Type = 1<<6,
ScopeFlag_HasBeenImported = 1<<10, // This is only applicable to file scopes
};
struct Scope {
Ast * node;
Scope * parent;
Scope * prev;
Scope * next;
Scope * first_child;
Scope * last_child;
Map<Entity *> elements; // Key: String
Array<Ast *> delayed_directives;
Array<Ast *> delayed_imports;
PtrSet<Scope *> imported;
i32 flags; // ScopeFlag
union {
AstPackage *pkg;
AstFile * file;
};
};
struct EntityGraphNode;
typedef PtrSet<EntityGraphNode *> EntityGraphNodeSet;
struct EntityGraphNode {
Entity * entity; // Procedure, Variable, Constant
EntityGraphNodeSet pred;
EntityGraphNodeSet succ;
isize index; // Index in array/queue
isize dep_count;
};
struct ImportGraphNode;
typedef PtrSet<ImportGraphNode *> ImportGraphNodeSet;
struct ImportGraphNode {
AstPackage * pkg;
Scope * scope;
ImportGraphNodeSet pred;
ImportGraphNodeSet succ;
isize index; // Index in array/queue
isize dep_count;
};
struct ForeignContext {
Ast * curr_library;
ProcCallingConvention default_cc;
String link_prefix;
bool in_export;
};
typedef Array<Entity *> CheckerTypePath;
typedef Array<Type *> CheckerPolyPath;
// CheckerInfo stores all the symbol information for a type-checked program
struct CheckerInfo {
Map<ExprInfo> untyped; // Key: Ast * | Expression -> ExprInfo
// NOTE(bill): This needs to be a map and not on the Ast
// as it needs to be iterated across
Map<AstFile *> files; // Key: String (full path)
Map<AstPackage *> packages; // Key: String (full path)
Map<Entity *> foreigns; // Key: String
Array<Entity *> definitions;
Array<Entity *> entities;
Array<DeclInfo *> variable_init_order;
Map<Array<Entity *> > gen_procs; // Key: Ast * | Identifier -> Entity
Map<Array<Entity *> > gen_types; // Key: Type *
Array<Type *> type_info_types;
Map<isize> type_info_map; // Key: Type *
AstPackage * builtin_package;
AstPackage * runtime_package;
Scope * init_scope;
Entity * entry_point;
PtrSet<Entity *> minimum_dependency_set;
PtrSet<isize> minimum_dependency_type_info_set;
};
struct CheckerContext {
Checker * checker;
CheckerInfo * info;
AstPackage * pkg;
AstFile * file;
Scope * scope;
DeclInfo * decl;
u32 stmt_state_flags;
bool in_defer; // TODO(bill): Actually handle correctly
Type * type_hint;
String proc_name;
DeclInfo * curr_proc_decl;
Type * curr_proc_sig;
bool in_proc_sig;
ForeignContext foreign_context;
gbAllocator allocator;
CheckerTypePath *type_path;
isize type_level; // TODO(bill): Actually handle correctly
CheckerPolyPath *poly_path;
isize poly_level; // TODO(bill): Actually handle correctly
bool in_enum_type;
bool collect_delayed_decls;
bool allow_polymorphic_types;
bool no_polymorphic_errors;
bool in_polymorphic_specialization;
Scope * polymorphic_scope;
};
struct Checker {
Parser * parser;
CheckerInfo info;
Array<ProcInfo> procs_to_check;
gbAllocator allocator;
CheckerContext init_ctx;
};
gb_global AstPackage *builtin_pkg = nullptr;
gb_global AstPackage *intrinsics_pkg = nullptr;
HashKey hash_node (Ast *node) { return hash_pointer(node); }
HashKey hash_ast_file (AstFile *file) { return hash_pointer(file); }
HashKey hash_entity (Entity *e) { return hash_pointer(e); }
HashKey hash_type (Type *t) { return hash_pointer(t); }
HashKey hash_decl_info(DeclInfo *decl) { return hash_pointer(decl); }
// CheckerInfo API
TypeAndValue type_and_value_of_expr (Ast *expr);
Type * type_of_expr (Ast *expr);
Entity * entity_of_ident (Ast *identifier);
Entity * implicit_entity_of_node(Ast *clause);
Scope * scope_of_node (Ast *node);
DeclInfo * decl_info_of_ident (Ast *ident);
DeclInfo * decl_info_of_entity (Entity * e);
AstFile * ast_file_of_filename (CheckerInfo *i, String filename);
// IMPORTANT: Only to use once checking is done
isize type_info_index (CheckerInfo *i, Type * type, bool error_on_failure = true);
// Will return nullptr if not found
Entity *entity_of_node(Ast *expr);
Entity *scope_lookup_current(Scope *s, String name);
Entity *scope_lookup (Scope *s, String name);
void scope_lookup_parent (Scope *s, String name, Scope **scope_, Entity **entity_);
Entity *scope_insert (Scope *s, Entity *entity);
ExprInfo *check_get_expr_info (CheckerInfo *i, Ast *expr);
void check_set_expr_info (CheckerInfo *i, Ast *expr, ExprInfo info);
void check_remove_expr_info (CheckerInfo *i, Ast *expr);
void add_untyped (CheckerInfo *i, Ast *expression, bool lhs, AddressingMode mode, Type *basic_type, ExactValue value);
void add_type_and_value (CheckerInfo *i, Ast *expression, AddressingMode mode, Type *type, ExactValue value);
void add_entity_use (CheckerContext *c, Ast *identifier, Entity *entity);
void add_implicit_entity (CheckerContext *c, Ast *node, Entity *e);
void add_entity_and_decl_info(CheckerContext *c, Ast *identifier, Entity *e, DeclInfo *d);
void add_type_info_type (CheckerContext *c, Type *t);
void check_add_import_decl(CheckerContext *c, Ast *decl);
void check_add_foreign_import_decl(CheckerContext *c, Ast *decl);
bool check_arity_match(CheckerContext *c, AstValueDecl *vd, bool is_global = false);
void check_collect_entities(CheckerContext *c, Array<Ast *> const &nodes);
void check_collect_entities_from_when_stmt(CheckerContext *c, AstWhenStmt *ws);
void check_delayed_file_import_entity(CheckerContext *c, Ast *decl);
CheckerTypePath *new_checker_type_path();
void destroy_checker_type_path(CheckerTypePath *tp);
void check_type_path_push(CheckerContext *c, Entity *e);
Entity *check_type_path_pop (CheckerContext *c);
CheckerPolyPath *new_checker_poly_path();
void destroy_checker_poly_path(CheckerPolyPath *);
void check_poly_path_push(CheckerContext *c, Type *t);
Type *check_poly_path_pop (CheckerContext *c);
+729 -104
View File
@@ -3,6 +3,10 @@
#include <xmmintrin.h>
#endif
#if defined(GB_COMPILER_MSVC)
#include <intrin.h>
#endif
#define GB_IMPLEMENTATION
#include "gb/gb.h"
@@ -13,132 +17,446 @@
#include <math.h>
template <typename U, typename V>
gb_inline U bit_cast(V &v) { return reinterpret_cast<U &>(v); }
template <typename U, typename V>
gb_inline U const &bit_cast(V const &v) { return reinterpret_cast<U const &>(v); }
gb_inline i64 align_formula(i64 size, i64 align) {
if (align > 0) {
i64 result = size + align-1;
return result - result%align;
}
return size;
}
gb_inline isize align_formula_isize(isize size, isize align) {
if (align > 0) {
isize result = size + align-1;
return result - result%align;
}
return size;
}
GB_ALLOCATOR_PROC(heap_allocator_proc);
gbAllocator heap_allocator(void) {
return gb_heap_allocator();
}
#include "unicode.cpp"
#include "string.cpp"
#include "array.cpp"
#include "integer128.cpp"
#include "murmurhash3.cpp"
u128 fnv128a(void const *data, isize len) {
u128 o = u128_lo_hi(0x13bull, 0x1000000ull);
u128 h = u128_lo_hi(0x62b821756295c58dull, 0x6c62272e07bb0142ull);
u8 const *bytes = cast(u8 const *)data;
for (isize i = 0; i < len; i++) {
h.lo ^= bytes[i];
h = h * o;
}
return h;
}
#include "map.cpp"
gb_global String global_module_path = {0};
gb_global bool global_module_path_set = false;
gb_global gbScratchMemory scratch_memory = {0};
void init_scratch_memory(isize size) {
void *memory = gb_alloc(heap_allocator(), size);
gb_scratch_memory_init(&scratch_memory, memory, size);
}
gbAllocator scratch_allocator(void) {
return gb_scratch_allocator(&scratch_memory);
gbAllocator a;
a.proc = heap_allocator_proc;
a.data = nullptr;
return a;
}
struct DynamicArenaBlock {
DynamicArenaBlock *prev;
DynamicArenaBlock *next;
u8 * start;
isize count;
isize capacity;
GB_ALLOCATOR_PROC(heap_allocator_proc) {
void *ptr = nullptr;
gb_unused(allocator_data);
gb_unused(old_size);
gbVirtualMemory vm;
};
struct DynamicArena {
DynamicArenaBlock *start_block;
DynamicArenaBlock *current_block;
isize block_size;
};
DynamicArenaBlock *add_dynamic_arena_block(DynamicArena *a) {
GB_ASSERT(a != NULL);
GB_ASSERT(a->block_size > 0);
gbVirtualMemory vm = gb_vm_alloc(NULL, a->block_size);
DynamicArenaBlock *block = cast(DynamicArenaBlock *)vm.data;
u8 *start = cast(u8 *)gb_align_forward(cast(u8 *)(block + 1), GB_DEFAULT_MEMORY_ALIGNMENT);
u8 *end = cast(u8 *)vm.data + vm.size;
block->vm = vm;
block->start = start;
block->count = 0;
block->capacity = end-start;
if (a->current_block != NULL) {
a->current_block->next = block;
block->prev = a->current_block;
}
a->current_block = block;
return block;
}
void init_dynamic_arena(DynamicArena *a, isize block_size) {
isize size = gb_size_of(DynamicArenaBlock) + block_size;
size = cast(isize)gb_align_forward(cast(void *)cast(uintptr)size, GB_DEFAULT_MEMORY_ALIGNMENT);
a->block_size = size;
a->start_block = add_dynamic_arena_block(a);
}
void destroy_dynamic_arena(DynamicArena *a) {
DynamicArenaBlock *b = a->current_block;
while (b != NULL) {
gbVirtualMemory vm = b->vm;
b = b->prev;
gb_vm_free(b->vm);
}
}
GB_ALLOCATOR_PROC(dynamic_arena_allocator_proc) {
DynamicArena *a = cast(DynamicArena *)allocator_data;
void *ptr = NULL;
// TODO(bill): Throughly test!
switch (type) {
case gbAllocation_Alloc: {
#if defined(GB_COMPILER_MSVC)
#if 0
case gbAllocation_Alloc:
ptr = _aligned_malloc(size, alignment);
if (flags & gbAllocatorFlag_ClearToZero) {
gb_zero_size(ptr, size);
}
break;
case gbAllocation_Free:
_aligned_free(old_memory);
break;
case gbAllocation_Resize:
ptr = _aligned_realloc(old_memory, size, alignment);
break;
#else
case gbAllocation_Alloc:
// TODO(bill): Make sure this is aligned correctly
ptr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, align_formula_isize(size, alignment));
break;
case gbAllocation_Free:
HeapFree(GetProcessHeap(), 0, old_memory);
break;
case gbAllocation_Resize:
ptr = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, old_memory, align_formula_isize(size, alignment));
break;
#endif
} break;
#elif defined(GB_SYSTEM_LINUX)
// TODO(bill): *nix version that's decent
case gbAllocation_Alloc: {
ptr = aligned_alloc(alignment, size);
// ptr = malloc(size+alignment);
if (flags & gbAllocatorFlag_ClearToZero) {
gb_zero_size(ptr, size);
}
break;
}
case gbAllocation_Free: {
} break;
free(old_memory);
break;
}
case gbAllocation_Resize: {
} break;
// ptr = realloc(old_memory, size);
ptr = gb_default_resize_align(heap_allocator(), old_memory, old_size, size, alignment);
break;
}
#else
// TODO(bill): *nix version that's decent
case gbAllocation_Alloc: {
posix_memalign(&ptr, alignment, size);
if (flags & gbAllocatorFlag_ClearToZero) {
gb_zero_size(ptr, size);
}
break;
}
case gbAllocation_Free: {
free(old_memory);
break;
}
case gbAllocation_Resize: {
ptr = gb_default_resize_align(heap_allocator(), old_memory, old_size, size, alignment);
break;
}
#endif
case gbAllocation_FreeAll:
GB_PANIC("free_all is not supported by this allocator");
break;
}
return ptr;
}
gbAllocator dynamic_arena_allocator(DynamicArena *a) {
gbAllocator allocator = {dynamic_arena_allocator_proc, a};
return allocator;
#include "unicode.cpp"
#include "string.cpp"
#include "array.cpp"
#include "murmurhash3.cpp"
#define for_array(index_, array_) for (isize index_ = 0; index_ < (array_).count; index_++)
u64 fnv64a(void const *data, isize len) {
u8 const *bytes = cast(u8 const *)data;
u64 h = 0xcbf29ce484222325ull;
for (isize i = 0; i < len; i++) {
u64 b = cast(u64)bytes[i];
h = (h ^ b) * 0x100000001b3ull;
}
return h;
}
u64 u64_digit_value(Rune r) {
if ('0' <= r && r <= '9') {
return r - '0';
} else if ('a' <= r && r <= 'f') {
return r - 'a' + 10;
} else if ('A' <= r && r <= 'F') {
return r - 'A' + 10;
}
return 16; // NOTE(bill): Larger than highest possible
}
u64 u64_from_string(String string) {
u64 base = 10;
bool has_prefix = false;
if (string.len > 2 && string[0] == '0') {
switch (string[1]) {
case 'b': base = 2; has_prefix = true; break;
case 'o': base = 8; has_prefix = true; break;
case 'd': base = 10; has_prefix = true; break;
case 'z': base = 12; has_prefix = true; break;
case 'x': base = 16; has_prefix = true; break;
case 'h': base = 16; has_prefix = true; break;
}
}
u8 *text = string.text;
isize len = string.len;
if (has_prefix) {
text += 2;
len -= 2;
}
u64 result = 0ull;
for (isize i = 0; i < len; i++) {
Rune r = cast(Rune)text[i];
if (r == '_') {
continue;
}
u64 v = u64_digit_value(r);
if (v >= base) {
break;
}
result *= base;
result += v;
}
return result;
}
String u64_to_string(u64 v, char *out_buf, isize out_buf_len) {
char buf[32] = {0};
isize i = gb_size_of(buf);
u64 b = 10;
while (v >= b) {
buf[--i] = gb__num_to_char_table[v%b];
v /= b;
}
buf[--i] = gb__num_to_char_table[v%b];
isize len = gb_min(gb_size_of(buf)-i, out_buf_len);
gb_memmove(out_buf, &buf[i], len);
return make_string(cast(u8 *)out_buf, len);
}
String i64_to_string(i64 a, char *out_buf, isize out_buf_len) {
char buf[32] = {0};
isize i = gb_size_of(buf);
bool negative = false;
if (a < 0) {
negative = true;
a = -a;
}
u64 v = cast(u64)a;
u64 b = 10;
while (v >= b) {
buf[--i] = gb__num_to_char_table[v%b];
v /= b;
}
buf[--i] = gb__num_to_char_table[v%b];
if (negative) {
buf[--i] = '-';
}
isize len = gb_min(gb_size_of(buf)-i, out_buf_len);
gb_memmove(out_buf, &buf[i], len);
return make_string(cast(u8 *)out_buf, len);
}
gb_global i64 const signed_integer_mins[] = {
0,
-128ll,
-32768ll,
0,
-2147483648ll,
0,
0,
0,
(-9223372036854775807ll - 1ll),
};
gb_global i64 const signed_integer_maxs[] = {
0,
127ll,
32767ll,
0,
2147483647ll,
0,
0,
0,
9223372036854775807ll,
};
gb_global u64 const unsigned_integer_maxs[] = {
0,
255ull,
65535ull,
0,
4294967295ull,
0,
0,
0,
18446744073709551615ull,
};
bool add_overflow_u64(u64 x, u64 y, u64 *result) {
*result = x + y;
return *result < x || *result < y;
}
bool sub_overflow_u64(u64 x, u64 y, u64 *result) {
*result = x - y;
return *result > x;
}
void mul_overflow_u64(u64 x, u64 y, u64 *lo, u64 *hi) {
#if defined(GB_COMPILER_MSVC)
*lo = _umul128(x, y, hi);
#else
// URL(bill): https://stackoverflow.com/questions/25095741/how-can-i-multiply-64-bit-operands-and-get-128-bit-result-portably#25096197
u64 u1, v1, w1, t, w3, k;
u1 = (x & 0xffffffff);
v1 = (y & 0xffffffff);
t = (u1 * v1);
w3 = (t & 0xffffffff);
k = (t >> 32);
x >>= 32;
t = (x * v1) + k;
k = (t & 0xffffffff);
w1 = (t >> 32);
y >>= 32;
t = (u1 * y) + k;
k = (t >> 32);
*hi = (x * y) + w1 + k;
*lo = (t << 32) + w3;
#endif
}
#include "map.cpp"
#include "ptr_set.cpp"
#include "string_set.cpp"
#include "priority_queue.cpp"
gb_global String global_module_path = {0};
gb_global bool global_module_path_set = false;
// Arena from Per Vognsen
#define ALIGN_DOWN(n, a) ((n) & ~((a) - 1))
#define ALIGN_UP(n, a) ALIGN_DOWN((n) + (a) - 1, (a))
#define ALIGN_DOWN_PTR(p, a) (cast(void *)ALIGN_DOWN(cast(uintptr)(p), (a)))
#define ALIGN_UP_PTR(p, a) (cast(void *)ALIGN_UP(cast(uintptr)(p), (a)))
typedef struct Arena {
u8 * ptr;
u8 * end;
u8 * prev;
Array<u8 *> blocks;
gbAllocator backing;
isize block_size;
gbMutex mutex;
isize total_used;
} Arena;
#define ARENA_MIN_ALIGNMENT 16
#define ARENA_DEFAULT_BLOCK_SIZE (8*1024*1024)
void arena_init(Arena *arena, gbAllocator backing, isize block_size=ARENA_DEFAULT_BLOCK_SIZE) {
arena->backing = backing;
arena->block_size = block_size;
array_init(&arena->blocks, backing);
gb_mutex_init(&arena->mutex);
}
void arena_grow(Arena *arena, isize min_size) {
gb_mutex_lock(&arena->mutex);
defer (gb_mutex_unlock(&arena->mutex));
isize size = gb_max(arena->block_size, min_size);
size = ALIGN_UP(size, ARENA_MIN_ALIGNMENT);
void *new_ptr = gb_alloc(arena->backing, size);
arena->ptr = cast(u8 *)new_ptr;
gb_zero_size(arena->ptr, size);
GB_ASSERT(arena->ptr == ALIGN_DOWN_PTR(arena->ptr, ARENA_MIN_ALIGNMENT));
arena->end = arena->ptr + size;
array_add(&arena->blocks, arena->ptr);
}
void *arena_alloc(Arena *arena, isize size, isize alignment) {
gb_mutex_lock(&arena->mutex);
defer (gb_mutex_unlock(&arena->mutex));
arena->total_used += size;
if (size > (arena->end - arena->ptr)) {
arena_grow(arena, size);
GB_ASSERT(size <= (arena->end - arena->ptr));
}
isize align = gb_max(alignment, ARENA_MIN_ALIGNMENT);
void *ptr = arena->ptr;
arena->prev = arena->ptr;
arena->ptr = cast(u8 *)ALIGN_UP_PTR(arena->ptr + size, align);
GB_ASSERT(arena->ptr <= arena->end);
GB_ASSERT(ptr == ALIGN_DOWN_PTR(ptr, align));
gb_zero_size(ptr, size);
return ptr;
}
void arena_free_all(Arena *arena) {
gb_mutex_lock(&arena->mutex);
defer (gb_mutex_unlock(&arena->mutex));
for_array(i, arena->blocks) {
gb_free(arena->backing, arena->blocks[i]);
}
array_clear(&arena->blocks);
arena->ptr = nullptr;
arena->end = nullptr;
}
GB_ALLOCATOR_PROC(arena_allocator_proc);
gbAllocator arena_allocator(Arena *arena) {
gbAllocator a;
a.proc = arena_allocator_proc;
a.data = arena;
return a;
}
GB_ALLOCATOR_PROC(arena_allocator_proc) {
void *ptr = nullptr;
Arena *arena = cast(Arena *)allocator_data;
GB_ASSERT_NOT_NULL(arena);
switch (type) {
case gbAllocation_Alloc:
ptr = arena_alloc(arena, size, alignment);
break;
case gbAllocation_Free:
GB_PANIC("gbAllocation_Free not supported");
break;
case gbAllocation_Resize:
GB_PANIC("gbAllocation_Resize: not supported");
break;
case gbAllocation_FreeAll:
arena_free_all(arena);
break;
}
return ptr;
}
i32 next_pow2(i32 n) {
if (n <= 0) {
return 0;
}
n--;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n++;
return n;
}
i64 next_pow2(i64 n) {
if (n <= 0) {
return 0;
@@ -154,6 +472,79 @@ i64 next_pow2(i64 n) {
return n;
}
i32 bit_set_count(u32 x) {
x -= ((x >> 1) & 0x55555555);
x = (((x >> 2) & 0x33333333) + (x & 0x33333333));
x = (((x >> 4) + x) & 0x0f0f0f0f);
x += (x >> 8);
x += (x >> 16);
return cast(i32)(x & 0x0000003f);
}
i64 bit_set_count(u64 x) {
u32 a = *(cast(u32 *)&x);
u32 b = *(cast(u32 *)&x + 1);
return bit_set_count(a) + bit_set_count(b);
}
u32 floor_log2(u32 x) {
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return cast(u32)(bit_set_count(x) - 1);
}
u64 floor_log2(u64 x) {
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x |= x >> 32;
return cast(u64)(bit_set_count(x) - 1);
}
u32 ceil_log2(u32 x) {
i32 y = cast(i32)(x & (x-1));
y |= -y;
y >>= 32-1;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return cast(u32)(bit_set_count(x) - 1 - y);
}
u64 ceil_log2(u64 x) {
i64 y = cast(i64)(x & (x-1));
y |= -y;
y >>= 64-1;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x |= x >> 32;
return cast(u64)(bit_set_count(x) - 1 - y);
}
i32 prev_pow2(i32 n) {
if (n <= 0) {
return 0;
}
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
return n - (n >> 1);
}
i64 prev_pow2(i64 n) {
if (n <= 0) {
return 0;
@@ -224,7 +615,6 @@ f64 gb_sqrt(f64 x) {
#define for_array(index_, array_) for (isize index_ = 0; index_ < (array_).count; index_++)
// Doubly Linked Lists
@@ -236,7 +626,7 @@ f64 gb_sqrt(f64 x) {
} while (0)
#define DLIST_APPEND(root_element, curr_element, next_element) do { \
if ((root_element) == NULL) { \
if ((root_element) == nullptr) { \
(root_element) = (curr_element) = (next_element); \
} else { \
DLIST_SET(curr_element, next_element); \
@@ -250,7 +640,7 @@ f64 gb_sqrt(f64 x) {
wchar_t **command_line_to_wargv(wchar_t *cmd_line, int *_argc) {
u32 i, j;
u32 len = string16_len(cmd_line);
u32 len = cast(u32)string16_len(cmd_line);
i = ((len+2)/2)*gb_size_of(void *) + gb_size_of(void *);
wchar_t **argv = cast(wchar_t **)GlobalAlloc(GMEM_FIXED, i + (len+2)*gb_size_of(wchar_t));
@@ -302,10 +692,245 @@ wchar_t **command_line_to_wargv(wchar_t *cmd_line, int *_argc) {
i++;
}
_argv[j] = '\0';
argv[argc] = NULL;
argv[argc] = nullptr;
if (_argc) *_argc = argc;
return argv;
}
#endif
#if defined(GB_SYSTEM_WINDOWS)
bool path_is_directory(String path) {
gbAllocator a = heap_allocator();
String16 wstr = string_to_string16(a, path);
defer (gb_free(a, wstr.text));
i32 attribs = GetFileAttributesW(wstr.text);
if (attribs < 0) return false;
return (attribs & FILE_ATTRIBUTE_DIRECTORY) != 0;
}
#else
bool path_is_directory(String path) {
gbAllocator a = heap_allocator();
char *copy = cast(char *)copy_string(a, path).text;
defer (gb_free(a, copy));
struct stat s;
if (stat(copy, &s) == 0) {
return (s.st_mode & S_IFDIR) != 0;
}
return false;
}
#endif
String path_to_full_path(gbAllocator a, String path) {
gbAllocator ha = heap_allocator();
char *path_c = gb_alloc_str_len(ha, cast(char *)path.text, path.len);
defer (gb_free(ha, path_c));
char *fullpath = gb_path_get_full_name(a, path_c);
return make_string_c(fullpath);
}
struct FileInfo {
String name;
String fullpath;
i64 size;
bool is_dir;
};
enum ReadDirectoryError {
ReadDirectory_None,
ReadDirectory_InvalidPath,
ReadDirectory_NotExists,
ReadDirectory_Permission,
ReadDirectory_NotDir,
ReadDirectory_Empty,
ReadDirectory_Unknown,
ReadDirectory_COUNT,
};
i64 get_file_size(String path) {
char *c_str = alloc_cstring(heap_allocator(), path);
defer (gb_free(heap_allocator(), c_str));
gbFile f = {};
gbFileError err = gb_file_open(&f, c_str);
defer (gb_file_close(&f));
if (err != gbFileError_None) {
return -1;
}
return gb_file_size(&f);
}
#if defined(GB_SYSTEM_WINDOWS)
ReadDirectoryError read_directory(String path, Array<FileInfo> *fi) {
GB_ASSERT(fi != nullptr);
gbAllocator a = heap_allocator();
while (path.len > 0) {
Rune end = path[path.len-1];
if (end == '/') {
path.len -= 1;
} else if (end == '\\') {
path.len -= 1;
} else {
break;
}
}
if (path.len == 0) {
return ReadDirectory_InvalidPath;
}
{
char *c_str = alloc_cstring(a, path);
defer (gb_free(a, c_str));
gbFile f = {};
gbFileError file_err = gb_file_open(&f, c_str);
defer (gb_file_close(&f));
switch (file_err) {
case gbFileError_Invalid: return ReadDirectory_InvalidPath;
case gbFileError_NotExists: return ReadDirectory_NotExists;
// case gbFileError_Permission: return ReadDirectory_Permission;
}
}
if (!path_is_directory(path)) {
return ReadDirectory_NotDir;
}
char *new_path = gb_alloc_array(a, char, path.len+3);
defer (gb_free(a, new_path));
gb_memmove(new_path, path.text, path.len);
gb_memmove(new_path+path.len, "/*", 2);
new_path[path.len+2] = 0;
String np = make_string(cast(u8 *)new_path, path.len+2);
String16 wstr = string_to_string16(a, np);
defer (gb_free(a, wstr.text));
WIN32_FIND_DATAW file_data = {};
HANDLE find_file = FindFirstFileW(wstr.text, &file_data);
if (find_file == INVALID_HANDLE_VALUE) {
return ReadDirectory_Unknown;
}
defer (FindClose(find_file));
array_init(fi, a, 0, 100);
do {
wchar_t *filename_w = file_data.cFileName;
i64 size = cast(i64)file_data.nFileSizeLow;
size |= (cast(i64)file_data.nFileSizeHigh) << 32;
String name = string16_to_string(a, make_string16_c(filename_w));
if (name == "." || name == "..") {
gb_free(a, name.text);
continue;
}
String filepath = {};
filepath.len = path.len+1+name.len;
filepath.text = gb_alloc_array(a, u8, filepath.len+1);
defer (gb_free(a, filepath.text));
gb_memmove(filepath.text, path.text, path.len);
gb_memmove(filepath.text+path.len, "/", 1);
gb_memmove(filepath.text+path.len+1, name.text, name.len);
FileInfo info = {};
info.name = name;
info.fullpath = path_to_full_path(a, filepath);
info.size = size;
info.is_dir = (file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
array_add(fi, info);
} while (FindNextFileW(find_file, &file_data));
if (fi->count == 0) {
return ReadDirectory_Empty;
}
return ReadDirectory_None;
}
#elif defined(GB_SYSTEM_LINUX) || defined(GB_SYSTEM_OSX)
#include <dirent.h>
ReadDirectoryError read_directory(String path, Array<FileInfo> *fi) {
GB_ASSERT(fi != nullptr);
gbAllocator a = heap_allocator();
char *c_path = alloc_cstring(a, path);
defer (gb_free(a, c_path));
DIR *dir = opendir(c_path);
if (!dir) {
return ReadDirectory_NotDir;
}
array_init(fi, a, 0, 100);
for (;;) {
struct dirent *entry = readdir(dir);
if (entry == nullptr) {
break;
}
String name = make_string_c(entry->d_name);
if (name == "." || name == "..") {
continue;
}
String filepath = {};
filepath.len = path.len+1+name.len;
filepath.text = gb_alloc_array(a, u8, filepath.len+1);
defer (gb_free(a, filepath.text));
gb_memmove(filepath.text, path.text, path.len);
gb_memmove(filepath.text+path.len, "/", 1);
gb_memmove(filepath.text+path.len+1, name.text, name.len);
filepath.text[filepath.len] = 0;
struct stat dir_stat = {};
if (stat((char *)filepath.text, &dir_stat)) {
continue;
}
if (S_ISDIR(dir_stat.st_mode)) {
continue;
}
i64 size = dir_stat.st_size;
FileInfo info = {};
info.name = name;
info.fullpath = path_to_full_path(a, filepath);
info.size = size;
array_add(fi, info);
}
if (fi->count == 0) {
return ReadDirectory_Empty;
}
return ReadDirectory_None;
}
#else
#error Implement read_directory
#endif
+20 -49
View File
@@ -1,6 +1,6 @@
// Generates Documentation
gbString expr_to_string(AstNode *expression);
gbString expr_to_string(Ast *expression);
String alloc_comment_group_string(gbAllocator a, CommentGroup g) {
isize len = 0;
@@ -10,7 +10,7 @@ String alloc_comment_group_string(gbAllocator a, CommentGroup g) {
len += 1; // for \n
}
if (len == 0) {
return make_string(NULL, 0);
return make_string(nullptr, 0);
}
u8 *text = gb_alloc_array(a, u8, len+1);
@@ -32,9 +32,10 @@ String alloc_comment_group_string(gbAllocator a, CommentGroup g) {
return make_string(text, len);
}
void print_type_spec(AstNode *spec) {
#if 0
void print_type_spec(Ast *spec) {
ast_node(ts, TypeSpec, spec);
GB_ASSERT(ts->name->kind == AstNode_Ident);
GB_ASSERT(ts->name->kind == Ast_Ident);
String name = ts->name->Ident.string;
if (name.len == 0) {
return;
@@ -45,8 +46,8 @@ void print_type_spec(AstNode *spec) {
gb_printf("type %.*s\n", LIT(name));
}
void print_proc_decl(AstNodeProcDecl *pd) {
GB_ASSERT(pd->name->kind == AstNode_Ident);
void print_proc_decl(AstProcDecl *pd) {
GB_ASSERT(pd->name->kind == Ast_Ident);
String name = pd->name->Ident.string;
if (name.len == 0) {
return;
@@ -69,7 +70,7 @@ void print_proc_decl(AstNodeProcDecl *pd) {
gbString params = expr_to_string(proc_type->params);
defer (gb_string_free(params));
gb_printf("proc %.*s(%s)", LIT(name), params);
if (proc_type->results != NULL) {
if (proc_type->results != nullptr) {
ast_node(fl, FieldList, proc_type->results);
isize count = fl->list.count;
if (count > 0) {
@@ -87,50 +88,20 @@ void print_proc_decl(AstNodeProcDecl *pd) {
}
gb_printf("\n\n");
}
void print_declaration(AstNode *decl) {
switch (decl->kind) {
case_ast_node(gd, GenDecl, decl);
for_array(spec_index, gd->specs) {
AstNode *spec = gd->specs[spec_index];
switch(gd->token.kind) {
case Token_var:
break;
case Token_const:
break;
case Token_type:
// print_type_spec(spec);
break;
case Token_import:
case Token_import_load:
break;
case Token_foreign_library:
case Token_foreign_system_library:
break;
}
}
case_end;
case_ast_node(pd, ProcDecl, decl);
print_proc_decl(pd);
case_end;
case_ast_node(fb, ForeignBlockDecl, decl);
// TODO(bill)
case_end;
}
#endif
void print_declaration(Ast *decl) {
}
void generate_documentation(Parser *parser) {
for_array(file_index, parser->files) {
AstFile *file = &parser->files[file_index];
Tokenizer *tokenizer = &file->tokenizer;
String fullpath = tokenizer->fullpath;
gb_printf("%.*s\n", LIT(fullpath));
// for_array(file_index, parser->files) {
// AstFile *file = parser->files[file_index];
// Tokenizer *tokenizer = &file->tokenizer;
// String fullpath = tokenizer->fullpath;
// gb_printf("%.*s\n", LIT(fullpath));
for_array(decl_index, file->decls) {
AstNode *decl = file->decls[decl_index];
print_declaration(decl);
}
}
// for_array(decl_index, file->decls) {
// Ast *decl = file->decls[decl_index];
// print_declaration(decl);
// }
// }
}
-143
View File
@@ -1,143 +0,0 @@
/*
Package: dyncall
Library: dyncall
File: dyncall/dyncall.h
Description: public header for library dyncall
License:
Copyright (c) 2007-2015 Daniel Adler <dadler@uni-goettingen.de>,
Tassilo Philipp <tphilipp@potion-studios.com>
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
dyncall C API
REVISION
2015/07/08 added SYS_PPC64 system call
2015/01/16 added SYS_PPC32 system call
2007/12/11 initial
*/
#ifndef DYNCALL_H
#define DYNCALL_H
#include "dyncall_types.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct DCCallVM_ DCCallVM;
typedef struct DCstruct_ DCstruct;
/* Supported Calling Convention Modes */
#define DC_CALL_C_DEFAULT 0
#define DC_CALL_C_ELLIPSIS 100
#define DC_CALL_C_ELLIPSIS_VARARGS 101
#define DC_CALL_C_X86_CDECL 1
#define DC_CALL_C_X86_WIN32_STD 2
#define DC_CALL_C_X86_WIN32_FAST_MS 3
#define DC_CALL_C_X86_WIN32_FAST_GNU 4
#define DC_CALL_C_X86_WIN32_THIS_MS 5
#define DC_CALL_C_X86_WIN32_THIS_GNU 6
#define DC_CALL_C_X64_WIN64 7
#define DC_CALL_C_X64_SYSV 8
#define DC_CALL_C_PPC32_DARWIN 9
#define DC_CALL_C_PPC32_OSX DC_CALL_C_PPC32_DARWIN /* alias */
#define DC_CALL_C_ARM_ARM_EABI 10
#define DC_CALL_C_ARM_THUMB_EABI 11
#define DC_CALL_C_ARM_ARMHF 30
#define DC_CALL_C_MIPS32_EABI 12
#define DC_CALL_C_MIPS32_PSPSDK DC_CALL_C_MIPS32_EABI /* alias - deprecated. */
#define DC_CALL_C_PPC32_SYSV 13
#define DC_CALL_C_PPC32_LINUX DC_CALL_C_PPC32_SYSV /* alias */
#define DC_CALL_C_ARM_ARM 14
#define DC_CALL_C_ARM_THUMB 15
#define DC_CALL_C_MIPS32_O32 16
#define DC_CALL_C_MIPS64_N32 17
#define DC_CALL_C_MIPS64_N64 18
#define DC_CALL_C_X86_PLAN9 19
#define DC_CALL_C_SPARC32 20
#define DC_CALL_C_SPARC64 21
#define DC_CALL_C_ARM64 22
#define DC_CALL_C_PPC64 23
#define DC_CALL_C_PPC64_LINUX DC_CALL_C_PPC64 /* alias */
#define DC_CALL_SYS_DEFAULT 200
#define DC_CALL_SYS_X86_INT80H_LINUX 201
#define DC_CALL_SYS_X86_INT80H_BSD 202
#define DC_CALL_SYS_PPC32 210
#define DC_CALL_SYS_PPC64 211
/* Error codes. */
#define DC_ERROR_NONE 0
#define DC_ERROR_UNSUPPORTED_MODE -1
DC_API DCCallVM* dcNewCallVM (DCsize size);
DC_API void dcFree (DCCallVM* vm);
DC_API void dcReset (DCCallVM* vm);
DC_API void dcMode (DCCallVM* vm, DCint mode);
DC_API void dcArgBool (DCCallVM* vm, DCbool value);
DC_API void dcArgChar (DCCallVM* vm, DCchar value);
DC_API void dcArgShort (DCCallVM* vm, DCshort value);
DC_API void dcArgInt (DCCallVM* vm, DCint value);
DC_API void dcArgLong (DCCallVM* vm, DClong value);
DC_API void dcArgLongLong (DCCallVM* vm, DClonglong value);
DC_API void dcArgFloat (DCCallVM* vm, DCfloat value);
DC_API void dcArgDouble (DCCallVM* vm, DCdouble value);
DC_API void dcArgPointer (DCCallVM* vm, DCpointer value);
DC_API void dcArgStruct (DCCallVM* vm, DCstruct* s, DCpointer value);
DC_API void dcCallVoid (DCCallVM* vm, DCpointer funcptr);
DC_API DCbool dcCallBool (DCCallVM* vm, DCpointer funcptr);
DC_API DCchar dcCallChar (DCCallVM* vm, DCpointer funcptr);
DC_API DCshort dcCallShort (DCCallVM* vm, DCpointer funcptr);
DC_API DCint dcCallInt (DCCallVM* vm, DCpointer funcptr);
DC_API DClong dcCallLong (DCCallVM* vm, DCpointer funcptr);
DC_API DClonglong dcCallLongLong (DCCallVM* vm, DCpointer funcptr);
DC_API DCfloat dcCallFloat (DCCallVM* vm, DCpointer funcptr);
DC_API DCdouble dcCallDouble (DCCallVM* vm, DCpointer funcptr);
DC_API DCpointer dcCallPointer (DCCallVM* vm, DCpointer funcptr);
DC_API void dcCallStruct (DCCallVM* vm, DCpointer funcptr, DCstruct* s, DCpointer returnValue);
DC_API DCint dcGetError (DCCallVM* vm);
#define DEFAULT_ALIGNMENT 0
DC_API DCstruct* dcNewStruct (DCsize fieldCount, DCint alignment);
DC_API void dcStructField (DCstruct* s, DCint type, DCint alignment, DCsize arrayLength);
DC_API void dcSubStruct (DCstruct* s, DCsize fieldCount, DCint alignment, DCsize arrayLength);
/* Each dcNewStruct or dcSubStruct call must be paired with a dcCloseStruct. */
DC_API void dcCloseStruct (DCstruct* s);
DC_API DCsize dcStructSize (DCstruct* s);
DC_API DCsize dcStructAlignment(DCstruct* s);
DC_API void dcFreeStruct (DCstruct* s);
DC_API DCstruct* dcDefineStruct (const char* signature);
#ifdef __cplusplus
}
#endif
#endif /* DYNCALL_H */
-47
View File
@@ -1,47 +0,0 @@
/*
Package: dyncall
Library: dyncallback
File: dyncallback/dyncall_alloc_wx.h
Description: Allocate write/executable memory - Interface
License:
Copyright (c) 2007-2015 Daniel Adler <dadler@uni-goettingen.de>,
Tassilo Philipp <tphilipp@potion-studios.com>
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef DYNCALL_ALLOC_WX_HPP
#define DYNCALL_ALLOC_WX_HPP
#include "dyncall_types.h"
typedef int DCerror;
#ifdef __cplusplus
extern "C" {
#endif
DCerror dcAllocWX(DCsize size, void** p);
void dcFreeWX (void* p, DCsize size);
#ifdef __cplusplus
}
#endif
#endif /* DYNCALL_ALLOC_WX_HPP */
-66
View File
@@ -1,66 +0,0 @@
/*
Package: dyncall
Library: dyncallback
File: dyncallback/dyncall_args.h
Description: Callback's Arguments VM - Interface
License:
Copyright (c) 2007-2015 Daniel Adler <dadler@uni-goettingen.de>,
Tassilo Philipp <tphilipp@potion-studios.com>
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef DYNCALL_ARGS_H
#define DYNCALL_ARGS_H
/*
* dyncall args C API
*
* dyncall args provides serialized access to arguments of a function call.
* related concepts: callback
*
*/
#include "dyncall.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct DCArgs DCArgs;
DC_API DCbool dcbArgBool (DCArgs*);
DC_API DCchar dcbArgChar (DCArgs*);
DC_API DCshort dcbArgShort (DCArgs*);
DC_API DCint dcbArgInt (DCArgs*);
DC_API DClong dcbArgLong (DCArgs*);
DC_API DClonglong dcbArgLongLong (DCArgs*);
DC_API DCuchar dcbArgUChar (DCArgs*);
DC_API DCushort dcbArgUShort (DCArgs*);
DC_API DCuint dcbArgUInt (DCArgs*);
DC_API DCulong dcbArgULong (DCArgs*);
DC_API DCulonglong dcbArgULongLong(DCArgs*);
DC_API DCfloat dcbArgFloat (DCArgs*);
DC_API DCdouble dcbArgDouble (DCArgs*);
DC_API DCpointer dcbArgPointer (DCArgs*);
#ifdef __cplusplus
}
#endif
#endif /* DYNCALL_ARGS_H */
@@ -1,46 +0,0 @@
/*
Package: dyncall
Library: dyncallback
File: dyncallback/dyncall_args_arm32_arm.h
Description: Callback's Arguments VM - Header for ARM32 (ARM mode)
License:
Copyright (c) 2007-2015 Daniel Adler <dadler@uni-goettingen.de>,
Tassilo Philipp <tphilipp@potion-studios.com>
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef DYNCALLBACK_ARGS_ARM32_ARM_H
#define DYNCALLBACK_ARGS_ARM32_ARM_H
#include "dyncall_args.h"
struct DCArgs
{
/* Don't change order! */
long reg_data[4];
int reg_count;
long* stack_ptr;
#if defined(DC__ABI_ARM_HF)
DCfloat f[16];
int freg_count;
int dreg_count;
#endif
};
#endif /* DYNCALLBACK_ARGS_ARM32_ARM_H */
@@ -1,33 +0,0 @@
/*
Package: dyncall
Library: dyncallback
File: dyncallback/dyncall_args_arm32_thumb.h
Description: Callback's Arguments VM - Header for ARM32 (THUMB mode)
License:
Copyright (c) 2007-2015 Daniel Adler <dadler@uni-goettingen.de>,
Tassilo Philipp <tphilipp@potion-studios.com>
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef DYNCALLBACK_ARGS_ARM32_THUMB_H
#define DYNCALLBACK_ARGS_ARM32_THUMB_H
#include "dyncall_args_arm32_arm.h" /* Uses same code as ARM mode. */
#endif /* DYNCALLBACK_ARGS_ARM32_THUMB_H */
-42
View File
@@ -1,42 +0,0 @@
/*
Package: dyncall
Library: dyncallback
File: dyncallback/dyncall_args_mips.h
Description: Callback's Arguments VM - Header for MIPS
License:
Copyright (c) 2013-2015 Daniel Adler <dadler@uni-goettingen.de>,
Tassilo Philipp <tphilipp@potion-studios.com>
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef DYNCALLBACK_ARGS_MIPS_H
#define DYNCALLBACK_ARGS_MIPS_H
#include "dyncall_args.h"
struct DCArgs
{
int ireg_data[8];
float freg_data[8];
int ireg_count;
int freg_count;
unsigned char* stackptr;
};
#endif /* DYNCALLBACK_ARGS_MIPS_H */
-43
View File
@@ -1,43 +0,0 @@
/*
Package: dyncall
Library: dyncallback
File: dyncallback/dyncall_args_ppc32.h
Description: Callback's Arguments VM - Header for ppc32
License:
Copyright (c) 2007-2015 Daniel Adler <dadler@uni-goettingen.de>,
Tassilo Philipp <tphilipp@potion-studios.com>
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef DYNCALLBACK_ARGS_PPC32_H
#define DYNCALLBACK_ARGS_PPC32_H
#include "dyncall_args.h"
/* Common Args iterator for Apple and System V ABI. */
struct DCArgs
{
int ireg_data[8]; /* offset: 0 size: 4*8 = 32 */
double freg_data[13]; /* offset: 32 size: 8*13= 104 */
unsigned char* stackptr; /* offset: 136 size: 4 */
int ireg_count; /* offset: 140 size: 4 */
int freg_count; /* offset: 144 size: 4 */
}; /* total size: 148 */
#endif /* DYNCALLBACK_ARGS_PPC32_H */
-40
View File
@@ -1,40 +0,0 @@
/*
Package: dyncall
Library: dyncallback
File: dyncallback/dyncall_args_ppc64.h
Description: Callback's Arguments VM - Header for ppc64
License:
Copyright (c) 2014-2015 Masanori Mitsugi <mitsugi@linux.vnet.ibm.com>
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef DYNCALLBACK_ARGS_PPC64_H
#define DYNCALLBACK_ARGS_PPC64_H
#include "dyncall_args.h"
struct DCArgs
{
long long ireg_data[8];
double freg_data[13];
unsigned char* stackptr;
int ireg_count;
int freg_count;
};
#endif /* DYNCALLBACK_ARGS_PPC64_H */
@@ -1,38 +0,0 @@
/*
Package: dyncall
Library: dyncallback
File: dyncallback/dyncall_args_sparc32.h
Description: Callback's Arguments VM - Header for sparc32
License:
Copyright (c) 2007-2015 Daniel Adler <dadler@uni-goettingen.de>,
Tassilo Philipp <tphilipp@potion-studios.com>
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef DYNCALLBACK_ARGS_SPARC32_H
#define DYNCALLBACK_ARGS_SPARC32_H
#include "dyncall_args.h"
struct DCArgs
{
int dummy;
};
#endif /* DYNCALLBACK_ARGS_SPARC32_H */
@@ -1,38 +0,0 @@
/*
Package: dyncall
Library: dyncallback
File: dyncallback/dyncall_args_sparc64.h
Description: Callback's Arguments VM - Header for sparc32 - not yet
License:
Copyright (c) 2007-2015 Daniel Adler <dadler@uni-goettingen.de>,
Tassilo Philipp <tphilipp@potion-studios.com>
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef DYNCALLBACK_ARGS_SPARC64_H
#define DYNCALLBACK_ARGS_SPARC64_H
#include "dyncall_args.h"
struct DCArgs
{
int dummy;
};
#endif /* DYNCALLBACK_ARGS_SPARC64_H */
-45
View File
@@ -1,45 +0,0 @@
/*
Package: dyncall
Library: dyncallback
File: dyncallback/dyncall_args_x64.h
Description: Callback's Arguments VM - Header for x64
License:
Copyright (c) 2007-2015 Daniel Adler <dadler@uni-goettingen.de>,
Tassilo Philipp <tphilipp@potion-studios.com>
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef DYNCALLBACK_ARGS_X64_H
#define DYNCALLBACK_ARGS_X64_H
#include "dyncall_args.h"
#include "dyncall_callvm_x64.h" /* reuse structures */
struct DCArgs
{
/* state */
int64* stack_ptr;
DCRegCount_x64 reg_count; /* @@@ win64 version should maybe force alignment to 8 in order to be secure */
/* reg data */
DCRegData_x64_s reg_data;
};
#endif /* DYNCALLBACK_ARGS_X64_H */

Some files were not shown because too many files have changed in this diff Show More