Skip to content
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

Implement Code Action to Generate JSON Encoder #4229

Merged
merged 8 commits into from
Feb 11, 2025
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
28 changes: 28 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,34 @@

([Giacomo Cavalieri](https://github.com/giacomocavalieri))

- The Language Server now suggests a code action to generate a function to
encode a custom type as JSON using the `gleam_json` package. For example:

```gleam
pub type Person {
Person(name: String, age: Int)
}
```

Will become:

```gleam
import gleam/json

pub type Person {
Person(name: String, age: Int)
}

fn encode_person(person: Person) -> json.Json {
json.object([
#("name", json.string(person.name)),
#("age", json.int(person.age)),
])
}
```

([Surya Rose](https://github.com/GearsDatapacks))

### Formatter

### Bug fixes
271 changes: 271 additions & 0 deletions compiler-core/src/language_server/code_action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3281,6 +3281,277 @@ impl<'a> DecoderPrinter<'a> {
}
}

/// Builder for code action to apply the "Generate JSON encoder" action.
///
pub struct GenerateJsonEncoder<'a> {
module: &'a Module,
params: &'a CodeActionParams,
edits: TextEdits<'a>,
printer: Printer<'a>,
actions: &'a mut Vec<CodeAction>,
}

const JSON_MODULE: &str = "gleam/json";
const JSON_PACKAGE_NAME: &str = "gleam_json";

impl<'a> GenerateJsonEncoder<'a> {
pub fn new(
module: &'a Module,
line_numbers: &'a LineNumbers,
params: &'a CodeActionParams,
actions: &'a mut Vec<CodeAction>,
) -> Self {
let printer = Printer::new(&module.ast.names);
Self {
module,
params,
edits: TextEdits::new(line_numbers),
printer,
actions,
}
}

pub fn code_actions(&mut self) {
self.visit_typed_module(&self.module.ast);
}
}

impl<'ast> ast::visit::Visit<'ast> for GenerateJsonEncoder<'ast> {
fn visit_typed_custom_type(&mut self, custom_type: &'ast ast::TypedCustomType) {
let range = self.edits.src_span_to_lsp_range(custom_type.location);
if !overlaps(self.params.range, range) {
return;
}

// For now, we only generate json encoders for types with one variant.
let constructor = match custom_type.constructors.as_slice() {
[constructor] => constructor,
_ => return,
};

let record_name = custom_type.name.to_snake_case();
let name = eco_format!("encode_{record_name}");

let Some(fields): Option<Vec<_>> = constructor
.arguments
.iter()
.map(|argument| {
Some(RecordField {
label: RecordLabel::Labeled(
argument.label.as_ref().map(|(_, name)| name.as_str())?,
),
type_: &argument.type_,
})
})
.collect()
else {
return;
};

let mut encoder_printer = EncoderPrinter::new(
&self.module.ast.names,
custom_type.name.clone(),
self.module.name.clone(),
);

let encoders = fields
.iter()
.map(|field| encoder_printer.encode_field(&record_name, field, 4))
.join(",\n");

let json_type = self.printer.print_type(&Type::Named {
publicity: ast::Publicity::Public,
package: JSON_PACKAGE_NAME.into(),
module: JSON_MODULE.into(),
name: "Json".into(),
args: vec![],
inferred_variant: None,
});
let json_module = self.printer.print_module(JSON_MODULE);
let parameters = match custom_type.parameters.len() {
0 => EcoString::new(),
_ => eco_format!(
"({})",
custom_type
.parameters
.iter()
.map(|(_, name)| name)
.join(", ")
),
};

let function = format!(
"

fn {name}({record_name}: {type_name}{parameters}) -> {json_type} {{
{json_module}.object([
{encoders},
])
}}",
type_name = custom_type.name,
);

self.edits.insert(custom_type.end_position, function);
maybe_import(&mut self.edits, self.module, JSON_MODULE);

CodeActionBuilder::new("Generate JSON encoder")
.kind(CodeActionKind::REFACTOR)
.preferred(false)
.changes(
self.params.text_document.uri.clone(),
std::mem::take(&mut self.edits.edits),
)
.push_to(self.actions);
}
}

struct EncoderPrinter<'a> {
printer: Printer<'a>,
/// The name of the root type we are printing an encoder for
type_name: EcoString,
/// The module name of the root type we are printing an encoder for
type_module: EcoString,
}

impl<'a> EncoderPrinter<'a> {
fn new(names: &'a Names, type_name: EcoString, type_module: EcoString) -> Self {
Self {
type_name,
type_module,
printer: Printer::new(names),
}
}

fn encoder_for(&mut self, encoded_value: &str, type_: &Type, indent: usize) -> EcoString {
let module_name = self.printer.print_module(JSON_MODULE);
let is_capture = encoded_value == "_";
let maybe_capture = |mut function: EcoString| {
if is_capture {
function
} else {
function.push('(');
function.push_str(encoded_value);
function.push(')');
function
}
};

if type_.is_bool() {
maybe_capture(eco_format!("{module_name}.bool"))
} else if type_.is_float() {
maybe_capture(eco_format!("{module_name}.float"))
} else if type_.is_int() {
maybe_capture(eco_format!("{module_name}.int"))
} else if type_.is_string() {
maybe_capture(eco_format!("{module_name}.string"))
} else if let Some(types) = type_.tuple_types() {
let (tuple, new_indent) = if is_capture {
("value", indent + 4)
} else {
(encoded_value, indent + 2)
};

let encoders = types
.iter()
.enumerate()
.map(|(index, type_)| {
self.encoder_for(&format!("{tuple}.{index}"), type_, new_indent)
})
.collect_vec();

if is_capture {
eco_format!(
"fn(value) {{
{indent} {module_name}.preprocessed_array([
{indent} {encoders},
{indent} ])
{indent}}}",
indent = " ".repeat(indent),
encoders = encoders.join(&format!(",\n{}", " ".repeat(new_indent))),
)
} else {
eco_format!(
"{module_name}.preprocessed_array([
{indent} {encoders},
{indent}])",
indent = " ".repeat(indent),
encoders = encoders.join(&format!(",\n{}", " ".repeat(new_indent))),
)
}
} else {
let type_information = type_.named_type_information();
let type_information: Option<(&str, &str, &[Arc<Type>])> =
type_information.as_ref().map(|(module, name, arguments)| {
(module.as_str(), name.as_str(), arguments.as_slice())
});

match type_information {
Some(("gleam", "List", [element])) => {
eco_format!(
"{module_name}.array({encoded_value}, {map_function})",
map_function = self.encoder_for("_", element, indent)
)
}
Some(("gleam/option", "Option", [some])) => {
eco_format!(
"case {encoded_value} {{
{indent} {none} -> {module_name}.null()
{indent} {some}(value) -> {encoder}
{indent}}}",
indent = " ".repeat(indent),
none = self
.printer
.print_constructor(&"gleam/option".into(), &"None".into()),
some = self
.printer
.print_constructor(&"gleam/option".into(), &"Some".into()),
encoder = self.encoder_for("value", some, indent + 2)
)
}
Some(("gleam/dict", "Dict", [key, value])) => {
let stringify_function = match key.named_type_information().as_ref().map(
|(module, name, arguments)| {
(module.as_str(), name.as_str(), arguments.as_slice())
},
) {
Some(("gleam", "String", [])) => "fn(string) { string }",
_ => &format!(
r#"todo as "Function to stringify {}""#,
self.printer.print_type(key)
),
};
eco_format!(
"{module_name}.dict({encoded_value}, {stringify_function}, {})",
self.encoder_for("_", value, indent)
)
}
Some((module, name, _)) if module == self.type_module && name == self.type_name => {
maybe_capture(eco_format!("encode_{}", name.to_snake_case()))
}
_ => eco_format!(
r#"todo as "Encoder for {}""#,
self.printer.print_type(type_)
),
}
}
}

fn encode_field(
&mut self,
record_name: &str,
field: &RecordField<'_>,
indent: usize,
) -> EcoString {
let field_name = field.label.variable_name();
let encoder = self.encoder_for(&format!("{record_name}.{field_name}"), field.type_, indent);

eco_format!(
r#"{indent}#("{field_name}", {encoder})"#,
indent = " ".repeat(indent),
)
}
}

/// Builder for code action to pattern match on things like (anonymous) function
/// arguments or variables.
/// For example:
Expand Down
6 changes: 4 additions & 2 deletions compiler-core/src/language_server/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@ use super::{
code_action_convert_unqualified_constructor_to_qualified, code_action_import_module,
code_action_inexhaustive_let_to_case, AddAnnotations, CodeActionBuilder,
ConvertToFunctionCall, DesugarUse, ExpandFunctionCapture, ExtractVariable,
FillInMissingLabelledArgs, GenerateDynamicDecoder, GenerateFunction, LetAssertToCase,
PatternMatchOnValue, RedundantTupleInCaseSubject, TurnIntoUse, UseLabelShorthandSyntax,
FillInMissingLabelledArgs, GenerateDynamicDecoder, GenerateFunction, GenerateJsonEncoder,
LetAssertToCase, PatternMatchOnValue, RedundantTupleInCaseSubject, TurnIntoUse,
UseLabelShorthandSyntax,
},
completer::Completer,
rename::{rename_local_variable, VariableRenameKind},
Expand Down Expand Up @@ -343,6 +344,7 @@ where
PatternMatchOnValue::new(module, &lines, &params, &this.compiler).code_actions(),
);
GenerateDynamicDecoder::new(module, &lines, &params, &mut actions).code_actions();
GenerateJsonEncoder::new(module, &lines, &params, &mut actions).code_actions();
AddAnnotations::new(module, &lines, &params).code_action(&mut actions);
Ok(if actions.is_empty() {
None
Expand Down
Loading
Loading