]> git.donarmstrong.com Git - lilypond.git/blob - lily/parse-scm.cc
catch GUILE errors
[lilypond.git] / lily / parse-scm.cc
1
2 #include "lily-guile.hh"
3 #include "parse-scm.hh"
4 #include "string.hh"
5
6
7 /*
8   Pass string to scm parser, evaluate one expression.
9   Return result value and #chars read.
10
11   Thanks to Gary Houston <ghouston@freewire.co.uk>
12
13   Need guile-1.3.4 (>1.3 anyway) for ftell on str ports -- jcn
14 */
15 SCM
16 internal_ly_parse_scm (Parse_start * ps)
17 {
18   SCM str = ly_str02scm (ps->str);
19   SCM port = scm_mkstrport (SCM_INUM0, str, SCM_OPN | SCM_RDNG,
20                             "ly_eval_scm_0str");
21
22   scm_set_port_filename_x (port, scm_makfrom0str (ps->start_location.file_string ().get_str0()));
23   scm_set_port_line_x (port,  gh_int2scm (ps->start_location.line_number ()));
24   scm_set_port_column_x (port,  gh_int2scm (ps->start_location.column_number()));
25   
26   SCM from = scm_ftell (port);
27
28   SCM form;
29   SCM answer = SCM_UNSPECIFIED;
30
31   /* Read expression from port */
32   if (!SCM_EOF_OBJECT_P (form = scm_read (port)))
33     answer = scm_primitive_eval (form);
34  
35   /*
36    After parsing
37
38  (begin (foo 1 2))
39
40    all seems fine, but after parsing
41
42  (foo 1 2)
43
44    read_buf has been advanced to read_pos - 1,
45    so that scm_ftell returns 1, instead of #parsed chars
46    */
47   
48   /*
49     urg: reset read_buf for scm_ftell
50     shouldn't scm_read () do this for us?
51   */
52   scm_fill_input (port);
53   SCM to = scm_ftell (port);
54   ps->nchars = gh_scm2int (to) - gh_scm2int (from);
55
56   /* Don't close the port here; if we re-enter this function via a
57      continuation, then the next time we enter it, we'll get an error.
58      It's a string port anyway, so there's no advantage to closing it
59      early.
60
61      scm_close_port (port);
62   */
63
64   return answer;
65 }
66
67
68 SCM
69 catch_protected_parse_body (void *p)
70 {
71   Parse_start *ps = (Parse_start*) p;
72   return internal_ly_parse_scm (ps);
73 }
74
75 SCM 
76 parse_handler (void * data, SCM tag, SCM args)
77 {
78   Parse_start* ps = (Parse_start*) data;
79
80   ps->start_location.error (_("GUILE signaled an error for the expression begining here"));
81
82   gh_display (args);
83   gh_newline();
84   return SCM_EOL;
85 }
86
87 /*
88   Do some magical incantations: if not, lily will exit on the first
89   GUILE error, leaving no location trace. 
90  */
91 SCM
92 protected_ly_parse_scm (Parse_start *ps)
93 {
94   return scm_internal_catch (scm_misc_error_key, &catch_protected_parse_body,
95                              (void*)ps,
96                              &parse_handler, (void*)ps);
97
98 }
99
100
101 SCM
102 ly_parse_scm (char const* s, int *n, Input i)
103 {
104   Parse_start ps ;
105   ps.str = s;
106   ps.start_location = i;
107
108   SCM ans = protected_ly_parse_scm (&ps);
109   *n = ps.nchars;
110   return ans;  
111 }
112