More progress

This commit is contained in:
Alexandros Naskos 2020-06-10 20:48:40 +03:00
parent d6609d918b
commit 3bdb2ee444
2 changed files with 145 additions and 133 deletions

View File

@ -244,13 +244,13 @@ fn findReturnStatement(tree: *ast.Tree, fn_decl: *ast.Node.FnProto) ?*ast.Node.C
} }
/// Resolves the return type of a function /// Resolves the return type of a function
fn resolveReturnType(store: *DocumentStore, fn_decl: *ast.Node.FnProto, handle: *DocumentStore.Handle) !?NodeWithHandle { fn resolveReturnType(store: *DocumentStore, arena: *std.heap.ArenaAllocator, fn_decl: *ast.Node.FnProto, handle: *DocumentStore.Handle) !?NodeWithHandle {
if (isTypeFunction(handle.tree, fn_decl) and fn_decl.body_node != null) { if (isTypeFunction(handle.tree, fn_decl) and fn_decl.body_node != null) {
// If this is a type function and it only contains a single return statement that returns // If this is a type function and it only contains a single return statement that returns
// a container declaration, we will return that declaration. // a container declaration, we will return that declaration.
const ret = findReturnStatement(handle.tree, fn_decl) orelse return null; const ret = findReturnStatement(handle.tree, fn_decl) orelse return null;
if (ret.rhs) |rhs| if (ret.rhs) |rhs|
if (try resolveTypeOfNode(store, .{ .node = rhs, .handle = handle })) |res_rhs| switch (res_rhs.node.id) { if (try resolveTypeOfNode(store, arena, .{ .node = rhs, .handle = handle })) |res_rhs| switch (res_rhs.node.id) {
.ContainerDecl => { .ContainerDecl => {
return res_rhs; return res_rhs;
}, },
@ -261,16 +261,16 @@ fn resolveReturnType(store: *DocumentStore, fn_decl: *ast.Node.FnProto, handle:
} }
return switch (fn_decl.return_type) { return switch (fn_decl.return_type) {
.Explicit, .InferErrorSet => |return_type| try resolveTypeOfNode(store, .{ .node = return_type, .handle = handle }), .Explicit, .InferErrorSet => |return_type| try resolveTypeOfNode(store, arena, .{ .node = return_type, .handle = handle }),
.Invalid => null, .Invalid => null,
}; };
} }
/// Resolves the child type of an optional type /// Resolves the child type of an optional type
fn resolveUnwrapOptionalType(store: *DocumentStore, opt: NodeWithHandle) !?NodeWithHandle { fn resolveUnwrapOptionalType(store: *DocumentStore, arena: *std.heap.ArenaAllocator, opt: NodeWithHandle) !?NodeWithHandle {
if (opt.node.cast(ast.Node.PrefixOp)) |prefix_op| { if (opt.node.cast(ast.Node.PrefixOp)) |prefix_op| {
if (prefix_op.op == .OptionalType) { if (prefix_op.op == .OptionalType) {
return try resolveTypeOfNode(store, .{ .node = prefix_op.rhs, .handle = opt.handle }); return try resolveTypeOfNode(store, arena, .{ .node = prefix_op.rhs, .handle = opt.handle });
} }
} }
@ -278,12 +278,12 @@ fn resolveUnwrapOptionalType(store: *DocumentStore, opt: NodeWithHandle) !?NodeW
} }
/// Resolves the child type of a defer type /// Resolves the child type of a defer type
fn resolveDerefType(store: *DocumentStore, deref: NodeWithHandle) !?NodeWithHandle { fn resolveDerefType(store: *DocumentStore, arena: *std.heap.ArenaAllocator, deref: NodeWithHandle) !?NodeWithHandle {
if (deref.node.cast(ast.Node.PrefixOp)) |pop| { if (deref.node.cast(ast.Node.PrefixOp)) |pop| {
if (pop.op == .PtrType) { if (pop.op == .PtrType) {
const op_token_id = deref.handle.tree.token_ids[pop.op_token]; const op_token_id = deref.handle.tree.token_ids[pop.op_token];
switch (op_token_id) { switch (op_token_id) {
.Asterisk => return try resolveTypeOfNode(store, .{ .node = pop.rhs, .handle = deref.handle }), .Asterisk => return try resolveTypeOfNode(store, arena, .{ .node = pop.rhs, .handle = deref.handle }),
.LBracket, .AsteriskAsterisk => return null, .LBracket, .AsteriskAsterisk => return null,
else => unreachable, else => unreachable,
} }
@ -315,26 +315,26 @@ fn makeSliceType(arena: *std.heap.ArenaAllocator, child_type: *ast.Node) ?*ast.N
/// Resolves bracket access type (both slicing and array access) /// Resolves bracket access type (both slicing and array access)
fn resolveBracketAccessType( fn resolveBracketAccessType(
store: *DocumentStore, store: *DocumentStore,
lhs: NodeWithHandle,
arena: *std.heap.ArenaAllocator, arena: *std.heap.ArenaAllocator,
lhs: NodeWithHandle,
rhs: enum { Single, Range }, rhs: enum { Single, Range },
) !?NodeWithHandle { ) !?NodeWithHandle {
if (lhs.node.cast(ast.Node.PrefixOp)) |pop| { if (lhs.node.cast(ast.Node.PrefixOp)) |pop| {
switch (pop.op) { switch (pop.op) {
.SliceType => { .SliceType => {
if (rhs == .Single) return resolveTypeOfNode(store, .{ .node = pop.rhs, .handle = lhs.handle }); if (rhs == .Single) return try resolveTypeOfNode(store, arena, .{ .node = pop.rhs, .handle = lhs.handle });
return lhs; return lhs;
}, },
.ArrayType => { .ArrayType => {
if (rhs == .Single) return resolveTypeOfNode(store, .{ .node = pop.rhs, .handle = lhs.handle }); if (rhs == .Single) return try resolveTypeOfNode(store, arena, .{ .node = pop.rhs, .handle = lhs.handle });
return NodeWithHandle{ .node = makeSliceType(arena, pop.rhs), .handle = lhs.handle }; return NodeWithHandle{ .node = makeSliceType(arena, pop.rhs) orelse return null, .handle = lhs.handle };
}, },
.PtrType => { .PtrType => {
if (pop.rhs.cast(std.zig.ast.Node.PrefixOp)) |child_pop| { if (pop.rhs.cast(std.zig.ast.Node.PrefixOp)) |child_pop| {
switch (child_pop.op) { switch (child_pop.op) {
.ArrayType => { .ArrayType => {
if (rhs == .Single) { if (rhs == .Single) {
return resolveTypeOfNode(store, .{ .node = child_pop.rhs, .handle = lhs.handle }); return try resolveTypeOfNode(store, arena, .{ .node = child_pop.rhs, .handle = lhs.handle });
} }
return lhs; return lhs;
}, },
@ -349,39 +349,36 @@ fn resolveBracketAccessType(
} }
/// Called to remove one level of pointerness before a field access /// Called to remove one level of pointerness before a field access
fn resolveFieldAccessLhsType(store: *DocumentStore, lhs: NodeWithHandle) !NodeWithHandle { fn resolveFieldAccessLhsType(store: *DocumentStore, arena: *std.heap.ArenaAllocator, lhs: NodeWithHandle) !NodeWithHandle {
return resolveDerefType(store, lhs) orelse lhs; return (try resolveDerefType(store, arena, lhs)) orelse lhs;
} }
// @TODO try errors
/// Resolves the type of a node /// Resolves the type of a node
pub fn resolveTypeOfNode(store: *DocumentStore, node_handle: NodeWithHandle) !?NodeWithHandle { pub fn resolveTypeOfNode(store: *DocumentStore, arena: *std.heap.ArenaAllocator, node_handle: NodeWithHandle) error{OutOfMemory}!?NodeWithHandle {
const node = node_handle.node;
const handle = node_handle.handle;
switch (node.id) { switch (node.id) {
.VarDecl => { .VarDecl => {
const vari = node.cast(ast.Node.VarDecl).?; const vari = node.cast(ast.Node.VarDecl).?;
return try resolveTypeOfNode(store, arena, .{ .node = vari.type_node orelse vari.init_node.?, .handle = handle });
return resolveTypeOfNode(analysis_ctx, vari.type_node orelse vari.init_node.?) orelse null;
}, },
.Identifier => { .Identifier => {
if (getChildOfSlice(analysis_ctx.tree(), analysis_ctx.scope_nodes, analysis_ctx.tree().getNodeSource(node))) |child| { if (try lookupSymbolGlobal(store, handle, handle.tree.getNodeSource(node), handle.tree.token_locs[node.firstToken()].start)) |child| {
if (child == node) return null; return try child.resolveType(store, arena);
return resolveTypeOfNode(analysis_ctx, child); }
} else return null; return null;
}, },
.ContainerField => { .ContainerField => {
const field = node.cast(ast.Node.ContainerField).?; const field = node.cast(ast.Node.ContainerField).?;
return resolveTypeOfNode(analysis_ctx, field.type_expr orelse return null); return try resolveTypeOfNode(store, arena, .{ .node = field.type_expr orelse return null, .handle = handle });
}, },
.Call => { .Call => {
const call = node.cast(ast.Node.Call).?; const call = node.cast(ast.Node.Call).?;
const previous_tree = analysis_ctx.tree();
const decl = resolveTypeOfNode(analysis_ctx, call.lhs) orelse return null;
if (decl.cast(ast.Node.FnProto)) |fn_decl| {
if (previous_tree != analysis_ctx.tree()) {
return resolveReturnType(analysis_ctx, fn_decl);
}
// @TODO use BoundTypeParams: ParamDecl -> NodeWithHandle or something
const decl = (try resolveTypeOfNode(store, arena, .{ .node = call.lhs, .handle = handle })) orelse return null;
if (decl.node.cast(ast.Node.FnProto)) |fn_decl| {
// Add type param values to the scope nodes // Add type param values to the scope nodes
const param_len = std.math.min(call.params_len, fn_decl.params_len); const param_len = std.math.min(call.params_len, fn_decl.params_len);
var scope_nodes = std.ArrayList(*ast.Node).fromOwnedSlice(&analysis_ctx.arena.allocator, analysis_ctx.scope_nodes); var scope_nodes = std.ArrayList(*ast.Node).fromOwnedSlice(&analysis_ctx.arena.allocator, analysis_ctx.scope_nodes);
@ -629,7 +626,7 @@ pub fn getFieldAccessTypeNode(
while (true) { while (true) {
const tok = tokenizer.next(); const tok = tokenizer.next();
switch (tok.id) { switch (tok.id) {
.Eof => return try resolveFieldAccessLhsType(store, current_node), .Eof => return try resolveFieldAccessLhsType(store, arena, current_node),
.Identifier => { .Identifier => {
if (try lookupSymbolGlobal(store, current_node.handle, tokenizer.buffer[tok.loc.start..tok.loc.end], tok.loc.start)) |child| { if (try lookupSymbolGlobal(store, current_node.handle, tokenizer.buffer[tok.loc.start..tok.loc.end], tok.loc.start)) |child| {
current_node = (try child.resolveType(store, arena)) orelse return null; current_node = (try child.resolveType(store, arena)) orelse return null;
@ -638,22 +635,22 @@ pub fn getFieldAccessTypeNode(
.Period => { .Period => {
const after_period = tokenizer.next(); const after_period = tokenizer.next();
switch (after_period.id) { switch (after_period.id) {
.Eof => return try resolveFieldAccessLhsType(store, current_node), .Eof => return try resolveFieldAccessLhsType(store, arena, current_node),
.Identifier => { .Identifier => {
if (after_period.loc.end == tokenizer.buffer.len) return try resolveFieldAccessLhsType(store, current_node); if (after_period.loc.end == tokenizer.buffer.len) return try resolveFieldAccessLhsType(store, arena, current_node);
current_node = resolveFieldAccessLhsType(store, current_node); current_node = try resolveFieldAccessLhsType(store, arena, current_node);
if (current_node.node.id != .ContainerDecl and current_node.node.id != .Root) { if (current_node.node.id != .ContainerDecl and current_node.node.id != .Root) {
// @TODO Is this ok? // @TODO Is this ok?
return null; return null;
} }
if (lookupSymbolContainer(store, current_node, tokenizer.buffer[after_period.loc.start..after_period.loc.end], true)) |child| { if (try lookupSymbolContainer(store, current_node, tokenizer.buffer[after_period.loc.start..after_period.loc.end], true)) |child| {
current_node = (try child.resolveType(store, arena)) orelse return null; current_node = (try child.resolveType(store, arena)) orelse return null;
} else return null; } else return null;
}, },
.QuestionMark => { .QuestionMark => {
current_node = (try resolveUnwrapOptionalType(store, current_node)) orelse return null; current_node = (try resolveUnwrapOptionalType(store, arena, current_node)) orelse return null;
}, },
else => { else => {
std.debug.warn("Unrecognized token {} after period.\n", .{after_period.id}); std.debug.warn("Unrecognized token {} after period.\n", .{after_period.id});
@ -662,13 +659,13 @@ pub fn getFieldAccessTypeNode(
} }
}, },
.PeriodAsterisk => { .PeriodAsterisk => {
current_node = (try resolveDerefType(store, current_node)) orelse return null; current_node = (try resolveDerefType(store, arena, current_node)) orelse return null;
}, },
.LParen => { .LParen => {
switch (current_node.node.id) { switch (current_node.node.id) {
.FnProto => { .FnProto => {
const func = current_node.node.cast(ast.Node.FnProto).?; const func = current_node.node.cast(ast.Node.FnProto).?;
if (try resolveReturnType(store, func, current_node.handle)) |ret| { if (try resolveReturnType(store, arena, func, current_node.handle)) |ret| {
current_node = ret; current_node = ret;
// Skip to the right paren // Skip to the right paren
var paren_count: usize = 1; var paren_count: usize = 1;
@ -701,7 +698,7 @@ pub fn getFieldAccessTypeNode(
} }
} else return null; } else return null;
current_node = (try resolveBracketAccessType(store, current_node, arena, if (is_range) .Range else .Single)) orelse return null; current_node = (try resolveBracketAccessType(store, arena, current_node, if (is_range) .Range else .Single)) orelse return null;
}, },
else => { else => {
std.debug.warn("Unimplemented token: {}\n", .{tok.id}); std.debug.warn("Unimplemented token: {}\n", .{tok.id});
@ -710,7 +707,7 @@ pub fn getFieldAccessTypeNode(
} }
} }
return try resolveFieldAccessLhsType(store, current_node); return try resolveFieldAccessLhsType(store, arena, current_node);
} }
pub fn isNodePublic(tree: *ast.Tree, node: *ast.Node) bool { pub fn isNodePublic(tree: *ast.Tree, node: *ast.Node) bool {
@ -1092,27 +1089,27 @@ pub const DeclWithHandle = struct {
} }
fn resolveType(self: DeclWithHandle, store: *DocumentStore, arena: *std.heap.ArenaAllocator) !?NodeWithHandle { fn resolveType(self: DeclWithHandle, store: *DocumentStore, arena: *std.heap.ArenaAllocator) !?NodeWithHandle {
// resolveTypeOfNode(store: *DocumentStore, node_handle: NodeWithHandle) return switch (self.decl.*) {
return switch (self.decl) { .ast_node => |node| try resolveTypeOfNode(store, arena, .{ .node = node, .handle = self.handle }),
.ast_node => |node| try resolveTypeOfNode(store, .{ .node = node, .handle = self.handle }),
.param_decl => |param_decl| switch (param_decl.param_type) { .param_decl => |param_decl| switch (param_decl.param_type) {
.type_expr => |type_node| try resolveTypeOfNode(store, .{ .node = node, .handle = self.handle }), .type_expr => |type_node| try resolveTypeOfNode(store, arena, .{ .node = type_node, .handle = self.handle }),
else => null, else => null,
}, },
.pointer_payload => |pay| try resolveUnwrapOptionalType( .pointer_payload => |pay| try resolveUnwrapOptionalType(
store, store,
try resolveTypeOfNode(store, .{ arena,
(try resolveTypeOfNode(store, arena, .{
.node = pay.condition, .node = pay.condition,
.handle = self.handle, .handle = self.handle,
}) orelse return null, })) orelse return null,
), ),
.array_payload => |pay| try resolveBracketAccessType( .array_payload => |pay| try resolveBracketAccessType(
store, store,
arena,
.{ .{
.node = pay.array_expr, .node = pay.array_expr,
.handle = self.handle, .handle = self.handle,
}, },
arena,
.Single, .Single,
), ),
// TODO Resolve switch payload types // TODO Resolve switch payload types
@ -1171,18 +1168,19 @@ pub fn lookupSymbolGlobal(store: *DocumentStore, handle: *DocumentStore.Handle,
return null; return null;
} }
pub fn lookupSymbolContainer(store: *DocumentScope, container_handle: NodeWithHandle, symbol: []const u8, accept_fields: bool) !?DeclWithHandle { pub fn lookupSymbolContainer(store: *DocumentStore, container_handle: NodeWithHandle, symbol: []const u8, accept_fields: bool) !?DeclWithHandle {
const container = container_handle.node; const container = container_handle.node;
const handle = container_handle.handle; const handle = container_handle.handle;
std.debug.assert(container.id == .ContainerDecl or container.id == .Root); std.debug.assert(container.id == .ContainerDecl or container.id == .Root);
// Find the container scope. // Find the container scope.
var maybe_container_scope: ?*Scope = null; var maybe_container_scope: ?*Scope = null;
for (handle.document_scope.scopes) |*scope| { for (handle.document_scope.scopes) |*scope| {
switch (scope.*) { switch (scope.*.data) {
.container => |node| if (node == container) { .container => |node| if (node == container) {
maybe_container_scope = scope; maybe_container_scope = scope;
break; break;
}, },
else => {},
} }
} }
@ -1194,7 +1192,7 @@ pub fn lookupSymbolContainer(store: *DocumentScope, container_handle: NodeWithHa
}, },
else => {}, else => {},
} }
return &candidate.value; return DeclWithHandle{ .decl = &candidate.value, .handle = handle };
} }
for (container_scope.uses) |use| { for (container_scope.uses) |use| {
@ -1206,7 +1204,7 @@ pub fn lookupSymbolContainer(store: *DocumentScope, container_handle: NodeWithHa
} }
pub const DocumentScope = struct { pub const DocumentScope = struct {
scopes: []const Scope, scopes: []Scope,
pub fn debugPrint(self: DocumentScope) void { pub fn debugPrint(self: DocumentScope) void {
for (self.scopes) |scope| { for (self.scopes) |scope| {
@ -1338,6 +1336,7 @@ fn makeScopeInternal(
.range = nodeSourceRange(tree, node), .range = nodeSourceRange(tree, node),
.decls = std.StringHashMap(Declaration).init(allocator), .decls = std.StringHashMap(Declaration).init(allocator),
.uses = &[0]*ast.Node.Use{}, .uses = &[0]*ast.Node.Use{},
.tests = &[0]*ast.Node{},
.data = .{ .function = node }, .data = .{ .function = node },
}; };
var scope_idx = scopes.items.len - 1; var scope_idx = scopes.items.len - 1;
@ -1365,6 +1364,7 @@ fn makeScopeInternal(
.range = nodeSourceRange(tree, node), .range = nodeSourceRange(tree, node),
.decls = std.StringHashMap(Declaration).init(allocator), .decls = std.StringHashMap(Declaration).init(allocator),
.uses = &[0]*ast.Node.Use{}, .uses = &[0]*ast.Node.Use{},
.tests = &[0]*ast.Node{},
.data = .{ .block = node }, .data = .{ .block = node },
}; };
var scope_idx = scopes.items.len - 1; var scope_idx = scopes.items.len - 1;
@ -1410,6 +1410,7 @@ fn makeScopeInternal(
}, },
.decls = std.StringHashMap(Declaration).init(allocator), .decls = std.StringHashMap(Declaration).init(allocator),
.uses = &[0]*ast.Node.Use{}, .uses = &[0]*ast.Node.Use{},
.tests = &[0]*ast.Node{},
.data = .other, .data = .other,
}; };
errdefer scope.decls.deinit(); errdefer scope.decls.deinit();
@ -1437,6 +1438,7 @@ fn makeScopeInternal(
}, },
.decls = std.StringHashMap(Declaration).init(allocator), .decls = std.StringHashMap(Declaration).init(allocator),
.uses = &[0]*ast.Node.Use{}, .uses = &[0]*ast.Node.Use{},
.tests = &[0]*ast.Node{},
.data = .other, .data = .other,
}; };
errdefer scope.decls.deinit(); errdefer scope.decls.deinit();
@ -1461,6 +1463,7 @@ fn makeScopeInternal(
}, },
.decls = std.StringHashMap(Declaration).init(allocator), .decls = std.StringHashMap(Declaration).init(allocator),
.uses = &[0]*ast.Node.Use{}, .uses = &[0]*ast.Node.Use{},
.tests = &[0]*ast.Node{},
.data = .other, .data = .other,
}; };
errdefer scope.decls.deinit(); errdefer scope.decls.deinit();
@ -1488,6 +1491,7 @@ fn makeScopeInternal(
}, },
.decls = std.StringHashMap(Declaration).init(allocator), .decls = std.StringHashMap(Declaration).init(allocator),
.uses = &[0]*ast.Node.Use{}, .uses = &[0]*ast.Node.Use{},
.tests = &[0]*ast.Node{},
.data = .other, .data = .other,
}; };
errdefer scope.decls.deinit(); errdefer scope.decls.deinit();
@ -1514,6 +1518,7 @@ fn makeScopeInternal(
}, },
.decls = std.StringHashMap(Declaration).init(allocator), .decls = std.StringHashMap(Declaration).init(allocator),
.uses = &[0]*ast.Node.Use{}, .uses = &[0]*ast.Node.Use{},
.tests = &[0]*ast.Node{},
.data = .other, .data = .other,
}; };
errdefer scope.decls.deinit(); errdefer scope.decls.deinit();
@ -1554,6 +1559,7 @@ fn makeScopeInternal(
}, },
.decls = std.StringHashMap(Declaration).init(allocator), .decls = std.StringHashMap(Declaration).init(allocator),
.uses = &[0]*ast.Node.Use{}, .uses = &[0]*ast.Node.Use{},
.tests = &[0]*ast.Node{},
.data = .other, .data = .other,
}; };
errdefer scope.decls.deinit(); errdefer scope.decls.deinit();

View File

@ -81,7 +81,7 @@ fn respondGeneric(id: types.RequestId, response: []const u8) !void {
const json_fmt = "{{\"jsonrpc\":\"2.0\",\"id\":"; const json_fmt = "{{\"jsonrpc\":\"2.0\",\"id\":";
const stdout_stream = stdout.outStream(); const stdout_stream = stdout.outStream();
try stdout_stream.print("Content-Length: {}\r\n\r\n" ++ json_fmt, .{ response.len + id_len + json_fmt.len - 1 }); try stdout_stream.print("Content-Length: {}\r\n\r\n" ++ json_fmt, .{response.len + id_len + json_fmt.len - 1});
switch (id) { switch (id) {
.Integer => |int| try stdout_stream.print("{}", .{int}), .Integer => |int| try stdout_stream.print("{}", .{int}),
.String => |str| try stdout_stream.print("\"{}\"", .{str}), .String => |str| try stdout_stream.print("\"{}\"", .{str}),
@ -98,7 +98,7 @@ fn showMessage(@"type": types.MessageType, message: []const u8) !void {
.params = .{ .params = .{
.ShowMessageParams = .{ .ShowMessageParams = .{
.@"type" = @"type", .@"type" = @"type",
.message = message .message = message,
}, },
}, },
}); });
@ -198,31 +198,32 @@ fn publishDiagnostics(handle: DocumentStore.Handle, config: Config) !void {
fn containerToCompletion( fn containerToCompletion(
list: *std.ArrayList(types.CompletionItem), list: *std.ArrayList(types.CompletionItem),
analysis_ctx: *DocumentStore.AnalysisContext, container_handle: analysis.NodeWithHandle,
orig_handle: *DocumentStore.Handle, orig_handle: *DocumentStore.Handle,
container: *std.zig.ast.Node,
config: Config, config: Config,
) !void { ) !void {
// @TODO Something like iterateSymbolsGlobal but for container to support uses.
const container = container_handle.node;
const handle = container_handle.handle;
var child_idx: usize = 0; var child_idx: usize = 0;
while (container.iterate(child_idx)) |child_node| : (child_idx += 1) { while (container.iterate(child_idx)) |child_node| : (child_idx += 1) {
// Declarations in the same file do not need to be public. // Declarations in the same file do not need to be public.
if (orig_handle == analysis_ctx.handle or analysis.isNodePublic(analysis_ctx.tree(), child_node)) { if (orig_handle == handle or analysis.isNodePublic(handle.tree, child_node)) {
try nodeToCompletion(list, analysis_ctx, orig_handle, child_node, config); try nodeToCompletion(list, .{ .node = child_node, .handle = handle }, orig_handle, config);
} }
} }
} }
const ResolveVarDeclFnAliasRewsult = struct { fn resolveVarDeclFnAlias(arena: *std.heap.ArenaAllocator, decl_handle: analysis.NodeWithHandle) !analysis.NodeWithHandle {
decl: *std.zig.ast.Node, const decl = decl_handle.node;
analysis_ctx: DocumentStore.AnalysisContext, const handle = decl_handle.handle;
};
fn resolveVarDeclFnAlias(analysis_ctx: *DocumentStore.AnalysisContext, decl: *std.zig.ast.Node) !ResolveVarDeclFnAliasRewsult {
if (decl.cast(std.zig.ast.Node.VarDecl)) |var_decl| { if (decl.cast(std.zig.ast.Node.VarDecl)) |var_decl| {
var child_analysis_context = analysis_ctx.*;
const child_node = block: { const child_node = block: {
if (var_decl.type_node) |type_node| { if (var_decl.type_node) |type_node| {
if (std.mem.eql(u8, "type", analysis_ctx.tree().tokenSlice(type_node.firstToken()))) { if (std.mem.eql(u8, "type", handle.tree.tokenSlice(type_node.firstToken()))) {
break :block var_decl.init_node orelse type_node; break :block var_decl.init_node orelse type_node;
} }
break :block type_node; break :block type_node;
@ -230,27 +231,28 @@ fn resolveVarDeclFnAlias(analysis_ctx: *DocumentStore.AnalysisContext, decl: *st
break :block var_decl.init_node.?; break :block var_decl.init_node.?;
}; };
if (analysis.resolveTypeOfNode(&child_analysis_context, child_node)) |resolved_node| { if (try analysis.resolveTypeOfNode(&document_store, arena, .{ .node = child_node, .handle = handle })) |resolved_node| {
if (resolved_node.id == .FnProto) { // TODO Just return it anyway?
return ResolveVarDeclFnAliasRewsult{ // This would allow deep goto definition etc.
.decl = resolved_node, // Try it out.
.analysis_ctx = child_analysis_context, if (resolved_node.node.id == .FnProto) {
}; return resolved_node;
} }
} }
} }
return ResolveVarDeclFnAliasRewsult{ return decl_handle;
.decl = decl,
.analysis_ctx = analysis_ctx.*,
};
} }
fn nodeToCompletion( fn nodeToCompletion(
list: *std.ArrayList(types.CompletionItem), list: *std.ArrayList(types.CompletionItem),
node_handle: analysis.NodeWithHandle, node_handle: analysis.NodeWithHandle,
orig_handle: *DocumentStore.Handle,
config: Config, config: Config,
) error{OutOfMemory}!void { ) error{OutOfMemory}!void {
const doc = if (try analysis.getDocComments(list.allocator, analysis_ctx.tree(), node)) |doc_comments| const node = node_handle.node;
const handle = node_handle.handle;
const doc = if (try analysis.getDocComments(list.allocator, handle.tree, node)) |doc_comments|
types.MarkupContent{ types.MarkupContent{
.kind = .Markdown, .kind = .Markdown,
.value = doc_comments, .value = doc_comments,
@ -260,7 +262,7 @@ fn nodeToCompletion(
switch (node.id) { switch (node.id) {
.ErrorSetDecl, .Root, .ContainerDecl => { .ErrorSetDecl, .Root, .ContainerDecl => {
try containerToCompletion(list, analysis_ctx, orig_handle, node, config); try containerToCompletion(list, node_handle, orig_handle, config);
}, },
.FnProto => { .FnProto => {
const func = node.cast(std.zig.ast.Node.FnProto).?; const func = node.cast(std.zig.ast.Node.FnProto).?;
@ -344,12 +346,12 @@ fn nodeToCompletion(
.kind = .Field, .kind = .Field,
}); });
}, },
else => if (analysis.nodeToString(analysis_ctx.tree(), node)) |string| { else => if (analysis.nodeToString(handle.tree, node)) |string| {
try list.append(.{ try list.append(.{
.label = string, .label = string,
.kind = .Field, .kind = .Field,
.documentation = doc, .documentation = doc,
.detail = analysis_ctx.tree().getNodeSource(node) .detail = handle.tree.getNodeSource(node),
}); });
}, },
} }
@ -374,16 +376,17 @@ fn identifierFromPosition(pos_index: usize, handle: DocumentStore.Handle) []cons
return text[start_idx + 1 .. end_idx]; return text[start_idx + 1 .. end_idx];
} }
fn gotoDefinitionSymbol(id: types.RequestId, analysis_ctx: *DocumentStore.AnalysisContext, decl_handle: analysis.DeclWithHandle) !void { fn gotoDefinitionSymbol(id: types.RequestId, arena: *std.heap.ArenaAllocator, decl_handle: analysis.DeclWithHandle) !void {
var handle = analysis_ctx.handle; var handle = decl_handle.handle;
const location = switch (decl_handle.decl.*) { const location = switch (decl_handle.decl.*) {
.ast_node => |node| block: { .ast_node => |node| block: {
const result = try resolveVarDeclFnAlias(analysis_ctx, node); const result = try resolveVarDeclFnAlias(arena, .{ .node = node, .handle = handle });
handle = result.analysis_ctx.handle; handle = result.handle;
const name_token = analysis.getDeclNameToken(handle.tree, result.decl) orelse
const name_token = analysis.getDeclNameToken(result.handle.tree, result.node) orelse
return try respondGeneric(id, null_result_response); return try respondGeneric(id, null_result_response);
break :block handle.tree.tokenLocation(0, name_token); break :block result.handle.tree.tokenLocation(0, name_token);
}, },
else => decl_handle.location(), else => decl_handle.location(),
}; };
@ -399,35 +402,41 @@ fn gotoDefinitionSymbol(id: types.RequestId, analysis_ctx: *DocumentStore.Analys
}); });
} }
fn hoverSymbol(id: types.RequestId, analysis_ctx: *DocumentStore.AnalysisContext, decl: *std.zig.ast.Node) !void { fn hoverSymbol(id: types.RequestId, arena: *std.heap.ArenaAllocator, decl_handle: analysis.DeclWithHandle) !void {
const result = try resolveVarDeclFnAlias(analysis_ctx, decl); switch (decl_handle.decl.*) {
.ast_node => |node| {
const result = try resolveVarDeclFnAlias(arena, .{ .node = node, .handle = decl_handle.handle });
const doc_str = if (try analysis.getDocComments(&analysis_ctx.arena.allocator, result.analysis_ctx.tree(), result.decl)) |str| const doc_str = if (try analysis.getDocComments(&arena.allocator, result.handle.tree, result.node)) |str|
str str
else else
""; "";
const signature_str = switch (result.decl.id) { const signature_str = switch (result.node.id) {
.VarDecl => blk: { .VarDecl => blk: {
const var_decl = result.decl.cast(std.zig.ast.Node.VarDecl).?; const var_decl = result.node.cast(std.zig.ast.Node.VarDecl).?;
break :blk analysis.getVariableSignature(result.analysis_ctx.tree(), var_decl); break :blk analysis.getVariableSignature(result.handle.tree, var_decl);
}, },
.FnProto => blk: { .FnProto => blk: {
const fn_decl = result.decl.cast(std.zig.ast.Node.FnProto).?; const fn_decl = result.node.cast(std.zig.ast.Node.FnProto).?;
break :blk analysis.getFunctionSignature(result.analysis_ctx.tree(), fn_decl); break :blk analysis.getFunctionSignature(result.handle.tree, fn_decl);
}, },
else => analysis.nodeToString(result.analysis_ctx.tree(), result.decl) orelse return try respondGeneric(id, null_result_response), else => analysis.nodeToString(result.handle.tree, result.node) orelse return try respondGeneric(id, null_result_response),
}; };
const md_string = try std.fmt.allocPrint(&analysis_ctx.arena.allocator, "```zig\n{}\n```\n{}", .{ signature_str, doc_str }); const md_string = try std.fmt.allocPrint(&arena.allocator, "```zig\n{}\n```\n{}", .{ signature_str, doc_str });
try send(types.Response{ try send(types.Response{
.id = id, .id = id,
.result = .{ .result = .{
.Hover = .{ .Hover = .{
.contents = .{ .value = md_string }, .contents = .{ .value = md_string },
}, },
},
});
}, },
}); // @TODO Rest of decls
else => return try respondGeneric(id, null_result_response),
}
} }
fn getSymbolGlobal(arena: *std.heap.ArenaAllocator, pos_index: usize, handle: *DocumentStore.Handle) !?analysis.DeclWithHandle { fn getSymbolGlobal(arena: *std.heap.ArenaAllocator, pos_index: usize, handle: *DocumentStore.Handle) !?analysis.DeclWithHandle {
@ -442,36 +451,33 @@ fn gotoDefinitionGlobal(id: types.RequestId, pos_index: usize, handle: *Document
defer arena.deinit(); defer arena.deinit();
const decl = (try getSymbolGlobal(&arena, pos_index, handle)) orelse return try respondGeneric(id, null_result_response); const decl = (try getSymbolGlobal(&arena, pos_index, handle)) orelse return try respondGeneric(id, null_result_response);
return try gotoDefinitionSymbol(id, &arena, decl);
var analysis_ctx = try document_store.analysisContext(decl.handle, &arena, config.zig_lib_path);
return try gotoDefinitionSymbol(id, &analysis_ctx, decl);
} }
fn hoverDefinitionGlobal(id: types.RequestId, pos_index: usize, handle: *DocumentStore.Handle, config: Config) !void { fn hoverDefinitionGlobal(id: types.RequestId, pos_index: usize, handle: *DocumentStore.Handle, config: Config) !void {
var arena = std.heap.ArenaAllocator.init(allocator); var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit(); defer arena.deinit();
const decl = (try getSymbolGlobal(&arena, pos_index, handle.*)) orelse return try respondGeneric(id, null_result_response); const decl = (try getSymbolGlobal(&arena, pos_index, handle)) orelse return try respondGeneric(id, null_result_response);
var analysis_ctx = try document_store.analysisContext(handle, &arena, pos_index, config.zig_lib_path); return try hoverSymbol(id, &arena, decl);
return try hoverSymbol(id, &analysis_ctx, decl);
} }
fn getSymbolFieldAccess( fn getSymbolFieldAccess(
analysis_ctx: *DocumentStore.AnalysisContext, handle: *DocumentStore.Handle,
arena: *std.heap.ArenaAllocator,
position: types.Position, position: types.Position,
range: analysis.SourceRange, range: analysis.SourceRange,
config: Config, config: Config,
) !?*std.zig.ast.Node { ) !?analysis.DeclWithHandle {
const pos_index = try analysis_ctx.handle.document.positionToIndex(position); const pos_index = try handle.document.positionToIndex(position);
var name = identifierFromPosition(pos_index, analysis_ctx.handle.*); const name = identifierFromPosition(pos_index, handle.*);
if (name.len == 0) return null; if (name.len == 0) return null;
const line = try analysis_ctx.handle.document.getLine(@intCast(usize, position.line)); const line = try handle.document.getLine(@intCast(usize, position.line));
var tokenizer = std.zig.Tokenizer.init(line[range.start..range.end]); var tokenizer = std.zig.Tokenizer.init(line[range.start..range.end]);
name = try std.mem.dupe(&analysis_ctx.arena.allocator, u8, name); if (try analysis.getFieldAccessTypeNode(&document_store, arena, handle, &tokenizer)) |container_handle| {
if (analysis.getFieldAccessTypeNode(analysis_ctx, &tokenizer)) |container| { return try analysis.lookupSymbolContainer(&document_store, container_handle, name, true);
return analysis.getChild(analysis_ctx.tree(), container, name);
} }
return null; return null;
} }
@ -486,9 +492,8 @@ fn gotoDefinitionFieldAccess(
var arena = std.heap.ArenaAllocator.init(allocator); var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit(); defer arena.deinit();
var analysis_ctx = try document_store.analysisContext(handle, &arena, config.zig_lib_path); const decl = (try getSymbolFieldAccess(handle, &arena, position, range, config)) orelse return try respondGeneric(id, null_result_response);
const decl = (try getSymbolFieldAccess(&analysis_ctx, position, range, config)) orelse return try respondGeneric(id, null_result_response); return try gotoDefinitionSymbol(id, &arena, decl);
return try gotoDefinitionSymbol(id, &analysis_ctx, decl);
} }
fn hoverDefinitionFieldAccess( fn hoverDefinitionFieldAccess(
@ -501,9 +506,8 @@ fn hoverDefinitionFieldAccess(
var arena = std.heap.ArenaAllocator.init(allocator); var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit(); defer arena.deinit();
var analysis_ctx = try document_store.analysisContext(handle, &arena, try handle.document.positionToIndex(position), config.zig_lib_path); const decl = (try getSymbolFieldAccess(handle, &arena, position, range, config)) orelse return try respondGeneric(id, null_result_response);
const decl = (try getSymbolFieldAccess(&analysis_ctx, position, range, config)) orelse return try respondGeneric(id, null_result_response); return try hoverSymbol(id, &arena, decl);
return try hoverSymbol(id, &analysis_ctx, decl);
} }
fn gotoDefinitionString(id: types.RequestId, pos_index: usize, handle: *DocumentStore.Handle, config: Config) !void { fn gotoDefinitionString(id: types.RequestId, pos_index: usize, handle: *DocumentStore.Handle, config: Config) !void {
@ -537,12 +541,13 @@ const DeclToCompletionContext = struct {
completions: *std.ArrayList(types.CompletionItem), completions: *std.ArrayList(types.CompletionItem),
config: *const Config, config: *const Config,
arena: *std.heap.ArenaAllocator, arena: *std.heap.ArenaAllocator,
orig_handle: *DocumentStore.Handle,
}; };
fn decltoCompletion(context: DeclToCompletionContext, decl_handle: analysis.DeclWithHandle) !void { fn decltoCompletion(context: DeclToCompletionContext, decl_handle: analysis.DeclWithHandle) !void {
switch (decl_handle.decl.*) { switch (decl_handle.decl.*) {
.ast_node => |node| { .ast_node => |node| {
try nodeToCompletion(context.completions, .{ .node = node, .handle = decl_handle.handle }, context.config.*); try nodeToCompletion(context.completions, .{ .node = node, .handle = decl_handle.handle }, context.orig_handle, context.config.*);
}, },
else => {}, else => {},
// @TODO The rest // @TODO The rest
@ -560,6 +565,7 @@ fn completeGlobal(id: types.RequestId, pos_index: usize, handle: *DocumentStore.
.completions = &completions, .completions = &completions,
.config = &config, .config = &config,
.arena = &arena, .arena = &arena,
.orig_handle = handle,
}; };
try analysis.iterateSymbolsGlobal(&document_store, handle, pos_index, decltoCompletion, context); try analysis.iterateSymbolsGlobal(&document_store, handle, pos_index, decltoCompletion, context);
@ -578,15 +584,15 @@ fn completeFieldAccess(id: types.RequestId, handle: *DocumentStore.Handle, posit
var arena = std.heap.ArenaAllocator.init(allocator); var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit(); defer arena.deinit();
var analysis_ctx = try document_store.analysisContext(handle, &arena, config.zig_lib_path);
var completions = std.ArrayList(types.CompletionItem).init(&arena.allocator); var completions = std.ArrayList(types.CompletionItem).init(&arena.allocator);
const line = try handle.document.getLine(@intCast(usize, position.line)); const line = try handle.document.getLine(@intCast(usize, position.line));
var tokenizer = std.zig.Tokenizer.init(line[range.start..range.end]); var tokenizer = std.zig.Tokenizer.init(line[range.start..range.end]);
if (analysis.getFieldAccessTypeNode(&analysis_ctx, &tokenizer)) |node| { if (try analysis.getFieldAccessTypeNode(&document_store, &arena, handle, &tokenizer)) |node| {
try nodeToCompletion(&completions, &analysis_ctx, handle, node, config); try nodeToCompletion(&completions, node, handle, config);
} }
try send(types.Response{ try send(types.Response{
.id = id, .id = id,
.result = .{ .result = .{