Debian Codegraph @

libhylafax/DialRules.c++

raw
1 /* $Id$ */
2 /*
3 * Copyright (c) 1993-1996 Sam Leffler
4 * Copyright (c) 1993-1996 Silicon Graphics, Inc.
5 * HylaFAX is a trademark of Silicon Graphics
6 *
7 * Permission to use, copy, modify, distribute, and sell this software and
8 * its documentation for any purpose is hereby granted without fee, provided
9 * that (i) the above copyright notices and this permission notice appear in
10 * all copies of the software and related documentation, and (ii) the names of
11 * Sam Leffler and Silicon Graphics may not be used in any advertising or
12 * publicity relating to the software without the specific, prior written
13 * permission of Sam Leffler and Silicon Graphics.
14 *
15 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
17 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
18 *
19 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
20 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
21 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
22 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
23 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
24 * OF THIS SOFTWARE.
25 */
26
27 /*
28 * HylaFAX Dialing String Rule Support.
29 */
30 #include "DialRules.h"
31 #include "REArray.h"
32 #include "Dictionary.h"
33
34 #include <ctype.h>
35
36 #include "NLS.h"
37
38 /*
39 * Interpolation points in replacement strings have
40 * the META bit or'd together with their match identifier.
41 * That is ``\1'' is META|1, ``\2'' is META|2, etc.
42 * The ``&'' interpolation is treated as ``\0''.
43 */
44 const u_int META = 0200; // interpolation marker
45
46 struct DialRule {
47 REPtr pat; // pattern to match
48 fxStr replace; // replacement string
49
50 DialRule();
51 ~DialRule();
52
53 int compare(const DialRule *) const;
54 };
55 DialRule::DialRule(){}
56 DialRule::~DialRule(){}
57 int DialRule::compare(const DialRule*) const { return 0; }
58
59 fxDECLARE_ObjArray(RuleArray, DialRule)
60 fxIMPLEMENT_ObjArray(RuleArray, DialRule)
61 fxDECLARE_StrKeyDictionary(VarDict, fxStr)
62 fxIMPLEMENT_StrKeyObjValueDictionary(VarDict, fxStr)
63 fxDECLARE_StrKeyDictionary(RulesDict, RuleArrayPtr)
64 fxIMPLEMENT_StrKeyObjValueDictionary(RulesDict, RuleArrayPtr)
65
66 DialStringRules::DialStringRules(const char* file) : filename(file)
67 {
68 verbose = false;
69 fp = NULL;
70 vars = new VarDict;
71 regex = new REArray;
72 rules = new RulesDict;
73 }
74
75 DialStringRules::~DialStringRules()
76 {
77 delete rules;
78 delete regex;
79 delete vars;
80 }
81
82 void DialStringRules::setVerbose(bool b) { verbose = b; }
83
84 /*
85 * Parse the dialing string rules file
86 * to create the in-memory rules.
87 */
88 bool
89 DialStringRules::parse(bool shouldExist)
90 {
91 bool ok = false;
92 lineno = 0;
93 fp = fopen(filename, "r");
94 if (fp) {
95 ok = parseRules();
96 fclose(fp);
97 } else if (shouldExist)
98 parseError(NLS::TEXT("Cannot open file \"%s\" for reading"),
99 (const char*) filename);
100 return (ok);
101 }
102
103 void
104 DialStringRules::def(const fxStr& var, const fxStr& value)
105 {
106 if (verbose)
107 // translator: Screen output about a variable %s being defined to "%s"
108 traceParse(NLS::TEXT("Define %s = \"%s\""),
109 (const char*) var, (const char*) value);
110 (*vars)[var] = value;
111 }
112
113 void
114 DialStringRules::undef(const fxStr& var)
115 {
116 if (verbose)
117 // translator: Screen output about undefining variable %s
118 traceParse(NLS::TEXT("Undefine %s"), (const char*) var);
119 vars->remove(var);
120 }
121
122 bool
123 DialStringRules::parseRules()
124 {
125 char line[1024];
126 char* cp;
127 while ((cp = nextLine(line, sizeof (line)))) {
128 // collect token
129 if (!isalpha(*cp)) {
130 parseError(NLS::TEXT("Syntax error, expecting identifier"));
131 return (false);
132 }
133 const char* tp = cp;
134 for (cp++; isalnum(*cp); cp++)
135 ;
136 fxStr var(tp, cp-tp);
137 while (isspace(*cp))
138 cp++;
139 if (*cp == ':' && cp[1] == '=') { // rule set definition
140 for (cp += 2; *cp != '['; cp++)
141 if (*cp == '\0') {
142 parseError(NLS::TEXT("Missing '[' while parsing rule set"));
143 return (false);
144 }
145 if (verbose)
146 traceParse("%s := [", (const char*) var);
147 RuleArray* ra = new RuleArray;
148 if (!parseRuleSet(*ra)) {
149 delete ra;
150 return (false);
151 }
152 (*rules)[var] = ra;
153 if (verbose)
154 traceParse("]");
155 } else if (*cp == '=') { // variable definition
156 fxStr value;
157 if (parseToken(cp+1, value) == NULL)
158 return (false);
159 def(var, value);
160 } else { // an error
161 parseError(NLS::TEXT("Missing '=' or ':=' after \"%s\""), (const char*) var);
162 return (false);
163 }
164 }
165 if (verbose) {
166 RuleArray* ra = (*rules)["CanonicalNumber"];
167 if (ra == 0)
168 // translator: "CanonicalNumber" is the name of a rule and must not be translated.
169 traceParse(NLS::TEXT("Warning, no \"CanonicalNumber\" rules."));
170 ra = (*rules)["DialString"];
171 if (ra == 0)
172 // translator: "DialString" is the name of a rule and must not be translated.
173 traceParse(NLS::TEXT("Warning, no \"DialString\" rules."));
174 }
175 return (true);
176 }
177
178 /*
179 * Locate the next non-blank line in the file
180 * and return a pointer to the first non-whitespace
181 * character on the line. Leading white space and
182 * comments are stripped. NULL is returned on EOF.
183 */
184 char*
185 DialStringRules::nextLine(char* line, int lineSize)
186 {
187 char* cp;
188 do {
189 if (!fgets(line, lineSize, fp))
190 return (NULL);
191 lineno++;
192 for (cp = line; (cp = strchr(cp, '!')); cp++)
193 if (cp == line || cp[-1] != '\\')
194 break;
195 if (cp)
196 *cp = '\0';
197 else if ((cp = strchr(line, '\n')))
198 *cp = '\0';
199 for (cp = line; isspace(*cp); cp++)
200 ;
201 } while (*cp == '\0');
202 return (cp);
203 }
204
205 /*
206 * Parse the next token on the input line and return
207 * the result in the string v. Variable references
208 * are interpolated here, though they might be better
209 * done at a later time.
210 */
211 const char*
212 DialStringRules::parseToken(const char* cp, fxStr& v)
213 {
214 while (isspace(*cp))
215 cp++;
216 const char* tp;
217 if (*cp == '"') { // "..."
218 tp = ++cp;
219 for (;;) {
220 if (*cp == '\0') {
221 parseError(NLS::TEXT("String with unmatched '\"'"));
222 return (NULL);
223 }
224 if (*cp == '\\' && cp[1] == '\0') {
225 parseError(NLS::TEXT("Bad '\\' escape sequence"));
226 return (NULL);
227 }
228 if (*cp == '"' && (cp == tp || cp[-1] != '\\'))
229 break;
230 cp++;
231 }
232 v = fxStr(tp, cp-tp);
233 cp++; // skip trailing ``"''
234 } else { // token terminated by white space
235 for (tp = cp; *cp != '\0'; cp++) {
236 if (*cp == '\\' && cp[1] == '\0') {
237 parseError(NLS::TEXT("Bad '\\' escape sequence"));
238 return (NULL);
239 }
240 if (isspace(*cp) && (cp == tp || cp[-1] != '\\'))
241 break;
242 }
243 v = fxStr(tp, cp-tp);
244 }
245 for (u_int i = 0, n = v.length(); i < n; i++) {
246 if (v[i] == '$' && (i+1<n && v[i+1] == '{')) {
247 /*
248 * Handle variable reference.
249 */
250 u_int l = v.next(i, '}');
251 if (l >= v.length()) {
252 parseError(NLS::TEXT("Missing '}' for variable reference"));
253 return (NULL);
254 }
255 fxStr var = v.cut(i+2,l-(i+2));// variable name
256 v.remove(i, 3); // remove ${}
257 const fxStr& value = (*vars)[var];
258 v.insert(value, i); // insert variable's value
259 n = v.length(); // adjust string length
260 i += value.length()-1; // don't scan substituted string
261 } else if (v[i] == '\\') // pass \<char> escapes unchanged
262 i++;
263 }
264 return cp;
265 }
266
267 /*
268 * Handle \escapes for a token
269 * that appears on the RHS of a rewriting rule.
270 */
271 void
272 DialStringRules::subRHS(fxStr& v)
273 {
274 /*
275 * Replace `&' and \n items with (META|<n>) to mark spots
276 * in the token where matches should be interpolated.
277 */
278 for (u_int i = 0, n = v.length(); i < n; i++) {
279 if (v[i] == '\\') { // process \<char> escapes
280 v.remove(i), n--;
281 if (isdigit(v[i]))
282 v[i] = META | (v[i] - '0');
283 } else if (v[i] == '&')
284 v[i] = META | 0;
285 }
286 }
287
288 /*
289 * Parse a set of rules and construct the array of
290 * rules (regular expressions + replacement strings).
291 */
292 bool
293 DialStringRules::parseRuleSet(RuleArray& rules)
294 {
295 for (;;) {
296 char line[1024];
297 const char* cp = nextLine(line, sizeof (line));
298 if (!cp) {
299 parseError(NLS::TEXT("Missing ']' while parsing rule set"));
300 return (false);
301 }
302 if (*cp == ']')
303 return (true);
304 // new rule
305 fxStr pat;
306 if ((cp = parseToken(cp, pat)) == NULL)
307 return (false);
308 while (isspace(*cp))
309 cp++;
310 if (*cp != '=') {
311 parseError(NLS::TEXT("Rule pattern without '='"));
312 return (false);
313 }
314 DialRule r;
315 if (parseToken(cp+1, r.replace) == NULL)
316 return (false);
317 if (verbose)
318 traceParse(" \"%s\" = \"%s\"",
319 (const char*) pat, (const char*) r.replace);
320 subRHS(r.replace);
321 u_int i = 0;
322 u_int n = regex->length();
323 while (i < n) {
324 RE* re = (*regex)[i];
325 if (strcmp(re->pattern(), pat) == 0)
326 break;
327 i++;
328 }
329 if (i >= n) {
330 r.pat = new RE(pat);
331 if (r.pat->getErrorCode() > REG_NOMATCH) {
332 fxStr emsg;
333 r.pat->getError(emsg);
334 parseError(pat | ": " | emsg);
335 }
336 regex->append(r.pat);
337 } else
338 r.pat = (*regex)[i];
339 rules.append(r);
340 }
341 }
342
343 fxStr
344 DialStringRules::applyRules(const fxStr& name, const fxStr& s)
345 {
346 if (verbose)
347 traceRules(NLS::TEXT("Apply %s rules to \"%s\""),
348 (const char*) name, (const char*) s);
349 fxStr result(s);
350 RuleArray* ra = (*rules)[name];
351 if (ra) {
352 for (u_int i = 0, n = (*ra).length(); i < n; i++) {
353 DialRule& rule = (*ra)[i];
354 u_int off = 0;
355 while (rule.pat->Find(result, off)) {
356 /*
357 * Regular expression match.
358 */
359 int ix = rule.pat->StartOfMatch();
360 int len = rule.pat->EndOfMatch() - ix;
361 if (len == 0) // avoid looping on zero-length matches
362 break;
363 /*
364 * Do ``&'' and ``\n'' interpolations in the
365 * replacement. NB: & is treated as \0.
366 */
367 fxStr replace(rule.replace);
368 for (u_int ri = 0, rlen = replace.length(); ri < rlen; ri++)
369 if (replace[ri] & META) {
370 u_char mn = replace[ri] &~ META;
371 int ms = rule.pat->StartOfMatch(mn);
372 int mlen = rule.pat->EndOfMatch(mn) - ms;
373 replace.remove(ri); // delete & or \n
374 replace.insert(result.extract(ms, mlen), ri);
375 rlen = replace.length();// adjust string length ...
376 ri += mlen - 1; // ... and scan index
377 }
378 /*
379 * Paste interpolated replacement string over match.
380 */
381 result.remove(ix, len);
382 result.insert(replace, ix);
383 off = ix + replace.length(); // skip replace when searching
384 if (verbose)
385 traceRules(NLS::TEXT("--> match rule \"%s\", result now \"%s\""),
386 rule.pat->pattern(), (const char*) result);
387 }
388 }
389 }
390 if (verbose)
391 traceRules(NLS::TEXT("--> return result \"%s\""), (const char*) result);
392 return result;
393 }
394
395 #include <stdarg.h>
396
397 void
398 DialStringRules::parseError(const char* fmt ...)
399 {
400 va_list ap;
401 va_start(ap, fmt);
402 // translator: "line" as in the line number %u of filename %s.
403 fprintf(stderr, NLS::TEXT("%s: line %u: "), (const char*) filename, lineno);
404 vfprintf(stderr, fmt, ap);
405 va_end(ap);
406 putc('\n', stderr);
407 }
408
409 void
410 DialStringRules::traceParse(const char* fmt ...)
411 {
412 va_list ap;
413 va_start(ap, fmt);
414 // translator: "line" as in the line number %u of filename %s.
415 fprintf(stdout, NLS::TEXT("%s: line %u: "), (const char*) filename, lineno);
416 vfprintf(stdout, fmt, ap);
417 va_end(ap);
418 putc('\n', stdout);
419 }
420
421 void
422 DialStringRules::traceRules(const char* fmt ...)
423 {
424 va_list ap;
425 va_start(ap, fmt);
426 vfprintf(stdout, fmt, ap);
427 va_end(ap);
428 putc('\n', stdout);
429 }
430
431 /*
432 * Apply the canonical number rule set to a string.
433 */
434 fxStr DialStringRules::canonicalNumber(const fxStr& s)
435 { return applyRules("CanonicalNumber", s); }
436 /*
437 * Apply the dial string rule set to a string.
438 */
439 fxStr DialStringRules::dialString(const fxStr& s)
440 { return applyRules("DialString", s); }
441 /*
442 * Apply the display number rule set to a string.
443 */
444 fxStr DialStringRules::displayNumber(const fxStr& s)
445 { return applyRules("DisplayNumber", s); }