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