Fix documentation
[senf.git] / Console / Parse.ih
1 // $Id$
2 //
3 // Copyright (C) 2008 
4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
5 // Competence Center NETwork research (NET), St. Augustin, GERMANY
6 //     Stefan Bund <g0dil@berlios.de>
7 //
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 2 of the License, or
11 // (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 // GNU General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the
20 // Free Software Foundation, Inc.,
21 // 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
23 /** \file
24     \brief Parse internal header */
25
26 #ifndef IH_Parse_
27 #define IH_Parse_ 1
28
29 // Custom includes
30 #include <vector>
31 #include <boost/regex.hpp>
32 #include <boost/spirit.hpp>
33 #include <boost/spirit/utility/grammar_def.hpp>
34 #include <boost/spirit/actor.hpp>
35 #include <boost/bind.hpp>
36 #include <boost/function.hpp>
37 #include <boost/ref.hpp>
38
39 ///////////////////////////////ih.p////////////////////////////////////////
40
41 namespace senf {
42 namespace console {
43 namespace detail {
44
45 #ifndef DOXYGEN
46
47     ///////////////////////////////////////////////////////////////////////////
48     // append_a
49
50     struct append_action
51     {
52         template <class T, class Value>
53         void act(T & ref, Value const & value) const
54             { ref += T(1, value); }
55
56         template <class T, class Iterator>
57         void act(T & ref, Iterator const & f, Iterator const & l) const
58             { ref += T(f,l); }
59     };
60
61     template <class T>
62     inline boost::spirit::ref_value_actor<T, append_action> 
63     append_a(T & ref)
64     { return boost::spirit::ref_value_actor<T, append_action>(ref); }
65     
66     template <class T, class Value>
67     inline boost::spirit::ref_const_ref_actor<T, Value, append_action> 
68     append_a(T & ref, Value const & value)
69     { return boost::spirit::ref_const_ref_actor<T, Value, append_action>(ref, value); }
70
71     ///////////////////////////////////////////////////////////////////////////
72     // Grammar
73
74     template <class ParseDispatcher>
75     struct CommandGrammar : boost::spirit::grammar<CommandGrammar<ParseDispatcher> >
76     {
77         ///////////////////////////////////////////////////////////////////////////
78         // Start rules
79
80         enum { CommandParser, SkipParser };
81
82         ///////////////////////////////////////////////////////////////////////////
83         // The parse context (variables needed while parsing)
84
85         struct Context {
86             std::string str;
87             std::vector<std::string> path;
88             char ch;
89         };
90
91         Context & context;
92
93         ///////////////////////////////////////////////////////////////////////////
94         // Dispatching semantic actions
95
96         ParseDispatcher & dispatcher;
97
98         struct Dispatch_actor
99         {
100             Dispatch_actor(boost::function<void ()> fn_) : fn (fn_) {}
101
102             template <class Value>
103             void operator()(Value const & value) const
104                 { fn(); }
105
106             template <class Iterator>
107             void operator()(Iterator const & f, Iterator const & l) const
108                 { fn(); }
109
110             boost::function<void ()> fn;
111         };
112         
113         template <class Callback>
114         Dispatch_actor dispatch(Callback cb) const
115             { return Dispatch_actor(boost::bind(cb, boost::ref(dispatcher))); }
116
117         template <class Callback, class Arg>
118         Dispatch_actor dispatch(Callback cb, Arg const & arg) const
119             { return Dispatch_actor(boost::bind(cb, boost::ref(dispatcher), arg)); }
120
121         ///////////////////////////////////////////////////////////////////////////
122
123         CommandGrammar(ParseDispatcher & d, Context & c) 
124             : context(c), dispatcher(d) {}
125
126         template <class Scanner>
127         struct definition 
128             : public boost::spirit::grammar_def< boost::spirit::rule<Scanner>, 
129                                                  boost::spirit::rule<Scanner> >
130         {
131             boost::spirit::rule<Scanner> command, path, argument, word, string, hexstring, token,
132                 punctuation, hexbyte, balanced_tokens, simple_argument, complex_argument, builtin, 
133                 skip, commands, block, statement, relpath, abspath;
134             boost::spirit::chset<> special_p, punctuation_p, space_p, invalid_p, word_p;
135             boost::spirit::distinct_parser<> keyword_p;
136
137             definition(CommandGrammar const & self) : 
138
139                 // Characters with a special meaning within the parser
140                 special_p ("/(){};"),
141
142                 // Characters which are returned as punctuation tokens
143                 // (only allowed within '()')
144                 punctuation_p (",=/{};"),
145
146                 // Whitespace characters
147                 space_p (" \t\n\r"),
148
149                 // Invalid characters: All chars below \x20 (space) which are not space_p
150                 // (don't put a \0 in the chset<> argument *string* ...)
151                 invalid_p (
152                     boost::spirit::chset<>('\0') | boost::spirit::chset<>("\x01-\x20") - space_p ),
153
154                 // Valid word characters
155                 word_p (
156                     boost::spirit::anychar_p - special_p - punctuation_p - space_p - invalid_p),
157
158                 // Keywords must not be followed by a word char or '/'
159                 keyword_p ( word_p | boost::spirit::ch_p('/') )
160
161             {
162                 using namespace boost::spirit;
163                 typedef ParseDispatcher PD;
164
165                 ///////////////////////////////////////////////////////////////////
166                 // Spirit grammar
167                 //
168                 // Syntax summary:
169                 // This is EBNF with some minor tweaks to accommodate C++ syntax
170                 //
171                 //   * and +    like EBNF but they precede their argument
172                 //   >>         is followed by
173                 //   !          optional
174                 //   a % b      match any number of a's separated by b
175                 //   a - b      match a but not b
176                 //
177                 // Beside this, we use some special parsers (ch_p, eps_p, confix_p, lex_escape_ch_p,
178                 // keyword_p, comment_p) and directives (lexeme_d), however, the parser should be
179                 // quite readable.
180                 //   
181                 //   ch_p             match character
182                 //   eps_p            always matches nothing (to attach unconditional actions)
183                 //   confix_p(a,b,c)  match b, preceded by a and terminated by c. Used to parse
184                 //                    string literals and comments
185                 //   lex_escape_ch_p  match a lex style escape char. This is like a C++ style
186                 //                    literal string escape char, however \x will be replaced by 'x'
187                 //                    for any char 'x' if it has no special meaning.
188                 //   keyword_p        match a delimited keyword
189                 //   comment_p(a,b)   match comment starting with a and terminated with b. b
190                 //                    defaults to end-of-line
191                 //
192                 //   lexeme_d         don't skip whitespace (as defined by the skip parser)
193                 //
194                 // Aligned to the right at column 50 are semantic actions.
195                 //
196                 // For clarity, I have used 'ch_p' explicitly throughout even though it is optional
197                 // in most cases.
198                 //
199                 // More info is in the Boost.Spirit documentation
200
201                 commands
202                     =  * command
203                     ;
204
205                 command 
206                     =    builtin >> (ch_p(';') | end_p)
207                     |    path  >> ( block | statement )
208                     |    ch_p(';') // Ignore empty commands
209                     ;
210
211                 builtin
212                     =    keyword_p("cd") 
213                       >> path
214                       >> eps_p                    [ self.dispatch(&PD::builtin_cd,
215                                                                   boost::ref(self.context.path)) ]
216                     |    keyword_p("ls")
217                       >> ! path
218                       >> eps_p                    [ self.dispatch(&PD::builtin_ls,
219                                                                   boost::ref(self.context.path)) ]
220                     |    keyword_p("exit")        [ self.dispatch(&PD::builtin_exit) ]
221                     
222                     |    keyword_p("help")
223                       >> ! path
224                       >> eps_p                    [ self.dispatch(&PD::builtin_help,
225                                                                   boost::ref(self.context.path)) ]
226                     ;
227
228                 block
229                     =    ch_p('{')                [ self.dispatch(&PD::pushDirectory,
230                                                                   boost::ref(self.context.path)) ]
231                       >> * command 
232                       >> ch_p('}')                [ self.dispatch(&PD::popDirectory) ]
233                     ;
234
235                 statement
236                     = eps_p                       [ self.dispatch(&PD::beginCommand, 
237                                                                   boost::ref(self.context.path)) ]
238                       >> * argument
239                       >> (ch_p(';') | end_p)
240                       >> eps_p                    [ self.dispatch(&PD::endCommand) ]
241                     ;
242
243                 argument
244                     =    simple_argument          [ self.dispatch(&PD::pushArgument, 
245                                                                   boost::ref(self.context.str)) ]
246                     |    complex_argument
247                     ;
248                 
249                 simple_argument         // All these return their value in context.str
250                     =    string
251                     |    hexstring
252                     |    word
253                     ;
254                 
255                 complex_argument        // Argument consists of multiple tokens
256                     =    ch_p('(')                [ self.dispatch(&PD::openGroup) ]
257                       >> * token
258                       >> ch_p(')')                [ self.dispatch(&PD::closeGroup) ]
259                     ;
260
261                 string                  // Returns value in context.str
262                     =    eps_p                    [ clear_a(self.context.str) ]
263                       >> lexeme_d
264                          [
265                              ch_p('"')
266                           >> * ( ( lex_escape_ch_p[ assign_a(self.context.ch) ] 
267                                    - '"' 
268                                  )                [ append_a(self.context.str,
269                                                              self.context.ch) ] 
270                                )
271                           >> ch_p('"')
272                          ]
273                     ;
274
275                 hexstring               // Returns value in context.str
276                     =    eps_p                    [ clear_a(self.context.str) ]
277                       >> confix_p( "x\"", * hexbyte, '"' )
278                     ;
279
280                 path                    // Returns value in context.path
281                     =    eps_p                    [ clear_a(self.context.path) ]
282                       >> relpath | abspath
283                     ;
284
285                 relpath
286                     =    (   word                 [ push_back_a(self.context.path) ] 
287                            % ch_p('/') )
288                       >> ( ! ch_p('/')            [ push_back_a(self.context.path,"") ] )
289                     ;
290
291                 abspath
292                     =    ch_p('/')                [ push_back_a(self.context.path, "") ]
293                       >> ( relpath
294                          | eps_p                  [ push_back_a(self.context.path, "") ] )
295                     ;
296
297                 balanced_tokens 
298                     =    ch_p('(')                [ self.dispatch(&PD::pushPunctuation, "(") ]
299                       >> * token
300                       >> ch_p(')')                [ self.dispatch(&PD::pushPunctuation, ")") ]
301                     ;
302
303                 token
304                     =    simple_argument          [ self.dispatch(&PD::pushWord, 
305                                                                   boost::ref(self.context.str)) ]
306                     |    punctuation              [ self.dispatch(&PD::pushPunctuation,
307                                                                   boost::ref(self.context.str)) ]
308                     |    balanced_tokens
309                     ;
310
311                 punctuation             // Returns value in context.str
312                     =    punctuation_p            [ assign_a(self.context.str) ]
313                     ;
314
315                 word                    // Returns value in context.str
316                     =    lexeme_d[ + word_p ]     [ assign_a(self.context.str) ]
317                     ;
318
319                 hexbyte
320                     =    uint_parser<char, 16, 2, 2>()
321                                                   [ append_a(self.context.str) ]
322                     ;
323
324                 skip
325                     =    space_p | comment_p('#')
326                     ;
327
328                 ///////////////////////////////////////////////////////////////////
329
330                 start_parsers(
331                     commands,           // CommandParser
332                     skip                // SkipParser
333                 );
334
335                 BOOST_SPIRIT_DEBUG_TRACE_RULE(command,1);
336                 BOOST_SPIRIT_DEBUG_TRACE_RULE(path,1);
337                 BOOST_SPIRIT_DEBUG_TRACE_RULE(argument,1);
338                 BOOST_SPIRIT_DEBUG_TRACE_RULE(word,1);
339                 BOOST_SPIRIT_DEBUG_TRACE_RULE(string,1);
340                 BOOST_SPIRIT_DEBUG_TRACE_RULE(hexstring,1);
341                 BOOST_SPIRIT_DEBUG_TRACE_RULE(token,1);
342                 BOOST_SPIRIT_DEBUG_TRACE_RULE(punctuation,1);
343                 BOOST_SPIRIT_DEBUG_TRACE_RULE(hexbyte,1);
344                 BOOST_SPIRIT_DEBUG_TRACE_RULE(balanced_tokens,1);
345                 BOOST_SPIRIT_DEBUG_TRACE_RULE(simple_argument,1);
346                 BOOST_SPIRIT_DEBUG_TRACE_RULE(complex_argument,1);
347                 BOOST_SPIRIT_DEBUG_TRACE_RULE(builtin,1);
348                 BOOST_SPIRIT_DEBUG_TRACE_RULE(commands,1);
349                 BOOST_SPIRIT_DEBUG_TRACE_RULE(block,1);
350                 BOOST_SPIRIT_DEBUG_TRACE_RULE(statement,1);
351                 BOOST_SPIRIT_DEBUG_TRACE_RULE(relpath,1);
352                 BOOST_SPIRIT_DEBUG_TRACE_RULE(abspath,1);
353             }
354         };
355     };
356
357
358
359 #endif
360
361 }}}
362
363 ///////////////////////////////ih.e////////////////////////////////////////
364 #endif
365
366 \f
367 // Local Variables:
368 // mode: c++
369 // fill-column: 100
370 // comment-column: 40
371 // c-file-style: "senf"
372 // indent-tabs-mode: nil
373 // ispell-local-dictionary: "american"
374 // compile-command: "scons -u test"
375 // End: