1 /* $NetBSD: misc.c,v 1.5 2014/10/30 18:44:05 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 */
36 __RCSID("$NetBSD: misc.c,v 1.5 2014/10/30 18:44:05 christos Exp $");
41 #define CMD_IF_TABLES_SER "%if-tables-serialization"
42 #define CMD_TABLES_YYDMAP "%tables-yydmap"
43 #define CMD_DEFINE_YYTABLES "%define-yytables"
44 #define CMD_IF_CPP_ONLY "%if-c++-only"
45 #define CMD_IF_C_ONLY "%if-c-only"
46 #define CMD_IF_C_OR_CPP "%if-c-or-c++"
47 #define CMD_NOT_FOR_HEADER "%not-for-header"
48 #define CMD_OK_FOR_HEADER "%ok-for-header"
49 #define CMD_PUSH "%push"
50 #define CMD_POP "%pop"
51 #define CMD_IF_REENTRANT "%if-reentrant"
52 #define CMD_IF_NOT_REENTRANT "%if-not-reentrant"
53 #define CMD_IF_BISON_BRIDGE "%if-bison-bridge"
54 #define CMD_IF_NOT_BISON_BRIDGE "%if-not-bison-bridge"
55 #define CMD_ENDIF "%endif"
57 /* we allow the skeleton to push and pop. */
59 bool dc
; /**< do_copy */
61 static struct sko_state
*sko_stack
=0;
62 static int sko_len
=0,sko_sz
=0;
63 static void sko_push(bool dc
)
67 sko_stack
= (struct sko_state
*)flex_alloc(sizeof(struct sko_state
)*sko_sz
);
69 flexfatal(_("allocation of sko_stack failed"));
72 if(sko_len
>= sko_sz
){
74 sko_stack
= (struct sko_state
*)flex_realloc(sko_stack
,sizeof(struct sko_state
)*sko_sz
);
77 /* initialize to zero and push */
78 sko_stack
[sko_len
].dc
= dc
;
81 static void sko_peek(bool *dc
)
84 flex_die("peek attempt when sko stack is empty");
86 *dc
= sko_stack
[sko_len
-1].dc
;
88 static void sko_pop(bool* dc
)
93 flex_die("popped too many times in skeleton.");
96 /* Append "#define defname value\n" to the running buffer. */
97 void action_define (defname
, value
)
104 if ((int) strlen (defname
) > MAXLINE
/ 2) {
105 format_pinpoint_message (_
106 ("name \"%s\" ridiculously long"),
111 snprintf (buf
, sizeof(buf
), "#define %s %d\n", defname
, value
);
114 /* track #defines so we can undef them when we're done. */
115 cpy
= copy_string (defname
);
116 buf_append (&defs_buf
, &cpy
, 1);
121 /** Append "m4_define([[defname]],[[value]])m4_dnl\n" to the running buffer.
122 * @param defname The macro name.
123 * @param value The macro value, can be NULL, which is the same as the empty string.
125 static void action_m4_define (const char *defname
, const char * value
)
129 flexfatal ("DO NOT USE THIS FUNCTION!");
131 if ((int) strlen (defname
) > MAXLINE
/ 2) {
132 format_pinpoint_message (_
133 ("name \"%s\" ridiculously long"),
138 snprintf (buf
, sizeof(buf
), "m4_define([[%s]],[[%s]])m4_dnl\n", defname
, value
?value
:"");
143 /* Append "new_text" to the running buffer. */
144 void add_action (new_text
)
145 const char *new_text
;
147 int len
= strlen (new_text
);
149 while (len
+ action_index
>= action_size
- 10 /* slop */ ) {
150 int new_size
= action_size
* 2;
153 /* Increase just a little, to try to avoid overflow
154 * on 16-bit machines.
156 action_size
+= action_size
/ 8;
158 action_size
= new_size
;
161 reallocate_character_array (action_array
,
165 strcpy (&action_array
[action_index
], new_text
);
171 /* allocate_array - allocate memory for an integer array of the given size */
173 void *allocate_array (size
, element_size
)
178 size_t num_bytes
= element_size
* size
;
180 mem
= flex_alloc (num_bytes
);
183 ("memory allocation failed in allocate_array()"));
189 /* all_lower - true if a string is all lower-case */
195 if (!isascii ((Char
) * str
) || !islower ((Char
) * str
))
204 /* all_upper - true if a string is all upper-case */
210 if (!isascii ((Char
) * str
) || !isupper ((Char
) * str
))
219 /* intcmp - compares two integers for use by qsort. */
221 int intcmp (const void *a
, const void *b
)
223 return *(const int *) a
- *(const int *) b
;
227 /* check_char - checks a character to make sure it's within the range
228 * we're expecting. If not, generates fatal error message
236 lerrsf (_("bad character '%s' detected in check_char()"),
241 ("scanner requires -8 flag to use the character %s"),
247 /* clower - replace upper-case letter to lower-case */
252 return (Char
) ((isascii (c
) && isupper (c
)) ? tolower (c
) : c
);
256 /* copy_string - returns a dynamically allocated copy of a string */
258 char *copy_string (str
)
259 register const char *str
;
261 register const char *c1
;
267 for (c1
= str
; *c1
; ++c1
) ;
269 size
= (c1
- str
+ 1) * sizeof (char);
271 copy
= (char *) flex_alloc (size
);
274 flexfatal (_("dynamic memory failure in copy_string()"));
276 for (c2
= copy
; (*c2
++ = *str
++) != 0;) ;
282 /* copy_unsigned_string -
283 * returns a dynamically allocated copy of a (potentially) unsigned string
286 Char
*copy_unsigned_string (str
)
293 for (c
= str
; *c
; ++c
) ;
295 copy
= allocate_Character_array (c
- str
+ 1);
297 for (c
= copy
; (*c
++ = *str
++) != 0;) ;
303 /* cclcmp - compares two characters for use by qsort with '\0' sorting last. */
305 int cclcmp (const void *a
, const void *b
)
307 if (!*(const Char
*) a
)
310 if (!*(const Char
*) b
)
313 return *(const Char
*) a
- *(const Char
*) b
;
317 /* dataend - finish up a block of data declarations */
321 /* short circuit any output */
327 /* add terminator for initialization; { for vi */
335 /* dataflush - flush generated data statements */
339 /* short circuit any output */
345 if (++dataline
>= NUMDATALINES
) {
346 /* Put out a blank line so that the table is grouped into
347 * large blocks that enable the user to find elements easily.
353 /* Reset the number of characters written on the current line. */
358 /* flexerror - report an error message and terminate */
363 fprintf (stderr
, "%s: %s\n", program_name
, msg
);
368 /* flexfatal - report a fatal error message and terminate */
373 fprintf (stderr
, _("%s: fatal internal error, %s\n"),
379 /* htoi - convert a hexadecimal digit string to an integer value */
386 (void) sscanf ((char *) str
, "%x", &result
);
392 /* lerrif - report an error message formatted with one integer argument */
394 void lerrif (msg
, arg
)
398 char errmsg
[MAXLINE
];
400 snprintf (errmsg
, sizeof(errmsg
), msg
, arg
);
405 /* lerrsf - report an error message formatted with one string argument */
407 void lerrsf (msg
, arg
)
408 const char *msg
, arg
[];
410 char errmsg
[MAXLINE
];
412 snprintf (errmsg
, sizeof(errmsg
)-1, msg
, arg
);
413 errmsg
[sizeof(errmsg
)-1] = 0; /* ensure NULL termination */
418 /* lerrsf_fatal - as lerrsf, but call flexfatal */
420 void lerrsf_fatal (const char *msg
, ...)
422 char errmsg
[MAXLINE
];
426 vsnprintf (errmsg
, sizeof(errmsg
)-1, msg
, ap
);
428 errmsg
[sizeof(errmsg
)-1] = 0; /* ensure NULL termination */
433 /* line_directive_out - spit out a "#line" statement */
435 void line_directive_out (output_file
, do_infile
)
439 char directive
[MAXLINE
], filename
[MAXLINE
];
441 static const char line_fmt
[] = "#line %d \"%s\"\n";
446 s1
= do_infile
? infilename
: "M4_YY_OUTFILE_NAME";
448 if (do_infile
&& !s1
)
452 s3
= &filename
[sizeof (filename
) - 2];
454 while (s2
< s3
&& *s1
) {
465 snprintf (directive
, sizeof(directive
), line_fmt
, linenum
, filename
);
467 snprintf (directive
, sizeof(directive
), line_fmt
, 0, filename
);
470 /* If output_file is nil then we should put the directive in
471 * the accumulated actions.
474 fputs (directive
, output_file
);
477 add_action (directive
);
481 /* mark_defs1 - mark the current position in the action array as
482 * representing where the user's section 1 definitions end
483 * and the prolog begins
488 action_array
[action_index
++] = '\0';
489 action_offset
= prolog_offset
= action_index
;
490 action_array
[action_index
] = '\0';
494 /* mark_prolog - mark the current position in the action array as
495 * representing the end of the action prolog
499 action_array
[action_index
++] = '\0';
500 action_offset
= action_index
;
501 action_array
[action_index
] = '\0';
505 /* mk2data - generate a data statement for a two-dimensional array
507 * Generates a data statement initializing the current 2-D array to "value".
512 /* short circuit any output */
516 if (datapos
>= NUMDATAITEMS
) {
530 out_dec ("%5d", value
);
534 /* mkdata - generate a data statement
536 * Generates a data statement initializing the current array element to
542 /* short circuit any output */
546 if (datapos
>= NUMDATAITEMS
) {
559 out_dec ("%5d", value
);
563 /* myctoi - return the integer represented by a string of digits */
570 (void) sscanf (array
, "%d", &val
);
576 /* myesc - return character corresponding to escape sequence */
595 #if defined (__STDC__)
618 while (isascii (array
[sptr
]) &&
619 isdigit (array
[sptr
]))
620 /* Don't increment inside loop control
621 * because if isdigit() is a macro it might
622 * expand into multiple increments ...
629 esc_char
= otoi (array
+ 1);
640 while (isascii (array
[sptr
]) &&
641 isxdigit (array
[sptr
]))
642 /* Don't increment inside loop control
643 * because if isdigit() is a macro it might
644 * expand into multiple increments ...
651 esc_char
= htoi (array
+ 2);
664 /* otoi - convert an octal digit string to an integer value */
671 (void) sscanf ((char *) str
, "%o", &result
);
676 /* out - various flavors of outputing a (possibly formatted) string for the
677 * generated scanner, keeping track of the line count.
686 void out_dec (fmt
, n
)
690 fprintf (stdout
, fmt
, n
);
693 void out_dec2 (fmt
, n1
, n2
)
697 fprintf (stdout
, fmt
, n1
, n2
);
700 void out_hex (fmt
, x
)
704 fprintf (stdout
, fmt
, x
);
707 void out_str (fmt
, str
)
708 const char *fmt
, str
[];
710 fprintf (stdout
,fmt
, str
);
713 void out_str3 (fmt
, s1
, s2
, s3
)
714 const char *fmt
, s1
[], s2
[], s3
[];
716 fprintf (stdout
,fmt
, s1
, s2
, s3
);
719 void out_str_dec (fmt
, str
, n
)
720 const char *fmt
, str
[];
723 fprintf (stdout
,fmt
, str
, n
);
739 /** Print "m4_define( [[def]], [[val]])m4_dnl\n".
740 * @param def The m4 symbol to define.
741 * @param val The definition; may be NULL.
744 void out_m4_define (const char* def
, const char* val
)
746 const char * fmt
= "m4_define( [[%s]], [[%s]])m4_dnl\n";
747 fprintf(stdout
, fmt
, def
, val
?val
:"");
751 /* readable_form - return the the human-readable form of a character
753 * The returned string is in static storage.
756 char *readable_form (c
)
759 static char rform
[10];
761 if ((c
>= 0 && c
< 32) || c
>= 127) {
774 #if defined (__STDC__)
782 snprintf (rform
, sizeof(rform
), "\\%.3o", (unsigned int) c
);
799 /* reallocate_array - increase the size of a dynamic array */
801 void *reallocate_array (array
, size
, element_size
)
806 register void *new_array
;
807 size_t num_bytes
= element_size
* size
;
809 new_array
= flex_realloc (array
, num_bytes
);
811 flexfatal (_("attempt to increase array size failed"));
817 /* skelout - write out one section of the skeleton file
820 * Copies skelfile or skel array to stdout until a line beginning with
821 * "%%" or EOF is found.
825 char buf_storage
[MAXLINE
];
826 char *buf
= buf_storage
;
829 /* "reset" the state by clearing the buffer and pushing a '1' */
833 sko_push(do_copy
=true);
836 /* Loop pulling lines either from the skelfile, if we're using
837 * one, or from the skel[] array.
840 (fgets (buf
, MAXLINE
, skelfile
) != NULL
) :
841 ((buf
= (char *) skel
[skel_ind
++]) != 0)) {
846 /* copy from skel array */
847 if (buf
[0] == '%') { /* control line */
848 /* print the control line as a comment. */
849 if (ddebug
&& buf
[1] != '#') {
850 if (buf
[strlen (buf
) - 1] == '\\')
851 out_str ("/* %s */\\\n", buf
);
853 out_str ("/* %s */\n", buf
);
856 /* We've been accused of using cryptic markers in the skel.
857 * So we'll use emacs-style-hyphenated-commands.
858 * We might consider a hash if this if-else-if-else
859 * chain gets too large.
861 #define cmd_match(s) (strncmp(buf,(s),strlen(s))==0)
864 /* %% is a break point for skelout() */
867 else if (cmd_match (CMD_PUSH
)){
870 out_str("/*(state = (%s) */",do_copy
?"true":"false");
872 out_str("%s\n", buf
[strlen (buf
) - 1] =='\\' ? "\\" : "");
874 else if (cmd_match (CMD_POP
)){
877 out_str("/*(state = (%s) */",do_copy
?"true":"false");
879 out_str("%s\n", buf
[strlen (buf
) - 1] =='\\' ? "\\" : "");
881 else if (cmd_match (CMD_IF_REENTRANT
)){
883 do_copy
= reentrant
&& do_copy
;
885 else if (cmd_match (CMD_IF_NOT_REENTRANT
)){
887 do_copy
= !reentrant
&& do_copy
;
889 else if (cmd_match(CMD_IF_BISON_BRIDGE
)){
891 do_copy
= bison_bridge_lval
&& do_copy
;
893 else if (cmd_match(CMD_IF_NOT_BISON_BRIDGE
)){
895 do_copy
= !bison_bridge_lval
&& do_copy
;
897 else if (cmd_match (CMD_ENDIF
)){
900 else if (cmd_match (CMD_IF_TABLES_SER
)) {
901 do_copy
= do_copy
&& tablesext
;
903 else if (cmd_match (CMD_TABLES_YYDMAP
)) {
904 if (tablesext
&& yydmap_buf
.elts
)
905 outn ((char *) (yydmap_buf
.elts
));
907 else if (cmd_match (CMD_DEFINE_YYTABLES
)) {
908 out_str("#define YYTABLES_NAME \"%s\"\n",
909 tablesname
?tablesname
:"yytables");
911 else if (cmd_match (CMD_IF_CPP_ONLY
)) {
914 do_copy
= C_plus_plus
;
916 else if (cmd_match (CMD_IF_C_ONLY
)) {
919 do_copy
= !C_plus_plus
;
921 else if (cmd_match (CMD_IF_C_OR_CPP
)) {
922 /* %* for C and C++ */
926 else if (cmd_match (CMD_NOT_FOR_HEADER
)) {
927 /* %c begin linkage-only (non-header) code. */
930 else if (cmd_match (CMD_OK_FOR_HEADER
)) {
931 /* %e end linkage-only code. */
934 else if (buf
[1] == '#') {
935 /* %# a comment in the skel. ignore. */
938 flexfatal (_("bad line in skeleton file"));
948 /* transition_struct_out - output a yy_trans_info structure
950 * outputs the yy_trans_info structure with the two elements, element_v and
951 * element_n. Formats the output with spaces and carriage returns.
954 void transition_struct_out (element_v
, element_n
)
955 int element_v
, element_n
;
958 /* short circuit any output */
962 out_dec2 (" {%4d,%4d },", element_v
, element_n
);
964 datapos
+= TRANS_STRUCT_PRINT_LENGTH
;
966 if (datapos
>= 79 - TRANS_STRUCT_PRINT_LENGTH
) {
969 if (++dataline
% 10 == 0)
977 /* The following is only needed when building flex's parser using certain
978 * broken versions of bison.
980 void *yy_flex_xmalloc (size
)
983 void *result
= flex_alloc ((size_t) size
);
987 ("memory allocation failed in yy_flex_xmalloc()"));
993 /* zero_out - set a region of memory to 0
995 * Sets region_ptr[0] through region_ptr[size_in_bytes - 1] to zero.
998 void zero_out (region_ptr
, size_in_bytes
)
1000 size_t size_in_bytes
;
1002 register char *rp
, *rp_end
;
1005 rp_end
= region_ptr
+ size_in_bytes
;
1011 /* Remove all '\n' and '\r' characters, if any, from the end of str.
1012 * str can be any null-terminated string, or NULL.
1019 if (!str
|| !*str
) /* s is null or empty string */
1022 /* find end of string minus one */
1028 while (p
>= str
&& (*p
== '\r' || *p
== '\n'))