Improve error messages for unknown variables in evalerror

This commit is contained in:
elkowar 2021-07-27 17:24:40 +02:00
parent 01c7ba6e2a
commit 99fd51dc12
No known key found for this signature in database
GPG Key ID: E321AD71B1D1F27F
4 changed files with 22 additions and 9 deletions

View File

@ -10,7 +10,7 @@ use std::collections::HashMap;
#[derive(Debug, thiserror::Error)]
pub enum EvalError {
#[error("Tried to reference variable `{0}`, but we cannot access variables here")]
NoVariablesAllowed(String),
NoVariablesAllowed(VarName),
#[error("Invalid regex: {0}")]
InvalidRegex(#[from] regex::Error),
@ -28,7 +28,7 @@ pub enum EvalError {
UnknownFunction(String),
#[error("Unknown variable {0}")]
UnknownVariable(String),
UnknownVariable(VarName),
#[error("Unable to index into value {0}")]
CannotIndex(String),
@ -116,7 +116,7 @@ impl SimplExpr {
)),
VarRef(span, ref name) => match variables.get(name) {
Some(value) => Ok(Literal(span, value.clone())),
None => Err(EvalError::UnknownVariable(name.to_string()).at(span)),
None => Err(EvalError::UnknownVariable(name.clone()).at(span)),
},
}
}

View File

@ -11,6 +11,9 @@ use crate::{
use super::parser::parse_error;
use eww_shared_util::{AttrName, Span, Spanned, VarName};
fn span_to_primary_label(span: Span) -> Label<usize> {
Label::primary(span.2, span.0..span.1)
}
fn span_to_secondary_label(span: Span) -> Label<usize> {
Label::secondary(span.2, span.0..span.1)
}
@ -189,7 +192,15 @@ impl ToDiagnostic for simplexpr::parser::lexer::LexicalError {
impl ToDiagnostic for simplexpr::eval::EvalError {
fn to_diagnostic(&self) -> Diagnostic<usize> {
gen_diagnostic!(self, self.span())
use simplexpr::eval::EvalError::*;
match self {
UnresolvedVariable(name) | UnknownVariable(name) | NoVariablesAllowed(name) => gen_diagnostic! {
msg = self,
note = format!("If you meant to use the literal value \"{}\", surround the value in quotes", name)
},
Spanned(span, error) => error.as_ref().to_diagnostic().with_label(span_to_primary_label(*span)),
_ => gen_diagnostic!(self, self.span()),
}
}
}

View File

@ -92,6 +92,8 @@ impl Lexer {
}
}
// TODO string literal interpolation stuff by looking for indexes of {{ and }}?
impl Iterator for Lexer {
type Item = Result<(usize, Token, usize), parse_error::ParseError>;

View File

@ -45,11 +45,11 @@
(defpoll music :interval "5s" "playerctl metadata --format '{{ artist }} - {{ title }}' || true")
(defpoll volume :interval "16s" "scripts/getvol")
(defpoll number_day :interval "5h" "date '+%d'")
(defpoll month :interval "10h" "date '+%b'")
(defpoll min :interval "10s" "date '+%M'")
(defpoll hour :interval "1m" "date '+%H'")
(defpoll year_full :interval "15h" "date '+%Y'")
(defpoll number_day :interval "5h" "date '+%d'")
(defpoll month :interval "10h" "date '+%b'")
(defpoll min :interval "10s" "date '+%M'")
(defpoll hour :interval "1m" "date '+%H'")
(defpoll year_full :interval "15h" "date '+%Y'")
(deflisten battery-remaining "/sys/class/power_supply/BAT0/capacity")