1 /* $NetBSD: misc.c,v 1.3 2013/04/06 14:27:52 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 */
40 #define CMD_IF_TABLES_SER "%if-tables-serialization"
41 #define CMD_TABLES_YYDMAP "%tables-yydmap"
42 #define CMD_DEFINE_YYTABLES "%define-yytables"
43 #define CMD_IF_CPP_ONLY "%if-c++-only"
44 #define CMD_IF_C_ONLY "%if-c-only"
45 #define CMD_IF_C_OR_CPP "%if-c-or-c++"
46 #define CMD_NOT_FOR_HEADER "%not-for-header"
47 #define CMD_OK_FOR_HEADER "%ok-for-header"
48 #define CMD_PUSH "%push"
49 #define CMD_POP "%pop"
50 #define CMD_IF_REENTRANT "%if-reentrant"
51 #define CMD_IF_NOT_REENTRANT "%if-not-reentrant"
52 #define CMD_IF_BISON_BRIDGE "%if-bison-bridge"
53 #define CMD_IF_NOT_BISON_BRIDGE "%if-not-bison-bridge"
54 #define CMD_ENDIF "%endif"
56 /* we allow the skeleton to push and pop. */
58 bool dc
; /**< do_copy */
60 static struct sko_state
*sko_stack
=0;
61 static int sko_len
=0,sko_sz
=0;
62 static void sko_push(bool dc
)
66 sko_stack
= (struct sko_state
*)flex_alloc(sizeof(struct sko_state
)*sko_sz
);
68 flexfatal(_("allocation of sko_stack failed"));
71 if(sko_len
>= sko_sz
){
73 sko_stack
= (struct sko_state
*)flex_realloc(sko_stack
,sizeof(struct sko_state
)*sko_sz
);
76 /* initialize to zero and push */
77 sko_stack
[sko_len
].dc
= dc
;
80 static void sko_peek(bool *dc
)
83 flex_die("peek attempt when sko stack is empty");
85 *dc
= sko_stack
[sko_len
-1].dc
;
87 static void sko_pop(bool* dc
)
92 flex_die("popped too many times in skeleton.");
95 /* Append "#define defname value\n" to the running buffer. */
96 void action_define (defname
, value
)
103 if ((int) strlen (defname
) > MAXLINE
/ 2) {
104 format_pinpoint_message (_
105 ("name \"%s\" ridiculously long"),
110 snprintf (buf
, sizeof(buf
), "#define %s %d\n", defname
, value
);
113 /* track #defines so we can undef them when we're done. */
114 cpy
= copy_string (defname
);
115 buf_append (&defs_buf
, &cpy
, 1);
120 /** Append "m4_define([[defname]],[[value]])m4_dnl\n" to the running buffer.
121 * @param defname The macro name.
122 * @param value The macro value, can be NULL, which is the same as the empty string.
124 static void action_m4_define (const char *defname
, const char * value
)
128 flexfatal ("DO NOT USE THIS FUNCTION!");
130 if ((int) strlen (defname
) > MAXLINE
/ 2) {
131 format_pinpoint_message (_
132 ("name \"%s\" ridiculously long"),
137 snprintf (buf
, sizeof(buf
), "m4_define([[%s]],[[%s]])m4_dnl\n", defname
, value
?value
:"");
142 /* Append "new_text" to the running buffer. */
143 void add_action (new_text
)
144 const char *new_text
;
146 int len
= strlen (new_text
);
148 while (len
+ action_index
>= action_size
- 10 /* slop */ ) {
149 int new_size
= action_size
* 2;
152 /* Increase just a little, to try to avoid overflow
153 * on 16-bit machines.
155 action_size
+= action_size
/ 8;
157 action_size
= new_size
;
160 reallocate_character_array (action_array
,
164 strcpy (&action_array
[action_index
], new_text
);
170 /* allocate_array - allocate memory for an integer array of the given size */
172 void *allocate_array (size
, element_size
)
177 size_t num_bytes
= element_size
* size
;
179 mem
= flex_alloc (num_bytes
);
182 ("memory allocation failed in allocate_array()"));
188 /* all_lower - true if a string is all lower-case */
194 if (!isascii ((Char
) * str
) || !islower ((Char
) * str
))
203 /* all_upper - true if a string is all upper-case */
209 if (!isascii ((Char
) * str
) || !isupper ((Char
) * str
))
218 /* intcmp - compares two integers for use by qsort. */
220 int intcmp (const void *a
, const void *b
)
222 return *(const int *) a
- *(const int *) b
;
226 /* check_char - checks a character to make sure it's within the range
227 * we're expecting. If not, generates fatal error message
235 lerrsf (_("bad character '%s' detected in check_char()"),
240 ("scanner requires -8 flag to use the character %s"),
246 /* clower - replace upper-case letter to lower-case */
251 return (Char
) ((isascii (c
) && isupper (c
)) ? tolower (c
) : c
);
255 /* copy_string - returns a dynamically allocated copy of a string */
257 char *copy_string (str
)
258 register const char *str
;
260 register const char *c1
;
266 for (c1
= str
; *c1
; ++c1
) ;
268 size
= (c1
- str
+ 1) * sizeof (char);
270 copy
= (char *) flex_alloc (size
);
273 flexfatal (_("dynamic memory failure in copy_string()"));
275 for (c2
= copy
; (*c2
++ = *str
++) != 0;) ;
281 /* copy_unsigned_string -
282 * returns a dynamically allocated copy of a (potentially) unsigned string
285 Char
*copy_unsigned_string (str
)
292 for (c
= str
; *c
; ++c
) ;
294 copy
= allocate_Character_array (c
- str
+ 1);
296 for (c
= copy
; (*c
++ = *str
++) != 0;) ;
302 /* cclcmp - compares two characters for use by qsort with '\0' sorting last. */
304 int cclcmp (const void *a
, const void *b
)
306 if (!*(const Char
*) a
)
309 if (!*(const Char
*) b
)
312 return *(const Char
*) a
- *(const Char
*) b
;
316 /* dataend - finish up a block of data declarations */
320 /* short circuit any output */
326 /* add terminator for initialization; { for vi */
334 /* dataflush - flush generated data statements */
338 /* short circuit any output */
344 if (++dataline
>= NUMDATALINES
) {
345 /* Put out a blank line so that the table is grouped into
346 * large blocks that enable the user to find elements easily.
352 /* Reset the number of characters written on the current line. */
357 /* flexerror - report an error message and terminate */
362 fprintf (stderr
, "%s: %s\n", program_name
, msg
);
367 /* flexfatal - report a fatal error message and terminate */
372 fprintf (stderr
, _("%s: fatal internal error, %s\n"),
378 /* htoi - convert a hexadecimal digit string to an integer value */
385 (void) sscanf ((char *) str
, "%x", &result
);
391 /* lerrif - report an error message formatted with one integer argument */
393 void lerrif (msg
, arg
)
397 char errmsg
[MAXLINE
];
399 snprintf (errmsg
, sizeof(errmsg
), msg
, arg
);
404 /* lerrsf - report an error message formatted with one string argument */
406 void lerrsf (msg
, arg
)
407 const char *msg
, arg
[];
409 char errmsg
[MAXLINE
];
411 snprintf (errmsg
, sizeof(errmsg
)-1, msg
, arg
);
412 errmsg
[sizeof(errmsg
)-1] = 0; /* ensure NULL termination */
417 /* lerrsf_fatal - as lerrsf, but call flexfatal */
419 void lerrsf_fatal (const char *msg
, ...)
421 char errmsg
[MAXLINE
];
425 vsnprintf (errmsg
, sizeof(errmsg
)-1, msg
, ap
);
427 errmsg
[sizeof(errmsg
)-1] = 0; /* ensure NULL termination */
432 /* line_directive_out - spit out a "#line" statement */
434 void line_directive_out (output_file
, do_infile
)
438 char directive
[MAXLINE
], filename
[MAXLINE
];
440 static const char line_fmt
[] = "#line %d \"%s\"\n";
445 s1
= do_infile
? infilename
: "M4_YY_OUTFILE_NAME";
447 if (do_infile
&& !s1
)
451 s3
= &filename
[sizeof (filename
) - 2];
453 while (s2
< s3
&& *s1
) {
464 snprintf (directive
, sizeof(directive
), line_fmt
, linenum
, filename
);
466 snprintf (directive
, sizeof(directive
), line_fmt
, 0, filename
);
469 /* If output_file is nil then we should put the directive in
470 * the accumulated actions.
473 fputs (directive
, output_file
);
476 add_action (directive
);
480 /* mark_defs1 - mark the current position in the action array as
481 * representing where the user's section 1 definitions end
482 * and the prolog begins
487 action_array
[action_index
++] = '\0';
488 action_offset
= prolog_offset
= action_index
;
489 action_array
[action_index
] = '\0';
493 /* mark_prolog - mark the current position in the action array as
494 * representing the end of the action prolog
498 action_array
[action_index
++] = '\0';
499 action_offset
= action_index
;
500 action_array
[action_index
] = '\0';
504 /* mk2data - generate a data statement for a two-dimensional array
506 * Generates a data statement initializing the current 2-D array to "value".
511 /* short circuit any output */
515 if (datapos
>= NUMDATAITEMS
) {
529 out_dec ("%5d", value
);
533 /* mkdata - generate a data statement
535 * Generates a data statement initializing the current array element to
541 /* short circuit any output */
545 if (datapos
>= NUMDATAITEMS
) {
558 out_dec ("%5d", value
);
562 /* myctoi - return the integer represented by a string of digits */
569 (void) sscanf (array
, "%d", &val
);
575 /* myesc - return character corresponding to escape sequence */
594 #if defined (__STDC__)
617 while (isascii (array
[sptr
]) &&
618 isdigit (array
[sptr
]))
619 /* Don't increment inside loop control
620 * because if isdigit() is a macro it might
621 * expand into multiple increments ...
628 esc_char
= otoi (array
+ 1);
639 while (isascii (array
[sptr
]) &&
640 isxdigit (array
[sptr
]))
641 /* Don't increment inside loop control
642 * because if isdigit() is a macro it might
643 * expand into multiple increments ...
650 esc_char
= htoi (array
+ 2);
663 /* otoi - convert an octal digit string to an integer value */
670 (void) sscanf ((char *) str
, "%o", &result
);
675 /* out - various flavors of outputing a (possibly formatted) string for the
676 * generated scanner, keeping track of the line count.
685 void out_dec (fmt
, n
)
689 fprintf (stdout
, fmt
, n
);
692 void out_dec2 (fmt
, n1
, n2
)
696 fprintf (stdout
, fmt
, n1
, n2
);
699 void out_hex (fmt
, x
)
703 fprintf (stdout
, fmt
, x
);
706 void out_str (fmt
, str
)
707 const char *fmt
, str
[];
709 fprintf (stdout
,fmt
, str
);
712 void out_str3 (fmt
, s1
, s2
, s3
)
713 const char *fmt
, s1
[], s2
[], s3
[];
715 fprintf (stdout
,fmt
, s1
, s2
, s3
);
718 void out_str_dec (fmt
, str
, n
)
719 const char *fmt
, str
[];
722 fprintf (stdout
,fmt
, str
, n
);
738 /** Print "m4_define( [[def]], [[val]])m4_dnl\n".
739 * @param def The m4 symbol to define.
740 * @param val The definition; may be NULL.
743 void out_m4_define (const char* def
, const char* val
)
745 const char * fmt
= "m4_define( [[%s]], [[%s]])m4_dnl\n";
746 fprintf(stdout
, fmt
, def
, val
?val
:"");
750 /* readable_form - return the the human-readable form of a character
752 * The returned string is in static storage.
755 char *readable_form (c
)
758 static char rform
[10];
760 if ((c
>= 0 && c
< 32) || c
>= 127) {
773 #if defined (__STDC__)
781 snprintf (rform
, sizeof(rform
), "\\%.3o", (unsigned int) c
);
798 /* reallocate_array - increase the size of a dynamic array */
800 void *reallocate_array (array
, size
, element_size
)
805 register void *new_array
;
806 size_t num_bytes
= element_size
* size
;
808 new_array
= flex_realloc (array
, num_bytes
);
810 flexfatal (_("attempt to increase array size failed"));
816 /* skelout - write out one section of the skeleton file
819 * Copies skelfile or skel array to stdout until a line beginning with
820 * "%%" or EOF is found.
824 char buf_storage
[MAXLINE
];
825 char *buf
= buf_storage
;
828 /* "reset" the state by clearing the buffer and pushing a '1' */
832 sko_push(do_copy
=true);
835 /* Loop pulling lines either from the skelfile, if we're using
836 * one, or from the skel[] array.
839 (fgets (buf
, MAXLINE
, skelfile
) != NULL
) :
840 ((buf
= (char *) skel
[skel_ind
++]) != 0)) {
845 /* copy from skel array */
846 if (buf
[0] == '%') { /* control line */
847 /* print the control line as a comment. */
848 if (ddebug
&& buf
[1] != '#') {
849 if (buf
[strlen (buf
) - 1] == '\\')
850 out_str ("/* %s */\\\n", buf
);
852 out_str ("/* %s */\n", buf
);
855 /* We've been accused of using cryptic markers in the skel.
856 * So we'll use emacs-style-hyphenated-commands.
857 * We might consider a hash if this if-else-if-else
858 * chain gets too large.
860 #define cmd_match(s) (strncmp(buf,(s),strlen(s))==0)
863 /* %% is a break point for skelout() */
866 else if (cmd_match (CMD_PUSH
)){
869 out_str("/*(state = (%s) */",do_copy
?"true":"false");
871 out_str("%s\n", buf
[strlen (buf
) - 1] =='\\' ? "\\" : "");
873 else if (cmd_match (CMD_POP
)){
876 out_str("/*(state = (%s) */",do_copy
?"true":"false");
878 out_str("%s\n", buf
[strlen (buf
) - 1] =='\\' ? "\\" : "");
880 else if (cmd_match (CMD_IF_REENTRANT
)){
882 do_copy
= reentrant
&& do_copy
;
884 else if (cmd_match (CMD_IF_NOT_REENTRANT
)){
886 do_copy
= !reentrant
&& do_copy
;
888 else if (cmd_match(CMD_IF_BISON_BRIDGE
)){
890 do_copy
= bison_bridge_lval
&& do_copy
;
892 else if (cmd_match(CMD_IF_NOT_BISON_BRIDGE
)){
894 do_copy
= !bison_bridge_lval
&& do_copy
;
896 else if (cmd_match (CMD_ENDIF
)){
899 else if (cmd_match (CMD_IF_TABLES_SER
)) {
900 do_copy
= do_copy
&& tablesext
;
902 else if (cmd_match (CMD_TABLES_YYDMAP
)) {
903 if (tablesext
&& yydmap_buf
.elts
)
904 outn ((char *) (yydmap_buf
.elts
));
906 else if (cmd_match (CMD_DEFINE_YYTABLES
)) {
907 out_str("#define YYTABLES_NAME \"%s\"\n",
908 tablesname
?tablesname
:"yytables");
910 else if (cmd_match (CMD_IF_CPP_ONLY
)) {
913 do_copy
= C_plus_plus
;
915 else if (cmd_match (CMD_IF_C_ONLY
)) {
918 do_copy
= !C_plus_plus
;
920 else if (cmd_match (CMD_IF_C_OR_CPP
)) {
921 /* %* for C and C++ */
925 else if (cmd_match (CMD_NOT_FOR_HEADER
)) {
926 /* %c begin linkage-only (non-header) code. */
929 else if (cmd_match (CMD_OK_FOR_HEADER
)) {
930 /* %e end linkage-only code. */
933 else if (buf
[1] == '#') {
934 /* %# a comment in the skel. ignore. */
937 flexfatal (_("bad line in skeleton file"));
947 /* transition_struct_out - output a yy_trans_info structure
949 * outputs the yy_trans_info structure with the two elements, element_v and
950 * element_n. Formats the output with spaces and carriage returns.
953 void transition_struct_out (element_v
, element_n
)
954 int element_v
, element_n
;
957 /* short circuit any output */
961 out_dec2 (" {%4d,%4d },", element_v
, element_n
);
963 datapos
+= TRANS_STRUCT_PRINT_LENGTH
;
965 if (datapos
>= 79 - TRANS_STRUCT_PRINT_LENGTH
) {
968 if (++dataline
% 10 == 0)
976 /* The following is only needed when building flex's parser using certain
977 * broken versions of bison.
979 void *yy_flex_xmalloc (size
)
982 void *result
= flex_alloc ((size_t) size
);
986 ("memory allocation failed in yy_flex_xmalloc()"));
992 /* zero_out - set a region of memory to 0
994 * Sets region_ptr[0] through region_ptr[size_in_bytes - 1] to zero.
997 void zero_out (region_ptr
, size_in_bytes
)
999 size_t size_in_bytes
;
1001 register char *rp
, *rp_end
;
1004 rp_end
= region_ptr
+ size_in_bytes
;
1010 /* Remove all '\n' and '\r' characters, if any, from the end of str.
1011 * str can be any null-terminated string, or NULL.
1018 if (!str
|| !*str
) /* s is null or empty string */
1021 /* find end of string minus one */
1027 while (p
>= str
&& (*p
== '\r' || *p
== '\n'))