diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 38ac85392..89ecff732 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -71,7 +71,7 @@ The compiler comes with a number of libraries that are located in `lib/`: * `c/`: Contains wrappers to the standard C library for both Linux and Windows. * `core/`: This is the heart of Rivet, it contains the code that gives life to - the strings, vectors, the backtrace, etc. + the strings, dynamic arrays, the backtrace, etc. * `std/`: The standard Rivet library, this module contains several submodules with functions and types useful for development. * `rivet/`: The self-hosted compiler code. diff --git a/ROADMAP.md b/ROADMAP.md index b21ee54e8..41024db0f 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -20,7 +20,7 @@ - [ ] Constant-folding: `x := 2 * 2;` => `x := 4;`. - [ ] Optimize code, inline functions/methods annotated with `inline`, delete unused code, etc. -- [ ] (Atomic) Reference-Counting for traits, boxed enums, strings, vectors and structs. +- [ ] (Atomic) Reference-Counting for traits, boxed enums, strings, dynamic arrays and structs. - [ ] Better support for embedded structs. - [ ] `undefined` for uninitialized variables: `x: [5]uint8 := undefined;`. - [ ] Disallow empty array literal (`x := []!; -> ERROR`). diff --git a/lib/core/src/Vector.ri b/lib/core/src/DynArray.ri similarity index 91% rename from lib/core/src/Vector.ri rename to lib/core/src/DynArray.ri index 7526fc05d..aadd65749 100644 --- a/lib/core/src/Vector.ri +++ b/lib/core/src/DynArray.ri @@ -39,14 +39,14 @@ struct DynArray { func get(self, idx: uint) -> rawptr { if idx >= self.len { - runtime_error("vector index out of range (index: {}, len: {})", idx, self.len); + runtime_error("dynamic array index out of range (index: {}, len: {})", idx, self.len); } return unsafe { @ptr_add(@as([&]mut uint8, self.ptr), idx * self.elem_size) }; } func set(self, idx: uint, val: rawptr) { if idx >= self.len { - runtime_error("vector index out of range (index: {}, len: {})", idx, self.len); + runtime_error("dynamic array index out of range (index: {}, len: {})", idx, self.len); } unsafe { mem_copy( @@ -66,11 +66,11 @@ struct DynArray { self.len += 1; } - /// Returns the last element of the vector, and removes it. If the - /// vector is empty, this will panic. + /// Returns the last element of the dynamic array, and removes it. If the + /// dynamic array is empty, this will panic. func pop(mut self) -> rawptr { if self.len == 0 { - runtime_error("Vec.pop: vector is empty"); + runtime_error("DynArray.pop: dynamic array is empty"); } new_len := self.len - 1; self.len = new_len; @@ -79,8 +79,8 @@ struct DynArray { /// Deletes `size` elements beginning with index `i`. /// NOTE: This function does NOT operate in-place. Internally, it creates a copy - /// of the vector, skipping over `size` elements starting at `i`, and then points - /// the original variable to the new memory location. + /// of the dynamic array, skipping over `size` elements starting at `i`, and then + /// points the original variable to the new memory location. pub func delete(mut self, i: uint, size: uint := 1, no_slices: bool := false) { if i + size > self.len { end_idx := if size == 1 { "..{}".fmt(i + size) } else { "" }; diff --git a/lib/core/src/StringFormatter.ri b/lib/core/src/StringFormatter.ri index fe77b684c..52704f135 100644 --- a/lib/core/src/StringFormatter.ri +++ b/lib/core/src/StringFormatter.ri @@ -27,7 +27,7 @@ pub struct StringFormatter { args_idx += 1; if arg_idx >= args.len { runtime_error( - "string.fmt(): argument index out of range (argument index: {}, len: {}) at index {}", + "string.fmt: argument index out of range (argument index: {}, len: {}) at index {}", arg_idx, args.len, self.i ); } @@ -60,7 +60,7 @@ pub struct StringFormatter { self.i += 1; if self.i >= self.buf.len { runtime_error( - "string.fmt(): incomplete format string at index {}", + "string.fmt: incomplete format string at index {}", start ); } @@ -68,7 +68,7 @@ pub struct StringFormatter { index := buf.as_uint64(); if index >= args.len { runtime_error( - "string.fmt(): argument index out of range (index: {}, len: {})", + "string.fmt: argument index out of range (index: {}, len: {})", index, args.len ); } @@ -90,7 +90,7 @@ pub struct StringFormatter { } } else { runtime_error( - "string.fmt(): expecting closing `}}` in format string at index {}", + "string.fmt: expecting closing `}}` in format string at index {}", self.i ); } @@ -101,7 +101,7 @@ pub struct StringFormatter { self.i += 1; } else { runtime_error( - "string.fmt(): single `}}` encountered in format string at index {}", + "string.fmt: single `}}` encountered in format string at index {}", self.i ); } @@ -123,13 +123,13 @@ pub struct StringFormatter { buf.push(unsafe { self.buf.ptr[self.i] }); self.i += 1; if self.i >= self.buf.len { - runtime_error("string.fmt(): incomplete format string (index: {})", start); + runtime_error("string.fmt: incomplete format string (index: {})", start); } } fwidth := buf.as_int(); if fwidth == 0 { runtime_error( - "string.fmt(): invalid width value (cannot be 0 and cannot be omitted) -> (index: {})", + "string.fmt: invalid width value (cannot be 0 and cannot be omitted) -> (index: {})", start ); } diff --git a/lib/core/src/entry_point.ri b/lib/core/src/entry_point.ri index cafcd86bd..236bf2ff7 100644 --- a/lib/core/src/entry_point.ri +++ b/lib/core/src/entry_point.ri @@ -12,7 +12,7 @@ extern (Rivet) { func init_args(_argc: uint, _argv: [&][&]uint8) { unsafe { - ARGS = @vec(string, _argc); + ARGS = @dyn_array(string, _argc); mut i: uint := 0; while i < _argc : i += 1 { ARGS.push(string.from_raw(_argv[i])); diff --git a/lib/core/src/rune.ri b/lib/core/src/rune.ri index d44c874d0..1973e1e97 100644 --- a/lib/core/src/rune.ri +++ b/lib/core/src/rune.ri @@ -49,7 +49,7 @@ extend rune < Stringable { } pub func as_bytes(self) -> []uint8 { - res := @vec(uint8, 5); + res := @dyn_array(uint8, 5); res_v := @as(DynArray, res); res_v.len = utf32_decode_to_buffer(self, unsafe { @as([&]mut uint8, res_v.ptr) }); return res; @@ -148,4 +148,4 @@ func utf8_to_utf32(bytes: []uint8) -> !rune { shift = 6; } return res; -} +} \ No newline at end of file diff --git a/lib/core/src/string.c.ri b/lib/core/src/string.c.ri index e80d8d017..9dae11b62 100644 --- a/lib/core/src/string.c.ri +++ b/lib/core/src/string.c.ri @@ -100,7 +100,7 @@ pub struct string < Stringable, Hashable, Throwable { /// Returns a string array of the string split by '\t' and ' '. pub func fields(self) -> []Self { - mut res := @vec(Self); + mut res := @dyn_array(Self); mut word_start: uint := 0; mut word_len: uint := 0; mut is_in_word := false; @@ -458,7 +458,7 @@ pub struct string < Stringable, Hashable, Throwable { return self; } mut idx: uint := 0; - mut idxs := @vec(uint); + mut idxs := @dyn_array(uint); while { idx = self.index_after_of(rep, idx) ?? break; idxs.push(idx); @@ -508,7 +508,7 @@ pub struct string < Stringable, Hashable, Throwable { /// Returns an array of all the UTF8 runes in the string `self` which is useful /// if you want random access to them. pub func as_runes(self) -> []rune { - mut runes := @vec(rune, self.runes_count()); + mut runes := @dyn_array(rune, self.runes_count()); mut i: uint := 0; while i < self.len : i += 1 { char_len := unsafe { self.ptr[i] }.len_utf8(); @@ -541,7 +541,7 @@ pub struct string < Stringable, Hashable, Throwable { /// remainder contains more `delim` substrings. pub func split(self, delim: Self, nth: uint := 0) -> []Self { mut i: uint := 0; - mut res := @vec(Self); + mut res := @dyn_array(Self); match delim.len { 0 -> { i = 1; @@ -602,7 +602,7 @@ pub struct string < Stringable, Hashable, Throwable { /// If the delimiter string is empty then `.split()` is used. pub func split_any(self, delim: Self) -> []Self { mut i: uint := 0; - mut res := @vec(Self); + mut res := @dyn_array(Self); // check empty source string if self.len > 0 { // if empty delimiter string using default split @@ -630,7 +630,7 @@ pub struct string < Stringable, Hashable, Throwable { /// NOTE: algorithm is "greedy", consuming '\r\n' as a single line ending with higher /// priority than '\r' and '\n' as multiple endings pub func split_into_lines(self) -> []Self { - mut res := @vec(Self); + mut res := @dyn_array(Self); if self.len == 0 { return res; } diff --git a/lib/core/tests/string_test.ri b/lib/core/tests/string_test.ri index d94d3906b..62bbc72b5 100644 --- a/lib/core/tests/string_test.ri +++ b/lib/core/tests/string_test.ri @@ -56,7 +56,7 @@ test "string.runes_count()" { test "string.tokenize()" { mut iterator := " abc def ghi ".tokenize(b' '); - mut res := @vec(string, 3); + mut res := @dyn_array(string, 3); while w := iterator.next() { res.push(w); } diff --git a/lib/core/tests/vector_test.ri b/lib/core/tests/vector_test.ri index b7d7d2340..54c3df57c 100644 --- a/lib/core/tests/vector_test.ri +++ b/lib/core/tests/vector_test.ri @@ -1,4 +1,4 @@ -test "vectors: push and pop" { +test "dynamic arrays: push and pop" { mut vec := ["A", "B"]; @assert(vec.len == 2); @@ -11,7 +11,7 @@ test "vectors: push and pop" { @assert(vec.len == 2); } -test "vectors: clear" { +test "dynamic arrays: clear" { mut vec := ["A", "B"]; @assert(vec.len == 2); @assert(vec[0] == "A"); diff --git a/lib/rivet/src/ast/CHeader.ri b/lib/rivet/src/ast/CHeader.ri index a7355a570..a03bc93fa 100644 --- a/lib/rivet/src/ast/CHeader.ri +++ b/lib/rivet/src/ast/CHeader.ri @@ -126,7 +126,7 @@ extend Table { mut name := tokens.next()?; define_value := tokens.rest(); has_value := define_value.len > 0; - mut args := @vec(string); + mut args := @dyn_array(string); mut is_macro := true; if has_value { if paren_idx := name.index_of_byte(b'(') { @@ -157,7 +157,7 @@ extend Table { lines := result.output.find_between( "#include <...> search starts here:", "End of search list." ).split_into_lines(); - mut paths := @vec(string); + mut paths := @dyn_array(string); for line in lines { if line.is_empty() { continue; diff --git a/lib/rivet/src/ast/Decl.ri b/lib/rivet/src/ast/Decl.ri index 6f41d7ae0..7ffd8a6c6 100644 --- a/lib/rivet/src/ast/Decl.ri +++ b/lib/rivet/src/ast/Decl.ri @@ -210,7 +210,7 @@ pub struct ImportedMod { } pub func filter_field_decl(decls: []Decl) -> []Decl { - mut fields := @vec(Decl); + mut fields := @dyn_array(Decl); for decl in decls { if decl is .Field { fields.push(decl); diff --git a/lib/rivet/src/ast/Expr.ri b/lib/rivet/src/ast/Expr.ri index 969d2d882..857862a24 100644 --- a/lib/rivet/src/ast/Expr.ri +++ b/lib/rivet/src/ast/Expr.ri @@ -214,7 +214,7 @@ pub enum Expr < traits.Stringable { BuiltinCall { name: string; args: []CallArg; - vec_is_mut: bool; + dyn_array_is_mut: bool; pos: token.Pos; mut builtin: Builtin := .Invalid(); mut type: Type; @@ -377,16 +377,16 @@ pub enum Expr < traits.Stringable { sb.write_byte(b')'); sb.to_string() }, - .DynArrayLiteral as vector_lit -> { + .DynArrayLiteral as dyn_array_lit -> { mut sb := strings.Builder.from_string("["); - for i, value in vector_lit.values { + for i, value in dyn_array_lit.values { sb.write_string(value.to_string()); - if i < vector_lit.values.len - 1 { + if i < dyn_array_lit.values.len - 1 { sb.write_string(", "); } } sb.write_byte(b']'); - if vector_lit.is_arr { + if dyn_array_lit.is_arr { sb.write_byte(b'!'); } sb.to_string() @@ -602,4 +602,4 @@ pub struct MatchBranch { pub is_else: bool; pub pos: token.Pos; pub mut type: Type; -} +} \ No newline at end of file diff --git a/lib/rivet/src/ast/Sym.ri b/lib/rivet/src/ast/Sym.ri index 5f5a4231c..1c0c506c4 100644 --- a/lib/rivet/src/ast/Sym.ri +++ b/lib/rivet/src/ast/Sym.ri @@ -174,7 +174,7 @@ pub struct Module < Sym { return type_sym; } - pub func add_or_get_vec(mut self, elem_type: Type, is_mut: bool) -> TypeSym { + pub func add_or_get_dyn_array(mut self, elem_type: Type, is_mut: bool) -> TypeSym { unique_name := if is_mut { "[]mut " } else { "[]" }.concat(elem_type.to_qualstring()); if type_sym := self.scope.find(unique_name) { return @as(TypeSym, type_sym); @@ -221,11 +221,11 @@ pub struct Module < Sym { ret_type: .Basic(type_sym), has_body: true )) catch {}; - if vector_sym := self.scope.find("core")?.scope.find("DynArray") { - type_sym.scope.add(vector_sym.scope.find("is_empty")?) catch {}; - type_sym.scope.add(vector_sym.scope.find("delete")?) catch {}; - type_sym.scope.add(vector_sym.scope.find("trim")?) catch {}; - type_sym.scope.add(vector_sym.scope.find("clear")?) catch {}; + if dyn_array_sym := self.scope.find("core")?.scope.find("DynArray") { + type_sym.scope.add(dyn_array_sym.scope.find("is_empty")?) catch {}; + type_sym.scope.add(dyn_array_sym.scope.find("delete")?) catch {}; + type_sym.scope.add(dyn_array_sym.scope.find("trim")?) catch {}; + type_sym.scope.add(dyn_array_sym.scope.find("clear")?) catch {}; } self.scope.add(type_sym) catch {}; return type_sym; @@ -246,7 +246,7 @@ pub struct Module < Sym { if type_sym := self.scope.find(unique_name) { return @as(TypeSym, type_sym); } - mut fields := @vec(Field); + mut fields := @dyn_array(Field); for i, type in types { fields.push(Field(name: i.to_string(), is_public: true, type: type)); } @@ -398,4 +398,4 @@ pub struct Func < Sym { pos: token.noPos ); } -} +} \ No newline at end of file diff --git a/lib/rivet/src/ast/Table.ri b/lib/rivet/src/ast/Table.ri index 8797a119d..8794cc6c4 100644 --- a/lib/rivet/src/ast/Table.ri +++ b/lib/rivet/src/ast/Table.ri @@ -48,7 +48,7 @@ pub struct Table { pub mut float64_sym: TypeSym; pub mut string_sym: TypeSym; pub mut throwable_sym: TypeSym; - pub mut vector_sym: TypeSym; // from `core` module + pub mut dyn_array_sym: TypeSym; // from `core` module /// Primitive types. pub mut bool_t: Type; @@ -171,7 +171,7 @@ pub struct Table { BuiltinArg("msg", type: self.string_t, is_optional: true) ]), - .Func("vec", [ + .Func("dyn_array", [ BuiltinArg("type", is_any: true), BuiltinArg("cap", type: self.uint_t, is_optional: true) ], checks: [ @@ -342,7 +342,7 @@ pub struct Table { } else { self.type_size(enum_info.underlying_type) }, - .DynArray -> self.type_symbol_size(self.vector_sym, is_raw), + .DynArray -> self.type_symbol_size(self.dyn_array_sym, is_raw), .Array as array_info -> { (elem_size, elem_align) := self.type_size(array_info.elem_type); (array_info.size * elem_size, elem_align) @@ -353,7 +353,7 @@ pub struct Table { types := if type_sym.info is .Tuple as tuple_lit { tuple_lit.types } else { - mut tmp := @vec(Type); + mut tmp := @dyn_array(Type); for field in type_sym.full_fields() { tmp.push(field.type); } @@ -388,7 +388,7 @@ pub struct Table { } pub func filter_files(self, inputs: []string) -> []string { - mut new_inputs := @vec(string, inputs.len); + mut new_inputs := @dyn_array(string, inputs.len); for input in inputs { base_name_input := Path.base_name(input); if base_name_input.count(".") == 1 { @@ -396,7 +396,7 @@ pub struct Table { continue; } exts := base_name_input[..base_name_input.len - 3].split(".")[1..]; - mut already_exts := @vec(string, exts.len); + mut already_exts := @dyn_array(string, exts.len); mut should_compile := false; for ext in exts { if ext in already_exts { @@ -577,4 +577,4 @@ enum BuiltinFuncCheck { arg_idx: uint; type: BuiltinFuncType; } -} +} \ No newline at end of file diff --git a/lib/rivet/src/ast/Type.ri b/lib/rivet/src/ast/Type.ri index 908e5e4d4..be1f5ec4a 100644 --- a/lib/rivet/src/ast/Type.ri +++ b/lib/rivet/src/ast/Type.ri @@ -116,14 +116,14 @@ pub enum Type < traits.Stringable { .Result as result -> .Result(result.inner.unalias() ?? result.inner), .Option as option -> .Option(option.inner.unalias() ?? option.inner), .Tuple as tuple_data -> { - unaliased_types := @vec(mut Type, tuple_data.inners.len); + unaliased_types := @dyn_array(mut Type, tuple_data.inners.len); for i, tuple_type in tuple_data.inners { unaliased_types[i] = tuple_type.unalias() ?? tuple_type; } .Tuple(unaliased_types, tuple_data.sym) }, - .DynArray as vector_data -> .DynArray( - vector_data.inner.unalias() ?? vector_data.inner, vector_data.is_mut + .DynArray as dyn_array_data -> .DynArray( + dyn_array_data.inner.unalias() ?? dyn_array_data.inner, dyn_array_data.is_mut ), .Array as array_data -> .Array( array_data.inner.unalias() ?? array_data.inner, ...self @@ -165,7 +165,7 @@ pub enum Type < traits.Stringable { .Option as option -> option.inner.symbol(), .Tuple as tuple_data -> tuple_data.sym, .Variadic as variadic_data -> variadic_data.sym, - .DynArray as vector_data -> vector_data.sym, + .DynArray as dyn_array_data -> dyn_array_data.sym, .Array as array_data -> array_data.sym, .Pointer as pointer_data -> pointer_data.inner.symbol(), .Func as func_data -> func_data.sym, @@ -236,7 +236,7 @@ pub enum Type < traits.Stringable { .Result as res_t -> res_t.pos, .Tuple as tuple_t -> tuple_t.pos, .Variadic as variadic_t -> variadic_t.pos, - .DynArray as vec_t -> vec_t.pos, + .DynArray as dyn_array_t -> dyn_array_t.pos, .Array as arr_t -> arr_t.pos, .Pointer as ptr_t -> ptr_t.pos, .Rawptr as rawptr_t -> rawptr_t.pos, @@ -262,8 +262,8 @@ pub enum Type < traits.Stringable { .Tuple as tuple_lhs if rhs is .Tuple as tuple_rhs -> tuple_lhs == tuple_rhs, .Variadic as variadic_lhs if rhs is .Variadic as variadic_rhs -> variadic_lhs.inner == variadic_rhs.inner, - .DynArray as vector_lhs if rhs is .DynArray as vector_rhs -> - vector_lhs.inner == vector_rhs.inner and vector_lhs.is_mut == vector_rhs.is_mut, + .DynArray as dyn_array_lhs if rhs is .DynArray as dyn_array_rhs -> + dyn_array_lhs.inner == dyn_array_rhs.inner and dyn_array_lhs.is_mut == dyn_array_rhs.is_mut, .Array as array_lhs if rhs is .Array as array_rhs -> array_lhs.inner == array_rhs.inner and array_lhs.size_value == array_rhs.size_value and array_lhs.is_mut == array_rhs.is_mut, @@ -336,11 +336,11 @@ pub enum Type < traits.Stringable { sb.to_string() }, .Variadic as variadic_data -> "...".concat(variadic_data.inner.to_string_(qualstr)), - .DynArray as vector_data -> if vector_data.is_mut { + .DynArray as dyn_array_data -> if dyn_array_data.is_mut { "[]mut" } else { "[]" - }.concat(vector_data.inner.to_string_(qualstr)), + }.concat(dyn_array_data.inner.to_string_(qualstr)), .Array as array_data -> "[".concat( array_data.size.to_string(), "]", if array_data.is_mut { "mut " @@ -400,4 +400,4 @@ pub enum Type < traits.Stringable { } }; } -} +} \ No newline at end of file diff --git a/lib/rivet/src/ast/TypeInfo.ri b/lib/rivet/src/ast/TypeInfo.ri index 92c5a947b..1a973b39f 100644 --- a/lib/rivet/src/ast/TypeInfo.ri +++ b/lib/rivet/src/ast/TypeInfo.ri @@ -10,16 +10,16 @@ pub enum TypeInfo < traits.Stringable { None, Bool, Rune, + ComptimeInt, + ComptimeFloat, + Int, SizedInt { size: uint; }, + Uint, SizedUint { size: uint; }, - Int, - Uint, - ComptimeInt, - ComptimeFloat, Float { size: uint; }, @@ -168,10 +168,10 @@ pub enum TypeInfo < traits.Stringable { .None -> "none", .Bool -> "bool", .Rune -> "rune", - .SizedInt as int_info -> "int{}".fmt(int_info.size), .Int -> "int", - .SizedUint as uint_info -> "uint{}".fmt(uint_info.size), + .SizedInt as int_info -> "int{}".fmt(int_info.size), .Uint -> "uint", + .SizedUint as uint_info -> "uint{}".fmt(uint_info.size), .ComptimeInt -> "comptime_int", .ComptimeFloat -> "comptime_float", .Float as float_info -> "float{}".fmt(float_info.size), @@ -179,7 +179,7 @@ pub enum TypeInfo < traits.Stringable { .Func -> "func", .Alias -> "alias", .Array -> "array", - .DynArray -> "vector", + .DynArray -> "dynamic array", .Tuple -> "tuple", .Trait -> "trait", .Struct as struct_info -> if struct_info.is_enum_variant { @@ -199,4 +199,4 @@ pub struct EnumVariant { pub has_type: bool; pub mut type: Type; pub has_fields: bool; -} +} \ No newline at end of file diff --git a/lib/rivet/src/ast/TypeSym.ri b/lib/rivet/src/ast/TypeSym.ri index 8eef9c4ed..46b96fd90 100644 --- a/lib/rivet/src/ast/TypeSym.ri +++ b/lib/rivet/src/ast/TypeSym.ri @@ -131,7 +131,7 @@ pub struct TypeSym < Sym { if !self.full_fields_.is_empty() { return self.full_fields_; } - mut fields := @vec(Field); + mut fields := @dyn_array(Field); if self.info is .Trait as trait_info { for mut b in trait_info.bases { for bf in b.full_fields() { diff --git a/lib/rivet/src/checker/builtin_call.ri b/lib/rivet/src/checker/builtin_call.ri index 1c14b33c7..7bc4fcdf9 100644 --- a/lib/rivet/src/checker/builtin_call.ri +++ b/lib/rivet/src/checker/builtin_call.ri @@ -96,9 +96,9 @@ extend Checker { } match b_func.name { "as" -> self.check_builtin_as(builtin_call), - "vec" if builtin_call.args[0].expr is .Type as vec_t -> - return_type = .Basic(self.table.universe.add_or_get_vec( - vec_t, builtin_call.vec_is_mut + "dyn_array" if builtin_call.args[0].expr is .Type as dyn_array_t -> + return_type = .Basic(self.table.universe.add_or_get_dyn_array( + dyn_array_t, builtin_call.dyn_array_is_mut )), else -> {} } @@ -158,8 +158,8 @@ extend Checker { } else if to_ts := to_type.symbol() { mod_sym := self.sym.module()?; if mod_sym.is_core() { - if (from_ts == self.table.vector_sym and to_ts.info is .DynArray) - or (to_ts == self.table.vector_sym and from_ts.info is .DynArray) { + if (from_ts == self.table.dyn_array_sym and to_ts.info is .DynArray) + or (to_ts == self.table.dyn_array_sym and from_ts.info is .DynArray) { return; // Valid inside `core` module } } @@ -190,4 +190,4 @@ extend Checker { ); } } -} +} \ No newline at end of file diff --git a/lib/rivet/src/checker/call_expr.ri b/lib/rivet/src/checker/call_expr.ri index 9797f36fd..98e96547d 100644 --- a/lib/rivet/src/checker/call_expr.ri +++ b/lib/rivet/src/checker/call_expr.ri @@ -492,13 +492,13 @@ extend Checker { spread_expr_sym := spread_expr_t.symbol()?; if spread_expr_sym.info is .DynArray { last_arg_type := func_.args[func_.args.len - 1].type; - vec_t := ast.Type.Basic(last_arg_type.symbol()?); - self.check_types(spread_expr_t, vec_t) catch |err| { + dyn_array_t := ast.Type.Basic(last_arg_type.symbol()?); + self.check_types(spread_expr_t, dyn_array_t) catch |err| { report.error(err.to_string(), call_expr.spread_expr.position()); }; } else { report.error( - "spread operator can only be used with vectors", + "spread operator can only be used with dynamic arrays", call_expr.spread_expr.position() ); } diff --git a/lib/rivet/src/checker/check_trait_impl.ri b/lib/rivet/src/checker/check_trait_impl.ri index 8718dbac4..7343e2ed8 100644 --- a/lib/rivet/src/checker/check_trait_impl.ri +++ b/lib/rivet/src/checker/check_trait_impl.ri @@ -8,11 +8,11 @@ import ../report; extend Checker { func check_trait_impl(mut self, impltor: ast.TypeSym, trait_sym: ast.TypeSym, pos: token.Pos) { - mut impl_does_not_implemented := @vec(string); + mut impl_does_not_implemented := @dyn_array(string); for sym in trait_sym.scope.syms { if sym is ast.Func as trait_func { if impl := impltor.find_func(trait_func.name); !trait_func.has_body { - mut errors := @vec(string); + mut errors := @dyn_array(string); if !impl.is_public { errors.push("method `{}` should be public.".fmt(impl.name)); } diff --git a/lib/rivet/src/checker/exprs.ri b/lib/rivet/src/checker/exprs.ri index 47c5a1ff4..8db7edc91 100644 --- a/lib/rivet/src/checker/exprs.ri +++ b/lib/rivet/src/checker/exprs.ri @@ -81,7 +81,7 @@ extend Checker { enum_lit.type }, .TupleLiteral as mut tuple_lit -> self.check_tuple_literal(tuple_lit), - .DynArrayLiteral as mut vec_lit -> self.check_vector_literal(vec_lit), + .DynArrayLiteral as mut vec_lit -> self.check_dyn_array_literal(vec_lit), .Ident as ident -> { ident.type = if ident.name == "_" { .Void() @@ -222,12 +222,12 @@ extend Checker { func check_tuple_literal(mut self, mut tuple_lit: ast.Expr.TupleLiteral) -> ast.Type { old_expected_type := self.expected_type; mut has_expected_types := false; - mut expected_types := @vec(ast.Type); + mut expected_types := @dyn_array(ast.Type); if expected_type_sym := self.expected_type.symbol(); expected_type_sym.info is .Tuple as tuple_info { has_expected_types = tuple_lit.values.len == tuple_info.types.len; expected_types = tuple_info.types; } - mut types := @vec(ast.Type); + mut types := @dyn_array(ast.Type); for i, mut value in tuple_lit.values { if has_expected_types { self.expected_type = expected_types[i]; @@ -249,7 +249,7 @@ extend Checker { return tuple_lit.type; } - func check_vector_literal(mut self, mut vec_lit: ast.Expr.DynArrayLiteral) -> ast.Type { + func check_dyn_array_literal(mut self, mut vec_lit: ast.Expr.DynArrayLiteral) -> ast.Type { old_expected_type := self.expected_type; mut size: uint := 0; mut is_mut := false; @@ -282,7 +282,7 @@ extend Checker { err_b.add_note(if vec_lit.is_arr { "in element {} of array literal" } else { - "in element {} of vector literal" + "in element {} of dynamic array literal" }.fmt(i + 1)); err_b.emit(); }; @@ -303,7 +303,7 @@ extend Checker { pos: vec_lit.pos ) } else { - .Basic(self.table.universe.add_or_get_vec(value_type, is_mut), pos: vec_lit.pos) + .Basic(self.table.universe.add_or_get_dyn_array(value_type, is_mut), pos: vec_lit.pos) }; return vec_lit.type; } @@ -422,7 +422,7 @@ extend Checker { } else { .DynArray( elem_type, is_mut, - self.table.universe.add_or_get_vec(elem_type, is_mut) + self.table.universe.add_or_get_dyn_array(elem_type, is_mut) ) } } else { @@ -435,7 +435,7 @@ extend Checker { "type `{}` does not support indexing".fmt(index.left_type), index.pos ); - err.add_note("only pointers, arrays, vectors and string supports indexing"); + err.add_note("only pointers, arrays, dynamic arrays and string supports indexing"); err.emit(); } else if index.left_type is .Pointer as pointer { if !self.inside_unsafe() { @@ -631,7 +631,7 @@ extend Checker { }; } else { report.error( - "operator `{}` can only be used with arrays and vectors".fmt( + "operator `{}` can only be used with arrays and dynamic arrays".fmt( binary.op ), binary.pos ); @@ -887,4 +887,4 @@ extend Checker { }; return .Void(); } -} +} \ No newline at end of file diff --git a/lib/rivet/src/checker/match_expr.ri b/lib/rivet/src/checker/match_expr.ri index 3b87e495e..0efa628b6 100644 --- a/lib/rivet/src/checker/match_expr.ri +++ b/lib/rivet/src/checker/match_expr.ri @@ -41,7 +41,7 @@ extend Checker { expr_type = guard_expr.vars[0].type; expr_sym = expr_type.symbol()?; } else { - mut types := @vec(mut ast.Type); + mut types := @dyn_array(mut ast.Type); for var_ in guard_expr.vars { types.push(var_.type); } @@ -166,7 +166,7 @@ extend Checker { // check that expressions are exhaustive, this is achieved either by putting // an `else` or when the `match` is on an enum by listing all variants. match_expr.is_exhaustive = true; - mut unhandled := @vec(string); + mut unhandled := @dyn_array(string); if expr_type == self.table.bool_t and match_expr.branches.len == 1 { for v in ["true", "false"]! { if !branch_exprs.contains(v) { diff --git a/lib/rivet/src/checker/stmts.ri b/lib/rivet/src/checker/stmts.ri index 8681d7660..05d8cdeaf 100644 --- a/lib/rivet/src/checker/stmts.ri +++ b/lib/rivet/src/checker/stmts.ri @@ -114,7 +114,7 @@ extend Checker { "`{}` is not an iterable type".fmt(iterable_t), for_stmt.iterable.position() ); - err.add_note("expected array or vector value"); + err.add_note("expected array value"); err.emit(); } } diff --git a/lib/rivet/src/checker/types.ri b/lib/rivet/src/checker/types.ri index aa32c396c..d18c13477 100644 --- a/lib/rivet/src/checker/types.ri +++ b/lib/rivet/src/checker/types.ri @@ -131,8 +131,8 @@ extend Checker { if expected is .Func and got is .Func { return expected == got; - } else if expected is .DynArray as vector_info and got is .DynArray as vector_info2 { - return vector_info.inner == vector_info2.inner; + } else if expected is .DynArray as dyn_array_info and got is .DynArray as dyn_array_info2 { + return dyn_array_info.inner == dyn_array_info2.inner; } if expected == self.table.rune_t and got == self.table.comptime_int_t { @@ -163,11 +163,11 @@ extend Checker { return array_info.elem_type == array_info2.elem_type and array_info.size == array_info2.size; }, - .DynArray as vector_lhs if got_sym.info is .DynArray as vector_rhs -> { - if vector_lhs.is_mut and !vector_rhs.is_mut { + .DynArray as dyn_array_lhs if got_sym.info is .DynArray as dyn_array_rhs -> { + if dyn_array_lhs.is_mut and !dyn_array_rhs.is_mut { return false; } - return vector_lhs.elem_type == vector_rhs.elem_type; + return dyn_array_lhs.elem_type == dyn_array_rhs.elem_type; }, .Tuple as tuple_lhs if got_sym.info is .Tuple as tuple_rhs -> { if tuple_lhs.types.len != tuple_rhs.types.len { @@ -185,7 +185,7 @@ extend Checker { mod_sym := self.sym.module()?; if mod_sym.is_core() { - if expected_sym.info is .DynArray and got_sym == self.table.vector_sym { + if expected_sym.info is .DynArray and got_sym == self.table.dyn_array_sym { return true; } } @@ -267,4 +267,4 @@ func check_pointer(expected: ast.Type, got: ast.Type) -> bool { return ptr.inner == ptr2.inner; } return false; -} +} \ No newline at end of file diff --git a/lib/rivet/src/codegen/mir/Type.ri b/lib/rivet/src/codegen/mir/Type.ri index 0621a10eb..0f5052a97 100644 --- a/lib/rivet/src/codegen/mir/Type.ri +++ b/lib/rivet/src/codegen/mir/Type.ri @@ -49,7 +49,7 @@ pub enum Type < traits.Stringable { .Pointer as ptr -> ptr.size, .Array as arr -> arr.size, .Func as func_ -> func_.size, - .Void, .Never -> process.panic("codegen.mir.Type.size(): `void` or `never` type") + .Void, .Never -> process.panic("codegen.mir.Type.size: `void` or `never` type use") }; } diff --git a/lib/rivet/src/codegen/mod.ri b/lib/rivet/src/codegen/mod.ri index a578719fa..ae5431786 100644 --- a/lib/rivet/src/codegen/mod.ri +++ b/lib/rivet/src/codegen/mod.ri @@ -27,7 +27,7 @@ pub struct Codegen { mut int_t: mir.Type; mut uint_t: mir.Type; mut bool_t: mir.Type; - mut vector_t: mir.Type; + mut dyn_array_t: mir.Type; mut throwable_t: mir.Type; mut generated_opt_res_types: maps.MapStringBool; @@ -74,9 +74,9 @@ pub struct Codegen { self.type_to_mir(self.table.uint32_t) }; self.bool_t = self.type_to_mir(self.table.uint8_t); - self.vector_t = .Pointer(.Basic( - self.mangle_symbol(self.table.vector_sym), - self.table.type_symbol_size(self.table.vector_sym, true).0 + self.dyn_array_t = .Pointer(.Basic( + self.mangle_symbol(self.table.dyn_array_sym), + self.table.type_symbol_size(self.table.dyn_array_sym, true).0 ), true); self.throwable_t = self.type_to_mir(self.table.throwable_t); diff --git a/lib/rivet/src/codegen/types.ri b/lib/rivet/src/codegen/types.ri index 2e7a0a395..0c003bbc3 100644 --- a/lib/rivet/src/codegen/types.ri +++ b/lib/rivet/src/codegen/types.ri @@ -9,7 +9,7 @@ import ../depgraph; extend Codegen { func get_type_symbols(mut self, root: ast.Sym) -> []ast.TypeSym { - mut ts := @vec(ast.TypeSym); + mut ts := @dyn_array(ast.TypeSym); for sym in root.scope.syms { if sym is ast.TypeSym as type_sym and !( type_sym.info is .DynArray or type_sym.info is .Alias @@ -26,12 +26,12 @@ extend Codegen { func sort_type_symbols(mut self, tss: []ast.TypeSym) { mut dg := depgraph.DepGraph.new(); - mut type_names := @vec(string); + mut type_names := @dyn_array(string); for ts in tss { type_names.push(ts.qualname()); } for ts in tss { - mut field_deps := @vec(string); + mut field_deps := @dyn_array(string); match ts.info is { .Array as array_info -> { dep := array_info.elem_type.to_qualstring(); @@ -39,8 +39,8 @@ extend Codegen { field_deps.push(dep); } }, - .DynArray as vector_info -> { - dep := vector_info.elem_type.to_qualstring(); + .DynArray as dyn_array_info -> { + dep := dyn_array_info.elem_type.to_qualstring(); if dep in type_names { field_deps.push(dep); } @@ -115,7 +115,7 @@ extend Codegen { is_void := result.inner.is_void(); name := "_R6Result".concat(self.mangle_type(result.inner)); if !self.generated_opt_res_types.contains(name) { - mut fields := @vec(mir.Field); + mut fields := @dyn_array(mir.Field); if !is_void { fields.push(mir.Field("value", self.type_to_mir(result.inner))); } @@ -133,7 +133,7 @@ extend Codegen { is_void := option.inner.is_void(); name := "_R6Option".concat(self.mangle_type(result.inner)); if !self.generated_opt_res_types.contains(name) { - mut fields := @vec(mir.Field); + mut fields := @dyn_array(mir.Field); if !is_void { fields.push(mir.Field("value", self.type_to_mir(option.inner))); } @@ -147,7 +147,7 @@ extend Codegen { .Array as array_t -> .Array( self.type_to_mir(array_t.inner), array_t.size_value, size ), - .DynArray -> self.vector_t, + .DynArray -> self.dyn_array_t, .Rawptr -> .Rawptr(self.table.pointer_size), .Pointer as ptr_t -> .Pointer( self.type_to_mir(ptr_t.inner), size: self.table.pointer_size @@ -166,7 +166,7 @@ extend Codegen { } match type_sym.info is { .Func as func_info -> { - mut args := @vec(mir.Type); + mut args := @dyn_array(mir.Type); for arg in func_info.args { args.push(self.type_to_mir(arg.type)); } @@ -192,4 +192,4 @@ extend Codegen { } }; } -} +} \ No newline at end of file diff --git a/lib/rivet/src/depgraph/OrderedDepMap.ri b/lib/rivet/src/depgraph/OrderedDepMap.ri index aa481b28e..2e2b725f8 100644 --- a/lib/rivet/src/depgraph/OrderedDepMap.ri +++ b/lib/rivet/src/depgraph/OrderedDepMap.ri @@ -43,7 +43,7 @@ pub struct OrderedDepMap { pub func delete(mut self, name: string) { if !self.data.contains(name) { - process.panic("OrderedDepMap.delete(): no such key: `{}`", name); + process.panic("OrderedDepMap.delete: no such key: `{}`", name); } for i, _ in self.keys { if self.keys[i] == name { @@ -55,7 +55,7 @@ pub struct OrderedDepMap { } pub func apply_diff(mut self, name: string, deps: []string) { - mut diff := @vec(string); + mut diff := @dyn_array(string); deps_of_name := self.get(name); for dep in deps_of_name { if dep !in deps { diff --git a/lib/rivet/src/depgraph/mod.ri b/lib/rivet/src/depgraph/mod.ri index 744631cff..d5f541a8d 100644 --- a/lib/rivet/src/depgraph/mod.ri +++ b/lib/rivet/src/depgraph/mod.ri @@ -19,7 +19,7 @@ pub struct DepGraph { #[inline] pub func new() -> Self { - return Self(true, @vec(DepGraphNode, 1024)); + return Self(true, @dyn_array(DepGraphNode, 1024)); } #[inline] @@ -38,7 +38,7 @@ pub struct DepGraph { mut resolved := Self.new(); while node_deps.size() != 0 { iterations += 1; - mut ready_set := @vec(string); + mut ready_set := @dyn_array(string); for name in node_deps.keys { deps := node_deps.get(name); if deps.is_empty() { @@ -83,7 +83,7 @@ pub struct DepGraph { } mut nn_names_it := nn.names.iterator(); while k := nn_names_it.next() { - mut cycle_names := @vec(string); + mut cycle_names := @dyn_array(string); if nn.is_cycle.contains(k.key) { continue; } @@ -113,7 +113,7 @@ struct NodeNames { return (true, new_already_seen); } new_already_seen.push(name); - deps := self.names.get(name) ?? @vec(string); + deps := self.names.get(name) ?? @dyn_array(string); if deps.is_empty() { self.is_cycle.set(name, false); return (false, new_already_seen); diff --git a/lib/rivet/src/fmt/mod.ri b/lib/rivet/src/fmt/mod.ri index 89319d063..d69466e3e 100644 --- a/lib/rivet/src/fmt/mod.ri +++ b/lib/rivet/src/fmt/mod.ri @@ -104,7 +104,7 @@ pub struct Formatter { buffer.go_back(if i > 0 { i - 1 } else { buffer.len() - i - 1 }); self.empty_line = false; mut line_len: uint := 0; - mut last_line_str := @vec(uint8); + mut last_line_str := @dyn_array(uint8); i = if buffer.len() > 0 { buffer.len() - 1 } else { 0 }; while i >= 0 : i -= 1 { ch := buffer.byte_at(i); @@ -153,7 +153,7 @@ pub struct Formatter { } func reverse(buf: []uint8) -> []uint8 { - mut reversed := @vec(uint8); + mut reversed := @dyn_array(uint8); mut i := buf.len - 1; while i >= 0 : i -= 1 { reversed.push(buf[i]); diff --git a/lib/rivet/src/lib.ri b/lib/rivet/src/lib.ri index ea2d5a252..63248439d 100644 --- a/lib/rivet/src/lib.ri +++ b/lib/rivet/src/lib.ri @@ -169,7 +169,7 @@ pub struct Compiler { mut name := ""; mut full_name := ""; mut abspath := ""; - mut files := @vec(string); + mut files := @dyn_array(string); is_super := pathx.starts_with("../"); if pathx.starts_with("./") or is_super { self.vlog(" searching module in local path"); @@ -288,7 +288,7 @@ pub struct Compiler { } self.vlog("-----------------------------------------"); source_files := self.table.source_files; - self.table.source_files = @vec(ast.SourceFile, source_files.len); + self.table.source_files = @dyn_array(ast.SourceFile, source_files.len); for node in g_resolved.nodes { for pf in source_files { if pf.mod.name == node.name { @@ -302,7 +302,7 @@ pub struct Compiler { func import_graph(self) -> depgraph.DepGraph { mut g := depgraph.DepGraph.new(); for pf in self.table.source_files { - mut deps := @vec(string); + mut deps := @dyn_array(string); if pf.mod.name !in ["c.ctypes", "c.libc", "c", "core"] { deps.push("core"); } diff --git a/lib/rivet/src/parser/decls.ri b/lib/rivet/src/parser/decls.ri index 2bd726bf7..0496e6d31 100644 --- a/lib/rivet/src/parser/decls.ri +++ b/lib/rivet/src/parser/decls.ri @@ -10,7 +10,7 @@ import ../token; extend Parser { func parse_doc_comments(mut self) -> []ast.Comment { - mut comments := @vec(ast.Comment); + mut comments := @dyn_array(ast.Comment); while self.tok.kind == .DocComment or (self.tok.kind == .Comment and comments.len > 0) { comments.push(self.parse_comment()); } @@ -25,7 +25,7 @@ extend Parser { } if self.accept(.Lbracket) { while { - mut args := @vec(ast.AttributeArgument); + mut args := @dyn_array(ast.AttributeArgument); pos := self.tok.pos; attribute_name := if self.accept(.KwUnsafe) { "unsafe" @@ -81,7 +81,7 @@ extend Parser { } func parse_decls(mut self) -> []ast.Decl { - mut decls := @vec(ast.Decl); + mut decls := @dyn_array(ast.Decl); while self.tok.kind != .EndOfFile { decls.push(self.parse_decl()); } @@ -98,7 +98,7 @@ extend Parser { match { self.tok.kind == .Comment -> return .Comment(self.parse_comment()), self.accept(.KwImport) -> { - mut import_list := @vec(ast.ImportListInfo); + mut import_list := @dyn_array(ast.ImportListInfo); mut glob := false; if self.accept(.Lbrace) { while { @@ -173,7 +173,7 @@ extend Parser { self.inside_extern = true; // extern function or var abi := self.parse_abi(); - mut decls := @vec(ast.Decl); + mut decls := @dyn_array(ast.Decl); if self.accept(.Lbrace) { if is_public { report.error("`extern` blocks cannot be declared public", pos); @@ -249,7 +249,7 @@ extend Parser { }, self.accept(.KwVar) -> { // variable declarations - mut lefts := @vec(ast.ObjectData); + mut lefts := @dyn_array(ast.ObjectData); if self.accept(.Lparen) { // multiple variables while { @@ -284,7 +284,7 @@ extend Parser { old_inside_trait := self.inside_trait; self.inside_trait = true; name := self.parse_name(); - mut bases := @vec(mut ast.Type); + mut bases := @dyn_array(mut ast.Type); if self.accept(.Lt) { while { bases.push(self.parse_type()); @@ -293,7 +293,7 @@ extend Parser { } } } - mut decls := @vec(ast.Decl); + mut decls := @dyn_array(ast.Decl); self.expect(.Lbrace); while !self.accept(.Rbrace) { decls.push(self.parse_decl()); @@ -315,8 +315,8 @@ extend Parser { self.inside_struct = true; name := self.parse_name(); is_opaque := self.accept(.Semicolon); - mut bases := @vec(mut ast.Type); - mut decls := @vec(ast.Decl); + mut bases := @dyn_array(mut ast.Type); + mut decls := @dyn_array(ast.Decl); if !is_opaque { if self.accept(.Lt) { while { @@ -351,7 +351,7 @@ extend Parser { } else { self.table.comptime_int_t }; - mut bases := @vec(mut ast.Type); + mut bases := @dyn_array(mut ast.Type); if self.accept(.Lt) { while { bases.push(self.parse_type()); @@ -362,7 +362,7 @@ extend Parser { } self.expect(.Lbrace); mut is_boxed := false; - mut variants := @vec(ast.EnumVariantDecl); + mut variants := @dyn_array(ast.EnumVariantDecl); while { v_pos := self.tok.pos; v_name := self.parse_name(); @@ -370,7 +370,7 @@ extend Parser { mut has_value := false; mut v_type := ast.Type.Void; mut value := ast.Expr.Empty(self.tok.pos); - mut variant_decls := @vec(ast.Decl); + mut variant_decls := @dyn_array(ast.Decl); if self.accept(.Lbrace) { has_type = true; is_boxed = true; @@ -401,7 +401,7 @@ extend Parser { break; } } - mut decls := @vec(ast.Decl); + mut decls := @dyn_array(ast.Decl); if self.accept(.Semicolon) { while self.tok.kind != .Rbrace { decls.push(self.parse_decl()); @@ -444,7 +444,7 @@ extend Parser { }, self.accept(.KwExtend) -> { type := self.parse_type(); - mut bases := @vec(mut ast.Type); + mut bases := @dyn_array(mut ast.Type); if self.accept(.Lt) { while { bases.push(self.parse_type()); @@ -454,7 +454,7 @@ extend Parser { } } self.expect(.Lbrace); - mut decls := @vec(ast.Decl); + mut decls := @dyn_array(ast.Decl); while !self.accept(.Rbrace) { decls.push(self.parse_decl()); } @@ -479,7 +479,7 @@ extend Parser { self.open_scope(); sc := self.scope; sc.detached_from_parent = true; - mut stmts := @vec(mut ast.Stmt); + mut stmts := @dyn_array(mut ast.Stmt); self.expect(.Lbrace); while !self.accept(.Rbrace) { stmts.push(self.parse_stmt()); @@ -542,7 +542,7 @@ extend Parser { mut self_is_mut := false; mut self_is_ptr := false; mut self_pos := token.noPos; - mut args := @vec(ast.Arg); + mut args := @dyn_array(ast.Arg); mut has_named_args := false; mut is_variadic := false; @@ -618,7 +618,7 @@ extend Parser { } } - mut stmts := @vec(mut ast.Stmt); + mut stmts := @dyn_array(mut ast.Stmt); mut has_body := true; if (self.inside_trait or self.inside_extern) and self.accept(.Semicolon) { has_body = false; diff --git a/lib/rivet/src/parser/exprs.ri b/lib/rivet/src/parser/exprs.ri index bbbbe9208..05465049d 100644 --- a/lib/rivet/src/parser/exprs.ri +++ b/lib/rivet/src/parser/exprs.ri @@ -224,11 +224,11 @@ extend Parser { } else { self.parse_name() }; - mut args := @vec(ast.CallArg); + mut args := @dyn_array(ast.CallArg); self.expect(.Lparen); - mut vec_is_mut := false; - if name in ["vec", "as", "size_of", "align_of"] { - vec_is_mut = name == "vec" and self.accept(.KwMut); + mut dyn_array_is_mut := false; + if name in ["dyn_array", "as", "size_of", "align_of"] { + dyn_array_is_mut = name == "dyn_array" and self.accept(.KwMut); arg_pos := self.tok.pos; args.push( ast.CallArg( @@ -250,7 +250,7 @@ extend Parser { } } self.expect(.Rparen); - .BuiltinCall(name, args, vec_is_mut, pos + self.prev_tok.pos) + .BuiltinCall(name, args, dyn_array_is_mut, pos + self.prev_tok.pos) } else { self.parse_ident(true) // builtin variable } @@ -308,7 +308,7 @@ extend Parser { } }, self.tok.kind == .Lbracket -> { - mut elems := @vec(mut ast.Expr); + mut elems := @dyn_array(mut ast.Expr); mut pos := self.tok.pos; self.next(); if self.tok.kind != .Rbracket { @@ -364,7 +364,7 @@ extend Parser { and (expr is .Ident or expr is .Selector or expr is .Paren or expr is .SelfTy or expr is .EnumLiteral) -> { self.next(); - mut args := @vec(ast.CallArg); + mut args := @dyn_array(ast.CallArg); mut spread_expr := ast.Expr.Empty(self.tok.pos); mut has_spread_expr := false; if self.tok.kind != .Rparen { @@ -499,7 +499,7 @@ extend Parser { } func parse_if_expr(mut self) -> ast.Expr { - mut branches := @vec(ast.IfBranch); + mut branches := @dyn_array(ast.IfBranch); mut has_else := false; mut pos := self.tok.pos; while self.tok.kind in [.KwIf, .KwElse] { @@ -541,7 +541,7 @@ extend Parser { func parse_match_expr(mut self) -> ast.Expr { mut has_else := false; - mut branches := @vec(ast.MatchBranch); + mut branches := @dyn_array(ast.MatchBranch); pos := self.prev_tok.pos; old_inside_match_header := self.inside_match_header; self.inside_match_header = true; @@ -561,7 +561,7 @@ extend Parser { self.inside_match_header = old_inside_match_header; while { branch_pos := self.tok.pos; - mut cases := @vec(mut ast.Expr); + mut cases := @dyn_array(mut ast.Expr); mut has_var := false; mut var_is_mut := false; mut var_name := ""; @@ -654,7 +654,7 @@ extend Parser { pos := self.tok.pos; is_unsafe := self.accept(.KwUnsafe); self.expect(.Lbrace); - mut stmts := @vec(mut ast.Stmt); + mut stmts := @dyn_array(mut ast.Stmt); mut has_expr := false; mut expr := ast.Expr.Empty(self.tok.pos); while !self.accept(.Rbrace) { @@ -674,7 +674,7 @@ extend Parser { func parse_guard_expr(mut self) -> ast.Expr { pos := self.tok.pos; - mut vars := @vec(ast.ObjectData); + mut vars := @dyn_array(ast.ObjectData); if self.accept(.Lparen) { while { vars.push(self.parse_var_decl(support_type: false)); diff --git a/lib/rivet/src/parser/mod.ri b/lib/rivet/src/parser/mod.ri index e1bf96547..f1778e60d 100644 --- a/lib/rivet/src/parser/mod.ri +++ b/lib/rivet/src/parser/mod.ri @@ -39,7 +39,7 @@ pub struct Parser { pub func parse_module(mut self, mod_sym: ast.Module, files: []string) -> []ast.SourceFile { self.scope = mod_sym.scope; self.mod_sym = mod_sym; - mut source_files := @vec(ast.SourceFile); + mut source_files := @dyn_array(ast.SourceFile); for file in files { source_files.push(self.parse_file(file)); } @@ -173,7 +173,7 @@ pub struct Parser { // - follow_up: comments directly below the previous token as long as there // - is no empty line. func eat_comments(mut self, same_line: bool := false, follow_up: bool := false) -> []ast.Comment { - mut comments := @vec(ast.Comment); + mut comments := @dyn_array(ast.Comment); mut line := self.prev_tok.pos.line; while { if self.tok.kind != .Comment or (same_line and self.tok.pos.line > line) diff --git a/lib/rivet/src/parser/stmts.ri b/lib/rivet/src/parser/stmts.ri index c645942a2..d97be4260 100644 --- a/lib/rivet/src/parser/stmts.ri +++ b/lib/rivet/src/parser/stmts.ri @@ -59,7 +59,7 @@ extend Parser { index = self.parse_var_decl(support_mut: false, support_type: false); self.expect(.Comma); } - mut values := @vec(ast.ObjectData); + mut values := @dyn_array(ast.ObjectData); if self.accept(.Lparen) { while { values.push( @@ -113,7 +113,7 @@ extend Parser { and self.decl_operator_is_used() -> { // variable declarations mut pos := self.tok.pos; - mut lefts := @vec(ast.ObjectData); + mut lefts := @dyn_array(ast.ObjectData); if self.accept(.Lparen) { // multiple variables while { diff --git a/lib/rivet/src/parser/types.ri b/lib/rivet/src/parser/types.ri index 24c57f068..16ed0dbcf 100644 --- a/lib/rivet/src/parser/types.ri +++ b/lib/rivet/src/parser/types.ri @@ -16,7 +16,7 @@ extend Parser { // function types self.expect(.KwFunc); self.expect(.Lparen); - mut args := @vec(ast.Arg); + mut args := @dyn_array(ast.Arg); if self.tok.kind != .Rparen { while { arg_pos := self.tok.pos; @@ -53,7 +53,7 @@ extend Parser { .Pointer(self.parse_type(), is_mut, pos: pos + self.prev_tok.pos) }, self.accept(.Lbracket) -> { - // arrays or vectors + // arrays or dynamic arrays if self.tok.kind != .Rbracket { // indexable pointers if self.accept(.Amp) { @@ -77,7 +77,7 @@ extend Parser { }, self.accept(.Lparen) -> { // tuples - mut inners := @vec(mut ast.Type); + mut inners := @dyn_array(mut ast.Type); while { inners.push(self.parse_type()); if !self.accept(.Comma) { diff --git a/lib/rivet/src/resolver/Register.ri b/lib/rivet/src/resolver/Register.ri index f23be4634..6bd548cb9 100644 --- a/lib/rivet/src/resolver/Register.ri +++ b/lib/rivet/src/resolver/Register.ri @@ -93,7 +93,7 @@ pub struct Register { ), struct_decl.pos) }; if self.is_core_mod and struct_decl.name == "DynArray" { - self.table.vector_sym = @as(ast.TypeSym, struct_decl.sym); + self.table.dyn_array_sym = @as(ast.TypeSym, struct_decl.sym); } self.sym = struct_decl.sym; self.walk_decls(struct_decl.decls); @@ -382,4 +382,4 @@ pub struct Register { report.error("{} `{}` is private".fmt(sym.type_of(), sym.name), pos); } } -} +} \ No newline at end of file diff --git a/lib/rivet/src/resolver/exprs.ri b/lib/rivet/src/resolver/exprs.ri index 8e83fe29c..8e176e9f9 100644 --- a/lib/rivet/src/resolver/exprs.ri +++ b/lib/rivet/src/resolver/exprs.ri @@ -35,8 +35,8 @@ extend Resolver { self.resolve_expr(value); } }, - .DynArrayLiteral as vector_lit -> { - for mut value in vector_lit.values { + .DynArrayLiteral as dyn_array_lit -> { + for mut value in dyn_array_lit.values { self.resolve_expr(value); } }, @@ -372,4 +372,4 @@ extend Resolver { } } } -} +} \ No newline at end of file diff --git a/lib/rivet/src/resolver/types.ri b/lib/rivet/src/resolver/types.ri index b381c8d26..929da13f3 100644 --- a/lib/rivet/src/resolver/types.ri +++ b/lib/rivet/src/resolver/types.ri @@ -16,13 +16,13 @@ extend Resolver { if elem_sym.info is .Trait as trait_info { trait_info.has_objects = true; } - variadic.sym = self.table.universe.add_or_get_vec(variadic.inner, false); + variadic.sym = self.table.universe.add_or_get_dyn_array(variadic.inner, false); true } else { false }, .DynArray as vec -> if self.resolve_type(vec.inner) { - vec.sym = self.table.universe.add_or_get_vec(vec.inner, vec.is_mut); + vec.sym = self.table.universe.add_or_get_dyn_array(vec.inner, vec.is_mut); true } else { false @@ -146,4 +146,4 @@ extend Resolver { else -> false }; } -} +} \ No newline at end of file diff --git a/lib/rivet/src/tokenizer/mod.ri b/lib/rivet/src/tokenizer/mod.ri index ea6a28ad7..564961608 100644 --- a/lib/rivet/src/tokenizer/mod.ri +++ b/lib/rivet/src/tokenizer/mod.ri @@ -47,7 +47,7 @@ pub struct Tokenizer { } func init(mut self) { - self.all_tokens = @vec(token.Token, self.text.len / 3); + self.all_tokens = @dyn_array(token.Token, self.text.len / 3); self.tokenize_remaining_text(); } @@ -242,7 +242,7 @@ pub struct Tokenizer { if escapes_pos.is_empty() { return s; } - mut ss := @vec(string, escapes_pos.len * 2 + 1); + mut ss := @dyn_array(string, escapes_pos.len * 2 + 1); ss.push(s[..escapes_pos[escapes_pos.len - 1] - start]); for i, pos in escapes_pos { idx := pos - start; @@ -285,7 +285,7 @@ func decode_o_escapes(s: string, start: uint, escapes_pos: []uint) -> string { if escapes_pos.is_empty() { return s; } - mut ss := @vec(string, escapes_pos.len); + mut ss := @dyn_array(string, escapes_pos.len); // everything before the first escape code position ss.push(s[..escapes_pos[escapes_pos.len - 1] - start]); for i, pos in escapes_pos { @@ -315,7 +315,7 @@ func decode_unicode_escaped_rune(str: string) -> string { return if str.len == end_idx { segment } else { - mut ss := @vec(string, 2); + mut ss := @dyn_array(string, 2); ss.push(segment); ss.push(str[end_idx..]); utils.join(ss, "") @@ -344,4 +344,4 @@ func number_literal_without_separator(lit: string) -> string { } else { lit }; -} +} \ No newline at end of file diff --git a/lib/rivet/src/tokenizer/next.ri b/lib/rivet/src/tokenizer/next.ri index 7f9e20c78..5ccc842fa 100644 --- a/lib/rivet/src/tokenizer/next.ri +++ b/lib/rivet/src/tokenizer/next.ri @@ -627,7 +627,7 @@ extend Tokenizer { ch = decode_unicode_escaped_rune(ch); } else { // find escape sequence start positions - mut escapes_pos := @vec(uint); + mut escapes_pos := @dyn_array(uint); for i, v in ch.as_bytes() { if v == BACKSLASH { escapes_pos.push(i); @@ -678,8 +678,8 @@ extend Tokenizer { if start_char == LF { self.inc_line_number(); } - mut u_escapes_pos := @vec(uint); // pos list of \uXXXX - mut h_escapes_pos := @vec(uint); // pos list of \xXX + mut u_escapes_pos := @dyn_array(uint); // pos list of \uXXXX + mut h_escapes_pos := @dyn_array(uint); // pos list of \xXX while { self.pos += 1; if self.pos >= self.text.len { @@ -742,9 +742,9 @@ extend Tokenizer { lit = self.text[start..self.pos].clone(); if !self.prefs.is_fmt { mut segment_idx: uint := 0; - mut str_segments := @vec(string); + mut str_segments := @dyn_array(string); if u_escapes_pos.len + h_escapes_pos.len > 0 { - mut all_pos := @vec(uint, u_escapes_pos.len + h_escapes_pos.len); + mut all_pos := @dyn_array(uint, u_escapes_pos.len + h_escapes_pos.len); for pos1 in u_escapes_pos { all_pos.push(pos1); } @@ -781,4 +781,4 @@ extend Tokenizer { return lit; } -} +} \ No newline at end of file diff --git a/lib/rivet/tests/tokenizer.ri b/lib/rivet/tests/tokenizer.ri index fc3b5989f..48bf287cc 100644 --- a/lib/rivet/tests/tokenizer.ri +++ b/lib/rivet/tests/tokenizer.ri @@ -11,7 +11,7 @@ var prefs_ := prefs.Prefs(); func tokenize(text: string) -> []token.Token { mut tokenizer_ := tokenizer.Tokenizer.new(text, prefs_, Table.new(prefs_)); - mut tokens := @vec(token.Token, text.len / 3); + mut tokens := @dyn_array(token.Token, text.len / 3); mut token := tokenizer_.next(); while { tokens.push(token); diff --git a/lib/std/src/flag/mod.ri b/lib/std/src/flag/mod.ri index e934a3cd0..315d32290 100644 --- a/lib/std/src/flag/mod.ri +++ b/lib/std/src/flag/mod.ri @@ -74,7 +74,7 @@ pub struct FlagParser { pub func new(args: []string) -> Self { original_args := args.clone(); mut all_before_dashdash := args.clone(); - mut all_after_dashdash := @vec(string); + mut all_after_dashdash := @dyn_array(string); idx_dashdash := index_of(args, "--"); if v := idx_dashdash { all_before_dashdash.trim(v); @@ -405,8 +405,8 @@ pub struct FlagParser { /// - found arguments and corresponding values are removed from args list. func parse_value(mut self, long_hand: string, short_hand: uint8) -> []string { full := "--".concat(long_hand); - mut found_entries := @vec(string); - mut to_delete := @vec(uint); + mut found_entries := @dyn_array(string); + mut to_delete := @dyn_array(uint); mut should_skip_one := false; for i, arg in self.args { if should_skip_one { diff --git a/lib/std/src/fs/Directory.c.ri b/lib/std/src/fs/Directory.c.ri index abac9b99b..7df677948 100644 --- a/lib/std/src/fs/Directory.c.ri +++ b/lib/std/src/fs/Directory.c.ri @@ -78,7 +78,7 @@ pub struct Directory { rpath := Path.resolve(path_)!; unsafe { if dir := libc.opendir(path_.ptr) { - mut res := @vec(string, 15); + mut res := @dyn_array(string, 15); while ent := libc.readdir(dir) { bptr: [&]uint8 := &ent.*.d_name[0]; if (bptr[0] == 0 or (bptr[0] == b'.' and bptr[1] == 0) diff --git a/lib/std/src/semver/range.ri b/lib/std/src/semver/range.ri index 8f79f643f..598b4c19e 100644 --- a/lib/std/src/semver/range.ri +++ b/lib/std/src/semver/range.ri @@ -75,7 +75,7 @@ struct ComparatorSet { "invalid format of comparator set for input '{}'".fmt(input) ); } - mut comparators := @vec(Comparator); + mut comparators := @dyn_array(Comparator); for raw_comp in raw_comparators { comparators.push( Comparator.parse(raw_comp) ?? throw InvalidComparatorFormatError( @@ -116,7 +116,7 @@ struct Range { func parse(input: string) -> ?Range { raw_comparator_sets := input.split(comparatorSetSep); - mut comparator_sets := @vec(ComparatorSet); + mut comparator_sets := @dyn_array(ComparatorSet); for raw_comp_set in raw_comparator_sets { if can_expand(raw_comp_set) { comparator_sets.push(ComparatorSet.expand(raw_comp_set) ?? return none); diff --git a/lib/std/src/strings/mod.ri b/lib/std/src/strings/mod.ri index 4c55e20d3..02a598952 100644 --- a/lib/std/src/strings/mod.ri +++ b/lib/std/src/strings/mod.ri @@ -6,8 +6,8 @@ import core; pub alias Builder := core.StringBuilder; -func fill_vector(len: uint) -> []mut int32 { - mut vec := @vec(mut int32, len); +func fill_dyn_array(len: uint) -> []mut int32 { + mut vec := @dyn_array(mut int32, len); mut i: uint := 0; while i < len : i += 1 { vec.push(@as(int32, i)); @@ -18,7 +18,7 @@ func fill_vector(len: uint) -> []mut int32 { /// Uses levenshtein distance algorithm to calculate the distance between /// two strings (lower is closer). pub func levenshtein_distance(a: string, b: string) -> int32 { - f := fill_vector(b.len + 1); + f := fill_dyn_array(b.len + 1); for ca in a.as_bytes() { mut j: uint := 1; mut fj1 := f[0]; diff --git a/rivetc/src/__init__.py b/rivetc/src/__init__.py index 41969ffe4..1de8abbf1 100644 --- a/rivetc/src/__init__.py +++ b/rivetc/src/__init__.py @@ -22,7 +22,7 @@ def __init__(self, args): self.pointer_size = 8 if self.prefs.target_bits == prefs.Bits.X64 else 4 self.core_mod = None - self.vec_sym = None # from `core` module + self.dyn_array_sym = None # from `core` module self.throwable_sym = None # from `core` module # Primitive types. diff --git a/rivetc/src/ast.py b/rivetc/src/ast.py index c28aee67a..93e5aae95 100644 --- a/rivetc/src/ast.py +++ b/rivetc/src/ast.py @@ -757,7 +757,7 @@ def __init__(self, name, args, pos): self.name = name self.args = args self.pos = pos - self.vec_is_mut = False + self.dyn_array_is_mut = False self.typ = None def __repr__(self): diff --git a/rivetc/src/checker.py b/rivetc/src/checker.py index 8d399ffa8..600fdda52 100644 --- a/rivetc/src/checker.py +++ b/rivetc/src/checker.py @@ -276,7 +276,7 @@ def check_stmt(self, stmt): elif isinstance(stmt, ast.ForStmt): iterable_t = self.check_expr(stmt.iterable) iterable_sym = iterable_t.symbol() - if iterable_sym.kind in (TypeKind.Array, TypeKind.Vec): + if iterable_sym.kind in (TypeKind.Array, TypeKind.DynArray): elem_typ = self.comp.comptime_number_to_type( iterable_sym.info.elem_typ ) @@ -298,7 +298,7 @@ def check_stmt(self, stmt): report.error( f"`{iterable_t}` is not an iterable type", stmt.iterable.pos ) - report.note("expected array or vector value") + report.note("expected array value") elif isinstance(stmt, ast.DeferStmt): self.check_expr(stmt.expr) self.defer_stmts.append(stmt) @@ -434,7 +434,7 @@ def check_expr(self, expr): has_exp_typ = False if not isinstance(self.expected_type, type.Func): elem_sym = self.expected_type.symbol() - if elem_sym.kind in (TypeKind.Array, TypeKind.Vec): + if elem_sym.kind in (TypeKind.Array, TypeKind.DynArray): has_exp_typ = True elem_typ = elem_sym.info.elem_typ self.expected_type = elem_typ @@ -458,7 +458,9 @@ def check_expr(self, expr): if expr.is_arr: report.note(f"in element {i + 1} of array literal") else: - report.note(f"in element {i + 1} of vector literal") + report.note( + f"in element {i + 1} of dynamic array literal" + ) if expr.is_arr: if len(expr.elems) > 0: arr_len = str(len(expr.elems)) @@ -476,7 +478,7 @@ def check_expr(self, expr): ) else: expr.typ = type.Type( - self.comp.universe.add_or_get_vec( + self.comp.universe.add_or_get_dyn_array( self.comp.comptime_number_to_type(elem_typ), is_mut ) ) @@ -659,9 +661,9 @@ def check_expr(self, expr): expr.typ = self.comp.bool_t rsym = rtyp.symbol() assert rsym != None, (expr.pos) - if rsym.kind not in (TypeKind.Vec, TypeKind.Array): + if rsym.kind not in (TypeKind.DynArray, TypeKind.Array): report.error( - f"operator `{expr.op}` can only be used with arrays and vectors", + f"operator `{expr.op}` can only be used with arrays and dynamic arrays", expr.pos ) return expr.typ @@ -792,18 +794,18 @@ def check_expr(self, expr): f"expected unsigned integer value, found `{idx_t}`", expr.index.pos ) - if left_sym.kind in (TypeKind.Array, TypeKind.Vec): + if left_sym.kind in (TypeKind.Array, TypeKind.DynArray): if isinstance(expr.index, ast.RangeExpr): - if left_sym.kind == TypeKind.Vec: + if left_sym.kind == TypeKind.DynArray: expr.typ = expr.left_typ else: - expr.typ = type.Vec( + expr.typ = type.DynArray( left_sym.info.elem_typ, left_sym.info.is_mut ) - expr.typ.sym = self.comp.universe.add_or_get_vec( + expr.typ.sym = self.comp.universe.add_or_get_dyn_array( left_sym.info.elem_typ, left_sym.info.is_mut ) - elif left_sym.kind == TypeKind.Vec: + elif left_sym.kind == TypeKind.DynArray: expr.typ = left_sym.info.elem_typ else: expr.typ = left_sym.info.elem_typ @@ -1005,12 +1007,12 @@ def check_expr(self, expr): elif expr.name == "ignore_not_mutated_warn": _ = self.check_expr(expr.args[0]) self.check_expr_is_mut(expr.args[0]) - elif expr.name == "vec": + elif expr.name == "dyn_array": if len(expr.args) in (1, 2): elem_t = expr.args[0].typ expr.typ = type.Type( - self.comp.universe.add_or_get_vec( - elem_t, expr.vec_is_mut + self.comp.universe.add_or_get_dyn_array( + elem_t, expr.dyn_array_is_mut ) ) if len(expr.args) == 2: @@ -1020,7 +1022,7 @@ def check_expr(self, expr): except utils.CompilerError as e: report.error(e.args[0], expr.args[1].pos) report.note( - "in second argument of builtin function `vec`" + "in second argument of builtin function `dyn_array`" ) else: report.error( @@ -1208,7 +1210,9 @@ def check_expr(self, expr): expr.field_pos ) if expr.field_name.isdigit(): - if left_sym.kind in (TypeKind.Array, TypeKind.Vec): + if left_sym.kind in ( + TypeKind.Array, TypeKind.DynArray + ): report.note( f"instead of using tuple indexing, use array indexing: `expr[{expr.field_name}]`" ) @@ -1661,9 +1665,9 @@ def check_call(self, info, expr): if expr.has_spread_expr: spread_expr_t = self.check_expr(expr.spread_expr) spread_expr_sym = spread_expr_t.symbol() - if spread_expr_sym.kind != TypeKind.Vec: + if spread_expr_sym.kind != TypeKind.DynArray: report.error( - "spread operator can only be used with vectors", + "spread operator can only be used with dynamic arrays", expr.spread_expr.pos ) elif not isinstance(info.args[-1].typ, type.Variadic): @@ -1672,10 +1676,10 @@ def check_call(self, info, expr): ) else: last_arg_typ = info.args[-1].typ - vec_t = type.Vec(last_arg_typ, False) - vec_t.sym = last_arg_typ.sym + dyn_array_t = type.DynArray(last_arg_typ, False) + dyn_array_t.sym = last_arg_typ.sym try: - self.check_types(spread_expr_t, vec_t) + self.check_types(spread_expr_t, dyn_array_t) except utils.CompilerError as e: report.error(e.args[0], expr.spread_expr.pos) return expr.typ @@ -1778,7 +1782,8 @@ def check_compatible_types(self, got, expected): if isinstance(expected, type.Func) and isinstance(got, type.Func): return expected == got - elif isinstance(expected, type.Vec) and isinstance(got, type.Vec): + elif isinstance(expected, + type.DynArray) and isinstance(got, type.DynArray): return expected.typ == got.typ if expected == self.comp.rune_t and got == self.comp.comptime_int_t: @@ -1800,7 +1805,7 @@ def check_compatible_types(self, got, expected): if exp_sym.info.is_mut and not got_sym.info.is_mut: return False return exp_sym.info.elem_typ == got_sym.info.elem_typ and exp_sym.info.size == got_sym.info.size - elif exp_sym.kind == TypeKind.Vec and got_sym.kind == TypeKind.Vec: + elif exp_sym.kind == TypeKind.DynArray and got_sym.kind == TypeKind.DynArray: if exp_sym.info.is_mut and not got_sym.info.is_mut: return False return exp_sym.info.elem_typ == got_sym.info.elem_typ @@ -1813,7 +1818,7 @@ def check_compatible_types(self, got, expected): return True if self.sym.is_core_mod(): - if exp_sym.kind == TypeKind.Vec and got_sym == self.comp.vec_sym: + if exp_sym.kind == TypeKind.DynArray and got_sym == self.comp.dyn_array_sym: return True return False diff --git a/rivetc/src/codegen/__init__.py b/rivetc/src/codegen/__init__.py index e07e57b8c..631afc927 100644 --- a/rivetc/src/codegen/__init__.py +++ b/rivetc/src/codegen/__init__.py @@ -8,104 +8,8 @@ from .. import ast, sym, type, token, prefs, report, utils from ..token import Kind, OVERLOADABLE_OPERATORS_STR, NO_POS -from . import ir from .c import CGen - -def prefix_type(tt): - prefix = "" - if isinstance(tt, type.Ptr): - _t = tt - while isinstance(_t, type.Ptr): - prefix += "ptr_" - if _t.is_mut: - prefix += "mut_" - _t = _t.typ - prefix += prefix_type(tt.typ) - elif isinstance(tt, type.Ptr): - prefix += "ref_" - if tt.is_mut: - prefix += "mut_" - prefix += prefix_type(tt.typ) - elif isinstance(tt, type.Option): - prefix += "opt_" + prefix_type(tt.typ) - return prefix - -def mangle_type(typ): - if isinstance(typ, type.Func): - s = "fn_" - if typ.is_unsafe: - s += "unsafe_" - if typ.is_extern: - s += f"extern_{typ.abi}_" - if typ.is_method: - s += "m_" - if typ.self_is_mut: - s += "_sm_" - elif typ.self_is_ptr: - s += "_sr_" - if typ.is_variadic: - s += "_v_" - s += f"_args{len(typ.args)}" - return s - return f"{prefix_type(typ)}{mangle_symbol(typ.symbol())}" - -def mangle_symbol(s): - if len(s.mangled_name) > 0: - return s.mangled_name - res = [] - root = s - while True: - if s.is_universe: - break - if isinstance(s, sym.Mod): - s.mangled_name = "".join([ - f"{len(n)}{n}" for n in s.name.split(".") - ]) - res.insert(0, s.mangled_name) - elif isinstance(s, sym.Type): - if s.kind == TypeKind.Tuple: - name = "Tuple_" - for i, tt in enumerate(s.info.types): - name += mangle_type(tt) - if i < len(s.info.types) - 1: - name += "_" - name = f"{len(name)}{name}" - res.insert(0, name) - s.mangled_name = name - elif s.kind == TypeKind.Vec: - res.insert(0, "4core8DynArray") - s.mangled_name = "_R4core8DynArray" - elif s.kind == TypeKind.Array: - name = f"Array_{mangle_type(s.info.elem_typ)}_{s.info.size}" - name = f"{len(name)}{name}" - res.insert(0, name) - s.mangled_name = name - elif s.kind == TypeKind.String: - res.insert(0, "4core6string") - s.mangled_name = "_R4core6string" - else: - res.insert(0, f"{len(s.name)}{s.name}") - elif s.name in OVERLOADABLE_OPERATORS_STR: - name = OVERLOADABLE_OPERATORS_STR[s.name] - name = f"{len(name)}{name}" - res.insert(0, name) - s.mangled_name = name - else: - res.insert(0, f"{len(s.name)}{s.name}") - if s.parent == None: - break - else: - s = s.parent - res.insert(0, "_R") - - if isinstance(root, sym.Func): - if root.is_method: - res.append("M") - else: - res.append("F") - - root.mangled_name = "".join(res) - return root.mangled_name +from . import ir, cg_utils class TestInfo: def __init__(self, name, func): @@ -184,7 +88,9 @@ def gen_source_files(self, source_files): self.cur_fn.add_call("_R4core16init_string_litsF") testRunner = ir.Ident(ir.TEST_RUNNER_T, "_testRunner") main_fn.alloca(testRunner) - tests_field = ir.Selector(ir.VEC_T, testRunner, ir.Name("tests")) + tests_field = ir.Selector( + ir.DYN_ARRAY_T, testRunner, ir.Name("tests") + ) main_fn.store( ir.Selector(ir.UINT64_T, testRunner, ir.Name("ok_tests")), ir.IntLit(ir.UINT64_T, "0") @@ -198,7 +104,7 @@ def gen_source_files(self, source_files): ir.IntLit(ir.UINT64_T, "0") ) tests_vec = ir.Selector( - ir.VEC_T.ptr(True), testRunner, ir.Name("tests") + ir.DYN_ARRAY_T.ptr(True), testRunner, ir.Name("tests") ) test_t = ir.TEST_T.ptr() gtests_array = [] @@ -342,7 +248,7 @@ def gen_decl(self, decl): self.inside_var_decl = True for l in decl.lefts: is_extern = decl.is_extern and decl.abi != sym.ABI.Rivet - name = l.name if is_extern else mangle_symbol(l.sym) + name = l.name if is_extern else cg_utils.mangle_symbol(l.sym) typ = self.ir_type(l.typ) self.out_rir.globals.append( ir.GlobalVar(is_extern, is_extern, typ, name) @@ -420,7 +326,7 @@ def gen_decl(self, decl): else: assert False else: - name = mangle_symbol(decl.sym) + name = cg_utils.mangle_symbol(decl.sym) fn_decl = ir.FuncDecl( False, decl.attributes, decl.is_extern and not decl.has_body, name, args, decl.is_variadic and decl.is_extern, ret_typ, @@ -818,12 +724,12 @@ def gen_expr(self, expr, custom_tmp = None): if expr.sym.is_extern: return ir.Ident( ir_typ, - mangle_symbol(expr.sym) + cg_utils.mangle_symbol(expr.sym) if expr.sym.abi == sym.ABI.Rivet else expr.sym.name ) - return ir.Ident(ir_typ, mangle_symbol(expr.sym)) + return ir.Ident(ir_typ, cg_utils.mangle_symbol(expr.sym)) elif isinstance(expr.sym, sym.Func): - return ir.Ident(self.ir_type(expr.typ), mangle_symbol(expr.sym)) + return ir.Ident(self.ir_type(expr.typ), cg_utils.mangle_symbol(expr.sym)) elif expr.is_comptime: if expr.name == "_RIVET_COMMIT_": return self.gen_string_literal(utils.commit_hash()) @@ -846,11 +752,13 @@ def gen_expr(self, expr, custom_tmp = None): self.cur_fn.store_ptr( arg0, ir.Inst(ir.InstKind.LoadPtr, [arg1]) ) - elif expr.name == "vec": + elif expr.name == "dyn_array": typ_sym = expr.typ.symbol() if len(expr.args) == 2: - return self.empty_vec(typ_sym, self.gen_expr(expr.args[1])) - return self.empty_vec(typ_sym) + return self.empty_dyn_array( + typ_sym, self.gen_expr(expr.args[1]) + ) + return self.empty_dyn_array(typ_sym) elif expr.name == "as": arg1 = expr.args[1] arg1_is_voidptr = isinstance( @@ -1060,7 +968,7 @@ def gen_expr(self, expr, custom_tmp = None): ir.Inst( ir.InstKind.Call, [ ir.Name( - f"{mangle_symbol(expr_left_sym)}{len(ov_m)}{ov_m}M" + f"{cg_utils.mangle_symbol(expr_left_sym)}{len(ov_m)}{ov_m}M" ), left_operand, right_operand ] ) @@ -1092,7 +1000,7 @@ def gen_expr(self, expr, custom_tmp = None): elif typ_sym.kind == TypeKind.Enum: if expr.is_enum_variant: tmp = self.boxed_instance( - mangle_symbol(expr.enum_variant_sym), + cg_utils.mangle_symbol(expr.enum_variant_sym), expr.enum_variant_sym.id ) initted_fields = [] @@ -1164,7 +1072,7 @@ def gen_expr(self, expr, custom_tmp = None): tmp = custom_tmp elif typ_sym.is_boxed(): tmp = self.boxed_instance( - mangle_symbol(typ_sym), typ_sym.id + cg_utils.mangle_symbol(typ_sym), typ_sym.id ) else: tmp = ir.Ident( @@ -1228,7 +1136,7 @@ def gen_expr(self, expr, custom_tmp = None): id_value = ir.Inst( ir.InstKind.Call, [ ir.Name( - f"{mangle_symbol(left_sym)}17__index_of_vtbl__" + f"{cg_utils.mangle_symbol(left_sym)}17__index_of_vtbl__" ), ir.Selector( ir.UINT_T, self_expr, ir.Name("_idx_") @@ -1243,7 +1151,7 @@ def gen_expr(self, expr, custom_tmp = None): id_value = ir.Inst( ir.InstKind.Call, [ ir.Name( - f"{mangle_symbol(left_sym)}17__index_of_vtbl__" + f"{cg_utils.mangle_symbol(left_sym)}17__index_of_vtbl__" ), ir.Selector( ir.UINT_T, self_expr, ir.Name("_idx_") @@ -1258,7 +1166,7 @@ def gen_expr(self, expr, custom_tmp = None): ir.Inst( ir.InstKind.Add, [ ir.Name( - mangle_symbol(left_sym) + + cg_utils.mangle_symbol(left_sym) + "4VTBL" ), id_value ] @@ -1295,12 +1203,12 @@ def gen_expr(self, expr, custom_tmp = None): elif expr.sym.is_extern and expr.sym.abi != sym.ABI.Rivet and not expr.sym.has_body: name = ir.Name(expr.sym.name) else: - name = ir.Name(mangle_symbol(expr.sym)) + name = ir.Name(cg_utils.mangle_symbol(expr.sym)) args.append(name) if expr.sym.is_method: left_sym = expr.sym.self_typ.symbol() - if left_sym.kind == TypeKind.Vec: - expr.sym = self.comp.vec_sym[expr.sym.name] + if left_sym.kind == TypeKind.DynArray: + expr.sym = self.comp.dyn_array_sym[expr.sym.name] sym_rec_is_ref = expr.sym.self_is_mut or expr.sym.self_is_ptr receiver = expr.left.left if left_sym.kind == TypeKind.Trait and expr.sym.self_typ != receiver.typ: @@ -1334,7 +1242,7 @@ def gen_expr(self, expr, custom_tmp = None): arg_value = self.gen_expr_with_cast(fn_arg_typ, arg.expr) if expr.sym.is_method: left_sym = expr.left.left_typ.symbol() - if left_sym.kind == TypeKind.Vec and expr.sym.name == "push": + if left_sym.kind == TypeKind.DynArray and expr.sym.name == "push": if arg.typ.symbol().is_boxed(): arg_value = ir.Inst( ir.InstKind.GetRef, [arg_value], @@ -1372,9 +1280,11 @@ def gen_expr(self, expr, custom_tmp = None): ) args.append(self.variadic_args(vargs, var_arg.typ.typ)) else: - args.append(self.empty_vec(var_arg.typ.symbol())) + args.append(self.empty_dyn_array(var_arg.typ.symbol())) if expr.sym.ret_typ == self.comp.never_t: - self.gen_defer_stmts(scope = expr.scope, run_defer_previous = True) + self.gen_defer_stmts( + scope = expr.scope, run_defer_previous = True + ) inst = ir.Inst(ir.InstKind.Call, args) if expr.sym.ret_typ in self.void_types: self.cur_fn.add_inst(inst) @@ -1398,7 +1308,7 @@ def gen_expr(self, expr, custom_tmp = None): ir.IntLit(ir.UINT_T, str(size)) ] ) - elif expr.sym.is_method and expr.sym.name == "pop" and left_sym.kind == TypeKind.Vec: + elif expr.sym.is_method and expr.sym.name == "pop" and left_sym.kind == TypeKind.DynArray: ret_typ = self.ir_type(expr.sym.ret_typ) value = ir.Inst(ir.InstKind.Cast, [inst, ret_typ.ptr()]) if custom_tmp: @@ -1557,14 +1467,14 @@ def gen_expr(self, expr, custom_tmp = None): ) elif isinstance(expr.left_sym, sym.Func): return ir.Ident( - self.ir_type(expr.typ), mangle_symbol(expr.left_sym) + self.ir_type(expr.typ), cg_utils.mangle_symbol(expr.left_sym) ) elif isinstance( expr.field_sym, sym.Var ) and expr.field_sym.is_extern and expr.field_sym.abi != sym.ABI.Rivet: return ir.Ident(self.ir_type(expr.typ), expr.field_sym.name) return ir.Ident( - self.ir_type(expr.typ), mangle_symbol(expr.field_sym) + self.ir_type(expr.typ), cg_utils.mangle_symbol(expr.field_sym) ) old_inside_selector_expr = self.inside_selector_expr self.inside_selector_expr = True @@ -1619,7 +1529,7 @@ def gen_expr(self, expr, custom_tmp = None): if expr.is_arr: return self.default_value(expr.typ) tmp = ir.Ident(self.ir_type(expr.typ), self.cur_fn.local_name()) - self.cur_fn.alloca(tmp, self.empty_vec(typ_sym)) + self.cur_fn.alloca(tmp, self.empty_dyn_array(typ_sym)) return tmp elem_typ = typ_sym.info.elem_typ size, _ = self.comp.type_size(elem_typ) @@ -1682,7 +1592,7 @@ def gen_expr(self, expr, custom_tmp = None): end ] ) - elif s.kind == TypeKind.Vec: + elif s.kind == TypeKind.DynArray: if end == None: inst = ir.Inst( ir.InstKind.Call, [ @@ -1741,7 +1651,7 @@ def gen_expr(self, expr, custom_tmp = None): ir.InstKind.Call, [ir.Name("_R4core6string2atM"), left, idx], expr_typ_ir ) - elif s.kind == TypeKind.Vec: + elif s.kind == TypeKind.DynArray: expr_typ_ir2 = expr_typ_ir.ptr() value = ir.Inst( ir.InstKind.Cast, [ @@ -1938,15 +1848,15 @@ def gen_expr(self, expr, custom_tmp = None): left_sym = expr_left_typ.symbol() right_sym = expr.right.typ.symbol() contains_method = f"contains_{right_sym.id}" - right_is_vector = right_sym.kind == sym.TypeKind.Vec - if right_is_vector: + right_is_dyn_array = right_sym.kind == sym.TypeKind.DynArray + if right_is_dyn_array: full_name = f"_R4core8DynArray{len(contains_method)}{contains_method}" else: full_name = f"_R4core5Array{len(contains_method)}{contains_method}" if not right_sym.info.has_contains_method: right_sym.info.has_contains_method = True - if right_is_vector: - self_idx_ = ir.Ident(ir.VEC_T.ptr(True), "self") + if right_is_dyn_array: + self_idx_ = ir.Ident(ir.DYN_ARRAY_T.ptr(True), "self") elem_idx_ = ir.Ident( self.ir_type(expr_left_typ), "_elem_" ) @@ -1981,22 +1891,22 @@ def gen_expr(self, expr, custom_tmp = None): ir.Name("<"), inc_v, ir.Selector( ir.UINT_T, self_idx_, ir.Name("len") - ) if right_is_vector else + ) if right_is_dyn_array else ir.Ident(ir.UINT_T, "_len_") ] ), body_l, exit_l ) contains_decl.add_label(body_l) - if right_is_vector: + if right_is_dyn_array: cur_elem = ir.Inst( ir.InstKind.LoadPtr, [ ir.Inst( ir.InstKind.Cast, [ ir.Inst( ir.InstKind.Call, [ - ir. - Name("_R4core8DynArray7raw_getM"), - self_idx_, inc_v + ir.Name( + "_R4core8DynArray7raw_getM" + ), self_idx_, inc_v ] ), self.ir_type(expr_left_typ).ptr() @@ -2026,7 +1936,7 @@ def gen_expr(self, expr, custom_tmp = None): else: cond = ir.Inst( ir.InstKind.Call, [ - ir.Name(f"{mangle_symbol(left_sym)}4_eq_M"), + ir.Name(f"{cg_utils.mangle_symbol(left_sym)}4_eq_M"), cur_elem, elem_idx_ ] ) @@ -2040,7 +1950,7 @@ def gen_expr(self, expr, custom_tmp = None): contains_decl.add_ret(ir.IntLit(ir.BOOL_T, "0")) self.out_rir.decls.append(contains_decl) args = [ir.Name(full_name), right] - if not right_is_vector: + if not right_is_dyn_array: args.append(ir.IntLit(ir.UINT_T, str(right_sym.info.size))) args.append(left) call = ir.Inst(ir.InstKind.Call, args, ir.BOOL_T) @@ -2058,7 +1968,7 @@ def gen_expr(self, expr, custom_tmp = None): typ_sym = expr_left_typ.symbol() if expr.op.is_overloadable_op() and ( typ_sym.kind in ( - TypeKind.Array, TypeKind.Vec, TypeKind.String, + TypeKind.Array, TypeKind.DynArray, TypeKind.String, TypeKind.Struct ) or (typ_sym.kind == TypeKind.Enum and typ_sym.info.is_boxed) ) and not isinstance(expr_left_typ, type.Ptr): @@ -2085,7 +1995,7 @@ def gen_expr(self, expr, custom_tmp = None): ir.Inst( ir.InstKind.Call, [ ir.Name( - mangle_symbol(typ_sym) + + cg_utils.mangle_symbol(typ_sym) + f"{len(op_method)}{op_method}M" ), left if sym_is_boxed else ir.Inst(ir.InstKind.GetRef, [left]), @@ -2326,7 +2236,7 @@ def gen_expr(self, expr, custom_tmp = None): inst = ir.Inst( ir.InstKind.Call, [ ir.Name( - f"{mangle_symbol(p_typ_sym)}4_eq_M" + f"{cg_utils.mangle_symbol(p_typ_sym)}4_eq_M" ), match_expr, p_conv, ] ) @@ -2478,7 +2388,7 @@ def gen_left_assign(self, expr, right, assign_op): left_ir_typ = self.ir_type(expr.left_typ) left_sym = expr.left_typ.symbol() sym_is_boxed = left_sym.is_boxed() - if left_sym.kind == TypeKind.Vec and assign_op == Kind.Assign: + if left_sym.kind == TypeKind.DynArray and assign_op == Kind.Assign: rec = self.gen_expr_with_cast(expr.left_typ, expr.left) if not isinstance(left_ir_typ, ir.Pointer): rec = ir.Inst(ir.InstKind.GetRef, [rec]) @@ -2624,13 +2534,13 @@ def runtime_error(self, msg): self.cur_fn.add_call( "_R4core13runtime_errorF", [ self.gen_string_literal(utils.smart_quote(msg, False)), - self.empty_vec(self.comp.universe["[]core.Stringable"]) + self.empty_dyn_array(self.comp.universe["[]core.Stringable"]) ] ) def variadic_args(self, vargs, var_arg_typ_): if len(vargs) == 0: - return self.empty_vec(var_arg_typ_.typ.symbol()) + return self.empty_dyn_array(var_arg_typ_.typ.symbol()) elem_size, _ = self.comp.type_size(var_arg_typ_) return ir.Inst( ir.InstKind.Call, [ @@ -2670,8 +2580,8 @@ def default_value(self, typ, custom_tmp = None): return ir.ArrayLit( self.ir_type(typ), [self.default_value(typ_sym.info.elem_typ)] ) - elif typ_sym.kind == TypeKind.Vec: - return self.empty_vec(typ_sym) + elif typ_sym.kind == TypeKind.DynArray: + return self.empty_dyn_array(typ_sym) elif typ_sym.kind == TypeKind.Enum: if typ_sym.info.is_boxed and typ_sym.default_value: return self.gen_expr_with_cast(typ, typ_sym.default_value) @@ -2689,7 +2599,7 @@ def default_value(self, typ, custom_tmp = None): if custom_tmp: tmp = custom_tmp elif typ_sym.info.is_boxed: - tmp = self.boxed_instance(mangle_symbol(typ_sym), typ_sym.id) + tmp = self.boxed_instance(cg_utils.mangle_symbol(typ_sym), typ_sym.id) else: tmp = ir.Ident(self.ir_type(typ), self.cur_fn.local_name()) self.cur_fn.alloca(tmp) @@ -2709,7 +2619,7 @@ def default_value(self, typ, custom_tmp = None): return ir.NoneLit(ir.VOID_PTR_T) return None - def empty_vec(self, typ_sym, cap = None): + def empty_dyn_array(self, typ_sym, cap = None): elem_typ = typ_sym.info.elem_typ size, _ = self.comp.type_size(elem_typ) return ir.Inst( @@ -2777,7 +2687,7 @@ def trait_value(self, value, value_typ, trait_typ): value_sym = self.comp.comptime_number_to_type(value_typ).symbol() trait_sym = trait_typ.symbol() size, _ = self.comp.type_size(value_typ) - tmp = self.boxed_instance(mangle_symbol(trait_sym), 0) + tmp = self.boxed_instance(cg_utils.mangle_symbol(trait_sym), 0) is_ptr = isinstance(value.typ, ir.Pointer) for f in trait_sym.fields: f_typ = self.ir_type(f.typ) @@ -2797,7 +2707,7 @@ def trait_value(self, value, value_typ, trait_typ): if value_sym.kind == TypeKind.Trait: index = ir.Inst( ir.InstKind.Call, [ - ir.Name(f"{mangle_symbol(trait_sym)}17__index_of_vtbl__"), + ir.Name(f"{cg_utils.mangle_symbol(trait_sym)}17__index_of_vtbl__"), ir.Selector(ir.UINT_T, value, ir.Name("_idx_")) ], ir.UINT_T ) @@ -2824,7 +2734,7 @@ def boxed_enum_value( if custom_tmp: tmp = custom_tmp else: - tmp = self.boxed_instance(mangle_symbol(enum_sym), enum_sym.id) + tmp = self.boxed_instance(cg_utils.mangle_symbol(enum_sym), enum_sym.id) uint_t = ir.UINT_T variant_info = enum_sym.info.get_variant(variant_name) self.cur_fn.store( @@ -2857,7 +2767,7 @@ def boxed_enum_variant_with_fields_value( if custom_tmp: tmp = custom_tmp else: - tmp = self.boxed_instance(mangle_symbol(enum_sym), enum_sym.id) + tmp = self.boxed_instance(cg_utils.mangle_symbol(enum_sym), enum_sym.id) variant_info = enum_sym.info.get_variant(variant_name) self.cur_fn.store( ir.Selector(ir.UINT_T, tmp, ir.Name("_idx_")), @@ -2948,7 +2858,7 @@ def gen_guard_expr(self, expr, entry_label, exit_label, gen_cond = True): def ir_type(self, typ, gen_self_arg = False): if isinstance(typ, type.Result): - name = f"_R6Result{mangle_type(typ.typ)}" + name = f"_R6Result{cg_utils.mangle_type(typ.typ)}" if name not in self.generated_opt_res_types: is_void = typ.typ in self.void_types self.out_rir.structs.append( @@ -2970,7 +2880,7 @@ def ir_type(self, typ, gen_self_arg = False): elif isinstance(typ, type.Option): if typ.is_pointer(): return self.ir_type(typ.typ) - name = f"_R6Option{mangle_type(typ.typ)}" + name = f"_R6Option{cg_utils.mangle_type(typ.typ)}" if name not in self.generated_opt_res_types: is_void = typ.typ in self.void_types self.out_rir.structs.append( @@ -2998,16 +2908,16 @@ def ir_type(self, typ, gen_self_arg = False): return ir.Function(args, self.ir_type(typ.ret_typ)) elif isinstance(typ, type.Array): return ir.Array(self.ir_type(typ.typ), typ.size) - elif isinstance(typ, type.Vec): - return ir.VEC_T.ptr(True) + elif isinstance(typ, type.DynArray): + return ir.DYN_ARRAY_T.ptr(True) elif isinstance(typ, type.Ptr): inner_t = self.ir_type(typ.typ) if isinstance(inner_t, ir.Pointer) and inner_t.is_managed: return inner_t return ir.Pointer(inner_t) typ_sym = typ.symbol() - if typ_sym.kind == TypeKind.Vec: - return ir.VEC_T.ptr(True) + if typ_sym.kind == TypeKind.DynArray: + return ir.DYN_ARRAY_T.ptr(True) elif typ_sym.kind == TypeKind.Array: return ir.Array( self.ir_type(typ_sym.info.elem_typ), typ_sym.info.size @@ -3018,7 +2928,7 @@ def ir_type(self, typ, gen_self_arg = False): return ir.VOID_PTR_T elif typ_sym.kind == TypeKind.Enum: if typ_sym.info.is_boxed: - return ir.Type(mangle_symbol(typ_sym)).ptr(True) + return ir.Type(cg_utils.mangle_symbol(typ_sym)).ptr(True) return ir.Type(str(typ_sym.info.underlying_typ)) elif typ_sym.kind.is_primitive(): if typ_sym.name == "int": @@ -3026,7 +2936,7 @@ def ir_type(self, typ, gen_self_arg = False): if typ_sym.name == "uint": return ir.UINT_T return ir.Type(typ_sym.name) - res = ir.Type(mangle_symbol(typ_sym)) + res = ir.Type(cg_utils.mangle_symbol(typ_sym)) if typ_sym.is_boxed(): return res.ptr(True) return res @@ -3041,7 +2951,7 @@ def gen_types(self): for i, f in enumerate(ts.info.types): fields.append(ir.Field(f"f{i}", self.ir_type(f))) self.out_rir.structs.append( - ir.Struct(False, mangle_symbol(ts), fields) + ir.Struct(False, cg_utils.mangle_symbol(ts), fields) ) elif ts.kind == TypeKind.Enum: # TODO: in the self-hosted compiler calculate the enum value here @@ -3049,7 +2959,7 @@ def gen_types(self): if ts.info.is_boxed: self.out_rir.structs.append( ir.Struct( - False, mangle_symbol(ts), [ + False, cg_utils.mangle_symbol(ts), [ ir.Field("_rc_", ir.UINT_T), ir.Field("_idx_", ir.UINT_T), ir.Field("obj", ir.VOID_PTR_T) @@ -3057,7 +2967,7 @@ def gen_types(self): ) ) elif ts.kind == TypeKind.Trait: - ts_name = mangle_symbol(ts) + ts_name = cg_utils.mangle_symbol(ts) fields = [ ir.Field("_rc_", ir.UINT_T), ir.Field("_idx_", ir.UINT_T), @@ -3100,9 +3010,9 @@ def gen_types(self): m.name ] if m.name in OVERLOADABLE_OPERATORS_STR else m.name if ts_method := its.find(m.name): - map[method_name] = mangle_symbol(ts_method) + map[method_name] = cg_utils.mangle_symbol(ts_method) else: - map[method_name] = mangle_symbol(m) + map[method_name] = cg_utils.mangle_symbol(m) funcs.append(map) index_of_vtbl.append((its.qualname(), its.id, idx)) if len(funcs) > 0 and ts.info.has_objects: @@ -3117,7 +3027,7 @@ def gen_types(self): ) index_of_vtbl_fn = ir.FuncDecl( False, ast.Annotations(), False, - mangle_symbol(ts) + "17__index_of_vtbl__", + cg_utils.mangle_symbol(ts) + "17__index_of_vtbl__", [ir.Ident(ir.UINT_T, "self")], False, ir.UINT_T, False ) for child_name, child_idx_, child_idx_x in index_of_vtbl: @@ -3140,13 +3050,15 @@ def gen_types(self): index_of_vtbl_fn.add_label(l2) index_of_vtbl_fn.add_ret(ir.IntLit(ir.UINT_T, "0")) self.out_rir.decls.append(index_of_vtbl_fn) - elif ts.kind in (TypeKind.Struct, TypeKind.String, TypeKind.Vec): + elif ts.kind in ( + TypeKind.Struct, TypeKind.String, TypeKind.DynArray + ): fields = [ir.Field("_rc_", ir.UINT_T) ] if ts.info.is_boxed else [] for f in ts.full_fields(): fields.append(ir.Field(f.name, self.ir_type(f.typ))) self.out_rir.structs.append( - ir.Struct(ts.info.is_opaque, mangle_symbol(ts), fields) + ir.Struct(ts.info.is_opaque, cg_utils.mangle_symbol(ts), fields) ) def get_type_symbols(self, root): @@ -3154,7 +3066,8 @@ def get_type_symbols(self, root): for s in root.syms: if isinstance(s, sym.Type): if not ( - s.kind in (TypeKind.Vec, TypeKind.Alias, TypeKind.Never) + s.kind + in (TypeKind.DynArray, TypeKind.Alias, TypeKind.Never) or s.kind.is_primitive() ): ts.append(s) @@ -3165,21 +3078,21 @@ def sort_type_symbols(self, tss): dg = utils.DepGraph() typ_names = [] for ts in tss: - ts.mangled_name = mangle_symbol(ts) + ts.mangled_name = cg_utils.mangle_symbol(ts) typ_names.append(ts.mangled_name) for ts in tss: field_deps = [] if ts.kind == TypeKind.Array: - dep = mangle_symbol(ts.info.elem_typ.symbol()) + dep = cg_utils.mangle_symbol(ts.info.elem_typ.symbol()) if dep in typ_names: field_deps.append(dep) - elif ts.kind == TypeKind.Vec: - dep = mangle_symbol(ts.info.elem_typ.symbol()) + elif ts.kind == TypeKind.DynArray: + dep = cg_utils.mangle_symbol(ts.info.elem_typ.symbol()) if dep in typ_names: field_deps.append(dep) elif ts.kind == TypeKind.Tuple: for f in ts.info.types: - dep = mangle_symbol(f.symbol()) + dep = cg_utils.mangle_symbol(f.symbol()) if dep not in typ_names or dep in field_deps or isinstance( f, type.Option ): @@ -3187,12 +3100,12 @@ def sort_type_symbols(self, tss): field_deps.append(dep) elif ts.kind == TypeKind.Trait: for base in ts.info.bases: - dep = mangle_symbol(base) + dep = cg_utils.mangle_symbol(base) if dep not in typ_names or dep in field_deps: continue field_deps.append(dep) for f in ts.fields: - dep = mangle_symbol(f.typ.symbol()) + dep = cg_utils.mangle_symbol(f.typ.symbol()) if dep not in typ_names or dep in field_deps or isinstance( f.typ, type.Option ): @@ -3200,12 +3113,12 @@ def sort_type_symbols(self, tss): field_deps.append(dep) elif ts.kind == TypeKind.Struct: for base in ts.info.bases: - dep = mangle_symbol(base) + dep = cg_utils.mangle_symbol(base) if dep not in typ_names or dep in field_deps: continue field_deps.append(dep) for f in ts.fields: - dep = mangle_symbol(f.typ.symbol()) + dep = cg_utils.mangle_symbol(f.typ.symbol()) if dep not in typ_names or dep in field_deps or isinstance( f.typ, type.Option ): @@ -3241,4 +3154,4 @@ def decode_escape(self, ch): return "\t" elif code == "v": return "\v" - return ch + return ch \ No newline at end of file diff --git a/rivetc/src/codegen/cg_utils.py b/rivetc/src/codegen/cg_utils.py new file mode 100644 index 000000000..4fca34dc4 --- /dev/null +++ b/rivetc/src/codegen/cg_utils.py @@ -0,0 +1,105 @@ +# Copyright (C) 2023 The Rivet Developers. All rights reserved. +# Use of this source code is governed by an MIT license that can +# be found in the LICENSE file. + +import os + +from ..sym import TypeKind +from .. import ast, sym, type +from ..token import OVERLOADABLE_OPERATORS_STR + +def prefix_type(tt): + prefix = "" + if isinstance(tt, type.Ptr): + _t = tt + while isinstance(_t, type.Ptr): + prefix += "ptr_" + if _t.is_mut: + prefix += "mut_" + _t = _t.typ + prefix += prefix_type(tt.typ) + elif isinstance(tt, type.Ptr): + prefix += "ref_" + if tt.is_mut: + prefix += "mut_" + prefix += prefix_type(tt.typ) + elif isinstance(tt, type.Option): + prefix += "opt_" + prefix_type(tt.typ) + return prefix + +def mangle_type(typ): + if isinstance(typ, type.Func): + s = "fn_" + if typ.is_unsafe: + s += "unsafe_" + if typ.is_extern: + s += f"extern_{typ.abi}_" + if typ.is_method: + s += "m_" + if typ.self_is_mut: + s += "_sm_" + elif typ.self_is_ptr: + s += "_sr_" + if typ.is_variadic: + s += "_v_" + s += f"_args{len(typ.args)}" + return s + return f"{prefix_type(typ)}{mangle_symbol(typ.symbol())}" + +def mangle_symbol(s): + if len(s.mangled_name) > 0: + return s.mangled_name + res = [] + root = s + while True: + if s.is_universe: + break + if isinstance(s, sym.Mod): + s.mangled_name = "".join([ + f"{len(n)}{n}" for n in s.name.split(".") + ]) + res.insert(0, s.mangled_name) + elif isinstance(s, sym.Type): + if s.kind == TypeKind.Tuple: + name = "Tuple_" + for i, tt in enumerate(s.info.types): + name += mangle_type(tt) + if i < len(s.info.types) - 1: + name += "_" + name = f"{len(name)}{name}" + res.insert(0, name) + s.mangled_name = name + elif s.kind == TypeKind.DynArray: + res.insert(0, "4core8DynArray") + s.mangled_name = "_R4core8DynArray" + elif s.kind == TypeKind.Array: + name = f"Array_{mangle_type(s.info.elem_typ)}_{s.info.size}" + name = f"{len(name)}{name}" + res.insert(0, name) + s.mangled_name = name + elif s.kind == TypeKind.String: + res.insert(0, "4core6string") + s.mangled_name = "_R4core6string" + else: + res.insert(0, f"{len(s.name)}{s.name}") + elif s.name in OVERLOADABLE_OPERATORS_STR: + name = OVERLOADABLE_OPERATORS_STR[s.name] + name = f"{len(name)}{name}" + res.insert(0, name) + s.mangled_name = name + else: + res.insert(0, f"{len(s.name)}{s.name}") + if s.parent == None: + break + else: + s = s.parent + res.insert(0, "_R") + + if isinstance(root, sym.Func): + if root.is_method: + res.append("M") + else: + res.append("F") + + root.mangled_name = "".join(res) + return root.mangled_name diff --git a/rivetc/src/codegen/ir.py b/rivetc/src/codegen/ir.py index 3447fa0fb..f4d895271 100644 --- a/rivetc/src/codegen/ir.py +++ b/rivetc/src/codegen/ir.py @@ -86,7 +86,7 @@ def __eq__(self, other): Float64_T = Type("float64") INT_T = Type("ri_int") UINT_T = Type("ri_uint") -VEC_T = Type("_R4core8DynArray") +DYN_ARRAY_T = Type("_R4core8DynArray") STRING_T = Type("_R4core6string") TEST_T = Type("_R4core4Test") TEST_RUNNER_T = Type("_R4core10TestRunner") @@ -599,4 +599,4 @@ def __repr__(self): return f"{self.kind} {', '.join([str(arg) for arg in self.args])}" def __str__(self): - return self.__repr__() + return self.__repr__() \ No newline at end of file diff --git a/rivetc/src/parser.py b/rivetc/src/parser.py index 3be27b839..448aa1559 100644 --- a/rivetc/src/parser.py +++ b/rivetc/src/parser.py @@ -801,10 +801,12 @@ def parse_primary_expr(self): name = self.parse_name() self.expect(Kind.Lparen) args = [] - vec_is_mut = False - if name in ("vec", "as", "size_of", "align_of"): + dyn_array_is_mut = False + if name in ("dyn_array", "as", "size_of", "align_of"): pos = self.tok.pos - vec_is_mut = name == "vec" and self.accept(Kind.KwMut) + dyn_array_is_mut = name == "dyn_array" and self.accept( + Kind.KwMut + ) args.append(ast.TypeNode(self.parse_type(), pos)) if self.tok.kind != Kind.Rparen: self.expect(Kind.Comma) @@ -815,7 +817,7 @@ def parse_primary_expr(self): break self.expect(Kind.Rparen) expr = ast.BuiltinCallExpr(name, args, expr.pos) - expr.vec_is_mut = vec_is_mut + expr.dyn_array_is_mut = dyn_array_is_mut else: # builtin variable expr = self.parse_ident(True) elif self.tok.kind == Kind.Dot and self.peek_tok.kind == Kind.Name: @@ -1291,7 +1293,7 @@ def parse_type(self): report.help("use an indexable pointer instead (`[&]T`)") return type.Ptr(self.parse_type(), is_mut) elif self.accept(Kind.Lbracket): - # arrays or vectors + # arrays or dynamic arrays if self.tok.kind != Kind.Rbracket: # indexable pointers if self.accept(Kind.Amp): @@ -1305,7 +1307,7 @@ def parse_type(self): return type.Array(self.parse_type(), size, is_mut) self.expect(Kind.Rbracket) is_mut = self.accept(Kind.KwMut) - return type.Vec(self.parse_type(), is_mut) + return type.DynArray(self.parse_type(), is_mut) elif self.accept(Kind.Lparen): # tuples types = [] diff --git a/rivetc/src/register.py b/rivetc/src/register.py index 3d3c670fa..23dc90b65 100644 --- a/rivetc/src/register.py +++ b/rivetc/src/register.py @@ -127,7 +127,7 @@ def walk_decls(self, decls): ) ) if self.is_core_mod and decl.name == "DynArray": - self.comp.vec_sym = decl.sym + self.comp.dyn_array_sym = decl.sym self.sym = decl.sym self.walk_decls(decl.decls) except utils.CompilerError as e: @@ -245,4 +245,4 @@ def check_imported_symbol(self, s, pos): report.error( f"another symbol with the name `{s.name}` already exists", pos ) - report.help("you can use `as` to change the name of the import") + report.help("you can use `as` to change the name of the import") \ No newline at end of file diff --git a/rivetc/src/resolver.py b/rivetc/src/resolver.py index 24acb8ca5..f37517693 100644 --- a/rivetc/src/resolver.py +++ b/rivetc/src/resolver.py @@ -479,7 +479,7 @@ def resolve_type(self, typ): elem_sym = typ.typ.symbol() if elem_sym.kind == type.TypeKind.Trait: elem_sym.info.has_objects = True - typ.resolve(self.comp.universe.add_or_get_vec(typ.typ)) + typ.resolve(self.comp.universe.add_or_get_dyn_array(typ.typ)) return True elif isinstance(typ, type.Array): if self.resolve_type(typ.typ): @@ -499,10 +499,12 @@ def resolve_type(self, typ): report.error( "array size cannot use non-constant value", typ.size.pos ) - elif isinstance(typ, type.Vec): + elif isinstance(typ, type.DynArray): if self.resolve_type(typ.typ): typ.resolve( - self.comp.universe.add_or_get_vec(typ.typ, typ.is_mut) + self.comp.universe.add_or_get_dyn_array( + typ.typ, typ.is_mut + ) ) return True elif isinstance(typ, type.Tuple): diff --git a/rivetc/src/sym.py b/rivetc/src/sym.py index 85b9f64e9..45475a0e9 100644 --- a/rivetc/src/sym.py +++ b/rivetc/src/sym.py @@ -248,7 +248,7 @@ def add_or_get_array(self, elem_typ, size, is_mut = False): ) ) - def add_or_get_vec(self, elem_typ, is_mut = False): + def add_or_get_dyn_array(self, elem_typ, is_mut = False): if is_mut: unique_name = f"[]mut {elem_typ.qualstr()}" else: @@ -256,44 +256,44 @@ def add_or_get_vec(self, elem_typ, is_mut = False): if sym := self.find(unique_name): return sym from .type import Type as type_Type - vec_sym = Type( - True, unique_name, TypeKind.Vec, info = VecInfo(elem_typ, is_mut), + dyn_array_sym = Type( + True, unique_name, TypeKind.DynArray, info = info(elem_typ, is_mut), fields = [ Field("len", False, True, type_Type(self[14])), Field("cap", False, True, type_Type(self[14])) ] ) - vec_sym.add( + dyn_array_sym.add( Func( ABI.Rivet, True, False, False, True, False, "push", [Arg("value", False, elem_typ, None, False, NO_POS)], type_Type(self[0]), False, True, NO_POS, True, False, - type_Type(vec_sym) + type_Type(dyn_array_sym) ) ) - vec_sym.add( + dyn_array_sym.add( Func( ABI.Rivet, True, False, False, True, False, "pop", [], elem_typ, - False, True, NO_POS, True, False, type_Type(vec_sym) + False, True, NO_POS, True, False, type_Type(dyn_array_sym) ) ) - vec_sym.add( + dyn_array_sym.add( Func( ABI.Rivet, True, False, False, True, False, "clone", [], - type_Type(vec_sym), False, True, NO_POS, False, False, - type_Type(vec_sym) + type_Type(dyn_array_sym), False, True, NO_POS, False, False, + type_Type(dyn_array_sym) ) ) - if vector_sym := self.find("core").find("DynArray"): - if is_empty_m := vector_sym.find("is_empty"): - vec_sym.add(is_empty_m) - if delete_m := vector_sym.find("delete"): - vec_sym.add(delete_m) - if trim_m := vector_sym.find("trim"): - vec_sym.add(trim_m) - if clear_m := vector_sym.find("clear"): - vec_sym.add(clear_m) - return self.add_and_return(vec_sym) + if core_dyn_array_sym := self.find("core").find("DynArray"): + if is_empty_m := core_dyn_array_sym.find("is_empty"): + dyn_array_sym.add(is_empty_m) + if delete_m := core_dyn_array_sym.find("delete"): + dyn_array_sym.add(delete_m) + if trim_m := core_dyn_array_sym.find("trim"): + dyn_array_sym.add(trim_m) + if clear_m := core_dyn_array_sym.find("clear"): + dyn_array_sym.add(clear_m) + return self.add_and_return(dyn_array_sym) def add_or_get_tuple(self, types): unique_name = f"({', '.join([t.qualstr() for t in types])})" @@ -358,7 +358,7 @@ class TypeKind(Enum): String = auto_enum() Alias = auto_enum() Array = auto_enum() - Vec = auto_enum() + DynArray = auto_enum() Tuple = auto_enum() Enum = auto_enum() Trait = auto_enum() @@ -419,8 +419,8 @@ def __repr__(self): return "alias" elif self == TypeKind.Array: return "array" - elif self == TypeKind.Vec: - return "vector" + elif self == TypeKind.DynArray: + return "dynamic array" elif self == TypeKind.Tuple: return "tuple" elif self == TypeKind.Trait: @@ -450,7 +450,7 @@ def __init__(self, elem_typ, size, is_mut): self.is_mut = is_mut self.has_contains_method = False -class VecInfo: +class info: def __init__(self, elem_typ, is_mut): self.elem_typ = elem_typ self.is_mut = is_mut @@ -604,7 +604,7 @@ def is_boxed(self): return self.info.is_boxed elif isinstance(self.info, StructInfo): return self.info.is_boxed - return self.kind in (TypeKind.Trait, TypeKind.String, TypeKind.Vec) + return self.kind in (TypeKind.Trait, TypeKind.String, TypeKind.DynArray) def is_primitive(self): if self.kind == TypeKind.Enum: @@ -700,4 +700,4 @@ def universe(): ) ) - return uni + return uni \ No newline at end of file diff --git a/rivetc/src/type.py b/rivetc/src/type.py index bf7d88d1a..d52b1f676 100644 --- a/rivetc/src/type.py +++ b/rivetc/src/type.py @@ -17,7 +17,7 @@ def store(self, val): class TBase: def symbol(self): - if isinstance(self, (Vec, Array, Tuple, Variadic)): + if isinstance(self, (DynArray, Array, Tuple, Variadic)): return self.sym elif isinstance(self, Func): return self.info() @@ -33,7 +33,7 @@ def unalias(self): elif isinstance(self, Tuple): for t in self.types: t.unalias() - elif isinstance(self, (Array, Vec, Ptr, Variadic)): + elif isinstance(self, (Array, DynArray, Ptr, Variadic)): self.typ.unalias() elif isinstance(self, Type): if self.is_resolved() and self.sym.kind == TypeKind.Alias: @@ -128,7 +128,7 @@ def __str__(self): return f"[&]{self.typ}" return f"&{self.typ}" -class Vec(TBase): +class DynArray(TBase): def __init__(self, typ, is_mut): self.typ = typ self.is_mut = is_mut @@ -143,7 +143,7 @@ def qualstr(self): return f"[]{self.typ.qualstr()}" def __eq__(self, other): - if not isinstance(other, Vec): + if not isinstance(other, DynArray): return False return self.typ == other.typ and self.is_mut == other.is_mut diff --git a/tests/gen_b_out_files.py b/tests/gen_b_out_files.py index 96998a171..20e820c05 100644 --- a/tests/gen_b_out_files.py +++ b/tests/gen_b_out_files.py @@ -14,7 +14,7 @@ res = utils.run_process(sys.executable, "rivetc", file) if res.exit_code != 0: utils.eprint(f"[OK] {file}") - with open(out_name, "w", encoding = 'UTF-8') as f: + with open(out_name, "w", encoding='UTF-8') as f: f.write(res.err) else: utils.eprint(f"[BAD: exit_code == 0] {file}") diff --git a/tests/gen_out_files.py b/tests/gen_out_files.py index a712c8889..814ea83e7 100644 --- a/tests/gen_out_files.py +++ b/tests/gen_out_files.py @@ -14,7 +14,7 @@ res = utils.run_process("./rivet", "check", "--show-color=false", file) if res.exit_code != 0: utils.eprint(f"[OK] {file}") - with open(out_name, "w", encoding = 'UTF-8') as f: + with open(out_name, "w", encoding='UTF-8') as f: f.write(res.err) else: utils.eprint(f"[BAD: exit_code == 0] {file}") diff --git a/tests/run_b_invalid_tests.py b/tests/run_b_invalid_tests.py index 7f69118a0..86bf5e205 100644 --- a/tests/run_b_invalid_tests.py +++ b/tests/run_b_invalid_tests.py @@ -5,6 +5,7 @@ from os import path import glob, sys, os, utils + def run_fail_tests(): ok, fail, skip = 0, 0, 0 exit_code = 0 @@ -14,7 +15,7 @@ def run_fail_tests(): start = f" [{i+1}/{len(FAIL_FILES)}]" res = utils.run_process(sys.executable, "rivetc", file) try: - outf = open(file.replace(".ri", ".out"), encoding = 'UTF-8').read() + outf = open(file.replace(".ri", ".out"), encoding='UTF-8').read() if outf.strip() == res.err: utils.eprint(start, file, utils.bold(utils.green("-> OK"))) ok += 1 @@ -32,20 +33,20 @@ def run_fail_tests(): utils.eprint("Exit code: 0") except FileNotFoundError: utils.eprint( - utils.bold(utils.yellow("-> SKIP (.out file not found)")), file - ) + utils.bold(utils.yellow("-> SKIP (.out file not found)")), + file) skip += 1 - utils.eprint(utils.bold("Summary for all tests: "), end = "") + utils.eprint(utils.bold("Summary for all tests: "), end="") if ok > 0: - utils.eprint(utils.bold(utils.green(f"{ok} passed")) + ", ", end = "") + utils.eprint(utils.bold(utils.green(f"{ok} passed")) + ", ", end="") if fail > 0: - utils.eprint(utils.bold(utils.red(f"{fail} failed")) + ", ", end = "") + utils.eprint(utils.bold(utils.red(f"{fail} failed")) + ", ", end="") if skip > 0: - utils.eprint( - utils.bold(utils.yellow(f"{skip} skipped")) + ", ", end = "" - ) + utils.eprint(utils.bold(utils.yellow(f"{skip} skipped")) + ", ", + end="") utils.eprint(utils.bold(f"{len(FAIL_FILES)} total.")) return exit_code + exit(run_fail_tests()) diff --git a/tests/run_invalid_tests.py b/tests/run_invalid_tests.py index 8ee120045..0ad3e722b 100644 --- a/tests/run_invalid_tests.py +++ b/tests/run_invalid_tests.py @@ -5,6 +5,7 @@ from os import path import glob, sys, os, utils + def run_fail_tests(): ok, fail, skip = 0, 0, 0 exit_code = 0 @@ -20,7 +21,7 @@ def run_fail_tests(): start = f" [{i+1}/{len(FAIL_FILES)}]" res = utils.run_process("./rivet", "check", "--show-color=false", file) try: - outf = open(file.replace(".ri", ".out"), encoding = 'UTF-8').read() + outf = open(file.replace(".ri", ".out"), encoding='UTF-8').read() if outf.strip() == res.err: utils.eprint(start, file, utils.bold(utils.green("-> OK"))) ok += 1 @@ -39,20 +40,19 @@ def run_fail_tests(): except FileNotFoundError: utils.eprint( start, file, - utils.bold(utils.yellow("-> SKIP (.out file not found)")) - ) + utils.bold(utils.yellow("-> SKIP (.out file not found)"))) skip += 1 - utils.eprint(utils.bold("Summary for all tests: "), end = "") + utils.eprint(utils.bold("Summary for all tests: "), end="") if ok > 0: - utils.eprint(utils.bold(utils.green(f"{ok} passed")) + ", ", end = "") + utils.eprint(utils.bold(utils.green(f"{ok} passed")) + ", ", end="") if fail > 0: - utils.eprint(utils.bold(utils.red(f"{fail} failed")) + ", ", end = "") + utils.eprint(utils.bold(utils.red(f"{fail} failed")) + ", ", end="") if skip > 0: - utils.eprint( - utils.bold(utils.yellow(f"{skip} skipped")) + ", ", end = "" - ) + utils.eprint(utils.bold(utils.yellow(f"{skip} skipped")) + ", ", + end="") utils.eprint(utils.bold(f"{len(FAIL_FILES)} total.")) return exit_code + exit(run_fail_tests()) diff --git a/tests/utils.py b/tests/utils.py index 22713f853..631e4decf 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -4,49 +4,61 @@ import os, sys, subprocess + def filename(path): return os.path.splitext(os.path.basename(path))[0] -def eprint(*s, end = "\n"): - print(*s, end = end, file = sys.stderr) + +def eprint(*s, end="\n"): + print(*s, end=end, file=sys.stderr) + class ProcessResult: + def __init__(self, out, err, exit_code): self.out = out self.err = err self.exit_code = exit_code + def run_process(*args): - res = subprocess.run(args, capture_output = True) + res = subprocess.run(args, capture_output=True) return ProcessResult( - res.stdout.decode(encoding = 'UTF-8').strip(), - res.stderr.decode(encoding = 'UTF-8').strip(), res.returncode - ) + res.stdout.decode(encoding='UTF-8').strip(), + res.stderr.decode(encoding='UTF-8').strip(), res.returncode) + def supports_escape_sequences(fd): if os.getenv("TERM") == "dumb": return False return os.isatty(fd) > 0 + def can_show_color_on_stdout(): return supports_escape_sequences(1) + def can_show_color_on_stderr(): return supports_escape_sequences(2) + def format(msg, open, close): if not (can_show_color_on_stdout() and can_show_color_on_stderr()): return msg return f"\x1b[{open}m{msg}\x1b[{close}m" + def red(msg): return format(msg, "91", "39") + def yellow(msg): return format(msg, "33", "39") + def green(msg): return format(msg, "32", "39") + def bold(msg): return format(msg, "1", "22") diff --git a/tests/valid/src/dynamic_array.ri b/tests/valid/src/dynamic_array.ri new file mode 100644 index 000000000..8f377f262 --- /dev/null +++ b/tests/valid/src/dynamic_array.ri @@ -0,0 +1,24 @@ +test "dynamic array from fixed array" { + arr := [1, 2, 3]!; + mut dyn_array := arr[..]; + dyn_array.push(2); + @assert(dyn_array.len == 4); + + dyn_array2 := dyn_array.clone(); + @assert(dyn_array2.len == 4); + @assert(dyn_array == dyn_array2); +} + +test "`@dyn_array` builtin function" { + { + mut da := @dyn_array(int32); + da.push(5); + @assert(da[0] == 5); + } + { + mut da := @dyn_array(int32, 2); + da.push(10); + @assert(da.cap == 2); + @assert(da[0] == 10); + } +} diff --git a/tests/valid/src/for_stmt.ri b/tests/valid/src/for_stmt.ri index 294cf905e..beb48f0eb 100644 --- a/tests/valid/src/for_stmt.ri +++ b/tests/valid/src/for_stmt.ri @@ -6,7 +6,7 @@ test "`for` statement with array" { @assert(sum == 55); } -test "`for` statement with vector" { +test "`for` statement with dynamic array" { mut sum := 0; for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] { sum += i; diff --git a/tests/valid/src/operator_in.ri b/tests/valid/src/operator_in.ri index 868a233e8..b8a31e810 100644 --- a/tests/valid/src/operator_in.ri +++ b/tests/valid/src/operator_in.ri @@ -9,13 +9,13 @@ test "operator `!in` with arrays" { @assert("Rivet" !in ["Hello", "World"]!); } -test "operator `in` with vectors" { +test "operator `in` with dynamic arrays" { @assert(true in [true, false, true]); @assert(1 in [1, 2, 3]); @assert("Hello" in ["Hello", "World"]); } -test "operator `!in` with vectors" { +test "operator `!in` with dynamic arrays" { @assert(5 !in [1, 2, 3]); @assert("Rivet" !in ["Hello", "World"]); } diff --git a/tests/valid/src/overloadable_operators.ri b/tests/valid/src/overloadable_operators.ri index 40c59cfb0..20e203420 100644 --- a/tests/valid/src/overloadable_operators.ri +++ b/tests/valid/src/overloadable_operators.ri @@ -1,25 +1,25 @@ -struct Vec { +struct DynArray { x: int32; y: int32; - func +(&self, other: &Vec) -> Vec { - return Vec(self.x + other.x, self.y + other.y); + func +(&self, other: &DynArray) -> DynArray { + return DynArray(self.x + other.x, self.y + other.y); } - func -(&self, other: &Vec) -> Vec { - return Vec(self.x - other.x, self.y - other.y); + func -(&self, other: &DynArray) -> DynArray { + return DynArray(self.x - other.x, self.y - other.y); } - func *(&self, other: &Vec) -> Vec { - return Vec(self.x * other.x, self.y * other.y); + func *(&self, other: &DynArray) -> DynArray { + return DynArray(self.x * other.x, self.y * other.y); } - func /(&self, other: &Vec) -> Vec { - return Vec(self.x / other.x, self.y / other.y); + func /(&self, other: &DynArray) -> DynArray { + return DynArray(self.x / other.x, self.y / other.y); } } -var vec := Vec(2, 2); +var vec := DynArray(2, 2); test "overloadable operators: +" { mut v1 := vec; diff --git a/tests/valid/src/vector.ri b/tests/valid/src/vector.ri deleted file mode 100644 index 2312c2382..000000000 --- a/tests/valid/src/vector.ri +++ /dev/null @@ -1,24 +0,0 @@ -test "vector from array" { - arr := [1, 2, 3]!; - mut vec := arr[..]; - vec.push(2); - @assert(vec.len == 4); - - vec2 := vec.clone(); - @assert(vec2.len == 4); - @assert(vec == vec2); -} - -test "`@vec` builtin function" { - { - mut v := @vec(int32); - v.push(5); - @assert(v[0] == 5); - } - { - mut v := @vec(int32, 2); - v.push(10); - @assert(v.cap == 2); - @assert(v[0] == 10); - } -}