Skip to content

Commit 518916f

Browse files
committed
Return correct path and line in query errors from the CLI
1 parent 297e2bc commit 518916f

5 files changed

Lines changed: 372 additions & 234 deletions

File tree

‎cli/src/error.rs‎

Lines changed: 13 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use super::test_highlight;
22
use std::fmt::Write;
33
use std::io;
4-
use tree_sitter::QueryError;
4+
use tree_sitter::{QueryError, QueryErrorKind};
55

66
#[derive(Debug)]
77
pub struct Error(pub Vec<String>);
@@ -51,31 +51,19 @@ impl Error {
5151
}
5252
}
5353

54-
impl<'a> From<QueryError> for Error {
55-
fn from(error: QueryError) -> Self {
56-
match error {
57-
QueryError::Capture(row, c) => Error::new(format!(
58-
"Query error on line {}: Invalid capture name {}",
59-
row, c
60-
)),
61-
QueryError::Field(row, f) => Error::new(format!(
62-
"Query error on line {}: Invalid field name {}",
63-
row, f
64-
)),
65-
QueryError::NodeType(row, t) => Error::new(format!(
66-
"Query error on line {}. Invalid node type {}",
67-
row, t
68-
)),
69-
QueryError::Syntax(row, l) => Error::new(format!(
70-
"Query error on line {}. Invalid syntax:\n{}",
71-
row, l
72-
)),
73-
QueryError::Structure(row, l) => Error::new(format!(
74-
"Query error on line {}. Impossible pattern:\n{}",
75-
row, l
76-
)),
77-
QueryError::Predicate(p) => Error::new(format!("Query error: {}", p)),
54+
impl<'a> From<(&str, QueryError)> for Error {
55+
fn from((path, error): (&str, QueryError)) -> Self {
56+
let mut msg = format!("Query error at {}:{}. ", path, error.row + 1);
57+
match error.kind {
58+
QueryErrorKind::Capture => write!(&mut msg, "Invalid capture name {}", error.message),
59+
QueryErrorKind::Field => write!(&mut msg, "Invalid field name {}", error.message),
60+
QueryErrorKind::NodeType => write!(&mut msg, "Invalid node type {}", error.message),
61+
QueryErrorKind::Syntax => write!(&mut msg, "Invalid syntax:\n{}", error.message),
62+
QueryErrorKind::Structure => write!(&mut msg, "Impossible pattern:\n{}", error.message),
63+
QueryErrorKind::Predicate => write!(&mut msg, "Invalid predicate: {}", error.message),
7864
}
65+
.unwrap();
66+
Self::new(msg)
7967
}
8068
}
8169

‎cli/src/loader.rs‎

Lines changed: 61 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,13 @@ use regex::{Regex, RegexBuilder};
55
use serde_derive::Deserialize;
66
use std::collections::HashMap;
77
use std::io::BufReader;
8+
use std::ops::Range;
89
use std::path::{Path, PathBuf};
910
use std::process::Command;
1011
use std::sync::Mutex;
1112
use std::time::SystemTime;
1213
use std::{fs, mem};
13-
use tree_sitter::Language;
14+
use tree_sitter::{Language, QueryError};
1415
use tree_sitter_highlight::HighlightConfiguration;
1516
use tree_sitter_tags::TagsConfiguration;
1617

@@ -543,13 +544,32 @@ impl Loader {
543544

544545
impl<'a> LanguageConfiguration<'a> {
545546
pub fn highlight_config(&self, language: Language) -> Result<Option<&HighlightConfiguration>> {
547+
fn include_path_in_error<'a>(
548+
mut error: QueryError,
549+
ranges: &'a Vec<(String, Range<usize>)>,
550+
source: &str,
551+
start_offset: usize,
552+
) -> (&'a str, QueryError) {
553+
let offset = error.offset - start_offset;
554+
let (path, range) = ranges
555+
.iter()
556+
.find(|(_, range)| range.contains(&offset))
557+
.unwrap();
558+
error.row = source[range.start..offset]
559+
.chars()
560+
.filter(|c| *c == '\n')
561+
.count();
562+
(path.as_ref(), error)
563+
}
564+
546565
self.highlight_config
547566
.get_or_try_init(|| {
548-
let highlights_query =
567+
let (highlights_query, highlight_ranges) =
549568
self.read_queries(&self.highlights_filenames, "highlights.scm")?;
550-
let injections_query =
569+
let (injections_query, injection_ranges) =
551570
self.read_queries(&self.injections_filenames, "injections.scm")?;
552-
let locals_query = self.read_queries(&self.locals_filenames, "locals.scm")?;
571+
let (locals_query, locals_ranges) =
572+
self.read_queries(&self.locals_filenames, "locals.scm")?;
553573

554574
if highlights_query.is_empty() {
555575
Ok(None)
@@ -560,9 +580,25 @@ impl<'a> LanguageConfiguration<'a> {
560580
&injections_query,
561581
&locals_query,
562582
)
563-
.map_err(Error::wrap(|| {
564-
format!("Failed to load queries in {:?}", self.root_path)
565-
}))?;
583+
.map_err(|error| {
584+
if error.offset < injections_query.len() {
585+
include_path_in_error(error, &injection_ranges, &injections_query, 0)
586+
} else if error.offset < injections_query.len() + locals_query.len() {
587+
include_path_in_error(
588+
error,
589+
&locals_ranges,
590+
&locals_query,
591+
injections_query.len(),
592+
)
593+
} else {
594+
include_path_in_error(
595+
error,
596+
&highlight_ranges,
597+
&highlights_query,
598+
injections_query.len() + locals_query.len(),
599+
)
600+
}
601+
})?;
566602
let mut all_highlight_names = self.highlight_names.lock().unwrap();
567603
if self.use_all_highlight_names {
568604
for capture_name in result.query.capture_names() {
@@ -581,8 +617,8 @@ impl<'a> LanguageConfiguration<'a> {
581617
pub fn tags_config(&self, language: Language) -> Result<Option<&TagsConfiguration>> {
582618
self.tags_config
583619
.get_or_try_init(|| {
584-
let tags_query = self.read_queries(&self.tags_filenames, "tags.scm")?;
585-
let locals_query = self.read_queries(&self.locals_filenames, "locals.scm")?;
620+
let (tags_query, _) = self.read_queries(&self.tags_filenames, "tags.scm")?;
621+
let (locals_query, _) = self.read_queries(&self.locals_filenames, "locals.scm")?;
586622
if tags_query.is_empty() {
587623
Ok(None)
588624
} else {
@@ -596,27 +632,34 @@ impl<'a> LanguageConfiguration<'a> {
596632
.map(Option::as_ref)
597633
}
598634

599-
fn read_queries(&self, paths: &Option<Vec<String>>, default_path: &str) -> Result<String> {
635+
fn read_queries(
636+
&self,
637+
paths: &Option<Vec<String>>,
638+
default_path: &str,
639+
) -> Result<(String, Vec<(String, Range<usize>)>)> {
640+
let mut query = String::new();
641+
let mut path_ranges = Vec::new();
600642
if let Some(paths) = paths.as_ref() {
601-
let mut query = String::new();
602643
for path in paths {
603-
let path = self.root_path.join(path);
604-
query += &fs::read_to_string(&path).map_err(Error::wrap(|| {
644+
let abs_path = self.root_path.join(path);
645+
let prev_query_len = query.len();
646+
query += &fs::read_to_string(&abs_path).map_err(Error::wrap(|| {
605647
format!("Failed to read query file {:?}", path)
606648
}))?;
649+
path_ranges.push((path.clone(), prev_query_len..query.len()));
607650
}
608-
Ok(query)
609651
} else {
610652
let queries_path = self.root_path.join("queries");
611653
let path = queries_path.join(default_path);
612654
if path.exists() {
613-
fs::read_to_string(&path).map_err(Error::wrap(|| {
655+
query = fs::read_to_string(&path).map_err(Error::wrap(|| {
614656
format!("Failed to read query file {:?}", path)
615-
}))
616-
} else {
617-
Ok(String::new())
657+
}))?;
658+
path_ranges.push((default_path.to_string(), 0..query.len()));
618659
}
619660
}
661+
662+
Ok((query, path_ranges))
620663
}
621664
}
622665

‎cli/src/test.rs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -102,14 +102,14 @@ pub fn check_queries_at_path(language: Language, path: &Path) -> Result<()> {
102102
if path.exists() {
103103
for entry in fs::read_dir(path)? {
104104
let entry = entry?;
105-
let hidden = entry.file_name().to_str().unwrap_or("").starts_with(".");
105+
let filepath = entry.file_name();
106+
let filepath = filepath.to_str().unwrap_or("");
107+
let hidden = filepath.starts_with(".");
106108
if !hidden {
107109
let content = fs::read_to_string(entry.path()).map_err(Error::wrap(|| {
108110
format!("Error reading query file {:?}", entry.file_name())
109111
}))?;
110-
Query::new(language, &content).map_err(Error::wrap(|| {
111-
format!("Error in query file {:?}", entry.file_name())
112-
}))?;
112+
Query::new(language, &content).map_err(|e| (filepath, e))?;
113113
}
114114
}
115115
}

0 commit comments

Comments
 (0)