Debian Codegraph @

src/parse.cc

raw
1 /*
2 * This file is part of MUSIC.
3 * Copyright (C) 2007, 2008, 2009 INCF
4 *
5 * MUSIC is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * MUSIC is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include "music/parse.hh"
20
21 #include <sstream>
22 #include <vector>
23 #include <cstdio>
24
25 namespace MUSIC {
26
27 Parser::Parser (std::string s)
28 : in (new std::istringstream (s))
29 {
30
31 }
32 Parser::~Parser ()
33 {
34 delete in;
35 }
36
37 void
38 Parser::ignoreWhitespace ()
39 {
40 while (isspace (in->peek ()))
41 in->ignore ();
42 }
43
44
45 void
46 Parser::parseString (std::ostringstream& arg, char delim)
47 {
48 while (true)
49 {
50 int c;
51 switch (c = in->get ())
52 {
53 case '\'':
54 case '"':
55 if (c == delim)
56 break;
57 default:
58 arg << (char) c;
59 continue;
60 case '\\':
61 arg << (char) in->get ();
62 continue;
63 case EOF:
64 // NOTE: generate error message
65 break;
66 }
67 break;
68 }
69 }
70
71
72 std::string
73 Parser::nextArg ()
74 {
75 std::ostringstream arg;
76 while (true)
77 {
78 int c;
79 switch (c = in->get ())
80 {
81 default:
82 arg << (char) c;
83 continue;
84 case '\\':
85 arg << (char) in->get ();
86 continue;
87 case '\'':
88 case '"':
89 parseString (arg, c);
90 continue;
91 case ' ':
92 case '\t':
93 case EOF:
94 break;
95 }
96 break;
97 }
98 return arg.str ();
99 }
100
101
102 char **
103 parseArgs (std::string cmd,
104 std::string argstring,
105 int* argc)
106 {
107 Parser in (argstring);
108 std::vector<std::string> args;
109 args.push_back (cmd);
110 in.ignoreWhitespace ();
111
112 while (! in.eof ())
113 args.push_back (in.nextArg ());
114
115 int nArgs = args.size ();
116 char** result = new char*[nArgs + 1];
117 for (int i = 0; i < nArgs; ++i)
118 {
119 int len = args[i].length ();
120 result[i] = new char[len + 1];
121 args[i].copy (result[i], len);
122 result[i][len] = '\0';
123 }
124 result[nArgs] = 0;
125 *argc = nArgs;
126 return result;
127 }
128
129 }