@@ -29,25 +29,27 @@ pub fn render_with_highlighting(src: &str, class: Option<&str>, id: Option<&str>
2929
3030 let mut out = Vec :: new ( ) ;
3131 write_header ( class, id, & mut out) . unwrap ( ) ;
32- write_source ( & sess,
33- lexer:: StringReader :: new ( & sess. span_diagnostic , fm) ,
34- & mut out) . unwrap ( ) ;
32+ if let Err ( _) = write_source ( & sess,
33+ lexer:: StringReader :: new ( & sess. span_diagnostic , fm) ,
34+ & mut out) {
35+ return format ! ( "<pre>{}</pre>" , src)
36+ }
3537 write_footer ( & mut out) . unwrap ( ) ;
3638 String :: from_utf8_lossy ( & out[ ..] ) . into_owned ( )
3739}
3840
3941/// Highlights `src`, returning the HTML output. Returns only the inner html to
4042/// be inserted into an element. C.f., `render_with_highlighting` which includes
4143/// an enclosing `<pre>` block.
42- pub fn render_inner_with_highlighting ( src : & str ) -> String {
44+ pub fn render_inner_with_highlighting ( src : & str ) -> io :: Result < String > {
4345 let sess = parse:: ParseSess :: new ( ) ;
4446 let fm = sess. codemap ( ) . new_filemap ( "<stdin>" . to_string ( ) , src. to_string ( ) ) ;
4547
4648 let mut out = Vec :: new ( ) ;
4749 write_source ( & sess,
4850 lexer:: StringReader :: new ( & sess. span_diagnostic , fm) ,
49- & mut out) . unwrap ( ) ;
50- String :: from_utf8_lossy ( & out[ ..] ) . into_owned ( )
51+ & mut out) ? ;
52+ Ok ( String :: from_utf8_lossy ( & out[ ..] ) . into_owned ( ) )
5153}
5254
5355/// Exhausts the `lexer` writing the output into `out`.
@@ -65,7 +67,17 @@ fn write_source(sess: &parse::ParseSess,
6567 let mut is_macro = false ;
6668 let mut is_macro_nonterminal = false ;
6769 loop {
68- let next = lexer. next_token ( ) ;
70+ let next = match lexer. try_next_token ( ) {
71+ Ok ( tok) => tok,
72+ Err ( _) => {
73+ lexer. emit_fatal_errors ( ) ;
74+ lexer. span_diagnostic . struct_warn ( "Backing out of syntax highlighting" )
75+ . note ( "You probably did not intend to render this \
76+ as a rust code-block")
77+ . emit ( ) ;
78+ return Err ( io:: Error :: new ( io:: ErrorKind :: Other , "" ) )
79+ } ,
80+ } ;
6981
7082 let snip = |sp| sess. codemap ( ) . span_to_snippet ( sp) . unwrap ( ) ;
7183
0 commit comments