1 const char pcrs_rcs[] = "$Id: pcrs.c,v 1.13 2001/09/06 14:05:59 oes 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.13 2001/09/06 14:05:59 oes
39 * Revision 1.12 2001/08/18 11:35:00 oes
40 * - Introduced pcrs_strerror()
41 * - made some NULL arguments non-fatal
42 * - added support for \n \r \e \b \t \f \a \0 in substitute
43 * - made quoting adhere to standard rules
44 * - added warning for bad backrefs
45 * - added pcrs_execute_list()
47 * - bugfix & cosmetics
49 * Revision 1.11 2001/08/15 15:32:03 oes
50 * - Added support for Perl's special variables $+, $' and $`
51 * - Improved the substitute parser
52 * - Replaced the hard limit for the maximum number of matches
53 * by dynamic reallocation
55 * Revision 1.10 2001/08/05 13:13:11 jongfoster
56 * Making parameters "const" where possible.
58 * Revision 1.9 2001/07/18 17:27:00 oes
59 * Changed interface; Cosmetics
61 * Revision 1.8 2001/06/29 21:45:41 oes
62 * Indentation, CRLF->LF, Tab-> Space
64 * Revision 1.7 2001/06/29 13:33:04 oes
65 * - Cleaned up, renamed and reordered functions,
68 * - Replaced globalflag with a general flags int
69 * that holds PCRS_GLOBAL, PCRS_SUCCESS, and PCRS_TRIVIAL
70 * - Introduced trivial option that will prevent pcrs
71 * from honouring backreferences in the substitute,
72 * which is useful for large substitutes that are
73 * red in from somewhere and saves the pain of escaping
75 * - Introduced convenience function pcrs_free_joblist()
76 * - Split pcrs_make_job() into pcrs_compile(), which still
77 * takes a complete s/// comand as argument and parses it,
78 * and a new function pcrs_make_job, which takes the
79 * three separate components. This should make for a
80 * much friendlier frontend.
81 * - Removed create_pcrs_job() which was useless
82 * - Fixed a bug in pcrs_execute
83 * - Success flag is now handled by pcrs instead of user
85 * Revision 1.6 2001/06/03 19:12:45 oes
88 * Revision 1.5 2001/05/29 09:50:24 jongfoster
89 * (Fixed one int -> size_t)
91 * Revision 1.4 2001/05/25 14:12:40 oes
92 * Fixed bug: Empty substitutes now detected
94 * Revision 1.3 2001/05/25 11:03:55 oes
95 * Added sanity check for NULL jobs to pcrs_exec_substitution
97 * Revision 1.2 2001/05/22 18:46:04 oes
99 * Added support for PCRE_UNGREEDY behaviour to pcrs,
100 * which is selected by the (nonstandard and therefore
101 * capital) letter 'U' in the option string.
102 * It causes the quantifiers to be ungreedy by default.
103 * Appending a ? turns back to greedy (!).
105 * Revision 1.1.1.1 2001/05/15 13:59:02 oes
106 * Initial import of version 2.9.3 source tree
109 *********************************************************************/
118 const char pcrs_h_rcs[] = PCRS_H_VERSION;
120 /*********************************************************************
122 * Function : pcrs_strerror
124 * Description : Return a string describing a given error code.
127 * 1 : error = the error code
129 * Returns : char * to the descriptive string
131 *********************************************************************/
132 const char *pcrs_strerror(const int error)
138 /* Passed-through PCRE error: */
139 case PCRE_ERROR_NOMEMORY: return "(pcre:) No memory";
141 /* Shouldn't happen unless PCRE or PCRS bug, or user messed with compiled job: */
142 case PCRE_ERROR_NULL: return "(pcre:) NULL code or subject or ovector";
143 case PCRE_ERROR_BADOPTION: return "(pcre:) Unrecognized option bit";
144 case PCRE_ERROR_BADMAGIC: return "(pcre:) Bad magic number in code";
145 case PCRE_ERROR_UNKNOWN_NODE: return "(pcre:) Bad node in pattern";
147 /* Can't happen / not passed: */
148 case PCRE_ERROR_NOSUBSTRING: return "(pcre:) Fire in power supply";
149 case PCRE_ERROR_NOMATCH: return "(pcre:) Water in power supply";
152 case PCRS_ERR_NOMEM: return "(pcrs:) No memory";
153 case PCRS_ERR_CMDSYNTAX: return "(pcrs:) Syntax error while parsing command";
154 case PCRS_ERR_STUDY: return "(pcrs:) PCRE error while studying the pattern";
155 case PCRS_ERR_BADJOB: return "(pcrs:) Bad job - NULL job, pattern or substitute";
156 case PCRS_WARN_BADREF: return "(pcrs:) Backreference out of range";
159 default: return "Unknown error";
162 /* error >= 0: No error */
163 return "(pcrs:) Everything's just fine. Thanks for asking.";
168 /*********************************************************************
170 * Function : pcrs_parse_perl_options
172 * Description : This function parses a string containing the options to
173 * Perl's s/// operator. It returns an integer that is the
174 * pcre equivalent of the symbolic optstring.
175 * Since pcre doesn't know about Perl's 'g' (global) or pcrs',
176 * 'T' (trivial) options but pcrs needs them, the corresponding
177 * flags are set if 'g'or 'T' is encountered.
178 * Note: The 'T' and 'U' options do not conform to Perl.
181 * 1 : optstring = string with options in perl syntax
182 * 2 : flags = see description
184 * Returns : option integer suitable for pcre
186 *********************************************************************/
187 int pcrs_parse_perl_options(const char *optstring, int *flags)
193 if (NULL == optstring) return 0;
195 for (i=0; i < strlen(optstring); i++)
199 case 'e': break; /* ToDo ;-) */
200 case 'g': *flags |= PCRS_GLOBAL; break;
201 case 'i': rc |= PCRE_CASELESS; break;
202 case 'm': rc |= PCRE_MULTILINE; break;
204 case 's': rc |= PCRE_DOTALL; break;
205 case 'x': rc |= PCRE_EXTENDED; break;
206 case 'U': rc |= PCRE_UNGREEDY; break;
207 case 'T': *flags |= PCRS_TRIVIAL; break;
216 /*********************************************************************
218 * Function : pcrs_compile_replacement
220 * Description : This function takes a Perl-style replacement (2nd argument
221 * to the s/// operator and returns a compiled pcrs_substitute,
222 * or NULL if memory allocation for the substitute structure
226 * 1 : replacement = replacement part of s/// operator
228 * 2 : trivialflag = Flag that causes backreferences to be
230 * 3 : capturecount = Number of capturing subpatterns in
231 * the pattern. Needed for $+ handling.
232 * 4 : errptr = pointer to an integer in which error
233 * conditions can be returned.
235 * Returns : pcrs_substitute data structure, or NULL if an
236 * error is encountered. In that case, *errptr has
239 *********************************************************************/
240 pcrs_substitute *pcrs_compile_replacement(const char *replacement, int trivialflag, int capturecount, int *errptr)
242 int length, i, k, l, quoted;
246 i = k = l = quoted = 0;
251 if (NULL == replacement)
259 if (NULL == (r = (pcrs_substitute *)malloc(sizeof(pcrs_substitute))))
261 *errptr = PCRS_ERR_NOMEM;
264 memset(r, '\0', sizeof(pcrs_substitute));
266 length = strlen(replacement);
268 if (NULL == (text = (char *)malloc(length + 1)))
271 *errptr = PCRS_ERR_NOMEM;
274 memset(text, '\0', length + 1);
278 * In trivial mode, just copy the substitute text
282 text = strncpy(text, replacement, length + 1);
287 * Else, parse, cut out and record all backreferences
294 if (replacement[i] == '\\')
298 text[k++] = replacement[i++];
303 if (replacement[i+1] && strchr("tnrfae0", replacement[i+1]))
305 switch(replacement[++i])
341 if (replacement[i] == '$' && !quoted && i < length - 1)
343 char *symbol, symbols[] = "'`+&";
344 r->block_length[l] = k - r->block_offset[l];
346 /* Numerical backreferences */
347 if (isdigit(replacement[i + 1]))
349 while (i < length && isdigit(replacement[++i]))
351 r->backref[l] = r->backref[l] * 10 + replacement[i] - 48;
353 if (r->backref[l] > capturecount)
355 *errptr = PCRS_WARN_BADREF;
359 /* Symbolic backreferences: */
360 else if (NULL != (symbol = strchr(symbols, replacement[i + 1])))
363 if (symbol - symbols == 2) /* $+ */
365 r->backref[l] = capturecount;
367 else if (symbol - symbols == 3) /* $& */
373 r->backref[l] = PCRS_MAX_SUBMATCHES + 1 - (symbol - symbols);
378 /* Invalid backref -> plain '$' */
384 /* Valid and in range? -> record */
385 if (r->backref[l] < PCRS_MAX_SUBMATCHES + 2)
387 r->backref_count[r->backref[l]] += 1;
388 r->block_offset[++l] = k;
392 *errptr = PCRS_WARN_BADREF;
398 /* Plain chars are copied */
399 text[k++] = replacement[i++];
402 } /* -END- if (!trivialflag) */
409 r->block_length[l] = k - r->block_offset[l];
416 /*********************************************************************
418 * Function : pcrs_free_job
420 * Description : Frees the memory used by a pcrs_job struct and its
421 * dependant structures.
424 * 1 : job = pointer to the pcrs_job structure to be freed
426 * Returns : a pointer to the next job, if there was any, or
429 *********************************************************************/
430 pcrs_job *pcrs_free_job(pcrs_job *job)
441 if (job->pattern != NULL) free(job->pattern);
442 if (job->hints != NULL) free(job->hints);
443 if (job->substitute != NULL)
445 if (job->substitute->text != NULL) free(job->substitute->text);
446 free(job->substitute);
455 /*********************************************************************
457 * Function : pcrs_free_joblist
459 * Description : Iterates through a chained list of pcrs_job's and
460 * frees them using pcrs_free_job.
463 * 1 : joblist = pointer to the first pcrs_job structure to
468 *********************************************************************/
469 void pcrs_free_joblist(pcrs_job *joblist)
471 while ( NULL != (joblist = pcrs_free_job(joblist)) ) {};
478 /*********************************************************************
480 * Function : pcrs_compile_command
482 * Description : Parses a string with a Perl-style s/// command,
483 * calls pcrs_compile, and returns a corresponding
484 * pcrs_job, or NULL if parsing or compiling the job
488 * 1 : command = string with perl-style s/// command
489 * 2 : errptr = pointer to an integer in which error
490 * conditions can be returned.
492 * Returns : a corresponding pcrs_job data structure, or NULL
493 * if an error was encountered. In that case, *errptr
496 *********************************************************************/
497 pcrs_job *pcrs_compile_command(const char *command, int *errptr)
499 int i, k, l, limit, quoted = FALSE;
507 * Tokenize the perl command
509 limit = strlen(command);
512 *errptr = PCRS_ERR_CMDSYNTAX;
517 delimiter = command[1];
520 tokens[l] = (char *) malloc(limit + 1);
522 for (i=0; i <= limit; i++)
525 if (command[i] == delimiter && !quoted)
532 tokens[0][k++] = '\0';
533 tokens[++l] = tokens[0] + k;
537 else if (command[i] == '\\' && !quoted)
540 if (command[i+1] == delimiter) continue;
546 tokens[0][k++] = command[i];
554 *errptr = PCRS_ERR_CMDSYNTAX;
559 newjob = pcrs_compile(tokens[1], tokens[2], tokens[3], errptr);
566 /*********************************************************************
568 * Function : pcrs_compile
570 * Description : Takes the three arguments to a perl s/// command
571 * and compiles a pcrs_job structure from them.
574 * 1 : pattern = string with perl-style pattern
575 * 2 : substitute = string with perl-style substitute
576 * 3 : options = string with perl-style options
577 * 4 : errptr = pointer to an integer in which error
578 * conditions can be returned.
580 * Returns : a corresponding pcrs_job data structure, or NULL
581 * if an error was encountered. In that case, *errptr
584 *********************************************************************/
585 pcrs_job *pcrs_compile(const char *pattern, const char *substitute, const char *options, int *errptr)
595 * Handle NULL arguments
597 if (pattern == NULL) pattern = "";
598 if (substitute == NULL) substitute = "";
602 * Get and init memory
604 if (NULL == (newjob = (pcrs_job *)malloc(sizeof(pcrs_job))))
606 *errptr = PCRS_ERR_NOMEM;
609 memset(newjob, '\0', sizeof(pcrs_job));
613 * Evaluate the options
615 newjob->options = pcrs_parse_perl_options(options, &flags);
616 newjob->flags = flags;
620 * Compile the pattern
622 newjob->pattern = pcre_compile(pattern, newjob->options, &error, errptr, NULL);
623 if (newjob->pattern == NULL)
625 pcrs_free_job(newjob);
631 * Generate hints. This has little overhead, since the
632 * hints will be NULL for a boring pattern anyway.
634 newjob->hints = pcre_study(newjob->pattern, 0, &error);
637 *errptr = PCRS_ERR_STUDY;
638 pcrs_free_job(newjob);
644 * Determine the number of capturing subpatterns.
645 * This is needed for handling $+ in the substitute.
647 if (0 > (*errptr = pcre_fullinfo(newjob->pattern, newjob->hints, PCRE_INFO_CAPTURECOUNT, &capturecount)))
649 pcrs_free_job(newjob);
655 * Compile the substitute
657 if (NULL == (newjob->substitute = pcrs_compile_replacement(substitute, newjob->flags & PCRS_TRIVIAL, capturecount, errptr)))
659 pcrs_free_job(newjob);
668 /*********************************************************************
670 * Function : pcrs_execute_list
672 * Description : This is a multiple job wrapper for pcrs_execute().
673 * Apply the regular substitutions defined by the jobs in
674 * the joblist to the subject.
675 * The subject itself is left untouched, memory for the result
676 * is malloc()ed and it is the caller's responsibility to free
677 * the result when it's no longer needed.
680 * 1 : joblist = the chained list of pcrs_jobs to be executed
681 * 2 : subject = the subject string
682 * 3 : subject_length = the subject's length
683 * INCLUDING the terminating zero, if string!
684 * 4 : result = char** for returning the result
685 * 5 : result_length = size_t* for returning the result's length
687 * Returns : On success, the number of substitutions that were made.
688 * May be > 1 if job->flags contained PCRS_GLOBAL
689 * On failiure, the (negative) pcre error code describing the
690 * failiure, which may be translated to text using pcrs_strerror().
692 *********************************************************************/
693 int pcrs_execute_list(pcrs_job *joblist, char *subject, size_t subject_length, char **result, size_t *result_length)
697 int hits, total_hits;
700 *result_length = subject_length;
701 hits = total_hits = 0;
703 for (job = joblist; job != NULL; job = job->next)
705 hits = pcrs_execute(job, old, *result_length, &new, result_length);
707 if (old != subject) free(old);
726 /*********************************************************************
728 * Function : pcrs_execute
730 * Description : Apply the regular substitution defined by the job to the
732 * The subject itself is left untouched, memory for the result
733 * is malloc()ed and it is the caller's responsibility to free
734 * the result when it's no longer needed.
737 * 1 : job = the pcrs_job to be executed
738 * 2 : subject = the subject (== original) string
739 * 3 : subject_length = the subject's length
740 * INCLUDING the terminating zero, if string!
741 * 4 : result = char** for returning the result
742 * 5 : result_length = size_t* for returning the result's length
744 * Returns : On success, the number of substitutions that were made.
745 * May be > 1 if job->flags contained PCRS_GLOBAL
746 * On failiure, the (negative) pcre error code describing the
747 * failiure, which may be translated to text using pcrs_strerror().
749 *********************************************************************/
750 int pcrs_execute(pcrs_job *job, char *subject, size_t subject_length, char **result, size_t *result_length)
752 int offsets[3 * PCRS_MAX_SUBMATCHES],
757 max_matches = PCRS_MAX_MATCH_INIT;
758 pcrs_match *matches, *dummy;
764 * Sanity check & memory allocation
766 if (job == NULL || job->pattern == NULL || job->substitute == NULL)
769 return(PCRS_ERR_BADJOB);
772 if (NULL == (matches = (pcrs_match *)malloc(max_matches * sizeof(pcrs_match))))
775 return(PCRS_ERR_NOMEM);
777 memset(matches, '\0', max_matches * sizeof(pcrs_match));
781 * Find the pattern and calculate the space
782 * requirements for the result
784 newsize=subject_length;
786 while ((submatches = pcre_exec(job->pattern, job->hints, subject, subject_length, offset, 0, offsets, 3 * PCRS_MAX_SUBMATCHES)) > 0)
788 job->flags |= PCRS_SUCCESS;
789 matches[i].submatches = submatches;
791 for (k=0; k < submatches; k++)
793 matches[i].submatch_offset[k] = offsets[2 * k];
795 /* Note: Non-found optional submatches have length -1-(-1)==0 */
796 matches[i].submatch_length[k] = offsets[2 * k + 1] - offsets[2 * k];
798 /* reserve mem for each submatch as often as it is ref'd */
799 newsize += matches[i].submatch_length[k] * job->substitute->backref_count[k];
801 /* plus replacement text size minus match text size */
802 newsize += strlen(job->substitute->text) - matches[i].submatch_length[0];
804 /* chunk before match */
805 matches[i].submatch_offset[PCRS_MAX_SUBMATCHES] = 0;
806 matches[i].submatch_length[PCRS_MAX_SUBMATCHES] = offsets[0];
807 newsize += offsets[0] * job->substitute->backref_count[PCRS_MAX_SUBMATCHES];
809 /* chunk after match */
810 matches[i].submatch_offset[PCRS_MAX_SUBMATCHES + 1] = offsets[1];
811 matches[i].submatch_length[PCRS_MAX_SUBMATCHES + 1] = subject_length - offsets[1] - 1;
812 newsize += (subject_length - offsets[1]) * job->substitute->backref_count[PCRS_MAX_SUBMATCHES + 1];
814 /* Storage for matches exhausted? -> Extend! */
815 if (++i >= max_matches)
817 max_matches *= PCRS_MAX_MATCH_GROW;
818 if (NULL == (dummy = (pcrs_match *)realloc(matches, max_matches * sizeof(pcrs_match))))
822 return(PCRS_ERR_NOMEM);
827 /* Non-global search or limit reached? */
828 if (!(job->flags & PCRS_GLOBAL)) break;
830 /* Don't loop on empty matches */
831 if (offsets[1] == offset)
832 if (offset < subject_length)
836 /* Go find the next one */
840 /* Pass pcre error through if (bad) failiure */
841 if (submatches < PCRE_ERROR_NOMATCH)
850 * Get memory for the result
852 if ((*result = (char *)malloc(newsize)) == NULL) /* must be free()d by caller */
855 return PCRS_ERR_NOMEM;
863 result_offset = *result;
865 for (i=0; i < matches_found; i++)
867 /* copy the chunk preceding the match */
868 memcpy(result_offset, subject + offset, matches[i].submatch_offset[0] - offset);
869 result_offset += matches[i].submatch_offset[0] - offset;
871 /* For every segment of the substitute.. */
872 for (k=0; k <= job->substitute->backrefs; k++)
874 /* ...copy its text.. */
875 memcpy(result_offset, job->substitute->text + job->substitute->block_offset[k], job->substitute->block_length[k]);
876 result_offset += job->substitute->block_length[k];
878 /* ..plus, if it's not the last chunk, i.e.: There *is* a backref.. */
879 if (k != job->substitute->backrefs
880 /* ..in legal range.. */
881 && job->substitute->backref[k] < PCRS_MAX_SUBMATCHES + 2
882 /* ..and referencing a nonempty match.. */
883 && matches[i].submatch_length[job->substitute->backref[k]] > 0)
885 /* ..copy the submatch that is ref'd. */
888 subject + matches[i].submatch_offset[job->substitute->backref[k]],
889 matches[i].submatch_length[job->substitute->backref[k]]
891 result_offset += matches[i].submatch_length[job->substitute->backref[k]];
894 offset = matches[i].submatch_offset[0] + matches[i].submatch_length[0];
898 memcpy(result_offset, subject + offset, subject_length - offset);
900 *result_length = newsize;
902 return matches_found;