@@ -25,7 +25,7 @@ mod symbol;
2525mod token;
2626mod vm;
2727
28- use std:: { borrow:: Cow , fs, path:: PathBuf } ;
28+ use std:: { borrow:: Cow , fmt , fs, path:: PathBuf } ;
2929
3030// Public API
3131pub use ir:: IrBuilder ;
@@ -40,6 +40,25 @@ pub use source::Source;
4040pub use symbol:: { SymTable , Symbol , SymbolError } ;
4141pub use vm:: { Vm , VmError } ;
4242
43+ /// A wrapper that formats errors with source code highlighting
44+ struct FormattedError {
45+ message : String ,
46+ }
47+
48+ impl fmt:: Display for FormattedError {
49+ fn fmt ( & self , f : & mut fmt:: Formatter < ' _ > ) -> fmt:: Result {
50+ write ! ( f, "{}" , self . message)
51+ }
52+ }
53+
54+ impl < T : SpanError > From < ( & T , & Source < ' _ > ) > for FormattedError {
55+ fn from ( ( error, source) : ( & T , & Source < ' _ > ) ) -> Self {
56+ Self {
57+ message : format ! ( "{}\n {}" , error, source. highlight( & error. span( ) ) ) ,
58+ }
59+ }
60+ }
61+
4362#[ derive( Debug ) ]
4463enum EvalSource < ' str > {
4564 Source ( Cow < ' str , Source < ' str > > ) ,
@@ -97,14 +116,14 @@ impl<'str> Eval<'str> {
97116 let mut parser = Parser :: new ( source) ;
98117 let mut ast: Expr = match parser
99118 . parse ( )
100- . map_err ( |err| Self :: error_with_source ( & err, source) ) ?
119+ . map_err ( |err| FormattedError :: from ( ( & err, source. as_ref ( ) ) ) . to_string ( ) ) ?
101120 {
102121 Some ( ast) => ast,
103122 None => return Ok ( Program :: default ( ) ) ,
104123 } ;
105124 Sema :: new ( table)
106125 . visit ( & mut ast)
107- . map_err ( |err| Self :: error_with_source ( & err, source) ) ?;
126+ . map_err ( |err| FormattedError :: from ( ( & err, source. as_ref ( ) ) ) . to_string ( ) ) ?;
108127 IrBuilder :: new ( ) . build ( & ast) . map_err ( |err| err. to_string ( ) )
109128 }
110129 EvalSource :: File ( path) => {
@@ -113,8 +132,4 @@ impl<'str> Eval<'str> {
113132 }
114133 }
115134 }
116-
117- fn error_with_source < T : SpanError > ( error : & T , source : & Source ) -> String {
118- format ! ( "{}\n {}" , error, source. highlight( & error. span( ) ) )
119- }
120135}
0 commit comments