Skip to content
This repository was archived by the owner on Dec 29, 2022. It is now read-only.

Refactoring #168

Merged
merged 3 commits into from
Feb 9, 2017
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
102 changes: 102 additions & 0 deletions src/actions/compiler_message_parsing.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::path::PathBuf;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs copyright notice

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay.


use ls_types::{Diagnostic, DiagnosticSeverity, NumberOrString};
use serde_json;
use span::compiler::DiagnosticSpan;

use lsp_data::ls_util;

#[derive(Debug, Deserialize)]
struct CompilerMessageCode {
code: String
}

#[derive(Debug, Deserialize)]
struct CompilerMessage {
message: String,
code: Option<CompilerMessageCode>,
level: String,
spans: Vec<DiagnosticSpan>,
children: Vec<CompilerMessage>,
}

#[derive(Debug)]
pub struct FileDiagnostic {
pub file_path: PathBuf,
pub diagnostic: Diagnostic,
}

#[derive(Debug)]
pub enum ParseError {
JsonError(serde_json::Error),
NoSpans,
}

impl From<serde_json::Error> for ParseError {
fn from(error: serde_json::Error) -> Self {
ParseError::JsonError(error)
}
}

pub fn parse(message: &str) -> Result<FileDiagnostic, ParseError> {
let message = serde_json::from_str::<CompilerMessage>(&message)?;

if message.spans.is_empty() {
return Err(ParseError::NoSpans);
}

let span = message.spans[0].rls_span().zero_indexed();

let message_text = compose_message(&message);

let diagnostic = Diagnostic {
range: ls_util::rls_to_range(span.range),
severity: Some(if message.level == "error" {
DiagnosticSeverity::Error
} else {
DiagnosticSeverity::Warning
}),
code: Some(NumberOrString::String(match message.code {
Some(c) => c.code.clone(),
None => String::new(),
})),
source: Some("rustc".into()),
message: message_text,
};

Ok(FileDiagnostic {
file_path: span.file.clone(),
diagnostic: diagnostic
})
}

/// Builds a more sophisticated error message
fn compose_message(compiler_message: &CompilerMessage) -> String {
let mut message = compiler_message.message.clone();
for sp in &compiler_message.spans {
if !sp.is_primary {
continue;
}
if let Some(ref label) = sp.label {
message.push_str("\n");
message.push_str(label);
}
}
if !compiler_message.children.is_empty() {
message.push_str("\n");
for child in &compiler_message.children {
message.push_str(&format!("\n{}: {}", child.level, child.message));
}
}
message
}
74 changes: 10 additions & 64 deletions src/actions.rs → src/actions/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

mod compiler_message_parsing;

use analysis::{AnalysisHost};
use hyper::Url;
use vfs::{Vfs, Change};
Expand All @@ -29,6 +31,8 @@ use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

use self::compiler_message_parsing::{FileDiagnostic, ParseError};

type BuildResults = HashMap<PathBuf, Vec<Diagnostic>>;

pub struct ActionHandler {
Expand Down Expand Up @@ -65,20 +69,6 @@ impl ActionHandler {
}

pub fn build(&self, project_path: &Path, priority: BuildPriority, out: &Output) {
#[derive(Debug, Deserialize)]
pub struct CompilerMessageCode {
pub code: String
}

#[derive(Debug, Deserialize)]
pub struct CompilerMessage {
pub message: String,
pub code: Option<CompilerMessageCode>,
pub level: String,
pub spans: Vec<span::compiler::DiagnosticSpan>,
pub children: Vec<CompilerMessage>,
}

fn clear_build_results(results: &mut BuildResults) {
// We must not clear the hashmap, just the values in each list.
// This allows us to save allocated before memory.
Expand All @@ -88,61 +78,17 @@ impl ActionHandler {
}

fn parse_compiler_messages(messages: &[String], results: &mut BuildResults) {
/// Builds a more sophisticated error message
fn compose_message(compiler_message: &CompilerMessage) -> String {
let mut message = compiler_message.message.clone();

for sp in &compiler_message.spans {
if sp.is_primary && sp.label.is_some() {
message.push_str("\n");
message.push_str(sp.label.as_ref().unwrap());
}
}

if !compiler_message.children.is_empty() {
message.push_str("\n");
for child in &compiler_message.children {
message.push_str(&format!("\n{}: {}", child.level, child.message));
}
}

message
}

for msg in messages {
let message = match serde_json::from_str::<CompilerMessage>(&msg) {
Ok(message) => message,
Err(e) => {
match compiler_message_parsing::parse(msg) {
Ok(FileDiagnostic { file_path, diagnostic }) => {
results.entry(file_path).or_insert(vec![]).push(diagnostic);
}
Err(ParseError::JsonError(e)) => {
debug!("build error {:?}", e);
debug!("from {}", msg);
continue;
}
};

if message.spans.is_empty() {
continue;
Err(ParseError::NoSpans) => {}
}

let span = message.spans[0].rls_span().zero_indexed();

let message_text = compose_message(&message);

let diag = Diagnostic {
range: ls_util::rls_to_range(span.range),
severity: Some(if message.level == "error" {
DiagnosticSeverity::Error
} else {
DiagnosticSeverity::Warning
}),
code: Some(NumberOrString::String(match message.code {
Some(c) => c.code.clone(),
None => String::new(),
})),
source: Some("rustc".into()),
message: message_text,
};

results.entry(span.file.clone()).or_insert(vec![]).push(diag);
}
}

Expand Down