Nice string formatting

This commit is contained in:
Aleksey Kladov 2020-03-28 11:08:19 +01:00
parent b764c38436
commit 6596e7cddf
11 changed files with 38 additions and 21 deletions

4
Cargo.lock generated
View file

@ -966,6 +966,7 @@ dependencies = [
"ra_syntax", "ra_syntax",
"ra_tt", "ra_tt",
"rustc-hash", "rustc-hash",
"stdx",
"test_utils", "test_utils",
] ]
@ -1002,6 +1003,7 @@ dependencies = [
"ra_prof", "ra_prof",
"ra_syntax", "ra_syntax",
"rustc-hash", "rustc-hash",
"stdx",
"test_utils", "test_utils",
] ]
@ -1116,6 +1118,7 @@ dependencies = [
"rustc_lexer", "rustc_lexer",
"serde", "serde",
"smol_str", "smol_str",
"stdx",
"test_utils", "test_utils",
"walkdir", "walkdir",
] ]
@ -1307,6 +1310,7 @@ dependencies = [
"rustc-hash", "rustc-hash",
"serde", "serde",
"serde_json", "serde_json",
"stdx",
"tempfile", "tempfile",
"test_utils", "test_utils",
"threadpool", "threadpool",

View file

@ -15,6 +15,8 @@ either = "1.5.3"
anymap = "0.12.1" anymap = "0.12.1"
drop_bomb = "0.1.4" drop_bomb = "0.1.4"
stdx = { path = "../stdx" }
ra_arena = { path = "../ra_arena" } ra_arena = { path = "../ra_arena" }
ra_db = { path = "../ra_db" } ra_db = { path = "../ra_db" }
ra_syntax = { path = "../ra_syntax" } ra_syntax = { path = "../ra_syntax" }

View file

@ -63,6 +63,7 @@ use ra_db::{CrateId, Edition, FileId};
use ra_prof::profile; use ra_prof::profile;
use ra_syntax::ast; use ra_syntax::ast;
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use stdx::format_to;
use crate::{ use crate::{
db::DefDatabase, db::DefDatabase,
@ -246,7 +247,7 @@ impl CrateDefMap {
entries.sort_by_key(|(name, _)| name.clone()); entries.sort_by_key(|(name, _)| name.clone());
for (name, def) in entries { for (name, def) in entries {
*buf += &format!("{}:", name); format_to!(buf, "{}:", name);
if def.types.is_some() { if def.types.is_some() {
*buf += " t"; *buf += " t";
@ -265,7 +266,7 @@ impl CrateDefMap {
} }
for (name, child) in map.modules[module].children.iter() { for (name, child) in map.modules[module].children.iter() {
let path = path.to_string() + &format!("::{}", name); let path = &format!("{}::{}", path, name);
go(buf, map, &path, *child); go(buf, map, &path, *child);
} }
} }

View file

@ -13,6 +13,8 @@ ena = "0.13.1"
log = "0.4.8" log = "0.4.8"
rustc-hash = "1.1.0" rustc-hash = "1.1.0"
stdx = { path = "../stdx" }
hir_def = { path = "../ra_hir_def", package = "ra_hir_def" } hir_def = { path = "../ra_hir_def", package = "ra_hir_def" }
hir_expand = { path = "../ra_hir_expand", package = "ra_hir_expand" } hir_expand = { path = "../ra_hir_expand", package = "ra_hir_expand" }
ra_arena = { path = "../ra_arena" } ra_arena = { path = "../ra_arena" }

View file

@ -10,6 +10,7 @@ use hir_expand::{db::AstDatabase, diagnostics::DiagnosticSink};
use ra_db::{ use ra_db::{
salsa, CrateId, FileId, FileLoader, FileLoaderDelegate, RelativePath, SourceDatabase, Upcast, salsa, CrateId, FileId, FileLoader, FileLoaderDelegate, RelativePath, SourceDatabase, Upcast,
}; };
use stdx::format_to;
use crate::{db::HirDatabase, expr::ExprValidator}; use crate::{db::HirDatabase, expr::ExprValidator};
@ -131,7 +132,7 @@ impl TestDB {
for f in fns { for f in fns {
let infer = self.infer(f.into()); let infer = self.infer(f.into());
let mut sink = DiagnosticSink::new(|d| { let mut sink = DiagnosticSink::new(|d| {
buf += &format!("{:?}: {}\n", d.syntax_node(self).text(), d.message()); format_to!(buf, "{:?}: {}\n", d.syntax_node(self).text(), d.message());
}); });
infer.add_diagnostics(self, f, &mut sink); infer.add_diagnostics(self, f, &mut sink);
let mut validator = ExprValidator::new(f, infer, &mut sink); let mut validator = ExprValidator::new(f, infer, &mut sink);

View file

@ -18,6 +18,8 @@ rustc-hash = "1.1.0"
arrayvec = "0.5.1" arrayvec = "0.5.1"
once_cell = "1.3.1" once_cell = "1.3.1"
stdx = { path = "../stdx" }
ra_text_edit = { path = "../ra_text_edit" } ra_text_edit = { path = "../ra_text_edit" }
ra_parser = { path = "../ra_parser" } ra_parser = { path = "../ra_parser" }

View file

@ -1,6 +1,7 @@
//! This module contains free-standing functions for creating AST fragments out //! This module contains free-standing functions for creating AST fragments out
//! of smaller pieces. //! of smaller pieces.
use itertools::Itertools; use itertools::Itertools;
use stdx::format_to;
use crate::{ast, AstNode, SourceFile, SyntaxKind, SyntaxNode, SyntaxToken}; use crate::{ast, AstNode, SourceFile, SyntaxKind, SyntaxNode, SyntaxToken};
@ -34,14 +35,14 @@ pub fn use_tree(
let mut buf = "use ".to_string(); let mut buf = "use ".to_string();
buf += &path.syntax().to_string(); buf += &path.syntax().to_string();
if let Some(use_tree_list) = use_tree_list { if let Some(use_tree_list) = use_tree_list {
buf += &format!("::{}", use_tree_list); format_to!(buf, "::{}", use_tree_list);
} }
if add_star { if add_star {
buf += "::*"; buf += "::*";
} }
if let Some(alias) = alias { if let Some(alias) = alias {
buf += &format!(" {}", alias); format_to!(buf, " {}", alias);
} }
ast_from_text(&buf) ast_from_text(&buf)
} }
@ -70,15 +71,15 @@ pub fn block_expr(
stmts: impl IntoIterator<Item = ast::Stmt>, stmts: impl IntoIterator<Item = ast::Stmt>,
tail_expr: Option<ast::Expr>, tail_expr: Option<ast::Expr>,
) -> ast::BlockExpr { ) -> ast::BlockExpr {
let mut text = "{\n".to_string(); let mut buf = "{\n".to_string();
for stmt in stmts.into_iter() { for stmt in stmts.into_iter() {
text += &format!(" {}\n", stmt); format_to!(buf, " {}\n", stmt);
} }
if let Some(tail_expr) = tail_expr { if let Some(tail_expr) = tail_expr {
text += &format!(" {}\n", tail_expr) format_to!(buf, " {}\n", tail_expr)
} }
text += "}"; buf += "}";
ast_from_text(&format!("fn f() {}", text)) ast_from_text(&format!("fn f() {}", buf))
} }
pub fn block_from_expr(e: ast::Expr) -> ast::Block { pub fn block_from_expr(e: ast::Expr) -> ast::Block {

View file

@ -32,9 +32,10 @@ pub mod ast;
#[doc(hidden)] #[doc(hidden)]
pub mod fuzz; pub mod fuzz;
use std::{fmt::Write, marker::PhantomData, sync::Arc}; use std::{marker::PhantomData, sync::Arc};
use ra_text_edit::AtomTextEdit; use ra_text_edit::AtomTextEdit;
use stdx::format_to;
use crate::syntax_node::GreenNode; use crate::syntax_node::GreenNode;
@ -115,7 +116,7 @@ impl Parse<SourceFile> {
pub fn debug_dump(&self) -> String { pub fn debug_dump(&self) -> String {
let mut buf = format!("{:#?}", self.tree().syntax()); let mut buf = format!("{:#?}", self.tree().syntax());
for err in self.errors.iter() { for err in self.errors.iter() {
writeln!(buf, "error {:?}: {}", err.range(), err).unwrap(); format_to!(buf, "error {:?}: {}\n", err.range(), err);
} }
buf buf
} }
@ -296,7 +297,7 @@ fn api_walkthrough() {
NodeOrToken::Node(it) => it.text().to_string(), NodeOrToken::Node(it) => it.text().to_string(),
NodeOrToken::Token(it) => it.text().to_string(), NodeOrToken::Token(it) => it.text().to_string(),
}; };
buf += &format!("{:indent$}{:?} {:?}\n", " ", text, node.kind(), indent = indent); format_to!(buf, "{:indent$}{:?} {:?}\n", " ", text, node.kind(), indent = indent);
indent += 2; indent += 2;
} }
WalkEvent::Leave(_) => indent -= 2, WalkEvent::Leave(_) => indent -= 2,

View file

@ -30,6 +30,8 @@ serde = { version = "1.0.104", features = ["derive"] }
serde_json = "1.0.48" serde_json = "1.0.48"
threadpool = "1.7.1" threadpool = "1.7.1"
stdx = { path = "../stdx" }
lsp-server = "0.3.1" lsp-server = "0.3.1"
ra_cargo_watch = { path = "../ra_cargo_watch" } ra_cargo_watch = { path = "../ra_cargo_watch" }
ra_ide = { path = "../ra_ide" } ra_ide = { path = "../ra_ide" }

View file

@ -19,6 +19,7 @@ use ra_ide::{
use ra_project_model::{get_rustc_cfg_options, ProcMacroClient, ProjectWorkspace}; use ra_project_model::{get_rustc_cfg_options, ProcMacroClient, ProjectWorkspace};
use ra_vfs::{LineEndings, RootEntry, Vfs, VfsChange, VfsFile, VfsRoot, VfsTask, Watch}; use ra_vfs::{LineEndings, RootEntry, Vfs, VfsChange, VfsFile, VfsRoot, VfsTask, Watch};
use relative_path::RelativePathBuf; use relative_path::RelativePathBuf;
use stdx::format_to;
use crate::{ use crate::{
diagnostics::{CheckFixes, DiagnosticCollection}, diagnostics::{CheckFixes, DiagnosticCollection},
@ -319,23 +320,23 @@ impl WorldSnapshot {
} }
pub fn status(&self) -> String { pub fn status(&self) -> String {
let mut res = String::new(); let mut buf = String::new();
if self.workspaces.is_empty() { if self.workspaces.is_empty() {
res.push_str("no workspaces\n") buf.push_str("no workspaces\n")
} else { } else {
res.push_str("workspaces:\n"); buf.push_str("workspaces:\n");
for w in self.workspaces.iter() { for w in self.workspaces.iter() {
res += &format!("{} packages loaded\n", w.n_packages()); format_to!(buf, "{} packages loaded\n", w.n_packages());
} }
} }
res.push_str("\nanalysis:\n"); buf.push_str("\nanalysis:\n");
res.push_str( buf.push_str(
&self &self
.analysis .analysis
.status() .status()
.unwrap_or_else(|_| "Analysis retrieval was cancelled".to_owned()), .unwrap_or_else(|_| "Analysis retrieval was cancelled".to_owned()),
); );
res buf
} }
pub fn workspace_root_for(&self, file_id: FileId) -> Option<&Path> { pub fn workspace_root_for(&self, file_id: FileId) -> Option<&Path> {

View file

@ -21,7 +21,7 @@ where
I: Iterator, I: Iterator,
I::Item: fmt::Display, I::Item: fmt::Display,
{ {
fn sep_by<'a>(self, sep: &'a std::primitive::str) -> SepByBuilder<'a, Self> { fn sep_by<'a>(self, sep: &'a str) -> SepByBuilder<'a, Self> {
SepByBuilder::new(sep, self) SepByBuilder::new(sep, self)
} }
} }