79b30b60cdd7905600ea3d2762961aa4cac084c7
[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         typedef Token::TokenType TokenType;
86
87         struct Context {
88             std::string str;
89             std::vector<Token> path;
90             char ch;
91             Token token;
92             
93             // OUCH ... This is sooooo stupid .. push_back_a and assign_a take their 
94             // arguments by const-reference and STORE the REFERENCE ... they do NOT accept
95             // literal values !!!!!! 
96             static const Token EmptyToken;
97         };
98
99         Context & context;
100
101         ///////////////////////////////////////////////////////////////////////////
102         // Dispatching semantic actions
103
104         ParseDispatcher & dispatcher;
105
106         struct Dispatch_actor
107         {
108             Dispatch_actor(boost::function<void ()> fn_) : fn (fn_) {}
109
110             template <class Value>
111             void operator()(Value const & value) const
112                 { fn(); }
113
114             template <class Iterator>
115             void operator()(Iterator const & f, Iterator const & l) const
116                 { fn(); }
117
118             boost::function<void ()> fn;
119         };
120         
121         template <class Callback>
122         Dispatch_actor dispatch(Callback cb) const
123             { return Dispatch_actor(boost::bind(cb, boost::ref(dispatcher))); }
124
125         template <class Callback, class Arg>
126         Dispatch_actor dispatch(Callback cb, Arg const & arg) const
127             { return Dispatch_actor(boost::bind(cb, boost::ref(dispatcher), arg)); }
128
129         template <class Callback, class Arg1, class Arg2>
130         Dispatch_actor dispatch(Callback cb, Arg1 const & arg1, Arg2 const & arg2) const
131             { return Dispatch_actor(boost::bind(cb, boost::ref(dispatcher), arg1, arg2)); }
132
133         struct TokenSetter_actor
134         {
135             TokenSetter_actor(Context & c, TokenType t) : c_ (c), t_ (t) {}
136             
137             void operator()(std::string const & value) const
138                 { c_.token = Token(t_, value); }
139             void operator()(char value) const
140                 { c_.token = Token(t_, std::string(1,value)); }
141             template <class Iterator> void operator()(Iterator const & f, Iterator const & l) const
142                 { c_.token = Token(t_, std::string(f,l)); }
143
144             Context & c_;
145             TokenType t_;
146         };
147
148         struct TokenSetter_value_actor
149             : public TokenSetter_actor
150         {
151             TokenSetter_value_actor(Context & c, TokenType t, std::string & v) 
152                 : TokenSetter_actor(c,t), v_ (v) {}
153
154             template <class Value> void operator()(Value const &) const
155                 { TokenSetter_actor::operator()(v_); }
156
157             template <class Iterator> void operator()(Iterator const &, Iterator const &) const
158                 { TokenSetter_actor::operator()(v_); }
159
160             std::string & v_;
161         };
162
163         TokenSetter_actor set_token_a(TokenType t) const
164             { return TokenSetter_actor(context, t); }
165
166         TokenSetter_value_actor set_token_a(TokenType t, std::string & arg) const
167             { return TokenSetter_value_actor(context, t, arg); }
168
169         ///////////////////////////////////////////////////////////////////////////
170
171         CommandGrammar(ParseDispatcher & d, Context & c) 
172             : context(c), dispatcher(d) {}
173
174         template <class Scanner>
175         struct definition 
176             : public boost::spirit::grammar_def< boost::spirit::rule<Scanner>, 
177                                                  boost::spirit::rule<Scanner> >
178         {
179             boost::spirit::rule<Scanner> command, path, argument, word, string, hexstring, token,
180                 punctuation, hexbyte, balanced_tokens, simple_argument, complex_argument, builtin, 
181                 skip, commands, block, statement, relpath, abspath;
182             boost::spirit::chset<> special_p, punctuation_p, space_p, invalid_p, word_p;
183             boost::spirit::distinct_parser<> keyword_p;
184
185             definition(CommandGrammar const & self) : 
186
187                 // Characters with a special meaning within the parser
188                 special_p ("/(){};"),
189
190                 // Additional characters which are returned as punctuation tokens
191                 // (only allowed within '()').
192                 punctuation_p (",="),
193
194                 // Whitespace characters
195                 space_p (" \t\n\r"),
196
197                 // Invalid characters: All chars below \x20 (space) which are not space_p
198                 // (don't put a \0 in the chset<> argument *string* ...)
199                 invalid_p (
200                     boost::spirit::chset<>('\0') | boost::spirit::chset<>("\x01-\x20") - space_p ),
201
202                 // Valid word characters
203                 word_p (
204                     boost::spirit::anychar_p - special_p - punctuation_p - space_p - invalid_p),
205
206                 // Keywords must not be followed by a word char or '/'
207                 keyword_p ( word_p | boost::spirit::ch_p('/') )
208
209             {
210                 using namespace boost::spirit;
211                 typedef ParseDispatcher PD;
212                 typedef Token AT;
213
214                 ///////////////////////////////////////////////////////////////////
215                 // Spirit grammar
216                 //
217                 // Syntax summary:
218                 // This is EBNF with some minor tweaks to accommodate C++ syntax
219                 //
220                 //   * and +    like EBNF but they precede their argument
221                 //   >>         is followed by
222                 //   !          optional
223                 //   a % b      match any number of a's separated by b
224                 //   a - b      match a but not b
225                 //
226                 // Beside this, we use some special parsers (ch_p, eps_p, confix_p, lex_escape_ch_p,
227                 // keyword_p, comment_p) and directives (lexeme_d), however, the parser should be
228                 // quite readable.
229                 //   
230                 //   ch_p             match character
231                 //   eps_p            always matches nothing (to attach unconditional actions)
232                 //   confix_p(a,b,c)  match b, preceded by a and terminated by c. Used to parse
233                 //                    string literals and comments
234                 //   lex_escape_ch_p  match a lex style escape char. This is like a C++ style
235                 //                    literal string escape char, however \x will be replaced by 'x'
236                 //                    for any char 'x' if it has no special meaning.
237                 //   keyword_p        match a delimited keyword
238                 //   comment_p(a,b)   match comment starting with a and terminated with b. b
239                 //                    defaults to end-of-line
240                 //
241                 //   lexeme_d         don't skip whitespace (as defined by the skip parser)
242                 //
243                 // Aligned to the right at column 50 are semantic actions.
244                 //
245                 // For clarity, I have used 'ch_p' explicitly throughout even though it is optional
246                 // in most cases.
247                 //
248                 // More info is in the Boost.Spirit documentation
249
250                 commands
251                     =  * command
252                     ;
253
254                 command 
255                     =    builtin >> (ch_p(';') | end_p)
256                     |    path  >> ( block | statement )
257                     |    ch_p(';') // Ignore empty commands
258                     ;
259
260                 builtin
261                     =    keyword_p("cd") 
262                       >> path
263                       >> eps_p                    [ self.dispatch(&PD::builtin_cd,
264                                                                   boost::ref(self.context.path)) ]
265                     |    keyword_p("ls")
266                       >> ! path
267                       >> eps_p                    [ self.dispatch(&PD::builtin_ls,
268                                                                   boost::ref(self.context.path)) ]
269                     |    keyword_p("exit")        [ self.dispatch(&PD::builtin_exit) ]
270                     
271                     |    keyword_p("help")
272                       >> ! path
273                       >> eps_p                    [ self.dispatch(&PD::builtin_help,
274                                                                   boost::ref(self.context.path)) ]
275                     ;
276
277                 block
278                     =    ch_p('{')                [ self.dispatch(&PD::pushDirectory,
279                                                                   boost::ref(self.context.path)) ]
280                       >> * command 
281                       >> ch_p('}')                [ self.dispatch(&PD::popDirectory) ]
282                     ;
283
284                 statement
285                     = eps_p                       [ self.dispatch(&PD::beginCommand, 
286                                                                   boost::ref(self.context.path)) ]
287                       >> * argument
288                       >> (ch_p(';') | end_p)
289                       >> eps_p                    [ self.dispatch(&PD::endCommand) ]
290                     ;
291
292                 argument
293                     =    simple_argument          [ self.dispatch(&PD::pushToken, 
294                                                                   boost::ref(self.context.token)) ]
295                     |    balanced_tokens
296                     ;
297                 
298                 simple_argument         // All these return their value in context.token
299                     =    string
300                     |    hexstring
301                     |    word
302                     ;
303                 
304                 string                  // Returns value in context.token
305                     =    eps_p                    [ clear_a(self.context.str) ]
306                       >> lexeme_d
307                          [
308                              ch_p('"')
309                           >> * ( ( lex_escape_ch_p[ assign_a(self.context.ch) ] 
310                                    - '"' 
311                                  )                [ append_a(self.context.str,
312                                                              self.context.ch) ] 
313                                )
314                           >> ch_p('"')            [ self.set_token_a(AT::BasicString, 
315                                                                      self.context.str) ]
316                          ]
317                     ;
318
319                 hexstring               // Returns value in context.token
320                     =    eps_p                    [ clear_a(self.context.str) ]
321                       >> confix_p( "x\"", * hexbyte, '"' )
322                                                   [ self.set_token_a(AT::HexString,
323                                                                      self.context.str) ]
324                     ;
325
326                 path                    // Returns value in context.path
327                     =    eps_p                    [ clear_a(self.context.path) ]
328                       >> relpath | abspath
329                     ;
330
331                 relpath
332                     =    (   word                 [ push_back_a(self.context.path,
333                                                                 self.context.token) ]
334                            % ch_p('/') )
335                       >> ( ! ch_p('/')            [ push_back_a(self.context.path,
336                                                                 self.context.EmptyToken) ] )
337                     ;
338
339                 abspath
340                     =    ch_p('/')                [ push_back_a(self.context.path,
341                                                                 self.context.EmptyToken) ]
342                       >> ( relpath
343                          | eps_p                  [ push_back_a(self.context.path,
344                                                                 self.context.EmptyToken) ] )
345                     ;
346
347                 balanced_tokens 
348                     =    ch_p('(')                [ self.set_token_a(AT::ArgumentGroupOpen) ]
349                                                   [ self.dispatch(&PD::pushToken, 
350                                                                   boost::ref(self.context.token)) ]
351                       >> * token
352                       >> ch_p(')')                [ self.set_token_a(AT::ArgumentGroupClose) ]
353                                                   [ self.dispatch(&PD::pushToken, 
354                                                                   boost::ref(self.context.token)) ]
355                     ;
356
357                 token
358                     =    simple_argument          [ self.dispatch(&PD::pushToken,
359                                                                   boost::ref(self.context.token)) ]
360                     |    punctuation              [ self.dispatch(&PD::pushToken,
361                                                                   boost::ref(self.context.token)) ]
362                     |    balanced_tokens
363                     ;
364
365                 punctuation             // Returns value in context.str
366                     =    ch_p('/')                [ self.set_token_a(AT::PathSeparator) ]
367                     |    ch_p('{')                [ self.set_token_a(AT::DirectoryGroupOpen) ]
368                     |    ch_p('}')                [ self.set_token_a(AT::DirectoryGroupClose) ]
369                     |    ch_p(';')                [ self.set_token_a(AT::CommandTerminator) ]
370                     |    punctuation_p            [ self.set_token_a(AT::OtherPunctuation) ]
371                     ;
372
373                 word                    // Returns value in context.token
374                     =    lexeme_d
375                          [
376                              eps_p
377                           >> (+ word_p)           [ assign_a(self.context.str) ]
378                          ]
379                       >> eps_p                    [ self.set_token_a(AT::Word, self.context.str) ]
380                     ;
381
382                 hexbyte
383                     =    uint_parser<char, 16, 2, 2>()
384                                                   [ append_a(self.context.str) ]
385                     ;
386
387                 skip
388                     =    space_p | comment_p('#')
389                     ;
390
391                 ///////////////////////////////////////////////////////////////////
392
393                 start_parsers(
394                     commands,           // CommandParser
395                     skip                // SkipParser
396                 );
397
398                 BOOST_SPIRIT_DEBUG_TRACE_RULE(command,1);
399                 BOOST_SPIRIT_DEBUG_TRACE_RULE(path,1);
400                 BOOST_SPIRIT_DEBUG_TRACE_RULE(argument,1);
401                 BOOST_SPIRIT_DEBUG_TRACE_RULE(word,1);
402                 BOOST_SPIRIT_DEBUG_TRACE_RULE(string,1);
403                 BOOST_SPIRIT_DEBUG_TRACE_RULE(hexstring,1);
404                 BOOST_SPIRIT_DEBUG_TRACE_RULE(token,1);
405                 BOOST_SPIRIT_DEBUG_TRACE_RULE(punctuation,1);
406                 BOOST_SPIRIT_DEBUG_TRACE_RULE(hexbyte,1);
407                 BOOST_SPIRIT_DEBUG_TRACE_RULE(balanced_tokens,1);
408                 BOOST_SPIRIT_DEBUG_TRACE_RULE(simple_argument,1);
409                 BOOST_SPIRIT_DEBUG_TRACE_RULE(complex_argument,1);
410                 BOOST_SPIRIT_DEBUG_TRACE_RULE(builtin,1);
411                 BOOST_SPIRIT_DEBUG_TRACE_RULE(commands,1);
412                 BOOST_SPIRIT_DEBUG_TRACE_RULE(block,1);
413                 BOOST_SPIRIT_DEBUG_TRACE_RULE(statement,1);
414                 BOOST_SPIRIT_DEBUG_TRACE_RULE(relpath,1);
415                 BOOST_SPIRIT_DEBUG_TRACE_RULE(abspath,1);
416             }
417         };
418     };
419
420     template <class ParseDispatcher>
421     Token const CommandGrammar<ParseDispatcher>::Context::EmptyToken;
422
423 #endif
424
425 }}}
426
427 ///////////////////////////////ih.e////////////////////////////////////////
428 #endif
429
430 \f
431 // Local Variables:
432 // mode: c++
433 // fill-column: 100
434 // comment-column: 40
435 // c-file-style: "senf"
436 // indent-tabs-mode: nil
437 // ispell-local-dictionary: "american"
438 // compile-command: "scons -u test"
439 // End: