Skip to content

Generate rust type from json #12905

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/hir/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use crate::{MacroKind, Type};

macro_rules! diagnostics {
($($diag:ident,)*) => {
#[derive(Debug)]
pub enum AnyDiagnostic {$(
$diag(Box<$diag>),
)*}
Expand Down
157 changes: 10 additions & 147 deletions crates/ide-assists/src/assist_context.rs
Original file line number Diff line number Diff line change
@@ -1,28 +1,20 @@
//! See [`AssistContext`].

use std::mem;

use hir::Semantics;
use ide_db::{
base_db::{AnchoredPathBuf, FileId, FileRange},
SnippetCap,
};
use ide_db::{
label::Label,
source_change::{FileSystemEdit, SourceChange},
RootDatabase,
};
use ide_db::base_db::{FileId, FileRange};
use ide_db::{label::Label, RootDatabase};
use syntax::{
algo::{self, find_node_at_offset, find_node_at_range},
AstNode, AstToken, Direction, SourceFile, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxNodePtr,
SyntaxToken, TextRange, TextSize, TokenAtOffset,
AstNode, AstToken, Direction, SourceFile, SyntaxElement, SyntaxKind, SyntaxToken, TextRange,
TextSize, TokenAtOffset,
};
use text_edit::{TextEdit, TextEditBuilder};

use crate::{
assist_config::AssistConfig, Assist, AssistId, AssistKind, AssistResolveStrategy, GroupLabel,
};

pub(crate) use ide_db::source_change::{SourceChangeBuilder, TreeMutator};

/// `AssistContext` allows to apply an assist or check if it could be applied.
///
/// Assists use a somewhat over-engineered approach, given the current needs.
Expand Down Expand Up @@ -163,7 +155,7 @@ impl Assists {
id: AssistId,
label: impl Into<String>,
target: TextRange,
f: impl FnOnce(&mut AssistBuilder),
f: impl FnOnce(&mut SourceChangeBuilder),
) -> Option<()> {
let mut f = Some(f);
self.add_impl(None, id, label.into(), target, &mut |it| f.take().unwrap()(it))
Expand All @@ -175,7 +167,7 @@ impl Assists {
id: AssistId,
label: impl Into<String>,
target: TextRange,
f: impl FnOnce(&mut AssistBuilder),
f: impl FnOnce(&mut SourceChangeBuilder),
) -> Option<()> {
let mut f = Some(f);
self.add_impl(Some(group), id, label.into(), target, &mut |it| f.take().unwrap()(it))
Expand All @@ -187,15 +179,15 @@ impl Assists {
id: AssistId,
label: String,
target: TextRange,
f: &mut dyn FnMut(&mut AssistBuilder),
f: &mut dyn FnMut(&mut SourceChangeBuilder),
) -> Option<()> {
if !self.is_allowed(&id) {
return None;
}

let mut trigger_signature_help = false;
let source_change = if self.resolve.should_resolve(&id) {
let mut builder = AssistBuilder::new(self.file);
let mut builder = SourceChangeBuilder::new(self.file);
f(&mut builder);
trigger_signature_help = builder.trigger_signature_help;
Some(builder.finish())
Expand All @@ -216,132 +208,3 @@ impl Assists {
}
}
}

pub(crate) struct AssistBuilder {
edit: TextEditBuilder,
file_id: FileId,
source_change: SourceChange,
trigger_signature_help: bool,

/// Maps the original, immutable `SyntaxNode` to a `clone_for_update` twin.
mutated_tree: Option<TreeMutator>,
}

pub(crate) struct TreeMutator {
immutable: SyntaxNode,
mutable_clone: SyntaxNode,
}

impl TreeMutator {
pub(crate) fn new(immutable: &SyntaxNode) -> TreeMutator {
let immutable = immutable.ancestors().last().unwrap();
let mutable_clone = immutable.clone_for_update();
TreeMutator { immutable, mutable_clone }
}

pub(crate) fn make_mut<N: AstNode>(&self, node: &N) -> N {
N::cast(self.make_syntax_mut(node.syntax())).unwrap()
}

pub(crate) fn make_syntax_mut(&self, node: &SyntaxNode) -> SyntaxNode {
let ptr = SyntaxNodePtr::new(node);
ptr.to_node(&self.mutable_clone)
}
}

impl AssistBuilder {
pub(crate) fn new(file_id: FileId) -> AssistBuilder {
AssistBuilder {
edit: TextEdit::builder(),
file_id,
source_change: SourceChange::default(),
trigger_signature_help: false,
mutated_tree: None,
}
}

pub(crate) fn edit_file(&mut self, file_id: FileId) {
self.commit();
self.file_id = file_id;
}

fn commit(&mut self) {
if let Some(tm) = self.mutated_tree.take() {
algo::diff(&tm.immutable, &tm.mutable_clone).into_text_edit(&mut self.edit)
}

let edit = mem::take(&mut self.edit).finish();
if !edit.is_empty() {
self.source_change.insert_source_edit(self.file_id, edit);
}
}

pub(crate) fn make_mut<N: AstNode>(&mut self, node: N) -> N {
self.mutated_tree.get_or_insert_with(|| TreeMutator::new(node.syntax())).make_mut(&node)
}
/// Returns a copy of the `node`, suitable for mutation.
///
/// Syntax trees in rust-analyzer are typically immutable, and mutating
/// operations panic at runtime. However, it is possible to make a copy of
/// the tree and mutate the copy freely. Mutation is based on interior
/// mutability, and different nodes in the same tree see the same mutations.
///
/// The typical pattern for an assist is to find specific nodes in the read
/// phase, and then get their mutable couterparts using `make_mut` in the
/// mutable state.
pub(crate) fn make_syntax_mut(&mut self, node: SyntaxNode) -> SyntaxNode {
self.mutated_tree.get_or_insert_with(|| TreeMutator::new(&node)).make_syntax_mut(&node)
}

/// Remove specified `range` of text.
pub(crate) fn delete(&mut self, range: TextRange) {
self.edit.delete(range)
}
/// Append specified `text` at the given `offset`
pub(crate) fn insert(&mut self, offset: TextSize, text: impl Into<String>) {
self.edit.insert(offset, text.into())
}
/// Append specified `snippet` at the given `offset`
pub(crate) fn insert_snippet(
&mut self,
_cap: SnippetCap,
offset: TextSize,
snippet: impl Into<String>,
) {
self.source_change.is_snippet = true;
self.insert(offset, snippet);
}
/// Replaces specified `range` of text with a given string.
pub(crate) fn replace(&mut self, range: TextRange, replace_with: impl Into<String>) {
self.edit.replace(range, replace_with.into())
}
/// Replaces specified `range` of text with a given `snippet`.
pub(crate) fn replace_snippet(
&mut self,
_cap: SnippetCap,
range: TextRange,
snippet: impl Into<String>,
) {
self.source_change.is_snippet = true;
self.replace(range, snippet);
}
pub(crate) fn replace_ast<N: AstNode>(&mut self, old: N, new: N) {
algo::diff(old.syntax(), new.syntax()).into_text_edit(&mut self.edit)
}
pub(crate) fn create_file(&mut self, dst: AnchoredPathBuf, content: impl Into<String>) {
let file_system_edit = FileSystemEdit::CreateFile { dst, initial_contents: content.into() };
self.source_change.push_file_system_edit(file_system_edit);
}
pub(crate) fn move_file(&mut self, src: FileId, dst: AnchoredPathBuf) {
let file_system_edit = FileSystemEdit::MoveFile { src, dst };
self.source_change.push_file_system_edit(file_system_edit);
}
pub(crate) fn trigger_signature_help(&mut self) {
self.trigger_signature_help = true;
}

fn finish(mut self) -> SourceChange {
self.commit();
mem::take(&mut self.source_change)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use syntax::{
match_ast, SyntaxNode,
};

use crate::{assist_context::AssistBuilder, AssistContext, AssistId, AssistKind, Assists};
use crate::{assist_context::SourceChangeBuilder, AssistContext, AssistId, AssistKind, Assists};

// Assist: convert_tuple_struct_to_named_struct
//
Expand Down Expand Up @@ -80,7 +80,7 @@ pub(crate) fn convert_tuple_struct_to_named_struct(

fn edit_struct_def(
ctx: &AssistContext<'_>,
edit: &mut AssistBuilder,
edit: &mut SourceChangeBuilder,
strukt: &Either<ast::Struct, ast::Variant>,
tuple_fields: ast::TupleFieldList,
names: Vec<ast::Name>,
Expand Down Expand Up @@ -122,7 +122,7 @@ fn edit_struct_def(

fn edit_struct_references(
ctx: &AssistContext<'_>,
edit: &mut AssistBuilder,
edit: &mut SourceChangeBuilder,
strukt: Either<hir::Struct, hir::Variant>,
names: &[ast::Name],
) {
Expand All @@ -132,7 +132,7 @@ fn edit_struct_references(
};
let usages = strukt_def.usages(&ctx.sema).include_self_refs().all();

let edit_node = |edit: &mut AssistBuilder, node: SyntaxNode| -> Option<()> {
let edit_node = |edit: &mut SourceChangeBuilder, node: SyntaxNode| -> Option<()> {
match_ast! {
match node {
ast::TupleStructPat(tuple_struct_pat) => {
Expand Down Expand Up @@ -203,7 +203,7 @@ fn edit_struct_references(

fn edit_field_references(
ctx: &AssistContext<'_>,
edit: &mut AssistBuilder,
edit: &mut SourceChangeBuilder,
fields: impl Iterator<Item = ast::TupleField>,
names: &[ast::Name],
) {
Expand Down
10 changes: 5 additions & 5 deletions crates/ide-assists/src/handlers/destructure_tuple_binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use syntax::{
TextRange,
};

use crate::assist_context::{AssistBuilder, AssistContext, Assists};
use crate::assist_context::{AssistContext, Assists, SourceChangeBuilder};

// Assist: destructure_tuple_binding
//
Expand Down Expand Up @@ -151,7 +151,7 @@ struct TupleData {
}
fn edit_tuple_assignment(
ctx: &AssistContext<'_>,
builder: &mut AssistBuilder,
builder: &mut SourceChangeBuilder,
data: &TupleData,
in_sub_pattern: bool,
) {
Expand Down Expand Up @@ -195,7 +195,7 @@ fn edit_tuple_assignment(

fn edit_tuple_usages(
data: &TupleData,
builder: &mut AssistBuilder,
builder: &mut SourceChangeBuilder,
ctx: &AssistContext<'_>,
in_sub_pattern: bool,
) {
Expand All @@ -211,7 +211,7 @@ fn edit_tuple_usages(
}
fn edit_tuple_usage(
ctx: &AssistContext<'_>,
builder: &mut AssistBuilder,
builder: &mut SourceChangeBuilder,
usage: &FileReference,
data: &TupleData,
in_sub_pattern: bool,
Expand Down Expand Up @@ -239,7 +239,7 @@ fn edit_tuple_usage(

fn edit_tuple_field_usage(
ctx: &AssistContext<'_>,
builder: &mut AssistBuilder,
builder: &mut SourceChangeBuilder,
data: &TupleData,
index: TupleIndex,
) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use syntax::{
SyntaxNode, T,
};

use crate::{assist_context::AssistBuilder, AssistContext, AssistId, AssistKind, Assists};
use crate::{assist_context::SourceChangeBuilder, AssistContext, AssistId, AssistKind, Assists};

// Assist: extract_struct_from_enum_variant
//
Expand Down Expand Up @@ -374,7 +374,7 @@ fn apply_references(

fn process_references(
ctx: &AssistContext<'_>,
builder: &mut AssistBuilder,
builder: &mut SourceChangeBuilder,
visited_modules: &mut FxHashSet<Module>,
enum_module_def: &ModuleDef,
variant_hir_name: &Name,
Expand Down
4 changes: 2 additions & 2 deletions crates/ide-assists/src/handlers/generate_deref.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use syntax::{
};

use crate::{
assist_context::{AssistBuilder, AssistContext, Assists},
assist_context::{AssistContext, Assists, SourceChangeBuilder},
utils::generate_trait_impl_text,
AssistId, AssistKind,
};
Expand Down Expand Up @@ -120,7 +120,7 @@ fn generate_tuple_deref(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()
}

fn generate_edit(
edit: &mut AssistBuilder,
edit: &mut SourceChangeBuilder,
strukt: ast::Struct,
field_type_syntax: &SyntaxNode,
field_name: impl Display,
Expand Down
4 changes: 2 additions & 2 deletions crates/ide-assists/src/handlers/introduce_named_lifetime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use syntax::{
AstNode, TextRange,
};

use crate::{assist_context::AssistBuilder, AssistContext, AssistId, AssistKind, Assists};
use crate::{assist_context::SourceChangeBuilder, AssistContext, AssistId, AssistKind, Assists};

static ASSIST_NAME: &str = "introduce_named_lifetime";
static ASSIST_LABEL: &str = "Introduce named lifetime";
Expand Down Expand Up @@ -140,7 +140,7 @@ enum NeedsLifetime {
}

impl NeedsLifetime {
fn make_mut(self, builder: &mut AssistBuilder) -> Self {
fn make_mut(self, builder: &mut SourceChangeBuilder) -> Self {
match self {
Self::SelfParam(it) => Self::SelfParam(builder.make_mut(it)),
Self::RefType(it) => Self::RefType(builder.make_mut(it)),
Expand Down
5 changes: 3 additions & 2 deletions crates/ide-assists/src/handlers/remove_unused_param.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ use syntax::{
use SyntaxKind::WHITESPACE;

use crate::{
assist_context::AssistBuilder, utils::next_prev, AssistContext, AssistId, AssistKind, Assists,
assist_context::SourceChangeBuilder, utils::next_prev, AssistContext, AssistId, AssistKind,
Assists,
};

// Assist: remove_unused_param
Expand Down Expand Up @@ -88,7 +89,7 @@ pub(crate) fn remove_unused_param(acc: &mut Assists, ctx: &AssistContext<'_>) ->

fn process_usages(
ctx: &AssistContext<'_>,
builder: &mut AssistBuilder,
builder: &mut SourceChangeBuilder,
file_id: FileId,
references: Vec<FileReference>,
arg_to_remove: usize,
Expand Down
Loading