]> git.saurik.com Git - bison.git/blob - src/scan-gram.l
(<SC_PRE_CODE>.): Don't double-quote token names,
[bison.git] / src / scan-gram.l
1 /* Bison Grammar Scanner -*- C -*-
2
3 Copyright (C) 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
4
5 This file is part of Bison, the GNU Compiler Compiler.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
20 02110-1301 USA
21 */
22
23 %option debug nodefault nounput noyywrap never-interactive
24 %option prefix="gram_" outfile="lex.yy.c"
25
26 %{
27 #include "system.h"
28
29 #include <mbswidth.h>
30 #include <get-errno.h>
31 #include <quote.h>
32
33 #include "complain.h"
34 #include "files.h"
35 #include "getargs.h"
36 #include "gram.h"
37 #include "quotearg.h"
38 #include "reader.h"
39 #include "uniqstr.h"
40
41 #define YY_USER_INIT \
42 do \
43 { \
44 scanner_cursor.file = current_file; \
45 scanner_cursor.line = 1; \
46 scanner_cursor.column = 1; \
47 code_start = scanner_cursor; \
48 } \
49 while (0)
50
51 /* Pacify "gcc -Wmissing-prototypes" when flex 2.5.31 is used. */
52 int gram_get_lineno (void);
53 FILE *gram_get_in (void);
54 FILE *gram_get_out (void);
55 int gram_get_leng (void);
56 char *gram_get_text (void);
57 void gram_set_lineno (int);
58 void gram_set_in (FILE *);
59 void gram_set_out (FILE *);
60 int gram_get_debug (void);
61 void gram_set_debug (int);
62 int gram_lex_destroy (void);
63
64 /* Location of scanner cursor. */
65 boundary scanner_cursor;
66
67 static void adjust_location (location *, char const *, size_t);
68 #define YY_USER_ACTION adjust_location (loc, yytext, yyleng);
69
70 static size_t no_cr_read (FILE *, char *, size_t);
71 #define YY_INPUT(buf, result, size) ((result) = no_cr_read (yyin, buf, size))
72
73
74 /* OBSTACK_FOR_STRING -- Used to store all the characters that we need to
75 keep (to construct ID, STRINGS etc.). Use the following macros to
76 use it.
77
78 Use STRING_GROW to append what has just been matched, and
79 STRING_FINISH to end the string (it puts the ending 0).
80 STRING_FINISH also stores this string in LAST_STRING, which can be
81 used, and which is used by STRING_FREE to free the last string. */
82
83 static struct obstack obstack_for_string;
84
85 /* A string representing the most recently saved token. */
86 static char *last_string;
87
88
89 #define STRING_GROW \
90 obstack_grow (&obstack_for_string, yytext, yyleng)
91
92 #define STRING_FINISH \
93 do { \
94 obstack_1grow (&obstack_for_string, '\0'); \
95 last_string = obstack_finish (&obstack_for_string); \
96 } while (0)
97
98 #define STRING_FREE \
99 obstack_free (&obstack_for_string, last_string)
100
101 void
102 scanner_last_string_free (void)
103 {
104 STRING_FREE;
105 }
106
107 /* Within well-formed rules, RULE_LENGTH is the number of values in
108 the current rule so far, which says where to find `$0' with respect
109 to the top of the stack. It is not the same as the rule->length in
110 the case of mid rule actions.
111
112 Outside of well-formed rules, RULE_LENGTH has an undefined value. */
113 static int rule_length;
114
115 static void handle_dollar (int token_type, char *cp, location loc);
116 static void handle_at (int token_type, char *cp, location loc);
117 static void handle_syncline (char *args);
118 static unsigned long int scan_integer (char const *p, int base, location loc);
119 static int convert_ucn_to_byte (char const *hex_text);
120 static void unexpected_eof (boundary, char const *);
121 static void unexpected_newline (boundary, char const *);
122
123 %}
124 %x SC_COMMENT SC_LINE_COMMENT SC_YACC_COMMENT
125 %x SC_STRING SC_CHARACTER
126 %x SC_AFTER_IDENTIFIER
127 %x SC_ESCAPED_STRING SC_ESCAPED_CHARACTER
128 %x SC_PRE_CODE SC_BRACED_CODE SC_PROLOGUE SC_EPILOGUE
129
130 letter [.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_]
131 id {letter}({letter}|[0-9])*
132 directive %{letter}({letter}|[0-9]|-)*
133 int [0-9]+
134
135 /* POSIX says that a tag must be both an id and a C union member, but
136 historically almost any character is allowed in a tag. We disallow
137 NUL and newline, as this simplifies our implementation. */
138 tag [^\0\n>]+
139
140 /* Zero or more instances of backslash-newline. Following GCC, allow
141 white space between the backslash and the newline. */
142 splice (\\[ \f\t\v]*\n)*
143
144 %%
145 %{
146 /* Nesting level of the current code in braces. */
147 int braces_level IF_LINT (= 0);
148
149 /* Parent context state, when applicable. */
150 int context_state IF_LINT (= 0);
151
152 /* Token type to return, when applicable. */
153 int token_type IF_LINT (= 0);
154
155 /* Location of most recent identifier, when applicable. */
156 location id_loc IF_LINT (= empty_location);
157
158 /* Where containing code started, when applicable. Its initial
159 value is relevant only when yylex is invoked in the SC_EPILOGUE
160 start condition. */
161 boundary code_start = scanner_cursor;
162
163 /* Where containing comment or string or character literal started,
164 when applicable. */
165 boundary token_start IF_LINT (= scanner_cursor);
166 %}
167
168
169 /*-----------------------.
170 | Scanning white space. |
171 `-----------------------*/
172
173 <INITIAL,SC_AFTER_IDENTIFIER,SC_PRE_CODE>
174 {
175 /* Comments and white space. */
176 "," warn_at (*loc, _("stray `,' treated as white space"));
177 [ \f\n\t\v] |
178 "//".* ;
179 "/*" {
180 token_start = loc->start;
181 context_state = YY_START;
182 BEGIN SC_YACC_COMMENT;
183 }
184
185 /* #line directives are not documented, and may be withdrawn or
186 modified in future versions of Bison. */
187 ^"#line "{int}" \"".*"\"\n" {
188 handle_syncline (yytext + sizeof "#line " - 1);
189 }
190 }
191
192
193 /*----------------------------.
194 | Scanning Bison directives. |
195 `----------------------------*/
196 <INITIAL>
197 {
198 "%binary" return PERCENT_NONASSOC;
199 "%debug" return PERCENT_DEBUG;
200 "%default"[-_]"prec" return PERCENT_DEFAULT_PREC;
201 "%define" return PERCENT_DEFINE;
202 "%defines" return PERCENT_DEFINES;
203 "%destructor" token_type = PERCENT_DESTRUCTOR; BEGIN SC_PRE_CODE;
204 "%dprec" return PERCENT_DPREC;
205 "%error"[-_]"verbose" return PERCENT_ERROR_VERBOSE;
206 "%expect" return PERCENT_EXPECT;
207 "%expect"[-_]"rr" return PERCENT_EXPECT_RR;
208 "%file-prefix" return PERCENT_FILE_PREFIX;
209 "%fixed"[-_]"output"[-_]"files" return PERCENT_YACC;
210 "%initial-action" token_type = PERCENT_INITIAL_ACTION; BEGIN SC_PRE_CODE;
211 "%glr-parser" return PERCENT_GLR_PARSER;
212 "%left" return PERCENT_LEFT;
213 "%lex-param" token_type = PERCENT_LEX_PARAM; BEGIN SC_PRE_CODE;
214 "%locations" return PERCENT_LOCATIONS;
215 "%merge" return PERCENT_MERGE;
216 "%name"[-_]"prefix" return PERCENT_NAME_PREFIX;
217 "%no"[-_]"default"[-_]"prec" return PERCENT_NO_DEFAULT_PREC;
218 "%no"[-_]"lines" return PERCENT_NO_LINES;
219 "%nonassoc" return PERCENT_NONASSOC;
220 "%nondeterministic-parser" return PERCENT_NONDETERMINISTIC_PARSER;
221 "%nterm" return PERCENT_NTERM;
222 "%output" return PERCENT_OUTPUT;
223 "%parse-param" token_type = PERCENT_PARSE_PARAM; BEGIN SC_PRE_CODE;
224 "%prec" rule_length--; return PERCENT_PREC;
225 "%printer" token_type = PERCENT_PRINTER; BEGIN SC_PRE_CODE;
226 "%pure"[-_]"parser" return PERCENT_PURE_PARSER;
227 "%right" return PERCENT_RIGHT;
228 "%skeleton" return PERCENT_SKELETON;
229 "%start" return PERCENT_START;
230 "%term" return PERCENT_TOKEN;
231 "%token" return PERCENT_TOKEN;
232 "%token"[-_]"table" return PERCENT_TOKEN_TABLE;
233 "%type" return PERCENT_TYPE;
234 "%union" token_type = PERCENT_UNION; BEGIN SC_PRE_CODE;
235 "%verbose" return PERCENT_VERBOSE;
236 "%yacc" return PERCENT_YACC;
237
238 {directive} {
239 complain_at (*loc, _("invalid directive: %s"), quote (yytext));
240 }
241
242 "=" return EQUAL;
243 "|" rule_length = 0; return PIPE;
244 ";" return SEMICOLON;
245
246 {id} {
247 val->symbol = symbol_get (yytext, *loc);
248 id_loc = *loc;
249 rule_length++;
250 BEGIN SC_AFTER_IDENTIFIER;
251 }
252
253 {int} {
254 val->integer = scan_integer (yytext, 10, *loc);
255 return INT;
256 }
257 0[xX][0-9abcdefABCDEF]+ {
258 val->integer = scan_integer (yytext, 16, *loc);
259 return INT;
260 }
261
262 /* Characters. We don't check there is only one. */
263 "'" STRING_GROW; token_start = loc->start; BEGIN SC_ESCAPED_CHARACTER;
264
265 /* Strings. */
266 "\"" token_start = loc->start; BEGIN SC_ESCAPED_STRING;
267
268 /* Prologue. */
269 "%{" code_start = loc->start; BEGIN SC_PROLOGUE;
270
271 /* Code in between braces. */
272 "{" {
273 STRING_GROW;
274 token_type = BRACED_CODE;
275 braces_level = 0;
276 code_start = loc->start;
277 BEGIN SC_BRACED_CODE;
278 }
279
280 /* A type. */
281 "<"{tag}">" {
282 obstack_grow (&obstack_for_string, yytext + 1, yyleng - 2);
283 STRING_FINISH;
284 val->uniqstr = uniqstr_new (last_string);
285 STRING_FREE;
286 return TYPE;
287 }
288
289 "%%" {
290 static int percent_percent_count;
291 if (++percent_percent_count == 2)
292 BEGIN SC_EPILOGUE;
293 return PERCENT_PERCENT;
294 }
295
296 . {
297 complain_at (*loc, _("invalid character: %s"), quote (yytext));
298 }
299
300 <<EOF>> {
301 loc->start = loc->end = scanner_cursor;
302 yyterminate ();
303 }
304 }
305
306
307 /*-----------------------------------------------------------------.
308 | Scanning after an identifier, checking whether a colon is next. |
309 `-----------------------------------------------------------------*/
310
311 <SC_AFTER_IDENTIFIER>
312 {
313 ":" {
314 rule_length = 0;
315 *loc = id_loc;
316 BEGIN INITIAL;
317 return ID_COLON;
318 }
319 . {
320 scanner_cursor.column -= mbsnwidth (yytext, yyleng, 0);
321 yyless (0);
322 *loc = id_loc;
323 BEGIN INITIAL;
324 return ID;
325 }
326 <<EOF>> {
327 *loc = id_loc;
328 BEGIN INITIAL;
329 return ID;
330 }
331 }
332
333
334 /*---------------------------------------------------------------.
335 | Scanning a Yacc comment. The initial `/ *' is already eaten. |
336 `---------------------------------------------------------------*/
337
338 <SC_YACC_COMMENT>
339 {
340 "*/" BEGIN context_state;
341 .|\n ;
342 <<EOF>> unexpected_eof (token_start, "*/"); BEGIN context_state;
343 }
344
345
346 /*------------------------------------------------------------.
347 | Scanning a C comment. The initial `/ *' is already eaten. |
348 `------------------------------------------------------------*/
349
350 <SC_COMMENT>
351 {
352 "*"{splice}"/" STRING_GROW; BEGIN context_state;
353 <<EOF>> unexpected_eof (token_start, "*/"); BEGIN context_state;
354 }
355
356
357 /*--------------------------------------------------------------.
358 | Scanning a line comment. The initial `//' is already eaten. |
359 `--------------------------------------------------------------*/
360
361 <SC_LINE_COMMENT>
362 {
363 "\n" STRING_GROW; BEGIN context_state;
364 {splice} STRING_GROW;
365 <<EOF>> BEGIN context_state;
366 }
367
368
369 /*------------------------------------------------.
370 | Scanning a Bison string, including its escapes. |
371 | The initial quote is already eaten. |
372 `------------------------------------------------*/
373
374 <SC_ESCAPED_STRING>
375 {
376 "\"" {
377 STRING_FINISH;
378 loc->start = token_start;
379 val->chars = last_string;
380 rule_length++;
381 BEGIN INITIAL;
382 return STRING;
383 }
384 \n unexpected_newline (token_start, "\""); BEGIN INITIAL;
385 <<EOF>> unexpected_eof (token_start, "\""); BEGIN INITIAL;
386 }
387
388 /*----------------------------------------------------------.
389 | Scanning a Bison character literal, decoding its escapes. |
390 | The initial quote is already eaten. |
391 `----------------------------------------------------------*/
392
393 <SC_ESCAPED_CHARACTER>
394 {
395 "'" {
396 unsigned char last_string_1;
397 STRING_GROW;
398 STRING_FINISH;
399 loc->start = token_start;
400 val->symbol = symbol_get (quotearg_style (escape_quoting_style,
401 last_string),
402 *loc);
403 symbol_class_set (val->symbol, token_sym, *loc);
404 last_string_1 = last_string[1];
405 symbol_user_token_number_set (val->symbol, last_string_1, *loc);
406 STRING_FREE;
407 rule_length++;
408 BEGIN INITIAL;
409 return ID;
410 }
411 \n unexpected_newline (token_start, "'"); BEGIN INITIAL;
412 <<EOF>> unexpected_eof (token_start, "'"); BEGIN INITIAL;
413 }
414
415 <SC_ESCAPED_CHARACTER,SC_ESCAPED_STRING>
416 {
417 \0 complain_at (*loc, _("invalid null character"));
418 }
419
420
421 /*----------------------------.
422 | Decode escaped characters. |
423 `----------------------------*/
424
425 <SC_ESCAPED_STRING,SC_ESCAPED_CHARACTER>
426 {
427 \\[0-7]{1,3} {
428 unsigned long int c = strtoul (yytext + 1, 0, 8);
429 if (UCHAR_MAX < c)
430 complain_at (*loc, _("invalid escape sequence: %s"), quote (yytext));
431 else if (! c)
432 complain_at (*loc, _("invalid null character: %s"), quote (yytext));
433 else
434 obstack_1grow (&obstack_for_string, c);
435 }
436
437 \\x[0-9abcdefABCDEF]+ {
438 unsigned long int c;
439 set_errno (0);
440 c = strtoul (yytext + 2, 0, 16);
441 if (UCHAR_MAX < c || get_errno ())
442 complain_at (*loc, _("invalid escape sequence: %s"), quote (yytext));
443 else if (! c)
444 complain_at (*loc, _("invalid null character: %s"), quote (yytext));
445 else
446 obstack_1grow (&obstack_for_string, c);
447 }
448
449 \\a obstack_1grow (&obstack_for_string, '\a');
450 \\b obstack_1grow (&obstack_for_string, '\b');
451 \\f obstack_1grow (&obstack_for_string, '\f');
452 \\n obstack_1grow (&obstack_for_string, '\n');
453 \\r obstack_1grow (&obstack_for_string, '\r');
454 \\t obstack_1grow (&obstack_for_string, '\t');
455 \\v obstack_1grow (&obstack_for_string, '\v');
456
457 /* \\[\"\'?\\] would be shorter, but it confuses xgettext. */
458 \\("\""|"'"|"?"|"\\") obstack_1grow (&obstack_for_string, yytext[1]);
459
460 \\(u|U[0-9abcdefABCDEF]{4})[0-9abcdefABCDEF]{4} {
461 int c = convert_ucn_to_byte (yytext);
462 if (c < 0)
463 complain_at (*loc, _("invalid escape sequence: %s"), quote (yytext));
464 else if (! c)
465 complain_at (*loc, _("invalid null character: %s"), quote (yytext));
466 else
467 obstack_1grow (&obstack_for_string, c);
468 }
469 \\(.|\n) {
470 complain_at (*loc, _("unrecognized escape sequence: %s"), quote (yytext));
471 STRING_GROW;
472 }
473 }
474
475 /*--------------------------------------------.
476 | Scanning user-code characters and strings. |
477 `--------------------------------------------*/
478
479 <SC_CHARACTER,SC_STRING>
480 {
481 {splice}|\\{splice}[^\n$@\[\]] STRING_GROW;
482 }
483
484 <SC_CHARACTER>
485 {
486 "'" STRING_GROW; BEGIN context_state;
487 \n unexpected_newline (token_start, "'"); BEGIN context_state;
488 <<EOF>> unexpected_eof (token_start, "'"); BEGIN context_state;
489 }
490
491 <SC_STRING>
492 {
493 "\"" STRING_GROW; BEGIN context_state;
494 \n unexpected_newline (token_start, "\""); BEGIN context_state;
495 <<EOF>> unexpected_eof (token_start, "\""); BEGIN context_state;
496 }
497
498
499 /*---------------------------------------------------.
500 | Strings, comments etc. can be found in user code. |
501 `---------------------------------------------------*/
502
503 <SC_BRACED_CODE,SC_PROLOGUE,SC_EPILOGUE>
504 {
505 "'" {
506 STRING_GROW;
507 context_state = YY_START;
508 token_start = loc->start;
509 BEGIN SC_CHARACTER;
510 }
511 "\"" {
512 STRING_GROW;
513 context_state = YY_START;
514 token_start = loc->start;
515 BEGIN SC_STRING;
516 }
517 "/"{splice}"*" {
518 STRING_GROW;
519 context_state = YY_START;
520 token_start = loc->start;
521 BEGIN SC_COMMENT;
522 }
523 "/"{splice}"/" {
524 STRING_GROW;
525 context_state = YY_START;
526 BEGIN SC_LINE_COMMENT;
527 }
528 }
529
530
531 /*---------------------------------------------------------------.
532 | Scanning after %union etc., possibly followed by white space. |
533 | For %union only, allow arbitrary C code to appear before the |
534 | following brace, as an extension to POSIX. |
535 `---------------------------------------------------------------*/
536
537 <SC_PRE_CODE>
538 {
539 . {
540 bool valid = yytext[0] == '{' || token_type == PERCENT_UNION;
541 scanner_cursor.column -= mbsnwidth (yytext, yyleng, 0);
542 yyless (0);
543
544 if (valid)
545 {
546 braces_level = -1;
547 code_start = loc->start;
548 BEGIN SC_BRACED_CODE;
549 }
550 else
551 {
552 complain_at (*loc, _("missing `{' in %s"),
553 token_name (token_type));
554 obstack_sgrow (&obstack_for_string, "{}");
555 STRING_FINISH;
556 val->chars = last_string;
557 BEGIN INITIAL;
558 return token_type;
559 }
560 }
561
562 <<EOF>> unexpected_eof (scanner_cursor, "{}"); BEGIN INITIAL;
563 }
564
565
566 /*---------------------------------------------------------------.
567 | Scanning some code in braces (%union and actions). The initial |
568 | "{" is already eaten. |
569 `---------------------------------------------------------------*/
570
571 <SC_BRACED_CODE>
572 {
573 "{"|"<"{splice}"%" STRING_GROW; braces_level++;
574 "%"{splice}">" STRING_GROW; braces_level--;
575 "}" {
576 bool outer_brace = --braces_level < 0;
577
578 /* As an undocumented Bison extension, append `;' before the last
579 brace in braced code, so that the user code can omit trailing
580 `;'. But do not append `;' if emulating Yacc, since Yacc does
581 not append one.
582
583 FIXME: Bison should warn if a semicolon seems to be necessary
584 here, and should omit the semicolon if it seems unnecessary
585 (e.g., after ';', '{', or '}', each followed by comments or
586 white space). Such a warning shouldn't depend on --yacc; it
587 should depend on a new --pedantic option, which would cause
588 Bison to warn if it detects an extension to POSIX. --pedantic
589 should also diagnose other Bison extensions like %yacc.
590 Perhaps there should also be a GCC-style --pedantic-errors
591 option, so that such warnings are diagnosed as errors. */
592 if (outer_brace && token_type == BRACED_CODE && ! yacc_flag)
593 obstack_1grow (&obstack_for_string, ';');
594
595 obstack_1grow (&obstack_for_string, '}');
596
597 if (outer_brace)
598 {
599 STRING_FINISH;
600 rule_length++;
601 loc->start = code_start;
602 val->chars = last_string;
603 BEGIN INITIAL;
604 return token_type;
605 }
606 }
607
608 /* Tokenize `<<%' correctly (as `<<' `%') rather than incorrrectly
609 (as `<' `<%'). */
610 "<"{splice}"<" STRING_GROW;
611
612 "$"("<"{tag}">")?(-?[0-9]+|"$") handle_dollar (token_type, yytext, *loc);
613 "@"(-?[0-9]+|"$") handle_at (token_type, yytext, *loc);
614
615 <<EOF>> unexpected_eof (code_start, "}"); BEGIN INITIAL;
616 }
617
618
619 /*--------------------------------------------------------------.
620 | Scanning some prologue: from "%{" (already scanned) to "%}". |
621 `--------------------------------------------------------------*/
622
623 <SC_PROLOGUE>
624 {
625 "%}" {
626 STRING_FINISH;
627 loc->start = code_start;
628 val->chars = last_string;
629 BEGIN INITIAL;
630 return PROLOGUE;
631 }
632
633 <<EOF>> unexpected_eof (code_start, "%}"); BEGIN INITIAL;
634 }
635
636
637 /*---------------------------------------------------------------.
638 | Scanning the epilogue (everything after the second "%%", which |
639 | has already been eaten). |
640 `---------------------------------------------------------------*/
641
642 <SC_EPILOGUE>
643 {
644 <<EOF>> {
645 STRING_FINISH;
646 loc->start = code_start;
647 val->chars = last_string;
648 BEGIN INITIAL;
649 return EPILOGUE;
650 }
651 }
652
653
654 /*-----------------------------------------.
655 | Escape M4 quoting characters in C code. |
656 `-----------------------------------------*/
657
658 <SC_COMMENT,SC_LINE_COMMENT,SC_STRING,SC_CHARACTER,SC_BRACED_CODE,SC_PROLOGUE,SC_EPILOGUE>
659 {
660 \$ obstack_sgrow (&obstack_for_string, "$][");
661 \@ obstack_sgrow (&obstack_for_string, "@@");
662 \[ obstack_sgrow (&obstack_for_string, "@{");
663 \] obstack_sgrow (&obstack_for_string, "@}");
664 }
665
666
667 /*-----------------------------------------------------.
668 | By default, grow the string obstack with the input. |
669 `-----------------------------------------------------*/
670
671 <SC_COMMENT,SC_LINE_COMMENT,SC_BRACED_CODE,SC_PROLOGUE,SC_EPILOGUE,SC_STRING,SC_CHARACTER,SC_ESCAPED_STRING,SC_ESCAPED_CHARACTER>. |
672 <SC_COMMENT,SC_LINE_COMMENT,SC_BRACED_CODE,SC_PROLOGUE,SC_EPILOGUE>\n STRING_GROW;
673
674 %%
675
676 /* Keeps track of the maximum number of semantic values to the left of
677 a handle (those referenced by $0, $-1, etc.) are required by the
678 semantic actions of this grammar. */
679 int max_left_semantic_context = 0;
680
681 /* Set *LOC and adjust scanner cursor to account for token TOKEN of
682 size SIZE. */
683
684 static void
685 adjust_location (location *loc, char const *token, size_t size)
686 {
687 int line = scanner_cursor.line;
688 int column = scanner_cursor.column;
689 char const *p0 = token;
690 char const *p = token;
691 char const *lim = token + size;
692
693 loc->start = scanner_cursor;
694
695 for (p = token; p < lim; p++)
696 switch (*p)
697 {
698 case '\n':
699 line++;
700 column = 1;
701 p0 = p + 1;
702 break;
703
704 case '\t':
705 column += mbsnwidth (p0, p - p0, 0);
706 column += 8 - ((column - 1) & 7);
707 p0 = p + 1;
708 break;
709 }
710
711 scanner_cursor.line = line;
712 scanner_cursor.column = column + mbsnwidth (p0, p - p0, 0);
713
714 loc->end = scanner_cursor;
715 }
716
717
718 /* Read bytes from FP into buffer BUF of size SIZE. Return the
719 number of bytes read. Remove '\r' from input, treating \r\n
720 and isolated \r as \n. */
721
722 static size_t
723 no_cr_read (FILE *fp, char *buf, size_t size)
724 {
725 size_t bytes_read = fread (buf, 1, size, fp);
726 if (bytes_read)
727 {
728 char *w = memchr (buf, '\r', bytes_read);
729 if (w)
730 {
731 char const *r = ++w;
732 char const *lim = buf + bytes_read;
733
734 for (;;)
735 {
736 /* Found an '\r'. Treat it like '\n', but ignore any
737 '\n' that immediately follows. */
738 w[-1] = '\n';
739 if (r == lim)
740 {
741 int ch = getc (fp);
742 if (ch != '\n' && ungetc (ch, fp) != ch)
743 break;
744 }
745 else if (*r == '\n')
746 r++;
747
748 /* Copy until the next '\r'. */
749 do
750 {
751 if (r == lim)
752 return w - buf;
753 }
754 while ((*w++ = *r++) != '\r');
755 }
756
757 return w - buf;
758 }
759 }
760
761 return bytes_read;
762 }
763
764
765 /*------------------------------------------------------------------.
766 | TEXT is pointing to a wannabee semantic value (i.e., a `$'). |
767 | |
768 | Possible inputs: $[<TYPENAME>]($|integer) |
769 | |
770 | Output to OBSTACK_FOR_STRING a reference to this semantic value. |
771 `------------------------------------------------------------------*/
772
773 static inline bool
774 handle_action_dollar (char *text, location loc)
775 {
776 const char *type_name = NULL;
777 char *cp = text + 1;
778
779 if (! current_rule)
780 return false;
781
782 /* Get the type name if explicit. */
783 if (*cp == '<')
784 {
785 type_name = ++cp;
786 while (*cp != '>')
787 ++cp;
788 *cp = '\0';
789 ++cp;
790 }
791
792 if (*cp == '$')
793 {
794 if (!type_name)
795 type_name = symbol_list_n_type_name_get (current_rule, loc, 0);
796 if (!type_name && typed)
797 complain_at (loc, _("$$ of `%s' has no declared type"),
798 current_rule->sym->tag);
799 if (!type_name)
800 type_name = "";
801 obstack_fgrow1 (&obstack_for_string,
802 "]b4_lhs_value([%s])[", type_name);
803 }
804 else
805 {
806 long int num;
807 set_errno (0);
808 num = strtol (cp, 0, 10);
809
810 if (INT_MIN <= num && num <= rule_length && ! get_errno ())
811 {
812 int n = num;
813 if (1-n > max_left_semantic_context)
814 max_left_semantic_context = 1-n;
815 if (!type_name && n > 0)
816 type_name = symbol_list_n_type_name_get (current_rule, loc, n);
817 if (!type_name && typed)
818 complain_at (loc, _("$%d of `%s' has no declared type"),
819 n, current_rule->sym->tag);
820 if (!type_name)
821 type_name = "";
822 obstack_fgrow3 (&obstack_for_string,
823 "]b4_rhs_value(%d, %d, [%s])[",
824 rule_length, n, type_name);
825 }
826 else
827 complain_at (loc, _("integer out of range: %s"), quote (text));
828 }
829
830 return true;
831 }
832
833
834 /*----------------------------------------------------------------.
835 | Map `$?' onto the proper M4 symbol, depending on its TOKEN_TYPE |
836 | (are we in an action?). |
837 `----------------------------------------------------------------*/
838
839 static void
840 handle_dollar (int token_type, char *text, location loc)
841 {
842 switch (token_type)
843 {
844 case BRACED_CODE:
845 if (handle_action_dollar (text, loc))
846 return;
847 break;
848
849 case PERCENT_DESTRUCTOR:
850 case PERCENT_INITIAL_ACTION:
851 case PERCENT_PRINTER:
852 if (text[1] == '$')
853 {
854 obstack_sgrow (&obstack_for_string, "]b4_dollar_dollar[");
855 return;
856 }
857 break;
858
859 default:
860 break;
861 }
862
863 complain_at (loc, _("invalid value: %s"), quote (text));
864 }
865
866
867 /*------------------------------------------------------.
868 | TEXT is a location token (i.e., a `@...'). Output to |
869 | OBSTACK_FOR_STRING a reference to this location. |
870 `------------------------------------------------------*/
871
872 static inline bool
873 handle_action_at (char *text, location loc)
874 {
875 char *cp = text + 1;
876 locations_flag = true;
877
878 if (! current_rule)
879 return false;
880
881 if (*cp == '$')
882 obstack_sgrow (&obstack_for_string, "]b4_lhs_location[");
883 else
884 {
885 long int num;
886 set_errno (0);
887 num = strtol (cp, 0, 10);
888
889 if (INT_MIN <= num && num <= rule_length && ! get_errno ())
890 {
891 int n = num;
892 obstack_fgrow2 (&obstack_for_string, "]b4_rhs_location(%d, %d)[",
893 rule_length, n);
894 }
895 else
896 complain_at (loc, _("integer out of range: %s"), quote (text));
897 }
898
899 return true;
900 }
901
902
903 /*----------------------------------------------------------------.
904 | Map `@?' onto the proper M4 symbol, depending on its TOKEN_TYPE |
905 | (are we in an action?). |
906 `----------------------------------------------------------------*/
907
908 static void
909 handle_at (int token_type, char *text, location loc)
910 {
911 switch (token_type)
912 {
913 case BRACED_CODE:
914 handle_action_at (text, loc);
915 return;
916
917 case PERCENT_INITIAL_ACTION:
918 case PERCENT_DESTRUCTOR:
919 case PERCENT_PRINTER:
920 if (text[1] == '$')
921 {
922 obstack_sgrow (&obstack_for_string, "]b4_at_dollar[");
923 return;
924 }
925 break;
926
927 default:
928 break;
929 }
930
931 complain_at (loc, _("invalid value: %s"), quote (text));
932 }
933
934
935 /*------------------------------------------------------.
936 | Scan NUMBER for a base-BASE integer at location LOC. |
937 `------------------------------------------------------*/
938
939 static unsigned long int
940 scan_integer (char const *number, int base, location loc)
941 {
942 unsigned long int num;
943 set_errno (0);
944 num = strtoul (number, 0, base);
945 if (INT_MAX < num || get_errno ())
946 {
947 complain_at (loc, _("integer out of range: %s"), quote (number));
948 num = INT_MAX;
949 }
950 return num;
951 }
952
953
954 /*------------------------------------------------------------------.
955 | Convert universal character name UCN to a single-byte character, |
956 | and return that character. Return -1 if UCN does not correspond |
957 | to a single-byte character. |
958 `------------------------------------------------------------------*/
959
960 static int
961 convert_ucn_to_byte (char const *ucn)
962 {
963 unsigned long int code = strtoul (ucn + 2, 0, 16);
964
965 /* FIXME: Currently we assume Unicode-compatible unibyte characters
966 on ASCII hosts (i.e., Latin-1 on hosts with 8-bit bytes). On
967 non-ASCII hosts we support only the portable C character set.
968 These limitations should be removed once we add support for
969 multibyte characters. */
970
971 if (UCHAR_MAX < code)
972 return -1;
973
974 #if ! ('$' == 0x24 && '@' == 0x40 && '`' == 0x60 && '~' == 0x7e)
975 {
976 /* A non-ASCII host. Use CODE to index into a table of the C
977 basic execution character set, which is guaranteed to exist on
978 all Standard C platforms. This table also includes '$', '@',
979 and '`', which are not in the basic execution character set but
980 which are unibyte characters on all the platforms that we know
981 about. */
982 static signed char const table[] =
983 {
984 '\0', -1, -1, -1, -1, -1, -1, '\a',
985 '\b', '\t', '\n', '\v', '\f', '\r', -1, -1,
986 -1, -1, -1, -1, -1, -1, -1, -1,
987 -1, -1, -1, -1, -1, -1, -1, -1,
988 ' ', '!', '"', '#', '$', '%', '&', '\'',
989 '(', ')', '*', '+', ',', '-', '.', '/',
990 '0', '1', '2', '3', '4', '5', '6', '7',
991 '8', '9', ':', ';', '<', '=', '>', '?',
992 '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
993 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
994 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
995 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
996 '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
997 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
998 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
999 'x', 'y', 'z', '{', '|', '}', '~'
1000 };
1001
1002 code = code < sizeof table ? table[code] : -1;
1003 }
1004 #endif
1005
1006 return code;
1007 }
1008
1009
1010 /*----------------------------------------------------------------.
1011 | Handle `#line INT "FILE"'. ARGS has already skipped `#line '. |
1012 `----------------------------------------------------------------*/
1013
1014 static void
1015 handle_syncline (char *args)
1016 {
1017 int lineno = strtol (args, &args, 10);
1018 const char *file = NULL;
1019 file = strchr (args, '"') + 1;
1020 *strchr (file, '"') = 0;
1021 scanner_cursor.file = current_file = uniqstr_new (file);
1022 scanner_cursor.line = lineno;
1023 scanner_cursor.column = 1;
1024 }
1025
1026
1027 /*----------------------------------------------------------------.
1028 | For a token or comment starting at START, report message MSGID, |
1029 | which should say that an end marker was found before |
1030 | the expected TOKEN_END. |
1031 `----------------------------------------------------------------*/
1032
1033 static void
1034 unexpected_end (boundary start, char const *msgid, char const *token_end)
1035 {
1036 location loc;
1037 loc.start = start;
1038 loc.end = scanner_cursor;
1039 complain_at (loc, _(msgid), token_end);
1040 }
1041
1042
1043 /*------------------------------------------------------------------------.
1044 | Report an unexpected EOF in a token or comment starting at START. |
1045 | An end of file was encountered and the expected TOKEN_END was missing. |
1046 `------------------------------------------------------------------------*/
1047
1048 static void
1049 unexpected_eof (boundary start, char const *token_end)
1050 {
1051 unexpected_end (start, N_("missing `%s' at end of file"), token_end);
1052 }
1053
1054
1055 /*----------------------------------------.
1056 | Likewise, but for unexpected newlines. |
1057 `----------------------------------------*/
1058
1059 static void
1060 unexpected_newline (boundary start, char const *token_end)
1061 {
1062 unexpected_end (start, N_("missing `%s' at end of line"), token_end);
1063 }
1064
1065
1066 /*-------------------------.
1067 | Initialize the scanner. |
1068 `-------------------------*/
1069
1070 void
1071 scanner_initialize (void)
1072 {
1073 obstack_init (&obstack_for_string);
1074 }
1075
1076
1077 /*-----------------------------------------------.
1078 | Free all the memory allocated to the scanner. |
1079 `-----------------------------------------------*/
1080
1081 void
1082 scanner_free (void)
1083 {
1084 obstack_free (&obstack_for_string, 0);
1085 /* Reclaim Flex's buffers. */
1086 yy_delete_buffer (YY_CURRENT_BUFFER);
1087 }