remove implicit cast from T to *const T

closes #1465
This commit is contained in:
Andrew Kelley 2018-10-15 18:23:47 -04:00
parent 378d3e4403
commit d5648d2640
No known key found for this signature in database
GPG Key ID: 4E7CD66038A4D47C
29 changed files with 112 additions and 270 deletions

View File

@ -121,7 +121,7 @@ pub fn build(b: *Builder) !void {
test_step.dependOn(docs_step);
}
fn dependOnLib(lib_exe_obj: var, dep: *const LibraryDep) void {
fn dependOnLib(lib_exe_obj: var, dep: LibraryDep) void {
for (dep.libdirs.toSliceConst()) |lib_dir| {
lib_exe_obj.addLibPath(lib_dir);
}

View File

@ -191,7 +191,7 @@ const Tokenizer = struct.{
line_end: usize,
};
fn getTokenLocation(self: *Tokenizer, token: *const Token) Location {
fn getTokenLocation(self: *Tokenizer, token: Token) Location {
var loc = Location.{
.line = 0,
.column = 0,
@ -216,7 +216,7 @@ const Tokenizer = struct.{
}
};
fn parseError(tokenizer: *Tokenizer, token: *const Token, comptime fmt: []const u8, args: ...) error {
fn parseError(tokenizer: *Tokenizer, token: Token, comptime fmt: []const u8, args: ...) error {
const loc = tokenizer.getTokenLocation(token);
warn("{}:{}:{}: error: " ++ fmt ++ "\n", tokenizer.source_file_name, loc.line + 1, loc.column + 1, args);
if (loc.line_start <= loc.line_end) {
@ -239,7 +239,7 @@ fn parseError(tokenizer: *Tokenizer, token: *const Token, comptime fmt: []const
return error.ParseError;
}
fn assertToken(tokenizer: *Tokenizer, token: *const Token, id: Token.Id) !void {
fn assertToken(tokenizer: *Tokenizer, token: Token, id: Token.Id) !void {
if (token.id != id) {
return parseError(tokenizer, token, "expected {}, found {}", @tagName(id), @tagName(token.id));
}

View File

@ -1905,7 +1905,7 @@ const Vec3 = struct.{
};
}
pub fn dot(self: *const Vec3, other: *const Vec3) f32 {
pub fn dot(self: Vec3, other: Vec3) f32 {
return self.x * other.x + self.y * other.y + self.z * other.z;
}
};
@ -2243,8 +2243,8 @@ const Variant = union(enum).{
Int: i32,
Bool: bool,
fn truthy(self: *const Variant) bool {
return switch (self.*) {
fn truthy(self: Variant) bool {
return switch (self) {
Variant.Int => |x_int| x_int != 0,
Variant.Bool => |x_bool| x_bool,
};
@ -4040,9 +4040,6 @@ test "float widening" {
{#header_open|Implicit Cast: undefined#}
<p>TODO</p>
{#header_close#}
{#header_open|Implicit Cast: T to *const T#}
<p>TODO</p>
{#header_close#}
{#header_close#}
{#header_open|Explicit Casts#}

View File

@ -658,7 +658,7 @@ fn cmdFmt(allocator: *Allocator, args: []const []const u8) !void {
const main_handle = try async<allocator> asyncFmtMainChecked(
&result,
&loop,
flags,
&flags,
color,
);
defer cancel main_handle;

View File

@ -9758,46 +9758,6 @@ static IrInstruction *ir_analyze_err_wrap_code(IrAnalyze *ira, IrInstruction *so
return result;
}
static IrInstruction *ir_analyze_cast_ref(IrAnalyze *ira, IrInstruction *source_instr,
IrInstruction *value, ZigType *wanted_type)
{
if (instr_is_comptime(value)) {
ConstExprValue *val = ir_resolve_const(ira, value, UndefBad);
if (!val)
return ira->codegen->invalid_instruction;
IrInstructionConst *const_instruction = ir_create_instruction<IrInstructionConst>(&ira->new_irb,
source_instr->scope, source_instr->source_node);
const_instruction->base.value.type = wanted_type;
const_instruction->base.value.special = ConstValSpecialStatic;
const_instruction->base.value.data.x_ptr.special = ConstPtrSpecialRef;
const_instruction->base.value.data.x_ptr.data.ref.pointee = val;
return &const_instruction->base;
}
if (value->id == IrInstructionIdLoadPtr) {
IrInstructionLoadPtr *load_ptr_inst = (IrInstructionLoadPtr *)value;
ConstCastOnly const_cast_result = types_match_const_cast_only(ira, wanted_type,
load_ptr_inst->ptr->value.type, source_instr->source_node, false);
if (const_cast_result.id == ConstCastResultIdInvalid)
return ira->codegen->invalid_instruction;
if (const_cast_result.id == ConstCastResultIdOk)
return load_ptr_inst->ptr;
}
IrInstruction *new_instruction = ir_build_ref(&ira->new_irb, source_instr->scope,
source_instr->source_node, value, true, false);
new_instruction->value.type = wanted_type;
ZigType *child_type = wanted_type->data.pointer.child_type;
if (type_has_bits(child_type)) {
ZigFn *fn_entry = exec_fn_entry(ira->new_irb.exec);
assert(fn_entry);
fn_entry->alloca_list.append(new_instruction);
}
ir_add_alloca(ira, new_instruction, child_type);
return new_instruction;
}
static IrInstruction *ir_analyze_null_to_maybe(IrAnalyze *ira, IrInstruction *source_instr, IrInstruction *value, ZigType *wanted_type) {
assert(wanted_type->id == ZigTypeIdOptional);
assert(instr_is_comptime(value));
@ -10929,14 +10889,6 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst
return ir_analyze_undefined_to_anything(ira, source_instr, value, wanted_type);
}
// cast from something to const pointer of it
if (!type_requires_comptime(actual_type)) {
ZigType *const_ptr_actual = get_pointer_to_type(ira->codegen, actual_type, true);
if (types_match_const_cast_only(ira, wanted_type, const_ptr_actual, source_node, false).id == ConstCastResultIdOk) {
return ir_analyze_cast_ref(ira, source_instr, value, wanted_type);
}
}
ErrorMsg *parent_msg = ir_add_error_node(ira, source_instr->source_node,
buf_sprintf("expected type '%s', found '%s'",
buf_ptr(&wanted_type->name),

View File

@ -32,7 +32,7 @@ pub const Buffer = struct.{
}
/// Must deinitialize with deinit.
pub fn initFromBuffer(buffer: *const Buffer) !Buffer {
pub fn initFromBuffer(buffer: Buffer) !Buffer {
return Buffer.init(buffer.list.allocator, buffer.toSliceConst());
}
@ -148,7 +148,7 @@ test "simple Buffer" {
assert(buf.eql("hello world"));
assert(mem.eql(u8, cstr.toSliceConst(buf.toSliceConst().ptr), buf.toSliceConst()));
var buf2 = try Buffer.initFromBuffer(&buf);
var buf2 = try Buffer.initFromBuffer(buf);
assert(buf.eql(buf2.toSliceConst()));
assert(buf.startsWith("hell"));

View File

@ -37,7 +37,7 @@ pub const Builder = struct.{
invalid_user_input: bool,
zig_exe: []const u8,
default_step: *Step,
env_map: BufMap,
env_map: *const BufMap,
top_level_steps: ArrayList(*TopLevelStep),
prefix: []const u8,
search_prefixes: ArrayList([]const u8),
@ -89,6 +89,8 @@ pub const Builder = struct.{
};
pub fn init(allocator: *Allocator, zig_exe: []const u8, build_root: []const u8, cache_root: []const u8) Builder {
const env_map = allocator.createOne(BufMap) catch unreachable;
env_map.* = os.getEnvMap(allocator) catch unreachable;
var self = Builder.{
.zig_exe = zig_exe,
.build_root = build_root,
@ -110,7 +112,7 @@ pub const Builder = struct.{
.available_options_list = ArrayList(AvailableOption).init(allocator),
.top_level_steps = ArrayList(*TopLevelStep).init(allocator),
.default_step = undefined,
.env_map = os.getEnvMap(allocator) catch unreachable,
.env_map = env_map,
.prefix = undefined,
.search_prefixes = ArrayList([]const u8).init(allocator),
.lib_dir = undefined,
@ -155,7 +157,7 @@ pub const Builder = struct.{
return LibExeObjStep.createObject(self, name, root_src);
}
pub fn addSharedLibrary(self: *Builder, name: []const u8, root_src: ?[]const u8, ver: *const Version) *LibExeObjStep {
pub fn addSharedLibrary(self: *Builder, name: []const u8, root_src: ?[]const u8, ver: Version) *LibExeObjStep {
return LibExeObjStep.createSharedLibrary(self, name, root_src, ver);
}
@ -178,7 +180,7 @@ pub const Builder = struct.{
return LibExeObjStep.createCStaticLibrary(self, name);
}
pub fn addCSharedLibrary(self: *Builder, name: []const u8, ver: *const Version) *LibExeObjStep {
pub fn addCSharedLibrary(self: *Builder, name: []const u8, ver: Version) *LibExeObjStep {
return LibExeObjStep.createCSharedLibrary(self, name, ver);
}
@ -541,7 +543,7 @@ pub const Builder = struct.{
}
fn spawnChild(self: *Builder, argv: []const []const u8) !void {
return self.spawnChildEnvMap(null, &self.env_map, argv);
return self.spawnChildEnvMap(null, self.env_map, argv);
}
fn printCmd(cwd: ?[]const u8, argv: []const []const u8) void {
@ -850,12 +852,12 @@ pub const LibExeObjStep = struct.{
Obj,
};
pub fn createSharedLibrary(builder: *Builder, name: []const u8, root_src: ?[]const u8, ver: *const Version) *LibExeObjStep {
pub fn createSharedLibrary(builder: *Builder, name: []const u8, root_src: ?[]const u8, ver: Version) *LibExeObjStep {
const self = builder.allocator.create(initExtraArgs(builder, name, root_src, Kind.Lib, false, ver)) catch unreachable;
return self;
}
pub fn createCSharedLibrary(builder: *Builder, name: []const u8, version: *const Version) *LibExeObjStep {
pub fn createCSharedLibrary(builder: *Builder, name: []const u8, version: Version) *LibExeObjStep {
const self = builder.allocator.create(initC(builder, name, Kind.Lib, version, false)) catch unreachable;
return self;
}
@ -891,7 +893,7 @@ pub const LibExeObjStep = struct.{
return self;
}
fn initExtraArgs(builder: *Builder, name: []const u8, root_src: ?[]const u8, kind: Kind, static: bool, ver: *const Version) LibExeObjStep {
fn initExtraArgs(builder: *Builder, name: []const u8, root_src: ?[]const u8, kind: Kind, static: bool, ver: Version) LibExeObjStep {
var self = LibExeObjStep.{
.no_rosegment = false,
.strip = false,
@ -909,7 +911,7 @@ pub const LibExeObjStep = struct.{
.step = Step.init(name, builder.allocator, make),
.output_path = null,
.output_h_path = null,
.version = ver.*,
.version = ver,
.out_filename = undefined,
.out_h_filename = builder.fmt("{}.h", name),
.major_only_filename = undefined,
@ -933,13 +935,13 @@ pub const LibExeObjStep = struct.{
return self;
}
fn initC(builder: *Builder, name: []const u8, kind: Kind, version: *const Version, static: bool) LibExeObjStep {
fn initC(builder: *Builder, name: []const u8, kind: Kind, version: Version, static: bool) LibExeObjStep {
var self = LibExeObjStep.{
.no_rosegment = false,
.builder = builder,
.name = name,
.kind = kind,
.version = version.*,
.version = version,
.static = static,
.target = Target.Native,
.cflags = ArrayList([]const u8).init(builder.allocator),

View File

@ -976,7 +976,7 @@ fn openSelfDebugInfoMacOs(allocator: *mem.Allocator) !DebugInfo {
};
}
fn printLineFromFile(out_stream: var, line_info: *const LineInfo) !void {
fn printLineFromFile(out_stream: var, line_info: LineInfo) !void {
var f = try os.File.openRead(line_info.file_name);
defer f.close();
// TODO fstat and make sure that the file has the correct size

View File

@ -8,7 +8,7 @@ const posix = os.posix;
const Loop = std.event.Loop;
pub const Server = struct.{
handleRequestFn: async<*mem.Allocator> fn (*Server, *const std.net.Address, *const os.File) void,
handleRequestFn: async<*mem.Allocator> fn (*Server, *const std.net.Address, os.File) void,
loop: *Loop,
sockfd: ?i32,
@ -40,7 +40,7 @@ pub const Server = struct.{
pub fn listen(
self: *Server,
address: *const std.net.Address,
handleRequestFn: async<*mem.Allocator> fn (*Server, *const std.net.Address, *const os.File) void,
handleRequestFn: async<*mem.Allocator> fn (*Server, *const std.net.Address, os.File) void,
) !void {
self.handleRequestFn = handleRequestFn;
@ -82,7 +82,7 @@ pub const Server = struct.{
continue;
}
var socket = os.File.openHandle(accepted_fd);
_ = async<self.loop.allocator> self.handleRequestFn(self, accepted_addr, socket) catch |err| switch (err) {
_ = async<self.loop.allocator> self.handleRequestFn(self, &accepted_addr, socket) catch |err| switch (err) {
error.OutOfMemory => {
socket.close();
continue;
@ -278,9 +278,9 @@ test "listen on a port, send bytes, receive bytes" {
tcp_server: Server,
const Self = @This();
async<*mem.Allocator> fn handler(tcp_server: *Server, _addr: *const std.net.Address, _socket: *const os.File) void {
async<*mem.Allocator> fn handler(tcp_server: *Server, _addr: *const std.net.Address, _socket: os.File) void {
const self = @fieldParentPtr(Self, "tcp_server", tcp_server);
var socket = _socket.*; // TODO https://github.com/ziglang/zig/issues/1592
var socket = _socket; // TODO https://github.com/ziglang/zig/issues/1592
defer socket.close();
// TODO guarantee elision of this allocation
const next_handler = async errorableHandler(self, _addr, socket) catch unreachable;
@ -307,9 +307,9 @@ test "listen on a port, send bytes, receive bytes" {
try loop.initSingleThreaded(std.debug.global_allocator);
var server = MyServer.{ .tcp_server = Server.init(&loop) };
defer server.tcp_server.deinit();
try server.tcp_server.listen(addr, MyServer.handler);
try server.tcp_server.listen(&addr, MyServer.handler);
const p = try async<std.debug.global_allocator> doAsyncTest(&loop, server.tcp_server.listen_address, &server.tcp_server);
const p = try async<std.debug.global_allocator> doAsyncTest(&loop, &server.tcp_server.listen_address, &server.tcp_server);
defer cancel p;
loop.run();
}

View File

@ -217,7 +217,7 @@ fn tableLowerBound(k: u64) usize {
/// @in: The HP number.
/// @val: The double.
/// &returns: The HP number.
fn hpProd(in: *const HP, val: f64) HP {
fn hpProd(in: HP, val: f64) HP {
var hi: f64 = undefined;
var lo: f64 = undefined;
split(in.val, &hi, &lo);

View File

@ -74,7 +74,7 @@ pub const Token = struct.{
}
// Slice into the underlying input string.
pub fn slice(self: *const Token, input: []const u8, i: usize) []const u8 {
pub fn slice(self: Token, input: []const u8, i: usize) []const u8 {
return input[i + self.offset - self.count .. i + self.offset];
}
};
@ -1008,8 +1008,8 @@ pub const Value = union(enum).{
Array: ArrayList(Value),
Object: ObjectMap,
pub fn dump(self: *const Value) void {
switch (self.*) {
pub fn dump(self: Value) void {
switch (self) {
Value.Null => {
debug.warn("null");
},
@ -1055,7 +1055,7 @@ pub const Value = union(enum).{
}
}
pub fn dumpIndent(self: *const Value, indent: usize) void {
pub fn dumpIndent(self: Value, indent: usize) void {
if (indent == 0) {
self.dump();
} else {
@ -1063,8 +1063,8 @@ pub const Value = union(enum).{
}
}
fn dumpIndentLevel(self: *const Value, indent: usize, level: usize) void {
switch (self.*) {
fn dumpIndentLevel(self: Value, indent: usize, level: usize) void {
switch (self) {
Value.Null => {
debug.warn("null");
},
@ -1178,7 +1178,7 @@ pub const Parser = struct.{
// Even though p.allocator exists, we take an explicit allocator so that allocation state
// can be cleaned up on error correctly during a `parse` on call.
fn transition(p: *Parser, allocator: *Allocator, input: []const u8, i: usize, token: *const Token) !void {
fn transition(p: *Parser, allocator: *Allocator, input: []const u8, i: usize, token: Token) !void {
switch (p.state) {
State.ObjectKey => switch (token.id) {
Token.Id.ObjectEnd => {
@ -1311,19 +1311,19 @@ pub const Parser = struct.{
}
}
fn pushToParent(p: *Parser, value: *const Value) !void {
fn pushToParent(p: *Parser, value: Value) !void {
switch (p.stack.at(p.stack.len - 1)) {
// Object Parent -> [ ..., object, <key>, value ]
Value.String => |key| {
_ = p.stack.pop();
var object = &p.stack.items[p.stack.len - 1].Object;
_ = try object.put(key, value.*);
_ = try object.put(key, value);
p.state = State.ObjectKey;
},
// Array Parent -> [ ..., <array>, value ]
Value.Array => |*array| {
try array.append(value.*);
try array.append(value);
p.state = State.ArrayValue;
},
else => {
@ -1332,14 +1332,14 @@ pub const Parser = struct.{
}
}
fn parseString(p: *Parser, allocator: *Allocator, token: *const Token, input: []const u8, i: usize) !Value {
fn parseString(p: *Parser, allocator: *Allocator, token: Token, input: []const u8, i: usize) !Value {
// TODO: We don't strictly have to copy values which do not contain any escape
// characters if flagged with the option.
const slice = token.slice(input, i);
return Value.{ .String = try mem.dupe(p.allocator, u8, slice) };
}
fn parseNumber(p: *Parser, token: *const Token, input: []const u8, i: usize) !Value {
fn parseNumber(p: *Parser, token: Token, input: []const u8, i: usize) !Value {
return if (token.number_is_integer)
Value.{ .Integer = try std.fmt.parseInt(i64, token.slice(input, i), 10) }
else

View File

@ -15,7 +15,7 @@ pub fn cosh(z: var) Complex(@typeOf(z.re)) {
};
}
fn cosh32(z: *const Complex(f32)) Complex(f32) {
fn cosh32(z: Complex(f32)) Complex(f32) {
const x = z.re;
const y = z.im;
@ -78,7 +78,7 @@ fn cosh32(z: *const Complex(f32)) Complex(f32) {
return Complex(f32).new((x * x) * (y - y), (x + x) * (y - y));
}
fn cosh64(z: *const Complex(f64)) Complex(f64) {
fn cosh64(z: Complex(f64)) Complex(f64) {
const x = z.re;
const y = z.im;

View File

@ -4,7 +4,7 @@ const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
pub fn pow(comptime T: type, z: *const T, c: *const T) T {
pub fn pow(comptime T: type, z: T, c: T) T {
const p = cmath.log(z);
const q = c.mul(p);
return cmath.exp(q);

View File

@ -46,8 +46,8 @@ pub const Address = struct.{
};
}
pub fn initPosix(addr: *const posix.sockaddr) Address {
return Address.{ .os_addr = addr.* };
pub fn initPosix(addr: posix.sockaddr) Address {
return Address.{ .os_addr = addr };
}
pub fn format(self: *const Address, out_stream: var) !void {

View File

@ -777,9 +777,9 @@ fn makePipe() ![2]i32 {
return fds;
}
fn destroyPipe(pipe: *const [2]i32) void {
os.close((pipe.*)[0]);
os.close((pipe.*)[1]);
fn destroyPipe(pipe: [2]i32) void {
os.close(pipe[0]);
os.close(pipe[1]);
}
// Child of fork calls this to report an error to the fork parent.

View File

@ -122,13 +122,13 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type
return self.uncheckedAt(i);
}
pub fn count(self: *const Self) usize {
pub fn count(self: Self) usize {
return self.len;
}
pub fn push(self: *Self, item: *const T) !void {
pub fn push(self: *Self, item: T) !void {
const new_item_ptr = try self.addOne();
new_item_ptr.* = item.*;
new_item_ptr.* = item;
}
pub fn pushMany(self: *Self, items: []const T) !void {

View File

@ -400,7 +400,7 @@ pub const Node = struct.{
Id.While => {
const while_node = @fieldParentPtr(While, "base", n);
if (while_node.@"else") |@"else"| {
n = @"else".base;
n = &@"else".base;
continue;
}
@ -409,7 +409,7 @@ pub const Node = struct.{
Id.For => {
const for_node = @fieldParentPtr(For, "base", n);
if (for_node.@"else") |@"else"| {
n = @"else".base;
n = &@"else".base;
continue;
}
@ -418,7 +418,7 @@ pub const Node = struct.{
Id.If => {
const if_node = @fieldParentPtr(If, "base", n);
if (if_node.@"else") |@"else"| {
n = @"else".base;
n = &@"else".base;
continue;
}

View File

@ -1848,7 +1848,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree {
continue;
},
else => {
if (!try parseBlockExpr(&stack, arena, opt_ctx, token_ptr, token_index)) {
if (!try parseBlockExpr(&stack, arena, opt_ctx, token_ptr.*, token_index)) {
prevToken(&tok_it, &tree);
stack.append(State.{ .UnwrapExpressionBegin = opt_ctx }) catch unreachable;
}
@ -2665,7 +2665,7 @@ pub fn parse(allocator: *mem.Allocator, source: []const u8) !ast.Tree {
continue;
},
else => {
if (!try parseBlockExpr(&stack, arena, opt_ctx, token.ptr, token.index)) {
if (!try parseBlockExpr(&stack, arena, opt_ctx, token.ptr.*, token.index)) {
prevToken(&tok_it, &tree);
if (opt_ctx != OptionalCtx.Optional) {
try tree.errors.push(Error.{ .ExpectedPrimaryExpr = Error.ExpectedPrimaryExpr.{ .token = token.index } });
@ -2949,29 +2949,29 @@ const OptionalCtx = union(enum).{
RequiredNull: *?*ast.Node,
Required: **ast.Node,
pub fn store(self: *const OptionalCtx, value: *ast.Node) void {
switch (self.*) {
pub fn store(self: OptionalCtx, value: *ast.Node) void {
switch (self) {
OptionalCtx.Optional => |ptr| ptr.* = value,
OptionalCtx.RequiredNull => |ptr| ptr.* = value,
OptionalCtx.Required => |ptr| ptr.* = value,
}
}
pub fn get(self: *const OptionalCtx) ?*ast.Node {
switch (self.*) {
pub fn get(self: OptionalCtx) ?*ast.Node {
switch (self) {
OptionalCtx.Optional => |ptr| return ptr.*,
OptionalCtx.RequiredNull => |ptr| return ptr.*.?,
OptionalCtx.Required => |ptr| return ptr.*,
}
}
pub fn toRequired(self: *const OptionalCtx) OptionalCtx {
switch (self.*) {
pub fn toRequired(self: OptionalCtx) OptionalCtx {
switch (self) {
OptionalCtx.Optional => |ptr| {
return OptionalCtx.{ .RequiredNull = ptr };
},
OptionalCtx.RequiredNull => |ptr| return self.*,
OptionalCtx.Required => |ptr| return self.*,
OptionalCtx.RequiredNull => |ptr| return self,
OptionalCtx.Required => |ptr| return self,
}
}
};
@ -3161,7 +3161,7 @@ fn parseStringLiteral(arena: *mem.Allocator, tok_it: *ast.Tree.TokenList.Iterato
}
}
fn parseBlockExpr(stack: *std.ArrayList(State), arena: *mem.Allocator, ctx: *const OptionalCtx, token_ptr: *const Token, token_index: TokenIndex) !bool {
fn parseBlockExpr(stack: *std.ArrayList(State), arena: *mem.Allocator, ctx: OptionalCtx, token_ptr: Token, token_index: TokenIndex) !bool {
switch (token_ptr.id) {
Token.Id.Keyword_suspend => {
const node = try arena.create(ast.Node.Suspend.{
@ -3199,7 +3199,7 @@ fn parseBlockExpr(stack: *std.ArrayList(State), arena: *mem.Allocator, ctx: *con
.label = null,
.inline_token = null,
.loop_token = token_index,
.opt_ctx = ctx.*,
.opt_ctx = ctx,
},
}) catch unreachable;
return true;
@ -3210,7 +3210,7 @@ fn parseBlockExpr(stack: *std.ArrayList(State), arena: *mem.Allocator, ctx: *con
.label = null,
.inline_token = null,
.loop_token = token_index,
.opt_ctx = ctx.*,
.opt_ctx = ctx,
},
}) catch unreachable;
return true;
@ -3295,10 +3295,10 @@ fn expectCommaOrEnd(tok_it: *ast.Tree.TokenList.Iterator, tree: *ast.Tree, end:
}
}
fn tokenIdToAssignment(id: *const Token.Id) ?ast.Node.InfixOp.Op {
fn tokenIdToAssignment(id: Token.Id) ?ast.Node.InfixOp.Op {
// TODO: We have to cast all cases because of this:
// error: expected type '?InfixOp', found '?@TagType(InfixOp)'
return switch (id.*) {
return switch (id) {
Token.Id.AmpersandEqual => ast.Node.InfixOp.Op.{ .AssignBitAnd = {} },
Token.Id.AngleBracketAngleBracketLeftEqual => ast.Node.InfixOp.Op.{ .AssignBitShiftLeft = {} },
Token.Id.AngleBracketAngleBracketRightEqual => ast.Node.InfixOp.Op.{ .AssignBitShiftRight = {} },
@ -3396,7 +3396,7 @@ fn createLiteral(arena: *mem.Allocator, comptime T: type, token_index: TokenInde
});
}
fn createToCtxLiteral(arena: *mem.Allocator, opt_ctx: *const OptionalCtx, comptime T: type, token_index: TokenIndex) !*T {
fn createToCtxLiteral(arena: *mem.Allocator, opt_ctx: OptionalCtx, comptime T: type, token_index: TokenIndex) !*T {
const node = try createLiteral(arena, T, token_index);
opt_ctx.store(&node.base);

View File

@ -1,10 +1,10 @@
const std = @import("std");
const other_file = @import("655_other_file.zig");
test "function with &const parameter with type dereferenced by namespace" {
test "function with *const parameter with type dereferenced by namespace" {
const x: other_file.Integer = 1234;
comptime std.debug.assert(@typeOf(&x) == *const other_file.Integer);
foo(x);
foo(&x);
}
fn foo(x: *const other_file.Integer) void {

View File

@ -22,88 +22,6 @@ test "pointer reinterpret const float to int" {
assert(int_val == 858993411);
}
test "implicitly cast a pointer to a const pointer of it" {
var x: i32 = 1;
const xp = &x;
funcWithConstPtrPtr(xp);
assert(x == 2);
}
fn funcWithConstPtrPtr(x: *const *i32) void {
x.*.* += 1;
}
test "implicitly cast a container to a const pointer of it" {
const z = Struct(void).{ .x = void.{} };
assert(0 == @sizeOf(@typeOf(z)));
assert(void.{} == Struct(void).pointer(z).x);
assert(void.{} == Struct(void).pointer(&z).x);
assert(void.{} == Struct(void).maybePointer(z).x);
assert(void.{} == Struct(void).maybePointer(&z).x);
assert(void.{} == Struct(void).maybePointer(null).x);
const s = Struct(u8).{ .x = 42 };
assert(0 != @sizeOf(@typeOf(s)));
assert(42 == Struct(u8).pointer(s).x);
assert(42 == Struct(u8).pointer(&s).x);
assert(42 == Struct(u8).maybePointer(s).x);
assert(42 == Struct(u8).maybePointer(&s).x);
assert(0 == Struct(u8).maybePointer(null).x);
const u = Union.{ .x = 42 };
assert(42 == Union.pointer(u).x);
assert(42 == Union.pointer(&u).x);
assert(42 == Union.maybePointer(u).x);
assert(42 == Union.maybePointer(&u).x);
assert(0 == Union.maybePointer(null).x);
const e = Enum.Some;
assert(Enum.Some == Enum.pointer(e));
assert(Enum.Some == Enum.pointer(&e));
assert(Enum.Some == Enum.maybePointer(e));
assert(Enum.Some == Enum.maybePointer(&e));
assert(Enum.None == Enum.maybePointer(null));
}
fn Struct(comptime T: type) type {
return struct.{
const Self = @This();
x: T,
fn pointer(self: *const Self) Self {
return self.*;
}
fn maybePointer(self: ?*const Self) Self {
const none = Self.{ .x = if (T == void) void.{} else 0 };
return (self orelse &none).*;
}
};
}
const Union = union.{
x: u8,
fn pointer(self: *const Union) Union {
return self.*;
}
fn maybePointer(self: ?*const Union) Union {
const none = Union.{ .x = 0 };
return (self orelse &none).*;
}
};
const Enum = enum.{
None,
Some,
fn pointer(self: *const Enum) Enum {
return self.*;
}
fn maybePointer(self: ?*const Enum) Enum {
return (self orelse &Enum.None).*;
}
};
test "implicitly cast indirect pointer to maybe-indirect pointer" {
const S = struct.{
const Self = @This();
@ -125,13 +43,9 @@ test "implicitly cast indirect pointer to maybe-indirect pointer" {
const p = &s;
const q = &p;
const r = &q;
assert(42 == S.constConst(p));
assert(42 == S.constConst(q));
assert(42 == S.maybeConstConst(p));
assert(42 == S.maybeConstConst(q));
assert(42 == S.constConstConst(q));
assert(42 == S.constConstConst(r));
assert(42 == S.maybeConstConstConst(q));
assert(42 == S.maybeConstConstConst(r));
}
@ -166,16 +80,6 @@ fn testPeerResolveArrayConstSlice(b: bool) void {
assert(mem.eql(u8, value2, "zz"));
}
test "integer literal to &const int" {
const x: *const i32 = 3;
assert(x.* == 3);
}
test "string literal to &const []const u8" {
const x: *const []const u8 = "hello";
assert(mem.eql(u8, x.*, "hello"));
}
test "implicitly cast from T to error!?T" {
castToOptionalTypeError(1);
comptime castToOptionalTypeError(1);

View File

@ -56,15 +56,15 @@ test "constant enum with payload" {
shouldBeNotEmpty(full);
}
fn shouldBeEmpty(x: *const AnEnumWithPayload) void {
switch (x.*) {
fn shouldBeEmpty(x: AnEnumWithPayload) void {
switch (x) {
AnEnumWithPayload.Empty => {},
else => unreachable,
}
}
fn shouldBeNotEmpty(x: *const AnEnumWithPayload) void {
switch (x.*) {
fn shouldBeNotEmpty(x: AnEnumWithPayload) void {
switch (x) {
AnEnumWithPayload.Empty => unreachable,
else => {},
}

View File

@ -16,7 +16,7 @@ const C = struct.{
}
};
fn foo(a: *const A) i32 {
fn foo(a: A) i32 {
return a.b.c.d();
}

View File

@ -353,8 +353,8 @@ const test3_foo = Test3Foo.{
},
};
const test3_bar = Test3Foo.{ .Two = 13 };
fn test3_1(f: *const Test3Foo) void {
switch (f.*) {
fn test3_1(f: Test3Foo) void {
switch (f) {
Test3Foo.Three => |pt| {
assert(pt.x == 3);
assert(pt.y == 4);
@ -362,8 +362,8 @@ fn test3_1(f: *const Test3Foo) void {
else => unreachable,
}
}
fn test3_2(f: *const Test3Foo) void {
switch (f.*) {
fn test3_2(f: Test3Foo) void {
switch (f) {
Test3Foo.Two => |x| {
assert(x == 13);
},
@ -672,10 +672,10 @@ const PackedEnum = packed enum.{
};
test "packed struct, enum, union parameters in extern function" {
testPackedStuff(PackedStruct.{
testPackedStuff(&(PackedStruct.{
.a = 1,
.b = 2,
}, PackedUnion.{ .a = 1 }, PackedEnum.A);
}), &(PackedUnion.{ .a = 1 }), PackedEnum.A);
}
export fn testPackedStuff(a: *const PackedStruct, b: *const PackedUnion, c: PackedEnum) void {}

View File

@ -65,8 +65,8 @@ test "if var maybe pointer" {
.d = 1,
}) == 15);
}
fn shouldBeAPlus1(p: *const Particle) u64 {
var maybe_particle: ?Particle = p.*;
fn shouldBeAPlus1(p: Particle) u64 {
var maybe_particle: ?Particle = p;
if (maybe_particle) |*particle| {
particle.a += 1;
}

View File

@ -55,7 +55,7 @@ const StructFoo = struct.{
b: bool,
c: f32,
};
fn testFoo(foo: *const StructFoo) void {
fn testFoo(foo: StructFoo) void {
assert(foo.b);
}
fn testMutation(foo: *StructFoo) void {
@ -112,7 +112,7 @@ fn aFunc() i32 {
return 13;
}
fn callStructField(foo: *const Foo) i32 {
fn callStructField(foo: Foo) i32 {
return foo.ptr();
}
@ -124,7 +124,7 @@ test "store member function in variable" {
}
const MemberFnTestFoo = struct.{
x: i32,
fn member(foo: *const MemberFnTestFoo) i32 {
fn member(foo: MemberFnTestFoo) i32 {
return foo.x;
}
};
@ -443,8 +443,8 @@ test "implicit cast packed struct field to const ptr" {
move_id: u9,
level: u7,
fn toInt(value: *const u7) u7 {
return value.*;
fn toInt(value: u7) u7 {
return value;
}
};

View File

@ -90,8 +90,8 @@ const SwitchProngWithVarEnum = union(enum).{
Two: f32,
Meh: void,
};
fn switchProngWithVarFn(a: *const SwitchProngWithVarEnum) void {
switch (a.*) {
fn switchProngWithVarFn(a: SwitchProngWithVarEnum) void {
switch (a) {
SwitchProngWithVarEnum.One => |x| {
assert(x == 13);
},

View File

@ -108,9 +108,9 @@ fn doTest() void {
assert(bar(Payload.{ .A = 1234 }) == -10);
}
fn bar(value: *const Payload) i32 {
assert(Letter(value.*) == Letter.A);
return switch (value.*) {
fn bar(value: Payload) i32 {
assert(Letter(value) == Letter.A);
return switch (value) {
Payload.A => |x| return x - 1244,
Payload.B => |x| if (x == 12.34) i32(20) else 21,
Payload.C => |x| if (x) i32(30) else 31,
@ -147,9 +147,9 @@ test "union(enum(u32)) with specified and unspecified tag values" {
comptime testEnumWithSpecifiedAndUnspecifiedTagValues(MultipleChoice2.{ .C = 123 });
}
fn testEnumWithSpecifiedAndUnspecifiedTagValues(x: *const MultipleChoice2) void {
assert(@enumToInt(@TagType(MultipleChoice2)(x.*)) == 60);
assert(1123 == switch (x.*) {
fn testEnumWithSpecifiedAndUnspecifiedTagValues(x: MultipleChoice2) void {
assert(@enumToInt(@TagType(MultipleChoice2)(x)) == 60);
assert(1123 == switch (x) {
MultipleChoice2.A => 1,
MultipleChoice2.B => 2,
MultipleChoice2.C => |v| i32(1000) + v,
@ -206,8 +206,8 @@ test "cast union to tag type of union" {
comptime testCastUnionToTagType(TheUnion.{ .B = 1234 });
}
fn testCastUnionToTagType(x: *const TheUnion) void {
assert(TheTag(x.*) == TheTag.B);
fn testCastUnionToTagType(x: TheUnion) void {
assert(TheTag(x) == TheTag.B);
}
test "cast tag type of union to union" {
@ -234,19 +234,6 @@ fn giveMeLetterB(x: Letter2) void {
assert(x == Value2.B);
}
test "implicit cast from @EnumTagType(TheUnion) to &const TheUnion" {
assertIsTheUnion2Item1(TheUnion2.Item1);
}
const TheUnion2 = union(enum).{
Item1,
Item2: i32,
};
fn assertIsTheUnion2Item1(value: *const TheUnion2) void {
assert(value.* == TheUnion2.Item1);
}
pub const PackThis = union(enum).{
Invalid: bool,
StringLiteral: u2,

View File

@ -116,7 +116,7 @@ fn expandString(input: []const u8, output: *Buffer) !void {
}
var token_index: usize = 0;
const root = try parse(tokens, &token_index);
const root = try parse(&tokens, &token_index);
const last_token = tokens.items[token_index];
switch (last_token) {
Token.Eof => {},
@ -139,9 +139,9 @@ fn expandString(input: []const u8, output: *Buffer) !void {
const ExpandNodeError = error.{OutOfMemory};
fn expandNode(node: *const Node, output: *ArrayList(Buffer)) ExpandNodeError!void {
fn expandNode(node: Node, output: *ArrayList(Buffer)) ExpandNodeError!void {
assert(output.len == 0);
switch (node.*) {
switch (node) {
Node.Scalar => |scalar| {
try output.append(try Buffer.init(global_allocator, scalar));
},

View File

@ -271,7 +271,7 @@ pub const CompareOutputContext = struct.{
child.stdin_behavior = StdIo.Ignore;
child.stdout_behavior = StdIo.Pipe;
child.stderr_behavior = StdIo.Pipe;
child.env_map = &b.env_map;
child.env_map = b.env_map;
child.spawn() catch |err| debug.panic("Unable to spawn {}: {}\n", full_exe_path, @errorName(err));
@ -347,7 +347,7 @@ pub const CompareOutputContext = struct.{
const child = os.ChildProcess.init([][]u8.{full_exe_path}, b.allocator) catch unreachable;
defer child.deinit();
child.env_map = &b.env_map;
child.env_map = b.env_map;
child.stdin_behavior = StdIo.Ignore;
child.stdout_behavior = StdIo.Ignore;
child.stderr_behavior = StdIo.Ignore;
@ -417,7 +417,7 @@ pub const CompareOutputContext = struct.{
self.addCase(tc);
}
pub fn addCase(self: *CompareOutputContext, case: *const TestCase) void {
pub fn addCase(self: *CompareOutputContext, case: TestCase) void {
const b = self.b;
const root_src = os.path.join(b.allocator, b.cache_root, case.sources.items[0].filename) catch unreachable;
@ -583,7 +583,7 @@ pub const CompileErrorContext = struct.{
const child = os.ChildProcess.init(zig_args.toSliceConst(), b.allocator) catch unreachable;
defer child.deinit();
child.env_map = &b.env_map;
child.env_map = b.env_map;
child.stdin_behavior = StdIo.Ignore;
child.stdout_behavior = StdIo.Pipe;
child.stderr_behavior = StdIo.Pipe;
@ -847,7 +847,7 @@ pub const TranslateCContext = struct.{
const child = os.ChildProcess.init(zig_args.toSliceConst(), b.allocator) catch unreachable;
defer child.deinit();
child.env_map = &b.env_map;
child.env_map = b.env_map;
child.stdin_behavior = StdIo.Ignore;
child.stdout_behavior = StdIo.Pipe;
child.stderr_behavior = StdIo.Pipe;