1 /** @file transform.cc
2 * @brief Implement OmegaScript $transform function.
3 */
4 /* Copyright (C) 2003,2009 Olly Betts
5 *
6 * This program 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
21 #include <config.h>
22
23 #include "transform.h"
24
25 #include <pcre.h>
26
27 #include <string>
28 #include <vector>
29
30 using namespace std;
31
32 void
omegascript_transform(string & value,const vector<string> & args)33 omegascript_transform(string & value, const vector<string> & args)
34 {
35 const char *error;
36 int erroffset;
37 int offsets[30];
38 pcre * re = pcre_compile(args[0].c_str(), 0, &error, &erroffset, NULL);
39 int matches = pcre_exec(re, NULL, args[2].data(), args[2].size(),
40 0, 0, offsets, 30);
41 if (matches <= 0) {
42 // Error. FIXME: should we report this rather than ignoring it?
43 value = args[2];
44 return;
45 }
46
47 // Substitute \1 ... \9, and \\.
48 string::const_iterator i;
49 value.assign(args[2], 0, offsets[0]);
50 for (i = args[1].begin(); i != args[1].end(); ++i) {
51 char ch = *i;
52 if (ch != '\\') {
53 value += ch;
54 continue;
55 }
56
57 if (rare(++i == args[1].end())) {
58 // Trailing single '\'.
59 value += ch;
60 break;
61 }
62
63 int c = *i;
64 if (c >= '1' && c <= '9') {
65 c -= '0';
66 // If there aren't that many groupings, expand to nothing.
67 if (c >= matches) continue;
68 } else {
69 value += ch;
70 if (c != '\\') value += char(c);
71 continue;
72 }
73
74 int off_c = offsets[c * 2];
75 value.append(args[2], off_c, offsets[c * 2 + 1] - off_c);
76 }
77 value.append(args[2], offsets[1], string::npos);
78 }
79