Skip to content
This repository was archived by the owner on Dec 29, 2022. It is now read-only.
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
5 changes: 1 addition & 4 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,7 @@ fn commit_hash() -> Option<String> {

fn commit_date() -> Option<String> {
Command::new("git")
.args(&["log",
"-1",
"--date=short",
"--pretty=format:%cd"])
.args(&["log", "-1", "--date=short", "--pretty=format:%cd"])
.output()
.ok()
.and_then(|r| String::from_utf8(r.stdout).ok())
Expand Down
77 changes: 47 additions & 30 deletions src/actions/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,15 @@ use std::collections::HashMap;
use std::iter;
use std::path::{Path, PathBuf};

use languageserver_types::{DiagnosticRelatedInformation, DiagnosticSeverity, Location, NumberOrString, Range};
use crate::lsp_data::ls_util;
use serde_json;
use languageserver_types::{
DiagnosticRelatedInformation, DiagnosticSeverity, Location, NumberOrString, Range,
};
use log::debug;
use rls_span::compiler::DiagnosticSpan;
use url::Url;
use serde_derive::Deserialize;
use log::debug;
use serde_json;
use url::Url;

pub use languageserver_types::Diagnostic;

Expand Down Expand Up @@ -240,8 +242,7 @@ fn make_related_information<'a>(
},
message: label.trim().to_owned(),
})
})
.collect();
}).collect();

related_information.sort_by_key(|info| info.location.range.start);

Expand All @@ -264,8 +265,7 @@ fn make_suggestions<'a>(
.as_ref()
.and_then(|label| label_suggestion(span, label))
})
})
.collect();
}).collect();

// Suggestions are displayed at primary span, so if the change is somewhere
// else, be sure to specify that
Expand Down Expand Up @@ -313,7 +313,9 @@ trait IsWithin {

impl<T: PartialOrd<T>> IsWithin for ::std::ops::Range<T> {
fn is_within(&self, other: &Self) -> bool {
self.start >= other.start && self.start <= other.end && self.end <= other.end
self.start >= other.start
&& self.start <= other.end
&& self.end <= other.end
&& self.end >= other.start
}
}
Expand Down Expand Up @@ -372,7 +374,8 @@ mod diagnostic_message_test {
}

fn to_messages(&self) -> Vec<(String, Vec<String>)> {
(self.single_file_results()
(self
.single_file_results()
.iter()
.map(|(diagnostic, _)| {
(
Expand All @@ -385,8 +388,7 @@ mod diagnostic_message_test {
.map(|d| d.message.clone())
.collect(),
)
})
.collect())
}).collect())
}

fn to_primary_messages(&self) -> Vec<String> {
Expand Down Expand Up @@ -656,7 +658,8 @@ help: consider borrowing here: `&string`"#,
"the operation is ineffective. Consider reducing it to `1`\n\n\
note: #[warn(identity_op)] implied by #[warn(clippy)]\n\
help: for further information visit "
.to_owned() + link
.to_owned()
+ link
);

assert!(messages[0].1.is_empty(), "{:?}", messages[0].1);
Expand All @@ -677,21 +680,28 @@ help: consider borrowing here: `&string`"#,
assert_eq!(diag.diagnostics.len(), 1, "{:#?}", diag.diagnostics);

let file = &diag.diagnostics.keys().nth(0).unwrap();
assert!(file.to_str().unwrap().ends_with("src/main.rs"), "Unexpected file {:?}", file);
assert!(
file.to_str().unwrap().ends_with("src/main.rs"),
"Unexpected file {:?}",
file
);

let diagnostic = &diag.diagnostics.values().nth(0).unwrap()[0];
assert_eq!(diagnostic.0.source, Some("rustc".into()));
assert_eq!(diagnostic.0.range, Range {
start: Position::new(2, 4),
end: Position::new(2, 27),
});
assert_eq!(
diagnostic.0.range,
Range {
start: Position::new(2, 4),
end: Position::new(2, 27),
}
);

let messages = diag.to_messages();
assert_eq!(
messages[0].0,
"no method named `write_fmt` found for type `std::string::String` \
in the current scope\n\n\
help: items from traits can only be used if the trait is in scope"
in the current scope\n\n\
help: items from traits can only be used if the trait is in scope"
);

assert!(messages[0].1.is_empty(), "{:?}", messages[0].1);
Expand All @@ -713,21 +723,25 @@ help: consider borrowing here: `&string`"#,
assert_eq!(diag.diagnostics.len(), 1, "{:#?}", diag.diagnostics);

let file = &diag.diagnostics.keys().nth(0).unwrap();
assert!(file.to_str().unwrap().ends_with("src/main.rs"), "Unexpected file {:?}", file);
assert!(
file.to_str().unwrap().ends_with("src/main.rs"),
"Unexpected file {:?}",
file
);

let diagnostic = &diag.diagnostics.values().nth(0).unwrap()[0];
assert_eq!(diagnostic.0.source, Some("rustc".into()));
assert_eq!(diagnostic.0.range, Range {
start: Position::new(4, 4),
end: Position::new(4, 33),
});

let messages = diag.to_messages();
assert_eq!(
messages[0].0,
"expected token: `,`"
diagnostic.0.range,
Range {
start: Position::new(4, 4),
end: Position::new(4, 33),
}
);

let messages = diag.to_messages();
assert_eq!(messages[0].0, "expected token: `,`");

assert!(messages[0].1.is_empty(), "{:?}", messages[0].1);
}
}
Expand Down Expand Up @@ -845,7 +859,10 @@ mod diagnostic_suggestion_test {
.find(|s| s.new_text == "use std::fmt::Write;\n\n")
.expect("`use std::fmt::Write;` not found");

assert_eq!(change_to_mut.label, "Line 1: Add `use std::fmt::Write;\n\n`");
assert_eq!(
change_to_mut.label,
"Line 1: Add `use std::fmt::Write;\n\n`"
);

assert_eq!(
change_to_mut.range,
Expand Down
36 changes: 23 additions & 13 deletions src/actions/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

use rand::{Rng, thread_rng};
use log::debug;
use rustfmt_nightly::{Config, Session, Input};
use rand::{thread_rng, Rng};
use rustfmt_nightly::{Config, Input, Session};
use serde_json;

/// Specified which `rustfmt` to use.
Expand All @@ -28,14 +28,14 @@ pub enum Rustfmt {
/// (Path to external `rustfmt`, cwd where it should be spawned at)
External(PathBuf, PathBuf),
/// Statically linked `rustfmt`
Internal
Internal,
}

impl From<Option<(String, PathBuf)>> for Rustfmt {
fn from(value: Option<(String, PathBuf)>) -> Rustfmt {
match value {
Some((path, cwd)) => Rustfmt::External(PathBuf::from(path), cwd),
None => Rustfmt::Internal
None => Rustfmt::Internal,
}
}
}
Expand All @@ -49,7 +49,12 @@ impl Rustfmt {
}
}

fn format_external(path: &PathBuf, cwd: &PathBuf, input: String, cfg: Config) -> Result<String, String> {
fn format_external(
path: &PathBuf,
cwd: &PathBuf,
input: String,
cfg: Config,
) -> Result<String, String> {
let (_file_handle, config_path) = gen_config_file(&cfg)?;
let args = rustfmt_args(&cfg, &config_path);

Expand All @@ -62,19 +67,25 @@ fn format_external(path: &PathBuf, cwd: &PathBuf, input: String, cfg: Config) ->
.map_err(|_| format!("Couldn't spawn `{}`", path.display()))?;

{
let stdin = rustfmt.stdin.as_mut()
let stdin = rustfmt
.stdin
.as_mut()
.ok_or_else(|| "Failed to open rustfmt stdin".to_string())?;
stdin.write_all(input.as_bytes())
stdin
.write_all(input.as_bytes())
.map_err(|_| "Failed to pass input to rustfmt".to_string())?;
}

rustfmt.wait_with_output()
rustfmt
.wait_with_output()
.map_err(|err| format!("Error running rustfmt: {}", err))
.and_then(|out| String::from_utf8(out.stdout)
.map_err(|_| "Formatted code is not valid UTF-8".to_string()))
.and_then(|out| {
String::from_utf8(out.stdout)
.map_err(|_| "Formatted code is not valid UTF-8".to_string())
})
}

fn format_internal(input: String, config:Config) -> Result<String, String> {
fn format_internal(input: String, config: Config) -> Result<String, String> {
let mut buf = Vec::<u8>::new();

{
Expand All @@ -100,8 +111,7 @@ fn format_internal(input: String, config:Config) -> Result<String, String> {
}
}

String::from_utf8(buf)
.map_err(|_| "Reformat output is not a valid UTF-8".into())
String::from_utf8(buf).map_err(|_| "Reformat output is not a valid UTF-8".into())
}

fn random_file() -> Result<(File, PathBuf), String> {
Expand Down
45 changes: 21 additions & 24 deletions src/actions/hover.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ use rls_span::{Column, Row, Span, ZeroIndexed};
use rls_vfs::{self as vfs, Vfs};
use rustfmt_nightly::NewlineStyle;

use std::path::{Path, PathBuf};
use log::*;
use std::path::{Path, PathBuf};

/// Cleanup documentation code blocks. The `docs` are expected to have
/// the preceeding `///` or `//!` prefixes already trimmed away. Rust code
Expand Down Expand Up @@ -217,8 +217,7 @@ fn extract_and_process_docs(vfs: &Vfs, file: &Path, row_start: Row<ZeroIndexed>)
"failed to extract docs: row: {:?}, file: {:?} ({:?})",
row_start, file, e
);
})
.ok()
}).ok()
.map(|docs| docs.join("\n"))
.map(|docs| process_docs(&docs))
.and_then(empty_to_none)
Expand Down Expand Up @@ -544,13 +543,13 @@ fn skip_path_components<P: AsRef<Path>>(
skip_components: usize,
) -> PathBuf {
if path.starts_with(prefix) {
let comps: PathBuf = path.components().skip(skip_components).fold(
PathBuf::new(),
|mut comps, comp| {
comps.push(comp);
comps
},
);
let comps: PathBuf =
path.components()
.skip(skip_components)
.fold(PathBuf::new(), |mut comps, comp| {
comps.push(comp);
comps
});
comps
} else {
path
Expand Down Expand Up @@ -648,7 +647,11 @@ fn racer_match_to_def(ctx: &InitActionContext, m: &racer::Match) -> Option<Def>
let matchstr_len = matchstr.len() as u32;
let docs = m.docs.trim().to_string();
m.coords.map(|coords| {
assert!(coords.row.0 > 0, "racer_match_to_def: racer returned `0` for a 1-based row: {:?}", m);
assert!(
coords.row.0 > 0,
"racer_match_to_def: racer returned `0` for a 1-based row: {:?}",
m
);
let (row, col1) = requests::from_racer_coord(coords);
let col2 = Column::new_zero_indexed(col1.0 + matchstr_len);
let row = Row::new_zero_indexed(row.0 - 1);
Expand Down Expand Up @@ -775,8 +778,7 @@ fn format_object(rustfmt: Rustfmt, fmt_config: &FmtConfig, the_type: String) ->
} else {
part.to_string()
}
})
.collect::<Vec<String>>();
}).collect::<Vec<String>>();
decl = &decl[0..pos];
if hidden_count != tuple_parts.len() {
format!("{}({})", decl, tuple_parts.join(", "))
Expand Down Expand Up @@ -826,8 +828,7 @@ fn format_method(rustfmt: Rustfmt, fmt_config: &FmtConfig, the_type: String) ->
};
let line = line.trim_left_matches(should_trim);
format!("{}\n", line)
})
.collect()
}).collect()
}
Err(e) => {
error!("format_method: error: {:?}, input: {:?}", e, method);
Expand Down Expand Up @@ -942,7 +943,7 @@ pub mod test {
use crate::lsp_data::{Position, TextDocumentIdentifier, TextDocumentPositionParams};
use crate::server::{Output, RequestId};
use rls_analysis as analysis;
use serde_derive::{Serialize, Deserialize};
use serde_derive::{Deserialize, Serialize};
use serde_json as json;
use url::Url;

Expand Down Expand Up @@ -1175,8 +1176,7 @@ pub mod test {
let result = test.run(&self.project_dir, &self.ctx);
result.save(&save_dir).unwrap();
result
})
.collect();
}).collect();

let failures: Vec<TestFailure> = results
.iter()
Expand All @@ -1195,8 +1195,7 @@ pub mod test {
}
Err(e) => Some((Err(e), actual_result)),
}
})
.filter(|failed_result| failed_result.is_some())
}).filter(|failed_result| failed_result.is_some())
.map(|failed_result| failed_result.unwrap())
.map(|failed_result| match failed_result {
(Ok(expect_result), actual_result) => {
Expand All @@ -1221,8 +1220,7 @@ pub mod test {
actual_file: save_file,
}
}
})
.collect();
}).collect();

Ok(failures)
}
Expand Down Expand Up @@ -1251,8 +1249,7 @@ pub mod test {
.scan(0, |_, ch| if ch.is_whitespace() { Some(1) } else { None })
.fuse()
.sum()
})
.unwrap_or(0);
}).unwrap_or(0);

text.lines()
.map(|line| line.chars().skip(indent).collect::<String>())
Expand Down
Loading