mirror of
https://github.com/Ed94/Odin.git
synced 2026-08-03 05:08:14 +00:00
Merge branch 'master' of https://github.com/odin-lang/Odin
This commit is contained in:
@@ -526,6 +526,14 @@ replace :: proc(s, old, new: []byte, n: int, allocator := context.allocator) ->
|
||||
return;
|
||||
}
|
||||
|
||||
remove :: proc(s, key: []byte, n: int, allocator := context.allocator) -> (output: []byte, was_allocation: bool) {
|
||||
return replace(s, key, {}, n, allocator);
|
||||
}
|
||||
|
||||
remove_all :: proc(s, key: []byte, allocator := context.allocator) -> (output: []byte, was_allocation: bool) {
|
||||
return remove(s, key, -1, allocator);
|
||||
}
|
||||
|
||||
@(private) _ascii_space := [256]u8{'\t' = 1, '\n' = 1, '\v' = 1, '\f' = 1, '\r' = 1, ' ' = 1};
|
||||
|
||||
|
||||
|
||||
+3
-3
@@ -641,9 +641,9 @@ fmt_write_padding :: proc(fi: ^Info, width: int) {
|
||||
return;
|
||||
}
|
||||
|
||||
pad_byte: byte = '0';
|
||||
if fi.space {
|
||||
pad_byte = ' ';
|
||||
pad_byte: byte = ' ';
|
||||
if !fi.space {
|
||||
pad_byte = '0';
|
||||
}
|
||||
|
||||
for i := 0; i < width; i += 1 {
|
||||
|
||||
@@ -31,6 +31,13 @@ overflow_add :: proc(lhs, rhs: $T) -> (T, bool) #optional_ok ---
|
||||
overflow_sub :: proc(lhs, rhs: $T) -> (T, bool) #optional_ok ---
|
||||
overflow_mul :: proc(lhs, rhs: $T) -> (T, bool) #optional_ok ---
|
||||
|
||||
sqrt :: proc(x: $T) -> T where type_is_float(T) ---
|
||||
|
||||
mem_copy :: proc(dst, src: rawptr, len: int) ---
|
||||
mem_copy_non_overlapping :: proc(dst, src: rawptr, len: int) ---
|
||||
mem_zero :: proc(ptr: rawptr, len: int) ---
|
||||
|
||||
|
||||
fixed_point_mul :: proc(lhs, rhs: $T, #const scale: uint) -> T where type_is_integer(T) ---
|
||||
fixed_point_div :: proc(lhs, rhs: $T, #const scale: uint) -> T where type_is_integer(T) ---
|
||||
fixed_point_mul_sat :: proc(lhs, rhs: $T, #const scale: uint) -> T where type_is_integer(T) ---
|
||||
@@ -159,6 +166,7 @@ type_is_simd_vector :: proc($T: typeid) -> bool ---
|
||||
type_has_nil :: proc($T: typeid) -> bool ---
|
||||
|
||||
type_is_specialization_of :: proc($T, $S: typeid) -> bool ---
|
||||
type_is_variant_of :: proc($U, $V: typeid) -> bool where type_is_union(U) ---
|
||||
|
||||
type_has_field :: proc($T: typeid, $name: string) -> bool ---
|
||||
|
||||
|
||||
@@ -6,9 +6,9 @@ Rand :: struct {
|
||||
}
|
||||
|
||||
|
||||
@(private, static)
|
||||
@(private)
|
||||
_GLOBAL_SEED_DATA := 1234567890;
|
||||
@(private, static)
|
||||
@(private)
|
||||
global_rand := create(u64(uintptr(&_GLOBAL_SEED_DATA)));
|
||||
|
||||
set_global_seed :: proc(seed: u64) {
|
||||
|
||||
+7
-11
@@ -16,16 +16,12 @@ Proc_Inlining :: enum u32 {
|
||||
No_Inline = 2,
|
||||
}
|
||||
|
||||
Proc_Calling_Convention :: enum i32 {
|
||||
Invalid = 0,
|
||||
Odin,
|
||||
Contextless,
|
||||
C_Decl,
|
||||
Std_Call,
|
||||
Fast_Call,
|
||||
None,
|
||||
|
||||
Foreign_Block_Default = -1,
|
||||
Proc_Calling_Convention_Extra :: enum i32 {
|
||||
Foreign_Block_Default,
|
||||
}
|
||||
Proc_Calling_Convention :: union {
|
||||
string,
|
||||
Proc_Calling_Convention_Extra,
|
||||
}
|
||||
|
||||
Node_State_Flag :: enum {
|
||||
@@ -69,7 +65,7 @@ File :: struct {
|
||||
pkg: ^Package,
|
||||
|
||||
fullpath: string,
|
||||
src: []byte,
|
||||
src: string,
|
||||
|
||||
docs: ^Comment_Group,
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package odin_format
|
||||
|
||||
import "core:odin/printer"
|
||||
import "core:odin/parser"
|
||||
import "core:odin/ast"
|
||||
|
||||
default_style := printer.default_style;
|
||||
|
||||
simplify :: proc(file: ^ast.File) {
|
||||
|
||||
}
|
||||
|
||||
format :: proc(filepath: string, source: string, config: printer.Config, parser_flags := parser.Flags{}, allocator := context.allocator) -> (string, bool) {
|
||||
config := config;
|
||||
|
||||
pkg := ast.Package {
|
||||
kind = .Normal,
|
||||
};
|
||||
|
||||
file := ast.File {
|
||||
pkg = &pkg,
|
||||
src = source,
|
||||
fullpath = filepath,
|
||||
};
|
||||
|
||||
config.newline_limit = clamp(config.newline_limit, 0, 16);
|
||||
config.spaces = clamp(config.spaces, 1, 16);
|
||||
config.align_length_break = clamp(config.align_length_break, 0, 64);
|
||||
|
||||
p := parser.default_parser(parser_flags);
|
||||
|
||||
ok := parser.parse_file(&p, &file);
|
||||
|
||||
if !ok || file.syntax_error_count > 0 {
|
||||
return {}, false;
|
||||
}
|
||||
|
||||
prnt := printer.make_printer(config, allocator);
|
||||
|
||||
return printer.print(&prnt, &file), true;
|
||||
}
|
||||
@@ -39,7 +39,7 @@ collect_package :: proc(path: string) -> (pkg: ^ast.Package, success: bool) {
|
||||
}
|
||||
file := ast.new(ast.File, NO_POS, NO_POS);
|
||||
file.pkg = pkg;
|
||||
file.src = src;
|
||||
file.src = string(src);
|
||||
file.fullpath = fullpath;
|
||||
pkg.files[fullpath] = file;
|
||||
}
|
||||
|
||||
@@ -8,10 +8,21 @@ import "core:fmt"
|
||||
Warning_Handler :: #type proc(pos: tokenizer.Pos, fmt: string, args: ..any);
|
||||
Error_Handler :: #type proc(pos: tokenizer.Pos, fmt: string, args: ..any);
|
||||
|
||||
Flag :: enum u32 {
|
||||
Optional_Semicolons,
|
||||
}
|
||||
|
||||
Flags :: distinct bit_set[Flag; u32];
|
||||
|
||||
|
||||
Parser :: struct {
|
||||
file: ^ast.File,
|
||||
tok: tokenizer.Tokenizer,
|
||||
|
||||
// If .Optional_Semicolons is true, semicolons are completely as statement terminators
|
||||
// different to .Insert_Semicolon in tok.flags
|
||||
flags: Flags,
|
||||
|
||||
warn: Warning_Handler,
|
||||
err: Error_Handler,
|
||||
|
||||
@@ -100,8 +111,9 @@ end_pos :: proc(tok: tokenizer.Token) -> tokenizer.Pos {
|
||||
return pos;
|
||||
}
|
||||
|
||||
default_parser :: proc() -> Parser {
|
||||
default_parser :: proc(flags := Flags{}) -> Parser {
|
||||
return Parser {
|
||||
flags = flags,
|
||||
err = default_error_handler,
|
||||
warn = default_warning_handler,
|
||||
};
|
||||
@@ -128,6 +140,10 @@ parse_file :: proc(p: ^Parser, file: ^ast.File) -> bool {
|
||||
p.line_comment = nil;
|
||||
}
|
||||
|
||||
if .Optional_Semicolons in p.flags {
|
||||
p.tok.flags += {.Insert_Semicolon};
|
||||
}
|
||||
|
||||
p.file = file;
|
||||
tokenizer.init(&p.tok, file.src, file.fullpath, p.err);
|
||||
if p.tok.ch <= 0 {
|
||||
@@ -400,6 +416,11 @@ is_semicolon_optional_for_node :: proc(p: ^Parser, node: ^ast.Node) -> bool {
|
||||
if node == nil {
|
||||
return false;
|
||||
}
|
||||
|
||||
if .Optional_Semicolons in p.flags {
|
||||
return true;
|
||||
}
|
||||
|
||||
switch n in node.derived {
|
||||
case ast.Empty_Stmt, ast.Block_Stmt:
|
||||
return true;
|
||||
@@ -439,14 +460,34 @@ is_semicolon_optional_for_node :: proc(p: ^Parser, node: ^ast.Node) -> bool {
|
||||
return false;
|
||||
}
|
||||
|
||||
expect_semicolon_newline_error :: proc(p: ^Parser, token: tokenizer.Token, s: ^ast.Node) {
|
||||
if .Optional_Semicolons not_in p.flags && .Insert_Semicolon in p.tok.flags && token.text == "\n" {
|
||||
#partial switch token.kind {
|
||||
case .Close_Brace:
|
||||
case .Close_Paren:
|
||||
case .Else:
|
||||
return;
|
||||
}
|
||||
if is_semicolon_optional_for_node(p, s) {
|
||||
return;
|
||||
}
|
||||
|
||||
tok := token;
|
||||
tok.pos.column -= 1;
|
||||
error(p, tok.pos, "expected ';', got newline");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
expect_semicolon :: proc(p: ^Parser, node: ^ast.Node) -> bool {
|
||||
if allow_token(p, .Semicolon) {
|
||||
expect_semicolon_newline_error(p, p.prev_tok, node);
|
||||
return true;
|
||||
}
|
||||
|
||||
prev := p.prev_tok;
|
||||
if prev.kind == .Semicolon {
|
||||
expect_semicolon_newline_error(p, p.prev_tok, node);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -615,7 +656,7 @@ parse_if_stmt :: proc(p: ^Parser) -> ^ast.If_Stmt {
|
||||
cond = parse_expr(p, false);
|
||||
} else {
|
||||
init = parse_simple_stmt(p, nil);
|
||||
if allow_token(p, .Semicolon) {
|
||||
if parse_control_statement_semicolon_separator(p) {
|
||||
cond = parse_expr(p, false);
|
||||
} else {
|
||||
cond = convert_stmt_to_expr(p, init, "boolean expression");
|
||||
@@ -668,6 +709,18 @@ parse_if_stmt :: proc(p: ^Parser) -> ^ast.If_Stmt {
|
||||
return if_stmt;
|
||||
}
|
||||
|
||||
parse_control_statement_semicolon_separator :: proc(p: ^Parser) -> bool {
|
||||
tok := peek_token(p);
|
||||
if tok.kind != .Open_Brace {
|
||||
return allow_token(p, .Semicolon);
|
||||
}
|
||||
if tok.text == ";" {
|
||||
return allow_token(p, .Semicolon);
|
||||
}
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
parse_for_stmt :: proc(p: ^Parser) -> ^ast.Stmt {
|
||||
if p.curr_proc == nil {
|
||||
error(p, p.curr_tok.pos, "you cannot use a for statement in the file scope");
|
||||
@@ -716,7 +769,7 @@ parse_for_stmt :: proc(p: ^Parser) -> ^ast.Stmt {
|
||||
}
|
||||
}
|
||||
|
||||
if !is_range && allow_token(p, .Semicolon) {
|
||||
if !is_range && parse_control_statement_semicolon_separator(p) {
|
||||
init = cond;
|
||||
cond = nil;
|
||||
if p.curr_tok.kind != .Semicolon {
|
||||
@@ -820,7 +873,7 @@ parse_switch_stmt :: proc(p: ^Parser) -> ^ast.Stmt {
|
||||
tag = parse_simple_stmt(p, {Stmt_Allow_Flag.In});
|
||||
if as, ok := tag.derived.(ast.Assign_Stmt); ok && as.op.kind == .In {
|
||||
is_type_switch = true;
|
||||
} else if allow_token(p, .Semicolon) {
|
||||
} else if parse_control_statement_semicolon_separator(p) {
|
||||
init = tag;
|
||||
tag = nil;
|
||||
if p.curr_tok.kind != .Open_Brace {
|
||||
@@ -831,6 +884,7 @@ parse_switch_stmt :: proc(p: ^Parser) -> ^ast.Stmt {
|
||||
}
|
||||
|
||||
|
||||
skip_possible_newline(p);
|
||||
open := expect_token(p, .Open_Brace);
|
||||
|
||||
for p.curr_tok.kind == .Case {
|
||||
@@ -958,6 +1012,7 @@ parse_foreign_block :: proc(p: ^Parser, tok: tokenizer.Token) -> ^ast.Foreign_Bl
|
||||
defer p.in_foreign_block = prev_in_foreign_block;
|
||||
p.in_foreign_block = true;
|
||||
|
||||
skip_possible_newline_for_literal(p);
|
||||
open := expect_token(p, .Open_Brace);
|
||||
for p.curr_tok.kind != .Close_Brace && p.curr_tok.kind != .EOF {
|
||||
decl := parse_foreign_block_decl(p);
|
||||
@@ -1287,7 +1342,7 @@ token_precedence :: proc(p: ^Parser, kind: tokenizer.Token_Kind) -> int {
|
||||
#partial switch kind {
|
||||
case .Question, .If, .When:
|
||||
return 1;
|
||||
case .Ellipsis, .Range_Half:
|
||||
case .Ellipsis, .Range_Half, .Range_Full:
|
||||
if !p.allow_range {
|
||||
return 0;
|
||||
}
|
||||
@@ -1884,24 +1939,12 @@ parse_results :: proc(p: ^Parser) -> (list: ^ast.Field_List, diverging: bool) {
|
||||
|
||||
string_to_calling_convention :: proc(s: string) -> ast.Proc_Calling_Convention {
|
||||
if s[0] != '"' && s[0] != '`' {
|
||||
return .Invalid;
|
||||
return nil;
|
||||
}
|
||||
switch s[1:len(s)-1] {
|
||||
case "odin":
|
||||
return .Odin;
|
||||
case "contextless":
|
||||
return .Contextless;
|
||||
case "cdecl", "c":
|
||||
return .C_Decl;
|
||||
case "stdcall", "std":
|
||||
return .Std_Call;
|
||||
case "fast", "fastcall":
|
||||
return .Fast_Call;
|
||||
|
||||
case "none":
|
||||
return .None;
|
||||
if len(s) == 2 {
|
||||
return nil;
|
||||
}
|
||||
return .Invalid;
|
||||
return s;
|
||||
}
|
||||
|
||||
parse_proc_tags :: proc(p: ^Parser) -> (tags: ast.Proc_Tags) {
|
||||
@@ -1926,21 +1969,17 @@ parse_proc_tags :: proc(p: ^Parser) -> (tags: ast.Proc_Tags) {
|
||||
}
|
||||
|
||||
parse_proc_type :: proc(p: ^Parser, tok: tokenizer.Token) -> ^ast.Proc_Type {
|
||||
cc := ast.Proc_Calling_Convention.Invalid;
|
||||
cc: ast.Proc_Calling_Convention;
|
||||
if p.curr_tok.kind == .String {
|
||||
str := expect_token(p, .String);
|
||||
cc = string_to_calling_convention(str.text);
|
||||
if cc == ast.Proc_Calling_Convention.Invalid {
|
||||
if cc == nil {
|
||||
error(p, str.pos, "unknown calling convention '%s'", str.text);
|
||||
}
|
||||
}
|
||||
|
||||
if cc == ast.Proc_Calling_Convention.Invalid {
|
||||
if p.in_foreign_block {
|
||||
cc = ast.Proc_Calling_Convention.Foreign_Block_Default;
|
||||
} else {
|
||||
cc = ast.Proc_Calling_Convention.Odin;
|
||||
}
|
||||
if cc == nil && p.in_foreign_block {
|
||||
cc = .Foreign_Block_Default;
|
||||
}
|
||||
|
||||
expect_token(p, .Open_Paren);
|
||||
@@ -1976,23 +2015,6 @@ parse_proc_type :: proc(p: ^Parser, tok: tokenizer.Token) -> ^ast.Proc_Type {
|
||||
return pt;
|
||||
}
|
||||
|
||||
check_poly_params_for_type :: proc(p: ^Parser, poly_params: ^ast.Field_List, tok: tokenizer.Token) {
|
||||
if poly_params == nil {
|
||||
return;
|
||||
}
|
||||
for field in poly_params.list {
|
||||
for name in field.names {
|
||||
if name == nil {
|
||||
continue;
|
||||
}
|
||||
if _, ok := name.derived.(ast.Poly_Type); ok {
|
||||
error(p, name.pos, "polymorphic names are not needed for %s parameters", tok.text);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
parse_inlining_operand :: proc(p: ^Parser, lhs: bool, tok: tokenizer.Token) -> ^ast.Expr {
|
||||
expr := parse_unary_expr(p, lhs);
|
||||
|
||||
@@ -2224,6 +2246,7 @@ parse_operand :: proc(p: ^Parser, lhs: bool) -> ^ast.Expr {
|
||||
p.expr_level = -1;
|
||||
where_clauses = parse_rhs_expr_list(p);
|
||||
p.expr_level = prev_level;
|
||||
tags = parse_proc_tags(p);
|
||||
}
|
||||
if p.allow_type && p.expr_level < 0 {
|
||||
if where_token.kind != .Invalid {
|
||||
@@ -2233,6 +2256,8 @@ parse_operand :: proc(p: ^Parser, lhs: bool) -> ^ast.Expr {
|
||||
}
|
||||
body: ^ast.Stmt;
|
||||
|
||||
skip_possible_newline_for_literal(p);
|
||||
|
||||
if allow_token(p, .Undef) {
|
||||
body = nil;
|
||||
if where_token.kind != .Invalid {
|
||||
@@ -2358,7 +2383,6 @@ parse_operand :: proc(p: ^Parser, lhs: bool) -> ^ast.Expr {
|
||||
poly_params = nil;
|
||||
}
|
||||
expect_token_after(p, .Close_Paren, "parameter list");
|
||||
check_poly_params_for_type(p, poly_params, tok);
|
||||
}
|
||||
|
||||
prev_level := p.expr_level;
|
||||
@@ -2405,6 +2429,7 @@ parse_operand :: proc(p: ^Parser, lhs: bool) -> ^ast.Expr {
|
||||
p.expr_level = where_prev_level;
|
||||
}
|
||||
|
||||
skip_possible_newline_for_literal(p);
|
||||
expect_token(p, .Open_Brace);
|
||||
fields, name_count = parse_field_list(p, .Close_Brace, ast.Field_Flags_Struct);
|
||||
close := expect_token(p, .Close_Brace);
|
||||
@@ -2434,7 +2459,6 @@ parse_operand :: proc(p: ^Parser, lhs: bool) -> ^ast.Expr {
|
||||
poly_params = nil;
|
||||
}
|
||||
expect_token_after(p, .Close_Paren, "parameter list");
|
||||
check_poly_params_for_type(p, poly_params, tok);
|
||||
}
|
||||
|
||||
prev_level := p.expr_level;
|
||||
@@ -2473,6 +2497,7 @@ parse_operand :: proc(p: ^Parser, lhs: bool) -> ^ast.Expr {
|
||||
|
||||
variants: [dynamic]^ast.Expr;
|
||||
|
||||
skip_possible_newline_for_literal(p);
|
||||
expect_token_after(p, .Open_Brace, "union");
|
||||
|
||||
for p.curr_tok.kind != .Close_Brace && p.curr_tok.kind != .EOF {
|
||||
@@ -2503,6 +2528,8 @@ parse_operand :: proc(p: ^Parser, lhs: bool) -> ^ast.Expr {
|
||||
if p.curr_tok.kind != .Open_Brace {
|
||||
base_type = parse_type(p);
|
||||
}
|
||||
|
||||
skip_possible_newline_for_literal(p);
|
||||
open := expect_token(p, .Open_Brace);
|
||||
fields := parse_elem_list(p);
|
||||
close := expect_token(p, .Close_Brace);
|
||||
@@ -2601,6 +2628,7 @@ parse_operand :: proc(p: ^Parser, lhs: bool) -> ^ast.Expr {
|
||||
}
|
||||
}
|
||||
|
||||
skip_possible_newline_for_literal(p);
|
||||
open := expect_token(p, .Open_Brace);
|
||||
asm_string := parse_expr(p, false);
|
||||
expect_token(p, .Comma);
|
||||
@@ -2811,7 +2839,7 @@ parse_atom_expr :: proc(p: ^Parser, value: ^ast.Expr, lhs: bool) -> (operand: ^a
|
||||
open := expect_token(p, .Open_Bracket);
|
||||
|
||||
#partial switch p.curr_tok.kind {
|
||||
case .Colon, .Ellipsis, .Range_Half:
|
||||
case .Colon, .Ellipsis, .Range_Half, .Range_Full:
|
||||
// NOTE(bill): Do not err yet
|
||||
break;
|
||||
case:
|
||||
@@ -2819,7 +2847,7 @@ parse_atom_expr :: proc(p: ^Parser, value: ^ast.Expr, lhs: bool) -> (operand: ^a
|
||||
}
|
||||
|
||||
#partial switch p.curr_tok.kind {
|
||||
case .Ellipsis, .Range_Half:
|
||||
case .Ellipsis, .Range_Half, .Range_Full:
|
||||
error(p, p.curr_tok.pos, "expected a colon, not a range");
|
||||
fallthrough;
|
||||
case .Colon:
|
||||
@@ -3150,6 +3178,7 @@ parse_simple_stmt :: proc(p: ^Parser, flags: Stmt_Allow_Flags) -> ^ast.Stmt {
|
||||
case ast.For_Stmt: n.label = label;
|
||||
case ast.Switch_Stmt: n.label = label;
|
||||
case ast.Type_Switch_Stmt: n.label = label;
|
||||
case ast.Range_Stmt: n.label = label;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,924 @@
|
||||
package odin_printer
|
||||
|
||||
import "core:odin/ast"
|
||||
import "core:odin/tokenizer"
|
||||
import "core:strings"
|
||||
import "core:runtime"
|
||||
import "core:fmt"
|
||||
import "core:unicode/utf8"
|
||||
import "core:mem"
|
||||
|
||||
Type_Enum :: enum {Line_Comment, Value_Decl, Switch_Stmt, Struct, Assign, Call, Enum, If, For, Proc_Lit};
|
||||
|
||||
Line_Type :: bit_set[Type_Enum];
|
||||
|
||||
/*
|
||||
Represents an unwrapped line
|
||||
*/
|
||||
Line :: struct {
|
||||
format_tokens: [dynamic]Format_Token,
|
||||
finalized: bool,
|
||||
used: bool,
|
||||
depth: int,
|
||||
types: Line_Type, //for performance, so you don't have to verify what types are in it by going through the tokens - might give problems when adding linebreaking
|
||||
}
|
||||
|
||||
/*
|
||||
Represents a singular token in a unwrapped line
|
||||
*/
|
||||
Format_Token :: struct {
|
||||
kind: tokenizer.Token_Kind,
|
||||
text: string,
|
||||
type: Type_Enum,
|
||||
spaces_before: int,
|
||||
parameter_count: int,
|
||||
}
|
||||
|
||||
Printer :: struct {
|
||||
string_builder: strings.Builder,
|
||||
config: Config,
|
||||
depth: int, //the identation depth
|
||||
comments: [dynamic]^ast.Comment_Group,
|
||||
latest_comment_index: int,
|
||||
allocator: mem.Allocator,
|
||||
file: ^ast.File,
|
||||
source_position: tokenizer.Pos,
|
||||
last_source_position: tokenizer.Pos,
|
||||
lines: [dynamic]Line, //need to look into a better data structure, one that can handle inserting lines rather than appending
|
||||
skip_semicolon: bool,
|
||||
current_line: ^Line,
|
||||
current_line_index: int,
|
||||
last_line_index: int,
|
||||
last_token: ^Format_Token,
|
||||
merge_next_token: bool,
|
||||
space_next_token: bool,
|
||||
debug: bool,
|
||||
}
|
||||
|
||||
Config :: struct {
|
||||
spaces: int, //Spaces per indentation
|
||||
newline_limit: int, //The limit of newlines between statements and declarations.
|
||||
tabs: bool, //Enable or disable tabs
|
||||
convert_do: bool, //Convert all do statements to brace blocks
|
||||
semicolons: bool, //Enable semicolons
|
||||
split_multiple_stmts: bool,
|
||||
align_switch: bool,
|
||||
brace_style: Brace_Style,
|
||||
align_assignments: bool,
|
||||
align_structs: bool,
|
||||
align_style: Alignment_Style,
|
||||
align_enums: bool,
|
||||
align_length_break: int,
|
||||
indent_cases: bool,
|
||||
newline_style: Newline_Style,
|
||||
}
|
||||
|
||||
Brace_Style :: enum {
|
||||
_1TBS,
|
||||
Allman,
|
||||
Stroustrup,
|
||||
K_And_R,
|
||||
}
|
||||
|
||||
Block_Type :: enum {
|
||||
None,
|
||||
If_Stmt,
|
||||
Proc,
|
||||
Generic,
|
||||
Comp_Lit,
|
||||
Switch_Stmt,
|
||||
}
|
||||
|
||||
Alignment_Style :: enum {
|
||||
Align_On_Type_And_Equals,
|
||||
Align_On_Colon_And_Equals,
|
||||
}
|
||||
|
||||
Newline_Style :: enum {
|
||||
CRLF,
|
||||
LF,
|
||||
}
|
||||
|
||||
default_style := Config {
|
||||
spaces = 4,
|
||||
newline_limit = 2,
|
||||
convert_do = false,
|
||||
semicolons = true,
|
||||
tabs = true,
|
||||
brace_style = ._1TBS,
|
||||
split_multiple_stmts = true,
|
||||
align_assignments = true,
|
||||
align_style = .Align_On_Type_And_Equals,
|
||||
indent_cases = false,
|
||||
align_switch = true,
|
||||
align_structs = true,
|
||||
align_enums = true,
|
||||
newline_style = .CRLF,
|
||||
align_length_break = 9,
|
||||
};
|
||||
|
||||
make_printer :: proc(config: Config, allocator := context.allocator) -> Printer {
|
||||
return {
|
||||
config = config,
|
||||
allocator = allocator,
|
||||
debug = false,
|
||||
};
|
||||
}
|
||||
|
||||
print :: proc(p: ^Printer, file: ^ast.File) -> string {
|
||||
p.comments = file.comments;
|
||||
|
||||
if len(file.decls) > 0 {
|
||||
p.lines = make([dynamic]Line, 0, (file.decls[len(file.decls) - 1].end.line - file.decls[0].pos.line) * 2, context.temp_allocator);
|
||||
}
|
||||
|
||||
set_source_position(p, file.pkg_token.pos);
|
||||
|
||||
p.last_source_position.line = 1;
|
||||
|
||||
set_line(p, 0);
|
||||
|
||||
push_generic_token(p, .Package, 0);
|
||||
push_ident_token(p, file.pkg_name, 1);
|
||||
|
||||
for decl in file.decls {
|
||||
visit_decl(p, cast(^ast.Decl)decl);
|
||||
}
|
||||
|
||||
if len(p.comments) > 0 {
|
||||
infinite := p.comments[len(p.comments) - 1].end;
|
||||
infinite.offset = 9999999;
|
||||
push_comments(p, infinite);
|
||||
}
|
||||
|
||||
fix_lines(p);
|
||||
|
||||
builder := strings.make_builder(0, mem.megabytes(5), p.allocator);
|
||||
|
||||
last_line := 0;
|
||||
|
||||
newline: string;
|
||||
|
||||
if p.config.newline_style == .LF {
|
||||
newline = "\n";
|
||||
} else {
|
||||
newline = "\r\n";
|
||||
}
|
||||
|
||||
for line, line_index in p.lines {
|
||||
diff_line := line_index - last_line;
|
||||
|
||||
for i := 0; i < diff_line; i += 1 {
|
||||
strings.write_string(&builder, newline);
|
||||
}
|
||||
|
||||
if p.config.tabs {
|
||||
for i := 0; i < line.depth; i += 1 {
|
||||
strings.write_byte(&builder, '\t');
|
||||
}
|
||||
} else {
|
||||
for i := 0; i < line.depth * p.config.spaces; i += 1 {
|
||||
strings.write_byte(&builder, ' ');
|
||||
}
|
||||
}
|
||||
|
||||
if p.debug {
|
||||
strings.write_string(&builder, fmt.tprintf("line %v: ", line_index));
|
||||
}
|
||||
|
||||
for format_token in line.format_tokens {
|
||||
|
||||
for i := 0; i < format_token.spaces_before; i += 1 {
|
||||
strings.write_byte(&builder, ' ');
|
||||
}
|
||||
|
||||
strings.write_string(&builder, format_token.text);
|
||||
}
|
||||
|
||||
last_line = line_index;
|
||||
}
|
||||
|
||||
strings.write_string(&builder, newline);
|
||||
|
||||
return strings.to_string(builder);
|
||||
}
|
||||
|
||||
fix_lines :: proc(p: ^Printer) {
|
||||
align_var_decls(p);
|
||||
format_generic(p);
|
||||
align_comments(p); //align them last since they rely on the other alignments
|
||||
}
|
||||
|
||||
format_value_decl :: proc(p: ^Printer, index: int) {
|
||||
|
||||
eq_found := false;
|
||||
eq_token: Format_Token;
|
||||
eq_line: int;
|
||||
largest := 0;
|
||||
|
||||
found_eq: for line, line_index in p.lines[index:] {
|
||||
for format_token in line.format_tokens {
|
||||
|
||||
largest += len(format_token.text) + format_token.spaces_before;
|
||||
|
||||
if format_token.kind == .Eq {
|
||||
eq_token = format_token;
|
||||
eq_line = line_index + index;
|
||||
eq_found = true;
|
||||
break found_eq;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !eq_found {
|
||||
return;
|
||||
}
|
||||
|
||||
align_next := false;
|
||||
|
||||
//check to see if there is a binary operator in the last token(this is guaranteed by the ast visit), otherwise it's not multilined
|
||||
for line, line_index in p.lines[eq_line:] {
|
||||
|
||||
if len(line.format_tokens) == 0 {
|
||||
break;
|
||||
}
|
||||
|
||||
if align_next {
|
||||
line.format_tokens[0].spaces_before = largest + 1;
|
||||
align_next = false;
|
||||
}
|
||||
|
||||
kind := find_last_token(line.format_tokens).kind;
|
||||
|
||||
if tokenizer.Token_Kind.B_Operator_Begin < kind && kind <= tokenizer.Token_Kind.Cmp_Or {
|
||||
align_next = true;
|
||||
}
|
||||
|
||||
if !align_next {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
find_last_token :: proc(format_tokens: [dynamic]Format_Token) -> Format_Token {
|
||||
|
||||
for i := len(format_tokens) - 1; i >= 0; i -= 1 {
|
||||
|
||||
if format_tokens[i].kind != .Comment {
|
||||
return format_tokens[i];
|
||||
}
|
||||
}
|
||||
|
||||
panic("not possible");
|
||||
}
|
||||
|
||||
format_assignment :: proc(p: ^Printer, index: int) {
|
||||
}
|
||||
|
||||
format_call :: proc(p: ^Printer, line_index: int, format_index: int) {
|
||||
|
||||
paren_found := false;
|
||||
paren_token: Format_Token;
|
||||
paren_line: int;
|
||||
paren_token_index: int;
|
||||
largest := 0;
|
||||
|
||||
found_paren: for line, i in p.lines[line_index:] {
|
||||
for format_token, j in line.format_tokens {
|
||||
|
||||
largest += len(format_token.text) + format_token.spaces_before;
|
||||
|
||||
if i == 0 && j < format_index {
|
||||
continue;
|
||||
}
|
||||
|
||||
if format_token.kind == .Open_Paren && format_token.type == .Call {
|
||||
paren_token = format_token;
|
||||
paren_line = line_index + i;
|
||||
paren_found = true;
|
||||
paren_token_index = j;
|
||||
break found_paren;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !paren_found {
|
||||
panic("Should not be possible");
|
||||
}
|
||||
|
||||
paren_count := 1;
|
||||
done := false;
|
||||
|
||||
for line, line_index in p.lines[paren_line:] {
|
||||
|
||||
if len(line.format_tokens) == 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
for format_token, i in line.format_tokens {
|
||||
|
||||
if format_token.kind == .Comment {
|
||||
continue;
|
||||
}
|
||||
|
||||
if line_index == 0 && i <= paren_token_index {
|
||||
continue;
|
||||
}
|
||||
|
||||
if format_token.kind == .Open_Paren {
|
||||
paren_count += 1;
|
||||
} else if format_token.kind == .Close_Paren {
|
||||
paren_count -= 1;
|
||||
}
|
||||
|
||||
if paren_count == 0 {
|
||||
done = true;
|
||||
}
|
||||
}
|
||||
|
||||
if line_index != 0 {
|
||||
line.format_tokens[0].spaces_before = largest;
|
||||
}
|
||||
|
||||
if done {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
format_keyword_to_brace :: proc(p: ^Printer, line_index: int, format_index: int, keyword: tokenizer.Token_Kind) {
|
||||
|
||||
keyword_found := false;
|
||||
keyword_token: Format_Token;
|
||||
keyword_line: int;
|
||||
|
||||
largest := 0;
|
||||
brace_count := 0;
|
||||
done := false;
|
||||
|
||||
found_keyword: for line, i in p.lines[line_index:] {
|
||||
for format_token in line.format_tokens {
|
||||
|
||||
largest += len(format_token.text) + format_token.spaces_before;
|
||||
|
||||
if format_token.kind == keyword {
|
||||
keyword_token = format_token;
|
||||
keyword_line = line_index + i;
|
||||
keyword_found = true;
|
||||
break found_keyword;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !keyword_found {
|
||||
panic("Should not be possible");
|
||||
}
|
||||
|
||||
for line, line_index in p.lines[keyword_line:] {
|
||||
|
||||
if len(line.format_tokens) == 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
for format_token, i in line.format_tokens {
|
||||
|
||||
if format_token.kind == .Comment {
|
||||
break;
|
||||
} else if format_token.kind == .Undef {
|
||||
return;
|
||||
}
|
||||
|
||||
if line_index == 0 && i <= format_index {
|
||||
continue;
|
||||
}
|
||||
|
||||
if format_token.kind == .Open_Brace {
|
||||
brace_count += 1;
|
||||
} else if format_token.kind == .Close_Brace {
|
||||
brace_count -= 1;
|
||||
}
|
||||
|
||||
if brace_count == 1 {
|
||||
done = true;
|
||||
}
|
||||
}
|
||||
|
||||
if line_index != 0 {
|
||||
line.format_tokens[0].spaces_before = largest + 1;
|
||||
}
|
||||
|
||||
if done {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
format_generic :: proc(p: ^Printer) {
|
||||
next_struct_line := 0;
|
||||
|
||||
for line, line_index in p.lines {
|
||||
|
||||
if len(line.format_tokens) <= 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
for format_token, token_index in line.format_tokens {
|
||||
#partial switch format_token.kind {
|
||||
case .For, .If, .When, .Switch:
|
||||
format_keyword_to_brace(p, line_index, token_index, format_token.kind);
|
||||
case .Proc:
|
||||
if format_token.type == .Proc_Lit {
|
||||
format_keyword_to_brace(p, line_index, token_index, format_token.kind);
|
||||
}
|
||||
case:
|
||||
if format_token.type == .Call {
|
||||
format_call(p, line_index, token_index);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if .Switch_Stmt in line.types && p.config.align_switch {
|
||||
align_switch_stmt(p, line_index);
|
||||
}
|
||||
|
||||
if .Enum in line.types && p.config.align_enums {
|
||||
align_enum(p, line_index);
|
||||
}
|
||||
|
||||
if .Struct in line.types && p.config.align_structs && next_struct_line <= 0 {
|
||||
next_struct_line = align_struct(p, line_index);
|
||||
}
|
||||
|
||||
if .Value_Decl in line.types {
|
||||
format_value_decl(p, line_index);
|
||||
}
|
||||
|
||||
if .Assign in line.types {
|
||||
format_assignment(p, line_index);
|
||||
}
|
||||
|
||||
next_struct_line -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
align_var_decls :: proc(p: ^Printer) {
|
||||
|
||||
current_line: int;
|
||||
current_typed: bool;
|
||||
current_not_mutable: bool;
|
||||
|
||||
largest_lhs := 0;
|
||||
largest_rhs := 0;
|
||||
|
||||
TokenAndLength :: struct {
|
||||
format_token: ^Format_Token,
|
||||
length: int,
|
||||
};
|
||||
|
||||
colon_tokens := make([dynamic]TokenAndLength, 0, 10, context.temp_allocator);
|
||||
type_tokens := make([dynamic]TokenAndLength, 0, 10, context.temp_allocator);
|
||||
equal_tokens := make([dynamic]TokenAndLength, 0, 10, context.temp_allocator);
|
||||
|
||||
for line, line_index in p.lines {
|
||||
|
||||
//It is only possible to align value decls that are one one line, otherwise just ignore them
|
||||
if .Value_Decl not_in line.types {
|
||||
continue;
|
||||
}
|
||||
|
||||
typed := true;
|
||||
not_mutable := false;
|
||||
continue_flag := false;
|
||||
|
||||
for i := 0; i < len(line.format_tokens); i += 1 {
|
||||
if line.format_tokens[i].kind == .Colon && line.format_tokens[min(i + 1, len(line.format_tokens) - 1)].kind == .Eq {
|
||||
typed = false;
|
||||
}
|
||||
|
||||
if line.format_tokens[i].kind == .Colon && line.format_tokens[min(i + 1, len(line.format_tokens) - 1)].kind == .Colon {
|
||||
not_mutable = true;
|
||||
}
|
||||
|
||||
if line.format_tokens[i].kind == .Union ||
|
||||
line.format_tokens[i].kind == .Enum ||
|
||||
line.format_tokens[i].kind == .Struct ||
|
||||
line.format_tokens[i].kind == .For ||
|
||||
line.format_tokens[i].kind == .If ||
|
||||
line.format_tokens[i].kind == .Comment {
|
||||
continue_flag = true;
|
||||
}
|
||||
|
||||
//enforced undef is always on the last line, if it exists
|
||||
if line.format_tokens[i].kind == .Proc && line.format_tokens[len(line.format_tokens)-1].kind != .Undef {
|
||||
continue_flag = true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if continue_flag {
|
||||
continue;
|
||||
}
|
||||
|
||||
if line_index != current_line + 1 || typed != current_typed || not_mutable != current_not_mutable {
|
||||
|
||||
if p.config.align_style == .Align_On_Colon_And_Equals || !current_typed || current_not_mutable {
|
||||
for colon_token in colon_tokens {
|
||||
colon_token.format_token.spaces_before = largest_lhs - colon_token.length + 1;
|
||||
}
|
||||
} else if p.config.align_style == .Align_On_Type_And_Equals {
|
||||
for type_token in type_tokens {
|
||||
type_token.format_token.spaces_before = largest_lhs - type_token.length + 1;
|
||||
}
|
||||
}
|
||||
|
||||
if current_typed {
|
||||
for equal_token in equal_tokens {
|
||||
equal_token.format_token.spaces_before = largest_rhs - equal_token.length + 1;
|
||||
}
|
||||
} else {
|
||||
for equal_token in equal_tokens {
|
||||
equal_token.format_token.spaces_before = 0;
|
||||
}
|
||||
}
|
||||
|
||||
clear(&colon_tokens);
|
||||
clear(&type_tokens);
|
||||
clear(&equal_tokens);
|
||||
|
||||
largest_rhs = 0;
|
||||
largest_lhs = 0;
|
||||
current_typed = typed;
|
||||
current_not_mutable = not_mutable;
|
||||
}
|
||||
|
||||
current_line = line_index;
|
||||
|
||||
current_token_index := 0;
|
||||
lhs_length := 0;
|
||||
rhs_length := 0;
|
||||
|
||||
//calcuate the length of lhs of a value decl i.e. `a, b:`
|
||||
for; current_token_index < len(line.format_tokens); current_token_index += 1 {
|
||||
|
||||
lhs_length += len(line.format_tokens[current_token_index].text) + line.format_tokens[current_token_index].spaces_before;
|
||||
|
||||
if line.format_tokens[current_token_index].kind == .Colon {
|
||||
append(&colon_tokens, TokenAndLength {format_token = &line.format_tokens[current_token_index], length = lhs_length});
|
||||
|
||||
if len(line.format_tokens) > current_token_index && line.format_tokens[current_token_index + 1].kind != .Eq {
|
||||
append(&type_tokens, TokenAndLength {format_token = &line.format_tokens[current_token_index + 1], length = lhs_length});
|
||||
}
|
||||
|
||||
current_token_index += 1;
|
||||
largest_lhs = max(largest_lhs, lhs_length);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
//calcuate the length of the rhs i.e. `[dynamic]int = 123123`
|
||||
for; current_token_index < len(line.format_tokens); current_token_index += 1 {
|
||||
|
||||
rhs_length += len(line.format_tokens[current_token_index].text) + line.format_tokens[current_token_index].spaces_before;
|
||||
|
||||
if line.format_tokens[current_token_index].kind == .Eq {
|
||||
append(&equal_tokens, TokenAndLength {format_token = &line.format_tokens[current_token_index], length = rhs_length});
|
||||
largest_rhs = max(largest_rhs, rhs_length);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//repeating myself, move to sub procedure
|
||||
if p.config.align_style == .Align_On_Colon_And_Equals || !current_typed || current_not_mutable {
|
||||
for colon_token in colon_tokens {
|
||||
colon_token.format_token.spaces_before = largest_lhs - colon_token.length + 1;
|
||||
}
|
||||
} else if p.config.align_style == .Align_On_Type_And_Equals {
|
||||
for type_token in type_tokens {
|
||||
type_token.format_token.spaces_before = largest_lhs - type_token.length + 1;
|
||||
}
|
||||
}
|
||||
|
||||
if current_typed {
|
||||
for equal_token in equal_tokens {
|
||||
equal_token.format_token.spaces_before = largest_rhs - equal_token.length + 1;
|
||||
}
|
||||
} else {
|
||||
for equal_token in equal_tokens {
|
||||
equal_token.format_token.spaces_before = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
align_switch_stmt :: proc(p: ^Printer, index: int) {
|
||||
switch_found := false;
|
||||
brace_token: Format_Token;
|
||||
brace_line: int;
|
||||
|
||||
found_switch_brace: for line, line_index in p.lines[index:] {
|
||||
for format_token in line.format_tokens {
|
||||
if format_token.kind == .Open_Brace && switch_found {
|
||||
brace_token = format_token;
|
||||
brace_line = line_index + index;
|
||||
break found_switch_brace;
|
||||
} else if format_token.kind == .Open_Brace {
|
||||
break;
|
||||
} else if format_token.kind == .Switch {
|
||||
switch_found = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !switch_found {
|
||||
return;
|
||||
}
|
||||
|
||||
largest := 0;
|
||||
case_count := 0;
|
||||
|
||||
TokenAndLength :: struct {
|
||||
format_token: ^Format_Token,
|
||||
length: int,
|
||||
};
|
||||
|
||||
format_tokens := make([dynamic]TokenAndLength, 0, brace_token.parameter_count, context.temp_allocator);
|
||||
|
||||
//find all the switch cases that are one lined
|
||||
for line, line_index in p.lines[brace_line + 1:] {
|
||||
|
||||
case_found := false;
|
||||
colon_found := false;
|
||||
length := 0;
|
||||
|
||||
for format_token, i in line.format_tokens {
|
||||
|
||||
if format_token.kind == .Comment {
|
||||
break;
|
||||
}
|
||||
|
||||
//this will only happen if the case is one lined
|
||||
if case_found && colon_found {
|
||||
append(&format_tokens, TokenAndLength {format_token = &line.format_tokens[i], length = length});
|
||||
largest = max(length, largest);
|
||||
break;
|
||||
}
|
||||
|
||||
if format_token.kind == .Case {
|
||||
case_found = true;
|
||||
case_count += 1;
|
||||
} else if format_token.kind == .Colon {
|
||||
colon_found = true;
|
||||
}
|
||||
|
||||
length += len(format_token.text) + format_token.spaces_before;
|
||||
}
|
||||
|
||||
if case_count >= brace_token.parameter_count {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for token in format_tokens {
|
||||
token.format_token.spaces_before = largest - token.length + 1;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
align_enum :: proc(p: ^Printer, index: int) {
|
||||
enum_found := false;
|
||||
brace_token: Format_Token;
|
||||
brace_line: int;
|
||||
|
||||
found_enum_brace: for line, line_index in p.lines[index:] {
|
||||
for format_token in line.format_tokens {
|
||||
if format_token.kind == .Open_Brace && enum_found {
|
||||
brace_token = format_token;
|
||||
brace_line = line_index + index;
|
||||
break found_enum_brace;
|
||||
} else if format_token.kind == .Open_Brace {
|
||||
break;
|
||||
} else if format_token.kind == .Enum {
|
||||
enum_found = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !enum_found {
|
||||
return;
|
||||
}
|
||||
|
||||
largest := 0;
|
||||
comma_count := 0;
|
||||
|
||||
TokenAndLength :: struct {
|
||||
format_token: ^Format_Token,
|
||||
length: int,
|
||||
};
|
||||
|
||||
format_tokens := make([dynamic]TokenAndLength, 0, brace_token.parameter_count, context.temp_allocator);
|
||||
|
||||
for line, line_index in p.lines[brace_line + 1:] {
|
||||
length := 0;
|
||||
|
||||
for format_token, i in line.format_tokens {
|
||||
if format_token.kind == .Comment {
|
||||
break;
|
||||
}
|
||||
|
||||
if format_token.kind == .Eq {
|
||||
append(&format_tokens, TokenAndLength {format_token = &line.format_tokens[i], length = length});
|
||||
largest = max(length, largest);
|
||||
break;
|
||||
} else if format_token.kind == .Comma {
|
||||
comma_count += 1;
|
||||
}
|
||||
|
||||
length += len(format_token.text) + format_token.spaces_before;
|
||||
}
|
||||
|
||||
if comma_count >= brace_token.parameter_count {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for token in format_tokens {
|
||||
token.format_token.spaces_before = largest - token.length + 1;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
align_struct :: proc(p: ^Printer, index: int) -> int {
|
||||
struct_found := false;
|
||||
brace_token: Format_Token;
|
||||
brace_line: int;
|
||||
|
||||
found_struct_brace: for line, line_index in p.lines[index:] {
|
||||
for format_token in line.format_tokens {
|
||||
if format_token.kind == .Open_Brace && struct_found {
|
||||
brace_token = format_token;
|
||||
brace_line = line_index + index;
|
||||
break found_struct_brace;
|
||||
} else if format_token.kind == .Open_Brace {
|
||||
break;
|
||||
} else if format_token.kind == .Struct {
|
||||
struct_found = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !struct_found {
|
||||
return 0;
|
||||
}
|
||||
|
||||
largest := 0;
|
||||
colon_count := 0;
|
||||
nested := false;
|
||||
seen_brace := false;
|
||||
|
||||
TokenAndLength :: struct {
|
||||
format_token: ^Format_Token,
|
||||
length: int,
|
||||
};
|
||||
|
||||
format_tokens := make([]TokenAndLength, brace_token.parameter_count, context.temp_allocator);
|
||||
|
||||
if brace_token.parameter_count == 0 {
|
||||
return 0;
|
||||
}
|
||||
|
||||
end_line_index := 0;
|
||||
|
||||
for line, line_index in p.lines[brace_line + 1:] {
|
||||
length := 0;
|
||||
|
||||
for format_token, i in line.format_tokens {
|
||||
|
||||
//give up on nested structs
|
||||
if format_token.kind == .Comment {
|
||||
break;
|
||||
} else if format_token.kind == .Open_Paren {
|
||||
break;
|
||||
} else if format_token.kind == .Open_Brace {
|
||||
seen_brace = true;
|
||||
} else if format_token.kind == .Close_Brace {
|
||||
seen_brace = false;
|
||||
} else if seen_brace {
|
||||
continue;
|
||||
}
|
||||
|
||||
if format_token.kind == .Colon {
|
||||
format_tokens[colon_count] = {format_token = &line.format_tokens[i + 1], length = length};
|
||||
|
||||
if format_tokens[colon_count].format_token.kind == .Struct {
|
||||
nested = true;
|
||||
}
|
||||
|
||||
colon_count += 1;
|
||||
largest = max(length, largest);
|
||||
}
|
||||
|
||||
length += len(format_token.text) + format_token.spaces_before;
|
||||
}
|
||||
|
||||
if nested {
|
||||
end_line_index = line_index + brace_line + 1;
|
||||
}
|
||||
|
||||
if colon_count >= brace_token.parameter_count {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
//give up aligning nested, it never looks good
|
||||
if nested {
|
||||
for line, line_index in p.lines[end_line_index:] {
|
||||
for format_token in line.format_tokens {
|
||||
if format_token.kind == .Close_Brace {
|
||||
return end_line_index + line_index - index;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for token in format_tokens {
|
||||
token.format_token.spaces_before = largest - token.length + 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
align_comments :: proc(p: ^Printer) {
|
||||
|
||||
Comment_Align_Info :: struct {
|
||||
length: int,
|
||||
begin: int,
|
||||
end: int,
|
||||
depth: int,
|
||||
};
|
||||
|
||||
comment_infos := make([dynamic]Comment_Align_Info, 0, context.temp_allocator);
|
||||
|
||||
current_info: Comment_Align_Info;
|
||||
|
||||
for line, line_index in p.lines {
|
||||
if len(line.format_tokens) <= 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
if .Line_Comment in line.types {
|
||||
if current_info.end + 1 != line_index || current_info.depth != line.depth ||
|
||||
(current_info.begin == current_info.end && current_info.length == 0) {
|
||||
|
||||
if (current_info.begin != 0 && current_info.end != 0) || current_info.length > 0 {
|
||||
append(&comment_infos, current_info);
|
||||
}
|
||||
|
||||
current_info.begin = line_index;
|
||||
current_info.end = line_index;
|
||||
current_info.depth = line.depth;
|
||||
current_info.length = 0;
|
||||
}
|
||||
|
||||
length := 0;
|
||||
|
||||
for format_token, i in line.format_tokens {
|
||||
if format_token.kind == .Comment {
|
||||
current_info.length = max(current_info.length, length);
|
||||
current_info.end = line_index;
|
||||
}
|
||||
|
||||
length += format_token.spaces_before + len(format_token.text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (current_info.begin != 0 && current_info.end != 0) || current_info.length > 0 {
|
||||
append(&comment_infos, current_info);
|
||||
}
|
||||
|
||||
for info in comment_infos {
|
||||
|
||||
if info.begin == info.end || info.length == 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
for i := info.begin; i <= info.end; i += 1 {
|
||||
l := p.lines[i];
|
||||
|
||||
length := 0;
|
||||
|
||||
for format_token, i in l.format_tokens {
|
||||
if format_token.kind == .Comment {
|
||||
if len(l.format_tokens) == 1 {
|
||||
l.format_tokens[i].spaces_before = info.length + 1;
|
||||
} else {
|
||||
l.format_tokens[i].spaces_before = info.length - length + 1;
|
||||
}
|
||||
}
|
||||
|
||||
length += format_token.spaces_before + len(format_token.text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -107,6 +107,7 @@ Token_Kind :: enum u32 {
|
||||
Comma, // ,
|
||||
Ellipsis, // ..
|
||||
Range_Half, // ..<
|
||||
Range_Full, // ..=
|
||||
Back_Slash, // \
|
||||
B_Operator_End,
|
||||
|
||||
@@ -233,6 +234,7 @@ tokens := [Token_Kind.COUNT]string {
|
||||
",",
|
||||
"..",
|
||||
"..<",
|
||||
"..=",
|
||||
"\\",
|
||||
"",
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ Flags :: distinct bit_set[Flag; u32];
|
||||
Tokenizer :: struct {
|
||||
// Immutable data
|
||||
path: string,
|
||||
src: []byte,
|
||||
src: string,
|
||||
err: Error_Handler,
|
||||
|
||||
flags: Flags,
|
||||
@@ -31,7 +31,7 @@ Tokenizer :: struct {
|
||||
error_count: int,
|
||||
}
|
||||
|
||||
init :: proc(t: ^Tokenizer, src: []byte, path: string, err: Error_Handler = default_error_handler) {
|
||||
init :: proc(t: ^Tokenizer, src: string, path: string, err: Error_Handler = default_error_handler) {
|
||||
t.src = src;
|
||||
t.err = err;
|
||||
t.ch = ' ';
|
||||
@@ -87,7 +87,7 @@ advance_rune :: proc(using t: ^Tokenizer) {
|
||||
case r == 0:
|
||||
error(t, t.offset, "illegal character NUL");
|
||||
case r >= utf8.RUNE_SELF:
|
||||
r, w = utf8.decode_rune(src[read_offset:]);
|
||||
r, w = utf8.decode_rune_in_string(src[read_offset:]);
|
||||
if r == utf8.RUNE_ERROR && w == 1 {
|
||||
error(t, t.offset, "illegal UTF-8 encoding");
|
||||
} else if r == utf8.RUNE_BOM && offset > 0 {
|
||||
@@ -608,7 +608,7 @@ scan :: proc(t: ^Tokenizer) -> Token {
|
||||
kind = switch3(t, .And, .And_Eq, '&', .Cmp_And);
|
||||
}
|
||||
case '|': kind = switch3(t, .Or, .Or_Eq, '|', .Cmp_Or);
|
||||
case '~': kind = .Xor;
|
||||
case '~': kind = switch2(t, .Xor, .Xor_Eq);
|
||||
case '<': kind = switch4(t, .Lt, .Lt_Eq, '<', .Shl, .Shl_Eq);
|
||||
case '>': kind = switch4(t, .Gt, .Gt_Eq, '>', .Shr,.Shr_Eq);
|
||||
|
||||
@@ -623,6 +623,9 @@ scan :: proc(t: ^Tokenizer) -> Token {
|
||||
if t.ch == '<' {
|
||||
advance_rune(t);
|
||||
kind = .Range_Half;
|
||||
} else if t.ch == '=' {
|
||||
advance_rune(t);
|
||||
kind = .Range_Full;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -273,7 +273,7 @@ is_file :: proc(path: string) -> bool {
|
||||
attribs := win32.GetFileAttributesW(wpath);
|
||||
|
||||
if i32(attribs) != win32.INVALID_FILE_ATTRIBUTES {
|
||||
return attribs & win32.FILE_ATTRIBUTE_DIRECTORY == win32.FILE_ATTRIBUTE_DIRECTORY;
|
||||
return attribs & win32.FILE_ATTRIBUTE_DIRECTORY == 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -283,7 +283,7 @@ is_dir :: proc(path: string) -> bool {
|
||||
attribs := win32.GetFileAttributesW(wpath);
|
||||
|
||||
if i32(attribs) != win32.INVALID_FILE_ATTRIBUTES {
|
||||
return attribs & win32.FILE_ATTRIBUTE_DIRECTORY != win32.FILE_ATTRIBUTE_DIRECTORY;
|
||||
return attribs & win32.FILE_ATTRIBUTE_DIRECTORY != 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
+18
-47
@@ -1,11 +1,8 @@
|
||||
package os2
|
||||
|
||||
Platform_Error_Min_Bits :: 32;
|
||||
import "core:io"
|
||||
|
||||
Error :: enum u64 {
|
||||
None = 0,
|
||||
|
||||
// General Errors
|
||||
General_Error :: enum u32 {
|
||||
Invalid_Argument,
|
||||
|
||||
Permission_Denied,
|
||||
@@ -13,43 +10,20 @@ Error :: enum u64 {
|
||||
Not_Exist,
|
||||
Closed,
|
||||
|
||||
// Timeout Errors
|
||||
Timeout,
|
||||
|
||||
// I/O Errors
|
||||
// EOF is the error returned by `read` when no more input is available
|
||||
EOF,
|
||||
|
||||
// Unexpected_EOF means that EOF was encountered in the middle of reading a fixed-sized block of data
|
||||
Unexpected_EOF,
|
||||
|
||||
// Short_Write means that a write accepted fewer bytes than requested but failed to return an explicit error
|
||||
Short_Write,
|
||||
|
||||
// Invalid_Write means that a write returned an impossible count
|
||||
Invalid_Write,
|
||||
|
||||
// Short_Buffer means that a read required a longer buffer than was provided
|
||||
Short_Buffer,
|
||||
|
||||
// No_Progress is returned by some implementations of `io.Reader` when many calls
|
||||
// to `read` have failed to return any data or error.
|
||||
// This is usually a signed of a broken `io.Reader` implementation
|
||||
No_Progress,
|
||||
|
||||
Invalid_Whence,
|
||||
Invalid_Offset,
|
||||
Invalid_Unread,
|
||||
|
||||
Negative_Read,
|
||||
Negative_Write,
|
||||
Negative_Count,
|
||||
Buffer_Full,
|
||||
|
||||
// Platform Specific Errors
|
||||
Platform_Minimum = 1<<Platform_Error_Min_Bits,
|
||||
}
|
||||
|
||||
Platform_Error :: struct {
|
||||
err: i32,
|
||||
}
|
||||
|
||||
Error :: union {
|
||||
General_Error,
|
||||
io.Error,
|
||||
Platform_Error,
|
||||
}
|
||||
#assert(size_of(Error) == size_of(u64));
|
||||
|
||||
Path_Error :: struct {
|
||||
op: string,
|
||||
path: string,
|
||||
@@ -83,20 +57,17 @@ link_error_delete :: proc(lerr: Maybe(Link_Error)) {
|
||||
|
||||
|
||||
is_platform_error :: proc(ferr: Error) -> (err: i32, ok: bool) {
|
||||
if ferr >= .Platform_Minimum {
|
||||
err = i32(u64(ferr)>>Platform_Error_Min_Bits);
|
||||
ok = true;
|
||||
v: Platform_Error;
|
||||
if v, ok = ferr.(Platform_Error); ok {
|
||||
err = v.err;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
error_from_platform_error :: proc(errno: i32) -> Error {
|
||||
return Error(u64(errno) << Platform_Error_Min_Bits);
|
||||
}
|
||||
|
||||
error_string :: proc(ferr: Error) -> string {
|
||||
#partial switch ferr {
|
||||
case .None: return "";
|
||||
switch ferr {
|
||||
case nil: return "";
|
||||
case .Invalid_Argument: return "invalid argument";
|
||||
case .Permission_Denied: return "permission denied";
|
||||
case .Exist: return "file already exists";
|
||||
|
||||
@@ -10,23 +10,14 @@ file_to_stream :: proc(fd: Handle) -> (s: io.Stream) {
|
||||
|
||||
@(private)
|
||||
error_to_io_error :: proc(ferr: Error) -> io.Error {
|
||||
#partial switch ferr {
|
||||
case .None: return .None;
|
||||
case .EOF: return .EOF;
|
||||
case .Unexpected_EOF: return .Unexpected_EOF;
|
||||
case .Short_Write: return .Short_Write;
|
||||
case .Invalid_Write: return .Invalid_Write;
|
||||
case .Short_Buffer: return .Short_Buffer;
|
||||
case .No_Progress: return .No_Progress;
|
||||
case .Invalid_Whence: return .Invalid_Whence;
|
||||
case .Invalid_Offset: return .Invalid_Offset;
|
||||
case .Invalid_Unread: return .Invalid_Unread;
|
||||
case .Negative_Read: return .Negative_Read;
|
||||
case .Negative_Write: return .Negative_Write;
|
||||
case .Negative_Count: return .Negative_Count;
|
||||
case .Buffer_Full: return .Buffer_Full;
|
||||
if ferr == nil {
|
||||
return .None;
|
||||
}
|
||||
return .Unknown;
|
||||
err, ok := ferr.(io.Error);
|
||||
if !ok {
|
||||
err = .Unknown;
|
||||
}
|
||||
return err;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package os2
|
||||
|
||||
import "core:mem"
|
||||
import "core:io"
|
||||
import "core:strconv"
|
||||
import "core:unicode/utf8"
|
||||
|
||||
|
||||
@@ -5,19 +5,19 @@ import "core:io"
|
||||
import "core:time"
|
||||
|
||||
_create :: proc(name: string) -> (Handle, Error) {
|
||||
return 0, .None;
|
||||
return 0, nil;
|
||||
}
|
||||
|
||||
_open :: proc(name: string) -> (Handle, Error) {
|
||||
return 0, .None;
|
||||
return 0, nil;
|
||||
}
|
||||
|
||||
_open_file :: proc(name: string, flag: int, perm: File_Mode) -> (Handle, Error) {
|
||||
return 0, .None;
|
||||
return 0, nil;
|
||||
}
|
||||
|
||||
_close :: proc(fd: Handle) -> Error {
|
||||
return .None;
|
||||
return nil;
|
||||
}
|
||||
|
||||
_name :: proc(fd: Handle, allocator := context.allocator) -> string {
|
||||
@@ -58,11 +58,11 @@ _file_size :: proc(fd: Handle) -> (n: i64, err: Error) {
|
||||
|
||||
|
||||
_sync :: proc(fd: Handle) -> Error {
|
||||
return .None;
|
||||
return nil;
|
||||
}
|
||||
|
||||
_flush :: proc(fd: Handle) -> Error {
|
||||
return .None;
|
||||
return nil;
|
||||
}
|
||||
|
||||
_truncate :: proc(fd: Handle, size: i64) -> Maybe(Path_Error) {
|
||||
@@ -92,20 +92,20 @@ _read_link :: proc(name: string) -> (string, Maybe(Path_Error)) {
|
||||
|
||||
|
||||
_chdir :: proc(fd: Handle) -> Error {
|
||||
return .None;
|
||||
return nil;
|
||||
}
|
||||
|
||||
_chmod :: proc(fd: Handle, mode: File_Mode) -> Error {
|
||||
return .None;
|
||||
return nil;
|
||||
}
|
||||
|
||||
_chown :: proc(fd: Handle, uid, gid: int) -> Error {
|
||||
return .None;
|
||||
return nil;
|
||||
}
|
||||
|
||||
|
||||
_lchown :: proc(name: string, uid, gid: int) -> Error {
|
||||
return .None;
|
||||
return nil;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import win32 "core:sys/windows"
|
||||
_pipe :: proc() -> (r, w: Handle, err: Error) {
|
||||
p: [2]win32.HANDLE;
|
||||
if !win32.CreatePipe(&p[0], &p[1], nil, 0) {
|
||||
return 0, 0, error_from_platform_error(i32(win32.GetLastError()));
|
||||
return 0, 0, Platform_Error{i32(win32.GetLastError())};
|
||||
}
|
||||
return Handle(p[0]), Handle(p[1]), nil;
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ _same_file :: proc(fi1, fi2: File_Info) -> bool {
|
||||
|
||||
|
||||
_stat_errno :: proc(errno: win32.DWORD) -> Path_Error {
|
||||
return Path_Error{err = error_from_platform_error(i32(errno))};
|
||||
return Path_Error{err = Platform_Error{i32(errno)}};
|
||||
}
|
||||
|
||||
|
||||
@@ -89,7 +89,7 @@ internal_stat :: proc(name: string, create_file_attributes: u32, allocator := co
|
||||
fd: win32.WIN32_FIND_DATAW;
|
||||
sh := win32.FindFirstFileW(wname, &fd);
|
||||
if sh == win32.INVALID_HANDLE_VALUE {
|
||||
e = Path_Error{err = error_from_platform_error(i32(win32.GetLastError()))};
|
||||
e = Path_Error{err = Platform_Error{i32(win32.GetLastError())}};
|
||||
return;
|
||||
}
|
||||
win32.FindClose(sh);
|
||||
@@ -99,7 +99,7 @@ internal_stat :: proc(name: string, create_file_attributes: u32, allocator := co
|
||||
|
||||
h := win32.CreateFileW(wname, 0, 0, nil, win32.OPEN_EXISTING, create_file_attributes, nil);
|
||||
if h == win32.INVALID_HANDLE_VALUE {
|
||||
e = Path_Error{err = error_from_platform_error(i32(win32.GetLastError()))};
|
||||
e = Path_Error{err = Platform_Error{i32(win32.GetLastError())}};
|
||||
return;
|
||||
}
|
||||
defer win32.CloseHandle(h);
|
||||
|
||||
@@ -4,11 +4,11 @@ package os2
|
||||
import win32 "core:sys/windows"
|
||||
|
||||
_create_temp :: proc(dir, pattern: string) -> (Handle, Error) {
|
||||
return 0, .None;
|
||||
return 0, nil;
|
||||
}
|
||||
|
||||
_mkdir_temp :: proc(dir, pattern: string, allocator := context.allocator) -> (string, Error) {
|
||||
return "", .None;
|
||||
return "", nil;
|
||||
}
|
||||
|
||||
_temp_dir :: proc(allocator := context.allocator) -> string {
|
||||
|
||||
@@ -10,7 +10,7 @@ import "core:c"
|
||||
Handle :: distinct i32;
|
||||
File_Time :: distinct u64;
|
||||
Errno :: distinct i32;
|
||||
Syscall :: distinct int;
|
||||
Syscall :: distinct i32;
|
||||
|
||||
INVALID_HANDLE :: ~Handle(0);
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import "core:strconv"
|
||||
Handle :: distinct i32;
|
||||
File_Time :: distinct u64;
|
||||
Errno :: distinct i32;
|
||||
Syscall :: distinct int;
|
||||
Syscall :: distinct i32;
|
||||
|
||||
INVALID_HANDLE :: ~Handle(0);
|
||||
|
||||
@@ -269,7 +269,7 @@ SYS_GETTID: Syscall : 186;
|
||||
|
||||
foreign libc {
|
||||
@(link_name="__errno_location") __errno_location :: proc() -> ^int ---;
|
||||
@(link_name="syscall") syscall :: proc(number: Syscall, #c_vararg args: ..any) -> int ---;
|
||||
@(link_name="syscall") syscall :: proc(number: Syscall, #c_vararg args: ..any) -> i32 ---;
|
||||
|
||||
@(link_name="open") _unix_open :: proc(path: cstring, flags: c.int, mode: c.int) -> Handle ---;
|
||||
@(link_name="close") _unix_close :: proc(fd: Handle) -> c.int ---;
|
||||
@@ -595,7 +595,7 @@ exit :: proc "contextless" (code: int) -> ! {
|
||||
}
|
||||
|
||||
current_thread_id :: proc "contextless" () -> int {
|
||||
return syscall(SYS_GETTID);
|
||||
return cast(int)syscall(SYS_GETTID);
|
||||
}
|
||||
|
||||
dlopen :: proc(filename: string, flags: int) -> rawptr {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package runtime
|
||||
|
||||
when ODIN_DEFAULT_TO_NIL_ALLOCATOR || ODIN_OS == "freestanding" {
|
||||
when ODIN_DEFAULT_TO_NIL_ALLOCATOR || ODIN_OS == "freestanding" || ODIN_OS == "js" {
|
||||
// mem.nil_allocator reimplementation
|
||||
|
||||
default_allocator_proc :: proc(allocator_data: rawptr, mode: mem.Allocator_Mode,
|
||||
@@ -15,7 +15,46 @@ when ODIN_DEFAULT_TO_NIL_ALLOCATOR || ODIN_OS == "freestanding" {
|
||||
data = nil,
|
||||
};
|
||||
}
|
||||
} else when ODIN_OS != "windows" {
|
||||
|
||||
} else when ODIN_OS == "windows" {
|
||||
default_allocator_proc :: proc(allocator_data: rawptr, mode: Allocator_Mode,
|
||||
size, alignment: int,
|
||||
old_memory: rawptr, old_size: int, loc := #caller_location) -> ([]byte, Allocator_Error) {
|
||||
switch mode {
|
||||
case .Alloc:
|
||||
return _windows_default_alloc(size, alignment);
|
||||
|
||||
case .Free:
|
||||
_windows_default_free(old_memory);
|
||||
|
||||
case .Free_All:
|
||||
// NOTE(tetra): Do nothing.
|
||||
|
||||
case .Resize:
|
||||
return _windows_default_resize(old_memory, old_size, size, alignment);
|
||||
|
||||
case .Query_Features:
|
||||
set := (^Allocator_Mode_Set)(old_memory);
|
||||
if set != nil {
|
||||
set^ = {.Alloc, .Free, .Resize, .Query_Features};
|
||||
}
|
||||
return nil, nil;
|
||||
|
||||
case .Query_Info:
|
||||
return nil, nil;
|
||||
}
|
||||
|
||||
return nil, nil;
|
||||
}
|
||||
|
||||
default_allocator :: proc() -> Allocator {
|
||||
return Allocator{
|
||||
procedure = default_allocator_proc,
|
||||
data = nil,
|
||||
};
|
||||
}
|
||||
|
||||
} else {
|
||||
// TODO(bill): reimplement these procedures in the os_specific stuff
|
||||
import "core:os"
|
||||
|
||||
|
||||
+12
-33
@@ -97,7 +97,7 @@ mem_zero :: proc "contextless" (data: rawptr, len: int) -> rawptr {
|
||||
if len < 0 {
|
||||
return data;
|
||||
}
|
||||
memset(data, 0, len);
|
||||
intrinsics.mem_zero(data, len);
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -105,17 +105,9 @@ mem_copy :: proc "contextless" (dst, src: rawptr, len: int) -> rawptr {
|
||||
if src == nil {
|
||||
return dst;
|
||||
}
|
||||
|
||||
// NOTE(bill): This _must_ be implemented like C's memmove
|
||||
foreign _ {
|
||||
when size_of(rawptr) == 8 {
|
||||
@(link_name="llvm.memmove.p0i8.p0i8.i64")
|
||||
llvm_memmove :: proc "none" (dst, src: rawptr, len: int, is_volatile: bool = false) ---;
|
||||
} else {
|
||||
@(link_name="llvm.memmove.p0i8.p0i8.i32")
|
||||
llvm_memmove :: proc "none" (dst, src: rawptr, len: int, is_volatile: bool = false) ---;
|
||||
}
|
||||
}
|
||||
llvm_memmove(dst, src, len);
|
||||
intrinsics.mem_copy(dst, src, len);
|
||||
return dst;
|
||||
}
|
||||
|
||||
@@ -123,17 +115,9 @@ mem_copy_non_overlapping :: proc "contextless" (dst, src: rawptr, len: int) -> r
|
||||
if src == nil {
|
||||
return dst;
|
||||
}
|
||||
|
||||
// NOTE(bill): This _must_ be implemented like C's memcpy
|
||||
foreign _ {
|
||||
when size_of(rawptr) == 8 {
|
||||
@(link_name="llvm.memcpy.p0i8.p0i8.i64")
|
||||
llvm_memcpy :: proc "none" (dst, src: rawptr, len: int, is_volatile: bool = false) ---;
|
||||
} else {
|
||||
@(link_name="llvm.memcpy.p0i8.p0i8.i32")
|
||||
llvm_memcpy :: proc "none" (dst, src: rawptr, len: int, is_volatile: bool = false) ---;
|
||||
}
|
||||
}
|
||||
llvm_memcpy(dst, src, len);
|
||||
intrinsics.mem_copy_non_overlapping(dst, src, len);
|
||||
return dst;
|
||||
}
|
||||
|
||||
@@ -409,11 +393,6 @@ string_decode_rune :: #force_inline proc "contextless" (s: string) -> (rune, int
|
||||
return rune(s0&MASK4)<<18 | rune(b1&MASKX)<<12 | rune(b2&MASKX)<<6 | rune(b3&MASKX), 4;
|
||||
}
|
||||
|
||||
@(default_calling_convention = "none")
|
||||
foreign {
|
||||
@(link_name="llvm.sqrt.f32") _sqrt_f32 :: proc(x: f32) -> f32 ---
|
||||
@(link_name="llvm.sqrt.f64") _sqrt_f64 :: proc(x: f64) -> f64 ---
|
||||
}
|
||||
abs_f16 :: #force_inline proc "contextless" (x: f16) -> f16 {
|
||||
return -x if x < 0 else x;
|
||||
}
|
||||
@@ -445,27 +424,27 @@ max_f64 :: proc(a, b: f64) -> f64 {
|
||||
|
||||
abs_complex32 :: #force_inline proc "contextless" (x: complex32) -> f16 {
|
||||
r, i := real(x), imag(x);
|
||||
return f16(_sqrt_f32(f32(r*r + i*i)));
|
||||
return f16(intrinsics.sqrt(f32(r*r + i*i)));
|
||||
}
|
||||
abs_complex64 :: #force_inline proc "contextless" (x: complex64) -> f32 {
|
||||
r, i := real(x), imag(x);
|
||||
return _sqrt_f32(r*r + i*i);
|
||||
return intrinsics.sqrt(r*r + i*i);
|
||||
}
|
||||
abs_complex128 :: #force_inline proc "contextless" (x: complex128) -> f64 {
|
||||
r, i := real(x), imag(x);
|
||||
return _sqrt_f64(r*r + i*i);
|
||||
return intrinsics.sqrt(r*r + i*i);
|
||||
}
|
||||
abs_quaternion64 :: #force_inline proc "contextless" (x: quaternion64) -> f16 {
|
||||
r, i, j, k := real(x), imag(x), jmag(x), kmag(x);
|
||||
return f16(_sqrt_f32(f32(r*r + i*i + j*j + k*k)));
|
||||
return f16(intrinsics.sqrt(f32(r*r + i*i + j*j + k*k)));
|
||||
}
|
||||
abs_quaternion128 :: #force_inline proc "contextless" (x: quaternion128) -> f32 {
|
||||
r, i, j, k := real(x), imag(x), jmag(x), kmag(x);
|
||||
return _sqrt_f32(r*r + i*i + j*j + k*k);
|
||||
return intrinsics.sqrt(r*r + i*i + j*j + k*k);
|
||||
}
|
||||
abs_quaternion256 :: #force_inline proc "contextless" (x: quaternion256) -> f64 {
|
||||
r, i, j, k := real(x), imag(x), jmag(x), kmag(x);
|
||||
return _sqrt_f64(r*r + i*i + j*j + k*k);
|
||||
return intrinsics.sqrt(r*r + i*i + j*j + k*k);
|
||||
}
|
||||
|
||||
|
||||
@@ -644,7 +623,7 @@ truncsfhf2 :: proc "c" (value: f32) -> u16 {
|
||||
}
|
||||
|
||||
if (e > 30) {
|
||||
f := 1e12;
|
||||
f := i64(1e12);
|
||||
for j := 0; j < 10; j += 1 {
|
||||
/* NOTE(bill): Cause overflow */
|
||||
g := intrinsics.volatile_load(&f);
|
||||
|
||||
@@ -1,3 +1,11 @@
|
||||
package runtime
|
||||
|
||||
_OS_Errno :: distinct int;
|
||||
|
||||
os_write :: proc "contextless" (data: []byte) -> (int, _OS_Errno) {
|
||||
return _os_write(data);
|
||||
}
|
||||
|
||||
current_thread_id :: proc "contextless" () -> int {
|
||||
return _current_thread_id();
|
||||
}
|
||||
|
||||
@@ -6,12 +6,12 @@ import "core:os"
|
||||
|
||||
// TODO(bill): reimplement `os.write` so that it does not rely on package os
|
||||
// NOTE: Use os_specific_linux.odin, os_specific_darwin.odin, etc
|
||||
os_write :: proc "contextless" (data: []byte) -> (int, _OS_Errno) {
|
||||
_os_write :: proc "contextless" (data: []byte) -> (int, _OS_Errno) {
|
||||
context = default_context();
|
||||
n, err := os.write(os.stderr, data);
|
||||
return int(n), _OS_Errno(err);
|
||||
}
|
||||
|
||||
current_thread_id :: proc "contextless" () -> int {
|
||||
_current_thread_id :: proc "contextless" () -> int {
|
||||
return os.current_thread_id();
|
||||
}
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
package runtime
|
||||
|
||||
// TODO(bill): reimplement `os.write`
|
||||
os_write :: proc "contextless" (data: []byte) -> (int, _OS_Errno) {
|
||||
_os_write :: proc "contextless" (data: []byte) -> (int, _OS_Errno) {
|
||||
return 0, -1;
|
||||
}
|
||||
|
||||
current_thread_id :: proc "contextless" () -> int {
|
||||
_current_thread_id :: proc "contextless" () -> int {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
//+private
|
||||
//+build windows
|
||||
package runtime
|
||||
|
||||
@@ -24,7 +25,7 @@ foreign kernel32 {
|
||||
HeapFree :: proc(hHeap: rawptr, dwFlags: u32, lpMem: rawptr) -> b32 ---
|
||||
}
|
||||
|
||||
os_write :: proc "contextless" (data: []byte) -> (n: int, err: _OS_Errno) {
|
||||
_os_write :: proc "contextless" (data: []byte) -> (n: int, err: _OS_Errno) {
|
||||
if len(data) == 0 {
|
||||
return 0, 0;
|
||||
}
|
||||
@@ -58,7 +59,7 @@ os_write :: proc "contextless" (data: []byte) -> (n: int, err: _OS_Errno) {
|
||||
return;
|
||||
}
|
||||
|
||||
current_thread_id :: proc "contextless" () -> int {
|
||||
_current_thread_id :: proc "contextless" () -> int {
|
||||
return int(GetCurrentThreadId());
|
||||
}
|
||||
|
||||
@@ -86,89 +87,58 @@ heap_free :: proc "contextless" (ptr: rawptr) {
|
||||
HeapFree(GetProcessHeap(), 0, ptr);
|
||||
}
|
||||
|
||||
default_allocator_proc :: proc(allocator_data: rawptr, mode: Allocator_Mode,
|
||||
size, alignment: int,
|
||||
old_memory: rawptr, old_size: int, loc := #caller_location) -> ([]byte, Allocator_Error) {
|
||||
|
||||
//
|
||||
// NOTE(tetra, 2020-01-14): The heap doesn't respect alignment.
|
||||
// Instead, we overallocate by `alignment + size_of(rawptr) - 1`, and insert
|
||||
// padding. We also store the original pointer returned by heap_alloc right before
|
||||
// the pointer we return to the user.
|
||||
//
|
||||
//
|
||||
// NOTE(tetra, 2020-01-14): The heap doesn't respect alignment.
|
||||
// Instead, we overallocate by `alignment + size_of(rawptr) - 1`, and insert
|
||||
// padding. We also store the original pointer returned by heap_alloc right before
|
||||
// the pointer we return to the user.
|
||||
//
|
||||
|
||||
aligned_alloc :: proc "contextless" (size, alignment: int, old_ptr: rawptr = nil) -> ([]byte, Allocator_Error) {
|
||||
a := max(alignment, align_of(rawptr));
|
||||
space := size + a - 1;
|
||||
|
||||
allocated_mem: rawptr;
|
||||
if old_ptr != nil {
|
||||
original_old_ptr := ptr_offset((^rawptr)(old_ptr), -1)^;
|
||||
allocated_mem = heap_resize(original_old_ptr, space+size_of(rawptr));
|
||||
} else {
|
||||
allocated_mem = heap_alloc(space+size_of(rawptr));
|
||||
}
|
||||
aligned_mem := rawptr(ptr_offset((^u8)(allocated_mem), size_of(rawptr)));
|
||||
|
||||
ptr := uintptr(aligned_mem);
|
||||
aligned_ptr := (ptr - 1 + uintptr(a)) & -uintptr(a);
|
||||
diff := int(aligned_ptr - ptr);
|
||||
if (size + diff) > space {
|
||||
return nil, .Out_Of_Memory;
|
||||
}
|
||||
|
||||
aligned_mem = rawptr(aligned_ptr);
|
||||
ptr_offset((^rawptr)(aligned_mem), -1)^ = allocated_mem;
|
||||
|
||||
return byte_slice(aligned_mem, size), nil;
|
||||
}
|
||||
|
||||
aligned_free :: proc "contextless" (p: rawptr) {
|
||||
if p != nil {
|
||||
heap_free(ptr_offset((^rawptr)(p), -1)^);
|
||||
}
|
||||
}
|
||||
|
||||
aligned_resize :: proc "contextless" (p: rawptr, old_size: int, new_size: int, new_alignment: int) -> ([]byte, Allocator_Error) {
|
||||
if p == nil {
|
||||
return nil, nil;
|
||||
}
|
||||
return aligned_alloc(new_size, new_alignment, p);
|
||||
}
|
||||
|
||||
switch mode {
|
||||
case .Alloc:
|
||||
return aligned_alloc(size, alignment);
|
||||
|
||||
case .Free:
|
||||
aligned_free(old_memory);
|
||||
|
||||
case .Free_All:
|
||||
// NOTE(tetra): Do nothing.
|
||||
|
||||
case .Resize:
|
||||
if old_memory == nil {
|
||||
return aligned_alloc(size, alignment);
|
||||
}
|
||||
return aligned_resize(old_memory, old_size, size, alignment);
|
||||
|
||||
case .Query_Features:
|
||||
set := (^Allocator_Mode_Set)(old_memory);
|
||||
if set != nil {
|
||||
set^ = {.Alloc, .Free, .Resize, .Query_Features};
|
||||
}
|
||||
return nil, nil;
|
||||
|
||||
case .Query_Info:
|
||||
_windows_default_alloc_or_resize :: proc "contextless" (size, alignment: int, old_ptr: rawptr = nil) -> ([]byte, Allocator_Error) {
|
||||
if size == 0 {
|
||||
_windows_default_free(old_ptr);
|
||||
return nil, nil;
|
||||
}
|
||||
|
||||
return nil, nil;
|
||||
a := max(alignment, align_of(rawptr));
|
||||
space := size + a - 1;
|
||||
|
||||
allocated_mem: rawptr;
|
||||
if old_ptr != nil {
|
||||
original_old_ptr := ptr_offset((^rawptr)(old_ptr), -1)^;
|
||||
allocated_mem = heap_resize(original_old_ptr, space+size_of(rawptr));
|
||||
} else {
|
||||
allocated_mem = heap_alloc(space+size_of(rawptr));
|
||||
}
|
||||
aligned_mem := rawptr(ptr_offset((^u8)(allocated_mem), size_of(rawptr)));
|
||||
|
||||
ptr := uintptr(aligned_mem);
|
||||
aligned_ptr := (ptr - 1 + uintptr(a)) & -uintptr(a);
|
||||
diff := int(aligned_ptr - ptr);
|
||||
if (size + diff) > space {
|
||||
return nil, .Out_Of_Memory;
|
||||
}
|
||||
|
||||
aligned_mem = rawptr(aligned_ptr);
|
||||
ptr_offset((^rawptr)(aligned_mem), -1)^ = allocated_mem;
|
||||
|
||||
return byte_slice(aligned_mem, size), nil;
|
||||
}
|
||||
|
||||
default_allocator :: proc() -> Allocator {
|
||||
return Allocator{
|
||||
procedure = default_allocator_proc,
|
||||
data = nil,
|
||||
};
|
||||
_windows_default_alloc :: proc "contextless" (size, alignment: int) -> ([]byte, Allocator_Error) {
|
||||
return _windows_default_alloc_or_resize(size, alignment, nil);
|
||||
}
|
||||
|
||||
|
||||
_windows_default_free :: proc "contextless" (ptr: rawptr) {
|
||||
if ptr != nil {
|
||||
heap_free(ptr_offset((^rawptr)(ptr), -1)^);
|
||||
}
|
||||
}
|
||||
|
||||
_windows_default_resize :: proc "contextless" (p: rawptr, old_size: int, new_size: int, new_alignment: int) -> ([]byte, Allocator_Error) {
|
||||
return _windows_default_alloc_or_resize(new_size, new_alignment, p);
|
||||
}
|
||||
|
||||
@@ -1,18 +1,22 @@
|
||||
package runtime
|
||||
|
||||
import "core:sys/es"
|
||||
|
||||
@(link_name="memset")
|
||||
memset :: proc "c" (ptr: rawptr, val: i32, len: int) -> rawptr {
|
||||
return es.CRTmemset(ptr, val, len);
|
||||
addr := 0x1000 + 196 * size_of(int);
|
||||
fp := (rawptr(((^uintptr)(uintptr(addr)))^));
|
||||
return ((proc "c" (rawptr, i32, int) -> rawptr)(fp))(ptr, val, len);
|
||||
}
|
||||
|
||||
@(link_name="memmove")
|
||||
memmove :: proc "c" (dst, src: rawptr, len: int) -> rawptr {
|
||||
return es.CRTmemmove(dst, src, len);
|
||||
addr := 0x1000 + 195 * size_of(int);
|
||||
fp := (rawptr(((^uintptr)(uintptr(addr)))^));
|
||||
return ((proc "c" (rawptr, rawptr, int) -> rawptr)(fp))(dst, src, len);
|
||||
}
|
||||
|
||||
@(link_name="memcpy")
|
||||
memcpy :: proc "c" (dst, src: rawptr, len: int) -> rawptr {
|
||||
return es.CRTmemcpy(dst, src, len);
|
||||
addr := 0x1000 + 194 * size_of(int);
|
||||
fp := (rawptr(((^uintptr)(uintptr(addr)))^));
|
||||
return ((proc "c" (rawptr, rawptr, int) -> rawptr)(fp))(dst, src, len);
|
||||
}
|
||||
|
||||
@@ -221,7 +221,7 @@ pop_rune :: proc(b: ^Builder) -> (r: rune, width: int) {
|
||||
}
|
||||
|
||||
|
||||
@(private, static)
|
||||
@(private)
|
||||
DIGITS_LOWER := "0123456789abcdefx";
|
||||
|
||||
write_quoted_string :: proc{
|
||||
|
||||
@@ -541,6 +541,14 @@ replace :: proc(s, old, new: string, n: int, allocator := context.allocator) ->
|
||||
return;
|
||||
}
|
||||
|
||||
remove :: proc(s, key: string, n: int, allocator := context.allocator) -> (output: string, was_allocation: bool) {
|
||||
return replace(s, key, "", n, allocator);
|
||||
}
|
||||
|
||||
remove_all :: proc(s, key: string, allocator := context.allocator) -> (output: string, was_allocation: bool) {
|
||||
return remove(s, key, -1, allocator);
|
||||
}
|
||||
|
||||
@(private) _ascii_space := [256]u8{'\t' = 1, '\n' = 1, '\v' = 1, '\f' = 1, '\r' = 1, ' ' = 1};
|
||||
|
||||
|
||||
|
||||
@@ -56,6 +56,7 @@ atomic_exchange_release :: intrinsics.atomic_xchg_rel;
|
||||
atomic_exchange_acqrel :: intrinsics.atomic_xchg_acqrel;
|
||||
atomic_exchange_relaxed :: intrinsics.atomic_xchg_relaxed;
|
||||
|
||||
// Returns value and optional ok boolean
|
||||
atomic_compare_exchange_strong :: intrinsics.atomic_cxchg;
|
||||
atomic_compare_exchange_strong_acquire :: intrinsics.atomic_cxchg_acq;
|
||||
atomic_compare_exchange_strong_release :: intrinsics.atomic_cxchg_rel;
|
||||
@@ -66,6 +67,7 @@ atomic_compare_exchange_strong_failacquire :: intrinsics.atomic_cxchg_fa
|
||||
atomic_compare_exchange_strong_acquire_failrelaxed :: intrinsics.atomic_cxchg_acq_failrelaxed;
|
||||
atomic_compare_exchange_strong_acqrel_failrelaxed :: intrinsics.atomic_cxchg_acqrel_failrelaxed;
|
||||
|
||||
// Returns value and optional ok boolean
|
||||
atomic_compare_exchange_weak :: intrinsics.atomic_cxchgweak;
|
||||
atomic_compare_exchange_weak_acquire :: intrinsics.atomic_cxchgweak_acq;
|
||||
atomic_compare_exchange_weak_release :: intrinsics.atomic_cxchgweak_rel;
|
||||
|
||||
@@ -1,886 +0,0 @@
|
||||
package sync2
|
||||
|
||||
// TODO(bill): The Channel implementation needs a complete rewrite for this new package sync design
|
||||
// Especially how the `select` things work
|
||||
|
||||
import "core:mem"
|
||||
import "core:time"
|
||||
import "core:math/rand"
|
||||
|
||||
_, _ :: time, rand;
|
||||
|
||||
Channel_Direction :: enum i8 {
|
||||
Both = 0,
|
||||
Send = +1,
|
||||
Recv = -1,
|
||||
}
|
||||
|
||||
Channel :: struct(T: typeid, Direction := Channel_Direction.Both) {
|
||||
using _internal: ^Raw_Channel,
|
||||
}
|
||||
|
||||
channel_init :: proc(ch: ^$C/Channel($T, $D), cap := 0, allocator := context.allocator) {
|
||||
context.allocator = allocator;
|
||||
ch._internal = raw_channel_create(size_of(T), align_of(T), cap);
|
||||
return;
|
||||
}
|
||||
|
||||
channel_make :: proc($T: typeid, cap := 0, allocator := context.allocator) -> (ch: Channel(T, .Both)) {
|
||||
context.allocator = allocator;
|
||||
ch._internal = raw_channel_create(size_of(T), align_of(T), cap);
|
||||
return;
|
||||
}
|
||||
|
||||
channel_make_send :: proc($T: typeid, cap := 0, allocator := context.allocator) -> (ch: Channel(T, .Send)) {
|
||||
context.allocator = allocator;
|
||||
ch._internal = raw_channel_create(size_of(T), align_of(T), cap);
|
||||
return;
|
||||
}
|
||||
channel_make_recv :: proc($T: typeid, cap := 0, allocator := context.allocator) -> (ch: Channel(T, .Recv)) {
|
||||
context.allocator = allocator;
|
||||
ch._internal = raw_channel_create(size_of(T), align_of(T), cap);
|
||||
return;
|
||||
}
|
||||
|
||||
channel_destroy :: proc(ch: $C/Channel($T, $D)) {
|
||||
raw_channel_destroy(ch._internal);
|
||||
}
|
||||
|
||||
channel_as_send :: proc(ch: $C/Channel($T, .Both)) -> (res: Channel(T, .Send)) {
|
||||
res._internal = ch._internal;
|
||||
return;
|
||||
}
|
||||
|
||||
channel_as_recv :: proc(ch: $C/Channel($T, .Both)) -> (res: Channel(T, .Recv)) {
|
||||
res._internal = ch._internal;
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
channel_len :: proc(ch: $C/Channel($T, $D)) -> int {
|
||||
return ch._internal.len if ch._internal != nil else 0;
|
||||
}
|
||||
channel_cap :: proc(ch: $C/Channel($T, $D)) -> int {
|
||||
return ch._internal.cap if ch._internal != nil else 0;
|
||||
}
|
||||
|
||||
|
||||
channel_send :: proc(ch: $C/Channel($T, $D), msg: T, loc := #caller_location) where D >= .Both {
|
||||
msg := msg;
|
||||
_ = raw_channel_send_impl(ch._internal, &msg, /*block*/true, loc);
|
||||
}
|
||||
channel_try_send :: proc(ch: $C/Channel($T, $D), msg: T, loc := #caller_location) -> bool where D >= .Both {
|
||||
msg := msg;
|
||||
return raw_channel_send_impl(ch._internal, &msg, /*block*/false, loc);
|
||||
}
|
||||
|
||||
channel_recv :: proc(ch: $C/Channel($T, $D), loc := #caller_location) -> (msg: T) where D <= .Both {
|
||||
c := ch._internal;
|
||||
if c == nil {
|
||||
panic(message="cannot recv message; channel is nil", loc=loc);
|
||||
}
|
||||
mutex_lock(&c.mutex);
|
||||
raw_channel_recv_impl(c, &msg, loc);
|
||||
mutex_unlock(&c.mutex);
|
||||
return;
|
||||
}
|
||||
channel_try_recv :: proc(ch: $C/Channel($T, $D), loc := #caller_location) -> (msg: T, ok: bool) where D <= .Both {
|
||||
c := ch._internal;
|
||||
if c != nil && mutex_try_lock(&c.mutex) {
|
||||
if c.len > 0 {
|
||||
raw_channel_recv_impl(c, &msg, loc);
|
||||
ok = true;
|
||||
}
|
||||
mutex_unlock(&c.mutex);
|
||||
}
|
||||
return;
|
||||
}
|
||||
channel_try_recv_ptr :: proc(ch: $C/Channel($T, $D), msg: ^T, loc := #caller_location) -> (ok: bool) where D <= .Both {
|
||||
res: T;
|
||||
res, ok = channel_try_recv(ch, loc);
|
||||
if ok && msg != nil {
|
||||
msg^ = res;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
channel_is_nil :: proc(ch: $C/Channel($T, $D)) -> bool {
|
||||
return ch._internal == nil;
|
||||
}
|
||||
channel_is_open :: proc(ch: $C/Channel($T, $D)) -> bool {
|
||||
c := ch._internal;
|
||||
return c != nil && !c.closed;
|
||||
}
|
||||
|
||||
|
||||
channel_eq :: proc(a, b: $C/Channel($T, $D)) -> bool {
|
||||
return a._internal == b._internal;
|
||||
}
|
||||
channel_ne :: proc(a, b: $C/Channel($T, $D)) -> bool {
|
||||
return a._internal != b._internal;
|
||||
}
|
||||
|
||||
|
||||
channel_can_send :: proc(ch: $C/Channel($T, $D)) -> (ok: bool) where D >= .Both {
|
||||
return raw_channel_can_send(ch._internal);
|
||||
}
|
||||
channel_can_recv :: proc(ch: $C/Channel($T, $D)) -> (ok: bool) where D <= .Both {
|
||||
return raw_channel_can_recv(ch._internal);
|
||||
}
|
||||
|
||||
|
||||
channel_peek :: proc(ch: $C/Channel($T, $D)) -> int {
|
||||
c := ch._internal;
|
||||
if c == nil {
|
||||
return -1;
|
||||
}
|
||||
if atomic_load(&c.closed) {
|
||||
return -1;
|
||||
}
|
||||
return atomic_load(&c.len);
|
||||
}
|
||||
|
||||
|
||||
channel_close :: proc(ch: $C/Channel($T, $D), loc := #caller_location) {
|
||||
raw_channel_close(ch._internal, loc);
|
||||
}
|
||||
|
||||
|
||||
channel_iterator :: proc(ch: $C/Channel($T, $D)) -> (msg: T, ok: bool) where D <= .Both {
|
||||
c := ch._internal;
|
||||
if c == nil {
|
||||
return;
|
||||
}
|
||||
|
||||
if !c.closed || c.len > 0 {
|
||||
msg, ok = channel_recv(ch), true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
channel_drain :: proc(ch: $C/Channel($T, $D)) where D >= .Both {
|
||||
raw_channel_drain(ch._internal);
|
||||
}
|
||||
|
||||
|
||||
channel_move :: proc(dst: $C1/Channel($T, $D1) src: $C2/Channel(T, $D2)) where D1 <= .Both, D2 >= .Both {
|
||||
for msg in channel_iterator(src) {
|
||||
channel_send(dst, msg);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Raw_Channel_Wait_Queue :: struct {
|
||||
next: ^Raw_Channel_Wait_Queue,
|
||||
state: ^uintptr,
|
||||
}
|
||||
|
||||
|
||||
Raw_Channel :: struct {
|
||||
closed: bool,
|
||||
ready: bool, // ready to recv
|
||||
data_offset: u16, // data is stored at the end of this data structure
|
||||
elem_size: u32,
|
||||
len, cap: int,
|
||||
read, write: int,
|
||||
mutex: Mutex,
|
||||
cond: Cond,
|
||||
allocator: mem.Allocator,
|
||||
|
||||
sendq: ^Raw_Channel_Wait_Queue,
|
||||
recvq: ^Raw_Channel_Wait_Queue,
|
||||
}
|
||||
|
||||
raw_channel_wait_queue_insert :: proc(head: ^^Raw_Channel_Wait_Queue, val: ^Raw_Channel_Wait_Queue) {
|
||||
val.next = head^;
|
||||
head^ = val;
|
||||
}
|
||||
raw_channel_wait_queue_remove :: proc(head: ^^Raw_Channel_Wait_Queue, val: ^Raw_Channel_Wait_Queue) {
|
||||
p := head;
|
||||
for p^ != nil && p^ != val {
|
||||
p = &p^.next;
|
||||
}
|
||||
if p != nil {
|
||||
p^ = p^.next;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
raw_channel_create :: proc(elem_size, elem_align: int, cap := 0) -> ^Raw_Channel {
|
||||
assert(int(u32(elem_size)) == elem_size);
|
||||
|
||||
s := size_of(Raw_Channel);
|
||||
s = mem.align_forward_int(s, elem_align);
|
||||
data_offset := uintptr(s);
|
||||
s += elem_size * max(cap, 1);
|
||||
|
||||
a := max(elem_align, align_of(Raw_Channel));
|
||||
|
||||
c := (^Raw_Channel)(mem.alloc(s, a));
|
||||
if c == nil {
|
||||
return nil;
|
||||
}
|
||||
|
||||
c.data_offset = u16(data_offset);
|
||||
c.elem_size = u32(elem_size);
|
||||
c.len, c.cap = 0, max(cap, 0);
|
||||
c.read, c.write = 0, 0;
|
||||
c.allocator = context.allocator;
|
||||
c.closed = false;
|
||||
|
||||
return c;
|
||||
}
|
||||
|
||||
|
||||
raw_channel_destroy :: proc(c: ^Raw_Channel) {
|
||||
if c == nil {
|
||||
return;
|
||||
}
|
||||
context.allocator = c.allocator;
|
||||
atomic_store(&c.closed, true);
|
||||
free(c);
|
||||
}
|
||||
|
||||
raw_channel_close :: proc(c: ^Raw_Channel, loc := #caller_location) {
|
||||
if c == nil {
|
||||
panic(message="cannot close nil channel", loc=loc);
|
||||
}
|
||||
mutex_lock(&c.mutex);
|
||||
defer mutex_unlock(&c.mutex);
|
||||
atomic_store(&c.closed, true);
|
||||
|
||||
// Release readers and writers
|
||||
raw_channel_wait_queue_broadcast(c.recvq);
|
||||
raw_channel_wait_queue_broadcast(c.sendq);
|
||||
cond_broadcast(&c.cond);
|
||||
}
|
||||
|
||||
|
||||
|
||||
raw_channel_send_impl :: proc(c: ^Raw_Channel, msg: rawptr, block: bool, loc := #caller_location) -> bool {
|
||||
send :: proc(c: ^Raw_Channel, src: rawptr) {
|
||||
data := uintptr(c) + uintptr(c.data_offset);
|
||||
dst := data + uintptr(c.write * int(c.elem_size));
|
||||
mem.copy(rawptr(dst), src, int(c.elem_size));
|
||||
c.len += 1;
|
||||
c.write = (c.write + 1) % max(c.cap, 1);
|
||||
}
|
||||
|
||||
switch {
|
||||
case c == nil:
|
||||
panic(message="cannot send message; channel is nil", loc=loc);
|
||||
case c.closed:
|
||||
panic(message="cannot send message; channel is closed", loc=loc);
|
||||
}
|
||||
|
||||
mutex_lock(&c.mutex);
|
||||
defer mutex_unlock(&c.mutex);
|
||||
|
||||
if c.cap > 0 {
|
||||
if !block && c.len >= c.cap {
|
||||
return false;
|
||||
}
|
||||
|
||||
for c.len >= c.cap {
|
||||
cond_wait(&c.cond, &c.mutex);
|
||||
}
|
||||
} else if c.len > 0 { // TODO(bill): determine correct behaviour
|
||||
if !block {
|
||||
return false;
|
||||
}
|
||||
cond_wait(&c.cond, &c.mutex);
|
||||
} else if c.len == 0 && !block {
|
||||
return false;
|
||||
}
|
||||
|
||||
send(c, msg);
|
||||
cond_signal(&c.cond);
|
||||
raw_channel_wait_queue_signal(c.recvq);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
raw_channel_recv_impl :: proc(c: ^Raw_Channel, res: rawptr, loc := #caller_location) {
|
||||
recv :: proc(c: ^Raw_Channel, dst: rawptr, loc := #caller_location) {
|
||||
if c.len < 1 {
|
||||
panic(message="cannot recv message; channel is empty", loc=loc);
|
||||
}
|
||||
c.len -= 1;
|
||||
|
||||
data := uintptr(c) + uintptr(c.data_offset);
|
||||
src := data + uintptr(c.read * int(c.elem_size));
|
||||
mem.copy(dst, rawptr(src), int(c.elem_size));
|
||||
c.read = (c.read + 1) % max(c.cap, 1);
|
||||
}
|
||||
|
||||
if c == nil {
|
||||
panic(message="cannot recv message; channel is nil", loc=loc);
|
||||
}
|
||||
atomic_store(&c.ready, true);
|
||||
for c.len < 1 {
|
||||
raw_channel_wait_queue_signal(c.sendq);
|
||||
cond_wait(&c.cond, &c.mutex);
|
||||
}
|
||||
atomic_store(&c.ready, false);
|
||||
recv(c, res, loc);
|
||||
if c.cap > 0 {
|
||||
if c.len == c.cap - 1 {
|
||||
// NOTE(bill): Only signal on the last one
|
||||
cond_signal(&c.cond);
|
||||
}
|
||||
} else {
|
||||
cond_signal(&c.cond);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
raw_channel_can_send :: proc(c: ^Raw_Channel) -> (ok: bool) {
|
||||
if c == nil {
|
||||
return false;
|
||||
}
|
||||
mutex_lock(&c.mutex);
|
||||
switch {
|
||||
case c.closed:
|
||||
ok = false;
|
||||
case c.cap > 0:
|
||||
ok = c.ready && c.len < c.cap;
|
||||
case:
|
||||
ok = c.ready && c.len == 0;
|
||||
}
|
||||
mutex_unlock(&c.mutex);
|
||||
return;
|
||||
}
|
||||
raw_channel_can_recv :: proc(c: ^Raw_Channel) -> (ok: bool) {
|
||||
if c == nil {
|
||||
return false;
|
||||
}
|
||||
mutex_lock(&c.mutex);
|
||||
ok = c.len > 0;
|
||||
mutex_unlock(&c.mutex);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
raw_channel_drain :: proc(c: ^Raw_Channel) {
|
||||
if c == nil {
|
||||
return;
|
||||
}
|
||||
mutex_lock(&c.mutex);
|
||||
c.len = 0;
|
||||
c.read = 0;
|
||||
c.write = 0;
|
||||
mutex_unlock(&c.mutex);
|
||||
}
|
||||
|
||||
|
||||
|
||||
MAX_SELECT_CHANNELS :: 64;
|
||||
SELECT_MAX_TIMEOUT :: max(time.Duration);
|
||||
|
||||
Select_Command :: enum {
|
||||
Recv,
|
||||
Send,
|
||||
}
|
||||
|
||||
Select_Channel :: struct {
|
||||
channel: ^Raw_Channel,
|
||||
command: Select_Command,
|
||||
}
|
||||
|
||||
|
||||
|
||||
select :: proc(channels: ..Select_Channel) -> (index: int) {
|
||||
return select_timeout(SELECT_MAX_TIMEOUT, ..channels);
|
||||
}
|
||||
select_timeout :: proc(timeout: time.Duration, channels: ..Select_Channel) -> (index: int) {
|
||||
switch len(channels) {
|
||||
case 0:
|
||||
panic("sync: select with no channels");
|
||||
}
|
||||
|
||||
assert(len(channels) <= MAX_SELECT_CHANNELS);
|
||||
|
||||
backing: [MAX_SELECT_CHANNELS]int;
|
||||
queues: [MAX_SELECT_CHANNELS]Raw_Channel_Wait_Queue;
|
||||
candidates := backing[:];
|
||||
cap := len(channels);
|
||||
candidates = candidates[:cap];
|
||||
|
||||
count := u32(0);
|
||||
for c, i in channels {
|
||||
if c.channel == nil {
|
||||
continue;
|
||||
}
|
||||
switch c.command {
|
||||
case .Recv:
|
||||
if raw_channel_can_recv(c.channel) {
|
||||
candidates[count] = i;
|
||||
count += 1;
|
||||
}
|
||||
case .Send:
|
||||
if raw_channel_can_send(c.channel) {
|
||||
candidates[count] = i;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if count == 0 {
|
||||
wait_state: uintptr = 0;
|
||||
for _, i in channels {
|
||||
q := &queues[i];
|
||||
q.state = &wait_state;
|
||||
}
|
||||
|
||||
for c, i in channels {
|
||||
if c.channel == nil {
|
||||
continue;
|
||||
}
|
||||
q := &queues[i];
|
||||
switch c.command {
|
||||
case .Recv: raw_channel_wait_queue_insert(&c.channel.recvq, q);
|
||||
case .Send: raw_channel_wait_queue_insert(&c.channel.sendq, q);
|
||||
}
|
||||
}
|
||||
raw_channel_wait_queue_wait_on(&wait_state, timeout);
|
||||
for c, i in channels {
|
||||
if c.channel == nil {
|
||||
continue;
|
||||
}
|
||||
q := &queues[i];
|
||||
switch c.command {
|
||||
case .Recv: raw_channel_wait_queue_remove(&c.channel.recvq, q);
|
||||
case .Send: raw_channel_wait_queue_remove(&c.channel.sendq, q);
|
||||
}
|
||||
}
|
||||
|
||||
for c, i in channels {
|
||||
switch c.command {
|
||||
case .Recv:
|
||||
if raw_channel_can_recv(c.channel) {
|
||||
candidates[count] = i;
|
||||
count += 1;
|
||||
}
|
||||
case .Send:
|
||||
if raw_channel_can_send(c.channel) {
|
||||
candidates[count] = i;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if count == 0 && timeout == SELECT_MAX_TIMEOUT {
|
||||
index = -1;
|
||||
return;
|
||||
}
|
||||
|
||||
assert(count != 0);
|
||||
}
|
||||
|
||||
t := time.now();
|
||||
r := rand.create(transmute(u64)t);
|
||||
i := rand.uint32(&r);
|
||||
|
||||
index = candidates[i % count];
|
||||
return;
|
||||
}
|
||||
|
||||
select_recv :: proc(channels: ..^Raw_Channel) -> (index: int) {
|
||||
switch len(channels) {
|
||||
case 0:
|
||||
panic("sync: select with no channels");
|
||||
}
|
||||
|
||||
assert(len(channels) <= MAX_SELECT_CHANNELS);
|
||||
|
||||
backing: [MAX_SELECT_CHANNELS]int;
|
||||
queues: [MAX_SELECT_CHANNELS]Raw_Channel_Wait_Queue;
|
||||
candidates := backing[:];
|
||||
cap := len(channels);
|
||||
candidates = candidates[:cap];
|
||||
|
||||
count := u32(0);
|
||||
for c, i in channels {
|
||||
if raw_channel_can_recv(c) {
|
||||
candidates[count] = i;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if count == 0 {
|
||||
state: uintptr;
|
||||
for c, i in channels {
|
||||
q := &queues[i];
|
||||
q.state = &state;
|
||||
raw_channel_wait_queue_insert(&c.recvq, q);
|
||||
}
|
||||
raw_channel_wait_queue_wait_on(&state, SELECT_MAX_TIMEOUT);
|
||||
for c, i in channels {
|
||||
q := &queues[i];
|
||||
raw_channel_wait_queue_remove(&c.recvq, q);
|
||||
}
|
||||
|
||||
for c, i in channels {
|
||||
if raw_channel_can_recv(c) {
|
||||
candidates[count] = i;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
assert(count != 0);
|
||||
}
|
||||
|
||||
t := time.now();
|
||||
r := rand.create(transmute(u64)t);
|
||||
i := rand.uint32(&r);
|
||||
|
||||
index = candidates[i % count];
|
||||
return;
|
||||
}
|
||||
|
||||
select_recv_msg :: proc(channels: ..$C/Channel($T, $D)) -> (msg: T, index: int) {
|
||||
switch len(channels) {
|
||||
case 0:
|
||||
panic("sync: select with no channels");
|
||||
}
|
||||
|
||||
assert(len(channels) <= MAX_SELECT_CHANNELS);
|
||||
|
||||
queues: [MAX_SELECT_CHANNELS]Raw_Channel_Wait_Queue;
|
||||
candidates: [MAX_SELECT_CHANNELS]int;
|
||||
|
||||
count := u32(0);
|
||||
for c, i in channels {
|
||||
if raw_channel_can_recv(c) {
|
||||
candidates[count] = i;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if count == 0 {
|
||||
state: uintptr;
|
||||
for c, i in channels {
|
||||
q := &queues[i];
|
||||
q.state = &state;
|
||||
raw_channel_wait_queue_insert(&c.recvq, q);
|
||||
}
|
||||
raw_channel_wait_queue_wait_on(&state, SELECT_MAX_TIMEOUT);
|
||||
for c, i in channels {
|
||||
q := &queues[i];
|
||||
raw_channel_wait_queue_remove(&c.recvq, q);
|
||||
}
|
||||
|
||||
for c, i in channels {
|
||||
if raw_channel_can_recv(c) {
|
||||
candidates[count] = i;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
assert(count != 0);
|
||||
}
|
||||
|
||||
t := time.now();
|
||||
r := rand.create(transmute(u64)t);
|
||||
i := rand.uint32(&r);
|
||||
|
||||
index = candidates[i % count];
|
||||
msg = channel_recv(channels[index]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
select_send_msg :: proc(msg: $T, channels: ..$C/Channel(T, $D)) -> (index: int) {
|
||||
switch len(channels) {
|
||||
case 0:
|
||||
panic("sync: select with no channels");
|
||||
}
|
||||
|
||||
assert(len(channels) <= MAX_SELECT_CHANNELS);
|
||||
|
||||
backing: [MAX_SELECT_CHANNELS]int;
|
||||
queues: [MAX_SELECT_CHANNELS]Raw_Channel_Wait_Queue;
|
||||
candidates := backing[:];
|
||||
cap := len(channels);
|
||||
candidates = candidates[:cap];
|
||||
|
||||
count := u32(0);
|
||||
for c, i in channels {
|
||||
if raw_channel_can_recv(c) {
|
||||
candidates[count] = i;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if count == 0 {
|
||||
state: uintptr;
|
||||
for c, i in channels {
|
||||
q := &queues[i];
|
||||
q.state = &state;
|
||||
raw_channel_wait_queue_insert(&c.recvq, q);
|
||||
}
|
||||
raw_channel_wait_queue_wait_on(&state, SELECT_MAX_TIMEOUT);
|
||||
for c, i in channels {
|
||||
q := &queues[i];
|
||||
raw_channel_wait_queue_remove(&c.recvq, q);
|
||||
}
|
||||
|
||||
for c, i in channels {
|
||||
if raw_channel_can_recv(c) {
|
||||
candidates[count] = i;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
assert(count != 0);
|
||||
}
|
||||
|
||||
t := time.now();
|
||||
r := rand.create(transmute(u64)t);
|
||||
i := rand.uint32(&r);
|
||||
|
||||
index = candidates[i % count];
|
||||
|
||||
if msg != nil {
|
||||
channel_send(channels[index], msg);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
select_send :: proc(channels: ..^Raw_Channel) -> (index: int) {
|
||||
switch len(channels) {
|
||||
case 0:
|
||||
panic("sync: select with no channels");
|
||||
}
|
||||
|
||||
assert(len(channels) <= MAX_SELECT_CHANNELS);
|
||||
candidates: [MAX_SELECT_CHANNELS]int;
|
||||
queues: [MAX_SELECT_CHANNELS]Raw_Channel_Wait_Queue;
|
||||
|
||||
count := u32(0);
|
||||
for c, i in channels {
|
||||
if raw_channel_can_send(c) {
|
||||
candidates[count] = i;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if count == 0 {
|
||||
state: uintptr;
|
||||
for c, i in channels {
|
||||
q := &queues[i];
|
||||
q.state = &state;
|
||||
raw_channel_wait_queue_insert(&c.sendq, q);
|
||||
}
|
||||
raw_channel_wait_queue_wait_on(&state, SELECT_MAX_TIMEOUT);
|
||||
for c, i in channels {
|
||||
q := &queues[i];
|
||||
raw_channel_wait_queue_remove(&c.sendq, q);
|
||||
}
|
||||
|
||||
for c, i in channels {
|
||||
if raw_channel_can_send(c) {
|
||||
candidates[count] = i;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
assert(count != 0);
|
||||
}
|
||||
|
||||
t := time.now();
|
||||
r := rand.create(transmute(u64)t);
|
||||
i := rand.uint32(&r);
|
||||
|
||||
index = candidates[i % count];
|
||||
return;
|
||||
}
|
||||
|
||||
select_try :: proc(channels: ..Select_Channel) -> (index: int) {
|
||||
switch len(channels) {
|
||||
case 0:
|
||||
panic("sync: select with no channels");
|
||||
}
|
||||
|
||||
assert(len(channels) <= MAX_SELECT_CHANNELS);
|
||||
|
||||
backing: [MAX_SELECT_CHANNELS]int;
|
||||
candidates := backing[:];
|
||||
cap := len(channels);
|
||||
candidates = candidates[:cap];
|
||||
|
||||
count := u32(0);
|
||||
for c, i in channels {
|
||||
switch c.command {
|
||||
case .Recv:
|
||||
if raw_channel_can_recv(c.channel) {
|
||||
candidates[count] = i;
|
||||
count += 1;
|
||||
}
|
||||
case .Send:
|
||||
if raw_channel_can_send(c.channel) {
|
||||
candidates[count] = i;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if count == 0 {
|
||||
index = -1;
|
||||
return;
|
||||
}
|
||||
|
||||
t := time.now();
|
||||
r := rand.create(transmute(u64)t);
|
||||
i := rand.uint32(&r);
|
||||
|
||||
index = candidates[i % count];
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
select_try_recv :: proc(channels: ..^Raw_Channel) -> (index: int) {
|
||||
switch len(channels) {
|
||||
case 0:
|
||||
index = -1;
|
||||
return;
|
||||
case 1:
|
||||
index = -1;
|
||||
if raw_channel_can_recv(channels[0]) {
|
||||
index = 0;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
assert(len(channels) <= MAX_SELECT_CHANNELS);
|
||||
candidates: [MAX_SELECT_CHANNELS]int;
|
||||
|
||||
count := u32(0);
|
||||
for c, i in channels {
|
||||
if raw_channel_can_recv(c) {
|
||||
candidates[count] = i;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if count == 0 {
|
||||
index = -1;
|
||||
return;
|
||||
}
|
||||
|
||||
t := time.now();
|
||||
r := rand.create(transmute(u64)t);
|
||||
i := rand.uint32(&r);
|
||||
|
||||
index = candidates[i % count];
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
select_try_send :: proc(channels: ..^Raw_Channel) -> (index: int) #no_bounds_check {
|
||||
switch len(channels) {
|
||||
case 0:
|
||||
return -1;
|
||||
case 1:
|
||||
if raw_channel_can_send(channels[0]) {
|
||||
return 0;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
assert(len(channels) <= MAX_SELECT_CHANNELS);
|
||||
candidates: [MAX_SELECT_CHANNELS]int;
|
||||
|
||||
count := u32(0);
|
||||
for c, i in channels {
|
||||
if raw_channel_can_send(c) {
|
||||
candidates[count] = i;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if count == 0 {
|
||||
index = -1;
|
||||
return;
|
||||
}
|
||||
|
||||
t := time.now();
|
||||
r := rand.create(transmute(u64)t);
|
||||
i := rand.uint32(&r);
|
||||
|
||||
index = candidates[i % count];
|
||||
return;
|
||||
}
|
||||
|
||||
select_try_recv_msg :: proc(channels: ..$C/Channel($T, $D)) -> (msg: T, index: int) {
|
||||
switch len(channels) {
|
||||
case 0:
|
||||
index = -1;
|
||||
return;
|
||||
case 1:
|
||||
ok: bool;
|
||||
if msg, ok = channel_try_recv(channels[0]); ok {
|
||||
index = 0;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
assert(len(channels) <= MAX_SELECT_CHANNELS);
|
||||
candidates: [MAX_SELECT_CHANNELS]int;
|
||||
|
||||
count := u32(0);
|
||||
for c, i in channels {
|
||||
if channel_can_recv(c) {
|
||||
candidates[count] = i;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if count == 0 {
|
||||
index = -1;
|
||||
return;
|
||||
}
|
||||
|
||||
t := time.now();
|
||||
r := rand.create(transmute(u64)t);
|
||||
i := rand.uint32(&r);
|
||||
|
||||
index = candidates[i % count];
|
||||
msg = channel_recv(channels[index]);
|
||||
return;
|
||||
}
|
||||
|
||||
select_try_send_msg :: proc(msg: $T, channels: ..$C/Channel(T, $D)) -> (index: int) {
|
||||
index = -1;
|
||||
switch len(channels) {
|
||||
case 0:
|
||||
return;
|
||||
case 1:
|
||||
if channel_try_send(channels[0], msg) {
|
||||
index = 0;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
assert(len(channels) <= MAX_SELECT_CHANNELS);
|
||||
candidates: [MAX_SELECT_CHANNELS]int;
|
||||
|
||||
count := u32(0);
|
||||
for c, i in channels {
|
||||
if raw_channel_can_send(c) {
|
||||
candidates[count] = i;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if count == 0 {
|
||||
index = -1;
|
||||
return;
|
||||
}
|
||||
|
||||
t := time.now();
|
||||
r := rand.create(transmute(u64)t);
|
||||
i := rand.uint32(&r);
|
||||
|
||||
index = candidates[i % count];
|
||||
channel_send(channels[index], msg);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
//+build linux, darwin, freebsd
|
||||
//+private
|
||||
package sync2
|
||||
|
||||
import "core:time"
|
||||
|
||||
raw_channel_wait_queue_wait_on :: proc(state: ^uintptr, timeout: time.Duration) {
|
||||
// stub
|
||||
}
|
||||
|
||||
raw_channel_wait_queue_signal :: proc(q: ^Raw_Channel_Wait_Queue) {
|
||||
// stub
|
||||
}
|
||||
|
||||
raw_channel_wait_queue_broadcast :: proc(q: ^Raw_Channel_Wait_Queue) {
|
||||
// stub
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
//+build windows
|
||||
//+private
|
||||
package sync2
|
||||
|
||||
import win32 "core:sys/windows"
|
||||
import "core:time"
|
||||
|
||||
raw_channel_wait_queue_wait_on :: proc(state: ^uintptr, timeout: time.Duration) {
|
||||
ms: win32.DWORD = win32.INFINITE;
|
||||
if max(time.Duration) != SELECT_MAX_TIMEOUT {
|
||||
ms = win32.DWORD((max(time.duration_nanoseconds(timeout), 0) + 999999)/1000000);
|
||||
}
|
||||
|
||||
v := atomic_load(state);
|
||||
for v == 0 {
|
||||
win32.WaitOnAddress(state, &v, size_of(state^), ms);
|
||||
v = atomic_load(state);
|
||||
}
|
||||
atomic_store(state, 0);
|
||||
}
|
||||
|
||||
raw_channel_wait_queue_signal :: proc(q: ^Raw_Channel_Wait_Queue) {
|
||||
for x := q; x != nil; x = x.next {
|
||||
atomic_add(x.state, 1);
|
||||
win32.WakeByAddressSingle(x.state);
|
||||
}
|
||||
}
|
||||
|
||||
raw_channel_wait_queue_broadcast :: proc(q: ^Raw_Channel_Wait_Queue) {
|
||||
for x := q; x != nil; x = x.next {
|
||||
atomic_add(x.state, 1);
|
||||
win32.WakeByAddressAll(x.state);
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ mutex_lock :: proc(m: ^Mutex) {
|
||||
_mutex_lock(m);
|
||||
}
|
||||
|
||||
// mutex_lock unlocks m
|
||||
// mutex_unlock unlocks m
|
||||
mutex_unlock :: proc(m: ^Mutex) {
|
||||
_mutex_unlock(m);
|
||||
}
|
||||
@@ -103,7 +103,7 @@ rw_mutex_shared_guard :: proc(m: ^RW_Mutex) -> bool {
|
||||
|
||||
|
||||
|
||||
// A Recusrive_Mutex is a recursive mutual exclusion lock
|
||||
// A Recursive_Mutex is a recursive mutual exclusion lock
|
||||
// The zero value for a Recursive_Mutex is an unlocked mutex
|
||||
//
|
||||
// A Recursive_Mutex must not be copied after first use
|
||||
|
||||
@@ -1,159 +1,193 @@
|
||||
//+build linux, darwin, freebsd
|
||||
//+private
|
||||
package sync2
|
||||
|
||||
when !#config(ODIN_SYNC_USE_PTHREADS, true) {
|
||||
|
||||
import "core:time"
|
||||
import "core:runtime"
|
||||
|
||||
_Mutex_State :: enum i32 {
|
||||
Atomic_Mutex_State :: enum i32 {
|
||||
Unlocked = 0,
|
||||
Locked = 1,
|
||||
Waiting = 2,
|
||||
}
|
||||
_Mutex :: struct {
|
||||
state: _Mutex_State,
|
||||
|
||||
|
||||
// An Atomic_Mutex is a mutual exclusion lock
|
||||
// The zero value for a Atomic_Mutex is an unlocked mutex
|
||||
//
|
||||
// An Atomic_Mutex must not be copied after first use
|
||||
Atomic_Mutex :: struct {
|
||||
state: Atomic_Mutex_State,
|
||||
}
|
||||
|
||||
_mutex_lock :: proc(m: ^Mutex) {
|
||||
if atomic_xchg_rel(&m.impl.state, .Unlocked) != .Unlocked {
|
||||
_mutex_unlock_slow(m);
|
||||
// atomic_mutex_lock locks m
|
||||
atomic_mutex_lock :: proc(m: ^Atomic_Mutex) {
|
||||
@(cold)
|
||||
lock_slow :: proc(m: ^Atomic_Mutex, curr_state: Atomic_Mutex_State) {
|
||||
new_state := curr_state; // Make a copy of it
|
||||
|
||||
spin_lock: for spin in 0..<i32(100) {
|
||||
state, ok := atomic_compare_exchange_weak_acquire(&m.state, .Unlocked, new_state);
|
||||
if ok {
|
||||
return;
|
||||
}
|
||||
|
||||
if state == .Waiting {
|
||||
break spin_lock;
|
||||
}
|
||||
|
||||
for i := min(spin+1, 32); i > 0; i -= 1 {
|
||||
cpu_relax();
|
||||
}
|
||||
}
|
||||
|
||||
for {
|
||||
if atomic_exchange_acquire(&m.state, .Waiting) == .Unlocked {
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO(bill): Use a Futex here for Linux to improve performance and error handling
|
||||
cpu_relax();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
switch v := atomic_exchange_acquire(&m.state, .Locked); v {
|
||||
case .Unlocked:
|
||||
// Okay
|
||||
case: fallthrough;
|
||||
case .Locked, .Waiting:
|
||||
lock_slow(m, v);
|
||||
}
|
||||
}
|
||||
|
||||
_mutex_unlock :: proc(m: ^Mutex) {
|
||||
switch atomic_xchg_rel(&m.impl.state, .Unlocked) {
|
||||
// atomic_mutex_unlock unlocks m
|
||||
atomic_mutex_unlock :: proc(m: ^Atomic_Mutex) {
|
||||
@(cold)
|
||||
unlock_slow :: proc(m: ^Atomic_Mutex) {
|
||||
// TODO(bill): Use a Futex here for Linux to improve performance and error handling
|
||||
}
|
||||
|
||||
|
||||
switch atomic_exchange_release(&m.state, .Unlocked) {
|
||||
case .Unlocked:
|
||||
unreachable();
|
||||
case .Locked:
|
||||
// Okay
|
||||
case .Waiting:
|
||||
_mutex_unlock_slow(m);
|
||||
unlock_slow(m);
|
||||
}
|
||||
}
|
||||
|
||||
_mutex_try_lock :: proc(m: ^Mutex) -> bool {
|
||||
_, ok := atomic_cxchg_acq(&m.impl.state, .Unlocked, .Locked);
|
||||
// atomic_mutex_try_lock tries to lock m, will return true on success, and false on failure
|
||||
atomic_mutex_try_lock :: proc(m: ^Atomic_Mutex) -> bool {
|
||||
_, ok := atomic_compare_exchange_strong_acquire(&m.state, .Unlocked, .Locked);
|
||||
return ok;
|
||||
}
|
||||
|
||||
|
||||
@(cold)
|
||||
_mutex_lock_slow :: proc(m: ^Mutex, curr_state: _Mutex_State) {
|
||||
new_state := curr_state; // Make a copy of it
|
||||
// Example:
|
||||
//
|
||||
// if atomic_mutex_guard(&m) {
|
||||
// ...
|
||||
// }
|
||||
//
|
||||
@(deferred_in=atomic_mutex_unlock)
|
||||
atomic_mutex_guard :: proc(m: ^Atomic_Mutex) -> bool {
|
||||
atomic_mutex_lock(m);
|
||||
return true;
|
||||
}
|
||||
|
||||
spin_lock: for spin in 0..<i32(100) {
|
||||
state, ok := atomic_cxchgweak_acq(&m.impl.state, .Unlocked, new_state);
|
||||
if ok {
|
||||
return;
|
||||
}
|
||||
|
||||
if state == .Waiting {
|
||||
break spin_lock;
|
||||
}
|
||||
Atomic_RW_Mutex_State :: distinct uint;
|
||||
Atomic_RW_Mutex_State_Half_Width :: size_of(Atomic_RW_Mutex_State)*8/2;
|
||||
Atomic_RW_Mutex_State_Is_Writing :: Atomic_RW_Mutex_State(1);
|
||||
Atomic_RW_Mutex_State_Writer :: Atomic_RW_Mutex_State(1)<<1;
|
||||
Atomic_RW_Mutex_State_Reader :: Atomic_RW_Mutex_State(1)<<Atomic_RW_Mutex_State_Half_Width;
|
||||
|
||||
for i := min(spin+1, 32); i > 0; i -= 1 {
|
||||
cpu_relax();
|
||||
}
|
||||
}
|
||||
Atomic_RW_Mutex_State_Writer_Mask :: Atomic_RW_Mutex_State(1<<(Atomic_RW_Mutex_State_Half_Width-1) - 1) << 1;
|
||||
Atomic_RW_Mutex_State_Reader_Mask :: Atomic_RW_Mutex_State(1<<(Atomic_RW_Mutex_State_Half_Width-1) - 1) << Atomic_RW_Mutex_State_Half_Width;
|
||||
|
||||
for {
|
||||
if atomic_xchg_acq(&m.impl.state, .Waiting) == .Unlocked {
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO(bill): Use a Futex here for Linux to improve performance and error handling
|
||||
cpu_relax();
|
||||
// An Atomic_RW_Mutex is a reader/writer mutual exclusion lock
|
||||
// The lock can be held by any arbitrary number of readers or a single writer
|
||||
// The zero value for an Atomic_RW_Mutex is an unlocked mutex
|
||||
//
|
||||
// An Atomic_RW_Mutex must not be copied after first use
|
||||
Atomic_RW_Mutex :: struct {
|
||||
state: Atomic_RW_Mutex_State,
|
||||
mutex: Atomic_Mutex,
|
||||
sema: Atomic_Sema,
|
||||
}
|
||||
|
||||
// atomic_rw_mutex_lock locks rw for writing (with a single writer)
|
||||
// If the mutex is already locked for reading or writing, the mutex blocks until the mutex is available.
|
||||
atomic_rw_mutex_lock :: proc(rw: ^Atomic_RW_Mutex) {
|
||||
_ = atomic_add(&rw.state, Atomic_RW_Mutex_State_Writer);
|
||||
atomic_mutex_lock(&rw.mutex);
|
||||
|
||||
state := atomic_or(&rw.state, Atomic_RW_Mutex_State_Writer);
|
||||
if state & Atomic_RW_Mutex_State_Reader_Mask != 0 {
|
||||
atomic_sema_wait(&rw.sema);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@(cold)
|
||||
_mutex_unlock_slow :: proc(m: ^Mutex) {
|
||||
// TODO(bill): Use a Futex here for Linux to improve performance and error handling
|
||||
// atomic_rw_mutex_unlock unlocks rw for writing (with a single writer)
|
||||
atomic_rw_mutex_unlock :: proc(rw: ^Atomic_RW_Mutex) {
|
||||
_ = atomic_and(&rw.state, ~Atomic_RW_Mutex_State_Is_Writing);
|
||||
atomic_mutex_unlock(&rw.mutex);
|
||||
}
|
||||
|
||||
|
||||
RW_Mutex_State :: distinct uint;
|
||||
RW_Mutex_State_Half_Width :: size_of(RW_Mutex_State)*8/2;
|
||||
RW_Mutex_State_Is_Writing :: RW_Mutex_State(1);
|
||||
RW_Mutex_State_Writer :: RW_Mutex_State(1)<<1;
|
||||
RW_Mutex_State_Reader :: RW_Mutex_State(1)<<RW_Mutex_State_Half_Width;
|
||||
|
||||
RW_Mutex_State_Writer_Mask :: RW_Mutex_State(1<<(RW_Mutex_State_Half_Width-1) - 1) << 1;
|
||||
RW_Mutex_State_Reader_Mask :: RW_Mutex_State(1<<(RW_Mutex_State_Half_Width-1) - 1) << RW_Mutex_State_Half_Width;
|
||||
|
||||
|
||||
_RW_Mutex :: struct {
|
||||
state: RW_Mutex_State,
|
||||
mutex: Mutex,
|
||||
sema: Sema,
|
||||
}
|
||||
|
||||
_rw_mutex_lock :: proc(rw: ^RW_Mutex) {
|
||||
_ = atomic_add(&rw.impl.state, RW_Mutex_State_Writer);
|
||||
mutex_lock(&rw.impl.mutex);
|
||||
|
||||
state := atomic_or(&rw.impl.state, RW_Mutex_State_Writer);
|
||||
if state & RW_Mutex_State_Reader_Mask != 0 {
|
||||
sema_wait(&rw.impl.sema);
|
||||
}
|
||||
}
|
||||
|
||||
_rw_mutex_unlock :: proc(rw: ^RW_Mutex) {
|
||||
_ = atomic_and(&rw.impl.state, ~RW_Mutex_State_Is_Writing);
|
||||
mutex_unlock(&rw.impl.mutex);
|
||||
}
|
||||
|
||||
_rw_mutex_try_lock :: proc(rw: ^RW_Mutex) -> bool {
|
||||
if mutex_try_lock(&rw.impl.mutex) {
|
||||
state := atomic_load(&rw.impl.state);
|
||||
if state & RW_Mutex_State_Reader_Mask == 0 {
|
||||
_ = atomic_or(&rw.impl.state, RW_Mutex_State_Is_Writing);
|
||||
// atomic_rw_mutex_try_lock tries to lock rw for writing (with a single writer)
|
||||
atomic_rw_mutex_try_lock :: proc(rw: ^Atomic_RW_Mutex) -> bool {
|
||||
if atomic_mutex_try_lock(&rw.mutex) {
|
||||
state := atomic_load(&rw.state);
|
||||
if state & Atomic_RW_Mutex_State_Reader_Mask == 0 {
|
||||
_ = atomic_or(&rw.state, Atomic_RW_Mutex_State_Is_Writing);
|
||||
return true;
|
||||
}
|
||||
|
||||
mutex_unlock(&rw.impl.mutex);
|
||||
atomic_mutex_unlock(&rw.mutex);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
_rw_mutex_shared_lock :: proc(rw: ^RW_Mutex) {
|
||||
state := atomic_load(&rw.impl.state);
|
||||
for state & (RW_Mutex_State_Is_Writing|RW_Mutex_State_Writer_Mask) == 0 {
|
||||
// atomic_rw_mutex_shared_lock locks rw for reading (with arbitrary number of readers)
|
||||
atomic_rw_mutex_shared_lock :: proc(rw: ^Atomic_RW_Mutex) {
|
||||
state := atomic_load(&rw.state);
|
||||
for state & (Atomic_RW_Mutex_State_Is_Writing|Atomic_RW_Mutex_State_Writer_Mask) == 0 {
|
||||
ok: bool;
|
||||
state, ok = atomic_cxchgweak(&rw.impl.state, state, state + RW_Mutex_State_Reader);
|
||||
state, ok = atomic_compare_exchange_weak(&rw.state, state, state + Atomic_RW_Mutex_State_Reader);
|
||||
if ok {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
mutex_lock(&rw.impl.mutex);
|
||||
_ = atomic_add(&rw.impl.state, RW_Mutex_State_Reader);
|
||||
mutex_unlock(&rw.impl.mutex);
|
||||
atomic_mutex_lock(&rw.mutex);
|
||||
_ = atomic_add(&rw.state, Atomic_RW_Mutex_State_Reader);
|
||||
atomic_mutex_unlock(&rw.mutex);
|
||||
}
|
||||
|
||||
_rw_mutex_shared_unlock :: proc(rw: ^RW_Mutex) {
|
||||
state := atomic_sub(&rw.impl.state, RW_Mutex_State_Reader);
|
||||
// atomic_rw_mutex_shared_unlock unlocks rw for reading (with arbitrary number of readers)
|
||||
atomic_rw_mutex_shared_unlock :: proc(rw: ^Atomic_RW_Mutex) {
|
||||
state := atomic_sub(&rw.state, Atomic_RW_Mutex_State_Reader);
|
||||
|
||||
if (state & RW_Mutex_State_Reader_Mask == RW_Mutex_State_Reader) &&
|
||||
(state & RW_Mutex_State_Is_Writing != 0) {
|
||||
sema_post(&rw.impl.sema);
|
||||
if (state & Atomic_RW_Mutex_State_Reader_Mask == Atomic_RW_Mutex_State_Reader) &&
|
||||
(state & Atomic_RW_Mutex_State_Is_Writing != 0) {
|
||||
atomic_sema_post(&rw.sema);
|
||||
}
|
||||
}
|
||||
|
||||
_rw_mutex_try_shared_lock :: proc(rw: ^RW_Mutex) -> bool {
|
||||
state := atomic_load(&rw.impl.state);
|
||||
if state & (RW_Mutex_State_Is_Writing|RW_Mutex_State_Writer_Mask) == 0 {
|
||||
_, ok := atomic_cxchg(&rw.impl.state, state, state + RW_Mutex_State_Reader);
|
||||
// atomic_rw_mutex_try_shared_lock tries to lock rw for reading (with arbitrary number of readers)
|
||||
atomic_rw_mutex_try_shared_lock :: proc(rw: ^Atomic_RW_Mutex) -> bool {
|
||||
state := atomic_load(&rw.state);
|
||||
if state & (Atomic_RW_Mutex_State_Is_Writing|Atomic_RW_Mutex_State_Writer_Mask) == 0 {
|
||||
_, ok := atomic_compare_exchange_strong(&rw.state, state, state + Atomic_RW_Mutex_State_Reader);
|
||||
if ok {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if mutex_try_lock(&rw.impl.mutex) {
|
||||
_ = atomic_add(&rw.impl.state, RW_Mutex_State_Reader);
|
||||
mutex_unlock(&rw.impl.mutex);
|
||||
if atomic_mutex_try_lock(&rw.mutex) {
|
||||
_ = atomic_add(&rw.state, Atomic_RW_Mutex_State_Reader);
|
||||
atomic_mutex_unlock(&rw.mutex);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -161,127 +195,177 @@ _rw_mutex_try_shared_lock :: proc(rw: ^RW_Mutex) -> bool {
|
||||
}
|
||||
|
||||
|
||||
_Recursive_Mutex :: struct {
|
||||
owner: int,
|
||||
recursion: int,
|
||||
mutex: Mutex,
|
||||
// Example:
|
||||
//
|
||||
// if atomic_rw_mutex_guard(&m) {
|
||||
// ...
|
||||
// }
|
||||
//
|
||||
@(deferred_in=atomic_rw_mutex_unlock)
|
||||
atomic_rw_mutex_guard :: proc(m: ^Atomic_RW_Mutex) -> bool {
|
||||
atomic_rw_mutex_lock(m);
|
||||
return true;
|
||||
}
|
||||
|
||||
_recursive_mutex_lock :: proc(m: ^Recursive_Mutex) {
|
||||
tid := runtime.current_thread_id();
|
||||
if tid != m.impl.owner {
|
||||
mutex_lock(&m.impl.mutex);
|
||||
}
|
||||
// inside the lock
|
||||
m.impl.owner = tid;
|
||||
m.impl.recursion += 1;
|
||||
}
|
||||
|
||||
_recursive_mutex_unlock :: proc(m: ^Recursive_Mutex) {
|
||||
tid := runtime.current_thread_id();
|
||||
assert(tid == m.impl.owner);
|
||||
m.impl.recursion -= 1;
|
||||
recursion := m.impl.recursion;
|
||||
if recursion == 0 {
|
||||
m.impl.owner = 0;
|
||||
}
|
||||
if recursion == 0 {
|
||||
mutex_unlock(&m.impl.mutex);
|
||||
}
|
||||
// outside the lock
|
||||
|
||||
}
|
||||
|
||||
_recursive_mutex_try_lock :: proc(m: ^Recursive_Mutex) -> bool {
|
||||
tid := runtime.current_thread_id();
|
||||
if m.impl.owner == tid {
|
||||
return mutex_try_lock(&m.impl.mutex);
|
||||
}
|
||||
if !mutex_try_lock(&m.impl.mutex) {
|
||||
return false;
|
||||
}
|
||||
// inside the lock
|
||||
m.impl.owner = tid;
|
||||
m.impl.recursion += 1;
|
||||
// Example:
|
||||
//
|
||||
// if atomic_rw_mutex_shared_guard(&m) {
|
||||
// ...
|
||||
// }
|
||||
//
|
||||
@(deferred_in=atomic_rw_mutex_shared_unlock)
|
||||
atomic_rw_mutex_shared_guard :: proc(m: ^Atomic_RW_Mutex) -> bool {
|
||||
atomic_rw_mutex_shared_lock(m);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
// An Atomic_Recursive_Mutex is a recursive mutual exclusion lock
|
||||
// The zero value for a Recursive_Mutex is an unlocked mutex
|
||||
//
|
||||
// An Atomic_Recursive_Mutex must not be copied after first use
|
||||
Atomic_Recursive_Mutex :: struct {
|
||||
owner: int,
|
||||
recursion: int,
|
||||
mutex: Mutex,
|
||||
}
|
||||
|
||||
atomic_recursive_mutex_lock :: proc(m: ^Atomic_Recursive_Mutex) {
|
||||
tid := runtime.current_thread_id();
|
||||
if tid != m.owner {
|
||||
mutex_lock(&m.mutex);
|
||||
}
|
||||
// inside the lock
|
||||
m.owner = tid;
|
||||
m.recursion += 1;
|
||||
}
|
||||
|
||||
atomic_recursive_mutex_unlock :: proc(m: ^Atomic_Recursive_Mutex) {
|
||||
tid := runtime.current_thread_id();
|
||||
assert(tid == m.owner);
|
||||
m.recursion -= 1;
|
||||
recursion := m.recursion;
|
||||
if recursion == 0 {
|
||||
m.owner = 0;
|
||||
}
|
||||
if recursion == 0 {
|
||||
mutex_unlock(&m.mutex);
|
||||
}
|
||||
// outside the lock
|
||||
|
||||
}
|
||||
|
||||
atomic_recursive_mutex_try_lock :: proc(m: ^Atomic_Recursive_Mutex) -> bool {
|
||||
tid := runtime.current_thread_id();
|
||||
if m.owner == tid {
|
||||
return mutex_try_lock(&m.mutex);
|
||||
}
|
||||
if !mutex_try_lock(&m.mutex) {
|
||||
return false;
|
||||
}
|
||||
// inside the lock
|
||||
m.owner = tid;
|
||||
m.recursion += 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
// Example:
|
||||
//
|
||||
// if atomic_recursive_mutex_guard(&m) {
|
||||
// ...
|
||||
// }
|
||||
//
|
||||
@(deferred_in=atomic_recursive_mutex_unlock)
|
||||
atomic_recursive_mutex_guard :: proc(m: ^Atomic_Recursive_Mutex) -> bool {
|
||||
atomic_recursive_mutex_lock(m);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@(private="file")
|
||||
Queue_Item :: struct {
|
||||
next: ^Queue_Item,
|
||||
futex: i32,
|
||||
}
|
||||
|
||||
@(private="file")
|
||||
queue_item_wait :: proc(item: ^Queue_Item) {
|
||||
for atomic_load_acq(&item.futex) == 0 {
|
||||
for atomic_load_acquire(&item.futex) == 0 {
|
||||
// TODO(bill): Use a Futex here for Linux to improve performance and error handling
|
||||
cpu_relax();
|
||||
}
|
||||
}
|
||||
@(private="file")
|
||||
queue_item_signal :: proc(item: ^Queue_Item) {
|
||||
atomic_store_rel(&item.futex, 1);
|
||||
atomic_store_release(&item.futex, 1);
|
||||
// TODO(bill): Use a Futex here for Linux to improve performance and error handling
|
||||
}
|
||||
|
||||
|
||||
_Cond :: struct {
|
||||
queue_mutex: Mutex,
|
||||
// Atomic_Cond implements a condition variable, a rendezvous point for threads
|
||||
// waiting for signalling the occurence of an event
|
||||
//
|
||||
// An Atomic_Cond must not be copied after first use
|
||||
Atomic_Cond :: struct {
|
||||
queue_mutex: Atomic_Mutex,
|
||||
queue_head: ^Queue_Item,
|
||||
pending: bool,
|
||||
}
|
||||
|
||||
_cond_wait :: proc(c: ^Cond, m: ^Mutex) {
|
||||
atomic_cond_wait :: proc(c: ^Atomic_Cond, m: ^Atomic_Mutex) {
|
||||
waiter := &Queue_Item{};
|
||||
|
||||
mutex_lock(&c.impl.queue_mutex);
|
||||
waiter.next = c.impl.queue_head;
|
||||
c.impl.queue_head = waiter;
|
||||
atomic_mutex_lock(&c.queue_mutex);
|
||||
waiter.next = c.queue_head;
|
||||
c.queue_head = waiter;
|
||||
|
||||
atomic_store(&c.impl.pending, true);
|
||||
mutex_unlock(&c.impl.queue_mutex);
|
||||
atomic_store(&c.pending, true);
|
||||
atomic_mutex_unlock(&c.queue_mutex);
|
||||
|
||||
mutex_unlock(m);
|
||||
atomic_mutex_unlock(m);
|
||||
queue_item_wait(waiter);
|
||||
mutex_lock(m);
|
||||
atomic_mutex_lock(m);
|
||||
}
|
||||
|
||||
_cond_wait_with_timeout :: proc(c: ^Cond, m: ^Mutex, timeout: time.Duration) -> bool {
|
||||
atomic_cond_wait_with_timeout :: proc(c: ^Atomic_Cond, m: ^Atomic_Mutex, timeout: time.Duration) -> bool {
|
||||
// TODO(bill): _cond_wait_with_timeout for unix
|
||||
return false;
|
||||
}
|
||||
|
||||
_cond_signal :: proc(c: ^Cond) {
|
||||
if !atomic_load(&c.impl.pending) {
|
||||
atomic_cond_signal :: proc(c: ^Atomic_Cond) {
|
||||
if !atomic_load(&c.pending) {
|
||||
return;
|
||||
}
|
||||
|
||||
mutex_lock(&c.impl.queue_mutex);
|
||||
waiter := c.impl.queue_head;
|
||||
if c.impl.queue_head != nil {
|
||||
c.impl.queue_head = c.impl.queue_head.next;
|
||||
atomic_mutex_lock(&c.queue_mutex);
|
||||
waiter := c.queue_head;
|
||||
if c.queue_head != nil {
|
||||
c.queue_head = c.queue_head.next;
|
||||
}
|
||||
atomic_store(&c.impl.pending, c.impl.queue_head != nil);
|
||||
mutex_unlock(&c.impl.queue_mutex);
|
||||
atomic_store(&c.pending, c.queue_head != nil);
|
||||
atomic_mutex_unlock(&c.queue_mutex);
|
||||
|
||||
if waiter != nil {
|
||||
queue_item_signal(waiter);
|
||||
}
|
||||
}
|
||||
|
||||
_cond_broadcast :: proc(c: ^Cond) {
|
||||
if !atomic_load(&c.impl.pending) {
|
||||
atomic_cond_broadcast :: proc(c: ^Atomic_Cond) {
|
||||
if !atomic_load(&c.pending) {
|
||||
return;
|
||||
}
|
||||
|
||||
atomic_store(&c.impl.pending, false);
|
||||
atomic_store(&c.pending, false);
|
||||
|
||||
mutex_lock(&c.impl.queue_mutex);
|
||||
waiters := c.impl.queue_head;
|
||||
c.impl.queue_head = nil;
|
||||
mutex_unlock(&c.impl.queue_mutex);
|
||||
atomic_mutex_lock(&c.queue_mutex);
|
||||
waiters := c.queue_head;
|
||||
c.queue_head = nil;
|
||||
atomic_mutex_unlock(&c.queue_mutex);
|
||||
|
||||
for waiters != nil {
|
||||
queue_item_signal(waiters);
|
||||
@@ -289,35 +373,35 @@ _cond_broadcast :: proc(c: ^Cond) {
|
||||
}
|
||||
}
|
||||
|
||||
_Sema :: struct {
|
||||
mutex: Mutex,
|
||||
cond: Cond,
|
||||
// When waited upon, blocks until the internal count is greater than zero, then subtracts one.
|
||||
// Posting to the semaphore increases the count by one, or the provided amount.
|
||||
//
|
||||
// An Atomic_Sema must not be copied after first use
|
||||
Atomic_Sema :: struct {
|
||||
mutex: Atomic_Mutex,
|
||||
cond: Atomic_Cond,
|
||||
count: int,
|
||||
}
|
||||
|
||||
_sema_wait :: proc(s: ^Sema) {
|
||||
mutex_lock(&s.impl.mutex);
|
||||
defer mutex_unlock(&s.impl.mutex);
|
||||
atomic_sema_wait :: proc(s: ^Atomic_Sema) {
|
||||
atomic_mutex_lock(&s.mutex);
|
||||
defer atomic_mutex_unlock(&s.mutex);
|
||||
|
||||
for s.impl.count == 0 {
|
||||
cond_wait(&s.impl.cond, &s.impl.mutex);
|
||||
for s.count == 0 {
|
||||
atomic_cond_wait(&s.cond, &s.mutex);
|
||||
}
|
||||
|
||||
s.impl.count -= 1;
|
||||
if s.impl.count > 0 {
|
||||
cond_signal(&s.impl.cond);
|
||||
s.count -= 1;
|
||||
if s.count > 0 {
|
||||
atomic_cond_signal(&s.cond);
|
||||
}
|
||||
}
|
||||
|
||||
_sema_post :: proc(s: ^Sema, count := 1) {
|
||||
mutex_lock(&s.impl.mutex);
|
||||
defer mutex_unlock(&s.impl.mutex);
|
||||
atomic_sema_post :: proc(s: ^Atomic_Sema, count := 1) {
|
||||
atomic_mutex_lock(&s.mutex);
|
||||
defer atomic_mutex_unlock(&s.mutex);
|
||||
|
||||
s.impl.count += count;
|
||||
cond_signal(&s.impl.cond);
|
||||
s.count += count;
|
||||
atomic_cond_signal(&s.cond);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
} // !ODIN_SYNC_USE_PTHREADS
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//+build linux, darwin, freebsd
|
||||
//+build linux, freebsd
|
||||
//+private
|
||||
package sync2
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ package unicode
|
||||
@(private) pLo :: pLl | pLu; // a letter that is neither upper nor lower case.
|
||||
@(private) pLmask :: pLo;
|
||||
|
||||
@(static)
|
||||
char_properties := [MAX_LATIN1+1]u8{
|
||||
0x00 = pC, // '\x00'
|
||||
0x01 = pC, // '\x01'
|
||||
@@ -273,7 +272,6 @@ char_properties := [MAX_LATIN1+1]u8{
|
||||
};
|
||||
|
||||
|
||||
@(static)
|
||||
alpha_ranges := [?]i32{
|
||||
0x00d8, 0x00f6,
|
||||
0x00f8, 0x01f5,
|
||||
@@ -429,7 +427,6 @@ alpha_ranges := [?]i32{
|
||||
0xffda, 0xffdc,
|
||||
};
|
||||
|
||||
@(static)
|
||||
alpha_singlets := [?]i32{
|
||||
0x00aa,
|
||||
0x00b5,
|
||||
@@ -465,7 +462,6 @@ alpha_singlets := [?]i32{
|
||||
0xfe74,
|
||||
};
|
||||
|
||||
@(static)
|
||||
space_ranges := [?]i32{
|
||||
0x0009, 0x000d, // tab and newline
|
||||
0x0020, 0x0020, // space
|
||||
@@ -481,7 +477,6 @@ space_ranges := [?]i32{
|
||||
0xfeff, 0xfeff,
|
||||
};
|
||||
|
||||
@(static)
|
||||
unicode_spaces := [?]i32{
|
||||
0x0009, // tab
|
||||
0x000a, // LF
|
||||
@@ -499,7 +494,6 @@ unicode_spaces := [?]i32{
|
||||
0xfeff, // unknown
|
||||
};
|
||||
|
||||
@(static)
|
||||
to_upper_ranges := [?]i32{
|
||||
0x0061, 0x007a, 468, // a-z A-Z
|
||||
0x00e0, 0x00f6, 468,
|
||||
@@ -538,7 +532,6 @@ to_upper_ranges := [?]i32{
|
||||
0xff41, 0xff5a, 468,
|
||||
};
|
||||
|
||||
@(static)
|
||||
to_upper_singlets := [?]i32{
|
||||
0x00ff, 621,
|
||||
0x0101, 499,
|
||||
@@ -882,7 +875,6 @@ to_upper_singlets := [?]i32{
|
||||
0x1ff3, 509,
|
||||
};
|
||||
|
||||
@(static)
|
||||
to_lower_ranges := [?]i32{
|
||||
0x0041, 0x005a, 532, // A-Z a-z
|
||||
0x00c0, 0x00d6, 532, // - -
|
||||
@@ -922,7 +914,6 @@ to_lower_ranges := [?]i32{
|
||||
0xff21, 0xff3a, 532, // - -
|
||||
};
|
||||
|
||||
@(static)
|
||||
to_lower_singlets := [?]i32{
|
||||
0x0100, 501,
|
||||
0x0102, 501,
|
||||
@@ -1259,7 +1250,6 @@ to_lower_singlets := [?]i32{
|
||||
0x1ffc, 491,
|
||||
};
|
||||
|
||||
@(static)
|
||||
to_title_singlets := [?]i32{
|
||||
0x01c4, 501,
|
||||
0x01c6, 499,
|
||||
|
||||
Reference in New Issue
Block a user