Move from language-reporting to codespan (#1825)

This commit is contained in:
Jonathan Turner 2020-05-18 11:44:27 -07:00 committed by GitHub
parent 5f1136dcb0
commit 0743b69ad5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 116 additions and 320 deletions

60
Cargo.lock generated
View File

@ -491,6 +491,17 @@ dependencies = [
"encoding_rs",
]
[[package]]
name = "codespan-reporting"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ceface2475f2f57a7ece9ba239b96e06bda8323ee68aa6df539752f13a74f60"
dependencies = [
"serde 1.0.110",
"termcolor",
"unicode-width",
]
[[package]]
name = "config"
version = "0.9.3"
@ -1661,15 +1672,6 @@ dependencies = [
"winapi 0.3.8",
]
[[package]]
name = "itertools"
version = "0.7.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d47946d458e94a1b7bcabbf6521ea7c037062c81f534615abcad76e84d4970d"
dependencies = [
"either",
]
[[package]]
name = "itertools"
version = "0.9.0"
@ -1731,21 +1733,6 @@ dependencies = [
"log",
]
[[package]]
name = "language-reporting"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e6a84e1e6cccd818617d299427ad1519f127af2738b1d3a581835ef56ae298b"
dependencies = [
"derive-new",
"itertools 0.7.11",
"log",
"render-tree",
"serde 1.0.110",
"serde_derive",
"termcolor",
]
[[package]]
name = "lazy_static"
version = "0.2.11"
@ -2217,6 +2204,7 @@ dependencies = [
"chrono",
"clap",
"clipboard",
"codespan-reporting",
"csv",
"ctrlc",
"derive-new",
@ -2236,8 +2224,7 @@ dependencies = [
"ical",
"ichwh",
"indexmap",
"itertools 0.9.0",
"language-reporting",
"itertools",
"log",
"meval",
"natural",
@ -2295,10 +2282,10 @@ version = "0.14.1"
dependencies = [
"ansi_term 0.12.1",
"bigdecimal",
"codespan-reporting",
"derive-new",
"getset",
"glob",
"language-reporting",
"nu-build",
"nu-source",
"num-bigint",
@ -2314,9 +2301,9 @@ name = "nu-parser"
version = "0.14.1"
dependencies = [
"bigdecimal",
"codespan-reporting",
"derive-new",
"indexmap",
"language-reporting",
"log",
"nu-errors",
"nu-protocol",
@ -2351,10 +2338,10 @@ dependencies = [
"bigdecimal",
"byte-unit",
"chrono",
"codespan-reporting",
"derive-new",
"getset",
"indexmap",
"language-reporting",
"log",
"natural",
"nu-build",
@ -2375,9 +2362,9 @@ dependencies = [
name = "nu-source"
version = "0.14.1"
dependencies = [
"codespan-reporting",
"derive-new",
"getset",
"language-reporting",
"nu-build",
"pretty",
"serde 1.0.110",
@ -2405,7 +2392,7 @@ name = "nu-value-ext"
version = "0.14.1"
dependencies = [
"indexmap",
"itertools 0.9.0",
"itertools",
"nu-build",
"nu-errors",
"nu-parser",
@ -3269,17 +3256,6 @@ dependencies = [
"winapi 0.3.8",
]
[[package]]
name = "render-tree"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68ed587df09cfb7ce1bc6fe8f77e24db219f222c049326ccbfb948ec67e31664"
dependencies = [
"itertools 0.7.11",
"log",
"termcolor",
]
[[package]]
name = "result"
version = "1.0.0"

View File

@ -52,7 +52,7 @@ ical = "0.6.*"
ichwh = "0.3.4"
indexmap = { version = "1.3.2", features = ["serde-1"] }
itertools = "0.9.0"
language-reporting = "0.4.0"
codespan-reporting = "0.9.4"
log = "0.4.8"
meval = "0.2"
natural = "0.5.0"

View File

@ -464,8 +464,8 @@ pub async fn run_pipeline_standalone(
}
LineResult::Error(line, err) => {
context.with_host(|host| {
print_err(err, host, &Text::from(line.clone()));
context.with_host(|_host| {
print_err(err, &Text::from(line.clone()));
});
context.maybe_print_errors(Text::from(line));
@ -654,8 +654,8 @@ pub async fn cli(
rl.add_history_entry(line.clone());
let _ = rl.save_history(&History::path());
context.with_host(|host| {
print_err(err, host, &Text::from(line.clone()));
context.with_host(|_host| {
print_err(err, &Text::from(line.clone()));
});
context.maybe_print_errors(Text::from(line.clone()));
@ -908,19 +908,19 @@ async fn process_line(
}
}
pub fn print_err(err: ShellError, host: &dyn Host, source: &Text) {
pub fn print_err(err: ShellError, source: &Text) {
if let Some(diag) = err.into_diagnostic() {
let writer = host.err_termcolor();
let mut source = source.to_string();
source.push_str(" ");
let files = nu_parser::Files::new(source);
let source = source.to_string();
let mut files = codespan_reporting::files::SimpleFiles::new();
files.add("shell", source);
let writer = codespan_reporting::term::termcolor::StandardStream::stderr(
codespan_reporting::term::termcolor::ColorChoice::Always,
);
let config = codespan_reporting::term::Config::default();
let _ = std::panic::catch_unwind(move || {
let _ = language_reporting::emit(
&mut writer.lock(),
&files,
&diag,
&language_reporting::DefaultConfig,
);
let _ = codespan_reporting::term::emit(&mut writer.lock(), &config, &files, &diag);
});
}
}

View File

@ -181,14 +181,11 @@ impl Context {
let errors = self.current_errors.clone();
let mut errors = errors.lock();
let host = self.host.clone();
let host = host.lock();
if errors.len() > 0 {
let error = errors[0].clone();
*errors = vec![];
crate::cli::print_err(error, &*host, &source);
crate::cli::print_err(error, &source);
true
} else {
false

View File

@ -15,7 +15,7 @@ nu-source = { path = "../nu-source", version = "0.14.1" }
ansi_term = "0.12.1"
bigdecimal = { version = "0.1.2", features = ["serde"] }
derive-new = "0.5.8"
language-reporting = "0.4.0"
codespan-reporting = { version = "0.9.4", features = ["serialization"]}
num-bigint = { version = "0.2.6", features = ["serde"] }
num-traits = "0.2.11"
serde = { version = "1.0.110", features = ["derive"] }

View File

@ -1,8 +1,8 @@
use ansi_term::Color;
use bigdecimal::BigDecimal;
use codespan_reporting::diagnostic::{Diagnostic, Label};
use derive_new::new;
use getset::Getters;
use language_reporting::{Diagnostic, Label, Severity};
use nu_source::{b, DebugDocBuilder, HasFallibleSpan, PrettyDebug, Span, Spanned, SpannedItem};
use num_bigint::BigInt;
use num_traits::ToPrimitive;
@ -414,7 +414,7 @@ impl ShellError {
.start()
}
pub fn diagnostic(diagnostic: Diagnostic<Span>) -> ShellError {
pub fn diagnostic(diagnostic: Diagnostic<usize>) -> ShellError {
ProximateShellError::Diagnostic(ShellDiagnostic { diagnostic }).start()
}
@ -422,16 +422,13 @@ impl ShellError {
ProximateShellError::ExternalPlaceholderError.start()
}
pub fn into_diagnostic(self) -> Option<Diagnostic<Span>> {
pub fn into_diagnostic(self) -> Option<Diagnostic<usize>> {
match self.error {
ProximateShellError::MissingValue { span, reason } => {
let mut d = Diagnostic::new(
Severity::Bug,
format!("Internal Error (missing value) :: {}", reason),
);
let mut d = Diagnostic::bug().with_message(format!("Internal Error (missing value) :: {}", reason));
if let Some(span) = span {
d = d.with_label(Label::new_primary(span));
d = d.with_labels(vec![Label::primary(0, span)]);
}
Some(d)
@ -440,57 +437,49 @@ impl ShellError {
command,
error,
} => Some(match error {
ArgumentError::InvalidExternalWord => Diagnostic::new(
Severity::Error,
"Invalid bare word for Nu command (did you intend to invoke an external command?)".to_string())
.with_label(Label::new_primary(command.span)),
ArgumentError::UnexpectedArgument(argument) => Diagnostic::new(
Severity::Error,
ArgumentError::InvalidExternalWord => Diagnostic::error().with_message("Invalid bare word for Nu command (did you intend to invoke an external command?)")
.with_labels(vec![Label::primary(0, command.span)]),
ArgumentError::UnexpectedArgument(argument) => Diagnostic::error().with_message(
format!(
"{} unexpected {}",
Color::Cyan.paint(&command.item),
Color::Green.bold().paint(&argument.item)
),
)
)
.with_label(
Label::new_primary(argument.span).with_message(
format!("unexpected argument (try {} -h)", &command.item))
.with_labels(
vec![Label::primary(0, argument.span).with_message(
format!("unexpected argument (try {} -h)", &command.item))]
),
ArgumentError::UnexpectedFlag(flag) => Diagnostic::new(
Severity::Error,
ArgumentError::UnexpectedFlag(flag) => Diagnostic::error().with_message(
format!(
"{} unexpected {}",
Color::Cyan.paint(&command.item),
Color::Green.bold().paint(&flag.item)
),
)
.with_label(
Label::new_primary(flag.span).with_message(
.with_labels(vec![
Label::primary(0, flag.span).with_message(
format!("unexpected flag (try {} -h)", &command.item))
),
ArgumentError::MissingMandatoryFlag(name) => Diagnostic::new(
Severity::Error,
format!(
]),
ArgumentError::MissingMandatoryFlag(name) => Diagnostic::error().with_message( format!(
"{} requires {}{}",
Color::Cyan.paint(&command.item),
Color::Green.bold().paint("--"),
Color::Green.bold().paint(name)
),
)
.with_label(Label::new_primary(command.span)),
ArgumentError::MissingMandatoryPositional(name) => Diagnostic::new(
Severity::Error,
.with_labels(vec![Label::primary(0, command.span)]),
ArgumentError::MissingMandatoryPositional(name) => Diagnostic::error().with_message(
format!(
"{} requires {} parameter",
Color::Cyan.paint(&command.item),
Color::Green.bold().paint(name.clone())
),
)
.with_label(
Label::new_primary(command.span).with_message(format!("requires {} parameter", name)),
.with_labels(
vec![Label::primary(0, command.span).with_message(format!("requires {} parameter", name))],
),
ArgumentError::MissingValueForName(name) => Diagnostic::new(
Severity::Error,
ArgumentError::MissingValueForName(name) => Diagnostic::error().with_message(
format!(
"{} is missing value for flag {}{}",
Color::Cyan.paint(&command.item),
@ -498,7 +487,7 @@ impl ShellError {
Color::Green.bold().paint(name)
),
)
.with_label(Label::new_primary(command.span)),
.with_labels(vec![Label::primary(0, command.span)]),
}),
ProximateShellError::TypeError {
expected,
@ -507,9 +496,9 @@ impl ShellError {
item: Some(actual),
span,
},
} => Some(Diagnostic::new(Severity::Error, "Type Error").with_label(
Label::new_primary(span)
.with_message(format!("Expected {}, found {}", expected, actual))),
} => Some(Diagnostic::error().with_message("Type Error").with_labels(
vec![Label::primary(0, span)
.with_message(format!("Expected {}, found {}", expected, actual))]),
),
ProximateShellError::TypeError {
expected,
@ -518,13 +507,13 @@ impl ShellError {
item: None,
span
},
} => Some(Diagnostic::new(Severity::Error, "Type Error")
.with_label(Label::new_primary(span).with_message(expected))),
} => Some(Diagnostic::error().with_message("Type Error")
.with_labels(vec![Label::primary(0, span).with_message(expected)])),
ProximateShellError::UnexpectedEof {
expected, span
} => Some(Diagnostic::new(Severity::Error, "Unexpected end of input".to_string())
.with_label(Label::new_primary(span).with_message(format!("Expected {}", expected)))),
} => Some(Diagnostic::error().with_message("Unexpected end of input")
.with_labels(vec![Label::primary(0, span).with_message(format!("Expected {}", expected))])),
ProximateShellError::RangeError {
kind,
@ -534,13 +523,13 @@ impl ShellError {
item,
span
},
} => Some(Diagnostic::new(Severity::Error, "Range Error").with_label(
Label::new_primary(span).with_message(format!(
} => Some(Diagnostic::error().with_message("Range Error").with_labels(
vec![Label::primary(0, span).with_message(format!(
"Expected to convert {} to {} while {}, but it was out of range",
item,
kind.display(),
operation
))),
))]),
),
ProximateShellError::SyntaxError {
@ -549,52 +538,55 @@ impl ShellError {
span,
item
},
} => Some(Diagnostic::new(Severity::Error, "Syntax Error")
.with_label(Label::new_primary(span).with_message(item))),
} => Some(Diagnostic::error().with_message("Syntax Error")
.with_labels(vec![Label::primary(0, span).with_message(item)])),
ProximateShellError::MissingProperty { subpath, expr, .. } => {
let mut diag = Diagnostic::new(Severity::Error, "Missing property");
let mut diag = Diagnostic::error().with_message("Missing property");
if subpath.span == Span::unknown() {
diag.message = format!("Missing property (for {})", subpath.item);
} else {
let subpath = Label::new_primary(subpath.span).with_message(subpath.item);
diag = diag.with_label(subpath);
let subpath = Label::primary(0, subpath.span).with_message(subpath.item);
let mut labels = vec![];
labels.push(subpath);
if expr.span != Span::unknown() {
let expr = Label::new_primary(expr.span).with_message(expr.item);
diag = diag.with_label(expr)
let expr = Label::primary(0, expr.span).with_message(expr.item);
labels.push(expr);
}
diag = diag.with_labels(labels);
}
Some(diag)
}
ProximateShellError::InvalidIntegerIndex { subpath,integer } => {
let mut diag = Diagnostic::new(Severity::Error, "Invalid integer property");
let mut diag = Diagnostic::error().with_message("Invalid integer property");
let mut labels = vec![];
if subpath.span == Span::unknown() {
diag.message = format!("Invalid integer property (for {})", subpath.item)
} else {
let label = Label::new_primary(subpath.span).with_message(subpath.item);
diag = diag.with_label(label)
let label = Label::primary(0, subpath.span).with_message(subpath.item);
labels.push(label);
}
diag = diag.with_label(Label::new_secondary(integer).with_message("integer"));
labels.push(Label::secondary(0, integer).with_message("integer"));
diag = diag.with_labels(labels);
Some(diag)
}
ProximateShellError::Diagnostic(diag) => Some(diag.diagnostic),
ProximateShellError::CoerceError { left, right } => {
Some(Diagnostic::new(Severity::Error, "Coercion error")
.with_label(Label::new_primary(left.span).with_message(left.item))
.with_label(Label::new_secondary(right.span).with_message(right.item)))
Some(Diagnostic::error().with_message("Coercion error")
.with_labels(vec![Label::primary(0, left.span).with_message(left.item),
Label::secondary(0, right.span).with_message(right.item)]))
}
ProximateShellError::UntaggedRuntimeError { reason } => Some(Diagnostic::new(Severity::Error, format!("Error: {}", reason))),
ProximateShellError::UntaggedRuntimeError { reason } => Some(Diagnostic::error().with_message(format!("Error: {}", reason))),
ProximateShellError::ExternalPlaceholderError => None,
}
}
@ -605,8 +597,11 @@ impl ShellError {
span: impl Into<Span>,
) -> ShellError {
ShellError::diagnostic(
Diagnostic::new(Severity::Error, msg.into())
.with_label(Label::new_primary(span.into()).with_message(label.into())),
Diagnostic::error()
.with_message(msg.into())
.with_labels(vec![
Label::primary(0, span.into()).with_message(label.into())
]),
)
}
@ -618,14 +613,12 @@ impl ShellError {
secondary_span: impl Into<Span>,
) -> ShellError {
ShellError::diagnostic(
Diagnostic::new_error(msg.into())
.with_label(
Label::new_primary(primary_span.into()).with_message(primary_label.into()),
)
.with_label(
Label::new_secondary(secondary_span.into())
.with_message(secondary_label.into()),
),
Diagnostic::error()
.with_message(msg.into())
.with_labels(vec![
Label::primary(0, primary_span.into()).with_message(primary_label.into()),
Label::secondary(0, secondary_span.into()).with_message(secondary_label.into()),
]),
)
}
@ -780,7 +773,7 @@ impl HasFallibleSpan for ProximateShellError {
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShellDiagnostic {
pub(crate) diagnostic: Diagnostic<Span>,
pub(crate) diagnostic: Diagnostic<usize>,
}
impl std::hash::Hash for ShellDiagnostic {
@ -790,11 +783,11 @@ impl std::hash::Hash for ShellDiagnostic {
self.diagnostic.message.hash(state);
for label in &self.diagnostic.labels {
label.span.hash(state);
label.range.hash(state);
label.message.hash(state);
match label.style {
language_reporting::LabelStyle::Primary => 0.hash(state),
language_reporting::LabelStyle::Secondary => 1.hash(state),
codespan_reporting::diagnostic::LabelStyle::Primary => 0.hash(state),
codespan_reporting::diagnostic::LabelStyle::Secondary => 1.hash(state),
}
}
}

View File

@ -16,7 +16,7 @@ parking_lot = "0.10.2"
num-traits = "0.2.11"
derive-new = "0.5.8"
serde = "1.0.110"
language-reporting = "0.4.0"
codespan-reporting = "0.9.4"
log = "0.4.8"
shellexpand = "2.0.0"

View File

@ -1,151 +0,0 @@
use derive_new::new;
use language_reporting::{FileName, Location};
use log::trace;
use nu_source::Span;
#[derive(new, Debug, Clone)]
pub struct Files {
snippet: String,
}
impl language_reporting::ReportingFiles for Files {
type Span = Span;
type FileId = usize;
fn byte_span(
&self,
_file: Self::FileId,
from_index: usize,
to_index: usize,
) -> Option<Self::Span> {
Some(Span::new(from_index, to_index))
}
fn file_id(&self, _tag: Self::Span) -> Self::FileId {
0
}
fn file_name(&self, _file: Self::FileId) -> FileName {
FileName::Verbatim("shell".to_string())
}
fn byte_index(&self, _file: Self::FileId, _line: usize, _column: usize) -> Option<usize> {
unimplemented!("byte_index")
}
fn location(&self, _file: Self::FileId, byte_index: usize) -> Option<Location> {
trace!("finding location for {}", byte_index);
let source = &self.snippet;
let mut seen_lines = 0;
let mut seen_bytes = 0;
for (pos, slice) in source.match_indices('\n') {
trace!(
"searching byte_index={} seen_bytes={} pos={} slice={:?} slice.len={} source={:?}",
byte_index,
seen_bytes,
pos,
slice,
source.len(),
source
);
if pos >= byte_index {
trace!(
"returning {}:{} seen_lines={} byte_index={} pos={} seen_bytes={}",
seen_lines,
byte_index,
pos,
seen_lines,
byte_index,
seen_bytes
);
return Some(language_reporting::Location::new(
seen_lines,
byte_index - pos,
));
} else {
seen_lines += 1;
seen_bytes = pos;
}
}
if seen_lines == 0 {
trace!("seen_lines=0 end={}", source.len() - 1);
// if we got here, there were no newlines in the source
Some(language_reporting::Location::new(0, source.len() - 1))
} else {
trace!(
"last line seen_lines={} end={}",
seen_lines,
source.len() - 1 - byte_index
);
// if we got here and we didn't return, it should mean that we're talking about
// the last line
Some(language_reporting::Location::new(
seen_lines,
source.len() - 1 - byte_index,
))
}
}
fn line_span(&self, _file: Self::FileId, lineno: usize) -> Option<Self::Span> {
trace!("finding line_span for {}", lineno);
let source = &self.snippet;
let mut seen_lines = 0;
let mut seen_bytes = 0;
for (pos, _) in source.match_indices('\n') {
trace!(
"lineno={} seen_lines={} seen_bytes={} pos={}",
lineno,
seen_lines,
seen_bytes,
pos
);
if seen_lines == lineno {
trace!("returning start={} end={}", seen_bytes, pos);
// If the number of seen lines is the lineno, seen_bytes is the start of the
// line and pos is the end of the line
return Some(Span::new(seen_bytes, pos));
} else {
// If it's not, increment seen_lines, and move seen_bytes to the beginning of
// the next line
seen_lines += 1;
seen_bytes = pos + 1;
}
}
if seen_lines == 0 {
trace!("returning start={} end={}", 0, self.snippet.len() - 1);
// if we got here, there were no newlines in the source
Some(Span::new(0, self.snippet.len() - 1))
} else {
trace!(
"returning start={} end={}",
seen_bytes,
self.snippet.len() - 1
);
// if we got here and we didn't return, it should mean that we're talking about
// the last line
Some(Span::new(seen_bytes, self.snippet.len() - 1))
}
}
fn source(&self, span: Self::Span) -> Option<String> {
trace!("source(tag={:?}) snippet={:?}", span, self.snippet);
if span.start() > span.end() || span.end() > self.snippet.len() {
return None;
}
Some(span.slice(&self.snippet).to_string())
}
}

View File

@ -1,11 +1,9 @@
mod files;
mod lite_parse;
mod parse;
mod path;
mod shapes;
mod signature;
pub use crate::files::Files;
pub use crate::lite_parse::{lite_parse, LiteBlock};
pub use crate::parse::{classify_block, garbage};
pub use crate::path::expand_ndots;

View File

@ -23,7 +23,7 @@ serde_bytes = "0.11.4"
getset = "0.1.1"
derive-new = "0.5.8"
ansi_term = "0.12.1"
language-reporting = "0.4.0"
codespan-reporting = "0.9.4"
typetag = "0.1.4"
query_interface = "0.3.5"
byte-unit = "3.0.3"

View File

@ -13,7 +13,7 @@ doctest = false
serde = { version = "1.0.106", features = ["derive"] }
derive-new = "0.5.8"
getset = "0.1.1"
language-reporting = "0.4.0"
codespan-reporting = "0.9.4"
termcolor = "1.1.0"
pretty = "0.5.2"

View File

@ -472,6 +472,15 @@ impl From<Option<Span>> for Span {
}
}
impl From<Span> for std::ops::Range<usize> {
fn from(input: Span) -> std::ops::Range<usize> {
std::ops::Range {
start: input.start,
end: input.end,
}
}
}
impl Span {
/// Creates a default new `Span` that has 0 start and 0 end.
pub fn default() -> Self {
@ -657,32 +666,6 @@ impl PartialEq<usize> for Span {
}
}
impl language_reporting::ReportingSpan for Span {
fn with_start(&self, start: usize) -> Self {
if self.end < start {
Span::new(start, start)
} else {
Span::new(start, self.end)
}
}
fn with_end(&self, end: usize) -> Self {
if end < self.start {
Span::new(end, end)
} else {
Span::new(self.start, end)
}
}
fn start(&self) -> usize {
self.start
}
fn end(&self) -> usize {
self.end
}
}
pub trait IntoSpanned {
type Output: HasFallibleSpan;