1 /* Process source files and output type information.
2 Copyright (C) 2006, 2007, 2010, 2012 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
28 /* This is a simple recursive-descent parser which understands a subset of
31 Rule functions are suffixed _seq if they scan a sequence of items;
32 _opt if they may consume zero tokens; _seqopt if both are true. The
33 "consume_" prefix indicates that a sequence of tokens is parsed for
34 syntactic correctness and then thrown away. */
36 /* Simple one-token lookahead mechanism. */
44 static struct token T
;
46 /* Retrieve the code of the current token; if there is no current token,
47 get the next one from the lexer. */
53 T
.code
= yylex (&T
.value
);
59 /* Retrieve the value of the current token (if any) and mark it consumed.
60 The next call to token() will get another token from the lexer. */
61 static inline const char *
70 /* This array is indexed by the token code minus CHAR_TOKEN_OFFSET. */
71 static const char *const token_names
[] = {
82 "a param<N>_is option",
87 "a character constant",
88 "an array declarator",
89 "a C++ keyword to ignore"
92 /* This array is indexed by token code minus FIRST_TOKEN_WITH_VALUE. */
93 static const char *const token_value_format
[] = {
104 /* Produce a printable representation for a token defined by CODE and
105 VALUE. This sometimes returns pointers into malloc memory and
106 sometimes not, therefore it is unsafe to free the pointer it
107 returns, so that memory is leaked. This does not matter, as this
108 function is only used for diagnostics, and in a successful run of
109 the program there will be none. */
111 print_token (int code
, const char *value
)
113 if (code
< CHAR_TOKEN_OFFSET
)
114 return xasprintf ("'%c'", code
);
115 else if (code
< FIRST_TOKEN_WITH_VALUE
)
116 return xasprintf ("'%s'", token_names
[code
- CHAR_TOKEN_OFFSET
]);
118 return token_names
[code
- CHAR_TOKEN_OFFSET
]; /* don't quote these */
120 return xasprintf (token_value_format
[code
- FIRST_TOKEN_WITH_VALUE
],
124 /* Convenience wrapper around print_token which produces the printable
125 representation of the current token. */
126 static inline const char *
127 print_cur_token (void)
129 return print_token (T
.code
, T
.value
);
132 /* Report a parse error on the current line, with diagnostic MSG.
133 Behaves as standard printf with respect to additional arguments and
135 static void ATTRIBUTE_PRINTF_1
136 parse_error (const char *msg
, ...)
140 fprintf (stderr
, "%s:%d: parse error: ",
141 get_input_file_name (lexer_line
.file
), lexer_line
.line
);
144 vfprintf (stderr
, msg
, ap
);
147 fputc ('\n', stderr
);
152 /* If the next token does not have code T, report a parse error; otherwise
153 return the token's value. */
158 const char *v
= advance ();
161 parse_error ("expected %s, have %s",
162 print_token (t
, 0), print_token (u
, v
));
168 /* If the next token does not have one of the codes T1 or T2, report a
169 parse error; otherwise return the token's value. */
171 require2 (int t1
, int t2
)
174 const char *v
= advance ();
175 if (u
!= t1
&& u
!= t2
)
177 parse_error ("expected %s or %s, have %s",
178 print_token (t1
, 0), print_token (t2
, 0),
185 /* Near-terminals. */
187 /* C-style string constant concatenation: STRING+
188 Bare STRING should appear nowhere else in this file. */
196 s1
= require (STRING
);
199 while (token () == STRING
)
205 buf
= XRESIZEVEC (char, CONST_CAST (char *, s1
), l1
+ l2
+ 1);
206 memcpy (buf
+ l1
, s2
, l2
+ 1);
207 XDELETE (CONST_CAST (char *, s2
));
214 /* The caller has detected a template declaration that starts
215 with TMPL_NAME. Parse up to the closing '>'. This recognizes
216 simple template declarations of the form ID<ID1,ID2,...,IDn>.
217 It does not try to parse anything more sophisticated than that.
219 Returns the template declaration string "ID<ID1,ID2,...,IDn>". */
222 require_template_declaration (const char *tmpl_name
)
226 /* Recognize the opening '<'. */
228 str
= concat (tmpl_name
, "<", (char *) 0);
230 /* Read the comma-separated list of identifiers. */
231 while (token () != '>')
233 const char *id
= require2 (ID
, ',');
236 str
= concat (str
, id
, (char *) 0);
239 /* Recognize the closing '>'. */
241 str
= concat (str
, ">", (char *) 0);
247 /* typedef_name: either an ID, or a template type
248 specification of the form ID<t1,t2,...,tn>. */
253 const char *id
= require (ID
);
255 return require_template_declaration (id
);
260 /* Absorb a sequence of tokens delimited by balanced ()[]{}. */
262 consume_balanced (int opener
, int closer
)
272 consume_balanced ('(', ')');
275 consume_balanced ('[', ']');
278 consume_balanced ('{', '}');
284 if (token () != closer
)
285 parse_error ("unbalanced delimiters - expected '%c', have '%c'",
291 parse_error ("unexpected end of file within %c%c-delimited construct",
297 /* Absorb a sequence of tokens, possibly including ()[]{}-delimited
298 expressions, until we encounter an end-of-statement marker (a ';' or
299 a '}') outside any such delimiters; absorb that too. */
302 consume_until_eos (void)
312 consume_balanced ('{', '}');
316 consume_balanced ('(', ')');
320 consume_balanced ('[', ']');
326 parse_error ("unmatched '%c' while scanning for ';'", token ());
330 parse_error ("unexpected end of file while scanning for ';'");
339 /* Absorb a sequence of tokens, possibly including ()[]{}-delimited
340 expressions, until we encounter a comma or semicolon outside any
341 such delimiters; absorb that too. Returns true if the loop ended
345 consume_until_comma_or_eos ()
359 consume_balanced ('{', '}');
363 consume_balanced ('(', ')');
367 consume_balanced ('[', ']');
373 parse_error ("unmatched '%s' while scanning for ',' or ';'",
378 parse_error ("unexpected end of file while scanning for ',' or ';'");
388 /* GTY(()) option handling. */
389 static type_p
type (options_p
*optsp
, bool nested
);
391 /* Optional parenthesized string: ('(' string_seq ')')? */
393 str_optvalue_opt (options_p prev
)
395 const char *name
= advance ();
396 const char *value
= "";
400 value
= string_seq ();
403 return create_string_option (prev
, name
, value
);
406 /* absdecl: type '*'*
407 -- a vague approximation to what the C standard calls an abstract
408 declarator. The only kinds that are actually used are those that
409 are just a bare type and those that have trailing pointer-stars.
410 Further kinds should be implemented if and when they become
411 necessary. Used only within GTY(()) option values, therefore
412 further GTY(()) tags within the type are invalid. Note that the
413 return value has already been run through adjust_field_type. */
420 ty
= type (&opts
, true);
421 while (token () == '*')
423 ty
= create_pointer (ty
);
428 parse_error ("nested GTY(()) options are invalid");
430 return adjust_field_type (ty
, 0);
433 /* Type-option: '(' absdecl ')' */
435 type_optvalue (options_p prev
, const char *name
)
441 return create_type_option (prev
, name
, ty
);
444 /* Nested pointer data: '(' type '*'* ',' string_seq ',' string_seq ')' */
446 nestedptr_optvalue (options_p prev
)
449 const char *from
, *to
;
456 from
= string_seq ();
459 return create_nested_ptr_option (prev
, ty
, to
, from
);
462 /* One GTY(()) option:
464 | PTR_ALIAS type_optvalue
465 | PARAM_IS type_optvalue
466 | NESTED_PTR nestedptr_optvalue
469 option (options_p prev
)
474 return str_optvalue_opt (prev
);
478 return type_optvalue (prev
, "ptr_alias");
481 return type_optvalue (prev
, advance ());
485 return nestedptr_optvalue (prev
);
489 return create_string_option (prev
, "user", "");
492 parse_error ("expected an option keyword, have %s", print_cur_token ());
494 return create_string_option (prev
, "", "");
498 /* One comma-separated list of options. */
505 while (token () == ',')
513 /* GTY marker: 'GTY' '(' '(' option_seq? ')' ')' */
517 options_p result
= 0;
522 result
= option_seq ();
528 /* Optional GTY marker. */
532 if (token () != GTY_TOKEN
)
539 /* Declarators. The logic here is largely lifted from c-parser.c.
540 Note that we do not have to process abstract declarators, which can
541 appear only in parameter type lists or casts (but see absdecl,
542 above). Also, type qualifiers are thrown out in gengtype-lex.l so
543 we don't have to do it. */
545 /* array_and_function_declarators_opt:
547 array_and_function_declarators_opt ARRAY
548 array_and_function_declarators_opt '(' ... ')'
550 where '...' indicates stuff we ignore except insofar as grouping
551 symbols ()[]{} must balance.
553 Subroutine of direct_declarator - do not use elsewhere. */
556 array_and_function_declarators_opt (type_p ty
)
558 if (token () == ARRAY
)
560 const char *array
= advance ();
561 return create_array (array_and_function_declarators_opt (ty
), array
);
563 else if (token () == '(')
565 /* We don't need exact types for functions. */
566 consume_balanced ('(', ')');
567 array_and_function_declarators_opt (ty
);
568 return create_scalar_type ("function type");
574 static type_p
inner_declarator (type_p
, const char **, options_p
*, bool);
576 /* direct_declarator:
577 '(' inner_declarator ')'
578 '(' \epsilon ')' <-- C++ ctors/dtors
579 gtymarker_opt ID array_and_function_declarators_opt
581 Subroutine of declarator, mutually recursive with inner_declarator;
582 do not use elsewhere.
584 IN_STRUCT is true if we are called while parsing structures or classes. */
587 direct_declarator (type_p ty
, const char **namep
, options_p
*optsp
,
590 /* The first token in a direct-declarator must be an ID, a
591 GTY marker, or an open parenthesis. */
595 *optsp
= gtymarker ();
599 *namep
= require (ID
);
600 /* If the next token is '(', we are parsing a function declaration.
601 Functions are ignored by gengtype, so we return NULL. */
607 /* If the declarator starts with a '(', we have three options. We
608 are either parsing 'TYPE (*ID)' (i.e., a function pointer)
611 The latter will be a constructor iff we are inside a
612 structure or class. Otherwise, it could be a typedef, but
613 since we explicitly reject typedefs inside structures, we can
614 assume that we found a ctor and return NULL. */
616 if (in_struct
&& token () != '*')
618 /* Found a constructor. Find and consume the closing ')'. */
619 while (token () != ')')
622 /* Tell the caller to ignore this. */
625 ty
= inner_declarator (ty
, namep
, optsp
, in_struct
);
629 case IGNORABLE_CXX_KEYWORD
:
630 /* Any C++ keyword like 'operator' means that we are not looking
631 at a regular data declarator. */
635 parse_error ("expected '(', ')', 'GTY', or an identifier, have %s",
637 /* Do _not_ advance if what we have is a close squiggle brace, as
638 we will get much better error recovery that way. */
643 return array_and_function_declarators_opt (ty
);
646 /* The difference between inner_declarator and declarator is in the
647 handling of stars. Consider this declaration:
651 It declares a pointer to a function that takes no arguments and
652 returns a char*. To construct the correct type for this
653 declaration, the star outside the parentheses must be processed
654 _before_ the function type, the star inside the parentheses must
655 be processed _after_ the function type. To accomplish this,
656 declarator() creates pointers before recursing (it is actually
657 coded as a while loop), whereas inner_declarator() recurses before
658 creating pointers. */
664 Mutually recursive subroutine of direct_declarator; do not use
667 IN_STRUCT is true if we are called while parsing structures or classes. */
670 inner_declarator (type_p ty
, const char **namep
, options_p
*optsp
,
677 inner
= inner_declarator (ty
, namep
, optsp
, in_struct
);
681 return create_pointer (ty
);
684 return direct_declarator (ty
, namep
, optsp
, in_struct
);
687 /* declarator: '*'+ direct_declarator
689 This is the sole public interface to this part of the grammar.
690 Arguments are the type known so far, a pointer to where the name
691 may be stored, and a pointer to where GTY options may be stored.
693 IN_STRUCT is true when we are called to parse declarators inside
694 a structure or class.
696 Returns the final type. */
699 declarator (type_p ty
, const char **namep
, options_p
*optsp
,
700 bool in_struct
= false)
704 while (token () == '*')
707 ty
= create_pointer (ty
);
709 return direct_declarator (ty
, namep
, optsp
, in_struct
);
712 /* Types and declarations. */
714 /* Structure field(s) declaration:
717 | type declarator bitfield? ( ',' declarator bitfield? )+ ';'
720 Knows that such declarations must end with a close brace (or,
721 erroneously, at EOF).
724 struct_field_seq (void)
728 options_p opts
, dopts
;
734 ty
= type (&opts
, true);
736 if (!ty
|| token () == ':')
738 consume_until_eos ();
744 dty
= declarator (ty
, &name
, &dopts
, true);
746 /* There could be any number of weird things after the declarator,
747 notably bitfield declarations and __attribute__s. If this
748 function returns true, the last thing was a comma, so we have
749 more than one declarator paired with the current type. */
750 another
= consume_until_comma_or_eos ();
756 parse_error ("two GTY(()) options for field %s", name
);
760 f
= create_field_at (f
, dty
, name
, dopts
, &lexer_line
);
764 while (token () != '}' && token () != EOF_TOKEN
);
765 return nreverse_pairs (f
);
768 /* Return true if OPTS contain the option named STR. */
771 opts_have (options_p opts
, const char *str
)
773 for (options_p opt
= opts
; opt
; opt
= opt
->next
)
774 if (strcmp (opt
->name
, str
) == 0)
780 /* This is called type(), but what it parses (sort of) is what C calls
781 declaration-specifiers and specifier-qualifier-list:
785 | (STRUCT|UNION) ID? gtymarker? ( '{' gtymarker? struct_field_seq '}' )?
786 | ENUM ID ( '{' ... '}' )?
788 Returns a partial type; under some conditions (notably
789 "struct foo GTY((...)) thing;") it may write an options
792 NESTED is true when parsing a declaration already known to have a
793 GTY marker. In these cases, typedef and enum declarations are not
794 allowed because gengtype only understands types at the global
798 type (options_p
*optsp
, bool nested
)
806 return create_scalar_type (s
);
810 return resolve_typedef (s
, &lexer_line
);
812 case IGNORABLE_CXX_KEYWORD
:
813 /* By returning NULL here, we indicate to the caller that they
814 should ignore everything following this keyword up to the
822 /* GTY annotations follow attribute syntax
823 GTY_BEFORE_ID is for union/struct declarations
824 GTY_AFTER_ID is for variable declarations. */
831 enum typekind kind
= (token () == UNION
) ? TYPE_UNION
: TYPE_STRUCT
;
834 /* Top-level structures that are not explicitly tagged GTY(())
835 are treated as mere forward declarations. This is because
836 there are a lot of structures that we don't need to know
837 about, and some of those have C++ and macro constructs that
839 if (nested
|| token () == GTY_TOKEN
)
841 is_gty
= GTY_BEFORE_ID
;
842 opts
= gtymarker_opt ();
848 s
= xasprintf ("anonymous:%s:%d",
849 get_input_file_name (lexer_line
.file
),
852 /* Unfortunately above GTY_TOKEN check does not capture the
853 typedef struct_type GTY case. */
854 if (token () == GTY_TOKEN
)
856 is_gty
= GTY_AFTER_ID
;
857 opts
= gtymarker_opt ();
862 /* Skip over C++ inheritance specification. */
863 while (token () != '{')
869 bool is_user_gty
= opts_have (opts
, "user");
874 if (is_gty
== GTY_AFTER_ID
)
875 parse_error ("GTY must be specified before identifier");
880 fields
= struct_field_seq ();
885 /* Do not look inside user defined structures. */
887 kind
= TYPE_USER_STRUCT
;
888 consume_balanced ('{', '}');
889 return create_user_defined_type (s
, &lexer_line
);
892 return new_structure (s
, kind
, &lexer_line
, fields
, opts
);
895 else if (token () == '{')
896 consume_balanced ('{', '}');
899 return find_structure (s
, kind
);
903 /* In C++, a typedef inside a struct/class/union defines a new
904 type for that inner scope. We cannot support this in
905 gengtype because we have no concept of scoping.
907 We handle typedefs in the global scope separately (see
908 parse_file), so if we find a 'typedef', we must be inside
911 parse_error ("typedefs not supported in structures marked with "
912 "automatic GTY markers. Use GTY((user)) to mark "
922 s
= xasprintf ("anonymous:%s:%d",
923 get_input_file_name (lexer_line
.file
),
927 consume_balanced ('{', '}');
929 /* If after parsing the enum we are at the end of the statement,
930 and we are currently inside a structure, then this was an
931 enum declaration inside this scope.
933 We cannot support this for the same reason we cannot support
934 'typedef' inside structures (see the TYPEDEF handler above).
935 If this happens, emit an error and return NULL. */
936 if (nested
&& token () == ';')
938 parse_error ("enum definitions not supported in structures marked "
939 "with automatic GTY markers. Use GTY((user)) to mark "
945 return create_scalar_type (s
);
948 parse_error ("expected a type specifier, have %s", print_cur_token ());
950 return create_scalar_type ("erroneous type");
954 /* Top level constructs. */
956 /* Dispatch declarations beginning with 'typedef'. */
966 gcc_assert (token () == TYPEDEF
);
969 ty
= type (&opts
, false);
973 parse_error ("GTY((...)) cannot be applied to a typedef");
976 dty
= declarator (ty
, &name
, &opts
);
978 parse_error ("GTY((...)) cannot be applied to a typedef");
980 /* Yet another place where we could have junk (notably attributes)
981 after the declarator. */
982 another
= consume_until_comma_or_eos ();
984 do_typedef (name
, dty
, &lexer_line
);
989 /* Structure definition: type() does all the work. */
992 struct_or_union (void)
995 type (&dummy
, false);
996 /* There may be junk after the type: notably, we cannot currently
997 distinguish 'struct foo *function(prototype);' from 'struct foo;'
998 ... we could call declarator(), but it's a waste of time at
999 present. Instead, just eat whatever token is currently lookahead
1000 and go back to lexical skipping mode. */
1004 /* GC root declaration:
1005 (extern|static) gtymarker? type ID array_declarators_opt (';'|'=')
1006 If the gtymarker is not present, we ignore the rest of the declaration. */
1008 extern_or_static (void)
1010 options_p opts
, opts2
, dopts
;
1013 require2 (EXTERN
, STATIC
);
1015 if (token () != GTY_TOKEN
)
1021 opts
= gtymarker ();
1022 ty
= type (&opts2
, true); /* if we get here, it's got a GTY(()) */
1023 dty
= declarator (ty
, &name
, &dopts
);
1025 if ((opts
&& dopts
) || (opts
&& opts2
) || (opts2
&& dopts
))
1026 parse_error ("GTY((...)) specified more than once for %s", name
);
1034 note_variable (name
, adjust_field_type (dty
, opts
), opts
, &lexer_line
);
1035 require2 (';', '=');
1039 /* Parse the file FNAME for GC-relevant declarations and definitions.
1040 This is the only entry point to this file. */
1042 parse_file (const char *fname
)
1051 extern_or_static ();
1067 parse_error ("unexpected top level token, %s", print_cur_token ());
1070 lexer_toplevel_done
= 1;