Compare commits

..

132 Commits

Author SHA1 Message Date
Ginger Bill 5df854fcef Fixed demo 2017-06-27 15:58:53 +01:00
Ginger Bill 260089431e Write demo for v0.5.0 2017-06-26 21:34:54 +01:00
Ginger Bill d0d8da8c08 Revert demo 2017-06-26 19:42:32 +01:00
Ginger Bill d1365b3466 Fix poly-procs for variadic calls 2017-06-26 19:24:04 +01:00
Ginger Bill c949ca2a5c Allow for named arguments for polymorphic procedures 2017-06-26 18:20:24 +01:00
Ginger Bill d974b29f67 Reduce excessive node cloning on para-poly checking and fix scope bug 2017-06-26 14:39:51 +01:00
Ginger Bill cc7316bb35 Fix IR printing for para-poly procedures 2017-06-26 14:16:16 +01:00
Ginger Bill a0d8dcd974 Remove let 2017-06-26 13:59:15 +01:00
Ginger Bill c642e326ce Undef value --- (for setting a value to be uninitialized/undefined) 2017-06-26 11:57:26 +01:00
Ginger Bill 362a118782 Remove "overloading" bug of para-poly-procs 2017-06-25 23:41:46 +01:00
Ginger Bill 3ab481df17 new as a user-level procedure 2017-06-25 22:31:30 +01:00
Ginger Bill 4e7150b470 Allow nested para-poly procedures 2017-06-25 22:29:23 +01:00
Ginger Bill 1ced92be47 Rudimentary para-poly procedures 2017-06-25 22:15:30 +01:00
Ginger Bill 15dbea6899 Generic procedures generate types on use 2017-06-25 19:41:07 +01:00
Ginger Bill c4081393c1 Fix typo for some built-in procedures 2017-06-25 17:36:10 +01:00
Ginger Bill 1d81b73df9 Basic command line flags: e.g. -opt=0 2017-06-24 22:58:50 +01:00
Ginger Bill 18f885efab expand_to_tuple 2017-06-24 20:39:37 +01:00
Ginger Bill bba088bee7 Use UTF-8 command line on windows 2017-06-24 11:42:49 +01:00
Ginger Bill 6cbb6bef0b Wrap hashing functions 2017-06-22 16:14:02 +01:00
Ginger Bill 8744c60563 Clean up code for return statements, slightly 2017-06-22 13:47:50 +01:00
Ginger Bill 8197c02dcf Default result values for procedure types; Named result values in return statements 2017-06-22 01:14:45 +01:00
Ginger Bill 9faf0020cc Amend Checker API 2017-06-21 21:46:27 +01:00
Ginger Bill 53075e2570 Update old demos 2017-06-21 21:20:26 +01:00
Ginger Bill 264ca00db7 Merge branch 'master' of https://github.com/gingerBill/Odin 2017-06-21 17:49:05 +01:00
Ginger Bill 6b65ef6d88 Fix compilation bug on Linux 2017-06-21 17:48:50 +01:00
Ginger Bill 5957d7f7be Implicit Parameter Passing based context system (replacing Thread Local Storage (TLS) approach) 2017-06-20 12:38:05 +01:00
Ginger Bill 35c102137f Compiler compiles for x86 (doesn't work properly) 2017-06-19 18:49:11 +01:00
Ginger Bill 5427d14416 Code will compile as 32 bit but will causes errors in the linker on Windows 2017-06-19 15:55:09 +01:00
Ginger Bill 178236d1ff Barebones layout for the documentation declarations 2017-06-18 23:41:13 +01:00
Ginger Bill 736c880ba9 Add docs.cpp 2017-06-18 23:18:15 +01:00
Ginger Bill 126f7aa892 Begin work on documentation generation 2017-06-18 23:16:57 +01:00
Ginger Bill 2957f007e3 Fix #location for anonymous procedures 2017-06-18 17:35:27 +01:00
Ginger Bill 04501c93fe Implement assert and panic in user side code
Removes 2 more built-in procedures!
2017-06-18 17:25:28 +01:00
Ginger Bill 4236519b84 #location(..) and #call_location 2017-06-18 14:36:06 +01:00
Ginger Bill e4944b4f2e Fix error reporting for foreign blocks 2017-06-17 20:03:52 +01:00
Ginger Bill 2deb2f8eeb Declaration grouping uses () rather than {}; Fix some problem with compilation on *nix 2017-06-17 12:01:53 +01:00
Ginger Bill 3fa398ec43 Add extra check for bodiless procedures 2017-06-15 21:36:29 +01:00
Ginger Bill 1851674b50 Code use API rather than raw CheckerInfo; begin work on generic procedures 2017-06-15 18:11:58 +01:00
Ginger Bill c5ef5279d4 Add foreign variables 2017-06-15 14:42:08 +01:00
Ginger Bill d3c24d159f Merge size_of and size_of_val et al. 2017-06-15 12:25:53 +01:00
Ginger Bill 23f9f9064e Add CheckerInfo API functions 2017-06-15 12:14:56 +01:00
Ginger Bill a134307dcd Fix issue #72 - 128-bit literal corruption 2017-06-14 14:58:48 +01:00
Ginger Bill c3b510c2d9 C-style c_varargs (Not heavily tested) 2017-06-13 21:00:42 +01:00
Ginger Bill e7fc24e48c Fix compilation error for Invalid EntityKind 2017-06-13 18:04:22 +01:00
Ginger Bill 6a88dc322a Declaration grouping uses braces rather than parentheses 2017-06-13 15:04:23 +01:00
Ginger Bill 6b464e3558 Update README.md 2017-06-12 21:41:14 +01:00
Ginger Bill 76b0c7b765 "Revert" to older demo 2017-06-12 21:27:53 +01:00
Ginger Bill 91857e8f16 Remove redundant paths in parsing 2017-06-12 21:25:47 +01:00
Ginger Bill ccda456c0a foreign blocks for procedures 2017-06-12 21:21:18 +01:00
Ginger Bill 83bad13e9e Update default field value syntax; Use more declaration groupings 2017-06-12 18:38:27 +01:00
Ginger Bill e6a206a430 Check for empty generic declaration list 2017-06-12 16:58:25 +01:00
Ginger Bill f52a1e4ded Fix IR bug for TypeSpec 2017-06-12 16:47:07 +01:00
Ginger Bill a8e458339b foreign_library allow for Pascal-style grouping 2017-06-12 16:26:51 +01:00
Ginger Bill 6b5e9aec8e Pascal style declaration grouping with () 2017-06-12 15:42:21 +01:00
Ginger Bill 2ab0d97573 import and import_load as keywords; Fix procedure literal call trick 2017-06-12 14:19:12 +01:00
Ginger Bill 0c05fc1432 Prefix type and let to replace immutable 2017-06-12 12:56:47 +01:00
Ginger Bill 33eeb58521 Prefix proc syntax 2017-06-12 12:34:55 +01:00
Ginger Bill 8fafdb185c Remove := with var and :: with const 2017-06-12 11:48:12 +01:00
Ginger Bill c2c935ba81 Fix trailing default argument checking 2017-06-11 20:52:54 +01:00
Ginger Bill 2d73c8868b Make default arguments for records invalid syntax 2017-06-11 19:01:36 +01:00
gingerBill b95bb1286b Merge pull request #70 from ThisDrunkDane/master
Add some WM_*, some WS_* and map_virtual_key
2017-06-11 18:54:30 +01:00
Mikkel Hjortshoej 4237c8ec30 Merge branch 'master' of github.com:gingerBill/Odin 2017-06-11 19:53:44 +02:00
Ginger Bill 49b4b39055 Minor change for overloaded procedures 2017-06-11 18:53:20 +01:00
Mikkel Hjortshoej bf15fea135 Merge branch 'master' of github.com:gingerBill/Odin 2017-06-11 19:47:57 +02:00
Mikkel Hjortshoej 47c03e376d Merge branch 'master' of github.com:gingerBill/Odin 2017-06-11 19:47:05 +02:00
Ginger Bill 1cabfac36c Update README.md 2017-06-11 18:46:59 +01:00
Mikkel Hjortshoej 8e32276283 Added a bunch of VM_* and map_virtual_key 2017-06-11 19:46:55 +02:00
Ginger Bill 366b306df0 Default parameters for procedures 2017-06-11 18:38:30 +01:00
Ginger Bill 4bf1f798f5 Allow for ignoring named procedural call arguments with _ 2017-06-11 17:41:55 +01:00
Ginger Bill b2fdb69b4d Named procedure calls 2017-06-11 12:01:40 +01:00
Ginger Bill af2736daec Fix bit field bug 2017-06-08 16:29:05 +01:00
Ginger Bill 5cad7d44a6 Use templated Map for extra type safety 2017-06-08 13:26:48 +01:00
Ginger Bill 2b96be0ae8 Remove unnecessary typedef usage 2017-06-08 13:08:39 +01:00
Ginger Bill 2a89d8021c Use templated Array with bounds checking 2017-06-08 12:54:52 +01:00
Ginger Bill 13deb4706c Update String to use overloading 2017-06-08 12:37:07 +01:00
Ginger Bill 9b61adb97d Build as C++ 2017-06-08 12:03:40 +01:00
Ginger Bill 333924cce1 v0.3 Release 2017-06-08 11:35:22 +01:00
Ginger Bill 574b82c0c7 v0.3.0 2017-06-07 22:09:16 +01:00
Ginger Bill f60c772c11 Make rune a basic type and not an alias; Remove byte 2017-06-06 23:54:33 +01:00
Ginger Bill 107740ca5e Fix issue #69 for fmt.printf padding 2017-06-06 10:02:53 +01:00
gingerBill 88b990eb63 Merge pull request #53 from ghost/master
Fix link time error about missing -fPIC flag
2017-06-06 09:47:40 +01:00
Ginger Bill d2e7d730ac Fix key generation for constant strings in IR 2017-06-05 23:06:15 +01:00
Ginger Bill 817e4b663e Add murmurhash3.c 2017-06-05 22:52:56 +01:00
Ginger Bill 214bb73454 Merge branch 'master' of https://github.com/gingerBill/Odin 2017-06-05 18:01:57 +01:00
Ginger Bill eba2c74bff Allow 128 bit map keys 2017-06-05 18:01:41 +01:00
gingerBill 7c5e6c808b Merge pull request #68 from ThisDrunkDane/master
Added extra sys/windows.odin stuff
2017-06-05 15:18:04 +01:00
Ginger Bill ebe5beaafd Allow using on bit fields 2017-06-04 11:53:33 +01:00
Ginger Bill 029a6095d9 Fix enum printing bug 2017-06-04 00:20:16 +01:00
Ginger Bill 2c0e59ae06 bit_field; Lexical sugar operators ≠ ≤ ≥
Example below:
// See: https://en.wikipedia.org/wiki/Bit_field
BoxProps :: bit_field {
	opaque        : 1,
	fill_colour   : 3,
	_             : 4,
	show_border   : 1,
	border_colour : 3,
	border_style  : 2,
	_             : 2,
	width         : 4,
	height        : 4,
	_             : 8,
}
2017-06-03 22:27:23 +01:00
Ginger Bill 9d1a4c304a Remove Quat from math.odin 2017-06-01 15:12:54 +01:00
Ginger Bill 13b8a1e348 Remove quaternion128 and quaternion256 as core types 2017-06-01 14:52:33 +01:00
Ginger Bill 0d4945dc87 Implement u128/i128 features; Add bits.odin 2017-06-01 14:23:46 +01:00
Mikkel Hjortshoej e0b9c4a275 Added extra sys/windows.odin stuff
- Added PM_NOREMOVE
	- Added PM_NOYIELD
	- Added get_message_a
	- Added post_message_a
2017-06-01 00:05:33 +02:00
Ginger Bill fec6df65b3 Use 128-bit integers for ExactValue integers 2017-05-30 15:23:01 +01:00
Ginger Bill 78494e84d5 Remove some asserts in timings.c 2017-05-29 19:41:13 +01:00
Ginger Bill 60d7c833c0 Fix unary expression type check 2017-05-28 21:56:40 +01:00
Ginger Bill 98dbbf11f3 Fix procedure overloading distinguishing 2017-05-28 18:51:42 +01:00
Ginger Bill f4924e39d4 Fix printing of struct literals with custom alignment 2017-05-28 16:11:19 +01:00
Ginger Bill 826e05c96e Convert windows.odin to the new naming convention 2017-05-28 16:08:29 +01:00
Ginger Bill d3f63e5903 Change label syntax for for and match from #label name to name: 2017-05-28 15:01:39 +01:00
Ginger Bill 80c034ec7c Change naming convention from Ada_Like to RustLike
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
2017-05-28 14:47:11 +01:00
Ginger Bill b41f09b730 Experimental try for ABI for return values on windows
It's all done by reverse engineering it. I may be wrong...
2017-05-28 14:11:00 +01:00
Ginger Bill 06185e1769 Try a different ABI type for return values on Windows 2017-05-28 01:07:52 +01:00
Ginger Bill f8fa7fe380 Fix bug with too many field values in a structure literal. 2017-05-27 20:57:48 +01:00
Ginger Bill 45dbe8d354 default: to case:; no_alias to #no_alias 2017-05-27 11:47:21 +01:00
Ginger Bill ddb99dd638 Fix interval loop constant bug; Fix ir edge checking; Fix vector arithmetic with scalars 2017-05-22 23:29:09 +01:00
Ginger Bill 41aa4e606b Optional main for DLL; access struct elements by "index" 2017-05-17 21:23:52 +01:00
Ginger Bill e025a828ca Fix issue #66 2017-05-14 10:32:48 +01:00
Ginger Bill 807e17207a Merge branch 'master' of https://github.com/gingerBill/Odin 2017-05-13 16:09:04 +01:00
Ginger Bill 3e18f5f057 Fix Ternary Operator IR bug 2017-05-13 16:08:50 +01:00
gingerBill 9637cc5690 Add #ordered to the "raw" types in raw.odin 2017-05-12 16:04:05 +01:00
Ginger Bill ded99a2cab Fix issue with os.file_size on *nix 2017-05-12 10:29:55 +01:00
Ginger Bill 45eecc0905 Reimplement #ordered again 2017-05-12 10:27:14 +01:00
Ginger Bill 87f1a62ca4 Fix alignment for normal structures to match LLVM 2017-05-10 22:51:35 +01:00
Ginger Bill c6d531df95 Add %% operator (divisor modulo) 2017-05-09 16:21:31 +01:00
Ginger Bill 8677c81da7 Fix ir bug; allow formatting options for arrays & et al. 2017-05-09 12:05:17 +01:00
Ginger Bill 5595daf5a3 Revert demo.odin 2017-05-09 10:01:50 +01:00
Ginger Bill 64b5afd820 Fix issue #63 for block comments not terminating at an EOF 2017-05-09 10:01:10 +01:00
Ginger Bill 7692061eef Add XOR for booleans 2017-05-07 20:52:20 +01:00
Ginger Bill f7f2272c50 Fix fmt_float precision 2017-05-07 11:42:27 +01:00
Ginger Bill 03fbdc3f75 Fix IR printing bug with global unicode identifiers 2017-05-06 23:02:47 +01:00
Ginger Bill ea6a4859ed Merge branch 'master' of https://github.com/gingerBill/Odin 2017-05-06 20:56:18 +01:00
Ginger Bill 615fa82d1f Fix using issue #62 2017-05-06 20:55:09 +01:00
gingerBill b60b310121 Merge pull request #61 from ThisDrunkDane/master
Fix constant casing and add several win32 functions, structure and constants
2017-05-05 21:00:58 +01:00
Mikkel Hjortshoej c7f7e562a0 Add following win32 functions
- ShowCursor
	- GetFileAttributesA
	- FindFirstFileA
	- FindNextFileA
	- FindClose

Add following win32 constants
	- MAX_PATH
	- INVALID_FILE_ATTRIBUTES

Add following win32 structure
	- Find_Data
2017-05-05 20:32:48 +02:00
Mikkel Hjortshoej a317237404 Fix casing on FILE_ATTRIBUTE_DIRECTORY 2017-05-05 20:22:18 +02:00
Ginger Bill 51ea59d76a Fix calculation of vector type sizes 2017-05-04 23:18:54 +01:00
Ginger Bill 789b297f32 Add hidden __tag for union variables. 2017-05-04 20:34:50 +01:00
Ginger Bill 3b25f924cb Remove debug bug 2017-05-03 11:01:17 +01:00
Ginger Bill cc6282a6e3 Fix alignment and size bug of enums; Remove #ordered and make the default #ordered. 2017-05-02 21:16:09 +01:00
Ginger Bill 206a3e093c Remove check on array/slice/dynamic element size 2017-05-02 20:17:53 +01:00
Constantine Tarasenkov d05ec5e484 Fix link time error about missing -fPIC flag 2017-04-28 18:08:11 +03:00
67 changed files with 16525 additions and 12606 deletions
+4 -5
View File
@@ -8,7 +8,6 @@ The Odin programming language is fast, concise, readable, pragmatic and open sou
* built for modern systems
* joy of programming
* metaprogramming
* designed for good programmers
Website: [https://odin.handmade.network/](https://odin.handmade.network/)
@@ -20,15 +19,15 @@ Website: [https://odin.handmade.network/](https://odin.handmade.network/)
* [Composition & Refactorability](https://www.youtube.com/watch?v=n1wemZfcbXM)
* [Introspection, Modules, and Record Layout](https://www.youtube.com/watch?v=UFq8rhWhx4s)
* [push_allocator & Minimal Dependency Building](https://www.youtube.com/watch?v=f_LGVOAMb78)
* [when, for, & procedure overloading](https://www.youtube.com/watch?v=OzeOekzyZK8)
* [when, for, & procedure overloading](https://www.youtube.com/watch?v=OzeOekzyZK8)
* [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)
## Requirements to build and run
- Windows
* x86-64
* MSVC 2015 installed (C99 support)
* 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`
* Requires MSVC's link.exe as the linker
* run `vcvarsall.bat` to setup the path
@@ -42,7 +41,7 @@ Website: [https://odin.handmade.network/](https://odin.handmade.network/)
* x86-64
* Build tools (ld)
* LLVM installed
* Clang installed (temporary - this is calling the linker for now)
* Clang installed (temporary - this is Calling the linker for now)
## Warnings
+4 -6
View File
@@ -5,7 +5,7 @@ set exe_name=odin.exe
:: Debug = 0, Release = 1
set release_mode=0
set compiler_flags= -nologo -Oi -TC -fp:fast -fp:except- -Gm- -MP -FC -GS- -EHsc- -GR-
set compiler_flags= -nologo -Oi -TP -fp:fast -fp:except- -Gm- -MP -FC -GS- -EHsc- -GR-
if %release_mode% EQU 0 ( rem Debug
set compiler_flags=%compiler_flags% -Od -MDd -Z7
@@ -42,12 +42,10 @@ set linker_settings=%libs% %linker_flags%
del *.pdb > NUL 2> NUL
del *.ilk > NUL 2> NUL
cl %compiler_settings% "src\main.c" ^
cl %compiler_settings% "src\main.cpp" ^
/link %linker_settings% -OUT:%exe_name% ^
&& odin run code/demo.odin
rem && odin build code/metagen.odin ^
rem && call "code\metagen.exe" "src\ast_nodes.metagen"
rem && odin run code/Jaze/src/main.odin
&& odin run code/demo.odin -opt=0
rem && odin docs core/fmt.odin
del *.obj > NUL 2> NUL
+3 -3
View File
@@ -2,8 +2,8 @@
release_mode=0
warnings_to_disable="-std=c11 -Wno-switch -Wno-pointer-sign -Wno-tautological-constant-out-of-range-compare -Wno-tautological-compare -Wno-macro-redefined"
libraries="-pthread -ldl -lm"
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"
libraries="-pthread -ldl -lm -lstdc++"
other_args=""
compiler="clang"
@@ -19,6 +19,6 @@ if [[ "$(uname)" == "Darwin" ]]; then
other_args="${other_args} -liconv"
fi
${compiler} src/main.c ${warnings_to_disable} ${libraries} ${other_args} -o odin
${compiler} src/main.cpp ${warnings_to_disable} ${libraries} ${other_args} -o odin
./odin run code/demo.odin
+421 -6
View File
@@ -1,8 +1,420 @@
#import "fmt.odin";
import "fmt.odin";
main :: proc() {
immutable program := "+ + * - /";
accumulator := 0;
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 {
@@ -10,9 +422,12 @@ main :: proc() {
case '-': accumulator -= 1;
case '*': accumulator *= 2;
case '/': accumulator /= 2;
default: // Ignore everything else
case: // Ignore everything else
}
}
fmt.printf("The program \"%s\" calculates the value %d\n", program, accumulator);
fmt.printf("The program \"%s\" calculates the value %d\n",
program, accumulator);
}
*/
+78 -78
View File
@@ -1,38 +1,37 @@
#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";
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";
TWO_HEARTS :: '💕';
const TWO_HEARTS = '💕';
win32_perf_count_freq := win32.GetQueryPerformanceFrequency();
time_now :: proc() -> f64 {
var win32_perf_count_freq = win32.get_query_performance_frequency();
proc time_now() -> f64 {
assert(win32_perf_count_freq != 0);
counter: i64;
win32.QueryPerformanceCounter(^counter);
result := cast(f64)counter / cast(f64)win32_perf_count_freq;
return result;
var counter: i64;
win32.query_performance_counter(&counter);
return f64(counter) / f64(win32_perf_count_freq);
}
win32_print_last_error :: proc() {
err_code := cast(int)win32.GetLastError();
proc win32_print_last_error() {
var err_code = win32.get_last_error();
if err_code != 0 {
fmt.println("GetLastError: %", err_code);
fmt.println("get_last_error: ", err_code);
}
}
// Yuk!
to_c_string :: proc(s: string) -> []u8 {
c_str := make([]u8, len(s)+1);
copy(c_str, cast([]byte)s);
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;
}
Window :: struct {
type Window struct {
width, height: int,
wc: win32.WndClassExA,
dc: win32.Hdc,
@@ -41,52 +40,52 @@ Window :: struct {
c_title: []u8,
}
make_window :: proc(title: string, msg, height: int, window_proc: win32.Wnd_Proc) -> (Window, bool) {
proc make_window(title: string, msg, height: int, window_proc: win32.WndProc) -> (Window, bool) {
using win32;
w: Window;
var w: Window;
w.width, w.height = msg, height;
class_name := "Win32-Odin-Window\x00";
c_class_name := ^class_name[0];
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 = cast([]u8)title;
w.c_title = []u8(title);
}
instance := GetModuleHandleA(nil);
var instance = get_module_handle_a(nil);
w.wc = WndClassExA{
size = size_of(WndClassExA),
style = CS_VREDRAW | CS_HREDRAW,
instance = cast(Hinstance)instance,
instance = Hinstance(instance),
class_name = c_class_name,
wnd_proc = window_proc,
};
if RegisterClassExA(^w.wc) == 0 {
if register_class_ex_a(&w.wc) == 0 {
win32_print_last_error();
return w, false;
}
w.hwnd = CreateWindowExA(0,
c_class_name, ^w.c_title[0],
WS_VISIBLE | WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX,
CW_USEDEFAULT, CW_USEDEFAULT,
cast(i32)w.width, cast(i32)w.height,
nil, nil, instance, nil);
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 = GetDC(w.hwnd);
w.dc = get_dc(w.hwnd);
{
pfd := PIXELFORMATDESCRIPTOR{
size = size_of(PIXELFORMATDESCRIPTOR),
var pfd = PixelFormatDescriptor{
size = size_of(PixelFormatDescriptor),
version = 1,
flags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
pixel_type = PFD_TYPE_RGBA,
@@ -97,88 +96,89 @@ make_window :: proc(title: string, msg, height: int, window_proc: win32.Wnd_Proc
layer_type = PFD_MAIN_PLANE,
};
SetPixelFormat(w.dc, ChoosePixelFormat(w.dc, ^pfd), nil);
w.opengl_context = wgl.CreateContext(w.dc);
wgl.MakeCurrent(w.dc, w.opengl_context);
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);
attribs := [8]i32{
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
};
wgl_str := "wglCreateContextAttribsARB\x00";
wglCreateContextAttribsARB := cast(wgl.Create_Context_Attribs_ARB_Type)wgl.GetProcAddress(^wgl_str[0]);
w.rc = wglCreateContextAttribsARB(w.dc, nil, ^attribs[0]);
wgl.MakeCurrent(w.dc, w.rc);
SwapBuffers(w.dc);
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;
}
destroy_window :: proc(w: ^Window) {
proc destroy_window(w: ^Window) {
free(w.c_title);
}
display_window :: proc(w: ^Window) {
win32.SwapBuffers(w.dc);
proc display_window(w: ^Window) {
win32.swap_buffers(w.dc);
}
run :: proc() {
using win32;
proc run() {
using math;
win32_proc :: proc(hwnd: win32.Hwnd, msg: u32, wparam: win32.Wparam, lparam: win32.Lparam) -> win32.Lresult #no_inline {
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 DefWindowProcA(hwnd, msg, wparam, lparam);
return def_window_proc_a(hwnd, msg, wparam, lparam);
}
window, window_success := make_window("Odin Language Demo", 854, 480, cast(Wnd_Proc)win32_proc);
var window, window_success = make_window("Odin Language Demo", 854, 480, win32.WndProc(win32_proc));
if !window_success {
return;
}
defer destroy_window(^window);
defer destroy_window(&window);
gl.init();
using win32;
prev_time := time_now();
running := true;
var prev_time = time_now();
var running = true;
pos := Vec2{100, 100};
var pos = Vec2{100, 100};
for running {
curr_time := time_now();
dt := cast(f32)(curr_time - prev_time);
var curr_time = time_now();
var dt = f32(curr_time - prev_time);
prev_time = curr_time;
msg: Msg;
for PeekMessageA(^msg, nil, 0, 0, PM_REMOVE) > 0 {
var msg: Msg;
for peek_message_a(&msg, nil, 0, 0, PM_REMOVE) > 0 {
if msg.message == WM_QUIT {
running = false;
}
TranslateMessage(^msg);
DispatchMessageA(^msg);
translate_message(&msg);
dispatch_message_a(&msg);
}
if is_key_down(Key_Code.ESCAPE) {
if is_key_down(KeyCode.Escape) {
running = false;
}
{
SPEED :: 500;
v: Vec2;
const SPEED = 500;
var v: Vec2;
if is_key_down(Key_Code.RIGHT) { v[0] += 1; }
if is_key_down(Key_Code.LEFT) { v[0] -= 1; }
if is_key_down(Key_Code.UP) { v[1] += 1; }
if is_key_down(Key_Code.DOWN) { v[1] -= 1; }
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);
@@ -190,10 +190,10 @@ run :: proc() {
gl.Clear(gl.COLOR_BUFFER_BIT);
gl.LoadIdentity();
gl.Ortho(0, cast(f64)window.width,
0, cast(f64)window.height, 0, 1);
gl.Ortho(0, f64(window.width),
0, f64(window.height), 0, 1);
draw_rect :: proc(x, y, w, h: f32) {
proc draw_rect(x, y, w, h: f32) {
gl.Begin(gl.TRIANGLES);
defer gl.End();
@@ -208,15 +208,15 @@ run :: proc() {
draw_rect(pos.x, pos.y, 50, 50);
display_window(^window);
ms_to_sleep := cast(i32)(16 - 1000*dt);
display_window(&window);
var ms_to_sleep = i32(16 - 1000*dt);
if ms_to_sleep > 0 {
win32.Sleep(ms_to_sleep);
win32.sleep(ms_to_sleep);
}
}
}
main :: proc() {
proc main() {
run();
}
+62 -58
View File
@@ -1,12 +1,12 @@
#import "fmt.odin";
import "fmt.odin";
#foreign_system_library ws2 "Ws2_32.lib" when ODIN_OS == "windows";
foreign_system_library ws2 "Ws2_32.lib" when ODIN_OS == "windows";
SOCKET :: #type uint;
INVALID_SOCKET :: ~(cast(SOCKET)0);
type SOCKET uint;
const INVALID_SOCKET = ~SOCKET(0);
AF :: enum i32 {
type AF enum i32 {
UNSPEC = 0, // unspecified
UNIX = 1, // local to host (pipes, portals)
INET = 2, // internetwork: UDP, TCP, etc.
@@ -37,19 +37,22 @@ AF :: enum i32 {
MAX = 26,
};
SOCK_STREAM :: 1;
SOCKET_ERROR :: -1;
IPPROTO_TCP :: 6;
AI_PASSIVE :: 0x0020;
SOMAXCONN :: 128;
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;
)
SD_RECEIVE :: 0;
SD_SEND :: 1;
SD_BOTH :: 2;
WSADESCRIPTION_LEN :: 256;
WSASYS_STATUS_LEN :: 128;
WSADATA :: struct #ordered {
const WSADESCRIPTION_LEN = 256;
const WSASYS_STATUS_LEN = 128;
type WSADATA struct #ordered {
version: i16,
high_version: i16,
@@ -57,12 +60,12 @@ WSADATA :: struct #ordered {
// NOTE(bill): This is x64 ordering
max_sockets: u16,
max_udp_dg: u16,
vendor_info: ^byte,
description: [WSADESCRIPTION_LEN+1]byte,
system_status: [WSASYS_STATUS_LEN+1]byte,
vendor_info: ^u8,
description: [WSADESCRIPTION_LEN+1]u8,
system_status: [WSASYS_STATUS_LEN+1]u8,
}
addrinfo :: struct #ordered {
type addrinfo struct #ordered {
flags: i32,
family: i32,
socktype: i32,
@@ -73,52 +76,53 @@ addrinfo :: struct #ordered {
next: ^addrinfo,
}
sockaddr :: struct #ordered {
type sockaddr struct #ordered {
family: u16,
data: [14]byte,
data: [14]u8,
}
WSAStartup :: proc(version_requested: i16, data: ^WSADATA) -> i32 #foreign ws2;
WSACleanup :: proc() -> i32 #foreign ws2;
getaddrinfo :: proc(node_name, service_name: ^u8, hints: ^addrinfo, result: ^^addrinfo) -> i32 #foreign ws2;
freeaddrinfo :: proc(ai: ^addrinfo) #foreign ws2;
socket :: proc(af, type_, protocol: i32) -> SOCKET #foreign ws2;
closesocket :: proc(s: SOCKET) -> i32 #foreign ws2;
bind :: proc(s: SOCKET, name: ^sockaddr, name_len: i32) -> i32 #foreign ws2;
listen :: proc(s: SOCKET, back_log: i32) -> i32 #foreign ws2;
accept :: proc(s: SOCKET, addr: ^sockaddr, addr_len: i32) -> SOCKET #foreign ws2;
recv :: proc(s: SOCKET, buf: ^byte, len: i32, flags: i32) -> i32 #foreign ws2;
send :: proc(s: SOCKET, buf: ^byte, len: i32, flags: i32) -> i32 #foreign ws2;
shutdown :: proc(s: SOCKET, how: i32) -> i32 #foreign ws2;
WSAGetLastError :: proc() -> i32 #foreign ws2;
to_c_string :: proc(s: string) -> ^byte {
c_str := new_slice(byte, s.count+1);
assert(c_str.data != nil);
copy(c_str, cast([]byte)s);
c_str[s.count] = 0;
return c_str.data;
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];
}
run :: proc() {
wsa: WSADATA;
res: ^addrinfo = nil;
hints: addrinfo;
s, client: SOCKET;
proc run() {
var (
wsa: WSADATA;
res: ^addrinfo = nil;
hints: addrinfo;
s, client: SOCKET;
)
if WSAStartup(2 | (2 << 8), ^wsa) != 0 {
if WSAStartup(2 | (2 << 8), &wsa) != 0 {
fmt.println("WSAStartup failed: ", WSAGetLastError());
return;
}
defer WSACleanup();
hints.family = cast(i32)AF.INET;
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 {
if getaddrinfo(nil, to_c_string("8080"), &hints, &res) != 0 {
fmt.println("getaddrinfo failed: ", WSAGetLastError());
return;
}
@@ -131,7 +135,7 @@ run :: proc() {
}
defer closesocket(s);
bind(s, res.addr, cast(i32)res.addrlen);
bind(s, res.addr, i32(res.addrlen));
listen(s, SOMAXCONN);
client = accept(s, nil, 0);
@@ -141,7 +145,7 @@ run :: proc() {
}
defer closesocket(client);
html :=
var html =
`HTTP/1.1 200 OK
Connection: close
Content-type: text/html
@@ -156,12 +160,12 @@ Content-type: text/html
</html>
`;
buf: [1024]byte;
var buf: [1024]u8;
for {
bytes := recv(client, ^buf[0], cast(i32)buf.count, 0);
var bytes = recv(client, &buf[0], i32(len(buf)), 0);
if bytes > 0 {
// fmt.println(buf[:bytes] as string)
bytes_sent := send(client, html.data, cast(i32)(html.count-1), 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;
+233 -224
View File
@@ -1,35 +1,42 @@
#import win32 "sys/windows.odin";
#import "fmt.odin";
#import "os.odin";
#import "mem.odin";
import (
win32 "sys/windows.odin";
"fmt.odin";
"os.odin";
"mem.odin";
)
CANVAS_WIDTH :: 128;
CANVAS_HEIGHT :: 128;
CANVAS_SCALE :: 3;
FRAME_TIME :: 1.0/30.0;
WINDOW_TITLE :: "Punity\x00";
const (
CANVAS_WIDTH = 128;
CANVAS_HEIGHT = 128;
CANVAS_SCALE = 3;
FRAME_TIME = 1.0/30.0;
WINDOW_TITLE = "Punity\x00";
)
_ := compile_assert(CANVAS_WIDTH % 16 == 0);
const _ = compile_assert(CANVAS_WIDTH % 16 == 0);
WINDOW_WIDTH :: CANVAS_WIDTH * CANVAS_SCALE;
WINDOW_HEIGHT :: CANVAS_HEIGHT * CANVAS_SCALE;
const (
WINDOW_WIDTH = CANVAS_WIDTH * CANVAS_SCALE;
WINDOW_HEIGHT = CANVAS_HEIGHT * CANVAS_SCALE;
)
const (
STACK_CAPACITY = 1<<20;
STORAGE_CAPACITY = 1<<20;
STACK_CAPACITY :: 1<<20;
STORAGE_CAPACITY :: 1<<20;
DRAW_LIST_RESERVE = 128;
DRAW_LIST_RESERVE :: 128;
MAX_KEYS = 256;
)
MAX_KEYS :: 256;
Core :: struct {
type Core struct {
stack: ^Bank,
storage: ^Bank,
running: bool,
key_modifiers: u32,
key_states: [MAX_KEYS]byte,
key_deltas: [MAX_KEYS]byte,
key_states: [MAX_KEYS]u8,
key_deltas: [MAX_KEYS]u8,
perf_frame,
perf_frame_inner,
@@ -45,52 +52,52 @@ Core :: struct {
draw_list: ^Draw_List,
}
Perf_Span :: struct {
type Perf_Span struct {
stamp: f64,
delta: f32,
}
Bank :: struct {
memory: []byte,
type Bank struct {
memory: []u8,
cursor: int,
}
Bank_State :: struct {
type Bank_State struct {
state: Bank,
bank: ^Bank,
}
Color :: raw_union {
using channels: struct{a, b, g, r: byte},
type Color raw_union {
using channels: struct{a, b, g, r: u8},
rgba: u32,
}
Palette :: struct {
type Palette struct {
colors: [256]Color,
colors_count: byte,
colors_count: u8,
}
Rect :: raw_union {
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,
}
Bitmap :: struct {
pixels: []byte,
type Bitmap struct {
pixels: []u8,
width: int,
height: int,
}
Font :: struct {
type Font struct {
using bitmap: Bitmap,
char_width: int,
char_height: int,
}
Canvas :: struct {
type Canvas struct {
using bitmap: ^Bitmap,
palette: Palette,
translate_x: int,
@@ -99,89 +106,92 @@ Canvas :: struct {
font: ^Font,
}
DrawFlag :: enum {
type DrawFlag enum {
NONE = 0,
FLIP_H = 1<<0,
FLIP_V = 1<<1,
MASK = 1<<2,
}
Draw_Item :: struct {}
Draw_List :: struct {
type Draw_Item struct {}
type Draw_List struct {
items: []Draw_Item,
}
Key :: enum {
MOD_SHIFT = 0x0001,
MOD_CONTROL = 0x0002,
MOD_ALT = 0x0004,
MOD_SUPER = 0x0008,
type Key enum {
ModShift = 0x0001,
ModControl = 0x0002,
ModAlt = 0x0004,
ModSuper = 0x0008,
UNKNOWN =-1,
INVALID =-2,
LBUTTON = 1,
RBUTTON = 2,
CANCEL = 3,
MBUTTON = 4,
Unknown =-1,
Invalid =-2,
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,
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,
@@ -206,32 +216,33 @@ Key :: enum {
F22 = 0x85,
F23 = 0x86,
F24 = 0x87,
NUMLOCK = 0x90,
SCROLL = 0x91,
LSHIFT = 0xA0,
RSHIFT = 0xA1,
LCONTROL = 0xA2,
RCONTROL = 0xA3,
LMENU = 0xA4,
RMENU = 0xA5,
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, /* = */
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,
@@ -258,56 +269,55 @@ Key :: enum {
X = 88,
Y = 89,
Z = 90,
LEFT_BRACKET = 91, /* [ */
BACKSLASH = 92, /* \ */
RIGHT_BRACKET = 93, /* ] */
GRAVE_ACCENT = 96, /* ` */
LeftBracket = 91, /* [ */
Backslash = 92, /* \ */
RightBracket = 93, /* ] */
GraveAccent = 96, /* ` */
};
key_down :: proc(k: Key) -> bool {
proc key_down(k: Key) -> bool {
return _core.key_states[k] != 0;
}
key_pressed :: proc(k: Key) -> bool {
proc key_pressed(k: Key) -> bool {
return (_core.key_deltas[k] != 0) && key_down(k);
}
win32_perf_count_freq := win32.GetQueryPerformanceFrequency();
time_now :: proc() -> f64 {
let win32_perf_count_freq = win32.get_query_performance_frequency();
proc time_now() -> f64 {
assert(win32_perf_count_freq != 0);
counter: i64;
win32.QueryPerformanceCounter(^counter);
result := cast(f64)counter / cast(f64)win32_perf_count_freq;
return result;
var counter: i64;
win32.query_performance_counter(&counter);
return f64(counter) / f64(win32_perf_count_freq);
}
_core: Core;
var _core: Core;
run :: proc(user_init, user_step: proc(c: ^Core)) {
proc run(user_init, user_step: proc(c: ^Core)) {
using win32;
_core.running = true;
win32_proc :: proc(hwnd: win32.HWND, msg: u32, wparam: win32.WPARAM, lparam: win32.LPARAM) -> win32.LRESULT #no_inline #cc_c {
win32_app_key_mods :: proc() -> u32 {
mods: u32 = 0;
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(Key_Code.SHIFT) {
mods |= cast(u32)Key.MOD_SHIFT;
if is_key_down(KeyCode.Shift) {
mods |= u32(Key.ModShift);
}
if is_key_down(Key_Code.CONTROL) {
mods |= cast(u32)Key.MOD_CONTROL;
if is_key_down(KeyCode.Control) {
mods |= u32(Key.ModControl);
}
if is_key_down(Key_Code.MENU) {
mods |= cast(u32)Key.MOD_ALT;
if is_key_down(KeyCode.Menu) {
mods |= u32(Key.ModAlt);
}
if is_key_down(Key_Code.LWIN) || is_key_down(Key_Code.RWIN) {
mods |= cast(u32)Key.MOD_SUPER;
if is_key_down(KeyCode.Lwin) || is_key_down(KeyCode.Rwin) {
mods |= u32(Key.ModSuper);
}
return mods;
@@ -331,61 +341,62 @@ run :: proc(user_init, user_step: proc(c: ^Core)) {
return 0;
case WM_CLOSE:
PostQuitMessage(0);
post_quit_message(0);
_core.running = false;
return 0;
}
return DefWindowProcA(hwnd, msg, wparam, lparam);
return def_window_proc_a(hwnd, msg, wparam, lparam);
}
window_class := WNDCLASSEXA{
class_name = (cast(string)"Punity\x00").data, // C-style string
size = size_of(WNDCLASSEXA),
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 = cast(HINSTANCE)GetModuleHandleA(nil),
instance = Hinstance(get_module_handle_a(nil)),
wnd_proc = win32_proc,
// wnd_proc = DefWindowProcA,
background = cast(HBRUSH)GetStockObject(BLACK_BRUSH),
background = Hbrush(get_stock_object(BLACK_BRUSH)),
};
if RegisterClassExA(^window_class) == 0 {
fmt.fprintln(os.stderr, "RegisterClassExA failed");
if register_class_ex_a(&window_class) == 0 {
fmt.fprintln(os.stderr, "register_class_ex_a failed");
return;
}
screen_width := GetSystemMetrics(SM_CXSCREEN);
screen_height := GetSystemMetrics(SM_CYSCREEN);
var screen_width = get_system_metrics(SM_CXSCREEN);
var screen_height = get_system_metrics(SM_CYSCREEN);
rc: RECT;
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;
style: u32 = WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
assert(AdjustWindowRect(^rc, style, 0) != 0);
var style: u32 = WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
assert(adjust_window_rect(&rc, style, 0) != 0);
wt := WINDOW_TITLE;
var wt = WINDOW_TITLE;
win32_window := CreateWindowExA(0,
window_class.class_name,
wt.data,
style,
rc.left, rc.top,
rc.right-rc.left, rc.bottom-rc.top,
nil, nil, window_class.instance,
nil);
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, "CreateWindowExA failed");
fmt.fprintln(os.stderr, "create_window_ex_a failed");
return;
}
window_bmi: BITMAPINFO;
window_bmi.size = size_of(BITMAPINFOHEADER);
var window_bmi: BitmapInfo;
window_bmi.size = size_of(BitmapInfoHeader);
window_bmi.width = CANVAS_WIDTH;
window_bmi.height = CANVAS_HEIGHT;
window_bmi.planes = 1;
@@ -393,27 +404,27 @@ run :: proc(user_init, user_step: proc(c: ^Core)) {
window_bmi.compression = BI_RGB;
user_init(^_core);
user_init(&_core);
ShowWindow(win32_window, SW_SHOW);
show_window(win32_window, SW_SHOW);
window_buffer := new_slice(u32, CANVAS_WIDTH * CANVAS_HEIGHT);
var window_buffer = make([]u32, CANVAS_WIDTH * CANVAS_HEIGHT);
defer free(window_buffer);
for i := 0; i < window_buffer.count; i += 1 {
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;
)
dt: f64;
prev_time := time_now();
curr_time := time_now();
total_time : f64 = 0;
offset_x := 0;
offset_y := 0;
message: MSG;
var message: Msg;
for _core.running {
curr_time = time_now();
dt = curr_time - prev_time;
@@ -424,64 +435,62 @@ run :: proc(user_init, user_step: proc(c: ^Core)) {
offset_y += 2;
{
data: [128]byte;
buf: fmt.Buffer;
buf.data = data[:];
fmt.bprintf(^buf, "Punity: %.4f ms\x00", dt*1000);
win32.SetWindowTextA(win32_window, ^buf[0]);
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 y := 0; y < CANVAS_HEIGHT; y += 1 {
for x := 0; x < CANVAS_WIDTH; x += 1 {
g := (x % 32) * 8;
b := (y % 32) * 8;
window_buffer[x + y*CANVAS_WIDTH] = cast(u32)(g << 8 | b);
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_val(_core.key_deltas));
mem.zero(&_core.key_deltas[0], size_of(_core.key_deltas));
for PeekMessageA(^message, nil, 0, 0, PM_REMOVE) != 0 {
for peek_message_a(&message, nil, 0, 0, PM_REMOVE) != 0 {
if message.message == WM_QUIT {
_core.running = false;
}
TranslateMessage(^message);
DispatchMessageA(^message);
translate_message(&message);
dispatch_message_a(&message);
}
user_step(^_core);
user_step(&_core);
dc := GetDC(win32_window);
StretchDIBits(dc,
0, 0, CANVAS_WIDTH * CANVAS_SCALE, CANVAS_HEIGHT * CANVAS_SCALE,
0, 0, CANVAS_WIDTH, CANVAS_HEIGHT,
window_buffer.data,
^window_bmi,
DIB_RGB_COLORS,
SRCCOPY);
ReleaseDC(win32_window, dc);
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);
{
delta := time_now() - prev_time;
ms := cast(i32)((FRAME_TIME - delta) * 1000);
var delta = time_now() - prev_time;
var ms = i32((FRAME_TIME - delta) * 1000);
if ms > 0 {
win32.Sleep(ms);
win32.sleep(ms);
}
}
_core.frame += 1;
_core.frame++;
}
}
main :: proc() {
user_init :: proc(c: ^Core) {
proc main() {
proc user_init(c: ^Core) {
}
user_step :: proc(c: ^Core) {
proc user_step(c: ^Core) {
}
-5
View File
@@ -1,5 +0,0 @@
#import "fmt.odin" as fmt
thing :: proc() {
fmt.println("Sub Hello!")
}
-35
View File
@@ -1,35 +0,0 @@
/*#import "fmt.odin"
thing :: proc() {
fmt.println("Hello1!")
}*/
#import "fmt.odin";
main :: proc() {
fmt.println("hello, world!");
}
/*#import "fmt.odin" as .
thing :: proc() {
println("Hello3!")
}
*/
/*#import "fmt.odin" as _
thing :: proc() {
// println("Hello4!")
}
*/
/*
#include "fmt.odin"
thing :: proc() {
println("Hello5!")
}*/
+402 -351
View File
File diff suppressed because it is too large Load Diff
+211 -142
View File
@@ -1,158 +1,227 @@
#shared_global_scope;
// import "fmt.odin";
// proc __u128_mod(a, b: u128) -> u128 #link_name "__umodti3" {
// var _, r := __u128_quo_mod(a, b)
// return r
// }
// proc __u128_quo(a, b: u128) -> u128 #link_name "__udivti3" {
// var n, _ := __u128_quo_mod(a, b)
// return n
// }
// proc __i128_mod(a, b: i128) -> i128 #link_name "__modti3" {
// var _, r := __i128_quo_mod(a, b)
// return r
// }
// proc __i128_quo(a, b: i128) -> i128 #link_name "__divti3" {
// var n, _ := __i128_quo_mod(a, b)
// return n
// }
// proc __i128_quo_mod(a, b: i128) -> (i128, i128) #link_name "__divmodti4" {
// var s := b >> 127
// b = (b ~ s) - s
// s = a >> 127
// a = (a ~ s) - s
// var n, r := __u128_quo_mod(a as u128, b as u128)
// return (n as i128 ~ s) - s, (r as i128 ~ s) - s
// }
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);
// proc __u128_quo_mod(a, b: u128) -> (u128, u128) #link_name "__udivmodti4" {
// proc clz(x: u64) -> u64 {
// proc clz_u64(x: u64, is_zero_undef: bool) -> u64 #foreign "llvm.ctlz.i64"
// return clz_u64(x, false)
// }
// proc ctz(x: u64) -> u64 {
// proc ctz_u64(x: u64, is_zero_undef: bool) -> u64 #foreign "llvm.cttz.i64"
// return ctz_u64(x, false)
// }
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;
}
// u128_lo_hi :: raw_union {
// all: u128
// using _lohi: struct {lo, hi: u64;}
// }
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);
}
// n, d, q, r: u128_lo_hi
// sr: u64
var r, d, x, q: u128 = a, b, 1, 0;
// n.all = a
// d.all = b
for r >= d && (d>>127)&1 == 0 {
x <<= 1;
d <<= 1;
}
// if n.hi == 0 {
// if d.hi == 0 {
// return (n.lo / d.lo) as u128, (n.lo % d.lo) as u128
// }
// return 0, n.lo as u128
// }
// if d.lo == 0 {
// if d.hi == 0 {
// return (n.hi / d.lo) as u128, (n.hi % d.lo) as u128
// }
// if n.lo == 0 {
// r.hi = n.hi % d.hi
// r.lo = 0
// return (n.hi / d.hi) as u128, r.all
// }
// if (d.hi & (d.hi-1)) == 0 {
// r.lo = n.lo
// r.hi = n.hi & (d.hi-1)
// return (n.hi >> ctz(d.hi)) as u128, r.all
// }
for x != 0 {
if r >= d {
r -= d;
q |= x;
}
x >>= 1;
d >>= 1;
}
// sr = clz(d.hi) - clz(n.hi)
// if sr > 64 - 2 {
// return 0, n.all
// }
// sr++
// q.lo = 0
// q.hi = n.lo << (64-sr)
// r.hi = n.hi >> sr
// r.lo = (n.hi << (64-sr)) | (n.lo >> sr)
// } else {
// if d.hi == 0 {
// if (d.lo & (d.lo - 1)) == 0 {
// var rem := (n.lo % (d.lo - 1)) as u128
// if d.lo == 1 {
// return n.all, rem
// }
// sr = ctz(d.lo)
// q.hi = n.hi >> sr
// q.lo = (n.hi << (64-sr)) | (n.lo >> sr)
// return q.all, rem
// }
if rem != nil { rem^ = r; }
return q;
}
// sr = 1 + 64 + clz(d.lo) - clz(n.hi)
/*
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};
// q.all = n.all << (128-sr)
// r.all = n.all >> sr
// if sr == 64 {
// q.lo = 0
// q.hi = n.lo
// r.hi = 0
// r.lo = n.hi
// } else if sr < 64 {
// q.lo = 0
// q.hi = n.lo << (64-sr)
// r.hi = n.hi >> sr
// r.lo = (n.hi << (64-sr)) | (n.lo >> sr)
// } else {
// q.lo = n.lo << (128-sr)
// q.hi = (n.hi << (128-sr)) | (n.lo >> (sr-64))
// r.hi = 0
// r.lo = n.hi >> (sr-64)
// }
// } else {
// sr = clz(d.hi) - clz(n.hi)
// if sr > 64-1 {
// return 0, n.all
// }
// sr++
// q.lo = 0
// q.hi = n.lo << (64-sr)
// r.all = n.all >> sr
// if sr < 64 {
// r.hi = n.hi >> sr
// r.lo = (n.hi << (64-sr)) | (n.lo >> sr)
// } else {
// r.hi = 0
// r.lo = n.hi
// }
// }
// }
magic, was_infnan: FP32;
magic.u = (254-15) << 23;
was_infnan.u = (127+16) << 23;
// carry: u64
// for ; sr > 0; sr-- {
// r.hi = (r.hi << 1) | (r.lo >> (64-1))
// r.lo = (r.lo << 1) | (r.hi >> (64-1))
// q.hi = (q.hi << 1) | (q.lo >> (64-1))
// q.lo = (q.lo << 1) | carry
hu := transmute(u16, f);
// carry = 0
// if r.all >= d.all {
// r.all -= d.all
// carry = 1
// }
// }
o := FP32{};
// q.all = (q.all << 1) | (carry as u128)
// return q.all, r.all
// }
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));
}
*/
+42 -42
View File
@@ -1,41 +1,41 @@
// TODO(bill): Use assembly instead here to implement atomics
// Inline vs external file?
#import win32 "sys/windows.odin" when ODIN_OS == "windows";
_ := compile_assert(ODIN_ARCH == "amd64"); // TODO(bill): x86 version
import win32 "sys/windows.odin" when ODIN_OS == "windows";
var _ = compile_assert(ODIN_ARCH == "amd64"); // TODO(bill): x86 version
yield_thread :: proc() { win32.mm_pause(); }
mfence :: proc() { win32.ReadWriteBarrier(); }
sfence :: proc() { win32.WriteBarrier(); }
lfence :: proc() { win32.ReadBarrier(); }
proc yield_thread() { win32.mm_pause(); }
proc mfence () { win32.read_write_barrier(); }
proc sfence () { win32.write_barrier(); }
proc lfence () { win32.read_barrier(); }
load :: proc(a: ^i32) -> i32 {
proc load(a: ^i32) -> i32 {
return a^;
}
store :: proc(a: ^i32, value: i32) {
proc store(a: ^i32, value: i32) {
a^ = value;
}
compare_exchange :: proc(a: ^i32, expected, desired: i32) -> i32 {
return win32.InterlockedCompareExchange(a, desired, expected);
proc compare_exchange(a: ^i32, expected, desired: i32) -> i32 {
return win32.interlocked_compare_exchange(a, desired, expected);
}
exchanged :: proc(a: ^i32, desired: i32) -> i32 {
return win32.InterlockedExchange(a, desired);
proc exchanged(a: ^i32, desired: i32) -> i32 {
return win32.interlocked_exchange(a, desired);
}
fetch_add :: proc(a: ^i32, operand: i32) -> i32 {
return win32.InterlockedExchangeAdd(a, operand);
proc fetch_add(a: ^i32, operand: i32) -> i32 {
return win32.interlocked_exchange_add(a, operand);
}
fetch_and :: proc(a: ^i32, operand: i32) -> i32 {
return win32.InterlockedAnd(a, operand);
proc fetch_and(a: ^i32, operand: i32) -> i32 {
return win32.interlocked_and(a, operand);
}
fetch_or :: proc(a: ^i32, operand: i32) -> i32 {
return win32.InterlockedOr(a, operand);
proc fetch_or(a: ^i32, operand: i32) -> i32 {
return win32.interlocked_or(a, operand);
}
spin_lock :: proc(a: ^i32, time_out: int) -> bool { // NOTE(bill) time_out = -1 as default
old_value := compare_exchange(a, 1, 0);
counter := 0;
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();
@@ -44,42 +44,42 @@ spin_lock :: proc(a: ^i32, time_out: int) -> bool { // NOTE(bill) time_out = -1
}
return old_value == 0;
}
spin_unlock :: proc(a: ^i32) {
proc spin_unlock(a: ^i32) {
store(a, 0);
mfence();
}
try_acquire_lock :: proc(a: ^i32) -> bool {
proc try_acquire_lock(a: ^i32) -> bool {
yield_thread();
old_value := compare_exchange(a, 1, 0);
var old_value = compare_exchange(a, 1, 0);
mfence();
return old_value == 0;
}
load :: proc(a: ^i64) -> i64 {
proc load(a: ^i64) -> i64 {
return a^;
}
store :: proc(a: ^i64, value: i64) {
proc store(a: ^i64, value: i64) {
a^ = value;
}
compare_exchange :: proc(a: ^i64, expected, desired: i64) -> i64 {
return win32.InterlockedCompareExchange64(a, desired, expected);
proc compare_exchange(a: ^i64, expected, desired: i64) -> i64 {
return win32.interlocked_compare_exchange64(a, desired, expected);
}
exchanged :: proc(a: ^i64, desired: i64) -> i64 {
return win32.InterlockedExchange64(a, desired);
proc exchanged(a: ^i64, desired: i64) -> i64 {
return win32.interlocked_exchange64(a, desired);
}
fetch_add :: proc(a: ^i64, operand: i64) -> i64 {
return win32.InterlockedExchangeAdd64(a, operand);
proc fetch_add(a: ^i64, operand: i64) -> i64 {
return win32.interlocked_exchange_add64(a, operand);
}
fetch_and :: proc(a: ^i64, operand: i64) -> i64 {
return win32.InterlockedAnd64(a, operand);
proc fetch_and(a: ^i64, operand: i64) -> i64 {
return win32.interlocked_and64(a, operand);
}
fetch_or :: proc(a: ^i64, operand: i64) -> i64 {
return win32.InterlockedOr64(a, operand);
proc fetch_or(a: ^i64, operand: i64) -> i64 {
return win32.interlocked_or64(a, operand);
}
spin_lock :: proc(a: ^i64, time_out: int) -> bool { // NOTE(bill) time_out = -1 as default
old_value := compare_exchange(a, 1, 0);
counter := 0;
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();
@@ -88,13 +88,13 @@ spin_lock :: proc(a: ^i64, time_out: int) -> bool { // NOTE(bill) time_out = -1
}
return old_value == 0;
}
spin_unlock :: proc(a: ^i64) {
proc spin_unlock(a: ^i64) {
store(a, 0);
mfence();
}
try_acquire_lock :: proc(a: ^i64) -> bool {
proc try_acquire_lock(a: ^i64) -> bool {
yield_thread();
old_value := compare_exchange(a, 1, 0);
var old_value = compare_exchange(a, 1, 0);
mfence();
return old_value == 0;
}
+287
View File
@@ -0,0 +1,287 @@
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; }
+53 -53
View File
@@ -2,23 +2,21 @@
// Multiple precision decimal numbers
// NOTE: This is only for floating point printing and nothing else
Decimal :: struct {
digits: [384]byte, // big-endian digits
type Decimal struct {
digits: [384]u8, // big-endian digits
count: int,
decimal_point: int,
neg, trunc: bool,
}
decimal_to_string :: proc(buf: []byte, a: ^Decimal) -> string {
digit_zero :: proc(buf: []byte) -> int {
for _, i in buf {
buf[i] = '0';
}
proc decimal_to_string(buf: []u8, a: ^Decimal) -> string {
proc digit_zero(buf: []u8) -> int {
for _, i in buf -> buf[i] = '0';
return len(buf);
}
n := 10 + a.count + abs(a.decimal_point);
var 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);
@@ -29,7 +27,7 @@ decimal_to_string :: proc(buf: []byte, a: ^Decimal) -> string {
return string(buf[0..<1]);
}
w := 0;
var w = 0;
if a.decimal_point <= 0 {
buf[w] = '0'; w++;
buf[w] = '.'; w++;
@@ -48,7 +46,7 @@ decimal_to_string :: proc(buf: []byte, a: ^Decimal) -> string {
}
// trim trailing zeros
trim :: proc(a: ^Decimal) {
proc trim(a: ^Decimal) {
for a.count > 0 && a.digits[a.count-1] == '0' {
a.count--;
}
@@ -58,13 +56,13 @@ trim :: proc(a: ^Decimal) {
}
assign :: proc(a: ^Decimal, i: u64) {
buf: [32]byte;
n := 0;
proc assign(a: ^Decimal, i: u64) {
var buf: [32]u8;
var n = 0;
for i > 0 {
j := i/10;
var j = i/10;
i -= 10*j;
buf[n] = byte('0'+i);
buf[n] = u8('0'+i);
n++;
i = j;
}
@@ -78,14 +76,13 @@ assign :: proc(a: ^Decimal, i: u64) {
trim(a);
}
uint_size :: 8*size_of(uint);
max_shift :: uint_size-4;
shift_right :: proc(a: ^Decimal, k: uint) {
r := 0; // read index
w := 0; // write index
n: uint;
proc shift_right(a: ^Decimal, k: uint) {
var r = 0; // read index
var w = 0; // write index
var n: uint;
for ; n>>k == 0; r++ {
if r >= a.count {
if n == 0 {
@@ -99,27 +96,27 @@ shift_right :: proc(a: ^Decimal, k: uint) {
}
break;
}
c := uint(a.digits[r]);
var c = uint(a.digits[r]);
n = n*10 + c - '0';
}
a.decimal_point -= r-1;
mask: uint = (1<<k) - 1;
var mask: uint = (1<<k) - 1;
for ; r < a.count; r++ {
c := uint(a.digits[r]);
dig := n>>k;
var c = uint(a.digits[r]);
var dig = n>>k;
n &= mask;
a.digits[w] = byte('0' + dig);
a.digits[w] = u8('0' + dig);
w++;
n = n*10 + c - '0';
}
for n > 0 {
dig := n>>k;
var dig = n>>k;
n &= mask;
if w < len(a.digits) {
a.digits[w] = byte('0' + dig);
a.digits[w] = u8('0' + dig);
w++;
} else if dig > 0 {
a.trunc = true;
@@ -132,20 +129,20 @@ shift_right :: proc(a: ^Decimal, k: uint) {
trim(a);
}
shift_left :: proc(a: ^Decimal, k: uint) {
delta := int(k/4);
proc shift_left(a: ^Decimal, k: uint) {
var delta = int(k/4);
r := a.count; // read index
w := a.count+delta; // write index
var r = a.count; // read index
var w = a.count+delta; // write index
n: uint;
var n: uint;
for r--; r >= 0; r-- {
n += (uint(a.digits[r]) - '0') << k;
quo := n/10;
rem := n - 10*quo;
var quo = n/10;
var rem = n - 10*quo;
w--;
if w < len(a.digits) {
a.digits[w] = byte('0' + rem);
a.digits[w] = u8('0' + rem);
} else if rem != 0 {
a.trunc = true;
}
@@ -153,11 +150,11 @@ shift_left :: proc(a: ^Decimal, k: uint) {
}
for n > 0 {
quo := n/10;
rem := n - 10*quo;
var quo = n/10;
var rem = n - 10*quo;
w--;
if 0 <= w && w < len(a.digits) {
a.digits[w] = byte('0' + rem);
a.digits[w] = u8('0' + rem);
} else if rem != 0 {
a.trunc = true;
}
@@ -170,7 +167,12 @@ shift_left :: proc(a: ^Decimal, k: uint) {
trim(a);
}
shift :: proc(a: ^Decimal, k: int) {
proc shift(a: ^Decimal, k: int) {
const (
uint_size = 8*size_of(uint);
max_shift = uint_size-4;
)
match {
case a.count == 0:
// no need to update
@@ -191,19 +193,17 @@ shift :: proc(a: ^Decimal, k: int) {
}
}
can_round_up :: proc(a: ^Decimal, nd: int) -> bool {
proc can_round_up(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 -> return true;
return nd > 0 && (a.digits[nd-1]-'0')%2 != 0;
}
return a.digits[nd] >= '5';
}
round :: proc(a: ^Decimal, nd: int) {
proc round(a: ^Decimal, nd: int) {
if nd < 0 || nd >= a.count { return; }
if can_round_up(a, nd) {
round_up(a, nd);
@@ -212,11 +212,11 @@ round :: proc(a: ^Decimal, nd: int) {
}
}
round_up :: proc(a: ^Decimal, nd: int) {
proc round_up(a: ^Decimal, nd: int) {
if nd < 0 || nd >= a.count { return; }
for i := nd-1; i >= 0; i-- {
if c := a.digits[i]; c < '9' {
for var i = nd-1; i >= 0; i-- {
if var c = a.digits[i]; c < '9' {
a.digits[i]++;
a.count = i+1;
return;
@@ -229,7 +229,7 @@ round_up :: proc(a: ^Decimal, nd: int) {
a.decimal_point++;
}
round_down :: proc(a: ^Decimal, nd: int) {
proc round_down(a: ^Decimal, nd: int) {
if nd < 0 || nd >= a.count { return; }
a.count = nd;
trim(a);
@@ -237,13 +237,13 @@ round_down :: proc(a: ^Decimal, nd: int) {
// Extract integer part, rounded appropriately. There are no guarantees about overflow.
rounded_integer :: proc(a: ^Decimal) -> u64 {
proc rounded_integer(a: ^Decimal) -> u64 {
if a.decimal_point > 20 {
return 0xffff_ffff_ffff_ffff;
}
i: int;
n: u64 = 0;
m := min(a.decimal_point, a.count);
var i: int;
var n: u64 = 0;
var m = min(a.decimal_point, a.count);
for i = 0; i < m; i++ {
n = n*10 + u64(a.digits[i]-'0');
}
+442 -481
View File
File diff suppressed because it is too large Load Diff
+52 -45
View File
@@ -1,61 +1,65 @@
crc32 :: proc(data: []byte) -> u32 {
result := ~u32(0);
proc crc32(data: []u8) -> u32 {
var result = ~u32(0);
for b in data {
result = result>>8 ~ _crc32_table[(result ~ u32(b)) & 0xff];
}
return ~result;
}
crc64 :: proc(data: []byte) -> u64 {
result := ~u64(0);
proc crc64(data: []u8) -> u64 {
var result = ~u64(0);
for b in data {
result = result>>8 ~ _crc64_table[(result ~ u64(b)) & 0xff];
}
return ~result;
}
fnv32 :: proc(data: []byte) -> u32 {
h: u32 = 0x811c9dc5;
proc fnv32(data: []u8) -> u32 {
var h: u32 = 0x811c9dc5;
for b in data {
h = (h * 0x01000193) ~ u32(b);
}
return h;
}
fnv64 :: proc(data: []byte) -> u64 {
h: u64 = 0xcbf29ce484222325;
proc fnv64(data: []u8) -> u64 {
var h: u64 = 0xcbf29ce484222325;
for b in data {
h = (h * 0x100000001b3) ~ u64(b);
}
return h;
}
fnv32a :: proc(data: []byte) -> u32 {
h: u32 = 0x811c9dc5;
proc fnv32a(data: []u8) -> u32 {
var h: u32 = 0x811c9dc5;
for b in data {
h = (h ~ u32(b)) * 0x01000193;
}
return h;
}
fnv64a :: proc(data: []byte) -> u64 {
h: u64 = 0xcbf29ce484222325;
proc fnv64a(data: []u8) -> u64 {
var h: u64 = 0xcbf29ce484222325;
for b in data {
h = (h ~ u64(b)) * 0x100000001b3;
}
return h;
}
murmur32 :: proc(data: []byte) -> u32 {
c1_32: u32 : 0xcc9e2d51;
c2_32: u32 : 0x1b873593;
proc murmur32(data: []u8) -> u32 {
const (
c1_32: u32 = 0xcc9e2d51;
c2_32: u32 = 0x1b873593;
)
h1: u32 = 0;
nblocks := len(data)/4;
p := &data[0];
p1 := p + 4*nblocks;
var (
h1: u32 = 0;
nblocks = len(data)/4;
p = &data[0];
p1 = p + 4*nblocks;
)
for ; p < p1; p += 4 {
k1 := ^u32(p)^;
var k1 = ^u32(p)^;
k1 *= c1_32;
k1 = (k1 << 15) | (k1 >> 17);
@@ -66,9 +70,8 @@ murmur32 :: proc(data: []byte) -> u32 {
h1 = h1*5 + 0xe6546b64;
}
tail := data[nblocks*4 ..];
k1: u32;
var tail = data[nblocks*4 ..];
var k1: u32;
match len(tail)&3 {
case 3:
k1 ~= u32(tail[2]) << 16;
@@ -95,18 +98,20 @@ murmur32 :: proc(data: []byte) -> u32 {
return h1;
}
murmur64 :: proc(data: []byte) -> u64 {
SEED :: 0x9747b28c;
proc murmur64(data: []u8) -> u64 {
const SEED = 0x9747b28c;
when size_of(int) == 8 {
m :: 0xc6a4a7935bd1e995;
r :: 47;
const (
m = 0xc6a4a7935bd1e995;
r = 47;
)
h: u64 = SEED ~ (u64(len(data)) * m);
data64 := slice_ptr(^u64(&data[0]), len(data)/size_of(u64));
var h: u64 = SEED ~ (u64(len(data)) * m);
var data64 = slice_ptr(^u64(&data[0]), len(data)/size_of(u64));
for _, i in data64 {
k := data64[i];
var k = data64[i];
k *= m;
k ~= k>>r;
@@ -134,18 +139,21 @@ murmur64 :: proc(data: []byte) -> u64 {
return h;
} else {
m :: 0x5bd1e995;
r :: 24;
const (
m = 0x5bd1e995;
r = 24;
)
h1 := u32(SEED) ~ u32(len(data));
h2 := u32(SEED) >> 32;
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;
)
data32 := slice_ptr(cast(^u32)&data[0], len(data)/size_of(u32));
len := len(data);
i := 0;
for len >= 8 {
k1, k2: u32;
var k1, k2: u32;
k1 = data32[i]; i++;
k1 *= m;
k1 ~= k1>>r;
@@ -164,7 +172,7 @@ murmur64 :: proc(data: []byte) -> u64 {
}
if len >= 4 {
k1: u32;
var k1: u32;
k1 = data32[i]; i++;
k1 *= m;
k1 ~= k1>>r;
@@ -175,7 +183,7 @@ murmur64 :: proc(data: []byte) -> u64 {
}
// TODO(bill): Fix this
#no_bounds_check data8 := slice_to_bytes(data32[i..])[0..<3];
#no_bounds_check var data8 = slice_to_bytes(data32[i..])[0..<3];
match len {
case 3:
h2 ~= u32(data8[2]) << 16;
@@ -197,13 +205,12 @@ murmur64 :: proc(data: []byte) -> u64 {
h2 ~= h1>>19;
h2 *= m;
h := cast(u64)(h1)<<32 | cast(u64)(h2);
return h;
return u64(h1)<<32 | u64(h2);
}
}
immutable _crc32_table := [256]u32{
var _crc32_table = [256]u32{
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba,
0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
@@ -269,7 +276,7 @@ immutable _crc32_table := [256]u32{
0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,
};
immutable _crc64_table := [256]u64{
var _crc64_table = [256]u64{
0x0000000000000000, 0x42f0e1eba9ea3693, 0x85e1c3d753d46d26, 0xc711223cfa3e5bb5,
0x493366450e42ecdf, 0x0bc387aea7a8da4c, 0xccd2a5925d9681f9, 0x8e224479f47cb76a,
0x9266cc8a1c85d9be, 0xd0962d61b56fef2d, 0x17870f5d4f51b498, 0x5577eeb6e6bb820b,
+175 -161
View File
@@ -1,102 +1,108 @@
TAU :: 6.28318530717958647692528676655900576;
PI :: 3.14159265358979323846264338327950288;
ONE_OVER_TAU :: 0.636619772367581343075535053490057448;
ONE_OVER_PI :: 0.159154943091895335768883763372514362;
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;
E = 2.71828182845904523536;
SQRT_TWO = 1.41421356237309504880168872420969808;
SQRT_THREE = 1.73205080756887729352744634150587236;
SQRT_FIVE = 2.23606797749978969640917366873127623;
LOG_TWO :: 0.693147180559945309417232121458176568;
LOG_TEN :: 2.30258509299404568401799145468436421;
LOG_TWO = 0.693147180559945309417232121458176568;
LOG_TEN = 2.30258509299404568401799145468436421;
EPSILON :: 1.19209290e-7;
EPSILON = 1.19209290e-7;
τ :: TAU;
π :: PI;
τ = TAU;
π = PI;
)
type (
Vec2 [vector 2]f32;
Vec3 [vector 3]f32;
Vec4 [vector 4]f32;
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;
// Column major
Mat2 :: [2][2]f32;
Mat3 :: [3][3]f32;
Mat4 :: [4][4]f32;
Complex complex64;
)
Complex :: complex64;
Quat :: quaternion128;
foreign __llvm_core {
proc sqrt(x: f32) -> f32 #link_name "llvm.sqrt.f32";
proc sqrt(x: f64) -> f64 #link_name "llvm.sqrt.f64";
sqrt :: proc(x: f32) -> f32 #foreign __llvm_core "llvm.sqrt.f32";
sqrt :: proc(x: f64) -> f64 #foreign __llvm_core "llvm.sqrt.f64";
proc sin (θ: f32) -> f32 #link_name "llvm.sin.f32";
proc sin (θ: f64) -> f64 #link_name "llvm.sin.f64";
sin :: proc(θ: f32) -> f32 #foreign __llvm_core "llvm.sin.f32";
sin :: proc(θ: f64) -> f64 #foreign __llvm_core "llvm.sin.f64";
proc cos (θ: f32) -> f32 #link_name "llvm.cos.f32";
proc cos (θ: f64) -> f64 #link_name "llvm.cos.f64";
cos :: proc(θ: f32) -> f32 #foreign __llvm_core "llvm.cos.f32";
cos :: proc(θ: f64) -> f64 #foreign __llvm_core "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";
tan :: proc(θ: f32) -> f32 #inline { return sin(θ)/cos(θ); }
tan :: proc(θ: f64) -> f64 #inline { return sin(θ)/cos(θ); }
proc fmuladd(a, b, c: f32) -> f32 #link_name "llvm.fmuladd.f32";
proc fmuladd(a, b, c: f64) -> f64 #link_name "llvm.fmuladd.f64";
}
pow :: proc(x, power: f32) -> f32 #foreign __llvm_core "llvm.pow.f32";
pow :: proc(x, power: f64) -> f64 #foreign __llvm_core "llvm.pow.f64";
proc tan (θ: f32) -> f32 #inline { return sin(θ)/cos(θ); }
proc tan (θ: f64) -> f64 #inline { return sin(θ)/cos(θ); }
lerp :: proc(a, b, t: f32) -> f32 { return a*(1-t) + b*t; }
lerp :: proc(a, b, t: f64) -> f64 { return a*(1-t) + b*t; }
sign :: proc(x: f32) -> f32 { return x >= 0 ? +1 : -1; }
sign :: proc(x: f64) -> f64 { return x >= 0 ? +1 : -1; }
bit_reverse :: proc(b: u16) -> u16 #foreign __llvm_core "llvm.bitreverse.i16";
bit_reverse :: proc(b: u32) -> u32 #foreign __llvm_core "llvm.bitreverse.i32";
bit_reverse :: proc(b: u64) -> u64 #foreign __llvm_core "llvm.bitreverse.i64";
fmuladd :: proc(a, b, c: f32) -> f32 #foreign __llvm_core "llvm.fmuladd.f32";
fmuladd :: proc(a, b, c: f64) -> f64 #foreign __llvm_core "llvm.fmuladd.f64";
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); }
copy_sign :: proc(x, y: f32) -> f32 {
ix := transmute(u32, x);
iy := transmute(u32, y);
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);
}
copy_sign :: proc(x, y: f64) -> f64 {
ix := transmute(u64, x);
iy := transmute(u64, y);
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);
}
round :: proc(x: f32) -> f32 { return x >= 0 ? floor(x + 0.5) : ceil(x - 0.5); }
round :: proc(x: f64) -> f64 { return x >= 0 ? floor(x + 0.5) : ceil(x - 0.5); }
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); }
floor :: proc(x: f32) -> f32 { return x >= 0 ? f32(i64(x)) : f32(i64(x-0.5)); } // TODO: Get accurate versions
floor :: proc(x: f64) -> f64 { return x >= 0 ? f64(i64(x)) : f64(i64(x-0.5)); } // TODO: Get accurate versions
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
ceil :: proc(x: f32) -> f32 { return x < 0 ? f32(i64(x)) : f32(i64(x+1)); } // TODO: Get accurate versions
ceil :: proc(x: f64) -> f64 { return x < 0 ? f64(i64(x)) : f64(i64(x+1)); } // 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
remainder :: proc(x, y: f32) -> f32 { return x - round(x/y) * y; }
remainder :: proc(x, y: f64) -> f64 { return x - round(x/y) * y; }
proc remainder(x, y: f32) -> f32 { return x - round(x/y) * y; }
proc remainder(x, y: f64) -> f64 { return x - round(x/y) * y; }
mod :: proc(x, y: f32) -> f32 {
proc mod(x, y: f32) -> f32 {
var result: f32;
y = abs(y);
result := remainder(abs(x), y);
result = remainder(abs(x), y);
if sign(result) < 0 {
result += y;
}
return copy_sign(result, x);
}
mod :: proc(x, y: f64) -> f64 {
proc mod(x, y: f64) -> f64 {
var result: f64;
y = abs(y);
result := remainder(abs(x), y);
result = remainder(abs(x), y);
if sign(result) < 0 {
result += y;
}
@@ -104,48 +110,48 @@ mod :: proc(x, y: f64) -> f64 {
}
to_radians :: proc(degrees: f32) -> f32 { return degrees * TAU / 360; }
to_degrees :: proc(radians: f32) -> f32 { return radians * 360 / TAU; }
proc to_radians(degrees: f32) -> f32 { return degrees * TAU / 360; }
proc to_degrees(radians: f32) -> f32 { return radians * 360 / TAU; }
dot :: proc(a, b: Vec2) -> f32 { c := a*b; return c.x + c.y; }
dot :: proc(a, b: Vec3) -> f32 { c := a*b; return c.x + c.y + c.z; }
dot :: proc(a, b: Vec4) -> f32 { c := a*b; return c.x + c.y + c.z + c.w; }
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; }
cross :: proc(x, y: Vec3) -> Vec3 {
a := swizzle(x, 1, 2, 0) * swizzle(y, 2, 0, 1);
b := swizzle(x, 2, 0, 1) * swizzle(y, 1, 2, 0);
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;
}
mag :: proc(v: Vec2) -> f32 { return sqrt(dot(v, v)); }
mag :: proc(v: Vec3) -> f32 { return sqrt(dot(v, v)); }
mag :: proc(v: Vec4) -> f32 { return sqrt(dot(v, v)); }
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)); }
norm :: proc(v: Vec2) -> Vec2 { return v / mag(v); }
norm :: proc(v: Vec3) -> Vec3 { return v / mag(v); }
norm :: proc(v: Vec4) -> Vec4 { return v / mag(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); }
norm0 :: proc(v: Vec2) -> Vec2 {
m := mag(v);
proc norm0(v: Vec2) -> Vec2 {
var m = mag(v);
if m == 0 {
return 0;
}
return v / m;
}
norm0 :: proc(v: Vec3) -> Vec3 {
m := mag(v);
proc norm0(v: Vec3) -> Vec3 {
var m = mag(v);
if m == 0 {
return 0;
}
return v / m;
}
norm0 :: proc(v: Vec4) -> Vec4 {
m := mag(v);
proc norm0(v: Vec4) -> Vec4 {
var m = mag(v);
if m == 0 {
return 0;
}
@@ -154,7 +160,7 @@ norm0 :: proc(v: Vec4) -> Vec4 {
mat4_identity :: proc() -> Mat4 {
proc mat4_identity() -> Mat4 {
return Mat4{
{1, 0, 0, 0},
{0, 1, 0, 0},
@@ -163,7 +169,7 @@ mat4_identity :: proc() -> Mat4 {
};
}
mat4_transpose :: proc(m: Mat4) -> Mat4 {
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];
@@ -172,8 +178,8 @@ mat4_transpose :: proc(m: Mat4) -> Mat4 {
return m;
}
mul :: proc(a, b: Mat4) -> Mat4 {
c: Mat4;
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] +
@@ -185,7 +191,7 @@ mul :: proc(a, b: Mat4) -> Mat4 {
return c;
}
mul :: proc(m: Mat4, v: Vec4) -> Vec4 {
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,
@@ -194,28 +200,30 @@ mul :: proc(m: Mat4, v: Vec4) -> Vec4 {
};
}
inverse :: proc(m: Mat4) -> Mat4 {
o: Mat4;
proc inverse(m: Mat4) -> Mat4 {
var 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];
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);
@@ -237,7 +245,7 @@ inverse :: proc(m: Mat4) -> Mat4 {
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] +
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]);
@@ -263,8 +271,8 @@ inverse :: proc(m: Mat4) -> Mat4 {
}
mat4_translate :: proc(v: Vec3) -> Mat4 {
m := mat4_identity();
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;
@@ -272,14 +280,16 @@ mat4_translate :: proc(v: Vec3) -> Mat4 {
return m;
}
mat4_rotate :: proc(v: Vec3, angle_radians: f32) -> Mat4 {
c := cos(angle_radians);
s := sin(angle_radians);
proc mat4_rotate(v: Vec3, angle_radians: f32) -> Mat4 {
var (
c = cos(angle_radians);
s = sin(angle_radians);
a := norm(v);
t := a * Vec3{1-c};
a = norm(v);
t = a * (1-c);
rot := mat4_identity();
rot = mat4_identity();
)
rot[0][0] = c + t.x*a.x;
rot[0][1] = 0 + t.x*a.y + s*a.z;
@@ -299,14 +309,14 @@ mat4_rotate :: proc(v: Vec3, angle_radians: f32) -> Mat4 {
return rot;
}
scale :: proc(m: Mat4, v: Vec3) -> Mat4 {
proc scale(m: Mat4, v: Vec3) -> Mat4 {
m[0][0] *= v.x;
m[1][1] *= v.y;
m[2][2] *= v.z;
return m;
}
scale :: proc(m: Mat4, s: f32) -> Mat4 {
proc scale(m: Mat4, s: f32) -> Mat4 {
m[0][0] *= s;
m[1][1] *= s;
m[2][2] *= s;
@@ -314,23 +324,26 @@ scale :: proc(m: Mat4, s: f32) -> Mat4 {
}
look_at :: proc(eye, centre, up: Vec3) -> Mat4 {
f := norm(centre - eye);
s := norm(cross(f, up));
u := cross(s, f);
proc look_at(eye, centre, up: Vec3) -> Mat4 {
var (
f = norm(centre - eye);
s = norm(cross(f, up));
u = cross(s, f);
)
m: Mat4;
m[0] = [4]f32{+s.x, +s.y, +s.z, 0};
m[1] = [4]f32{+u.x, +u.y, +u.z, 0};
m[2] = [4]f32{-f.x, -f.y, -f.z, 0};
m[3] = [4]f32{dot(s, eye), dot(u, eye), dot(f, eye), 1};
return m;
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);
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);
@@ -340,8 +353,8 @@ perspective :: proc(fovy, aspect, near, far: f32) -> Mat4 {
}
ortho3d :: proc(left, right, bottom, top, near, far: f32) -> Mat4 {
m := mat4_identity();
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);
@@ -354,29 +367,30 @@ ortho3d :: proc(left, right, bottom, top, near, far: f32) -> Mat4 {
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;
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
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
)
+86 -83
View File
@@ -1,47 +1,49 @@
#import "fmt.odin";
#import "os.odin";
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";
}
swap :: proc(b: u16) -> u16 #foreign __llvm_core "llvm.bswap.i16";
swap :: proc(b: u32) -> u32 #foreign __llvm_core "llvm.bswap.i32";
swap :: proc(b: u64) -> u64 #foreign __llvm_core "llvm.bswap.i64";
set :: proc(data: rawptr, value: i32, len: int) -> rawptr {
proc set(data: rawptr, value: i32, len: int) -> rawptr {
return __mem_set(data, value, len);
}
zero :: proc(data: rawptr, len: int) -> rawptr {
proc zero(data: rawptr, len: int) -> rawptr {
return __mem_zero(data, len);
}
copy :: proc(dst, src: rawptr, len: int) -> rawptr {
proc copy(dst, src: rawptr, len: int) -> rawptr {
return __mem_copy(dst, src, len);
}
copy_non_overlapping :: proc(dst, src: rawptr, len: int) -> rawptr {
proc copy_non_overlapping(dst, src: rawptr, len: int) -> rawptr {
return __mem_copy_non_overlapping(dst, src, len);
}
compare :: proc(a, b: []byte) -> int {
proc compare(a, b: []u8) -> int {
return __mem_compare(&a[0], &b[0], min(len(a), len(b)));
}
kilobytes :: proc(x: int) -> int #inline { return (x) * 1024; }
megabytes :: proc(x: int) -> int #inline { return kilobytes(x) * 1024; }
gigabytes :: proc(x: int) -> int #inline { return megabytes(x) * 1024; }
terabytes :: proc(x: int) -> int #inline { return gigabytes(x) * 1024; }
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; }
is_power_of_two :: proc(x: int) -> bool {
proc is_power_of_two(x: int) -> bool {
if x <= 0 {
return false;
}
return (x & (x-1)) == 0;
}
align_forward :: proc(ptr: rawptr, align: int) -> rawptr {
proc align_forward(ptr: rawptr, align: int) -> rawptr {
assert(is_power_of_two(align));
a := uint(align);
p := uint(ptr);
modulo := p & (a-1);
var a = uint(align);
var p = uint(ptr);
var modulo = p & (a-1);
if modulo != 0 {
p += a - modulo;
}
@@ -50,27 +52,27 @@ align_forward :: proc(ptr: rawptr, align: int) -> rawptr {
Allocation_Header :: struct {
type AllocationHeader struct {
size: int,
}
allocation_header_fill :: proc(header: ^Allocation_Header, data: rawptr, size: int) {
proc allocation_header_fill(header: ^AllocationHeader, data: rawptr, size: int) {
header.size = size;
ptr := ^int(header+1);
var ptr = ^int(header+1);
for i := 0; rawptr(ptr) < data; i++ {
for var i = 0; rawptr(ptr) < data; i++ {
(ptr+i)^ = -1;
}
}
allocation_header :: proc(data: rawptr) -> ^Allocation_Header {
proc allocation_header(data: rawptr) -> ^AllocationHeader {
if data == nil {
return nil;
}
p := ^int(data);
var p = ^int(data);
for (p-1)^ == -1 {
p = (p-1);
}
return ^Allocation_Header(p-1);
return ^AllocationHeader(p-1);
}
@@ -78,35 +80,36 @@ allocation_header :: proc(data: rawptr) -> ^Allocation_Header {
// Custom allocators
Arena :: struct {
backing: Allocator,
offset: int,
memory: []byte,
temp_count: int,
}
type (
Arena struct {
backing: Allocator,
offset: int,
memory: []u8,
temp_count: int,
}
Arena_Temp_Memory :: struct {
arena: ^Arena,
original_count: int,
}
ArenaTempMemory struct {
arena: ^Arena,
original_count: int,
}
)
init_arena_from_memory :: proc(using a: ^Arena, data: []byte) {
proc init_arena_from_memory(using a: ^Arena, data: []u8) {
backing = Allocator{};
memory = data[0..<0];
temp_count = 0;
}
init_arena_from_context :: proc(using a: ^Arena, size: int) {
proc init_arena_from_context(using a: ^Arena, size: int) {
backing = context.allocator;
memory = make([]byte, size);
memory = make([]u8, size);
temp_count = 0;
}
free_arena :: proc(using a: ^Arena) {
proc free_arena(using a: ^Arena) {
if backing.procedure != nil {
push_allocator backing {
free(memory);
@@ -116,57 +119,57 @@ free_arena :: proc(using a: ^Arena) {
}
}
arena_allocator :: proc(arena: ^Arena) -> Allocator {
proc arena_allocator(arena: ^Arena) -> Allocator {
return Allocator{
procedure = arena_allocator_proc,
data = arena,
};
}
arena_allocator_proc :: proc(allocator_data: rawptr, mode: Allocator_Mode,
proc arena_allocator_proc(allocator_data: rawptr, mode: AllocatorMode,
size, alignment: int,
old_memory: rawptr, old_size: int, flags: u64) -> rawptr {
using Allocator_Mode;
arena := ^Arena(allocator_data);
using AllocatorMode;
var arena = ^Arena(allocator_data);
match mode {
case ALLOC:
total_size := size + alignment;
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 end := &arena.memory[arena.offset];
#no_bounds_check var end = &arena.memory[arena.offset];
ptr := align_forward(end, alignment);
var ptr = align_forward(end, alignment);
arena.offset += total_size;
return zero(ptr, size);
case FREE:
case Free:
// NOTE(bill): Free all at once
// Use Arena_Temp_Memory if you want to free a block
// Use ArenaTempMemory if you want to free a block
case FREE_ALL:
case FreeAll:
arena.offset = 0;
case RESIZE:
case Resize:
return default_resize_align(old_memory, old_size, size, alignment);
}
return nil;
}
begin_arena_temp_memory :: proc(a: ^Arena) -> Arena_Temp_Memory {
tmp: Arena_Temp_Memory;
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;
}
end_arena_temp_memory :: proc(using tmp: Arena_Temp_Memory) {
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];
@@ -179,8 +182,8 @@ end_arena_temp_memory :: proc(using tmp: Arena_Temp_Memory) {
align_of_type_info :: proc(type_info: ^Type_Info) -> int {
prev_pow2 :: proc(n: i64) -> i64 {
proc align_of_type_info(type_info: ^TypeInfo) -> int {
proc prev_pow2(n: i64) -> i64 {
if n <= 0 {
return 0;
}
@@ -193,9 +196,9 @@ align_of_type_info :: proc(type_info: ^Type_Info) -> int {
return n - (n >> 1);
}
WORD_SIZE :: size_of(int);
MAX_ALIGN :: size_of([vector 64]f64); // TODO(bill): Should these constants be builtin constants?
using Type_Info;
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);
@@ -215,14 +218,14 @@ align_of_type_info :: proc(type_info: ^Type_Info) -> int {
return WORD_SIZE;
case Array:
return align_of_type_info(info.elem);
case Dynamic_Array:
case DynamicArray:
return WORD_SIZE;
case Slice:
return WORD_SIZE;
case Vector:
size := size_of_type_info(info.elem);
count := int(max(prev_pow2(i64(info.count)), 1));
total := size * count;
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;
@@ -230,7 +233,7 @@ align_of_type_info :: proc(type_info: ^Type_Info) -> int {
return info.align;
case Union:
return info.align;
case Raw_Union:
case RawUnion:
return info.align;
case Enum:
return align_of_type_info(info.base);
@@ -241,14 +244,14 @@ align_of_type_info :: proc(type_info: ^Type_Info) -> int {
return 0;
}
align_formula :: proc(size, align: int) -> int {
result := size + align-1;
proc align_formula(size, align: int) -> int {
var result = size + align-1;
return result - result%align;
}
size_of_type_info :: proc(type_info: ^Type_Info) -> int {
WORD_SIZE :: size_of(int);
using Type_Info;
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);
@@ -267,32 +270,32 @@ size_of_type_info :: proc(type_info: ^Type_Info) -> int {
case Procedure:
return WORD_SIZE;
case Array:
count := info.count;
var count = info.count;
if count == 0 {
return 0;
}
size := size_of_type_info(info.elem);
align := align_of_type_info(info.elem);
alignment := align_formula(size, align);
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 Dynamic_Array:
case DynamicArray:
return size_of(rawptr) + 2*size_of(int) + size_of(Allocator);
case Slice:
return 2*WORD_SIZE;
case Vector:
count := info.count;
var count = info.count;
if count == 0 {
return 0;
}
size := size_of_type_info(info.elem);
align := align_of_type_info(info.elem);
alignment := align_formula(size, align);
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 Raw_Union:
case RawUnion:
return info.size;
case Enum:
return size_of_type_info(info.base);
+97 -87
View File
@@ -1,116 +1,125 @@
#foreign_system_library lib "opengl32.lib" when ODIN_OS == "windows";
#foreign_system_library lib "gl" when ODIN_OS == "linux";
#import win32 "sys/windows.odin" when ODIN_OS == "windows";
#import "sys/wgl.odin" when ODIN_OS == "windows";
#load "opengl_constants.odin";
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";
Clear :: proc(mask: u32) #foreign lib "glClear";
ClearColor :: proc(r, g, b, a: f32) #foreign lib "glClearColor";
Begin :: proc(mode: i32) #foreign lib "glBegin";
End :: proc() #foreign lib "glEnd";
Finish :: proc() #foreign lib "glFinish";
BlendFunc :: proc(sfactor, dfactor: i32) #foreign lib "glBlendFunc";
Enable :: proc(cap: i32) #foreign lib "glEnable";
Disable :: proc(cap: i32) #foreign lib "glDisable";
GenTextures :: proc(count: i32, result: ^u32) #foreign lib "glGenTextures";
DeleteTextures:: proc(count: i32, result: ^u32) #foreign lib "glDeleteTextures";
TexParameteri :: proc(target, pname, param: i32) #foreign lib "glTexParameteri";
TexParameterf :: proc(target: i32, pname: i32, param: f32) #foreign lib "glTexParameterf";
BindTexture :: proc(target: i32, texture: u32) #foreign lib "glBindTexture";
LoadIdentity :: proc() #foreign lib "glLoadIdentity";
Viewport :: proc(x, y, width, height: i32) #foreign lib "glViewport";
Ortho :: proc(left, right, bottom, top, near, far: f64) #foreign lib "glOrtho";
Color3f :: proc(r, g, b: f32) #foreign lib "glColor3f";
Vertex3f :: proc(x, y, z: f32) #foreign lib "glVertex3f";
GetError :: proc() -> i32 #foreign lib "glGetError";
GetString :: proc(name: i32) -> ^byte #foreign lib "glGetString";
GetIntegerv :: proc(name: i32, v: ^i32) #foreign lib "glGetIntegerv";
TexCoord2f :: proc(x, y: f32) #foreign lib "glTexCoord2f";
TexImage2D :: proc(target, level, internal_format,
width, height, border,
format, type: i32, pixels: rawptr) #foreign lib "glTexImage2D";
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";
}
_string_data :: proc(s: string) -> ^u8 #inline { return &s[0]; }
proc _string_data(s: string) -> ^u8 #inline { return &s[0]; }
_libgl := win32.LoadLibraryA(_string_data("opengl32.dll\x00"));
var _libgl = win32.load_library_a(_string_data("opengl32.dll\x00"));
GetProcAddress :: proc(name: string) -> proc() #cc_c {
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);
res := wgl.GetProcAddress(&name[0]);
var res = wgl.get_proc_address(&name[0]);
if res == nil {
res = win32.GetProcAddress(_libgl, &name[0]);
res = win32.get_proc_address(_libgl, &name[0]);
}
return res;
return rawptr(res);
}
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;
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;
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;
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;
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;
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: ^^byte, 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;
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: ^byte) #cc_c;
GetProgramInfoLog: proc(program: u32, max_length: u32, length: ^u32, info_long: ^byte) #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;
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;
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;
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: ^byte) -> i32 #cc_c;
GetUniformLocation: proc(program: u32, name: ^u8) -> i32 #cc_c;
)
init :: proc() {
set_proc_address :: proc(p: rawptr, name: string) #inline {
x := ^(proc() #cc_c)(p);
x^ = GetProcAddress(name);
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");
@@ -120,6 +129,7 @@ init :: proc() {
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");
+1367 -1367
View File
File diff suppressed because it is too large Load Diff
+49 -3
View File
@@ -1,3 +1,49 @@
#load "os_windows.odin" when ODIN_OS == "windows";
#load "os_x.odin" when ODIN_OS == "osx";
#load "os_linux.odin" when ODIN_OS == "linux";
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;
}
+157 -179
View File
@@ -1,42 +1,51 @@
#import "fmt.odin";
#import "strings.odin";
foreign_system_library (
dl "dl";
libc "c";
)
import "strings.odin";
Handle :: i32;
File_Time :: u64;
Errno :: i32;
type (
Handle i32;
FileTime u64;
Errno i32;
)
// 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;
)
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;
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;
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
immutable args := _alloc_command_line_arguments();
var args = _alloc_command_line_arguments();
_File_Time :: struct #ordered {
type _FileTime struct #ordered {
seconds: i64,
nanoseconds: i32,
reserved: i32,
@@ -46,7 +55,7 @@ _File_Time :: struct #ordered {
// 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 #ordered {
type Stat struct #ordered {
device_id: u64, // ID of device containing file
serial: u64, // File serial number
nlink: u32, // Number of hard links
@@ -59,9 +68,9 @@ Stat :: struct #ordered {
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
last_access: _FileTime, // Time of last access
modified: _FileTime, // Time of last modification
status_change: _FileTime, // Time of last status change
_reserve1,
_reserve2,
@@ -71,84 +80,84 @@ Stat :: struct #ordered {
};
// 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
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
// File mode
// Read, write, execute/search by 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
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 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
// Read, write, execute/search by group
S_ISUID = 0004000; // Set user id on execution
S_ISGID = 0002000; // Set group id on execution
S_ISVTX = 0001000; // Directory restrcted delete
)
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
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;}
// Read, write, execute/search by others
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
)
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
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";
S_ISUID :: 0004000; // Set user id on execution
S_ISGID :: 0002000; // Set group id on execution
S_ISVTX :: 0001000; // Directory restrcted delete
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";
S_ISLNK :: proc(m: u32) -> bool #inline {return ((m) & S_IFMT) == S_IFLNK; }
S_ISREG :: proc(m: u32) -> bool #inline {return ((m) & S_IFMT) == S_IFREG; }
S_ISDIR :: proc(m: u32) -> bool #inline {return ((m) & S_IFMT) == S_IFDIR; }
S_ISCHR :: proc(m: u32) -> bool #inline {return ((m) & S_IFMT) == S_IFCHR; }
S_ISBLK :: proc(m: u32) -> bool #inline {return ((m) & S_IFMT) == S_IFBLK; }
S_ISFIFO :: proc(m: u32) -> bool #inline {return ((m) & S_IFMT) == S_IFIFO; }
S_ISSOCK :: proc(m: u32) -> bool #inline {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_system_library dl "dl";
#foreign_system_library libc "c";
_unix_open :: proc(path: ^u8, mode: int) -> Handle #foreign libc "open";
_unix_close :: proc(fd: Handle) -> i32 #foreign libc "close";
_unix_read :: proc(fd: Handle, buf: rawptr, size: int) -> int #foreign libc "read";
_unix_write :: proc(fd: Handle, buf: rawptr, size: int) -> int #foreign libc "write";
_unix_seek :: proc(fd: Handle, offset: i64, whence: i32) -> i64 #foreign libc "lseek64";
_unix_gettid :: proc() -> u64 #foreign libc "gettid";
_unix_stat :: proc(path: ^u8, stat: ^Stat) -> i32 #foreign libc "stat";
_unix_access :: proc(path: ^u8, mask: int) -> i32 #foreign libc "access";
_unix_malloc :: proc(size: int) -> rawptr #foreign libc "malloc";
_unix_free :: proc(ptr: rawptr) #foreign libc "free";
_unix_realloc :: proc(ptr: rawptr, size: int) -> rawptr #foreign libc "realloc";
_unix_getenv :: proc(^u8) -> ^u8 #foreign libc "getenv";
_unix_exit :: proc(status: int) #foreign libc "exit";
_unix_dlopen :: proc(filename: ^u8, flags: int) -> rawptr #foreign dl "dlopen";
_unix_dlsym :: proc(handle: rawptr, symbol: ^u8) -> (proc() #cc_c) #foreign dl "dlsym";
_unix_dlclose :: proc(handle: rawptr) -> int #foreign dl "dlclose";
_unix_dlerror :: proc() -> ^u8 #foreign dl "dlerror";
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.
open_simple :: proc(path: string, mode: int) -> (Handle, Errno) {
proc open_simple(path: string, mode: int) -> (Handle, Errno) {
cstr := strings.new_c_string(path);
handle := _unix_open(cstr, mode);
var cstr = strings.new_c_string(path);
var handle = _unix_open(cstr, mode);
free(cstr);
if(handle == -1) {
return 0, 1;
@@ -156,109 +165,78 @@ open_simple :: proc(path: string, mode: int) -> (Handle, Errno) {
return handle, 0;
}
// NOTE(zangent): This is here for compatability reasons. Should this be here?
open :: proc(path: string, mode: int, perm: u32) -> (Handle, Errno) {
proc open(path: string, mode: int = O_RDONLY, perm: u32 = 0) -> (Handle, Errno) {
return open_simple(path, mode);
}
close :: proc(fd: Handle) {
proc close(fd: Handle) {
_unix_close(fd);
}
read :: proc(fd: Handle, data: []byte) -> (int, Errno) {
sz := _unix_read(fd, &data[0], len(data));
proc read(fd: Handle, data: []u8) -> (int, Errno) {
var 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));
proc write(fd: Handle, data: []u8) -> (int, Errno) {
var 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));
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
stdin: Handle = 0;
stdout: Handle = 1;
stderr: Handle = 2;
var (
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 {}
proc last_write_time(fd: Handle) -> FileTime {}
proc last_write_time_by_name(name: string) -> FileTime {}
*/
stat :: proc(path: string) -> (Stat, int) #inline {
s: Stat;
cstr := strings.new_c_string(path);
proc stat(path: string) -> (Stat, int) #inline {
var s: Stat;
var cstr = strings.new_c_string(path);
defer free(cstr);
ret_int := _unix_stat(cstr, &s);
var ret_int = _unix_stat(cstr, &s);
return s, int(ret_int);
}
access :: proc(path: string, mask: int) -> bool #inline {
cstr := strings.new_c_string(path);
proc access(path: string, mask: int) -> bool #inline {
var cstr = strings.new_c_string(path);
defer free(cstr);
return _unix_access(cstr, mask) == 0;
}
read_entire_file :: proc(name: string) -> ([]byte, bool) {
fd: Handle;
err: Errno;
size: i64;
fd, err = open_simple(name, O_RDONLY);
if(err != 0) {
fmt.println("Failed to open file.");
return nil, false;
}
defer close(fd);
// We have a file
size, err = seek(fd, 0, SEEK_END);
if(err != 0) {
fmt.println("Failed to seek to end of file.");
return nil, false;
}
_, err = seek(fd, 0, SEEK_SET);
if(err != 0) {
fmt.println("Failed to seek to beginning of file.");
return nil, false;
}
// We have a file size!
data := make([]u8, size+1);
if data == nil {
fmt.println("Failed to allocate file buffer.");
return nil, false;
}
read(fd, data);
data[size] = 0;
return data, true;
}
heap_alloc :: proc(size: int) -> rawptr {
proc heap_alloc(size: int) -> rawptr {
assert(size > 0);
return _unix_malloc(size);
}
heap_resize :: proc(ptr: rawptr, new_size: int) -> rawptr {
proc heap_resize(ptr: rawptr, new_size: int) -> rawptr {
return _unix_realloc(ptr, new_size);
}
heap_free :: proc(ptr: rawptr) {
proc heap_free(ptr: rawptr) {
_unix_free(ptr);
}
getenv :: proc(name: string) -> (string, bool) {
path_str := strings.new_c_string(name);
cstr: ^u8 = _unix_getenv(path_str);
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;
@@ -266,38 +244,38 @@ getenv :: proc(name: string) -> (string, bool) {
return strings.to_odin_string(cstr), true;
}
exit :: proc(code: int) {
proc exit(code: int) {
_unix_exit(code);
}
current_thread_id :: proc() -> int {
proc current_thread_id() -> int {
// return int(_unix_gettid());
return 0;
}
dlopen :: proc(filename: string, flags: int) -> rawptr #inline {
cstr := strings.new_c_string(filename);
handle := _unix_dlopen(cstr, flags);
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;
}
dlsym :: proc(handle: rawptr, symbol: string) -> (proc() #cc_c) #inline {
proc dlsym(handle: rawptr, symbol: string) -> (proc() #cc_c) #inline {
assert(handle != nil);
cstr := strings.new_c_string(symbol);
proc_handle := _unix_dlsym(handle, cstr);
var cstr = strings.new_c_string(symbol);
var proc_handle = _unix_dlsym(handle, cstr);
free(cstr);
return proc_handle;
}
dlclose :: proc(handle: rawptr) -> bool #inline {
proc dlclose(handle: rawptr) -> bool #inline {
assert(handle != nil);
return _unix_dlclose(handle) == 0;
}
dlerror :: proc() -> string {
proc dlerror() -> string {
return strings.to_odin_string(_unix_dlerror());
}
_alloc_command_line_arguments :: proc() -> []string {
proc _alloc_command_line_arguments() -> []string {
// TODO(bill):
return nil;
}
+175 -183
View File
@@ -1,64 +1,68 @@
#import win32 "sys/windows.odin";
#import fmt "fmt.odin";
import win32 "sys/windows.odin";
Handle :: int;
File_Time :: u64;
Errno :: int;
type (
Handle int;
FileTime u64;
)
INVALID_HANDLE: Handle : -1;
const INVALID_HANDLE: Handle = -1;
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 (
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;
)
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;
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
immutable args := _alloc_command_line_arguments();
var args = _alloc_command_line_arguments();
open :: proc(path: string, mode: int, perm: u32) -> (Handle, Errno) {
proc open(path: string, mode: int = O_RDONLY, perm: u32 = 0) -> (Handle, Errno) {
if len(path) == 0 {
return INVALID_HANDLE, ERROR_FILE_NOT_FOUND;
}
access: u32;
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;
@@ -73,14 +77,14 @@ open :: proc(path: string, mode: int, perm: u32) -> (Handle, Errno) {
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 = 1};
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;
}
create_mode: u32;
var create_mode: u32;
match {
case mode&(O_CREAT|O_EXCL) == (O_CREAT | O_EXCL):
create_mode = win32.CREATE_NEW;
@@ -90,85 +94,123 @@ open :: proc(path: string, mode: int, perm: u32) -> (Handle, Errno) {
create_mode = win32.OPEN_ALWAYS;
case mode&O_TRUNC == O_TRUNC:
create_mode = win32.TRUNCATE_EXISTING;
default:
case:
create_mode = win32.OPEN_EXISTING;
}
buf: [300]byte;
copy(buf[..], []byte(path));
var buf: [300]u8;
copy(buf[..], []u8(path));
handle := Handle(win32.CreateFileA(&buf[0], access, share_mode, sa, create_mode, win32.FILE_ATTRIBUTE_NORMAL, nil));
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;
}
err := win32.GetLastError();
var err = win32.get_last_error();
return INVALID_HANDLE, Errno(err);
}
close :: proc(fd: Handle) {
win32.CloseHandle(win32.Handle(fd));
proc close(fd: Handle) {
win32.close_handle(win32.Handle(fd));
}
write_string :: proc(fd: Handle, str: string) -> (int, Errno) {
return write(fd, []byte(str));
}
write :: proc(fd: Handle, data: []byte) -> (int, Errno) {
proc write(fd: Handle, data: []u8) -> (int, Errno) {
if len(data) == 0 {
return 0, ERROR_NONE;
}
bytes_written: i32;
e := win32.WriteFile(win32.Handle(fd), &data[0], i32(len(data)), &bytes_written, nil);
if e == win32.FALSE {
err := win32.GetLastError();
return 0, Errno(err);
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(bytes_written), ERROR_NONE;
return int(total_write), ERROR_NONE;
}
read :: proc(fd: Handle, data: []byte) -> (int, Errno) {
proc read(fd: Handle, data: []u8) -> (int, Errno) {
if len(data) == 0 {
return 0, ERROR_NONE;
}
bytes_read: i32;
e := win32.ReadFile(win32.Handle(fd), &data[0], u32(len(data)), &bytes_read, nil);
if e == win32.FALSE {
err := win32.GetLastError();
return 0, Errno(err);
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(bytes_read), ERROR_NONE;
return int(total_read), ERROR_NONE;
}
seek :: proc(fd: Handle, offset: i64, whence: int) -> (i64, Errno) {
w: u32;
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;
}
hi := i32(offset>>32);
lo := i32(offset);
ft := win32.GetFileType(win32.Handle(fd));
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;
}
dw_ptr := win32.SetFilePointer(win32.Handle(fd), lo, &hi, w);
var dw_ptr = win32.set_file_pointer(win32.Handle(fd), lo, &hi, w);
if dw_ptr == win32.INVALID_SET_FILE_POINTER {
err := win32.GetLastError();
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
stdin := get_std_handle(win32.STD_INPUT_HANDLE);
stdout := get_std_handle(win32.STD_OUTPUT_HANDLE);
stderr := get_std_handle(win32.STD_ERROR_HANDLE);
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);
get_std_handle :: proc(h: int) -> Handle {
fd := win32.GetStdHandle(i32(h));
win32.SetHandleInformation(fd, win32.HANDLE_FLAG_INHERIT, 0);
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);
}
@@ -177,88 +219,38 @@ get_std_handle :: proc(h: int) -> Handle {
last_write_time :: proc(fd: Handle) -> File_Time {
file_info: win32.By_Handle_File_Information;
win32.GetFileInformationByHandle(win32.Handle(fd), &file_info);
lo := File_Time(file_info.last_write_time.lo);
hi := File_Time(file_info.last_write_time.hi);
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;
}
last_write_time_by_name :: proc(name: string) -> File_Time {
last_write_time: win32.Filetime;
data: win32.File_Attribute_Data;
buf: [1024]byte;
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[..], []byte(name));
copy(buf[..], []u8(name));
if win32.GetFileAttributesExA(&buf[0], win32.GetFileExInfoStandard, &data) != 0 {
if win32.get_file_attributes_ex_a(&buf[0], win32.GetFileExInfoStandard, &data) != 0 {
last_write_time = data.last_write_time;
}
l := File_Time(last_write_time.lo);
h := File_Time(last_write_time.hi);
var l = FileTime(last_write_time.lo);
var h = FileTime(last_write_time.hi);
return l | h << 32;
}
read_entire_file :: proc(name: string) -> ([]byte, bool) {
buf: [300]byte;
copy(buf[..], []byte(name));
fd, err := open(name, O_RDONLY, 0);
if err != ERROR_NONE {
return nil, false;
}
defer close(fd);
length: i64;
if ok := win32.GetFileSizeEx(win32.Handle(fd), &length) != 0; !ok {
return nil, false;
}
if length == 0 {
return nil, true;
}
data := make([]byte, length);
if data == nil {
return nil, false;
}
single_read_length: i32;
total_read: i64;
for total_read < length {
remaining := length - total_read;
to_read: u32;
MAX :: 1<<32-1;
if remaining <= MAX {
to_read = u32(remaining);
} else {
to_read = MAX;
}
win32.ReadFile(win32.Handle(fd), &data[total_read], to_read, &single_read_length, nil);
if single_read_length <= 0 {
free(data);
return nil, false;
}
total_read += i64(single_read_length);
}
return data, true;
proc heap_alloc(size: int) -> rawptr {
return win32.heap_alloc(win32.get_process_heap(), win32.HEAP_ZERO_MEMORY, size);
}
heap_alloc :: proc(size: int) -> rawptr {
return win32.HeapAlloc(win32.GetProcessHeap(), win32.HEAP_ZERO_MEMORY, size);
}
heap_resize :: proc(ptr: rawptr, new_size: int) -> rawptr {
proc heap_resize(ptr: rawptr, new_size: int) -> rawptr {
if new_size == 0 {
heap_free(ptr);
return nil;
@@ -266,74 +258,74 @@ heap_resize :: proc(ptr: rawptr, new_size: int) -> rawptr {
if ptr == nil {
return heap_alloc(new_size);
}
return win32.HeapReAlloc(win32.GetProcessHeap(), win32.HEAP_ZERO_MEMORY, ptr, new_size);
return win32.heap_realloc(win32.get_process_heap(), win32.HEAP_ZERO_MEMORY, ptr, new_size);
}
heap_free :: proc(ptr: rawptr) {
proc heap_free(ptr: rawptr) {
if ptr == nil {
return;
}
win32.HeapFree(win32.GetProcessHeap(), 0, ptr);
win32.heap_free(win32.get_process_heap(), 0, ptr);
}
exit :: proc(code: int) {
win32.ExitProcess(u32(code));
proc exit(code: int) {
win32.exit_process(u32(code));
}
current_thread_id :: proc() -> int {
return int(win32.GetCurrentThreadId());
proc current_thread_id() -> int {
return int(win32.get_current_thread_id());
}
_alloc_command_line_arguments :: proc() -> []string {
alloc_ucs2_to_utf8 :: proc(wstr: ^u16) -> string {
wstr_len := 0;
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++;
}
len := 2*wstr_len-1;
buf := make([]byte, len+1);
str := slice_ptr(wstr, wstr_len+1);
var len = 2*wstr_len-1;
var buf = make([]u8, len+1);
var str = slice_ptr(wstr, wstr_len+1);
i, j := 0, 0;
var i, j = 0, 0;
for str[j] != 0 {
match {
case str[j] < 0x80:
if i+1 > len {
return "";
}
buf[i] = byte(str[j]); i++;
buf[i] = u8(str[j]); i++;
j++;
case str[j] < 0x800:
if i+2 > len {
return "";
}
buf[i] = byte(0xc0 + (str[j]>>6)); i++;
buf[i] = byte(0x80 + (str[j]&0x3f)); i++;
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 "";
}
c := rune((str[j] - 0xd800) << 10) + rune((str[j+1]) - 0xdc00) + 0x10000;
buf[i] = byte(0xf0 + (c >> 18)); i++;
buf[i] = byte(0x80 + ((c >> 12) & 0x3f)); i++;
buf[i] = byte(0x80 + ((c >> 6) & 0x3f)); i++;
buf[i] = byte(0x80 + ((c ) & 0x3f)); i++;
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 "";
default:
case:
if i+3 > len {
return "";
}
buf[i] = 0xe0 + byte (str[j] >> 12); i++;
buf[i] = 0x80 + byte((str[j] >> 6) & 0x3f); i++;
buf[i] = 0x80 + byte((str[j] ) & 0x3f); i++;
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++;
}
}
@@ -341,9 +333,9 @@ _alloc_command_line_arguments :: proc() -> []string {
return string(buf[0..<i]);
}
arg_count: i32;
arg_list_ptr := win32.CommandLineToArgvW(win32.GetCommandLineW(), &arg_count);
arg_list := make([]string, arg_count);
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)^);
}
+158 -178
View File
@@ -1,52 +1,61 @@
#import "fmt.odin";
#import "strings.odin";
foreign_system_library (
dl "dl";
libc "c";
)
Handle :: i32;
File_Time :: u64;
Errno :: int;
import "strings.odin";
// TODO(zangent): Find out how to make this work on x64 and x32.
AddressSize :: i64;
type (
Handle i32;
FileTime u64;
Errno int;
// INVALID_HANDLE: Handle : -1;
AddressSize int;
)
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;
SEEK_SET :: 0;
SEEK_CUR :: 1;
SEEK_END :: 2;
SEEK_DATA :: 3;
SEEK_HOLE :: 4;
SEEK_MAX :: SEEK_HOLE;
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;
)
// 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;
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;
)
args: [dynamic]string;
var args: [dynamic]string;
FileTime :: struct #ordered {
type _FileTime struct #ordered {
seconds: i64,
nanoseconds: i64
}
Stat :: struct #ordered {
type Stat struct #ordered {
device_id : i32, // ID of device containing file
mode : u16, // Mode of the file
nlink : u16, // Number of hard links
@@ -71,85 +80,85 @@ Stat :: struct #ordered {
};
// 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
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
// File mode
// Read, write, execute/search by 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
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 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
// Read, write, execute/search by group
S_ISUID = 0004000; // Set user id on execution
S_ISGID = 0002000; // Set group id on execution
S_ISVTX = 0001000; // Directory restrcted delete
)
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
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;}
// Read, write, execute/search by others
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
)
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
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";
S_ISUID :: 0004000; // Set user id on execution
S_ISGID :: 0002000; // Set group id on execution
S_ISVTX :: 0001000; // Directory restrcted delete
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";
S_ISLNK :: proc(m: u32) -> bool #inline {return ((m) & S_IFMT) == S_IFLNK; }
S_ISREG :: proc(m: u32) -> bool #inline {return ((m) & S_IFMT) == S_IFREG; }
S_ISDIR :: proc(m: u32) -> bool #inline {return ((m) & S_IFMT) == S_IFDIR; }
S_ISCHR :: proc(m: u32) -> bool #inline {return ((m) & S_IFMT) == S_IFCHR; }
S_ISBLK :: proc(m: u32) -> bool #inline {return ((m) & S_IFMT) == S_IFBLK; }
S_ISFIFO :: proc(m: u32) -> bool #inline {return ((m) & S_IFMT) == S_IFIFO; }
S_ISSOCK :: proc(m: u32) -> bool #inline {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_system_library dl "dl";
#foreign_system_library libc "c";
unix_open :: proc(path: ^u8, mode: int) -> Handle #foreign libc "open";
unix_close :: proc(handle: Handle) #foreign libc "close";
unix_read :: proc(handle: Handle, buffer: rawptr, count: int) -> AddressSize #foreign libc "read";
unix_write :: proc(handle: Handle, buffer: rawptr, count: int) -> AddressSize #foreign libc "write";
unix_lseek :: proc(fs: Handle, offset: AddressSize, whence: int) -> AddressSize #foreign libc "lseek";
unix_gettid :: proc() -> u64 #foreign libc "gettid";
unix_stat :: proc(path: ^u8, stat: ^Stat) -> int #foreign libc "stat";
unix_access :: proc(path: ^u8, mask: int) -> int #foreign libc "access";
unix_malloc :: proc(size: int) -> rawptr #foreign libc "malloc";
unix_free :: proc(ptr: rawptr) #foreign libc "free";
unix_realloc :: proc(ptr: rawptr, size: int) -> rawptr #foreign libc "realloc";
unix_getenv :: proc(^u8) -> ^u8 #foreign libc "getenv";
unix_exit :: proc(status: int) #foreign libc "exit";
unix_dlopen :: proc(filename: ^u8, flags: int) -> rawptr #foreign dl "dlopen";
unix_dlsym :: proc(handle: rawptr, symbol: ^u8) -> (proc() #cc_c) #foreign dl "dlsym";
unix_dlclose :: proc(handle: rawptr) -> int #foreign dl "dlclose";
unix_dlerror :: proc() -> ^u8 #foreign dl "dlerror";
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.
open_simple :: proc(path: string, mode: int) -> (Handle, Errno) {
proc open_simple(path: string, mode: int) -> (Handle, Errno) {
cstr := strings.new_c_string(path);
handle := unix_open(cstr, mode);
var cstr = strings.new_c_string(path);
var handle = unix_open(cstr, mode);
free(cstr);
if(handle == -1) {
return 0, 1;
@@ -158,121 +167,92 @@ open_simple :: proc(path: string, mode: int) -> (Handle, Errno) {
}
// NOTE(zangent): This is here for compatability reasons. Should this be here?
open :: proc(path: string, mode: int, perm: u32) -> (Handle, Errno) {
proc open(path: string, mode: int = O_RDONLY, perm: u32 = 0) -> (Handle, Errno) {
return open_simple(path, mode);
}
close :: proc(fd: Handle) {
proc close(fd: Handle) {
unix_close(fd);
}
write :: proc(fd: Handle, data: []byte) -> (AddressSize, Errno) {
proc write(fd: Handle, data: []u8) -> (AddressSize, Errno) {
assert(fd != -1);
bytes_written := unix_write(fd, &data[0], len(data));
var 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: []byte) -> (AddressSize, Errno) {
proc read(fd: Handle, data: []u8) -> (AddressSize, Errno) {
assert(fd != -1);
bytes_read := unix_read(fd, &data[0], len(data));
var 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: AddressSize, whence: int) -> (AddressSize, Errno) {
proc seek(fd: Handle, offset: AddressSize, whence: int) -> (AddressSize, Errno) {
assert(fd != -1);
final_offset := unix_lseek(fd, offset, whence);
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
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);
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!
last_write_time :: proc(fd: Handle) -> File_Time {}
last_write_time_by_name :: proc(name: string) -> File_Time {}
proc last_write_time(fd: Handle) -> FileTime {}
proc last_write_time_by_name(name: string) -> FileTime {}
*/
stat :: proc(path: string) -> (Stat, bool) #inline {
s: Stat;
cstr := strings.new_c_string(path);
proc stat(path: string) -> (Stat, bool) #inline {
var s: Stat;
var cstr = strings.new_c_string(path);
defer free(cstr);
ret_int := unix_stat(cstr, &s);
var ret_int = unix_stat(cstr, &s);
return s, ret_int==0;
}
access :: proc(path: string, mask: int) -> bool #inline {
cstr := strings.new_c_string(path);
proc access(path: string, mask: int) -> bool #inline {
var cstr = strings.new_c_string(path);
defer free(cstr);
return unix_access(cstr, mask) == 0;
}
read_entire_file :: proc(name: string) -> ([]byte, bool) {
handle, err := open_simple(name, O_RDONLY);
if(err != 0) {
fmt.println("Failed to open file.");
return nil, false;
}
defer(close(handle));
// We have a file!
size: AddressSize;
size, err = seek(handle, 0, SEEK_END);
if(err != 0) {
fmt.println("Failed to seek to end of file.");
return nil, false;
}
_, err = seek(handle, 0, SEEK_SET);
if(err != 0) {
fmt.println("Failed to seek to beginning of file.");
return nil, false;
}
// We have a file size!
data := make([]u8, size+1);
if data == nil {
fmt.println("Failed to allocate file buffer.");
return nil, false;
}
read(handle, data);
data[size] = 0;
return data, true;
}
heap_alloc :: proc(size: int) -> rawptr #inline {
proc heap_alloc(size: int) -> rawptr #inline {
assert(size > 0);
return unix_malloc(size);
}
heap_resize :: proc(ptr: rawptr, new_size: int) -> rawptr #inline {
proc heap_resize(ptr: rawptr, new_size: int) -> rawptr #inline {
return unix_realloc(ptr, new_size);
}
heap_free :: proc(ptr: rawptr) #inline {
proc heap_free(ptr: rawptr) #inline {
unix_free(ptr);
}
getenv :: proc(name: string) -> (string, bool) {
path_str := strings.new_c_string(name);
cstr: ^u8 = unix_getenv(path_str);
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;
@@ -280,33 +260,33 @@ getenv :: proc(name: string) -> (string, bool) {
return strings.to_odin_string(cstr), true;
}
exit :: proc(code: int) #inline {
proc exit(code: int) #inline {
unix_exit(code);
}
current_thread_id :: proc() -> int {
proc current_thread_id() -> int {
// return cast(int) unix_gettid();
return 0;
}
dlopen :: proc(filename: string, flags: int) -> rawptr #inline {
cstr := strings.new_c_string(filename);
handle := unix_dlopen(cstr, flags);
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;
}
dlsym :: proc(handle: rawptr, symbol: string) -> (proc() #cc_c) #inline {
proc dlsym(handle: rawptr, symbol: string) -> (proc() #cc_c) #inline {
assert(handle != nil);
cstr := strings.new_c_string(symbol);
proc_handle := unix_dlsym(handle, cstr);
var cstr = strings.new_c_string(symbol);
var proc_handle = unix_dlsym(handle, cstr);
free(cstr);
return proc_handle;
}
dlclose :: proc(handle: rawptr) -> bool #inline {
proc dlclose(handle: rawptr) -> bool #inline {
assert(handle != nil);
return unix_dlclose(handle) == 0;
}
dlerror :: proc() -> string {
proc dlerror() -> string {
return strings.to_odin_string(unix_dlerror());
}
+25 -23
View File
@@ -1,27 +1,29 @@
Any :: struct #ordered {
data: rawptr,
type_info: ^Type_Info,
}
type (
Any struct #ordered {
data: rawptr,
type_info: ^TypeInfo,
};
String :: struct #ordered {
data: ^byte,
len: int,
};
String struct #ordered {
data: ^u8,
len: int,
};
Slice :: struct #ordered {
data: rawptr,
len: int,
cap: int,
};
Slice struct #ordered {
data: rawptr,
len: int,
cap: int,
};
Dynamic_Array :: struct #ordered {
data: rawptr,
len: int,
cap: int,
allocator: Allocator,
};
DynamicArray struct #ordered {
data: rawptr,
len: int,
cap: int,
allocator: Allocator,
};
Dynamic_Map :: struct #ordered {
hashes: [dynamic]int,
entries: Dynamic_Array,
};
DynamicMap struct #ordered {
hashes: [dynamic]int,
entries: DynamicArray,
};
)
+244 -124
View File
@@ -1,14 +1,13 @@
#import . "decimal.odin";
#import "math.odin";
import . "decimal.odin";
Int_Flag :: enum {
PREFIX = 1<<0,
PLUS = 1<<1,
SPACE = 1<<2,
type IntFlag enum {
Prefix = 1<<0,
Plus = 1<<1,
Space = 1<<2,
}
parse_bool :: proc(s: string) -> (result: bool, ok: bool) {
proc parse_bool(s: string) -> (result: bool, ok: bool) {
match s {
case "1", "t", "T", "true", "TRUE", "True":
return true, true;
@@ -18,9 +17,9 @@ parse_bool :: proc(s: string) -> (result: bool, ok: bool) {
return false, false;
}
_digit_value :: proc(r: rune) -> (int) {
ri := int(r);
v: int = 16;
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;
@@ -29,97 +28,228 @@ _digit_value :: proc(r: rune) -> (int) {
return v;
}
parse_i64 :: proc(s: string, base: int) -> i64 {
result: i64;
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 {
v := _digit_value(r);
if r == '_' {
continue;
}
var v = i128(_digit_value(r));
if v >= base {
break;
}
result *= i64(base);
result += i64(v);
value *= base;
value += v;
}
return result;
return neg ? -value : value;
}
parse_u64 :: proc(s: string, base: int) -> u64 {
result: u64;
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 {
v := _digit_value(r);
if r == '_' {
continue;
}
var v = u128(_digit_value(r));
if v >= base {
break;
}
result *= u64(base);
result += u64(v);
value *= base;
value += u128(v);
}
return result;
}
parse_int :: proc(s: string, base: int) -> int {
return int(parse_i64(s, base));
}
parse_uint :: proc(s: string, base: int) -> uint {
return uint(parse_u64(s, base));
return neg ? -value : value;
}
append_bool :: proc(buf: []byte, b: bool) -> string {
s := b ? "true" : "false";
append(buf, ..[]byte(s));
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);
}
append_uint :: proc(buf: []byte, u: u64, base: int) -> string {
return append_bits(buf, u, base, false, 8*size_of(uint), digits, 0);
proc append_uint(buf: []u8, u: u64, base: int) -> string {
return append_bits(buf, u128(u), base, false, 8*size_of(uint), digits, 0);
}
append_int :: proc(buf: []byte, i: i64, base: int) -> string {
return append_bits(buf, u64(i), base, true, 8*size_of(int), 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);
}
itoa :: proc(buf: []byte, i: int) -> string { return append_int(buf, i64(i), 10); }
proc itoa(buf: []u8, i: int) -> string { return append_int(buf, i64(i), 10); }
append_float :: proc(buf: []byte, f: f64, fmt: byte, prec, bit_size: int) -> string {
proc append_float(buf: []u8, f: f64, fmt: u8, prec, bit_size: int) -> string {
return string(generic_ftoa(buf, f, fmt, prec, bit_size));
}
Decimal_Slice :: struct {
digits: []byte,
type DecimalSlice struct {
digits: []u8,
count: int,
decimal_point: int,
neg: bool,
}
Float_Info :: struct {
type Float_Info struct {
mantbits: uint,
expbits: uint,
bias: int,
}
f32_info := Float_Info{23, 8, -127};
f64_info := Float_Info{52, 11, -1023};
var (
_f16_info = Float_Info{10, 5, -15};
_f32_info = Float_Info{23, 8, -127};
_f64_info = Float_Info{52, 11, -1023};
)
generic_ftoa :: proc(buf: []byte, val: f64, fmt: byte, prec, bit_size: int) -> []byte {
bits: u64;
flt: ^Float_Info;
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;
flt = &_f32_info;
case 64:
bits = transmute(u64, val);
flt = &f64_info;
default:
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);
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:
s: string;
var s: string;
if mant != 0 {
s = "NaN";
} else if neg {
@@ -127,27 +257,27 @@ generic_ftoa :: proc(buf: []byte, val: f64, fmt: byte, prec, bit_size: int) -> [
} else {
s = "+Inf";
}
append(buf, ..[]byte(s));
append(buf, ..[]u8(s));
return buf;
case 0: // denormalized
exp++;
default:
case:
mant |= u64(1) << flt.mantbits;
}
exp += flt.bias;
d_: Decimal;
d := &d_;
var d_: Decimal;
var d = &d_;
assign(d, mant);
shift(d, exp - int(flt.mantbits));
digs: Decimal_Slice;
shortest := prec < 0;
var digs: DecimalSlice;
var shortest = prec < 0;
if shortest {
round_shortest(d, mant, exp, flt);
digs = Decimal_Slice{digits = d.digits[..], count = d.count, decimal_point = d.decimal_point};
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);
@@ -164,21 +294,21 @@ generic_ftoa :: proc(buf: []byte, val: f64, fmt: byte, prec, bit_size: int) -> [
round(d, prec);
}
digs = Decimal_Slice{digits = d.digits[..], count = d.count, decimal_point = d.decimal_point};
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: Decimal_Slice, prec: int, fmt: byte) -> []byte {
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 {
m := min(digs.count, digs.decimal_point);
var m = min(digs.count, digs.decimal_point);
append(buf, ..digs.digits[0..<m]);
for ; m < digs.decimal_point; m++ {
append(buf, '0');
@@ -191,9 +321,9 @@ format_digits :: proc(buf: []byte, shortest: bool, neg: bool, digs: Decimal_Slic
// fractional part
if prec > 0 {
append(buf, '.');
for i in 0..prec {
c: byte = '0';
if j := digs.decimal_point + i; 0 <= j && j < digs.count {
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);
@@ -211,14 +341,14 @@ format_digits :: proc(buf: []byte, shortest: bool, neg: bool, digs: Decimal_Slic
return buf; // TODO
}
c: [2]byte;
var c: [2]u8;
c[0] = '%';
c[1] = fmt;
append(buf, ..c[..]);
return buf;
}
round_shortest :: proc(d: ^Decimal, mant: u64, exp: int, flt: ^Float_Info) {
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;
@@ -230,18 +360,18 @@ round_shortest :: proc(d: ^Decimal, mant: u64, exp: int, flt: ^Float_Info) {
log(2) >~ 0.332
332*(dp-nd) >= 100*(exp-mantbits)
*/
minexp := flt.bias+1;
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;
}
upper_: Decimal; upper: = &upper_;
var upper_: Decimal; var upper = &upper_;
assign(upper, 2*mant - 1);
shift(upper, exp - int(flt.mantbits) - 1);
mantlo: u64;
explo: int;
var mantlo: u64;
var explo: int;
if mant > 1<<flt.mantbits || exp == minexp {
mantlo = mant-1;
explo = exp;
@@ -249,25 +379,25 @@ round_shortest :: proc(d: ^Decimal, mant: u64, exp: int, flt: ^Float_Info) {
mantlo = 2*mant - 1;
explo = exp-1;
}
lower_: Decimal; lower: = &lower_;
var lower_: Decimal; var lower = &lower_;
assign(lower, 2*mantlo + 1);
shift(lower, explo - int(flt.mantbits) - 1);
inclusive := mant%2 == 0;
var inclusive = mant%2 == 0;
for i in 0..<d.count {
l: byte = '0'; // lower digit
var l: u8 = '0'; // lower digit
if i < lower.count {
l = lower.digits[i];
}
m := d.digits[i]; // middle digit
u: byte = '0'; // upper digit
var m = d.digits[i]; // middle digit
var u: u8 = '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);
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);
@@ -285,95 +415,85 @@ round_shortest :: proc(d: ^Decimal, mant: u64, exp: int, flt: ^Float_Info) {
}
MAX_BASE :: 32;
immutable digits := "0123456789abcdefghijklmnopqrstuvwxyz";
const MAX_BASE = 32;
var digits = "0123456789abcdefghijklmnopqrstuvwxyz";
is_integer_negative :: proc(u: u64, is_signed: bool, bit_size: int) -> (unsigned: u64, neg: bool) {
neg := false;
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:
i := i8(u);
var i = i8(u);
neg = i < 0;
if neg { i = -i; }
u = u64(i);
u = u128(i);
case 16:
i := i16(u);
var i = i16(u);
neg = i < 0;
if neg { i = -i; }
u = u64(i);
u = u128(i);
case 32:
i := i32(u);
var i = i32(u);
neg = i < 0;
if neg { i = -i; }
u = u64(i);
u = u128(i);
case 64:
i := i64(u);
var i = i64(u);
neg = i < 0;
if neg { i = -i; }
u = u64(i);
default:
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;
}
append_bits :: proc(buf: []byte, u: u64, base: int, is_signed: bool, bit_size: int, digits: string, flags: Int_Flag) -> string {
is_pow2 :: proc(x: i64) -> bool {
if (x <= 0) {
return false;
}
return x&(x-1) == 0;
}
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");
}
a: [65]byte;
i := len(a);
neg: bool;
var neg: bool;
var a: [129]u8;
var i = len(a);
u, neg = is_integer_negative(u, is_signed, bit_size);
for b := u64(base); u >= b; {
i--;
q := u / b;
a[i] = digits[uint(u-q*b)];
u = q;
var b = u128(base);
for u >= b {
i--; a[i] = digits[uint(u % b)];
u /= b;
}
i--; a[i] = digits[uint(u % b)];
i--;
a[i] = digits[uint(u)];
if flags&Int_Flag.PREFIX != 0 {
ok := true;
if flags&IntFlag.Prefix != 0 {
var ok = true;
match base {
case 2: i--; a[i] = 'b';
case 8: i--; a[i] = 'o';
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';
default: ok = false;
case: ok = false;
}
if ok {
i--;
a[i] = '0';
i--; a[i] = '0';
}
}
if neg {
i--; a[i] = '-';
} else if flags&Int_Flag.PLUS != 0 {
} else if flags&IntFlag.Plus != 0 {
i--; a[i] = '+';
} else if flags&Int_Flag.SPACE != 0 {
} else if flags&IntFlag.Space != 0 {
i--; a[i] = ' ';
}
append(buf, ..a[i..]);
return string(buf);
}
+12 -5
View File
@@ -1,12 +1,19 @@
new_c_string :: proc(s: string) -> ^byte {
c := make([]byte, len(s)+1);
copy(c, []byte(s));
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];
}
to_odin_string :: proc(c: ^byte) -> string {
len := 0;
proc to_odin_string(c: ^u8) -> string {
var len = 0;
for (c+len)^ != 0 {
len++;
}
+4 -2
View File
@@ -1,2 +1,4 @@
#load "sync_windows.odin" when ODIN_OS == "windows";
#load "sync_linux.odin" when ODIN_OS == "linux";
import_load (
"sync_windows.odin" when ODIN_OS == "windows";
"sync_linux.odin" when ODIN_OS == "linux";
)
+22 -20
View File
@@ -1,53 +1,55 @@
#import "atomics.odin";
#import "os.odin";
import (
"atomics.odin";
"os.odin";
)
Semaphore :: struct {
type Semaphore struct {
// _handle: win32.Handle,
}
Mutex :: struct {
type Mutex struct {
_semaphore: Semaphore,
_counter: i32,
_owner: i32,
_recursion: i32,
}
current_thread_id :: proc() -> i32 {
proc current_thread_id() -> i32 {
return i32(os.current_thread_id());
}
semaphore_init :: proc(s: ^Semaphore) {
proc semaphore_init(s: ^Semaphore) {
// s._handle = win32.CreateSemaphoreA(nil, 0, 1<<31-1, nil);
}
semaphore_destroy :: proc(s: ^Semaphore) {
proc semaphore_destroy(s: ^Semaphore) {
// win32.CloseHandle(s._handle);
}
semaphore_post :: proc(s: ^Semaphore, count: int) {
proc semaphore_post(s: ^Semaphore, count: int) {
// win32.ReleaseSemaphore(s._handle, cast(i32)count, nil);
}
semaphore_release :: proc(s: ^Semaphore) #inline {
proc semaphore_release(s: ^Semaphore) #inline {
semaphore_post(s, 1);
}
semaphore_wait :: proc(s: ^Semaphore) {
proc semaphore_wait(s: ^Semaphore) {
// win32.WaitForSingleObject(s._handle, win32.INFINITE);
}
mutex_init :: proc(m: ^Mutex) {
proc mutex_init(m: ^Mutex) {
atomics.store(&m._counter, 0);
atomics.store(&m._owner, current_thread_id());
semaphore_init(&m._semaphore);
m._recursion = 0;
}
mutex_destroy :: proc(m: ^Mutex) {
proc mutex_destroy(m: ^Mutex) {
semaphore_destroy(&m._semaphore);
}
mutex_lock :: proc(m: ^Mutex) {
thread_id := current_thread_id();
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);
@@ -56,12 +58,12 @@ mutex_lock :: proc(m: ^Mutex) {
atomics.store(&m._owner, thread_id);
m._recursion++;
}
mutex_try_lock :: proc(m: ^Mutex) -> bool {
thread_id := current_thread_id();
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 {
expected: i32 = 0;
var expected: i32 = 0;
if atomics.load(&m._counter) != 0 {
return false;
}
@@ -73,9 +75,9 @@ mutex_try_lock :: proc(m: ^Mutex) -> bool {
m._recursion++;
return true;
}
mutex_unlock :: proc(m: ^Mutex) {
recursion: i32;
thread_id := current_thread_id();
proc mutex_unlock(m: ^Mutex) {
var recursion: i32;
var thread_id = current_thread_id();
assert(thread_id == atomics.load(&m._owner));
m._recursion--;
+27 -25
View File
@@ -1,51 +1,53 @@
#import win32 "sys/windows.odin" when ODIN_OS == "windows";
#import "atomics.odin";
import (
win32 "sys/windows.odin" when ODIN_OS == "windows";
"atomics.odin";
)
Semaphore :: struct {
type Semaphore struct {
_handle: win32.Handle,
}
Mutex :: struct {
type Mutex struct {
_semaphore: Semaphore,
_counter: i32,
_owner: i32,
_recursion: i32,
}
current_thread_id :: proc() -> i32 {
return i32(win32.GetCurrentThreadId());
proc current_thread_id() -> i32 {
return i32(win32.get_current_thread_id());
}
semaphore_init :: proc(s: ^Semaphore) {
s._handle = win32.CreateSemaphoreA(nil, 0, 1<<31-1, nil);
proc semaphore_init(s: ^Semaphore) {
s._handle = win32.create_semaphore_a(nil, 0, 1<<31-1, nil);
}
semaphore_destroy :: proc(s: ^Semaphore) {
win32.CloseHandle(s._handle);
proc semaphore_destroy(s: ^Semaphore) {
win32.close_handle(s._handle);
}
semaphore_post :: proc(s: ^Semaphore, count: int) {
win32.ReleaseSemaphore(s._handle, i32(count), nil);
proc semaphore_post(s: ^Semaphore, count: int) {
win32.release_semaphore(s._handle, i32(count), nil);
}
semaphore_release :: proc(s: ^Semaphore) #inline { semaphore_post(s, 1); }
proc semaphore_release(s: ^Semaphore) #inline { semaphore_post(s, 1); }
semaphore_wait :: proc(s: ^Semaphore) {
win32.WaitForSingleObject(s._handle, win32.INFINITE);
proc semaphore_wait(s: ^Semaphore) {
win32.wait_for_single_object(s._handle, win32.INFINITE);
}
mutex_init :: proc(m: ^Mutex) {
proc mutex_init(m: ^Mutex) {
atomics.store(&m._counter, 0);
atomics.store(&m._owner, current_thread_id());
semaphore_init(&m._semaphore);
m._recursion = 0;
}
mutex_destroy :: proc(m: ^Mutex) {
proc mutex_destroy(m: ^Mutex) {
semaphore_destroy(&m._semaphore);
}
mutex_lock :: proc(m: ^Mutex) {
thread_id := current_thread_id();
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);
@@ -54,12 +56,12 @@ mutex_lock :: proc(m: ^Mutex) {
atomics.store(&m._owner, thread_id);
m._recursion++;
}
mutex_try_lock :: proc(m: ^Mutex) -> bool {
thread_id := current_thread_id();
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 {
expected: i32 = 0;
var expected: i32 = 0;
if atomics.load(&m._counter) != 0 {
return false;
}
@@ -71,9 +73,9 @@ mutex_try_lock :: proc(m: ^Mutex) -> bool {
m._recursion++;
return true;
}
mutex_unlock :: proc(m: ^Mutex) {
recursion: i32;
thread_id := current_thread_id();
proc mutex_unlock(m: ^Mutex) {
var recursion: i32;
var thread_id = current_thread_id();
assert(thread_id == atomics.load(&m._owner));
m._recursion--;
+86 -78
View File
@@ -1,82 +1,90 @@
#foreign_system_library "opengl32.lib" when ODIN_OS == "windows";
#import . "windows.odin";
foreign_system_library "opengl32.lib" when ODIN_OS == "windows";
import . "windows.odin";
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;
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;
)
Hglrc :: Handle;
Color_Ref :: u32;
type (
Hglrc Handle;
ColorRef u32;
Layer_Plane_Descriptor :: struct #ordered {
size: u16,
version: u16,
flags: u32,
pixel_type: byte,
color_bits: byte,
red_bits: byte,
red_shift: byte,
green_bits: byte,
green_shift: byte,
blue_bits: byte,
blue_shift: byte,
alpha_bits: byte,
alpha_shift: byte,
accum_bits: byte,
accum_red_bits: byte,
accum_green_bits: byte,
accum_blue_bits: byte,
accum_alpha_bits: byte,
depth_bits: byte,
stencil_bits: byte,
aux_buffers: byte,
layer_type: byte,
reserved: byte,
transparent: Color_Ref,
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";
}
Point_Float :: struct #ordered {
x, y: f32,
}
Glyph_Metrics_Float :: struct #ordered {
black_box_x: f32,
black_box_y: f32,
glyph_origin: Point_Float,
cell_inc_x: f32,
cell_inc_y: f32,
}
CreateContextAttribsARB_Type :: #type proc(hdc: Hdc, h_share_context: rawptr, attribList: ^i32) -> Hglrc;
ChoosePixelFormatARB_Type :: #type proc(hdc: Hdc, attrib_i_list: ^i32, attrib_f_list: ^f32, max_formats: u32, formats: ^i32, num_formats : ^u32) -> Bool #cc_c;
SwapIntervalEXT_Type :: #type proc(interval : i32) -> bool #cc_c;
GetExtensionsStringARB_Type :: #type proc(Hdc) -> ^byte #cc_c;
CreateContextAttribsARB: CreateContextAttribsARB_Type;
ChoosePixelFormatARB: ChoosePixelFormatARB_Type;
SwapIntervalEXT: SwapIntervalEXT_Type;
GetExtensionsStringARB: GetExtensionsStringARB_Type;
CreateContext :: proc(hdc: Hdc) -> Hglrc #foreign opengl32 "wglCreateContext";
MakeCurrent :: proc(hdc: Hdc, hglrc: Hglrc) -> Bool #foreign opengl32 "wglMakeCurrent";
GetProcAddress :: proc(c_str: ^u8) -> Proc #foreign opengl32 "wglGetProcAddress";
DeleteContext :: proc(hglrc: Hglrc) -> Bool #foreign opengl32 "wglDeleteContext";
CopyContext :: proc(src, dst: Hglrc, mask: u32) -> Bool #foreign opengl32 "wglCopyContext";
CreateLayerContext :: proc(hdc: Hdc, layer_plane: i32) -> Hglrc #foreign opengl32 "wglCreateLayerContext";
DescribeLayerPlane :: proc(hdc: Hdc, pixel_format, layer_plane: i32, bytes: u32, pd: ^Layer_Plane_Descriptor) -> Bool #foreign opengl32 "wglDescribeLayerPlane";
GetCurrentContext :: proc() -> Hglrc #foreign opengl32 "wglGetCurrentContext";
GetCurrentDC :: proc() -> Hdc #foreign opengl32 "wglGetCurrentDC";
GetLayerPaletteEntries :: proc(hdc: Hdc, layer_plane, start, entries: i32, cr: ^Color_Ref) -> i32 #foreign opengl32 "wglGetLayerPaletteEntries";
RealizeLayerPalette :: proc(hdc: Hdc, layer_plane: i32, realize: Bool) -> Bool #foreign opengl32 "wglRealizeLayerPalette";
SetLayerPaletteEntries :: proc(hdc: Hdc, layer_plane, start, entries: i32, cr: ^Color_Ref) -> i32 #foreign opengl32 "wglSetLayerPaletteEntries";
ShareLists :: proc(hglrc1, hglrc2: Hglrc) -> Bool #foreign opengl32 "wglShareLists";
SwapLayerBuffers :: proc(hdc: Hdc, planes: u32) -> Bool #foreign opengl32 "wglSwapLayerBuffers";
UseFontBitmaps :: proc(hdc: Hdc, first, count, list_base: u32) -> Bool #foreign opengl32 "wglUseFontBitmaps";
UseFontOutlines :: proc(hdc: Hdc, first, count, list_base: u32, deviation, extrusion: f32, format: i32, gmf: ^Glyph_Metrics_Float) -> Bool #foreign opengl32 "wglUseFontOutlines";
+541 -468
View File
File diff suppressed because it is too large Load Diff
+39 -39
View File
@@ -1,98 +1,98 @@
is_signed :: proc(info: ^Type_Info) -> bool {
proc is_signed(info: ^TypeInfo) -> bool {
if info == nil { return false; }
match i in type_info_base(info) {
case Type_Info.Integer: return i.signed;
case Type_Info.Float: return true;
case TypeInfo.Integer: return i.signed;
case TypeInfo.Float: return true;
}
return false;
}
is_integer :: proc(info: ^Type_Info) -> bool {
proc is_integer(info: ^TypeInfo) -> bool {
if info == nil { return false; }
_, ok := type_info_base(info).(^Type_Info.Integer);
var _, ok = type_info_base(info).(^TypeInfo.Integer);
return ok;
}
is_float :: proc(info: ^Type_Info) -> bool {
proc is_float(info: ^TypeInfo) -> bool {
if info == nil { return false; }
_, ok := type_info_base(info).(^Type_Info.Float);
var _, ok = type_info_base(info).(^TypeInfo.Float);
return ok;
}
is_complex :: proc(info: ^Type_Info) -> bool {
proc is_complex(info: ^TypeInfo) -> bool {
if info == nil { return false; }
_, ok := type_info_base(info).(^Type_Info.Complex);
var _, ok = type_info_base(info).(^TypeInfo.Complex);
return ok;
}
is_any :: proc(info: ^Type_Info) -> bool {
proc is_any(info: ^TypeInfo) -> bool {
if info == nil { return false; }
_, ok := type_info_base(info).(^Type_Info.Any);
var _, ok = type_info_base(info).(^TypeInfo.Any);
return ok;
}
is_string :: proc(info: ^Type_Info) -> bool {
proc is_string(info: ^TypeInfo) -> bool {
if info == nil { return false; }
_, ok := type_info_base(info).(^Type_Info.String);
var _, ok = type_info_base(info).(^TypeInfo.String);
return ok;
}
is_boolean :: proc(info: ^Type_Info) -> bool {
proc is_boolean(info: ^TypeInfo) -> bool {
if info == nil { return false; }
_, ok := type_info_base(info).(^Type_Info.Boolean);
var _, ok = type_info_base(info).(^TypeInfo.Boolean);
return ok;
}
is_pointer :: proc(info: ^Type_Info) -> bool {
proc is_pointer(info: ^TypeInfo) -> bool {
if info == nil { return false; }
_, ok := type_info_base(info).(^Type_Info.Pointer);
var _, ok = type_info_base(info).(^TypeInfo.Pointer);
return ok;
}
is_procedure :: proc(info: ^Type_Info) -> bool {
proc is_procedure(info: ^TypeInfo) -> bool {
if info == nil { return false; }
_, ok := type_info_base(info).(^Type_Info.Procedure);
var _, ok = type_info_base(info).(^TypeInfo.Procedure);
return ok;
}
is_array :: proc(info: ^Type_Info) -> bool {
proc is_array(info: ^TypeInfo) -> bool {
if info == nil { return false; }
_, ok := type_info_base(info).(^Type_Info.Array);
var _, ok = type_info_base(info).(^TypeInfo.Array);
return ok;
}
is_dynamic_array :: proc(info: ^Type_Info) -> bool {
proc is_dynamic_array(info: ^TypeInfo) -> bool {
if info == nil { return false; }
_, ok := type_info_base(info).(^Type_Info.Dynamic_Array);
var _, ok = type_info_base(info).(^TypeInfo.DynamicArray);
return ok;
}
is_dynamic_map :: proc(info: ^Type_Info) -> bool {
proc is_dynamic_map(info: ^TypeInfo) -> bool {
if info == nil { return false; }
_, ok := type_info_base(info).(^Type_Info.Map);
var _, ok = type_info_base(info).(^TypeInfo.Map);
return ok;
}
is_slice :: proc(info: ^Type_Info) -> bool {
proc is_slice(info: ^TypeInfo) -> bool {
if info == nil { return false; }
_, ok := type_info_base(info).(^Type_Info.Slice);
var _, ok = type_info_base(info).(^TypeInfo.Slice);
return ok;
}
is_vector :: proc(info: ^Type_Info) -> bool {
proc is_vector(info: ^TypeInfo) -> bool {
if info == nil { return false; }
_, ok := type_info_base(info).(^Type_Info.Vector);
var _, ok = type_info_base(info).(^TypeInfo.Vector);
return ok;
}
is_tuple :: proc(info: ^Type_Info) -> bool {
proc is_tuple(info: ^TypeInfo) -> bool {
if info == nil { return false; }
_, ok := type_info_base(info).(^Type_Info.Tuple);
var _, ok = type_info_base(info).(^TypeInfo.Tuple);
return ok;
}
is_struct :: proc(info: ^Type_Info) -> bool {
proc is_struct(info: ^TypeInfo) -> bool {
if info == nil { return false; }
_, ok := type_info_base(info).(^Type_Info.Struct);
var _, ok = type_info_base(info).(^TypeInfo.Struct);
return ok;
}
is_union :: proc(info: ^Type_Info) -> bool {
proc is_union(info: ^TypeInfo) -> bool {
if info == nil { return false; }
_, ok := type_info_base(info).(^Type_Info.Union);
var _, ok = type_info_base(info).(^TypeInfo.Union);
return ok;
}
is_raw_union :: proc(info: ^Type_Info) -> bool {
proc is_raw_union(info: ^TypeInfo) -> bool {
if info == nil { return false; }
_, ok := type_info_base(info).(^Type_Info.Raw_Union);
var _, ok = type_info_base(info).(^TypeInfo.RawUnion);
return ok;
}
is_enum :: proc(info: ^Type_Info) -> bool {
proc is_enum(info: ^TypeInfo) -> bool {
if info == nil { return false; }
_, ok := type_info_base(info).(^Type_Info.Enum);
var _, ok = type_info_base(info).(^TypeInfo.Enum);
return ok;
}
+16 -15
View File
@@ -1,17 +1,18 @@
REPLACEMENT_CHAR :: '\uFFFD';
MAX_RUNE :: '\U0010FFFF';
const (
REPLACEMENT_CHAR = '\uFFFD';
MAX_RUNE = '\U0010FFFF';
_surr1 :: 0xd800;
_surr2 :: 0xdc00;
_surr3 :: 0xe000;
_surr_self :: 0x10000;
_surr1 = 0xd800;
_surr2 = 0xdc00;
_surr3 = 0xe000;
_surr_self = 0x10000;
)
is_surrogate :: proc(r: rune) -> bool {
proc is_surrogate(r: rune) -> bool {
return _surr1 <= r && r < _surr3;
}
decode_surrogate_pair :: proc(r1, r2: rune) -> rune {
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;
}
@@ -19,7 +20,7 @@ decode_surrogate_pair :: proc(r1, r2: rune) -> rune {
}
encode_surrogate_pair :: proc(r: rune) -> (r1, r2: rune) {
proc encode_surrogate_pair(r: rune) -> (r1, r2: rune) {
if r < _surr_self || r > MAX_RUNE {
return REPLACEMENT_CHAR, REPLACEMENT_CHAR;
}
@@ -27,15 +28,15 @@ encode_surrogate_pair :: proc(r: rune) -> (r1, r2: rune) {
return _surr1 + (r>>10)&0x3ff, _surr2 + r&0x3ff;
}
encode :: proc(d: []u16, s: []rune) {
n := len(s);
proc encode(d: []u16, s: []rune) {
var n = len(s);
for r in s {
if r >= _surr_self {
n++;
}
}
max_n := min(len(d), n);
var max_n = min(len(d), n);
n = 0;
for r in s {
@@ -45,12 +46,12 @@ encode :: proc(d: []u16, s: []rune) {
n++;
case _surr_self..MAX_RUNE:
r1, r2 := encode_surrogate_pair(r);
var r1, r2 = encode_surrogate_pair(r);
d[n] = u16(r1);
d[n+1] = u16(r2);
n += 2;
default:
case:
d[n] = u16(REPLACEMENT_CHAR);
n++;
}
+109 -105
View File
@@ -1,74 +1,78 @@
RUNE_ERROR :: '\ufffd';
RUNE_SELF :: 0x80;
RUNE_BOM :: 0xfeff;
RUNE_EOF :: ~rune(0);
MAX_RUNE :: '\U0010ffff';
UTF_MAX :: 4;
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;
SURROGATE_MIN = 0xd800;
SURROGATE_MAX = 0xdfff;
T1 :: 0b0000_0000;
TX :: 0b1000_0000;
T2 :: 0b1100_0000;
T3 :: 0b1110_0000;
T4 :: 0b1111_0000;
T5 :: 0b1111_1000;
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;
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;
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;
// The default lowest and highest continuation byte.
LOCB = 0b1000_0000;
HICB = 0b1011_1111;
)
Accept_Range :: struct { lo, hi: u8 }
type AcceptRange struct { lo, hi: u8 }
immutable accept_ranges := [5]Accept_Range{
{0x80, 0xbf},
{0xa0, 0xbf},
{0x80, 0x9f},
{0x90, 0xbf},
{0x80, 0x8f},
};
var (
accept_ranges = [5]AcceptRange{
{0x80, 0xbf},
{0xa0, 0xbf},
{0x80, 0x9f},
{0x90, 0xbf},
{0x80, 0x8f},
};
immutable accept_sizes := [256]byte{
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
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
};
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]byte, int) {
buf: [4]byte;
i := u32(r);
mask: byte : 0x3f;
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] = byte(r);
buf[0] = u8(r);
return buf, 1;
}
if i <= 1<<11-1 {
buf[0] = 0xc0 | byte(r>>6);
buf[1] = 0x80 | byte(r) & mask;
buf[0] = 0xc0 | u8(r>>6);
buf[1] = 0x80 | u8(r) & mask;
return buf, 2;
}
@@ -79,51 +83,51 @@ encode_rune :: proc(r: rune) -> ([4]byte, int) {
}
if i <= 1<<16-1 {
buf[0] = 0xe0 | byte(r>>12);
buf[1] = 0x80 | byte(r>>6) & mask;
buf[2] = 0x80 | byte(r) & mask;
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 | byte(r>>18);
buf[1] = 0x80 | byte(r>>12) & mask;
buf[2] = 0x80 | byte(r>>6) & mask;
buf[3] = 0x80 | byte(r) & mask;
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 :: proc(s: string) -> (rune, int) #inline { return decode_rune([]byte(s)); }
decode_rune :: proc(s: []byte) -> (rune, int) {
n := len(s);
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;
}
s0 := s[0];
x := accept_sizes[s0];
var s0 = s[0];
var x = accept_sizes[s0];
if x >= 0xF0 {
mask := rune(x) << 31 >> 31; // NOTE(bill): Create 0x0000 or 0xffff.
var 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];
var sz = x & 7;
var accept = accept_ranges[x>>4];
if n < int(sz) {
return RUNE_ERROR, 1;
}
b1 := s[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;
}
b2 := s[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;
}
b3 := s[3];
var b3 = s[3];
if b3 < LOCB || HICB < b3 {
return RUNE_ERROR, 1;
}
@@ -132,11 +136,11 @@ decode_rune :: proc(s: []byte) -> (rune, int) {
decode_last_rune :: proc(s: string) -> (rune, int) #inline { return decode_last_rune([]byte(s)); }
decode_last_rune :: proc(s: []byte) -> (rune, int) {
r: rune;
size: int;
start, end, limit: int;
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 {
@@ -171,7 +175,7 @@ decode_last_rune :: proc(s: []byte) -> (rune, int) {
valid_rune :: proc(r: rune) -> bool {
proc valid_rune(r: rune) -> bool {
if r < 0 {
return false;
} else if SURROGATE_MIN <= r && r <= SURROGATE_MAX {
@@ -182,32 +186,32 @@ valid_rune :: proc(r: rune) -> bool {
return true;
}
valid_string :: proc(s: string) -> bool {
n := len(s);
for i := 0; i < n; {
si := s[i];
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;
}
x := accept_sizes[si];
var x = accept_sizes[si];
if x == 0xf1 {
return false;
}
size := int(x & 7);
var 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 {
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 b := s[i+2]; b < 0x80 || 0xbf < b {
} else if var 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 {
} else if var b = s[i+3]; b < 0x80 || 0xbf < b {
return false;
}
i += size;
@@ -215,40 +219,40 @@ valid_string :: proc(s: string) -> bool {
return true;
}
rune_start :: proc(b: byte) -> bool #inline { return b&0xc0 != 0x80; }
proc rune_start(b: u8) -> bool #inline { return b&0xc0 != 0x80; }
rune_count :: proc(s: string) -> int #inline { return rune_count([]byte(s)); }
rune_count :: proc(s: []byte) -> int {
count := 0;
n := len(s);
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 i := 0; i < n; {
for var i = 0; i < n; {
defer count++;
si := s[i];
var si = s[i];
if si < RUNE_SELF { // ascii
i++;
continue;
}
x := accept_sizes[si];
var x = accept_sizes[si];
if x == 0xf1 {
i++;
continue;
}
size := int(x & 7);
var size = int(x & 7);
if i+size > n {
i++;
continue;
}
ar := accept_ranges[x>>4];
if b := s[i+1]; b < ar.lo || ar.hi < b {
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 b := s[i+2]; b < 0x80 || 0xbf < b {
} else if var 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 {
} else if var b = s[i+3]; b < 0x80 || 0xbf < b {
size = 1;
}
i += size;
@@ -257,7 +261,7 @@ rune_count :: proc(s: []byte) -> int {
}
rune_size :: proc(r: rune) -> int {
proc rune_size(r: rune) -> int {
match {
case r < 0: return -1;
case r <= 1<<7 - 1: return 1;
+4 -1
View File
@@ -1,7 +1,10 @@
@echo off
call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x64 1> NUL
rem call "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" x86 1> NUL
call "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" x64 1> NUL
rem call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x64 1> NUL
rem call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvarsall.bat" x86 1> NUL
rem call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvarsall.bat" x64 1> NUL
set _NO_DEBUG_HEAP=1
set path=w:\Odin\misc;%path%
+94 -94
View File
@@ -1,98 +1,7 @@
#define ARRAY_GROW_FORMULA(x) (2*(x) + 8)
GB_STATIC_ASSERT(ARRAY_GROW_FORMULA(0) > 0);
#define Array(Type_) struct { \
gbAllocator allocator; \
Type_ * e; \
isize count; \
isize capacity; \
}
typedef Array(void) ArrayVoid;
#define array_init_reserve(x_, allocator_, init_capacity_) do { \
void **e = cast(void **)&((x_)->e); \
GB_ASSERT((x_) != NULL); \
(x_)->allocator = (allocator_); \
(x_)->count = 0; \
(x_)->capacity = (init_capacity_); \
*e = gb_alloc((allocator_), gb_size_of(*(x_)->e)*(init_capacity_)); \
} while (0)
#define array_init_count(x_, allocator_, init_count_) do { \
void **e = cast(void **)&((x_)->e); \
GB_ASSERT((x_) != NULL); \
(x_)->allocator = (allocator_); \
(x_)->count = (init_count_); \
(x_)->capacity = (init_count_); \
*e = gb_alloc((allocator_), gb_size_of(*(x_)->e)*(init_count_)); \
} while (0)
#define array_init(x_, allocator_) do { array_init_reserve(x_, allocator_, ARRAY_GROW_FORMULA(0)); } while (0)
#define array_free(x_) do { gb_free((x_)->allocator, (x_)->e); } while (0)
#define array_set_capacity(x_, capacity_) do { array__set_capacity((x_), (capacity_), gb_size_of(*(x_)->e)); } while (0)
#define array_grow(x_, min_capacity_) do { \
isize new_capacity = ARRAY_GROW_FORMULA((x_)->capacity); \
if (new_capacity < (min_capacity_)) { \
new_capacity = (min_capacity_); \
} \
array_set_capacity(x_, new_capacity); \
} while (0)
#define array_add(x_, item_) do { \
if ((x_)->capacity < (x_)->count+1) { \
array_grow(x_, 0); \
} \
(x_)->e[(x_)->count++] = item_; \
} while (0)
#define array_pop(x_) do { GB_ASSERT((x_)->count > 0); (x_)->count--; } while (0)
#define array_clear(x_) do { (x_)->count = 0; } while (0)
#define array_resize(x_, new_count_) do { \
if ((x_)->capacity < (new_count_)) { \
array_grow((x_), (new_count_)); \
} \
(x_)->count = (new_count_); \
} while (0)
#define array_reserve(x_, new_capacity_) do { \
if ((x_)->capacity < (new_capacity_)) { \
array_set_capacity((x_), (new_capacity_)); \
} \
} while (0)
void array__set_capacity(void *ptr, isize capacity, isize element_size) {
ArrayVoid *x = cast(ArrayVoid *)ptr;
GB_ASSERT(ptr != NULL);
GB_ASSERT(element_size > 0);
if (capacity == x->capacity) {
return;
}
if (capacity < x->count) {
if (x->capacity < capacity) {
isize new_capacity = ARRAY_GROW_FORMULA(x->capacity);
if (new_capacity < capacity) {
new_capacity = capacity;
}
array__set_capacity(ptr, new_capacity, element_size);
}
x->count = capacity;
}
x->e = gb_resize(x->allocator, x->e, element_size*x->capacity, element_size*capacity);
x->capacity = capacity;
}
#if 0
#if 1
template <typename T>
struct Array {
gbAllocator allocator;
@@ -224,6 +133,97 @@ void array_set_capacity(Array<T> *array, isize capacity) {
array->capacity = capacity;
}
#endif
#if 0
#define Array(Type_) struct { \
gbAllocator allocator; \
Type_ * e; \
isize count; \
isize capacity; \
}
typedef Array(void) ArrayVoid;
#define array_init_reserve(x_, allocator_, init_capacity_) do { \
void **e = cast(void **)&((x_)->e); \
GB_ASSERT((x_) != NULL); \
(x_)->allocator = (allocator_); \
(x_)->count = 0; \
(x_)->capacity = (init_capacity_); \
*e = gb_alloc((allocator_), gb_size_of(*(x_)->e)*(init_capacity_)); \
} while (0)
#define array_init_count(x_, allocator_, init_count_) do { \
void **e = cast(void **)&((x_)->e); \
GB_ASSERT((x_) != NULL); \
(x_)->allocator = (allocator_); \
(x_)->count = (init_count_); \
(x_)->capacity = (init_count_); \
*e = gb_alloc((allocator_), gb_size_of(*(x_)->e)*(init_count_)); \
} while (0)
#define array_init(x_, allocator_) do { array_init_reserve(x_, allocator_, ARRAY_GROW_FORMULA(0)); } while (0)
#define array_free(x_) do { gb_free((x_)->allocator, (x_)->e); } while (0)
#define array_set_capacity(x_, capacity_) do { array__set_capacity((x_), (capacity_), gb_size_of(*(x_)->e)); } while (0)
#define array_grow(x_, min_capacity_) do { \
isize new_capacity = ARRAY_GROW_FORMULA((x_)->capacity); \
if (new_capacity < (min_capacity_)) { \
new_capacity = (min_capacity_); \
} \
array_set_capacity(x_, new_capacity); \
} while (0)
#define array_add(x_, item_) do { \
if ((x_)->capacity < (x_)->count+1) { \
array_grow(x_, 0); \
} \
(x_)->e[(x_)->count++] = item_; \
} while (0)
#define array_pop(x_) do { GB_ASSERT((x_)->count > 0); (x_)->count--; } while (0)
#define array_clear(x_) do { (x_)->count = 0; } while (0)
#define array_resize(x_, new_count_) do { \
if ((x_)->capacity < (new_count_)) { \
array_grow((x_), (new_count_)); \
} \
(x_)->count = (new_count_); \
} while (0)
#define array_reserve(x_, new_capacity_) do { \
if ((x_)->capacity < (new_capacity_)) { \
array_set_capacity((x_), (new_capacity_)); \
} \
} while (0)
void array__set_capacity(void *ptr, isize capacity, isize element_size) {
ArrayVoid *x = cast(ArrayVoid *)ptr;
GB_ASSERT(ptr != NULL);
GB_ASSERT(element_size > 0);
if (capacity == x->capacity) {
return;
}
if (capacity < x->count) {
if (x->capacity < capacity) {
isize new_capacity = ARRAY_GROW_FORMULA(x->capacity);
if (new_capacity < capacity) {
new_capacity = capacity;
}
array__set_capacity(ptr, new_capacity, element_size);
}
x->count = capacity;
}
x->e = gb_resize(x->allocator, x->e, element_size*x->capacity, element_size*capacity);
x->capacity = capacity;
}
#endif
+82 -50
View File
@@ -1,5 +1,5 @@
// This stores the information for the specify architecture of this build
typedef struct BuildContext {
struct BuildContext {
// Constants
String ODIN_OS; // target operating system
String ODIN_ARCH; // target architecture
@@ -12,16 +12,21 @@ typedef struct BuildContext {
i64 word_size; // Size of a pointer, must be >= 4
i64 max_align; // max alignment, must be >= 1 (and typically >= word_size)
String opt_flags;
String llc_flags;
String link_flags;
bool is_dll;
} BuildContext;
bool generate_docs;
i32 optimization_level;
};
gb_global BuildContext build_context = {0};
// TODO(bill): OS dependent versions for the BuildContext
// join_path
// is_dir
@@ -35,7 +40,7 @@ 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;
Array<wchar_t> path_buf;
isize len, i;
gbTempArenaMemory tmp;
wchar_t *text;
@@ -48,7 +53,7 @@ String odin_root_dir(void) {
len = 0;
for (;;) {
len = GetModuleFileNameW(NULL, &path_buf.e[0], path_buf.count);
len = GetModuleFileNameW(NULL, &path_buf[0], path_buf.count);
if (len == 0) {
return make_string(NULL, 0);
}
@@ -57,6 +62,8 @@ String odin_root_dir(void) {
}
array_resize(&path_buf, 2*path_buf.count + 300);
}
len += 1; // NOTE(bill): It needs an extra 1 for some reason
tmp = gb_temp_arena_memory_begin(&string_buffer_arena);
@@ -64,8 +71,9 @@ String odin_root_dir(void) {
GetModuleFileNameW(NULL, text, len);
path = string16_to_string(heap_allocator(), make_string16(text, len));
for (i = path.len-1; i >= 0; i--) {
u8 c = path.text[i];
u8 c = path[i];
if (c == '/' || c == '\\') {
break;
}
@@ -88,10 +96,10 @@ String odin_root_dir(void) {
String odin_root_dir(void) {
String path = global_module_path;
Array(char) path_buf;
Array<char> path_buf;
isize len, i;
gbTempArenaMemory tmp;
wchar_t *text;
u8 *text;
if (global_module_path_set) {
return global_module_path;
@@ -101,8 +109,8 @@ String odin_root_dir(void) {
len = 0;
for (;;) {
int sz = path_buf.count;
int res = _NSGetExecutablePath(&path_buf.e[0], &sz);
u32 sz = path_buf.count;
int res = _NSGetExecutablePath(&path_buf[0], &sz);
if(res == 0) {
len = sz;
break;
@@ -114,11 +122,11 @@ String odin_root_dir(void) {
tmp = gb_temp_arena_memory_begin(&string_buffer_arena);
text = gb_alloc_array(string_buffer_allocator, u8, len + 1);
gb_memmove(text, &path_buf.e[0], len);
gb_memmove(text, &path_buf[0], len);
path = make_string(text, len);
for (i = path.len-1; i >= 0; i--) {
u8 c = path.text[i];
u8 c = path[i];
if (c == '/' || c == '\\') {
break;
}
@@ -141,7 +149,7 @@ String odin_root_dir(void) {
String odin_root_dir(void) {
String path = global_module_path;
Array(char) path_buf;
Array<char> path_buf;
isize len, i;
gbTempArenaMemory tmp;
u8 *text;
@@ -158,7 +166,7 @@ String odin_root_dir(void) {
// of this compiler, it should be _good enough_.
// That said, there's no solid 100% method on Linux to get the program's
// path without checking this link. Sorry.
len = readlink("/proc/self/exe", &path_buf.e[0], path_buf.count);
len = readlink("/proc/self/exe", &path_buf[0], path_buf.count);
if(len == 0) {
return make_string(NULL, 0);
}
@@ -171,11 +179,11 @@ String odin_root_dir(void) {
tmp = gb_temp_arena_memory_begin(&string_buffer_arena);
text = gb_alloc_array(string_buffer_allocator, u8, len + 1);
gb_memmove(text, &path_buf.e[0], len);
gb_memmove(text, &path_buf[0], len);
path = make_string(text, len);
for (i = path.len-1; i >= 0; i--) {
u8 c = path.text[i];
u8 c = path[i];
if (c == '/' || c == '\\') {
break;
}
@@ -200,10 +208,10 @@ String path_to_fullpath(gbAllocator a, String s) {
String16 string16 = string_to_string16(string_buffer_allocator, s);
String result = {0};
DWORD len = GetFullPathNameW(string16.text, 0, NULL, NULL);
DWORD len = GetFullPathNameW(&string16[0], 0, NULL, NULL);
if (len != 0) {
wchar_t *text = gb_alloc_array(string_buffer_allocator, wchar_t, len+1);
GetFullPathNameW(string16.text, len, text, NULL);
GetFullPathNameW(&string16[0], len, text, NULL);
text[len] = 0;
result = string16_to_string(a, make_string16(text, len));
}
@@ -212,7 +220,7 @@ String path_to_fullpath(gbAllocator a, String s) {
}
#elif defined(GB_SYSTEM_OSX) || defined(GB_SYSTEM_UNIX)
String path_to_fullpath(gbAllocator a, String s) {
char *p = realpath(cast(char *)s.text, 0);
char *p = realpath(cast(char *)&s[0], 0);
if(p == NULL) return make_string_c("");
return make_string_c(p);
@@ -229,8 +237,8 @@ String get_fullpath_relative(gbAllocator a, String base_dir, String path) {
u8 *str = gb_alloc_array(heap_allocator(), u8, str_len+1);
isize i = 0;
gb_memmove(str+i, base_dir.text, base_dir.len); i += base_dir.len;
gb_memmove(str+i, path.text, path.len);
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);
@@ -247,9 +255,9 @@ String get_fullpath_core(gbAllocator a, String path) {
isize str_len = module_dir.len + core_len + path.len;
u8 *str = gb_alloc_array(heap_allocator(), u8, str_len+1);
gb_memmove(str, module_dir.text, module_dir.len);
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.text, path.len);
gb_memmove(str+module_dir.len+core_len, &path[0], path.len);
str[str_len] = '\0';
res = path_to_fullpath(a, make_string(str, str_len));
@@ -263,66 +271,90 @@ String get_fullpath_core(gbAllocator a, String path) {
void init_build_context(void) {
BuildContext *bc = &build_context;
bc->ODIN_VENDOR = str_lit("odin");
bc->ODIN_VERSION = str_lit("0.2.1");
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");
bc->ODIN_ARCH = str_lit("amd64");
bc->ODIN_ENDIAN = str_lit("little");
#elif defined(GB_SYSTEM_OSX)
bc->ODIN_OS = str_lit("osx");
bc->ODIN_ARCH = str_lit("amd64");
bc->ODIN_ENDIAN = str_lit("little");
#else
bc->ODIN_OS = str_lit("linux");
bc->ODIN_ARCH = str_lit("amd64");
bc->ODIN_ENDIAN = str_lit("little");
#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");
}
// 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"
#define LINK_FLAG_X64 "/machine:x64"
#define LINK_FLAG_X86 "/machine:x86"
#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");
// 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(str_eq(bc->ODIN_ARCH, str_lit("amd64")));
#define LINK_FLAG_X64 ""
#define LINK_FLAG_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"
// 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 (str_eq(bc->ODIN_ARCH, str_lit("amd64"))) {
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 (str_eq(bc->ODIN_ARCH, str_lit("x86"))) {
} 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 " ");
} else {
gb_printf_err("This current architecture is not supported");
gb_exit(1);
}
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);
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, "");
}
if (opt_len > 0) {
opt_len--;
}
bc->opt_flags = make_string(cast(u8 *)opt_flags_string, opt_len);
#undef LINK_FLAG_X64
#undef LINK_FLAG_X86
}
+226 -167
View File
@@ -12,8 +12,8 @@ Type *check_init_variable(Checker *c, Entity *e, Operand *operand, String contex
// TODO(bill): is this a good enough error message?
// TODO(bill): Actually allow built in procedures to be passed around and thus be created on use
error_node(operand->expr,
"Cannot assign builtin procedure `%s` in %.*s",
error(operand->expr,
"Cannot assign built-in procedure `%s` in %.*s",
expr_str,
LIT(context_name));
@@ -34,16 +34,36 @@ Type *check_init_variable(Checker *c, Entity *e, Operand *operand, String contex
Type *t = operand->type;
if (is_type_untyped(t)) {
if (t == t_invalid || is_type_untyped_nil(t)) {
error(e->token, "Use of untyped nil in %.*s", LIT(context_name));
error(e->token, "Invalid use of untyped nil in %.*s", LIT(context_name));
e->type = t_invalid;
return NULL;
}
if (t == t_invalid || is_type_untyped_undef(t)) {
error(e->token, "Invalid use of --- in %.*s", LIT(context_name));
e->type = t_invalid;
return NULL;
}
t = default_type(t);
}
if (is_type_gen_proc(t)) {
error(e->token, "Invalid use of a generic procedure in %.*s", LIT(context_name));
e->type = t_invalid;
return NULL;
}
if (is_type_bit_field_value(t)) {
t = default_bit_field_value_type(t);
}
if (is_type_variant(t)) {
Type *st = base_type(t);
GB_ASSERT(st->Record.variant_parent != NULL);
t = st->Record.variant_parent;
}
GB_ASSERT(is_type_typed(t));
e->type = t;
}
e->parent_proc_decl = c->context.curr_proc_decl;
check_assignment(c, operand, e->type, context_name);
if (operand->mode == Addressing_Invalid) {
return NULL;
@@ -52,34 +72,36 @@ Type *check_init_variable(Checker *c, Entity *e, Operand *operand, String contex
return e->type;
}
void check_init_variables(Checker *c, Entity **lhs, isize lhs_count, AstNodeArray inits, String context_name) {
void check_init_variables(Checker *c, Entity **lhs, isize lhs_count, Array<AstNode *> inits, String context_name) {
if ((lhs == NULL || lhs_count == 0) && inits.count == 0) {
return;
}
gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&c->tmp_arena);
// NOTE(bill): If there is a bad syntax error, rhs > lhs which would mean there would need to be
// an extra allocation
ArrayOperand operands = {0};
array_init_reserve(&operands, c->tmp_allocator, 2*lhs_count);
Array<Operand> operands = {};
array_init(&operands, c->tmp_allocator, 2*lhs_count);
check_unpack_arguments(c, lhs_count, &operands, inits, true);
isize rhs_count = operands.count;
for_array(i, operands) {
if (operands.e[i].mode == Addressing_Invalid) {
if (operands[i].mode == Addressing_Invalid) {
rhs_count--;
}
}
isize max = gb_min(lhs_count, rhs_count);
for (isize i = 0; i < max; i++) {
check_init_variable(c, lhs[i], &operands.e[i], context_name);
check_init_variable(c, lhs[i], &operands[i], context_name);
}
if (rhs_count > 0 && lhs_count != rhs_count) {
error(lhs[0]->token, "Assignment count mismatch `%td` = `%td`", lhs_count, rhs_count);
}
gb_temp_arena_memory_end(tmp);
}
@@ -96,7 +118,7 @@ void check_init_constant(Checker *c, Entity *e, Operand *operand) {
if (operand->mode != Addressing_Constant) {
// TODO(bill): better error
gbString str = expr_to_string(operand->expr);
error_node(operand->expr, "`%s` is not a constant", str);
error(operand->expr, "`%s` is not a constant", str);
gb_string_free(str);
if (e->type == NULL) {
e->type = t_invalid;
@@ -105,7 +127,7 @@ void check_init_constant(Checker *c, Entity *e, Operand *operand) {
}
if (!is_type_constant_type(operand->type)) {
gbString type_str = type_to_string(operand->type);
error_node(operand->expr, "Invalid constant type: `%s`", type_str);
error(operand->expr, "Invalid constant type: `%s`", type_str);
gb_string_free(type_str);
if (e->type == NULL) {
e->type = t_invalid;
@@ -122,12 +144,15 @@ void check_init_constant(Checker *c, Entity *e, Operand *operand) {
return;
}
e->parent_proc_decl = c->context.curr_proc_decl;
e->Constant.value = operand->value;
}
void check_type_decl(Checker *c, Entity *e, AstNode *type_expr, Type *def) {
GB_ASSERT(e->type == NULL);
Type *named = make_type_named(c->allocator, e->token.string, NULL, e);
String name = e->token.string;
Type *named = make_type_named(c->allocator, name, NULL, e);
named->Named.type_name = e;
if (def != NULL && def->kind == Type_Named) {
def->Named.base = named;
@@ -136,7 +161,7 @@ void check_type_decl(Checker *c, Entity *e, AstNode *type_expr, Type *def) {
// gb_printf_err("%.*s %p\n", LIT(e->token.string), e);
Type *bt = check_type_extra(c, type_expr, named);
Type *bt = check_type(c, type_expr, named);
named->Named.base = base_type(bt);
if (named->Named.base == t_invalid) {
// gb_printf("check_type_decl: %s\n", type_to_string(named));
@@ -157,7 +182,7 @@ void check_const_decl(Checker *c, Entity *e, AstNode *type_expr, AstNode *init,
Type *t = check_type(c, type_expr);
if (!is_type_constant_type(t)) {
gbString str = type_to_string(t);
error_node(type_expr, "Invalid constant type `%s`", str);
error(type_expr, "Invalid constant type `%s`", str);
gb_string_free(str);
e->type = t_invalid;
return;
@@ -165,10 +190,11 @@ void check_const_decl(Checker *c, Entity *e, AstNode *type_expr, AstNode *init,
e->type = t;
}
Operand operand = {0};
Operand operand = {};
if (init != NULL) {
check_expr_or_type(c, &operand, init);
}
#if 0
if (operand.mode == Addressing_Type) {
e->kind = Entity_TypeName;
@@ -177,6 +203,7 @@ void check_const_decl(Checker *c, Entity *e, AstNode *type_expr, AstNode *init,
check_type_decl(c, e, d->type_expr, named_type);
return;
}
#endif
check_init_constant(c, e, &operand);
@@ -201,12 +228,20 @@ bool are_signatures_similar_enough(Type *a_, Type *b_) {
return false;
}
for (isize i = 0; i < a->param_count; i++) {
Type *x = base_type(a->params->Tuple.variables[i]->type);
Type *y = base_type(b->params->Tuple.variables[i]->type);
Type *x = core_type(a->params->Tuple.variables[i]->type);
Type *y = core_type(b->params->Tuple.variables[i]->type);
if (is_type_pointer(x) && is_type_pointer(y)) {
continue;
}
if (is_type_integer(x) && is_type_integer(y)) {
GB_ASSERT(x->kind == Type_Basic);
GB_ASSERT(y->kind == Type_Basic);
if (x->Basic.size == y->Basic.size) {
continue;
}
}
if (!are_types_identical(x, y)) {
return false;
}
@@ -218,6 +253,14 @@ bool are_signatures_similar_enough(Type *a_, Type *b_) {
continue;
}
if (is_type_integer(x) && is_type_integer(y)) {
GB_ASSERT(x->kind == Type_Basic);
GB_ASSERT(y->kind == Type_Basic);
if (x->Basic.size == y->Basic.size) {
continue;
}
}
if (!are_types_identical(x, y)) {
return false;
}
@@ -226,19 +269,66 @@ bool are_signatures_similar_enough(Type *a_, Type *b_) {
return true;
}
void check_proc_lit(Checker *c, Entity *e, DeclInfo *d) {
GB_ASSERT(e->type == NULL);
if (d->proc_lit->kind != AstNode_ProcLit) {
// TOOD(bill): Better error message
error_node(d->proc_lit, "Expected a procedure to check");
void init_entity_foreign_library(Checker *c, Entity *e) {
AstNode *ident = NULL;
Entity **foreign_library = NULL;
switch (e->kind) {
case Entity_Procedure:
ident = e->Procedure.foreign_library_ident;
foreign_library = &e->Procedure.foreign_library;
break;
case Entity_Variable:
ident = e->Variable.foreign_library_ident;
foreign_library = &e->Variable.foreign_library;
break;
default:
return;
}
Type *proc_type = make_type_proc(c->allocator, e->scope, NULL, 0, NULL, 0, false, ProcCC_Odin);
if (ident == NULL) {
error(e->token, "foreign entiies must declare which library they are from");
} else if (ident->kind != AstNode_Ident) {
error(ident, "foreign library names must be an identifier");
} else {
String name = ident->Ident.string;
Entity *found = scope_lookup_entity(c->context.scope, name);
if (found == NULL) {
if (name == "_") {
error(ident, "`_` cannot be used as a value type");
} else {
error(ident, "Undeclared name: %.*s", LIT(name));
}
} else if (found->kind != Entity_LibraryName) {
error(ident, "`%.*s` cannot be used as a library name", LIT(name));
} else {
// TODO(bill): Extra stuff to do with library names?
*foreign_library = found;
add_entity_use(c, ident, found);
}
}
}
void check_proc_decl(Checker *c, Entity *e, DeclInfo *d) {
GB_ASSERT(e->type == NULL);
if (d->proc_decl->kind != AstNode_ProcDecl) {
// TOOD(bill): Better error message
error(d->proc_decl, "Expected a procedure to check");
return;
}
Type *proc_type = e->type;
if (d->gen_proc_type != NULL) {
proc_type = d->gen_proc_type;
} else {
proc_type = make_type_proc(c->allocator, e->scope, NULL, 0, NULL, 0, false, ProcCC_Odin);
}
e->type = proc_type;
ast_node(pd, ProcLit, d->proc_lit);
ast_node(pd, ProcDecl, d->proc_decl);
check_open_scope(c, pd->type);
defer (check_close_scope(c));
check_procedure_type(c, proc_type, pd->type);
bool is_foreign = (pd->tags & ProcTag_foreign) != 0;
@@ -249,98 +339,100 @@ void check_proc_lit(Checker *c, Entity *e, DeclInfo *d) {
bool is_require_results = (pd->tags & ProcTag_require_results) != 0;
if (d->scope->is_file && str_eq(e->token.string, str_lit("main"))) {
if (proc_type != NULL) {
TypeProc *pt = &proc_type->Proc;
if (pt->param_count != 0 ||
pt->result_count != 0) {
gbString str = type_to_string(proc_type);
error(e->token, "Procedure type of `main` was expected to be `proc()`, got %s", str);
gb_string_free(str);
}
TypeProc *pt = &proc_type->Proc;
if (d->scope->is_file && e->token.string == "main") {
if (pt->param_count != 0 ||
pt->result_count != 0) {
gbString str = type_to_string(proc_type);
error(e->token, "Procedure type of `main` was expected to be `proc()`, got %s", str);
gb_string_free(str);
}
if (proc_type->Proc.calling_convention != ProcCC_Odin &&
proc_type->Proc.calling_convention != ProcCC_Contextless) {
error(e->token, "Procedure `main` cannot have a custom calling convention");
}
proc_type->Proc.calling_convention = ProcCC_Contextless;
}
if (is_inline && is_no_inline) {
error_node(pd->type, "You cannot apply both `inline` and `no_inline` to a procedure");
error(pd->type, "You cannot apply both `inline` and `no_inline` to a procedure");
}
if (is_foreign && is_link_name) {
error_node(pd->type, "You cannot apply both `foreign` and `link_name` to a procedure");
} else if (is_foreign && is_export) {
error_node(pd->type, "You cannot apply both `foreign` and `export` to a procedure");
if (is_foreign && is_export) {
error(pd->type, "A foreign procedure cannot have an `export` tag");
}
if (pt->is_generic) {
if (pd->body == NULL) {
error(e->token, "Polymorphic procedures must have a body");
}
if (is_foreign) {
error(e->token, "A foreign procedures cannot be a polymorphic");
return;
}
}
if (pd->body != NULL) {
if (is_foreign) {
error_node(pd->body, "A procedure tagged as `#foreign` cannot have a body");
error(pd->body, "A foreign procedure cannot have a body");
}
if (proc_type->Proc.c_vararg) {
error(pd->body, "A procedure with a `#c_vararg` field cannot have a body");
}
d->scope = c->context.scope;
GB_ASSERT(pd->body->kind == AstNode_BlockStmt);
check_procedure_later(c, c->curr_ast_file, e->token, d, proc_type, pd->body, pd->tags);
} else if (!is_foreign) {
error(e->token, "Only a foreign procedure cannot have a body");
}
if (pt->result_count == 0 && is_require_results) {
error(pd->type, "`#require_results` is not needed on a procedure with no results");
} else {
pt->require_results = is_require_results;
}
if (proc_type != NULL && is_type_proc(proc_type)) {
TypeProc *tp = &proc_type->Proc;
if (tp->result_count == 0 && is_require_results) {
error_node(pd->type, "`#require_results` is not needed on a procedure with no results");
} else {
tp->require_results = is_require_results;
}
}
if (is_foreign) {
MapEntity *fp = &c->info.foreigns;
String name = e->token.string;
if (pd->foreign_name.len > 0) {
name = pd->foreign_name;
if (pd->link_name.len > 0) {
name = pd->link_name;
}
AstNode *foreign_library = d->proc_lit->ProcLit.foreign_library;
if (foreign_library == NULL) {
error(e->token, "#foreign procedures must declare which library they are from");
} else if (foreign_library->kind != AstNode_Ident) {
error_node(foreign_library, "#foreign library names must be an identifier");
} else {
String name = foreign_library->Ident.string;
Entity *found = scope_lookup_entity(c->context.scope, name);
if (found == NULL) {
if (str_eq(name, str_lit("_"))) {
error_node(foreign_library, "`_` cannot be used as a value type");
} else {
error_node(foreign_library, "Undeclared name: %.*s", LIT(name));
}
} else if (found->kind != Entity_LibraryName) {
error_node(foreign_library, "`_` cannot be used as a library name");
} else {
// TODO(bill): Extra stuff to do with library names?
e->Procedure.foreign_library = found;
add_entity_use(c, foreign_library, found);
}
}
e->Procedure.is_foreign = true;
e->Procedure.foreign_name = name;
e->Procedure.link_name = name;
init_entity_foreign_library(c, e);
auto *fp = &c->info.foreigns;
HashKey key = hash_string(name);
Entity **found = map_entity_get(fp, key);
Entity **found = map_get(fp, key);
if (found) {
Entity *f = *found;
TokenPos pos = f->token.pos;
Type *this_type = base_type(e->type);
Type *other_type = base_type(f->type);
if (!are_signatures_similar_enough(this_type, other_type)) {
error_node(d->proc_lit,
"Redeclaration of #foreign procedure `%.*s` with different type signatures\n"
if (is_type_proc(this_type) && is_type_proc(other_type)) {
if (!are_signatures_similar_enough(this_type, other_type)) {
error(d->proc_decl,
"Redeclaration of foreign procedure `%.*s` with different type signatures\n"
"\tat %.*s(%td:%td)",
LIT(name), LIT(pos.file), pos.line, pos.column);
}
} else if (!are_types_identical(this_type, other_type)) {
error(d->proc_decl,
"Foreign entity `%.*s` previously declared elsewhere with a different type\n"
"\tat %.*s(%td:%td)",
LIT(name), LIT(pos.file), pos.line, pos.column);
}
} else {
map_entity_set(fp, key, e);
map_set(fp, key, e);
}
} else {
String name = e->token.string;
@@ -349,27 +441,25 @@ void check_proc_lit(Checker *c, Entity *e, DeclInfo *d) {
}
if (is_link_name || is_export) {
MapEntity *fp = &c->info.foreigns;
auto *fp = &c->info.foreigns;
e->Procedure.link_name = name;
HashKey key = hash_string(name);
Entity **found = map_entity_get(fp, key);
Entity **found = map_get(fp, key);
if (found) {
Entity *f = *found;
TokenPos pos = f->token.pos;
// TODO(bill): Better error message?
error_node(d->proc_lit,
error(d->proc_decl,
"Non unique linking name for procedure `%.*s`\n"
"\tother at %.*s(%td:%td)",
LIT(name), LIT(pos.file), pos.line, pos.column);
} else {
map_entity_set(fp, key, e);
map_set(fp, key, e);
}
}
}
check_close_scope(c);
}
void check_var_decl(Checker *c, Entity *e, Entity **entities, isize entity_count, AstNode *type_expr, AstNode *init_expr) {
@@ -383,7 +473,34 @@ void check_var_decl(Checker *c, Entity *e, Entity **entities, isize entity_count
e->flags |= EntityFlag_Visited;
if (type_expr != NULL) {
e->type = check_type_extra(c, type_expr, NULL);
e->type = check_type(c, type_expr);
}
if (e->Variable.is_foreign) {
if (init_expr != NULL) {
error(e->token, "A foreign variable declaration cannot have a default value");
}
init_entity_foreign_library(c, e);
String name = e->token.string;
auto *fp = &c->info.foreigns;
HashKey key = hash_string(name);
Entity **found = map_get(fp, key);
if (found) {
Entity *f = *found;
TokenPos pos = f->token.pos;
Type *this_type = base_type(e->type);
Type *other_type = base_type(f->type);
if (!are_types_identical(this_type, other_type)) {
error(e->token,
"Foreign entity `%.*s` previously declared elsewhere with a different type\n"
"\tat %.*s(%td:%td)",
LIT(name), LIT(pos.file), pos.line, pos.column);
}
} else {
map_set(fp, key, e);
}
}
if (init_expr == NULL) {
@@ -395,7 +512,7 @@ void check_var_decl(Checker *c, Entity *e, Entity **entities, isize entity_count
if (entities == NULL || entity_count == 1) {
GB_ASSERT(entities == NULL || entities[0] == e);
Operand operand = {0};
Operand operand = {};
check_expr(c, &operand, init_expr);
check_init_variable(c, e, &operand, str_lit("variable declaration"));
}
@@ -406,84 +523,21 @@ void check_var_decl(Checker *c, Entity *e, Entity **entities, isize entity_count
}
}
AstNodeArray inits;
array_init_reserve(&inits, c->allocator, 1);
Array<AstNode *> inits;
array_init(&inits, c->allocator, 1);
array_add(&inits, init_expr);
check_init_variables(c, entities, entity_count, inits, str_lit("variable declaration"));
}
void check_alias_decl(Checker *c, Entity *e, AstNode *expr, Type *named_type) {
GB_ASSERT(e->type == NULL);
GB_ASSERT(e->kind == Entity_Alias);
if (e->flags & EntityFlag_Visited) {
e->type = t_invalid;
return;
}
e->flags |= EntityFlag_Visited;
e->type = t_invalid;
expr = unparen_expr(expr);
if (expr->kind == AstNode_Alias) {
error_node(expr, "#alias of an #alias is not allowed");
return;
}
Operand operand = {0};
check_expr_or_type(c, &operand, expr);
if (operand.mode != Addressing_Type) {
error_node(expr, "#alias declarations only allow types");
return;
}
e->kind = Entity_TypeName;
e->TypeName.is_type_alias = true;
e->type = NULL;
DeclInfo *d = c->context.decl;
d->type_expr = expr;
check_type_decl(c, e, d->type_expr, named_type);
// Operand o = {0};
// Entity *f = NULL;
// if (expr->kind == AstNode_Ident) {
// f = check_ident(c, &o, expr, NULL, NULL, true);
// } else if (expr->kind == AstNode_SelectorExpr) {
// f = check_selector(c, &o, expr, NULL);
// } else {
// check_expr_or_type(c, &o, expr);
// }
// if (o.mode == Addressing_Invalid) {
// return;
// }
// switch (o.mode) {
// case Addressing_Type:
// e->type = o.type;
// // e->kind = Entity_TypeName;
// // e->TypeName.is_type_alias = true;
// e->Alias.kind = EntityAlias_Type;
// e->Alias.original = f;
// break;
// default:
// error_node(expr, "#alias declarations only allow types");
// e->kind = Entity_Invalid;
// e->type = t_invalid;
// break;
// }
}
void check_entity_decl(Checker *c, Entity *e, DeclInfo *d, Type *named_type) {
if (e->type != NULL) {
return;
}
if (d == NULL) {
DeclInfo **found = map_decl_info_get(&c->info.entities, hash_pointer(e));
if (found) {
d = *found;
} else {
d = decl_info_of_entity(&c->info, e);
if (d == NULL) {
// TODO(bill): Err here?
e->type = t_invalid;
set_base_type(named_type, t_invalid);
@@ -496,6 +550,8 @@ void check_entity_decl(Checker *c, Entity *e, DeclInfo *d, Type *named_type) {
c->context.scope = d->scope;
c->context.decl = d;
e->parent_proc_decl = c->context.curr_proc_decl;
switch (e->kind) {
case Entity_Variable:
check_var_decl(c, e, d->entities, d->entity_count, d->type_expr, d->init_expr);
@@ -506,11 +562,8 @@ void check_entity_decl(Checker *c, Entity *e, DeclInfo *d, Type *named_type) {
case Entity_TypeName:
check_type_decl(c, e, d->type_expr, named_type);
break;
case Entity_Alias:
check_alias_decl(c, e, d->init_expr, named_type);
break;
case Entity_Procedure:
check_proc_lit(c, e, d);
check_proc_decl(c, e, d);
break;
}
@@ -520,9 +573,12 @@ void check_entity_decl(Checker *c, Entity *e, DeclInfo *d, Type *named_type) {
void check_proc_body(Checker *c, Token token, DeclInfo *decl, Type *type, AstNode *body) {
if (body == NULL) {
return;
}
GB_ASSERT(body->kind == AstNode_BlockStmt);
String proc_name = {0};
String proc_name = {};
if (token.kind == Token_Ident) {
proc_name = token.string;
} else {
@@ -534,13 +590,16 @@ void check_proc_body(Checker *c, Token token, DeclInfo *decl, Type *type, AstNod
c->context.scope = decl->scope;
c->context.decl = decl;
c->context.proc_name = proc_name;
c->context.curr_proc_decl = decl;
GB_ASSERT(type->kind == Type_Proc);
if (type->Proc.param_count > 0) {
TypeTuple *params = &type->Proc.params->Tuple;
for (isize i = 0; i < params->variable_count; i++) {
Entity *e = params->variables[i];
GB_ASSERT(e->kind == Entity_Variable);
if (e->kind != Entity_Variable) {
continue;
}
if (!(e->flags & EntityFlag_Using)) {
continue;
}
@@ -548,10 +607,10 @@ void check_proc_body(Checker *c, Token token, DeclInfo *decl, Type *type, AstNod
String name = e->token.string;
Type *t = base_type(type_deref(e->type));
if (is_type_struct(t) || is_type_raw_union(t)) {
Scope **found = map_scope_get(&c->info.scopes, hash_pointer(t->Record.node));
GB_ASSERT(found != NULL);
for_array(i, (*found)->elements.entries) {
Entity *f = (*found)->elements.entries.e[i].value;
Scope *scope = scope_of_node(&c->info, t->Record.node);
GB_ASSERT(scope != NULL);
for_array(i, scope->elements.entries) {
Entity *f = scope->elements.entries[i].value;
if (f->kind == Entity_Variable) {
Entity *uvar = make_entity_using_variable(c->allocator, e, f->token, f->type);
uvar->Variable.is_immutable = is_immutable;
@@ -592,9 +651,9 @@ void check_proc_body(Checker *c, Token token, DeclInfo *decl, Type *type, AstNod
if (decl->parent != NULL) {
// NOTE(bill): Add the dependencies from the procedure literal (lambda)
for_array(i, decl->deps.entries) {
HashKey key = decl->deps.entries.e[i].key;
HashKey key = decl->deps.entries[i].key;
Entity *e = cast(Entity *)key.ptr;
map_bool_set(&decl->parent->deps, key, true);
map_set(&decl->parent->deps, key, true);
}
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+87 -26
View File
@@ -3,19 +3,40 @@
#include <xmmintrin.h>
#endif
#define GB_NO_DEFER
#define GB_IMPLEMENTATION
#include "gb/gb.h"
#include <wchar.h>
#include <stdio.h>
#include <math.h>
gbAllocator heap_allocator(void) {
return gb_heap_allocator();
}
#include "unicode.c"
#include "string.c"
#include "array.c"
#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;
@@ -31,8 +52,6 @@ gbAllocator scratch_allocator(void) {
return gb_scratch_allocator(&scratch_memory);
}
typedef struct DynamicArenaBlock DynamicArenaBlock;
typedef struct DynamicArena DynamicArena;
struct DynamicArenaBlock {
DynamicArenaBlock *prev;
@@ -224,27 +243,69 @@ f64 gb_sqrt(f64 x) {
} \
} while (0)
////////////////////////////////////////////////////////////////
//
// Generic Data Structures
//
////////////////////////////////////////////////////////////////
typedef Array(i32) Array_i32;
typedef Array(isize) Array_isize;
#define MAP_TYPE String
#define MAP_PROC map_string_
#define MAP_NAME MapString
#include "map.c"
#if defined(GB_SYSTEM_WINDOWS)
#define MAP_TYPE bool
#define MAP_PROC map_bool_
#define MAP_NAME MapBool
#include "map.c"
wchar_t **command_line_to_wargv(wchar_t *cmd_line, int *_argc) {
u32 i, j;
#define MAP_TYPE isize
#define MAP_PROC map_isize_
#define MAP_NAME MapIsize
#include "map.c"
u32 len = 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));
wchar_t *_argv = cast(wchar_t *)((cast(u8 *)argv)+i);
u32 argc = 0;
argv[argc] = _argv;
bool in_quote = false;
bool in_text = false;
bool in_space = true;
i = 0;
j = 0;
for (;;) {
wchar_t a = cmd_line[i];
if (a == 0) {
break;
}
if (in_quote) {
if (a == '\"') {
in_quote = false;
} else {
_argv[j++] = a;
}
} else {
switch (a) {
case '\"':
in_quote = true;
in_text = true;
if (in_space) argv[argc++] = _argv+j;
in_space = false;
break;
case ' ':
case '\t':
case '\n':
case '\r':
if (in_text) _argv[j++] = '\0';
in_text = false;
in_space = true;
break;
default:
in_text = true;
if (in_space) argv[argc++] = _argv+j;
_argv[j++] = a;
in_space = false;
break;
}
}
i++;
}
_argv[j] = '\0';
argv[argc] = NULL;
if (_argc) *_argc = argc;
return argv;
}
#endif
+136
View File
@@ -0,0 +1,136 @@
// Generates Documentation
gbString expr_to_string(AstNode *expression);
String alloc_comment_group_string(gbAllocator a, CommentGroup g) {
isize len = 0;
for_array(i, g.list) {
String comment = g.list[i].string;
len += comment.len;
len += 1; // for \n
}
if (len == 0) {
return make_string(NULL, 0);
}
u8 *text = gb_alloc_array(a, u8, len+1);
len = 0;
for_array(i, g.list) {
String comment = g.list[i].string;
if (comment[1] == '/') {
comment.text += 2;
comment.len -= 2;
} else if (comment[1] == '*') {
comment.text += 2;
comment.len -= 4;
}
comment = string_trim_whitespace(comment);
gb_memmove(text+len, comment.text, comment.len);
len += comment.len;
text[len++] = '\n';
}
return make_string(text, len);
}
void print_type_spec(AstNode *spec) {
ast_node(ts, TypeSpec, spec);
GB_ASSERT(ts->name->kind == AstNode_Ident);
String name = ts->name->Ident.string;
if (name.len == 0) {
return;
}
if (name[0] == '_') {
return;
}
gb_printf("type %.*s\n", LIT(name));
}
void print_proc_decl(AstNodeProcDecl *pd) {
GB_ASSERT(pd->name->kind == AstNode_Ident);
String name = pd->name->Ident.string;
if (name.len == 0) {
return;
}
if (name[0] == '_') {
return;
}
String docs = alloc_comment_group_string(heap_allocator(), pd->docs);
defer (gb_free(heap_allocator(), docs.text));
if (docs.len > 0) {
gb_file_write(&gb__std_files[gbFileStandard_Output], docs.text, docs.len);
} else {
return;
}
ast_node(proc_type, ProcType, pd->type);
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) {
ast_node(fl, FieldList, proc_type->results);
isize count = fl->list.count;
if (count > 0) {
gbString results = expr_to_string(proc_type->results);
defer (gb_string_free(results));
gb_printf(" -> ");
if (count != 1) {
gb_printf("(");
}
gb_printf("%s", results);
if (count != 1) {
gb_printf(")");
}
}
}
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;
}
}
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(decl_index, file->decls) {
AstNode *decl = file->decls[decl_index];
print_declaration(decl);
}
}
}
+47 -43
View File
@@ -1,6 +1,7 @@
typedef struct Scope Scope;
typedef struct Checker Checker;
typedef struct Type Type;
struct Scope;
struct Checker;
struct Type;
struct DeclInfo;
// typedef enum BuiltinProcId BuiltinProcId;
@@ -13,16 +14,15 @@ typedef struct Type Type;
ENTITY_KIND(Builtin) \
ENTITY_KIND(ImportName) \
ENTITY_KIND(LibraryName) \
ENTITY_KIND(Alias) \
ENTITY_KIND(Nil) \
ENTITY_KIND(Label)
typedef enum EntityKind {
enum EntityKind {
#define ENTITY_KIND(k) GB_JOIN2(Entity_, k),
ENTITY_KINDS
#undef ENTITY_KIND
Entity_Count,
} EntityKind;
};
String const entity_strings[] = {
#define ENTITY_KIND(k) {cast(u8 *)#k, gb_size_of(#k)-1},
@@ -30,35 +30,39 @@ String const entity_strings[] = {
#undef ENTITY_KIND
};
typedef enum EntityFlag {
EntityFlag_Visited = 1<<0,
EntityFlag_Used = 1<<1,
EntityFlag_Using = 1<<2,
EntityFlag_Field = 1<<3,
EntityFlag_Param = 1<<4,
EntityFlag_VectorElem = 1<<5,
EntityFlag_Ellipsis = 1<<6,
EntityFlag_NoAlias = 1<<7,
EntityFlag_TypeField = 1<<8,
EntityFlag_Value = 1<<9,
} EntityFlag;
enum EntityFlag {
EntityFlag_Visited = 1<<0,
EntityFlag_Used = 1<<1,
EntityFlag_Using = 1<<2,
EntityFlag_Field = 1<<3,
EntityFlag_Param = 1<<4,
EntityFlag_VectorElem = 1<<5,
EntityFlag_Ellipsis = 1<<6,
EntityFlag_NoAlias = 1<<7,
EntityFlag_TypeField = 1<<8,
EntityFlag_Value = 1<<9,
EntityFlag_Sret = 1<<10,
EntityFlag_BitFieldValue = 1<<11,
EntityFlag_CVarArg = 1<<20,
};
// Zero value means the overloading process is not yet done
typedef enum OverloadKind {
enum OverloadKind {
Overload_Unknown,
Overload_No,
Overload_Yes,
} OverloadKind;
};
typedef enum EntityAliasKind {
enum EntityAliasKind {
EntityAlias_Invalid,
EntityAlias_Type,
EntityAlias_Entity,
} EntityAliasKind;
};
// An Entity is a named "thing" in the language
typedef struct Entity Entity;
struct Entity {
EntityKind kind;
u64 id;
@@ -67,6 +71,7 @@ struct Entity {
Scope * scope;
Type * type;
AstNode * identifier; // Can be NULL
DeclInfo * parent_proc_decl; // NULL if in file/global scope
// TODO(bill): Cleanup how `using` works for entities
Entity * using_parent;
@@ -77,21 +82,27 @@ struct Entity {
ExactValue value;
} Constant;
struct {
i32 field_index;
i32 field_src_index;
bool is_immutable;
bool is_thread_local;
i32 field_index;
i32 field_src_index;
ExactValue default_value;
bool default_is_nil;
bool default_is_location;
bool is_immutable;
bool is_thread_local;
bool is_foreign;
Entity * foreign_library;
AstNode * foreign_library_ident;
} Variable;
struct {
bool is_type_alias;
} TypeName;
struct {
bool is_foreign;
String foreign_name;
Entity * foreign_library;
OverloadKind overload_kind;
String link_name;
u64 tags;
OverloadKind overload_kind;
bool is_foreign;
Entity * foreign_library;
AstNode * foreign_library_ident;
} Procedure;
struct {
i32 id;
@@ -107,10 +118,6 @@ struct Entity {
String name;
bool used;
} LibraryName;
struct {
EntityAliasKind kind;
Entity * original;
} Alias;
i32 Nil;
struct {
String name;
@@ -143,7 +150,7 @@ bool is_entity_exported(Entity *e) {
if (name.len == 0) {
return false;
}
return name.text[0] != '_';
return name[0] != '_';
}
gb_global u64 global_entity_id = 0;
@@ -169,6 +176,7 @@ Entity *make_entity_using_variable(gbAllocator a, Entity *parent, Token token, T
token.pos = parent->token.pos;
Entity *entity = alloc_entity(a, Entity_Variable, parent->scope, token, type);
entity->using_parent = parent;
entity->parent_proc_decl = parent->parent_proc_decl;
entity->flags |= EntityFlag_Using;
return entity;
}
@@ -240,13 +248,9 @@ Entity *make_entity_library_name(gbAllocator a, Scope *scope, Token token, Type
return entity;
}
Entity *make_entity_alias(gbAllocator a, Scope *scope, Token token, Type *type,
EntityAliasKind kind, Entity *original) {
Entity *entity = alloc_entity(a, Entity_Alias, scope, token, type);
entity->Alias.kind = kind;
entity->Alias.original = original;
return entity;
}
Entity *make_entity_nil(gbAllocator a, String name, Type *type) {
Token token = make_token_ident(name);
+102 -261
View File
@@ -3,17 +3,14 @@
// TODO(bill): Big numbers
// IMPORTANT TODO(bill): This needs to be completely fixed!!!!!!!!
typedef struct AstNode AstNode;
struct AstNode;
struct HashKey;
typedef struct Complex128 {
struct Complex128 {
f64 real, imag;
} Complex128;
};
typedef struct Quaternion256 {
f64 real, imag, jmag, kmag;
} Quaternion256;
typedef enum ExactValueKind {
enum ExactValueKind {
ExactValue_Invalid,
ExactValue_Bool,
@@ -21,26 +18,26 @@ typedef enum ExactValueKind {
ExactValue_Integer,
ExactValue_Float,
ExactValue_Complex,
ExactValue_Quaternion,
ExactValue_Pointer,
ExactValue_Compound, // TODO(bill): Is this good enough?
ExactValue_Count,
} ExactValueKind;
};
typedef struct ExactValue {
struct ExactValue {
ExactValueKind kind;
union {
bool value_bool;
String value_string;
i64 value_integer; // NOTE(bill): This must be an integer and not a pointer
i128 value_integer; // NOTE(bill): This must be an integer and not a pointer
f64 value_float;
i64 value_pointer;
Complex128 value_complex;
Quaternion256 value_quaternion;
AstNode * value_compound;
};
} ExactValue;
};
gb_global ExactValue const empty_exact_value = {};
HashKey hash_exact_value(ExactValue v) {
return hashing_proc(&v, gb_size_of(ExactValue));
@@ -66,11 +63,22 @@ ExactValue exact_value_string(String string) {
return result;
}
ExactValue exact_value_integer(i64 i) {
ExactValue exact_value_i64(i64 i) {
ExactValue result = {ExactValue_Integer};
result.value_integer = i128_from_i64(i);
return result;
}
ExactValue exact_value_i128(i128 i) {
ExactValue result = {ExactValue_Integer};
result.value_integer = i;
return result;
}
ExactValue exact_value_u128(u128 i) {
ExactValue result = {ExactValue_Integer};
result.value_integer = u128_to_i128(i);
return result;
}
ExactValue exact_value_float(f64 f) {
ExactValue result = {ExactValue_Float};
@@ -85,16 +93,6 @@ ExactValue exact_value_complex(f64 real, f64 imag) {
return result;
}
ExactValue exact_value_quaternion(f64 real, f64 imag, f64 jmag, f64 kmag) {
ExactValue result = {ExactValue_Quaternion};
result.value_quaternion.real = real;
result.value_quaternion.imag = imag;
result.value_quaternion.jmag = jmag;
result.value_quaternion.kmag = kmag;
return result;
}
ExactValue exact_value_pointer(i64 ptr) {
ExactValue result = {ExactValue_Pointer};
result.value_pointer = ptr;
@@ -103,43 +101,7 @@ ExactValue exact_value_pointer(i64 ptr) {
ExactValue exact_value_integer_from_string(String string) {
// TODO(bill): Allow for numbers with underscores in them
i32 base = 10;
bool has_prefix = false;
if (string.len > 2 && string.text[0] == '0') {
switch (string.text[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;
}
}
u8 *text = string.text;
isize len = string.len;
if (has_prefix) {
text += 2;
len -= 2;
}
i64 result = 0;
for (isize i = 0; i < len; i++) {
Rune r = cast(Rune)text[i];
if (r == '_') {
continue;
}
i64 v = 0;
v = digit_value(r);
if (v >= base) {
break;
}
result *= base;
result += v;
}
return exact_value_integer(result);
return exact_value_u128(u128_from_string(string));
}
f64 float_from_string(String string) {
@@ -155,6 +117,39 @@ f64 float_from_string(String string) {
i++;
}
#if 0
if (len-i > 2 &&
str[i] == '0' &&
str[i+1] == 'h') {
i += 2;
u8 *text = string.text;
isize len = string.len;
if (has_prefix) {
text += 2;
len -= 2;
}
u64 base = 16;
u64 result = {0};
for (isize i = 0; i < len; i++) {
Rune r = cast(Rune)text[i];
if (r == '_') {
continue;
}
u64 v = bit128__digit_value(r);
if (v >= base) {
break;
}
result *= base;
result += v;
}
return *cast(f64 *)&result;
}
#endif
f64 value = 0.0;
for (; i < len; i++) {
Rune r = cast(Rune)str[i];
@@ -232,21 +227,19 @@ ExactValue exact_value_from_basic_literal(Token token) {
case Token_Float: return exact_value_float_from_string(token.string);
case Token_Imag: {
String str = token.string;
Rune last_rune = cast(Rune)str.text[str.len-1];
Rune last_rune = cast(Rune)str[str.len-1];
str.len--; // Ignore the `i|j|k`
f64 imag = float_from_string(str);
switch (last_rune) {
case 'i': return exact_value_complex(0, imag);
case 'j': return exact_value_quaternion(0, 0, imag, 0);
case 'k': return exact_value_quaternion(0, 0, 0, imag);
if (last_rune == 'i') {
return exact_value_complex(0, imag);
}
}
case Token_Rune: {
Rune r = GB_RUNE_INVALID;
gb_utf8_decode(token.string.text, token.string.len, &r);
// gb_printf("%.*s rune: %d\n", LIT(token.string), r);
return exact_value_integer(r);
return exact_value_i64(r);
}
default:
GB_PANIC("Invalid token for basic literal");
@@ -262,15 +255,15 @@ ExactValue exact_value_to_integer(ExactValue v) {
case ExactValue_Integer:
return v;
case ExactValue_Float: {
i64 i = cast(i64)v.value_float;
f64 f = cast(f64)i;
i128 i = i128_from_f64(v.value_float);
f64 f = i128_to_f64(i);
if (f == v.value_float) {
return exact_value_integer(i);
return exact_value_i128(i);
}
} break;
case ExactValue_Pointer:
return exact_value_integer(cast(i64)cast(intptr)v.value_pointer);
return exact_value_i64(cast(i64)cast(intptr)v.value_pointer);
}
ExactValue r = {ExactValue_Invalid};
return r;
@@ -279,7 +272,7 @@ ExactValue exact_value_to_integer(ExactValue v) {
ExactValue exact_value_to_float(ExactValue v) {
switch (v.kind) {
case ExactValue_Integer:
return exact_value_float(cast(i64)v.value_integer);
return exact_value_float(i128_to_f64(v.value_integer));
case ExactValue_Float:
return v;
}
@@ -290,7 +283,7 @@ ExactValue exact_value_to_float(ExactValue v) {
ExactValue exact_value_to_complex(ExactValue v) {
switch (v.kind) {
case ExactValue_Integer:
return exact_value_complex(cast(i64)v.value_integer, 0);
return exact_value_complex(i128_to_f64(v.value_integer), 0);
case ExactValue_Float:
return exact_value_complex(v.value_float, 0);
case ExactValue_Complex:
@@ -301,22 +294,6 @@ ExactValue exact_value_to_complex(ExactValue v) {
}
ExactValue exact_value_to_quaternion(ExactValue v) {
switch (v.kind) {
case ExactValue_Integer:
return exact_value_quaternion(cast(i64)v.value_integer, 0, 0, 0);
case ExactValue_Float:
return exact_value_quaternion(v.value_float, 0, 0, 0);
case ExactValue_Complex:
return exact_value_quaternion(v.value_complex.real, v.value_complex.imag, 0, 0);
case ExactValue_Quaternion:
return v;
}
ExactValue r = {ExactValue_Invalid};
return r;
}
ExactValue exact_value_real(ExactValue v) {
switch (v.kind) {
case ExactValue_Integer:
@@ -324,8 +301,6 @@ ExactValue exact_value_real(ExactValue v) {
return v;
case ExactValue_Complex:
return exact_value_float(v.value_complex.real);
case ExactValue_Quaternion:
return exact_value_float(v.value_quaternion.real);
}
ExactValue r = {ExactValue_Invalid};
return r;
@@ -335,42 +310,14 @@ ExactValue exact_value_imag(ExactValue v) {
switch (v.kind) {
case ExactValue_Integer:
case ExactValue_Float:
return exact_value_integer(0);
return exact_value_i64(0);
case ExactValue_Complex:
return exact_value_float(v.value_complex.imag);
case ExactValue_Quaternion:
return exact_value_float(v.value_quaternion.imag);
}
ExactValue r = {ExactValue_Invalid};
return r;
}
ExactValue exact_value_jmag(ExactValue v) {
switch (v.kind) {
case ExactValue_Integer:
case ExactValue_Float:
case ExactValue_Complex:
return exact_value_integer(0);
case ExactValue_Quaternion:
return exact_value_float(v.value_quaternion.jmag);
}
ExactValue r = {ExactValue_Invalid};
return r;
}
ExactValue exact_value_kmag(ExactValue v) {
switch (v.kind) {
case ExactValue_Integer:
case ExactValue_Float:
case ExactValue_Complex:
return exact_value_integer(0);
case ExactValue_Quaternion:
return exact_value_float(v.value_quaternion.kmag);
}
ExactValue r = {ExactValue_Invalid};
return r;
}
ExactValue exact_value_make_imag(ExactValue v) {
switch (v.kind) {
case ExactValue_Integer:
@@ -383,31 +330,6 @@ ExactValue exact_value_make_imag(ExactValue v) {
ExactValue r = {ExactValue_Invalid};
return r;
}
ExactValue exact_value_make_jmag(ExactValue v) {
switch (v.kind) {
case ExactValue_Integer:
return exact_value_quaternion(0, 0, exact_value_to_float(v).value_float, 0);
case ExactValue_Float:
return exact_value_quaternion(0, 0, v.value_float, 0);
default:
GB_PANIC("Expected an integer or float type for `exact_value_make_jmag`");
}
ExactValue r = {ExactValue_Invalid};
return r;
}
ExactValue exact_value_make_kmag(ExactValue v) {
switch (v.kind) {
case ExactValue_Integer:
return exact_value_quaternion(0, 0, 0, exact_value_to_float(v).value_float);
case ExactValue_Float:
return exact_value_quaternion(0, 0, 0, v.value_float);
default:
GB_PANIC("Expected an integer or float type for `exact_value_make_kmag`");
}
ExactValue r = {ExactValue_Invalid};
return r;
}
ExactValue exact_unary_operator_value(TokenKind op, ExactValue v, i32 precision) {
@@ -418,7 +340,6 @@ ExactValue exact_unary_operator_value(TokenKind op, ExactValue v, i32 precision)
case ExactValue_Integer:
case ExactValue_Float:
case ExactValue_Complex:
case ExactValue_Quaternion:
return v;
}
} break;
@@ -442,18 +363,11 @@ ExactValue exact_unary_operator_value(TokenKind op, ExactValue v, i32 precision)
f64 imag = v.value_complex.imag;
return exact_value_complex(-real, -imag);
}
case ExactValue_Quaternion: {
f64 real = v.value_quaternion.real;
f64 imag = v.value_quaternion.imag;
f64 jmag = v.value_quaternion.jmag;
f64 kmag = v.value_quaternion.kmag;
return exact_value_quaternion(-real, -imag, -jmag, -kmag);
}
}
} break;
case Token_Xor: {
i64 i = 0;
i128 i = I128_ZERO;
switch (v.kind) {
case ExactValue_Invalid:
return v;
@@ -467,11 +381,11 @@ ExactValue exact_unary_operator_value(TokenKind op, ExactValue v, i32 precision)
// NOTE(bill): unsigned integers will be negative and will need to be
// limited to the types precision
// IMPORTANT NOTE(bill): Max precision is 64 bits as that's how integers are stored
if (0 < precision && precision < 64) {
i &= ~((~0ll)<<precision);
if (0 < precision && precision < 128) {
i = i & ~(I128_NEG_ONE << precision);
}
return exact_value_integer(i);
return exact_value_i128(i);
} break;
case Token_Not: {
@@ -486,7 +400,7 @@ ExactValue exact_unary_operator_value(TokenKind op, ExactValue v, i32 precision)
failure:
GB_PANIC("Invalid unary operation, %.*s", LIT(token_strings[op]));
ExactValue error_value = {0};
ExactValue error_value = {};
return error_value;
}
@@ -504,10 +418,8 @@ i32 exact_value_order(ExactValue v) {
return 3;
case ExactValue_Complex:
return 4;
case ExactValue_Quaternion:
return 5;
case ExactValue_Pointer:
return 6;
return 5;
default:
GB_PANIC("How'd you get here? Invalid Value.kind");
@@ -529,7 +441,6 @@ void match_exact_values(ExactValue *x, ExactValue *y) {
case ExactValue_Bool:
case ExactValue_String:
case ExactValue_Complex:
case ExactValue_Quaternion:
return;
case ExactValue_Integer:
@@ -538,13 +449,10 @@ void match_exact_values(ExactValue *x, ExactValue *y) {
return;
case ExactValue_Float:
// TODO(bill): Is this good enough?
*x = exact_value_float(cast(f64)x->value_integer);
*x = exact_value_float(i128_to_f64(x->value_integer));
return;
case ExactValue_Complex:
*x = exact_value_complex(cast(f64)x->value_integer, 0);
return;
case ExactValue_Quaternion:
*x = exact_value_quaternion(cast(f64)x->value_integer, 0, 0, 0);
*x = exact_value_complex(i128_to_f64(x->value_integer), 0);
return;
}
break;
@@ -556,9 +464,6 @@ void match_exact_values(ExactValue *x, ExactValue *y) {
case ExactValue_Complex:
*x = exact_value_to_complex(*x);
return;
case ExactValue_Quaternion:
*x = exact_value_to_quaternion(*x);
return;
}
break;
}
@@ -585,26 +490,27 @@ ExactValue exact_binary_operator_value(TokenKind op, ExactValue x, ExactValue y)
break;
case ExactValue_Integer: {
i64 a = x.value_integer;
i64 b = y.value_integer;
i64 c = 0;
i128 a = x.value_integer;
i128 b = y.value_integer;
i128 c = I128_ZERO;
switch (op) {
case Token_Add: c = a + b; break;
case Token_Sub: c = a - b; break;
case Token_Mul: c = a * b; break;
case Token_Quo: return exact_value_float(fmod(cast(f64)a, cast(f64)b));
case Token_QuoEq: c = a / b; break; // NOTE(bill): Integer division
case Token_Mod: c = a % b; break;
case Token_And: c = a & b; break;
case Token_Or: c = a | b; break;
case Token_Xor: c = a ^ b; break;
case Token_AndNot: c = a&(~b); break;
case Token_Shl: c = a << b; break;
case Token_Shr: c = a >> b; break;
case Token_Add: c = a + b; break;
case Token_Sub: c = a - b; break;
case Token_Mul: c = a * b; break;
case Token_Quo: return exact_value_float(fmod(i128_to_f64(a), i128_to_f64(b)));
case Token_QuoEq: c = a / b; break; // NOTE(bill): Integer division
case Token_Mod: c = a % b; break;
case Token_ModMod: c = ((a % b) + b) % b; break;
case Token_And: c = a & b; break;
case Token_Or: c = a | b; break;
case Token_Xor: c = a ^ b; break;
case Token_AndNot: c = i128_and_not(a, b); break;
case Token_Shl: c = a << i128_to_u64(b); break;
case Token_Shr: c = a >> i128_to_u64(b); break;
default: goto error;
}
return exact_value_integer(c);
return exact_value_i128(c);
} break;
case ExactValue_Float: {
@@ -649,58 +555,11 @@ ExactValue exact_binary_operator_value(TokenKind op, ExactValue x, ExactValue y)
}
return exact_value_complex(real, imag);
} break;
case ExactValue_Quaternion: {
y = exact_value_to_quaternion(y);
f64 a = x.value_quaternion.real;
f64 b = x.value_quaternion.imag;
f64 c = x.value_quaternion.jmag;
f64 d = x.value_quaternion.kmag;
f64 e = x.value_quaternion.real;
f64 f = x.value_quaternion.imag;
f64 g = x.value_quaternion.jmag;
f64 h = x.value_quaternion.kmag;
f64 real = 0;
f64 imag = 0;
f64 jmag = 0;
f64 kmag = 0;
switch (op) {
case Token_Add:
real = a + e;
imag = b + f;
jmag = c + g;
kmag = d + h;
break;
case Token_Sub:
real = a - e;
imag = b - f;
jmag = c - g;
kmag = d - h;
break;
case Token_Mul:
real = a*f + b*e + c*h - d*g;
imag = a*g - b*h + c*e + d*f;
jmag = a*h + b*g - c*f + d*e;
kmag = a*e - b*f - c*g - d*h;
break;
case Token_Quo: {
f64 s = e*e + f*f + g*g + h*h;
real = (+a*e + b*f + c*g + d*h)/s;
imag = (-a*f + b*e - c*h + d*h)/s;
jmag = (-a*g + b*h + c*e - d*f)/s;
kmag = (-a*h - b*g + c*f + d*e)/s;
} break;
default: goto error;
}
return exact_value_quaternion(real, imag, jmag, kmag);
} break;
}
error:
; // MSVC accepts this??? apparently you cannot declare variables immediately after labels...
ExactValue error_value = {0};
ExactValue error_value = {};
// gb_printf_err("Invalid binary operation: %s\n", token_kind_to_string(op));
return error_value;
}
@@ -731,8 +590,8 @@ bool compare_exact_values(TokenKind op, ExactValue x, ExactValue y) {
break;
case ExactValue_Integer: {
i64 a = x.value_integer;
i64 b = y.value_integer;
i128 a = x.value_integer;
i128 b = y.value_integer;
switch (op) {
case Token_CmpEq: return a == b;
case Token_NotEq: return a != b;
@@ -767,35 +626,17 @@ bool compare_exact_values(TokenKind op, ExactValue x, ExactValue y) {
}
} break;
case ExactValue_Quaternion: {
f64 a = x.value_quaternion.real;
f64 b = x.value_quaternion.imag;
f64 c = x.value_quaternion.jmag;
f64 d = x.value_quaternion.kmag;
f64 e = y.value_quaternion.real;
f64 f = y.value_quaternion.imag;
f64 g = y.value_quaternion.jmag;
f64 h = y.value_quaternion.kmag;
switch (op) {
case Token_CmpEq: return cmp_f64(a, e) == 0 && cmp_f64(b, f) == 0 && cmp_f64(c, g) == 0 && cmp_f64(d, h) == 0;
case Token_NotEq: return cmp_f64(a, e) != 0 || cmp_f64(b, f) != 0 || cmp_f64(c, g) != 0 || cmp_f64(d, h) != 0;
}
} break;
case ExactValue_String: {
String a = x.value_string;
String b = y.value_string;
isize len = gb_min(a.len, b.len);
// TODO(bill): gb_memcompare is used because the strings are UTF-8
switch (op) {
case Token_CmpEq: return gb_memcompare(a.text, b.text, len) == 0;
case Token_NotEq: return gb_memcompare(a.text, b.text, len) != 0;
case Token_Lt: return gb_memcompare(a.text, b.text, len) < 0;
case Token_LtEq: return gb_memcompare(a.text, b.text, len) <= 0;
case Token_Gt: return gb_memcompare(a.text, b.text, len) > 0;
case Token_GtEq: return gb_memcompare(a.text, b.text, len) >= 0;
case Token_CmpEq: return a == b;
case Token_NotEq: return a != b;
case Token_Lt: return a < b;
case Token_LtEq: return a <= b;
case Token_Gt: return a > b;
case Token_GtEq: return a >= b;
}
} break;
}
+13 -10
View File
@@ -164,11 +164,11 @@ extern "C" {
#endif
#ifndef GB_EDIAN_ORDER
#define GB_EDIAN_ORDER
#ifndef GB_ENDIAN_ORDER
#define GB_ENDIAN_ORDER
// TODO(bill): Is the a good way or is it better to test for certain compilers and macros?
#define GB_IS_BIG_EDIAN (!*(u8*)&(u16){1})
#define GB_IS_LITTLE_EDIAN (!GB_IS_BIG_EDIAN)
#define GB_IS_BIG_ENDIAN (!*(u8*)&(u16){1})
#define GB_IS_LITTLE_ENDIAN (!GB_IS_BIG_ENDIAN)
#endif
#if defined(_WIN32) || defined(_WIN64)
@@ -3602,7 +3602,7 @@ extern "C" {
#endif
void gb_assert_handler(char const *condition, char const *file, i32 line, char const *msg, ...) {
gb_printf_err("%s:%d: Assert Failure: ", file, line);
gb_printf_err("%s(%d): Assert Failure: ", file, line);
if (condition)
gb_printf_err( "`%s` ", condition);
if (msg) {
@@ -6384,20 +6384,23 @@ gb_global char const gb__num_to_char_table[] =
gb_inline void gb_i64_to_str(i64 value, char *string, i32 base) {
char *buf = string;
b32 negative = false;
u64 v;
if (value < 0) {
negative = true;
value = -value;
}
if (value) {
while (value > 0) {
*buf++ = gb__num_to_char_table[value % base];
value /= base;
v = cast(u64)value;
if (v != 0) {
while (v > 0) {
*buf++ = gb__num_to_char_table[v % base];
v /= base;
}
} else {
*buf++ = '0';
}
if (negative)
if (negative) {
*buf++ = '-';
}
*buf = '\0';
gb_strrev(string);
}
+726
View File
@@ -0,0 +1,726 @@
#if defined(GB_COMPILER_MSVC) && defined(GB_ARCH_64_BIT) && defined(GB_CPU_X86)
#define MSVC_AMD64_INTRINSICS
#include <intrin.h>
#pragma intrinsic(_mul128)
#endif
#define BIT128_U64_HIGHBIT 0x8000000000000000ull
#define BIT128_U64_BITS62 0x7fffffffffffffffull
#define BIT128_U64_ALLBITS 0xffffffffffffffffull
typedef struct u128 { u64 lo; u64 hi; } u128;
typedef struct i128 { u64 lo; i64 hi; } i128;
static u128 const U128_ZERO = {0, 0};
static u128 const U128_ONE = {1, 0};
static i128 const I128_ZERO = {0, 0};
static i128 const I128_ONE = {1, 0};
static u128 const U128_NEG_ONE = {BIT128_U64_ALLBITS, BIT128_U64_ALLBITS};
static i128 const I128_NEG_ONE = {BIT128_U64_ALLBITS, cast(i64)BIT128_U64_ALLBITS};
u128 u128_lo_hi (u64 lo, u64 hi);
u128 u128_from_u32 (u32 u);
u128 u128_from_u64 (u64 u);
u128 u128_from_i64 (i64 u);
u128 u128_from_f32 (f32 f);
u128 u128_from_f64 (f64 f);
u128 u128_from_string(String string);
i128 i128_lo_hi (u64 lo, i64 hi);
i128 i128_from_u32 (u32 u);
i128 i128_from_u64 (u64 u);
i128 i128_from_i64 (i64 u);
i128 i128_from_f32 (f32 f);
i128 i128_from_f64 (f64 f);
i128 i128_from_string(String string);
u64 u128_to_u64(u128 a);
i64 u128_to_i64(u128 a);
f64 u128_to_f64(u128 a);
i128 u128_to_i128(u128 a);
u64 i128_to_u64(i128 a);
i64 i128_to_i64(i128 a);
f64 i128_to_f64(i128 a);
u128 i128_to_u128(i128 a);
String u128_to_string(u128 a, char *buf, isize len);
String i128_to_string(i128 a, char *buf, isize len);
i32 u128_cmp (u128 a, u128 b);
bool u128_eq (u128 a, u128 b);
bool u128_ne (u128 a, u128 b);
bool u128_lt (u128 a, u128 b);
bool u128_gt (u128 a, u128 b);
bool u128_le (u128 a, u128 b);
bool u128_ge (u128 a, u128 b);
u128 u128_add (u128 a, u128 b);
u128 u128_not (u128 a);
u128 u128_neg (u128 a);
u128 u128_sub (u128 a, u128 b);
u128 u128_and (u128 a, u128 b);
u128 u128_or (u128 a, u128 b);
u128 u128_xor (u128 a, u128 b);
u128 u128_and_not(u128 a, u128 b);
u128 u128_shl (u128 a, u32 n);
u128 u128_shr (u128 a, u32 n);
u128 u128_mul (u128 a, u128 b);
void u128_divide (u128 num, u128 den, u128 *quo, u128 *rem);
u128 u128_quo (u128 a, u128 b);
u128 u128_mod (u128 a, u128 b);
i128 i128_abs (i128 a);
i32 i128_cmp (i128 a, i128 b);
bool i128_eq (i128 a, i128 b);
bool i128_ne (i128 a, i128 b);
bool i128_lt (i128 a, i128 b);
bool i128_gt (i128 a, i128 b);
bool i128_le (i128 a, i128 b);
bool i128_ge (i128 a, i128 b);
i128 i128_add (i128 a, i128 b);
i128 i128_not (i128 a);
i128 i128_neg (i128 a);
i128 i128_sub (i128 a, i128 b);
i128 i128_and (i128 a, i128 b);
i128 i128_or (i128 a, i128 b);
i128 i128_xor (i128 a, i128 b);
i128 i128_and_not(i128 a, i128 b);
i128 i128_shl (i128 a, u32 n);
i128 i128_shr (i128 a, u32 n);
i128 i128_mul (i128 a, i128 b);
void i128_divide (i128 num, i128 den, i128 *quo, i128 *rem);
i128 i128_quo (i128 a, i128 b);
i128 i128_mod (i128 a, i128 b);
bool operator==(u128 a, u128 b) { return u128_eq(a, b); }
bool operator!=(u128 a, u128 b) { return u128_ne(a, b); }
bool operator< (u128 a, u128 b) { return u128_lt(a, b); }
bool operator> (u128 a, u128 b) { return u128_gt(a, b); }
bool operator<=(u128 a, u128 b) { return u128_le(a, b); }
bool operator>=(u128 a, u128 b) { return u128_ge(a, b); }
u128 operator+(u128 a, u128 b) { return u128_add(a, b); }
u128 operator-(u128 a, u128 b) { return u128_sub(a, b); }
u128 operator*(u128 a, u128 b) { return u128_mul(a, b); }
u128 operator/(u128 a, u128 b) { return u128_quo(a, b); }
u128 operator%(u128 a, u128 b) { return u128_mod(a, b); }
u128 operator&(u128 a, u128 b) { return u128_and(a, b); }
u128 operator|(u128 a, u128 b) { return u128_or (a, b); }
u128 operator^(u128 a, u128 b) { return u128_xor(a, b); }
u128 operator~(u128 a) { return u128_not(a); }
u128 operator+(u128 a) { return a; }
u128 operator-(u128 a) { return u128_neg(a); }
u128 operator<<(u128 a, u32 b) { return u128_shl(a, b); }
u128 operator>>(u128 a, u32 b) { return u128_shr(a, b); }
bool operator==(i128 a, i128 b) { return i128_eq(a, b); }
bool operator!=(i128 a, i128 b) { return i128_ne(a, b); }
bool operator< (i128 a, i128 b) { return i128_lt(a, b); }
bool operator> (i128 a, i128 b) { return i128_gt(a, b); }
bool operator<=(i128 a, i128 b) { return i128_le(a, b); }
bool operator>=(i128 a, i128 b) { return i128_ge(a, b); }
i128 operator+(i128 a, i128 b) { return i128_add(a, b); }
i128 operator-(i128 a, i128 b) { return i128_sub(a, b); }
i128 operator*(i128 a, i128 b) { return i128_mul(a, b); }
i128 operator/(i128 a, i128 b) { return i128_quo(a, b); }
i128 operator%(i128 a, i128 b) { return i128_mod(a, b); }
i128 operator&(i128 a, i128 b) { return i128_and(a, b); }
i128 operator|(i128 a, i128 b) { return i128_or (a, b); }
i128 operator^(i128 a, i128 b) { return i128_xor(a, b); }
i128 operator~(i128 a) { return i128_not(a); }
i128 operator+(i128 a) { return a; }
i128 operator-(i128 a) { return i128_neg(a); }
i128 operator<<(i128 a, u32 b) { return i128_shl(a, b); }
i128 operator>>(i128 a, u32 b) { return i128_shr(a, b); }
////////////////////////////////////////////////////////////////
u64 bit128__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
}
u128 u128_lo_hi(u64 lo, u64 hi) {
u128 r = {};
r.lo = lo;
r.hi = hi;
return r;
}
u128 u128_from_u32(u32 u) { return u128_lo_hi(cast(u64)u, 0); }
u128 u128_from_u64(u64 u) { return u128_lo_hi(cast(u64)u, 0); }
u128 u128_from_i64(i64 u) { return u128_lo_hi(cast(u64)u, u < 0 ? -1 : 0); }
u128 u128_from_f32(f32 f) { return u128_lo_hi(cast(u64)f, 0); }
u128 u128_from_f64(f64 f) { return u128_lo_hi(cast(u64)f, 0); }
u128 u128_from_string(String string) {
// TODO(bill): Allow for numbers with underscores in them
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;
}
}
u8 *text = string.text;
isize len = string.len;
if (has_prefix) {
text += 2;
len -= 2;
}
u128 base_ = u128_from_u64(base);
u128 result = {0};
for (isize i = 0; i < len; i++) {
Rune r = cast(Rune)text[i];
if (r == '_') {
continue;
}
u64 v = bit128__digit_value(r);
if (v >= base) {
break;
}
result = u128_mul(result, base_);
result = u128_add(result, u128_from_u64(v));
}
return result;
}
i128 i128_lo_hi(u64 lo, i64 hi) {
i128 i;
i.lo = lo;
i.hi = hi;
return i;
}
i128 i128_from_u32(u32 u) { return i128_lo_hi(cast(u64)u, 0); }
i128 i128_from_u64(u64 u) { return i128_lo_hi(cast(u64)u, 0); }
i128 i128_from_i64(i64 u) { return i128_lo_hi(cast(u64)u, u < 0 ? -1 : 0); }
i128 i128_from_f32(f32 f) { return i128_lo_hi(cast(u64)f, 0); }
i128 i128_from_f64(f64 f) { return i128_lo_hi(cast(u64)f, 0); }
i128 i128_from_string(String string) {
// TODO(bill): Allow for numbers with underscores in them
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;
}
}
u8 *text = string.text;
isize len = string.len;
if (has_prefix) {
text += 2;
len -= 2;
}
i128 base_ = i128_from_u64(base);
i128 result = {0};
for (isize i = 0; i < len; i++) {
Rune r = cast(Rune)text[i];
if (r == '_') {
continue;
}
u64 v = bit128__digit_value(r);
if (v >= base) {
break;
}
result = i128_mul(result, base_);
result = i128_add(result, i128_from_u64(v));
}
return result;
}
u64 u128_to_u64(u128 a) {
return (a.lo&BIT128_U64_BITS62) | (a.hi&BIT128_U64_HIGHBIT);
}
i64 u128_to_i64(u128 a) {
return a.lo;
}
f64 u128_to_f64(u128 a) {
if (a.hi >= 0) {
return (cast(f64)a.hi * 18446744073709551616.0) + cast(f64)a.lo;
}
i64 h = cast(i64)a.hi;
u64 l = a.lo;
h = ~h;
l = ~l;
l += 1;
if (l == 0) {
h += 1;
}
return -((cast(f64)h * 18446744073709551616.0) + cast(f64)l);
}
i128 u128_to_i128(u128 a) {
return *cast(i128 *)&a;
}
u64 i128_to_u64(i128 a) {
return (a.lo&BIT128_U64_BITS62) | (a.hi&BIT128_U64_HIGHBIT);
}
i64 i128_to_i64(i128 a) {
return cast(i64)a.lo;
}
f64 i128_to_f64(i128 a) {
if (a.hi >= 0) {
return (cast(f64)a.hi * 18446744073709551616.0) + cast(f64)a.lo;
}
i64 h = a.hi;
u64 l = a.lo;
h = ~h;
l = ~l;
l += 1;
if (l == 0) {
h += 1;
}
return -((cast(f64)h * 18446744073709551616.0) + cast(f64)l);
}
u128 i128_to_u128(i128 a) {
return *cast(u128 *)&a;
}
String u128_to_string(u128 v, char *out_buf, isize out_buf_len) {
char buf[200] = {0};
isize i = gb_size_of(buf);
u128 b = u128_from_u64(10);;
while (u128_ge(v, b)) {
buf[--i] = gb__num_to_char_table[u128_to_i64(u128_mod(v, b))];
v = u128_quo(v, b);
}
buf[--i] = gb__num_to_char_table[u128_to_i64(u128_mod(v, b))];
isize len = gb_min(gb_size_of(buf)-i, out_buf_len);
gb_memcopy(out_buf, &buf[i], len);
return make_string(cast(u8 *)out_buf, len);
}
String i128_to_string(i128 a, char *out_buf, isize out_buf_len) {
char buf[200] = {0};
isize i = gb_size_of(buf);
bool negative = false;
if (i128_lt(a, I128_ZERO)) {
negative = true;
a = i128_neg(a);
}
u128 v = *cast(u128 *)&a;
u128 b = u128_from_u64(10);;
while (u128_ge(v, b)) {
buf[--i] = gb__num_to_char_table[u128_to_i64(u128_mod(v, b))];
v = u128_quo(v, b);
}
buf[--i] = gb__num_to_char_table[u128_to_i64(u128_mod(v, b))];
if (negative) {
buf[--i] = '-';
}
isize len = gb_min(gb_size_of(buf)-i, out_buf_len);
gb_memcopy(out_buf, &buf[i], len);
return make_string(cast(u8 *)out_buf, len);
}
////////////////////////////////////////////////////////////////
i32 u128_cmp(u128 a, u128 b) {
if (a.hi == b.hi && b.lo == b.lo) {
return 0;
}
if (a.hi == b.hi) {
return a.lo < b.lo ? -1 : +1;
}
return a.hi < b.hi ? -1 : +1;
}
bool u128_eq(u128 a, u128 b) { return a.hi == b.hi && a.lo == b.lo; }
bool u128_ne(u128 a, u128 b) { return !u128_eq(a, b); }
bool u128_lt(u128 a, u128 b) { return a.hi == b.hi ? a.lo < b.lo : a.hi < b.hi; }
bool u128_gt(u128 a, u128 b) { return a.hi == b.hi ? a.lo > b.lo : a.hi > b.hi; }
bool u128_le(u128 a, u128 b) { return !u128_gt(a, b); }
bool u128_ge(u128 a, u128 b) { return !u128_lt(a, b); }
u128 u128_add(u128 a, u128 b) {
u128 old_a = a;
a.lo += b.lo;
a.hi += b.hi;
if (a.lo < old_a.lo) {
a.hi += 1;
}
return a;
}
u128 u128_not(u128 a) { return u128_lo_hi(~a.lo, ~a.hi); }
u128 u128_neg(u128 a) {
return u128_add(u128_not(a), u128_from_u64(1));
}
u128 u128_sub(u128 a, u128 b) {
return u128_add(a, u128_neg(b));
}
u128 u128_and(u128 a, u128 b) { return u128_lo_hi(a.lo&b.lo, a.hi&b.hi); }
u128 u128_or (u128 a, u128 b) { return u128_lo_hi(a.lo|b.lo, a.hi|b.hi); }
u128 u128_xor(u128 a, u128 b) { return u128_lo_hi(a.lo^b.lo, a.hi^b.hi); }
u128 u128_and_not(u128 a, u128 b) { return u128_lo_hi(a.lo&(~b.lo), a.hi&(~b.hi)); }
u128 u128_shl(u128 a, u32 n) {
if (n >= 128) {
return u128_lo_hi(0, 0);
}
#if 0 && defined(MSVC_AMD64_INTRINSICS)
a.hi = __shiftleft128(a.lo, a.hi, n);
a.lo = a.lo << n;
return a;
#else
if (n >= 64) {
n -= 64;
a.hi = a.lo;
a.lo = 0;
}
if (n != 0) {
u64 mask = ~(BIT128_U64_ALLBITS >> n);
a.hi <<= n;
a.hi |= (a.lo&mask) >> (64 - n);
a.lo <<= n;
}
return a;
#endif
}
u128 u128_shr(u128 a, u32 n) {
if (n >= 128) {
return u128_lo_hi(0, 0);
}
#if 0 && defined(MSVC_AMD64_INTRINSICS)
a.lo = __shiftright128(a.lo, a.hi, n);
a.hi = a.hi >> n;
return a;
#else
if (n >= 64) {
n -= 64;
a.lo = a.hi;
a.hi = 0;
}
if (n != 0) {
u64 mask = ~(BIT128_U64_ALLBITS << n);
a.lo >>= n;
a.lo |= (a.hi&mask) << (64 - n);
a.hi >>= n;
}
return a;
#endif
}
u128 u128_mul(u128 a, u128 b) {
if (a.lo == 0 && a.hi == 0) {
return u128_from_u64(0);
} else if (b.lo == 0 && b.hi == 0) {
return u128_from_u64(0);
}
if (u128_eq(a, U128_ONE)) {
return b;
}
if (u128_eq(b, U128_ONE)) {
return a;
}
#if defined(MSVC_AMD64_INTRINSICS)
if (a.hi == 0 && b.hi == 0) {
a.lo = _umul128(a.lo, b.lo, &a.hi);
return a;
}
#endif
u128 res = {0};
u128 t = b;
for (u32 i = 0; i < 128; i++) {
if ((t.lo&1) != 0) {
res = u128_add(res, u128_shl(a, i));
}
t = u128_shr(t, 1);
}
return res;
}
bool u128_hibit(u128 *d) { return (d->hi & BIT128_U64_HIGHBIT) != 0; }
void u128_divide(u128 num, u128 den, u128 *quo, u128 *rem) {
if (u128_eq(den, U128_ZERO)) {
if (quo) *quo = u128_from_u64(num.lo/den.lo);
if (rem) *rem = U128_ZERO;
} else {
u128 n = num;
u128 d = den;
u128 x = U128_ONE;
u128 r = U128_ZERO;
while (u128_ge(n, d) && !u128_hibit(&d)) {
x = u128_shl(x, 1);
d = u128_shl(d, 1);
}
while (u128_ne(x, U128_ZERO)) {
if (u128_ge(n, d)) {
n = u128_sub(n, d);
r = u128_or(r, x);
}
x = u128_shr(x, 1);
d = u128_shr(d, 1);
}
if (quo) *quo = r;
if (rem) *rem = n;
}
}
u128 u128_quo(u128 a, u128 b) {
if (a.hi == 0 && b.hi == 0) {
return u128_from_u64(a.lo/b.lo);
}
u128 res = {0};
u128_divide(a, b, &res, NULL);
return res;
}
u128 u128_mod(u128 a, u128 b) {
if (a.hi == 0 && b.hi == 0) {
return u128_from_u64(a.lo%b.lo);
}
u128 res = {0};
u128_divide(a, b, NULL, &res);
return res;
}
////////////////////////////////////////////////////////////////
i128 i128_abs(i128 a) {
if ((a.hi&BIT128_U64_HIGHBIT) != 0) {
return i128_neg(a);
}
return a;
}
i32 i128_cmp(i128 a, i128 b) {
if (a.hi == b.hi && b.lo == b.lo) {
return 0;
}
if (a.hi == b.hi) {
return a.lo < b.lo ? -1 : +1;
}
return a.hi < b.hi ? -1 : +1;
}
bool i128_eq(i128 a, i128 b) { return a.hi == b.hi && a.lo == b.lo; }
bool i128_ne(i128 a, i128 b) { return !i128_eq(a, b); }
bool i128_lt(i128 a, i128 b) { return a.hi == b.hi ? a.lo < b.lo : a.hi < b.hi; }
bool i128_gt(i128 a, i128 b) { return a.hi == b.hi ? a.lo > b.lo : a.hi > b.hi; }
bool i128_le(i128 a, i128 b) { return a.hi == b.hi ? a.lo <= b.lo : a.hi <= b.hi; }
bool i128_ge(i128 a, i128 b) { return a.hi == b.hi ? a.lo >= b.lo : a.hi >= b.hi; }
i128 i128_add(i128 a, i128 b) {
i128 old_a = a;
a.lo += b.lo;
a.hi += b.hi;
if (a.lo < old_a.lo) {
a.hi += 1;
}
return a;
}
i128 i128_not(i128 a) { return i128_lo_hi(~a.lo, ~a.hi); }
i128 i128_neg(i128 a) {
return i128_add(i128_not(a), i128_from_u64(1));
}
i128 i128_sub(i128 a, i128 b) {
return i128_add(a, i128_neg(b));
}
i128 i128_and(i128 a, i128 b) { return i128_lo_hi(a.lo&b.lo, a.hi&b.hi); }
i128 i128_or (i128 a, i128 b) { return i128_lo_hi(a.lo|b.lo, a.hi|b.hi); }
i128 i128_xor(i128 a, i128 b) { return i128_lo_hi(a.lo^b.lo, a.hi^b.hi); }
i128 i128_and_not(i128 a, i128 b) { return i128_lo_hi(a.lo&(~b.lo), a.hi&(~b.hi)); }
i128 i128_shl(i128 a, u32 n) {
if (n >= 128) {
return i128_lo_hi(0, 0);
}
#if 0 && defined(MSVC_AMD64_INTRINSICS)
a.hi = __shiftleft128(a.lo, a.hi, n);
a.lo = a.lo << n;
return a;
#else
if (n >= 64) {
n -= 64;
a.hi = a.lo;
a.lo = 0;
}
if (n != 0) {
u64 mask = ~(BIT128_U64_ALLBITS >> n);
a.hi <<= n;
a.hi |= (a.lo&mask) >> (64 - n);
a.lo <<= n;
}
return a;
#endif
}
i128 i128_shr(i128 a, u32 n) {
if (n >= 128) {
return i128_lo_hi(0, 0);
}
#if 0 && defined(MSVC_AMD64_INTRINSICS)
a.lo = __shiftright128(a.lo, a.hi, n);
a.hi = a.hi >> n;
return a;
#else
if (n >= 64) {
n -= 64;
a.lo = a.hi;
a.hi = 0;
}
if (n != 0) {
u64 mask = ~(BIT128_U64_ALLBITS << n);
a.lo >>= n;
a.lo |= (a.hi&mask) << (64 - n);
a.hi >>= n;
}
return a;
#endif
}
i128 i128_mul(i128 a, i128 b) {
if (a.lo == 0 && a.hi == 0) {
return i128_from_u64(0);
} else if (b.lo == 0 && b.hi == 0) {
return i128_from_u64(0);
}
if (i128_eq(a, I128_ONE)) {
return b;
}
if (i128_eq(b, I128_ONE)) {
return a;
}
#if defined(MSVC_AMD64_INTRINSICS)
if (a.hi == 0 && b.hi == 0) {
a.lo = _mul128(a.lo, b.lo, &a.hi);
return a;
}
#endif
i128 res = {0};
i128 t = b;
for (u32 i = 0; i < 128; i++) {
if ((t.lo&1) != 0) {
res = i128_add(res, i128_shl(a, i));
}
t = i128_shr(t, 1);
}
return res;
}
void i128_divide(i128 a, i128 b, i128 *quo, i128 *rem) {
// TODO(bill): Which one is correct?!
#if 1
i128 s = i128_shr(b, 127);
b = i128_sub(i128_xor(b, s), s);
s = i128_shr(a, 127);
b = i128_sub(i128_xor(a, s), s);
u128 n, r = {0};
u128_divide(*cast(u128 *)&a, *cast(u128 *)&b, &n, &r);
i128 ni = *cast(i128 *)&n;
i128 ri = *cast(i128 *)&r;
if (quo) *quo = i128_sub(i128_xor(ni, s), s);
if (rem) *rem = i128_sub(i128_xor(ri, s), s);
#else
if (i128_eq(b, I128_ZERO)) {
if (quo) *quo = i128_from_u64(a.lo/b.lo);
if (rem) *rem = I128_ZERO;
} else {
i128 n = a;
i128 d = b;
i128 x = I128_ONE;
i128 r = I128_ZERO;
while (i128_ge(n, d) && ((i128_shr(d, 128-1).lo&1) == 0)) {
x = i128_shl(x, 1);
d = i128_shl(d, 1);
}
while (i128_ne(x, I128_ZERO)) {
if (i128_ge(n, d)) {
n = i128_sub(n, d);
r = i128_or(r, x);
}
x = i128_shr(x, 1);
d = i128_shr(d, 1);
}
if (quo) *quo = r;
if (rem) *rem = n;
}
#endif
}
i128 i128_quo(i128 a, i128 b) {
i128 res = {0};
i128_divide(a, b, &res, NULL);
return res;
}
i128 i128_mod(i128 a, i128 b) {
i128 res = {0};
i128_divide(a, b, NULL, &res);
return res;
}
+2002 -1655
View File
File diff suppressed because it is too large Load Diff
+46 -43
View File
@@ -1,6 +1,6 @@
// Optimizations for the IR code
void ir_opt_add_operands(irValueArray *ops, irInstr *i) {
void ir_opt_add_operands(Array<irValue *> *ops, irInstr *i) {
switch (i->kind) {
case irInstr_Comment:
break;
@@ -48,7 +48,7 @@ void ir_opt_add_operands(irValueArray *ops, irInstr *i) {
break;
case irInstr_Phi:
for_array(j, i->Phi.edges) {
array_add(ops, i->Phi.edges.e[j]);
array_add(ops, i->Phi.edges[j]);
}
break;
case irInstr_Unreachable:
@@ -80,6 +80,8 @@ void ir_opt_add_operands(irValueArray *ops, irInstr *i) {
// break;
case irInstr_StartupRuntime:
break;
#if 0
case irInstr_BoundsCheck:
array_add(ops, i->BoundsCheck.index);
array_add(ops, i->BoundsCheck.len);
@@ -88,6 +90,7 @@ void ir_opt_add_operands(irValueArray *ops, irInstr *i) {
array_add(ops, i->SliceBoundsCheck.low);
array_add(ops, i->SliceBoundsCheck.high);
break;
#endif
}
}
@@ -97,24 +100,24 @@ void ir_opt_add_operands(irValueArray *ops, irInstr *i) {
void ir_opt_block_replace_pred(irBlock *b, irBlock *from, irBlock *to) {
for_array(i, b->preds) {
irBlock *pred = b->preds.e[i];
irBlock *pred = b->preds[i];
if (pred == from) {
b->preds.e[i] = to;
b->preds[i] = to;
}
}
}
void ir_opt_block_replace_succ(irBlock *b, irBlock *from, irBlock *to) {
for_array(i, b->succs) {
irBlock *succ = b->succs.e[i];
irBlock *succ = b->succs[i];
if (succ == from) {
b->succs.e[i] = to;
b->succs[i] = to;
}
}
}
bool ir_opt_block_has_phi(irBlock *b) {
return b->instrs.e[0]->Instr.kind == irInstr_Phi;
return b->instrs[0]->Instr.kind == irInstr_Phi;
}
@@ -126,10 +129,10 @@ bool ir_opt_block_has_phi(irBlock *b) {
irValueArray ir_get_block_phi_nodes(irBlock *b) {
irValueArray phis = {0};
Array<irValue *> ir_get_block_phi_nodes(irBlock *b) {
Array<irValue *> phis = {0};
for_array(i, b->instrs) {
irInstr *instr = &b->instrs.e[i]->Instr;
irInstr *instr = &b->instrs[i]->Instr;
if (instr->kind != irInstr_Phi) {
phis = b->instrs;
phis.count = i;
@@ -140,22 +143,22 @@ irValueArray ir_get_block_phi_nodes(irBlock *b) {
}
void ir_remove_pred(irBlock *b, irBlock *p) {
irValueArray phis = ir_get_block_phi_nodes(b);
Array<irValue *> phis = ir_get_block_phi_nodes(b);
isize i = 0;
for_array(j, b->preds) {
irBlock *pred = b->preds.e[j];
irBlock *pred = b->preds[j];
if (pred != p) {
b->preds.e[i] = b->preds.e[j];
b->preds[i] = b->preds[j];
for_array(k, phis) {
irInstrPhi *phi = &phis.e[k]->Instr.Phi;
phi->edges.e[i] = phi->edges.e[j];
irInstrPhi *phi = &phis[k]->Instr.Phi;
phi->edges[i] = phi->edges[j];
}
i++;
}
}
b->preds.count = i;
for_array(k, phis) {
irInstrPhi *phi = &phis.e[k]->Instr.Phi;
irInstrPhi *phi = &phis[k]->Instr.Phi;
phi->edges.count = i;
}
@@ -164,13 +167,13 @@ void ir_remove_pred(irBlock *b, irBlock *p) {
void ir_remove_dead_blocks(irProcedure *proc) {
isize j = 0;
for_array(i, proc->blocks) {
irBlock *b = proc->blocks.e[i];
irBlock *b = proc->blocks[i];
if (b == NULL) {
continue;
}
// NOTE(bill): Swap order
b->index = j;
proc->blocks.e[j++] = b;
proc->blocks[j++] = b;
}
proc->blocks.count = j;
}
@@ -180,7 +183,7 @@ void ir_mark_reachable(irBlock *b) {
isize const BLACK = -1;
b->index = BLACK;
for_array(i, b->succs) {
irBlock *succ = b->succs.e[i];
irBlock *succ = b->succs[i];
if (succ->index == WHITE) {
ir_mark_reachable(succ);
}
@@ -191,23 +194,23 @@ void ir_remove_unreachable_blocks(irProcedure *proc) {
isize const WHITE = 0;
isize const BLACK = -1;
for_array(i, proc->blocks) {
proc->blocks.e[i]->index = WHITE;
proc->blocks[i]->index = WHITE;
}
ir_mark_reachable(proc->blocks.e[0]);
ir_mark_reachable(proc->blocks[0]);
for_array(i, proc->blocks) {
irBlock *b = proc->blocks.e[i];
irBlock *b = proc->blocks[i];
if (b->index == WHITE) {
for_array(j, b->succs) {
irBlock *c = b->succs.e[j];
irBlock *c = b->succs[j];
if (c->index == BLACK) {
ir_remove_pred(c, b);
}
}
// NOTE(bill): Mark as empty but don't actually free it
// As it's been allocated with an arena
proc->blocks.e[i] = NULL;
proc->blocks[i] = NULL;
}
}
ir_remove_dead_blocks(proc);
@@ -217,7 +220,7 @@ bool ir_opt_block_fusion(irProcedure *proc, irBlock *a) {
if (a->succs.count != 1) {
return false;
}
irBlock *b = a->succs.e[0];
irBlock *b = a->succs[0];
if (b->preds.count != 1) {
return false;
}
@@ -228,21 +231,21 @@ bool ir_opt_block_fusion(irProcedure *proc, irBlock *a) {
array_pop(&a->instrs); // Remove branch at end
for_array(i, b->instrs) {
array_add(&a->instrs, b->instrs.e[i]);
ir_set_instr_parent(b->instrs.e[i], a);
array_add(&a->instrs, b->instrs[i]);
ir_set_instr_parent(b->instrs[i], a);
}
array_clear(&a->succs);
for_array(i, b->succs) {
array_add(&a->succs, b->succs.e[i]);
array_add(&a->succs, b->succs[i]);
}
// Fix preds links
for_array(i, b->succs) {
ir_opt_block_replace_pred(b->succs.e[i], b, a);
ir_opt_block_replace_pred(b->succs[i], b, a);
}
proc->blocks.e[b->index] = NULL;
proc->blocks[b->index] = NULL;
return true;
}
@@ -254,7 +257,7 @@ void ir_opt_blocks(irProcedure *proc) {
while (changed) {
changed = false;
for_array(i, proc->blocks) {
irBlock *b = proc->blocks.e[i];
irBlock *b = proc->blocks[i];
if (b == NULL) {
continue;
}
@@ -273,20 +276,20 @@ void ir_opt_blocks(irProcedure *proc) {
void ir_opt_build_referrers(irProcedure *proc) {
gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&proc->module->tmp_arena);
irValueArray ops = {0}; // NOTE(bill): Act as a buffer
array_init_reserve(&ops, proc->module->tmp_allocator, 64); // HACK(bill): This _could_ overflow the temp arena
Array<irValue *> ops = {0}; // NOTE(bill): Act as a buffer
array_init(&ops, proc->module->tmp_allocator, 64); // HACK(bill): This _could_ overflow the temp arena
for_array(i, proc->blocks) {
irBlock *b = proc->blocks.e[i];
irBlock *b = proc->blocks[i];
for_array(j, b->instrs) {
irValue *instr = b->instrs.e[j];
irValue *instr = b->instrs[j];
array_clear(&ops);
ir_opt_add_operands(&ops, &instr->Instr);
for_array(k, ops) {
irValue *op = ops.e[k];
irValue *op = ops[k];
if (op == NULL) {
continue;
}
irValueArray *refs = ir_value_referrers(op);
Array<irValue *> *refs = ir_value_referrers(op);
if (refs != NULL) {
array_add(refs, instr);
}
@@ -324,7 +327,7 @@ i32 ir_lt_depth_first_search(irLTState *lt, irBlock *p, i32 i, irBlock **preorde
lt->sdom[p->index] = p;
ir_lt_link(lt, NULL, p);
for_array(index, p->succs) {
irBlock *q = p->succs.e[index];
irBlock *q = p->succs[index];
if (lt->sdom[q->index] == NULL) {
lt->parent[q->index] = p;
i = ir_lt_depth_first_search(lt, q, i, preorder);
@@ -354,7 +357,7 @@ irDomPrePost ir_opt_number_dom_tree(irBlock *v, i32 pre, i32 post) {
v->dom.pre = pre++;
for_array(i, v->dom.children) {
result = ir_opt_number_dom_tree(v->dom.children.e[i], result.pre, result.post);
result = ir_opt_number_dom_tree(v->dom.children[i], result.pre, result.post);
}
v->dom.post = post++;
@@ -381,7 +384,7 @@ void ir_opt_build_dom_tree(irProcedure *proc) {
irBlock **preorder = &buf[3*n];
irBlock **buckets = &buf[4*n];
irBlock *root = proc->blocks.e[0];
irBlock *root = proc->blocks[0];
// Step 1 - number vertices
i32 pre_num = ir_lt_depth_first_search(&lt, root, 0, preorder);
@@ -403,7 +406,7 @@ void ir_opt_build_dom_tree(irProcedure *proc) {
// Step 2 - Compute all sdoms
lt.sdom[w->index] = lt.parent[w->index];
for_array(pred_index, w->preds) {
irBlock *v = w->preds.e[pred_index];
irBlock *v = w->preds[pred_index];
irBlock *u = ir_lt_eval(&lt, v);
if (lt.sdom[u->index]->dom.pre < lt.sdom[w->index]->dom.pre) {
lt.sdom[w->index] = lt.sdom[u->index];
@@ -438,7 +441,7 @@ void ir_opt_build_dom_tree(irProcedure *proc) {
}
// Calculate children relation as inverse of idom
if (w->dom.idom->dom.children.e == NULL) {
if (w->dom.idom->dom.children.data == NULL) {
// TODO(bill): Is this good enough for memory allocations?
array_init(&w->dom.idom->dom.children, heap_allocator());
}
@@ -461,7 +464,7 @@ void ir_opt_tree(irGen *s) {
s->opt_called = true;
for_array(member_index, s->module.procs) {
irProcedure *proc = s->module.procs.e[member_index];
irProcedure *proc = s->module.procs[member_index];
if (proc->blocks.count == 0) { // Prototype/external procedure
continue;
}
+286 -204
View File
@@ -1,8 +1,8 @@
typedef struct irFileBuffer {
struct irFileBuffer {
gbVirtualMemory vm;
isize offset;
gbFile * output;
} irFileBuffer;
};
void ir_file_buffer_init(irFileBuffer *f, gbFile *output) {
isize size = 8*gb_virtual_memory_page_size(NULL);
@@ -39,12 +39,19 @@ void ir_file_buffer_write(irFileBuffer *f, void *data, isize len) {
void ir_fprintf(irFileBuffer *f, char *fmt, ...) {
va_list va;
va_start(va, fmt);
char buf[4096] = {0};
char buf[4096] = {};
isize len = gb_snprintf_va(buf, gb_size_of(buf), fmt, va);
ir_file_buffer_write(f, buf, len-1);
va_end(va);
}
void ir_fprint_string(irFileBuffer *f, String s) {
ir_file_buffer_write(f, s.text, s.len);
}
void ir_fprint_i128(irFileBuffer *f, i128 i) {
char buf[200] = {};
String str = i128_to_string(i, buf, gb_size_of(buf)-1);
ir_fprint_string(f, str);
}
void ir_file_write(irFileBuffer *f, void *data, isize len) {
ir_file_buffer_write(f, data, len);
@@ -71,10 +78,10 @@ bool ir_valid_char(u8 c) {
return false;
}
void ir_print_escape_string(irFileBuffer *f, String name, bool print_quotes) {
void ir_print_escape_string(irFileBuffer *f, String name, bool print_quotes, bool prefix_with_dot) {
isize extra = 0;
for (isize i = 0; i < name.len; i++) {
u8 c = name.text[i];
u8 c = name[i];
if (!ir_valid_char(c)) {
extra += 2;
}
@@ -87,7 +94,7 @@ void ir_print_escape_string(irFileBuffer *f, String name, bool print_quotes) {
char hex_table[] = "0123456789ABCDEF";
isize buf_len = name.len + extra + 2;
isize buf_len = name.len + extra + 2 + 1;
gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&string_buffer_arena);
@@ -99,8 +106,12 @@ void ir_print_escape_string(irFileBuffer *f, String name, bool print_quotes) {
buf[j++] = '"';
}
if (prefix_with_dot) {
buf[j++] = '.';
}
for (isize i = 0; i < name.len; i++) {
u8 c = name.text[i];
u8 c = name[i];
if (ir_valid_char(c)) {
buf[j++] = c;
} else {
@@ -124,15 +135,12 @@ void ir_print_escape_string(irFileBuffer *f, String name, bool print_quotes) {
void ir_print_encoded_local(irFileBuffer *f, String name) {
ir_fprintf(f, "%%");
ir_print_escape_string(f, name, true);
ir_print_escape_string(f, name, true, false);
}
void ir_print_encoded_global(irFileBuffer *f, String name, bool remove_prefix) {
ir_fprintf(f, "@");
if (!remove_prefix) {
ir_fprintf(f, ".");
}
ir_print_escape_string(f, name, true);
ir_print_escape_string(f, name, true, !remove_prefix);
}
void ir_print_type(irFileBuffer *f, irModule *m, Type *t);
@@ -141,23 +149,67 @@ void ir_print_proc_results(irFileBuffer *f, irModule *m, Type *t) {
GB_ASSERT(is_type_proc(t));
t = base_type(t);
isize result_count = t->Proc.result_count;
if (result_count == 0) {
if (result_count == 0 || t->Proc.return_by_pointer) {
ir_fprintf(f, "void");
} else if (result_count == 1) {
ir_print_type(f, m, t->Proc.abi_compat_results[0]);
} else {
ir_fprintf(f, "{");
for (isize i = 0; i < result_count; i++) {
if (i > 0) {
ir_fprintf(f, ", ");
Type *rt = t->Proc.abi_compat_result_type;
if (!is_type_tuple(rt)) {
ir_print_type(f, m, rt);
} else if (rt->Tuple.variable_count == 1) {
ir_print_type(f, m, rt->Tuple.variables[0]->type);
} else {
isize count = rt->Tuple.variable_count;
ir_fprintf(f, "{");
for (isize i = 0; i < count; i++) {
Entity *e = rt->Tuple.variables[i];
if (i > 0) {
ir_fprintf(f, ", ");
}
ir_print_type(f, m, e->type);
}
ir_print_type(f, m, t->Proc.abi_compat_results[i]);
ir_fprintf(f, "}");
}
ir_fprintf(f, "}");
}
}
void ir_print_proc_type_without_pointer(irFileBuffer *f, irModule *m, Type *t) {
i64 word_bits = 8*build_context.word_size;
t = base_type(t);
GB_ASSERT(is_type_proc(t));
isize param_count = t->Proc.param_count;
isize result_count = t->Proc.result_count;
ir_print_proc_results(f, m, t);
ir_fprintf(f, " (");
if (t->Proc.return_by_pointer) {
ir_print_type(f, m, reduce_tuple_to_single_type(t->Proc.results));
ir_fprintf(f, "* sret noalias ");
if (param_count > 0) {
ir_fprintf(f, ", ");
}
}
isize param_index = 0;
for (isize i = 0; i < param_count; i++) {
Entity *e = t->Proc.params->Tuple.variables[i];
if (e->kind != Entity_Variable) continue;
if (param_index > 0) ir_fprintf(f, ", ");
if (i+1 == param_count && t->Proc.c_vararg) {
ir_fprintf(f, "...");
} else {
ir_print_type(f, m, t->Proc.abi_compat_params[i]);
}
param_index++;
}
if (t->Proc.calling_convention == ProcCC_Odin) {
if (param_index > 0) ir_fprintf(f, ", ");
ir_print_type(f, m, t_context_ptr);
}
ir_fprintf(f, ")");
}
void ir_print_type(irFileBuffer *f, irModule *m, Type *t) {
i64 word_bits = 8*build_context.word_size;
GB_ASSERT_NOT_NULL(t);
@@ -176,16 +228,19 @@ void ir_print_type(irFileBuffer *f, irModule *m, Type *t) {
case Basic_u32: ir_fprintf(f, "i32"); return;
case Basic_i64: ir_fprintf(f, "i64"); return;
case Basic_u64: ir_fprintf(f, "i64"); return;
case Basic_i128: ir_fprintf(f, "i128"); return;
case Basic_u128: ir_fprintf(f, "i128"); return;
case Basic_rune: ir_fprintf(f, "i32"); return;
// case Basic_f16: ir_fprintf(f, "half"); return;
case Basic_f32: ir_fprintf(f, "float"); return;
case Basic_f64: ir_fprintf(f, "double"); return;
// case Basic_complex32: ir_fprintf(f, "%%..complex32"); return;
case Basic_complex64: ir_fprintf(f, "%%..complex64"); return;
case Basic_complex128: ir_fprintf(f, "%%..complex128"); return;
case Basic_quaternion128: ir_fprintf(f, "%%..quaternion128"); return;
case Basic_quaternion256: ir_fprintf(f, "%%..quaternion256"); return;
case Basic_rawptr: ir_fprintf(f, "%%..rawptr"); return;
case Basic_string: ir_fprintf(f, "%%..string"); return;
case Basic_uint: ir_fprintf(f, "i%lld", word_bits); return;
@@ -259,15 +314,7 @@ void ir_print_type(irFileBuffer *f, irModule *m, Type *t) {
i64 align = type_align_of(heap_allocator(), t);
i64 total_size = type_size_of(heap_allocator(), t);
#if 1
i64 fields_size = 0;
if (t->Record.field_count > 0) {
type_set_offsets(m->allocator, t);
isize end_index = t->Record.field_count-1;
i64 end_offset = t->Record.offsets[end_index];
isize end_size = type_size_of(m->allocator, t->Record.fields[end_index]->type);
fields_size = align_formula(end_offset + end_size, build_context.word_size);
}
i64 block_size = total_size - fields_size - build_context.word_size;
i64 block_size = t->Record.variant_block_size;
ir_fprintf(f, "{[0 x <%lld x i8>], ", align);
for (isize i = 0; i < t->Record.field_count; i++) {
@@ -297,7 +344,7 @@ void ir_print_type(irFileBuffer *f, irModule *m, Type *t) {
case Type_Named:
if (is_type_struct(t) || is_type_union(t)) {
String *name = map_string_get(&m->entity_names, hash_pointer(t->Named.type_name));
String *name = map_get(&m->entity_names, hash_pointer(t->Named.type_name));
GB_ASSERT_MSG(name != NULL, "%.*s", LIT(t->Named.name));
ir_print_encoded_local(f, *name);
} else {
@@ -309,33 +356,35 @@ void ir_print_type(irFileBuffer *f, irModule *m, Type *t) {
ir_print_type(f, m, t->Tuple.variables[0]->type);
} else {
ir_fprintf(f, "{");
isize index = 0;
for (isize i = 0; i < t->Tuple.variable_count; i++) {
if (i > 0) {
if (index > 0) {
ir_fprintf(f, ", ");
}
ir_print_type(f, m, t->Tuple.variables[i]->type);
Entity *e = t->Tuple.variables[i];
if (e->kind == Entity_Variable) {
ir_print_type(f, m, e->type);
index++;
}
}
ir_fprintf(f, "}");
}
return;
case Type_Proc: {
isize param_count = t->Proc.param_count;
isize result_count = t->Proc.result_count;
ir_print_proc_results(f, m, t);
ir_fprintf(f, " (");
for (isize i = 0; i < param_count; i++) {
if (i > 0) {
ir_fprintf(f, ", ");
}
ir_print_type(f, m, t->Proc.abi_compat_params[i]);
}
ir_fprintf(f, ")*");
ir_print_proc_type_without_pointer(f, m, t);
ir_fprintf(f, "*");
} return;
case Type_Map: {
GB_ASSERT(t->Map.generated_struct_type != NULL);
ir_print_type(f, m, t->Map.generated_struct_type);
} break;
case Type_BitField: {
i64 align = type_align_of(heap_allocator(), t);
i64 size = type_size_of(heap_allocator(), t);
ir_fprintf(f, "{[0 x <%lld x i8>], [%lld x i8]}", align, size);
} break;
}
}
@@ -369,7 +418,7 @@ void ir_print_exact_value(irFileBuffer *f, irModule *m, ExactValue value, Type *
if (!is_type_string(type)) {
GB_ASSERT(is_type_array(type));
ir_fprintf(f, "c\"");
ir_print_escape_string(f, str, false);
ir_print_escape_string(f, str, false, false);
ir_fprintf(f, "\"");
} else {
// HACK NOTE(bill): This is a hack but it works because strings are created at the very end
@@ -390,17 +439,19 @@ void ir_print_exact_value(irFileBuffer *f, irModule *m, ExactValue value, Type *
} break;
case ExactValue_Integer: {
if (is_type_pointer(type)) {
if (value.value_integer == 0) {
if (i128_eq(value.value_integer, I128_ZERO)) {
ir_fprintf(f, "null");
} else {
ir_fprintf(f, "inttoptr (");
ir_print_type(f, m, t_int);
ir_fprintf(f, " %llu to ", value.value_integer);
ir_fprintf(f, " ");
ir_fprint_i128(f, value.value_integer);
ir_fprintf(f, " to ");
ir_print_type(f, m, t_rawptr);
ir_fprintf(f, ")");
}
} else {
ir_fprintf(f, "%lld", value.value_integer);
ir_fprint_i128(f, value.value_integer);
}
} break;
case ExactValue_Float: {
@@ -412,12 +463,17 @@ void ir_print_exact_value(irFileBuffer *f, irModule *m, ExactValue value, Type *
// IMPORTANT NOTE(bill): LLVM requires all floating point constants to be
// a 64 bit number if bits_of(float type) <= 64.
// https://groups.google.com/forum/#!topic/llvm-dev/IlqV3TbSk6M
// 64 bit mantiir: 52 bits
// 32 bit mantiir: 23 bits
// 64 bit mantissa: 52 bits
// 32 bit mantissa: 23 bits
// 16 bit mantissa: 10 bits
// 29 == 52-23
u >>= 29;
u <<= 29;
break;
// case Basic_f16:
// u >>= 42;
// u <<= 42;
// break;
}
switch (type->Basic.kind) {
@@ -430,41 +486,12 @@ void ir_print_exact_value(irFileBuffer *f, irModule *m, ExactValue value, Type *
case ExactValue_Complex: {
type = core_type(type);
if (is_type_quaternion(type)) {
Type *ft = base_quaternion_elem_type(type);
ir_fprintf(f, " {"); ir_print_type(f, m, ft); ir_fprintf(f, " ");
ir_print_exact_value(f, m, exact_value_float(value.value_complex.real), ft);
ir_fprintf(f, ", "); ir_print_type(f, m, ft); ir_fprintf(f, " ");
ir_print_exact_value(f, m, exact_value_float(value.value_complex.imag), ft);
ir_fprintf(f, ", "); ir_print_type(f, m, ft); ir_fprintf(f, " ");
ir_print_exact_value(f, m, exact_value_float(0), ft);
ir_fprintf(f, ", "); ir_print_type(f, m, ft); ir_fprintf(f, " ");
ir_print_exact_value(f, m, exact_value_float(0), ft);
ir_fprintf(f, "}");
} else {
GB_ASSERT_MSG(is_type_complex(type), "%s", type_to_string(type));
Type *ft = base_complex_elem_type(type);
ir_fprintf(f, " {"); ir_print_type(f, m, ft); ir_fprintf(f, " ");
ir_print_exact_value(f, m, exact_value_float(value.value_complex.real), ft);
ir_fprintf(f, ", "); ir_print_type(f, m, ft); ir_fprintf(f, " ");
ir_print_exact_value(f, m, exact_value_float(value.value_complex.imag), ft);
ir_fprintf(f, "}");
}
} break;
case ExactValue_Quaternion: {
GB_ASSERT_MSG(is_type_quaternion(type), "%s", type_to_string(type));
type = core_type(type);
Type *ft = base_quaternion_elem_type(type);
GB_ASSERT_MSG(is_type_complex(type), "%s", type_to_string(type));
Type *ft = base_complex_elem_type(type);
ir_fprintf(f, " {"); ir_print_type(f, m, ft); ir_fprintf(f, " ");
ir_print_exact_value(f, m, exact_value_float(value.value_quaternion.real), ft);
ir_print_exact_value(f, m, exact_value_float(value.value_complex.real), ft);
ir_fprintf(f, ", "); ir_print_type(f, m, ft); ir_fprintf(f, " ");
ir_print_exact_value(f, m, exact_value_float(value.value_quaternion.imag), ft);
ir_fprintf(f, ", "); ir_print_type(f, m, ft); ir_fprintf(f, " ");
ir_print_exact_value(f, m, exact_value_float(value.value_quaternion.jmag), ft);
ir_fprintf(f, ", "); ir_print_type(f, m, ft); ir_fprintf(f, " ");
ir_print_exact_value(f, m, exact_value_float(value.value_quaternion.kmag), ft);
ir_print_exact_value(f, m, exact_value_float(value.value_complex.imag), ft);
ir_fprintf(f, "}");
} break;
@@ -497,9 +524,9 @@ void ir_print_exact_value(irFileBuffer *f, irModule *m, ExactValue value, Type *
if (i > 0) {
ir_fprintf(f, ", ");
}
TypeAndValue *tav = type_and_value_of_expression(m->info, cl->elems.e[i]);
GB_ASSERT(tav != NULL);
ir_print_compound_element(f, m, tav->value, elem_type);
TypeAndValue tav = type_and_value_of_expr(m->info, cl->elems[i]);
GB_ASSERT(tav.mode != Addressing_Invalid);
ir_print_compound_element(f, m, tav.value, elem_type);
}
for (isize i = elem_count; i < type->Array.count; i++) {
if (i >= elem_count) {
@@ -527,23 +554,23 @@ void ir_print_exact_value(irFileBuffer *f, irModule *m, ExactValue value, Type *
ir_fprintf(f, "][");
if (elem_count == 1 && type->Vector.count > 1) {
TypeAndValue *tav = type_and_value_of_expression(m->info, cl->elems.e[0]);
GB_ASSERT(tav != NULL);
TypeAndValue tav = type_and_value_of_expr(m->info, cl->elems[0]);
GB_ASSERT(tav.mode != Addressing_Invalid);
for (isize i = 0; i < type->Vector.count; i++) {
if (i > 0) {
ir_fprintf(f, ", ");
}
ir_print_compound_element(f, m, tav->value, elem_type);
ir_print_compound_element(f, m, tav.value, elem_type);
}
} else {
for (isize i = 0; i < elem_count; i++) {
if (i > 0) {
ir_fprintf(f, ", ");
}
TypeAndValue *tav = type_and_value_of_expression(m->info, cl->elems.e[i]);
GB_ASSERT(tav != NULL);
ir_print_compound_element(f, m, tav->value, elem_type);
TypeAndValue tav = type_and_value_of_expr(m->info, cl->elems[i]);
GB_ASSERT(tav.mode != Addressing_Invalid);
ir_print_compound_element(f, m, tav.value, elem_type);
}
}
@@ -563,31 +590,29 @@ void ir_print_exact_value(irFileBuffer *f, irModule *m, ExactValue value, Type *
ExactValue *values = gb_alloc_array(m->tmp_allocator, ExactValue, value_count);
if (cl->elems.e[0]->kind == AstNode_FieldValue) {
if (cl->elems[0]->kind == AstNode_FieldValue) {
isize elem_count = cl->elems.count;
for (isize i = 0; i < elem_count; i++) {
ast_node(fv, FieldValue, cl->elems.e[i]);
ast_node(fv, FieldValue, cl->elems[i]);
String name = fv->field->Ident.string;
TypeAndValue *tav = type_and_value_of_expression(m->info, fv->value);
GB_ASSERT(tav != NULL);
TypeAndValue tav = type_and_value_of_expr(m->info, fv->value);
GB_ASSERT(tav.mode != Addressing_Invalid);
Selection sel = lookup_field(m->allocator, type, name, false);
Entity *f = type->Record.fields[sel.index.e[0]];
Entity *f = type->Record.fields[sel.index[0]];
values[f->Variable.field_index] = tav->value;
values[f->Variable.field_index] = tav.value;
}
} else {
for (isize i = 0; i < value_count; i++) {
Entity *f = type->Record.fields_in_src_order[i];
if (str_eq(f->token.string, str_lit("_"))) {
values[f->Variable.field_index] = (ExactValue){0};
} else {
TypeAndValue *tav = type_and_value_of_expression(m->info, cl->elems.e[i]);
GB_ASSERT(tav != NULL);
values[f->Variable.field_index] = tav->value;
TypeAndValue tav = type_and_value_of_expr(m->info, cl->elems[i]);
ExactValue val = {};
if (tav.mode != Addressing_Invalid) {
val = tav.value;
}
values[f->Variable.field_index] = val;
}
}
@@ -597,6 +622,12 @@ void ir_print_exact_value(irFileBuffer *f, irModule *m, ExactValue value, Type *
ir_fprintf(f, "<");
}
ir_fprintf(f, "{");
if (type->Record.custom_align > 0) {
ir_fprintf(f, "[0 x <%lld x i8>] zeroinitializer", cast(i64)type->Record.custom_align);
if (value_count > 0) {
ir_fprintf(f, ", ");
}
}
for (isize i = 0; i < value_count; i++) {
@@ -630,7 +661,7 @@ void ir_print_exact_value(irFileBuffer *f, irModule *m, ExactValue value, Type *
void ir_print_block_name(irFileBuffer *f, irBlock *b) {
if (b != NULL) {
ir_print_escape_string(f, b->label, false);
ir_print_escape_string(f, b->label, false, false);
ir_fprintf(f, "-%td", b->index);
} else {
ir_fprintf(f, "<INVALID-BLOCK>");
@@ -693,6 +724,10 @@ void ir_print_value(irFileBuffer *f, irModule *m, irValue *value, Type *type_hin
ir_fprintf(f, "zeroinitializer");
break;
case irValue_Undef:
ir_fprintf(f, "undef");
break;
case irValue_TypeName:
ir_print_encoded_local(f, value->TypeName.name);
break;
@@ -719,10 +754,11 @@ void ir_print_value(irFileBuffer *f, irModule *m, irValue *value, Type *type_hin
void ir_print_calling_convention(irFileBuffer *f, irModule *m, ProcCallingConvention cc) {
switch (cc) {
case ProcCC_Odin: ir_fprintf(f, ""); break;
case ProcCC_C: ir_fprintf(f, "ccc "); break;
case ProcCC_Std: ir_fprintf(f, "cc 64 "); break;
case ProcCC_Fast: ir_fprintf(f, "cc 65 "); break;
case ProcCC_Odin: ir_fprintf(f, ""); break;
case ProcCC_Contextless: ir_fprintf(f, ""); break;
case ProcCC_C: ir_fprintf(f, "ccc "); break;
case ProcCC_Std: ir_fprintf(f, "cc 64 "); break;
case ProcCC_Fast: ir_fprintf(f, "cc 65 "); break;
default: GB_PANIC("unknown calling convention: %d", cc);
}
}
@@ -887,11 +923,11 @@ void ir_print_instr(irFileBuffer *f, irModule *m, irValue *value) {
ir_fprintf(f, ", ");
}
irValue *edge = instr->Phi.edges.e[i];
irValue *edge = instr->Phi.edges[i];
irBlock *block = NULL;
if (instr->parent != NULL &&
i < instr->parent->preds.count) {
block = instr->parent->preds.e[i];
block = instr->parent->preds[i];
}
ir_fprintf(f, "[ ");
@@ -1069,7 +1105,7 @@ void ir_print_instr(irFileBuffer *f, irModule *m, irValue *value) {
irInstrBinaryOp *bo = &value->Instr.BinaryOp;
Type *type = base_type(ir_type(bo->left));
Type *elem_type = type;
GB_ASSERT(!is_type_vector(elem_type));
GB_ASSERT_MSG(!is_type_vector(elem_type), type_to_string(elem_type));
ir_fprintf(f, "%%%d = ", value->index);
@@ -1132,39 +1168,6 @@ void ir_print_instr(irFileBuffer *f, irModule *m, irValue *value) {
break;
}
ir_fprintf(f, " ");
ir_print_encoded_global(f, make_string_c(runtime_proc), false);
ir_fprintf(f, "(");
ir_print_type(f, m, type);
ir_fprintf(f, " ");
ir_print_value(f, m, bo->left, type);
ir_fprintf(f, ", ");
ir_print_type(f, m, type);
ir_fprintf(f, " ");
ir_print_value(f, m, bo->right, type);
ir_fprintf(f, ")\n");
return;
} else if (is_type_quaternion(elem_type)) {
ir_fprintf(f, "call ");
ir_print_calling_convention(f, m, ProcCC_Odin);
ir_print_type(f, m, t_bool);
char *runtime_proc = "";
i64 sz = 8*type_size_of(m->allocator, elem_type);
switch (sz) {
case 128:
switch (bo->op) {
case Token_CmpEq: runtime_proc = "__quaternion128_eq"; break;
case Token_NotEq: runtime_proc = "__quaternion128_ne"; break;
}
break;
case 256:
switch (bo->op) {
case Token_CmpEq: runtime_proc = "__quaternion256_eq"; break;
case Token_NotEq: runtime_proc = "__quaternion256_ne"; break;
}
break;
}
ir_fprintf(f, " ");
ir_print_encoded_global(f, make_string_c(runtime_proc), false);
ir_fprintf(f, "(");
@@ -1245,13 +1248,16 @@ void ir_print_instr(irFileBuffer *f, irModule *m, irValue *value) {
irInstrCall *call = &instr->Call;
Type *proc_type = base_type(ir_type(call->value));
GB_ASSERT(is_type_proc(proc_type));
bool is_c_vararg = proc_type->Proc.c_vararg;
Type *result_type = call->type;
if (result_type) {
ir_fprintf(f, "%%%d = ", value->index);
}
ir_fprintf(f, "call ");
ir_print_calling_convention(f, m, proc_type->Proc.calling_convention);
if (result_type) {
if (is_c_vararg) {
ir_print_proc_type_without_pointer(f, m, proc_type);
} else if (result_type && !proc_type->Proc.return_by_pointer) {
ir_print_proc_results(f, m, proc_type);
} else {
ir_fprintf(f, "void");
@@ -1261,26 +1267,79 @@ void ir_print_instr(irFileBuffer *f, irModule *m, irValue *value) {
ir_fprintf(f, "(");
if (call->arg_count > 0) {
Type *proc_type = base_type(ir_type(call->value));
GB_ASSERT(proc_type->kind == Type_Proc);
TypeTuple *params = &proc_type->Proc.params->Tuple;
for (isize i = 0; i < call->arg_count; i++) {
Entity *e = params->variables[i];
GB_ASSERT(e != NULL);
Type *t = proc_type->Proc.abi_compat_params[i];
if (i > 0) {
ir_fprintf(f, ", ");
}
ir_print_type(f, m, t);
if (e->flags&EntityFlag_NoAlias) {
ir_fprintf(f, " noalias");
}
ir_fprintf(f, " ");
irValue *arg = call->args[i];
ir_print_value(f, m, arg, t);
if (proc_type->Proc.return_by_pointer) {
GB_ASSERT(call->return_ptr != NULL);
ir_print_type(f, m, proc_type->Proc.results);
ir_fprintf(f, "* ");
ir_print_value(f, m, call->return_ptr, ir_type(call->return_ptr));
if (call->arg_count > 0) {
ir_fprintf(f, ", ");
}
}
isize param_index = 0;
if (call->arg_count > 0) {
TypeTuple *params = &proc_type->Proc.params->Tuple;
if (proc_type->Proc.c_vararg) {
isize i = 0;
for (; i < params->variable_count-1; i++) {
Entity *e = params->variables[i];
GB_ASSERT(e != NULL);
if (e->kind != Entity_Variable) continue;
if (param_index > 0) ir_fprintf(f, ", ");
Type *t = proc_type->Proc.abi_compat_params[i];
ir_print_type(f, m, t);
if (e->flags&EntityFlag_NoAlias) {
ir_fprintf(f, " noalias");
}
ir_fprintf(f, " ");
irValue *arg = call->args[i];
ir_print_value(f, m, arg, t);
param_index++;
}
for (; i < call->arg_count; i++) {
if (param_index > 0) ir_fprintf(f, ", ");
irValue *arg = call->args[i];
Type *t = ir_type(arg);
ir_print_type(f, m, t);
ir_fprintf(f, " ");
ir_print_value(f, m, arg, t);
param_index++;
}
} else {
GB_ASSERT(call->arg_count == params->variable_count);
isize param_count = params->variable_count;
for (isize i = 0; i < param_count; i++) {
Entity *e = params->variables[i];
GB_ASSERT(e != NULL);
if (e->kind != Entity_Variable) continue;
if (param_index > 0) ir_fprintf(f, ", ");
irValue *arg = call->args[i];
Type *t = proc_type->Proc.abi_compat_params[i];
ir_print_type(f, m, t);
if (e->flags&EntityFlag_NoAlias) {
ir_fprintf(f, " noalias");
}
ir_fprintf(f, " ");
ir_print_value(f, m, arg, t);
param_index++;
}
}
}
if (proc_type->Proc.calling_convention == ProcCC_Odin) {
if (param_index > 0) ir_fprintf(f, ", ");
ir_print_type(f, m, t_context_ptr);
ir_fprintf(f, " noalias nonnull");
ir_print_value(f, m, call->context_ptr, t_context_ptr);
}
ir_fprintf(f, ")\n");
} break;
@@ -1362,6 +1421,7 @@ void ir_print_instr(irFileBuffer *f, irModule *m, irValue *value) {
// ir_fprintf(f, "\n");
// } break;
#if 0
case irInstr_BoundsCheck: {
irInstrBoundsCheck *bc = &instr->BoundsCheck;
ir_fprintf(f, "call void ");
@@ -1372,12 +1432,12 @@ void ir_print_instr(irFileBuffer *f, irModule *m, irValue *value) {
ir_print_type(f, m, t_int);
ir_fprintf(f, " ");
ir_print_exact_value(f, m, exact_value_integer(bc->pos.line), t_int);
ir_print_exact_value(f, m, exact_value_i64(bc->pos.line), t_int);
ir_fprintf(f, ", ");
ir_print_type(f, m, t_int);
ir_fprintf(f, " ");
ir_print_exact_value(f, m, exact_value_integer(bc->pos.column), t_int);
ir_print_exact_value(f, m, exact_value_i64(bc->pos.column), t_int);
ir_fprintf(f, ", ");
ir_print_type(f, m, t_int);
@@ -1407,12 +1467,12 @@ void ir_print_instr(irFileBuffer *f, irModule *m, irValue *value) {
ir_print_type(f, m, t_int);
ir_fprintf(f, " ");
ir_print_exact_value(f, m, exact_value_integer(bc->pos.line), t_int);
ir_print_exact_value(f, m, exact_value_i64(bc->pos.line), t_int);
ir_fprintf(f, ", ");
ir_print_type(f, m, t_int);
ir_fprintf(f, " ");
ir_print_exact_value(f, m, exact_value_integer(bc->pos.column), t_int);
ir_print_exact_value(f, m, exact_value_i64(bc->pos.column), t_int);
ir_fprintf(f, ", ");
ir_print_type(f, m, t_int);
@@ -1433,6 +1493,7 @@ void ir_print_instr(irFileBuffer *f, irModule *m, irValue *value) {
ir_fprintf(f, ")\n");
} break;
#endif
case irInstr_DebugDeclare: {
/* irInstrDebugDeclare *dd = &instr->DebugDeclare;
@@ -1496,30 +1557,52 @@ void ir_print_proc(irFileBuffer *f, irModule *m, irProcedure *proc) {
ir_fprintf(f, "(");
if (proc_type->return_by_pointer) {
ir_print_type(f, m, reduce_tuple_to_single_type(proc_type->results));
ir_fprintf(f, "* sret noalias ");
ir_fprintf(f, "%%agg.result");
if (param_count > 0) {
ir_fprintf(f, ", ");
}
}
isize param_index = 0;
if (param_count > 0) {
TypeTuple *params = &proc_type->params->Tuple;
for (isize i = 0; i < params->variable_count; i++) {
for (isize i = 0; i < param_count; i++) {
Entity *e = params->variables[i];
Type *original_type = e->type;
Type *abi_type = proc_type->abi_compat_params[i];
if (i > 0) {
ir_fprintf(f, ", ");
}
ir_print_type(f, m, abi_type);
if (e->flags&EntityFlag_NoAlias) {
ir_fprintf(f, " noalias");
}
if (proc->body != NULL) {
if (!str_eq(e->token.string, str_lit("")) &&
!str_eq(e->token.string, str_lit("_"))) {
ir_fprintf(f, " ");
ir_print_encoded_local(f, e->token.string);
} else {
ir_fprintf(f, " %%_.param_%td", i);
if (e->kind != Entity_Variable) continue;
if (param_index > 0) ir_fprintf(f, ", ");
if (i+1 == params->variable_count && proc_type->c_vararg) {
ir_fprintf(f, " ...");
} else {
ir_print_type(f, m, abi_type);
if (e->flags&EntityFlag_NoAlias) {
ir_fprintf(f, " noalias");
}
if (proc->body != NULL) {
if (e->token.string != "" &&
e->token.string != "_") {
ir_fprintf(f, " ");
ir_print_encoded_local(f, e->token.string);
} else {
ir_fprintf(f, " %%_.param_%td", i);
}
}
}
param_index++;
}
}
if (proc_type->calling_convention == ProcCC_Odin) {
if (param_index > 0) ir_fprintf(f, ", ");
ir_print_type(f, m, t_context_ptr);
ir_fprintf(f, " noalias nonnull %%__.context_ptr");
}
ir_fprintf(f, ") ");
@@ -1533,7 +1616,7 @@ void ir_print_proc(irFileBuffer *f, irModule *m, irProcedure *proc) {
if (proc->entity != NULL) {
if (proc->body != NULL) {
irDebugInfo **di_ = map_ir_debug_info_get(&proc->module->debug_info, hash_pointer(proc->entity));
irDebugInfo **di_ = map_get(&proc->module->debug_info, hash_pointer(proc->entity));
if (di_ != NULL) {
irDebugInfo *di = *di_;
GB_ASSERT(di->kind == irDebugInfo_Proc);
@@ -1548,14 +1631,14 @@ void ir_print_proc(irFileBuffer *f, irModule *m, irProcedure *proc) {
ir_fprintf(f, "{\n");
for_array(i, proc->blocks) {
irBlock *block = proc->blocks.e[i];
irBlock *block = proc->blocks[i];
if (i > 0) ir_fprintf(f, "\n");
ir_print_block_name(f, block);
ir_fprintf(f, ":\n");
for_array(j, block->instrs) {
irValue *value = block->instrs.e[j];
irValue *value = block->instrs[j];
ir_print_instr(f, m, value);
}
}
@@ -1565,7 +1648,7 @@ void ir_print_proc(irFileBuffer *f, irModule *m, irProcedure *proc) {
}
for_array(i, proc->children) {
ir_print_proc(f, m, proc->children.e[i]);
ir_print_proc(f, m, proc->children[i]);
}
}
@@ -1583,7 +1666,7 @@ void ir_print_type_name(irFileBuffer *f, irModule *m, irValue *v) {
void print_llvm_ir(irGen *ir) {
irModule *m = &ir->module;
irFileBuffer buf = {0}, *f = &buf;
irFileBuffer buf = {}, *f = &buf;
ir_file_buffer_init(f, &ir->output_file);
ir_print_encoded_local(f, str_lit("..string"));
@@ -1593,14 +1676,12 @@ void print_llvm_ir(irGen *ir) {
ir_print_encoded_local(f, str_lit("..rawptr"));
ir_fprintf(f, " = type i8* ; Basic_rawptr\n");
ir_print_encoded_local(f, str_lit("..complex32"));
ir_fprintf(f, " = type {half, half} ; Basic_complex32\n");
ir_print_encoded_local(f, str_lit("..complex64"));
ir_fprintf(f, " = type {float, float} ; Basic_complex64\n");
ir_print_encoded_local(f, str_lit("..complex128"));
ir_fprintf(f, " = type {double, double} ; Basic_complex128\n");
ir_print_encoded_local(f, str_lit("..quaternion128"));
ir_fprintf(f, " = type {float, float, float, float} ; Basic_quaternion128\n");
ir_print_encoded_local(f, str_lit("..quaternion256"));
ir_fprintf(f, " = type {double, double, double, double} ; Basic_quaternion256\n");
ir_print_encoded_local(f, str_lit("..any"));
@@ -1611,10 +1692,11 @@ void print_llvm_ir(irGen *ir) {
ir_fprintf(f, "} ; Basic_any\n");
ir_fprintf(f, "declare void @llvm.dbg.declare(metadata, metadata, metadata) nounwind readnone \n");
ir_fprintf(f, "\n");
for_array(member_index, m->members.entries) {
MapIrValueEntry *entry = &m->members.entries.e[member_index];
auto *entry = &m->members.entries[member_index];
irValue *v = entry->value;
if (v->kind != irValue_TypeName) {
continue;
@@ -1627,7 +1709,7 @@ void print_llvm_ir(irGen *ir) {
bool dll_main_found = false;
for_array(member_index, m->members.entries) {
MapIrValueEntry *entry = &m->members.entries.e[member_index];
auto *entry = &m->members.entries[member_index];
irValue *v = entry->value;
if (v->kind != irValue_Proc) {
continue;
@@ -1639,7 +1721,7 @@ void print_llvm_ir(irGen *ir) {
}
for_array(member_index, m->members.entries) {
MapIrValueEntry *entry = &m->members.entries.e[member_index];
auto *entry = &m->members.entries[member_index];
irValue *v = entry->value;
if (v->kind != irValue_Proc) {
continue;
@@ -1651,7 +1733,7 @@ void print_llvm_ir(irGen *ir) {
}
for_array(member_index, m->members.entries) {
MapIrValueEntry *entry = &m->members.entries.e[member_index];
auto *entry = &m->members.entries[member_index];
irValue *v = entry->value;
if (v->kind != irValue_Global) {
continue;
@@ -1715,13 +1797,13 @@ void print_llvm_ir(irGen *ir) {
ir_fprintf(f, "!%d = !{!\"clang version 3.9.0 (branches/release_39)\"}\n", diec+3);
for_array(di_index, m->debug_info.entries) {
MapIrDebugInfoEntry *entry = &m->debug_info.entries.e[di_index];
MapIrDebugInfoEntry *entry = &m->debug_info.entries[di_index];
irDebugInfo *di = entry->value;
ir_fprintf(f, "!%d = ", di->id);
switch (di->kind) {
case irDebugInfo_CompileUnit: {
irDebugInfo *file = *map_ir_debug_info_get(&m->debug_info, hash_pointer(di->CompileUnit.file));
irDebugInfo *file = *map_get(&m->debug_info, hash_pointer(di->CompileUnit.file));
ir_fprintf(f,
"distinct !DICompileUnit("
"language: DW_LANG_Go, " // Is this good enough?
@@ -1760,7 +1842,7 @@ void print_llvm_ir(irGen *ir) {
case irDebugInfo_AllProcs:
ir_fprintf(f, "!{");
for_array(proc_index, di->AllProcs.procs) {
irDebugInfo *p = di->AllProcs.procs.e[proc_index];
irDebugInfo *p = di->AllProcs.procs[proc_index];
if (proc_index > 0) {ir_fprintf(f, ",");}
ir_fprintf(f, "!%d", p->id);
}
-468
View File
@@ -1,468 +0,0 @@
#if defined(__cplusplus)
extern "C" {
#endif
#define USE_CUSTOM_BACKEND false
#include "common.c"
#include "timings.c"
#include "build_settings.c"
#include "tokenizer.c"
#include "parser.c"
#include "checker.c"
#include "ssa.c"
#include "ir.c"
#include "ir_opt.c"
#include "ir_print.c"
// #include "vm.c"
#if defined(GB_SYSTEM_WINDOWS)
// NOTE(bill): `name` is used in debugging and profiling modes
i32 system_exec_command_line_app(char *name, bool is_silent, char *fmt, ...) {
STARTUPINFOW start_info = {gb_size_of(STARTUPINFOW)};
PROCESS_INFORMATION pi = {0};
char cmd_line[4096] = {0};
isize cmd_len;
va_list va;
gbTempArenaMemory tmp;
String16 cmd;
i32 exit_code = 0;
start_info.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
start_info.wShowWindow = SW_SHOW;
start_info.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
start_info.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
start_info.hStdError = GetStdHandle(STD_ERROR_HANDLE);
va_start(va, fmt);
cmd_len = gb_snprintf_va(cmd_line, gb_size_of(cmd_line), fmt, va);
va_end(va);
// gb_printf("%.*s\n", cast(int)cmd_len, cmd_line);
tmp = gb_temp_arena_memory_begin(&string_buffer_arena);
cmd = string_to_string16(string_buffer_allocator, make_string(cast(u8 *)cmd_line, cmd_len-1));
if (CreateProcessW(NULL, cmd.text,
NULL, NULL, true, 0, NULL, NULL,
&start_info, &pi)) {
WaitForSingleObject(pi.hProcess, INFINITE);
GetExitCodeProcess(pi.hProcess, cast(DWORD *)&exit_code);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
} else {
// NOTE(bill): failed to create process
gb_printf_err("Failed to execute command:\n\t%s\n", cmd_line);
exit_code = -1;
}
gb_temp_arena_memory_end(tmp);
return exit_code;
}
#elif defined(GB_SYSTEM_OSX) || defined(GB_SYSTEM_UNIX)
i32 system_exec_command_line_app(char *name, bool is_silent, char *fmt, ...) {
char cmd_line[4096] = {0};
isize cmd_len;
va_list va;
String cmd;
i32 exit_code = 0;
va_start(va, fmt);
cmd_len = gb_snprintf_va(cmd_line, gb_size_of(cmd_line), fmt, va);
va_end(va);
cmd = make_string(cast(u8 *)&cmd_line, cmd_len-1);
exit_code = system(&cmd_line[0]);
// pid_t pid = fork();
// int status = 0;
// if(pid == 0) {
// // in child, pid == 0.
// int ret = execvp(cmd.text, (char* const*) cmd.text);
// if(ret == -1) {
// gb_printf_err("Failed to execute command:\n\t%s\n", cmd_line);
// // we're in the child, so returning won't do us any good -- just quit.
// exit(-1);
// }
// // unreachable
// abort();
// } else {
// // wait for child to finish, then we can continue cleanup
// int s = 0;
// waitpid(pid, &s, 0);
// status = WEXITSTATUS(s);
// }
// exit_code = status;
return exit_code;
}
#endif
void print_usage_line(i32 indent, char *fmt, ...) {
while (indent --> 0) {
gb_printf_err("\t");
}
va_list va;
va_start(va, fmt);
gb_printf_err_va(fmt, va);
va_end(va);
gb_printf_err("\n");
}
void usage(char *argv0) {
print_usage_line(0, "%s is a tool for managing Odin source code", argv0);
print_usage_line(0, "Usage:");
print_usage_line(1, "%s command [arguments]", argv0);
print_usage_line(0, "Commands:");
print_usage_line(1, "build compile .odin file as executable");
print_usage_line(1, "build_dll compile .odin file as dll");
print_usage_line(1, "run compile and run .odin file");
print_usage_line(1, "version print version");
}
int main(int argc, char **argv) {
if (argc < 2) {
usage(argv[0]);
return 1;
}
Timings timings = {0};
timings_init(&timings, str_lit("Total Time"), 128);
// defer (timings_destroy(&timings));
init_string_buffer_memory();
init_scratch_memory(gb_megabytes(10));
init_global_error_collector();
#if 1
init_build_context();
init_universal_scope();
char *init_filename = NULL;
bool run_output = false;
String arg1 = make_string_c(argv[1]);
if (str_eq(arg1, str_lit("run"))) {
if (argc != 3) {
usage(argv[0]);
return 1;
}
init_filename = argv[2];
run_output = true;
} else if (str_eq(arg1, str_lit("build_dll"))) {
if (argc != 3) {
usage(argv[0]);
return 1;
}
init_filename = argv[2];
build_context.is_dll = true;
} else if (str_eq(arg1, str_lit("build"))) {
if (argc != 3) {
usage(argv[0]);
return 1;
}
init_filename = argv[2];
} else if (str_eq(arg1, str_lit("version"))) {
gb_printf("%s version %.*s", argv[0], LIT(build_context.ODIN_VERSION));
return 0;
} else {
usage(argv[0]);
return 1;
}
// TODO(bill): prevent compiling without a linker
timings_start_section(&timings, str_lit("parse files"));
Parser parser = {0};
if (!init_parser(&parser)) {
return 1;
}
// defer (destroy_parser(&parser));
if (parse_files(&parser, init_filename) != ParseFile_None) {
return 1;
}
#if 1
timings_start_section(&timings, str_lit("type check"));
Checker checker = {0};
init_checker(&checker, &parser, &build_context);
// defer (destroy_checker(&checker));
check_parsed_files(&checker);
#endif
#if USE_CUSTOM_BACKEND
if (global_error_collector.count != 0) {
return 1;
}
if (checker.parser->total_token_count < 2) {
return 1;
}
if (!ssa_generate(&parser, &checker.info)) {
return 1;
}
#else
irGen ir_gen = {0};
if (!ir_gen_init(&ir_gen, &checker)) {
return 1;
}
// defer (ssa_gen_destroy(&ir_gen));
timings_start_section(&timings, str_lit("llvm ir gen"));
ir_gen_tree(&ir_gen);
timings_start_section(&timings, str_lit("llvm ir opt tree"));
ir_opt_tree(&ir_gen);
timings_start_section(&timings, str_lit("llvm ir print"));
print_llvm_ir(&ir_gen);
// prof_print_all();
#if 1
timings_start_section(&timings, str_lit("llvm-opt"));
String output_name = ir_gen.output_name;
String output_base = ir_gen.output_base;
int base_name_len = output_base.len;
i32 optimization_level = 0;
optimization_level = gb_clamp(optimization_level, 0, 3);
i32 exit_code = 0;
#if defined(GB_SYSTEM_WINDOWS)
// For more passes arguments: http://llvm.org/docs/Passes.html
exit_code = system_exec_command_line_app("llvm-opt", false,
"\"%.*sbin/opt\" \"%.*s\".ll -o \"%.*s\".bc "
"-mem2reg "
"-memcpyopt "
"-die "
// "-dse "
// "-dce "
// "-S "
"",
LIT(build_context.ODIN_ROOT),
LIT(output_base), LIT(output_base));
if (exit_code != 0) {
return exit_code;
}
#else
// NOTE(zangent): This is separate because it seems that LLVM tools are packaged
// with the Windows version, while they will be system-provided on MacOS and GNU/Linux
exit_code = system_exec_command_line_app("llvm-opt", false,
"opt \"%.*s\".ll -o \"%.*s\".bc "
"-mem2reg "
"-memcpyopt "
"-die "
#if defined(GB_SYSTEM_OSX)
// This sets a requirement of Mountain Lion and up, but the compiler doesn't work without this limit.
// NOTE: If you change this (although this minimum is as low as you can go with Odin working)
// make sure to also change the `macosx_version_min` param passed to `llc`
"-mtriple=x86_64-apple-macosx10.8 "
#endif
// "-dse "
// "-dce "
// "-S "
"",
LIT(output_base), LIT(output_base));
if (exit_code != 0) {
return exit_code;
}
#endif
#if defined(GB_SYSTEM_WINDOWS)
timings_start_section(&timings, str_lit("llvm-llc"));
// For more arguments: http://llvm.org/docs/CommandGuide/llc.html
exit_code = system_exec_command_line_app("llvm-llc", false,
"\"%.*sbin/llc\" \"%.*s.bc\" -filetype=obj -O%d "
"%.*s "
// "-debug-pass=Arguments "
"",
LIT(build_context.ODIN_ROOT),
LIT(output_base),
optimization_level,
LIT(build_context.llc_flags));
if (exit_code != 0) {
return exit_code;
}
timings_start_section(&timings, str_lit("msvc-link"));
gbString lib_str = gb_string_make(heap_allocator(), "");
// defer (gb_string_free(lib_str));
char lib_str_buf[1024] = {0};
for_array(i, ir_gen.module.foreign_library_paths) {
String lib = ir_gen.module.foreign_library_paths.e[i];
// gb_printf_err("Linking lib: %.*s\n", LIT(lib));
isize len = gb_snprintf(lib_str_buf, gb_size_of(lib_str_buf),
" \"%.*s\"", LIT(lib));
lib_str = gb_string_appendc(lib_str, lib_str_buf);
}
char *output_ext = "exe";
char *link_settings = "";
if (build_context.is_dll) {
output_ext = "dll";
link_settings = "/DLL";
} else {
link_settings = "/ENTRY:mainCRTStartup";
}
exit_code = system_exec_command_line_app("msvc-link", true,
"link \"%.*s\".obj -OUT:\"%.*s.%s\" %s "
"/defaultlib:libcmt "
"/nologo /incremental:no /opt:ref /subsystem:CONSOLE "
" %.*s "
" %s "
"",
LIT(output_base), LIT(output_base), output_ext,
lib_str, LIT(build_context.link_flags),
link_settings
);
if (exit_code != 0) {
return exit_code;
}
// timings_print_all(&timings);
if (run_output) {
system_exec_command_line_app("odin run", false, "%.*s.exe", LIT(output_base));
}
#else
// NOTE(zangent): Linux / Unix is unfinished and not tested very well.
timings_start_section(&timings, str_lit("llvm-llc"));
// For more arguments: http://llvm.org/docs/CommandGuide/llc.html
exit_code = system_exec_command_line_app("llc", false,
"llc \"%.*s.bc\" -filetype=obj -O%d "
"%.*s "
// "-debug-pass=Arguments "
"",
LIT(output_base),
optimization_level,
LIT(build_context.llc_flags));
if (exit_code != 0) {
return exit_code;
}
timings_start_section(&timings, str_lit("ld-link"));
gbString lib_str = gb_string_make(heap_allocator(), "");
// defer (gb_string_free(lib_str));
char lib_str_buf[1024] = {0};
for_array(i, ir_gen.module.foreign_library_paths) {
String lib = ir_gen.module.foreign_library_paths.e[i];
// NOTE(zangent): Sometimes, you have to use -framework on MacOS.
// This allows you to specify '-f' in a #foreign_system_library,
// without having to implement any new syntax specifically for MacOS.
#if defined(GB_SYSTEM_OSX)
isize len;
if(lib.len > 2 && lib.text[0] == '-' && lib.text[1] == 'f') {
len = gb_snprintf(lib_str_buf, gb_size_of(lib_str_buf),
" -framework %.*s ", (int)(lib.len) - 2, lib.text + 2);
} else {
len = gb_snprintf(lib_str_buf, gb_size_of(lib_str_buf),
" -l%.*s ", LIT(lib));
}
#else
isize len = gb_snprintf(lib_str_buf, gb_size_of(lib_str_buf),
" -l%.*s ", LIT(lib));
#endif
lib_str = gb_string_appendc(lib_str, lib_str_buf);
}
// Unlike the Win32 linker code, the output_ext includes the dot, because
// typically executable files on *NIX systems don't have extensions.
char *output_ext = "";
char *link_settings = "";
char *linker;
if (build_context.is_dll) {
// Shared libraries are .dylib on MacOS and .so on Linux.
// TODO(zangent): Is that statement entirely truthful?
#if defined(GB_SYSTEM_OSX)
output_ext = ".dylib";
#else
output_ext = ".so";
#endif
link_settings = "-shared";
} else {
// TODO: Do I need anything here?
link_settings = "";
}
#if defined(GB_SYSTEM_OSX)
linker = "ld";
#else
// TODO(zangent): Figure out how to make ld work on Linux.
// It probably has to do with including the entire CRT, but
// that's quite a complicated issue to solve while remaining distro-agnostic.
// Clang can figure out linker flags for us, and that's good enough _for now_.
linker = "clang -Wno-unused-command-line-argument";
#endif
exit_code = system_exec_command_line_app("ld-link", true,
"%s \"%.*s\".o -o \"%.*s%s\" %s "
"-lc -lm "
" %.*s "
" %s "
#if defined(GB_SYSTEM_OSX)
// This sets a requirement of Mountain Lion and up, but the compiler doesn't work without this limit.
// NOTE: If you change this (although this minimum is as low as you can go with Odin working)
// make sure to also change the `mtriple` param passed to `opt`
" -macosx_version_min 10.8.0 "
// This points the linker to where the entry point is
" -e _main "
#endif
, linker, LIT(output_base), LIT(output_base), output_ext,
lib_str, LIT(build_context.link_flags),
link_settings
);
if (exit_code != 0) {
return exit_code;
}
// timings_print_all(&timings);
if (run_output) {
system_exec_command_line_app("odin run", false, "%.*s", LIT(output_base));
}
#endif
#endif
#endif
#endif
return 0;
}
#if defined(__cplusplus)
}
#endif
+679
View File
@@ -0,0 +1,679 @@
#define USE_CUSTOM_BACKEND 0
// #define PRINT_TIMINGS
#include "common.cpp"
#include "timings.cpp"
#include "build_settings.cpp"
#include "tokenizer.cpp"
#include "parser.cpp"
#include "docs.cpp"
#include "checker.cpp"
#include "ssa.cpp"
#include "ir.cpp"
#include "ir_opt.cpp"
#include "ir_print.cpp"
#if defined(GB_SYSTEM_WINDOWS)
// NOTE(bill): `name` is used in debugging and profiling modes
i32 system_exec_command_line_app(char *name, bool is_silent, char *fmt, ...) {
STARTUPINFOW start_info = {gb_size_of(STARTUPINFOW)};
PROCESS_INFORMATION pi = {0};
char cmd_line[4096] = {0};
isize cmd_len;
va_list va;
gbTempArenaMemory tmp;
String16 cmd;
i32 exit_code = 0;
start_info.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
start_info.wShowWindow = SW_SHOW;
start_info.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
start_info.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
start_info.hStdError = GetStdHandle(STD_ERROR_HANDLE);
va_start(va, fmt);
cmd_len = gb_snprintf_va(cmd_line, gb_size_of(cmd_line), fmt, va);
va_end(va);
// gb_printf_err("%.*s\n", cast(int)cmd_len, cmd_line);
tmp = gb_temp_arena_memory_begin(&string_buffer_arena);
cmd = string_to_string16(string_buffer_allocator, make_string(cast(u8 *)cmd_line, cmd_len-1));
if (CreateProcessW(NULL, cmd.text,
NULL, NULL, true, 0, NULL, NULL,
&start_info, &pi)) {
WaitForSingleObject(pi.hProcess, INFINITE);
GetExitCodeProcess(pi.hProcess, cast(DWORD *)&exit_code);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
} else {
// NOTE(bill): failed to create process
gb_printf_err("Failed to execute command:\n\t%s\n", cmd_line);
exit_code = -1;
}
gb_temp_arena_memory_end(tmp);
return exit_code;
}
#elif defined(GB_SYSTEM_OSX) || defined(GB_SYSTEM_UNIX)
i32 system_exec_command_line_app(char *name, bool is_silent, char *fmt, ...) {
char cmd_line[4096] = {0};
isize cmd_len;
va_list va;
String cmd;
i32 exit_code = 0;
va_start(va, fmt);
cmd_len = gb_snprintf_va(cmd_line, gb_size_of(cmd_line), fmt, va);
va_end(va);
cmd = make_string(cast(u8 *)&cmd_line, cmd_len-1);
exit_code = system(&cmd_line[0]);
// pid_t pid = fork();
// int status = 0;
// if(pid == 0) {
// // in child, pid == 0.
// int ret = execvp(cmd.text, (char* const*) cmd.text);
// if(ret == -1) {
// gb_printf_err("Failed to execute command:\n\t%s\n", cmd_line);
// // we're in the child, so returning won't do us any good -- just quit.
// exit(-1);
// }
// // unreachable
// abort();
// } else {
// // wait for child to finish, then we can continue cleanup
// int s = 0;
// waitpid(pid, &s, 0);
// status = WEXITSTATUS(s);
// }
// exit_code = status;
return exit_code;
}
#endif
Array<String> setup_args(int argc, char **argv) {
Array<String> args = {};
gbAllocator a = heap_allocator();
int i;
#if defined(GB_SYSTEM_WINDOWS)
int wargc = 0;
wchar_t **wargv = command_line_to_wargv(GetCommandLineW(), &wargc);
array_init(&args, a, wargc);
for (i = 0; i < wargc; i++) {
wchar_t *warg = wargv[i];
isize wlen = string16_len(warg);
String16 wstr = make_string16(warg, wlen);
String arg = string16_to_string(a, wstr);
if (arg.len > 0) {
array_add(&args, arg);
}
}
#else
array_init(&args, a, argc);
for (i = 0; i < argc; i++) {
String arg = make_string_c(argv[i]);
if (arg.len > 0) {
array_add(&args, arg);
}
}
#endif
return args;
}
void print_usage_line(i32 indent, char *fmt, ...) {
while (indent --> 0) {
gb_printf_err("\t");
}
va_list va;
va_start(va, fmt);
gb_printf_err_va(fmt, va);
va_end(va);
gb_printf_err("\n");
}
void usage(String argv0) {
print_usage_line(0, "%.*s is a tool for managing Odin source code", LIT(argv0));
print_usage_line(0, "Usage:");
print_usage_line(1, "%.*s command [arguments]", LIT(argv0));
print_usage_line(0, "Commands:");
print_usage_line(1, "build compile .odin file as executable");
print_usage_line(1, "build_dll compile .odin file as dll");
print_usage_line(1, "run compile and run .odin file");
print_usage_line(1, "docs generate documentation for a .odin file");
print_usage_line(1, "version print version");
}
enum BuildFlagKind {
BuildFlag_Invalid,
BuildFlag_OptimizationLevel,
BuildFlag_COUNT,
};
enum BuildFlagParamKind {
BuildFlagParam_None,
BuildFlagParam_Boolean,
BuildFlagParam_Integer,
BuildFlagParam_Float,
BuildFlagParam_String,
BuildFlagParam_COUNT,
};
struct BuildFlag {
BuildFlagKind kind;
String name;
BuildFlagParamKind param_kind;
};
void add_flag(Array<BuildFlag> *build_flags, BuildFlagKind kind, String name, BuildFlagParamKind param_kind) {
BuildFlag flag = {kind, name, param_kind};
array_add(build_flags, flag);
}
bool parse_build_flags(Array<String> args) {
Array<BuildFlag> build_flags = {};
array_init(&build_flags, heap_allocator(), BuildFlag_COUNT);
add_flag(&build_flags, BuildFlag_OptimizationLevel, str_lit("opt"), BuildFlagParam_Integer);
Array<String> flag_args = args;
flag_args.data += 3;
flag_args.count -= 3;
bool set_flags[BuildFlag_COUNT] = {};
bool bad_flags = false;
for_array(i, flag_args) {
String flag = flag_args[i];
if (flag[0] != '-') {
gb_printf_err("Invalid flag: %.*s\n", LIT(flag));
} else {
String name = substring(flag, 1, flag.len);
isize end = 0;
for (; end < name.len; end++) {
if (name[end] == '=') {
break;
}
}
name.len = end;
String param = substring(flag, 2+end, flag.len);
bool found = false;
for_array(build_flag_index, build_flags) {
BuildFlag bf = build_flags[build_flag_index];
if (bf.name == name) {
found = true;
if (set_flags[bf.kind]) {
gb_printf_err("Previous flag set: `%.*s`\n", LIT(name));
bad_flags = true;
} else {
ExactValue value = {};
bool ok = false;
if (bf.param_kind == BuildFlagParam_None) {
if (param.len == 0) {
ok = true;
} else {
gb_printf_err("Flag `%.*s` was not expecting a parameter `%.*s`\n", LIT(name), LIT(param));
bad_flags = true;
}
} else {
if (param.len == 0) {
gb_printf_err("Flag missing for `%.*s`\n", LIT(name));
bad_flags = true;
} else {
ok = true;
switch (bf.param_kind) {
default: ok = false; break;
case BuildFlagParam_Boolean: {
if (param == "t") {
value = exact_value_bool(true);
} else if (param == "T") {
value = exact_value_bool(true);
} else if (param == "true") {
value = exact_value_bool(true);
} else if (param == "TRUE") {
value = exact_value_bool(true);
} else if (param == "1") {
value = exact_value_bool(true);
} else if (param == "f") {
value = exact_value_bool(false);
} else if (param == "F") {
value = exact_value_bool(false);
} else if (param == "false") {
value = exact_value_bool(false);
} else if (param == "FALSE") {
value = exact_value_bool(false);
} else if (param == "0") {
value = exact_value_bool(false);
} else {
gb_printf_err("Invalid flag parameter for `%.*s` = `%.*s`\n", LIT(name), LIT(param));
}
} break;
case BuildFlagParam_Integer:
value = exact_value_integer_from_string(param);
break;
case BuildFlagParam_Float:
value = exact_value_float_from_string(param);
break;
case BuildFlagParam_String:
value = exact_value_string(param);
break;
}
}
}
if (ok) {
switch (bf.kind) {
case BuildFlag_OptimizationLevel:
if (value.kind == ExactValue_Integer) {
build_context.optimization_level = cast(i32)i128_to_i64(value.value_integer);
} else {
gb_printf_err("%.*s expected an integer, got %.*s", LIT(name), LIT(param));
bad_flags = true;
ok = false;
}
break;
}
}
set_flags[bf.kind] = ok;
}
break;
}
}
if (!found) {
gb_printf_err("Unknown flag: `%.*s`\n", LIT(name));
bad_flags = true;
}
}
}
return !bad_flags;
}
int main(int arg_count, char **arg_ptr) {
if (arg_count < 2) {
usage(make_string_c(arg_ptr[0]));
return 1;
}
Timings timings = {0};
timings_init(&timings, str_lit("Total Time"), 128);
defer (timings_destroy(&timings));
init_string_buffer_memory();
init_scratch_memory(gb_megabytes(10));
init_global_error_collector();
Array<String> args = setup_args(arg_count, arg_ptr);
#if 1
String init_filename = {};
bool run_output = false;
if (args[1] == "run") {
if (args.count < 3) {
usage(args[0]);
return 1;
}
init_filename = args[2];
run_output = true;
} else if (args[1] == "build_dll") {
if (args.count < 3) {
usage(args[0]);
return 1;
}
init_filename = args[2];
build_context.is_dll = true;
} else if (args[1] == "build") {
if (args.count < 3) {
usage(args[0]);
return 1;
}
init_filename = args[2];
} else if (args[1] == "docs") {
if (args.count < 3) {
usage(args[0]);
return 1;
}
init_filename = args[2];
build_context.generate_docs = true;
#if 1
print_usage_line(0, "Documentation generation is not yet supported");
return 1;
#endif
} else if (args[1] == "version") {
gb_printf("%s version %.*s\n", args[0], LIT(build_context.ODIN_VERSION));
return 0;
} else {
usage(args[0]);
return 1;
}
if (!parse_build_flags(args)) {
return 1;
}
init_build_context();
if (build_context.word_size == 4) {
print_usage_line(0, "%s 32-bit is not yet supported", args[0]);
return 1;
}
init_universal_scope();
// TODO(bill): prevent compiling without a linker
timings_start_section(&timings, str_lit("parse files"));
Parser parser = {0};
if (!init_parser(&parser)) {
return 1;
}
defer (destroy_parser(&parser));
if (parse_files(&parser, init_filename) != ParseFile_None) {
return 1;
}
if (build_context.generate_docs) {
generate_documentation(&parser);
return 0;
}
#if 1
timings_start_section(&timings, str_lit("type check"));
Checker checker = {0};
init_checker(&checker, &parser);
defer (destroy_checker(&checker));
check_parsed_files(&checker);
#endif
#if defined(USE_CUSTOM_BACKEND) && USE_CUSTOM_BACKEND
if (global_error_collector.count != 0) {
return 1;
}
if (checker.parser->total_token_count < 2) {
return 1;
}
if (!ssa_generate(&parser, &checker.info)) {
return 1;
}
#else
irGen ir_gen = {0};
if (!ir_gen_init(&ir_gen, &checker)) {
return 1;
}
defer (ir_gen_destroy(&ir_gen));
timings_start_section(&timings, str_lit("llvm ir gen"));
ir_gen_tree(&ir_gen);
timings_start_section(&timings, str_lit("llvm ir opt tree"));
ir_opt_tree(&ir_gen);
timings_start_section(&timings, str_lit("llvm ir print"));
print_llvm_ir(&ir_gen);
// prof_print_all();
#if 1
timings_start_section(&timings, str_lit("llvm-opt"));
String output_name = ir_gen.output_name;
String output_base = ir_gen.output_base;
int base_name_len = output_base.len;
build_context.optimization_level = gb_clamp(build_context.optimization_level, 0, 3);
i32 exit_code = 0;
#if defined(GB_SYSTEM_WINDOWS)
// For more passes arguments: http://llvm.org/docs/Passes.html
exit_code = system_exec_command_line_app("llvm-opt", false,
"\"%.*sbin/opt\" \"%.*s\".ll -o \"%.*s\".bc %.*s "
"-mem2reg "
"-memcpyopt "
"-die "
"",
LIT(build_context.ODIN_ROOT),
LIT(output_base), LIT(output_base),
LIT(build_context.opt_flags));
if (exit_code != 0) {
return exit_code;
}
#else
// NOTE(zangent): This is separate because it seems that LLVM tools are packaged
// with the Windows version, while they will be system-provided on MacOS and GNU/Linux
exit_code = system_exec_command_line_app("llvm-opt", false,
"opt \"%.*s\".ll -o \"%.*s\".bc %.*s "
"-mem2reg "
"-memcpyopt "
"-die "
#if defined(GB_SYSTEM_OSX)
// This sets a requirement of Mountain Lion and up, but the compiler doesn't work without this limit.
// NOTE: If you change this (although this minimum is as low as you can go with Odin working)
// make sure to also change the `macosx_version_min` param passed to `llc`
"-mtriple=x86_64-apple-macosx10.8 "
#endif
"",
LIT(output_base), LIT(output_base),
LIT(build_context.opt_flags));
if (exit_code != 0) {
return exit_code;
}
#endif
#if defined(GB_SYSTEM_WINDOWS)
timings_start_section(&timings, str_lit("llvm-llc"));
// For more arguments: http://llvm.org/docs/CommandGuide/llc.html
exit_code = system_exec_command_line_app("llvm-llc", false,
"\"%.*sbin/llc\" \"%.*s.bc\" -filetype=obj -O%d "
"%.*s "
// "-debug-pass=Arguments "
"",
LIT(build_context.ODIN_ROOT),
LIT(output_base),
build_context.optimization_level,
LIT(build_context.llc_flags));
if (exit_code != 0) {
return exit_code;
}
timings_start_section(&timings, str_lit("msvc-link"));
gbString lib_str = gb_string_make(heap_allocator(), "");
defer (gb_string_free(lib_str));
char lib_str_buf[1024] = {0};
for_array(i, ir_gen.module.foreign_library_paths) {
String lib = ir_gen.module.foreign_library_paths[i];
// gb_printf_err("Linking lib: %.*s\n", LIT(lib));
isize len = gb_snprintf(lib_str_buf, gb_size_of(lib_str_buf),
" \"%.*s\"", LIT(lib));
lib_str = gb_string_appendc(lib_str, lib_str_buf);
}
char *output_ext = "exe";
char *link_settings = "";
if (build_context.is_dll) {
output_ext = "dll";
link_settings = "/DLL";
} else {
link_settings = "/ENTRY:mainCRTStartup";
}
exit_code = system_exec_command_line_app("msvc-link", true,
"link \"%.*s\".obj -OUT:\"%.*s.%s\" %s "
"/defaultlib:libcmt "
// "/nodefaultlib "
"/nologo /incremental:no /opt:ref /subsystem:CONSOLE "
" %.*s "
" %s "
"",
LIT(output_base), LIT(output_base), output_ext,
lib_str, LIT(build_context.link_flags),
link_settings
);
if (exit_code != 0) {
return exit_code;
}
#if defined(PRINT_TIMINGS)
timings_print_all(&timings);
#endif
if (run_output) {
system_exec_command_line_app("odin run", false, "%.*s.exe", LIT(output_base));
}
#else
// NOTE(zangent): Linux / Unix is unfinished and not tested very well.
timings_start_section(&timings, str_lit("llvm-llc"));
// For more arguments: http://llvm.org/docs/CommandGuide/llc.html
exit_code = system_exec_command_line_app("llc", false,
"llc \"%.*s.bc\" -filetype=obj -relocation-model=pic -O%d "
"%.*s "
// "-debug-pass=Arguments "
"",
LIT(output_base),
build_context.optimization_level,
LIT(build_context.llc_flags));
if (exit_code != 0) {
return exit_code;
}
timings_start_section(&timings, str_lit("ld-link"));
gbString lib_str = gb_string_make(heap_allocator(), "");
defer (gb_string_free(lib_str));
char lib_str_buf[1024] = {0};
for_array(i, ir_gen.module.foreign_library_paths) {
String lib = ir_gen.module.foreign_library_paths[i];
// NOTE(zangent): Sometimes, you have to use -framework on MacOS.
// This allows you to specify '-f' in a #foreign_system_library,
// without having to implement any new syntax specifically for MacOS.
#if defined(GB_SYSTEM_OSX)
isize len;
if(lib.len > 2 && lib[0] == '-' && lib[1] == 'f') {
len = gb_snprintf(lib_str_buf, gb_size_of(lib_str_buf),
" -framework %.*s ", (int)(lib.len) - 2, lib.text + 2);
} else {
len = gb_snprintf(lib_str_buf, gb_size_of(lib_str_buf),
" -l%.*s ", LIT(lib));
}
#else
isize len = gb_snprintf(lib_str_buf, gb_size_of(lib_str_buf),
" -l%.*s ", LIT(lib));
#endif
lib_str = gb_string_appendc(lib_str, lib_str_buf);
}
// Unlike the Win32 linker code, the output_ext includes the dot, because
// typically executable files on *NIX systems don't have extensions.
char *output_ext = "";
char *link_settings = "";
char *linker;
if (build_context.is_dll) {
// Shared libraries are .dylib on MacOS and .so on Linux.
// TODO(zangent): Is that statement entirely truthful?
#if defined(GB_SYSTEM_OSX)
output_ext = ".dylib";
#else
output_ext = ".so";
#endif
link_settings = "-shared";
} else {
// TODO: Do I need anything here?
link_settings = "";
}
#if defined(GB_SYSTEM_OSX)
linker = "ld";
#else
// TODO(zangent): Figure out how to make ld work on Linux.
// It probably has to do with including the entire CRT, but
// that's quite a complicated issue to solve while remaining distro-agnostic.
// Clang can figure out linker flags for us, and that's good enough _for now_.
linker = "clang -Wno-unused-command-line-argument";
#endif
exit_code = system_exec_command_line_app("ld-link", true,
"%s \"%.*s\".o -o \"%.*s%s\" %s "
"-lc -lm "
" %.*s "
" %s "
#if defined(GB_SYSTEM_OSX)
// This sets a requirement of Mountain Lion and up, but the compiler doesn't work without this limit.
// NOTE: If you change this (although this minimum is as low as you can go with Odin working)
// make sure to also change the `mtriple` param passed to `opt`
" -macosx_version_min 10.8.0 "
// This points the linker to where the entry point is
" -e _main "
#endif
, linker, LIT(output_base), LIT(output_base), output_ext,
lib_str, LIT(build_context.link_flags),
link_settings
);
if (exit_code != 0) {
return exit_code;
}
#if defined(PRINT_TIMINGS)
timings_print_all(&timings);
#endif
if (run_output) {
system_exec_command_line_app("odin run", false, "%.*s", LIT(output_base));
}
#endif
#endif
#endif
#endif
return 0;
}
-361
View File
@@ -1,361 +0,0 @@
/*
Example of usage:
#define MAP_TYPE String
#define MAP_PROC map_string_
#define MAP_NAME MapString
#include "map.c"
*/
// A `Map` is an unordered hash table which can allow for a key to point to multiple values
// with the use of the `multi_*` procedures.
// TODO(bill): I should probably allow the `multi_*` stuff to be #ifdefed out
#ifndef MAP_UTIL_STUFF
#define MAP_UTIL_STUFF
// NOTE(bill): This util stuff is the same for every `Map`
typedef struct MapFindResult {
isize hash_index;
isize entry_prev;
isize entry_index;
} MapFindResult;
typedef enum HashKeyKind {
HashKey_Default,
HashKey_String,
HashKey_Pointer,
} HashKeyKind;
typedef struct HashKey {
HashKeyKind kind;
u64 key;
union {
String string; // if String, s.len > 0
void * ptr;
};
} HashKey;
gb_inline HashKey hashing_proc(void const *data, isize len) {
HashKey h = {HashKey_Default};
h.kind = HashKey_Default;
// h.key = gb_murmur64(data, len);
h.key = gb_fnv64a(data, len);
return h;
}
gb_inline HashKey hash_string(String s) {
HashKey h = hashing_proc(s.text, s.len);
h.kind = HashKey_String;
h.string = s;
return h;
}
gb_inline HashKey hash_pointer(void *ptr) {
HashKey h = {HashKey_Default};
h.key = cast(u64)cast(uintptr)ptr;
h.ptr = ptr;
h.kind = HashKey_Default;
return h;
}
bool hash_key_equal(HashKey a, HashKey b) {
if (a.key == b.key) {
// NOTE(bill): If two string's hashes collide, compare the strings themselves
if (a.kind == HashKey_String) {
if (b.kind == HashKey_String) {
return str_eq(a.string, b.string);
}
return false;
}
return true;
}
return false;
}
#endif
#define _J2_IND(a, b) a##b
#define _J2(a, b) _J2_IND(a, b)
/*
MAP_TYPE - Entry type
MAP_PROC - Function prefix (e.g. entity_map_)
MAP_NAME - Name of Map (e.g. EntityMap)
*/
#define MAP_ENTRY _J2(MAP_NAME,Entry)
typedef struct MAP_ENTRY {
HashKey key;
isize next;
MAP_TYPE value;
} MAP_ENTRY;
typedef struct MAP_NAME {
Array(isize) hashes;
Array(MAP_ENTRY) entries;
} MAP_NAME;
void _J2(MAP_PROC,init) (MAP_NAME *h, gbAllocator a);
void _J2(MAP_PROC,init_with_reserve)(MAP_NAME *h, gbAllocator a, isize capacity);
void _J2(MAP_PROC,destroy) (MAP_NAME *h);
MAP_TYPE *_J2(MAP_PROC,get) (MAP_NAME *h, HashKey key);
void _J2(MAP_PROC,set) (MAP_NAME *h, HashKey key, MAP_TYPE value);
void _J2(MAP_PROC,remove) (MAP_NAME *h, HashKey key);
void _J2(MAP_PROC,clear) (MAP_NAME *h);
void _J2(MAP_PROC,grow) (MAP_NAME *h);
void _J2(MAP_PROC,rehash) (MAP_NAME *h, isize new_count);
// Mutlivalued map procedure
MAP_ENTRY *_J2(MAP_PROC,multi_find_first)(MAP_NAME *h, HashKey key);
MAP_ENTRY *_J2(MAP_PROC,multi_find_next) (MAP_NAME *h, MAP_ENTRY *e);
isize _J2(MAP_PROC,multi_count) (MAP_NAME *h, HashKey key);
void _J2(MAP_PROC,multi_get_all) (MAP_NAME *h, HashKey key, MAP_TYPE *items);
void _J2(MAP_PROC,multi_insert) (MAP_NAME *h, HashKey key, MAP_TYPE value);
void _J2(MAP_PROC,multi_remove) (MAP_NAME *h, HashKey key, MAP_ENTRY *e);
void _J2(MAP_PROC,multi_remove_all)(MAP_NAME *h, HashKey key);
gb_inline void _J2(MAP_PROC,init)(MAP_NAME *h, gbAllocator a) {
array_init(&h->hashes, a);
array_init(&h->entries, a);
}
gb_inline void _J2(MAP_PROC,init_with_reserve)(MAP_NAME *h, gbAllocator a, isize capacity) {
array_init_reserve(&h->hashes, a, capacity);
array_init_reserve(&h->entries, a, capacity);
}
gb_inline void _J2(MAP_PROC,destroy)(MAP_NAME *h) {
array_free(&h->entries);
array_free(&h->hashes);
}
gb_internal isize _J2(MAP_PROC,_add_entry)(MAP_NAME *h, HashKey key) {
MAP_ENTRY e = {0};
e.key = key;
e.next = -1;
array_add(&h->entries, e);
return h->entries.count-1;
}
gb_internal MapFindResult _J2(MAP_PROC,_find)(MAP_NAME *h, HashKey key) {
MapFindResult fr = {-1, -1, -1};
if (h->hashes.count > 0) {
fr.hash_index = key.key % h->hashes.count;
fr.entry_index = h->hashes.e[fr.hash_index];
while (fr.entry_index >= 0) {
if (hash_key_equal(h->entries.e[fr.entry_index].key, key)) {
return fr;
}
fr.entry_prev = fr.entry_index;
fr.entry_index = h->entries.e[fr.entry_index].next;
}
}
return fr;
}
gb_internal MapFindResult _J2(MAP_PROC,_find_from_entry)(MAP_NAME *h, MAP_ENTRY *e) {
MapFindResult fr = {-1, -1, -1};
if (h->hashes.count > 0) {
fr.hash_index = e->key.key % h->hashes.count;
fr.entry_index = h->hashes.e[fr.hash_index];
while (fr.entry_index >= 0) {
if (&h->entries.e[fr.entry_index] == e) {
return fr;
}
fr.entry_prev = fr.entry_index;
fr.entry_index = h->entries.e[fr.entry_index].next;
}
}
return fr;
}
gb_internal b32 _J2(MAP_PROC,_full)(MAP_NAME *h) {
return 0.75f * h->hashes.count <= h->entries.count;
}
gb_inline void _J2(MAP_PROC,grow)(MAP_NAME *h) {
isize new_count = ARRAY_GROW_FORMULA(h->entries.count);
_J2(MAP_PROC,rehash)(h, new_count);
}
void _J2(MAP_PROC,rehash)(MAP_NAME *h, isize new_count) {
isize i, j;
MAP_NAME nh = {0};
_J2(MAP_PROC,init)(&nh, h->hashes.allocator);
array_resize(&nh.hashes, new_count);
array_reserve(&nh.entries, h->entries.count);
for (i = 0; i < new_count; i++) {
nh.hashes.e[i] = -1;
}
for (i = 0; i < h->entries.count; i++) {
MAP_ENTRY *e = &h->entries.e[i];
MapFindResult fr;
if (nh.hashes.count == 0) {
_J2(MAP_PROC,grow)(&nh);
}
fr = _J2(MAP_PROC,_find)(&nh, e->key);
j = _J2(MAP_PROC,_add_entry)(&nh, e->key);
if (fr.entry_prev < 0) {
nh.hashes.e[fr.hash_index] = j;
} else {
nh.entries.e[fr.entry_prev].next = j;
}
nh.entries.e[j].next = fr.entry_index;
nh.entries.e[j].value = e->value;
if (_J2(MAP_PROC,_full)(&nh)) {
_J2(MAP_PROC,grow)(&nh);
}
}
_J2(MAP_PROC,destroy)(h);
*h = nh;
}
gb_inline MAP_TYPE *_J2(MAP_PROC,get)(MAP_NAME *h, HashKey key) {
isize index = _J2(MAP_PROC,_find)(h, key).entry_index;
if (index >= 0) {
return &h->entries.e[index].value;
}
return NULL;
}
void _J2(MAP_PROC,set)(MAP_NAME *h, HashKey key, MAP_TYPE value) {
isize index;
MapFindResult fr;
if (h->hashes.count == 0)
_J2(MAP_PROC,grow)(h);
fr = _J2(MAP_PROC,_find)(h, key);
if (fr.entry_index >= 0) {
index = fr.entry_index;
} else {
index = _J2(MAP_PROC,_add_entry)(h, key);
if (fr.entry_prev >= 0) {
h->entries.e[fr.entry_prev].next = index;
} else {
h->hashes.e[fr.hash_index] = index;
}
}
h->entries.e[index].value = value;
if (_J2(MAP_PROC,_full)(h)) {
_J2(MAP_PROC,grow)(h);
}
}
void _J2(MAP_PROC,_erase)(MAP_NAME *h, MapFindResult fr) {
MapFindResult last;
if (fr.entry_prev < 0) {
h->hashes.e[fr.hash_index] = h->entries.e[fr.entry_index].next;
} else {
h->entries.e[fr.entry_prev].next = h->entries.e[fr.entry_index].next;
}
if (fr.entry_index == h->entries.count-1) {
array_pop(&h->entries);
return;
}
h->entries.e[fr.entry_index] = h->entries.e[h->entries.count-1];
last = _J2(MAP_PROC,_find)(h, h->entries.e[fr.entry_index].key);
if (last.entry_prev >= 0) {
h->entries.e[last.entry_prev].next = fr.entry_index;
} else {
h->hashes.e[last.hash_index] = fr.entry_index;
}
}
void _J2(MAP_PROC,remove)(MAP_NAME *h, HashKey key) {
MapFindResult fr = _J2(MAP_PROC,_find)(h, key);
if (fr.entry_index >= 0) {
_J2(MAP_PROC,_erase)(h, fr);
}
}
gb_inline void _J2(MAP_PROC,clear)(MAP_NAME *h) {
array_clear(&h->hashes);
array_clear(&h->entries);
}
#if 1
MAP_ENTRY *_J2(MAP_PROC,multi_find_first)(MAP_NAME *h, HashKey key) {
isize i = _J2(MAP_PROC,_find)(h, key).entry_index;
if (i < 0) {
return NULL;
}
return &h->entries.e[i];
}
MAP_ENTRY *_J2(MAP_PROC,multi_find_next)(MAP_NAME *h, MAP_ENTRY *e) {
isize i = e->next;
while (i >= 0) {
if (hash_key_equal(h->entries.e[i].key, e->key)) {
return &h->entries.e[i];
}
i = h->entries.e[i].next;
}
return NULL;
}
isize _J2(MAP_PROC,multi_count)(MAP_NAME *h, HashKey key) {
isize count = 0;
MAP_ENTRY *e = _J2(MAP_PROC,multi_find_first)(h, key);
while (e != NULL) {
count++;
e = _J2(MAP_PROC,multi_find_next)(h, e);
}
return count;
}
void _J2(MAP_PROC,multi_get_all)(MAP_NAME *h, HashKey key, MAP_TYPE *items) {
isize i = 0;
MAP_ENTRY *e = _J2(MAP_PROC,multi_find_first)(h, key);
while (e != NULL) {
items[i++] = e->value;
e = _J2(MAP_PROC,multi_find_next)(h, e);
}
}
void _J2(MAP_PROC,multi_insert)(MAP_NAME *h, HashKey key, MAP_TYPE value) {
MapFindResult fr;
isize i;
if (h->hashes.count == 0) {
_J2(MAP_PROC,grow)(h);
}
// Make
fr = _J2(MAP_PROC,_find)(h, key);
i = _J2(MAP_PROC,_add_entry)(h, key);
if (fr.entry_prev < 0) {
h->hashes.e[fr.hash_index] = i;
} else {
h->entries.e[fr.entry_prev].next = i;
}
h->entries.e[i].next = fr.entry_index;
h->entries.e[i].value = value;
// Grow if needed
if (_J2(MAP_PROC,_full)(h)) {
_J2(MAP_PROC,grow)(h);
}
}
void _J2(MAP_PROC,multi_remove)(MAP_NAME *h, HashKey key, MAP_ENTRY *e) {
MapFindResult fr = _J2(MAP_PROC,_find_from_entry)(h, e);
if (fr.entry_index >= 0) {
_J2(MAP_PROC,_erase)(h, fr);
}
}
void _J2(MAP_PROC,multi_remove_all)(MAP_NAME *h, HashKey key) {
while (_J2(MAP_PROC,get)(h, key) != NULL) {
_J2(MAP_PROC,remove)(h, key);
}
}
#endif
#undef _J2
#undef MAP_TYPE
#undef MAP_PROC
#undef MAP_NAME
#undef MAP_ENTRY
+381
View File
@@ -0,0 +1,381 @@
// A `Map` is an unordered hash table which can allow for a key to point to multiple values
// with the use of the `multi_*` procedures.
// TODO(bill): I should probably allow the `multi_map_*` stuff to be #ifdefed out
#ifndef MAP_UTIL_STUFF
#define MAP_UTIL_STUFF
// NOTE(bill): This util stuff is the same for every `Map`
struct MapFindResult {
isize hash_index;
isize entry_prev;
isize entry_index;
};
enum HashKeyKind {
HashKey_Default,
HashKey_String,
HashKey_Ptr,
HashKey_PtrAndId,
};
struct PtrAndId {
void *ptr;
u32 id;
};
struct HashKey {
HashKeyKind kind;
// u128 key;
u64 key;
union {
String string; // if String, s.len > 0
void * ptr;
PtrAndId ptr_and_id;
};
};
gb_inline HashKey hashing_proc(void const *data, isize len) {
HashKey h = {HashKey_Default};
h.kind = HashKey_Default;
// h.key = u128_from_u64(gb_fnv64a(data, len));
h.key = gb_fnv64a(data, len);
return h;
}
gb_inline HashKey hash_string(String s) {
HashKey h = hashing_proc(s.text, s.len);
h.kind = HashKey_String;
h.string = s;
return h;
}
gb_inline HashKey hash_pointer(void *ptr) {
HashKey h = {HashKey_Ptr};
h.key = cast(u64)cast(uintptr)ptr;
h.ptr = ptr;
return h;
}
gb_inline HashKey hash_ptr_and_id(void *ptr, u32 id) {
HashKey h = {HashKey_PtrAndId};
h.key = cast(u64)cast(uintptr)ptr;
h.ptr_and_id.ptr = ptr;
h.ptr_and_id.id = id;
return h;
}
bool hash_key_equal(HashKey a, HashKey b) {
if (a.key == b.key) {
// NOTE(bill): If two string's hashes collide, compare the strings themselves
if (a.kind == HashKey_String) {
if (b.kind == HashKey_String) {
return a.string == b.string;
}
return false;
} else if (a.kind == HashKey_PtrAndId) {
if (b.kind == HashKey_PtrAndId) {
return a.ptr_and_id.id == b.ptr_and_id.id;
}
return false;
}
return true;
}
return false;
}
bool operator==(HashKey a, HashKey b) { return hash_key_equal(a, b); }
bool operator!=(HashKey a, HashKey b) { return !hash_key_equal(a, b); }
#endif
template <typename T>
struct MapEntry {
HashKey key;
isize next;
T value;
};
template <typename T>
struct Map {
Array<isize> hashes;
Array<MapEntry<T> > entries;
};
template <typename T> void map_init (Map<T> *h, gbAllocator a);
template <typename T> void map_init_with_reserve(Map<T> *h, gbAllocator a, isize capacity);
template <typename T> void map_destroy (Map<T> *h);
template <typename T> T * map_get (Map<T> *h, HashKey key);
template <typename T> void map_set (Map<T> *h, HashKey key, T const &value);
template <typename T> void map_remove (Map<T> *h, HashKey key);
template <typename T> void map_clear (Map<T> *h);
template <typename T> void map_grow (Map<T> *h);
template <typename T> void map_rehash (Map<T> *h, isize new_count);
// Mutlivalued map procedure
template <typename T> MapEntry<T> * multi_map_find_first(Map<T> *h, HashKey key);
template <typename T> MapEntry<T> * multi_map_find_next (Map<T> *h, MapEntry<T> *e);
template <typename T> isize multi_map_count (Map<T> *h, HashKey key);
template <typename T> void multi_map_get_all (Map<T> *h, HashKey key, T *items);
template <typename T> void multi_map_insert (Map<T> *h, HashKey key, T const &value);
template <typename T> void multi_map_remove (Map<T> *h, HashKey key, MapEntry<T> *e);
template <typename T> void multi_map_remove_all(Map<T> *h, HashKey key);
template <typename T>
gb_inline void map_init(Map<T> *h, gbAllocator a) {
array_init(&h->hashes, a);
array_init(&h->entries, a);
}
template <typename T>
gb_inline void map_init_with_reserve(Map<T> *h, gbAllocator a, isize capacity) {
array_init(&h->hashes, a, capacity);
array_init(&h->entries, a, capacity);
}
template <typename T>
gb_inline void map_destroy(Map<T> *h) {
array_free(&h->entries);
array_free(&h->hashes);
}
template <typename T>
gb_internal isize map__add_entry(Map<T> *h, HashKey key) {
MapEntry<T> e = {};
e.key = key;
e.next = -1;
array_add(&h->entries, e);
return h->entries.count-1;
}
template <typename T>
gb_internal MapFindResult map__find(Map<T> *h, HashKey key) {
MapFindResult fr = {-1, -1, -1};
if (h->hashes.count > 0) {
// fr.hash_index = u128_to_i64(key.key % u128_from_i64(h->hashes.count));
fr.hash_index = key.key % h->hashes.count;
fr.entry_index = h->hashes[fr.hash_index];
while (fr.entry_index >= 0) {
if (hash_key_equal(h->entries[fr.entry_index].key, key)) {
return fr;
}
fr.entry_prev = fr.entry_index;
fr.entry_index = h->entries[fr.entry_index].next;
}
}
return fr;
}
template <typename T>
gb_internal MapFindResult map__find_from_entry(Map<T> *h, MapEntry<T> *e) {
MapFindResult fr = {-1, -1, -1};
if (h->hashes.count > 0) {
fr.hash_index = e->key.key % h->hashes.count;
fr.entry_index = h->hashes[fr.hash_index];
while (fr.entry_index >= 0) {
if (&h->entries[fr.entry_index] == e) {
return fr;
}
fr.entry_prev = fr.entry_index;
fr.entry_index = h->entries[fr.entry_index].next;
}
}
return fr;
}
template <typename T>
gb_internal b32 map__full(Map<T> *h) {
return 0.75f * h->hashes.count <= h->entries.count;
}
template <typename T>
gb_inline void map_grow(Map<T> *h) {
isize new_count = ARRAY_GROW_FORMULA(h->entries.count);
map_rehash(h, new_count);
}
template <typename T>
void map_rehash(Map<T> *h, isize new_count) {
isize i, j;
Map<T> nh = {};
map_init(&nh, h->hashes.allocator);
array_resize(&nh.hashes, new_count);
array_reserve(&nh.entries, h->entries.count);
for (i = 0; i < new_count; i++) {
nh.hashes[i] = -1;
}
for (i = 0; i < h->entries.count; i++) {
MapEntry<T> *e = &h->entries[i];
MapFindResult fr;
if (nh.hashes.count == 0) {
map_grow(&nh);
}
fr = map__find(&nh, e->key);
j = map__add_entry(&nh, e->key);
if (fr.entry_prev < 0) {
nh.hashes[fr.hash_index] = j;
} else {
nh.entries[fr.entry_prev].next = j;
}
nh.entries[j].next = fr.entry_index;
nh.entries[j].value = e->value;
if (map__full(&nh)) {
map_grow(&nh);
}
}
map_destroy(h);
*h = nh;
}
template <typename T>
gb_inline T *map_get(Map<T> *h, HashKey key) {
isize index = map__find(h, key).entry_index;
if (index >= 0) {
return &h->entries[index].value;
}
return NULL;
}
template <typename T>
void map_set(Map<T> *h, HashKey key, T const &value) {
isize index;
MapFindResult fr;
if (h->hashes.count == 0)
map_grow(h);
fr = map__find(h, key);
if (fr.entry_index >= 0) {
index = fr.entry_index;
} else {
index = map__add_entry(h, key);
if (fr.entry_prev >= 0) {
h->entries[fr.entry_prev].next = index;
} else {
h->hashes[fr.hash_index] = index;
}
}
h->entries[index].value = value;
if (map__full(h)) {
map_grow(h);
}
}
template <typename T>
void map__erase(Map<T> *h, MapFindResult fr) {
MapFindResult last;
if (fr.entry_prev < 0) {
h->hashes[fr.hash_index] = h->entries[fr.entry_index].next;
} else {
h->entries[fr.entry_prev].next = h->entries[fr.entry_index].next;
}
if (fr.entry_index == h->entries.count-1) {
array_pop(&h->entries);
return;
}
h->entries[fr.entry_index] = h->entries[h->entries.count-1];
last = map__find(h, h->entries[fr.entry_index].key);
if (last.entry_prev >= 0) {
h->entries[last.entry_prev].next = fr.entry_index;
} else {
h->hashes[last.hash_index] = fr.entry_index;
}
}
template <typename T>
void map_remove(Map<T> *h, HashKey key) {
MapFindResult fr = map__find(h, key);
if (fr.entry_index >= 0) {
map__erase(h, fr);
}
}
template <typename T>
gb_inline void map_clear(Map<T> *h) {
array_clear(&h->hashes);
array_clear(&h->entries);
}
#if 1
template <typename T>
MapEntry<T> *multi_map_find_first(Map<T> *h, HashKey key) {
isize i = map__find(h, key).entry_index;
if (i < 0) {
return NULL;
}
return &h->entries[i];
}
template <typename T>
MapEntry<T> *multi_map_find_next(Map<T> *h, MapEntry<T> *e) {
isize i = e->next;
while (i >= 0) {
if (hash_key_equal(h->entries[i].key, e->key)) {
return &h->entries[i];
}
i = h->entries[i].next;
}
return NULL;
}
template <typename T>
isize multi_map_count(Map<T> *h, HashKey key) {
isize count = 0;
MapEntry<T> *e = multi_map_find_first(h, key);
while (e != NULL) {
count++;
e = multi_map_find_next(h, e);
}
return count;
}
template <typename T>
void multi_map_get_all(Map<T> *h, HashKey key, T *items) {
isize i = 0;
MapEntry<T> *e = multi_map_find_first(h, key);
while (e != NULL) {
items[i++] = e->value;
e = multi_map_find_next(h, e);
}
}
template <typename T>
void multi_map_insert(Map<T> *h, HashKey key, T const &value) {
MapFindResult fr;
isize i;
if (h->hashes.count == 0) {
map_grow(h);
}
// Make
fr = map__find(h, key);
i = map__add_entry(h, key);
if (fr.entry_prev < 0) {
h->hashes[fr.hash_index] = i;
} else {
h->entries[fr.entry_prev].next = i;
}
h->entries[i].next = fr.entry_index;
h->entries[i].value = value;
// Grow if needed
if (map__full(h)) {
map_grow(h);
}
}
template <typename T>
void multi_map_remove(Map<T> *h, HashKey key, MapEntry<T> *e) {
MapFindResult fr = map__find_from_entry(h, e);
if (fr.entry_index >= 0) {
map__erase(h, fr);
}
}
template <typename T>
void multi_map_remove_all(Map<T> *h, HashKey key) {
while (map_get(h, key) != NULL) {
map_remove(h, key);
}
}
#endif
+225
View File
@@ -0,0 +1,225 @@
//-----------------------------------------------------------------------------
// MurmurHash3 was written by Austin Appleby, and is placed in the public
// domain. The author hereby disclaims copyright to this source code.
// Note - The x86 and x64 versions do _not_ produce the same results, as the
// algorithms are optimized for their respective platforms. You can still
// compile and run any of them on any platform, but your performance with the
// non-native version will be less than optimal.
#if defined(_MSC_VER)
#define ROTL32(x,y) _rotl(x,y)
#define ROTL64(x,y) _rotl64(x,y)
#else
gb_inline u32 rotl32(u32 x, i8 r) {
return (x << r) | (x >> (32-r));
}
gb_inline u64 rotl64(u64 x, i8 r) {
return (x << r) | (x >> (64-r));
}
#define ROTL32(x,y) rotl32(x,y)
#define ROTL64(x,y) rotl64(x,y)
#endif
gb_inline u32 fmix32(u32 h) {
h ^= h >> 16;
h *= 0x85ebca6b;
h ^= h >> 13;
h *= 0xc2b2ae35;
h ^= h >> 16;
return h;
}
gb_inline u64 fmix64(u64 k) {
k ^= k >> 33;
k *= 0xff51afd7ed558ccdULL;
k ^= k >> 33;
k *= 0xc4ceb9fe1a85ec53ULL;
k ^= k >> 33;
return k;
}
gb_inline u32 mm3_getblock32(u32 const *p, isize i) {
return p[i];
}
gb_inline u64 mm3_getblock64(u64 const *p, isize i) {
return p[i];
}
void MurmurHash3_x64_128(void const *key, isize len, u32 seed, void *out) {
u8 const * data = cast(u8 const *)key;
isize nblocks = len / 16;
u64 h1 = seed;
u64 h2 = seed;
u64 const c1 = 0x87c37b91114253d5ULL;
u64 const c2 = 0x4cf5ad432745937fULL;
u64 const * blocks = cast(u64 const *)data;
for (isize i = 0; i < nblocks; i++) {
u64 k1 = mm3_getblock64(blocks, i*2 + 0);
u64 k2 = mm3_getblock64(blocks, i*2 + 1);
k1 *= c1; k1 = ROTL64(k1, 31); k1 *= c2; h1 ^= k1;
h1 = ROTL64(h1,27); h1 += h2; h1 = h1*5+0x52dce729;
k2 *= c2; k2 = ROTL64(k2,33); k2 *= c1; h2 ^= k2;
h2 = ROTL64(h2,31); h2 += h1; h2 = h2*5+0x38495ab5;
}
u8 const * tail = cast(u8 const *)(data + nblocks*16);
u64 k1 = 0;
u64 k2 = 0;
switch(len & 15) {
case 15: k2 ^= ((u64)tail[14]) << 48;
case 14: k2 ^= ((u64)tail[13]) << 40;
case 13: k2 ^= ((u64)tail[12]) << 32;
case 12: k2 ^= ((u64)tail[11]) << 24;
case 11: k2 ^= ((u64)tail[10]) << 16;
case 10: k2 ^= ((u64)tail[ 9]) << 8;
case 9: k2 ^= ((u64)tail[ 8]) << 0;
k2 *= c2; k2 = ROTL64(k2,33); k2 *= c1; h2 ^= k2;
case 8: k1 ^= ((u64)tail[ 7]) << 56;
case 7: k1 ^= ((u64)tail[ 6]) << 48;
case 6: k1 ^= ((u64)tail[ 5]) << 40;
case 5: k1 ^= ((u64)tail[ 4]) << 32;
case 4: k1 ^= ((u64)tail[ 3]) << 24;
case 3: k1 ^= ((u64)tail[ 2]) << 16;
case 2: k1 ^= ((u64)tail[ 1]) << 8;
case 1: k1 ^= ((u64)tail[ 0]) << 0;
k1 *= c1; k1 = ROTL64(k1,31); k1 *= c2; h1 ^= k1;
}
h1 ^= len;
h2 ^= len;
h1 += h2;
h2 += h1;
h1 = fmix64(h1);
h2 = fmix64(h2);
h1 += h2;
h2 += h1;
((u64 *)out)[0] = h1;
((u64 *)out)[1] = h2;
}
void MurmurHash3_x86_128(void const *key, isize len, u32 seed, void *out) {
u8 const * data = cast(u8 * const)key;
isize nblocks = len / 16;
u32 h1 = seed;
u32 h2 = seed;
u32 h3 = seed;
u32 h4 = seed;
u32 const c1 = 0x239b961b;
u32 const c2 = 0xab0e9789;
u32 const c3 = 0x38b34ae5;
u32 const c4 = 0xa1e38b93;
//----------
// body
u32 const * blocks = cast(u32 const *)(data + nblocks*16);
for (isize i = -nblocks; i != 0; i++) {
u32 k1 = mm3_getblock32(blocks, i*4 + 0);
u32 k2 = mm3_getblock32(blocks, i*4 + 1);
u32 k3 = mm3_getblock32(blocks, i*4 + 2);
u32 k4 = mm3_getblock32(blocks, i*4 + 3);
k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1;
h1 = ROTL32(h1,19); h1 += h2; h1 = h1*5+0x561ccd1b;
k2 *= c2; k2 = ROTL32(k2,16); k2 *= c3; h2 ^= k2;
h2 = ROTL32(h2,17); h2 += h3; h2 = h2*5+0x0bcaa747;
k3 *= c3; k3 = ROTL32(k3,17); k3 *= c4; h3 ^= k3;
h3 = ROTL32(h3,15); h3 += h4; h3 = h3*5+0x96cd1c35;
k4 *= c4; k4 = ROTL32(k4,18); k4 *= c1; h4 ^= k4;
h4 = ROTL32(h4,13); h4 += h1; h4 = h4*5+0x32ac3b17;
}
//----------
// tail
u8 const * tail = cast(u8 const *)(data + nblocks*16);
u32 k1 = 0;
u32 k2 = 0;
u32 k3 = 0;
u32 k4 = 0;
switch(len & 15) {
case 15: k4 ^= tail[14] << 16;
case 14: k4 ^= tail[13] << 8;
case 13: k4 ^= tail[12] << 0;
k4 *= c4; k4 = ROTL32(k4,18); k4 *= c1; h4 ^= k4;
case 12: k3 ^= tail[11] << 24;
case 11: k3 ^= tail[10] << 16;
case 10: k3 ^= tail[ 9] << 8;
case 9: k3 ^= tail[ 8] << 0;
k3 *= c3; k3 = ROTL32(k3,17); k3 *= c4; h3 ^= k3;
case 8: k2 ^= tail[ 7] << 24;
case 7: k2 ^= tail[ 6] << 16;
case 6: k2 ^= tail[ 5] << 8;
case 5: k2 ^= tail[ 4] << 0;
k2 *= c2; k2 = ROTL32(k2,16); k2 *= c3; h2 ^= k2;
case 4: k1 ^= tail[ 3] << 24;
case 3: k1 ^= tail[ 2] << 16;
case 2: k1 ^= tail[ 1] << 8;
case 1: k1 ^= tail[ 0] << 0;
k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1;
};
//----------
// finalization
h1 ^= len; h2 ^= len; h3 ^= len; h4 ^= len;
h1 += h2; h1 += h3; h1 += h4;
h2 += h1; h3 += h1; h4 += h1;
h1 = fmix32(h1);
h2 = fmix32(h2);
h3 = fmix32(h3);
h4 = fmix32(h4);
h1 += h2; h1 += h3; h1 += h4;
h2 += h1; h3 += h1; h4 += h1;
((u32 *)out)[0] = h1;
((u32 *)out)[1] = h2;
((u32 *)out)[2] = h3;
((u32 *)out)[3] = h4;
}
gb_inline u128 MurmurHash3_128(void const *key, isize len, u32 seed) {
u128 res;
#if defined(GB_ARCH_64_BIT)
MurmurHash3_x64_128(key, len, seed, &res);
#else
MurmurHash3_x86_128(key, len, seed, &res);
#endif
return res;
}
-1305
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
View File
+141 -202
View File
@@ -1,27 +1,18 @@
typedef struct ssaModule ssaModule;
typedef struct ssaValue ssaValue;
typedef struct ssaValueArgs ssaValueArgs;
typedef struct ssaDefer ssaDefer;
typedef struct ssaBlock ssaBlock;
typedef struct ssaProc ssaProc;
typedef struct ssaEdge ssaEdge;
typedef struct ssaRegister ssaRegister;
typedef struct ssaTargetList ssaTargetList;
typedef enum ssaBlockKind ssaBlockKind;
typedef enum ssaBranchPrediction ssaBranchPrediction;
typedef enum ssaDeferExitKind ssaDeferExitKind;
struct ssaModule;
struct ssaValue;
struct ssaValueArgs;
struct ssaDefer;
struct ssaBlock;
struct ssaProc;
struct ssaEdge;
struct ssaRegister;
struct ssaTargetList;
String ssa_mangle_name(ssaModule *m, String path, Entity *e);
#define MAP_TYPE ssaValue *
#define MAP_PROC map_ssa_value_
#define MAP_NAME MapSsaValue
#include "map.c"
typedef Array(ssaValue *) ssaValueArray;
#include "ssa_op.c"
#include "ssa_op.cpp"
#define SSA_DEFAULT_VALUE_ARG_CAPACITY 8
struct ssaValueArgs {
@@ -30,6 +21,15 @@ struct ssaValueArgs {
isize capacity;
ssaValue * backing[SSA_DEFAULT_VALUE_ARG_CAPACITY];
gbAllocator allocator;
ssaValue *&operator[](isize i) {
GB_ASSERT(0 <= i && i <= count);
return e[i];
}
ssaValue * const &operator[](isize i) const {
GB_ASSERT(0 <= i && i <= count);
return e[i];
}
};
struct ssaValue {
@@ -67,10 +67,10 @@ enum ssaBranchPrediction {
ssaBranch_Unlikely = -1,
};
typedef enum ssaDeferKind {
enum ssaDeferKind {
ssaDefer_Node,
ssaDefer_Instr,
} ssaDeferKind;
};
struct ssaDefer {
ssaDeferKind kind;
@@ -97,8 +97,6 @@ struct ssaEdge {
isize index;
};
typedef Array(ssaEdge) ssaEdgeArray;
struct ssaBlock {
i32 id; // Unique identifier but the pointer could be used too
ssaBlockKind kind;
@@ -115,9 +113,9 @@ struct ssaBlock {
// - BlockExit will be a memory control value
ssaValue *control;
ssaValueArray values;
ssaEdgeArray preds;
ssaEdgeArray succs;
Array<ssaValue *> values;
Array<ssaEdge> preds;
Array<ssaEdge> succs;
};
struct ssaTargetList {
@@ -134,7 +132,7 @@ struct ssaProc {
Entity * entity;
DeclInfo * decl_info;
Array(ssaBlock *) blocks;
Array<ssaBlock *> blocks;
ssaBlock * entry; // Entry block
ssaBlock * exit; // Exit block
ssaBlock * curr_block;
@@ -143,9 +141,9 @@ struct ssaProc {
i32 block_id;
i32 value_id;
MapSsaValue values; // Key: Entity *
Map<ssaValue *> values; // Key: Entity *
Array(ssaDefer) defer_stmts;
Array<ssaDefer> defer_stmts;
i32 scope_level;
};
@@ -161,10 +159,10 @@ struct ssaModule {
gbAllocator tmp_allocator;
gbArena tmp_arena;
MapEntity min_dep_map; // Key: Entity *
MapSsaValue values; // Key: Entity *
Map<Entity *> min_dep_map; // Key: Entity *
Map<ssaValue *> values; // Key: Entity *
// List of registers for the specific architecture
Array(ssaRegister) registers;
Array<ssaRegister> registers;
ssaProc *proc; // current procedure
@@ -172,19 +170,19 @@ struct ssaModule {
u32 stmt_state_flags;
Array(ssaProc *) procs;
ssaValueArray procs_to_generate;
Array<ssaProc *> procs;
Array<ssaValue *> procs_to_generate;
};
typedef enum ssaAddrKind {
enum ssaAddrKind {
ssaAddr_Default,
ssaAddr_Map,
} ssaAddrKind;
};
typedef struct ssaAddr {
struct ssaAddr {
ssaValue * addr;
ssaAddrKind kind;
} ssaAddr;
};
@@ -287,7 +285,7 @@ void ssa_add_arg(ssaValueArgs *va, ssaValue *arg) {
} else {
isize old_cap_size = va->capacity * gb_size_of(ssaValue *);
isize new_cap_size = capacity * gb_size_of(ssaValue *);
va->e = gb_resize(va->allocator, va->e, old_cap_size, new_cap_size);
*(cast(void **)&va->e) = gb_resize(va->allocator, va->e, old_cap_size, new_cap_size);
}
va->capacity = capacity;
}
@@ -329,7 +327,7 @@ ssaValue *ssa_new_value1v(ssaProc *p, ssaOp op, Type *t, ExactValue exact_value,
return v;
}
ssaValue *ssa_new_value1i(ssaProc *p, ssaOp op, Type *t, i64 i, ssaValue *arg) {
return ssa_new_value1v(p, op, t, exact_value_integer(i), arg);
return ssa_new_value1v(p, op, t, exact_value_i64(i), arg);
}
ssaValue *ssa_new_value2(ssaProc *p, ssaOp op, Type *t, ssaValue *arg0, ssaValue *arg1) {
@@ -371,16 +369,16 @@ ssaValue *ssa_const_val(ssaProc *p, ssaOp op, Type *t, ExactValue exact_value) {
}
ssaValue *ssa_const_bool (ssaProc *p, Type *t, bool c) { return ssa_const_val(p, ssaOp_ConstBool, t, exact_value_bool(c)); }
ssaValue *ssa_const_i8 (ssaProc *p, Type *t, i8 c) { return ssa_const_val(p, ssaOp_Const8, t, exact_value_integer(cast(i64)c)); }
ssaValue *ssa_const_i16 (ssaProc *p, Type *t, i16 c) { return ssa_const_val(p, ssaOp_Const16, t, exact_value_integer(cast(i64)c)); }
ssaValue *ssa_const_i32 (ssaProc *p, Type *t, i32 c) { return ssa_const_val(p, ssaOp_Const32, t, exact_value_integer(cast(i64)c)); }
ssaValue *ssa_const_i64 (ssaProc *p, Type *t, i64 c) { return ssa_const_val(p, ssaOp_Const64, t, exact_value_integer(cast(i64)c)); }
ssaValue *ssa_const_i8 (ssaProc *p, Type *t, i8 c) { return ssa_const_val(p, ssaOp_Const8, t, exact_value_i64(cast(i64)c)); }
ssaValue *ssa_const_i16 (ssaProc *p, Type *t, i16 c) { return ssa_const_val(p, ssaOp_Const16, t, exact_value_i64(cast(i64)c)); }
ssaValue *ssa_const_i32 (ssaProc *p, Type *t, i32 c) { return ssa_const_val(p, ssaOp_Const32, t, exact_value_i64(cast(i64)c)); }
ssaValue *ssa_const_i64 (ssaProc *p, Type *t, i64 c) { return ssa_const_val(p, ssaOp_Const64, t, exact_value_i64(cast(i64)c)); }
ssaValue *ssa_const_f32 (ssaProc *p, Type *t, f32 c) { return ssa_const_val(p, ssaOp_Const32F, t, exact_value_float(c)); }
ssaValue *ssa_const_f64 (ssaProc *p, Type *t, f64 c) { return ssa_const_val(p, ssaOp_Const64F, t, exact_value_float(c)); }
ssaValue *ssa_const_string (ssaProc *p, Type *t, String c) { return ssa_const_val(p, ssaOp_ConstString, t, exact_value_string(c)); }
ssaValue *ssa_const_empty_string(ssaProc *p, Type *t) { return ssa_const_val(p, ssaOp_ConstString, t, (ExactValue){0}); }
ssaValue *ssa_const_empty_string(ssaProc *p, Type *t) { return ssa_const_val(p, ssaOp_ConstString, t, empty_exact_value); }
ssaValue *ssa_const_slice (ssaProc *p, Type *t, ExactValue v) { return ssa_const_val(p, ssaOp_ConstSlice, t, v); }
ssaValue *ssa_const_nil (ssaProc *p, Type *t) { return ssa_const_val(p, ssaOp_ConstNil, t, (ExactValue){0}); }
ssaValue *ssa_const_nil (ssaProc *p, Type *t) { return ssa_const_val(p, ssaOp_ConstNil, t, empty_exact_value); }
ssaValue *ssa_const_int(ssaProc *p, Type *t, i64 c) {
switch (8*type_size_of(p->allocator, t)) {
@@ -399,21 +397,21 @@ ssaValue *ssa_const_int(ssaProc *p, Type *t, i64 c) {
ssaAddr ssa_build_addr (ssaProc *p, AstNode *expr);
ssaValue *ssa_build_expr (ssaProc *p, AstNode *expr);
void ssa_build_stmt (ssaProc *p, AstNode *node);
void ssa_build_stmt_list(ssaProc *p, AstNodeArray nodes);
void ssa_build_stmt_list(ssaProc *p, Array<AstNode *> nodes);
ssaValue *ssa_emit_deep_field_ptr_index(ssaProc *p, ssaValue *e, Selection sel);
void ssa_reset_value_args(ssaValue *v) {
for_array(i, v->args) {
v->args.e[i]->uses--;
v->args[i]->uses--;
}
v->args.count = 0;
}
void ssa_reset(ssaValue *v, ssaOp op) {
v->op = op;
v->exact_value = (ExactValue){0};
v->exact_value = empty_exact_value;
ssa_reset_value_args(v);
}
@@ -425,7 +423,7 @@ ssaValue *ssa_get_last_value(ssaBlock *b) {
if (len <= 0) {
return 0;
}
ssaValue *v = b->values.e[len-1];
ssaValue *v = b->values[len-1];
return v;
}
@@ -451,7 +449,7 @@ void ssa_build_defer_stmt(ssaProc *p, ssaDefer d) {
void ssa_emit_defer_stmts(ssaProc *p, ssaDeferExitKind kind, ssaBlock *b) {
isize count = p->defer_stmts.count;
for (isize i = count-1; i >= 0; i--) {
ssaDefer d = p->defer_stmts.e[i];
ssaDefer d = p->defer_stmts[i];
if (kind == ssaDeferExit_Default) {
gb_printf_err("scope_level %d %d\n", p->scope_level, d.scope_level);
if (p->scope_level == d.scope_level &&
@@ -579,7 +577,7 @@ ssaProc *ssa_new_proc(ssaModule *m, String name, Entity *entity, DeclInfo *decl_
array_init(&p->blocks, heap_allocator());
array_init(&p->defer_stmts, heap_allocator());
map_ssa_value_init(&p->values, heap_allocator());
map_init(&p->values, heap_allocator());
return p;
}
@@ -592,14 +590,14 @@ ssaAddr ssa_add_local(ssaProc *p, Entity *e, AstNode *expr) {
ssaValue *local = ssa_new_value0(p, ssaOp_Local, t);
p->curr_block = cb;
map_ssa_value_set(&p->values, hash_pointer(e), local);
map_ssa_value_set(&p->module->values, hash_pointer(e), local);
map_set(&p->values, hash_pointer(e), local);
map_set(&p->module->values, hash_pointer(e), local);
local->comment_string = e->token.string;
ssa_new_value1(p, ssaOp_Zero, t, local);
return ssa_addr(local);
}
ssaAddr ssa_add_local_for_ident(ssaProc *p, AstNode *name) {
Entity **found = map_entity_get(&p->module->info->definitions, hash_pointer(name));
Entity **found = map_get(&p->module->info->definitions, hash_pointer(name));
if (found) {
Entity *e = *found;
return ssa_add_local(p, e, name);
@@ -705,7 +703,7 @@ ssaValue *ssa_get_using_variable(ssaProc *p, Entity *e) {
Entity *parent = e->using_parent;
Selection sel = lookup_field(p->allocator, parent->type, name, false);
GB_ASSERT(sel.entity != NULL);
ssaValue **pv = map_ssa_value_get(&p->module->values, hash_pointer(parent));
ssaValue **pv = map_get(&p->module->values, hash_pointer(parent));
ssaValue *v = NULL;
if (pv != NULL) {
v = *pv;
@@ -721,7 +719,7 @@ ssaAddr ssa_build_addr_from_entity(ssaProc *p, Entity *e, AstNode *expr) {
GB_ASSERT(e != NULL);
ssaValue *v = NULL;
ssaValue **found = map_ssa_value_get(&p->module->values, hash_pointer(e));
ssaValue **found = map_get(&p->module->values, hash_pointer(e));
if (found) {
v = *found;
} else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
@@ -782,7 +780,7 @@ ssaValue *ssa_emit_conv(ssaProc *p, ssaValue *v, Type *t) {
// NOTE(bill): Returns NULL if not possible
ssaValue *ssa_address_from_load_or_generate_local(ssaProc *p, ssaValue *v) {
if (v->op == ssaOp_Load) {
return v->args.e[0];
return v->args[0];
}
ssaAddr addr = ssa_add_local_generated(p, v->type);
ssa_new_value2(p, ssaOp_Store, addr.addr->type, addr.addr, v);
@@ -863,7 +861,7 @@ ssaValue *ssa_emit_ptr_index(ssaProc *p, ssaValue *s, i64 index) {
ssaValue *ssa_emit_value_index(ssaProc *p, ssaValue *s, i64 index) {
if (s->op == ssaOp_Load) {
if (!can_ssa_type(s->type)) {
ssaValue *e = ssa_emit_ptr_index(p, s->args.e[0], index);
ssaValue *e = ssa_emit_ptr_index(p, s->args[0], index);
return ssa_emit_load(p, e);
}
}
@@ -930,7 +928,7 @@ ssaValue *ssa_emit_deep_field_ptr_index(ssaProc *p, ssaValue *e, Selection sel)
Type *type = type_deref(e->type);
for_array(i, sel.index) {
i32 index = cast(i32)sel.index.e[i];
i32 index = cast(i32)sel.index[i];
if (is_type_pointer(type)) {
type = type_deref(type);
e = ssa_emit_load(p, e);
@@ -994,14 +992,14 @@ ssaValue *ssa_emit_deep_field_value_index(ssaProc *p, ssaValue *e, Selection sel
Type *type = e->type;
if (e->op == ssaOp_Load) {
if (!can_ssa_type(e->type)) {
ssaValue *ptr = ssa_emit_deep_field_ptr_index(p, e->args.e[0], sel);
ssaValue *ptr = ssa_emit_deep_field_ptr_index(p, e->args[0], sel);
return ssa_emit_load(p, ptr);
}
}
GB_ASSERT(can_ssa_type(e->type));
for_array(i, sel.index) {
i32 index = cast(i32)sel.index.e[i];
i32 index = cast(i32)sel.index[i];
if (is_type_pointer(type)) {
e = ssa_emit_load(p, e);
}
@@ -1051,9 +1049,9 @@ ssaAddr ssa_build_addr(ssaProc *p, AstNode *expr) {
AstNode *sel = unparen_expr(se->selector);
if (sel->kind == AstNode_Ident) {
String selector = sel->Ident.string;
TypeAndValue *tav = type_and_value_of_expression(p->module->info, se->expr);
TypeAndValue tav = type_and_value_of_expr(p->module->info, se->expr);
if (tav == NULL) {
if (tav.mode == Addressing_Invalid) {
// NOTE(bill): Imports
Entity *imp = entity_of_ident(p->module->info, se->expr);
if (imp != NULL) {
@@ -1063,15 +1061,15 @@ ssaAddr ssa_build_addr(ssaProc *p, AstNode *expr) {
}
Type *type = base_type(tav->type);
if (tav->mode == Addressing_Type) { // Addressing_Type
Type *type = base_type(tav.type);
if (tav.mode == Addressing_Type) { // Addressing_Type
GB_PANIC("TODO: SelectorExpr Addressing_Type");
// Selection sel = lookup_field(p->allocator, type, selector, true);
// Entity *e = sel.entity;
// GB_ASSERT(e->kind == Entity_Variable);
// GB_ASSERT(e->flags & EntityFlag_TypeField);
// String name = e->token.string;
// if (str_eq(name, str_lit("names"))) {
// if (name == "names") {
// ssaValue *ti_ptr = ir_type_info(p, type);
// ssaValue *names_ptr = NULL;
@@ -1099,8 +1097,8 @@ ssaAddr ssa_build_addr(ssaProc *p, AstNode *expr) {
} else {
Type *type = base_type(type_of_expr(p->module->info, se->expr));
GB_ASSERT(is_type_integer(type));
ExactValue val = type_and_value_of_expression(p->module->info, sel)->value;
i64 index = val.value_integer;
ExactValue val = type_and_value_of_expr(p->module->info, sel).value;
i64 index = i128_to_i64(val.value_integer);
Selection sel = lookup_field_from_index(p->allocator, type, index);
GB_ASSERT(sel.entity != NULL);
@@ -1495,8 +1493,6 @@ ssaValue *ssa_emit_arith(ssaProc *p, TokenKind op, ssaValue *x, ssaValue *y, Typ
GB_PANIC("TODO(bill): ssa_emit_arith vector");
} else if (is_type_complex(x->type)) {
GB_PANIC("TODO(bill): ssa_emit_arith complex");
} else if (is_type_quaternion(x->type)) {
GB_PANIC("TODO(bill): ssa_emit_arith quaternion");
}
if (op == Token_Add) {
@@ -1635,43 +1631,43 @@ ssaValue *ssa_emit_logical_binary_expr(ssaProc *p, AstNode *expr) {
ssaValue *ssa_build_expr(ssaProc *p, AstNode *expr) {
expr = unparen_expr(expr);
TypeAndValue *tv = map_tav_get(&p->module->info->types, hash_pointer(expr));
GB_ASSERT_NOT_NULL(tv);
TypeAndValue tv = type_and_value_of_expr(p->module->info, expr);
GB_ASSERT(tv.mode != Addressing_Invalid);
if (tv->value.kind != ExactValue_Invalid) {
Type *t = core_type(tv->type);
if (tv.value.kind != ExactValue_Invalid) {
Type *t = core_type(tv.type);
if (is_type_boolean(t)) {
return ssa_const_bool(p, tv->type, tv->value.value_bool);
return ssa_const_bool(p, tv.type, tv.value.value_bool);
} else if (is_type_string(t)) {
GB_ASSERT(tv->value.kind == ExactValue_String);
return ssa_const_string(p, tv->type, tv->value.value_string);
GB_ASSERT(tv.value.kind == ExactValue_String);
return ssa_const_string(p, tv.type, tv.value.value_string);
} else if(is_type_slice(t)) {
return ssa_const_slice(p, tv->type, tv->value);
return ssa_const_slice(p, tv.type, tv.value);
} else if (is_type_integer(t)) {
GB_ASSERT(tv->value.kind == ExactValue_Integer);
GB_ASSERT(tv.value.kind == ExactValue_Integer);
i64 s = 8*type_size_of(p->allocator, t);
switch (s) {
case 8: return ssa_const_i8 (p, tv->type, tv->value.value_integer);
case 16: return ssa_const_i16(p, tv->type, tv->value.value_integer);
case 32: return ssa_const_i32(p, tv->type, tv->value.value_integer);
case 64: return ssa_const_i64(p, tv->type, tv->value.value_integer);
case 8: return ssa_const_i8 (p, tv.type, i128_to_i64(tv.value.value_integer));
case 16: return ssa_const_i16(p, tv.type, i128_to_i64(tv.value.value_integer));
case 32: return ssa_const_i32(p, tv.type, i128_to_i64(tv.value.value_integer));
case 64: return ssa_const_i64(p, tv.type, i128_to_i64(tv.value.value_integer));
default: GB_PANIC("Unknown integer size");
}
} else if (is_type_float(t)) {
GB_ASSERT(tv->value.kind == ExactValue_Float);
GB_ASSERT(tv.value.kind == ExactValue_Float);
i64 s = 8*type_size_of(p->allocator, t);
switch (s) {
case 32: return ssa_const_f32(p, tv->type, tv->value.value_float);
case 64: return ssa_const_f64(p, tv->type, tv->value.value_float);
case 32: return ssa_const_f32(p, tv.type, tv.value.value_float);
case 64: return ssa_const_f64(p, tv.type, tv.value.value_float);
default: GB_PANIC("Unknown float size");
}
}
// IMPORTANT TODO(bill): Do constant record/array literals correctly
return ssa_const_nil(p, tv->type);
return ssa_const_nil(p, tv.type);
}
if (tv->mode == Addressing_Variable) {
if (tv.mode == Addressing_Variable) {
return ssa_addr_load(p, ssa_build_addr(p, expr));
}
@@ -1687,7 +1683,7 @@ ssaValue *ssa_build_expr(ssaProc *p, AstNode *expr) {
case_end;
case_ast_node(i, Ident, expr);
Entity *e = *map_entity_get(&p->module->info->uses, hash_pointer(expr));
Entity *e = *map_get(&p->module->info->uses, hash_pointer(expr));
if (e->kind == Entity_Builtin) {
Token token = ast_node_token(expr);
GB_PANIC("TODO(bill): ssa_build_expr Entity_Builtin `%.*s`\n"
@@ -1699,7 +1695,7 @@ ssaValue *ssa_build_expr(ssaProc *p, AstNode *expr) {
return NULL;
}
ssaValue **found = map_ssa_value_get(&p->module->values, hash_pointer(e));
ssaValue **found = map_get(&p->module->values, hash_pointer(e));
if (found) {
ssaValue *v = *found;
if (v->op == ssaOp_Proc) {
@@ -1716,12 +1712,12 @@ ssaValue *ssa_build_expr(ssaProc *p, AstNode *expr) {
return ssa_build_addr(p, ue->expr).addr;
}
ssaValue *x = ssa_build_expr(p, ue->expr);
return ssa_emit_unary_arith(p, ue->op.kind, x, tv->type);
return ssa_emit_unary_arith(p, ue->op.kind, x, tv.type);
case_end;
case_ast_node(be, BinaryExpr, expr);
Type *type = default_type(tv->type);
Type *type = default_type(tv.type);
switch (be->op.kind) {
case Token_Add:
@@ -1803,7 +1799,7 @@ ssaValue *ssa_build_expr(ssaProc *p, AstNode *expr) {
ssa_emit_jump(p, done);
ssa_start_block(p, done);
return ssa_new_value2(p, ssaOp_Phi, tv->type, yes, no);
return ssa_new_value2(p, ssaOp_Phi, tv.type, yes, no);
case_end;
@@ -1837,10 +1833,10 @@ ssaValue *ssa_build_expr(ssaProc *p, AstNode *expr) {
case_ast_node(ce, CallExpr, expr);
if (map_tav_get(&p->module->info->types, hash_pointer(ce->proc))->mode == Addressing_Type) {
if (map_get(&p->module->info->types, hash_pointer(ce->proc))->mode == Addressing_Type) {
GB_ASSERT(ce->args.count == 1);
ssaValue *x = ssa_build_expr(p, ce->args.e[0]);
return ssa_emit_conv(p, x, tv->type);
ssaValue *x = ssa_build_expr(p, ce->args[0]);
return ssa_emit_conv(p, x, tv.type);
}
AstNode *p = unparen_expr(ce->proc);
@@ -1863,9 +1859,9 @@ ssaValue *ssa_build_expr(ssaProc *p, AstNode *expr) {
void ssa_build_stmt_list(ssaProc *p, AstNodeArray nodes) {
void ssa_build_stmt_list(ssaProc *p, Array<AstNode *> nodes) {
for_array(i, nodes) {
ssa_build_stmt(p, nodes.e[i]);
ssa_build_stmt(p, nodes[i]);
}
}
@@ -1948,8 +1944,8 @@ void ssa_build_stmt_internal(ssaProc *p, AstNode *node) {
case_ast_node(us, UsingStmt, node);
for_array(i, us->list) {
AstNode *decl = unparen_expr(us->list.e[i]);
if (decl->kind == AstNode_ValueDecl) {
AstNode *decl = unparen_expr(us->list[i]);
if (decl->kind == AstNode_GenDecl) {
ssa_build_stmt(p, decl);
}
}
@@ -1969,61 +1965,6 @@ void ssa_build_stmt_internal(ssaProc *p, AstNode *node) {
ssa_build_assign_op(p, addr, ssa_const_int(p, t, 1), op);
case_end;
case_ast_node(vd, ValueDecl, node);
if (vd->is_var) {
ssaModule *m = p->module;
gbTempArenaMemory tmp = gb_temp_arena_memory_begin(&m->tmp_arena);
if (vd->values.count == 0) {
for_array(i, vd->names) {
AstNode *name = vd->names.e[i];
if (!ssa_is_blank_ident(name)) {
ssa_add_local_for_ident(p, name);
}
}
} else {
Array(ssaAddr) lvals = {0};
ssaValueArray inits = {0};
array_init_reserve(&lvals, m->tmp_allocator, vd->names.count);
array_init_reserve(&inits, m->tmp_allocator, vd->names.count);
for_array(i, vd->names) {
AstNode *name = vd->names.e[i];
ssaAddr lval = ssa_addr(NULL);
if (!ssa_is_blank_ident(name)) {
lval = ssa_add_local_for_ident(p, name);
}
array_add(&lvals, lval);
}
for_array(i, vd->values) {
ssaValue *init = ssa_build_expr(p, vd->values.e[i]);
if (init == NULL) { // TODO(bill): remove this
continue;
}
Type *t = base_type(init->type);
if (t->kind == Type_Tuple) {
for (isize i = 0; i < t->Tuple.variable_count; i++) {
// Entity *e = t->Tuple.variables[i];
ssaValue *v = ssa_emit_value_index(p, init, i);
array_add(&inits, v);
}
} else {
array_add(&inits, init);
}
}
for_array(i, inits) {
ssa_addr_store(p, lvals.e[i], inits.e[i]);
}
}
gb_temp_arena_memory_end(tmp);
} else {
GB_PANIC("TODO(bill): ssa_build_stmt Type/Proc Entities");
}
case_end;
case_ast_node(as, AssignStmt, node);
ssa_emit_comment(p, str_lit("AssignStmt"));
@@ -2032,11 +1973,11 @@ void ssa_build_stmt_internal(ssaProc *p, AstNode *node) {
switch (as->op.kind) {
case Token_Eq: {
Array(ssaAddr) lvals = {0};
Array<ssaAddr> lvals = {0};
array_init(&lvals, m->tmp_allocator);
for_array(i, as->lhs) {
AstNode *lhs = as->lhs.e[i];
AstNode *lhs = as->lhs[i];
ssaAddr lval = {0};
if (!ssa_is_blank_ident(lhs)) {
lval = ssa_build_addr(p, lhs);
@@ -2046,28 +1987,28 @@ void ssa_build_stmt_internal(ssaProc *p, AstNode *node) {
if (as->lhs.count == as->rhs.count) {
if (as->lhs.count == 1) {
AstNode *rhs = as->rhs.e[0];
AstNode *rhs = as->rhs[0];
ssaValue *init = ssa_build_expr(p, rhs);
ssa_addr_store(p, lvals.e[0], init);
ssa_addr_store(p, lvals[0], init);
} else {
ssaValueArray inits;
array_init_reserve(&inits, m->tmp_allocator, lvals.count);
Array<ssaValue *> inits;
array_init(&inits, m->tmp_allocator, lvals.count);
for_array(i, as->rhs) {
ssaValue *init = ssa_build_expr(p, as->rhs.e[i]);
ssaValue *init = ssa_build_expr(p, as->rhs[i]);
array_add(&inits, init);
}
for_array(i, inits) {
ssa_addr_store(p, lvals.e[i], inits.e[i]);
ssa_addr_store(p, lvals[i], inits[i]);
}
}
} else {
ssaValueArray inits;
array_init_reserve(&inits, m->tmp_allocator, lvals.count);
Array<ssaValue *> inits;
array_init(&inits, m->tmp_allocator, lvals.count);
for_array(i, as->rhs) {
ssaValue *init = ssa_build_expr(p, as->rhs.e[i]);
ssaValue *init = ssa_build_expr(p, as->rhs[i]);
Type *t = base_type(init->type);
// TODO(bill): refactor for code reuse as this is repeated a bit
if (t->kind == Type_Tuple) {
@@ -2082,7 +2023,7 @@ void ssa_build_stmt_internal(ssaProc *p, AstNode *node) {
}
for_array(i, inits) {
ssa_addr_store(p, lvals.e[i], inits.e[i]);
ssa_addr_store(p, lvals[i], inits[i]);
}
}
} break;
@@ -2093,8 +2034,8 @@ void ssa_build_stmt_internal(ssaProc *p, AstNode *node) {
// +=, -=, etc
i32 op = cast(i32)as->op.kind;
op += Token_Add - Token_AddEq; // Convert += to +
ssaAddr lhs = ssa_build_addr(p, as->lhs.e[0]);
ssaValue *value = ssa_build_expr(p, as->rhs.e[0]);
ssaAddr lhs = ssa_build_addr(p, as->lhs[0]);
ssaValue *value = ssa_build_expr(p, as->rhs[0]);
ssa_build_assign_op(p, lhs, value, cast(TokenKind)op);
} break;
}
@@ -2276,9 +2217,9 @@ void ssa_print_exact_value(gbFile *f, ssaValue *v) {
break;
case ExactValue_Integer:
if (is_type_unsigned(t)) {
gb_fprintf(f, " [%llu]", cast(unsigned long long)ev.value_integer);
gb_fprintf(f, " [%llu]", cast(unsigned long long)i128_to_u64(ev.value_integer));
} else {
gb_fprintf(f, " [%lld]", cast(long long)ev.value_integer);
gb_fprintf(f, " [%lld]", cast(long long)i128_to_i64(ev.value_integer));
}
break;
case ExactValue_Float:
@@ -2291,7 +2232,7 @@ void ssa_print_exact_value(gbFile *f, ssaValue *v) {
u64 x = *cast(u64 *)&fp;
gb_fprintf(f, " [0x%llx]", cast(unsigned long long)x);
} else {
GB_PANIC("unhandled integer");
GB_PANIC("unhandled float");
}
break;
case ExactValue_String:
@@ -2318,7 +2259,7 @@ void ssa_print_reg_value(gbFile *f, ssaValue *v) {
for_array(i, v->args) {
gb_fprintf(f, " ");
ssa_print_value(f, v->args.e[i]);
ssa_print_value(f, v->args[i]);
}
if (v->comment_string.len > 0) {
@@ -2337,12 +2278,12 @@ void ssa_print_proc(gbFile *f, ssaProc *p) {
bool *printed = gb_alloc_array(heap_allocator(), bool, p->value_id+1);
for_array(i, p->blocks) {
ssaBlock *b = p->blocks.e[i];
ssaBlock *b = p->blocks[i];
gb_fprintf(f, " b%d:", b->id);
if (b->preds.count > 0) {
gb_fprintf(f, " <-");
for_array(j, b->preds) {
ssaBlock *pred = b->preds.e[j].block;
ssaBlock *pred = b->preds[j].block;
gb_fprintf(f, " b%d", pred->id);
}
}
@@ -2353,7 +2294,7 @@ void ssa_print_proc(gbFile *f, ssaProc *p) {
isize n = 0;
for_array(j, b->values) {
ssaValue *v = b->values.e[j];
ssaValue *v = b->values[j];
if (v->op != ssaOp_Phi) {
continue;
}
@@ -2365,13 +2306,13 @@ void ssa_print_proc(gbFile *f, ssaProc *p) {
while (n < b->values.count) {
isize m = 0;
for_array(j, b->values) {
ssaValue *v = b->values.e[j];
ssaValue *v = b->values[j];
if (printed[v->id]) {
continue;
}
bool skip = false;
for_array(k, v->args) {
ssaValue *w = v->args.e[k];
ssaValue *w = v->args[k];
if (w != NULL && w->block == b && !printed[w->id]) {
skip = true;
break;
@@ -2389,7 +2330,7 @@ void ssa_print_proc(gbFile *f, ssaProc *p) {
if (m == n) {
gb_fprintf(f, "!!!!DepCycle!!!!\n");
for_array(k, b->values) {
ssaValue *v = b->values.e[k];
ssaValue *v = b->values[k];
if (printed[v->id]) {
continue;
}
@@ -2403,14 +2344,14 @@ void ssa_print_proc(gbFile *f, ssaProc *p) {
if (b->kind == ssaBlock_Plain) {
GB_ASSERT(b->succs.count == 1);
ssaBlock *next = b->succs.e[0].block;
ssaBlock *next = b->succs[0].block;
gb_fprintf(f, " ");
gb_fprintf(f, "jump b%d", next->id);
gb_fprintf(f, "\n");
} else if (b->kind == ssaBlock_If) {
GB_ASSERT(b->succs.count == 2);
ssaBlock *yes = b->succs.e[0].block;
ssaBlock *no = b->succs.e[1].block;
ssaBlock *yes = b->succs[0].block;
ssaBlock *no = b->succs[1].block;
gb_fprintf(f, " ");
gb_fprintf(f, "branch v%d, b%d, b%d", b->control->id, yes->id, no->id);
gb_fprintf(f, "\n");
@@ -2436,12 +2377,12 @@ void ssa_build_proc(ssaModule *m, ssaProc *p) {
p->module = m;
m->proc = p;
if (p->decl_info->proc_lit == NULL ||
p->decl_info->proc_lit->kind != AstNode_ProcLit) {
if (p->decl_info->proc_decl == NULL ||
p->decl_info->proc_decl->kind != AstNode_ProcDecl) {
return;
}
ast_node(pl, ProcLit, p->decl_info->proc_lit);
ast_node(pl, ProcLit, p->decl_info->proc_decl);
if (pl->body == NULL) {
return;
}
@@ -2481,7 +2422,7 @@ bool ssa_generate(Parser *parser, CheckerInfo *info) {
m.tmp_allocator = gb_arena_allocator(&m.tmp_arena);
m.allocator = gb_arena_allocator(&m.arena);
map_ssa_value_init(&m.values, heap_allocator());
map_init(&m.values, heap_allocator());
array_init(&m.registers, heap_allocator());
array_init(&m.procs, heap_allocator());
array_init(&m.procs_to_generate, heap_allocator());
@@ -2493,21 +2434,21 @@ bool ssa_generate(Parser *parser, CheckerInfo *info) {
bool has_win_main = false;
for_array(i, info->entities.entries) {
MapDeclInfoEntry *entry = &info->entities.entries.e[i];
Entity *e = cast(Entity *)cast(uintptr)entry->key.key;
auto *entry = &info->entities.entries[i];
Entity *e = cast(Entity *)entry->key.ptr;
String name = e->token.string;
if (e->kind == Entity_Variable) {
global_variable_max_count++;
} else if (e->kind == Entity_Procedure && !e->scope->is_global) {
if (e->scope->is_init && str_eq(name, str_lit("main"))) {
if (e->scope->is_init && name == "main") {
entry_point = e;
}
if ((e->Procedure.tags & ProcTag_export) != 0 ||
(e->Procedure.link_name.len > 0) ||
(e->scope->is_file && e->Procedure.link_name.len > 0)) {
if (!has_dll_main && str_eq(name, str_lit("DllMain"))) {
if (!has_dll_main && name == "DllMain") {
has_dll_main = true;
} else if (!has_win_main && str_eq(name, str_lit("WinMain"))) {
} else if (!has_win_main && name == "WinMain") {
has_win_main = true;
}
}
@@ -2519,7 +2460,7 @@ bool ssa_generate(Parser *parser, CheckerInfo *info) {
m.min_dep_map = generate_minimum_dependency_map(info, entry_point);
for_array(i, info->entities.entries) {
MapDeclInfoEntry *entry = &info->entities.entries.e[i];
auto *entry = &info->entities.entries[i];
Entity *e = cast(Entity *)entry->key.ptr;
String name = e->token.string;
DeclInfo *decl = entry->value;
@@ -2529,7 +2470,7 @@ bool ssa_generate(Parser *parser, CheckerInfo *info) {
continue;
}
if (map_entity_get(&m.min_dep_map, hash_pointer(e)) == NULL) {
if (map_get(&m.min_dep_map, hash_pointer(e)) == NULL) {
// NOTE(bill): Nothing depends upon it so doesn't need to be built
continue;
}
@@ -2538,7 +2479,7 @@ bool ssa_generate(Parser *parser, CheckerInfo *info) {
if (e->kind == Entity_Procedure && (e->Procedure.tags & ProcTag_export) != 0) {
} else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
// Handle later
} else if (scope->is_init && e->kind == Entity_Procedure && str_eq(name, str_lit("main"))) {
} else if (scope->is_init && e->kind == Entity_Procedure && name == "main") {
} else {
name = ssa_mangle_name(&m, e->token.pos.file, e);
}
@@ -2554,15 +2495,13 @@ bool ssa_generate(Parser *parser, CheckerInfo *info) {
} break;
case Entity_Procedure: {
ast_node(pd, ProcLit, decl->proc_lit);
ast_node(pd, ProcDecl, decl->proc_decl);
String original_name = name;
AstNode *body = pd->body;
if (e->Procedure.is_foreign) {
name = e->token.string; // NOTE(bill): Don't use the mangled name
}
if (pd->foreign_name.len > 0) {
name = pd->foreign_name;
} else if (pd->link_name.len > 0) {
if (pd->link_name.len > 0) {
name = pd->link_name;
}
@@ -2576,8 +2515,8 @@ bool ssa_generate(Parser *parser, CheckerInfo *info) {
// ssa_module_add_value(m, e, p);
// HashKey hash_name = hash_string(name);
// if (map_ssa_value_get(&m.members, hash_name) == NULL) {
// map_ssa_value_set(&m.members, hash_name, p);
// if (map_get(&m.members, hash_name) == NULL) {
// map_set(&m.members, hash_name, p);
// }
} break;
}
@@ -2597,7 +2536,7 @@ String ssa_mangle_name(ssaModule *m, String path, Entity *e) {
String name = e->token.string;
CheckerInfo *info = m->info;
gbAllocator a = m->allocator;
AstFile *file = *map_ast_file_get(&info->files, hash_string(path));
AstFile *file = *map_get(&info->files, hash_string(path));
char *str = gb_alloc_array(a, char, path.len+1);
gb_memmove(str, path.text, path.len);
-1
View File
@@ -267,7 +267,6 @@ enum ssaOp {
SSA_OPS
#undef SSA_OP
};
typedef enum ssaOp ssaOp;
String const ssa_op_strings[] = {
#define SSA_OP(k) {cast(u8 *)#k, gb_size_of(#k)-1},
+90 -34
View File
@@ -1,5 +1,5 @@
gb_global gbArena string_buffer_arena = {0};
gb_global gbAllocator string_buffer_allocator = {0};
gb_global gbArena string_buffer_arena = {};
gb_global gbAllocator string_buffer_allocator = {};
void init_string_buffer_memory(void) {
// NOTE(bill): This should be enough memory for file systems
@@ -9,21 +9,41 @@ void init_string_buffer_memory(void) {
// NOTE(bill): Used for UTF-8 strings
typedef struct String {
struct String {
u8 * text;
isize len;
} String;
u8 &operator[](isize i) {
GB_ASSERT(0 <= i && i < len);
return text[i];
}
u8 const &operator[](isize i) const {
GB_ASSERT(0 <= i && i < len);
return text[i];
}
};
// NOTE(bill): used for printf style arguments
#define LIT(x) ((int)(x).len), (x).text
#define STR_LIT(c_str) {cast(u8 *)c_str, gb_size_of(c_str)-1}
#define str_lit(c_str) (String){cast(u8 *)c_str, gb_size_of(c_str)-1}
#if defined(GB_COMPILER_MSVC) && _MSC_VER < 1700
#define str_lit(c_str) make_string(cast(u8 *)c_str, gb_size_of(c_str)-1)
#else
#define str_lit(c_str) String{cast(u8 *)c_str, gb_size_of(c_str)-1}
#endif
// NOTE(bill): String16 is only used for Windows due to its file directories
typedef struct String16 {
struct String16 {
wchar_t *text;
isize len;
} String16;
wchar_t &operator[](isize i) {
GB_ASSERT(0 <= i && i < len);
return text[i];
}
wchar_t const &operator[](isize i) const {
GB_ASSERT(0 <= i && i < len);
return text[i];
}
};
gb_inline String make_string(u8 *text, isize len) {
@@ -44,11 +64,29 @@ gb_inline String16 make_string16(wchar_t *text, isize len) {
return s;
}
isize string16_len(wchar_t *s) {
if (s == NULL) {
return 0;
}
wchar_t *p = s;
while (*p) {
p++;
}
return p - s;
}
gb_inline String make_string_c(char *text) {
return make_string(cast(u8 *)cast(void *)text, gb_strlen(text));
}
String substring(String s, isize lo, isize hi) {
isize max = s.len;
GB_ASSERT(lo <= hi && hi <= max);
return make_string(s.text+lo, hi-lo);
}
@@ -56,8 +94,8 @@ gb_inline bool str_eq_ignore_case(String a, String b) {
if (a.len == b.len) {
isize i;
for (i = 0; i < a.len; i++) {
char x = cast(char)a.text[i];
char y = cast(char)b.text[i];
char x = cast(char)a[i];
char y = cast(char)b[i];
if (gb_char_to_lower(x) != gb_char_to_lower(y))
return false;
}
@@ -88,16 +126,16 @@ int string_compare(String x, String y) {
for (; curr_block < fast; curr_block++) {
if (la[curr_block] ^ lb[curr_block]) {
for (pos = curr_block*gb_size_of(isize); pos < n; pos++) {
if (x.text[pos] ^ y.text[pos]) {
return cast(int)x.text[pos] - cast(int)y.text[pos];
if (x[pos] ^ y[pos]) {
return cast(int)x[pos] - cast(int)y[pos];
}
}
}
}
for (; offset < n; offset++) {
if (x.text[offset] ^ y.text[offset]) {
return cast(int)x.text[offset] - cast(int)y.text[offset];
if (x[offset] ^ y[offset]) {
return cast(int)x[offset] - cast(int)y[offset];
}
}
}
@@ -117,13 +155,29 @@ gb_inline bool str_gt(String a, String b) { return string_compare(a, b) > 0;
gb_inline bool str_le(String a, String b) { return string_compare(a, b) <= 0; }
gb_inline bool str_ge(String a, String b) { return string_compare(a, b) >= 0; }
bool operator == (String a, String b) { return str_eq(a, b); }
bool operator != (String a, String b) { return str_ne(a, b); }
bool operator < (String a, String b) { return str_lt(a, b); }
bool operator > (String a, String b) { return str_gt(a, b); }
bool operator <= (String a, String b) { return str_le(a, b); }
bool operator >= (String a, String b) { return str_ge(a, b); }
template <isize N> bool operator == (String a, char const (&b)[N]) { return str_eq(a, make_string(cast(u8 *)b, N-1)); }
template <isize N> bool operator != (String a, char const (&b)[N]) { return str_ne(a, make_string(cast(u8 *)b, N-1)); }
template <isize N> bool operator < (String a, char const (&b)[N]) { return str_lt(a, make_string(cast(u8 *)b, N-1)); }
template <isize N> bool operator > (String a, char const (&b)[N]) { return str_gt(a, make_string(cast(u8 *)b, N-1)); }
template <isize N> bool operator <= (String a, char const (&b)[N]) { return str_le(a, make_string(cast(u8 *)b, N-1)); }
template <isize N> bool operator >= (String a, char const (&b)[N]) { return str_ge(a, make_string(cast(u8 *)b, N-1)); }
gb_inline bool str_has_prefix(String s, String prefix) {
isize i;
if (prefix.len < s.len) {
return false;
}
for (i = 0; i < prefix.len; i++) {
if (s.text[i] != prefix.text[i]) {
if (s[i] != prefix[i]) {
return false;
}
}
@@ -135,9 +189,9 @@ gb_inline isize string_extension_position(String str) {
isize i = str.len;
bool seen_dot = false;
while (i --> 0) {
if (str.text[i] == GB_PATH_SEPARATOR)
if (str[i] == GB_PATH_SEPARATOR)
break;
if (str.text[i] == '.') {
if (str[i] == '.') {
dot_pos = i;
break;
}
@@ -147,11 +201,11 @@ gb_inline isize string_extension_position(String str) {
}
String string_trim_whitespace(String str) {
while (str.len > 0 && rune_is_whitespace(str.text[str.len-1])) {
while (str.len > 0 && rune_is_whitespace(str[str.len-1])) {
str.len--;
}
while (str.len > 0 && rune_is_whitespace(str.text[0])) {
while (str.len > 0 && rune_is_whitespace(str[0])) {
str.text++;
str.len--;
}
@@ -166,7 +220,7 @@ gb_inline bool string_has_extension(String str, String ext) {
}
isize len = str.len;
for (isize i = len-1; i >= 0; i--) {
if (str.text[i] == '.') {
if (str[i] == '.') {
break;
}
len--;
@@ -182,7 +236,7 @@ gb_inline bool string_has_extension(String str, String ext) {
bool string_contains_char(String s, u8 c) {
isize i;
for (i = 0; i < s.len; i++) {
if (s.text[i] == c)
if (s[i] == c)
return true;
}
return false;
@@ -194,8 +248,8 @@ String filename_from_path(String s) {
isize j = 0;
s.len = i;
for (j = i-1; j >= 0; j--) {
if (s.text[j] == '/' ||
s.text[j] == '\\') {
if (s[j] == '/' ||
s[j] == '\\') {
break;
}
}
@@ -271,6 +325,7 @@ String16 string_to_string16(gbAllocator a, String s) {
return make_string16(text, len-1);
}
String string16_to_string(gbAllocator a, String16 s) {
int len, len1;
u8 *text;
@@ -283,6 +338,7 @@ String string16_to_string(gbAllocator a, String16 s) {
if (len == 0) {
return make_string(NULL, 0);
}
len += 1; // NOTE(bill): It needs an extra 1 for some reason
text = gb_alloc_array(a, u8, len+1);
@@ -315,18 +371,18 @@ String string16_to_string(gbAllocator a, String16 s) {
bool unquote_char(String s, u8 quote, Rune *rune, bool *multiple_bytes, String *tail_string) {
u8 c;
if (s.text[0] == quote &&
if (s[0] == quote &&
(quote == '\'' || quote == '"')) {
return false;
} else if (s.text[0] >= 0x80) {
} else if (s[0] >= 0x80) {
Rune r = -1;
isize size = gb_utf8_decode(s.text, s.len, &r);
*rune = r;
*multiple_bytes = true;
*tail_string = make_string(s.text+size, s.len-size);
return true;
} else if (s.text[0] != '\\') {
*rune = s.text[0];
} else if (s[0] != '\\') {
*rune = s[0];
*tail_string = make_string(s.text+1, s.len-1);
return true;
}
@@ -334,7 +390,7 @@ bool unquote_char(String s, u8 quote, Rune *rune, bool *multiple_bytes, String *
if (s.len <= 1) {
return false;
}
c = s.text[1];
c = s[1];
s = make_string(s.text+2, s.len-2);
switch (c) {
@@ -372,7 +428,7 @@ bool unquote_char(String s, u8 quote, Rune *rune, bool *multiple_bytes, String *
return false;
}
for (i = 0; i < 2; i++) {
i32 d = gb_digit_to_int(s.text[i]);
i32 d = gb_digit_to_int(s[i]);
if (d < 0 || d > 7) {
return false;
}
@@ -400,7 +456,7 @@ bool unquote_char(String s, u8 quote, Rune *rune, bool *multiple_bytes, String *
return false;
}
for (i = 0; i < count; i++) {
i32 d = gb_hex_digit_to_int(s.text[i]);
i32 d = gb_hex_digit_to_int(s[i]);
if (d < 0) {
return false;
}
@@ -433,8 +489,8 @@ i32 unquote_string(gbAllocator a, String *s_) {
if (n < 2) {
return 0;
}
quote = s.text[0];
if (quote != s.text[n-1]) {
quote = s[0];
if (quote != s[n-1]) {
return 0;
}
s.text += 1;
@@ -471,12 +527,12 @@ i32 unquote_string(gbAllocator a, String *s_) {
{
u8 rune_temp[4] = {0};
u8 rune_temp[4] = {};
isize buf_len = 3*s.len / 2;
u8 *buf = gb_alloc_array(a, u8, buf_len);
isize offset = 0;
while (s.len > 0) {
String tail_string = {0};
String tail_string = {};
Rune r = 0;
bool multiple_bytes = false;
bool success = unquote_char(s, quote, &r, &multiple_bytes, &tail_string);
+10 -16
View File
@@ -1,14 +1,14 @@
typedef struct TimeStamp {
struct TimeStamp {
u64 start;
u64 finish;
String label;
} TimeStamp;
};
typedef struct Timings {
struct Timings {
TimeStamp total;
Array(TimeStamp) sections;
Array<TimeStamp> sections;
u64 freq;
} Timings;
};
#if defined(GB_SYSTEM_WINDOWS)
@@ -45,13 +45,7 @@ u64 unix_time_stamp__freq(void) {
if (freq == 0) {
struct timespec ts;
clock_getres(CLOCK_PROCESS_CPUTIME_ID, &ts);
// that would be an absurd resolution (or lack thereof)
GB_ASSERT(ts.tv_sec == 0);
freq = cast(u64) ((1.0 / ts.tv_nsec) * 1000000000.0);
GB_ASSERT(freq != 0);
}
return freq;
@@ -89,7 +83,7 @@ TimeStamp make_time_stamp(String label) {
}
void timings_init(Timings *t, String label, isize buffer_size) {
array_init_reserve(&t->sections, heap_allocator(), buffer_size);
array_init(&t->sections, heap_allocator(), buffer_size);
t->total = make_time_stamp(label);
t->freq = time_stamp__freq();
}
@@ -100,7 +94,7 @@ void timings_destroy(Timings *t) {
void timings__stop_current_section(Timings *t) {
if (t->sections.count > 0) {
t->sections.e[t->sections.count-1].finish = time_stamp_time_now();
t->sections[t->sections.count-1].finish = time_stamp_time_now();
}
}
@@ -116,14 +110,14 @@ f64 time_stamp_as_ms(TimeStamp ts, u64 freq) {
void timings_print_all(Timings *t) {
char const SPACES[] = " ";
isize max_len, i;
isize max_len;
timings__stop_current_section(t);
t->total.finish = time_stamp_time_now();
max_len = t->total.label.len;
for_array(i, t->sections) {
TimeStamp ts = t->sections.e[i];
TimeStamp ts = t->sections[i];
max_len = gb_max(max_len, ts.label.len);
}
@@ -135,7 +129,7 @@ void timings_print_all(Timings *t) {
time_stamp_as_ms(t->total, t->freq));
for_array(i, t->sections) {
TimeStamp ts = t->sections.e[i];
TimeStamp ts = t->sections[i];
gb_printf("%.*s%.*s - %.3f ms\n",
LIT(ts.label),
cast(int)(max_len-ts.label.len), SPACES,
+101 -64
View File
@@ -25,6 +25,7 @@ TOKEN_KIND(Token__OperatorBegin, "_OperatorBegin"), \
TOKEN_KIND(Token_Mul, "*"), \
TOKEN_KIND(Token_Quo, "/"), \
TOKEN_KIND(Token_Mod, "%"), \
TOKEN_KIND(Token_ModMod, "%%"), \
TOKEN_KIND(Token_And, "&"), \
TOKEN_KIND(Token_Or, "|"), \
TOKEN_KIND(Token_Xor, "~"), \
@@ -41,6 +42,7 @@ TOKEN_KIND(Token__AssignOpBegin, "_AssignOpBegin"), \
TOKEN_KIND(Token_MulEq, "*="), \
TOKEN_KIND(Token_QuoEq, "/="), \
TOKEN_KIND(Token_ModEq, "%="), \
TOKEN_KIND(Token_ModModEq, "%%="), \
TOKEN_KIND(Token_AndEq, "&="), \
TOKEN_KIND(Token_OrEq, "|="), \
TOKEN_KIND(Token_XorEq, "~="), \
@@ -54,6 +56,7 @@ TOKEN_KIND(Token__AssignOpEnd, "_AssignOpEnd"), \
TOKEN_KIND(Token_ArrowLeft, "<-"), \
TOKEN_KIND(Token_Inc, "++"), \
TOKEN_KIND(Token_Dec, "--"), \
TOKEN_KIND(Token_Undef, "---"), \
\
TOKEN_KIND(Token__ComparisonBegin, "_ComparisonBegin"), \
TOKEN_KIND(Token_CmpEq, "=="), \
@@ -80,48 +83,53 @@ TOKEN_KIND(Token__ComparisonEnd, "_ComparisonEnd"), \
TOKEN_KIND(Token__OperatorEnd, "_OperatorEnd"), \
\
TOKEN_KIND(Token__KeywordBegin, "_KeywordBegin"), \
TOKEN_KIND(Token_when, "when"), \
TOKEN_KIND(Token_if, "if"), \
TOKEN_KIND(Token_else, "else"), \
TOKEN_KIND(Token_for, "for"), \
TOKEN_KIND(Token_in, "in"), \
TOKEN_KIND(Token_match, "match"), \
TOKEN_KIND(Token_default, "default"), \
TOKEN_KIND(Token_case, "case"), \
TOKEN_KIND(Token_break, "break"), \
TOKEN_KIND(Token_continue, "continue"), \
TOKEN_KIND(Token_fallthrough, "fallthrough"), \
TOKEN_KIND(Token_defer, "defer"), \
TOKEN_KIND(Token_return, "return"), \
TOKEN_KIND(Token_give, "give"), \
TOKEN_KIND(Token_proc, "proc"), \
TOKEN_KIND(Token_macro, "macro"), \
TOKEN_KIND(Token_struct, "struct"), \
TOKEN_KIND(Token_union, "union"), \
TOKEN_KIND(Token_raw_union, "raw_union"), \
TOKEN_KIND(Token_enum, "enum"), \
TOKEN_KIND(Token_vector, "vector"), \
TOKEN_KIND(Token_static, "static"), \
TOKEN_KIND(Token_dynamic, "dynamic"), \
TOKEN_KIND(Token_map, "map"), \
TOKEN_KIND(Token_using, "using"), \
TOKEN_KIND(Token_no_alias, "no_alias"), \
TOKEN_KIND(Token_immutable, "immutable"), \
TOKEN_KIND(Token_context, "context"), \
TOKEN_KIND(Token_push_context, "push_context"), \
TOKEN_KIND(Token_push_allocator, "push_allocator"), \
TOKEN_KIND(Token_asm, "asm"), \
TOKEN_KIND(Token_yield, "yield"), \
TOKEN_KIND(Token_await, "await"), \
TOKEN_KIND(Token_atomic, "atomic"), \
TOKEN_KIND(Token_var, "var"), \
TOKEN_KIND(Token_const, "const"), \
TOKEN_KIND(Token_type, "type"), \
TOKEN_KIND(Token_import, "import"), \
TOKEN_KIND(Token_import_load, "import_load"), \
TOKEN_KIND(Token_foreign, "foreign"), \
TOKEN_KIND(Token_foreign_library, "foreign_library"), \
TOKEN_KIND(Token_foreign_system_library, "foreign_system_library"), \
TOKEN_KIND(Token_when, "when"), \
TOKEN_KIND(Token_if, "if"), \
TOKEN_KIND(Token_else, "else"), \
TOKEN_KIND(Token_for, "for"), \
TOKEN_KIND(Token_in, "in"), \
TOKEN_KIND(Token_match, "match"), \
TOKEN_KIND(Token_case, "case"), \
TOKEN_KIND(Token_break, "break"), \
TOKEN_KIND(Token_continue, "continue"), \
TOKEN_KIND(Token_fallthrough, "fallthrough"), \
TOKEN_KIND(Token_defer, "defer"), \
TOKEN_KIND(Token_return, "return"), \
TOKEN_KIND(Token_proc, "proc"), \
TOKEN_KIND(Token_macro, "macro"), \
TOKEN_KIND(Token_struct, "struct"), \
TOKEN_KIND(Token_union, "union"), \
TOKEN_KIND(Token_raw_union, "raw_union"), \
TOKEN_KIND(Token_enum, "enum"), \
TOKEN_KIND(Token_bit_field, "bit_field"), \
TOKEN_KIND(Token_vector, "vector"), \
TOKEN_KIND(Token_static, "static"), \
TOKEN_KIND(Token_dynamic, "dynamic"), \
TOKEN_KIND(Token_map, "map"), \
TOKEN_KIND(Token_using, "using"), \
TOKEN_KIND(Token_context, "context"), \
TOKEN_KIND(Token_push_context, "push_context"), \
TOKEN_KIND(Token_push_allocator, "push_allocator"), \
TOKEN_KIND(Token_asm, "asm"), \
TOKEN_KIND(Token_yield, "yield"), \
TOKEN_KIND(Token_await, "await"), \
TOKEN_KIND(Token_atomic, "atomic"), \
TOKEN_KIND(Token__KeywordEnd, "_KeywordEnd"), \
TOKEN_KIND(Token_Count, "")
typedef enum TokenKind {
enum TokenKind {
#define TOKEN_KIND(e, s) e
TOKEN_KINDS
#undef TOKEN_KIND
} TokenKind;
};
String const token_strings[] = {
#define TOKEN_KIND(e, s) {cast(u8 *)s, gb_size_of(s)-1}
@@ -130,11 +138,11 @@ String const token_strings[] = {
};
typedef struct TokenPos {
struct TokenPos {
String file;
isize line;
isize column;
} TokenPos;
};
i32 token_pos_cmp(TokenPos a, TokenPos b) {
if (a.line == b.line) {
@@ -152,11 +160,11 @@ bool token_pos_eq(TokenPos a, TokenPos b) {
return token_pos_cmp(a, b) == 0;
}
typedef struct Token {
struct Token {
TokenKind kind;
String string;
TokenPos pos;
} Token;
};
Token empty_token = {Token_Invalid};
Token blank_token = {Token_Ident, {cast(u8 *)"_", 1}};
@@ -167,12 +175,12 @@ Token make_token_ident(String s) {
}
typedef struct ErrorCollector {
struct ErrorCollector {
TokenPos prev;
i64 count;
i64 warning_count;
gbMutex mutex;
} ErrorCollector;
};
gb_global ErrorCollector global_error_collector;
@@ -306,7 +314,7 @@ gb_inline bool token_is_shift(TokenKind t) {
gb_inline void print_token(Token t) { gb_printf("%.*s\n", LIT(t.string)); }
typedef enum TokenizerInitError {
enum TokenizerInitError {
TokenizerInit_None,
TokenizerInit_Invalid,
@@ -315,18 +323,18 @@ typedef enum TokenizerInitError {
TokenizerInit_Empty,
TokenizerInit_Count,
} TokenizerInitError;
};
typedef struct TokenizerState {
struct TokenizerState {
Rune curr_rune; // current character
u8 * curr; // character pos
u8 * read_curr; // pos from start
u8 * line; // current line pos
isize line_count;
} TokenizerState;
};
typedef struct Tokenizer {
struct Tokenizer {
String fullpath;
u8 *start;
u8 *end;
@@ -338,12 +346,12 @@ typedef struct Tokenizer {
isize line_count;
isize error_count;
Array(String) allocated_strings;
} Tokenizer;
Array<String> allocated_strings;
};
TokenizerState save_tokenizer_state(Tokenizer *t) {
TokenizerState state = {0};
TokenizerState state = {};
state.curr_rune = t->curr_rune;
state.curr = t->curr;
state.read_curr = t->read_curr;
@@ -435,7 +443,7 @@ TokenizerInitError init_tokenizer(Tokenizer *t, String fullpath) {
array_init(&t->allocated_strings, heap_allocator());
} else {
gbFile f = {0};
gbFile f = {};
gbFileError file_err = gb_file_open(&f, c_str);
switch (file_err) {
@@ -460,7 +468,7 @@ gb_inline void destroy_tokenizer(Tokenizer *t) {
gb_free(heap_allocator(), t->start);
}
for_array(i, t->allocated_strings) {
gb_free(heap_allocator(), t->allocated_strings.e[i].text);
gb_free(heap_allocator(), t->allocated_strings[i].text);
}
array_free(&t->allocated_strings);
}
@@ -492,7 +500,7 @@ gb_inline void scan_mantissa(Tokenizer *t, i32 base) {
}
Token scan_number_to_token(Tokenizer *t, bool seen_decimal_point) {
Token token = {0};
Token token = {};
token.kind = Token_Integer;
token.string = make_string(t->curr, 1);
token.pos.file = t->fullpath;
@@ -538,7 +546,14 @@ Token scan_number_to_token(Tokenizer *t, bool seen_decimal_point) {
if (t->curr - prev <= 2) {
token.kind = Token_Invalid;
}
} else {
} /* else if (t->curr_rune == 'h') { // Hexadecimal Float
token.kind = Token_Float;
advance_to_next_rune(t);
scan_mantissa(t, 16);
if (t->curr - prev <= 2) {
token.kind = Token_Invalid;
}
} */ else {
seen_decimal_point = false;
scan_mantissa(t, 10);
@@ -578,11 +593,9 @@ exponent:
scan_mantissa(t, 10);
}
switch (t->curr_rune) {
case 'i': case 'j': case 'k':
if (t->curr_rune == 'i') {
token.kind = Token_Imag;
advance_to_next_rune(t);
break;
}
end:
@@ -744,7 +757,7 @@ bool tokenizer_find_line_end(Tokenizer *t) {
Token tokenizer_get_token(Tokenizer *t) {
tokenizer_skip_whitespace(t);
Token token = {0};
Token token = {};
token.string = make_string(t->curr, 1);
token.pos.file = t->fullpath;
token.pos.line = t->line_count;
@@ -762,7 +775,7 @@ Token tokenizer_get_token(Tokenizer *t) {
// NOTE(bill): All keywords are > 1
if (token.string.len > 1) {
for (i32 k = Token__KeywordBegin+1; k < Token__KeywordEnd; k++) {
if (str_eq(token.string, token_strings[k])) {
if (token.string == token_strings[k]) {
token.kind = cast(TokenKind)k;
break;
}
@@ -892,13 +905,35 @@ Token tokenizer_get_token(Tokenizer *t) {
case '}': token.kind = Token_CloseBrace; break;
case '\\': token.kind = Token_BackSlash; break;
case 0x2260: token.kind = Token_NotEq; break; // '≠'
case 0x2264: token.kind = Token_LtEq; break; // '≤'
case 0x2265: token.kind = Token_GtEq; break; // '≥'
case '%': token.kind = token_kind_dub_eq(t, '%', Token_Mod, Token_ModEq, Token_ModMod, Token_ModModEq); break;
case '*': token.kind = token_kind_variant2(t, Token_Mul, Token_MulEq); break;
case '%': token.kind = token_kind_variant2(t, Token_Mod, Token_ModEq); break;
case '=': token.kind = token_kind_variant2(t, Token_Eq, Token_CmpEq); break;
case '~': token.kind = token_kind_variant2(t, Token_Xor, Token_XorEq); break;
case '!': token.kind = token_kind_variant2(t, Token_Not, Token_NotEq); break;
case '+': token.kind = token_kind_variant3(t, Token_Add, Token_AddEq, '+', Token_Inc); break;
case '-': token.kind = token_kind_variant4(t, Token_Sub, Token_SubEq, '-', Token_Dec, '>', Token_ArrowRight); break;
case '-':
token.kind = Token_Sub;
if (t->curr_rune == '=') {
advance_to_next_rune(t);
token.kind = Token_SubEq;
} else if (t->curr_rune == '-') {
advance_to_next_rune(t);
token.kind = Token_Dec;
if (t->curr_rune == '-') {
advance_to_next_rune(t);
token.kind = Token_Undef;
}
} else if (t->curr_rune == '>') {
advance_to_next_rune(t);
token.kind = Token_ArrowRight;
}
break;
case '/': {
if (t->curr_rune == '/') {
while (t->curr_rune != '\n' && t->curr_rune != GB_RUNE_EOF) {
@@ -909,7 +944,9 @@ Token tokenizer_get_token(Tokenizer *t) {
isize comment_scope = 1;
advance_to_next_rune(t);
while (comment_scope > 0) {
if (t->curr_rune == '/') {
if (t->curr_rune == GB_RUNE_EOF) {
break;
} else if (t->curr_rune == '/') {
advance_to_next_rune(t);
if (t->curr_rune == '*') {
advance_to_next_rune(t);
@@ -957,8 +994,8 @@ Token tokenizer_get_token(Tokenizer *t) {
case '|': token.kind = token_kind_dub_eq(t, '|', Token_Or, Token_OrEq, Token_CmpOr, Token_CmpOrEq); break;
default:
if (curr_rune != GB_RUNE_BOM) {
u8 str[4] = {0};
if (curr_rune != GB_RUNE_BOM) {
u8 str[4] = {};
int len = cast(int)gb_utf8_encode_rune(str, curr_rune);
tokenizer_err(t, "Illegal character: %.*s (%d) ", len, str, curr_rune);
}
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -1,9 +1,10 @@
#pragma warning(push)
#pragma warning(disable: 4245)
extern "C" {
// #include "utf8proc/utf8proc.h"
#include "utf8proc/utf8proc.c"
}
#pragma warning(pop)
+8 -12
View File
@@ -383,7 +383,7 @@ UTF8PROC_DLLEXPORT int utf8proc_charwidth(utf8proc_int32_t c) {
}
UTF8PROC_DLLEXPORT utf8proc_category_t utf8proc_category(utf8proc_int32_t c) {
return utf8proc_get_property(c)->category;
return cast(utf8proc_category_t)utf8proc_get_property(c)->category;
}
UTF8PROC_DLLEXPORT const char *utf8proc_category_string(utf8proc_int32_t c) {
@@ -393,15 +393,15 @@ UTF8PROC_DLLEXPORT const char *utf8proc_category_string(utf8proc_int32_t c) {
#define utf8proc_decompose_lump(replacement_uc) \
return utf8proc_decompose_char((replacement_uc), dst, bufsize, \
options & ~UTF8PROC_LUMP, last_boundclass)
(utf8proc_option_t)(options & ~UTF8PROC_LUMP), last_boundclass)
UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_decompose_char(utf8proc_int32_t uc, utf8proc_int32_t *dst, utf8proc_ssize_t bufsize, utf8proc_option_t options, int *last_boundclass) {
const utf8proc_property_t *property;
utf8proc_propval_t category;
utf8proc_category_t category;
utf8proc_int32_t hangul_sindex;
if (uc < 0 || uc >= 0x110000) return UTF8PROC_ERROR_NOTASSIGNED;
property = unsafe_get_property(uc);
category = property->category;
category = cast(utf8proc_category_t)property->category;
hangul_sindex = uc - UTF8PROC_HANGUL_SBASE;
if (options & (UTF8PROC_COMPOSE|UTF8PROC_DECOMPOSE)) {
if (hangul_sindex >= 0 && hangul_sindex < UTF8PROC_HANGUL_SCOUNT) {
@@ -728,28 +728,24 @@ UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_map_custom(
UTF8PROC_DLLEXPORT utf8proc_uint8_t *utf8proc_NFD(const utf8proc_uint8_t *str) {
utf8proc_uint8_t *retval;
utf8proc_map(str, 0, &retval, UTF8PROC_NULLTERM | UTF8PROC_STABLE |
UTF8PROC_DECOMPOSE);
utf8proc_map(str, 0, &retval, cast(utf8proc_option_t)(UTF8PROC_NULLTERM|UTF8PROC_STABLE|UTF8PROC_DECOMPOSE));
return retval;
}
UTF8PROC_DLLEXPORT utf8proc_uint8_t *utf8proc_NFC(const utf8proc_uint8_t *str) {
utf8proc_uint8_t *retval;
utf8proc_map(str, 0, &retval, UTF8PROC_NULLTERM | UTF8PROC_STABLE |
UTF8PROC_COMPOSE);
utf8proc_map(str, 0, &retval, cast(utf8proc_option_t)(UTF8PROC_NULLTERM|UTF8PROC_STABLE|UTF8PROC_COMPOSE));
return retval;
}
UTF8PROC_DLLEXPORT utf8proc_uint8_t *utf8proc_NFKD(const utf8proc_uint8_t *str) {
utf8proc_uint8_t *retval;
utf8proc_map(str, 0, &retval, UTF8PROC_NULLTERM | UTF8PROC_STABLE |
UTF8PROC_DECOMPOSE | UTF8PROC_COMPAT);
utf8proc_map(str, 0, &retval, cast(utf8proc_option_t)(UTF8PROC_NULLTERM|UTF8PROC_STABLE|UTF8PROC_DECOMPOSE|UTF8PROC_COMPAT));
return retval;
}
UTF8PROC_DLLEXPORT utf8proc_uint8_t *utf8proc_NFKC(const utf8proc_uint8_t *str) {
utf8proc_uint8_t *retval;
utf8proc_map(str, 0, &retval, UTF8PROC_NULLTERM | UTF8PROC_STABLE |
UTF8PROC_COMPOSE | UTF8PROC_COMPAT);
utf8proc_map(str, 0, &retval, cast(utf8proc_option_t)(UTF8PROC_NULLTERM|UTF8PROC_STABLE|UTF8PROC_COMPOSE|UTF8PROC_COMPAT));
return retval;
}