1 /* $NetBSD: misc.c,v 1.1.1.1 2009/10/26 00:26:26 christos Exp $ */
3 /* misc - miscellaneous flex routines */
5 /* Copyright (c) 1990 The Regents of the University of California. */
6 /* All rights reserved. */
8 /* This code is derived from software contributed to Berkeley by */
11 /* The United States Government has rights in this work pursuant */
12 /* to contract no. DE-AC03-76SF00098 between the United States */
13 /* Department of Energy and the University of California. */
15 /* This file is part of flex. */
17 /* Redistribution and use in source and binary forms, with or without */
18 /* modification, are permitted provided that the following conditions */
21 /* 1. Redistributions of source code must retain the above copyright */
22 /* notice, this list of conditions and the following disclaimer. */
23 /* 2. Redistributions in binary form must reproduce the above copyright */
24 /* notice, this list of conditions and the following disclaimer in the */
25 /* documentation and/or other materials provided with the distribution. */
27 /* Neither the name of the University nor the names of its contributors */
28 /* may be used to endorse or promote products derived from this software */
29 /* without specific prior written permission. */
31 /* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR */
32 /* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED */
33 /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR */
39 #define CMD_IF_TABLES_SER "%if-tables-serialization"
40 #define CMD_TABLES_YYDMAP "%tables-yydmap"
41 #define CMD_DEFINE_YYTABLES "%define-yytables"
42 #define CMD_IF_CPP_ONLY "%if-c++-only"
43 #define CMD_IF_C_ONLY "%if-c-only"
44 #define CMD_IF_C_OR_CPP "%if-c-or-c++"
45 #define CMD_NOT_FOR_HEADER "%not-for-header"
46 #define CMD_OK_FOR_HEADER "%ok-for-header"
47 #define CMD_PUSH "%push"
48 #define CMD_POP "%pop"
49 #define CMD_IF_REENTRANT "%if-reentrant"
50 #define CMD_IF_NOT_REENTRANT "%if-not-reentrant"
51 #define CMD_IF_BISON_BRIDGE "%if-bison-bridge"
52 #define CMD_IF_NOT_BISON_BRIDGE "%if-not-bison-bridge"
53 #define CMD_ENDIF "%endif"
55 /* we allow the skeleton to push and pop. */
57 bool dc
; /**< do_copy */
59 static struct sko_state
*sko_stack
=0;
60 static int sko_len
=0,sko_sz
=0;
61 static void sko_push(bool dc
)
65 sko_stack
= (struct sko_state
*)flex_alloc(sizeof(struct sko_state
)*sko_sz
);
68 if(sko_len
>= sko_sz
){
70 sko_stack
= (struct sko_state
*)flex_realloc(sko_stack
,sizeof(struct sko_state
)*sko_sz
);
73 /* initialize to zero and push */
74 sko_stack
[sko_len
].dc
= dc
;
77 static void sko_peek(bool *dc
)
80 flex_die("peek attempt when sko stack is empty");
82 *dc
= sko_stack
[sko_len
-1].dc
;
84 static void sko_pop(bool* dc
)
89 flex_die("popped too many times in skeleton.");
92 /* Append "#define defname value\n" to the running buffer. */
93 void action_define (defname
, value
)
100 if ((int) strlen (defname
) > MAXLINE
/ 2) {
101 format_pinpoint_message (_
102 ("name \"%s\" ridiculously long"),
107 snprintf (buf
, sizeof(buf
), "#define %s %d\n", defname
, value
);
110 /* track #defines so we can undef them when we're done. */
111 cpy
= copy_string (defname
);
112 buf_append (&defs_buf
, &cpy
, 1);
117 /** Append "m4_define([[defname]],[[value]])m4_dnl\n" to the running buffer.
118 * @param defname The macro name.
119 * @param value The macro value, can be NULL, which is the same as the empty string.
121 static void action_m4_define (const char *defname
, const char * value
)
125 flexfatal ("DO NOT USE THIS FUNCTION!");
127 if ((int) strlen (defname
) > MAXLINE
/ 2) {
128 format_pinpoint_message (_
129 ("name \"%s\" ridiculously long"),
134 snprintf (buf
, sizeof(buf
), "m4_define([[%s]],[[%s]])m4_dnl\n", defname
, value
?value
:"");
139 /* Append "new_text" to the running buffer. */
140 void add_action (new_text
)
141 const char *new_text
;
143 int len
= strlen (new_text
);
145 while (len
+ action_index
>= action_size
- 10 /* slop */ ) {
146 int new_size
= action_size
* 2;
149 /* Increase just a little, to try to avoid overflow
150 * on 16-bit machines.
152 action_size
+= action_size
/ 8;
154 action_size
= new_size
;
157 reallocate_character_array (action_array
,
161 strcpy (&action_array
[action_index
], new_text
);
167 /* allocate_array - allocate memory for an integer array of the given size */
169 void *allocate_array (size
, element_size
)
174 size_t num_bytes
= element_size
* size
;
176 mem
= flex_alloc (num_bytes
);
179 ("memory allocation failed in allocate_array()"));
185 /* all_lower - true if a string is all lower-case */
191 if (!isascii ((Char
)*str
) || !islower ((Char
)*str
))
200 /* all_upper - true if a string is all upper-case */
206 if (!isascii ((Char
)*str
) || !isupper ((Char
)*str
))
215 /* bubble - bubble sort an integer array in increasing order
219 * void bubble( v, n );
222 * sorts the first n elements of array v and replaces them in
226 * v - the array to be sorted
227 * n - the number of elements of 'v' to be sorted
233 register int i
, j
, k
;
235 for (i
= n
; i
> 1; --i
)
236 for (j
= 1; j
< i
; ++j
)
237 if (v
[j
] > v
[j
+ 1]) { /* compare */
238 k
= v
[j
]; /* exchange */
245 /* check_char - checks a character to make sure it's within the range
246 * we're expecting. If not, generates fatal error message
254 lerrsf (_("bad character '%s' detected in check_char()"),
259 ("scanner requires -8 flag to use the character %s"),
265 /* clower - replace upper-case letter to lower-case */
270 return (Char
) ((isascii (c
) && isupper (c
)) ? tolower (c
) : c
);
274 /* copy_string - returns a dynamically allocated copy of a string */
276 char *copy_string (str
)
277 register const char *str
;
279 register const char *c1
;
285 for (c1
= str
; *c1
; ++c1
) ;
287 size
= (c1
- str
+ 1) * sizeof (char);
289 copy
= (char *) flex_alloc (size
);
292 flexfatal (_("dynamic memory failure in copy_string()"));
294 for (c2
= copy
; (*c2
++ = *str
++) != 0;) ;
300 /* copy_unsigned_string -
301 * returns a dynamically allocated copy of a (potentially) unsigned string
304 Char
*copy_unsigned_string (str
)
311 for (c
= str
; *c
; ++c
) ;
313 copy
= allocate_Character_array (c
- str
+ 1);
315 for (c
= copy
; (*c
++ = *str
++) != 0;) ;
321 /* cshell - shell sort a character array in increasing order
326 * int n, special_case_0;
327 * cshell( v, n, special_case_0 );
330 * Does a shell sort of the first n elements of array v.
331 * If special_case_0 is true, then any element equal to 0
332 * is instead assumed to have infinite weight.
335 * v - array to be sorted
336 * n - number of elements of v to be sorted
339 void cshell (v
, n
, special_case_0
)
341 int n
, special_case_0
;
346 for (gap
= n
/ 2; gap
> 0; gap
= gap
/ 2)
347 for (i
= gap
; i
< n
; ++i
)
348 for (j
= i
- gap
; j
>= 0; j
= j
- gap
) {
351 if (special_case_0
) {
360 else if (v
[j
] <= v
[jg
])
370 /* dataend - finish up a block of data declarations */
374 /* short circuit any output */
380 /* add terminator for initialization; { for vi */
388 /* dataflush - flush generated data statements */
392 /* short circuit any output */
398 if (++dataline
>= NUMDATALINES
) {
399 /* Put out a blank line so that the table is grouped into
400 * large blocks that enable the user to find elements easily.
406 /* Reset the number of characters written on the current line. */
411 /* flexerror - report an error message and terminate */
416 fprintf (stderr
, "%s: %s\n", program_name
, msg
);
421 /* flexfatal - report a fatal error message and terminate */
426 fprintf (stderr
, _("%s: fatal internal error, %s\n"),
432 /* htoi - convert a hexadecimal digit string to an integer value */
439 (void) sscanf ((char *) str
, "%x", &result
);
445 /* lerrif - report an error message formatted with one integer argument */
447 void lerrif (msg
, arg
)
451 char errmsg
[MAXLINE
];
453 snprintf (errmsg
, sizeof(errmsg
), msg
, arg
);
458 /* lerrsf - report an error message formatted with one string argument */
460 void lerrsf (msg
, arg
)
461 const char *msg
, arg
[];
463 char errmsg
[MAXLINE
];
465 snprintf (errmsg
, sizeof(errmsg
), msg
, arg
);
470 /* line_directive_out - spit out a "#line" statement */
472 void line_directive_out (output_file
, do_infile
)
476 char directive
[MAXLINE
], filename
[MAXLINE
];
478 static const char line_fmt
[] = "#line %d \"%s\"\n";
483 s1
= do_infile
? infilename
: "M4_YY_OUTFILE_NAME";
485 if (do_infile
&& !s1
)
489 s3
= &filename
[sizeof (filename
) - 2];
491 while (s2
< s3
&& *s1
) {
502 snprintf (directive
, sizeof(directive
), line_fmt
, linenum
, filename
);
504 if (output_file
== stdout
)
505 /* Account for the line directive itself. */
508 snprintf (directive
, sizeof(directive
), line_fmt
, out_linenum
, filename
);
511 /* If output_file is nil then we should put the directive in
512 * the accumulated actions.
515 fputs (directive
, output_file
);
518 add_action (directive
);
522 /* mark_defs1 - mark the current position in the action array as
523 * representing where the user's section 1 definitions end
524 * and the prolog begins
529 action_array
[action_index
++] = '\0';
530 action_offset
= prolog_offset
= action_index
;
531 action_array
[action_index
] = '\0';
535 /* mark_prolog - mark the current position in the action array as
536 * representing the end of the action prolog
540 action_array
[action_index
++] = '\0';
541 action_offset
= action_index
;
542 action_array
[action_index
] = '\0';
546 /* mk2data - generate a data statement for a two-dimensional array
548 * Generates a data statement initializing the current 2-D array to "value".
553 /* short circuit any output */
557 if (datapos
>= NUMDATAITEMS
) {
571 out_dec ("%5d", value
);
575 /* mkdata - generate a data statement
577 * Generates a data statement initializing the current array element to
583 /* short circuit any output */
587 if (datapos
>= NUMDATAITEMS
) {
600 out_dec ("%5d", value
);
604 /* myctoi - return the integer represented by a string of digits */
611 (void) sscanf (array
, "%d", &val
);
617 /* myesc - return character corresponding to escape sequence */
636 #if defined (__STDC__)
659 while (isascii (array
[sptr
]) &&
660 isdigit (array
[sptr
]))
661 /* Don't increment inside loop control
662 * because if isdigit() is a macro it might
663 * expand into multiple increments ...
670 esc_char
= otoi (array
+ 1);
681 while (isascii (array
[sptr
]) &&
682 isxdigit ((Char
)array
[sptr
]))
683 /* Don't increment inside loop control
684 * because if isdigit() is a macro it might
685 * expand into multiple increments ...
692 esc_char
= htoi (array
+ 2);
705 /* otoi - convert an octal digit string to an integer value */
712 (void) sscanf ((char *) str
, "%o", &result
);
717 /* out - various flavors of outputing a (possibly formatted) string for the
718 * generated scanner, keeping track of the line count.
725 out_line_count (str
);
728 void out_dec (fmt
, n
)
732 fprintf (stdout
, fmt
, n
);
733 out_line_count (fmt
);
736 void out_dec2 (fmt
, n1
, n2
)
740 fprintf (stdout
, fmt
, n1
, n2
);
741 out_line_count (fmt
);
744 void out_hex (fmt
, x
)
748 fprintf (stdout
, fmt
, x
);
749 out_line_count (fmt
);
752 void out_line_count (str
)
757 for (i
= 0; str
[i
]; ++i
)
762 void out_str (fmt
, str
)
763 const char *fmt
, str
[];
765 fprintf (stdout
,fmt
, str
);
766 out_line_count (fmt
);
767 out_line_count (str
);
770 void out_str3 (fmt
, s1
, s2
, s3
)
771 const char *fmt
, s1
[], s2
[], s3
[];
773 fprintf (stdout
,fmt
, s1
, s2
, s3
);
774 out_line_count (fmt
);
780 void out_str_dec (fmt
, str
, n
)
781 const char *fmt
, str
[];
784 fprintf (stdout
,fmt
, str
, n
);
785 out_line_count (fmt
);
786 out_line_count (str
);
803 out_line_count (str
);
807 /** Print "m4_define( [[def]], [[val]])m4_dnl\n".
808 * @param def The m4 symbol to define.
809 * @param val The definition; may be NULL.
812 void out_m4_define (const char* def
, const char* val
)
814 const char * fmt
= "m4_define( [[%s]], [[%s]])m4_dnl\n";
815 fprintf(stdout
, fmt
, def
, val
?val
:"");
819 /* readable_form - return the the human-readable form of a character
821 * The returned string is in static storage.
824 char *readable_form (c
)
827 static char rform
[10];
829 if ((c
>= 0 && c
< 32) || c
>= 127) {
842 #if defined (__STDC__)
850 snprintf (rform
, sizeof(rform
), "\\%.3o", (unsigned int) c
);
867 /* reallocate_array - increase the size of a dynamic array */
869 void *reallocate_array (array
, size
, element_size
)
874 register void *new_array
;
875 size_t num_bytes
= element_size
* size
;
877 new_array
= flex_realloc (array
, num_bytes
);
879 flexfatal (_("attempt to increase array size failed"));
885 /* skelout - write out one section of the skeleton file
888 * Copies skelfile or skel array to stdout until a line beginning with
889 * "%%" or EOF is found.
893 char buf_storage
[MAXLINE
];
894 char *buf
= buf_storage
;
897 /* "reset" the state by clearing the buffer and pushing a '1' */
901 sko_push(do_copy
=true);
904 /* Loop pulling lines either from the skelfile, if we're using
905 * one, or from the skel[] array.
908 (fgets (buf
, MAXLINE
, skelfile
) != NULL
) :
909 ((buf
= (char *) skel
[skel_ind
++]) != 0)) {
914 /* copy from skel array */
915 if (buf
[0] == '%') { /* control line */
916 /* print the control line as a comment. */
917 if (ddebug
&& buf
[1] != '#') {
918 if (buf
[strlen (buf
) - 1] == '\\')
919 out_str ("/* %s */\\\n", buf
);
921 out_str ("/* %s */\n", buf
);
924 /* We've been accused of using cryptic markers in the skel.
925 * So we'll use emacs-style-hyphenated-commands.
926 * We might consider a hash if this if-else-if-else
927 * chain gets too large.
929 #define cmd_match(s) (strncmp(buf,(s),strlen(s))==0)
932 /* %% is a break point for skelout() */
935 else if (cmd_match (CMD_PUSH
)){
938 out_str("/*(state = (%s) */",do_copy
?"true":"false");
940 out_str("%s\n", buf
[strlen (buf
) - 1] =='\\' ? "\\" : "");
942 else if (cmd_match (CMD_POP
)){
945 out_str("/*(state = (%s) */",do_copy
?"true":"false");
947 out_str("%s\n", buf
[strlen (buf
) - 1] =='\\' ? "\\" : "");
949 else if (cmd_match (CMD_IF_REENTRANT
)){
951 do_copy
= reentrant
&& do_copy
;
953 else if (cmd_match (CMD_IF_NOT_REENTRANT
)){
955 do_copy
= !reentrant
&& do_copy
;
957 else if (cmd_match(CMD_IF_BISON_BRIDGE
)){
959 do_copy
= bison_bridge_lval
&& do_copy
;
961 else if (cmd_match(CMD_IF_NOT_BISON_BRIDGE
)){
963 do_copy
= !bison_bridge_lval
&& do_copy
;
965 else if (cmd_match (CMD_ENDIF
)){
968 else if (cmd_match (CMD_IF_TABLES_SER
)) {
969 do_copy
= do_copy
&& tablesext
;
971 else if (cmd_match (CMD_TABLES_YYDMAP
)) {
972 if (tablesext
&& yydmap_buf
.elts
)
973 outn ((char *) (yydmap_buf
.elts
));
975 else if (cmd_match (CMD_DEFINE_YYTABLES
)) {
976 out_str("#define YYTABLES_NAME \"%s\"\n",
977 tablesname
?tablesname
:"yytables");
979 else if (cmd_match (CMD_IF_CPP_ONLY
)) {
982 do_copy
= C_plus_plus
;
984 else if (cmd_match (CMD_IF_C_ONLY
)) {
987 do_copy
= !C_plus_plus
;
989 else if (cmd_match (CMD_IF_C_OR_CPP
)) {
990 /* %* for C and C++ */
994 else if (cmd_match (CMD_NOT_FOR_HEADER
)) {
995 /* %c begin linkage-only (non-header) code. */
998 else if (cmd_match (CMD_OK_FOR_HEADER
)) {
999 /* %e end linkage-only code. */
1002 else if (buf
[1] == '#') {
1003 /* %# a comment in the skel. ignore. */
1006 flexfatal (_("bad line in skeleton file"));
1016 /* transition_struct_out - output a yy_trans_info structure
1018 * outputs the yy_trans_info structure with the two elements, element_v and
1019 * element_n. Formats the output with spaces and carriage returns.
1022 void transition_struct_out (element_v
, element_n
)
1023 int element_v
, element_n
;
1026 /* short circuit any output */
1030 out_dec2 (" {%4d,%4d },", element_v
, element_n
);
1032 datapos
+= TRANS_STRUCT_PRINT_LENGTH
;
1034 if (datapos
>= 79 - TRANS_STRUCT_PRINT_LENGTH
) {
1037 if (++dataline
% 10 == 0)
1045 /* The following is only needed when building flex's parser using certain
1046 * broken versions of bison.
1048 void *yy_flex_xmalloc (size
)
1051 void *result
= flex_alloc ((size_t) size
);
1055 ("memory allocation failed in yy_flex_xmalloc()"));
1061 /* zero_out - set a region of memory to 0
1063 * Sets region_ptr[0] through region_ptr[size_in_bytes - 1] to zero.
1066 void zero_out (region_ptr
, size_in_bytes
)
1068 size_t size_in_bytes
;
1070 register char *rp
, *rp_end
;
1073 rp_end
= region_ptr
+ size_in_bytes
;
1079 /* Remove all '\n' and '\r' characters, if any, from the end of str.
1080 * str can be any null-terminated string, or NULL.
1087 if (!str
|| !*str
) /* s is null or empty string */
1090 /* find end of string minus one */
1096 while (p
>= str
&& (*p
== '\r' || *p
== '\n'))