Use ast::String for extracting string literal contents

This commit is contained in:
Igor Aleksanov 2020-10-02 13:23:49 +03:00
parent 2557cb8518
commit b7ac540f15
2 changed files with 19 additions and 14 deletions

View File

@ -4,7 +4,7 @@ mod format_like;
use assists::utils::TryEnum;
use syntax::{
ast::{self, AstNode},
ast::{self, AstNode, AstToken},
TextRange, TextSize,
};
use text_edit::TextEdit;
@ -212,7 +212,11 @@ pub(super) fn complete_postfix(acc: &mut Completions, ctx: &CompletionContext) {
)
.add_to(acc);
add_format_like_completions(acc, ctx, &dot_receiver, cap, &receiver_text);
if let ast::Expr::Literal(literal) = dot_receiver.clone() {
if let Some(literal_text) = ast::String::cast(literal.token()) {
add_format_like_completions(acc, ctx, &dot_receiver, cap, &literal_text);
}
}
}
fn get_receiver_text(receiver: &ast::Expr, receiver_is_ambiguous_float_literal: bool) -> String {

View File

@ -18,23 +18,22 @@ use crate::completion::{
complete_postfix::postfix_snippet, completion_config::SnippetCap,
completion_context::CompletionContext, completion_item::Completions,
};
use syntax::ast;
use syntax::ast::{self, AstToken};
pub(super) fn add_format_like_completions(
acc: &mut Completions,
ctx: &CompletionContext,
dot_receiver: &ast::Expr,
cap: SnippetCap,
receiver_text: &str,
receiver_text: &ast::String,
) {
if !is_string_literal(receiver_text) {
let input = match string_literal_contents(receiver_text) {
// It's not a string literal, do not parse input.
return;
}
Some(input) => input,
None => return,
};
let input = &receiver_text[1..receiver_text.len() - 1];
let mut parser = FormatStrParser::new(input.to_owned());
let mut parser = FormatStrParser::new(input);
if parser.parse().is_ok() {
for kind in PostfixKind::all_suggestions() {
@ -47,11 +46,13 @@ pub(super) fn add_format_like_completions(
}
/// Checks whether provided item is a string literal.
fn is_string_literal(item: &str) -> bool {
if item.len() < 2 {
return false;
fn string_literal_contents(item: &ast::String) -> Option<String> {
let item = item.text();
if item.len() >= 2 && item.starts_with("\"") && item.ends_with("\"") {
return Some(item[1..item.len() - 1].to_owned());
}
item.starts_with("\"") && item.ends_with("\"")
None
}
/// Parser for a format-like string. It is more allowing in terms of string contents,