microsoft/qdk
Publicmirrored from https://github.com/microsoft/qdkAvailable
source/language_service/src/completion/fields.rs
66lines · modeblame
29145c51Mine Starks1 years ago | 1 | // Copyright (c) Microsoft Corporation. |
| 2 | // Licensed under the MIT License. | |
| 3 | | |
e938e457orpuente-MS1 years ago | 4 | use super::{Completion, ast_context::AstContext}; |
29145c51Mine Starks1 years ago | 5 | use crate::{compilation::Compilation, protocol::CompletionItemKind}; |
| 6 | use qsc::{ | |
| 7 | display::Lookup, | |
| 8 | hir::{ | |
| 9 | ItemKind, Res, | |
e938e457orpuente-MS1 years ago | 10 | ty::{Ty, UdtDefKind}, |
29145c51Mine Starks1 years ago | 11 | }, |
| 12 | }; | |
| 13 | | |
| 14 | /// If there is an incomplete field access expression (e.g. `foo.bar.`) at the cursor offset, | |
| 15 | /// provides the possible field names. | |
| 16 | pub(super) struct Fields<'a> { | |
| 17 | compilation: &'a Compilation, | |
d591b52aMine Starks1 years ago | 18 | ast_context: &'a AstContext<'a>, |
29145c51Mine Starks1 years ago | 19 | } |
| 20 | | |
| 21 | impl<'a> Fields<'a> { | |
d591b52aMine Starks1 years ago | 22 | pub(crate) fn new(compilation: &'a Compilation, ast_context: &'a AstContext) -> Self { |
29145c51Mine Starks1 years ago | 23 | Self { |
| 24 | compilation, | |
d591b52aMine Starks1 years ago | 25 | ast_context, |
29145c51Mine Starks1 years ago | 26 | } |
| 27 | } | |
| 28 | | |
| 29 | pub(crate) fn fields(&self) -> Vec<Completion> { | |
d591b52aMine Starks1 years ago | 30 | let Some(id) = self.ast_context.field_access_context() else { |
29145c51Mine Starks1 years ago | 31 | return vec![]; |
| 32 | }; | |
| 33 | | |
| 34 | let mut completions = vec![]; | |
| 35 | let ty = self.compilation.get_ty(id); | |
| 36 | if let Some(Ty::Udt(_, Res::Item(item_id))) = ty { | |
| 37 | let (item, _, _) = self | |
| 38 | .compilation | |
| 39 | .resolve_item_relative_to_user_package(item_id); | |
| 40 | if let ItemKind::Ty(_, udt) = &item.kind { | |
| 41 | collect_fields(&mut completions, &udt.definition.kind); | |
| 42 | } | |
| 43 | } | |
| 44 | completions | |
| 45 | } | |
| 46 | } | |
| 47 | | |
| 48 | fn collect_fields(completions: &mut Vec<Completion>, field: &UdtDefKind) { | |
| 49 | match field { | |
| 50 | UdtDefKind::Field(field) => { | |
| 51 | if let Some(name) = &field.name { | |
| 52 | let detail = field.ty.display(); | |
| 53 | completions.push(Completion::with_detail( | |
| 54 | name.to_string(), | |
| 55 | CompletionItemKind::Field, | |
| 56 | Some(detail), | |
| 57 | )); | |
| 58 | } | |
| 59 | } | |
| 60 | UdtDefKind::Tuple(vec) => { | |
| 61 | for f in vec { | |
| 62 | collect_fields(completions, &f.kind); | |
| 63 | } | |
| 64 | } | |
| 65 | } | |
| 66 | } |