2 * This file is part of cparser.
3 * Copyright (C) 2007-2008 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
37 #include "lang_features.h"
38 #include "walk_statements.h"
40 #include "adt/bitfiddle.h"
41 #include "adt/error.h"
42 #include "adt/array.h"
44 //#define PRINT_TOKENS
45 #define MAX_LOOKAHEAD 1
50 entity_namespace_t namespc;
53 typedef struct argument_list_t argument_list_t;
54 struct argument_list_t {
56 argument_list_t *next;
59 typedef struct gnu_attribute_t gnu_attribute_t;
60 struct gnu_attribute_t {
61 gnu_attribute_kind_t kind; /**< The kind of the GNU attribute. */
62 gnu_attribute_t *next;
63 bool invalid; /**< Set if this attribute had argument errors, */
64 bool has_arguments; /**< True, if this attribute has arguments. */
69 long argument; /**< Single argument. */
70 argument_list_t *arguments; /**< List of argument expressions. */
74 typedef struct declaration_specifiers_t declaration_specifiers_t;
75 struct declaration_specifiers_t {
76 source_position_t source_position;
77 storage_class_t storage_class;
78 unsigned char alignment; /**< Alignment, 0 if not set. */
80 bool thread_local : 1; /**< GCC __thread */
82 decl_modifiers_t modifiers; /**< declaration modifiers */
83 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
84 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
85 symbol_t *get_property_sym; /**< the name of the get property if set. */
86 symbol_t *put_property_sym; /**< the name of the put property if set. */
91 * An environment for parsing initializers (and compound literals).
93 typedef struct parse_initializer_env_t {
94 type_t *type; /**< the type of the initializer. In case of an
95 array type with unspecified size this gets
96 adjusted to the actual size. */
97 entity_t *entity; /**< the variable that is initialized if any */
98 bool must_be_constant;
99 } parse_initializer_env_t;
101 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
103 /** The current token. */
104 static token_t token;
105 /** The lookahead ring-buffer. */
106 static token_t lookahead_buffer[MAX_LOOKAHEAD];
107 /** Position of the next token in the lookahead buffer. */
108 static size_t lookahead_bufpos;
109 static stack_entry_t *environment_stack = NULL;
110 static stack_entry_t *label_stack = NULL;
111 static scope_t *file_scope = NULL;
112 static scope_t *current_scope = NULL;
113 /** Point to the current function declaration if inside a function. */
114 static function_t *current_function = NULL;
115 static entity_t *current_init_decl = NULL;
116 static switch_statement_t *current_switch = NULL;
117 static statement_t *current_loop = NULL;
118 static statement_t *current_parent = NULL;
119 static ms_try_statement_t *current_try = NULL;
120 static linkage_kind_t current_linkage = LINKAGE_INVALID;
121 static goto_statement_t *goto_first = NULL;
122 static goto_statement_t **goto_anchor = NULL;
123 static label_statement_t *label_first = NULL;
124 static label_statement_t **label_anchor = NULL;
125 /** current translation unit. */
126 static translation_unit_t *unit = NULL;
127 /** true if we are in a type property context (evaluation only for type. */
128 static bool in_type_prop = false;
129 /** true in we are in a __extension__ context. */
130 static bool in_gcc_extension = false;
131 static struct obstack temp_obst;
132 static entity_t *anonymous_entity;
133 static declaration_t **incomplete_arrays;
136 #define PUSH_PARENT(stmt) \
137 statement_t *const prev_parent = current_parent; \
138 ((void)(current_parent = (stmt)))
139 #define POP_PARENT ((void)(current_parent = prev_parent))
141 /** special symbol used for anonymous entities. */
142 static const symbol_t *sym_anonymous = NULL;
144 /* symbols for Microsoft extended-decl-modifier */
145 static const symbol_t *sym_align = NULL;
146 static const symbol_t *sym_allocate = NULL;
147 static const symbol_t *sym_dllimport = NULL;
148 static const symbol_t *sym_dllexport = NULL;
149 static const symbol_t *sym_naked = NULL;
150 static const symbol_t *sym_noinline = NULL;
151 static const symbol_t *sym_returns_twice = NULL;
152 static const symbol_t *sym_noreturn = NULL;
153 static const symbol_t *sym_nothrow = NULL;
154 static const symbol_t *sym_novtable = NULL;
155 static const symbol_t *sym_property = NULL;
156 static const symbol_t *sym_get = NULL;
157 static const symbol_t *sym_put = NULL;
158 static const symbol_t *sym_selectany = NULL;
159 static const symbol_t *sym_thread = NULL;
160 static const symbol_t *sym_uuid = NULL;
161 static const symbol_t *sym_deprecated = NULL;
162 static const symbol_t *sym_restrict = NULL;
163 static const symbol_t *sym_noalias = NULL;
165 /** The token anchor set */
166 static unsigned char token_anchor_set[T_LAST_TOKEN];
168 /** The current source position. */
169 #define HERE (&token.source_position)
171 /** true if we are in GCC mode. */
172 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
174 static statement_t *parse_compound_statement(bool inside_expression_statement);
175 static statement_t *parse_statement(void);
177 static expression_t *parse_sub_expression(precedence_t);
178 static expression_t *parse_expression(void);
179 static type_t *parse_typename(void);
180 static void parse_externals(void);
181 static void parse_external(void);
183 static void parse_compound_type_entries(compound_t *compound_declaration);
185 static void check_call_argument(type_t *expected_type,
186 call_argument_t *argument, unsigned pos);
188 typedef enum declarator_flags_t {
190 DECL_MAY_BE_ABSTRACT = 1U << 0,
191 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
192 DECL_IS_PARAMETER = 1U << 2
193 } declarator_flags_t;
195 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
196 declarator_flags_t flags);
198 static entity_t *record_entity(entity_t *entity, bool is_definition);
200 static void semantic_comparison(binary_expression_t *expression);
202 static void create_gnu_builtins(void);
203 static void create_microsoft_intrinsics(void);
205 #define STORAGE_CLASSES \
206 STORAGE_CLASSES_NO_EXTERN \
209 #define STORAGE_CLASSES_NO_EXTERN \
216 #define TYPE_QUALIFIERS \
221 case T__forceinline: \
222 case T___attribute__:
224 #define COMPLEX_SPECIFIERS \
226 #define IMAGINARY_SPECIFIERS \
229 #define TYPE_SPECIFIERS \
231 case T___builtin_va_list: \
251 #define DECLARATION_START \
256 #define DECLARATION_START_NO_EXTERN \
257 STORAGE_CLASSES_NO_EXTERN \
261 #define TYPENAME_START \
265 #define EXPRESSION_START \
274 case T_CHARACTER_CONSTANT: \
275 case T_FLOATINGPOINT: \
279 case T_STRING_LITERAL: \
280 case T_WIDE_CHARACTER_CONSTANT: \
281 case T_WIDE_STRING_LITERAL: \
282 case T___FUNCDNAME__: \
283 case T___FUNCSIG__: \
284 case T___FUNCTION__: \
285 case T___PRETTY_FUNCTION__: \
286 case T___alignof__: \
287 case T___builtin_classify_type: \
288 case T___builtin_constant_p: \
289 case T___builtin_isgreater: \
290 case T___builtin_isgreaterequal: \
291 case T___builtin_isless: \
292 case T___builtin_islessequal: \
293 case T___builtin_islessgreater: \
294 case T___builtin_isunordered: \
295 case T___builtin_offsetof: \
296 case T___builtin_va_arg: \
297 case T___builtin_va_start: \
298 case T___builtin_va_copy: \
309 * Allocate an AST node with given size and
310 * initialize all fields with zero.
312 static void *allocate_ast_zero(size_t size)
314 void *res = allocate_ast(size);
315 memset(res, 0, size);
320 * Returns the size of an entity node.
322 * @param kind the entity kind
324 static size_t get_entity_struct_size(entity_kind_t kind)
326 static const size_t sizes[] = {
327 [ENTITY_VARIABLE] = sizeof(variable_t),
328 [ENTITY_PARAMETER] = sizeof(parameter_t),
329 [ENTITY_COMPOUND_MEMBER] = sizeof(compound_member_t),
330 [ENTITY_FUNCTION] = sizeof(function_t),
331 [ENTITY_TYPEDEF] = sizeof(typedef_t),
332 [ENTITY_STRUCT] = sizeof(compound_t),
333 [ENTITY_UNION] = sizeof(compound_t),
334 [ENTITY_ENUM] = sizeof(enum_t),
335 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
336 [ENTITY_LABEL] = sizeof(label_t),
337 [ENTITY_LOCAL_LABEL] = sizeof(label_t),
338 [ENTITY_NAMESPACE] = sizeof(namespace_t)
340 assert(kind < lengthof(sizes));
341 assert(sizes[kind] != 0);
346 * Allocate an entity of given kind and initialize all
349 * @param kind the kind of the entity to allocate
351 static entity_t *allocate_entity_zero(entity_kind_t kind)
353 size_t size = get_entity_struct_size(kind);
354 entity_t *entity = allocate_ast_zero(size);
360 * Returns the size of a statement node.
362 * @param kind the statement kind
364 static size_t get_statement_struct_size(statement_kind_t kind)
366 static const size_t sizes[] = {
367 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
368 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
369 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
370 [STATEMENT_RETURN] = sizeof(return_statement_t),
371 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
372 [STATEMENT_IF] = sizeof(if_statement_t),
373 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
374 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
375 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
376 [STATEMENT_BREAK] = sizeof(statement_base_t),
377 [STATEMENT_GOTO] = sizeof(goto_statement_t),
378 [STATEMENT_LABEL] = sizeof(label_statement_t),
379 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
380 [STATEMENT_WHILE] = sizeof(while_statement_t),
381 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
382 [STATEMENT_FOR] = sizeof(for_statement_t),
383 [STATEMENT_ASM] = sizeof(asm_statement_t),
384 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
385 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
387 assert(kind < lengthof(sizes));
388 assert(sizes[kind] != 0);
393 * Returns the size of an expression node.
395 * @param kind the expression kind
397 static size_t get_expression_struct_size(expression_kind_t kind)
399 static const size_t sizes[] = {
400 [EXPR_INVALID] = sizeof(expression_base_t),
401 [EXPR_REFERENCE] = sizeof(reference_expression_t),
402 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
403 [EXPR_CONST] = sizeof(const_expression_t),
404 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
405 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
406 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
407 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
408 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
409 [EXPR_CALL] = sizeof(call_expression_t),
410 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
411 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
412 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
413 [EXPR_SELECT] = sizeof(select_expression_t),
414 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
415 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
416 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
417 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
418 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
419 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
420 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
421 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
422 [EXPR_VA_START] = sizeof(va_start_expression_t),
423 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
424 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
425 [EXPR_STATEMENT] = sizeof(statement_expression_t),
426 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
428 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
429 return sizes[EXPR_UNARY_FIRST];
431 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
432 return sizes[EXPR_BINARY_FIRST];
434 assert(kind < lengthof(sizes));
435 assert(sizes[kind] != 0);
440 * Allocate a statement node of given kind and initialize all
441 * fields with zero. Sets its source position to the position
442 * of the current token.
444 static statement_t *allocate_statement_zero(statement_kind_t kind)
446 size_t size = get_statement_struct_size(kind);
447 statement_t *res = allocate_ast_zero(size);
449 res->base.kind = kind;
450 res->base.parent = current_parent;
451 res->base.source_position = token.source_position;
456 * Allocate an expression node of given kind and initialize all
459 * @param kind the kind of the expression to allocate
461 static expression_t *allocate_expression_zero(expression_kind_t kind)
463 size_t size = get_expression_struct_size(kind);
464 expression_t *res = allocate_ast_zero(size);
466 res->base.kind = kind;
467 res->base.type = type_error_type;
468 res->base.source_position = token.source_position;
473 * Creates a new invalid expression at the source position
474 * of the current token.
476 static expression_t *create_invalid_expression(void)
478 return allocate_expression_zero(EXPR_INVALID);
482 * Creates a new invalid statement.
484 static statement_t *create_invalid_statement(void)
486 return allocate_statement_zero(STATEMENT_INVALID);
490 * Allocate a new empty statement.
492 static statement_t *create_empty_statement(void)
494 return allocate_statement_zero(STATEMENT_EMPTY);
498 * Returns the size of a type node.
500 * @param kind the type kind
502 static size_t get_type_struct_size(type_kind_t kind)
504 static const size_t sizes[] = {
505 [TYPE_ATOMIC] = sizeof(atomic_type_t),
506 [TYPE_COMPLEX] = sizeof(complex_type_t),
507 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
508 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
509 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
510 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
511 [TYPE_ENUM] = sizeof(enum_type_t),
512 [TYPE_FUNCTION] = sizeof(function_type_t),
513 [TYPE_POINTER] = sizeof(pointer_type_t),
514 [TYPE_ARRAY] = sizeof(array_type_t),
515 [TYPE_BUILTIN] = sizeof(builtin_type_t),
516 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
517 [TYPE_TYPEOF] = sizeof(typeof_type_t),
519 assert(lengthof(sizes) == (int)TYPE_TYPEOF + 1);
520 assert(kind <= TYPE_TYPEOF);
521 assert(sizes[kind] != 0);
526 * Allocate a type node of given kind and initialize all
529 * @param kind type kind to allocate
531 static type_t *allocate_type_zero(type_kind_t kind)
533 size_t size = get_type_struct_size(kind);
534 type_t *res = obstack_alloc(type_obst, size);
535 memset(res, 0, size);
536 res->base.kind = kind;
541 static function_parameter_t *allocate_parameter(type_t *const type)
543 function_parameter_t *const param = obstack_alloc(type_obst, sizeof(*param));
544 memset(param, 0, sizeof(*param));
550 * Returns the size of an initializer node.
552 * @param kind the initializer kind
554 static size_t get_initializer_size(initializer_kind_t kind)
556 static const size_t sizes[] = {
557 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
558 [INITIALIZER_STRING] = sizeof(initializer_string_t),
559 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
560 [INITIALIZER_LIST] = sizeof(initializer_list_t),
561 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
563 assert(kind < lengthof(sizes));
564 assert(sizes[kind] != 0);
569 * Allocate an initializer node of given kind and initialize all
572 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
574 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
581 * Returns the index of the top element of the environment stack.
583 static size_t environment_top(void)
585 return ARR_LEN(environment_stack);
589 * Returns the index of the top element of the global label stack.
591 static size_t label_top(void)
593 return ARR_LEN(label_stack);
597 * Return the next token.
599 static inline void next_token(void)
601 token = lookahead_buffer[lookahead_bufpos];
602 lookahead_buffer[lookahead_bufpos] = lexer_token;
605 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
608 print_token(stderr, &token);
609 fprintf(stderr, "\n");
614 * Return the next token with a given lookahead.
616 static inline const token_t *look_ahead(size_t num)
618 assert(0 < num && num <= MAX_LOOKAHEAD);
619 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
620 return &lookahead_buffer[pos];
624 * Adds a token type to the token type anchor set (a multi-set).
626 static void add_anchor_token(int token_type)
628 assert(0 <= token_type && token_type < T_LAST_TOKEN);
629 ++token_anchor_set[token_type];
633 * Set the number of tokens types of the given type
634 * to zero and return the old count.
636 static int save_and_reset_anchor_state(int token_type)
638 assert(0 <= token_type && token_type < T_LAST_TOKEN);
639 int count = token_anchor_set[token_type];
640 token_anchor_set[token_type] = 0;
645 * Restore the number of token types to the given count.
647 static void restore_anchor_state(int token_type, int count)
649 assert(0 <= token_type && token_type < T_LAST_TOKEN);
650 token_anchor_set[token_type] = count;
654 * Remove a token type from the token type anchor set (a multi-set).
656 static void rem_anchor_token(int token_type)
658 assert(0 <= token_type && token_type < T_LAST_TOKEN);
659 assert(token_anchor_set[token_type] != 0);
660 --token_anchor_set[token_type];
664 * Return true if the token type of the current token is
667 static bool at_anchor(void)
671 return token_anchor_set[token.type];
675 * Eat tokens until a matching token type is found.
677 static void eat_until_matching_token(int type)
681 case '(': end_token = ')'; break;
682 case '{': end_token = '}'; break;
683 case '[': end_token = ']'; break;
684 default: end_token = type; break;
687 unsigned parenthesis_count = 0;
688 unsigned brace_count = 0;
689 unsigned bracket_count = 0;
690 while (token.type != end_token ||
691 parenthesis_count != 0 ||
693 bracket_count != 0) {
694 switch (token.type) {
696 case '(': ++parenthesis_count; break;
697 case '{': ++brace_count; break;
698 case '[': ++bracket_count; break;
701 if (parenthesis_count > 0)
711 if (bracket_count > 0)
714 if (token.type == end_token &&
715 parenthesis_count == 0 &&
729 * Eat input tokens until an anchor is found.
731 static void eat_until_anchor(void)
733 while (token_anchor_set[token.type] == 0) {
734 if (token.type == '(' || token.type == '{' || token.type == '[')
735 eat_until_matching_token(token.type);
741 * Eat a whole block from input tokens.
743 static void eat_block(void)
745 eat_until_matching_token('{');
746 if (token.type == '}')
750 #define eat(token_type) (assert(token.type == (token_type)), next_token())
753 * Report a parse error because an expected token was not found.
756 #if defined __GNUC__ && __GNUC__ >= 4
757 __attribute__((sentinel))
759 void parse_error_expected(const char *message, ...)
761 if (message != NULL) {
762 errorf(HERE, "%s", message);
765 va_start(ap, message);
766 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
771 * Report an incompatible type.
773 static void type_error_incompatible(const char *msg,
774 const source_position_t *source_position, type_t *type1, type_t *type2)
776 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
781 * Expect the current token is the expected token.
782 * If not, generate an error, eat the current statement,
783 * and goto the end_error label.
785 #define expect(expected, error_label) \
787 if (UNLIKELY(token.type != (expected))) { \
788 parse_error_expected(NULL, (expected), NULL); \
789 add_anchor_token(expected); \
790 eat_until_anchor(); \
791 if (token.type == expected) \
793 rem_anchor_token(expected); \
800 * Push a given scope on the scope stack and make it the
803 static scope_t *scope_push(scope_t *new_scope)
805 if (current_scope != NULL) {
806 new_scope->depth = current_scope->depth + 1;
809 scope_t *old_scope = current_scope;
810 current_scope = new_scope;
815 * Pop the current scope from the scope stack.
817 static void scope_pop(scope_t *old_scope)
819 current_scope = old_scope;
823 * Search an entity by its symbol in a given namespace.
825 static entity_t *get_entity(const symbol_t *const symbol,
826 namespace_tag_t namespc)
828 entity_t *entity = symbol->entity;
829 for (; entity != NULL; entity = entity->base.symbol_next) {
830 if (entity->base.namespc == namespc)
838 * pushs an entity on the environment stack and links the corresponding symbol
841 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
843 symbol_t *symbol = entity->base.symbol;
844 entity_namespace_t namespc = entity->base.namespc;
845 assert(namespc != NAMESPACE_INVALID);
847 /* replace/add entity into entity list of the symbol */
850 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
855 /* replace an entry? */
856 if (iter->base.namespc == namespc) {
857 entity->base.symbol_next = iter->base.symbol_next;
863 /* remember old declaration */
865 entry.symbol = symbol;
866 entry.old_entity = iter;
867 entry.namespc = namespc;
868 ARR_APP1(stack_entry_t, *stack_ptr, entry);
872 * Push an entity on the environment stack.
874 static void environment_push(entity_t *entity)
876 assert(entity->base.source_position.input_name != NULL);
877 assert(entity->base.parent_scope != NULL);
878 stack_push(&environment_stack, entity);
882 * Push a declaration on the global label stack.
884 * @param declaration the declaration
886 static void label_push(entity_t *label)
888 /* we abuse the parameters scope as parent for the labels */
889 label->base.parent_scope = ¤t_function->parameters;
890 stack_push(&label_stack, label);
894 * pops symbols from the environment stack until @p new_top is the top element
896 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
898 stack_entry_t *stack = *stack_ptr;
899 size_t top = ARR_LEN(stack);
902 assert(new_top <= top);
906 for (i = top; i > new_top; --i) {
907 stack_entry_t *entry = &stack[i - 1];
909 entity_t *old_entity = entry->old_entity;
910 symbol_t *symbol = entry->symbol;
911 entity_namespace_t namespc = entry->namespc;
913 /* replace with old_entity/remove */
916 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
918 assert(iter != NULL);
919 /* replace an entry? */
920 if (iter->base.namespc == namespc)
924 /* restore definition from outer scopes (if there was one) */
925 if (old_entity != NULL) {
926 old_entity->base.symbol_next = iter->base.symbol_next;
927 *anchor = old_entity;
929 /* remove entry from list */
930 *anchor = iter->base.symbol_next;
934 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
938 * Pop all entries from the environment stack until the new_top
941 * @param new_top the new stack top
943 static void environment_pop_to(size_t new_top)
945 stack_pop_to(&environment_stack, new_top);
949 * Pop all entries from the global label stack until the new_top
952 * @param new_top the new stack top
954 static void label_pop_to(size_t new_top)
956 stack_pop_to(&label_stack, new_top);
959 static int get_akind_rank(atomic_type_kind_t akind)
965 * Return the type rank for an atomic type.
967 static int get_rank(const type_t *type)
969 assert(!is_typeref(type));
970 if (type->kind == TYPE_ENUM)
971 return get_akind_rank(type->enumt.akind);
973 assert(type->kind == TYPE_ATOMIC);
974 return get_akind_rank(type->atomic.akind);
978 * Do integer promotion for a given type.
980 * @param type the type to promote
981 * @return the promoted type
983 static type_t *promote_integer(type_t *type)
985 if (type->kind == TYPE_BITFIELD)
986 type = type->bitfield.base_type;
988 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
995 * Create a cast expression.
997 * @param expression the expression to cast
998 * @param dest_type the destination type
1000 static expression_t *create_cast_expression(expression_t *expression,
1003 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
1005 cast->unary.value = expression;
1006 cast->base.type = dest_type;
1012 * Check if a given expression represents a null pointer constant.
1014 * @param expression the expression to check
1016 static bool is_null_pointer_constant(const expression_t *expression)
1018 /* skip void* cast */
1019 if (expression->kind == EXPR_UNARY_CAST ||
1020 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
1021 type_t *const type = skip_typeref(expression->base.type);
1022 if (types_compatible(type, type_void_ptr))
1023 expression = expression->unary.value;
1026 type_t *const type = skip_typeref(expression->base.type);
1028 is_type_integer(type) &&
1029 is_constant_expression(expression) &&
1030 fold_constant(expression) == 0;
1034 * Create an implicit cast expression.
1036 * @param expression the expression to cast
1037 * @param dest_type the destination type
1039 static expression_t *create_implicit_cast(expression_t *expression,
1042 type_t *const source_type = expression->base.type;
1044 if (source_type == dest_type)
1047 return create_cast_expression(expression, dest_type);
1050 typedef enum assign_error_t {
1052 ASSIGN_ERROR_INCOMPATIBLE,
1053 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1054 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1055 ASSIGN_WARNING_POINTER_FROM_INT,
1056 ASSIGN_WARNING_INT_FROM_POINTER
1059 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1060 const expression_t *const right,
1061 const char *context,
1062 const source_position_t *source_position)
1064 type_t *const orig_type_right = right->base.type;
1065 type_t *const type_left = skip_typeref(orig_type_left);
1066 type_t *const type_right = skip_typeref(orig_type_right);
1069 case ASSIGN_SUCCESS:
1071 case ASSIGN_ERROR_INCOMPATIBLE:
1072 errorf(source_position,
1073 "destination type '%T' in %s is incompatible with type '%T'",
1074 orig_type_left, context, orig_type_right);
1077 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1078 if (warning.other) {
1079 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1080 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1082 /* the left type has all qualifiers from the right type */
1083 unsigned missing_qualifiers
1084 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1085 warningf(source_position,
1086 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1087 orig_type_left, context, orig_type_right, missing_qualifiers);
1092 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1093 if (warning.other) {
1094 warningf(source_position,
1095 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1096 orig_type_left, context, right, orig_type_right);
1100 case ASSIGN_WARNING_POINTER_FROM_INT:
1101 if (warning.other) {
1102 warningf(source_position,
1103 "%s makes pointer '%T' from integer '%T' without a cast",
1104 context, orig_type_left, orig_type_right);
1108 case ASSIGN_WARNING_INT_FROM_POINTER:
1109 if (warning.other) {
1110 warningf(source_position,
1111 "%s makes integer '%T' from pointer '%T' without a cast",
1112 context, orig_type_left, orig_type_right);
1117 panic("invalid error value");
1121 /** Implements the rules from §6.5.16.1 */
1122 static assign_error_t semantic_assign(type_t *orig_type_left,
1123 const expression_t *const right)
1125 type_t *const orig_type_right = right->base.type;
1126 type_t *const type_left = skip_typeref(orig_type_left);
1127 type_t *const type_right = skip_typeref(orig_type_right);
1129 if (is_type_pointer(type_left)) {
1130 if (is_null_pointer_constant(right)) {
1131 return ASSIGN_SUCCESS;
1132 } else if (is_type_pointer(type_right)) {
1133 type_t *points_to_left
1134 = skip_typeref(type_left->pointer.points_to);
1135 type_t *points_to_right
1136 = skip_typeref(type_right->pointer.points_to);
1137 assign_error_t res = ASSIGN_SUCCESS;
1139 /* the left type has all qualifiers from the right type */
1140 unsigned missing_qualifiers
1141 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1142 if (missing_qualifiers != 0) {
1143 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1146 points_to_left = get_unqualified_type(points_to_left);
1147 points_to_right = get_unqualified_type(points_to_right);
1149 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1152 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1153 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1154 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1157 if (!types_compatible(points_to_left, points_to_right)) {
1158 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1162 } else if (is_type_integer(type_right)) {
1163 return ASSIGN_WARNING_POINTER_FROM_INT;
1165 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1166 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1167 && is_type_pointer(type_right))) {
1168 return ASSIGN_SUCCESS;
1169 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1170 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1171 type_t *const unqual_type_left = get_unqualified_type(type_left);
1172 type_t *const unqual_type_right = get_unqualified_type(type_right);
1173 if (types_compatible(unqual_type_left, unqual_type_right)) {
1174 return ASSIGN_SUCCESS;
1176 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1177 return ASSIGN_WARNING_INT_FROM_POINTER;
1180 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1181 return ASSIGN_SUCCESS;
1183 return ASSIGN_ERROR_INCOMPATIBLE;
1186 static expression_t *parse_constant_expression(void)
1188 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1190 if (!is_constant_expression(result)) {
1191 errorf(&result->base.source_position,
1192 "expression '%E' is not constant", result);
1198 static expression_t *parse_assignment_expression(void)
1200 return parse_sub_expression(PREC_ASSIGNMENT);
1203 static string_t parse_string_literals(void)
1205 assert(token.type == T_STRING_LITERAL);
1206 string_t result = token.v.string;
1210 while (token.type == T_STRING_LITERAL) {
1211 result = concat_strings(&result, &token.v.string);
1218 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1219 [GNU_AK_CONST] = "const",
1220 [GNU_AK_VOLATILE] = "volatile",
1221 [GNU_AK_CDECL] = "cdecl",
1222 [GNU_AK_STDCALL] = "stdcall",
1223 [GNU_AK_FASTCALL] = "fastcall",
1224 [GNU_AK_DEPRECATED] = "deprecated",
1225 [GNU_AK_NOINLINE] = "noinline",
1226 [GNU_AK_RETURNS_TWICE] = "returns_twice",
1227 [GNU_AK_NORETURN] = "noreturn",
1228 [GNU_AK_NAKED] = "naked",
1229 [GNU_AK_PURE] = "pure",
1230 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1231 [GNU_AK_MALLOC] = "malloc",
1232 [GNU_AK_WEAK] = "weak",
1233 [GNU_AK_CONSTRUCTOR] = "constructor",
1234 [GNU_AK_DESTRUCTOR] = "destructor",
1235 [GNU_AK_NOTHROW] = "nothrow",
1236 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1237 [GNU_AK_COMMON] = "common",
1238 [GNU_AK_NOCOMMON] = "nocommon",
1239 [GNU_AK_PACKED] = "packed",
1240 [GNU_AK_SHARED] = "shared",
1241 [GNU_AK_NOTSHARED] = "notshared",
1242 [GNU_AK_USED] = "used",
1243 [GNU_AK_UNUSED] = "unused",
1244 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1245 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1246 [GNU_AK_LONGCALL] = "longcall",
1247 [GNU_AK_SHORTCALL] = "shortcall",
1248 [GNU_AK_LONG_CALL] = "long_call",
1249 [GNU_AK_SHORT_CALL] = "short_call",
1250 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1251 [GNU_AK_INTERRUPT] = "interrupt",
1252 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1253 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1254 [GNU_AK_NESTING] = "nesting",
1255 [GNU_AK_NEAR] = "near",
1256 [GNU_AK_FAR] = "far",
1257 [GNU_AK_SIGNAL] = "signal",
1258 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1259 [GNU_AK_TINY_DATA] = "tiny_data",
1260 [GNU_AK_SAVEALL] = "saveall",
1261 [GNU_AK_FLATTEN] = "flatten",
1262 [GNU_AK_SSEREGPARM] = "sseregparm",
1263 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1264 [GNU_AK_RETURN_TWICE] = "return_twice",
1265 [GNU_AK_MAY_ALIAS] = "may_alias",
1266 [GNU_AK_MS_STRUCT] = "ms_struct",
1267 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1268 [GNU_AK_DLLIMPORT] = "dllimport",
1269 [GNU_AK_DLLEXPORT] = "dllexport",
1270 [GNU_AK_ALIGNED] = "aligned",
1271 [GNU_AK_ALIAS] = "alias",
1272 [GNU_AK_SECTION] = "section",
1273 [GNU_AK_FORMAT] = "format",
1274 [GNU_AK_FORMAT_ARG] = "format_arg",
1275 [GNU_AK_WEAKREF] = "weakref",
1276 [GNU_AK_NONNULL] = "nonnull",
1277 [GNU_AK_TLS_MODEL] = "tls_model",
1278 [GNU_AK_VISIBILITY] = "visibility",
1279 [GNU_AK_REGPARM] = "regparm",
1280 [GNU_AK_MODE] = "mode",
1281 [GNU_AK_MODEL] = "model",
1282 [GNU_AK_TRAP_EXIT] = "trap_exit",
1283 [GNU_AK_SP_SWITCH] = "sp_switch",
1284 [GNU_AK_SENTINEL] = "sentinel"
1288 * compare two string, ignoring double underscores on the second.
1290 static int strcmp_underscore(const char *s1, const char *s2)
1292 if (s2[0] == '_' && s2[1] == '_') {
1293 size_t len2 = strlen(s2);
1294 size_t len1 = strlen(s1);
1295 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1296 return strncmp(s1, s2+2, len2-4);
1300 return strcmp(s1, s2);
1304 * Allocate a new gnu temporal attribute of given kind.
1306 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1308 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1309 attribute->kind = kind;
1310 attribute->next = NULL;
1311 attribute->invalid = false;
1312 attribute->has_arguments = false;
1318 * Parse one constant expression argument of the given attribute.
1320 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1322 expression_t *expression;
1323 add_anchor_token(')');
1324 expression = parse_constant_expression();
1325 rem_anchor_token(')');
1326 expect(')', end_error);
1327 attribute->u.argument = fold_constant(expression);
1330 attribute->invalid = true;
1334 * Parse a list of constant expressions arguments of the given attribute.
1336 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1338 argument_list_t **list = &attribute->u.arguments;
1339 argument_list_t *entry;
1340 expression_t *expression;
1341 add_anchor_token(')');
1342 add_anchor_token(',');
1344 expression = parse_constant_expression();
1345 entry = obstack_alloc(&temp_obst, sizeof(entry));
1346 entry->argument = fold_constant(expression);
1349 list = &entry->next;
1350 if (token.type != ',')
1354 rem_anchor_token(',');
1355 rem_anchor_token(')');
1356 expect(')', end_error);
1359 attribute->invalid = true;
1363 * Parse one string literal argument of the given attribute.
1365 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1368 add_anchor_token('(');
1369 if (token.type != T_STRING_LITERAL) {
1370 parse_error_expected("while parsing attribute directive",
1371 T_STRING_LITERAL, NULL);
1374 *string = parse_string_literals();
1375 rem_anchor_token('(');
1376 expect(')', end_error);
1379 attribute->invalid = true;
1383 * Parse one tls model of the given attribute.
1385 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1387 static const char *const tls_models[] = {
1393 string_t string = { NULL, 0 };
1394 parse_gnu_attribute_string_arg(attribute, &string);
1395 if (string.begin != NULL) {
1396 for (size_t i = 0; i < 4; ++i) {
1397 if (strcmp(tls_models[i], string.begin) == 0) {
1398 attribute->u.value = i;
1402 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1404 attribute->invalid = true;
1408 * Parse one tls model of the given attribute.
1410 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1412 static const char *const visibilities[] = {
1418 string_t string = { NULL, 0 };
1419 parse_gnu_attribute_string_arg(attribute, &string);
1420 if (string.begin != NULL) {
1421 for (size_t i = 0; i < 4; ++i) {
1422 if (strcmp(visibilities[i], string.begin) == 0) {
1423 attribute->u.value = i;
1427 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1429 attribute->invalid = true;
1433 * Parse one (code) model of the given attribute.
1435 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1437 static const char *const visibilities[] = {
1442 string_t string = { NULL, 0 };
1443 parse_gnu_attribute_string_arg(attribute, &string);
1444 if (string.begin != NULL) {
1445 for (int i = 0; i < 3; ++i) {
1446 if (strcmp(visibilities[i], string.begin) == 0) {
1447 attribute->u.value = i;
1451 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1453 attribute->invalid = true;
1457 * Parse one mode of the given attribute.
1459 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1461 add_anchor_token(')');
1463 if (token.type != T_IDENTIFIER) {
1464 expect(T_IDENTIFIER, end_error);
1467 attribute->u.symbol = token.v.symbol;
1470 rem_anchor_token(')');
1471 expect(')', end_error);
1474 attribute->invalid = true;
1478 * Parse one interrupt argument of the given attribute.
1480 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1482 static const char *const interrupts[] = {
1489 string_t string = { NULL, 0 };
1490 parse_gnu_attribute_string_arg(attribute, &string);
1491 if (string.begin != NULL) {
1492 for (size_t i = 0; i < 5; ++i) {
1493 if (strcmp(interrupts[i], string.begin) == 0) {
1494 attribute->u.value = i;
1498 errorf(HERE, "'%s' is not an interrupt", string.begin);
1500 attribute->invalid = true;
1504 * Parse ( identifier, const expression, const expression )
1506 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1508 static const char *const format_names[] = {
1516 if (token.type != T_IDENTIFIER) {
1517 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1520 const char *name = token.v.symbol->string;
1521 for (i = 0; i < 4; ++i) {
1522 if (strcmp_underscore(format_names[i], name) == 0)
1526 if (warning.attribute)
1527 warningf(HERE, "'%s' is an unrecognized format function type", name);
1531 expect(',', end_error);
1532 add_anchor_token(')');
1533 add_anchor_token(',');
1534 parse_constant_expression();
1535 rem_anchor_token(',');
1536 rem_anchor_token(')');
1538 expect(',', end_error);
1539 add_anchor_token(')');
1540 parse_constant_expression();
1541 rem_anchor_token(')');
1542 expect(')', end_error);
1545 attribute->u.value = true;
1549 * Check that a given GNU attribute has no arguments.
1551 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1553 if (!attribute->has_arguments)
1556 /* should have no arguments */
1557 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1558 eat_until_matching_token('(');
1559 /* we have already consumed '(', so we stop before ')', eat it */
1561 attribute->invalid = true;
1565 * Parse one GNU attribute.
1567 * Note that attribute names can be specified WITH or WITHOUT
1568 * double underscores, ie const or __const__.
1570 * The following attributes are parsed without arguments
1595 * no_instrument_function
1596 * warn_unused_result
1613 * externally_visible
1621 * The following attributes are parsed with arguments
1622 * aligned( const expression )
1623 * alias( string literal )
1624 * section( string literal )
1625 * format( identifier, const expression, const expression )
1626 * format_arg( const expression )
1627 * tls_model( string literal )
1628 * visibility( string literal )
1629 * regparm( const expression )
1630 * model( string leteral )
1631 * trap_exit( const expression )
1632 * sp_switch( string literal )
1634 * The following attributes might have arguments
1635 * weak_ref( string literal )
1636 * non_null( const expression // ',' )
1637 * interrupt( string literal )
1638 * sentinel( constant expression )
1640 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1642 gnu_attribute_t *head = *attributes;
1643 gnu_attribute_t *last = *attributes;
1644 decl_modifiers_t modifiers = 0;
1645 gnu_attribute_t *attribute;
1647 eat(T___attribute__);
1648 expect('(', end_error);
1649 expect('(', end_error);
1651 if (token.type != ')') {
1652 /* find the end of the list */
1654 while (last->next != NULL)
1658 /* non-empty attribute list */
1661 if (token.type == T_const) {
1663 } else if (token.type == T_volatile) {
1665 } else if (token.type == T_cdecl) {
1666 /* __attribute__((cdecl)), WITH ms mode */
1668 } else if (token.type == T_IDENTIFIER) {
1669 const symbol_t *sym = token.v.symbol;
1672 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1679 for (i = 0; i < GNU_AK_LAST; ++i) {
1680 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1683 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1686 if (kind == GNU_AK_LAST) {
1687 if (warning.attribute)
1688 warningf(HERE, "'%s' attribute directive ignored", name);
1690 /* skip possible arguments */
1691 if (token.type == '(') {
1692 eat_until_matching_token(')');
1693 next_token(); /* skip the ')' */
1696 /* check for arguments */
1697 attribute = allocate_gnu_attribute(kind);
1698 if (token.type == '(') {
1700 if (token.type == ')') {
1701 /* empty args are allowed */
1704 attribute->has_arguments = true;
1708 case GNU_AK_VOLATILE:
1713 case GNU_AK_NOCOMMON:
1715 case GNU_AK_NOTSHARED:
1716 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1717 case GNU_AK_WARN_UNUSED_RESULT:
1718 case GNU_AK_LONGCALL:
1719 case GNU_AK_SHORTCALL:
1720 case GNU_AK_LONG_CALL:
1721 case GNU_AK_SHORT_CALL:
1722 case GNU_AK_FUNCTION_VECTOR:
1723 case GNU_AK_INTERRUPT_HANDLER:
1724 case GNU_AK_NMI_HANDLER:
1725 case GNU_AK_NESTING:
1729 case GNU_AK_EIGTHBIT_DATA:
1730 case GNU_AK_TINY_DATA:
1731 case GNU_AK_SAVEALL:
1732 case GNU_AK_FLATTEN:
1733 case GNU_AK_SSEREGPARM:
1734 case GNU_AK_EXTERNALLY_VISIBLE:
1735 case GNU_AK_RETURN_TWICE:
1736 case GNU_AK_MAY_ALIAS:
1737 case GNU_AK_MS_STRUCT:
1738 case GNU_AK_GCC_STRUCT:
1741 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1742 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1743 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1744 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1745 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1746 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1747 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1748 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1749 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1750 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1751 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1752 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1753 case GNU_AK_RETURNS_TWICE: modifiers |= DM_RETURNS_TWICE; goto no_arg;
1754 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1755 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1756 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1757 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1758 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1759 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1761 case GNU_AK_ALIGNED:
1762 /* __align__ may be used without an argument */
1763 if (attribute->has_arguments) {
1764 parse_gnu_attribute_const_arg(attribute);
1768 case GNU_AK_FORMAT_ARG:
1769 case GNU_AK_REGPARM:
1770 case GNU_AK_TRAP_EXIT:
1771 if (!attribute->has_arguments) {
1772 /* should have arguments */
1773 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1774 attribute->invalid = true;
1776 parse_gnu_attribute_const_arg(attribute);
1779 case GNU_AK_SECTION:
1780 case GNU_AK_SP_SWITCH:
1781 if (!attribute->has_arguments) {
1782 /* should have arguments */
1783 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1784 attribute->invalid = true;
1786 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1789 if (!attribute->has_arguments) {
1790 /* should have arguments */
1791 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1792 attribute->invalid = true;
1794 parse_gnu_attribute_format_args(attribute);
1796 case GNU_AK_WEAKREF:
1797 /* may have one string argument */
1798 if (attribute->has_arguments)
1799 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1801 case GNU_AK_NONNULL:
1802 if (attribute->has_arguments)
1803 parse_gnu_attribute_const_arg_list(attribute);
1805 case GNU_AK_TLS_MODEL:
1806 if (!attribute->has_arguments) {
1807 /* should have arguments */
1808 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1810 parse_gnu_attribute_tls_model_arg(attribute);
1812 case GNU_AK_VISIBILITY:
1813 if (!attribute->has_arguments) {
1814 /* should have arguments */
1815 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1817 parse_gnu_attribute_visibility_arg(attribute);
1820 if (!attribute->has_arguments) {
1821 /* should have arguments */
1822 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1824 parse_gnu_attribute_model_arg(attribute);
1828 if (!attribute->has_arguments) {
1829 /* should have arguments */
1830 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1832 parse_gnu_attribute_mode_arg(attribute);
1835 case GNU_AK_INTERRUPT:
1836 /* may have one string argument */
1837 if (attribute->has_arguments)
1838 parse_gnu_attribute_interrupt_arg(attribute);
1840 case GNU_AK_SENTINEL:
1841 /* may have one string argument */
1842 if (attribute->has_arguments)
1843 parse_gnu_attribute_const_arg(attribute);
1846 /* already handled */
1850 check_no_argument(attribute, name);
1853 if (attribute != NULL) {
1855 last->next = attribute;
1858 head = last = attribute;
1862 if (token.type != ',')
1867 expect(')', end_error);
1868 expect(')', end_error);
1876 * Parse GNU attributes.
1878 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1880 decl_modifiers_t modifiers = 0;
1883 switch (token.type) {
1884 case T___attribute__:
1885 modifiers |= parse_gnu_attribute(attributes);
1890 expect('(', end_error);
1891 if (token.type != T_STRING_LITERAL) {
1892 parse_error_expected("while parsing assembler attribute",
1893 T_STRING_LITERAL, NULL);
1894 eat_until_matching_token('(');
1897 parse_string_literals();
1899 expect(')', end_error);
1902 case T_cdecl: modifiers |= DM_CDECL; break;
1903 case T__fastcall: modifiers |= DM_FASTCALL; break;
1904 case T__stdcall: modifiers |= DM_STDCALL; break;
1907 /* TODO record modifier */
1909 warningf(HERE, "Ignoring declaration modifier %K", &token);
1913 default: return modifiers;
1920 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1922 static entity_t *determine_lhs_ent(expression_t *const expr,
1925 switch (expr->kind) {
1926 case EXPR_REFERENCE: {
1927 entity_t *const entity = expr->reference.entity;
1928 /* we should only find variables as lvalues... */
1929 if (entity->base.kind != ENTITY_VARIABLE
1930 && entity->base.kind != ENTITY_PARAMETER)
1936 case EXPR_ARRAY_ACCESS: {
1937 expression_t *const ref = expr->array_access.array_ref;
1938 entity_t * ent = NULL;
1939 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1940 ent = determine_lhs_ent(ref, lhs_ent);
1943 mark_vars_read(expr->select.compound, lhs_ent);
1945 mark_vars_read(expr->array_access.index, lhs_ent);
1950 if (is_type_compound(skip_typeref(expr->base.type))) {
1951 return determine_lhs_ent(expr->select.compound, lhs_ent);
1953 mark_vars_read(expr->select.compound, lhs_ent);
1958 case EXPR_UNARY_DEREFERENCE: {
1959 expression_t *const val = expr->unary.value;
1960 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1962 return determine_lhs_ent(val->unary.value, lhs_ent);
1964 mark_vars_read(val, NULL);
1970 mark_vars_read(expr, NULL);
1975 #define ENT_ANY ((entity_t*)-1)
1978 * Mark declarations, which are read. This is used to detect variables, which
1982 * x is not marked as "read", because it is only read to calculate its own new
1986 * x and y are not detected as "not read", because multiple variables are
1989 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1991 switch (expr->kind) {
1992 case EXPR_REFERENCE: {
1993 entity_t *const entity = expr->reference.entity;
1994 if (entity->kind != ENTITY_VARIABLE
1995 && entity->kind != ENTITY_PARAMETER)
1998 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1999 if (entity->kind == ENTITY_VARIABLE) {
2000 entity->variable.read = true;
2002 entity->parameter.read = true;
2009 // TODO respect pure/const
2010 mark_vars_read(expr->call.function, NULL);
2011 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
2012 mark_vars_read(arg->expression, NULL);
2016 case EXPR_CONDITIONAL:
2017 // TODO lhs_decl should depend on whether true/false have an effect
2018 mark_vars_read(expr->conditional.condition, NULL);
2019 if (expr->conditional.true_expression != NULL)
2020 mark_vars_read(expr->conditional.true_expression, lhs_ent);
2021 mark_vars_read(expr->conditional.false_expression, lhs_ent);
2025 if (lhs_ent == ENT_ANY
2026 && !is_type_compound(skip_typeref(expr->base.type)))
2028 mark_vars_read(expr->select.compound, lhs_ent);
2031 case EXPR_ARRAY_ACCESS: {
2032 expression_t *const ref = expr->array_access.array_ref;
2033 mark_vars_read(ref, lhs_ent);
2034 lhs_ent = determine_lhs_ent(ref, lhs_ent);
2035 mark_vars_read(expr->array_access.index, lhs_ent);
2040 mark_vars_read(expr->va_arge.ap, lhs_ent);
2044 mark_vars_read(expr->va_copye.src, lhs_ent);
2047 case EXPR_UNARY_CAST:
2048 /* Special case: Use void cast to mark a variable as "read" */
2049 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2054 case EXPR_UNARY_THROW:
2055 if (expr->unary.value == NULL)
2058 case EXPR_UNARY_DEREFERENCE:
2059 case EXPR_UNARY_DELETE:
2060 case EXPR_UNARY_DELETE_ARRAY:
2061 if (lhs_ent == ENT_ANY)
2065 case EXPR_UNARY_NEGATE:
2066 case EXPR_UNARY_PLUS:
2067 case EXPR_UNARY_BITWISE_NEGATE:
2068 case EXPR_UNARY_NOT:
2069 case EXPR_UNARY_TAKE_ADDRESS:
2070 case EXPR_UNARY_POSTFIX_INCREMENT:
2071 case EXPR_UNARY_POSTFIX_DECREMENT:
2072 case EXPR_UNARY_PREFIX_INCREMENT:
2073 case EXPR_UNARY_PREFIX_DECREMENT:
2074 case EXPR_UNARY_CAST_IMPLICIT:
2075 case EXPR_UNARY_ASSUME:
2077 mark_vars_read(expr->unary.value, lhs_ent);
2080 case EXPR_BINARY_ADD:
2081 case EXPR_BINARY_SUB:
2082 case EXPR_BINARY_MUL:
2083 case EXPR_BINARY_DIV:
2084 case EXPR_BINARY_MOD:
2085 case EXPR_BINARY_EQUAL:
2086 case EXPR_BINARY_NOTEQUAL:
2087 case EXPR_BINARY_LESS:
2088 case EXPR_BINARY_LESSEQUAL:
2089 case EXPR_BINARY_GREATER:
2090 case EXPR_BINARY_GREATEREQUAL:
2091 case EXPR_BINARY_BITWISE_AND:
2092 case EXPR_BINARY_BITWISE_OR:
2093 case EXPR_BINARY_BITWISE_XOR:
2094 case EXPR_BINARY_LOGICAL_AND:
2095 case EXPR_BINARY_LOGICAL_OR:
2096 case EXPR_BINARY_SHIFTLEFT:
2097 case EXPR_BINARY_SHIFTRIGHT:
2098 case EXPR_BINARY_COMMA:
2099 case EXPR_BINARY_ISGREATER:
2100 case EXPR_BINARY_ISGREATEREQUAL:
2101 case EXPR_BINARY_ISLESS:
2102 case EXPR_BINARY_ISLESSEQUAL:
2103 case EXPR_BINARY_ISLESSGREATER:
2104 case EXPR_BINARY_ISUNORDERED:
2105 mark_vars_read(expr->binary.left, lhs_ent);
2106 mark_vars_read(expr->binary.right, lhs_ent);
2109 case EXPR_BINARY_ASSIGN:
2110 case EXPR_BINARY_MUL_ASSIGN:
2111 case EXPR_BINARY_DIV_ASSIGN:
2112 case EXPR_BINARY_MOD_ASSIGN:
2113 case EXPR_BINARY_ADD_ASSIGN:
2114 case EXPR_BINARY_SUB_ASSIGN:
2115 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2116 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2117 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2118 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2119 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2120 if (lhs_ent == ENT_ANY)
2122 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
2123 mark_vars_read(expr->binary.right, lhs_ent);
2128 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
2134 case EXPR_CHARACTER_CONSTANT:
2135 case EXPR_WIDE_CHARACTER_CONSTANT:
2136 case EXPR_STRING_LITERAL:
2137 case EXPR_WIDE_STRING_LITERAL:
2138 case EXPR_COMPOUND_LITERAL: // TODO init?
2140 case EXPR_CLASSIFY_TYPE:
2143 case EXPR_BUILTIN_CONSTANT_P:
2144 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
2146 case EXPR_STATEMENT: // TODO
2147 case EXPR_LABEL_ADDRESS:
2148 case EXPR_REFERENCE_ENUM_VALUE:
2152 panic("unhandled expression");
2155 static designator_t *parse_designation(void)
2157 designator_t *result = NULL;
2158 designator_t *last = NULL;
2161 designator_t *designator;
2162 switch (token.type) {
2164 designator = allocate_ast_zero(sizeof(designator[0]));
2165 designator->source_position = token.source_position;
2167 add_anchor_token(']');
2168 designator->array_index = parse_constant_expression();
2169 rem_anchor_token(']');
2170 expect(']', end_error);
2173 designator = allocate_ast_zero(sizeof(designator[0]));
2174 designator->source_position = token.source_position;
2176 if (token.type != T_IDENTIFIER) {
2177 parse_error_expected("while parsing designator",
2178 T_IDENTIFIER, NULL);
2181 designator->symbol = token.v.symbol;
2185 expect('=', end_error);
2189 assert(designator != NULL);
2191 last->next = designator;
2193 result = designator;
2201 static initializer_t *initializer_from_string(array_type_t *type,
2202 const string_t *const string)
2204 /* TODO: check len vs. size of array type */
2207 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2208 initializer->string.string = *string;
2213 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2214 wide_string_t *const string)
2216 /* TODO: check len vs. size of array type */
2219 initializer_t *const initializer =
2220 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2221 initializer->wide_string.string = *string;
2227 * Build an initializer from a given expression.
2229 static initializer_t *initializer_from_expression(type_t *orig_type,
2230 expression_t *expression)
2232 /* TODO check that expression is a constant expression */
2234 /* §6.7.8.14/15 char array may be initialized by string literals */
2235 type_t *type = skip_typeref(orig_type);
2236 type_t *expr_type_orig = expression->base.type;
2237 type_t *expr_type = skip_typeref(expr_type_orig);
2238 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2239 array_type_t *const array_type = &type->array;
2240 type_t *const element_type = skip_typeref(array_type->element_type);
2242 if (element_type->kind == TYPE_ATOMIC) {
2243 atomic_type_kind_t akind = element_type->atomic.akind;
2244 switch (expression->kind) {
2245 case EXPR_STRING_LITERAL:
2246 if (akind == ATOMIC_TYPE_CHAR
2247 || akind == ATOMIC_TYPE_SCHAR
2248 || akind == ATOMIC_TYPE_UCHAR) {
2249 return initializer_from_string(array_type,
2250 &expression->string.value);
2254 case EXPR_WIDE_STRING_LITERAL: {
2255 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2256 if (get_unqualified_type(element_type) == bare_wchar_type) {
2257 return initializer_from_wide_string(array_type,
2258 &expression->wide_string.value);
2269 assign_error_t error = semantic_assign(type, expression);
2270 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2272 report_assign_error(error, type, expression, "initializer",
2273 &expression->base.source_position);
2275 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2277 if (type->kind == TYPE_BITFIELD) {
2278 type = type->bitfield.base_type;
2281 result->value.value = create_implicit_cast(expression, type);
2287 * Checks if a given expression can be used as an constant initializer.
2289 static bool is_initializer_constant(const expression_t *expression)
2291 return is_constant_expression(expression)
2292 || is_address_constant(expression);
2296 * Parses an scalar initializer.
2298 * §6.7.8.11; eat {} without warning
2300 static initializer_t *parse_scalar_initializer(type_t *type,
2301 bool must_be_constant)
2303 /* there might be extra {} hierarchies */
2305 if (token.type == '{') {
2307 warningf(HERE, "extra curly braces around scalar initializer");
2311 } while (token.type == '{');
2314 expression_t *expression = parse_assignment_expression();
2315 mark_vars_read(expression, NULL);
2316 if (must_be_constant && !is_initializer_constant(expression)) {
2317 errorf(&expression->base.source_position,
2318 "Initialisation expression '%E' is not constant",
2322 initializer_t *initializer = initializer_from_expression(type, expression);
2324 if (initializer == NULL) {
2325 errorf(&expression->base.source_position,
2326 "expression '%E' (type '%T') doesn't match expected type '%T'",
2327 expression, expression->base.type, type);
2332 bool additional_warning_displayed = false;
2333 while (braces > 0) {
2334 if (token.type == ',') {
2337 if (token.type != '}') {
2338 if (!additional_warning_displayed && warning.other) {
2339 warningf(HERE, "additional elements in scalar initializer");
2340 additional_warning_displayed = true;
2351 * An entry in the type path.
2353 typedef struct type_path_entry_t type_path_entry_t;
2354 struct type_path_entry_t {
2355 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2357 size_t index; /**< For array types: the current index. */
2358 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2363 * A type path expression a position inside compound or array types.
2365 typedef struct type_path_t type_path_t;
2366 struct type_path_t {
2367 type_path_entry_t *path; /**< An flexible array containing the current path. */
2368 type_t *top_type; /**< type of the element the path points */
2369 size_t max_index; /**< largest index in outermost array */
2373 * Prints a type path for debugging.
2375 static __attribute__((unused)) void debug_print_type_path(
2376 const type_path_t *path)
2378 size_t len = ARR_LEN(path->path);
2380 for (size_t i = 0; i < len; ++i) {
2381 const type_path_entry_t *entry = & path->path[i];
2383 type_t *type = skip_typeref(entry->type);
2384 if (is_type_compound(type)) {
2385 /* in gcc mode structs can have no members */
2386 if (entry->v.compound_entry == NULL) {
2390 fprintf(stderr, ".%s",
2391 entry->v.compound_entry->base.symbol->string);
2392 } else if (is_type_array(type)) {
2393 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
2395 fprintf(stderr, "-INVALID-");
2398 if (path->top_type != NULL) {
2399 fprintf(stderr, " (");
2400 print_type(path->top_type);
2401 fprintf(stderr, ")");
2406 * Return the top type path entry, ie. in a path
2407 * (type).a.b returns the b.
2409 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2411 size_t len = ARR_LEN(path->path);
2413 return &path->path[len-1];
2417 * Enlarge the type path by an (empty) element.
2419 static type_path_entry_t *append_to_type_path(type_path_t *path)
2421 size_t len = ARR_LEN(path->path);
2422 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2424 type_path_entry_t *result = & path->path[len];
2425 memset(result, 0, sizeof(result[0]));
2430 * Descending into a sub-type. Enter the scope of the current top_type.
2432 static void descend_into_subtype(type_path_t *path)
2434 type_t *orig_top_type = path->top_type;
2435 type_t *top_type = skip_typeref(orig_top_type);
2437 type_path_entry_t *top = append_to_type_path(path);
2438 top->type = top_type;
2440 if (is_type_compound(top_type)) {
2441 compound_t *compound = top_type->compound.compound;
2442 entity_t *entry = compound->members.entities;
2444 if (entry != NULL) {
2445 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2446 top->v.compound_entry = &entry->declaration;
2447 path->top_type = entry->declaration.type;
2449 path->top_type = NULL;
2451 } else if (is_type_array(top_type)) {
2453 path->top_type = top_type->array.element_type;
2455 assert(!is_type_valid(top_type));
2460 * Pop an entry from the given type path, ie. returning from
2461 * (type).a.b to (type).a
2463 static void ascend_from_subtype(type_path_t *path)
2465 type_path_entry_t *top = get_type_path_top(path);
2467 path->top_type = top->type;
2469 size_t len = ARR_LEN(path->path);
2470 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2474 * Pop entries from the given type path until the given
2475 * path level is reached.
2477 static void ascend_to(type_path_t *path, size_t top_path_level)
2479 size_t len = ARR_LEN(path->path);
2481 while (len > top_path_level) {
2482 ascend_from_subtype(path);
2483 len = ARR_LEN(path->path);
2487 static bool walk_designator(type_path_t *path, const designator_t *designator,
2488 bool used_in_offsetof)
2490 for (; designator != NULL; designator = designator->next) {
2491 type_path_entry_t *top = get_type_path_top(path);
2492 type_t *orig_type = top->type;
2494 type_t *type = skip_typeref(orig_type);
2496 if (designator->symbol != NULL) {
2497 symbol_t *symbol = designator->symbol;
2498 if (!is_type_compound(type)) {
2499 if (is_type_valid(type)) {
2500 errorf(&designator->source_position,
2501 "'.%Y' designator used for non-compound type '%T'",
2505 top->type = type_error_type;
2506 top->v.compound_entry = NULL;
2507 orig_type = type_error_type;
2509 compound_t *compound = type->compound.compound;
2510 entity_t *iter = compound->members.entities;
2511 for (; iter != NULL; iter = iter->base.next) {
2512 if (iter->base.symbol == symbol) {
2517 errorf(&designator->source_position,
2518 "'%T' has no member named '%Y'", orig_type, symbol);
2521 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2522 if (used_in_offsetof) {
2523 type_t *real_type = skip_typeref(iter->declaration.type);
2524 if (real_type->kind == TYPE_BITFIELD) {
2525 errorf(&designator->source_position,
2526 "offsetof designator '%Y' may not specify bitfield",
2532 top->type = orig_type;
2533 top->v.compound_entry = &iter->declaration;
2534 orig_type = iter->declaration.type;
2537 expression_t *array_index = designator->array_index;
2538 assert(designator->array_index != NULL);
2540 if (!is_type_array(type)) {
2541 if (is_type_valid(type)) {
2542 errorf(&designator->source_position,
2543 "[%E] designator used for non-array type '%T'",
2544 array_index, orig_type);
2549 long index = fold_constant(array_index);
2550 if (!used_in_offsetof) {
2552 errorf(&designator->source_position,
2553 "array index [%E] must be positive", array_index);
2554 } else if (type->array.size_constant) {
2555 long array_size = type->array.size;
2556 if (index >= array_size) {
2557 errorf(&designator->source_position,
2558 "designator [%E] (%d) exceeds array size %d",
2559 array_index, index, array_size);
2564 top->type = orig_type;
2565 top->v.index = (size_t) index;
2566 orig_type = type->array.element_type;
2568 path->top_type = orig_type;
2570 if (designator->next != NULL) {
2571 descend_into_subtype(path);
2580 static void advance_current_object(type_path_t *path, size_t top_path_level)
2582 type_path_entry_t *top = get_type_path_top(path);
2584 type_t *type = skip_typeref(top->type);
2585 if (is_type_union(type)) {
2586 /* in unions only the first element is initialized */
2587 top->v.compound_entry = NULL;
2588 } else if (is_type_struct(type)) {
2589 declaration_t *entry = top->v.compound_entry;
2591 entity_t *next_entity = entry->base.next;
2592 if (next_entity != NULL) {
2593 assert(is_declaration(next_entity));
2594 entry = &next_entity->declaration;
2599 top->v.compound_entry = entry;
2600 if (entry != NULL) {
2601 path->top_type = entry->type;
2604 } else if (is_type_array(type)) {
2605 assert(is_type_array(type));
2609 if (!type->array.size_constant || top->v.index < type->array.size) {
2613 assert(!is_type_valid(type));
2617 /* we're past the last member of the current sub-aggregate, try if we
2618 * can ascend in the type hierarchy and continue with another subobject */
2619 size_t len = ARR_LEN(path->path);
2621 if (len > top_path_level) {
2622 ascend_from_subtype(path);
2623 advance_current_object(path, top_path_level);
2625 path->top_type = NULL;
2630 * skip until token is found.
2632 static void skip_until(int type)
2634 while (token.type != type) {
2635 if (token.type == T_EOF)
2642 * skip any {...} blocks until a closing bracket is reached.
2644 static void skip_initializers(void)
2646 if (token.type == '{')
2649 while (token.type != '}') {
2650 if (token.type == T_EOF)
2652 if (token.type == '{') {
2660 static initializer_t *create_empty_initializer(void)
2662 static initializer_t empty_initializer
2663 = { .list = { { INITIALIZER_LIST }, 0 } };
2664 return &empty_initializer;
2668 * Parse a part of an initialiser for a struct or union,
2670 static initializer_t *parse_sub_initializer(type_path_t *path,
2671 type_t *outer_type, size_t top_path_level,
2672 parse_initializer_env_t *env)
2674 if (token.type == '}') {
2675 /* empty initializer */
2676 return create_empty_initializer();
2679 type_t *orig_type = path->top_type;
2680 type_t *type = NULL;
2682 if (orig_type == NULL) {
2683 /* We are initializing an empty compound. */
2685 type = skip_typeref(orig_type);
2688 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2691 designator_t *designator = NULL;
2692 if (token.type == '.' || token.type == '[') {
2693 designator = parse_designation();
2694 goto finish_designator;
2695 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2696 /* GNU-style designator ("identifier: value") */
2697 designator = allocate_ast_zero(sizeof(designator[0]));
2698 designator->source_position = token.source_position;
2699 designator->symbol = token.v.symbol;
2704 /* reset path to toplevel, evaluate designator from there */
2705 ascend_to(path, top_path_level);
2706 if (!walk_designator(path, designator, false)) {
2707 /* can't continue after designation error */
2711 initializer_t *designator_initializer
2712 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2713 designator_initializer->designator.designator = designator;
2714 ARR_APP1(initializer_t*, initializers, designator_initializer);
2716 orig_type = path->top_type;
2717 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2722 if (token.type == '{') {
2723 if (type != NULL && is_type_scalar(type)) {
2724 sub = parse_scalar_initializer(type, env->must_be_constant);
2728 if (env->entity != NULL) {
2730 "extra brace group at end of initializer for '%Y'",
2731 env->entity->base.symbol);
2733 errorf(HERE, "extra brace group at end of initializer");
2736 descend_into_subtype(path);
2738 add_anchor_token('}');
2739 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2741 rem_anchor_token('}');
2744 ascend_from_subtype(path);
2745 expect('}', end_error);
2747 expect('}', end_error);
2748 goto error_parse_next;
2752 /* must be an expression */
2753 expression_t *expression = parse_assignment_expression();
2754 mark_vars_read(expression, NULL);
2756 if (env->must_be_constant && !is_initializer_constant(expression)) {
2757 errorf(&expression->base.source_position,
2758 "Initialisation expression '%E' is not constant",
2763 /* we are already outside, ... */
2764 type_t *const outer_type_skip = skip_typeref(outer_type);
2765 if (is_type_compound(outer_type_skip) &&
2766 !outer_type_skip->compound.compound->complete) {
2767 goto error_parse_next;
2772 /* handle { "string" } special case */
2773 if ((expression->kind == EXPR_STRING_LITERAL
2774 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2775 && outer_type != NULL) {
2776 sub = initializer_from_expression(outer_type, expression);
2778 if (token.type == ',') {
2781 if (token.type != '}' && warning.other) {
2782 warningf(HERE, "excessive elements in initializer for type '%T'",
2785 /* TODO: eat , ... */
2790 /* descend into subtypes until expression matches type */
2792 orig_type = path->top_type;
2793 type = skip_typeref(orig_type);
2795 sub = initializer_from_expression(orig_type, expression);
2799 if (!is_type_valid(type)) {
2802 if (is_type_scalar(type)) {
2803 errorf(&expression->base.source_position,
2804 "expression '%E' doesn't match expected type '%T'",
2805 expression, orig_type);
2809 descend_into_subtype(path);
2813 /* update largest index of top array */
2814 const type_path_entry_t *first = &path->path[0];
2815 type_t *first_type = first->type;
2816 first_type = skip_typeref(first_type);
2817 if (is_type_array(first_type)) {
2818 size_t index = first->v.index;
2819 if (index > path->max_index)
2820 path->max_index = index;
2824 /* append to initializers list */
2825 ARR_APP1(initializer_t*, initializers, sub);
2828 if (warning.other) {
2829 if (env->entity != NULL) {
2830 warningf(HERE, "excess elements in struct initializer for '%Y'",
2831 env->entity->base.symbol);
2833 warningf(HERE, "excess elements in struct initializer");
2839 if (token.type == '}') {
2842 expect(',', end_error);
2843 if (token.type == '}') {
2848 /* advance to the next declaration if we are not at the end */
2849 advance_current_object(path, top_path_level);
2850 orig_type = path->top_type;
2851 if (orig_type != NULL)
2852 type = skip_typeref(orig_type);
2858 size_t len = ARR_LEN(initializers);
2859 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2860 initializer_t *result = allocate_ast_zero(size);
2861 result->kind = INITIALIZER_LIST;
2862 result->list.len = len;
2863 memcpy(&result->list.initializers, initializers,
2864 len * sizeof(initializers[0]));
2866 DEL_ARR_F(initializers);
2867 ascend_to(path, top_path_level+1);
2872 skip_initializers();
2873 DEL_ARR_F(initializers);
2874 ascend_to(path, top_path_level+1);
2879 * Parses an initializer. Parsers either a compound literal
2880 * (env->declaration == NULL) or an initializer of a declaration.
2882 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2884 type_t *type = skip_typeref(env->type);
2885 size_t max_index = 0xdeadbeaf; // TODO: Resolve this uninitialized variable problem
2886 initializer_t *result;
2888 if (is_type_scalar(type)) {
2889 result = parse_scalar_initializer(type, env->must_be_constant);
2890 } else if (token.type == '{') {
2894 memset(&path, 0, sizeof(path));
2895 path.top_type = env->type;
2896 path.path = NEW_ARR_F(type_path_entry_t, 0);
2898 descend_into_subtype(&path);
2900 add_anchor_token('}');
2901 result = parse_sub_initializer(&path, env->type, 1, env);
2902 rem_anchor_token('}');
2904 max_index = path.max_index;
2905 DEL_ARR_F(path.path);
2907 expect('}', end_error);
2909 /* parse_scalar_initializer() also works in this case: we simply
2910 * have an expression without {} around it */
2911 result = parse_scalar_initializer(type, env->must_be_constant);
2914 /* §6.7.8:22 array initializers for arrays with unknown size determine
2915 * the array type size */
2916 if (is_type_array(type) && type->array.size_expression == NULL
2917 && result != NULL) {
2919 switch (result->kind) {
2920 case INITIALIZER_LIST:
2921 assert(max_index != 0xdeadbeaf);
2922 size = max_index + 1;
2925 case INITIALIZER_STRING:
2926 size = result->string.string.size;
2929 case INITIALIZER_WIDE_STRING:
2930 size = result->wide_string.string.size;
2933 case INITIALIZER_DESIGNATOR:
2934 case INITIALIZER_VALUE:
2935 /* can happen for parse errors */
2940 internal_errorf(HERE, "invalid initializer type");
2943 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2944 cnst->base.type = type_size_t;
2945 cnst->conste.v.int_value = size;
2947 type_t *new_type = duplicate_type(type);
2949 new_type->array.size_expression = cnst;
2950 new_type->array.size_constant = true;
2951 new_type->array.has_implicit_size = true;
2952 new_type->array.size = size;
2953 env->type = new_type;
2961 static void append_entity(scope_t *scope, entity_t *entity)
2963 if (scope->last_entity != NULL) {
2964 scope->last_entity->base.next = entity;
2966 scope->entities = entity;
2968 scope->last_entity = entity;
2972 static compound_t *parse_compound_type_specifier(bool is_struct)
2974 gnu_attribute_t *attributes = NULL;
2975 decl_modifiers_t modifiers = 0;
2982 symbol_t *symbol = NULL;
2983 compound_t *compound = NULL;
2985 if (token.type == T___attribute__) {
2986 modifiers |= parse_attributes(&attributes);
2989 if (token.type == T_IDENTIFIER) {
2990 /* the compound has a name, check if we have seen it already */
2991 symbol = token.v.symbol;
2994 namespace_tag_t const namespc =
2995 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2996 entity_t *entity = get_entity(symbol, namespc);
2997 if (entity != NULL) {
2998 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
2999 compound = &entity->compound;
3000 if (compound->base.parent_scope != current_scope &&
3001 (token.type == '{' || token.type == ';')) {
3002 /* we're in an inner scope and have a definition. Shadow
3003 * existing definition in outer scope */
3005 } else if (compound->complete && token.type == '{') {
3006 assert(symbol != NULL);
3007 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
3008 is_struct ? "struct" : "union", symbol,
3009 &compound->base.source_position);
3010 /* clear members in the hope to avoid further errors */
3011 compound->members.entities = NULL;
3014 } else if (token.type != '{') {
3016 parse_error_expected("while parsing struct type specifier",
3017 T_IDENTIFIER, '{', NULL);
3019 parse_error_expected("while parsing union type specifier",
3020 T_IDENTIFIER, '{', NULL);
3026 if (compound == NULL) {
3027 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
3028 entity_t *entity = allocate_entity_zero(kind);
3029 compound = &entity->compound;
3031 compound->base.namespc =
3032 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
3033 compound->base.source_position = token.source_position;
3034 compound->base.symbol = symbol;
3035 compound->base.parent_scope = current_scope;
3036 if (symbol != NULL) {
3037 environment_push(entity);
3039 append_entity(current_scope, entity);
3042 if (token.type == '{') {
3043 parse_compound_type_entries(compound);
3044 modifiers |= parse_attributes(&attributes);
3046 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
3047 if (symbol == NULL) {
3048 assert(anonymous_entity == NULL);
3049 anonymous_entity = (entity_t*)compound;
3053 compound->modifiers |= modifiers;
3057 static void parse_enum_entries(type_t *const enum_type)
3061 if (token.type == '}') {
3062 errorf(HERE, "empty enum not allowed");
3067 add_anchor_token('}');
3069 if (token.type != T_IDENTIFIER) {
3070 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3072 rem_anchor_token('}');
3076 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3077 entity->enum_value.enum_type = enum_type;
3078 entity->base.symbol = token.v.symbol;
3079 entity->base.source_position = token.source_position;
3082 if (token.type == '=') {
3084 expression_t *value = parse_constant_expression();
3086 value = create_implicit_cast(value, enum_type);
3087 entity->enum_value.value = value;
3092 record_entity(entity, false);
3094 if (token.type != ',')
3097 } while (token.type != '}');
3098 rem_anchor_token('}');
3100 expect('}', end_error);
3106 static type_t *parse_enum_specifier(void)
3108 gnu_attribute_t *attributes = NULL;
3113 if (token.type == T_IDENTIFIER) {
3114 symbol = token.v.symbol;
3117 entity = get_entity(symbol, NAMESPACE_ENUM);
3118 if (entity != NULL) {
3119 assert(entity->kind == ENTITY_ENUM);
3120 if (entity->base.parent_scope != current_scope &&
3121 (token.type == '{' || token.type == ';')) {
3122 /* we're in an inner scope and have a definition. Shadow
3123 * existing definition in outer scope */
3125 } else if (entity->enume.complete && token.type == '{') {
3126 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
3127 symbol, &entity->base.source_position);
3130 } else if (token.type != '{') {
3131 parse_error_expected("while parsing enum type specifier",
3132 T_IDENTIFIER, '{', NULL);
3139 if (entity == NULL) {
3140 entity = allocate_entity_zero(ENTITY_ENUM);
3141 entity->base.namespc = NAMESPACE_ENUM;
3142 entity->base.source_position = token.source_position;
3143 entity->base.symbol = symbol;
3144 entity->base.parent_scope = current_scope;
3147 type_t *const type = allocate_type_zero(TYPE_ENUM);
3148 type->enumt.enume = &entity->enume;
3149 type->enumt.akind = ATOMIC_TYPE_INT;
3151 if (token.type == '{') {
3152 if (symbol != NULL) {
3153 environment_push(entity);
3155 append_entity(current_scope, entity);
3156 entity->enume.complete = true;
3158 parse_enum_entries(type);
3159 parse_attributes(&attributes);
3161 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
3162 if (symbol == NULL) {
3163 assert(anonymous_entity == NULL);
3164 anonymous_entity = entity;
3166 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
3167 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
3175 * if a symbol is a typedef to another type, return true
3177 static bool is_typedef_symbol(symbol_t *symbol)
3179 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3180 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3183 static type_t *parse_typeof(void)
3189 expect('(', end_error);
3190 add_anchor_token(')');
3192 expression_t *expression = NULL;
3194 bool old_type_prop = in_type_prop;
3195 bool old_gcc_extension = in_gcc_extension;
3196 in_type_prop = true;
3198 while (token.type == T___extension__) {
3199 /* This can be a prefix to a typename or an expression. */
3201 in_gcc_extension = true;
3203 switch (token.type) {
3205 if (is_typedef_symbol(token.v.symbol)) {
3206 type = parse_typename();
3208 expression = parse_expression();
3209 type = revert_automatic_type_conversion(expression);
3214 type = parse_typename();
3218 expression = parse_expression();
3219 type = expression->base.type;
3222 in_type_prop = old_type_prop;
3223 in_gcc_extension = old_gcc_extension;
3225 rem_anchor_token(')');
3226 expect(')', end_error);
3228 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3229 typeof_type->typeoft.expression = expression;
3230 typeof_type->typeoft.typeof_type = type;
3237 typedef enum specifiers_t {
3238 SPECIFIER_SIGNED = 1 << 0,
3239 SPECIFIER_UNSIGNED = 1 << 1,
3240 SPECIFIER_LONG = 1 << 2,
3241 SPECIFIER_INT = 1 << 3,
3242 SPECIFIER_DOUBLE = 1 << 4,
3243 SPECIFIER_CHAR = 1 << 5,
3244 SPECIFIER_WCHAR_T = 1 << 6,
3245 SPECIFIER_SHORT = 1 << 7,
3246 SPECIFIER_LONG_LONG = 1 << 8,
3247 SPECIFIER_FLOAT = 1 << 9,
3248 SPECIFIER_BOOL = 1 << 10,
3249 SPECIFIER_VOID = 1 << 11,
3250 SPECIFIER_INT8 = 1 << 12,
3251 SPECIFIER_INT16 = 1 << 13,
3252 SPECIFIER_INT32 = 1 << 14,
3253 SPECIFIER_INT64 = 1 << 15,
3254 SPECIFIER_INT128 = 1 << 16,
3255 SPECIFIER_COMPLEX = 1 << 17,
3256 SPECIFIER_IMAGINARY = 1 << 18,
3259 static type_t *create_builtin_type(symbol_t *const symbol,
3260 type_t *const real_type)
3262 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3263 type->builtin.symbol = symbol;
3264 type->builtin.real_type = real_type;
3265 return identify_new_type(type);
3268 static type_t *get_typedef_type(symbol_t *symbol)
3270 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3271 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3274 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3275 type->typedeft.typedefe = &entity->typedefe;
3281 * check for the allowed MS alignment values.
3283 static bool check_alignment_value(long long intvalue)
3285 if (intvalue < 1 || intvalue > 8192) {
3286 errorf(HERE, "illegal alignment value");
3289 unsigned v = (unsigned)intvalue;
3290 for (unsigned i = 1; i <= 8192; i += i) {
3294 errorf(HERE, "alignment must be power of two");
3298 #define DET_MOD(name, tag) do { \
3299 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3300 *modifiers |= tag; \
3303 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3305 decl_modifiers_t *modifiers = &specifiers->modifiers;
3308 if (token.type == T_restrict) {
3310 DET_MOD(restrict, DM_RESTRICT);
3312 } else if (token.type != T_IDENTIFIER)
3314 symbol_t *symbol = token.v.symbol;
3315 if (symbol == sym_align) {
3317 expect('(', end_error);
3318 if (token.type != T_INTEGER)
3320 if (check_alignment_value(token.v.intvalue)) {
3321 if (specifiers->alignment != 0 && warning.other)
3322 warningf(HERE, "align used more than once");
3323 specifiers->alignment = (unsigned char)token.v.intvalue;
3326 expect(')', end_error);
3327 } else if (symbol == sym_allocate) {
3329 expect('(', end_error);
3330 if (token.type != T_IDENTIFIER)
3332 (void)token.v.symbol;
3333 expect(')', end_error);
3334 } else if (symbol == sym_dllimport) {
3336 DET_MOD(dllimport, DM_DLLIMPORT);
3337 } else if (symbol == sym_dllexport) {
3339 DET_MOD(dllexport, DM_DLLEXPORT);
3340 } else if (symbol == sym_thread) {
3342 DET_MOD(thread, DM_THREAD);
3343 } else if (symbol == sym_naked) {
3345 DET_MOD(naked, DM_NAKED);
3346 } else if (symbol == sym_noinline) {
3348 DET_MOD(noinline, DM_NOINLINE);
3349 } else if (symbol == sym_returns_twice) {
3351 DET_MOD(returns_twice, DM_RETURNS_TWICE);
3352 } else if (symbol == sym_noreturn) {
3354 DET_MOD(noreturn, DM_NORETURN);
3355 } else if (symbol == sym_nothrow) {
3357 DET_MOD(nothrow, DM_NOTHROW);
3358 } else if (symbol == sym_novtable) {
3360 DET_MOD(novtable, DM_NOVTABLE);
3361 } else if (symbol == sym_property) {
3363 expect('(', end_error);
3365 bool is_get = false;
3366 if (token.type != T_IDENTIFIER)
3368 if (token.v.symbol == sym_get) {
3370 } else if (token.v.symbol == sym_put) {
3372 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3376 expect('=', end_error);
3377 if (token.type != T_IDENTIFIER)
3380 if (specifiers->get_property_sym != NULL) {
3381 errorf(HERE, "get property name already specified");
3383 specifiers->get_property_sym = token.v.symbol;
3386 if (specifiers->put_property_sym != NULL) {
3387 errorf(HERE, "put property name already specified");
3389 specifiers->put_property_sym = token.v.symbol;
3393 if (token.type == ',') {
3399 expect(')', end_error);
3400 } else if (symbol == sym_selectany) {
3402 DET_MOD(selectany, DM_SELECTANY);
3403 } else if (symbol == sym_uuid) {
3405 expect('(', end_error);
3406 if (token.type != T_STRING_LITERAL)
3409 expect(')', end_error);
3410 } else if (symbol == sym_deprecated) {
3412 if (specifiers->deprecated != 0 && warning.other)
3413 warningf(HERE, "deprecated used more than once");
3414 specifiers->deprecated = true;
3415 if (token.type == '(') {
3417 if (token.type == T_STRING_LITERAL) {
3418 specifiers->deprecated_string = token.v.string.begin;
3421 errorf(HERE, "string literal expected");
3423 expect(')', end_error);
3425 } else if (symbol == sym_noalias) {
3427 DET_MOD(noalias, DM_NOALIAS);
3430 warningf(HERE, "Unknown modifier '%Y' ignored", token.v.symbol);
3432 if (token.type == '(')
3436 if (token.type == ',')
3443 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3445 entity_t *entity = allocate_entity_zero(kind);
3446 entity->base.source_position = *HERE;
3447 entity->base.symbol = symbol;
3448 if (is_declaration(entity)) {
3449 entity->declaration.type = type_error_type;
3450 entity->declaration.implicit = true;
3451 } else if (kind == ENTITY_TYPEDEF) {
3452 entity->typedefe.type = type_error_type;
3453 entity->typedefe.builtin = true;
3455 if (kind != ENTITY_COMPOUND_MEMBER)
3456 record_entity(entity, false);
3460 static variable_t *parse_microsoft_based(void)
3462 if (token.type != T_IDENTIFIER) {
3463 parse_error_expected("while parsing __based", T_IDENTIFIER, NULL);
3466 symbol_t *symbol = token.v.symbol;
3467 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3469 variable_t *variable;
3470 if (entity == NULL || entity->base.kind != ENTITY_VARIABLE) {
3471 errorf(HERE, "'%Y' is not a variable name.", symbol);
3472 variable = &create_error_entity(symbol, ENTITY_VARIABLE)->variable;
3474 variable = &entity->variable;
3476 type_t *const type = variable->base.type;
3477 if (is_type_valid(type)) {
3478 if (! is_type_pointer(skip_typeref(type))) {
3479 errorf(HERE, "variable in __based modifier must have pointer type instead of '%T'", type);
3481 if (variable->base.base.parent_scope != file_scope) {
3482 errorf(HERE, "a nonstatic local variable may not be used in a __based specification");
3491 * Finish the construction of a struct type by calculating
3492 * its size, offsets, alignment.
3494 static void finish_struct_type(compound_type_t *type)
3496 assert(type->compound != NULL);
3498 compound_t *compound = type->compound;
3499 if (!compound->complete)
3504 il_alignment_t alignment = 1;
3505 bool need_pad = false;
3507 entity_t *entry = compound->members.entities;
3508 for (; entry != NULL; entry = entry->base.next) {
3509 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3512 type_t *m_type = skip_typeref(entry->declaration.type);
3513 if (! is_type_valid(m_type)) {
3514 /* simply ignore errors here */
3517 il_alignment_t m_alignment = m_type->base.alignment;
3518 if (m_alignment > alignment)
3519 alignment = m_alignment;
3521 offset = (size + m_alignment - 1) & -m_alignment;
3525 entry->compound_member.offset = offset;
3526 size = offset + m_type->base.size;
3528 if (type->base.alignment != 0) {
3529 alignment = type->base.alignment;
3532 offset = (size + alignment - 1) & -alignment;
3537 if (warning.padded) {
3538 warningf(&compound->base.source_position, "'%T' needs padding", type);
3541 if (compound->modifiers & DM_PACKED && warning.packed) {
3542 warningf(&compound->base.source_position,
3543 "superfluous packed attribute on '%T'", type);
3547 type->base.size = offset;
3548 type->base.alignment = alignment;
3552 * Finish the construction of an union type by calculating
3553 * its size and alignment.
3555 static void finish_union_type(compound_type_t *type)
3557 assert(type->compound != NULL);
3559 compound_t *compound = type->compound;
3560 if (! compound->complete)
3564 il_alignment_t alignment = 1;
3566 entity_t *entry = compound->members.entities;
3567 for (; entry != NULL; entry = entry->base.next) {
3568 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3571 type_t *m_type = skip_typeref(entry->declaration.type);
3572 if (! is_type_valid(m_type))
3575 entry->compound_member.offset = 0;
3576 if (m_type->base.size > size)
3577 size = m_type->base.size;
3578 if (m_type->base.alignment > alignment)
3579 alignment = m_type->base.alignment;
3581 if (type->base.alignment != 0) {
3582 alignment = type->base.alignment;
3584 size = (size + alignment - 1) & -alignment;
3585 type->base.size = size;
3586 type->base.alignment = alignment;
3589 static type_t *handle_attribute_mode(const gnu_attribute_t *attribute,
3592 type_t *type = skip_typeref(orig_type);
3594 /* at least: byte, word, pointer, list of machine modes
3595 * __XXX___ is interpreted as XXX */
3597 /* This isn't really correct, the backend should provide a list of machine
3598 * specific modes (according to gcc philosophy that is...) */
3599 const char *symbol_str = attribute->u.symbol->string;
3600 bool sign = is_type_signed(type);
3601 atomic_type_kind_t akind;
3602 if (strcmp_underscore("QI", symbol_str) == 0 ||
3603 strcmp_underscore("byte", symbol_str) == 0) {
3604 akind = sign ? ATOMIC_TYPE_CHAR : ATOMIC_TYPE_UCHAR;
3605 } else if (strcmp_underscore("HI", symbol_str) == 0) {
3606 akind = sign ? ATOMIC_TYPE_SHORT : ATOMIC_TYPE_USHORT;
3607 } else if (strcmp_underscore("SI", symbol_str) == 0
3608 || strcmp_underscore("word", symbol_str) == 0
3609 || strcmp_underscore("pointer", symbol_str) == 0) {
3610 akind = sign ? ATOMIC_TYPE_INT : ATOMIC_TYPE_UINT;
3611 } else if (strcmp_underscore("DI", symbol_str) == 0) {
3612 akind = sign ? ATOMIC_TYPE_LONGLONG : ATOMIC_TYPE_ULONGLONG;
3615 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
3619 if (type->kind == TYPE_ATOMIC) {
3620 type_t *copy = duplicate_type(type);
3621 copy->atomic.akind = akind;
3622 return identify_new_type(copy);
3623 } else if (type->kind == TYPE_ENUM) {
3624 type_t *copy = duplicate_type(type);
3625 copy->enumt.akind = akind;
3626 return identify_new_type(copy);
3627 } else if (is_type_pointer(type)) {
3628 warningf(HERE, "__attribute__((mode)) on pointers not implemented yet (ignored)");
3632 errorf(HERE, "__attribute__((mode)) only allowed on integer, enum or pointer type");
3636 static type_t *handle_type_attributes(const gnu_attribute_t *attributes,
3639 const gnu_attribute_t *attribute = attributes;
3640 for ( ; attribute != NULL; attribute = attribute->next) {
3641 if (attribute->invalid)
3644 if (attribute->kind == GNU_AK_MODE) {
3645 type = handle_attribute_mode(attribute, type);
3646 } else if (attribute->kind == GNU_AK_ALIGNED) {
3647 int alignment = 32; /* TODO: fill in maximum useful alignment for
3649 if (attribute->has_arguments)
3650 alignment = attribute->u.argument;
3652 type_t *copy = duplicate_type(type);
3653 copy->base.alignment = attribute->u.argument;
3654 type = identify_new_type(copy);
3661 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3663 type_t *type = NULL;
3664 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3665 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3666 unsigned type_specifiers = 0;
3667 bool newtype = false;
3668 bool saw_error = false;
3669 bool old_gcc_extension = in_gcc_extension;
3671 specifiers->source_position = token.source_position;
3674 specifiers->modifiers
3675 |= parse_attributes(&specifiers->gnu_attributes);
3677 switch (token.type) {
3679 #define MATCH_STORAGE_CLASS(token, class) \
3681 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3682 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3684 specifiers->storage_class = class; \
3685 if (specifiers->thread_local) \
3686 goto check_thread_storage_class; \
3690 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3691 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3692 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3693 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3694 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3698 expect('(', end_error);
3699 add_anchor_token(')');
3700 parse_microsoft_extended_decl_modifier(specifiers);
3701 rem_anchor_token(')');
3702 expect(')', end_error);
3706 if (specifiers->thread_local) {
3707 errorf(HERE, "duplicate '__thread'");
3709 specifiers->thread_local = true;
3710 check_thread_storage_class:
3711 switch (specifiers->storage_class) {
3712 case STORAGE_CLASS_EXTERN:
3713 case STORAGE_CLASS_NONE:
3714 case STORAGE_CLASS_STATIC:
3718 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
3719 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
3720 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
3721 wrong_thread_stoarge_class:
3722 errorf(HERE, "'__thread' used with '%s'", wrong);
3729 /* type qualifiers */
3730 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3732 qualifiers |= qualifier; \
3736 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3737 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3738 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3739 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3740 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3741 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3742 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3743 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3745 case T___extension__:
3747 in_gcc_extension = true;
3750 /* type specifiers */
3751 #define MATCH_SPECIFIER(token, specifier, name) \
3753 if (type_specifiers & specifier) { \
3754 errorf(HERE, "multiple " name " type specifiers given"); \
3756 type_specifiers |= specifier; \
3761 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3762 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3763 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3764 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3765 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3766 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3767 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3768 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3769 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3770 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3771 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3772 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3773 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3774 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3775 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3776 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3777 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3778 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
3780 case T__forceinline:
3781 /* only in microsoft mode */
3782 specifiers->modifiers |= DM_FORCEINLINE;
3787 specifiers->is_inline = true;
3791 if (type_specifiers & SPECIFIER_LONG_LONG) {
3792 errorf(HERE, "multiple type specifiers given");
3793 } else if (type_specifiers & SPECIFIER_LONG) {
3794 type_specifiers |= SPECIFIER_LONG_LONG;
3796 type_specifiers |= SPECIFIER_LONG;
3802 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3804 type->compound.compound = parse_compound_type_specifier(true);
3805 finish_struct_type(&type->compound);
3809 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3810 type->compound.compound = parse_compound_type_specifier(false);
3811 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3812 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3813 finish_union_type(&type->compound);
3817 type = parse_enum_specifier();
3820 type = parse_typeof();
3822 case T___builtin_va_list:
3823 type = duplicate_type(type_valist);
3827 case T_IDENTIFIER: {
3828 /* only parse identifier if we haven't found a type yet */
3829 if (type != NULL || type_specifiers != 0) {
3830 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3831 * declaration, so it doesn't generate errors about expecting '(' or
3833 switch (look_ahead(1)->type) {
3840 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3844 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3849 goto finish_specifiers;
3853 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3854 if (typedef_type == NULL) {
3855 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3856 * declaration, so it doesn't generate 'implicit int' followed by more
3857 * errors later on. */
3858 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3864 errorf(HERE, "%K does not name a type", &token);
3867 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3869 type = allocate_type_zero(TYPE_TYPEDEF);
3870 type->typedeft.typedefe = &entity->typedefe;
3874 if (la1_type == '&' || la1_type == '*')
3875 goto finish_specifiers;
3880 goto finish_specifiers;
3885 type = typedef_type;
3889 /* function specifier */
3891 goto finish_specifiers;
3896 specifiers->modifiers
3897 |= parse_attributes(&specifiers->gnu_attributes);
3899 in_gcc_extension = old_gcc_extension;
3901 if (type == NULL || (saw_error && type_specifiers != 0)) {
3902 atomic_type_kind_t atomic_type;
3904 /* match valid basic types */
3905 switch (type_specifiers) {
3906 case SPECIFIER_VOID:
3907 atomic_type = ATOMIC_TYPE_VOID;
3909 case SPECIFIER_WCHAR_T:
3910 atomic_type = ATOMIC_TYPE_WCHAR_T;
3912 case SPECIFIER_CHAR:
3913 atomic_type = ATOMIC_TYPE_CHAR;
3915 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3916 atomic_type = ATOMIC_TYPE_SCHAR;
3918 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3919 atomic_type = ATOMIC_TYPE_UCHAR;
3921 case SPECIFIER_SHORT:
3922 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3923 case SPECIFIER_SHORT | SPECIFIER_INT:
3924 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3925 atomic_type = ATOMIC_TYPE_SHORT;
3927 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3928 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3929 atomic_type = ATOMIC_TYPE_USHORT;
3932 case SPECIFIER_SIGNED:
3933 case SPECIFIER_SIGNED | SPECIFIER_INT:
3934 atomic_type = ATOMIC_TYPE_INT;
3936 case SPECIFIER_UNSIGNED:
3937 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3938 atomic_type = ATOMIC_TYPE_UINT;
3940 case SPECIFIER_LONG:
3941 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3942 case SPECIFIER_LONG | SPECIFIER_INT:
3943 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3944 atomic_type = ATOMIC_TYPE_LONG;
3946 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3947 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3948 atomic_type = ATOMIC_TYPE_ULONG;
3951 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3952 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3953 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3954 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3956 atomic_type = ATOMIC_TYPE_LONGLONG;
3957 goto warn_about_long_long;
3959 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3960 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3962 atomic_type = ATOMIC_TYPE_ULONGLONG;
3963 warn_about_long_long:
3964 if (warning.long_long) {
3965 warningf(&specifiers->source_position,
3966 "ISO C90 does not support 'long long'");
3970 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3971 atomic_type = unsigned_int8_type_kind;
3974 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3975 atomic_type = unsigned_int16_type_kind;
3978 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3979 atomic_type = unsigned_int32_type_kind;
3982 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3983 atomic_type = unsigned_int64_type_kind;
3986 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3987 atomic_type = unsigned_int128_type_kind;
3990 case SPECIFIER_INT8:
3991 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3992 atomic_type = int8_type_kind;
3995 case SPECIFIER_INT16:
3996 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3997 atomic_type = int16_type_kind;
4000 case SPECIFIER_INT32:
4001 case SPECIFIER_SIGNED | SPECIFIER_INT32:
4002 atomic_type = int32_type_kind;
4005 case SPECIFIER_INT64:
4006 case SPECIFIER_SIGNED | SPECIFIER_INT64:
4007 atomic_type = int64_type_kind;
4010 case SPECIFIER_INT128:
4011 case SPECIFIER_SIGNED | SPECIFIER_INT128:
4012 atomic_type = int128_type_kind;
4015 case SPECIFIER_FLOAT:
4016 atomic_type = ATOMIC_TYPE_FLOAT;
4018 case SPECIFIER_DOUBLE:
4019 atomic_type = ATOMIC_TYPE_DOUBLE;
4021 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
4022 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
4024 case SPECIFIER_BOOL:
4025 atomic_type = ATOMIC_TYPE_BOOL;
4027 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
4028 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
4029 atomic_type = ATOMIC_TYPE_FLOAT;
4031 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
4032 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
4033 atomic_type = ATOMIC_TYPE_DOUBLE;
4035 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
4036 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
4037 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
4040 /* invalid specifier combination, give an error message */
4041 if (type_specifiers == 0) {
4045 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
4046 if (!(c_mode & _CXX) && !strict_mode) {
4047 if (warning.implicit_int) {
4048 warningf(HERE, "no type specifiers in declaration, using 'int'");
4050 atomic_type = ATOMIC_TYPE_INT;
4053 errorf(HERE, "no type specifiers given in declaration");
4055 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
4056 (type_specifiers & SPECIFIER_UNSIGNED)) {
4057 errorf(HERE, "signed and unsigned specifiers given");
4058 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
4059 errorf(HERE, "only integer types can be signed or unsigned");
4061 errorf(HERE, "multiple datatypes in declaration");
4066 if (type_specifiers & SPECIFIER_COMPLEX) {
4067 type = allocate_type_zero(TYPE_COMPLEX);
4068 type->complex.akind = atomic_type;
4069 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
4070 type = allocate_type_zero(TYPE_IMAGINARY);
4071 type->imaginary.akind = atomic_type;
4073 type = allocate_type_zero(TYPE_ATOMIC);
4074 type->atomic.akind = atomic_type;
4076 type->base.alignment = get_atomic_type_alignment(atomic_type);
4077 unsigned const size = get_atomic_type_size(atomic_type);
4079 type_specifiers & SPECIFIER_COMPLEX ? size * 2 : size;
4081 } else if (type_specifiers != 0) {
4082 errorf(HERE, "multiple datatypes in declaration");
4085 /* FIXME: check type qualifiers here */
4087 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
4088 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4089 type->base.qualifiers = qualifiers;
4090 type->base.modifiers = modifiers;
4093 type = identify_new_type(type);
4095 type = typehash_insert(type);
4098 type = handle_type_attributes(specifiers->gnu_attributes, type);
4099 specifiers->type = type;
4103 specifiers->type = type_error_type;
4107 static type_qualifiers_t parse_type_qualifiers(void)
4109 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
4112 switch (token.type) {
4113 /* type qualifiers */
4114 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
4115 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
4116 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
4117 /* microsoft extended type modifiers */
4118 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
4119 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
4120 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
4121 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
4122 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
4131 * Parses an K&R identifier list
4133 static void parse_identifier_list(scope_t *scope)
4136 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
4137 entity->base.source_position = token.source_position;
4138 entity->base.namespc = NAMESPACE_NORMAL;
4139 entity->base.symbol = token.v.symbol;
4140 /* a K&R parameter has no type, yet */
4144 append_entity(scope, entity);
4146 if (token.type != ',') {
4150 } while (token.type == T_IDENTIFIER);
4153 static entity_t *parse_parameter(void)
4155 declaration_specifiers_t specifiers;
4156 memset(&specifiers, 0, sizeof(specifiers));
4158 parse_declaration_specifiers(&specifiers);
4160 entity_t *entity = parse_declarator(&specifiers,
4161 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
4162 anonymous_entity = NULL;
4166 static void semantic_parameter_incomplete(const entity_t *entity)
4168 assert(entity->kind == ENTITY_PARAMETER);
4170 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
4171 * list in a function declarator that is part of a
4172 * definition of that function shall not have
4173 * incomplete type. */
4174 type_t *type = skip_typeref(entity->declaration.type);
4175 if (is_type_incomplete(type)) {
4176 errorf(&entity->base.source_position,
4177 "parameter '%#T' has incomplete type",
4178 entity->declaration.type, entity->base.symbol);
4182 static bool has_parameters(void)
4184 /* func(void) is not a parameter */
4185 if (token.type == T_IDENTIFIER) {
4186 entity_t const *const entity = get_entity(token.v.symbol, NAMESPACE_NORMAL);
4187 if (entity->kind != ENTITY_TYPEDEF)
4189 if (skip_typeref(entity->typedefe.type) != type_void)
4191 } else if (token.type != T_void) {
4194 if (look_ahead(1)->type != ')')
4201 * Parses function type parameters (and optionally creates variable_t entities
4202 * for them in a scope)
4204 static void parse_parameters(function_type_t *type, scope_t *scope)
4207 add_anchor_token(')');
4208 int saved_comma_state = save_and_reset_anchor_state(',');
4210 if (token.type == T_IDENTIFIER &&
4211 !is_typedef_symbol(token.v.symbol)) {
4212 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4213 if (la1_type == ',' || la1_type == ')') {
4214 type->kr_style_parameters = true;
4215 type->unspecified_parameters = true;
4216 parse_identifier_list(scope);
4217 goto parameters_finished;
4221 if (token.type == ')') {
4222 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4223 if (!(c_mode & _CXX))
4224 type->unspecified_parameters = true;
4225 goto parameters_finished;
4228 if (has_parameters()) {
4229 function_parameter_t **anchor = &type->parameters;
4231 switch (token.type) {
4234 type->variadic = true;
4235 goto parameters_finished;
4238 case T___extension__:
4241 entity_t *entity = parse_parameter();
4242 if (entity->kind == ENTITY_TYPEDEF) {
4243 errorf(&entity->base.source_position,
4244 "typedef not allowed as function parameter");
4247 assert(is_declaration(entity));
4249 semantic_parameter_incomplete(entity);
4251 function_parameter_t *const parameter =
4252 allocate_parameter(entity->declaration.type);
4254 if (scope != NULL) {
4255 append_entity(scope, entity);
4258 *anchor = parameter;
4259 anchor = ¶meter->next;
4264 goto parameters_finished;
4266 if (token.type != ',') {
4267 goto parameters_finished;
4274 parameters_finished:
4275 rem_anchor_token(')');
4276 expect(')', end_error);
4279 restore_anchor_state(',', saved_comma_state);
4282 typedef enum construct_type_kind_t {
4285 CONSTRUCT_REFERENCE,
4288 } construct_type_kind_t;
4290 typedef union construct_type_t construct_type_t;
4292 typedef struct construct_type_base_t {
4293 construct_type_kind_t kind;
4294 construct_type_t *next;
4295 } construct_type_base_t;
4297 typedef struct parsed_pointer_t {
4298 construct_type_base_t base;
4299 type_qualifiers_t type_qualifiers;
4300 variable_t *base_variable; /**< MS __based extension. */
4303 typedef struct parsed_reference_t {
4304 construct_type_base_t base;
4305 } parsed_reference_t;
4307 typedef struct construct_function_type_t {
4308 construct_type_base_t base;
4309 type_t *function_type;
4310 } construct_function_type_t;
4312 typedef struct parsed_array_t {
4313 construct_type_base_t base;
4314 type_qualifiers_t type_qualifiers;
4320 union construct_type_t {
4321 construct_type_kind_t kind;
4322 construct_type_base_t base;
4323 parsed_pointer_t pointer;
4324 parsed_reference_t reference;
4325 construct_function_type_t function;
4326 parsed_array_t array;
4329 static construct_type_t *parse_pointer_declarator(variable_t *base_variable)
4333 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->pointer));
4334 parsed_pointer_t *pointer = &cons->pointer;
4335 memset(pointer, 0, sizeof(*pointer));
4336 cons->kind = CONSTRUCT_POINTER;
4337 pointer->type_qualifiers = parse_type_qualifiers();
4338 pointer->base_variable = base_variable;
4343 static construct_type_t *parse_reference_declarator(void)
4347 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->reference));
4348 parsed_reference_t *reference = &cons->reference;
4349 memset(reference, 0, sizeof(*reference));
4350 cons->kind = CONSTRUCT_REFERENCE;
4355 static construct_type_t *parse_array_declarator(void)
4358 add_anchor_token(']');
4360 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->array));
4361 parsed_array_t *array = &cons->array;
4362 memset(array, 0, sizeof(*array));
4363 cons->kind = CONSTRUCT_ARRAY;
4365 if (token.type == T_static) {
4366 array->is_static = true;
4370 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4371 if (type_qualifiers != 0) {
4372 if (token.type == T_static) {
4373 array->is_static = true;
4377 array->type_qualifiers = type_qualifiers;
4379 if (token.type == '*' && look_ahead(1)->type == ']') {
4380 array->is_variable = true;
4382 } else if (token.type != ']') {
4383 expression_t *const size = parse_assignment_expression();
4385 mark_vars_read(size, NULL);
4388 rem_anchor_token(']');
4389 expect(']', end_error);
4395 static construct_type_t *parse_function_declarator(scope_t *scope,
4396 decl_modifiers_t modifiers)
4398 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4399 function_type_t *ftype = &type->function;
4401 ftype->linkage = current_linkage;
4403 switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
4404 case DM_NONE: break;
4405 case DM_CDECL: ftype->calling_convention = CC_CDECL; break;
4406 case DM_STDCALL: ftype->calling_convention = CC_STDCALL; break;
4407 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
4408 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
4411 errorf(HERE, "multiple calling conventions in declaration");
4415 parse_parameters(ftype, scope);
4417 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->function));
4418 construct_function_type_t *function = &cons->function;
4419 memset(function, 0, sizeof(*function));
4420 cons->kind = CONSTRUCT_FUNCTION;
4421 function->function_type = type;
4426 typedef struct parse_declarator_env_t {
4427 decl_modifiers_t modifiers;
4429 source_position_t source_position;
4431 } parse_declarator_env_t;
4433 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4434 bool may_be_abstract)
4436 /* construct a single linked list of construct_type_t's which describe
4437 * how to construct the final declarator type */
4438 construct_type_t *first = NULL;
4439 construct_type_t **anchor = &first;
4440 gnu_attribute_t *attributes = NULL;
4442 decl_modifiers_t modifiers = parse_attributes(&attributes);
4445 construct_type_t *type;
4446 variable_t *based = NULL; /* MS __based extension */
4447 switch (token.type) {
4449 if (!(c_mode & _CXX))
4450 errorf(HERE, "references are only available for C++");
4451 type = parse_reference_declarator();
4455 source_position_t const pos = *HERE;
4457 expect('(', end_error);
4458 add_anchor_token(')');
4459 based = parse_microsoft_based();
4460 rem_anchor_token(')');
4461 expect(')', end_error);
4462 if (token.type != '*') {
4463 if (token.type == T__based) {
4464 errorf(&pos, "__based type modifier specified more than once");
4465 } else if (warning.other) {
4467 "__based does not precede a pointer declarator, ignored");
4475 type = parse_pointer_declarator(based);
4479 goto ptr_operator_end;
4483 anchor = &type->base.next;
4485 /* TODO: find out if this is correct */
4486 modifiers |= parse_attributes(&attributes);
4491 modifiers |= env->modifiers;
4492 env->modifiers = modifiers;
4495 construct_type_t *inner_types = NULL;
4497 switch (token.type) {
4500 errorf(HERE, "no identifier expected in typename");
4502 env->symbol = token.v.symbol;
4503 env->source_position = token.source_position;
4508 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
4509 * interpreted as ``function with no parameter specification'', rather
4510 * than redundant parentheses around the omitted identifier. */
4511 if (look_ahead(1)->type != ')') {
4513 add_anchor_token(')');
4514 inner_types = parse_inner_declarator(env, may_be_abstract);
4515 if (inner_types != NULL) {
4516 /* All later declarators only modify the return type */
4519 rem_anchor_token(')');
4520 expect(')', end_error);
4524 if (may_be_abstract)
4526 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4531 construct_type_t **const p = anchor;
4534 construct_type_t *type;
4535 switch (token.type) {
4537 scope_t *scope = NULL;
4539 scope = &env->parameters;
4541 type = parse_function_declarator(scope, modifiers);
4545 type = parse_array_declarator();
4548 goto declarator_finished;
4551 /* insert in the middle of the list (at p) */
4552 type->base.next = *p;
4555 anchor = &type->base.next;
4558 declarator_finished:
4559 /* append inner_types at the end of the list, we don't to set anchor anymore
4560 * as it's not needed anymore */
4561 *anchor = inner_types;
4568 static void parse_declaration_attributes(entity_t *entity)
4570 gnu_attribute_t *attributes = NULL;
4571 decl_modifiers_t modifiers = parse_attributes(&attributes);
4577 if (entity->kind == ENTITY_TYPEDEF) {
4578 modifiers |= entity->typedefe.modifiers;
4579 type = entity->typedefe.type;
4581 assert(is_declaration(entity));
4582 modifiers |= entity->declaration.modifiers;
4583 type = entity->declaration.type;
4588 gnu_attribute_t *attribute = attributes;
4589 for ( ; attribute != NULL; attribute = attribute->next) {
4590 if (attribute->invalid)
4593 if (attribute->kind == GNU_AK_MODE) {
4594 type = handle_attribute_mode(attribute, type);
4595 } else if (attribute->kind == GNU_AK_ALIGNED) {
4596 int alignment = 32; /* TODO: fill in maximum usefull alignment for target machine */
4597 if (attribute->has_arguments)
4598 alignment = attribute->u.argument;
4600 if (entity->kind == ENTITY_TYPEDEF) {
4601 type_t *copy = duplicate_type(type);
4602 copy->base.alignment = attribute->u.argument;
4603 type = identify_new_type(copy);
4604 } else if(entity->kind == ENTITY_VARIABLE) {
4605 entity->variable.alignment = alignment;
4606 } else if(entity->kind == ENTITY_COMPOUND_MEMBER) {
4607 entity->compound_member.alignment = alignment;
4612 type_modifiers_t type_modifiers = type->base.modifiers;
4613 if (modifiers & DM_TRANSPARENT_UNION)
4614 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4616 if (type->base.modifiers != type_modifiers) {
4617 type_t *copy = duplicate_type(type);
4618 copy->base.modifiers = type_modifiers;
4619 type = identify_new_type(copy);
4622 if (entity->kind == ENTITY_TYPEDEF) {
4623 entity->typedefe.type = type;
4624 entity->typedefe.modifiers = modifiers;
4626 entity->declaration.type = type;
4627 entity->declaration.modifiers = modifiers;
4631 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
4633 construct_type_t *iter = construct_list;
4634 for (; iter != NULL; iter = iter->base.next) {
4635 switch (iter->kind) {
4636 case CONSTRUCT_INVALID:
4638 case CONSTRUCT_FUNCTION: {
4639 construct_function_type_t *function = &iter->function;
4640 type_t *function_type = function->function_type;
4642 function_type->function.return_type = type;
4644 type_t *skipped_return_type = skip_typeref(type);
4646 if (is_type_function(skipped_return_type)) {
4647 errorf(HERE, "function returning function is not allowed");
4648 } else if (is_type_array(skipped_return_type)) {
4649 errorf(HERE, "function returning array is not allowed");
4651 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4653 "type qualifiers in return type of function type are meaningless");
4657 /* The function type was constructed earlier. Freeing it here will
4658 * destroy other types. */
4659 type = typehash_insert(function_type);
4663 case CONSTRUCT_POINTER: {
4664 if (is_type_reference(skip_typeref(type)))
4665 errorf(HERE, "cannot declare a pointer to reference");
4667 parsed_pointer_t *pointer = &iter->pointer;
4668 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
4672 case CONSTRUCT_REFERENCE:
4673 if (is_type_reference(skip_typeref(type)))
4674 errorf(HERE, "cannot declare a reference to reference");
4676 type = make_reference_type(type);
4679 case CONSTRUCT_ARRAY: {
4680 if (is_type_reference(skip_typeref(type)))
4681 errorf(HERE, "cannot declare an array of references");
4683 parsed_array_t *array = &iter->array;
4684 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4686 expression_t *size_expression = array->size;
4687 if (size_expression != NULL) {
4689 = create_implicit_cast(size_expression, type_size_t);
4692 array_type->base.qualifiers = array->type_qualifiers;
4693 array_type->array.element_type = type;
4694 array_type->array.is_static = array->is_static;
4695 array_type->array.is_variable = array->is_variable;
4696 array_type->array.size_expression = size_expression;
4698 if (size_expression != NULL) {
4699 if (is_constant_expression(size_expression)) {
4700 long const size = fold_constant(size_expression);
4701 array_type->array.size = size;
4702 array_type->array.size_constant = true;
4703 /* §6.7.5.2:1 If the expression is a constant expression, it shall
4704 * have a value greater than zero. */
4706 if (size < 0 || !GNU_MODE) {
4707 errorf(&size_expression->base.source_position,
4708 "size of array must be greater than zero");
4709 } else if (warning.other) {
4710 warningf(&size_expression->base.source_position,
4711 "zero length arrays are a GCC extension");
4715 array_type->array.is_vla = true;
4719 type_t *skipped_type = skip_typeref(type);
4721 if (is_type_incomplete(skipped_type)) {
4722 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4723 } else if (is_type_function(skipped_type)) {
4724 errorf(HERE, "array of functions is not allowed");
4726 type = identify_new_type(array_type);
4730 internal_errorf(HERE, "invalid type construction found");
4736 static type_t *automatic_type_conversion(type_t *orig_type);
4738 static type_t *semantic_parameter(const source_position_t *pos,
4740 const declaration_specifiers_t *specifiers,
4743 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
4744 * shall be adjusted to ``qualified pointer to type'',
4746 * §6.7.5.3:8 A declaration of a parameter as ``function returning
4747 * type'' shall be adjusted to ``pointer to function
4748 * returning type'', as in 6.3.2.1. */
4749 type = automatic_type_conversion(type);
4751 if (specifiers->is_inline && is_type_valid(type)) {
4752 errorf(pos, "parameter '%#T' declared 'inline'", type, symbol);
4755 /* §6.9.1:6 The declarations in the declaration list shall contain
4756 * no storage-class specifier other than register and no
4757 * initializations. */
4758 if (specifiers->thread_local || (
4759 specifiers->storage_class != STORAGE_CLASS_NONE &&
4760 specifiers->storage_class != STORAGE_CLASS_REGISTER)
4762 errorf(pos, "invalid storage class for parameter '%#T'", type, symbol);
4765 /* delay test for incomplete type, because we might have (void)
4766 * which is legal but incomplete... */
4771 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4772 declarator_flags_t flags)
4774 parse_declarator_env_t env;
4775 memset(&env, 0, sizeof(env));
4776 env.modifiers = specifiers->modifiers;
4778 construct_type_t *construct_type =
4779 parse_inner_declarator(&env, (flags & DECL_MAY_BE_ABSTRACT) != 0);
4781 construct_declarator_type(construct_type, specifiers->type);
4782 type_t *type = skip_typeref(orig_type);
4784 if (construct_type != NULL) {
4785 obstack_free(&temp_obst, construct_type);
4789 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4790 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4791 entity->base.symbol = env.symbol;
4792 entity->base.source_position = env.source_position;
4793 entity->typedefe.type = orig_type;
4795 if (anonymous_entity != NULL) {
4796 if (is_type_compound(type)) {
4797 assert(anonymous_entity->compound.alias == NULL);
4798 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4799 anonymous_entity->kind == ENTITY_UNION);
4800 anonymous_entity->compound.alias = entity;
4801 anonymous_entity = NULL;
4802 } else if (is_type_enum(type)) {
4803 assert(anonymous_entity->enume.alias == NULL);
4804 assert(anonymous_entity->kind == ENTITY_ENUM);
4805 anonymous_entity->enume.alias = entity;
4806 anonymous_entity = NULL;
4810 /* create a declaration type entity */
4811 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
4812 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4814 if (env.symbol != NULL) {
4815 if (specifiers->is_inline && is_type_valid(type)) {
4816 errorf(&env.source_position,
4817 "compound member '%Y' declared 'inline'", env.symbol);
4820 if (specifiers->thread_local ||
4821 specifiers->storage_class != STORAGE_CLASS_NONE) {
4822 errorf(&env.source_position,
4823 "compound member '%Y' must have no storage class",
4827 } else if (flags & DECL_IS_PARAMETER) {
4828 orig_type = semantic_parameter(&env.source_position, orig_type,
4829 specifiers, env.symbol);
4831 entity = allocate_entity_zero(ENTITY_PARAMETER);
4832 } else if (is_type_function(type)) {
4833 entity = allocate_entity_zero(ENTITY_FUNCTION);
4835 entity->function.is_inline = specifiers->is_inline;
4836 entity->function.parameters = env.parameters;
4838 if (env.symbol != NULL) {
4839 if (specifiers->thread_local || (
4840 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4841 specifiers->storage_class != STORAGE_CLASS_NONE &&
4842 specifiers->storage_class != STORAGE_CLASS_STATIC
4844 errorf(&env.source_position,
4845 "invalid storage class for function '%Y'", env.symbol);
4849 entity = allocate_entity_zero(ENTITY_VARIABLE);
4851 entity->variable.get_property_sym = specifiers->get_property_sym;
4852 entity->variable.put_property_sym = specifiers->put_property_sym;
4854 entity->variable.thread_local = specifiers->thread_local;
4856 if (env.symbol != NULL) {
4857 if (specifiers->is_inline && is_type_valid(type)) {
4858 errorf(&env.source_position,
4859 "variable '%Y' declared 'inline'", env.symbol);
4862 bool invalid_storage_class = false;
4863 if (current_scope == file_scope) {
4864 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4865 specifiers->storage_class != STORAGE_CLASS_NONE &&
4866 specifiers->storage_class != STORAGE_CLASS_STATIC) {
4867 invalid_storage_class = true;
4870 if (specifiers->thread_local &&
4871 specifiers->storage_class == STORAGE_CLASS_NONE) {
4872 invalid_storage_class = true;
4875 if (invalid_storage_class) {
4876 errorf(&env.source_position,
4877 "invalid storage class for variable '%Y'", env.symbol);
4882 if (env.symbol != NULL) {
4883 entity->base.symbol = env.symbol;
4884 entity->base.source_position = env.source_position;
4886 entity->base.source_position = specifiers->source_position;
4888 entity->base.namespc = NAMESPACE_NORMAL;
4889 entity->declaration.type = orig_type;
4890 entity->declaration.modifiers = env.modifiers;
4891 entity->declaration.deprecated_string = specifiers->deprecated_string;
4893 storage_class_t storage_class = specifiers->storage_class;
4894 entity->declaration.declared_storage_class = storage_class;
4896 if (storage_class == STORAGE_CLASS_NONE && current_scope != file_scope)
4897 storage_class = STORAGE_CLASS_AUTO;
4898 entity->declaration.storage_class = storage_class;
4901 parse_declaration_attributes(entity);
4906 static type_t *parse_abstract_declarator(type_t *base_type)
4908 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4910 type_t *result = construct_declarator_type(construct_type, base_type);
4911 if (construct_type != NULL) {
4912 obstack_free(&temp_obst, construct_type);
4919 * Check if the declaration of main is suspicious. main should be a
4920 * function with external linkage, returning int, taking either zero
4921 * arguments, two, or three arguments of appropriate types, ie.
4923 * int main([ int argc, char **argv [, char **env ] ]).
4925 * @param decl the declaration to check
4926 * @param type the function type of the declaration
4928 static void check_type_of_main(const entity_t *entity)
4930 const source_position_t *pos = &entity->base.source_position;
4931 if (entity->kind != ENTITY_FUNCTION) {
4932 warningf(pos, "'main' is not a function");
4936 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4937 warningf(pos, "'main' is normally a non-static function");
4940 type_t *type = skip_typeref(entity->declaration.type);
4941 assert(is_type_function(type));
4943 function_type_t *func_type = &type->function;
4944 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4945 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4946 func_type->return_type);
4948 const function_parameter_t *parm = func_type->parameters;
4950 type_t *const first_type = parm->type;
4951 if (!types_compatible(skip_typeref(first_type), type_int)) {
4953 "first argument of 'main' should be 'int', but is '%T'",
4958 type_t *const second_type = parm->type;
4959 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4960 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4964 type_t *const third_type = parm->type;
4965 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4966 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4970 goto warn_arg_count;
4974 warningf(pos, "'main' takes only zero, two or three arguments");
4980 * Check if a symbol is the equal to "main".
4982 static bool is_sym_main(const symbol_t *const sym)
4984 return strcmp(sym->string, "main") == 0;
4987 static void error_redefined_as_different_kind(const source_position_t *pos,
4988 const entity_t *old, entity_kind_t new_kind)
4990 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4991 get_entity_kind_name(old->kind), old->base.symbol,
4992 get_entity_kind_name(new_kind), &old->base.source_position);
4995 static bool is_error_entity(entity_t *const ent)
4997 if (is_declaration(ent)) {
4998 return is_type_valid(skip_typeref(ent->declaration.type));
4999 } else if (ent->kind == ENTITY_TYPEDEF) {
5000 return is_type_valid(skip_typeref(ent->typedefe.type));
5006 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
5007 * for various problems that occur for multiple definitions
5009 static entity_t *record_entity(entity_t *entity, const bool is_definition)
5011 const symbol_t *const symbol = entity->base.symbol;
5012 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
5013 const source_position_t *pos = &entity->base.source_position;
5015 /* can happen in error cases */
5019 entity_t *const previous_entity = get_entity(symbol, namespc);
5020 /* pushing the same entity twice will break the stack structure */
5021 assert(previous_entity != entity);
5023 if (entity->kind == ENTITY_FUNCTION) {
5024 type_t *const orig_type = entity->declaration.type;
5025 type_t *const type = skip_typeref(orig_type);
5027 assert(is_type_function(type));
5028 if (type->function.unspecified_parameters &&
5029 warning.strict_prototypes &&
5030 previous_entity == NULL) {
5031 warningf(pos, "function declaration '%#T' is not a prototype",
5035 if (warning.main && current_scope == file_scope
5036 && is_sym_main(symbol)) {
5037 check_type_of_main(entity);
5041 if (is_declaration(entity) &&
5042 warning.nested_externs &&
5043 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
5044 current_scope != file_scope) {
5045 warningf(pos, "nested extern declaration of '%#T'",
5046 entity->declaration.type, symbol);
5049 if (previous_entity != NULL) {
5050 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
5051 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
5052 assert(previous_entity->kind == ENTITY_PARAMETER);
5054 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
5055 entity->declaration.type, symbol,
5056 previous_entity->declaration.type, symbol,
5057 &previous_entity->base.source_position);
5061 if (previous_entity->base.parent_scope == current_scope) {
5062 if (previous_entity->kind != entity->kind) {
5063 if (!is_error_entity(previous_entity) && !is_error_entity(entity)) {
5064 error_redefined_as_different_kind(pos, previous_entity,
5069 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
5070 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
5071 symbol, &previous_entity->base.source_position);
5074 if (previous_entity->kind == ENTITY_TYPEDEF) {
5075 /* TODO: C++ allows this for exactly the same type */
5076 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
5077 symbol, &previous_entity->base.source_position);
5081 /* at this point we should have only VARIABLES or FUNCTIONS */
5082 assert(is_declaration(previous_entity) && is_declaration(entity));
5084 declaration_t *const prev_decl = &previous_entity->declaration;
5085 declaration_t *const decl = &entity->declaration;
5087 /* can happen for K&R style declarations */
5088 if (prev_decl->type == NULL &&
5089 previous_entity->kind == ENTITY_PARAMETER &&
5090 entity->kind == ENTITY_PARAMETER) {
5091 prev_decl->type = decl->type;
5092 prev_decl->storage_class = decl->storage_class;
5093 prev_decl->declared_storage_class = decl->declared_storage_class;
5094 prev_decl->modifiers = decl->modifiers;
5095 prev_decl->deprecated_string = decl->deprecated_string;
5096 return previous_entity;
5099 type_t *const orig_type = decl->type;
5100 assert(orig_type != NULL);
5101 type_t *const type = skip_typeref(orig_type);
5102 type_t *const prev_type = skip_typeref(prev_decl->type);
5104 if (!types_compatible(type, prev_type)) {
5106 "declaration '%#T' is incompatible with '%#T' (declared %P)",
5107 orig_type, symbol, prev_decl->type, symbol,
5108 &previous_entity->base.source_position);
5110 unsigned old_storage_class = prev_decl->storage_class;
5111 if (warning.redundant_decls &&
5114 !(prev_decl->modifiers & DM_USED) &&
5115 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
5116 warningf(&previous_entity->base.source_position,
5117 "unnecessary static forward declaration for '%#T'",
5118 prev_decl->type, symbol);
5121 storage_class_t new_storage_class = decl->storage_class;
5123 /* pretend no storage class means extern for function
5124 * declarations (except if the previous declaration is neither
5125 * none nor extern) */
5126 if (entity->kind == ENTITY_FUNCTION) {
5127 /* the previous declaration could have unspecified parameters or
5128 * be a typedef, so use the new type */
5129 if (prev_type->function.unspecified_parameters || is_definition)
5130 prev_decl->type = type;
5132 switch (old_storage_class) {
5133 case STORAGE_CLASS_NONE:
5134 old_storage_class = STORAGE_CLASS_EXTERN;
5137 case STORAGE_CLASS_EXTERN:
5138 if (is_definition) {
5139 if (warning.missing_prototypes &&
5140 prev_type->function.unspecified_parameters &&
5141 !is_sym_main(symbol)) {
5142 warningf(pos, "no previous prototype for '%#T'",
5145 } else if (new_storage_class == STORAGE_CLASS_NONE) {
5146 new_storage_class = STORAGE_CLASS_EXTERN;
5153 } else if (is_type_incomplete(prev_type)) {
5154 prev_decl->type = type;
5157 if (old_storage_class == STORAGE_CLASS_EXTERN &&
5158 new_storage_class == STORAGE_CLASS_EXTERN) {
5159 warn_redundant_declaration:
5160 if (!is_definition &&
5161 warning.redundant_decls &&
5162 is_type_valid(prev_type) &&
5163 strcmp(previous_entity->base.source_position.input_name,
5164 "<builtin>") != 0) {
5166 "redundant declaration for '%Y' (declared %P)",
5167 symbol, &previous_entity->base.source_position);
5169 } else if (current_function == NULL) {
5170 if (old_storage_class != STORAGE_CLASS_STATIC &&
5171 new_storage_class == STORAGE_CLASS_STATIC) {
5173 "static declaration of '%Y' follows non-static declaration (declared %P)",
5174 symbol, &previous_entity->base.source_position);
5175 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
5176 prev_decl->storage_class = STORAGE_CLASS_NONE;
5177 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
5179 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
5181 goto error_redeclaration;
5182 goto warn_redundant_declaration;
5184 } else if (is_type_valid(prev_type)) {
5185 if (old_storage_class == new_storage_class) {
5186 error_redeclaration:
5187 errorf(pos, "redeclaration of '%Y' (declared %P)",
5188 symbol, &previous_entity->base.source_position);
5191 "redeclaration of '%Y' with different linkage (declared %P)",
5192 symbol, &previous_entity->base.source_position);
5197 prev_decl->modifiers |= decl->modifiers;
5198 if (entity->kind == ENTITY_FUNCTION) {
5199 previous_entity->function.is_inline |= entity->function.is_inline;
5201 return previous_entity;
5204 if (warning.shadow) {
5205 warningf(pos, "%s '%Y' shadows %s (declared %P)",
5206 get_entity_kind_name(entity->kind), symbol,
5207 get_entity_kind_name(previous_entity->kind),
5208 &previous_entity->base.source_position);
5212 if (entity->kind == ENTITY_FUNCTION) {
5213 if (is_definition &&
5214 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
5215 if (warning.missing_prototypes && !is_sym_main(symbol)) {
5216 warningf(pos, "no previous prototype for '%#T'",
5217 entity->declaration.type, symbol);
5218 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
5219 warningf(pos, "no previous declaration for '%#T'",
5220 entity->declaration.type, symbol);
5223 } else if (warning.missing_declarations &&
5224 entity->kind == ENTITY_VARIABLE &&
5225 current_scope == file_scope) {
5226 declaration_t *declaration = &entity->declaration;
5227 if (declaration->storage_class == STORAGE_CLASS_NONE) {
5228 warningf(pos, "no previous declaration for '%#T'",
5229 declaration->type, symbol);
5234 assert(entity->base.parent_scope == NULL);
5235 assert(current_scope != NULL);
5237 entity->base.parent_scope = current_scope;
5238 entity->base.namespc = NAMESPACE_NORMAL;
5239 environment_push(entity);
5240 append_entity(current_scope, entity);
5245 static void parser_error_multiple_definition(entity_t *entity,
5246 const source_position_t *source_position)
5248 errorf(source_position, "multiple definition of '%Y' (declared %P)",
5249 entity->base.symbol, &entity->base.source_position);
5252 static bool is_declaration_specifier(const token_t *token,
5253 bool only_specifiers_qualifiers)
5255 switch (token->type) {
5260 return is_typedef_symbol(token->v.symbol);
5262 case T___extension__:
5264 return !only_specifiers_qualifiers;
5271 static void parse_init_declarator_rest(entity_t *entity)
5273 assert(is_declaration(entity));
5274 declaration_t *const declaration = &entity->declaration;
5278 type_t *orig_type = declaration->type;
5279 type_t *type = skip_typeref(orig_type);
5281 if (entity->kind == ENTITY_VARIABLE
5282 && entity->variable.initializer != NULL) {
5283 parser_error_multiple_definition(entity, HERE);
5286 bool must_be_constant = false;
5287 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5288 entity->base.parent_scope == file_scope) {
5289 must_be_constant = true;
5292 if (is_type_function(type)) {
5293 errorf(&entity->base.source_position,
5294 "function '%#T' is initialized like a variable",
5295 orig_type, entity->base.symbol);
5296 orig_type = type_error_type;
5299 parse_initializer_env_t env;
5300 env.type = orig_type;
5301 env.must_be_constant = must_be_constant;
5302 env.entity = entity;
5303 current_init_decl = entity;
5305 initializer_t *initializer = parse_initializer(&env);
5306 current_init_decl = NULL;
5308 if (entity->kind == ENTITY_VARIABLE) {
5309 /* §6.7.5:22 array initializers for arrays with unknown size
5310 * determine the array type size */
5311 declaration->type = env.type;
5312 entity->variable.initializer = initializer;
5316 /* parse rest of a declaration without any declarator */
5317 static void parse_anonymous_declaration_rest(
5318 const declaration_specifiers_t *specifiers)
5321 anonymous_entity = NULL;
5323 if (warning.other) {
5324 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
5325 specifiers->thread_local) {
5326 warningf(&specifiers->source_position,
5327 "useless storage class in empty declaration");
5330 type_t *type = specifiers->type;
5331 switch (type->kind) {
5332 case TYPE_COMPOUND_STRUCT:
5333 case TYPE_COMPOUND_UNION: {
5334 if (type->compound.compound->base.symbol == NULL) {
5335 warningf(&specifiers->source_position,
5336 "unnamed struct/union that defines no instances");
5345 warningf(&specifiers->source_position, "empty declaration");
5351 static void check_variable_type_complete(entity_t *ent)
5353 if (ent->kind != ENTITY_VARIABLE)
5356 /* §6.7:7 If an identifier for an object is declared with no linkage, the
5357 * type for the object shall be complete [...] */
5358 declaration_t *decl = &ent->declaration;
5359 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
5360 decl->storage_class == STORAGE_CLASS_STATIC)
5363 type_t *const orig_type = decl->type;
5364 type_t *const type = skip_typeref(orig_type);
5365 if (!is_type_incomplete(type))
5368 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
5369 * are given length one. */
5370 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
5371 ARR_APP1(declaration_t*, incomplete_arrays, decl);
5375 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
5376 orig_type, ent->base.symbol);
5380 static void parse_declaration_rest(entity_t *ndeclaration,
5381 const declaration_specifiers_t *specifiers,
5382 parsed_declaration_func finished_declaration,
5383 declarator_flags_t flags)
5385 add_anchor_token(';');
5386 add_anchor_token(',');
5388 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5390 if (token.type == '=') {
5391 parse_init_declarator_rest(entity);
5392 } else if (entity->kind == ENTITY_VARIABLE) {
5393 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
5394 * [...] where the extern specifier is explicitly used. */
5395 declaration_t *decl = &entity->declaration;
5396 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
5397 type_t *type = decl->type;
5398 if (is_type_reference(skip_typeref(type))) {
5399 errorf(&entity->base.source_position,
5400 "reference '%#T' must be initialized",
5401 type, entity->base.symbol);
5406 check_variable_type_complete(entity);
5408 if (token.type != ',')
5412 add_anchor_token('=');
5413 ndeclaration = parse_declarator(specifiers, flags);
5414 rem_anchor_token('=');
5416 expect(';', end_error);
5419 anonymous_entity = NULL;
5420 rem_anchor_token(';');
5421 rem_anchor_token(',');
5424 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5426 symbol_t *symbol = entity->base.symbol;
5427 if (symbol == NULL) {
5428 errorf(HERE, "anonymous declaration not valid as function parameter");
5432 assert(entity->base.namespc == NAMESPACE_NORMAL);
5433 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5434 if (previous_entity == NULL
5435 || previous_entity->base.parent_scope != current_scope) {
5436 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5441 if (is_definition) {
5442 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
5445 return record_entity(entity, false);
5448 static void parse_declaration(parsed_declaration_func finished_declaration,
5449 declarator_flags_t flags)
5451 declaration_specifiers_t specifiers;
5452 memset(&specifiers, 0, sizeof(specifiers));
5454 add_anchor_token(';');
5455 parse_declaration_specifiers(&specifiers);
5456 rem_anchor_token(';');
5458 if (token.type == ';') {
5459 parse_anonymous_declaration_rest(&specifiers);
5461 entity_t *entity = parse_declarator(&specifiers, flags);
5462 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
5466 static type_t *get_default_promoted_type(type_t *orig_type)
5468 type_t *result = orig_type;
5470 type_t *type = skip_typeref(orig_type);
5471 if (is_type_integer(type)) {
5472 result = promote_integer(type);
5473 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
5474 result = type_double;
5480 static void parse_kr_declaration_list(entity_t *entity)
5482 if (entity->kind != ENTITY_FUNCTION)
5485 type_t *type = skip_typeref(entity->declaration.type);
5486 assert(is_type_function(type));
5487 if (!type->function.kr_style_parameters)
5491 add_anchor_token('{');
5493 /* push function parameters */
5494 size_t const top = environment_top();
5495 scope_t *old_scope = scope_push(&entity->function.parameters);
5497 entity_t *parameter = entity->function.parameters.entities;
5498 for ( ; parameter != NULL; parameter = parameter->base.next) {
5499 assert(parameter->base.parent_scope == NULL);
5500 parameter->base.parent_scope = current_scope;
5501 environment_push(parameter);
5504 /* parse declaration list */
5506 switch (token.type) {
5508 case T___extension__:
5509 /* This covers symbols, which are no type, too, and results in
5510 * better error messages. The typical cases are misspelled type
5511 * names and missing includes. */
5513 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
5521 /* pop function parameters */
5522 assert(current_scope == &entity->function.parameters);
5523 scope_pop(old_scope);
5524 environment_pop_to(top);
5526 /* update function type */
5527 type_t *new_type = duplicate_type(type);
5529 function_parameter_t *parameters = NULL;
5530 function_parameter_t **anchor = ¶meters;
5532 parameter = entity->function.parameters.entities;
5533 for (; parameter != NULL; parameter = parameter->base.next) {
5534 if (parameter->kind != ENTITY_PARAMETER)
5537 type_t *parameter_type = parameter->declaration.type;
5538 if (parameter_type == NULL) {
5540 errorf(HERE, "no type specified for function parameter '%Y'",
5541 parameter->base.symbol);
5543 if (warning.implicit_int) {
5544 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5545 parameter->base.symbol);
5547 parameter_type = type_int;
5548 parameter->declaration.type = parameter_type;
5552 semantic_parameter_incomplete(parameter);
5553 parameter_type = parameter->declaration.type;
5556 * we need the default promoted types for the function type
5558 parameter_type = get_default_promoted_type(parameter_type);
5560 function_parameter_t *const parameter =
5561 allocate_parameter(parameter_type);
5563 *anchor = parameter;
5564 anchor = ¶meter->next;
5567 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
5569 new_type->function.parameters = parameters;
5570 new_type->function.unspecified_parameters = true;
5572 new_type = identify_new_type(new_type);
5574 entity->declaration.type = new_type;
5576 rem_anchor_token('{');
5579 static bool first_err = true;
5582 * When called with first_err set, prints the name of the current function,
5585 static void print_in_function(void)
5589 diagnosticf("%s: In function '%Y':\n",
5590 current_function->base.base.source_position.input_name,
5591 current_function->base.base.symbol);
5596 * Check if all labels are defined in the current function.
5597 * Check if all labels are used in the current function.
5599 static void check_labels(void)
5601 for (const goto_statement_t *goto_statement = goto_first;
5602 goto_statement != NULL;
5603 goto_statement = goto_statement->next) {
5604 /* skip computed gotos */
5605 if (goto_statement->expression != NULL)
5608 label_t *label = goto_statement->label;
5611 if (label->base.source_position.input_name == NULL) {
5612 print_in_function();
5613 errorf(&goto_statement->base.source_position,
5614 "label '%Y' used but not defined", label->base.symbol);
5618 if (warning.unused_label) {
5619 for (const label_statement_t *label_statement = label_first;
5620 label_statement != NULL;
5621 label_statement = label_statement->next) {
5622 label_t *label = label_statement->label;
5624 if (! label->used) {
5625 print_in_function();
5626 warningf(&label_statement->base.source_position,
5627 "label '%Y' defined but not used", label->base.symbol);
5633 static void warn_unused_entity(entity_t *entity, entity_t *last)
5635 entity_t const *const end = last != NULL ? last->base.next : NULL;
5636 for (; entity != end; entity = entity->base.next) {
5637 if (!is_declaration(entity))
5640 declaration_t *declaration = &entity->declaration;
5641 if (declaration->implicit)
5644 if (!declaration->used) {
5645 print_in_function();
5646 const char *what = get_entity_kind_name(entity->kind);
5647 warningf(&entity->base.source_position, "%s '%Y' is unused",
5648 what, entity->base.symbol);
5649 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5650 print_in_function();
5651 const char *what = get_entity_kind_name(entity->kind);
5652 warningf(&entity->base.source_position, "%s '%Y' is never read",
5653 what, entity->base.symbol);
5658 static void check_unused_variables(statement_t *const stmt, void *const env)
5662 switch (stmt->kind) {
5663 case STATEMENT_DECLARATION: {
5664 declaration_statement_t const *const decls = &stmt->declaration;
5665 warn_unused_entity(decls->declarations_begin,
5666 decls->declarations_end);
5671 warn_unused_entity(stmt->fors.scope.entities, NULL);
5680 * Check declarations of current_function for unused entities.
5682 static void check_declarations(void)
5684 if (warning.unused_parameter) {
5685 const scope_t *scope = ¤t_function->parameters;
5687 /* do not issue unused warnings for main */
5688 if (!is_sym_main(current_function->base.base.symbol)) {
5689 warn_unused_entity(scope->entities, NULL);
5692 if (warning.unused_variable) {
5693 walk_statements(current_function->statement, check_unused_variables,
5698 static int determine_truth(expression_t const* const cond)
5701 !is_constant_expression(cond) ? 0 :
5702 fold_constant(cond) != 0 ? 1 :
5706 static void check_reachable(statement_t *);
5707 static bool reaches_end;
5709 static bool expression_returns(expression_t const *const expr)
5711 switch (expr->kind) {
5713 expression_t const *const func = expr->call.function;
5714 if (func->kind == EXPR_REFERENCE) {
5715 entity_t *entity = func->reference.entity;
5716 if (entity->kind == ENTITY_FUNCTION
5717 && entity->declaration.modifiers & DM_NORETURN)
5721 if (!expression_returns(func))
5724 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5725 if (!expression_returns(arg->expression))
5732 case EXPR_REFERENCE:
5733 case EXPR_REFERENCE_ENUM_VALUE:
5735 case EXPR_CHARACTER_CONSTANT:
5736 case EXPR_WIDE_CHARACTER_CONSTANT:
5737 case EXPR_STRING_LITERAL:
5738 case EXPR_WIDE_STRING_LITERAL:
5739 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5740 case EXPR_LABEL_ADDRESS:
5741 case EXPR_CLASSIFY_TYPE:
5742 case EXPR_SIZEOF: // TODO handle obscure VLA case
5745 case EXPR_BUILTIN_CONSTANT_P:
5746 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
5751 case EXPR_STATEMENT: {
5752 bool old_reaches_end = reaches_end;
5753 reaches_end = false;
5754 check_reachable(expr->statement.statement);
5755 bool returns = reaches_end;
5756 reaches_end = old_reaches_end;
5760 case EXPR_CONDITIONAL:
5761 // TODO handle constant expression
5763 if (!expression_returns(expr->conditional.condition))
5766 if (expr->conditional.true_expression != NULL
5767 && expression_returns(expr->conditional.true_expression))
5770 return expression_returns(expr->conditional.false_expression);
5773 return expression_returns(expr->select.compound);
5775 case EXPR_ARRAY_ACCESS:
5777 expression_returns(expr->array_access.array_ref) &&
5778 expression_returns(expr->array_access.index);
5781 return expression_returns(expr->va_starte.ap);
5784 return expression_returns(expr->va_arge.ap);
5787 return expression_returns(expr->va_copye.src);
5789 EXPR_UNARY_CASES_MANDATORY
5790 return expression_returns(expr->unary.value);
5792 case EXPR_UNARY_THROW:
5796 // TODO handle constant lhs of && and ||
5798 expression_returns(expr->binary.left) &&
5799 expression_returns(expr->binary.right);
5805 panic("unhandled expression");
5808 static bool initializer_returns(initializer_t const *const init)
5810 switch (init->kind) {
5811 case INITIALIZER_VALUE:
5812 return expression_returns(init->value.value);
5814 case INITIALIZER_LIST: {
5815 initializer_t * const* i = init->list.initializers;
5816 initializer_t * const* const end = i + init->list.len;
5817 bool returns = true;
5818 for (; i != end; ++i) {
5819 if (!initializer_returns(*i))
5825 case INITIALIZER_STRING:
5826 case INITIALIZER_WIDE_STRING:
5827 case INITIALIZER_DESIGNATOR: // designators have no payload
5830 panic("unhandled initializer");
5833 static bool noreturn_candidate;
5835 static void check_reachable(statement_t *const stmt)
5837 if (stmt->base.reachable)
5839 if (stmt->kind != STATEMENT_DO_WHILE)
5840 stmt->base.reachable = true;
5842 statement_t *last = stmt;
5844 switch (stmt->kind) {
5845 case STATEMENT_INVALID:
5846 case STATEMENT_EMPTY:
5848 next = stmt->base.next;
5851 case STATEMENT_DECLARATION: {
5852 declaration_statement_t const *const decl = &stmt->declaration;
5853 entity_t const * ent = decl->declarations_begin;
5854 entity_t const *const last = decl->declarations_end;
5856 for (;; ent = ent->base.next) {
5857 if (ent->kind == ENTITY_VARIABLE &&
5858 ent->variable.initializer != NULL &&
5859 !initializer_returns(ent->variable.initializer)) {
5866 next = stmt->base.next;
5870 case STATEMENT_COMPOUND:
5871 next = stmt->compound.statements;
5873 next = stmt->base.next;
5876 case STATEMENT_RETURN: {
5877 expression_t const *const val = stmt->returns.value;
5878 if (val == NULL || expression_returns(val))
5879 noreturn_candidate = false;
5883 case STATEMENT_IF: {
5884 if_statement_t const *const ifs = &stmt->ifs;
5885 expression_t const *const cond = ifs->condition;
5887 if (!expression_returns(cond))
5890 int const val = determine_truth(cond);
5893 check_reachable(ifs->true_statement);
5898 if (ifs->false_statement != NULL) {
5899 check_reachable(ifs->false_statement);
5903 next = stmt->base.next;
5907 case STATEMENT_SWITCH: {
5908 switch_statement_t const *const switchs = &stmt->switchs;
5909 expression_t const *const expr = switchs->expression;
5911 if (!expression_returns(expr))
5914 if (is_constant_expression(expr)) {
5915 long const val = fold_constant(expr);
5916 case_label_statement_t * defaults = NULL;
5917 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5918 if (i->expression == NULL) {
5923 if (i->first_case <= val && val <= i->last_case) {
5924 check_reachable((statement_t*)i);
5929 if (defaults != NULL) {
5930 check_reachable((statement_t*)defaults);
5934 bool has_default = false;
5935 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5936 if (i->expression == NULL)
5939 check_reachable((statement_t*)i);
5946 next = stmt->base.next;
5950 case STATEMENT_EXPRESSION: {
5951 /* Check for noreturn function call */
5952 expression_t const *const expr = stmt->expression.expression;
5953 if (!expression_returns(expr))
5956 next = stmt->base.next;
5960 case STATEMENT_CONTINUE: {
5961 statement_t *parent = stmt;
5963 parent = parent->base.parent;
5964 if (parent == NULL) /* continue not within loop */
5968 switch (parent->kind) {
5969 case STATEMENT_WHILE: goto continue_while;
5970 case STATEMENT_DO_WHILE: goto continue_do_while;
5971 case STATEMENT_FOR: goto continue_for;
5978 case STATEMENT_BREAK: {
5979 statement_t *parent = stmt;
5981 parent = parent->base.parent;
5982 if (parent == NULL) /* break not within loop/switch */
5985 switch (parent->kind) {
5986 case STATEMENT_SWITCH:
5987 case STATEMENT_WHILE:
5988 case STATEMENT_DO_WHILE:
5991 next = parent->base.next;
5992 goto found_break_parent;
6001 case STATEMENT_GOTO:
6002 if (stmt->gotos.expression) {
6003 if (!expression_returns(stmt->gotos.expression))
6006 statement_t *parent = stmt->base.parent;
6007 if (parent == NULL) /* top level goto */
6011 next = stmt->gotos.label->statement;
6012 if (next == NULL) /* missing label */
6017 case STATEMENT_LABEL:
6018 next = stmt->label.statement;
6021 case STATEMENT_CASE_LABEL:
6022 next = stmt->case_label.statement;
6025 case STATEMENT_WHILE: {
6026 while_statement_t const *const whiles = &stmt->whiles;
6027 expression_t const *const cond = whiles->condition;
6029 if (!expression_returns(cond))
6032 int const val = determine_truth(cond);
6035 check_reachable(whiles->body);
6040 next = stmt->base.next;
6044 case STATEMENT_DO_WHILE:
6045 next = stmt->do_while.body;
6048 case STATEMENT_FOR: {
6049 for_statement_t *const fors = &stmt->fors;
6051 if (fors->condition_reachable)
6053 fors->condition_reachable = true;
6055 expression_t const *const cond = fors->condition;
6060 } else if (expression_returns(cond)) {
6061 val = determine_truth(cond);
6067 check_reachable(fors->body);
6072 next = stmt->base.next;
6076 case STATEMENT_MS_TRY: {
6077 ms_try_statement_t const *const ms_try = &stmt->ms_try;
6078 check_reachable(ms_try->try_statement);
6079 next = ms_try->final_statement;
6083 case STATEMENT_LEAVE: {
6084 statement_t *parent = stmt;
6086 parent = parent->base.parent;
6087 if (parent == NULL) /* __leave not within __try */
6090 if (parent->kind == STATEMENT_MS_TRY) {
6092 next = parent->ms_try.final_statement;
6100 panic("invalid statement kind");
6103 while (next == NULL) {
6104 next = last->base.parent;
6106 noreturn_candidate = false;
6108 type_t *const type = skip_typeref(current_function->base.type);
6109 assert(is_type_function(type));
6110 type_t *const ret = skip_typeref(type->function.return_type);
6111 if (warning.return_type &&
6112 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
6113 is_type_valid(ret) &&
6114 !is_sym_main(current_function->base.base.symbol)) {
6115 warningf(&stmt->base.source_position,
6116 "control reaches end of non-void function");
6121 switch (next->kind) {
6122 case STATEMENT_INVALID:
6123 case STATEMENT_EMPTY:
6124 case STATEMENT_DECLARATION:
6125 case STATEMENT_EXPRESSION:
6127 case STATEMENT_RETURN:
6128 case STATEMENT_CONTINUE:
6129 case STATEMENT_BREAK:
6130 case STATEMENT_GOTO:
6131 case STATEMENT_LEAVE:
6132 panic("invalid control flow in function");
6134 case STATEMENT_COMPOUND:
6135 if (next->compound.stmt_expr) {
6141 case STATEMENT_SWITCH:
6142 case STATEMENT_LABEL:
6143 case STATEMENT_CASE_LABEL:
6145 next = next->base.next;
6148 case STATEMENT_WHILE: {
6150 if (next->base.reachable)
6152 next->base.reachable = true;
6154 while_statement_t const *const whiles = &next->whiles;
6155 expression_t const *const cond = whiles->condition;
6157 if (!expression_returns(cond))
6160 int const val = determine_truth(cond);
6163 check_reachable(whiles->body);
6169 next = next->base.next;
6173 case STATEMENT_DO_WHILE: {
6175 if (next->base.reachable)
6177 next->base.reachable = true;
6179 do_while_statement_t const *const dw = &next->do_while;
6180 expression_t const *const cond = dw->condition;
6182 if (!expression_returns(cond))
6185 int const val = determine_truth(cond);
6188 check_reachable(dw->body);
6194 next = next->base.next;
6198 case STATEMENT_FOR: {
6200 for_statement_t *const fors = &next->fors;
6202 fors->step_reachable = true;
6204 if (fors->condition_reachable)
6206 fors->condition_reachable = true;
6208 expression_t const *const cond = fors->condition;
6213 } else if (expression_returns(cond)) {
6214 val = determine_truth(cond);
6220 check_reachable(fors->body);
6226 next = next->base.next;
6230 case STATEMENT_MS_TRY:
6232 next = next->ms_try.final_statement;
6237 check_reachable(next);
6240 static void check_unreachable(statement_t* const stmt, void *const env)
6244 switch (stmt->kind) {
6245 case STATEMENT_DO_WHILE:
6246 if (!stmt->base.reachable) {
6247 expression_t const *const cond = stmt->do_while.condition;
6248 if (determine_truth(cond) >= 0) {
6249 warningf(&cond->base.source_position,
6250 "condition of do-while-loop is unreachable");
6255 case STATEMENT_FOR: {
6256 for_statement_t const* const fors = &stmt->fors;
6258 // if init and step are unreachable, cond is unreachable, too
6259 if (!stmt->base.reachable && !fors->step_reachable) {
6260 warningf(&stmt->base.source_position, "statement is unreachable");
6262 if (!stmt->base.reachable && fors->initialisation != NULL) {
6263 warningf(&fors->initialisation->base.source_position,
6264 "initialisation of for-statement is unreachable");
6267 if (!fors->condition_reachable && fors->condition != NULL) {
6268 warningf(&fors->condition->base.source_position,
6269 "condition of for-statement is unreachable");
6272 if (!fors->step_reachable && fors->step != NULL) {
6273 warningf(&fors->step->base.source_position,
6274 "step of for-statement is unreachable");
6280 case STATEMENT_COMPOUND:
6281 if (stmt->compound.statements != NULL)
6283 goto warn_unreachable;
6285 case STATEMENT_DECLARATION: {
6286 /* Only warn if there is at least one declarator with an initializer.
6287 * This typically occurs in switch statements. */
6288 declaration_statement_t const *const decl = &stmt->declaration;
6289 entity_t const * ent = decl->declarations_begin;
6290 entity_t const *const last = decl->declarations_end;
6292 for (;; ent = ent->base.next) {
6293 if (ent->kind == ENTITY_VARIABLE &&
6294 ent->variable.initializer != NULL) {
6295 goto warn_unreachable;
6305 if (!stmt->base.reachable)
6306 warningf(&stmt->base.source_position, "statement is unreachable");
6311 static void parse_external_declaration(void)
6313 /* function-definitions and declarations both start with declaration
6315 declaration_specifiers_t specifiers;
6316 memset(&specifiers, 0, sizeof(specifiers));
6318 add_anchor_token(';');
6319 parse_declaration_specifiers(&specifiers);
6320 rem_anchor_token(';');
6322 /* must be a declaration */
6323 if (token.type == ';') {
6324 parse_anonymous_declaration_rest(&specifiers);
6328 add_anchor_token(',');
6329 add_anchor_token('=');
6330 add_anchor_token(';');
6331 add_anchor_token('{');
6333 /* declarator is common to both function-definitions and declarations */
6334 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
6336 rem_anchor_token('{');
6337 rem_anchor_token(';');
6338 rem_anchor_token('=');
6339 rem_anchor_token(',');
6341 /* must be a declaration */
6342 switch (token.type) {
6346 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
6351 /* must be a function definition */
6352 parse_kr_declaration_list(ndeclaration);
6354 if (token.type != '{') {
6355 parse_error_expected("while parsing function definition", '{', NULL);
6356 eat_until_matching_token(';');
6360 assert(is_declaration(ndeclaration));
6361 type_t *const orig_type = ndeclaration->declaration.type;
6362 type_t * type = skip_typeref(orig_type);
6364 if (!is_type_function(type)) {
6365 if (is_type_valid(type)) {
6366 errorf(HERE, "declarator '%#T' has a body but is not a function type",
6367 type, ndeclaration->base.symbol);
6371 } else if (is_typeref(orig_type)) {
6373 errorf(&ndeclaration->base.source_position,
6374 "type of function definition '%#T' is a typedef",
6375 orig_type, ndeclaration->base.symbol);
6378 if (warning.aggregate_return &&
6379 is_type_compound(skip_typeref(type->function.return_type))) {
6380 warningf(HERE, "function '%Y' returns an aggregate",
6381 ndeclaration->base.symbol);
6383 if (warning.traditional && !type->function.unspecified_parameters) {
6384 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6385 ndeclaration->base.symbol);
6387 if (warning.old_style_definition && type->function.unspecified_parameters) {
6388 warningf(HERE, "old-style function definition '%Y'",
6389 ndeclaration->base.symbol);
6392 /* §6.7.5.3:14 a function definition with () means no
6393 * parameters (and not unspecified parameters) */
6394 if (type->function.unspecified_parameters &&
6395 type->function.parameters == NULL &&
6396 !type->function.kr_style_parameters) {
6397 type_t *copy = duplicate_type(type);
6398 copy->function.unspecified_parameters = false;
6399 type = identify_new_type(copy);
6401 ndeclaration->declaration.type = type;
6404 entity_t *const entity = record_entity(ndeclaration, true);
6405 assert(entity->kind == ENTITY_FUNCTION);
6406 assert(ndeclaration->kind == ENTITY_FUNCTION);
6408 function_t *function = &entity->function;
6409 if (ndeclaration != entity) {
6410 function->parameters = ndeclaration->function.parameters;
6412 assert(is_declaration(entity));
6413 type = skip_typeref(entity->declaration.type);
6415 /* push function parameters and switch scope */
6416 size_t const top = environment_top();
6417 scope_t *old_scope = scope_push(&function->parameters);
6419 entity_t *parameter = function->parameters.entities;
6420 for (; parameter != NULL; parameter = parameter->base.next) {
6421 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6422 parameter->base.parent_scope = current_scope;
6424 assert(parameter->base.parent_scope == NULL
6425 || parameter->base.parent_scope == current_scope);
6426 parameter->base.parent_scope = current_scope;
6427 if (parameter->base.symbol == NULL) {
6428 errorf(¶meter->base.source_position, "parameter name omitted");
6431 environment_push(parameter);
6434 if (function->statement != NULL) {
6435 parser_error_multiple_definition(entity, HERE);
6438 /* parse function body */
6439 int label_stack_top = label_top();
6440 function_t *old_current_function = current_function;
6441 current_function = function;
6442 current_parent = NULL;
6445 goto_anchor = &goto_first;
6447 label_anchor = &label_first;
6449 statement_t *const body = parse_compound_statement(false);
6450 function->statement = body;
6453 check_declarations();
6454 if (warning.return_type ||
6455 warning.unreachable_code ||
6456 (warning.missing_noreturn
6457 && !(function->base.modifiers & DM_NORETURN))) {
6458 noreturn_candidate = true;
6459 check_reachable(body);
6460 if (warning.unreachable_code)
6461 walk_statements(body, check_unreachable, NULL);
6462 if (warning.missing_noreturn &&
6463 noreturn_candidate &&
6464 !(function->base.modifiers & DM_NORETURN)) {
6465 warningf(&body->base.source_position,
6466 "function '%#T' is candidate for attribute 'noreturn'",
6467 type, entity->base.symbol);
6471 assert(current_parent == NULL);
6472 assert(current_function == function);
6473 current_function = old_current_function;
6474 label_pop_to(label_stack_top);
6477 assert(current_scope == &function->parameters);
6478 scope_pop(old_scope);
6479 environment_pop_to(top);
6482 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6483 source_position_t *source_position,
6484 const symbol_t *symbol)
6486 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6488 type->bitfield.base_type = base_type;
6489 type->bitfield.size_expression = size;
6492 type_t *skipped_type = skip_typeref(base_type);
6493 if (!is_type_integer(skipped_type)) {
6494 errorf(HERE, "bitfield base type '%T' is not an integer type",
6498 bit_size = skipped_type->base.size * 8;
6501 if (is_constant_expression(size)) {
6502 long v = fold_constant(size);
6505 errorf(source_position, "negative width in bit-field '%Y'", symbol);
6506 } else if (v == 0) {
6507 errorf(source_position, "zero width for bit-field '%Y'", symbol);
6508 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6509 errorf(source_position, "width of '%Y' exceeds its type", symbol);
6511 type->bitfield.bit_size = v;
6518 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6520 entity_t *iter = compound->members.entities;
6521 for (; iter != NULL; iter = iter->base.next) {
6522 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6525 if (iter->base.symbol == symbol) {
6527 } else if (iter->base.symbol == NULL) {
6528 type_t *type = skip_typeref(iter->declaration.type);
6529 if (is_type_compound(type)) {
6531 = find_compound_entry(type->compound.compound, symbol);
6542 static void parse_compound_declarators(compound_t *compound,
6543 const declaration_specifiers_t *specifiers)
6548 if (token.type == ':') {
6549 source_position_t source_position = *HERE;
6552 type_t *base_type = specifiers->type;
6553 expression_t *size = parse_constant_expression();
6555 type_t *type = make_bitfield_type(base_type, size,
6556 &source_position, sym_anonymous);
6558 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6559 entity->base.namespc = NAMESPACE_NORMAL;
6560 entity->base.source_position = source_position;
6561 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6562 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6563 entity->declaration.modifiers = specifiers->modifiers;
6564 entity->declaration.type = type;
6565 append_entity(&compound->members, entity);
6567 entity = parse_declarator(specifiers,
6568 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
6569 if (entity->kind == ENTITY_TYPEDEF) {
6570 errorf(&entity->base.source_position,
6571 "typedef not allowed as compound member");
6573 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6575 /* make sure we don't define a symbol multiple times */
6576 symbol_t *symbol = entity->base.symbol;
6577 if (symbol != NULL) {
6578 entity_t *prev = find_compound_entry(compound, symbol);
6580 errorf(&entity->base.source_position,
6581 "multiple declarations of symbol '%Y' (declared %P)",
6582 symbol, &prev->base.source_position);
6586 if (token.type == ':') {
6587 source_position_t source_position = *HERE;
6589 expression_t *size = parse_constant_expression();
6591 type_t *type = entity->declaration.type;
6592 type_t *bitfield_type = make_bitfield_type(type, size,
6593 &source_position, entity->base.symbol);
6594 entity->declaration.type = bitfield_type;
6596 type_t *orig_type = entity->declaration.type;
6597 type_t *type = skip_typeref(orig_type);
6598 if (is_type_function(type)) {
6599 errorf(&entity->base.source_position,
6600 "compound member '%Y' must not have function type '%T'",
6601 entity->base.symbol, orig_type);
6602 } else if (is_type_incomplete(type)) {
6603 /* §6.7.2.1:16 flexible array member */
6604 if (!is_type_array(type) ||
6605 token.type != ';' ||
6606 look_ahead(1)->type != '}') {
6607 errorf(&entity->base.source_position,
6608 "compound member '%Y' has incomplete type '%T'",
6609 entity->base.symbol, orig_type);
6614 append_entity(&compound->members, entity);
6618 if (token.type != ',')
6622 expect(';', end_error);
6625 anonymous_entity = NULL;
6628 static void parse_compound_type_entries(compound_t *compound)
6631 add_anchor_token('}');
6633 while (token.type != '}') {
6634 if (token.type == T_EOF) {
6635 errorf(HERE, "EOF while parsing struct");
6638 declaration_specifiers_t specifiers;
6639 memset(&specifiers, 0, sizeof(specifiers));
6640 parse_declaration_specifiers(&specifiers);
6642 parse_compound_declarators(compound, &specifiers);
6644 rem_anchor_token('}');
6648 compound->complete = true;
6651 static type_t *parse_typename(void)
6653 declaration_specifiers_t specifiers;
6654 memset(&specifiers, 0, sizeof(specifiers));
6655 parse_declaration_specifiers(&specifiers);
6656 if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6657 specifiers.thread_local) {
6658 /* TODO: improve error message, user does probably not know what a
6659 * storage class is...
6661 errorf(HERE, "typename may not have a storage class");
6664 type_t *result = parse_abstract_declarator(specifiers.type);
6672 typedef expression_t* (*parse_expression_function)(void);
6673 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6675 typedef struct expression_parser_function_t expression_parser_function_t;
6676 struct expression_parser_function_t {
6677 parse_expression_function parser;
6678 precedence_t infix_precedence;
6679 parse_expression_infix_function infix_parser;
6682 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6685 * Prints an error message if an expression was expected but not read
6687 static expression_t *expected_expression_error(void)
6689 /* skip the error message if the error token was read */
6690 if (token.type != T_ERROR) {
6691 errorf(HERE, "expected expression, got token %K", &token);
6695 return create_invalid_expression();
6699 * Parse a string constant.
6701 static expression_t *parse_string_const(void)
6704 if (token.type == T_STRING_LITERAL) {
6705 string_t res = token.v.string;
6707 while (token.type == T_STRING_LITERAL) {
6708 res = concat_strings(&res, &token.v.string);
6711 if (token.type != T_WIDE_STRING_LITERAL) {
6712 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6713 /* note: that we use type_char_ptr here, which is already the
6714 * automatic converted type. revert_automatic_type_conversion
6715 * will construct the array type */
6716 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6717 cnst->string.value = res;
6721 wres = concat_string_wide_string(&res, &token.v.wide_string);
6723 wres = token.v.wide_string;
6728 switch (token.type) {
6729 case T_WIDE_STRING_LITERAL:
6730 wres = concat_wide_strings(&wres, &token.v.wide_string);
6733 case T_STRING_LITERAL:
6734 wres = concat_wide_string_string(&wres, &token.v.string);
6738 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6739 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6740 cnst->wide_string.value = wres;
6749 * Parse a boolean constant.
6751 static expression_t *parse_bool_const(bool value)
6753 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6754 cnst->base.type = type_bool;
6755 cnst->conste.v.int_value = value;
6763 * Parse an integer constant.
6765 static expression_t *parse_int_const(void)
6767 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6768 cnst->base.type = token.datatype;
6769 cnst->conste.v.int_value = token.v.intvalue;
6777 * Parse a character constant.
6779 static expression_t *parse_character_constant(void)
6781 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6782 cnst->base.type = token.datatype;
6783 cnst->conste.v.character = token.v.string;
6785 if (cnst->conste.v.character.size != 1) {
6787 errorf(HERE, "more than 1 character in character constant");
6788 } else if (warning.multichar) {
6789 warningf(HERE, "multi-character character constant");
6798 * Parse a wide character constant.
6800 static expression_t *parse_wide_character_constant(void)
6802 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6803 cnst->base.type = token.datatype;
6804 cnst->conste.v.wide_character = token.v.wide_string;
6806 if (cnst->conste.v.wide_character.size != 1) {
6808 errorf(HERE, "more than 1 character in character constant");
6809 } else if (warning.multichar) {
6810 warningf(HERE, "multi-character character constant");
6819 * Parse a float constant.
6821 static expression_t *parse_float_const(void)
6823 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6824 cnst->base.type = token.datatype;
6825 cnst->conste.v.float_value = token.v.floatvalue;
6832 static entity_t *create_implicit_function(symbol_t *symbol,
6833 const source_position_t *source_position)
6835 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6836 ntype->function.return_type = type_int;
6837 ntype->function.unspecified_parameters = true;
6838 ntype->function.linkage = LINKAGE_C;
6839 type_t *type = identify_new_type(ntype);
6841 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6842 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6843 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6844 entity->declaration.type = type;
6845 entity->declaration.implicit = true;
6846 entity->base.symbol = symbol;
6847 entity->base.source_position = *source_position;
6849 bool strict_prototypes_old = warning.strict_prototypes;
6850 warning.strict_prototypes = false;
6851 record_entity(entity, false);
6852 warning.strict_prototypes = strict_prototypes_old;
6858 * Creates a return_type (func)(argument_type) function type if not
6861 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6862 type_t *argument_type2)
6864 function_parameter_t *const parameter2 = allocate_parameter(argument_type2);
6865 function_parameter_t *const parameter1 = allocate_parameter(argument_type1);
6866 parameter1->next = parameter2;
6868 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6869 type->function.return_type = return_type;
6870 type->function.parameters = parameter1;
6872 return identify_new_type(type);
6876 * Creates a return_type (func)(argument_type) function type if not
6879 * @param return_type the return type
6880 * @param argument_type the argument type
6882 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6884 function_parameter_t *const parameter = allocate_parameter(argument_type);
6886 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6887 type->function.return_type = return_type;
6888 type->function.parameters = parameter;
6890 return identify_new_type(type);
6893 static type_t *make_function_1_type_variadic(type_t *return_type, type_t *argument_type)
6895 type_t *res = make_function_1_type(return_type, argument_type);
6896 res->function.variadic = 1;
6901 * Creates a return_type (func)(void) function type if not
6904 * @param return_type the return type
6906 static type_t *make_function_0_type(type_t *return_type)
6908 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6909 type->function.return_type = return_type;
6910 type->function.parameters = NULL;
6912 return identify_new_type(type);
6916 * Creates a NO_RETURN return_type (func)(void) function type if not
6919 * @param return_type the return type
6921 static type_t *make_function_0_type_noreturn(type_t *return_type)
6923 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6924 type->function.return_type = return_type;
6925 type->function.parameters = NULL;
6926 type->function.base.modifiers |= DM_NORETURN;
6929 return identify_new_type(type);
6933 * Performs automatic type cast as described in §6.3.2.1.
6935 * @param orig_type the original type
6937 static type_t *automatic_type_conversion(type_t *orig_type)
6939 type_t *type = skip_typeref(orig_type);
6940 if (is_type_array(type)) {
6941 array_type_t *array_type = &type->array;
6942 type_t *element_type = array_type->element_type;
6943 unsigned qualifiers = array_type->base.qualifiers;
6945 return make_pointer_type(element_type, qualifiers);
6948 if (is_type_function(type)) {
6949 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6956 * reverts the automatic casts of array to pointer types and function
6957 * to function-pointer types as defined §6.3.2.1
6959 type_t *revert_automatic_type_conversion(const expression_t *expression)
6961 switch (expression->kind) {
6962 case EXPR_REFERENCE: {
6963 entity_t *entity = expression->reference.entity;
6964 if (is_declaration(entity)) {
6965 return entity->declaration.type;
6966 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6967 return entity->enum_value.enum_type;
6969 panic("no declaration or enum in reference");
6974 entity_t *entity = expression->select.compound_entry;
6975 assert(is_declaration(entity));
6976 type_t *type = entity->declaration.type;
6977 return get_qualified_type(type,
6978 expression->base.type->base.qualifiers);
6981 case EXPR_UNARY_DEREFERENCE: {
6982 const expression_t *const value = expression->unary.value;
6983 type_t *const type = skip_typeref(value->base.type);
6984 if (!is_type_pointer(type))
6985 return type_error_type;
6986 return type->pointer.points_to;
6989 case EXPR_ARRAY_ACCESS: {
6990 const expression_t *array_ref = expression->array_access.array_ref;
6991 type_t *type_left = skip_typeref(array_ref->base.type);
6992 if (!is_type_pointer(type_left))
6993 return type_error_type;
6994 return type_left->pointer.points_to;
6997 case EXPR_STRING_LITERAL: {
6998 size_t size = expression->string.value.size;
6999 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
7002 case EXPR_WIDE_STRING_LITERAL: {
7003 size_t size = expression->wide_string.value.size;
7004 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
7007 case EXPR_COMPOUND_LITERAL:
7008 return expression->compound_literal.type;
7011 return expression->base.type;
7015 static expression_t *parse_reference(void)
7017 symbol_t *const symbol = token.v.symbol;
7019 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
7021 if (entity == NULL) {
7022 if (!strict_mode && look_ahead(1)->type == '(') {
7023 /* an implicitly declared function */
7024 if (warning.error_implicit_function_declaration) {
7025 errorf(HERE, "implicit declaration of function '%Y'", symbol);
7026 } else if (warning.implicit_function_declaration) {
7027 warningf(HERE, "implicit declaration of function '%Y'", symbol);
7030 entity = create_implicit_function(symbol, HERE);
7032 errorf(HERE, "unknown identifier '%Y' found.", symbol);
7033 entity = create_error_entity(symbol, ENTITY_VARIABLE);
7039 if (is_declaration(entity)) {
7040 orig_type = entity->declaration.type;
7041 } else if (entity->kind == ENTITY_ENUM_VALUE) {
7042 orig_type = entity->enum_value.enum_type;
7043 } else if (entity->kind == ENTITY_TYPEDEF) {
7044 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
7047 return create_invalid_expression();
7049 panic("expected declaration or enum value in reference");
7052 /* we always do the auto-type conversions; the & and sizeof parser contains
7053 * code to revert this! */
7054 type_t *type = automatic_type_conversion(orig_type);
7056 expression_kind_t kind = EXPR_REFERENCE;
7057 if (entity->kind == ENTITY_ENUM_VALUE)
7058 kind = EXPR_REFERENCE_ENUM_VALUE;
7060 expression_t *expression = allocate_expression_zero(kind);
7061 expression->reference.entity = entity;
7062 expression->base.type = type;
7064 /* this declaration is used */
7065 if (is_declaration(entity)) {
7066 entity->declaration.used = true;
7069 if (entity->base.parent_scope != file_scope
7070 && entity->base.parent_scope->depth < current_function->parameters.depth
7071 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
7072 if (entity->kind == ENTITY_VARIABLE) {
7073 /* access of a variable from an outer function */
7074 entity->variable.address_taken = true;
7075 } else if (entity->kind == ENTITY_PARAMETER) {
7076 entity->parameter.address_taken = true;
7078 current_function->need_closure = true;
7081 /* check for deprecated functions */
7082 if (warning.deprecated_declarations
7083 && is_declaration(entity)
7084 && entity->declaration.modifiers & DM_DEPRECATED) {
7085 declaration_t *declaration = &entity->declaration;
7087 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
7088 "function" : "variable";
7090 if (declaration->deprecated_string != NULL) {
7091 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
7092 prefix, entity->base.symbol, &entity->base.source_position,
7093 declaration->deprecated_string);
7095 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
7096 entity->base.symbol, &entity->base.source_position);
7100 if (warning.init_self && entity == current_init_decl && !in_type_prop
7101 && entity->kind == ENTITY_VARIABLE) {
7102 current_init_decl = NULL;
7103 warningf(HERE, "variable '%#T' is initialized by itself",
7104 entity->declaration.type, entity->base.symbol);
7111 static bool semantic_cast(expression_t *cast)
7113 expression_t *expression = cast->unary.value;
7114 type_t *orig_dest_type = cast->base.type;
7115 type_t *orig_type_right = expression->base.type;
7116 type_t const *dst_type = skip_typeref(orig_dest_type);
7117 type_t const *src_type = skip_typeref(orig_type_right);
7118 source_position_t const *pos = &cast->base.source_position;
7120 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
7121 if (dst_type == type_void)
7124 /* only integer and pointer can be casted to pointer */
7125 if (is_type_pointer(dst_type) &&
7126 !is_type_pointer(src_type) &&
7127 !is_type_integer(src_type) &&
7128 is_type_valid(src_type)) {
7129 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
7133 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
7134 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
7138 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
7139 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
7143 if (warning.cast_qual &&
7144 is_type_pointer(src_type) &&
7145 is_type_pointer(dst_type)) {
7146 type_t *src = skip_typeref(src_type->pointer.points_to);
7147 type_t *dst = skip_typeref(dst_type->pointer.points_to);
7148 unsigned missing_qualifiers =
7149 src->base.qualifiers & ~dst->base.qualifiers;
7150 if (missing_qualifiers != 0) {
7152 "cast discards qualifiers '%Q' in pointer target type of '%T'",
7153 missing_qualifiers, orig_type_right);
7159 static expression_t *parse_compound_literal(type_t *type)
7161 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
7163 parse_initializer_env_t env;
7166 env.must_be_constant = false;
7167 initializer_t *initializer = parse_initializer(&env);
7170 expression->compound_literal.initializer = initializer;
7171 expression->compound_literal.type = type;
7172 expression->base.type = automatic_type_conversion(type);
7178 * Parse a cast expression.
7180 static expression_t *parse_cast(void)
7182 add_anchor_token(')');
7184 source_position_t source_position = token.source_position;
7186 type_t *type = parse_typename();
7188 rem_anchor_token(')');
7189 expect(')', end_error);
7191 if (token.type == '{') {
7192 return parse_compound_literal(type);
7195 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
7196 cast->base.source_position = source_position;
7198 expression_t *value = parse_sub_expression(PREC_CAST);
7199 cast->base.type = type;
7200 cast->unary.value = value;
7202 if (! semantic_cast(cast)) {
7203 /* TODO: record the error in the AST. else it is impossible to detect it */
7208 return create_invalid_expression();
7212 * Parse a statement expression.
7214 static expression_t *parse_statement_expression(void)
7216 add_anchor_token(')');
7218 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
7220 statement_t *statement = parse_compound_statement(true);
7221 statement->compound.stmt_expr = true;
7222 expression->statement.statement = statement;
7224 /* find last statement and use its type */
7225 type_t *type = type_void;
7226 const statement_t *stmt = statement->compound.statements;
7228 while (stmt->base.next != NULL)
7229 stmt = stmt->base.next;
7231 if (stmt->kind == STATEMENT_EXPRESSION) {
7232 type = stmt->expression.expression->base.type;
7234 } else if (warning.other) {
7235 warningf(&expression->base.source_position, "empty statement expression ({})");
7237 expression->base.type = type;
7239 rem_anchor_token(')');
7240 expect(')', end_error);
7247 * Parse a parenthesized expression.
7249 static expression_t *parse_parenthesized_expression(void)
7253 switch (token.type) {
7255 /* gcc extension: a statement expression */
7256 return parse_statement_expression();
7260 return parse_cast();
7262 if (is_typedef_symbol(token.v.symbol)) {
7263 return parse_cast();
7267 add_anchor_token(')');
7268 expression_t *result = parse_expression();
7269 result->base.parenthesized = true;
7270 rem_anchor_token(')');
7271 expect(')', end_error);
7277 static expression_t *parse_function_keyword(void)
7281 if (current_function == NULL) {
7282 errorf(HERE, "'__func__' used outside of a function");
7285 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7286 expression->base.type = type_char_ptr;
7287 expression->funcname.kind = FUNCNAME_FUNCTION;
7294 static expression_t *parse_pretty_function_keyword(void)
7296 if (current_function == NULL) {
7297 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
7300 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7301 expression->base.type = type_char_ptr;
7302 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
7304 eat(T___PRETTY_FUNCTION__);
7309 static expression_t *parse_funcsig_keyword(void)
7311 if (current_function == NULL) {
7312 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7315 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7316 expression->base.type = type_char_ptr;
7317 expression->funcname.kind = FUNCNAME_FUNCSIG;
7324 static expression_t *parse_funcdname_keyword(void)
7326 if (current_function == NULL) {
7327 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7330 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7331 expression->base.type = type_char_ptr;
7332 expression->funcname.kind = FUNCNAME_FUNCDNAME;
7334 eat(T___FUNCDNAME__);
7339 static designator_t *parse_designator(void)
7341 designator_t *result = allocate_ast_zero(sizeof(result[0]));
7342 result->source_position = *HERE;
7344 if (token.type != T_IDENTIFIER) {
7345 parse_error_expected("while parsing member designator",
7346 T_IDENTIFIER, NULL);
7349 result->symbol = token.v.symbol;
7352 designator_t *last_designator = result;
7354 if (token.type == '.') {
7356 if (token.type != T_IDENTIFIER) {
7357 parse_error_expected("while parsing member designator",
7358 T_IDENTIFIER, NULL);
7361 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7362 designator->source_position = *HERE;
7363 designator->symbol = token.v.symbol;
7366 last_designator->next = designator;
7367 last_designator = designator;
7370 if (token.type == '[') {
7372 add_anchor_token(']');
7373 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7374 designator->source_position = *HERE;
7375 designator->array_index = parse_expression();
7376 rem_anchor_token(']');
7377 expect(']', end_error);
7378 if (designator->array_index == NULL) {
7382 last_designator->next = designator;
7383 last_designator = designator;
7395 * Parse the __builtin_offsetof() expression.
7397 static expression_t *parse_offsetof(void)
7399 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7400 expression->base.type = type_size_t;
7402 eat(T___builtin_offsetof);
7404 expect('(', end_error);
7405 add_anchor_token(',');
7406 type_t *type = parse_typename();
7407 rem_anchor_token(',');
7408 expect(',', end_error);
7409 add_anchor_token(')');
7410 designator_t *designator = parse_designator();
7411 rem_anchor_token(')');
7412 expect(')', end_error);
7414 expression->offsetofe.type = type;
7415 expression->offsetofe.designator = designator;
7418 memset(&path, 0, sizeof(path));
7419 path.top_type = type;
7420 path.path = NEW_ARR_F(type_path_entry_t, 0);
7422 descend_into_subtype(&path);
7424 if (!walk_designator(&path, designator, true)) {
7425 return create_invalid_expression();
7428 DEL_ARR_F(path.path);
7432 return create_invalid_expression();
7436 * Parses a _builtin_va_start() expression.
7438 static expression_t *parse_va_start(void)
7440 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7442 eat(T___builtin_va_start);
7444 expect('(', end_error);
7445 add_anchor_token(',');
7446 expression->va_starte.ap = parse_assignment_expression();
7447 rem_anchor_token(',');
7448 expect(',', end_error);
7449 expression_t *const expr = parse_assignment_expression();
7450 if (expr->kind == EXPR_REFERENCE) {
7451 entity_t *const entity = expr->reference.entity;
7452 if (entity->base.parent_scope != ¤t_function->parameters
7453 || entity->base.next != NULL
7454 || entity->kind != ENTITY_PARAMETER) {
7455 errorf(&expr->base.source_position,
7456 "second argument of 'va_start' must be last parameter of the current function");
7458 expression->va_starte.parameter = &entity->variable;
7460 expect(')', end_error);
7463 expect(')', end_error);
7465 return create_invalid_expression();
7469 * Parses a __builtin_va_arg() expression.
7471 static expression_t *parse_va_arg(void)
7473 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7475 eat(T___builtin_va_arg);
7477 expect('(', end_error);
7479 ap.expression = parse_assignment_expression();
7480 expression->va_arge.ap = ap.expression;
7481 check_call_argument(type_valist, &ap, 1);
7483 expect(',', end_error);
7484 expression->base.type = parse_typename();
7485 expect(')', end_error);
7489 return create_invalid_expression();
7493 * Parses a __builtin_va_copy() expression.
7495 static expression_t *parse_va_copy(void)
7497 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
7499 eat(T___builtin_va_copy);
7501 expect('(', end_error);
7502 expression_t *dst = parse_assignment_expression();
7503 assign_error_t error = semantic_assign(type_valist, dst);
7504 report_assign_error(error, type_valist, dst, "call argument 1",
7505 &dst->base.source_position);
7506 expression->va_copye.dst = dst;
7508 expect(',', end_error);
7510 call_argument_t src;
7511 src.expression = parse_assignment_expression();
7512 check_call_argument(type_valist, &src, 2);
7513 expression->va_copye.src = src.expression;
7514 expect(')', end_error);
7518 return create_invalid_expression();
7522 * Parses a __builtin_constant_p() expression.
7524 static expression_t *parse_builtin_constant(void)
7526 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7528 eat(T___builtin_constant_p);
7530 expect('(', end_error);
7531 add_anchor_token(')');
7532 expression->builtin_constant.value = parse_assignment_expression();
7533 rem_anchor_token(')');
7534 expect(')', end_error);
7535 expression->base.type = type_int;
7539 return create_invalid_expression();
7543 * Parses a __builtin_types_compatible_p() expression.
7545 static expression_t *parse_builtin_types_compatible(void)
7547 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
7549 eat(T___builtin_types_compatible_p);
7551 expect('(', end_error);
7552 add_anchor_token(')');
7553 add_anchor_token(',');
7554 expression->builtin_types_compatible.left = parse_typename();
7555 rem_anchor_token(',');
7556 expect(',', end_error);
7557 expression->builtin_types_compatible.right = parse_typename();
7558 rem_anchor_token(')');
7559 expect(')', end_error);
7560 expression->base.type = type_int;
7564 return create_invalid_expression();
7568 * Parses a __builtin_is_*() compare expression.
7570 static expression_t *parse_compare_builtin(void)
7572 expression_t *expression;
7574 switch (token.type) {
7575 case T___builtin_isgreater:
7576 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7578 case T___builtin_isgreaterequal:
7579 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7581 case T___builtin_isless:
7582 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7584 case T___builtin_islessequal:
7585 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7587 case T___builtin_islessgreater:
7588 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7590 case T___builtin_isunordered:
7591 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7594 internal_errorf(HERE, "invalid compare builtin found");
7596 expression->base.source_position = *HERE;
7599 expect('(', end_error);
7600 expression->binary.left = parse_assignment_expression();
7601 expect(',', end_error);
7602 expression->binary.right = parse_assignment_expression();
7603 expect(')', end_error);
7605 type_t *const orig_type_left = expression->binary.left->base.type;
7606 type_t *const orig_type_right = expression->binary.right->base.type;
7608 type_t *const type_left = skip_typeref(orig_type_left);
7609 type_t *const type_right = skip_typeref(orig_type_right);
7610 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7611 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7612 type_error_incompatible("invalid operands in comparison",
7613 &expression->base.source_position, orig_type_left, orig_type_right);
7616 semantic_comparison(&expression->binary);
7621 return create_invalid_expression();
7626 * Parses a __builtin_expect(, end_error) expression.
7628 static expression_t *parse_builtin_expect(void, end_error)
7630 expression_t *expression
7631 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7633 eat(T___builtin_expect);
7635 expect('(', end_error);
7636 expression->binary.left = parse_assignment_expression();
7637 expect(',', end_error);
7638 expression->binary.right = parse_constant_expression();
7639 expect(')', end_error);
7641 expression->base.type = expression->binary.left->base.type;
7645 return create_invalid_expression();
7650 * Parses a MS assume() expression.
7652 static expression_t *parse_assume(void)
7654 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7658 expect('(', end_error);
7659 add_anchor_token(')');
7660 expression->unary.value = parse_assignment_expression();
7661 rem_anchor_token(')');
7662 expect(')', end_error);
7664 expression->base.type = type_void;
7667 return create_invalid_expression();
7671 * Return the declaration for a given label symbol or create a new one.
7673 * @param symbol the symbol of the label
7675 static label_t *get_label(symbol_t *symbol)
7678 assert(current_function != NULL);
7680 label = get_entity(symbol, NAMESPACE_LABEL);
7681 /* if we found a local label, we already created the declaration */
7682 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7683 if (label->base.parent_scope != current_scope) {
7684 assert(label->base.parent_scope->depth < current_scope->depth);
7685 current_function->goto_to_outer = true;
7687 return &label->label;
7690 label = get_entity(symbol, NAMESPACE_LABEL);
7691 /* if we found a label in the same function, then we already created the
7694 && label->base.parent_scope == ¤t_function->parameters) {
7695 return &label->label;
7698 /* otherwise we need to create a new one */
7699 label = allocate_entity_zero(ENTITY_LABEL);
7700 label->base.namespc = NAMESPACE_LABEL;
7701 label->base.symbol = symbol;
7705 return &label->label;
7709 * Parses a GNU && label address expression.
7711 static expression_t *parse_label_address(void)
7713 source_position_t source_position = token.source_position;
7715 if (token.type != T_IDENTIFIER) {
7716 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7719 symbol_t *symbol = token.v.symbol;
7722 label_t *label = get_label(symbol);
7724 label->address_taken = true;
7726 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7727 expression->base.source_position = source_position;
7729 /* label address is threaten as a void pointer */
7730 expression->base.type = type_void_ptr;
7731 expression->label_address.label = label;
7734 return create_invalid_expression();
7738 * Parse a microsoft __noop expression.
7740 static expression_t *parse_noop_expression(void)
7742 /* the result is a (int)0 */
7743 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7744 cnst->base.type = type_int;
7745 cnst->conste.v.int_value = 0;
7746 cnst->conste.is_ms_noop = true;
7750 if (token.type == '(') {
7751 /* parse arguments */
7753 add_anchor_token(')');
7754 add_anchor_token(',');
7756 if (token.type != ')') {
7758 (void)parse_assignment_expression();
7759 if (token.type != ',')
7765 rem_anchor_token(',');
7766 rem_anchor_token(')');
7767 expect(')', end_error);
7774 * Parses a primary expression.
7776 static expression_t *parse_primary_expression(void)
7778 switch (token.type) {
7779 case T_false: return parse_bool_const(false);
7780 case T_true: return parse_bool_const(true);
7781 case T_INTEGER: return parse_int_const();
7782 case T_CHARACTER_CONSTANT: return parse_character_constant();
7783 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7784 case T_FLOATINGPOINT: return parse_float_const();
7785 case T_STRING_LITERAL:
7786 case T_WIDE_STRING_LITERAL: return parse_string_const();
7787 case T_IDENTIFIER: return parse_reference();
7788 case T___FUNCTION__:
7789 case T___func__: return parse_function_keyword();
7790 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7791 case T___FUNCSIG__: return parse_funcsig_keyword();
7792 case T___FUNCDNAME__: return parse_funcdname_keyword();
7793 case T___builtin_offsetof: return parse_offsetof();
7794 case T___builtin_va_start: return parse_va_start();
7795 case T___builtin_va_arg: return parse_va_arg();
7796 case T___builtin_va_copy: return parse_va_copy();
7797 case T___builtin_isgreater:
7798 case T___builtin_isgreaterequal:
7799 case T___builtin_isless:
7800 case T___builtin_islessequal:
7801 case T___builtin_islessgreater:
7802 case T___builtin_isunordered: return parse_compare_builtin();
7803 case T___builtin_constant_p: return parse_builtin_constant();
7804 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7805 case T__assume: return parse_assume();
7808 return parse_label_address();
7811 case '(': return parse_parenthesized_expression();
7812 case T___noop: return parse_noop_expression();
7815 errorf(HERE, "unexpected token %K, expected an expression", &token);
7816 return create_invalid_expression();
7820 * Check if the expression has the character type and issue a warning then.
7822 static void check_for_char_index_type(const expression_t *expression)
7824 type_t *const type = expression->base.type;
7825 const type_t *const base_type = skip_typeref(type);
7827 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7828 warning.char_subscripts) {
7829 warningf(&expression->base.source_position,
7830 "array subscript has type '%T'", type);
7834 static expression_t *parse_array_expression(expression_t *left)
7836 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7839 add_anchor_token(']');
7841 expression_t *inside = parse_expression();
7843 type_t *const orig_type_left = left->base.type;
7844 type_t *const orig_type_inside = inside->base.type;
7846 type_t *const type_left = skip_typeref(orig_type_left);
7847 type_t *const type_inside = skip_typeref(orig_type_inside);
7849 type_t *return_type;
7850 array_access_expression_t *array_access = &expression->array_access;
7851 if (is_type_pointer(type_left)) {
7852 return_type = type_left->pointer.points_to;
7853 array_access->array_ref = left;
7854 array_access->index = inside;
7855 check_for_char_index_type(inside);
7856 } else if (is_type_pointer(type_inside)) {
7857 return_type = type_inside->pointer.points_to;
7858 array_access->array_ref = inside;
7859 array_access->index = left;
7860 array_access->flipped = true;
7861 check_for_char_index_type(left);
7863 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7865 "array access on object with non-pointer types '%T', '%T'",
7866 orig_type_left, orig_type_inside);
7868 return_type = type_error_type;
7869 array_access->array_ref = left;
7870 array_access->index = inside;
7873 expression->base.type = automatic_type_conversion(return_type);
7875 rem_anchor_token(']');
7876 expect(']', end_error);
7881 static expression_t *parse_typeprop(expression_kind_t const kind)
7883 expression_t *tp_expression = allocate_expression_zero(kind);
7884 tp_expression->base.type = type_size_t;
7886 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7888 /* we only refer to a type property, mark this case */
7889 bool old = in_type_prop;
7890 in_type_prop = true;
7893 expression_t *expression;
7894 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7896 add_anchor_token(')');
7897 orig_type = parse_typename();
7898 rem_anchor_token(')');
7899 expect(')', end_error);
7901 if (token.type == '{') {
7902 /* It was not sizeof(type) after all. It is sizeof of an expression
7903 * starting with a compound literal */
7904 expression = parse_compound_literal(orig_type);
7905 goto typeprop_expression;
7908 expression = parse_sub_expression(PREC_UNARY);
7910 typeprop_expression:
7911 tp_expression->typeprop.tp_expression = expression;
7913 orig_type = revert_automatic_type_conversion(expression);
7914 expression->base.type = orig_type;
7917 tp_expression->typeprop.type = orig_type;
7918 type_t const* const type = skip_typeref(orig_type);
7919 char const* const wrong_type =
7920 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7921 is_type_incomplete(type) ? "incomplete" :
7922 type->kind == TYPE_FUNCTION ? "function designator" :
7923 type->kind == TYPE_BITFIELD ? "bitfield" :
7925 if (wrong_type != NULL) {
7926 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7927 errorf(&tp_expression->base.source_position,
7928 "operand of %s expression must not be of %s type '%T'",
7929 what, wrong_type, orig_type);
7934 return tp_expression;
7937 static expression_t *parse_sizeof(void)
7939 return parse_typeprop(EXPR_SIZEOF);
7942 static expression_t *parse_alignof(void)
7944 return parse_typeprop(EXPR_ALIGNOF);
7947 static expression_t *parse_select_expression(expression_t *compound)
7949 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7950 select->select.compound = compound;
7952 assert(token.type == '.' || token.type == T_MINUSGREATER);
7953 bool is_pointer = (token.type == T_MINUSGREATER);
7956 if (token.type != T_IDENTIFIER) {
7957 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7960 symbol_t *symbol = token.v.symbol;
7963 type_t *const orig_type = compound->base.type;
7964 type_t *const type = skip_typeref(orig_type);
7967 bool saw_error = false;
7968 if (is_type_pointer(type)) {
7971 "request for member '%Y' in something not a struct or union, but '%T'",
7975 type_left = skip_typeref(type->pointer.points_to);
7977 if (is_pointer && is_type_valid(type)) {
7978 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7985 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7986 type_left->kind == TYPE_COMPOUND_UNION) {
7987 compound_t *compound = type_left->compound.compound;
7989 if (!compound->complete) {
7990 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7992 goto create_error_entry;
7995 entry = find_compound_entry(compound, symbol);
7996 if (entry == NULL) {
7997 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7998 goto create_error_entry;
8001 if (is_type_valid(type_left) && !saw_error) {
8003 "request for member '%Y' in something not a struct or union, but '%T'",
8007 entry = create_error_entity(symbol, ENTITY_COMPOUND_MEMBER);
8010 assert(is_declaration(entry));
8011 select->select.compound_entry = entry;
8013 type_t *entry_type = entry->declaration.type;
8015 = get_qualified_type(entry_type, type_left->base.qualifiers);
8017 /* we always do the auto-type conversions; the & and sizeof parser contains
8018 * code to revert this! */
8019 select->base.type = automatic_type_conversion(res_type);
8021 type_t *skipped = skip_typeref(res_type);
8022 if (skipped->kind == TYPE_BITFIELD) {
8023 select->base.type = skipped->bitfield.base_type;
8029 static void check_call_argument(type_t *expected_type,
8030 call_argument_t *argument, unsigned pos)
8032 type_t *expected_type_skip = skip_typeref(expected_type);
8033 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
8034 expression_t *arg_expr = argument->expression;
8035 type_t *arg_type = skip_typeref(arg_expr->base.type);
8037 /* handle transparent union gnu extension */
8038 if (is_type_union(expected_type_skip)
8039 && (expected_type_skip->base.modifiers
8040 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
8041 compound_t *union_decl = expected_type_skip->compound.compound;
8042 type_t *best_type = NULL;
8043 entity_t *entry = union_decl->members.entities;
8044 for ( ; entry != NULL; entry = entry->base.next) {
8045 assert(is_declaration(entry));
8046 type_t *decl_type = entry->declaration.type;
8047 error = semantic_assign(decl_type, arg_expr);
8048 if (error == ASSIGN_ERROR_INCOMPATIBLE
8049 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
8052 if (error == ASSIGN_SUCCESS) {
8053 best_type = decl_type;
8054 } else if (best_type == NULL) {
8055 best_type = decl_type;
8059 if (best_type != NULL) {
8060 expected_type = best_type;
8064 error = semantic_assign(expected_type, arg_expr);
8065 argument->expression = create_implicit_cast(arg_expr, expected_type);
8067 if (error != ASSIGN_SUCCESS) {
8068 /* report exact scope in error messages (like "in argument 3") */
8070 snprintf(buf, sizeof(buf), "call argument %u", pos);
8071 report_assign_error(error, expected_type, arg_expr, buf,
8072 &arg_expr->base.source_position);
8073 } else if (warning.traditional || warning.conversion) {
8074 type_t *const promoted_type = get_default_promoted_type(arg_type);
8075 if (!types_compatible(expected_type_skip, promoted_type) &&
8076 !types_compatible(expected_type_skip, type_void_ptr) &&
8077 !types_compatible(type_void_ptr, promoted_type)) {
8078 /* Deliberately show the skipped types in this warning */
8079 warningf(&arg_expr->base.source_position,
8080 "passing call argument %u as '%T' rather than '%T' due to prototype",
8081 pos, expected_type_skip, promoted_type);
8087 * Handle the semantic restrictions of builtin calls
8089 static void handle_builtin_argument_restrictions(call_expression_t *call) {
8090 switch (call->function->reference.entity->function.btk) {
8091 case bk_gnu_builtin_return_address:
8092 case bk_gnu_builtin_frame_address: {
8093 /* argument must be constant */
8094 call_argument_t *argument = call->arguments;
8096 if (! is_constant_expression(argument->expression)) {
8097 errorf(&call->base.source_position,
8098 "argument of '%Y' must be a constant expression",
8099 call->function->reference.entity->base.symbol);
8103 case bk_gnu_builtin_prefetch: {
8104 /* second and third argument must be constant if existent */
8105 call_argument_t *rw = call->arguments->next;
8106 call_argument_t *locality = NULL;
8109 if (! is_constant_expression(rw->expression)) {
8110 errorf(&call->base.source_position,
8111 "second argument of '%Y' must be a constant expression",
8112 call->function->reference.entity->base.symbol);
8114 locality = rw->next;
8116 if (locality != NULL) {
8117 if (! is_constant_expression(locality->expression)) {
8118 errorf(&call->base.source_position,
8119 "third argument of '%Y' must be a constant expression",
8120 call->function->reference.entity->base.symbol);
8122 locality = rw->next;
8132 * Parse a call expression, ie. expression '( ... )'.
8134 * @param expression the function address
8136 static expression_t *parse_call_expression(expression_t *expression)
8138 expression_t *result = allocate_expression_zero(EXPR_CALL);
8139 call_expression_t *call = &result->call;
8140 call->function = expression;
8142 type_t *const orig_type = expression->base.type;
8143 type_t *const type = skip_typeref(orig_type);
8145 function_type_t *function_type = NULL;
8146 if (is_type_pointer(type)) {
8147 type_t *const to_type = skip_typeref(type->pointer.points_to);
8149 if (is_type_function(to_type)) {
8150 function_type = &to_type->function;
8151 call->base.type = function_type->return_type;
8155 if (function_type == NULL && is_type_valid(type)) {
8156 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
8159 /* parse arguments */
8161 add_anchor_token(')');
8162 add_anchor_token(',');
8164 if (token.type != ')') {
8165 call_argument_t **anchor = &call->arguments;
8167 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
8168 argument->expression = parse_assignment_expression();
8171 anchor = &argument->next;
8173 if (token.type != ',')
8178 rem_anchor_token(',');
8179 rem_anchor_token(')');
8180 expect(')', end_error);
8182 if (function_type == NULL)
8185 function_parameter_t *parameter = function_type->parameters;
8186 call_argument_t *argument = call->arguments;
8187 if (!function_type->unspecified_parameters) {
8188 for (unsigned pos = 0; parameter != NULL && argument != NULL;
8189 parameter = parameter->next, argument = argument->next) {
8190 check_call_argument(parameter->type, argument, ++pos);
8193 if (parameter != NULL) {
8194 errorf(HERE, "too few arguments to function '%E'", expression);
8195 } else if (argument != NULL && !function_type->variadic) {
8196 errorf(HERE, "too many arguments to function '%E'", expression);
8200 /* do default promotion */
8201 for (; argument != NULL; argument = argument->next) {
8202 type_t *type = argument->expression->base.type;
8204 type = get_default_promoted_type(type);
8206 argument->expression
8207 = create_implicit_cast(argument->expression, type);
8210 check_format(&result->call);
8212 if (warning.aggregate_return &&
8213 is_type_compound(skip_typeref(function_type->return_type))) {
8214 warningf(&result->base.source_position,
8215 "function call has aggregate value");
8218 if (call->function->kind == EXPR_REFERENCE) {
8219 reference_expression_t *reference = &call->function->reference;
8220 if (reference->entity->kind == ENTITY_FUNCTION &&
8221 reference->entity->function.btk != bk_none)
8222 handle_builtin_argument_restrictions(call);
8229 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
8231 static bool same_compound_type(const type_t *type1, const type_t *type2)
8234 is_type_compound(type1) &&
8235 type1->kind == type2->kind &&
8236 type1->compound.compound == type2->compound.compound;
8239 static expression_t const *get_reference_address(expression_t const *expr)
8241 bool regular_take_address = true;
8243 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8244 expr = expr->unary.value;
8246 regular_take_address = false;
8249 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8252 expr = expr->unary.value;
8255 if (expr->kind != EXPR_REFERENCE)
8258 /* special case for functions which are automatically converted to a
8259 * pointer to function without an extra TAKE_ADDRESS operation */
8260 if (!regular_take_address &&
8261 expr->reference.entity->kind != ENTITY_FUNCTION) {
8268 static void warn_reference_address_as_bool(expression_t const* expr)
8270 if (!warning.address)
8273 expr = get_reference_address(expr);
8275 warningf(&expr->base.source_position,
8276 "the address of '%Y' will always evaluate as 'true'",
8277 expr->reference.entity->base.symbol);
8281 static void warn_assignment_in_condition(const expression_t *const expr)
8283 if (!warning.parentheses)
8285 if (expr->base.kind != EXPR_BINARY_ASSIGN)
8287 if (expr->base.parenthesized)
8289 warningf(&expr->base.source_position,
8290 "suggest parentheses around assignment used as truth value");
8293 static void semantic_condition(expression_t const *const expr,
8294 char const *const context)
8296 type_t *const type = skip_typeref(expr->base.type);
8297 if (is_type_scalar(type)) {
8298 warn_reference_address_as_bool(expr);
8299 warn_assignment_in_condition(expr);
8300 } else if (is_type_valid(type)) {
8301 errorf(&expr->base.source_position,
8302 "%s must have scalar type", context);
8307 * Parse a conditional expression, ie. 'expression ? ... : ...'.
8309 * @param expression the conditional expression
8311 static expression_t *parse_conditional_expression(expression_t *expression)
8313 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
8315 conditional_expression_t *conditional = &result->conditional;
8316 conditional->condition = expression;
8319 add_anchor_token(':');
8321 /* §6.5.15:2 The first operand shall have scalar type. */
8322 semantic_condition(expression, "condition of conditional operator");
8324 expression_t *true_expression = expression;
8325 bool gnu_cond = false;
8326 if (GNU_MODE && token.type == ':') {
8329 true_expression = parse_expression();
8331 rem_anchor_token(':');
8332 expect(':', end_error);
8334 expression_t *false_expression =
8335 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
8337 type_t *const orig_true_type = true_expression->base.type;
8338 type_t *const orig_false_type = false_expression->base.type;
8339 type_t *const true_type = skip_typeref(orig_true_type);
8340 type_t *const false_type = skip_typeref(orig_false_type);
8343 type_t *result_type;
8344 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8345 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
8346 /* ISO/IEC 14882:1998(E) §5.16:2 */
8347 if (true_expression->kind == EXPR_UNARY_THROW) {
8348 result_type = false_type;
8349 } else if (false_expression->kind == EXPR_UNARY_THROW) {
8350 result_type = true_type;
8352 if (warning.other && (
8353 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8354 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
8356 warningf(&conditional->base.source_position,
8357 "ISO C forbids conditional expression with only one void side");
8359 result_type = type_void;
8361 } else if (is_type_arithmetic(true_type)
8362 && is_type_arithmetic(false_type)) {
8363 result_type = semantic_arithmetic(true_type, false_type);
8365 true_expression = create_implicit_cast(true_expression, result_type);
8366 false_expression = create_implicit_cast(false_expression, result_type);
8368 conditional->true_expression = true_expression;
8369 conditional->false_expression = false_expression;
8370 conditional->base.type = result_type;
8371 } else if (same_compound_type(true_type, false_type)) {
8372 /* just take 1 of the 2 types */
8373 result_type = true_type;
8374 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
8375 type_t *pointer_type;
8377 expression_t *other_expression;
8378 if (is_type_pointer(true_type) &&
8379 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
8380 pointer_type = true_type;
8381 other_type = false_type;
8382 other_expression = false_expression;
8384 pointer_type = false_type;
8385 other_type = true_type;
8386 other_expression = true_expression;
8389 if (is_null_pointer_constant(other_expression)) {
8390 result_type = pointer_type;
8391 } else if (is_type_pointer(other_type)) {
8392 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8393 type_t *to2 = skip_typeref(other_type->pointer.points_to);
8396 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8397 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8399 } else if (types_compatible(get_unqualified_type(to1),
8400 get_unqualified_type(to2))) {
8403 if (warning.other) {
8404 warningf(&conditional->base.source_position,
8405 "pointer types '%T' and '%T' in conditional expression are incompatible",
8406 true_type, false_type);
8411 type_t *const type =
8412 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8413 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8414 } else if (is_type_integer(other_type)) {
8415 if (warning.other) {
8416 warningf(&conditional->base.source_position,
8417 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8419 result_type = pointer_type;
8421 if (is_type_valid(other_type)) {
8422 type_error_incompatible("while parsing conditional",
8423 &expression->base.source_position, true_type, false_type);
8425 result_type = type_error_type;
8428 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8429 type_error_incompatible("while parsing conditional",
8430 &conditional->base.source_position, true_type,
8433 result_type = type_error_type;
8436 conditional->true_expression
8437 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8438 conditional->false_expression
8439 = create_implicit_cast(false_expression, result_type);
8440 conditional->base.type = result_type;
8445 * Parse an extension expression.
8447 static expression_t *parse_extension(void)
8449 eat(T___extension__);
8451 bool old_gcc_extension = in_gcc_extension;
8452 in_gcc_extension = true;
8453 expression_t *expression = parse_sub_expression(PREC_UNARY);
8454 in_gcc_extension = old_gcc_extension;
8459 * Parse a __builtin_classify_type() expression.
8461 static expression_t *parse_builtin_classify_type(void)
8463 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8464 result->base.type = type_int;
8466 eat(T___builtin_classify_type);
8468 expect('(', end_error);
8469 add_anchor_token(')');
8470 expression_t *expression = parse_expression();
8471 rem_anchor_token(')');
8472 expect(')', end_error);
8473 result->classify_type.type_expression = expression;
8477 return create_invalid_expression();
8481 * Parse a delete expression
8482 * ISO/IEC 14882:1998(E) §5.3.5
8484 static expression_t *parse_delete(void)
8486 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8487 result->base.type = type_void;
8491 if (token.type == '[') {
8493 result->kind = EXPR_UNARY_DELETE_ARRAY;
8494 expect(']', end_error);
8498 expression_t *const value = parse_sub_expression(PREC_CAST);
8499 result->unary.value = value;
8501 type_t *const type = skip_typeref(value->base.type);
8502 if (!is_type_pointer(type)) {
8503 if (is_type_valid(type)) {
8504 errorf(&value->base.source_position,
8505 "operand of delete must have pointer type");
8507 } else if (warning.other &&
8508 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8509 warningf(&value->base.source_position,
8510 "deleting 'void*' is undefined");
8517 * Parse a throw expression
8518 * ISO/IEC 14882:1998(E) §15:1
8520 static expression_t *parse_throw(void)
8522 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8523 result->base.type = type_void;
8527 expression_t *value = NULL;
8528 switch (token.type) {
8530 value = parse_assignment_expression();
8531 /* ISO/IEC 14882:1998(E) §15.1:3 */
8532 type_t *const orig_type = value->base.type;
8533 type_t *const type = skip_typeref(orig_type);
8534 if (is_type_incomplete(type)) {
8535 errorf(&value->base.source_position,
8536 "cannot throw object of incomplete type '%T'", orig_type);
8537 } else if (is_type_pointer(type)) {
8538 type_t *const points_to = skip_typeref(type->pointer.points_to);
8539 if (is_type_incomplete(points_to) &&
8540 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8541 errorf(&value->base.source_position,
8542 "cannot throw pointer to incomplete type '%T'", orig_type);
8550 result->unary.value = value;
8555 static bool check_pointer_arithmetic(const source_position_t *source_position,
8556 type_t *pointer_type,
8557 type_t *orig_pointer_type)
8559 type_t *points_to = pointer_type->pointer.points_to;
8560 points_to = skip_typeref(points_to);
8562 if (is_type_incomplete(points_to)) {
8563 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8564 errorf(source_position,
8565 "arithmetic with pointer to incomplete type '%T' not allowed",
8568 } else if (warning.pointer_arith) {
8569 warningf(source_position,
8570 "pointer of type '%T' used in arithmetic",
8573 } else if (is_type_function(points_to)) {
8575 errorf(source_position,
8576 "arithmetic with pointer to function type '%T' not allowed",
8579 } else if (warning.pointer_arith) {
8580 warningf(source_position,
8581 "pointer to a function '%T' used in arithmetic",
8588 static bool is_lvalue(const expression_t *expression)
8590 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
8591 switch (expression->kind) {
8592 case EXPR_ARRAY_ACCESS:
8593 case EXPR_COMPOUND_LITERAL:
8594 case EXPR_REFERENCE:
8596 case EXPR_UNARY_DEREFERENCE:
8600 type_t *type = skip_typeref(expression->base.type);
8602 /* ISO/IEC 14882:1998(E) §3.10:3 */
8603 is_type_reference(type) ||
8604 /* Claim it is an lvalue, if the type is invalid. There was a parse
8605 * error before, which maybe prevented properly recognizing it as
8607 !is_type_valid(type);
8612 static void semantic_incdec(unary_expression_t *expression)
8614 type_t *const orig_type = expression->value->base.type;
8615 type_t *const type = skip_typeref(orig_type);
8616 if (is_type_pointer(type)) {
8617 if (!check_pointer_arithmetic(&expression->base.source_position,
8621 } else if (!is_type_real(type) && is_type_valid(type)) {
8622 /* TODO: improve error message */
8623 errorf(&expression->base.source_position,
8624 "operation needs an arithmetic or pointer type");
8627 if (!is_lvalue(expression->value)) {
8628 /* TODO: improve error message */
8629 errorf(&expression->base.source_position, "lvalue required as operand");
8631 expression->base.type = orig_type;
8634 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8636 type_t *const orig_type = expression->value->base.type;
8637 type_t *const type = skip_typeref(orig_type);
8638 if (!is_type_arithmetic(type)) {
8639 if (is_type_valid(type)) {
8640 /* TODO: improve error message */
8641 errorf(&expression->base.source_position,
8642 "operation needs an arithmetic type");
8647 expression->base.type = orig_type;
8650 static void semantic_unexpr_plus(unary_expression_t *expression)
8652 semantic_unexpr_arithmetic(expression);
8653 if (warning.traditional)
8654 warningf(&expression->base.source_position,
8655 "traditional C rejects the unary plus operator");
8658 static void semantic_not(unary_expression_t *expression)
8660 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8661 semantic_condition(expression->value, "operand of !");
8662 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8665 static void semantic_unexpr_integer(unary_expression_t *expression)
8667 type_t *const orig_type = expression->value->base.type;
8668 type_t *const type = skip_typeref(orig_type);
8669 if (!is_type_integer(type)) {
8670 if (is_type_valid(type)) {
8671 errorf(&expression->base.source_position,
8672 "operand of ~ must be of integer type");
8677 expression->base.type = orig_type;
8680 static void semantic_dereference(unary_expression_t *expression)
8682 type_t *const orig_type = expression->value->base.type;
8683 type_t *const type = skip_typeref(orig_type);
8684 if (!is_type_pointer(type)) {
8685 if (is_type_valid(type)) {
8686 errorf(&expression->base.source_position,
8687 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8692 type_t *result_type = type->pointer.points_to;
8693 result_type = automatic_type_conversion(result_type);
8694 expression->base.type = result_type;
8698 * Record that an address is taken (expression represents an lvalue).
8700 * @param expression the expression
8701 * @param may_be_register if true, the expression might be an register
8703 static void set_address_taken(expression_t *expression, bool may_be_register)
8705 if (expression->kind != EXPR_REFERENCE)
8708 entity_t *const entity = expression->reference.entity;
8710 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8713 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8714 && !may_be_register) {
8715 errorf(&expression->base.source_position,
8716 "address of register %s '%Y' requested",
8717 get_entity_kind_name(entity->kind), entity->base.symbol);
8720 if (entity->kind == ENTITY_VARIABLE) {
8721 entity->variable.address_taken = true;
8723 assert(entity->kind == ENTITY_PARAMETER);
8724 entity->parameter.address_taken = true;
8729 * Check the semantic of the address taken expression.
8731 static void semantic_take_addr(unary_expression_t *expression)
8733 expression_t *value = expression->value;
8734 value->base.type = revert_automatic_type_conversion(value);
8736 type_t *orig_type = value->base.type;
8737 type_t *type = skip_typeref(orig_type);
8738 if (!is_type_valid(type))
8742 if (!is_lvalue(value)) {
8743 errorf(&expression->base.source_position, "'&' requires an lvalue");
8745 if (type->kind == TYPE_BITFIELD) {
8746 errorf(&expression->base.source_position,
8747 "'&' not allowed on object with bitfield type '%T'",
8751 set_address_taken(value, false);
8753 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8756 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8757 static expression_t *parse_##unexpression_type(void) \
8759 expression_t *unary_expression \
8760 = allocate_expression_zero(unexpression_type); \
8762 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8764 sfunc(&unary_expression->unary); \
8766 return unary_expression; \
8769 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8770 semantic_unexpr_arithmetic)
8771 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8772 semantic_unexpr_plus)
8773 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8775 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8776 semantic_dereference)
8777 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8779 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8780 semantic_unexpr_integer)
8781 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8783 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8786 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8788 static expression_t *parse_##unexpression_type(expression_t *left) \
8790 expression_t *unary_expression \
8791 = allocate_expression_zero(unexpression_type); \
8793 unary_expression->unary.value = left; \
8795 sfunc(&unary_expression->unary); \
8797 return unary_expression; \
8800 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8801 EXPR_UNARY_POSTFIX_INCREMENT,
8803 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8804 EXPR_UNARY_POSTFIX_DECREMENT,
8807 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8809 /* TODO: handle complex + imaginary types */
8811 type_left = get_unqualified_type(type_left);
8812 type_right = get_unqualified_type(type_right);
8814 /* §6.3.1.8 Usual arithmetic conversions */
8815 if (type_left == type_long_double || type_right == type_long_double) {
8816 return type_long_double;
8817 } else if (type_left == type_double || type_right == type_double) {
8819 } else if (type_left == type_float || type_right == type_float) {
8823 type_left = promote_integer(type_left);
8824 type_right = promote_integer(type_right);
8826 if (type_left == type_right)
8829 bool const signed_left = is_type_signed(type_left);
8830 bool const signed_right = is_type_signed(type_right);
8831 int const rank_left = get_rank(type_left);
8832 int const rank_right = get_rank(type_right);
8834 if (signed_left == signed_right)
8835 return rank_left >= rank_right ? type_left : type_right;
8844 u_rank = rank_right;
8845 u_type = type_right;
8847 s_rank = rank_right;
8848 s_type = type_right;
8853 if (u_rank >= s_rank)
8856 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8858 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8859 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8863 case ATOMIC_TYPE_INT: return type_unsigned_int;
8864 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8865 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8867 default: panic("invalid atomic type");
8872 * Check the semantic restrictions for a binary expression.
8874 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8876 expression_t *const left = expression->left;
8877 expression_t *const right = expression->right;
8878 type_t *const orig_type_left = left->base.type;
8879 type_t *const orig_type_right = right->base.type;
8880 type_t *const type_left = skip_typeref(orig_type_left);
8881 type_t *const type_right = skip_typeref(orig_type_right);
8883 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8884 /* TODO: improve error message */
8885 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8886 errorf(&expression->base.source_position,
8887 "operation needs arithmetic types");
8892 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8893 expression->left = create_implicit_cast(left, arithmetic_type);
8894 expression->right = create_implicit_cast(right, arithmetic_type);
8895 expression->base.type = arithmetic_type;
8898 static void warn_div_by_zero(binary_expression_t const *const expression)
8900 if (!warning.div_by_zero ||
8901 !is_type_integer(expression->base.type))
8904 expression_t const *const right = expression->right;
8905 /* The type of the right operand can be different for /= */
8906 if (is_type_integer(right->base.type) &&
8907 is_constant_expression(right) &&
8908 fold_constant(right) == 0) {
8909 warningf(&expression->base.source_position, "division by zero");
8914 * Check the semantic restrictions for a div/mod expression.
8916 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8918 semantic_binexpr_arithmetic(expression);
8919 warn_div_by_zero(expression);
8922 static void warn_addsub_in_shift(const expression_t *const expr)
8924 if (expr->base.parenthesized)
8928 switch (expr->kind) {
8929 case EXPR_BINARY_ADD: op = '+'; break;
8930 case EXPR_BINARY_SUB: op = '-'; break;
8934 warningf(&expr->base.source_position,
8935 "suggest parentheses around '%c' inside shift", op);
8938 static void semantic_shift_op(binary_expression_t *expression)
8940 expression_t *const left = expression->left;
8941 expression_t *const right = expression->right;
8942 type_t *const orig_type_left = left->base.type;
8943 type_t *const orig_type_right = right->base.type;
8944 type_t * type_left = skip_typeref(orig_type_left);
8945 type_t * type_right = skip_typeref(orig_type_right);
8947 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8948 /* TODO: improve error message */
8949 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8950 errorf(&expression->base.source_position,
8951 "operands of shift operation must have integer types");
8956 if (warning.parentheses) {
8957 warn_addsub_in_shift(left);
8958 warn_addsub_in_shift(right);
8961 type_left = promote_integer(type_left);
8962 type_right = promote_integer(type_right);
8964 expression->left = create_implicit_cast(left, type_left);
8965 expression->right = create_implicit_cast(right, type_right);
8966 expression->base.type = type_left;
8969 static void semantic_add(binary_expression_t *expression)
8971 expression_t *const left = expression->left;
8972 expression_t *const right = expression->right;
8973 type_t *const orig_type_left = left->base.type;
8974 type_t *const orig_type_right = right->base.type;
8975 type_t *const type_left = skip_typeref(orig_type_left);
8976 type_t *const type_right = skip_typeref(orig_type_right);
8979 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8980 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8981 expression->left = create_implicit_cast(left, arithmetic_type);
8982 expression->right = create_implicit_cast(right, arithmetic_type);
8983 expression->base.type = arithmetic_type;
8984 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8985 check_pointer_arithmetic(&expression->base.source_position,
8986 type_left, orig_type_left);
8987 expression->base.type = type_left;
8988 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8989 check_pointer_arithmetic(&expression->base.source_position,
8990 type_right, orig_type_right);
8991 expression->base.type = type_right;
8992 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8993 errorf(&expression->base.source_position,
8994 "invalid operands to binary + ('%T', '%T')",
8995 orig_type_left, orig_type_right);
8999 static void semantic_sub(binary_expression_t *expression)
9001 expression_t *const left = expression->left;
9002 expression_t *const right = expression->right;
9003 type_t *const orig_type_left = left->base.type;
9004 type_t *const orig_type_right = right->base.type;
9005 type_t *const type_left = skip_typeref(orig_type_left);
9006 type_t *const type_right = skip_typeref(orig_type_right);
9007 source_position_t const *const pos = &expression->base.source_position;
9010 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9011 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9012 expression->left = create_implicit_cast(left, arithmetic_type);
9013 expression->right = create_implicit_cast(right, arithmetic_type);
9014 expression->base.type = arithmetic_type;
9015 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9016 check_pointer_arithmetic(&expression->base.source_position,
9017 type_left, orig_type_left);
9018 expression->base.type = type_left;
9019 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
9020 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
9021 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
9022 if (!types_compatible(unqual_left, unqual_right)) {
9024 "subtracting pointers to incompatible types '%T' and '%T'",
9025 orig_type_left, orig_type_right);
9026 } else if (!is_type_object(unqual_left)) {
9027 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
9028 errorf(pos, "subtracting pointers to non-object types '%T'",
9030 } else if (warning.other) {
9031 warningf(pos, "subtracting pointers to void");
9034 expression->base.type = type_ptrdiff_t;
9035 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9036 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
9037 orig_type_left, orig_type_right);
9041 static void warn_string_literal_address(expression_t const* expr)
9043 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
9044 expr = expr->unary.value;
9045 if (expr->kind != EXPR_UNARY_DEREFERENCE)
9047 expr = expr->unary.value;
9050 if (expr->kind == EXPR_STRING_LITERAL ||
9051 expr->kind == EXPR_WIDE_STRING_LITERAL) {
9052 warningf(&expr->base.source_position,
9053 "comparison with string literal results in unspecified behaviour");
9057 static void warn_comparison_in_comparison(const expression_t *const expr)
9059 if (expr->base.parenthesized)
9061 switch (expr->base.kind) {
9062 case EXPR_BINARY_LESS:
9063 case EXPR_BINARY_GREATER:
9064 case EXPR_BINARY_LESSEQUAL:
9065 case EXPR_BINARY_GREATEREQUAL:
9066 case EXPR_BINARY_NOTEQUAL:
9067 case EXPR_BINARY_EQUAL:
9068 warningf(&expr->base.source_position,
9069 "comparisons like 'x <= y < z' do not have their mathematical meaning");
9076 static bool maybe_negative(expression_t const *const expr)
9079 !is_constant_expression(expr) ||
9080 fold_constant(expr) < 0;
9084 * Check the semantics of comparison expressions.
9086 * @param expression The expression to check.
9088 static void semantic_comparison(binary_expression_t *expression)
9090 expression_t *left = expression->left;
9091 expression_t *right = expression->right;
9093 if (warning.address) {
9094 warn_string_literal_address(left);
9095 warn_string_literal_address(right);
9097 expression_t const* const func_left = get_reference_address(left);
9098 if (func_left != NULL && is_null_pointer_constant(right)) {
9099 warningf(&expression->base.source_position,
9100 "the address of '%Y' will never be NULL",
9101 func_left->reference.entity->base.symbol);
9104 expression_t const* const func_right = get_reference_address(right);
9105 if (func_right != NULL && is_null_pointer_constant(right)) {
9106 warningf(&expression->base.source_position,
9107 "the address of '%Y' will never be NULL",
9108 func_right->reference.entity->base.symbol);
9112 if (warning.parentheses) {
9113 warn_comparison_in_comparison(left);
9114 warn_comparison_in_comparison(right);
9117 type_t *orig_type_left = left->base.type;
9118 type_t *orig_type_right = right->base.type;
9119 type_t *type_left = skip_typeref(orig_type_left);
9120 type_t *type_right = skip_typeref(orig_type_right);
9122 /* TODO non-arithmetic types */
9123 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9124 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9126 /* test for signed vs unsigned compares */
9127 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
9128 bool const signed_left = is_type_signed(type_left);
9129 bool const signed_right = is_type_signed(type_right);
9130 if (signed_left != signed_right) {
9131 /* FIXME long long needs better const folding magic */
9132 /* TODO check whether constant value can be represented by other type */
9133 if ((signed_left && maybe_negative(left)) ||
9134 (signed_right && maybe_negative(right))) {
9135 warningf(&expression->base.source_position,
9136 "comparison between signed and unsigned");
9141 expression->left = create_implicit_cast(left, arithmetic_type);
9142 expression->right = create_implicit_cast(right, arithmetic_type);
9143 expression->base.type = arithmetic_type;
9144 if (warning.float_equal &&
9145 (expression->base.kind == EXPR_BINARY_EQUAL ||
9146 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
9147 is_type_float(arithmetic_type)) {
9148 warningf(&expression->base.source_position,
9149 "comparing floating point with == or != is unsafe");
9151 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
9152 /* TODO check compatibility */
9153 } else if (is_type_pointer(type_left)) {
9154 expression->right = create_implicit_cast(right, type_left);
9155 } else if (is_type_pointer(type_right)) {
9156 expression->left = create_implicit_cast(left, type_right);
9157 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9158 type_error_incompatible("invalid operands in comparison",
9159 &expression->base.source_position,
9160 type_left, type_right);
9162 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9166 * Checks if a compound type has constant fields.
9168 static bool has_const_fields(const compound_type_t *type)
9170 compound_t *compound = type->compound;
9171 entity_t *entry = compound->members.entities;
9173 for (; entry != NULL; entry = entry->base.next) {
9174 if (!is_declaration(entry))
9177 const type_t *decl_type = skip_typeref(entry->declaration.type);
9178 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
9185 static bool is_valid_assignment_lhs(expression_t const* const left)
9187 type_t *const orig_type_left = revert_automatic_type_conversion(left);
9188 type_t *const type_left = skip_typeref(orig_type_left);
9190 if (!is_lvalue(left)) {
9191 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
9196 if (left->kind == EXPR_REFERENCE
9197 && left->reference.entity->kind == ENTITY_FUNCTION) {
9198 errorf(HERE, "cannot assign to function '%E'", left);
9202 if (is_type_array(type_left)) {
9203 errorf(HERE, "cannot assign to array '%E'", left);
9206 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
9207 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
9211 if (is_type_incomplete(type_left)) {
9212 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
9213 left, orig_type_left);
9216 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
9217 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
9218 left, orig_type_left);
9225 static void semantic_arithmetic_assign(binary_expression_t *expression)
9227 expression_t *left = expression->left;
9228 expression_t *right = expression->right;
9229 type_t *orig_type_left = left->base.type;
9230 type_t *orig_type_right = right->base.type;
9232 if (!is_valid_assignment_lhs(left))
9235 type_t *type_left = skip_typeref(orig_type_left);
9236 type_t *type_right = skip_typeref(orig_type_right);
9238 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
9239 /* TODO: improve error message */
9240 if (is_type_valid(type_left) && is_type_valid(type_right)) {
9241 errorf(&expression->base.source_position,
9242 "operation needs arithmetic types");
9247 /* combined instructions are tricky. We can't create an implicit cast on
9248 * the left side, because we need the uncasted form for the store.
9249 * The ast2firm pass has to know that left_type must be right_type
9250 * for the arithmetic operation and create a cast by itself */
9251 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9252 expression->right = create_implicit_cast(right, arithmetic_type);
9253 expression->base.type = type_left;
9256 static void semantic_divmod_assign(binary_expression_t *expression)
9258 semantic_arithmetic_assign(expression);
9259 warn_div_by_zero(expression);
9262 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
9264 expression_t *const left = expression->left;
9265 expression_t *const right = expression->right;
9266 type_t *const orig_type_left = left->base.type;
9267 type_t *const orig_type_right = right->base.type;
9268 type_t *const type_left = skip_typeref(orig_type_left);
9269 type_t *const type_right = skip_typeref(orig_type_right);
9271 if (!is_valid_assignment_lhs(left))
9274 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9275 /* combined instructions are tricky. We can't create an implicit cast on
9276 * the left side, because we need the uncasted form for the store.
9277 * The ast2firm pass has to know that left_type must be right_type
9278 * for the arithmetic operation and create a cast by itself */
9279 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
9280 expression->right = create_implicit_cast(right, arithmetic_type);
9281 expression->base.type = type_left;
9282 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9283 check_pointer_arithmetic(&expression->base.source_position,
9284 type_left, orig_type_left);
9285 expression->base.type = type_left;
9286 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9287 errorf(&expression->base.source_position,
9288 "incompatible types '%T' and '%T' in assignment",
9289 orig_type_left, orig_type_right);
9293 static void warn_logical_and_within_or(const expression_t *const expr)
9295 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
9297 if (expr->base.parenthesized)
9299 warningf(&expr->base.source_position,
9300 "suggest parentheses around && within ||");
9304 * Check the semantic restrictions of a logical expression.
9306 static void semantic_logical_op(binary_expression_t *expression)
9308 /* §6.5.13:2 Each of the operands shall have scalar type.
9309 * §6.5.14:2 Each of the operands shall have scalar type. */
9310 semantic_condition(expression->left, "left operand of logical operator");
9311 semantic_condition(expression->right, "right operand of logical operator");
9312 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
9313 warning.parentheses) {
9314 warn_logical_and_within_or(expression->left);
9315 warn_logical_and_within_or(expression->right);
9317 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9321 * Check the semantic restrictions of a binary assign expression.
9323 static void semantic_binexpr_assign(binary_expression_t *expression)
9325 expression_t *left = expression->left;
9326 type_t *orig_type_left = left->base.type;
9328 if (!is_valid_assignment_lhs(left))
9331 assign_error_t error = semantic_assign(orig_type_left, expression->right);
9332 report_assign_error(error, orig_type_left, expression->right,
9333 "assignment", &left->base.source_position);
9334 expression->right = create_implicit_cast(expression->right, orig_type_left);
9335 expression->base.type = orig_type_left;
9339 * Determine if the outermost operation (or parts thereof) of the given
9340 * expression has no effect in order to generate a warning about this fact.
9341 * Therefore in some cases this only examines some of the operands of the
9342 * expression (see comments in the function and examples below).
9344 * f() + 23; // warning, because + has no effect
9345 * x || f(); // no warning, because x controls execution of f()
9346 * x ? y : f(); // warning, because y has no effect
9347 * (void)x; // no warning to be able to suppress the warning
9348 * This function can NOT be used for an "expression has definitely no effect"-
9350 static bool expression_has_effect(const expression_t *const expr)
9352 switch (expr->kind) {
9353 case EXPR_UNKNOWN: break;
9354 case EXPR_INVALID: return true; /* do NOT warn */
9355 case EXPR_REFERENCE: return false;
9356 case EXPR_REFERENCE_ENUM_VALUE: return false;
9357 /* suppress the warning for microsoft __noop operations */
9358 case EXPR_CONST: return expr->conste.is_ms_noop;
9359 case EXPR_CHARACTER_CONSTANT: return false;
9360 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
9361 case EXPR_STRING_LITERAL: return false;
9362 case EXPR_WIDE_STRING_LITERAL: return false;
9363 case EXPR_LABEL_ADDRESS: return false;
9366 const call_expression_t *const call = &expr->call;
9367 if (call->function->kind != EXPR_REFERENCE)
9370 switch (call->function->reference.entity->function.btk) {
9371 /* FIXME: which builtins have no effect? */
9372 default: return true;
9376 /* Generate the warning if either the left or right hand side of a
9377 * conditional expression has no effect */
9378 case EXPR_CONDITIONAL: {
9379 conditional_expression_t const *const cond = &expr->conditional;
9380 expression_t const *const t = cond->true_expression;
9382 (t == NULL || expression_has_effect(t)) &&
9383 expression_has_effect(cond->false_expression);
9386 case EXPR_SELECT: return false;
9387 case EXPR_ARRAY_ACCESS: return false;
9388 case EXPR_SIZEOF: return false;
9389 case EXPR_CLASSIFY_TYPE: return false;
9390 case EXPR_ALIGNOF: return false;
9392 case EXPR_FUNCNAME: return false;
9393 case EXPR_BUILTIN_CONSTANT_P: return false;
9394 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
9395 case EXPR_OFFSETOF: return false;
9396 case EXPR_VA_START: return true;
9397 case EXPR_VA_ARG: return true;
9398 case EXPR_VA_COPY: return true;
9399 case EXPR_STATEMENT: return true; // TODO
9400 case EXPR_COMPOUND_LITERAL: return false;
9402 case EXPR_UNARY_NEGATE: return false;
9403 case EXPR_UNARY_PLUS: return false;
9404 case EXPR_UNARY_BITWISE_NEGATE: return false;
9405 case EXPR_UNARY_NOT: return false;
9406 case EXPR_UNARY_DEREFERENCE: return false;
9407 case EXPR_UNARY_TAKE_ADDRESS: return false;
9408 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
9409 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
9410 case EXPR_UNARY_PREFIX_INCREMENT: return true;
9411 case EXPR_UNARY_PREFIX_DECREMENT: return true;
9413 /* Treat void casts as if they have an effect in order to being able to
9414 * suppress the warning */
9415 case EXPR_UNARY_CAST: {
9416 type_t *const type = skip_typeref(expr->base.type);
9417 return is_type_atomic(type, ATOMIC_TYPE_VOID);
9420 case EXPR_UNARY_CAST_IMPLICIT: return true;
9421 case EXPR_UNARY_ASSUME: return true;
9422 case EXPR_UNARY_DELETE: return true;
9423 case EXPR_UNARY_DELETE_ARRAY: return true;
9424 case EXPR_UNARY_THROW: return true;
9426 case EXPR_BINARY_ADD: return false;
9427 case EXPR_BINARY_SUB: return false;
9428 case EXPR_BINARY_MUL: return false;
9429 case EXPR_BINARY_DIV: return false;
9430 case EXPR_BINARY_MOD: return false;
9431 case EXPR_BINARY_EQUAL: return false;
9432 case EXPR_BINARY_NOTEQUAL: return false;
9433 case EXPR_BINARY_LESS: return false;
9434 case EXPR_BINARY_LESSEQUAL: return false;
9435 case EXPR_BINARY_GREATER: return false;
9436 case EXPR_BINARY_GREATEREQUAL: return false;
9437 case EXPR_BINARY_BITWISE_AND: return false;
9438 case EXPR_BINARY_BITWISE_OR: return false;
9439 case EXPR_BINARY_BITWISE_XOR: return false;
9440 case EXPR_BINARY_SHIFTLEFT: return false;
9441 case EXPR_BINARY_SHIFTRIGHT: return false;
9442 case EXPR_BINARY_ASSIGN: return true;
9443 case EXPR_BINARY_MUL_ASSIGN: return true;
9444 case EXPR_BINARY_DIV_ASSIGN: return true;
9445 case EXPR_BINARY_MOD_ASSIGN: return true;
9446 case EXPR_BINARY_ADD_ASSIGN: return true;
9447 case EXPR_BINARY_SUB_ASSIGN: return true;
9448 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
9449 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
9450 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9451 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9452 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
9454 /* Only examine the right hand side of && and ||, because the left hand
9455 * side already has the effect of controlling the execution of the right
9457 case EXPR_BINARY_LOGICAL_AND:
9458 case EXPR_BINARY_LOGICAL_OR:
9459 /* Only examine the right hand side of a comma expression, because the left
9460 * hand side has a separate warning */
9461 case EXPR_BINARY_COMMA:
9462 return expression_has_effect(expr->binary.right);
9464 case EXPR_BINARY_ISGREATER: return false;
9465 case EXPR_BINARY_ISGREATEREQUAL: return false;
9466 case EXPR_BINARY_ISLESS: return false;
9467 case EXPR_BINARY_ISLESSEQUAL: return false;
9468 case EXPR_BINARY_ISLESSGREATER: return false;
9469 case EXPR_BINARY_ISUNORDERED: return false;
9472 internal_errorf(HERE, "unexpected expression");
9475 static void semantic_comma(binary_expression_t *expression)
9477 if (warning.unused_value) {
9478 const expression_t *const left = expression->left;
9479 if (!expression_has_effect(left)) {
9480 warningf(&left->base.source_position,
9481 "left-hand operand of comma expression has no effect");
9484 expression->base.type = expression->right->base.type;
9488 * @param prec_r precedence of the right operand
9490 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9491 static expression_t *parse_##binexpression_type(expression_t *left) \
9493 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9494 binexpr->binary.left = left; \
9497 expression_t *right = parse_sub_expression(prec_r); \
9499 binexpr->binary.right = right; \
9500 sfunc(&binexpr->binary); \
9505 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9506 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9507 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9508 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9509 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9510 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9511 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9512 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9513 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9514 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9515 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9516 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9517 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9518 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9519 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9520 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9521 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9522 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9523 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9524 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9525 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9526 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9527 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9528 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9529 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9530 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9531 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9532 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9533 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9534 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9537 static expression_t *parse_sub_expression(precedence_t precedence)
9539 if (token.type < 0) {
9540 return expected_expression_error();
9543 expression_parser_function_t *parser
9544 = &expression_parsers[token.type];
9545 source_position_t source_position = token.source_position;
9548 if (parser->parser != NULL) {
9549 left = parser->parser();
9551 left = parse_primary_expression();
9553 assert(left != NULL);
9554 left->base.source_position = source_position;
9557 if (token.type < 0) {
9558 return expected_expression_error();
9561 parser = &expression_parsers[token.type];
9562 if (parser->infix_parser == NULL)
9564 if (parser->infix_precedence < precedence)
9567 left = parser->infix_parser(left);
9569 assert(left != NULL);
9570 assert(left->kind != EXPR_UNKNOWN);
9571 left->base.source_position = source_position;
9578 * Parse an expression.
9580 static expression_t *parse_expression(void)
9582 return parse_sub_expression(PREC_EXPRESSION);
9586 * Register a parser for a prefix-like operator.
9588 * @param parser the parser function
9589 * @param token_type the token type of the prefix token
9591 static void register_expression_parser(parse_expression_function parser,
9594 expression_parser_function_t *entry = &expression_parsers[token_type];
9596 if (entry->parser != NULL) {
9597 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9598 panic("trying to register multiple expression parsers for a token");
9600 entry->parser = parser;
9604 * Register a parser for an infix operator with given precedence.
9606 * @param parser the parser function
9607 * @param token_type the token type of the infix operator
9608 * @param precedence the precedence of the operator
9610 static void register_infix_parser(parse_expression_infix_function parser,
9611 int token_type, precedence_t precedence)
9613 expression_parser_function_t *entry = &expression_parsers[token_type];
9615 if (entry->infix_parser != NULL) {
9616 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9617 panic("trying to register multiple infix expression parsers for a "
9620 entry->infix_parser = parser;
9621 entry->infix_precedence = precedence;
9625 * Initialize the expression parsers.
9627 static void init_expression_parsers(void)
9629 memset(&expression_parsers, 0, sizeof(expression_parsers));
9631 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9632 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9633 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9634 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9635 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9636 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9637 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9638 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9639 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9640 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9641 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9642 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9643 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9644 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9645 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9646 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9647 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9648 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9649 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9650 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9651 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9652 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9653 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9654 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9655 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9656 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9657 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9658 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9659 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9660 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9661 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9662 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9663 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9664 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9665 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9666 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9667 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9669 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9670 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9671 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9672 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9673 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9674 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9675 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9676 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9677 register_expression_parser(parse_sizeof, T_sizeof);
9678 register_expression_parser(parse_alignof, T___alignof__);
9679 register_expression_parser(parse_extension, T___extension__);
9680 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9681 register_expression_parser(parse_delete, T_delete);
9682 register_expression_parser(parse_throw, T_throw);
9686 * Parse a asm statement arguments specification.
9688 static asm_argument_t *parse_asm_arguments(bool is_out)
9690 asm_argument_t *result = NULL;
9691 asm_argument_t **anchor = &result;
9693 while (token.type == T_STRING_LITERAL || token.type == '[') {
9694 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9695 memset(argument, 0, sizeof(argument[0]));
9697 if (token.type == '[') {
9699 if (token.type != T_IDENTIFIER) {
9700 parse_error_expected("while parsing asm argument",
9701 T_IDENTIFIER, NULL);
9704 argument->symbol = token.v.symbol;
9706 expect(']', end_error);
9709 argument->constraints = parse_string_literals();
9710 expect('(', end_error);
9711 add_anchor_token(')');
9712 expression_t *expression = parse_expression();
9713 rem_anchor_token(')');
9715 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9716 * change size or type representation (e.g. int -> long is ok, but
9717 * int -> float is not) */
9718 if (expression->kind == EXPR_UNARY_CAST) {
9719 type_t *const type = expression->base.type;
9720 type_kind_t const kind = type->kind;
9721 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9724 if (kind == TYPE_ATOMIC) {
9725 atomic_type_kind_t const akind = type->atomic.akind;
9726 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9727 size = get_atomic_type_size(akind);
9729 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9730 size = get_atomic_type_size(get_intptr_kind());
9734 expression_t *const value = expression->unary.value;
9735 type_t *const value_type = value->base.type;
9736 type_kind_t const value_kind = value_type->kind;
9738 unsigned value_flags;
9739 unsigned value_size;
9740 if (value_kind == TYPE_ATOMIC) {
9741 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9742 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9743 value_size = get_atomic_type_size(value_akind);
9744 } else if (value_kind == TYPE_POINTER) {
9745 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9746 value_size = get_atomic_type_size(get_intptr_kind());
9751 if (value_flags != flags || value_size != size)
9755 } while (expression->kind == EXPR_UNARY_CAST);
9759 if (!is_lvalue(expression)) {
9760 errorf(&expression->base.source_position,
9761 "asm output argument is not an lvalue");
9764 if (argument->constraints.begin[0] == '+')
9765 mark_vars_read(expression, NULL);
9767 mark_vars_read(expression, NULL);
9769 argument->expression = expression;
9770 expect(')', end_error);
9772 set_address_taken(expression, true);
9775 anchor = &argument->next;
9777 if (token.type != ',')
9788 * Parse a asm statement clobber specification.
9790 static asm_clobber_t *parse_asm_clobbers(void)
9792 asm_clobber_t *result = NULL;
9793 asm_clobber_t *last = NULL;
9795 while (token.type == T_STRING_LITERAL) {
9796 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9797 clobber->clobber = parse_string_literals();
9800 last->next = clobber;
9806 if (token.type != ',')
9815 * Parse an asm statement.
9817 static statement_t *parse_asm_statement(void)
9819 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9820 asm_statement_t *asm_statement = &statement->asms;
9824 if (token.type == T_volatile) {
9826 asm_statement->is_volatile = true;
9829 expect('(', end_error);
9830 add_anchor_token(')');
9831 add_anchor_token(':');
9832 asm_statement->asm_text = parse_string_literals();
9834 if (token.type != ':') {
9835 rem_anchor_token(':');
9840 asm_statement->outputs = parse_asm_arguments(true);
9841 if (token.type != ':') {
9842 rem_anchor_token(':');
9847 asm_statement->inputs = parse_asm_arguments(false);
9848 if (token.type != ':') {
9849 rem_anchor_token(':');
9852 rem_anchor_token(':');
9855 asm_statement->clobbers = parse_asm_clobbers();
9858 rem_anchor_token(')');
9859 expect(')', end_error);
9860 expect(';', end_error);
9862 if (asm_statement->outputs == NULL) {
9863 /* GCC: An 'asm' instruction without any output operands will be treated
9864 * identically to a volatile 'asm' instruction. */
9865 asm_statement->is_volatile = true;
9870 return create_invalid_statement();
9874 * Parse a case statement.
9876 static statement_t *parse_case_statement(void)
9878 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9879 source_position_t *const pos = &statement->base.source_position;
9883 expression_t *const expression = parse_expression();
9884 statement->case_label.expression = expression;
9885 if (!is_constant_expression(expression)) {
9886 /* This check does not prevent the error message in all cases of an
9887 * prior error while parsing the expression. At least it catches the
9888 * common case of a mistyped enum entry. */
9889 if (is_type_valid(skip_typeref(expression->base.type))) {
9890 errorf(pos, "case label does not reduce to an integer constant");
9892 statement->case_label.is_bad = true;
9894 long const val = fold_constant(expression);
9895 statement->case_label.first_case = val;
9896 statement->case_label.last_case = val;
9900 if (token.type == T_DOTDOTDOT) {
9902 expression_t *const end_range = parse_expression();
9903 statement->case_label.end_range = end_range;
9904 if (!is_constant_expression(end_range)) {
9905 /* This check does not prevent the error message in all cases of an
9906 * prior error while parsing the expression. At least it catches the
9907 * common case of a mistyped enum entry. */
9908 if (is_type_valid(skip_typeref(end_range->base.type))) {
9909 errorf(pos, "case range does not reduce to an integer constant");
9911 statement->case_label.is_bad = true;
9913 long const val = fold_constant(end_range);
9914 statement->case_label.last_case = val;
9916 if (warning.other && val < statement->case_label.first_case) {
9917 statement->case_label.is_empty_range = true;
9918 warningf(pos, "empty range specified");
9924 PUSH_PARENT(statement);
9926 expect(':', end_error);
9929 if (current_switch != NULL) {
9930 if (! statement->case_label.is_bad) {
9931 /* Check for duplicate case values */
9932 case_label_statement_t *c = &statement->case_label;
9933 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9934 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9937 if (c->last_case < l->first_case || c->first_case > l->last_case)
9940 errorf(pos, "duplicate case value (previously used %P)",
9941 &l->base.source_position);
9945 /* link all cases into the switch statement */
9946 if (current_switch->last_case == NULL) {
9947 current_switch->first_case = &statement->case_label;
9949 current_switch->last_case->next = &statement->case_label;
9951 current_switch->last_case = &statement->case_label;
9953 errorf(pos, "case label not within a switch statement");
9956 statement_t *const inner_stmt = parse_statement();
9957 statement->case_label.statement = inner_stmt;
9958 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9959 errorf(&inner_stmt->base.source_position, "declaration after case label");
9967 * Parse a default statement.
9969 static statement_t *parse_default_statement(void)
9971 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9975 PUSH_PARENT(statement);
9977 expect(':', end_error);
9978 if (current_switch != NULL) {
9979 const case_label_statement_t *def_label = current_switch->default_label;
9980 if (def_label != NULL) {
9981 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9982 &def_label->base.source_position);
9984 current_switch->default_label = &statement->case_label;
9986 /* link all cases into the switch statement */
9987 if (current_switch->last_case == NULL) {
9988 current_switch->first_case = &statement->case_label;
9990 current_switch->last_case->next = &statement->case_label;
9992 current_switch->last_case = &statement->case_label;
9995 errorf(&statement->base.source_position,
9996 "'default' label not within a switch statement");
9999 statement_t *const inner_stmt = parse_statement();
10000 statement->case_label.statement = inner_stmt;
10001 if (inner_stmt->kind == STATEMENT_DECLARATION) {
10002 errorf(&inner_stmt->base.source_position, "declaration after default label");
10009 return create_invalid_statement();
10013 * Parse a label statement.
10015 static statement_t *parse_label_statement(void)
10017 assert(token.type == T_IDENTIFIER);
10018 symbol_t *symbol = token.v.symbol;
10019 label_t *label = get_label(symbol);
10021 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
10022 statement->label.label = label;
10026 PUSH_PARENT(statement);
10028 /* if statement is already set then the label is defined twice,
10029 * otherwise it was just mentioned in a goto/local label declaration so far
10031 if (label->statement != NULL) {
10032 errorf(HERE, "duplicate label '%Y' (declared %P)",
10033 symbol, &label->base.source_position);
10035 label->base.source_position = token.source_position;
10036 label->statement = statement;
10041 if (token.type == '}') {
10042 /* TODO only warn? */
10043 if (warning.other && false) {
10044 warningf(HERE, "label at end of compound statement");
10045 statement->label.statement = create_empty_statement();
10047 errorf(HERE, "label at end of compound statement");
10048 statement->label.statement = create_invalid_statement();
10050 } else if (token.type == ';') {
10051 /* Eat an empty statement here, to avoid the warning about an empty
10052 * statement after a label. label:; is commonly used to have a label
10053 * before a closing brace. */
10054 statement->label.statement = create_empty_statement();
10057 statement_t *const inner_stmt = parse_statement();
10058 statement->label.statement = inner_stmt;
10059 if (inner_stmt->kind == STATEMENT_DECLARATION) {
10060 errorf(&inner_stmt->base.source_position, "declaration after label");
10064 /* remember the labels in a list for later checking */
10065 *label_anchor = &statement->label;
10066 label_anchor = &statement->label.next;
10073 * Parse an if statement.
10075 static statement_t *parse_if(void)
10077 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
10081 PUSH_PARENT(statement);
10083 add_anchor_token('{');
10085 expect('(', end_error);
10086 add_anchor_token(')');
10087 expression_t *const expr = parse_expression();
10088 statement->ifs.condition = expr;
10089 /* §6.8.4.1:1 The controlling expression of an if statement shall have
10091 semantic_condition(expr, "condition of 'if'-statment");
10092 mark_vars_read(expr, NULL);
10093 rem_anchor_token(')');
10094 expect(')', end_error);
10097 rem_anchor_token('{');
10099 add_anchor_token(T_else);
10100 statement_t *const true_stmt = parse_statement();
10101 statement->ifs.true_statement = true_stmt;
10102 rem_anchor_token(T_else);
10104 if (token.type == T_else) {
10106 statement->ifs.false_statement = parse_statement();
10107 } else if (warning.parentheses &&
10108 true_stmt->kind == STATEMENT_IF &&
10109 true_stmt->ifs.false_statement != NULL) {
10110 warningf(&true_stmt->base.source_position,
10111 "suggest explicit braces to avoid ambiguous 'else'");
10119 * Check that all enums are handled in a switch.
10121 * @param statement the switch statement to check
10123 static void check_enum_cases(const switch_statement_t *statement)
10125 const type_t *type = skip_typeref(statement->expression->base.type);
10126 if (! is_type_enum(type))
10128 const enum_type_t *enumt = &type->enumt;
10130 /* if we have a default, no warnings */
10131 if (statement->default_label != NULL)
10134 /* FIXME: calculation of value should be done while parsing */
10135 /* TODO: quadratic algorithm here. Change to an n log n one */
10136 long last_value = -1;
10137 const entity_t *entry = enumt->enume->base.next;
10138 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
10139 entry = entry->base.next) {
10140 const expression_t *expression = entry->enum_value.value;
10141 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
10142 bool found = false;
10143 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
10144 if (l->expression == NULL)
10146 if (l->first_case <= value && value <= l->last_case) {
10152 warningf(&statement->base.source_position,
10153 "enumeration value '%Y' not handled in switch",
10154 entry->base.symbol);
10156 last_value = value;
10161 * Parse a switch statement.
10163 static statement_t *parse_switch(void)
10165 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
10169 PUSH_PARENT(statement);
10171 expect('(', end_error);
10172 add_anchor_token(')');
10173 expression_t *const expr = parse_expression();
10174 mark_vars_read(expr, NULL);
10175 type_t * type = skip_typeref(expr->base.type);
10176 if (is_type_integer(type)) {
10177 type = promote_integer(type);
10178 if (warning.traditional) {
10179 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
10180 warningf(&expr->base.source_position,
10181 "'%T' switch expression not converted to '%T' in ISO C",
10185 } else if (is_type_valid(type)) {
10186 errorf(&expr->base.source_position,
10187 "switch quantity is not an integer, but '%T'", type);
10188 type = type_error_type;
10190 statement->switchs.expression = create_implicit_cast(expr, type);
10191 expect(')', end_error);
10192 rem_anchor_token(')');
10194 switch_statement_t *rem = current_switch;
10195 current_switch = &statement->switchs;
10196 statement->switchs.body = parse_statement();
10197 current_switch = rem;
10199 if (warning.switch_default &&
10200 statement->switchs.default_label == NULL) {
10201 warningf(&statement->base.source_position, "switch has no default case");
10203 if (warning.switch_enum)
10204 check_enum_cases(&statement->switchs);
10210 return create_invalid_statement();
10213 static statement_t *parse_loop_body(statement_t *const loop)
10215 statement_t *const rem = current_loop;
10216 current_loop = loop;
10218 statement_t *const body = parse_statement();
10220 current_loop = rem;
10225 * Parse a while statement.
10227 static statement_t *parse_while(void)
10229 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
10233 PUSH_PARENT(statement);
10235 expect('(', end_error);
10236 add_anchor_token(')');
10237 expression_t *const cond = parse_expression();
10238 statement->whiles.condition = cond;
10239 /* §6.8.5:2 The controlling expression of an iteration statement shall
10240 * have scalar type. */
10241 semantic_condition(cond, "condition of 'while'-statement");
10242 mark_vars_read(cond, NULL);
10243 rem_anchor_token(')');
10244 expect(')', end_error);
10246 statement->whiles.body = parse_loop_body(statement);
10252 return create_invalid_statement();
10256 * Parse a do statement.
10258 static statement_t *parse_do(void)
10260 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
10264 PUSH_PARENT(statement);
10266 add_anchor_token(T_while);
10267 statement->do_while.body = parse_loop_body(statement);
10268 rem_anchor_token(T_while);
10270 expect(T_while, end_error);
10271 expect('(', end_error);
10272 add_anchor_token(')');
10273 expression_t *const cond = parse_expression();
10274 statement->do_while.condition = cond;
10275 /* §6.8.5:2 The controlling expression of an iteration statement shall
10276 * have scalar type. */
10277 semantic_condition(cond, "condition of 'do-while'-statement");
10278 mark_vars_read(cond, NULL);
10279 rem_anchor_token(')');
10280 expect(')', end_error);
10281 expect(';', end_error);
10287 return create_invalid_statement();
10291 * Parse a for statement.
10293 static statement_t *parse_for(void)
10295 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
10299 expect('(', end_error1);
10300 add_anchor_token(')');
10302 PUSH_PARENT(statement);
10304 size_t const top = environment_top();
10305 scope_t *old_scope = scope_push(&statement->fors.scope);
10307 if (token.type == ';') {
10309 } else if (is_declaration_specifier(&token, false)) {
10310 parse_declaration(record_entity, DECL_FLAGS_NONE);
10312 add_anchor_token(';');
10313 expression_t *const init = parse_expression();
10314 statement->fors.initialisation = init;
10315 mark_vars_read(init, ENT_ANY);
10316 if (warning.unused_value && !expression_has_effect(init)) {
10317 warningf(&init->base.source_position,
10318 "initialisation of 'for'-statement has no effect");
10320 rem_anchor_token(';');
10321 expect(';', end_error2);
10324 if (token.type != ';') {
10325 add_anchor_token(';');
10326 expression_t *const cond = parse_expression();
10327 statement->fors.condition = cond;
10328 /* §6.8.5:2 The controlling expression of an iteration statement
10329 * shall have scalar type. */
10330 semantic_condition(cond, "condition of 'for'-statement");
10331 mark_vars_read(cond, NULL);
10332 rem_anchor_token(';');
10334 expect(';', end_error2);
10335 if (token.type != ')') {
10336 expression_t *const step = parse_expression();
10337 statement->fors.step = step;
10338 mark_vars_read(step, ENT_ANY);
10339 if (warning.unused_value && !expression_has_effect(step)) {
10340 warningf(&step->base.source_position,
10341 "step of 'for'-statement has no effect");
10344 expect(')', end_error2);
10345 rem_anchor_token(')');
10346 statement->fors.body = parse_loop_body(statement);
10348 assert(current_scope == &statement->fors.scope);
10349 scope_pop(old_scope);
10350 environment_pop_to(top);
10357 rem_anchor_token(')');
10358 assert(current_scope == &statement->fors.scope);
10359 scope_pop(old_scope);
10360 environment_pop_to(top);
10364 return create_invalid_statement();
10368 * Parse a goto statement.
10370 static statement_t *parse_goto(void)
10372 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
10375 if (GNU_MODE && token.type == '*') {
10377 expression_t *expression = parse_expression();
10378 mark_vars_read(expression, NULL);
10380 /* Argh: although documentation says the expression must be of type void*,
10381 * gcc accepts anything that can be casted into void* without error */
10382 type_t *type = expression->base.type;
10384 if (type != type_error_type) {
10385 if (!is_type_pointer(type) && !is_type_integer(type)) {
10386 errorf(&expression->base.source_position,
10387 "cannot convert to a pointer type");
10388 } else if (warning.other && type != type_void_ptr) {
10389 warningf(&expression->base.source_position,
10390 "type of computed goto expression should be 'void*' not '%T'", type);
10392 expression = create_implicit_cast(expression, type_void_ptr);
10395 statement->gotos.expression = expression;
10397 if (token.type != T_IDENTIFIER) {
10399 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
10401 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
10402 eat_until_anchor();
10405 symbol_t *symbol = token.v.symbol;
10408 statement->gotos.label = get_label(symbol);
10411 /* remember the goto's in a list for later checking */
10412 *goto_anchor = &statement->gotos;
10413 goto_anchor = &statement->gotos.next;
10415 expect(';', end_error);
10419 return create_invalid_statement();
10423 * Parse a continue statement.
10425 static statement_t *parse_continue(void)
10427 if (current_loop == NULL) {
10428 errorf(HERE, "continue statement not within loop");
10431 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
10434 expect(';', end_error);
10441 * Parse a break statement.
10443 static statement_t *parse_break(void)
10445 if (current_switch == NULL && current_loop == NULL) {
10446 errorf(HERE, "break statement not within loop or switch");
10449 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10452 expect(';', end_error);
10459 * Parse a __leave statement.
10461 static statement_t *parse_leave_statement(void)
10463 if (current_try == NULL) {
10464 errorf(HERE, "__leave statement not within __try");
10467 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10470 expect(';', end_error);
10477 * Check if a given entity represents a local variable.
10479 static bool is_local_variable(const entity_t *entity)
10481 if (entity->kind != ENTITY_VARIABLE)
10484 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10485 case STORAGE_CLASS_AUTO:
10486 case STORAGE_CLASS_REGISTER: {
10487 const type_t *type = skip_typeref(entity->declaration.type);
10488 if (is_type_function(type)) {
10500 * Check if a given expression represents a local variable.
10502 static bool expression_is_local_variable(const expression_t *expression)
10504 if (expression->base.kind != EXPR_REFERENCE) {
10507 const entity_t *entity = expression->reference.entity;
10508 return is_local_variable(entity);
10512 * Check if a given expression represents a local variable and
10513 * return its declaration then, else return NULL.
10515 entity_t *expression_is_variable(const expression_t *expression)
10517 if (expression->base.kind != EXPR_REFERENCE) {
10520 entity_t *entity = expression->reference.entity;
10521 if (entity->kind != ENTITY_VARIABLE)
10528 * Parse a return statement.
10530 static statement_t *parse_return(void)
10534 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10536 expression_t *return_value = NULL;
10537 if (token.type != ';') {
10538 return_value = parse_expression();
10539 mark_vars_read(return_value, NULL);
10542 const type_t *const func_type = skip_typeref(current_function->base.type);
10543 assert(is_type_function(func_type));
10544 type_t *const return_type = skip_typeref(func_type->function.return_type);
10546 source_position_t const *const pos = &statement->base.source_position;
10547 if (return_value != NULL) {
10548 type_t *return_value_type = skip_typeref(return_value->base.type);
10550 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10551 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10552 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10553 /* Only warn in C mode, because GCC does the same */
10554 if (c_mode & _CXX || strict_mode) {
10556 "'return' with a value, in function returning 'void'");
10557 } else if (warning.other) {
10559 "'return' with a value, in function returning 'void'");
10561 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10562 /* Only warn in C mode, because GCC does the same */
10565 "'return' with expression in function return 'void'");
10566 } else if (warning.other) {
10568 "'return' with expression in function return 'void'");
10572 assign_error_t error = semantic_assign(return_type, return_value);
10573 report_assign_error(error, return_type, return_value, "'return'",
10576 return_value = create_implicit_cast(return_value, return_type);
10577 /* check for returning address of a local var */
10578 if (warning.other && return_value != NULL
10579 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10580 const expression_t *expression = return_value->unary.value;
10581 if (expression_is_local_variable(expression)) {
10582 warningf(pos, "function returns address of local variable");
10585 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10586 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10587 if (c_mode & _CXX || strict_mode) {
10589 "'return' without value, in function returning non-void");
10592 "'return' without value, in function returning non-void");
10595 statement->returns.value = return_value;
10597 expect(';', end_error);
10604 * Parse a declaration statement.
10606 static statement_t *parse_declaration_statement(void)
10608 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10610 entity_t *before = current_scope->last_entity;
10612 parse_external_declaration();
10614 parse_declaration(record_entity, DECL_FLAGS_NONE);
10617 declaration_statement_t *const decl = &statement->declaration;
10618 entity_t *const begin =
10619 before != NULL ? before->base.next : current_scope->entities;
10620 decl->declarations_begin = begin;
10621 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
10627 * Parse an expression statement, ie. expr ';'.
10629 static statement_t *parse_expression_statement(void)
10631 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10633 expression_t *const expr = parse_expression();
10634 statement->expression.expression = expr;
10635 mark_vars_read(expr, ENT_ANY);
10637 expect(';', end_error);
10644 * Parse a microsoft __try { } __finally { } or
10645 * __try{ } __except() { }
10647 static statement_t *parse_ms_try_statment(void)
10649 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10652 PUSH_PARENT(statement);
10654 ms_try_statement_t *rem = current_try;
10655 current_try = &statement->ms_try;
10656 statement->ms_try.try_statement = parse_compound_statement(false);
10661 if (token.type == T___except) {
10663 expect('(', end_error);
10664 add_anchor_token(')');
10665 expression_t *const expr = parse_expression();
10666 mark_vars_read(expr, NULL);
10667 type_t * type = skip_typeref(expr->base.type);
10668 if (is_type_integer(type)) {
10669 type = promote_integer(type);
10670 } else if (is_type_valid(type)) {
10671 errorf(&expr->base.source_position,
10672 "__expect expression is not an integer, but '%T'", type);
10673 type = type_error_type;
10675 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10676 rem_anchor_token(')');
10677 expect(')', end_error);
10678 statement->ms_try.final_statement = parse_compound_statement(false);
10679 } else if (token.type == T__finally) {
10681 statement->ms_try.final_statement = parse_compound_statement(false);
10683 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10684 return create_invalid_statement();
10688 return create_invalid_statement();
10691 static statement_t *parse_empty_statement(void)
10693 if (warning.empty_statement) {
10694 warningf(HERE, "statement is empty");
10696 statement_t *const statement = create_empty_statement();
10701 static statement_t *parse_local_label_declaration(void)
10703 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10707 entity_t *begin = NULL, *end = NULL;
10710 if (token.type != T_IDENTIFIER) {
10711 parse_error_expected("while parsing local label declaration",
10712 T_IDENTIFIER, NULL);
10715 symbol_t *symbol = token.v.symbol;
10716 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10717 if (entity != NULL && entity->base.parent_scope == current_scope) {
10718 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10719 symbol, &entity->base.source_position);
10721 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10723 entity->base.parent_scope = current_scope;
10724 entity->base.namespc = NAMESPACE_LABEL;
10725 entity->base.source_position = token.source_position;
10726 entity->base.symbol = symbol;
10729 end->base.next = entity;
10734 environment_push(entity);
10738 if (token.type != ',')
10744 statement->declaration.declarations_begin = begin;
10745 statement->declaration.declarations_end = end;
10749 static void parse_namespace_definition(void)
10753 entity_t *entity = NULL;
10754 symbol_t *symbol = NULL;
10756 if (token.type == T_IDENTIFIER) {
10757 symbol = token.v.symbol;
10760 entity = get_entity(symbol, NAMESPACE_NORMAL);
10761 if (entity != NULL &&
10762 entity->kind != ENTITY_NAMESPACE &&
10763 entity->base.parent_scope == current_scope) {
10764 if (!is_error_entity(entity)) {
10765 error_redefined_as_different_kind(&token.source_position,
10766 entity, ENTITY_NAMESPACE);
10772 if (entity == NULL) {
10773 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10774 entity->base.symbol = symbol;
10775 entity->base.source_position = token.source_position;
10776 entity->base.namespc = NAMESPACE_NORMAL;
10777 entity->base.parent_scope = current_scope;
10780 if (token.type == '=') {
10781 /* TODO: parse namespace alias */
10782 panic("namespace alias definition not supported yet");
10785 environment_push(entity);
10786 append_entity(current_scope, entity);
10788 size_t const top = environment_top();
10789 scope_t *old_scope = scope_push(&entity->namespacee.members);
10791 expect('{', end_error);
10793 expect('}', end_error);
10796 assert(current_scope == &entity->namespacee.members);
10797 scope_pop(old_scope);
10798 environment_pop_to(top);
10802 * Parse a statement.
10803 * There's also parse_statement() which additionally checks for
10804 * "statement has no effect" warnings
10806 static statement_t *intern_parse_statement(void)
10808 statement_t *statement = NULL;
10810 /* declaration or statement */
10811 add_anchor_token(';');
10812 switch (token.type) {
10813 case T_IDENTIFIER: {
10814 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10815 if (la1_type == ':') {
10816 statement = parse_label_statement();
10817 } else if (is_typedef_symbol(token.v.symbol)) {
10818 statement = parse_declaration_statement();
10820 /* it's an identifier, the grammar says this must be an
10821 * expression statement. However it is common that users mistype
10822 * declaration types, so we guess a bit here to improve robustness
10823 * for incorrect programs */
10824 switch (la1_type) {
10827 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10828 goto expression_statment;
10833 statement = parse_declaration_statement();
10837 expression_statment:
10838 statement = parse_expression_statement();
10845 case T___extension__:
10846 /* This can be a prefix to a declaration or an expression statement.
10847 * We simply eat it now and parse the rest with tail recursion. */
10850 } while (token.type == T___extension__);
10851 bool old_gcc_extension = in_gcc_extension;
10852 in_gcc_extension = true;
10853 statement = intern_parse_statement();
10854 in_gcc_extension = old_gcc_extension;
10858 statement = parse_declaration_statement();
10862 statement = parse_local_label_declaration();
10865 case ';': statement = parse_empty_statement(); break;
10866 case '{': statement = parse_compound_statement(false); break;
10867 case T___leave: statement = parse_leave_statement(); break;
10868 case T___try: statement = parse_ms_try_statment(); break;
10869 case T_asm: statement = parse_asm_statement(); break;
10870 case T_break: statement = parse_break(); break;
10871 case T_case: statement = parse_case_statement(); break;
10872 case T_continue: statement = parse_continue(); break;
10873 case T_default: statement = parse_default_statement(); break;
10874 case T_do: statement = parse_do(); break;
10875 case T_for: statement = parse_for(); break;
10876 case T_goto: statement = parse_goto(); break;
10877 case T_if: statement = parse_if(); break;
10878 case T_return: statement = parse_return(); break;
10879 case T_switch: statement = parse_switch(); break;
10880 case T_while: statement = parse_while(); break;
10883 statement = parse_expression_statement();
10887 errorf(HERE, "unexpected token %K while parsing statement", &token);
10888 statement = create_invalid_statement();
10893 rem_anchor_token(';');
10895 assert(statement != NULL
10896 && statement->base.source_position.input_name != NULL);
10902 * parse a statement and emits "statement has no effect" warning if needed
10903 * (This is really a wrapper around intern_parse_statement with check for 1
10904 * single warning. It is needed, because for statement expressions we have
10905 * to avoid the warning on the last statement)
10907 static statement_t *parse_statement(void)
10909 statement_t *statement = intern_parse_statement();
10911 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10912 expression_t *expression = statement->expression.expression;
10913 if (!expression_has_effect(expression)) {
10914 warningf(&expression->base.source_position,
10915 "statement has no effect");
10923 * Parse a compound statement.
10925 static statement_t *parse_compound_statement(bool inside_expression_statement)
10927 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10929 PUSH_PARENT(statement);
10932 add_anchor_token('}');
10933 /* tokens, which can start a statement */
10934 /* TODO MS, __builtin_FOO */
10935 add_anchor_token('!');
10936 add_anchor_token('&');
10937 add_anchor_token('(');
10938 add_anchor_token('*');
10939 add_anchor_token('+');
10940 add_anchor_token('-');
10941 add_anchor_token('{');
10942 add_anchor_token('~');
10943 add_anchor_token(T_CHARACTER_CONSTANT);
10944 add_anchor_token(T_COLONCOLON);
10945 add_anchor_token(T_FLOATINGPOINT);
10946 add_anchor_token(T_IDENTIFIER);
10947 add_anchor_token(T_INTEGER);
10948 add_anchor_token(T_MINUSMINUS);
10949 add_anchor_token(T_PLUSPLUS);
10950 add_anchor_token(T_STRING_LITERAL);
10951 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10952 add_anchor_token(T_WIDE_STRING_LITERAL);
10953 add_anchor_token(T__Bool);
10954 add_anchor_token(T__Complex);
10955 add_anchor_token(T__Imaginary);
10956 add_anchor_token(T___FUNCTION__);
10957 add_anchor_token(T___PRETTY_FUNCTION__);
10958 add_anchor_token(T___alignof__);
10959 add_anchor_token(T___attribute__);
10960 add_anchor_token(T___builtin_va_start);
10961 add_anchor_token(T___extension__);
10962 add_anchor_token(T___func__);
10963 add_anchor_token(T___imag__);
10964 add_anchor_token(T___label__);
10965 add_anchor_token(T___real__);
10966 add_anchor_token(T___thread);
10967 add_anchor_token(T_asm);
10968 add_anchor_token(T_auto);
10969 add_anchor_token(T_bool);
10970 add_anchor_token(T_break);
10971 add_anchor_token(T_case);
10972 add_anchor_token(T_char);
10973 add_anchor_token(T_class);
10974 add_anchor_token(T_const);
10975 add_anchor_token(T_const_cast);
10976 add_anchor_token(T_continue);
10977 add_anchor_token(T_default);
10978 add_anchor_token(T_delete);
10979 add_anchor_token(T_double);
10980 add_anchor_token(T_do);
10981 add_anchor_token(T_dynamic_cast);
10982 add_anchor_token(T_enum);
10983 add_anchor_token(T_extern);
10984 add_anchor_token(T_false);
10985 add_anchor_token(T_float);
10986 add_anchor_token(T_for);
10987 add_anchor_token(T_goto);
10988 add_anchor_token(T_if);
10989 add_anchor_token(T_inline);
10990 add_anchor_token(T_int);
10991 add_anchor_token(T_long);
10992 add_anchor_token(T_new);
10993 add_anchor_token(T_operator);
10994 add_anchor_token(T_register);
10995 add_anchor_token(T_reinterpret_cast);
10996 add_anchor_token(T_restrict);
10997 add_anchor_token(T_return);
10998 add_anchor_token(T_short);
10999 add_anchor_token(T_signed);
11000 add_anchor_token(T_sizeof);
11001 add_anchor_token(T_static);
11002 add_anchor_token(T_static_cast);
11003 add_anchor_token(T_struct);
11004 add_anchor_token(T_switch);
11005 add_anchor_token(T_template);
11006 add_anchor_token(T_this);
11007 add_anchor_token(T_throw);
11008 add_anchor_token(T_true);
11009 add_anchor_token(T_try);
11010 add_anchor_token(T_typedef);
11011 add_anchor_token(T_typeid);
11012 add_anchor_token(T_typename);
11013 add_anchor_token(T_typeof);
11014 add_anchor_token(T_union);
11015 add_anchor_token(T_unsigned);
11016 add_anchor_token(T_using);
11017 add_anchor_token(T_void);
11018 add_anchor_token(T_volatile);
11019 add_anchor_token(T_wchar_t);
11020 add_anchor_token(T_while);
11022 size_t const top = environment_top();
11023 scope_t *old_scope = scope_push(&statement->compound.scope);
11025 statement_t **anchor = &statement->compound.statements;
11026 bool only_decls_so_far = true;
11027 while (token.type != '}') {
11028 if (token.type == T_EOF) {
11029 errorf(&statement->base.source_position,
11030 "EOF while parsing compound statement");
11033 statement_t *sub_statement = intern_parse_statement();
11034 if (is_invalid_statement(sub_statement)) {
11035 /* an error occurred. if we are at an anchor, return */
11041 if (warning.declaration_after_statement) {
11042 if (sub_statement->kind != STATEMENT_DECLARATION) {
11043 only_decls_so_far = false;
11044 } else if (!only_decls_so_far) {
11045 warningf(&sub_statement->base.source_position,
11046 "ISO C90 forbids mixed declarations and code");
11050 *anchor = sub_statement;
11052 while (sub_statement->base.next != NULL)
11053 sub_statement = sub_statement->base.next;
11055 anchor = &sub_statement->base.next;
11059 /* look over all statements again to produce no effect warnings */
11060 if (warning.unused_value) {
11061 statement_t *sub_statement = statement->compound.statements;
11062 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
11063 if (sub_statement->kind != STATEMENT_EXPRESSION)
11065 /* don't emit a warning for the last expression in an expression
11066 * statement as it has always an effect */
11067 if (inside_expression_statement && sub_statement->base.next == NULL)
11070 expression_t *expression = sub_statement->expression.expression;
11071 if (!expression_has_effect(expression)) {
11072 warningf(&expression->base.source_position,
11073 "statement has no effect");
11079 rem_anchor_token(T_while);
11080 rem_anchor_token(T_wchar_t);
11081 rem_anchor_token(T_volatile);
11082 rem_anchor_token(T_void);
11083 rem_anchor_token(T_using);
11084 rem_anchor_token(T_unsigned);
11085 rem_anchor_token(T_union);
11086 rem_anchor_token(T_typeof);
11087 rem_anchor_token(T_typename);
11088 rem_anchor_token(T_typeid);
11089 rem_anchor_token(T_typedef);
11090 rem_anchor_token(T_try);
11091 rem_anchor_token(T_true);
11092 rem_anchor_token(T_throw);
11093 rem_anchor_token(T_this);
11094 rem_anchor_token(T_template);
11095 rem_anchor_token(T_switch);
11096 rem_anchor_token(T_struct);
11097 rem_anchor_token(T_static_cast);
11098 rem_anchor_token(T_static);
11099 rem_anchor_token(T_sizeof);
11100 rem_anchor_token(T_signed);
11101 rem_anchor_token(T_short);
11102 rem_anchor_token(T_return);
11103 rem_anchor_token(T_restrict);
11104 rem_anchor_token(T_reinterpret_cast);
11105 rem_anchor_token(T_register);
11106 rem_anchor_token(T_operator);
11107 rem_anchor_token(T_new);
11108 rem_anchor_token(T_long);
11109 rem_anchor_token(T_int);
11110 rem_anchor_token(T_inline);
11111 rem_anchor_token(T_if);
11112 rem_anchor_token(T_goto);
11113 rem_anchor_token(T_for);
11114 rem_anchor_token(T_float);
11115 rem_anchor_token(T_false);
11116 rem_anchor_token(T_extern);
11117 rem_anchor_token(T_enum);
11118 rem_anchor_token(T_dynamic_cast);
11119 rem_anchor_token(T_do);
11120 rem_anchor_token(T_double);
11121 rem_anchor_token(T_delete);
11122 rem_anchor_token(T_default);
11123 rem_anchor_token(T_continue);
11124 rem_anchor_token(T_const_cast);
11125 rem_anchor_token(T_const);
11126 rem_anchor_token(T_class);
11127 rem_anchor_token(T_char);
11128 rem_anchor_token(T_case);
11129 rem_anchor_token(T_break);
11130 rem_anchor_token(T_bool);
11131 rem_anchor_token(T_auto);
11132 rem_anchor_token(T_asm);
11133 rem_anchor_token(T___thread);
11134 rem_anchor_token(T___real__);
11135 rem_anchor_token(T___label__);
11136 rem_anchor_token(T___imag__);
11137 rem_anchor_token(T___func__);
11138 rem_anchor_token(T___extension__);
11139 rem_anchor_token(T___builtin_va_start);
11140 rem_anchor_token(T___attribute__);
11141 rem_anchor_token(T___alignof__);
11142 rem_anchor_token(T___PRETTY_FUNCTION__);
11143 rem_anchor_token(T___FUNCTION__);
11144 rem_anchor_token(T__Imaginary);
11145 rem_anchor_token(T__Complex);
11146 rem_anchor_token(T__Bool);
11147 rem_anchor_token(T_WIDE_STRING_LITERAL);
11148 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
11149 rem_anchor_token(T_STRING_LITERAL);
11150 rem_anchor_token(T_PLUSPLUS);
11151 rem_anchor_token(T_MINUSMINUS);
11152 rem_anchor_token(T_INTEGER);
11153 rem_anchor_token(T_IDENTIFIER);
11154 rem_anchor_token(T_FLOATINGPOINT);
11155 rem_anchor_token(T_COLONCOLON);
11156 rem_anchor_token(T_CHARACTER_CONSTANT);
11157 rem_anchor_token('~');
11158 rem_anchor_token('{');
11159 rem_anchor_token('-');
11160 rem_anchor_token('+');
11161 rem_anchor_token('*');
11162 rem_anchor_token('(');
11163 rem_anchor_token('&');
11164 rem_anchor_token('!');
11165 rem_anchor_token('}');
11166 assert(current_scope == &statement->compound.scope);
11167 scope_pop(old_scope);
11168 environment_pop_to(top);
11175 * Check for unused global static functions and variables
11177 static void check_unused_globals(void)
11179 if (!warning.unused_function && !warning.unused_variable)
11182 for (const entity_t *entity = file_scope->entities; entity != NULL;
11183 entity = entity->base.next) {
11184 if (!is_declaration(entity))
11187 const declaration_t *declaration = &entity->declaration;
11188 if (declaration->used ||
11189 declaration->modifiers & DM_UNUSED ||
11190 declaration->modifiers & DM_USED ||
11191 declaration->storage_class != STORAGE_CLASS_STATIC)
11194 type_t *const type = declaration->type;
11196 if (entity->kind == ENTITY_FUNCTION) {
11197 /* inhibit warning for static inline functions */
11198 if (entity->function.is_inline)
11201 s = entity->function.statement != NULL ? "defined" : "declared";
11206 warningf(&declaration->base.source_position, "'%#T' %s but not used",
11207 type, declaration->base.symbol, s);
11211 static void parse_global_asm(void)
11213 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
11216 expect('(', end_error);
11218 statement->asms.asm_text = parse_string_literals();
11219 statement->base.next = unit->global_asm;
11220 unit->global_asm = statement;
11222 expect(')', end_error);
11223 expect(';', end_error);
11228 static void parse_linkage_specification(void)
11231 assert(token.type == T_STRING_LITERAL);
11233 const char *linkage = parse_string_literals().begin;
11235 linkage_kind_t old_linkage = current_linkage;
11236 linkage_kind_t new_linkage;
11237 if (strcmp(linkage, "C") == 0) {
11238 new_linkage = LINKAGE_C;
11239 } else if (strcmp(linkage, "C++") == 0) {
11240 new_linkage = LINKAGE_CXX;
11242 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
11243 new_linkage = LINKAGE_INVALID;
11245 current_linkage = new_linkage;
11247 if (token.type == '{') {
11250 expect('}', end_error);
11256 assert(current_linkage == new_linkage);
11257 current_linkage = old_linkage;
11260 static void parse_external(void)
11262 switch (token.type) {
11263 DECLARATION_START_NO_EXTERN
11265 case T___extension__:
11266 /* tokens below are for implicit int */
11267 case '&': /* & x; -> int& x; (and error later, because C++ has no
11269 case '*': /* * x; -> int* x; */
11270 case '(': /* (x); -> int (x); */
11271 parse_external_declaration();
11275 if (look_ahead(1)->type == T_STRING_LITERAL) {
11276 parse_linkage_specification();
11278 parse_external_declaration();
11283 parse_global_asm();
11287 parse_namespace_definition();
11291 if (!strict_mode) {
11293 warningf(HERE, "stray ';' outside of function");
11300 errorf(HERE, "stray %K outside of function", &token);
11301 if (token.type == '(' || token.type == '{' || token.type == '[')
11302 eat_until_matching_token(token.type);
11308 static void parse_externals(void)
11310 add_anchor_token('}');
11311 add_anchor_token(T_EOF);
11314 unsigned char token_anchor_copy[T_LAST_TOKEN];
11315 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
11318 while (token.type != T_EOF && token.type != '}') {
11320 bool anchor_leak = false;
11321 for (int i = 0; i != T_LAST_TOKEN; ++i) {
11322 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
11324 errorf(HERE, "Leaked anchor token %k %d times", i, count);
11325 anchor_leak = true;
11328 if (in_gcc_extension) {
11329 errorf(HERE, "Leaked __extension__");
11330 anchor_leak = true;
11340 rem_anchor_token(T_EOF);
11341 rem_anchor_token('}');
11345 * Parse a translation unit.
11347 static void parse_translation_unit(void)
11349 add_anchor_token(T_EOF);
11354 if (token.type == T_EOF)
11357 errorf(HERE, "stray %K outside of function", &token);
11358 if (token.type == '(' || token.type == '{' || token.type == '[')
11359 eat_until_matching_token(token.type);
11367 * @return the translation unit or NULL if errors occurred.
11369 void start_parsing(void)
11371 environment_stack = NEW_ARR_F(stack_entry_t, 0);
11372 label_stack = NEW_ARR_F(stack_entry_t, 0);
11373 diagnostic_count = 0;
11377 type_set_output(stderr);
11378 ast_set_output(stderr);
11380 assert(unit == NULL);
11381 unit = allocate_ast_zero(sizeof(unit[0]));
11383 assert(file_scope == NULL);
11384 file_scope = &unit->scope;
11386 assert(current_scope == NULL);
11387 scope_push(&unit->scope);
11389 create_gnu_builtins();
11391 create_microsoft_intrinsics();
11394 translation_unit_t *finish_parsing(void)
11396 assert(current_scope == &unit->scope);
11399 assert(file_scope == &unit->scope);
11400 check_unused_globals();
11403 DEL_ARR_F(environment_stack);
11404 DEL_ARR_F(label_stack);
11406 translation_unit_t *result = unit;
11411 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
11412 * are given length one. */
11413 static void complete_incomplete_arrays(void)
11415 size_t n = ARR_LEN(incomplete_arrays);
11416 for (size_t i = 0; i != n; ++i) {
11417 declaration_t *const decl = incomplete_arrays[i];
11418 type_t *const orig_type = decl->type;
11419 type_t *const type = skip_typeref(orig_type);
11421 if (!is_type_incomplete(type))
11424 if (warning.other) {
11425 warningf(&decl->base.source_position,
11426 "array '%#T' assumed to have one element",
11427 orig_type, decl->base.symbol);
11430 type_t *const new_type = duplicate_type(type);
11431 new_type->array.size_constant = true;
11432 new_type->array.has_implicit_size = true;
11433 new_type->array.size = 1;
11435 type_t *const result = identify_new_type(new_type);
11437 decl->type = result;
11443 lookahead_bufpos = 0;
11444 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
11447 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
11448 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
11449 parse_translation_unit();
11450 complete_incomplete_arrays();
11451 DEL_ARR_F(incomplete_arrays);
11452 incomplete_arrays = NULL;
11456 * create a builtin function.
11458 static entity_t *create_builtin_function(builtin_kind_t kind, const char *name, type_t *function_type)
11460 symbol_t *symbol = symbol_table_insert(name);
11461 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
11462 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
11463 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
11464 entity->declaration.type = function_type;
11465 entity->declaration.implicit = true;
11466 entity->base.symbol = symbol;
11467 entity->base.source_position = builtin_source_position;
11469 entity->function.btk = kind;
11471 record_entity(entity, /*is_definition=*/false);
11477 * Create predefined gnu builtins.
11479 static void create_gnu_builtins(void)
11481 #define GNU_BUILTIN(a, b) create_builtin_function(bk_gnu_builtin_##a, "__builtin_" #a, b)
11483 GNU_BUILTIN(alloca, make_function_1_type(type_void_ptr, type_size_t));
11484 GNU_BUILTIN(huge_val, make_function_0_type(type_double));
11485 GNU_BUILTIN(inf, make_function_0_type(type_double));
11486 GNU_BUILTIN(inff, make_function_0_type(type_float));
11487 GNU_BUILTIN(infl, make_function_0_type(type_long_double));
11488 GNU_BUILTIN(nan, make_function_1_type(type_double, type_char_ptr));
11489 GNU_BUILTIN(nanf, make_function_1_type(type_float, type_char_ptr));
11490 GNU_BUILTIN(nanl, make_function_1_type(type_long_double, type_char_ptr));
11491 GNU_BUILTIN(va_end, make_function_1_type(type_void, type_valist));
11492 GNU_BUILTIN(expect, make_function_2_type(type_long, type_long, type_long));
11493 GNU_BUILTIN(return_address, make_function_1_type(type_void_ptr, type_unsigned_int));
11494 GNU_BUILTIN(frame_address, make_function_1_type(type_void_ptr, type_unsigned_int));
11495 GNU_BUILTIN(ffs, make_function_1_type(type_int, type_unsigned_int));
11496 GNU_BUILTIN(clz, make_function_1_type(type_int, type_unsigned_int));
11497 GNU_BUILTIN(ctz, make_function_1_type(type_int, type_unsigned_int));
11498 GNU_BUILTIN(popcount, make_function_1_type(type_int, type_unsigned_int));
11499 GNU_BUILTIN(parity, make_function_1_type(type_int, type_unsigned_int));
11500 GNU_BUILTIN(prefetch, make_function_1_type_variadic(type_float, type_void_ptr));
11501 GNU_BUILTIN(trap, make_function_0_type_noreturn(type_void));
11507 * Create predefined MS intrinsics.
11509 static void create_microsoft_intrinsics(void)
11511 #define MS_BUILTIN(a, b) create_builtin_function(bk_ms##a, #a, b)
11513 /* intrinsics for all architectures */
11514 MS_BUILTIN(_rotl, make_function_2_type(type_unsigned_int, type_unsigned_int, type_int));
11515 MS_BUILTIN(_rotr, make_function_2_type(type_unsigned_int, type_unsigned_int, type_int));
11516 MS_BUILTIN(_rotl64, make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
11517 MS_BUILTIN(_rotr64, make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
11518 MS_BUILTIN(_byteswap_ushort, make_function_1_type(type_unsigned_short, type_unsigned_short));
11519 MS_BUILTIN(_byteswap_ulong, make_function_1_type(type_unsigned_long, type_unsigned_long));
11520 MS_BUILTIN(_byteswap_uint64, make_function_1_type(type_unsigned_int64, type_unsigned_int64));
11522 MS_BUILTIN(__debugbreak, make_function_0_type(type_void));
11523 MS_BUILTIN(_ReturnAddress, make_function_0_type(type_void_ptr));
11524 MS_BUILTIN(_AddressOfReturnAddress, make_function_0_type(type_void_ptr));
11525 MS_BUILTIN(__popcount, make_function_1_type(type_unsigned_int, type_unsigned_int));
11528 MS_BUILTIN(_enable, make_function_0_type(type_void));
11529 MS_BUILTIN(_disable, make_function_0_type(type_void));
11530 MS_BUILTIN(__inbyte, make_function_1_type(type_unsigned_char, type_unsigned_short));
11531 MS_BUILTIN(__inword, make_function_1_type(type_unsigned_short, type_unsigned_short));
11532 MS_BUILTIN(__indword, make_function_1_type(type_unsigned_long, type_unsigned_short));
11533 MS_BUILTIN(__outbyte, make_function_2_type(type_void, type_unsigned_short, type_unsigned_char));
11534 MS_BUILTIN(__outword, make_function_2_type(type_void, type_unsigned_short, type_unsigned_short));
11535 MS_BUILTIN(__outdword, make_function_2_type(type_void, type_unsigned_short, type_unsigned_long));
11536 MS_BUILTIN(__ud2, make_function_0_type_noreturn(type_void));
11537 MS_BUILTIN(_BitScanForward, make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11538 MS_BUILTIN(_BitScanReverse, make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11539 MS_BUILTIN(_InterlockedExchange, make_function_2_type(type_long, type_long_ptr, type_long));
11540 MS_BUILTIN(_InterlockedExchange64, make_function_2_type(type_int64, type_int64_ptr, type_int64));
11542 if (machine_size <= 32) {
11543 MS_BUILTIN(__readeflags, make_function_0_type(type_unsigned_int));
11544 MS_BUILTIN(__writeeflags, make_function_1_type(type_void, type_unsigned_int));
11546 MS_BUILTIN(__readeflags, make_function_0_type(type_unsigned_int64));
11547 MS_BUILTIN(__writeeflags, make_function_1_type(type_void, type_unsigned_int64));
11554 * Initialize the parser.
11556 void init_parser(void)
11558 sym_anonymous = symbol_table_insert("<anonymous>");
11560 if (c_mode & _MS) {
11561 /* add predefined symbols for extended-decl-modifier */
11562 sym_align = symbol_table_insert("align");
11563 sym_allocate = symbol_table_insert("allocate");
11564 sym_dllimport = symbol_table_insert("dllimport");
11565 sym_dllexport = symbol_table_insert("dllexport");
11566 sym_naked = symbol_table_insert("naked");
11567 sym_noinline = symbol_table_insert("noinline");
11568 sym_returns_twice = symbol_table_insert("returns_twice");
11569 sym_noreturn = symbol_table_insert("noreturn");
11570 sym_nothrow = symbol_table_insert("nothrow");
11571 sym_novtable = symbol_table_insert("novtable");
11572 sym_property = symbol_table_insert("property");
11573 sym_get = symbol_table_insert("get");
11574 sym_put = symbol_table_insert("put");
11575 sym_selectany = symbol_table_insert("selectany");
11576 sym_thread = symbol_table_insert("thread");
11577 sym_uuid = symbol_table_insert("uuid");
11578 sym_deprecated = symbol_table_insert("deprecated");
11579 sym_restrict = symbol_table_insert("restrict");
11580 sym_noalias = symbol_table_insert("noalias");
11582 memset(token_anchor_set, 0, sizeof(token_anchor_set));
11584 init_expression_parsers();
11585 obstack_init(&temp_obst);
11587 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11588 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11592 * Terminate the parser.
11594 void exit_parser(void)
11596 obstack_free(&temp_obst, NULL);