1 const char pcrs_rcs[] = "$Id: pcrs.c,v 1.12 2001/08/18 11:35:00 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.12 2001/08/18 11:35:00 oes
37 * - Introduced pcrs_strerror()
38 * - made some NULL arguments non-fatal
39 * - added support for \n \r \e \b \t \f \a \0 in substitute
40 * - made quoting adhere to standard rules
41 * - added warning for bad backrefs
42 * - added pcrs_execute_list()
44 * - bugfix & cosmetics
46 * Revision 1.11 2001/08/15 15:32:03 oes
47 * - Added support for Perl's special variables $+, $' and $`
48 * - Improved the substitute parser
49 * - Replaced the hard limit for the maximum number of matches
50 * by dynamic reallocation
52 * Revision 1.10 2001/08/05 13:13:11 jongfoster
53 * Making parameters "const" where possible.
55 * Revision 1.9 2001/07/18 17:27:00 oes
56 * Changed interface; Cosmetics
58 * Revision 1.8 2001/06/29 21:45:41 oes
59 * Indentation, CRLF->LF, Tab-> Space
61 * Revision 1.7 2001/06/29 13:33:04 oes
62 * - Cleaned up, renamed and reordered functions,
65 * - Replaced globalflag with a general flags int
66 * that holds PCRS_GLOBAL, PCRS_SUCCESS, and PCRS_TRIVIAL
67 * - Introduced trivial option that will prevent pcrs
68 * from honouring backreferences in the substitute,
69 * which is useful for large substitutes that are
70 * red in from somewhere and saves the pain of escaping
72 * - Introduced convenience function pcrs_free_joblist()
73 * - Split pcrs_make_job() into pcrs_compile(), which still
74 * takes a complete s/// comand as argument and parses it,
75 * and a new function pcrs_make_job, which takes the
76 * three separate components. This should make for a
77 * much friendlier frontend.
78 * - Removed create_pcrs_job() which was useless
79 * - Fixed a bug in pcrs_execute
80 * - Success flag is now handled by pcrs instead of user
82 * Revision 1.6 2001/06/03 19:12:45 oes
85 * Revision 1.5 2001/05/29 09:50:24 jongfoster
86 * (Fixed one int -> size_t)
88 * Revision 1.4 2001/05/25 14:12:40 oes
89 * Fixed bug: Empty substitutes now detected
91 * Revision 1.3 2001/05/25 11:03:55 oes
92 * Added sanity check for NULL jobs to pcrs_exec_substitution
94 * Revision 1.2 2001/05/22 18:46:04 oes
96 * Added support for PCRE_UNGREEDY behaviour to pcrs,
97 * which is selected by the (nonstandard and therefore
98 * capital) letter 'U' in the option string.
99 * It causes the quantifiers to be ungreedy by default.
100 * Appending a ? turns back to greedy (!).
102 * Revision 1.1.1.1 2001/05/15 13:59:02 oes
103 * Initial import of version 2.9.3 source tree
106 *********************************************************************/
115 const char pcrs_h_rcs[] = PCRS_H_VERSION;
117 /*********************************************************************
119 * Function : pcrs_strerror
121 * Description : Return a string describing a given error code.
124 * 1 : error = the error code
126 * Returns : char * to the descriptive string
128 *********************************************************************/
129 const char *pcrs_strerror(const int error)
135 /* Passed-through PCRE error: */
136 case PCRE_ERROR_NOMEMORY: return "(pcre:) No memory";
138 /* Shouldn't happen unless PCRE or PCRS bug, or user messed with compiled job: */
139 case PCRE_ERROR_NULL: return "(pcre:) NULL code or subject or ovector";
140 case PCRE_ERROR_BADOPTION: return "(pcre:) Unrecognized option bit";
141 case PCRE_ERROR_BADMAGIC: return "(pcre:) Bad magic number in code";
142 case PCRE_ERROR_UNKNOWN_NODE: return "(pcre:) Bad node in pattern";
144 /* Can't happen / not passed: */
145 case PCRE_ERROR_NOSUBSTRING: return "(pcre:) Fire in power supply";
146 case PCRE_ERROR_NOMATCH: return "(pcre:) Water in power supply";
149 case PCRS_ERR_NOMEM: return "(pcrs:) No memory";
150 case PCRS_ERR_CMDSYNTAX: return "(pcrs:) Syntax error while parsing command";
151 case PCRS_ERR_STUDY: return "(pcrs:) PCRE error while studying the pattern";
152 case PCRS_ERR_BADJOB: return "(pcrs:) Bad job - NULL job, pattern or substitute";
153 case PCRS_WARN_BADREF: return "(pcrs:) Backreference out of range";
156 default: return "Unknown error";
159 /* error >= 0: No error */
160 return "(pcrs:) Everything's just fine. Thanks for asking.";
165 /*********************************************************************
167 * Function : pcrs_parse_perl_options
169 * Description : This function parses a string containing the options to
170 * Perl's s/// operator. It returns an integer that is the
171 * pcre equivalent of the symbolic optstring.
172 * Since pcre doesn't know about Perl's 'g' (global) or pcrs',
173 * 'T' (trivial) options but pcrs needs them, the corresponding
174 * flags are set if 'g'or 'T' is encountered.
175 * Note: The 'T' and 'U' options do not conform to Perl.
178 * 1 : optstring = string with options in perl syntax
179 * 2 : flags = see description
181 * Returns : option integer suitable for pcre
183 *********************************************************************/
184 int pcrs_parse_perl_options(const char *optstring, int *flags)
190 if (NULL == optstring) return 0;
192 for (i=0; i < strlen(optstring); i++)
196 case 'e': break; /* ToDo ;-) */
197 case 'g': *flags |= PCRS_GLOBAL; break;
198 case 'i': rc |= PCRE_CASELESS; break;
199 case 'm': rc |= PCRE_MULTILINE; break;
201 case 's': rc |= PCRE_DOTALL; break;
202 case 'x': rc |= PCRE_EXTENDED; break;
203 case 'U': rc |= PCRE_UNGREEDY; break;
204 case 'T': *flags |= PCRS_TRIVIAL; break;
213 /*********************************************************************
215 * Function : pcrs_compile_replacement
217 * Description : This function takes a Perl-style replacement (2nd argument
218 * to the s/// operator and returns a compiled pcrs_substitute,
219 * or NULL if memory allocation for the substitute structure
223 * 1 : replacement = replacement part of s/// operator
225 * 2 : trivialflag = Flag that causes backreferences to be
227 * 3 : capturecount = Number of capturing subpatterns in
228 * the pattern. Needed for $+ handling.
229 * 4 : errptr = pointer to an integer in which error
230 * conditions can be returned.
232 * Returns : pcrs_substitute data structure, or NULL if an
233 * error is encountered. In that case, *errptr has
236 *********************************************************************/
237 pcrs_substitute *pcrs_compile_replacement(const char *replacement, int trivialflag, int capturecount, int *errptr)
239 int length, i, k, l, quoted;
243 i = k = l = quoted = 0;
248 if (NULL == replacement)
256 if (NULL == (r = (pcrs_substitute *)malloc(sizeof(pcrs_substitute))))
258 *errptr = PCRS_ERR_NOMEM;
261 memset(r, '\0', sizeof(pcrs_substitute));
263 length = strlen(replacement);
265 if (NULL == (text = (char *)malloc(length + 1)))
268 *errptr = PCRS_ERR_NOMEM;
271 memset(r, '\0', length + 1);
275 * In trivial mode, just copy the substitute text
279 text = strncpy(text, replacement, length + 1);
284 * Else, parse, cut out and record all backreferences
291 if (replacement[i] == '\\')
295 text[k++] = replacement[i++];
300 if (replacement[i+1] && strchr("tnrfae0", replacement[i+1]))
302 switch(replacement[++i])
338 if (replacement[i] == '$' && !quoted && i < length - 1)
340 char *symbol, symbols[] = "'`+&";
341 r->block_length[l] = k - r->block_offset[l];
343 /* Numerical backreferences */
344 if (isdigit(replacement[i + 1]))
346 while (i < length && isdigit(replacement[++i]))
348 r->backref[l] = r->backref[l] * 10 + replacement[i] - 48;
350 if (r->backref[l] > capturecount)
352 *errptr = PCRS_WARN_BADREF;
356 /* Symbolic backreferences: */
357 else if (NULL != (symbol = strchr(symbols, replacement[i + 1])))
360 if (symbol - symbols == 2) /* $+ */
362 r->backref[l] = capturecount;
364 else if (symbol - symbols == 3) /* $& */
370 r->backref[l] = PCRS_MAX_SUBMATCHES + 1 - (symbol - symbols);
375 /* Invalid backref -> plain '$' */
381 /* Valid and in range? -> record */
382 if (r->backref[l] < PCRS_MAX_SUBMATCHES + 2)
384 r->backref_count[r->backref[l]] += 1;
385 r->block_offset[++l] = k;
389 *errptr = PCRS_WARN_BADREF;
395 /* Plain chars are copied */
396 text[k++] = replacement[i++];
399 } /* -END- if (!trivialflag) */
406 r->block_length[l] = k - r->block_offset[l];
413 /*********************************************************************
415 * Function : pcrs_free_job
417 * Description : Frees the memory used by a pcrs_job struct and its
418 * dependant structures.
421 * 1 : job = pointer to the pcrs_job structure to be freed
423 * Returns : a pointer to the next job, if there was any, or
426 *********************************************************************/
427 pcrs_job *pcrs_free_job(pcrs_job *job)
438 if (job->pattern != NULL) free(job->pattern);
439 if (job->hints != NULL) free(job->hints);
440 if (job->substitute != NULL)
442 if (job->substitute->text != NULL) free(job->substitute->text);
443 free(job->substitute);
452 /*********************************************************************
454 * Function : pcrs_free_joblist
456 * Description : Iterates through a chained list of pcrs_job's and
457 * frees them using pcrs_free_job.
460 * 1 : joblist = pointer to the first pcrs_job structure to
465 *********************************************************************/
466 void pcrs_free_joblist(pcrs_job *joblist)
468 while ( NULL != (joblist = pcrs_free_job(joblist)) ) {};
475 /*********************************************************************
477 * Function : pcrs_compile_command
479 * Description : Parses a string with a Perl-style s/// command,
480 * calls pcrs_compile, and returns a corresponding
481 * pcrs_job, or NULL if parsing or compiling the job
485 * 1 : command = string with perl-style s/// command
486 * 2 : errptr = pointer to an integer in which error
487 * conditions can be returned.
489 * Returns : a corresponding pcrs_job data structure, or NULL
490 * if an error was encountered. In that case, *errptr
493 *********************************************************************/
494 pcrs_job *pcrs_compile_command(const char *command, int *errptr)
496 int i, k, l, limit, quoted = FALSE;
504 * Tokenize the perl command
506 limit = strlen(command);
509 *errptr = PCRS_ERR_CMDSYNTAX;
514 delimiter = command[1];
517 tokens[l] = (char *) malloc(limit + 1);
519 for (i=0; i <= limit; i++)
522 if (command[i] == delimiter && !quoted)
529 tokens[0][k++] = '\0';
530 tokens[++l] = tokens[0] + k;
534 else if (command[i] == '\\' && !quoted)
537 if (command[i+1] == delimiter) continue;
543 tokens[0][k++] = command[i];
551 *errptr = PCRS_ERR_CMDSYNTAX;
556 newjob = pcrs_compile(tokens[1], tokens[2], tokens[3], errptr);
563 /*********************************************************************
565 * Function : pcrs_compile
567 * Description : Takes the three arguments to a perl s/// command
568 * and compiles a pcrs_job structure from them.
571 * 1 : pattern = string with perl-style pattern
572 * 2 : substitute = string with perl-style substitute
573 * 3 : options = string with perl-style options
574 * 4 : errptr = pointer to an integer in which error
575 * conditions can be returned.
577 * Returns : a corresponding pcrs_job data structure, or NULL
578 * if an error was encountered. In that case, *errptr
581 *********************************************************************/
582 pcrs_job *pcrs_compile(const char *pattern, const char *substitute, const char *options, int *errptr)
592 * Handle NULL arguments
594 if (pattern == NULL) pattern = "";
595 if (substitute == NULL) substitute = "";
599 * Get and init memory
601 if (NULL == (newjob = (pcrs_job *)malloc(sizeof(pcrs_job))))
603 *errptr = PCRS_ERR_NOMEM;
606 memset(newjob, '\0', sizeof(pcrs_job));
610 * Evaluate the options
612 newjob->options = pcrs_parse_perl_options(options, &flags);
613 newjob->flags = flags;
617 * Compile the pattern
619 newjob->pattern = pcre_compile(pattern, newjob->options, &error, errptr, NULL);
620 if (newjob->pattern == NULL)
622 pcrs_free_job(newjob);
628 * Generate hints. This has little overhead, since the
629 * hints will be NULL for a boring pattern anyway.
631 newjob->hints = pcre_study(newjob->pattern, 0, &error);
634 *errptr = PCRS_ERR_STUDY;
635 pcrs_free_job(newjob);
641 * Determine the number of capturing subpatterns.
642 * This is needed for handling $+ in the substitute.
644 if (0 > (*errptr = pcre_fullinfo(newjob->pattern, newjob->hints, PCRE_INFO_CAPTURECOUNT, &capturecount)))
646 pcrs_free_job(newjob);
652 * Compile the substitute
654 if (NULL == (newjob->substitute = pcrs_compile_replacement(substitute, newjob->flags & PCRS_TRIVIAL, capturecount, errptr)))
656 pcrs_free_job(newjob);
665 /*********************************************************************
667 * Function : pcrs_execute_list
669 * Description : This is a multiple job wrapper for pcrs_execute().
670 * Apply the regular substitutions defined by the jobs in
671 * the joblist to the subject.
672 * The subject itself is left untouched, memory for the result
673 * is malloc()ed and it is the caller's responsibility to free
674 * the result when it's no longer needed.
677 * 1 : joblist = the chained list of pcrs_jobs to be executed
678 * 2 : subject = the subject string
679 * 3 : subject_length = the subject's length
680 * INCLUDING the terminating zero, if string!
681 * 4 : result = char** for returning the result
682 * 5 : result_length = size_t* for returning the result's length
684 * Returns : On success, the number of substitutions that were made.
685 * May be > 1 if job->flags contained PCRS_GLOBAL
686 * On failiure, the (negative) pcre error code describing the
687 * failiure, which may be translated to text using pcrs_strerror().
689 *********************************************************************/
690 int pcrs_execute_list(pcrs_job *joblist, char *subject, size_t subject_length, char **result, size_t *result_length)
694 int hits, total_hits;
697 *result_length = subject_length;
698 hits = total_hits = 0;
700 for (job = joblist; job != NULL; job = job->next)
702 hits = pcrs_execute(job, old, *result_length, &new, result_length);
704 if (old != subject) free(old);
723 /*********************************************************************
725 * Function : pcrs_execute
727 * Description : Apply the regular substitution defined by the job to the
729 * The subject itself is left untouched, memory for the result
730 * is malloc()ed and it is the caller's responsibility to free
731 * the result when it's no longer needed.
734 * 1 : job = the pcrs_job to be executed
735 * 2 : subject = the subject (== original) string
736 * 3 : subject_length = the subject's length
737 * INCLUDING the terminating zero, if string!
738 * 4 : result = char** for returning the result
739 * 5 : result_length = size_t* for returning the result's length
741 * Returns : On success, the number of substitutions that were made.
742 * May be > 1 if job->flags contained PCRS_GLOBAL
743 * On failiure, the (negative) pcre error code describing the
744 * failiure, which may be translated to text using pcrs_strerror().
746 *********************************************************************/
747 int pcrs_execute(pcrs_job *job, char *subject, size_t subject_length, char **result, size_t *result_length)
749 int offsets[3 * PCRS_MAX_SUBMATCHES],
754 max_matches = PCRS_MAX_MATCH_INIT;
755 pcrs_match *matches, *dummy;
761 * Sanity check & memory allocation
763 if (job == NULL || job->pattern == NULL || job->substitute == NULL)
766 return(PCRS_ERR_BADJOB);
769 if (NULL == (matches = (pcrs_match *)malloc(max_matches * sizeof(pcrs_match))))
772 return(PCRS_ERR_NOMEM);
774 memset(matches, '\0', max_matches * sizeof(pcrs_match));
778 * Find the pattern and calculate the space
779 * requirements for the result
781 newsize=subject_length;
783 while ((submatches = pcre_exec(job->pattern, job->hints, subject, subject_length, offset, 0, offsets, 3 * PCRS_MAX_SUBMATCHES)) > 0)
785 job->flags |= PCRS_SUCCESS;
786 matches[i].submatches = submatches;
788 for (k=0; k < submatches; k++)
790 matches[i].submatch_offset[k] = offsets[2 * k];
792 /* Note: Non-found optional submatches have length -1-(-1)==0 */
793 matches[i].submatch_length[k] = offsets[2 * k + 1] - offsets[2 * k];
795 /* reserve mem for each submatch as often as it is ref'd */
796 newsize += matches[i].submatch_length[k] * job->substitute->backref_count[k];
798 /* plus replacement text size minus match text size */
799 newsize += strlen(job->substitute->text) - matches[i].submatch_length[0];
801 /* chunk before match */
802 matches[i].submatch_offset[PCRS_MAX_SUBMATCHES] = 0;
803 matches[i].submatch_length[PCRS_MAX_SUBMATCHES] = offsets[0];
804 newsize += offsets[0] * job->substitute->backref_count[PCRS_MAX_SUBMATCHES];
806 /* chunk after match */
807 matches[i].submatch_offset[PCRS_MAX_SUBMATCHES + 1] = offsets[1];
808 matches[i].submatch_length[PCRS_MAX_SUBMATCHES + 1] = subject_length - offsets[1] - 1;
809 newsize += (subject_length - offsets[1]) * job->substitute->backref_count[PCRS_MAX_SUBMATCHES + 1];
811 /* Storage for matches exhausted? -> Extend! */
812 if (++i >= max_matches)
814 max_matches *= PCRS_MAX_MATCH_GROW;
815 if (NULL == (dummy = (pcrs_match *)realloc(matches, max_matches * sizeof(pcrs_match))))
819 return(PCRS_ERR_NOMEM);
824 /* Non-global search or limit reached? */
825 if (!(job->flags & PCRS_GLOBAL)) break;
827 /* Don't loop on empty matches */
828 if (offsets[1] == offset)
829 if (offset < subject_length)
833 /* Go find the next one */
837 /* Pass pcre error through if (bad) failiure */
838 if (submatches < PCRE_ERROR_NOMATCH)
847 * Get memory for the result
849 if ((*result = (char *)malloc(newsize)) == NULL) /* must be free()d by caller */
852 return PCRS_ERR_NOMEM;
860 result_offset = *result;
862 for (i=0; i < matches_found; i++)
864 /* copy the chunk preceding the match */
865 memcpy(result_offset, subject + offset, matches[i].submatch_offset[0] - offset);
866 result_offset += matches[i].submatch_offset[0] - offset;
868 /* For every segment of the substitute.. */
869 for (k=0; k <= job->substitute->backrefs; k++)
871 /* ...copy its text.. */
872 memcpy(result_offset, job->substitute->text + job->substitute->block_offset[k], job->substitute->block_length[k]);
873 result_offset += job->substitute->block_length[k];
875 /* ..plus, if it's not the last chunk, i.e.: There *is* a backref.. */
876 if (k != job->substitute->backrefs
877 /* ..in legal range.. */
878 && job->substitute->backref[k] < PCRS_MAX_SUBMATCHES + 2
879 /* ..and referencing a nonempty match.. */
880 && matches[i].submatch_length[job->substitute->backref[k]] > 0)
882 /* ..copy the submatch that is ref'd. */
885 subject + matches[i].submatch_offset[job->substitute->backref[k]],
886 matches[i].submatch_length[job->substitute->backref[k]]
888 result_offset += matches[i].submatch_length[job->substitute->backref[k]];
891 offset = matches[i].submatch_offset[0] + matches[i].submatch_length[0];
895 memcpy(result_offset, subject + offset, subject_length - offset);
897 *result_length = newsize;
899 return matches_found;