Refactor BeRTOS to be in his own directory.
[bertos.git] / bertos / mware / parser.c
1 /**
2  * \file
3  * <!--
4  * This file is part of BeRTOS.
5  *
6  * Bertos is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * As a special exception, you may use this file as part of a free software
21  * library without restriction.  Specifically, if other files instantiate
22  * templates or use macros or inline functions from this file, or you compile
23  * this file and link it with other files to produce an executable, this
24  * file does not by itself cause the resulting executable to be covered by
25  * the GNU General Public License.  This exception does not however
26  * invalidate any other reasons why the executable file might be covered by
27  * the GNU General Public License.
28  *
29  * Copyright 2003, 2006 Develer S.r.l. (http://www.develer.com/)
30  * All Rights Reserved.
31  * -->
32  *
33  * \version $Id$
34  *
35  * \author Bernardo Innocenti <bernie@develer.com>
36  * \author Stefano Fedrigo <aleph@develer.com>
37  * \author Giovanni Bajo <rasky@develer.com>
38  *
39  * \brief Serial protocol parser and commands.
40  *
41  * This file contains the serial protocol parser and
42  * the definition of the protocol commands. Commands are defined
43  * in a "CmdTemplate" type array, containing:
44  * - the name of the command,
45  * - the arguments it expects to receive,
46  * - the output values,
47  * - the name of the function implementing the command.
48  *
49  * The arguments and results are passed to command function
50  * using an union: the element of the union to use for each
51  * argument is determined by format strings present in the
52  * CmdTemplate table.
53  */
54
55
56 #include "parser.h"
57 #include <drv/ser.h>
58
59 #include <stdlib.h> // atol(), NULL
60 #include <string.h> // strchr(), strcmp()
61
62 #include <mware/hashtable.h>
63
64 #include "appconfig.h"
65
66 #define ARG_SEP_S " "
67 #define ARG_SEP_C ' '
68
69 #define MAX_COMMANDS_NUMBER  128  // 64
70
71 /// Hashtable hook to extract the key from a command
72 static const void* get_key_from_command(const void* cmd, uint8_t* length);
73
74 /// Hashtable that handles the commands that can be executed
75 DECLARE_HASHTABLE_STATIC(commands, MAX_COMMANDS_NUMBER, get_key_from_command);
76
77
78 /**
79  * \brief Tokenize one word at a time from a text.
80  *
81  * This function is similar to strtok, but does not use any implicit
82  * context, nor it does modify the input buffer in any form.
83  * The word is returned as a STL-like [begin,end) range.
84  *
85  * To extract the first word, make both begin and end point at the
86  * start of the text, and call the function. Then, subsequent
87  * calls will return the following words (assuming the begin/end
88  * variable are not modified between calls).
89  *
90  * \param begin Will contain the index of the first character of the word
91  * \param end Will contain the index of the character after the last
92  *     character of the word
93  *
94  * \return True if a word was extracted, false if we got to the end
95  * of the string without extracting any word.
96  */
97 static bool get_word(const char **begin, const char **end)
98 {
99         const char *cur = *end;
100
101         while ((*cur == ' ' || *cur == '\t') && *cur)
102                 ++cur;
103
104         *begin = cur;
105
106         while ((*cur != ' ' && *cur != '\t') && *cur)
107                 ++cur;
108
109         *end = cur;
110
111         return (*end != *begin);
112 }
113
114
115 /**
116  * \brief Command arguments parser.
117  *
118  * Using the format pointed by the argument fmt
119  * parses the input string filling the array argv
120  * with input parameters of the correct type.
121  *
122  * \param fmt   Parameters format string.
123  * \param input Input string.
124  * \param argv  Array filled with parameters.
125  *
126  * \return False in case of errors, otherwise true.
127  */
128 static bool parseArgs(const char *fmt, const char *input, parms argv[])
129 {
130         const char *begin = input, *end = input;
131
132         while (*fmt)
133         {
134                 // Extract the argument
135                 if (!get_word(&begin, &end))
136                         return false;
137
138                 switch (*fmt)
139                 {
140                         case 'd':
141                                 (*argv++).l = atol(begin);
142                                 break;
143
144                         case 's':
145                                 (*argv++).s = begin;
146                                 break;
147
148                         default:
149                                 ASSERT2(0, "Unknown format for argument");
150                                 return false;
151                 }
152
153                 ++fmt;
154         }
155
156         /* check if there are remaining args */
157         if (get_word(&begin, &end))
158                 return false;
159
160         return true;
161 }
162
163
164 #ifdef UNUSED_CODE
165 /**
166  * \brief Command result formatting and printing.
167  *
168  * Prints out on device fd the values contained
169  * in the array result, using the format specified
170  * in fmt.
171  *
172  * \param ser     Serial handle.
173  * \param fmt     Values format string.
174  * \param result  Array containing result to be printed.
175  *
176  * \return -1 in case of errors, otherwise 0.
177  */
178 static int printResult(struct Serial *ser, const char *fmt, parms result[])
179 {
180         long n;
181         char repeat_cnt = 0;
182
183         while (*fmt)
184         {
185                 if (*fmt >= '0' && *fmt <= '9')
186                 {
187                         /* Collect repeat count digit (left to right order) */
188                         repeat_cnt = (repeat_cnt * 10) + (*fmt - '0');
189                 }
190                 else
191                 {
192                         /* Set default repeat cnt of 1 when not specified */
193                         if (repeat_cnt == 0)
194                                 repeat_cnt = 1;
195
196                         /* Loop repeat_cnt times */
197                         do
198                         {
199                                 switch (*fmt)
200                                 {
201                                         case 'd':
202                                                 ser_printf(ser, ARG_SEP_S "%ld", (*result).l);
203                                                 result++;
204                                                 break;
205                                         case 'c':
206                                                 ser_print(ser, ARG_SEP_S);
207                                                 ser_print(ser, (*result).s);
208                                                 result++;
209                                                 break;
210                                         case 's':
211                                                 ser_printf(ser, ARG_SEP_S "%s", (*result).s);
212                                                 result++;
213                                                 break;
214                                         case 'n':
215                                                 n = (*result++).l;
216                                                 ser_printf(ser, ARG_SEP_S "%ld", n);
217                                                 while (n--) {
218                                                         ser_printf(ser, ARG_SEP_S "%ld", (*result).l);
219                                                         result++;
220                                                 }
221                                                 break;
222                                         default:
223                                                 break;
224                                 }
225                         }
226                         while (--repeat_cnt);
227                 }
228
229                 /* Skip to next format char */
230                 ++fmt;
231
232         } /* while (*fmt) */
233
234
235         ser_print(ser, "\r\n");
236         return 0;
237 }
238 #endif /* UNUSED_CODE */
239
240 /// Hook provided by the parser for matching of command names (TAB completion) for readline
241 const char* parser_rl_match(UNUSED_ARG(void *,dummy), const char *word, int word_len)
242 {
243         HashIterator cur;
244         HashIterator end = ht_iter_end(&commands);
245         const char *found = NULL;
246
247         for (cur = ht_iter_begin(&commands);
248              !ht_iter_cmp(cur, end);
249              cur = ht_iter_next(cur))
250         {
251                 const struct CmdTemplate* cmdp = (const struct CmdTemplate*)ht_iter_get(cur);
252                 if (strncmp(cmdp->name, word, word_len) == 0)
253                 {
254                         // If there was another matching word, it means that we have a multiple
255                         //  match: then return NULL.
256                         if (found)
257                                 return NULL;
258
259                         found = cmdp->name;
260                 }
261         }
262
263         return found;
264 }
265
266 bool parser_get_cmd_id(const char* line, unsigned long* ID)
267 {
268         const char *begin = line, *end = line;
269         char *end2;
270
271         // The first word is the ID
272         if (!get_word(&begin, &end))
273                 return false;
274
275         *ID = strtoul(begin, &end2, 10);
276         if (end2 != end)
277                 return false;
278
279         return true;
280 }
281
282 const struct CmdTemplate* parser_get_cmd_template(const char *input)
283 {
284 //      const struct CmdTemplate *cmdp;
285 //      int cmdlen;
286         const char *begin = input, *end = input;
287
288         // Skip the ID, and get the command
289         if (!get_word(&begin, &end))
290                 return NULL;
291         if (!get_word(&begin, &end))
292                 return NULL;
293
294         return (const struct CmdTemplate*)ht_find(&commands, begin, end-begin);
295 }
296
297 static const char *skip_to_params(const char *input, const struct CmdTemplate *cmdp)
298 {
299         const char *begin = input, *end = input;
300
301         // Skip the ID, and get the command
302         if (!get_word(&begin, &end))
303                 return NULL;
304         if (!get_word(&begin, &end))
305                 return NULL;
306
307         ASSERT2(strlen(cmdp->name) == (size_t)(end-begin), "Invalid command template specified");
308         ASSERT2(!strncmp(begin, cmdp->name, end-begin), "Invalid command template specified");
309
310         return end;
311 }
312
313 bool parser_get_cmd_arguments(const char* input, const struct CmdTemplate* cmdp, parms args[PARSER_MAX_ARGS])
314 {
315         input = skip_to_params(input, cmdp);
316         if (!input)
317                 return false;
318
319         args[0].s = cmdp->name;
320         if (!parseArgs(cmdp->arg_fmt, input, args + 1))
321                 return false;
322
323         return true;
324 }
325
326 static const void* get_key_from_command(const void* cmd, uint8_t* length)
327 {
328         const struct CmdTemplate* c = cmd;
329         *length = strlen(c->name);
330         return c->name;
331 }
332
333 bool parser_process_line(const char* input)
334 {
335         const struct CmdTemplate *cmdp;
336         parms args[PARSER_MAX_ARGS];
337
338         cmdp = parser_get_cmd_template(input);
339         if (!cmdp)
340                 return false;
341
342         if (!parser_get_cmd_arguments(input, cmdp, args))
343                 return false;
344
345         if (!parser_execute_cmd(cmdp, args))
346                 return false;
347
348         return true;
349 }
350
351 void parser_register_cmd(const struct CmdTemplate* cmd)
352 {
353         ht_insert(&commands, cmd);
354 }
355
356 #if CONFIG_INTERNAL_COMMANDS
357 static ResultCode cmd_help(void)
358 {
359 #ifdef _DEBUG
360
361         // FIXME: There is no way at the moment to access the serial port. Dump
362         //  this through JTAG for now
363         for (HashIterator iter = ht_iter_begin(&commands);
364                 !ht_iter_cmp(iter, ht_iter_end(&commands));
365                 iter = ht_iter_next(iter))
366         {
367                 struct CmdTemplate* cmd = (struct CmdTemplate*)ht_iter_get(iter);
368                 kprintf("%-20s", cmd->name);
369                 for (unsigned j = 0; cmd->arg_fmt[j]; ++j)
370                         kprintf("%c ", 'a' + j);
371                 kprintf("\r\n");
372         }
373 #endif
374
375         return RC_OK;
376 }
377
378 #include "cmd_hunk.h"
379 DECLARE_CMD_HUNK(help, (NIL), (NIL));
380
381 #endif // CONFIG_INTERNAL_COMMANDS
382
383
384 void parser_init(void)
385 {
386         // Initialize the hashtable used to store the command description
387         ht_init(&commands);
388
389 #if CONFIG_INTERNAL_COMMANDS
390         parser_register_cmd(&CMD_HUNK_TEMPLATE(help));
391 #endif
392 }