Utils/Console: Implement command node return value support
[senf.git] / Utils / 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_SENF_Scheduler_Console_Parse_
27 #define IH_SENF_Scheduler_Console_Parse_ 1
28
29 // Custom includes
30 #include <vector>
31 #include "../../config.hh"
32 #include <boost/spirit.hpp>
33 #include <boost/spirit/utility/grammar_def.hpp>
34 #include <boost/spirit/dynamic.hpp>
35 #include <boost/spirit/phoenix.hpp>
36 #include "../../Utils/Phoenix.hh"
37
38 ///////////////////////////////ih.p////////////////////////////////////////
39
40 namespace senf {
41 namespace console {
42 namespace detail {
43
44 #ifndef DOXYGEN
45
46     ///////////////////////////////////////////////////////////////////////////
47     // Grammar
48
49     template <class ParseDispatcher>
50     struct CommandGrammar : boost::spirit::grammar<CommandGrammar<ParseDispatcher> >
51     {
52         ///////////////////////////////////////////////////////////////////////////
53         // Start rules
54
55         enum { CommandParser, SkipParser, ArgumentsParser, PathParser };
56
57         ///////////////////////////////////////////////////////////////////////////
58         // The parse context (variables needed while parsing)
59
60         typedef Token::TokenType TokenType;
61
62         struct Context {
63             std::string str;
64             std::vector<Token> path;
65             char ch;
66             Token token;
67         };
68
69         Context & context;
70
71         ///////////////////////////////////////////////////////////////////////////
72         // Configuration
73
74         bool incremental;
75
76         ///////////////////////////////////////////////////////////////////////////
77         // Dispatching semantic actions
78
79         ParseDispatcher & dispatcher;
80
81         ///////////////////////////////////////////////////////////////////////////
82         // Errors
83
84         enum Errors {
85             EndOfStatementExpected,
86             PathExpected,
87             ClosingParenExpected,
88             QuoteExpected
89         };
90
91         ///////////////////////////////////////////////////////////////////////////
92
93         CommandGrammar(ParseDispatcher & d, Context & c) 
94             : context(c), incremental(false), dispatcher(d) {}
95
96         template <class Scanner>
97         struct definition 
98             : public boost::spirit::grammar_def< boost::spirit::rule<Scanner>, 
99                                                  boost::spirit::rule<Scanner>,
100                                                  boost::spirit::rule<Scanner>,
101                                                  boost::spirit::rule<Scanner> >
102         {
103             boost::spirit::rule<Scanner> command, path, argument, word, string, hexstring, token,
104                 punctuation, hexbyte, balanced_tokens, simple_argument, complex_argument, builtin, 
105                 skip, statement, relpath, abspath, arguments, group_start, group_close, 
106                 statement_end, opt_path;
107             boost::spirit::chset<> special_p, punctuation_p, space_p, invalid_p, word_p;
108             boost::spirit::distinct_parser<> keyword_p;
109
110             definition(CommandGrammar const & self) : 
111
112                 // Characters with a special meaning within the parser
113                 special_p ("/(){};\""),
114
115                 // Additional characters which are returned as punctuation tokens
116                 // (only allowed within '()').
117                 punctuation_p (",="),
118
119                 // Whitespace characters
120                 space_p (" \t\n\r"),
121
122                 // Invalid characters: All chars below \x20 (space) which are not space_p
123                 // (don't put a \0 in the chset<> argument *string* ...)
124                 invalid_p ( (boost::spirit::chset<>('\0') 
125                              | boost::spirit::chset<>("\x01-\x20")) - space_p ),
126
127                 // Valid word characters
128                 word_p (
129                     boost::spirit::anychar_p - special_p - punctuation_p - space_p - invalid_p),
130
131                 // Keywords must not be followed by a word char or '/'
132                 keyword_p ( word_p | boost::spirit::ch_p('/') )
133
134             {
135                 using namespace boost::spirit;
136                 using namespace ::phoenix;
137                 using namespace senf::phoenix;
138                 typedef ParseDispatcher PD;
139
140                 actor< variable< char > >               ch_    (self.context.ch);
141                 actor< variable< std::string > >        str_   (self.context.str);
142                 actor< variable< std::vector<Token> > > path_  (self.context.path);
143                 actor< variable< Token > >              token_ (self.context.token);
144                 actor< variable< ParseDispatcher > >    d_     (self.dispatcher);
145
146                 assertion<Errors> end_of_statement_expected   (EndOfStatementExpected);
147                 assertion<Errors> path_expected               (PathExpected);
148                 assertion<Errors> closing_paren_expected      (ClosingParenExpected);
149                 assertion<Errors> quote_expected              (QuoteExpected);
150
151                 ///////////////////////////////////////////////////////////////////
152                 // Spirit grammar
153                 //
154                 // Syntax summary:
155                 // This is EBNF with some minor tweaks to accommodate C++ syntax
156                 //
157                 //   * a        any number of a's
158                 //   + a        at least one a
159                 //   ! a        an optional a
160                 //   a >> b     a followed by b
161                 //   a | b      a or b
162                 //   a % b      any number of a's separated by b's
163                 //   a - b      a but not b
164                 //
165                 // Beside this, we use some special parsers (ch_p, eps_p, confix_p, lex_escape_ch_p,
166                 // keyword_p, comment_p) and directives (lexeme_d), however, the parser should be
167                 // quite readable.
168                 //   
169                 //   ch_p             match character
170                 //   eps_p            always matches nothing (to attach unconditional actions)
171                 //   confix_p(a,b,c)  match b, preceded by a and terminated by c. Used to parse
172                 //                    string literals and comments
173                 //   lex_escape_ch_p  match a lex style escape char. This is like a C++ style
174                 //                    literal string escape char, however \x will be replaced by 'x'
175                 //                    for any char 'x' if it has no special meaning.
176                 //   keyword_p        match a delimited keyword
177                 //   comment_p(a,b)   match comment starting with a and terminated with b. b
178                 //                    defaults to end-of-line
179                 //
180                 //   lexeme_d         don't skip whitespace (as defined by the skip parser)
181                 //
182                 // Aligned to the right at column 50 are semantic actions.
183                 //
184                 // For clarity, I have used 'ch_p' explicitly throughout even though it is optional
185                 // in most cases.
186                 //
187                 // More info is in the Boost.Spirit documentation
188
189                 command 
190                     =    builtin >> end_of_statement_expected(statement_end)
191                     |    group_close
192                     |    ch_p(';') // Ignore empty commands
193                     |    statement
194                     ;
195
196                 statement
197                     =    path_expected(path)      [ bind(&PD::beginCommand)(d_, path_) ]
198                       >> arguments
199                       >> end_of_statement_expected( 
200                            ( group_start | statement_end )
201                                                   [ bind(&PD::endCommand)(d_) ]
202                          )
203                     ;
204
205                 builtin
206                     =    keyword_p("cd") 
207                       >> path_expected(path)
208                       >> eps_p                    [ bind(&PD::builtin_cd)(d_, path_) ]
209                     |    keyword_p("ls")
210                       >> ! path
211                       >> eps_p                    [ bind(&PD::builtin_ls)(d_, path_) ]
212                     |    keyword_p("exit")        [ bind(&PD::builtin_exit)(d_) ]
213                     |    keyword_p("help")
214                       >> ! path
215                       >> eps_p                    [ bind(&PD::builtin_help)(d_, path_) ]
216                     ;
217
218                 group_start
219                     =    ch_p('{')                [ bind(&PD::pushDirectory)(d_) ]
220                     ;
221
222                 group_close
223                     =    ch_p('}')                [ bind(&PD::popDirectory)(d_) ]
224                     ;
225
226                 arguments
227                     =    * argument
228                     ;
229
230                 argument
231                     =    simple_argument          [ bind(&PD::pushToken)(d_, token_) ]
232                     |    balanced_tokens
233                     ;
234                 
235                 simple_argument         // All these return their value in context.token
236                     =    string
237                     |    hexstring
238                     |    word
239                     ;
240                 
241                 string                  // Returns value in context.token
242                     =    eps_p                    [ clear(str_) ]
243                       >> lexeme_d
244                          [
245                              ch_p('"')
246                           >> * ( ( lex_escape_ch_p[ ch_ = arg1 ] 
247                                    - '"' 
248                                  )                [ str_ += ch_ ]
249                                )
250                           >> quote_expected(ch_p('"'))
251                                                   [ token_ = construct_<Token>(Token::BasicString, 
252                                                                                str_) ]
253                          ]
254                     ;
255
256                 hexstring               // Returns value in context.token
257                     =    eps_p                    [ clear(str_) ]
258                       >>  "x\""
259                       >> * ( hexbyte - ch_p('"') )
260                       >> quote_expected(ch_p('"'))
261                                                   [ token_ = construct_<Token>(Token::HexString,
262                                                                                str_) ]
263                     ;
264                 
265                 opt_path
266                     = ! path                      [ bind(&PD::beginCommand)(d_, path_) ]
267                                                   [ bind(&PD::endCommand)(d_) ]
268                     ;
269
270                 path                    // Returns value in context.path
271                     =    eps_p                    [ clear(path_) ]
272                       >> relpath | abspath
273                     ;
274
275                 relpath
276                     =    (   word                 [ push_back(path_, token_) ]
277                            % ch_p('/') )
278                       >> ( ! ch_p('/')            [ push_back(path_, construct_<Token>()) ] )
279                     ;
280
281                 abspath
282                     =    ch_p('/')                [ push_back(path_, construct_<Token>()) ]
283                       >> ( relpath
284                          | eps_p                  [ push_back(path_, construct_<Token>()) ] )
285                     ;
286
287                 balanced_tokens 
288                     =    ch_p('(')                [ token_ = construct_<Token>(
289                                                         Token::ArgumentGroupOpen,
290                                                         "(") ]
291                                                   [ bind(&PD::pushToken)(d_, token_) ]
292                       >> * token
293                       >> closing_paren_expected(ch_p(')'))
294                                                   [ token_ = construct_<Token>(
295                                                         Token::ArgumentGroupClose,
296                                                         ")") ]
297                                                   [ bind(&PD::pushToken)(d_, token_) ]
298                     ;
299
300                 token
301                     =    simple_argument          [ bind(&PD::pushToken)(d_, token_) ]
302                     |    punctuation              [ bind(&PD::pushToken)(d_, token_) ]
303                     |    balanced_tokens
304                     ;
305
306                 punctuation             // Returns value in context.str
307                     =    ch_p('/')                [ token_ = construct_<Token>(
308                                                         Token::PathSeparator,
309                                                         "/") ]
310                     |    ch_p('{')                [ token_ = construct_<Token>(
311                                                         Token::DirectoryGroupOpen,
312                                                         "{") ]
313                     |    ch_p('}')                [ token_ = construct_<Token>(
314                                                         Token::DirectoryGroupClose,
315                                                         "}") ]
316                     |    ch_p(';')                [ token_ = construct_<Token>(
317                                                         Token::CommandTerminator,
318                                                         ";") ]
319                     |    punctuation_p            [ token_ = construct_<Token>(
320                                                         Token::OtherPunctuation,
321                                                         construct_<std::string>(1u, arg1)) ]
322                     ;
323
324                 word                    // Returns value in context.token
325                     =    lexeme_d
326                          [
327                              (+ word_p)           [ str_ = construct_<std::string>(arg1, arg2) ]
328                          ]
329                       >> eps_p                    [ token_ = construct_<Token>(
330                                                         Token::Word, 
331                                                         str_) ]
332                     ;
333
334                 hexbyte
335                     =    uint_parser<char, 16, 2, 2>()
336                                                   [ push_back(str_, arg1) ]
337                     ;
338
339                 statement_end
340                     =    if_p(var(self.incremental)) [
341                                ch_p(';')
342                          ]
343                          .else_p [
344                                ch_p(';') 
345                              | end_p
346                          ]
347                     ;
348
349                 skip
350                     =    space_p | comment_p('#')
351                     ;
352
353                 ///////////////////////////////////////////////////////////////////
354
355                 start_parsers(
356                     command,            // CommandParser
357                     skip,               // SkipParser
358                     arguments,          // ArgumentsParser
359                     opt_path            // PathParser
360                 );
361
362                 BOOST_SPIRIT_DEBUG_TRACE_RULE(command,1);
363                 BOOST_SPIRIT_DEBUG_TRACE_RULE(path,1);
364                 BOOST_SPIRIT_DEBUG_TRACE_RULE(argument,1);
365                 BOOST_SPIRIT_DEBUG_TRACE_RULE(word,1);
366                 BOOST_SPIRIT_DEBUG_TRACE_RULE(string,1);
367                 BOOST_SPIRIT_DEBUG_TRACE_RULE(hexstring,1);
368                 BOOST_SPIRIT_DEBUG_TRACE_RULE(token,1);
369                 BOOST_SPIRIT_DEBUG_TRACE_RULE(punctuation,1);
370                 BOOST_SPIRIT_DEBUG_TRACE_RULE(hexbyte,1);
371                 BOOST_SPIRIT_DEBUG_TRACE_RULE(balanced_tokens,1);
372                 BOOST_SPIRIT_DEBUG_TRACE_RULE(simple_argument,1);
373                 BOOST_SPIRIT_DEBUG_TRACE_RULE(complex_argument,1);
374                 BOOST_SPIRIT_DEBUG_TRACE_RULE(builtin,1);
375                 BOOST_SPIRIT_DEBUG_TRACE_RULE(commands,1);
376                 BOOST_SPIRIT_DEBUG_TRACE_RULE(block,1);
377                 BOOST_SPIRIT_DEBUG_TRACE_RULE(statement,1);
378                 BOOST_SPIRIT_DEBUG_TRACE_RULE(relpath,1);
379                 BOOST_SPIRIT_DEBUG_TRACE_RULE(abspath,1);
380             }
381         };
382     };
383
384 #endif
385
386 }}}
387
388 ///////////////////////////////ih.e////////////////////////////////////////
389 #endif
390
391 \f
392 // Local Variables:
393 // mode: c++
394 // fill-column: 100
395 // comment-column: 40
396 // c-file-style: "senf"
397 // indent-tabs-mode: nil
398 // ispell-local-dictionary: "american"
399 // compile-command: "scons -u test"
400 // End: