1 const char pcrs_rcs[] = "$Id: pcrs.c,v 1.11 2001/08/15 15:32:03 oes Exp $";
3 /*********************************************************************
5 * File : $Source: /cvsroot/ijbswa/current/pcrs.c,v $
7 * Purpose : pcrs is a supplement to the brilliant pcre library by Philip
8 * Hazel <ph10@cam.ac.uk> and adds Perl-style substitution. That
9 * is, it mimics Perl's 's' operator.
11 * Currently, there's no documentation besides comments and the
14 * Note: In addition to perl's options, 'U' for ungreedy and 'T'
15 * for trivial (i.e.: ignore backrefs in the substitute) are
18 * Copyright : Written and Copyright (C) 2000, 2001 by Andreas S. Oesterhelt
19 * <andreas@oesterhelt.org>
21 * This program is free software; you can redistribute it
22 * and/or modify it under the terms of the GNU General
23 * Public License as published by the Free Software
24 * Foundation; either version 2 of the License, or (at
25 * your option) any later version.
27 * This program is distributed in the hope that it will
28 * be useful, but WITHOUT ANY WARRANTY; without even the
29 * implied warranty of MERCHANTABILITY or FITNESS FOR A
30 * PARTICULAR PURPOSE. See the GNU General Public
31 * License for more details.
33 * The GNU General Public License should be included with
34 * this file. If not, you can view it at
35 * http://www.gnu.org/copyleft/gpl.html
36 * or write to the Free Software Foundation, Inc., 59
37 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
41 * Revision 1.11 2001/08/15 15:32:03 oes
42 * - Added support for Perl's special variables $+, $' and $`
43 * - Improved the substitute parser
44 * - Replaced the hard limit for the maximum number of matches
45 * by dynamic reallocation
47 * Revision 1.10 2001/08/05 13:13:11 jongfoster
48 * Making parameters "const" where possible.
50 * Revision 1.9 2001/07/18 17:27:00 oes
51 * Changed interface; Cosmetics
53 * Revision 1.8 2001/06/29 21:45:41 oes
54 * Indentation, CRLF->LF, Tab-> Space
56 * Revision 1.7 2001/06/29 13:33:04 oes
57 * - Cleaned up, renamed and reordered functions,
60 * - Replaced globalflag with a general flags int
61 * that holds PCRS_GLOBAL, PCRS_SUCCESS, and PCRS_TRIVIAL
62 * - Introduced trivial option that will prevent pcrs
63 * from honouring backreferences in the substitute,
64 * which is useful for large substitutes that are
65 * red in from somewhere and saves the pain of escaping
67 * - Introduced convenience function pcrs_free_joblist()
68 * - Split pcrs_make_job() into pcrs_compile(), which still
69 * takes a complete s/// comand as argument and parses it,
70 * and a new function pcrs_make_job, which takes the
71 * three separate components. This should make for a
72 * much friendlier frontend.
73 * - Removed create_pcrs_job() which was useless
74 * - Fixed a bug in pcrs_execute
75 * - Success flag is now handled by pcrs instead of user
77 * Revision 1.6 2001/06/03 19:12:45 oes
80 * Revision 1.5 2001/05/29 09:50:24 jongfoster
81 * (Fixed one int -> size_t)
83 * Revision 1.4 2001/05/25 14:12:40 oes
84 * Fixed bug: Empty substitutes now detected
86 * Revision 1.3 2001/05/25 11:03:55 oes
87 * Added sanity check for NULL jobs to pcrs_exec_substitution
89 * Revision 1.2 2001/05/22 18:46:04 oes
91 * Added support for PCRE_UNGREEDY behaviour to pcrs,
92 * which is selected by the (nonstandard and therefore
93 * capital) letter 'U' in the option string.
94 * It causes the quantifiers to be ungreedy by default.
95 * Appending a ? turns back to greedy (!).
97 * Revision 1.1.1.1 2001/05/15 13:59:02 oes
98 * Initial import of version 2.9.3 source tree
101 *********************************************************************/
108 const char pcrs_h_rcs[] = PCRS_H_VERSION;
111 /*********************************************************************
113 * Function : pcrs_strerror
115 * Description : Return a string describing a given error code.
118 * 1 : error = the error code
120 * Returns : char * to the descriptive string
122 *********************************************************************/
123 const char *pcrs_strerror(const int error)
129 /* Passed-through PCRE error: */
130 case PCRE_ERROR_NOMEMORY: return "(pcre:) No memory";
132 /* Shouldn't happen unless PCRE or PCRS bug, or user messed with compiled job: */
133 case PCRE_ERROR_NULL: return "(pcre:) NULL code or subject or ovector";
134 case PCRE_ERROR_BADOPTION: return "(pcre:) Unrecognized option bit";
135 case PCRE_ERROR_BADMAGIC: return "(pcre:) Bad magic number in code";
136 case PCRE_ERROR_UNKNOWN_NODE: return "(pcre:) Bad node in pattern";
138 /* Can't happen / not passed: */
139 case PCRE_ERROR_NOSUBSTRING: return "(pcre:) Fire in power supply";
140 case PCRE_ERROR_NOMATCH: return "(pcre:) Water in power supply";
143 case PCRS_ERR_NOMEM: return "(pcrs:) No memory";
144 case PCRS_ERR_CMDSYNTAX: return "(pcrs:) Syntax error while parsing command";
145 case PCRS_ERR_STUDY: return "(pcrs:) PCRE error while studying the pattern";
146 case PCRS_ERR_BADJOB: return "(pcrs:) Bad job - NULL job, pattern or substitute";
147 case PCRS_WARN_BADREF: return "(pcrs:) Backreference out of range";
150 default: return "Unknown error";
153 /* error > 0: No error */
154 return "(pcrs:) Everything's just fine. Thanks for asking.";
159 /*********************************************************************
161 * Function : pcrs_parse_perl_options
163 * Description : This function parses a string containing the options to
164 * Perl's s/// operator. It returns an integer that is the
165 * pcre equivalent of the symbolic optstring.
166 * Since pcre doesn't know about Perl's 'g' (global) or pcrs',
167 * 'T' (trivial) options but pcrs needs them, the corresponding
168 * flags are set if 'g'or 'T' is encountered.
169 * Note: The 'T' and 'U' options do not conform to Perl.
172 * 1 : optstring = string with options in perl syntax
173 * 2 : flags = see description
175 * Returns : option integer suitable for pcre
177 *********************************************************************/
178 int pcrs_parse_perl_options(const char *optstring, int *flags)
184 if (NULL == optstring) return 0;
186 for (i=0; i < strlen(optstring); i++)
190 case 'e': break; /* ToDo ;-) */
191 case 'g': *flags |= PCRS_GLOBAL; break;
192 case 'i': rc |= PCRE_CASELESS; break;
193 case 'm': rc |= PCRE_MULTILINE; break;
195 case 's': rc |= PCRE_DOTALL; break;
196 case 'x': rc |= PCRE_EXTENDED; break;
197 case 'U': rc |= PCRE_UNGREEDY; break;
198 case 'T': *flags |= PCRS_TRIVIAL; break;
207 /*********************************************************************
209 * Function : pcrs_compile_replacement
211 * Description : This function takes a Perl-style replacement (2nd argument
212 * to the s/// operator and returns a compiled pcrs_substitute,
213 * or NULL if memory allocation for the substitute structure
217 * 1 : replacement = replacement part of s/// operator
219 * 2 : trivialflag = Flag that causes backreferences to be
221 * 3 : capturecount = Number of capturing subpatterns in
222 * the pattern. Needed for $+ handling.
223 * 4 : errptr = pointer to an integer in which error
224 * conditions can be returned.
226 * Returns : pcrs_substitute data structure, or NULL if an
227 * error is encountered. In that case, *errptr has
230 *********************************************************************/
231 pcrs_substitute *pcrs_compile_replacement(const char *replacement, int trivialflag, int capturecount, int *errptr)
233 int length, i, k, l, quoted;
237 i = k = l = quoted = 0;
242 if (NULL == replacement)
250 if (NULL == (r = (pcrs_substitute *)malloc(sizeof(pcrs_substitute))))
252 *errptr = PCRS_ERR_NOMEM;
255 memset(r, '\0', sizeof(pcrs_substitute));
257 length = strlen(replacement);
259 if (NULL == (text = (char *)malloc(length + 1)))
262 *errptr = PCRS_ERR_NOMEM;
265 memset(r, '\0', length + 1);
269 * In trivial mode, just copy the substitute text
273 text = strncpy(text, replacement, length + 1);
278 * Else, parse, cut out and record all backreferences
285 if (replacement[i] == '\\')
289 text[k++] = replacement[i++];
294 if (replacement[i+1] && strchr("tnrfae0", replacement[i+1]))
296 switch(replacement[++i])
332 if (replacement[i] == '$' && !quoted && i < length - 1)
334 char *symbol, symbols[] = "'`+&";
335 r->block_length[l] = k - r->block_offset[l];
337 /* Numerical backreferences */
338 if (isdigit(replacement[i + 1]))
340 while (i < length && isdigit(replacement[++i]))
342 r->backref[l] = r->backref[l] * 10 + replacement[i] - 48;
344 if (r->backref[l] > capturecount)
346 *errptr = PCRS_WARN_BADREF;
350 /* Symbolic backreferences: */
351 else if (NULL != (symbol = strchr(symbols, replacement[i + 1])))
354 if (symbol - symbols == 2) /* $+ */
356 r->backref[l] = capturecount;
358 else if (symbol - symbols == 3) /* $& */
364 r->backref[l] = PCRS_MAX_SUBMATCHES + 1 - (symbol - symbols);
369 /* Invalid backref -> plain '$' */
375 /* Valid and in range? -> record */
376 if (r->backref[l] < PCRS_MAX_SUBMATCHES + 2)
378 r->backref_count[r->backref[l]] += 1;
379 r->block_offset[++l] = k;
383 *errptr = PCRS_WARN_BADREF;
389 /* Plain chars are copied */
390 text[k++] = replacement[i++];
393 } /* -END- if (!trivialflag) */
400 r->block_length[l] = k - r->block_offset[l];
407 /*********************************************************************
409 * Function : pcrs_free_job
411 * Description : Frees the memory used by a pcrs_job struct and its
412 * dependant structures.
415 * 1 : job = pointer to the pcrs_job structure to be freed
417 * Returns : a pointer to the next job, if there was any, or
420 *********************************************************************/
421 pcrs_job *pcrs_free_job(pcrs_job *job)
432 if (job->pattern != NULL) free(job->pattern);
433 if (job->hints != NULL) free(job->hints);
434 if (job->substitute != NULL)
436 if (job->substitute->text != NULL) free(job->substitute->text);
437 free(job->substitute);
446 /*********************************************************************
448 * Function : pcrs_free_joblist
450 * Description : Iterates through a chained list of pcrs_job's and
451 * frees them using pcrs_free_job.
454 * 1 : joblist = pointer to the first pcrs_job structure to
459 *********************************************************************/
460 void pcrs_free_joblist(pcrs_job *joblist)
462 while ( NULL != (joblist = pcrs_free_job(joblist)) ) {};
469 /*********************************************************************
471 * Function : pcrs_compile_command
473 * Description : Parses a string with a Perl-style s/// command,
474 * calls pcrs_compile, and returns a corresponding
475 * pcrs_job, or NULL if parsing or compiling the job
479 * 1 : command = string with perl-style s/// command
480 * 2 : errptr = pointer to an integer in which error
481 * conditions can be returned.
483 * Returns : a corresponding pcrs_job data structure, or NULL
484 * if an error was encountered. In that case, *errptr
487 *********************************************************************/
488 pcrs_job *pcrs_compile_command(const char *command, int *errptr)
490 int i, k, l, limit, quoted = FALSE;
498 * Tokenize the perl command
500 limit = strlen(command);
503 *errptr = PCRS_ERR_CMDSYNTAX;
508 delimiter = command[1];
511 tokens[l] = (char *) malloc(limit + 1);
513 for (i=0; i <= limit; i++)
516 if (command[i] == delimiter && !quoted)
523 tokens[0][k++] = '\0';
524 tokens[++l] = tokens[0] + k;
528 else if (command[i] == '\\' && !quoted)
531 if (command[i+1] == delimiter) continue;
537 tokens[0][k++] = command[i];
545 *errptr = PCRS_ERR_CMDSYNTAX;
550 newjob = pcrs_compile(tokens[1], tokens[2], tokens[3], errptr);
557 /*********************************************************************
559 * Function : pcrs_compile
561 * Description : Takes the three arguments to a perl s/// command
562 * and compiles a pcrs_job structure from them.
565 * 1 : pattern = string with perl-style pattern
566 * 2 : substitute = string with perl-style substitute
567 * 3 : options = string with perl-style options
568 * 4 : errptr = pointer to an integer in which error
569 * conditions can be returned.
571 * Returns : a corresponding pcrs_job data structure, or NULL
572 * if an error was encountered. In that case, *errptr
575 *********************************************************************/
576 pcrs_job *pcrs_compile(const char *pattern, const char *substitute, const char *options, int *errptr)
586 * Handle NULL arguments
588 if (pattern == NULL) pattern = "";
589 if (substitute == NULL) substitute = "";
593 * Get and init memory
595 if (NULL == (newjob = (pcrs_job *)malloc(sizeof(pcrs_job))))
597 *errptr = PCRS_ERR_NOMEM;
600 memset(newjob, '\0', sizeof(pcrs_job));
604 * Evaluate the options
606 newjob->options = pcrs_parse_perl_options(options, &flags);
607 newjob->flags = flags;
611 * Compile the pattern
613 newjob->pattern = pcre_compile(pattern, newjob->options, &error, errptr, NULL);
614 if (newjob->pattern == NULL)
616 pcrs_free_job(newjob);
622 * Generate hints. This has little overhead, since the
623 * hints will be NULL for a boring pattern anyway.
625 newjob->hints = pcre_study(newjob->pattern, 0, &error);
628 *errptr = PCRS_ERR_STUDY;
629 pcrs_free_job(newjob);
635 * Determine the number of capturing subpatterns.
636 * This is needed for handling $+ in the substitute.
638 if (0 > (*errptr = pcre_fullinfo(newjob->pattern, newjob->hints, PCRE_INFO_CAPTURECOUNT, &capturecount)))
640 pcrs_free_job(newjob);
646 * Compile the substitute
648 if (NULL == (newjob->substitute = pcrs_compile_replacement(substitute, newjob->flags & PCRS_TRIVIAL, capturecount, errptr)))
650 pcrs_free_job(newjob);
659 /*********************************************************************
661 * Function : pcrs_execute_list
663 * Description : This is a multiple job wrapper for pcrs_execute().
664 * Apply the regular substitutions defined by the jobs in
665 * the joblist to the subject.
666 * The subject itself is left untouched, memory for the result
667 * is malloc()ed and it is the caller's responsibility to free
668 * the result when it's no longer needed.
671 * 1 : joblist = the chained list of pcrs_jobs to be executed
672 * 2 : subject = the subject string
673 * 3 : subject_length = the subject's length
674 * INCLUDING the terminating zero, if string!
675 * 4 : result = char** for returning the result
676 * 5 : result_length = size_t* for returning the result's length
678 * Returns : On success, the number of substitutions that were made.
679 * May be > 1 if job->flags contained PCRS_GLOBAL
680 * On failiure, the (negative) pcre error code describing the
681 * failiure, which may be translated to text using pcrs_strerror().
683 *********************************************************************/
684 int pcrs_execute_list(pcrs_job *joblist, char *subject, size_t subject_length, char **result, size_t *result_length)
688 int hits, total_hits;
691 *result_length = subject_length;
694 for (job = joblist; job != NULL; job = job->next)
696 hits = pcrs_execute(job, old, *result_length, &new, result_length);
697 if (old != subject) free(old);
715 /*********************************************************************
717 * Function : pcrs_execute
719 * Description : Apply the regular substitution defined by the job to the
721 * The subject itself is left untouched, memory for the result
722 * is malloc()ed and it is the caller's responsibility to free
723 * the result when it's no longer needed.
726 * 1 : job = the pcrs_job to be executed
727 * 2 : subject = the subject (== original) string
728 * 3 : subject_length = the subject's length
729 * INCLUDING the terminating zero, if string!
730 * 4 : result = char** for returning the result
731 * 5 : result_length = size_t* for returning the result's length
733 * Returns : On success, the number of substitutions that were made.
734 * May be > 1 if job->flags contained PCRS_GLOBAL
735 * On failiure, the (negative) pcre error code describing the
736 * failiure, which may be translated to text using pcrs_strerror().
738 *********************************************************************/
739 int pcrs_execute(pcrs_job *job, char *subject, size_t subject_length, char **result, size_t *result_length)
741 int offsets[3 * PCRS_MAX_SUBMATCHES],
746 max_matches = PCRS_MAX_MATCH_INIT;
747 pcrs_match *matches, *dummy;
753 * Sanity check & memory allocation
755 if (job == NULL || job->pattern == NULL || job->substitute == NULL)
758 return(PCRS_ERR_BADJOB);
761 if (NULL == (matches = (pcrs_match *)malloc(max_matches * sizeof(pcrs_match))))
764 return(PCRS_ERR_NOMEM);
766 memset(matches, '\0', max_matches * sizeof(pcrs_match));
770 * Find the pattern and calculate the space
771 * requirements for the result
773 newsize=subject_length;
775 while ((submatches = pcre_exec(job->pattern, job->hints, subject, subject_length, offset, 0, offsets, 3 * PCRS_MAX_SUBMATCHES)) > 0)
777 job->flags |= PCRS_SUCCESS;
778 matches[i].submatches = submatches;
780 for (k=0; k < submatches; k++)
782 matches[i].submatch_offset[k] = offsets[2 * k];
784 /* Note: Non-found optional submatches have length -1-(-1)==0 */
785 matches[i].submatch_length[k] = offsets[2 * k + 1] - offsets[2 * k];
787 /* reserve mem for each submatch as often as it is ref'd */
788 newsize += matches[i].submatch_length[k] * job->substitute->backref_count[k];
790 /* plus replacement text size minus match text size */
791 newsize += strlen(job->substitute->text) - matches[i].submatch_length[0];
793 /* chunk before match */
794 matches[i].submatch_offset[PCRS_MAX_SUBMATCHES] = 0;
795 matches[i].submatch_length[PCRS_MAX_SUBMATCHES] = offsets[0];
796 newsize += offsets[0] * job->substitute->backref_count[PCRS_MAX_SUBMATCHES];
798 /* chunk after match */
799 matches[i].submatch_offset[PCRS_MAX_SUBMATCHES + 1] = offsets[1];
800 matches[i].submatch_length[PCRS_MAX_SUBMATCHES + 1] = subject_length - offsets[1] - 1;
801 newsize += (subject_length - offsets[1]) * job->substitute->backref_count[PCRS_MAX_SUBMATCHES + 1];
803 /* Storage for matches exhausted? -> Extend! */
804 if (++i >= max_matches)
806 max_matches *= PCRS_MAX_MATCH_GROW;
807 if (NULL == (dummy = (pcrs_match *)realloc(matches, max_matches * sizeof(pcrs_match))))
811 return(PCRS_ERR_NOMEM);
816 /* Non-global search or limit reached? */
817 if (!(job->flags & PCRS_GLOBAL)) break;
819 /* Don't loop on empty matches */
820 if (offsets[1] == offset)
821 if (offset < subject_length)
825 /* Go find the next one */
829 /* Pass pcre error through if (bad) failiure */
830 if (submatches < PCRE_ERROR_NOMATCH)
839 * Get memory for the result
841 if ((*result = (char *)malloc(newsize)) == NULL) /* must be free()d by caller */
844 return PCRS_ERR_NOMEM;
852 result_offset = *result;
854 for (i=0; i < matches_found; i++)
856 /* copy the chunk preceding the match */
857 memcpy(result_offset, subject + offset, matches[i].submatch_offset[0] - offset);
858 result_offset += matches[i].submatch_offset[0] - offset;
860 /* For every segment of the substitute.. */
861 for (k=0; k <= job->substitute->backrefs; k++)
863 /* ...copy its text.. */
864 memcpy(result_offset, job->substitute->text + job->substitute->block_offset[k], job->substitute->block_length[k]);
865 result_offset += job->substitute->block_length[k];
867 /* ..plus, if it's not the last chunk, i.e.: There *is* a backref.. */
868 if (k != job->substitute->backrefs
869 /* ..in legal range.. */
870 && job->substitute->backref[k] < PCRS_MAX_SUBMATCHES + 2
871 /* ..and referencing a nonempty match.. */
872 && matches[i].submatch_length[job->substitute->backref[k]] > 0)
874 /* ..copy the submatch that is ref'd. */
877 subject + matches[i].submatch_offset[job->substitute->backref[k]],
878 matches[i].submatch_length[job->substitute->backref[k]]
880 result_offset += matches[i].submatch_length[job->substitute->backref[k]];
883 offset = matches[i].submatch_offset[0] + matches[i].submatch_length[0];
887 memcpy(result_offset, subject + offset, subject_length - offset);
889 *result_length = newsize;
891 return matches_found;