Initial import from FreeBSD RELENG_4:
[dragonfly.git] / usr.bin / lex / misc.c
1 /* misc - miscellaneous flex routines */
2
3 /*-
4  * Copyright (c) 1990 The Regents of the University of California.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Vern Paxson.
9  * 
10  * The United States Government has rights in this work pursuant
11  * to contract no. DE-AC03-76SF00098 between the United States
12  * Department of Energy and the University of California.
13  *
14  * Redistribution and use in source and binary forms are permitted provided
15  * that: (1) source distributions retain this entire copyright notice and
16  * comment, and (2) distributions including binaries display the following
17  * acknowledgement:  ``This product includes software developed by the
18  * University of California, Berkeley and its contributors'' in the
19  * documentation or other materials provided with the distribution and in
20  * all advertising materials mentioning features or use of this software.
21  * Neither the name of the University nor the names of its contributors may
22  * be used to endorse or promote products derived from this software without
23  * specific prior written permission.
24  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
25  * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
26  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
27  */
28
29 /* $Header: /home/daffy/u0/vern/flex/RCS/misc.c,v 2.47 95/04/28 11:39:39 vern Exp $ */
30 /* $FreeBSD: src/usr.bin/lex/misc.c,v 1.5 1999/10/27 07:56:45 obrien Exp $ */
31
32 #include "flexdef.h"
33
34
35 void action_define( defname, value )
36 char *defname;
37 int value;
38         {
39         char buf[MAXLINE];
40
41         if ( (int) strlen( defname ) > MAXLINE / 2 )
42                 {
43                 format_pinpoint_message( _( "name \"%s\" ridiculously long" ), 
44                         defname );
45                 return;
46                 }
47
48         sprintf( buf, "#define %s %d\n", defname, value );
49         add_action( buf );
50         }
51
52
53 void add_action( new_text )
54 char *new_text;
55         {
56         int len = strlen( new_text );
57
58         while ( len + action_index >= action_size - 10 /* slop */ )
59                 {
60                 int new_size = action_size * 2;
61
62                 if ( new_size <= 0 )
63                         /* Increase just a little, to try to avoid overflow
64                          * on 16-bit machines.
65                          */
66                         action_size += action_size / 8;
67                 else
68                         action_size = new_size;
69
70                 action_array =
71                         reallocate_character_array( action_array, action_size );
72                 }
73
74         strcpy( &action_array[action_index], new_text );
75
76         action_index += len;
77         }
78
79
80 /* allocate_array - allocate memory for an integer array of the given size */
81
82 void *allocate_array( size, element_size )
83 int size;
84 size_t element_size;
85         {
86         register void *mem;
87         size_t num_bytes = element_size * size;
88
89         mem = flex_alloc( num_bytes );
90         if ( ! mem )
91                 flexfatal(
92                         _( "memory allocation failed in allocate_array()" ) );
93
94         return mem;
95         }
96
97
98 /* all_lower - true if a string is all lower-case */
99
100 int all_lower( str )
101 register char *str;
102         {
103         while ( *str )
104                 {
105                 if ( ! isascii( (Char) *str ) || ! islower( *str ) )
106                         return 0;
107                 ++str;
108                 }
109
110         return 1;
111         }
112
113
114 /* all_upper - true if a string is all upper-case */
115
116 int all_upper( str )
117 register char *str;
118         {
119         while ( *str )
120                 {
121                 if ( ! isascii( (Char) *str ) || ! isupper( *str ) )
122                         return 0;
123                 ++str;
124                 }
125
126         return 1;
127         }
128
129
130 /* bubble - bubble sort an integer array in increasing order
131  *
132  * synopsis
133  *   int v[n], n;
134  *   void bubble( v, n );
135  *
136  * description
137  *   sorts the first n elements of array v and replaces them in
138  *   increasing order.
139  *
140  * passed
141  *   v - the array to be sorted
142  *   n - the number of elements of 'v' to be sorted
143  */
144
145 void bubble( v, n )
146 int v[], n;
147         {
148         register int i, j, k;
149
150         for ( i = n; i > 1; --i )
151                 for ( j = 1; j < i; ++j )
152                         if ( v[j] > v[j + 1] )  /* compare */
153                                 {
154                                 k = v[j];       /* exchange */
155                                 v[j] = v[j + 1];
156                                 v[j + 1] = k;
157                                 }
158         }
159
160
161 /* check_char - checks a character to make sure it's within the range
162  *              we're expecting.  If not, generates fatal error message
163  *              and exits.
164  */
165
166 void check_char( c )
167 int c;
168         {
169         if ( c >= CSIZE )
170                 lerrsf( _( "bad character '%s' detected in check_char()" ),
171                         readable_form( c ) );
172
173         if ( c >= csize )
174                 lerrsf(
175                 _( "scanner requires -8 flag to use the character %s" ),
176                         readable_form( c ) );
177         }
178
179
180
181 /* clower - replace upper-case letter to lower-case */
182
183 Char clower( c )
184 register int c;
185         {
186         return (Char) ((isascii( c ) && isupper( c )) ? tolower( c ) : c);
187         }
188
189
190 /* copy_string - returns a dynamically allocated copy of a string */
191
192 char *copy_string( str )
193 register const char *str;
194         {
195         register const char *c1;
196         register char *c2;
197         char *copy;
198         unsigned int size;
199
200         /* find length */
201         for ( c1 = str; *c1; ++c1 )
202                 ;
203
204         size = (c1 - str + 1) * sizeof( char );
205         copy = (char *) flex_alloc( size );
206
207         if ( copy == NULL )
208                 flexfatal( _( "dynamic memory failure in copy_string()" ) );
209
210         for ( c2 = copy; (*c2++ = *str++) != 0; )
211                 ;
212
213         return copy;
214         }
215
216
217 /* copy_unsigned_string -
218  *    returns a dynamically allocated copy of a (potentially) unsigned string
219  */
220
221 Char *copy_unsigned_string( str )
222 register Char *str;
223         {
224         register Char *c;
225         Char *copy;
226
227         /* find length */
228         for ( c = str; *c; ++c )
229                 ;
230
231         copy = allocate_Character_array( c - str + 1 );
232
233         for ( c = copy; (*c++ = *str++) != 0; )
234                 ;
235
236         return copy;
237         }
238
239
240 /* cshell - shell sort a character array in increasing order
241  *
242  * synopsis
243  *
244  *   Char v[n];
245  *   int n, special_case_0;
246  *   cshell( v, n, special_case_0 );
247  *
248  * description
249  *   Does a shell sort of the first n elements of array v.
250  *   If special_case_0 is true, then any element equal to 0
251  *   is instead assumed to have infinite weight.
252  *
253  * passed
254  *   v - array to be sorted
255  *   n - number of elements of v to be sorted
256  */
257
258 void cshell( v, n, special_case_0 )
259 Char v[];
260 int n, special_case_0;
261         {
262         int gap, i, j, jg;
263         Char k;
264
265         for ( gap = n / 2; gap > 0; gap = gap / 2 )
266                 for ( i = gap; i < n; ++i )
267                         for ( j = i - gap; j >= 0; j = j - gap )
268                                 {
269                                 jg = j + gap;
270
271                                 if ( special_case_0 )
272                                         {
273                                         if ( v[jg] == 0 )
274                                                 break;
275
276                                         else if ( v[j] != 0 && v[j] <= v[jg] )
277                                                 break;
278                                         }
279
280                                 else if ( v[j] <= v[jg] )
281                                         break;
282
283                                 k = v[j];
284                                 v[j] = v[jg];
285                                 v[jg] = k;
286                                 }
287         }
288
289
290 /* dataend - finish up a block of data declarations */
291
292 void dataend()
293         {
294         if ( datapos > 0 )
295                 dataflush();
296
297         /* add terminator for initialization; { for vi */
298         outn( "    } ;\n" );
299
300         dataline = 0;
301         datapos = 0;
302         }
303
304
305 /* dataflush - flush generated data statements */
306
307 void dataflush()
308         {
309         outc( '\n' );
310
311         if ( ++dataline >= NUMDATALINES )
312                 {
313                 /* Put out a blank line so that the table is grouped into
314                  * large blocks that enable the user to find elements easily.
315                  */
316                 outc( '\n' );
317                 dataline = 0;
318                 }
319
320         /* Reset the number of characters written on the current line. */
321         datapos = 0;
322         }
323
324
325 /* flexerror - report an error message and terminate */
326
327 void flexerror( msg )
328 const char msg[];
329         {
330         fprintf( stderr, "%s: %s\n", program_name, msg );
331         flexend( 1 );
332         }
333
334
335 /* flexfatal - report a fatal error message and terminate */
336
337 void flexfatal( msg )
338 const char msg[];
339         {
340         fprintf( stderr, _( "%s: fatal internal error, %s\n" ),
341                 program_name, msg );
342         exit( 1 );
343         }
344
345
346 /* htoi - convert a hexadecimal digit string to an integer value */
347
348 int htoi( str )
349 Char str[];
350         {
351         unsigned int result;
352
353         (void) sscanf( (char *) str, "%x", &result );
354
355         return result;
356         }
357
358
359 /* lerrif - report an error message formatted with one integer argument */
360
361 void lerrif( msg, arg )
362 const char msg[];
363 int arg;
364         {
365         char errmsg[MAXLINE];
366         (void) sprintf( errmsg, msg, arg );
367         flexerror( errmsg );
368         }
369
370
371 /* lerrsf - report an error message formatted with one string argument */
372
373 void lerrsf( msg, arg )
374 const char msg[], arg[];
375         {
376         char errmsg[MAXLINE];
377
378         (void) sprintf( errmsg, msg, arg );
379         flexerror( errmsg );
380         }
381
382
383 /* line_directive_out - spit out a "#line" statement */
384
385 void line_directive_out( output_file, do_infile )
386 FILE *output_file;
387 int do_infile;
388         {
389         char directive[MAXLINE], filename[MAXLINE];
390         char *s1, *s2, *s3;
391         static char line_fmt[] = "#line %d \"%s\"\n";
392
393         if ( ! gen_line_dirs )
394                 return;
395
396         if ( (do_infile && ! infilename) || (! do_infile && ! outfilename) )
397                 /* don't know the filename to use, skip */
398                 return;
399
400         s1 = do_infile ? infilename : outfilename;
401         s2 = filename;
402         s3 = &filename[sizeof( filename ) - 2];
403
404         while ( s2 < s3 && *s1 )
405                 {
406                 if ( *s1 == '\\' )
407                         /* Escape the '\' */
408                         *s2++ = '\\';
409
410                 *s2++ = *s1++;
411                 }
412
413         *s2 = '\0';
414
415         if ( do_infile )
416                 sprintf( directive, line_fmt, linenum, filename );
417         else
418                 {
419                 if ( output_file == stdout )
420                         /* Account for the line directive itself. */
421                         ++out_linenum;
422
423                 sprintf( directive, line_fmt, out_linenum, filename );
424                 }
425
426         /* If output_file is nil then we should put the directive in
427          * the accumulated actions.
428          */
429         if ( output_file )
430                 {
431                 fputs( directive, output_file );
432                 }
433         else
434                 add_action( directive );
435         }
436
437
438 /* mark_defs1 - mark the current position in the action array as
439  *               representing where the user's section 1 definitions end
440  *               and the prolog begins
441  */
442 void mark_defs1()
443         {
444         defs1_offset = 0;
445         action_array[action_index++] = '\0';
446         action_offset = prolog_offset = action_index;
447         action_array[action_index] = '\0';
448         }
449
450
451 /* mark_prolog - mark the current position in the action array as
452  *               representing the end of the action prolog
453  */
454 void mark_prolog()
455         {
456         action_array[action_index++] = '\0';
457         action_offset = action_index;
458         action_array[action_index] = '\0';
459         }
460
461
462 /* mk2data - generate a data statement for a two-dimensional array
463  *
464  * Generates a data statement initializing the current 2-D array to "value".
465  */
466 void mk2data( value )
467 int value;
468         {
469         if ( datapos >= NUMDATAITEMS )
470                 {
471                 outc( ',' );
472                 dataflush();
473                 }
474
475         if ( datapos == 0 )
476                 /* Indent. */
477                 out( "    " );
478
479         else
480                 outc( ',' );
481
482         ++datapos;
483
484         out_dec( "%5d", value );
485         }
486
487
488 /* mkdata - generate a data statement
489  *
490  * Generates a data statement initializing the current array element to
491  * "value".
492  */
493 void mkdata( value )
494 int value;
495         {
496         if ( datapos >= NUMDATAITEMS )
497                 {
498                 outc( ',' );
499                 dataflush();
500                 }
501
502         if ( datapos == 0 )
503                 /* Indent. */
504                 out( "    " );
505         else
506                 outc( ',' );
507
508         ++datapos;
509
510         out_dec( "%5d", value );
511         }
512
513
514 /* myctoi - return the integer represented by a string of digits */
515
516 int myctoi( array )
517 char array[];
518         {
519         int val = 0;
520
521         (void) sscanf( array, "%d", &val );
522
523         return val;
524         }
525
526
527 /* myesc - return character corresponding to escape sequence */
528
529 Char myesc( array )
530 Char array[];
531         {
532         Char c, esc_char;
533
534         switch ( array[1] )
535                 {
536                 case 'b': return '\b';
537                 case 'f': return '\f';
538                 case 'n': return '\n';
539                 case 'r': return '\r';
540                 case 't': return '\t';
541
542 #if __STDC__
543                 case 'a': return '\a';
544                 case 'v': return '\v';
545 #else
546                 case 'a': return '\007';
547                 case 'v': return '\013';
548 #endif
549
550                 case '0':
551                 case '1':
552                 case '2':
553                 case '3':
554                 case '4':
555                 case '5':
556                 case '6':
557                 case '7':
558                         { /* \<octal> */
559                         int sptr = 1;
560
561                         while ( isascii( array[sptr] ) &&
562                                 isdigit( array[sptr] ) )
563                                 /* Don't increment inside loop control
564                                  * because if isdigit() is a macro it might
565                                  * expand into multiple increments ...
566                                  */
567                                 ++sptr;
568
569                         c = array[sptr];
570                         array[sptr] = '\0';
571
572                         esc_char = otoi( array + 1 );
573
574                         array[sptr] = c;
575
576                         return esc_char;
577                         }
578
579                 case 'x':
580                         { /* \x<hex> */
581                         int sptr = 2;
582
583                         while ( isascii( array[sptr] ) &&
584                                 isxdigit( (char) array[sptr] ) )
585                                 /* Don't increment inside loop control
586                                  * because if isdigit() is a macro it might
587                                  * expand into multiple increments ...
588                                  */
589                                 ++sptr;
590
591                         c = array[sptr];
592                         array[sptr] = '\0';
593
594                         esc_char = htoi( array + 2 );
595
596                         array[sptr] = c;
597
598                         return esc_char;
599                         }
600
601                 default:
602                         return array[1];
603                 }
604         }
605
606
607 /* otoi - convert an octal digit string to an integer value */
608
609 int otoi( str )
610 Char str[];
611         {
612         unsigned int result;
613
614         (void) sscanf( (char *) str, "%o", &result );
615         return result;
616         }
617
618
619 /* out - various flavors of outputing a (possibly formatted) string for the
620  *       generated scanner, keeping track of the line count.
621  */
622
623 void out( str )
624 const char str[];
625         {
626         fputs( str, stdout );
627         out_line_count( str );
628         }
629
630 void out_dec( fmt, n )
631 const char fmt[];
632 int n;
633         {
634         printf( fmt, n );
635         out_line_count( fmt );
636         }
637
638 void out_dec2( fmt, n1, n2 )
639 const char fmt[];
640 int n1, n2;
641         {
642         printf( fmt, n1, n2 );
643         out_line_count( fmt );
644         }
645
646 void out_hex( fmt, x )
647 const char fmt[];
648 unsigned int x;
649         {
650         printf( fmt, x );
651         out_line_count( fmt );
652         }
653
654 void out_line_count( str )
655 const char str[];
656         {
657         register int i;
658
659         for ( i = 0; str[i]; ++i )
660                 if ( str[i] == '\n' )
661                         ++out_linenum;
662         }
663
664 void out_str( fmt, str )
665 const char fmt[], str[];
666         {
667         printf( fmt, str );
668         out_line_count( fmt );
669         out_line_count( str );
670         }
671
672 void out_str3( fmt, s1, s2, s3 )
673 const char fmt[], s1[], s2[], s3[];
674         {
675         printf( fmt, s1, s2, s3 );
676         out_line_count( fmt );
677         out_line_count( s1 );
678         out_line_count( s2 );
679         out_line_count( s3 );
680         }
681
682 void out_str_dec( fmt, str, n )
683 const char fmt[], str[];
684 int n;
685         {
686         printf( fmt, str, n );
687         out_line_count( fmt );
688         out_line_count( str );
689         }
690
691 void outc( c )
692 int c;
693         {
694         putc( c, stdout );
695
696         if ( c == '\n' )
697                 ++out_linenum;
698         }
699
700 void outn( str )
701 const char str[];
702         {
703         puts( str );
704         out_line_count( str );
705         ++out_linenum;
706         }
707
708
709 /* readable_form - return the the human-readable form of a character
710  *
711  * The returned string is in static storage.
712  */
713
714 char *readable_form( c )
715 register int c;
716         {
717         static char rform[10];
718
719         if ( (c >= 0 && c < 32) || c >= 127 )
720                 {
721                 switch ( c )
722                         {
723                         case '\b': return "\\b";
724                         case '\f': return "\\f";
725                         case '\n': return "\\n";
726                         case '\r': return "\\r";
727                         case '\t': return "\\t";
728
729 #if __STDC__
730                         case '\a': return "\\a";
731                         case '\v': return "\\v";
732 #endif
733
734                         default:
735                                 (void) sprintf( rform, "\\%.3o",
736                                                 (unsigned int) c );
737                                 return rform;
738                         }
739                 }
740
741         else if ( c == ' ' )
742                 return "' '";
743
744         else
745                 {
746                 rform[0] = c;
747                 rform[1] = '\0';
748
749                 return rform;
750                 }
751         }
752
753
754 /* reallocate_array - increase the size of a dynamic array */
755
756 void *reallocate_array( array, size, element_size )
757 void *array;
758 int size;
759 size_t element_size;
760         {
761         register void *new_array;
762         size_t num_bytes = element_size * size;
763
764         new_array = flex_realloc( array, num_bytes );
765         if ( ! new_array )
766                 flexfatal( _( "attempt to increase array size failed" ) );
767
768         return new_array;
769         }
770
771
772 /* skelout - write out one section of the skeleton file
773  *
774  * Description
775  *    Copies skelfile or skel array to stdout until a line beginning with
776  *    "%%" or EOF is found.
777  */
778 void skelout()
779         {
780         char buf_storage[MAXLINE];
781         char *buf = buf_storage;
782         int do_copy = 1;
783
784         /* Loop pulling lines either from the skelfile, if we're using
785          * one, or from the skel[] array.
786          */
787         while ( skelfile ?
788                 (fgets( buf, MAXLINE, skelfile ) != NULL) :
789                 ((buf = (char *) skel[skel_ind++]) != 0) )
790                 { /* copy from skel array */
791                 if ( buf[0] == '%' )
792                         { /* control line */
793                         switch ( buf[1] )
794                                 {
795                                 case '%':
796                                         return;
797
798                                 case '+':
799                                         do_copy = C_plus_plus;
800                                         break;
801
802                                 case '-':
803                                         do_copy = ! C_plus_plus;
804                                         break;
805
806                                 case '*':
807                                         do_copy = 1;
808                                         break;
809
810                                 default:
811                                         flexfatal(
812                                         _( "bad line in skeleton file" ) );
813                                 }
814                         }
815
816                 else if ( do_copy )
817                         {
818                         if ( skelfile )
819                                 /* Skeleton file reads include final
820                                  * newline, skel[] array does not.
821                                  */
822                                 out( buf );
823                         else
824                                 outn( buf );
825                         }
826                 }
827         }
828
829
830 /* transition_struct_out - output a yy_trans_info structure
831  *
832  * outputs the yy_trans_info structure with the two elements, element_v and
833  * element_n.  Formats the output with spaces and carriage returns.
834  */
835
836 void transition_struct_out( element_v, element_n )
837 int element_v, element_n;
838         {
839         out_dec2( " {%4d,%4d },", element_v, element_n );
840
841         datapos += TRANS_STRUCT_PRINT_LENGTH;
842
843         if ( datapos >= 79 - TRANS_STRUCT_PRINT_LENGTH )
844                 {
845                 outc( '\n' );
846
847                 if ( ++dataline % 10 == 0 )
848                         outc( '\n' );
849
850                 datapos = 0;
851                 }
852         }
853
854
855 /* The following is only needed when building flex's parser using certain
856  * broken versions of bison.
857  */
858 void *yy_flex_xmalloc( size )
859 int size;
860         {
861         void *result = flex_alloc( (size_t) size );
862
863         if ( ! result  )
864                 flexfatal(
865                         _( "memory allocation failed in yy_flex_xmalloc()" ) );
866
867         return result;
868         }
869
870
871 /* zero_out - set a region of memory to 0
872  *
873  * Sets region_ptr[0] through region_ptr[size_in_bytes - 1] to zero.
874  */
875
876 void zero_out( region_ptr, size_in_bytes )
877 char *region_ptr;
878 size_t size_in_bytes;
879         {
880         register char *rp, *rp_end;
881
882         rp = region_ptr;
883         rp_end = region_ptr + size_in_bytes;
884
885         while ( rp < rp_end )
886                 *rp++ = 0;
887         }