|
| 1 | +//! This diagnostic provides an assist for creating a struct definition from a JSON |
| 2 | +//! example. |
| 3 | +
|
| 4 | +use ide_db::{base_db::FileId, source_change::SourceChange}; |
| 5 | +use itertools::Itertools; |
| 6 | +use stdx::format_to; |
| 7 | +use syntax::{ |
| 8 | + ast::{self, make}, |
| 9 | + SyntaxKind, SyntaxNode, |
| 10 | +}; |
| 11 | +use text_edit::TextEdit; |
| 12 | + |
| 13 | +use crate::{fix, Diagnostic, Severity}; |
| 14 | + |
| 15 | +#[derive(Default)] |
| 16 | +struct State { |
| 17 | + result: String, |
| 18 | + struct_counts: usize, |
| 19 | +} |
| 20 | + |
| 21 | +impl State { |
| 22 | + fn generate_new_name(&mut self) -> ast::Name { |
| 23 | + self.struct_counts += 1; |
| 24 | + make::name(&format!("Struct{}", self.struct_counts)) |
| 25 | + } |
| 26 | + |
| 27 | + fn build_struct(&mut self, value: &serde_json::Map<String, serde_json::Value>) -> ast::Type { |
| 28 | + let name = self.generate_new_name(); |
| 29 | + let ty = make::ty(&name.to_string()); |
| 30 | + let strukt = make::struct_( |
| 31 | + None, |
| 32 | + name, |
| 33 | + None, |
| 34 | + make::record_field_list(value.iter().sorted_unstable_by_key(|x| x.0).map( |
| 35 | + |(name, value)| make::record_field(None, make::name(name), self.type_of(value)), |
| 36 | + )) |
| 37 | + .into(), |
| 38 | + ); |
| 39 | + format_to!(self.result, "#[derive(Serialize, Deserialize)]\n{}\n", strukt); |
| 40 | + ty |
| 41 | + } |
| 42 | + |
| 43 | + fn type_of(&mut self, value: &serde_json::Value) -> ast::Type { |
| 44 | + match value { |
| 45 | + serde_json::Value::Null => make::ty_unit(), |
| 46 | + serde_json::Value::Bool(_) => make::ty("bool"), |
| 47 | + serde_json::Value::Number(x) => make::ty(if x.is_i64() { "i64" } else { "f64" }), |
| 48 | + serde_json::Value::String(_) => make::ty("String"), |
| 49 | + serde_json::Value::Array(x) => { |
| 50 | + let ty = match x.iter().next() { |
| 51 | + Some(x) => self.type_of(x), |
| 52 | + None => make::ty_placeholder(), |
| 53 | + }; |
| 54 | + make::ty(&format!("Vec<{ty}>")) |
| 55 | + } |
| 56 | + serde_json::Value::Object(x) => self.build_struct(x), |
| 57 | + } |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +pub(crate) fn json_in_items(acc: &mut Vec<Diagnostic>, file_id: FileId, node: &SyntaxNode) { |
| 62 | + if node.kind() == SyntaxKind::ERROR |
| 63 | + && node.first_token().map(|x| x.kind()) == Some(SyntaxKind::L_CURLY) |
| 64 | + && node.last_token().map(|x| x.kind()) == Some(SyntaxKind::R_CURLY) |
| 65 | + { |
| 66 | + let node_string = node.to_string(); |
| 67 | + if let Ok(x) = serde_json::from_str(&node_string) { |
| 68 | + if let serde_json::Value::Object(x) = x { |
| 69 | + let range = node.text_range(); |
| 70 | + let mut edit = TextEdit::builder(); |
| 71 | + edit.delete(range); |
| 72 | + let mut state = State::default(); |
| 73 | + state.build_struct(&x); |
| 74 | + edit.insert(range.start(), state.result); |
| 75 | + acc.push( |
| 76 | + Diagnostic::new( |
| 77 | + "json-is-not-rust", |
| 78 | + "JSON syntax is not valid as a Rust item", |
| 79 | + range, |
| 80 | + ) |
| 81 | + .severity(Severity::WeakWarning) |
| 82 | + .with_fixes(Some(vec![fix( |
| 83 | + "convert_json_to_struct", |
| 84 | + "Convert JSON to struct", |
| 85 | + SourceChange::from_text_edit(file_id, edit.finish()), |
| 86 | + range, |
| 87 | + )])), |
| 88 | + ); |
| 89 | + } |
| 90 | + } |
| 91 | + } |
| 92 | +} |
| 93 | + |
| 94 | +#[cfg(test)] |
| 95 | +mod tests { |
| 96 | + use crate::{ |
| 97 | + tests::{check_diagnostics_with_config, check_fix, check_no_fix}, |
| 98 | + DiagnosticsConfig, |
| 99 | + }; |
| 100 | + |
| 101 | + #[test] |
| 102 | + fn diagnostic_for_simple_case() { |
| 103 | + let mut config = DiagnosticsConfig::default(); |
| 104 | + config.disabled.insert("syntax-error".to_string()); |
| 105 | + check_diagnostics_with_config( |
| 106 | + config, |
| 107 | + r#" |
| 108 | + { "foo": "bar" } |
| 109 | + // ^^^^^^^^^^^^^^^^ 💡 weak: JSON syntax is not valid as a Rust item |
| 110 | +"#, |
| 111 | + ); |
| 112 | + } |
| 113 | + |
| 114 | + #[test] |
| 115 | + fn types_of_primitives() { |
| 116 | + check_fix( |
| 117 | + r#" |
| 118 | + {$0 |
| 119 | + "foo": "bar", |
| 120 | + "bar": 2.3, |
| 121 | + "baz": null, |
| 122 | + "bay": 57, |
| 123 | + "box": true |
| 124 | + } |
| 125 | + "#, |
| 126 | + r#" |
| 127 | + #[derive(Serialize, Deserialize)] |
| 128 | + struct Struct1{ bar: f64, bay: i64, baz: (), r#box: bool, foo: String } |
| 129 | +
|
| 130 | + "#, |
| 131 | + ); |
| 132 | + } |
| 133 | + |
| 134 | + #[test] |
| 135 | + fn nested_structs() { |
| 136 | + check_fix( |
| 137 | + r#" |
| 138 | + {$0 |
| 139 | + "foo": "bar", |
| 140 | + "bar": { |
| 141 | + "kind": "Object", |
| 142 | + "value": {} |
| 143 | + } |
| 144 | + } |
| 145 | + "#, |
| 146 | + r#" |
| 147 | + #[derive(Serialize, Deserialize)] |
| 148 | + struct Struct3{ } |
| 149 | + #[derive(Serialize, Deserialize)] |
| 150 | + struct Struct2{ kind: String, value: Struct3 } |
| 151 | + #[derive(Serialize, Deserialize)] |
| 152 | + struct Struct1{ bar: Struct2, foo: String } |
| 153 | +
|
| 154 | + "#, |
| 155 | + ); |
| 156 | + } |
| 157 | + |
| 158 | + #[test] |
| 159 | + fn arrays() { |
| 160 | + check_fix( |
| 161 | + r#" |
| 162 | + { |
| 163 | + "of_string": ["foo", "2", "x"], $0 |
| 164 | + "of_object": [{ |
| 165 | + "x": 10, |
| 166 | + "y": 20 |
| 167 | + }, { |
| 168 | + "x": 10, |
| 169 | + "y": 20 |
| 170 | + }], |
| 171 | + "nested": [[[2]]], |
| 172 | + "empty": [] |
| 173 | + } |
| 174 | + "#, |
| 175 | + r#" |
| 176 | + #[derive(Serialize, Deserialize)] |
| 177 | + struct Struct2{ x: i64, y: i64 } |
| 178 | + #[derive(Serialize, Deserialize)] |
| 179 | + struct Struct1{ empty: Vec<_>, nested: Vec<Vec<Vec<i64>>>, of_object: Vec<Struct2>, of_string: Vec<String> } |
| 180 | +
|
| 181 | + "#, |
| 182 | + ); |
| 183 | + } |
| 184 | + |
| 185 | + #[test] |
| 186 | + fn no_emit_outside_of_item_position() { |
| 187 | + check_no_fix( |
| 188 | + r#" |
| 189 | + fn foo() { |
| 190 | + let json = {$0 |
| 191 | + "foo": "bar", |
| 192 | + "bar": { |
| 193 | + "kind": "Object", |
| 194 | + "value": {} |
| 195 | + } |
| 196 | + }; |
| 197 | + } |
| 198 | + "#, |
| 199 | + ); |
| 200 | + } |
| 201 | +} |
0 commit comments