1 const char pcrs_rcs[] = "$Id: pcrs.c,v 1.16 2001/11/30 21:32:14 jongfoster Exp $";
3 /*********************************************************************
5 * File : $Source: /cvsroot/ijbswa/current/pcrs.c,v $
7 * Purpose : pcrs is a supplement to the pcre library by Philip Hazel
8 * <ph10@cam.ac.uk> and adds Perl-style substitution. That
9 * is, it mimics Perl's 's' operator. See pcrs(3) for details.
12 * Copyright : Written and Copyright (C) 2000, 2001 by Andreas S. Oesterhelt
13 * <andreas@oesterhelt.org>
15 * This program is free software; you can redistribute it
16 * and/or modify it under the terms of the GNU Lesser
17 * General Public License (LGPL), version 2.1, which should
18 * be included in this distribution (see LICENSE.txt), with
19 * the exception that the permission to replace that license
20 * with the GNU General Public License (GPL) given in section
21 * 3 is restricted to version 2 of the GPL.
23 * This program is distributed in the hope that it will
24 * be useful, but WITHOUT ANY WARRANTY; without even the
25 * implied warranty of MERCHANTABILITY or FITNESS FOR A
26 * PARTICULAR PURPOSE. See the license for more details.
28 * The GNU Lesser General Public License should be included
29 * with this file. If not, you can view it at
30 * http://www.gnu.org/licenses/lgpl.html
31 * or write to the Free Software Foundation, Inc., 59
32 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
36 * Revision 1.16 2001/11/30 21:32:14 jongfoster
37 * Fixing signed/unsigned comparison (Andreas please check this!)
40 * Revision 1.15 2001/09/20 16:11:06 steudten
42 * Add casting for some string functions.
44 * Revision 1.14 2001/09/09 21:41:57 oes
45 * Fixing yet another silly bug
47 * Revision 1.13 2001/09/06 14:05:59 oes
50 * Revision 1.12 2001/08/18 11:35:00 oes
51 * - Introduced pcrs_strerror()
52 * - made some NULL arguments non-fatal
53 * - added support for \n \r \e \b \t \f \a \0 in substitute
54 * - made quoting adhere to standard rules
55 * - added warning for bad backrefs
56 * - added pcrs_execute_list()
58 * - bugfix & cosmetics
60 * Revision 1.11 2001/08/15 15:32:03 oes
61 * - Added support for Perl's special variables $+, $' and $`
62 * - Improved the substitute parser
63 * - Replaced the hard limit for the maximum number of matches
64 * by dynamic reallocation
66 * Revision 1.10 2001/08/05 13:13:11 jongfoster
67 * Making parameters "const" where possible.
69 * Revision 1.9 2001/07/18 17:27:00 oes
70 * Changed interface; Cosmetics
72 * Revision 1.8 2001/06/29 21:45:41 oes
73 * Indentation, CRLF->LF, Tab-> Space
75 * Revision 1.7 2001/06/29 13:33:04 oes
76 * - Cleaned up, renamed and reordered functions,
79 * - Replaced globalflag with a general flags int
80 * that holds PCRS_GLOBAL, PCRS_SUCCESS, and PCRS_TRIVIAL
81 * - Introduced trivial option that will prevent pcrs
82 * from honouring backreferences in the substitute,
83 * which is useful for large substitutes that are
84 * red in from somewhere and saves the pain of escaping
86 * - Introduced convenience function pcrs_free_joblist()
87 * - Split pcrs_make_job() into pcrs_compile(), which still
88 * takes a complete s/// comand as argument and parses it,
89 * and a new function pcrs_make_job, which takes the
90 * three separate components. This should make for a
91 * much friendlier frontend.
92 * - Removed create_pcrs_job() which was useless
93 * - Fixed a bug in pcrs_execute
94 * - Success flag is now handled by pcrs instead of user
96 * Revision 1.6 2001/06/03 19:12:45 oes
99 * Revision 1.5 2001/05/29 09:50:24 jongfoster
100 * (Fixed one int -> size_t)
102 * Revision 1.4 2001/05/25 14:12:40 oes
103 * Fixed bug: Empty substitutes now detected
105 * Revision 1.3 2001/05/25 11:03:55 oes
106 * Added sanity check for NULL jobs to pcrs_exec_substitution
108 * Revision 1.2 2001/05/22 18:46:04 oes
110 * Added support for PCRE_UNGREEDY behaviour to pcrs,
111 * which is selected by the (nonstandard and therefore
112 * capital) letter 'U' in the option string.
113 * It causes the quantifiers to be ungreedy by default.
114 * Appending a ? turns back to greedy (!).
116 * Revision 1.1.1.1 2001/05/15 13:59:02 oes
117 * Initial import of version 2.9.3 source tree
120 *********************************************************************/
129 const char pcrs_h_rcs[] = PCRS_H_VERSION;
132 * Internal prototypes
135 static int pcrs_parse_perl_options(const char *optstring, int *flags);
136 static pcrs_substitute *pcrs_compile_replacement(const char *replacement, int trivialflag,
137 int capturecount, int *errptr);
139 /*********************************************************************
141 * Function : pcrs_strerror
143 * Description : Return a string describing a given error code.
146 * 1 : error = the error code
148 * Returns : char * to the descriptive string
150 *********************************************************************/
151 const char *pcrs_strerror(const int error)
157 /* Passed-through PCRE error: */
158 case PCRE_ERROR_NOMEMORY: return "(pcre:) No memory";
160 /* Shouldn't happen unless PCRE or PCRS bug, or user messed with compiled job: */
161 case PCRE_ERROR_NULL: return "(pcre:) NULL code or subject or ovector";
162 case PCRE_ERROR_BADOPTION: return "(pcre:) Unrecognized option bit";
163 case PCRE_ERROR_BADMAGIC: return "(pcre:) Bad magic number in code";
164 case PCRE_ERROR_UNKNOWN_NODE: return "(pcre:) Bad node in pattern";
166 /* Can't happen / not passed: */
167 case PCRE_ERROR_NOSUBSTRING: return "(pcre:) Fire in power supply";
168 case PCRE_ERROR_NOMATCH: return "(pcre:) Water in power supply";
171 case PCRS_ERR_NOMEM: return "(pcrs:) No memory";
172 case PCRS_ERR_CMDSYNTAX: return "(pcrs:) Syntax error while parsing command";
173 case PCRS_ERR_STUDY: return "(pcrs:) PCRE error while studying the pattern";
174 case PCRS_ERR_BADJOB: return "(pcrs:) Bad job - NULL job, pattern or substitute";
175 case PCRS_WARN_BADREF: return "(pcrs:) Backreference out of range";
178 default: return "Unknown error";
181 /* error >= 0: No error */
182 return "(pcrs:) Everything's just fine. Thanks for asking.";
187 /*********************************************************************
189 * Function : pcrs_parse_perl_options
191 * Description : This function parses a string containing the options to
192 * Perl's s/// operator. It returns an integer that is the
193 * pcre equivalent of the symbolic optstring.
194 * Since pcre doesn't know about Perl's 'g' (global) or pcrs',
195 * 'T' (trivial) options but pcrs needs them, the corresponding
196 * flags are set if 'g'or 'T' is encountered.
197 * Note: The 'T' and 'U' options do not conform to Perl.
200 * 1 : optstring = string with options in perl syntax
201 * 2 : flags = see description
203 * Returns : option integer suitable for pcre
205 *********************************************************************/
206 static int pcrs_parse_perl_options(const char *optstring, int *flags)
212 if (NULL == optstring) return 0;
214 for (i=0; i < strlen(optstring); i++)
218 case 'e': break; /* ToDo ;-) */
219 case 'g': *flags |= PCRS_GLOBAL; break;
220 case 'i': rc |= PCRE_CASELESS; break;
221 case 'm': rc |= PCRE_MULTILINE; break;
223 case 's': rc |= PCRE_DOTALL; break;
224 case 'x': rc |= PCRE_EXTENDED; break;
225 case 'U': rc |= PCRE_UNGREEDY; break;
226 case 'T': *flags |= PCRS_TRIVIAL; break;
235 /*********************************************************************
237 * Function : pcrs_compile_replacement
239 * Description : This function takes a Perl-style replacement (2nd argument
240 * to the s/// operator and returns a compiled pcrs_substitute,
241 * or NULL if memory allocation for the substitute structure
245 * 1 : replacement = replacement part of s/// operator
247 * 2 : trivialflag = Flag that causes backreferences to be
249 * 3 : capturecount = Number of capturing subpatterns in
250 * the pattern. Needed for $+ handling.
251 * 4 : errptr = pointer to an integer in which error
252 * conditions can be returned.
254 * Returns : pcrs_substitute data structure, or NULL if an
255 * error is encountered. In that case, *errptr has
258 *********************************************************************/
259 static pcrs_substitute *pcrs_compile_replacement(const char *replacement, int trivialflag, int capturecount, int *errptr)
261 int length, i, k, l, quoted;
265 i = k = l = quoted = 0;
270 if (NULL == replacement)
278 if (NULL == (r = (pcrs_substitute *)malloc(sizeof(pcrs_substitute))))
280 *errptr = PCRS_ERR_NOMEM;
283 memset(r, '\0', sizeof(pcrs_substitute));
285 length = strlen(replacement);
287 if (NULL == (text = (char *)malloc(length + 1)))
290 *errptr = PCRS_ERR_NOMEM;
293 memset(text, '\0', length + 1);
297 * In trivial mode, just copy the substitute text
301 text = strncpy(text, replacement, length + 1);
306 * Else, parse, cut out and record all backreferences
313 if (replacement[i] == '\\')
317 text[k++] = replacement[i++];
322 if (replacement[i+1] && strchr("tnrfae0", replacement[i+1]))
324 switch(replacement[++i])
360 if (replacement[i] == '$' && !quoted && i < length - 1)
362 char *symbol, symbols[] = "'`+&";
363 r->block_length[l] = k - r->block_offset[l];
365 /* Numerical backreferences */
366 if (isdigit((int) replacement[i + 1]))
368 while (i < length && isdigit((int) replacement[++i]))
370 r->backref[l] = r->backref[l] * 10 + replacement[i] - 48;
372 if (r->backref[l] > capturecount)
374 *errptr = PCRS_WARN_BADREF;
378 /* Symbolic backreferences: */
379 else if (NULL != (symbol = strchr(symbols, replacement[i + 1])))
382 if (symbol - symbols == 2) /* $+ */
384 r->backref[l] = capturecount;
386 else if (symbol - symbols == 3) /* $& */
392 r->backref[l] = PCRS_MAX_SUBMATCHES + 1 - (symbol - symbols);
397 /* Invalid backref -> plain '$' */
403 /* Valid and in range? -> record */
404 if (r->backref[l] < PCRS_MAX_SUBMATCHES + 2)
406 r->backref_count[r->backref[l]] += 1;
407 r->block_offset[++l] = k;
411 *errptr = PCRS_WARN_BADREF;
417 /* Plain chars are copied */
418 text[k++] = replacement[i++];
421 } /* -END- if (!trivialflag) */
428 r->block_length[l] = k - r->block_offset[l];
435 /*********************************************************************
437 * Function : pcrs_free_job
439 * Description : Frees the memory used by a pcrs_job struct and its
440 * dependant structures.
443 * 1 : job = pointer to the pcrs_job structure to be freed
445 * Returns : a pointer to the next job, if there was any, or
448 *********************************************************************/
449 pcrs_job *pcrs_free_job(pcrs_job *job)
460 if (job->pattern != NULL) free(job->pattern);
461 if (job->hints != NULL) free(job->hints);
462 if (job->substitute != NULL)
464 if (job->substitute->text != NULL) free(job->substitute->text);
465 free(job->substitute);
474 /*********************************************************************
476 * Function : pcrs_free_joblist
478 * Description : Iterates through a chained list of pcrs_job's and
479 * frees them using pcrs_free_job.
482 * 1 : joblist = pointer to the first pcrs_job structure to
487 *********************************************************************/
488 void pcrs_free_joblist(pcrs_job *joblist)
490 while ( NULL != (joblist = pcrs_free_job(joblist)) ) {};
497 /*********************************************************************
499 * Function : pcrs_compile_command
501 * Description : Parses a string with a Perl-style s/// command,
502 * calls pcrs_compile, and returns a corresponding
503 * pcrs_job, or NULL if parsing or compiling the job
507 * 1 : command = string with perl-style s/// command
508 * 2 : errptr = pointer to an integer in which error
509 * conditions can be returned.
511 * Returns : a corresponding pcrs_job data structure, or NULL
512 * if an error was encountered. In that case, *errptr
515 *********************************************************************/
516 pcrs_job *pcrs_compile_command(const char *command, int *errptr)
518 int i, k, l, limit, quoted = FALSE;
526 * Tokenize the perl command
528 limit = strlen(command);
531 *errptr = PCRS_ERR_CMDSYNTAX;
536 delimiter = command[1];
539 tokens[l] = (char *) malloc(limit + 1);
541 for (i=0; i <= limit; i++)
544 if (command[i] == delimiter && !quoted)
551 tokens[0][k++] = '\0';
552 tokens[++l] = tokens[0] + k;
556 else if (command[i] == '\\' && !quoted)
559 if (command[i+1] == delimiter) continue;
565 tokens[0][k++] = command[i];
573 *errptr = PCRS_ERR_CMDSYNTAX;
578 newjob = pcrs_compile(tokens[1], tokens[2], tokens[3], errptr);
585 /*********************************************************************
587 * Function : pcrs_compile
589 * Description : Takes the three arguments to a perl s/// command
590 * and compiles a pcrs_job structure from them.
593 * 1 : pattern = string with perl-style pattern
594 * 2 : substitute = string with perl-style substitute
595 * 3 : options = string with perl-style options
596 * 4 : errptr = pointer to an integer in which error
597 * conditions can be returned.
599 * Returns : a corresponding pcrs_job data structure, or NULL
600 * if an error was encountered. In that case, *errptr
603 *********************************************************************/
604 pcrs_job *pcrs_compile(const char *pattern, const char *substitute, const char *options, int *errptr)
614 * Handle NULL arguments
616 if (pattern == NULL) pattern = "";
617 if (substitute == NULL) substitute = "";
621 * Get and init memory
623 if (NULL == (newjob = (pcrs_job *)malloc(sizeof(pcrs_job))))
625 *errptr = PCRS_ERR_NOMEM;
628 memset(newjob, '\0', sizeof(pcrs_job));
632 * Evaluate the options
634 newjob->options = pcrs_parse_perl_options(options, &flags);
635 newjob->flags = flags;
639 * Compile the pattern
641 newjob->pattern = pcre_compile(pattern, newjob->options, &error, errptr, NULL);
642 if (newjob->pattern == NULL)
644 pcrs_free_job(newjob);
650 * Generate hints. This has little overhead, since the
651 * hints will be NULL for a boring pattern anyway.
653 newjob->hints = pcre_study(newjob->pattern, 0, &error);
656 *errptr = PCRS_ERR_STUDY;
657 pcrs_free_job(newjob);
663 * Determine the number of capturing subpatterns.
664 * This is needed for handling $+ in the substitute.
666 if (0 > (*errptr = pcre_fullinfo(newjob->pattern, newjob->hints, PCRE_INFO_CAPTURECOUNT, &capturecount)))
668 pcrs_free_job(newjob);
674 * Compile the substitute
676 if (NULL == (newjob->substitute = pcrs_compile_replacement(substitute, newjob->flags & PCRS_TRIVIAL, capturecount, errptr)))
678 pcrs_free_job(newjob);
687 /*********************************************************************
689 * Function : pcrs_execute_list
691 * Description : This is a multiple job wrapper for pcrs_execute().
692 * Apply the regular substitutions defined by the jobs in
693 * the joblist to the subject.
694 * The subject itself is left untouched, memory for the result
695 * is malloc()ed and it is the caller's responsibility to free
696 * the result when it's no longer needed.
699 * 1 : joblist = the chained list of pcrs_jobs to be executed
700 * 2 : subject = the subject string
701 * 3 : subject_length = the subject's length
702 * INCLUDING the terminating zero, if string!
703 * 4 : result = char** for returning the result
704 * 5 : result_length = size_t* for returning the result's length
706 * Returns : On success, the number of substitutions that were made.
707 * May be > 1 if job->flags contained PCRS_GLOBAL
708 * On failiure, the (negative) pcre error code describing the
709 * failiure, which may be translated to text using pcrs_strerror().
711 *********************************************************************/
712 int pcrs_execute_list(pcrs_job *joblist, char *subject, size_t subject_length, char **result, size_t *result_length)
716 int hits, total_hits;
719 *result_length = subject_length;
720 hits = total_hits = 0;
722 for (job = joblist; job != NULL; job = job->next)
724 hits = pcrs_execute(job, old, *result_length, &new, result_length);
726 if (old != subject) free(old);
745 /*********************************************************************
747 * Function : pcrs_execute
749 * Description : Apply the regular substitution defined by the job to the
751 * The subject itself is left untouched, memory for the result
752 * is malloc()ed and it is the caller's responsibility to free
753 * the result when it's no longer needed.
756 * 1 : job = the pcrs_job to be executed
757 * 2 : subject = the subject (== original) string
758 * 3 : subject_length = the subject's length
759 * INCLUDING the terminating zero, if string!
760 * 4 : result = char** for returning the result
761 * 5 : result_length = size_t* for returning the result's length
763 * Returns : On success, the number of substitutions that were made.
764 * May be > 1 if job->flags contained PCRS_GLOBAL
765 * On failiure, the (negative) pcre error code describing the
766 * failiure, which may be translated to text using pcrs_strerror().
768 *********************************************************************/
769 int pcrs_execute(pcrs_job *job, char *subject, size_t subject_length, char **result, size_t *result_length)
771 int offsets[3 * PCRS_MAX_SUBMATCHES],
777 max_matches = PCRS_MAX_MATCH_INIT;
778 pcrs_match *matches, *dummy;
784 * Sanity check & memory allocation
786 if (job == NULL || job->pattern == NULL || job->substitute == NULL)
789 return(PCRS_ERR_BADJOB);
792 if (NULL == (matches = (pcrs_match *)malloc(max_matches * sizeof(pcrs_match))))
795 return(PCRS_ERR_NOMEM);
797 memset(matches, '\0', max_matches * sizeof(pcrs_match));
801 * Find the pattern and calculate the space
802 * requirements for the result
804 newsize=subject_length;
806 while ((submatches = pcre_exec(job->pattern, job->hints, subject, subject_length, offset, 0, offsets, 3 * PCRS_MAX_SUBMATCHES)) > 0)
808 job->flags |= PCRS_SUCCESS;
809 matches[i].submatches = submatches;
811 for (k=0; k < submatches; k++)
813 matches[i].submatch_offset[k] = offsets[2 * k];
815 /* Note: Non-found optional submatches have length -1-(-1)==0 */
816 matches[i].submatch_length[k] = offsets[2 * k + 1] - offsets[2 * k];
818 /* reserve mem for each submatch as often as it is ref'd */
819 newsize += matches[i].submatch_length[k] * job->substitute->backref_count[k];
821 /* plus replacement text size minus match text size */
822 newsize += strlen(job->substitute->text) - matches[i].submatch_length[0];
824 /* chunk before match */
825 matches[i].submatch_offset[PCRS_MAX_SUBMATCHES] = 0;
826 matches[i].submatch_length[PCRS_MAX_SUBMATCHES] = offsets[0];
827 newsize += offsets[0] * job->substitute->backref_count[PCRS_MAX_SUBMATCHES];
829 /* chunk after match */
830 matches[i].submatch_offset[PCRS_MAX_SUBMATCHES + 1] = offsets[1];
831 matches[i].submatch_length[PCRS_MAX_SUBMATCHES + 1] = subject_length - offsets[1] - 1;
832 newsize += (subject_length - offsets[1]) * job->substitute->backref_count[PCRS_MAX_SUBMATCHES + 1];
834 /* Storage for matches exhausted? -> Extend! */
835 if (++i >= max_matches)
837 max_matches = (int) (max_matches * PCRS_MAX_MATCH_GROW);
838 if (NULL == (dummy = (pcrs_match *)realloc(matches, max_matches * sizeof(pcrs_match))))
842 return(PCRS_ERR_NOMEM);
847 /* Non-global search or limit reached? */
848 if (!(job->flags & PCRS_GLOBAL)) break;
850 /* Don't loop on empty matches */
851 if (offsets[1] == offset)
852 /* FIXME: is offset an int or a size_t? Previous line compares
853 * against int, the next one compares against size_t.
855 if ((size_t)offset < subject_length)
859 /* Go find the next one */
863 /* Pass pcre error through if (bad) failiure */
864 if (submatches < PCRE_ERROR_NOMATCH)
873 * Get memory for the result
875 if ((*result = (char *)malloc(newsize)) == NULL) /* must be free()d by caller */
878 return PCRS_ERR_NOMEM;
886 result_offset = *result;
888 for (i=0; i < matches_found; i++)
890 /* copy the chunk preceding the match */
891 memcpy(result_offset, subject + offset, matches[i].submatch_offset[0] - offset);
892 result_offset += matches[i].submatch_offset[0] - offset;
894 /* For every segment of the substitute.. */
895 for (k=0; k <= job->substitute->backrefs; k++)
897 /* ...copy its text.. */
898 memcpy(result_offset, job->substitute->text + job->substitute->block_offset[k], job->substitute->block_length[k]);
899 result_offset += job->substitute->block_length[k];
901 /* ..plus, if it's not the last chunk, i.e.: There *is* a backref.. */
902 if (k != job->substitute->backrefs
903 /* ..in legal range.. */
904 && job->substitute->backref[k] < PCRS_MAX_SUBMATCHES + 2
905 /* ..and referencing a nonempty match.. */
906 && matches[i].submatch_length[job->substitute->backref[k]] > 0)
908 /* ..copy the submatch that is ref'd. */
911 subject + matches[i].submatch_offset[job->substitute->backref[k]],
912 matches[i].submatch_length[job->substitute->backref[k]]
914 result_offset += matches[i].submatch_length[job->substitute->backref[k]];
917 offset = matches[i].submatch_offset[0] + matches[i].submatch_length[0];
921 memcpy(result_offset, subject + offset, subject_length - offset);
923 *result_length = newsize;
925 return matches_found;