Skip to content
Open
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
7 changes: 7 additions & 0 deletions source/language_service/src/code_action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT License.

mod auto_import;
mod int_to_double;
mod wrap_in_array;
mod wrapper_refactor;

Expand Down Expand Up @@ -48,6 +49,12 @@ pub(crate) fn get_code_actions(
span,
position_encoding,
));
actions.extend(int_to_double::int_to_double_fixes(
compilation,
source_name,
span,
position_encoding,
));
actions
}

Expand Down
121 changes: 121 additions & 0 deletions source/language_service/src/code_action/int_to_double.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Code action: "Convert integer literal to double"
//! Detects when an integer literal is passed where a double is expected and
//! offers to add a trailing `.` to make it into a double literal.

#[cfg(test)]
mod tests;

use qsc::{
Span,
ast::{self, Expr, ExprKind, UnOp},
compile::{ErrorKind, TyInfoKind},
hir::ty::Prim,
line_column::Encoding,
};

use super::is_error_relevant;
use crate::{
compilation::Compilation,
protocol::{CodeAction, CodeActionKind, TextEdit, WorkspaceEdit},
qsc_utils::into_range,
};

pub(crate) fn int_to_double_fixes(
compilation: &Compilation,
source_name: &str,
span: Span,
encoding: Encoding,
) -> Vec<CodeAction> {
let mut code_actions = Vec::new();

let unit = compilation.user_unit();
let package = &unit.ast.package;
let source_map = &unit.sources;

let ty_mismatches = compilation
.compile_errors
.iter()
.filter(|error| is_error_relevant(error, span))
.filter_map(|error| match error.error() {
ErrorKind::Frontend(frontend_error) => frontend_error.ty_mismatch(),
_ => None,
});

for (expected, actual, error_span) in ty_mismatches {
// Check if expected is Double and actual is Int.
if matches!(&expected.kind, TyInfoKind::Prim(Prim::Double))
&& matches!(&actual.kind, TyInfoKind::Prim(Prim::Int))
{
// Confirm that it's a literal and not just some expression of type int
let Some(mut expr) = find_expr_at(package, error_span) else {
continue;
};

// Strip off any + or - unary operators
while let ExprKind::UnOp(UnOp::Pos | UnOp::Neg, inner) = expr.kind.as_ref() {
expr = inner;
}

if !matches!(expr.kind.as_ref(), ExprKind::Lit(_)) {
continue;
}

// Generate the fix: add a trailing `.`
// Note that this depends on the error span excluding surrounding parens
// so we don't end up with something like `(q).`.
let dot_range = into_range(
encoding,
Span {
lo: error_span.hi,
hi: error_span.hi,
},
source_map,
);

code_actions.push(CodeAction {
title: "Convert to double literal".to_string(),
edit: Some(WorkspaceEdit {
changes: vec![(
source_name.to_string(),
vec![TextEdit {
new_text: ".".to_string(),
range: dot_range,
}],
)],
}),
kind: Some(CodeActionKind::QuickFix),
is_preferred: Some(true),
});
Comment thread
amcasey marked this conversation as resolved.
}
}

code_actions
}

/// Finds the AST expression whose span exactly matches `target`.
fn find_expr_at(package: &ast::Package, target: Span) -> Option<&ast::Expr> {
let mut finder = ExprSpanFinder {
target,
found: None,
};
ast::visit::Visitor::visit_package(&mut finder, package);
finder.found
}

struct ExprSpanFinder<'a> {
target: Span,
found: Option<&'a ast::Expr>,
}

impl<'a> ast::visit::Visitor<'a> for ExprSpanFinder<'a> {
fn visit_expr(&mut self, expr: &'a Expr) {
if expr.span == self.target {
self.found = Some(expr);
} else if self.target.intersection(&expr.span).is_some() {
ast::visit::walk_expr(self, expr);
}
}
}
157 changes: 157 additions & 0 deletions source/language_service/src/code_action/int_to_double/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use crate::{
code_action,
test_utils::{compile_project_with_markers_no_cursor, whole_document_range},
};
use qsc::{line_column::Encoding, location::Location};

fn expect_single<T: std::fmt::Debug>(items: &[T]) -> &T {
let [item] = items else {
panic!("expected a single item, got: {items:?}");
};
item
}

fn get_int_to_double_actions(source: &str) -> (Vec<Location>, Vec<crate::protocol::CodeAction>) {
let (compilation, targets) =
compile_project_with_markers_no_cursor(&[("<source>", source)], false);
let range = whole_document_range(source);
let actions = code_action::get_code_actions(&compilation, "<source>", range, Encoding::Utf8);
(
targets,
actions
.into_iter()
.filter(|a| a.title == "Convert to double literal")
.collect(),
)
}

#[test]
fn int_literal_to_double() {
let source = "namespace A {
function Foo(d: Double) : Unit {
Foo(1◉◉);
}
}
";
let (locations, actions) = get_int_to_double_actions(source);
let action = expect_single(&actions);
let edit = action.edit.as_ref().expect("expected edit");
let (_, text_edits) = expect_single(&edit.changes);
let text_edit = expect_single(text_edits);
let location = expect_single(&locations);
assert_eq!(text_edit.range, location.range);
assert_eq!(text_edit.new_text, ".");
}

#[test]
fn int_literal_to_double_with_parens() {
let source = "namespace A {
function Foo(d: Double) : Unit {
Foo((1◉◉));
}
}
";
let (locations, actions) = get_int_to_double_actions(source);
let action = expect_single(&actions);
let edit = action.edit.as_ref().expect("expected edit");
let (_, text_edits) = expect_single(&edit.changes);
let text_edit = expect_single(text_edits);
let location = expect_single(&locations);
assert_eq!(text_edit.range, location.range);
assert_eq!(text_edit.new_text, ".");
}

#[test]
fn int_literal_to_double_with_pos() {
let source = "namespace A {
function Foo(d: Double) : Unit {
Foo((+1◉◉));
}
}
";
let (locations, actions) = get_int_to_double_actions(source);
let action = expect_single(&actions);
let edit = action.edit.as_ref().expect("expected edit");
let (_, text_edits) = expect_single(&edit.changes);
let text_edit = expect_single(text_edits);
let location = expect_single(&locations);
assert_eq!(text_edit.range, location.range);
assert_eq!(text_edit.new_text, ".");
}

#[test]
fn int_literal_to_double_with_neg() {
let source = "namespace A {
function Foo(d: Double) : Unit {
Foo((-1◉◉));
}
}
";
let (locations, actions) = get_int_to_double_actions(source);
let action = expect_single(&actions);
let edit = action.edit.as_ref().expect("expected edit");
let (_, text_edits) = expect_single(&edit.changes);
let text_edit = expect_single(text_edits);
let location = expect_single(&locations);
assert_eq!(text_edit.range, location.range);
assert_eq!(text_edit.new_text, ".");
}

#[test]
fn int_literal_to_double_with_neg_neg() {
let source = "namespace A {
function Foo(d: Double) : Unit {
Foo((--1◉◉));
}
}
";
let (locations, actions) = get_int_to_double_actions(source);
let action = expect_single(&actions);
let edit = action.edit.as_ref().expect("expected edit");
let (_, text_edits) = expect_single(&edit.changes);
let text_edit = expect_single(text_edits);
let location = expect_single(&locations);
assert_eq!(text_edit.range, location.range);
assert_eq!(text_edit.new_text, ".");
}

#[test]
fn int_literal_to_double_with_notb() {
let source = "namespace A {
function Foo(d: Double) : Unit {
Foo((~~~1));
}
}
";
let (_, actions) = get_int_to_double_actions(source);
assert_eq!(actions.len(), 0, "Expected 0 actions, got: {actions:?}");
}

#[test]
fn int_local_to_double() {
let source = "namespace A {
function Foo(d: Double) : Unit {
let x = 1;
Foo((x));
}
}
";
let (_, actions) = get_int_to_double_actions(source);
assert_eq!(actions.len(), 0, "Expected 0 actions, got: {actions:?}");
}

// We'd like this to work but the TyMismatch flags the whole array, not the elements
#[test]
fn int_array_to_double() {
let source = "namespace A {
function Foo(d: Double[]) : Unit {
Foo([1,2,3]);
}
}
";
let (_, actions) = get_int_to_double_actions(source);
assert_eq!(actions.len(), 0, "Expected 0 actions, got: {actions:?}");
}
Loading
Loading