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)
837 /* §6.2.3:1 24) There is only one name space for tags even though three are
839 static entity_t *get_tag(symbol_t const *const symbol,
840 entity_kind_tag_t const kind)
842 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
843 if (entity != NULL && entity->kind != kind) {
845 "'%Y' defined as wrong kind of tag (previous definition %P)",
846 symbol, &entity->base.source_position);
853 * pushs an entity on the environment stack and links the corresponding symbol
856 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
858 symbol_t *symbol = entity->base.symbol;
859 entity_namespace_t namespc = entity->base.namespc;
860 assert(namespc != NAMESPACE_INVALID);
862 /* replace/add entity into entity list of the symbol */
865 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
870 /* replace an entry? */
871 if (iter->base.namespc == namespc) {
872 entity->base.symbol_next = iter->base.symbol_next;
878 /* remember old declaration */
880 entry.symbol = symbol;
881 entry.old_entity = iter;
882 entry.namespc = namespc;
883 ARR_APP1(stack_entry_t, *stack_ptr, entry);
887 * Push an entity on the environment stack.
889 static void environment_push(entity_t *entity)
891 assert(entity->base.source_position.input_name != NULL);
892 assert(entity->base.parent_scope != NULL);
893 stack_push(&environment_stack, entity);
897 * Push a declaration on the global label stack.
899 * @param declaration the declaration
901 static void label_push(entity_t *label)
903 /* we abuse the parameters scope as parent for the labels */
904 label->base.parent_scope = ¤t_function->parameters;
905 stack_push(&label_stack, label);
909 * pops symbols from the environment stack until @p new_top is the top element
911 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
913 stack_entry_t *stack = *stack_ptr;
914 size_t top = ARR_LEN(stack);
917 assert(new_top <= top);
921 for (i = top; i > new_top; --i) {
922 stack_entry_t *entry = &stack[i - 1];
924 entity_t *old_entity = entry->old_entity;
925 symbol_t *symbol = entry->symbol;
926 entity_namespace_t namespc = entry->namespc;
928 /* replace with old_entity/remove */
931 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
933 assert(iter != NULL);
934 /* replace an entry? */
935 if (iter->base.namespc == namespc)
939 /* restore definition from outer scopes (if there was one) */
940 if (old_entity != NULL) {
941 old_entity->base.symbol_next = iter->base.symbol_next;
942 *anchor = old_entity;
944 /* remove entry from list */
945 *anchor = iter->base.symbol_next;
949 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
953 * Pop all entries from the environment stack until the new_top
956 * @param new_top the new stack top
958 static void environment_pop_to(size_t new_top)
960 stack_pop_to(&environment_stack, new_top);
964 * Pop all entries from the global label stack until the new_top
967 * @param new_top the new stack top
969 static void label_pop_to(size_t new_top)
971 stack_pop_to(&label_stack, new_top);
974 static int get_akind_rank(atomic_type_kind_t akind)
980 * Return the type rank for an atomic type.
982 static int get_rank(const type_t *type)
984 assert(!is_typeref(type));
985 if (type->kind == TYPE_ENUM)
986 return get_akind_rank(type->enumt.akind);
988 assert(type->kind == TYPE_ATOMIC);
989 return get_akind_rank(type->atomic.akind);
993 * §6.3.1.1:2 Do integer promotion for a given type.
995 * @param type the type to promote
996 * @return the promoted type
998 static type_t *promote_integer(type_t *type)
1000 if (type->kind == TYPE_BITFIELD)
1001 type = type->bitfield.base_type;
1003 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
1010 * Create a cast expression.
1012 * @param expression the expression to cast
1013 * @param dest_type the destination type
1015 static expression_t *create_cast_expression(expression_t *expression,
1018 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
1020 cast->unary.value = expression;
1021 cast->base.type = dest_type;
1027 * Check if a given expression represents a null pointer constant.
1029 * @param expression the expression to check
1031 static bool is_null_pointer_constant(const expression_t *expression)
1033 /* skip void* cast */
1034 if (expression->kind == EXPR_UNARY_CAST ||
1035 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
1036 type_t *const type = skip_typeref(expression->base.type);
1037 if (types_compatible(type, type_void_ptr))
1038 expression = expression->unary.value;
1041 type_t *const type = skip_typeref(expression->base.type);
1043 is_type_integer(type) &&
1044 is_constant_expression(expression) &&
1045 fold_constant(expression) == 0;
1049 * Create an implicit cast expression.
1051 * @param expression the expression to cast
1052 * @param dest_type the destination type
1054 static expression_t *create_implicit_cast(expression_t *expression,
1057 type_t *const source_type = expression->base.type;
1059 if (source_type == dest_type)
1062 return create_cast_expression(expression, dest_type);
1065 typedef enum assign_error_t {
1067 ASSIGN_ERROR_INCOMPATIBLE,
1068 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1069 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1070 ASSIGN_WARNING_POINTER_FROM_INT,
1071 ASSIGN_WARNING_INT_FROM_POINTER
1074 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1075 const expression_t *const right,
1076 const char *context,
1077 const source_position_t *source_position)
1079 type_t *const orig_type_right = right->base.type;
1080 type_t *const type_left = skip_typeref(orig_type_left);
1081 type_t *const type_right = skip_typeref(orig_type_right);
1084 case ASSIGN_SUCCESS:
1086 case ASSIGN_ERROR_INCOMPATIBLE:
1087 errorf(source_position,
1088 "destination type '%T' in %s is incompatible with type '%T'",
1089 orig_type_left, context, orig_type_right);
1092 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1093 if (warning.other) {
1094 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1095 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1097 /* the left type has all qualifiers from the right type */
1098 unsigned missing_qualifiers
1099 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1100 warningf(source_position,
1101 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1102 orig_type_left, context, orig_type_right, missing_qualifiers);
1107 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1108 if (warning.other) {
1109 warningf(source_position,
1110 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1111 orig_type_left, context, right, orig_type_right);
1115 case ASSIGN_WARNING_POINTER_FROM_INT:
1116 if (warning.other) {
1117 warningf(source_position,
1118 "%s makes pointer '%T' from integer '%T' without a cast",
1119 context, orig_type_left, orig_type_right);
1123 case ASSIGN_WARNING_INT_FROM_POINTER:
1124 if (warning.other) {
1125 warningf(source_position,
1126 "%s makes integer '%T' from pointer '%T' without a cast",
1127 context, orig_type_left, orig_type_right);
1132 panic("invalid error value");
1136 /** Implements the rules from §6.5.16.1 */
1137 static assign_error_t semantic_assign(type_t *orig_type_left,
1138 const expression_t *const right)
1140 type_t *const orig_type_right = right->base.type;
1141 type_t *const type_left = skip_typeref(orig_type_left);
1142 type_t *const type_right = skip_typeref(orig_type_right);
1144 if (is_type_pointer(type_left)) {
1145 if (is_null_pointer_constant(right)) {
1146 return ASSIGN_SUCCESS;
1147 } else if (is_type_pointer(type_right)) {
1148 type_t *points_to_left
1149 = skip_typeref(type_left->pointer.points_to);
1150 type_t *points_to_right
1151 = skip_typeref(type_right->pointer.points_to);
1152 assign_error_t res = ASSIGN_SUCCESS;
1154 /* the left type has all qualifiers from the right type */
1155 unsigned missing_qualifiers
1156 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1157 if (missing_qualifiers != 0) {
1158 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1161 points_to_left = get_unqualified_type(points_to_left);
1162 points_to_right = get_unqualified_type(points_to_right);
1164 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1167 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1168 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1169 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1172 if (!types_compatible(points_to_left, points_to_right)) {
1173 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1177 } else if (is_type_integer(type_right)) {
1178 return ASSIGN_WARNING_POINTER_FROM_INT;
1180 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1181 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1182 && is_type_pointer(type_right))) {
1183 return ASSIGN_SUCCESS;
1184 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1185 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1186 type_t *const unqual_type_left = get_unqualified_type(type_left);
1187 type_t *const unqual_type_right = get_unqualified_type(type_right);
1188 if (types_compatible(unqual_type_left, unqual_type_right)) {
1189 return ASSIGN_SUCCESS;
1191 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1192 return ASSIGN_WARNING_INT_FROM_POINTER;
1195 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1196 return ASSIGN_SUCCESS;
1198 return ASSIGN_ERROR_INCOMPATIBLE;
1201 static expression_t *parse_constant_expression(void)
1203 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1205 if (!is_constant_expression(result)) {
1206 errorf(&result->base.source_position,
1207 "expression '%E' is not constant", result);
1213 static expression_t *parse_assignment_expression(void)
1215 return parse_sub_expression(PREC_ASSIGNMENT);
1218 static string_t parse_string_literals(void)
1220 assert(token.type == T_STRING_LITERAL);
1221 string_t result = token.v.string;
1225 while (token.type == T_STRING_LITERAL) {
1226 result = concat_strings(&result, &token.v.string);
1233 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1234 [GNU_AK_CONST] = "const",
1235 [GNU_AK_VOLATILE] = "volatile",
1236 [GNU_AK_CDECL] = "cdecl",
1237 [GNU_AK_STDCALL] = "stdcall",
1238 [GNU_AK_FASTCALL] = "fastcall",
1239 [GNU_AK_DEPRECATED] = "deprecated",
1240 [GNU_AK_NOINLINE] = "noinline",
1241 [GNU_AK_RETURNS_TWICE] = "returns_twice",
1242 [GNU_AK_NORETURN] = "noreturn",
1243 [GNU_AK_NAKED] = "naked",
1244 [GNU_AK_PURE] = "pure",
1245 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1246 [GNU_AK_MALLOC] = "malloc",
1247 [GNU_AK_WEAK] = "weak",
1248 [GNU_AK_CONSTRUCTOR] = "constructor",
1249 [GNU_AK_DESTRUCTOR] = "destructor",
1250 [GNU_AK_NOTHROW] = "nothrow",
1251 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1252 [GNU_AK_COMMON] = "common",
1253 [GNU_AK_NOCOMMON] = "nocommon",
1254 [GNU_AK_PACKED] = "packed",
1255 [GNU_AK_SHARED] = "shared",
1256 [GNU_AK_NOTSHARED] = "notshared",
1257 [GNU_AK_USED] = "used",
1258 [GNU_AK_UNUSED] = "unused",
1259 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1260 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1261 [GNU_AK_LONGCALL] = "longcall",
1262 [GNU_AK_SHORTCALL] = "shortcall",
1263 [GNU_AK_LONG_CALL] = "long_call",
1264 [GNU_AK_SHORT_CALL] = "short_call",
1265 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1266 [GNU_AK_INTERRUPT] = "interrupt",
1267 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1268 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1269 [GNU_AK_NESTING] = "nesting",
1270 [GNU_AK_NEAR] = "near",
1271 [GNU_AK_FAR] = "far",
1272 [GNU_AK_SIGNAL] = "signal",
1273 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1274 [GNU_AK_TINY_DATA] = "tiny_data",
1275 [GNU_AK_SAVEALL] = "saveall",
1276 [GNU_AK_FLATTEN] = "flatten",
1277 [GNU_AK_SSEREGPARM] = "sseregparm",
1278 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1279 [GNU_AK_RETURN_TWICE] = "return_twice",
1280 [GNU_AK_MAY_ALIAS] = "may_alias",
1281 [GNU_AK_MS_STRUCT] = "ms_struct",
1282 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1283 [GNU_AK_DLLIMPORT] = "dllimport",
1284 [GNU_AK_DLLEXPORT] = "dllexport",
1285 [GNU_AK_ALIGNED] = "aligned",
1286 [GNU_AK_ALIAS] = "alias",
1287 [GNU_AK_SECTION] = "section",
1288 [GNU_AK_FORMAT] = "format",
1289 [GNU_AK_FORMAT_ARG] = "format_arg",
1290 [GNU_AK_WEAKREF] = "weakref",
1291 [GNU_AK_NONNULL] = "nonnull",
1292 [GNU_AK_TLS_MODEL] = "tls_model",
1293 [GNU_AK_VISIBILITY] = "visibility",
1294 [GNU_AK_REGPARM] = "regparm",
1295 [GNU_AK_MODE] = "mode",
1296 [GNU_AK_MODEL] = "model",
1297 [GNU_AK_TRAP_EXIT] = "trap_exit",
1298 [GNU_AK_SP_SWITCH] = "sp_switch",
1299 [GNU_AK_SENTINEL] = "sentinel"
1303 * compare two string, ignoring double underscores on the second.
1305 static int strcmp_underscore(const char *s1, const char *s2)
1307 if (s2[0] == '_' && s2[1] == '_') {
1308 size_t len2 = strlen(s2);
1309 size_t len1 = strlen(s1);
1310 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1311 return strncmp(s1, s2+2, len2-4);
1315 return strcmp(s1, s2);
1319 * Allocate a new gnu temporal attribute of given kind.
1321 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1323 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1324 attribute->kind = kind;
1325 attribute->next = NULL;
1326 attribute->invalid = false;
1327 attribute->has_arguments = false;
1333 * Parse one constant expression argument of the given attribute.
1335 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1337 expression_t *expression;
1338 add_anchor_token(')');
1339 expression = parse_constant_expression();
1340 rem_anchor_token(')');
1341 expect(')', end_error);
1342 attribute->u.argument = fold_constant(expression);
1345 attribute->invalid = true;
1349 * Parse a list of constant expressions arguments of the given attribute.
1351 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1353 argument_list_t **list = &attribute->u.arguments;
1354 argument_list_t *entry;
1355 expression_t *expression;
1356 add_anchor_token(')');
1357 add_anchor_token(',');
1359 expression = parse_constant_expression();
1360 entry = obstack_alloc(&temp_obst, sizeof(entry));
1361 entry->argument = fold_constant(expression);
1364 list = &entry->next;
1365 if (token.type != ',')
1369 rem_anchor_token(',');
1370 rem_anchor_token(')');
1371 expect(')', end_error);
1374 attribute->invalid = true;
1378 * Parse one string literal argument of the given attribute.
1380 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1383 add_anchor_token('(');
1384 if (token.type != T_STRING_LITERAL) {
1385 parse_error_expected("while parsing attribute directive",
1386 T_STRING_LITERAL, NULL);
1389 *string = parse_string_literals();
1390 rem_anchor_token('(');
1391 expect(')', end_error);
1394 attribute->invalid = true;
1398 * Parse one tls model of the given attribute.
1400 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1402 static const char *const tls_models[] = {
1408 string_t string = { NULL, 0 };
1409 parse_gnu_attribute_string_arg(attribute, &string);
1410 if (string.begin != NULL) {
1411 for (size_t i = 0; i < 4; ++i) {
1412 if (strcmp(tls_models[i], string.begin) == 0) {
1413 attribute->u.value = i;
1417 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1419 attribute->invalid = true;
1423 * Parse one tls model of the given attribute.
1425 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1427 static const char *const visibilities[] = {
1433 string_t string = { NULL, 0 };
1434 parse_gnu_attribute_string_arg(attribute, &string);
1435 if (string.begin != NULL) {
1436 for (size_t i = 0; i < 4; ++i) {
1437 if (strcmp(visibilities[i], string.begin) == 0) {
1438 attribute->u.value = i;
1442 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1444 attribute->invalid = true;
1448 * Parse one (code) model of the given attribute.
1450 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1452 static const char *const visibilities[] = {
1457 string_t string = { NULL, 0 };
1458 parse_gnu_attribute_string_arg(attribute, &string);
1459 if (string.begin != NULL) {
1460 for (int i = 0; i < 3; ++i) {
1461 if (strcmp(visibilities[i], string.begin) == 0) {
1462 attribute->u.value = i;
1466 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1468 attribute->invalid = true;
1472 * Parse one mode of the given attribute.
1474 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1476 add_anchor_token(')');
1478 if (token.type != T_IDENTIFIER) {
1479 expect(T_IDENTIFIER, end_error);
1482 attribute->u.symbol = token.v.symbol;
1485 rem_anchor_token(')');
1486 expect(')', end_error);
1489 attribute->invalid = true;
1493 * Parse one interrupt argument of the given attribute.
1495 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1497 static const char *const interrupts[] = {
1504 string_t string = { NULL, 0 };
1505 parse_gnu_attribute_string_arg(attribute, &string);
1506 if (string.begin != NULL) {
1507 for (size_t i = 0; i < 5; ++i) {
1508 if (strcmp(interrupts[i], string.begin) == 0) {
1509 attribute->u.value = i;
1513 errorf(HERE, "'%s' is not an interrupt", string.begin);
1515 attribute->invalid = true;
1519 * Parse ( identifier, const expression, const expression )
1521 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1523 static const char *const format_names[] = {
1531 if (token.type != T_IDENTIFIER) {
1532 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1535 const char *name = token.v.symbol->string;
1536 for (i = 0; i < 4; ++i) {
1537 if (strcmp_underscore(format_names[i], name) == 0)
1541 if (warning.attribute)
1542 warningf(HERE, "'%s' is an unrecognized format function type", name);
1546 expect(',', end_error);
1547 add_anchor_token(')');
1548 add_anchor_token(',');
1549 parse_constant_expression();
1550 rem_anchor_token(',');
1551 rem_anchor_token(')');
1553 expect(',', end_error);
1554 add_anchor_token(')');
1555 parse_constant_expression();
1556 rem_anchor_token(')');
1557 expect(')', end_error);
1560 attribute->u.value = true;
1564 * Check that a given GNU attribute has no arguments.
1566 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1568 if (!attribute->has_arguments)
1571 /* should have no arguments */
1572 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1573 eat_until_matching_token('(');
1574 /* we have already consumed '(', so we stop before ')', eat it */
1576 attribute->invalid = true;
1580 * Parse one GNU attribute.
1582 * Note that attribute names can be specified WITH or WITHOUT
1583 * double underscores, ie const or __const__.
1585 * The following attributes are parsed without arguments
1610 * no_instrument_function
1611 * warn_unused_result
1628 * externally_visible
1636 * The following attributes are parsed with arguments
1637 * aligned( const expression )
1638 * alias( string literal )
1639 * section( string literal )
1640 * format( identifier, const expression, const expression )
1641 * format_arg( const expression )
1642 * tls_model( string literal )
1643 * visibility( string literal )
1644 * regparm( const expression )
1645 * model( string leteral )
1646 * trap_exit( const expression )
1647 * sp_switch( string literal )
1649 * The following attributes might have arguments
1650 * weak_ref( string literal )
1651 * non_null( const expression // ',' )
1652 * interrupt( string literal )
1653 * sentinel( constant expression )
1655 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1657 gnu_attribute_t *head = *attributes;
1658 gnu_attribute_t *last = *attributes;
1659 decl_modifiers_t modifiers = 0;
1660 gnu_attribute_t *attribute;
1662 eat(T___attribute__);
1663 expect('(', end_error);
1664 expect('(', end_error);
1666 if (token.type != ')') {
1667 /* find the end of the list */
1669 while (last->next != NULL)
1673 /* non-empty attribute list */
1676 if (token.type == T_const) {
1678 } else if (token.type == T_volatile) {
1680 } else if (token.type == T_cdecl) {
1681 /* __attribute__((cdecl)), WITH ms mode */
1683 } else if (token.type == T_IDENTIFIER) {
1684 const symbol_t *sym = token.v.symbol;
1687 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1694 for (i = 0; i < GNU_AK_LAST; ++i) {
1695 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1698 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1701 if (kind == GNU_AK_LAST) {
1702 if (warning.attribute)
1703 warningf(HERE, "'%s' attribute directive ignored", name);
1705 /* skip possible arguments */
1706 if (token.type == '(') {
1707 eat_until_matching_token(')');
1708 next_token(); /* skip the ')' */
1711 /* check for arguments */
1712 attribute = allocate_gnu_attribute(kind);
1713 if (token.type == '(') {
1715 if (token.type == ')') {
1716 /* empty args are allowed */
1719 attribute->has_arguments = true;
1723 case GNU_AK_VOLATILE:
1728 case GNU_AK_NOCOMMON:
1730 case GNU_AK_NOTSHARED:
1731 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1732 case GNU_AK_WARN_UNUSED_RESULT:
1733 case GNU_AK_LONGCALL:
1734 case GNU_AK_SHORTCALL:
1735 case GNU_AK_LONG_CALL:
1736 case GNU_AK_SHORT_CALL:
1737 case GNU_AK_FUNCTION_VECTOR:
1738 case GNU_AK_INTERRUPT_HANDLER:
1739 case GNU_AK_NMI_HANDLER:
1740 case GNU_AK_NESTING:
1744 case GNU_AK_EIGTHBIT_DATA:
1745 case GNU_AK_TINY_DATA:
1746 case GNU_AK_SAVEALL:
1747 case GNU_AK_FLATTEN:
1748 case GNU_AK_SSEREGPARM:
1749 case GNU_AK_EXTERNALLY_VISIBLE:
1750 case GNU_AK_RETURN_TWICE:
1751 case GNU_AK_MAY_ALIAS:
1752 case GNU_AK_MS_STRUCT:
1753 case GNU_AK_GCC_STRUCT:
1756 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1757 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1758 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1759 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1760 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1761 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1762 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1763 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1764 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1765 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1766 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1767 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1768 case GNU_AK_RETURNS_TWICE: modifiers |= DM_RETURNS_TWICE; goto no_arg;
1769 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1770 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1771 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1772 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1773 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1774 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1776 case GNU_AK_ALIGNED:
1777 /* __align__ may be used without an argument */
1778 if (attribute->has_arguments) {
1779 parse_gnu_attribute_const_arg(attribute);
1783 case GNU_AK_FORMAT_ARG:
1784 case GNU_AK_REGPARM:
1785 case GNU_AK_TRAP_EXIT:
1786 if (!attribute->has_arguments) {
1787 /* should have arguments */
1788 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1789 attribute->invalid = true;
1791 parse_gnu_attribute_const_arg(attribute);
1794 case GNU_AK_SECTION:
1795 case GNU_AK_SP_SWITCH:
1796 if (!attribute->has_arguments) {
1797 /* should have arguments */
1798 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1799 attribute->invalid = true;
1801 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1804 if (!attribute->has_arguments) {
1805 /* should have arguments */
1806 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1807 attribute->invalid = true;
1809 parse_gnu_attribute_format_args(attribute);
1811 case GNU_AK_WEAKREF:
1812 /* may have one string argument */
1813 if (attribute->has_arguments)
1814 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1816 case GNU_AK_NONNULL:
1817 if (attribute->has_arguments)
1818 parse_gnu_attribute_const_arg_list(attribute);
1820 case GNU_AK_TLS_MODEL:
1821 if (!attribute->has_arguments) {
1822 /* should have arguments */
1823 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1825 parse_gnu_attribute_tls_model_arg(attribute);
1827 case GNU_AK_VISIBILITY:
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_visibility_arg(attribute);
1835 if (!attribute->has_arguments) {
1836 /* should have arguments */
1837 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1839 parse_gnu_attribute_model_arg(attribute);
1843 if (!attribute->has_arguments) {
1844 /* should have arguments */
1845 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1847 parse_gnu_attribute_mode_arg(attribute);
1850 case GNU_AK_INTERRUPT:
1851 /* may have one string argument */
1852 if (attribute->has_arguments)
1853 parse_gnu_attribute_interrupt_arg(attribute);
1855 case GNU_AK_SENTINEL:
1856 /* may have one string argument */
1857 if (attribute->has_arguments)
1858 parse_gnu_attribute_const_arg(attribute);
1861 /* already handled */
1865 check_no_argument(attribute, name);
1868 if (attribute != NULL) {
1870 last->next = attribute;
1873 head = last = attribute;
1877 if (token.type != ',')
1882 expect(')', end_error);
1883 expect(')', end_error);
1891 * Parse GNU attributes.
1893 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1895 decl_modifiers_t modifiers = 0;
1898 switch (token.type) {
1899 case T___attribute__:
1900 modifiers |= parse_gnu_attribute(attributes);
1905 expect('(', end_error);
1906 if (token.type != T_STRING_LITERAL) {
1907 parse_error_expected("while parsing assembler attribute",
1908 T_STRING_LITERAL, NULL);
1909 eat_until_matching_token('(');
1912 parse_string_literals();
1914 expect(')', end_error);
1917 case T_cdecl: modifiers |= DM_CDECL; break;
1918 case T__fastcall: modifiers |= DM_FASTCALL; break;
1919 case T__stdcall: modifiers |= DM_STDCALL; break;
1922 /* TODO record modifier */
1924 warningf(HERE, "Ignoring declaration modifier %K", &token);
1928 default: return modifiers;
1935 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1937 static entity_t *determine_lhs_ent(expression_t *const expr,
1940 switch (expr->kind) {
1941 case EXPR_REFERENCE: {
1942 entity_t *const entity = expr->reference.entity;
1943 /* we should only find variables as lvalues... */
1944 if (entity->base.kind != ENTITY_VARIABLE
1945 && entity->base.kind != ENTITY_PARAMETER)
1951 case EXPR_ARRAY_ACCESS: {
1952 expression_t *const ref = expr->array_access.array_ref;
1953 entity_t * ent = NULL;
1954 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1955 ent = determine_lhs_ent(ref, lhs_ent);
1958 mark_vars_read(expr->select.compound, lhs_ent);
1960 mark_vars_read(expr->array_access.index, lhs_ent);
1965 if (is_type_compound(skip_typeref(expr->base.type))) {
1966 return determine_lhs_ent(expr->select.compound, lhs_ent);
1968 mark_vars_read(expr->select.compound, lhs_ent);
1973 case EXPR_UNARY_DEREFERENCE: {
1974 expression_t *const val = expr->unary.value;
1975 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1977 return determine_lhs_ent(val->unary.value, lhs_ent);
1979 mark_vars_read(val, NULL);
1985 mark_vars_read(expr, NULL);
1990 #define ENT_ANY ((entity_t*)-1)
1993 * Mark declarations, which are read. This is used to detect variables, which
1997 * x is not marked as "read", because it is only read to calculate its own new
2001 * x and y are not detected as "not read", because multiple variables are
2004 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
2006 switch (expr->kind) {
2007 case EXPR_REFERENCE: {
2008 entity_t *const entity = expr->reference.entity;
2009 if (entity->kind != ENTITY_VARIABLE
2010 && entity->kind != ENTITY_PARAMETER)
2013 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
2014 if (entity->kind == ENTITY_VARIABLE) {
2015 entity->variable.read = true;
2017 entity->parameter.read = true;
2024 // TODO respect pure/const
2025 mark_vars_read(expr->call.function, NULL);
2026 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
2027 mark_vars_read(arg->expression, NULL);
2031 case EXPR_CONDITIONAL:
2032 // TODO lhs_decl should depend on whether true/false have an effect
2033 mark_vars_read(expr->conditional.condition, NULL);
2034 if (expr->conditional.true_expression != NULL)
2035 mark_vars_read(expr->conditional.true_expression, lhs_ent);
2036 mark_vars_read(expr->conditional.false_expression, lhs_ent);
2040 if (lhs_ent == ENT_ANY
2041 && !is_type_compound(skip_typeref(expr->base.type)))
2043 mark_vars_read(expr->select.compound, lhs_ent);
2046 case EXPR_ARRAY_ACCESS: {
2047 expression_t *const ref = expr->array_access.array_ref;
2048 mark_vars_read(ref, lhs_ent);
2049 lhs_ent = determine_lhs_ent(ref, lhs_ent);
2050 mark_vars_read(expr->array_access.index, lhs_ent);
2055 mark_vars_read(expr->va_arge.ap, lhs_ent);
2059 mark_vars_read(expr->va_copye.src, lhs_ent);
2062 case EXPR_UNARY_CAST:
2063 /* Special case: Use void cast to mark a variable as "read" */
2064 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2069 case EXPR_UNARY_THROW:
2070 if (expr->unary.value == NULL)
2073 case EXPR_UNARY_DEREFERENCE:
2074 case EXPR_UNARY_DELETE:
2075 case EXPR_UNARY_DELETE_ARRAY:
2076 if (lhs_ent == ENT_ANY)
2080 case EXPR_UNARY_NEGATE:
2081 case EXPR_UNARY_PLUS:
2082 case EXPR_UNARY_BITWISE_NEGATE:
2083 case EXPR_UNARY_NOT:
2084 case EXPR_UNARY_TAKE_ADDRESS:
2085 case EXPR_UNARY_POSTFIX_INCREMENT:
2086 case EXPR_UNARY_POSTFIX_DECREMENT:
2087 case EXPR_UNARY_PREFIX_INCREMENT:
2088 case EXPR_UNARY_PREFIX_DECREMENT:
2089 case EXPR_UNARY_CAST_IMPLICIT:
2090 case EXPR_UNARY_ASSUME:
2092 mark_vars_read(expr->unary.value, lhs_ent);
2095 case EXPR_BINARY_ADD:
2096 case EXPR_BINARY_SUB:
2097 case EXPR_BINARY_MUL:
2098 case EXPR_BINARY_DIV:
2099 case EXPR_BINARY_MOD:
2100 case EXPR_BINARY_EQUAL:
2101 case EXPR_BINARY_NOTEQUAL:
2102 case EXPR_BINARY_LESS:
2103 case EXPR_BINARY_LESSEQUAL:
2104 case EXPR_BINARY_GREATER:
2105 case EXPR_BINARY_GREATEREQUAL:
2106 case EXPR_BINARY_BITWISE_AND:
2107 case EXPR_BINARY_BITWISE_OR:
2108 case EXPR_BINARY_BITWISE_XOR:
2109 case EXPR_BINARY_LOGICAL_AND:
2110 case EXPR_BINARY_LOGICAL_OR:
2111 case EXPR_BINARY_SHIFTLEFT:
2112 case EXPR_BINARY_SHIFTRIGHT:
2113 case EXPR_BINARY_COMMA:
2114 case EXPR_BINARY_ISGREATER:
2115 case EXPR_BINARY_ISGREATEREQUAL:
2116 case EXPR_BINARY_ISLESS:
2117 case EXPR_BINARY_ISLESSEQUAL:
2118 case EXPR_BINARY_ISLESSGREATER:
2119 case EXPR_BINARY_ISUNORDERED:
2120 mark_vars_read(expr->binary.left, lhs_ent);
2121 mark_vars_read(expr->binary.right, lhs_ent);
2124 case EXPR_BINARY_ASSIGN:
2125 case EXPR_BINARY_MUL_ASSIGN:
2126 case EXPR_BINARY_DIV_ASSIGN:
2127 case EXPR_BINARY_MOD_ASSIGN:
2128 case EXPR_BINARY_ADD_ASSIGN:
2129 case EXPR_BINARY_SUB_ASSIGN:
2130 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2131 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2132 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2133 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2134 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2135 if (lhs_ent == ENT_ANY)
2137 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
2138 mark_vars_read(expr->binary.right, lhs_ent);
2143 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
2149 case EXPR_CHARACTER_CONSTANT:
2150 case EXPR_WIDE_CHARACTER_CONSTANT:
2151 case EXPR_STRING_LITERAL:
2152 case EXPR_WIDE_STRING_LITERAL:
2153 case EXPR_COMPOUND_LITERAL: // TODO init?
2155 case EXPR_CLASSIFY_TYPE:
2158 case EXPR_BUILTIN_CONSTANT_P:
2159 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
2161 case EXPR_STATEMENT: // TODO
2162 case EXPR_LABEL_ADDRESS:
2163 case EXPR_REFERENCE_ENUM_VALUE:
2167 panic("unhandled expression");
2170 static designator_t *parse_designation(void)
2172 designator_t *result = NULL;
2173 designator_t *last = NULL;
2176 designator_t *designator;
2177 switch (token.type) {
2179 designator = allocate_ast_zero(sizeof(designator[0]));
2180 designator->source_position = token.source_position;
2182 add_anchor_token(']');
2183 designator->array_index = parse_constant_expression();
2184 rem_anchor_token(']');
2185 expect(']', end_error);
2188 designator = allocate_ast_zero(sizeof(designator[0]));
2189 designator->source_position = token.source_position;
2191 if (token.type != T_IDENTIFIER) {
2192 parse_error_expected("while parsing designator",
2193 T_IDENTIFIER, NULL);
2196 designator->symbol = token.v.symbol;
2200 expect('=', end_error);
2204 assert(designator != NULL);
2206 last->next = designator;
2208 result = designator;
2216 static initializer_t *initializer_from_string(array_type_t *type,
2217 const string_t *const string)
2219 /* TODO: check len vs. size of array type */
2222 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2223 initializer->string.string = *string;
2228 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2229 wide_string_t *const string)
2231 /* TODO: check len vs. size of array type */
2234 initializer_t *const initializer =
2235 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2236 initializer->wide_string.string = *string;
2242 * Build an initializer from a given expression.
2244 static initializer_t *initializer_from_expression(type_t *orig_type,
2245 expression_t *expression)
2247 /* TODO check that expression is a constant expression */
2249 /* §6.7.8.14/15 char array may be initialized by string literals */
2250 type_t *type = skip_typeref(orig_type);
2251 type_t *expr_type_orig = expression->base.type;
2252 type_t *expr_type = skip_typeref(expr_type_orig);
2253 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2254 array_type_t *const array_type = &type->array;
2255 type_t *const element_type = skip_typeref(array_type->element_type);
2257 if (element_type->kind == TYPE_ATOMIC) {
2258 atomic_type_kind_t akind = element_type->atomic.akind;
2259 switch (expression->kind) {
2260 case EXPR_STRING_LITERAL:
2261 if (akind == ATOMIC_TYPE_CHAR
2262 || akind == ATOMIC_TYPE_SCHAR
2263 || akind == ATOMIC_TYPE_UCHAR) {
2264 return initializer_from_string(array_type,
2265 &expression->string.value);
2269 case EXPR_WIDE_STRING_LITERAL: {
2270 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2271 if (get_unqualified_type(element_type) == bare_wchar_type) {
2272 return initializer_from_wide_string(array_type,
2273 &expression->wide_string.value);
2284 assign_error_t error = semantic_assign(type, expression);
2285 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2287 report_assign_error(error, type, expression, "initializer",
2288 &expression->base.source_position);
2290 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2292 if (type->kind == TYPE_BITFIELD) {
2293 type = type->bitfield.base_type;
2296 result->value.value = create_implicit_cast(expression, type);
2302 * Checks if a given expression can be used as an constant initializer.
2304 static bool is_initializer_constant(const expression_t *expression)
2306 return is_constant_expression(expression)
2307 || is_address_constant(expression);
2311 * Parses an scalar initializer.
2313 * §6.7.8.11; eat {} without warning
2315 static initializer_t *parse_scalar_initializer(type_t *type,
2316 bool must_be_constant)
2318 /* there might be extra {} hierarchies */
2320 if (token.type == '{') {
2322 warningf(HERE, "extra curly braces around scalar initializer");
2326 } while (token.type == '{');
2329 expression_t *expression = parse_assignment_expression();
2330 mark_vars_read(expression, NULL);
2331 if (must_be_constant && !is_initializer_constant(expression)) {
2332 errorf(&expression->base.source_position,
2333 "Initialisation expression '%E' is not constant",
2337 initializer_t *initializer = initializer_from_expression(type, expression);
2339 if (initializer == NULL) {
2340 errorf(&expression->base.source_position,
2341 "expression '%E' (type '%T') doesn't match expected type '%T'",
2342 expression, expression->base.type, type);
2347 bool additional_warning_displayed = false;
2348 while (braces > 0) {
2349 if (token.type == ',') {
2352 if (token.type != '}') {
2353 if (!additional_warning_displayed && warning.other) {
2354 warningf(HERE, "additional elements in scalar initializer");
2355 additional_warning_displayed = true;
2366 * An entry in the type path.
2368 typedef struct type_path_entry_t type_path_entry_t;
2369 struct type_path_entry_t {
2370 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2372 size_t index; /**< For array types: the current index. */
2373 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2378 * A type path expression a position inside compound or array types.
2380 typedef struct type_path_t type_path_t;
2381 struct type_path_t {
2382 type_path_entry_t *path; /**< An flexible array containing the current path. */
2383 type_t *top_type; /**< type of the element the path points */
2384 size_t max_index; /**< largest index in outermost array */
2388 * Prints a type path for debugging.
2390 static __attribute__((unused)) void debug_print_type_path(
2391 const type_path_t *path)
2393 size_t len = ARR_LEN(path->path);
2395 for (size_t i = 0; i < len; ++i) {
2396 const type_path_entry_t *entry = & path->path[i];
2398 type_t *type = skip_typeref(entry->type);
2399 if (is_type_compound(type)) {
2400 /* in gcc mode structs can have no members */
2401 if (entry->v.compound_entry == NULL) {
2405 fprintf(stderr, ".%s",
2406 entry->v.compound_entry->base.symbol->string);
2407 } else if (is_type_array(type)) {
2408 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
2410 fprintf(stderr, "-INVALID-");
2413 if (path->top_type != NULL) {
2414 fprintf(stderr, " (");
2415 print_type(path->top_type);
2416 fprintf(stderr, ")");
2421 * Return the top type path entry, ie. in a path
2422 * (type).a.b returns the b.
2424 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2426 size_t len = ARR_LEN(path->path);
2428 return &path->path[len-1];
2432 * Enlarge the type path by an (empty) element.
2434 static type_path_entry_t *append_to_type_path(type_path_t *path)
2436 size_t len = ARR_LEN(path->path);
2437 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2439 type_path_entry_t *result = & path->path[len];
2440 memset(result, 0, sizeof(result[0]));
2445 * Descending into a sub-type. Enter the scope of the current top_type.
2447 static void descend_into_subtype(type_path_t *path)
2449 type_t *orig_top_type = path->top_type;
2450 type_t *top_type = skip_typeref(orig_top_type);
2452 type_path_entry_t *top = append_to_type_path(path);
2453 top->type = top_type;
2455 if (is_type_compound(top_type)) {
2456 compound_t *compound = top_type->compound.compound;
2457 entity_t *entry = compound->members.entities;
2459 if (entry != NULL) {
2460 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2461 top->v.compound_entry = &entry->declaration;
2462 path->top_type = entry->declaration.type;
2464 path->top_type = NULL;
2466 } else if (is_type_array(top_type)) {
2468 path->top_type = top_type->array.element_type;
2470 assert(!is_type_valid(top_type));
2475 * Pop an entry from the given type path, ie. returning from
2476 * (type).a.b to (type).a
2478 static void ascend_from_subtype(type_path_t *path)
2480 type_path_entry_t *top = get_type_path_top(path);
2482 path->top_type = top->type;
2484 size_t len = ARR_LEN(path->path);
2485 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2489 * Pop entries from the given type path until the given
2490 * path level is reached.
2492 static void ascend_to(type_path_t *path, size_t top_path_level)
2494 size_t len = ARR_LEN(path->path);
2496 while (len > top_path_level) {
2497 ascend_from_subtype(path);
2498 len = ARR_LEN(path->path);
2502 static bool walk_designator(type_path_t *path, const designator_t *designator,
2503 bool used_in_offsetof)
2505 for (; designator != NULL; designator = designator->next) {
2506 type_path_entry_t *top = get_type_path_top(path);
2507 type_t *orig_type = top->type;
2509 type_t *type = skip_typeref(orig_type);
2511 if (designator->symbol != NULL) {
2512 symbol_t *symbol = designator->symbol;
2513 if (!is_type_compound(type)) {
2514 if (is_type_valid(type)) {
2515 errorf(&designator->source_position,
2516 "'.%Y' designator used for non-compound type '%T'",
2520 top->type = type_error_type;
2521 top->v.compound_entry = NULL;
2522 orig_type = type_error_type;
2524 compound_t *compound = type->compound.compound;
2525 entity_t *iter = compound->members.entities;
2526 for (; iter != NULL; iter = iter->base.next) {
2527 if (iter->base.symbol == symbol) {
2532 errorf(&designator->source_position,
2533 "'%T' has no member named '%Y'", orig_type, symbol);
2536 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2537 if (used_in_offsetof) {
2538 type_t *real_type = skip_typeref(iter->declaration.type);
2539 if (real_type->kind == TYPE_BITFIELD) {
2540 errorf(&designator->source_position,
2541 "offsetof designator '%Y' may not specify bitfield",
2547 top->type = orig_type;
2548 top->v.compound_entry = &iter->declaration;
2549 orig_type = iter->declaration.type;
2552 expression_t *array_index = designator->array_index;
2553 assert(designator->array_index != NULL);
2555 if (!is_type_array(type)) {
2556 if (is_type_valid(type)) {
2557 errorf(&designator->source_position,
2558 "[%E] designator used for non-array type '%T'",
2559 array_index, orig_type);
2564 long index = fold_constant(array_index);
2565 if (!used_in_offsetof) {
2567 errorf(&designator->source_position,
2568 "array index [%E] must be positive", array_index);
2569 } else if (type->array.size_constant) {
2570 long array_size = type->array.size;
2571 if (index >= array_size) {
2572 errorf(&designator->source_position,
2573 "designator [%E] (%d) exceeds array size %d",
2574 array_index, index, array_size);
2579 top->type = orig_type;
2580 top->v.index = (size_t) index;
2581 orig_type = type->array.element_type;
2583 path->top_type = orig_type;
2585 if (designator->next != NULL) {
2586 descend_into_subtype(path);
2595 static void advance_current_object(type_path_t *path, size_t top_path_level)
2597 type_path_entry_t *top = get_type_path_top(path);
2599 type_t *type = skip_typeref(top->type);
2600 if (is_type_union(type)) {
2601 /* in unions only the first element is initialized */
2602 top->v.compound_entry = NULL;
2603 } else if (is_type_struct(type)) {
2604 declaration_t *entry = top->v.compound_entry;
2606 entity_t *next_entity = entry->base.next;
2607 if (next_entity != NULL) {
2608 assert(is_declaration(next_entity));
2609 entry = &next_entity->declaration;
2614 top->v.compound_entry = entry;
2615 if (entry != NULL) {
2616 path->top_type = entry->type;
2619 } else if (is_type_array(type)) {
2620 assert(is_type_array(type));
2624 if (!type->array.size_constant || top->v.index < type->array.size) {
2628 assert(!is_type_valid(type));
2632 /* we're past the last member of the current sub-aggregate, try if we
2633 * can ascend in the type hierarchy and continue with another subobject */
2634 size_t len = ARR_LEN(path->path);
2636 if (len > top_path_level) {
2637 ascend_from_subtype(path);
2638 advance_current_object(path, top_path_level);
2640 path->top_type = NULL;
2645 * skip until token is found.
2647 static void skip_until(int type)
2649 while (token.type != type) {
2650 if (token.type == T_EOF)
2657 * skip any {...} blocks until a closing bracket is reached.
2659 static void skip_initializers(void)
2661 if (token.type == '{')
2664 while (token.type != '}') {
2665 if (token.type == T_EOF)
2667 if (token.type == '{') {
2675 static initializer_t *create_empty_initializer(void)
2677 static initializer_t empty_initializer
2678 = { .list = { { INITIALIZER_LIST }, 0 } };
2679 return &empty_initializer;
2683 * Parse a part of an initialiser for a struct or union,
2685 static initializer_t *parse_sub_initializer(type_path_t *path,
2686 type_t *outer_type, size_t top_path_level,
2687 parse_initializer_env_t *env)
2689 if (token.type == '}') {
2690 /* empty initializer */
2691 return create_empty_initializer();
2694 type_t *orig_type = path->top_type;
2695 type_t *type = NULL;
2697 if (orig_type == NULL) {
2698 /* We are initializing an empty compound. */
2700 type = skip_typeref(orig_type);
2703 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2706 designator_t *designator = NULL;
2707 if (token.type == '.' || token.type == '[') {
2708 designator = parse_designation();
2709 goto finish_designator;
2710 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2711 /* GNU-style designator ("identifier: value") */
2712 designator = allocate_ast_zero(sizeof(designator[0]));
2713 designator->source_position = token.source_position;
2714 designator->symbol = token.v.symbol;
2719 /* reset path to toplevel, evaluate designator from there */
2720 ascend_to(path, top_path_level);
2721 if (!walk_designator(path, designator, false)) {
2722 /* can't continue after designation error */
2726 initializer_t *designator_initializer
2727 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2728 designator_initializer->designator.designator = designator;
2729 ARR_APP1(initializer_t*, initializers, designator_initializer);
2731 orig_type = path->top_type;
2732 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2737 if (token.type == '{') {
2738 if (type != NULL && is_type_scalar(type)) {
2739 sub = parse_scalar_initializer(type, env->must_be_constant);
2743 if (env->entity != NULL) {
2745 "extra brace group at end of initializer for '%Y'",
2746 env->entity->base.symbol);
2748 errorf(HERE, "extra brace group at end of initializer");
2751 descend_into_subtype(path);
2753 add_anchor_token('}');
2754 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2756 rem_anchor_token('}');
2759 ascend_from_subtype(path);
2760 expect('}', end_error);
2762 expect('}', end_error);
2763 goto error_parse_next;
2767 /* must be an expression */
2768 expression_t *expression = parse_assignment_expression();
2769 mark_vars_read(expression, NULL);
2771 if (env->must_be_constant && !is_initializer_constant(expression)) {
2772 errorf(&expression->base.source_position,
2773 "Initialisation expression '%E' is not constant",
2778 /* we are already outside, ... */
2779 type_t *const outer_type_skip = skip_typeref(outer_type);
2780 if (is_type_compound(outer_type_skip) &&
2781 !outer_type_skip->compound.compound->complete) {
2782 goto error_parse_next;
2787 /* handle { "string" } special case */
2788 if ((expression->kind == EXPR_STRING_LITERAL
2789 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2790 && outer_type != NULL) {
2791 sub = initializer_from_expression(outer_type, expression);
2793 if (token.type == ',') {
2796 if (token.type != '}' && warning.other) {
2797 warningf(HERE, "excessive elements in initializer for type '%T'",
2800 /* TODO: eat , ... */
2805 /* descend into subtypes until expression matches type */
2807 orig_type = path->top_type;
2808 type = skip_typeref(orig_type);
2810 sub = initializer_from_expression(orig_type, expression);
2814 if (!is_type_valid(type)) {
2817 if (is_type_scalar(type)) {
2818 errorf(&expression->base.source_position,
2819 "expression '%E' doesn't match expected type '%T'",
2820 expression, orig_type);
2824 descend_into_subtype(path);
2828 /* update largest index of top array */
2829 const type_path_entry_t *first = &path->path[0];
2830 type_t *first_type = first->type;
2831 first_type = skip_typeref(first_type);
2832 if (is_type_array(first_type)) {
2833 size_t index = first->v.index;
2834 if (index > path->max_index)
2835 path->max_index = index;
2839 /* append to initializers list */
2840 ARR_APP1(initializer_t*, initializers, sub);
2843 if (warning.other) {
2844 if (env->entity != NULL) {
2845 warningf(HERE, "excess elements in struct initializer for '%Y'",
2846 env->entity->base.symbol);
2848 warningf(HERE, "excess elements in struct initializer");
2854 if (token.type == '}') {
2857 expect(',', end_error);
2858 if (token.type == '}') {
2863 /* advance to the next declaration if we are not at the end */
2864 advance_current_object(path, top_path_level);
2865 orig_type = path->top_type;
2866 if (orig_type != NULL)
2867 type = skip_typeref(orig_type);
2873 size_t len = ARR_LEN(initializers);
2874 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2875 initializer_t *result = allocate_ast_zero(size);
2876 result->kind = INITIALIZER_LIST;
2877 result->list.len = len;
2878 memcpy(&result->list.initializers, initializers,
2879 len * sizeof(initializers[0]));
2881 DEL_ARR_F(initializers);
2882 ascend_to(path, top_path_level+1);
2887 skip_initializers();
2888 DEL_ARR_F(initializers);
2889 ascend_to(path, top_path_level+1);
2894 * Parses an initializer. Parsers either a compound literal
2895 * (env->declaration == NULL) or an initializer of a declaration.
2897 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2899 type_t *type = skip_typeref(env->type);
2900 size_t max_index = 0xdeadbeaf; // TODO: Resolve this uninitialized variable problem
2901 initializer_t *result;
2903 if (is_type_scalar(type)) {
2904 result = parse_scalar_initializer(type, env->must_be_constant);
2905 } else if (token.type == '{') {
2909 memset(&path, 0, sizeof(path));
2910 path.top_type = env->type;
2911 path.path = NEW_ARR_F(type_path_entry_t, 0);
2913 descend_into_subtype(&path);
2915 add_anchor_token('}');
2916 result = parse_sub_initializer(&path, env->type, 1, env);
2917 rem_anchor_token('}');
2919 max_index = path.max_index;
2920 DEL_ARR_F(path.path);
2922 expect('}', end_error);
2924 /* parse_scalar_initializer() also works in this case: we simply
2925 * have an expression without {} around it */
2926 result = parse_scalar_initializer(type, env->must_be_constant);
2929 /* §6.7.8:22 array initializers for arrays with unknown size determine
2930 * the array type size */
2931 if (is_type_array(type) && type->array.size_expression == NULL
2932 && result != NULL) {
2934 switch (result->kind) {
2935 case INITIALIZER_LIST:
2936 assert(max_index != 0xdeadbeaf);
2937 size = max_index + 1;
2940 case INITIALIZER_STRING:
2941 size = result->string.string.size;
2944 case INITIALIZER_WIDE_STRING:
2945 size = result->wide_string.string.size;
2948 case INITIALIZER_DESIGNATOR:
2949 case INITIALIZER_VALUE:
2950 /* can happen for parse errors */
2955 internal_errorf(HERE, "invalid initializer type");
2958 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2959 cnst->base.type = type_size_t;
2960 cnst->conste.v.int_value = size;
2962 type_t *new_type = duplicate_type(type);
2964 new_type->array.size_expression = cnst;
2965 new_type->array.size_constant = true;
2966 new_type->array.has_implicit_size = true;
2967 new_type->array.size = size;
2968 env->type = new_type;
2976 static void append_entity(scope_t *scope, entity_t *entity)
2978 if (scope->last_entity != NULL) {
2979 scope->last_entity->base.next = entity;
2981 scope->entities = entity;
2983 scope->last_entity = entity;
2987 static compound_t *parse_compound_type_specifier(bool is_struct)
2989 gnu_attribute_t *attributes = NULL;
2990 decl_modifiers_t modifiers = 0;
2997 symbol_t *symbol = NULL;
2998 compound_t *compound = NULL;
3000 if (token.type == T___attribute__) {
3001 modifiers |= parse_attributes(&attributes);
3004 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
3005 if (token.type == T_IDENTIFIER) {
3006 /* the compound has a name, check if we have seen it already */
3007 symbol = token.v.symbol;
3010 entity_t *entity = get_tag(symbol, kind);
3011 if (entity != NULL) {
3012 compound = &entity->compound;
3013 if (compound->base.parent_scope != current_scope &&
3014 (token.type == '{' || token.type == ';')) {
3015 /* we're in an inner scope and have a definition. Shadow
3016 * existing definition in outer scope */
3018 } else if (compound->complete && token.type == '{') {
3019 assert(symbol != NULL);
3020 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
3021 is_struct ? "struct" : "union", symbol,
3022 &compound->base.source_position);
3023 /* clear members in the hope to avoid further errors */
3024 compound->members.entities = NULL;
3027 } else if (token.type != '{') {
3029 parse_error_expected("while parsing struct type specifier",
3030 T_IDENTIFIER, '{', NULL);
3032 parse_error_expected("while parsing union type specifier",
3033 T_IDENTIFIER, '{', NULL);
3039 if (compound == NULL) {
3040 entity_t *entity = allocate_entity_zero(kind);
3041 compound = &entity->compound;
3043 compound->base.namespc = NAMESPACE_TAG;
3044 compound->base.source_position = token.source_position;
3045 compound->base.symbol = symbol;
3046 compound->base.parent_scope = current_scope;
3047 if (symbol != NULL) {
3048 environment_push(entity);
3050 append_entity(current_scope, entity);
3053 if (token.type == '{') {
3054 parse_compound_type_entries(compound);
3055 modifiers |= parse_attributes(&attributes);
3057 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
3058 if (symbol == NULL) {
3059 assert(anonymous_entity == NULL);
3060 anonymous_entity = (entity_t*)compound;
3064 compound->modifiers |= modifiers;
3068 static void parse_enum_entries(type_t *const enum_type)
3072 if (token.type == '}') {
3073 errorf(HERE, "empty enum not allowed");
3078 add_anchor_token('}');
3080 if (token.type != T_IDENTIFIER) {
3081 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3083 rem_anchor_token('}');
3087 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3088 entity->enum_value.enum_type = enum_type;
3089 entity->base.symbol = token.v.symbol;
3090 entity->base.source_position = token.source_position;
3093 if (token.type == '=') {
3095 expression_t *value = parse_constant_expression();
3097 value = create_implicit_cast(value, enum_type);
3098 entity->enum_value.value = value;
3103 record_entity(entity, false);
3105 if (token.type != ',')
3108 } while (token.type != '}');
3109 rem_anchor_token('}');
3111 expect('}', end_error);
3117 static type_t *parse_enum_specifier(void)
3119 gnu_attribute_t *attributes = NULL;
3124 if (token.type == T_IDENTIFIER) {
3125 symbol = token.v.symbol;
3128 entity = get_tag(symbol, ENTITY_ENUM);
3129 if (entity != NULL) {
3130 if (entity->base.parent_scope != current_scope &&
3131 (token.type == '{' || token.type == ';')) {
3132 /* we're in an inner scope and have a definition. Shadow
3133 * existing definition in outer scope */
3135 } else if (entity->enume.complete && token.type == '{') {
3136 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
3137 symbol, &entity->base.source_position);
3140 } else if (token.type != '{') {
3141 parse_error_expected("while parsing enum type specifier",
3142 T_IDENTIFIER, '{', NULL);
3149 if (entity == NULL) {
3150 entity = allocate_entity_zero(ENTITY_ENUM);
3151 entity->base.namespc = NAMESPACE_TAG;
3152 entity->base.source_position = token.source_position;
3153 entity->base.symbol = symbol;
3154 entity->base.parent_scope = current_scope;
3157 type_t *const type = allocate_type_zero(TYPE_ENUM);
3158 type->enumt.enume = &entity->enume;
3159 type->enumt.akind = ATOMIC_TYPE_INT;
3161 if (token.type == '{') {
3162 if (symbol != NULL) {
3163 environment_push(entity);
3165 append_entity(current_scope, entity);
3166 entity->enume.complete = true;
3168 parse_enum_entries(type);
3169 parse_attributes(&attributes);
3171 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
3172 if (symbol == NULL) {
3173 assert(anonymous_entity == NULL);
3174 anonymous_entity = entity;
3176 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
3177 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
3185 * if a symbol is a typedef to another type, return true
3187 static bool is_typedef_symbol(symbol_t *symbol)
3189 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3190 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3193 static type_t *parse_typeof(void)
3199 expect('(', end_error);
3200 add_anchor_token(')');
3202 expression_t *expression = NULL;
3204 bool old_type_prop = in_type_prop;
3205 bool old_gcc_extension = in_gcc_extension;
3206 in_type_prop = true;
3208 while (token.type == T___extension__) {
3209 /* This can be a prefix to a typename or an expression. */
3211 in_gcc_extension = true;
3213 switch (token.type) {
3215 if (is_typedef_symbol(token.v.symbol)) {
3216 type = parse_typename();
3218 expression = parse_expression();
3219 type = revert_automatic_type_conversion(expression);
3224 type = parse_typename();
3228 expression = parse_expression();
3229 type = expression->base.type;
3232 in_type_prop = old_type_prop;
3233 in_gcc_extension = old_gcc_extension;
3235 rem_anchor_token(')');
3236 expect(')', end_error);
3238 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3239 typeof_type->typeoft.expression = expression;
3240 typeof_type->typeoft.typeof_type = type;
3247 typedef enum specifiers_t {
3248 SPECIFIER_SIGNED = 1 << 0,
3249 SPECIFIER_UNSIGNED = 1 << 1,
3250 SPECIFIER_LONG = 1 << 2,
3251 SPECIFIER_INT = 1 << 3,
3252 SPECIFIER_DOUBLE = 1 << 4,
3253 SPECIFIER_CHAR = 1 << 5,
3254 SPECIFIER_WCHAR_T = 1 << 6,
3255 SPECIFIER_SHORT = 1 << 7,
3256 SPECIFIER_LONG_LONG = 1 << 8,
3257 SPECIFIER_FLOAT = 1 << 9,
3258 SPECIFIER_BOOL = 1 << 10,
3259 SPECIFIER_VOID = 1 << 11,
3260 SPECIFIER_INT8 = 1 << 12,
3261 SPECIFIER_INT16 = 1 << 13,
3262 SPECIFIER_INT32 = 1 << 14,
3263 SPECIFIER_INT64 = 1 << 15,
3264 SPECIFIER_INT128 = 1 << 16,
3265 SPECIFIER_COMPLEX = 1 << 17,
3266 SPECIFIER_IMAGINARY = 1 << 18,
3269 static type_t *create_builtin_type(symbol_t *const symbol,
3270 type_t *const real_type)
3272 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3273 type->builtin.symbol = symbol;
3274 type->builtin.real_type = real_type;
3275 return identify_new_type(type);
3278 static type_t *get_typedef_type(symbol_t *symbol)
3280 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3281 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3284 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3285 type->typedeft.typedefe = &entity->typedefe;
3291 * check for the allowed MS alignment values.
3293 static bool check_alignment_value(long long intvalue)
3295 if (intvalue < 1 || intvalue > 8192) {
3296 errorf(HERE, "illegal alignment value");
3299 unsigned v = (unsigned)intvalue;
3300 for (unsigned i = 1; i <= 8192; i += i) {
3304 errorf(HERE, "alignment must be power of two");
3308 #define DET_MOD(name, tag) do { \
3309 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3310 *modifiers |= tag; \
3313 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3315 decl_modifiers_t *modifiers = &specifiers->modifiers;
3318 if (token.type == T_restrict) {
3320 DET_MOD(restrict, DM_RESTRICT);
3322 } else if (token.type != T_IDENTIFIER)
3324 symbol_t *symbol = token.v.symbol;
3325 if (symbol == sym_align) {
3327 expect('(', end_error);
3328 if (token.type != T_INTEGER)
3330 if (check_alignment_value(token.v.intvalue)) {
3331 if (specifiers->alignment != 0 && warning.other)
3332 warningf(HERE, "align used more than once");
3333 specifiers->alignment = (unsigned char)token.v.intvalue;
3336 expect(')', end_error);
3337 } else if (symbol == sym_allocate) {
3339 expect('(', end_error);
3340 if (token.type != T_IDENTIFIER)
3342 (void)token.v.symbol;
3343 expect(')', end_error);
3344 } else if (symbol == sym_dllimport) {
3346 DET_MOD(dllimport, DM_DLLIMPORT);
3347 } else if (symbol == sym_dllexport) {
3349 DET_MOD(dllexport, DM_DLLEXPORT);
3350 } else if (symbol == sym_thread) {
3352 DET_MOD(thread, DM_THREAD);
3353 } else if (symbol == sym_naked) {
3355 DET_MOD(naked, DM_NAKED);
3356 } else if (symbol == sym_noinline) {
3358 DET_MOD(noinline, DM_NOINLINE);
3359 } else if (symbol == sym_returns_twice) {
3361 DET_MOD(returns_twice, DM_RETURNS_TWICE);
3362 } else if (symbol == sym_noreturn) {
3364 DET_MOD(noreturn, DM_NORETURN);
3365 } else if (symbol == sym_nothrow) {
3367 DET_MOD(nothrow, DM_NOTHROW);
3368 } else if (symbol == sym_novtable) {
3370 DET_MOD(novtable, DM_NOVTABLE);
3371 } else if (symbol == sym_property) {
3373 expect('(', end_error);
3375 bool is_get = false;
3376 if (token.type != T_IDENTIFIER)
3378 if (token.v.symbol == sym_get) {
3380 } else if (token.v.symbol == sym_put) {
3382 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3386 expect('=', end_error);
3387 if (token.type != T_IDENTIFIER)
3390 if (specifiers->get_property_sym != NULL) {
3391 errorf(HERE, "get property name already specified");
3393 specifiers->get_property_sym = token.v.symbol;
3396 if (specifiers->put_property_sym != NULL) {
3397 errorf(HERE, "put property name already specified");
3399 specifiers->put_property_sym = token.v.symbol;
3403 if (token.type == ',') {
3409 expect(')', end_error);
3410 } else if (symbol == sym_selectany) {
3412 DET_MOD(selectany, DM_SELECTANY);
3413 } else if (symbol == sym_uuid) {
3415 expect('(', end_error);
3416 if (token.type != T_STRING_LITERAL)
3419 expect(')', end_error);
3420 } else if (symbol == sym_deprecated) {
3422 if (specifiers->deprecated != 0 && warning.other)
3423 warningf(HERE, "deprecated used more than once");
3424 specifiers->deprecated = true;
3425 if (token.type == '(') {
3427 if (token.type == T_STRING_LITERAL) {
3428 specifiers->deprecated_string = token.v.string.begin;
3431 errorf(HERE, "string literal expected");
3433 expect(')', end_error);
3435 } else if (symbol == sym_noalias) {
3437 DET_MOD(noalias, DM_NOALIAS);
3440 warningf(HERE, "Unknown modifier '%Y' ignored", token.v.symbol);
3442 if (token.type == '(')
3446 if (token.type == ',')
3453 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3455 entity_t *entity = allocate_entity_zero(kind);
3456 entity->base.source_position = *HERE;
3457 entity->base.symbol = symbol;
3458 if (is_declaration(entity)) {
3459 entity->declaration.type = type_error_type;
3460 entity->declaration.implicit = true;
3461 } else if (kind == ENTITY_TYPEDEF) {
3462 entity->typedefe.type = type_error_type;
3463 entity->typedefe.builtin = true;
3465 if (kind != ENTITY_COMPOUND_MEMBER)
3466 record_entity(entity, false);
3470 static variable_t *parse_microsoft_based(void)
3472 if (token.type != T_IDENTIFIER) {
3473 parse_error_expected("while parsing __based", T_IDENTIFIER, NULL);
3476 symbol_t *symbol = token.v.symbol;
3477 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3479 variable_t *variable;
3480 if (entity == NULL || entity->base.kind != ENTITY_VARIABLE) {
3481 errorf(HERE, "'%Y' is not a variable name.", symbol);
3482 variable = &create_error_entity(symbol, ENTITY_VARIABLE)->variable;
3484 variable = &entity->variable;
3486 type_t *const type = variable->base.type;
3487 if (is_type_valid(type)) {
3488 if (! is_type_pointer(skip_typeref(type))) {
3489 errorf(HERE, "variable in __based modifier must have pointer type instead of '%T'", type);
3491 if (variable->base.base.parent_scope != file_scope) {
3492 errorf(HERE, "a nonstatic local variable may not be used in a __based specification");
3501 * Finish the construction of a struct type by calculating
3502 * its size, offsets, alignment.
3504 static void finish_struct_type(compound_type_t *type)
3506 assert(type->compound != NULL);
3508 compound_t *compound = type->compound;
3509 if (!compound->complete)
3514 il_alignment_t alignment = 1;
3515 bool need_pad = false;
3517 entity_t *entry = compound->members.entities;
3518 for (; entry != NULL; entry = entry->base.next) {
3519 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3522 type_t *m_type = skip_typeref(entry->declaration.type);
3523 if (! is_type_valid(m_type)) {
3524 /* simply ignore errors here */
3527 il_alignment_t m_alignment = m_type->base.alignment;
3528 if (m_alignment > alignment)
3529 alignment = m_alignment;
3531 offset = (size + m_alignment - 1) & -m_alignment;
3535 entry->compound_member.offset = offset;
3536 size = offset + m_type->base.size;
3538 if (type->base.alignment != 0) {
3539 alignment = type->base.alignment;
3542 offset = (size + alignment - 1) & -alignment;
3547 if (warning.padded) {
3548 warningf(&compound->base.source_position, "'%T' needs padding", type);
3551 if (compound->modifiers & DM_PACKED && warning.packed) {
3552 warningf(&compound->base.source_position,
3553 "superfluous packed attribute on '%T'", type);
3557 type->base.size = offset;
3558 type->base.alignment = alignment;
3562 * Finish the construction of an union type by calculating
3563 * its size and alignment.
3565 static void finish_union_type(compound_type_t *type)
3567 assert(type->compound != NULL);
3569 compound_t *compound = type->compound;
3570 if (! compound->complete)
3574 il_alignment_t alignment = 1;
3576 entity_t *entry = compound->members.entities;
3577 for (; entry != NULL; entry = entry->base.next) {
3578 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3581 type_t *m_type = skip_typeref(entry->declaration.type);
3582 if (! is_type_valid(m_type))
3585 entry->compound_member.offset = 0;
3586 if (m_type->base.size > size)
3587 size = m_type->base.size;
3588 if (m_type->base.alignment > alignment)
3589 alignment = m_type->base.alignment;
3591 if (type->base.alignment != 0) {
3592 alignment = type->base.alignment;
3594 size = (size + alignment - 1) & -alignment;
3595 type->base.size = size;
3596 type->base.alignment = alignment;
3599 static type_t *handle_attribute_mode(const gnu_attribute_t *attribute,
3602 type_t *type = skip_typeref(orig_type);
3604 /* at least: byte, word, pointer, list of machine modes
3605 * __XXX___ is interpreted as XXX */
3607 /* This isn't really correct, the backend should provide a list of machine
3608 * specific modes (according to gcc philosophy that is...) */
3609 const char *symbol_str = attribute->u.symbol->string;
3610 bool sign = is_type_signed(type);
3611 atomic_type_kind_t akind;
3612 if (strcmp_underscore("QI", symbol_str) == 0 ||
3613 strcmp_underscore("byte", symbol_str) == 0) {
3614 akind = sign ? ATOMIC_TYPE_CHAR : ATOMIC_TYPE_UCHAR;
3615 } else if (strcmp_underscore("HI", symbol_str) == 0) {
3616 akind = sign ? ATOMIC_TYPE_SHORT : ATOMIC_TYPE_USHORT;
3617 } else if (strcmp_underscore("SI", symbol_str) == 0
3618 || strcmp_underscore("word", symbol_str) == 0
3619 || strcmp_underscore("pointer", symbol_str) == 0) {
3620 akind = sign ? ATOMIC_TYPE_INT : ATOMIC_TYPE_UINT;
3621 } else if (strcmp_underscore("DI", symbol_str) == 0) {
3622 akind = sign ? ATOMIC_TYPE_LONGLONG : ATOMIC_TYPE_ULONGLONG;
3625 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
3629 if (type->kind == TYPE_ATOMIC) {
3630 type_t *copy = duplicate_type(type);
3631 copy->atomic.akind = akind;
3632 return identify_new_type(copy);
3633 } else if (type->kind == TYPE_ENUM) {
3634 type_t *copy = duplicate_type(type);
3635 copy->enumt.akind = akind;
3636 return identify_new_type(copy);
3637 } else if (is_type_pointer(type)) {
3638 warningf(HERE, "__attribute__((mode)) on pointers not implemented yet (ignored)");
3642 errorf(HERE, "__attribute__((mode)) only allowed on integer, enum or pointer type");
3646 static type_t *handle_type_attributes(const gnu_attribute_t *attributes,
3649 const gnu_attribute_t *attribute = attributes;
3650 for ( ; attribute != NULL; attribute = attribute->next) {
3651 if (attribute->invalid)
3654 if (attribute->kind == GNU_AK_MODE) {
3655 type = handle_attribute_mode(attribute, type);
3656 } else if (attribute->kind == GNU_AK_ALIGNED) {
3657 int alignment = 32; /* TODO: fill in maximum useful alignment for
3659 if (attribute->has_arguments)
3660 alignment = attribute->u.argument;
3662 type_t *copy = duplicate_type(type);
3663 copy->base.alignment = attribute->u.argument;
3664 type = identify_new_type(copy);
3671 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3673 type_t *type = NULL;
3674 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3675 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3676 unsigned type_specifiers = 0;
3677 bool newtype = false;
3678 bool saw_error = false;
3679 bool old_gcc_extension = in_gcc_extension;
3681 specifiers->source_position = token.source_position;
3684 specifiers->modifiers
3685 |= parse_attributes(&specifiers->gnu_attributes);
3687 switch (token.type) {
3689 #define MATCH_STORAGE_CLASS(token, class) \
3691 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3692 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3694 specifiers->storage_class = class; \
3695 if (specifiers->thread_local) \
3696 goto check_thread_storage_class; \
3700 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3701 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3702 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3703 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3704 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3708 expect('(', end_error);
3709 add_anchor_token(')');
3710 parse_microsoft_extended_decl_modifier(specifiers);
3711 rem_anchor_token(')');
3712 expect(')', end_error);
3716 if (specifiers->thread_local) {
3717 errorf(HERE, "duplicate '__thread'");
3719 specifiers->thread_local = true;
3720 check_thread_storage_class:
3721 switch (specifiers->storage_class) {
3722 case STORAGE_CLASS_EXTERN:
3723 case STORAGE_CLASS_NONE:
3724 case STORAGE_CLASS_STATIC:
3728 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
3729 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
3730 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
3731 wrong_thread_stoarge_class:
3732 errorf(HERE, "'__thread' used with '%s'", wrong);
3739 /* type qualifiers */
3740 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3742 qualifiers |= qualifier; \
3746 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3747 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3748 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3749 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3750 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3751 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3752 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3753 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3755 case T___extension__:
3757 in_gcc_extension = true;
3760 /* type specifiers */
3761 #define MATCH_SPECIFIER(token, specifier, name) \
3763 if (type_specifiers & specifier) { \
3764 errorf(HERE, "multiple " name " type specifiers given"); \
3766 type_specifiers |= specifier; \
3771 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3772 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3773 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3774 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3775 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3776 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3777 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3778 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3779 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3780 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3781 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3782 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3783 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3784 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3785 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3786 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3787 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3788 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
3790 case T__forceinline:
3791 /* only in microsoft mode */
3792 specifiers->modifiers |= DM_FORCEINLINE;
3797 specifiers->is_inline = true;
3801 if (type_specifiers & SPECIFIER_LONG_LONG) {
3802 errorf(HERE, "multiple type specifiers given");
3803 } else if (type_specifiers & SPECIFIER_LONG) {
3804 type_specifiers |= SPECIFIER_LONG_LONG;
3806 type_specifiers |= SPECIFIER_LONG;
3812 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3814 type->compound.compound = parse_compound_type_specifier(true);
3815 finish_struct_type(&type->compound);
3819 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3820 type->compound.compound = parse_compound_type_specifier(false);
3821 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3822 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3823 finish_union_type(&type->compound);
3827 type = parse_enum_specifier();
3830 type = parse_typeof();
3832 case T___builtin_va_list:
3833 type = duplicate_type(type_valist);
3837 case T_IDENTIFIER: {
3838 /* only parse identifier if we haven't found a type yet */
3839 if (type != NULL || type_specifiers != 0) {
3840 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3841 * declaration, so it doesn't generate errors about expecting '(' or
3843 switch (look_ahead(1)->type) {
3850 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3854 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3859 goto finish_specifiers;
3863 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3864 if (typedef_type == NULL) {
3865 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3866 * declaration, so it doesn't generate 'implicit int' followed by more
3867 * errors later on. */
3868 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3874 errorf(HERE, "%K does not name a type", &token);
3877 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3879 type = allocate_type_zero(TYPE_TYPEDEF);
3880 type->typedeft.typedefe = &entity->typedefe;
3884 if (la1_type == '&' || la1_type == '*')
3885 goto finish_specifiers;
3890 goto finish_specifiers;
3895 type = typedef_type;
3899 /* function specifier */
3901 goto finish_specifiers;
3906 specifiers->modifiers
3907 |= parse_attributes(&specifiers->gnu_attributes);
3909 in_gcc_extension = old_gcc_extension;
3911 if (type == NULL || (saw_error && type_specifiers != 0)) {
3912 atomic_type_kind_t atomic_type;
3914 /* match valid basic types */
3915 switch (type_specifiers) {
3916 case SPECIFIER_VOID:
3917 atomic_type = ATOMIC_TYPE_VOID;
3919 case SPECIFIER_WCHAR_T:
3920 atomic_type = ATOMIC_TYPE_WCHAR_T;
3922 case SPECIFIER_CHAR:
3923 atomic_type = ATOMIC_TYPE_CHAR;
3925 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3926 atomic_type = ATOMIC_TYPE_SCHAR;
3928 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3929 atomic_type = ATOMIC_TYPE_UCHAR;
3931 case SPECIFIER_SHORT:
3932 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3933 case SPECIFIER_SHORT | SPECIFIER_INT:
3934 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3935 atomic_type = ATOMIC_TYPE_SHORT;
3937 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3938 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3939 atomic_type = ATOMIC_TYPE_USHORT;
3942 case SPECIFIER_SIGNED:
3943 case SPECIFIER_SIGNED | SPECIFIER_INT:
3944 atomic_type = ATOMIC_TYPE_INT;
3946 case SPECIFIER_UNSIGNED:
3947 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3948 atomic_type = ATOMIC_TYPE_UINT;
3950 case SPECIFIER_LONG:
3951 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3952 case SPECIFIER_LONG | SPECIFIER_INT:
3953 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3954 atomic_type = ATOMIC_TYPE_LONG;
3956 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3957 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3958 atomic_type = ATOMIC_TYPE_ULONG;
3961 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3962 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3963 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3964 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3966 atomic_type = ATOMIC_TYPE_LONGLONG;
3967 goto warn_about_long_long;
3969 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3970 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3972 atomic_type = ATOMIC_TYPE_ULONGLONG;
3973 warn_about_long_long:
3974 if (warning.long_long) {
3975 warningf(&specifiers->source_position,
3976 "ISO C90 does not support 'long long'");
3980 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3981 atomic_type = unsigned_int8_type_kind;
3984 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3985 atomic_type = unsigned_int16_type_kind;
3988 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3989 atomic_type = unsigned_int32_type_kind;
3992 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3993 atomic_type = unsigned_int64_type_kind;
3996 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3997 atomic_type = unsigned_int128_type_kind;
4000 case SPECIFIER_INT8:
4001 case SPECIFIER_SIGNED | SPECIFIER_INT8:
4002 atomic_type = int8_type_kind;
4005 case SPECIFIER_INT16:
4006 case SPECIFIER_SIGNED | SPECIFIER_INT16:
4007 atomic_type = int16_type_kind;
4010 case SPECIFIER_INT32:
4011 case SPECIFIER_SIGNED | SPECIFIER_INT32:
4012 atomic_type = int32_type_kind;
4015 case SPECIFIER_INT64:
4016 case SPECIFIER_SIGNED | SPECIFIER_INT64:
4017 atomic_type = int64_type_kind;
4020 case SPECIFIER_INT128:
4021 case SPECIFIER_SIGNED | SPECIFIER_INT128:
4022 atomic_type = int128_type_kind;
4025 case SPECIFIER_FLOAT:
4026 atomic_type = ATOMIC_TYPE_FLOAT;
4028 case SPECIFIER_DOUBLE:
4029 atomic_type = ATOMIC_TYPE_DOUBLE;
4031 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
4032 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
4034 case SPECIFIER_BOOL:
4035 atomic_type = ATOMIC_TYPE_BOOL;
4037 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
4038 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
4039 atomic_type = ATOMIC_TYPE_FLOAT;
4041 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
4042 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
4043 atomic_type = ATOMIC_TYPE_DOUBLE;
4045 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
4046 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
4047 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
4050 /* invalid specifier combination, give an error message */
4051 if (type_specifiers == 0) {
4055 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
4056 if (!(c_mode & _CXX) && !strict_mode) {
4057 if (warning.implicit_int) {
4058 warningf(HERE, "no type specifiers in declaration, using 'int'");
4060 atomic_type = ATOMIC_TYPE_INT;
4063 errorf(HERE, "no type specifiers given in declaration");
4065 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
4066 (type_specifiers & SPECIFIER_UNSIGNED)) {
4067 errorf(HERE, "signed and unsigned specifiers given");
4068 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
4069 errorf(HERE, "only integer types can be signed or unsigned");
4071 errorf(HERE, "multiple datatypes in declaration");
4076 if (type_specifiers & SPECIFIER_COMPLEX) {
4077 type = allocate_type_zero(TYPE_COMPLEX);
4078 type->complex.akind = atomic_type;
4079 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
4080 type = allocate_type_zero(TYPE_IMAGINARY);
4081 type->imaginary.akind = atomic_type;
4083 type = allocate_type_zero(TYPE_ATOMIC);
4084 type->atomic.akind = atomic_type;
4086 type->base.alignment = get_atomic_type_alignment(atomic_type);
4087 unsigned const size = get_atomic_type_size(atomic_type);
4089 type_specifiers & SPECIFIER_COMPLEX ? size * 2 : size;
4091 } else if (type_specifiers != 0) {
4092 errorf(HERE, "multiple datatypes in declaration");
4095 /* FIXME: check type qualifiers here */
4097 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
4098 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4099 type->base.qualifiers = qualifiers;
4100 type->base.modifiers = modifiers;
4103 type = identify_new_type(type);
4105 type = typehash_insert(type);
4108 type = handle_type_attributes(specifiers->gnu_attributes, type);
4109 specifiers->type = type;
4113 specifiers->type = type_error_type;
4117 static type_qualifiers_t parse_type_qualifiers(void)
4119 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
4122 switch (token.type) {
4123 /* type qualifiers */
4124 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
4125 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
4126 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
4127 /* microsoft extended type modifiers */
4128 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
4129 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
4130 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
4131 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
4132 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
4141 * Parses an K&R identifier list
4143 static void parse_identifier_list(scope_t *scope)
4146 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
4147 entity->base.source_position = token.source_position;
4148 entity->base.namespc = NAMESPACE_NORMAL;
4149 entity->base.symbol = token.v.symbol;
4150 /* a K&R parameter has no type, yet */
4154 append_entity(scope, entity);
4156 if (token.type != ',') {
4160 } while (token.type == T_IDENTIFIER);
4163 static entity_t *parse_parameter(void)
4165 declaration_specifiers_t specifiers;
4166 memset(&specifiers, 0, sizeof(specifiers));
4168 parse_declaration_specifiers(&specifiers);
4170 entity_t *entity = parse_declarator(&specifiers,
4171 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
4172 anonymous_entity = NULL;
4176 static void semantic_parameter_incomplete(const entity_t *entity)
4178 assert(entity->kind == ENTITY_PARAMETER);
4180 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
4181 * list in a function declarator that is part of a
4182 * definition of that function shall not have
4183 * incomplete type. */
4184 type_t *type = skip_typeref(entity->declaration.type);
4185 if (is_type_incomplete(type)) {
4186 errorf(&entity->base.source_position,
4187 "parameter '%#T' has incomplete type",
4188 entity->declaration.type, entity->base.symbol);
4192 static bool has_parameters(void)
4194 /* func(void) is not a parameter */
4195 if (token.type == T_IDENTIFIER) {
4196 entity_t const *const entity = get_entity(token.v.symbol, NAMESPACE_NORMAL);
4199 if (entity->kind != ENTITY_TYPEDEF)
4201 if (skip_typeref(entity->typedefe.type) != type_void)
4203 } else if (token.type != T_void) {
4206 if (look_ahead(1)->type != ')')
4213 * Parses function type parameters (and optionally creates variable_t entities
4214 * for them in a scope)
4216 static void parse_parameters(function_type_t *type, scope_t *scope)
4219 add_anchor_token(')');
4220 int saved_comma_state = save_and_reset_anchor_state(',');
4222 if (token.type == T_IDENTIFIER &&
4223 !is_typedef_symbol(token.v.symbol)) {
4224 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4225 if (la1_type == ',' || la1_type == ')') {
4226 type->kr_style_parameters = true;
4227 type->unspecified_parameters = true;
4228 parse_identifier_list(scope);
4229 goto parameters_finished;
4233 if (token.type == ')') {
4234 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4235 if (!(c_mode & _CXX))
4236 type->unspecified_parameters = true;
4237 goto parameters_finished;
4240 if (has_parameters()) {
4241 function_parameter_t **anchor = &type->parameters;
4243 switch (token.type) {
4246 type->variadic = true;
4247 goto parameters_finished;
4250 case T___extension__:
4253 entity_t *entity = parse_parameter();
4254 if (entity->kind == ENTITY_TYPEDEF) {
4255 errorf(&entity->base.source_position,
4256 "typedef not allowed as function parameter");
4259 assert(is_declaration(entity));
4261 semantic_parameter_incomplete(entity);
4263 function_parameter_t *const parameter =
4264 allocate_parameter(entity->declaration.type);
4266 if (scope != NULL) {
4267 append_entity(scope, entity);
4270 *anchor = parameter;
4271 anchor = ¶meter->next;
4276 goto parameters_finished;
4278 if (token.type != ',') {
4279 goto parameters_finished;
4286 parameters_finished:
4287 rem_anchor_token(')');
4288 expect(')', end_error);
4291 restore_anchor_state(',', saved_comma_state);
4294 typedef enum construct_type_kind_t {
4297 CONSTRUCT_REFERENCE,
4300 } construct_type_kind_t;
4302 typedef union construct_type_t construct_type_t;
4304 typedef struct construct_type_base_t {
4305 construct_type_kind_t kind;
4306 construct_type_t *next;
4307 } construct_type_base_t;
4309 typedef struct parsed_pointer_t {
4310 construct_type_base_t base;
4311 type_qualifiers_t type_qualifiers;
4312 variable_t *base_variable; /**< MS __based extension. */
4315 typedef struct parsed_reference_t {
4316 construct_type_base_t base;
4317 } parsed_reference_t;
4319 typedef struct construct_function_type_t {
4320 construct_type_base_t base;
4321 type_t *function_type;
4322 } construct_function_type_t;
4324 typedef struct parsed_array_t {
4325 construct_type_base_t base;
4326 type_qualifiers_t type_qualifiers;
4332 union construct_type_t {
4333 construct_type_kind_t kind;
4334 construct_type_base_t base;
4335 parsed_pointer_t pointer;
4336 parsed_reference_t reference;
4337 construct_function_type_t function;
4338 parsed_array_t array;
4341 static construct_type_t *parse_pointer_declarator(variable_t *base_variable)
4345 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->pointer));
4346 parsed_pointer_t *pointer = &cons->pointer;
4347 memset(pointer, 0, sizeof(*pointer));
4348 cons->kind = CONSTRUCT_POINTER;
4349 pointer->type_qualifiers = parse_type_qualifiers();
4350 pointer->base_variable = base_variable;
4355 static construct_type_t *parse_reference_declarator(void)
4359 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->reference));
4360 parsed_reference_t *reference = &cons->reference;
4361 memset(reference, 0, sizeof(*reference));
4362 cons->kind = CONSTRUCT_REFERENCE;
4367 static construct_type_t *parse_array_declarator(void)
4370 add_anchor_token(']');
4372 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->array));
4373 parsed_array_t *array = &cons->array;
4374 memset(array, 0, sizeof(*array));
4375 cons->kind = CONSTRUCT_ARRAY;
4377 if (token.type == T_static) {
4378 array->is_static = true;
4382 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4383 if (type_qualifiers != 0) {
4384 if (token.type == T_static) {
4385 array->is_static = true;
4389 array->type_qualifiers = type_qualifiers;
4391 if (token.type == '*' && look_ahead(1)->type == ']') {
4392 array->is_variable = true;
4394 } else if (token.type != ']') {
4395 expression_t *const size = parse_assignment_expression();
4397 /* §6.7.5.2:1 Array size must have integer type */
4398 if (!is_type_integer(size->base.type)) {
4399 errorf(&size->base.source_position,
4400 "array size '%E' must have integer type but has type '%T'",
4401 size, size->base.type);
4405 mark_vars_read(size, NULL);
4408 rem_anchor_token(']');
4409 expect(']', end_error);
4415 static construct_type_t *parse_function_declarator(scope_t *scope,
4416 decl_modifiers_t modifiers)
4418 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4419 function_type_t *ftype = &type->function;
4421 ftype->linkage = current_linkage;
4423 switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
4424 case DM_NONE: break;
4425 case DM_CDECL: ftype->calling_convention = CC_CDECL; break;
4426 case DM_STDCALL: ftype->calling_convention = CC_STDCALL; break;
4427 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
4428 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
4431 errorf(HERE, "multiple calling conventions in declaration");
4435 parse_parameters(ftype, scope);
4437 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->function));
4438 construct_function_type_t *function = &cons->function;
4439 memset(function, 0, sizeof(*function));
4440 cons->kind = CONSTRUCT_FUNCTION;
4441 function->function_type = type;
4446 typedef struct parse_declarator_env_t {
4447 decl_modifiers_t modifiers;
4449 source_position_t source_position;
4451 } parse_declarator_env_t;
4453 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4454 bool may_be_abstract)
4456 /* construct a single linked list of construct_type_t's which describe
4457 * how to construct the final declarator type */
4458 construct_type_t *first = NULL;
4459 construct_type_t **anchor = &first;
4460 gnu_attribute_t *attributes = NULL;
4462 decl_modifiers_t modifiers = parse_attributes(&attributes);
4465 construct_type_t *type;
4466 variable_t *based = NULL; /* MS __based extension */
4467 switch (token.type) {
4469 if (!(c_mode & _CXX))
4470 errorf(HERE, "references are only available for C++");
4471 type = parse_reference_declarator();
4475 source_position_t const pos = *HERE;
4477 expect('(', end_error);
4478 add_anchor_token(')');
4479 based = parse_microsoft_based();
4480 rem_anchor_token(')');
4481 expect(')', end_error);
4482 if (token.type != '*') {
4483 if (token.type == T__based) {
4484 errorf(&pos, "__based type modifier specified more than once");
4485 } else if (warning.other) {
4487 "__based does not precede a pointer declarator, ignored");
4495 type = parse_pointer_declarator(based);
4499 goto ptr_operator_end;
4503 anchor = &type->base.next;
4505 /* TODO: find out if this is correct */
4506 modifiers |= parse_attributes(&attributes);
4511 modifiers |= env->modifiers;
4512 env->modifiers = modifiers;
4515 construct_type_t *inner_types = NULL;
4517 switch (token.type) {
4520 errorf(HERE, "no identifier expected in typename");
4522 env->symbol = token.v.symbol;
4523 env->source_position = token.source_position;
4528 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
4529 * interpreted as ``function with no parameter specification'', rather
4530 * than redundant parentheses around the omitted identifier. */
4531 if (look_ahead(1)->type != ')') {
4533 add_anchor_token(')');
4534 inner_types = parse_inner_declarator(env, may_be_abstract);
4535 if (inner_types != NULL) {
4536 /* All later declarators only modify the return type */
4539 rem_anchor_token(')');
4540 expect(')', end_error);
4544 if (may_be_abstract)
4546 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4551 construct_type_t **const p = anchor;
4554 construct_type_t *type;
4555 switch (token.type) {
4557 scope_t *scope = NULL;
4559 scope = &env->parameters;
4561 type = parse_function_declarator(scope, modifiers);
4565 type = parse_array_declarator();
4568 goto declarator_finished;
4571 /* insert in the middle of the list (at p) */
4572 type->base.next = *p;
4575 anchor = &type->base.next;
4578 declarator_finished:
4579 /* append inner_types at the end of the list, we don't to set anchor anymore
4580 * as it's not needed anymore */
4581 *anchor = inner_types;
4588 static void parse_declaration_attributes(entity_t *entity)
4590 gnu_attribute_t *attributes = NULL;
4591 decl_modifiers_t modifiers = parse_attributes(&attributes);
4597 if (entity->kind == ENTITY_TYPEDEF) {
4598 modifiers |= entity->typedefe.modifiers;
4599 type = entity->typedefe.type;
4601 assert(is_declaration(entity));
4602 modifiers |= entity->declaration.modifiers;
4603 type = entity->declaration.type;
4608 gnu_attribute_t *attribute = attributes;
4609 for ( ; attribute != NULL; attribute = attribute->next) {
4610 if (attribute->invalid)
4613 if (attribute->kind == GNU_AK_MODE) {
4614 type = handle_attribute_mode(attribute, type);
4615 } else if (attribute->kind == GNU_AK_ALIGNED) {
4616 int alignment = 32; /* TODO: fill in maximum usefull alignment for target machine */
4617 if (attribute->has_arguments)
4618 alignment = attribute->u.argument;
4620 if (entity->kind == ENTITY_TYPEDEF) {
4621 type_t *copy = duplicate_type(type);
4622 copy->base.alignment = attribute->u.argument;
4623 type = identify_new_type(copy);
4624 } else if(entity->kind == ENTITY_VARIABLE) {
4625 entity->variable.alignment = alignment;
4626 } else if(entity->kind == ENTITY_COMPOUND_MEMBER) {
4627 entity->compound_member.alignment = alignment;
4632 type_modifiers_t type_modifiers = type->base.modifiers;
4633 if (modifiers & DM_TRANSPARENT_UNION)
4634 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4636 if (type->base.modifiers != type_modifiers) {
4637 type_t *copy = duplicate_type(type);
4638 copy->base.modifiers = type_modifiers;
4639 type = identify_new_type(copy);
4642 if (entity->kind == ENTITY_TYPEDEF) {
4643 entity->typedefe.type = type;
4644 entity->typedefe.modifiers = modifiers;
4646 entity->declaration.type = type;
4647 entity->declaration.modifiers = modifiers;
4651 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
4653 construct_type_t *iter = construct_list;
4654 for (; iter != NULL; iter = iter->base.next) {
4655 switch (iter->kind) {
4656 case CONSTRUCT_INVALID:
4658 case CONSTRUCT_FUNCTION: {
4659 construct_function_type_t *function = &iter->function;
4660 type_t *function_type = function->function_type;
4662 function_type->function.return_type = type;
4664 type_t *skipped_return_type = skip_typeref(type);
4666 if (is_type_function(skipped_return_type)) {
4667 errorf(HERE, "function returning function is not allowed");
4668 } else if (is_type_array(skipped_return_type)) {
4669 errorf(HERE, "function returning array is not allowed");
4671 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4673 "type qualifiers in return type of function type are meaningless");
4677 /* The function type was constructed earlier. Freeing it here will
4678 * destroy other types. */
4679 type = typehash_insert(function_type);
4683 case CONSTRUCT_POINTER: {
4684 if (is_type_reference(skip_typeref(type)))
4685 errorf(HERE, "cannot declare a pointer to reference");
4687 parsed_pointer_t *pointer = &iter->pointer;
4688 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
4692 case CONSTRUCT_REFERENCE:
4693 if (is_type_reference(skip_typeref(type)))
4694 errorf(HERE, "cannot declare a reference to reference");
4696 type = make_reference_type(type);
4699 case CONSTRUCT_ARRAY: {
4700 if (is_type_reference(skip_typeref(type)))
4701 errorf(HERE, "cannot declare an array of references");
4703 parsed_array_t *array = &iter->array;
4704 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4706 expression_t *size_expression = array->size;
4707 if (size_expression != NULL) {
4709 = create_implicit_cast(size_expression, type_size_t);
4712 array_type->base.qualifiers = array->type_qualifiers;
4713 array_type->array.element_type = type;
4714 array_type->array.is_static = array->is_static;
4715 array_type->array.is_variable = array->is_variable;
4716 array_type->array.size_expression = size_expression;
4718 if (size_expression != NULL) {
4719 if (is_constant_expression(size_expression)) {
4720 long const size = fold_constant(size_expression);
4721 array_type->array.size = size;
4722 array_type->array.size_constant = true;
4723 /* §6.7.5.2:1 If the expression is a constant expression, it shall
4724 * have a value greater than zero. */
4726 if (size < 0 || !GNU_MODE) {
4727 errorf(&size_expression->base.source_position,
4728 "size of array must be greater than zero");
4729 } else if (warning.other) {
4730 warningf(&size_expression->base.source_position,
4731 "zero length arrays are a GCC extension");
4735 array_type->array.is_vla = true;
4739 type_t *skipped_type = skip_typeref(type);
4741 if (is_type_incomplete(skipped_type)) {
4742 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4743 } else if (is_type_function(skipped_type)) {
4744 errorf(HERE, "array of functions is not allowed");
4746 type = identify_new_type(array_type);
4750 internal_errorf(HERE, "invalid type construction found");
4756 static type_t *automatic_type_conversion(type_t *orig_type);
4758 static type_t *semantic_parameter(const source_position_t *pos,
4760 const declaration_specifiers_t *specifiers,
4763 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
4764 * shall be adjusted to ``qualified pointer to type'',
4766 * §6.7.5.3:8 A declaration of a parameter as ``function returning
4767 * type'' shall be adjusted to ``pointer to function
4768 * returning type'', as in 6.3.2.1. */
4769 type = automatic_type_conversion(type);
4771 if (specifiers->is_inline && is_type_valid(type)) {
4772 errorf(pos, "parameter '%#T' declared 'inline'", type, symbol);
4775 /* §6.9.1:6 The declarations in the declaration list shall contain
4776 * no storage-class specifier other than register and no
4777 * initializations. */
4778 if (specifiers->thread_local || (
4779 specifiers->storage_class != STORAGE_CLASS_NONE &&
4780 specifiers->storage_class != STORAGE_CLASS_REGISTER)
4782 errorf(pos, "invalid storage class for parameter '%#T'", type, symbol);
4785 /* delay test for incomplete type, because we might have (void)
4786 * which is legal but incomplete... */
4791 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4792 declarator_flags_t flags)
4794 parse_declarator_env_t env;
4795 memset(&env, 0, sizeof(env));
4796 env.modifiers = specifiers->modifiers;
4798 construct_type_t *construct_type =
4799 parse_inner_declarator(&env, (flags & DECL_MAY_BE_ABSTRACT) != 0);
4801 construct_declarator_type(construct_type, specifiers->type);
4802 type_t *type = skip_typeref(orig_type);
4804 if (construct_type != NULL) {
4805 obstack_free(&temp_obst, construct_type);
4809 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4810 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4811 entity->base.symbol = env.symbol;
4812 entity->base.source_position = env.source_position;
4813 entity->typedefe.type = orig_type;
4815 if (anonymous_entity != NULL) {
4816 if (is_type_compound(type)) {
4817 assert(anonymous_entity->compound.alias == NULL);
4818 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4819 anonymous_entity->kind == ENTITY_UNION);
4820 anonymous_entity->compound.alias = entity;
4821 anonymous_entity = NULL;
4822 } else if (is_type_enum(type)) {
4823 assert(anonymous_entity->enume.alias == NULL);
4824 assert(anonymous_entity->kind == ENTITY_ENUM);
4825 anonymous_entity->enume.alias = entity;
4826 anonymous_entity = NULL;
4830 /* create a declaration type entity */
4831 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
4832 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4834 if (env.symbol != NULL) {
4835 if (specifiers->is_inline && is_type_valid(type)) {
4836 errorf(&env.source_position,
4837 "compound member '%Y' declared 'inline'", env.symbol);
4840 if (specifiers->thread_local ||
4841 specifiers->storage_class != STORAGE_CLASS_NONE) {
4842 errorf(&env.source_position,
4843 "compound member '%Y' must have no storage class",
4847 } else if (flags & DECL_IS_PARAMETER) {
4848 orig_type = semantic_parameter(&env.source_position, orig_type,
4849 specifiers, env.symbol);
4851 entity = allocate_entity_zero(ENTITY_PARAMETER);
4852 } else if (is_type_function(type)) {
4853 entity = allocate_entity_zero(ENTITY_FUNCTION);
4855 entity->function.is_inline = specifiers->is_inline;
4856 entity->function.parameters = env.parameters;
4858 if (env.symbol != NULL) {
4859 if (specifiers->thread_local || (
4860 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4861 specifiers->storage_class != STORAGE_CLASS_NONE &&
4862 specifiers->storage_class != STORAGE_CLASS_STATIC
4864 errorf(&env.source_position,
4865 "invalid storage class for function '%Y'", env.symbol);
4869 entity = allocate_entity_zero(ENTITY_VARIABLE);
4871 entity->variable.get_property_sym = specifiers->get_property_sym;
4872 entity->variable.put_property_sym = specifiers->put_property_sym;
4874 entity->variable.thread_local = specifiers->thread_local;
4876 if (env.symbol != NULL) {
4877 if (specifiers->is_inline && is_type_valid(type)) {
4878 errorf(&env.source_position,
4879 "variable '%Y' declared 'inline'", env.symbol);
4882 bool invalid_storage_class = false;
4883 if (current_scope == file_scope) {
4884 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4885 specifiers->storage_class != STORAGE_CLASS_NONE &&
4886 specifiers->storage_class != STORAGE_CLASS_STATIC) {
4887 invalid_storage_class = true;
4890 if (specifiers->thread_local &&
4891 specifiers->storage_class == STORAGE_CLASS_NONE) {
4892 invalid_storage_class = true;
4895 if (invalid_storage_class) {
4896 errorf(&env.source_position,
4897 "invalid storage class for variable '%Y'", env.symbol);
4902 if (env.symbol != NULL) {
4903 entity->base.symbol = env.symbol;
4904 entity->base.source_position = env.source_position;
4906 entity->base.source_position = specifiers->source_position;
4908 entity->base.namespc = NAMESPACE_NORMAL;
4909 entity->declaration.type = orig_type;
4910 entity->declaration.modifiers = env.modifiers;
4911 entity->declaration.deprecated_string = specifiers->deprecated_string;
4913 storage_class_t storage_class = specifiers->storage_class;
4914 entity->declaration.declared_storage_class = storage_class;
4916 if (storage_class == STORAGE_CLASS_NONE && current_scope != file_scope)
4917 storage_class = STORAGE_CLASS_AUTO;
4918 entity->declaration.storage_class = storage_class;
4921 parse_declaration_attributes(entity);
4926 static type_t *parse_abstract_declarator(type_t *base_type)
4928 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4930 type_t *result = construct_declarator_type(construct_type, base_type);
4931 if (construct_type != NULL) {
4932 obstack_free(&temp_obst, construct_type);
4939 * Check if the declaration of main is suspicious. main should be a
4940 * function with external linkage, returning int, taking either zero
4941 * arguments, two, or three arguments of appropriate types, ie.
4943 * int main([ int argc, char **argv [, char **env ] ]).
4945 * @param decl the declaration to check
4946 * @param type the function type of the declaration
4948 static void check_type_of_main(const entity_t *entity)
4950 const source_position_t *pos = &entity->base.source_position;
4951 if (entity->kind != ENTITY_FUNCTION) {
4952 warningf(pos, "'main' is not a function");
4956 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4957 warningf(pos, "'main' is normally a non-static function");
4960 type_t *type = skip_typeref(entity->declaration.type);
4961 assert(is_type_function(type));
4963 function_type_t *func_type = &type->function;
4964 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4965 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4966 func_type->return_type);
4968 const function_parameter_t *parm = func_type->parameters;
4970 type_t *const first_type = parm->type;
4971 if (!types_compatible(skip_typeref(first_type), type_int)) {
4973 "first argument of 'main' should be 'int', but is '%T'",
4978 type_t *const second_type = parm->type;
4979 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4980 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4984 type_t *const third_type = parm->type;
4985 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4986 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4990 goto warn_arg_count;
4994 warningf(pos, "'main' takes only zero, two or three arguments");
5000 * Check if a symbol is the equal to "main".
5002 static bool is_sym_main(const symbol_t *const sym)
5004 return strcmp(sym->string, "main") == 0;
5007 static void error_redefined_as_different_kind(const source_position_t *pos,
5008 const entity_t *old, entity_kind_t new_kind)
5010 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
5011 get_entity_kind_name(old->kind), old->base.symbol,
5012 get_entity_kind_name(new_kind), &old->base.source_position);
5015 static bool is_error_entity(entity_t *const ent)
5017 if (is_declaration(ent)) {
5018 return is_type_valid(skip_typeref(ent->declaration.type));
5019 } else if (ent->kind == ENTITY_TYPEDEF) {
5020 return is_type_valid(skip_typeref(ent->typedefe.type));
5026 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
5027 * for various problems that occur for multiple definitions
5029 static entity_t *record_entity(entity_t *entity, const bool is_definition)
5031 const symbol_t *const symbol = entity->base.symbol;
5032 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
5033 const source_position_t *pos = &entity->base.source_position;
5035 /* can happen in error cases */
5039 entity_t *const previous_entity = get_entity(symbol, namespc);
5040 /* pushing the same entity twice will break the stack structure */
5041 assert(previous_entity != entity);
5043 if (entity->kind == ENTITY_FUNCTION) {
5044 type_t *const orig_type = entity->declaration.type;
5045 type_t *const type = skip_typeref(orig_type);
5047 assert(is_type_function(type));
5048 if (type->function.unspecified_parameters &&
5049 warning.strict_prototypes &&
5050 previous_entity == NULL) {
5051 warningf(pos, "function declaration '%#T' is not a prototype",
5055 if (warning.main && current_scope == file_scope
5056 && is_sym_main(symbol)) {
5057 check_type_of_main(entity);
5061 if (is_declaration(entity) &&
5062 warning.nested_externs &&
5063 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
5064 current_scope != file_scope) {
5065 warningf(pos, "nested extern declaration of '%#T'",
5066 entity->declaration.type, symbol);
5069 if (previous_entity != NULL) {
5070 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
5071 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
5072 assert(previous_entity->kind == ENTITY_PARAMETER);
5074 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
5075 entity->declaration.type, symbol,
5076 previous_entity->declaration.type, symbol,
5077 &previous_entity->base.source_position);
5081 if (previous_entity->base.parent_scope == current_scope) {
5082 if (previous_entity->kind != entity->kind) {
5083 if (!is_error_entity(previous_entity) && !is_error_entity(entity)) {
5084 error_redefined_as_different_kind(pos, previous_entity,
5089 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
5090 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
5091 symbol, &previous_entity->base.source_position);
5094 if (previous_entity->kind == ENTITY_TYPEDEF) {
5095 /* TODO: C++ allows this for exactly the same type */
5096 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
5097 symbol, &previous_entity->base.source_position);
5101 /* at this point we should have only VARIABLES or FUNCTIONS */
5102 assert(is_declaration(previous_entity) && is_declaration(entity));
5104 declaration_t *const prev_decl = &previous_entity->declaration;
5105 declaration_t *const decl = &entity->declaration;
5107 /* can happen for K&R style declarations */
5108 if (prev_decl->type == NULL &&
5109 previous_entity->kind == ENTITY_PARAMETER &&
5110 entity->kind == ENTITY_PARAMETER) {
5111 prev_decl->type = decl->type;
5112 prev_decl->storage_class = decl->storage_class;
5113 prev_decl->declared_storage_class = decl->declared_storage_class;
5114 prev_decl->modifiers = decl->modifiers;
5115 prev_decl->deprecated_string = decl->deprecated_string;
5116 return previous_entity;
5119 type_t *const orig_type = decl->type;
5120 assert(orig_type != NULL);
5121 type_t *const type = skip_typeref(orig_type);
5122 type_t *const prev_type = skip_typeref(prev_decl->type);
5124 if (!types_compatible(type, prev_type)) {
5126 "declaration '%#T' is incompatible with '%#T' (declared %P)",
5127 orig_type, symbol, prev_decl->type, symbol,
5128 &previous_entity->base.source_position);
5130 unsigned old_storage_class = prev_decl->storage_class;
5131 if (warning.redundant_decls &&
5134 !(prev_decl->modifiers & DM_USED) &&
5135 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
5136 warningf(&previous_entity->base.source_position,
5137 "unnecessary static forward declaration for '%#T'",
5138 prev_decl->type, symbol);
5141 storage_class_t new_storage_class = decl->storage_class;
5143 /* pretend no storage class means extern for function
5144 * declarations (except if the previous declaration is neither
5145 * none nor extern) */
5146 if (entity->kind == ENTITY_FUNCTION) {
5147 /* the previous declaration could have unspecified parameters or
5148 * be a typedef, so use the new type */
5149 if (prev_type->function.unspecified_parameters || is_definition)
5150 prev_decl->type = type;
5152 switch (old_storage_class) {
5153 case STORAGE_CLASS_NONE:
5154 old_storage_class = STORAGE_CLASS_EXTERN;
5157 case STORAGE_CLASS_EXTERN:
5158 if (is_definition) {
5159 if (warning.missing_prototypes &&
5160 prev_type->function.unspecified_parameters &&
5161 !is_sym_main(symbol)) {
5162 warningf(pos, "no previous prototype for '%#T'",
5165 } else if (new_storage_class == STORAGE_CLASS_NONE) {
5166 new_storage_class = STORAGE_CLASS_EXTERN;
5173 } else if (is_type_incomplete(prev_type)) {
5174 prev_decl->type = type;
5177 if (old_storage_class == STORAGE_CLASS_EXTERN &&
5178 new_storage_class == STORAGE_CLASS_EXTERN) {
5179 warn_redundant_declaration:
5180 if (!is_definition &&
5181 warning.redundant_decls &&
5182 is_type_valid(prev_type) &&
5183 strcmp(previous_entity->base.source_position.input_name,
5184 "<builtin>") != 0) {
5186 "redundant declaration for '%Y' (declared %P)",
5187 symbol, &previous_entity->base.source_position);
5189 } else if (current_function == NULL) {
5190 if (old_storage_class != STORAGE_CLASS_STATIC &&
5191 new_storage_class == STORAGE_CLASS_STATIC) {
5193 "static declaration of '%Y' follows non-static declaration (declared %P)",
5194 symbol, &previous_entity->base.source_position);
5195 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
5196 prev_decl->storage_class = STORAGE_CLASS_NONE;
5197 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
5199 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
5201 goto error_redeclaration;
5202 goto warn_redundant_declaration;
5204 } else if (is_type_valid(prev_type)) {
5205 if (old_storage_class == new_storage_class) {
5206 error_redeclaration:
5207 errorf(pos, "redeclaration of '%Y' (declared %P)",
5208 symbol, &previous_entity->base.source_position);
5211 "redeclaration of '%Y' with different linkage (declared %P)",
5212 symbol, &previous_entity->base.source_position);
5217 prev_decl->modifiers |= decl->modifiers;
5218 if (entity->kind == ENTITY_FUNCTION) {
5219 previous_entity->function.is_inline |= entity->function.is_inline;
5221 return previous_entity;
5224 if (warning.shadow) {
5225 warningf(pos, "%s '%Y' shadows %s (declared %P)",
5226 get_entity_kind_name(entity->kind), symbol,
5227 get_entity_kind_name(previous_entity->kind),
5228 &previous_entity->base.source_position);
5232 if (entity->kind == ENTITY_FUNCTION) {
5233 if (is_definition &&
5234 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
5235 if (warning.missing_prototypes && !is_sym_main(symbol)) {
5236 warningf(pos, "no previous prototype for '%#T'",
5237 entity->declaration.type, symbol);
5238 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
5239 warningf(pos, "no previous declaration for '%#T'",
5240 entity->declaration.type, symbol);
5243 } else if (warning.missing_declarations &&
5244 entity->kind == ENTITY_VARIABLE &&
5245 current_scope == file_scope) {
5246 declaration_t *declaration = &entity->declaration;
5247 if (declaration->storage_class == STORAGE_CLASS_NONE) {
5248 warningf(pos, "no previous declaration for '%#T'",
5249 declaration->type, symbol);
5254 assert(entity->base.parent_scope == NULL);
5255 assert(current_scope != NULL);
5257 entity->base.parent_scope = current_scope;
5258 entity->base.namespc = NAMESPACE_NORMAL;
5259 environment_push(entity);
5260 append_entity(current_scope, entity);
5265 static void parser_error_multiple_definition(entity_t *entity,
5266 const source_position_t *source_position)
5268 errorf(source_position, "multiple definition of '%Y' (declared %P)",
5269 entity->base.symbol, &entity->base.source_position);
5272 static bool is_declaration_specifier(const token_t *token,
5273 bool only_specifiers_qualifiers)
5275 switch (token->type) {
5280 return is_typedef_symbol(token->v.symbol);
5282 case T___extension__:
5284 return !only_specifiers_qualifiers;
5291 static void parse_init_declarator_rest(entity_t *entity)
5293 assert(is_declaration(entity));
5294 declaration_t *const declaration = &entity->declaration;
5298 type_t *orig_type = declaration->type;
5299 type_t *type = skip_typeref(orig_type);
5301 if (entity->kind == ENTITY_VARIABLE
5302 && entity->variable.initializer != NULL) {
5303 parser_error_multiple_definition(entity, HERE);
5306 bool must_be_constant = false;
5307 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5308 entity->base.parent_scope == file_scope) {
5309 must_be_constant = true;
5312 if (is_type_function(type)) {
5313 errorf(&entity->base.source_position,
5314 "function '%#T' is initialized like a variable",
5315 orig_type, entity->base.symbol);
5316 orig_type = type_error_type;
5319 parse_initializer_env_t env;
5320 env.type = orig_type;
5321 env.must_be_constant = must_be_constant;
5322 env.entity = entity;
5323 current_init_decl = entity;
5325 initializer_t *initializer = parse_initializer(&env);
5326 current_init_decl = NULL;
5328 if (entity->kind == ENTITY_VARIABLE) {
5329 /* §6.7.5:22 array initializers for arrays with unknown size
5330 * determine the array type size */
5331 declaration->type = env.type;
5332 entity->variable.initializer = initializer;
5336 /* parse rest of a declaration without any declarator */
5337 static void parse_anonymous_declaration_rest(
5338 const declaration_specifiers_t *specifiers)
5341 anonymous_entity = NULL;
5343 if (warning.other) {
5344 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
5345 specifiers->thread_local) {
5346 warningf(&specifiers->source_position,
5347 "useless storage class in empty declaration");
5350 type_t *type = specifiers->type;
5351 switch (type->kind) {
5352 case TYPE_COMPOUND_STRUCT:
5353 case TYPE_COMPOUND_UNION: {
5354 if (type->compound.compound->base.symbol == NULL) {
5355 warningf(&specifiers->source_position,
5356 "unnamed struct/union that defines no instances");
5365 warningf(&specifiers->source_position, "empty declaration");
5371 static void check_variable_type_complete(entity_t *ent)
5373 if (ent->kind != ENTITY_VARIABLE)
5376 /* §6.7:7 If an identifier for an object is declared with no linkage, the
5377 * type for the object shall be complete [...] */
5378 declaration_t *decl = &ent->declaration;
5379 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
5380 decl->storage_class == STORAGE_CLASS_STATIC)
5383 type_t *const orig_type = decl->type;
5384 type_t *const type = skip_typeref(orig_type);
5385 if (!is_type_incomplete(type))
5388 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
5389 * are given length one. */
5390 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
5391 ARR_APP1(declaration_t*, incomplete_arrays, decl);
5395 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
5396 orig_type, ent->base.symbol);
5400 static void parse_declaration_rest(entity_t *ndeclaration,
5401 const declaration_specifiers_t *specifiers,
5402 parsed_declaration_func finished_declaration,
5403 declarator_flags_t flags)
5405 add_anchor_token(';');
5406 add_anchor_token(',');
5408 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5410 if (token.type == '=') {
5411 parse_init_declarator_rest(entity);
5412 } else if (entity->kind == ENTITY_VARIABLE) {
5413 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
5414 * [...] where the extern specifier is explicitly used. */
5415 declaration_t *decl = &entity->declaration;
5416 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
5417 type_t *type = decl->type;
5418 if (is_type_reference(skip_typeref(type))) {
5419 errorf(&entity->base.source_position,
5420 "reference '%#T' must be initialized",
5421 type, entity->base.symbol);
5426 check_variable_type_complete(entity);
5428 if (token.type != ',')
5432 add_anchor_token('=');
5433 ndeclaration = parse_declarator(specifiers, flags);
5434 rem_anchor_token('=');
5436 expect(';', end_error);
5439 anonymous_entity = NULL;
5440 rem_anchor_token(';');
5441 rem_anchor_token(',');
5444 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5446 symbol_t *symbol = entity->base.symbol;
5447 if (symbol == NULL) {
5448 errorf(HERE, "anonymous declaration not valid as function parameter");
5452 assert(entity->base.namespc == NAMESPACE_NORMAL);
5453 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5454 if (previous_entity == NULL
5455 || previous_entity->base.parent_scope != current_scope) {
5456 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5461 if (is_definition) {
5462 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
5465 return record_entity(entity, false);
5468 static void parse_declaration(parsed_declaration_func finished_declaration,
5469 declarator_flags_t flags)
5471 declaration_specifiers_t specifiers;
5472 memset(&specifiers, 0, sizeof(specifiers));
5474 add_anchor_token(';');
5475 parse_declaration_specifiers(&specifiers);
5476 rem_anchor_token(';');
5478 if (token.type == ';') {
5479 parse_anonymous_declaration_rest(&specifiers);
5481 entity_t *entity = parse_declarator(&specifiers, flags);
5482 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
5487 static type_t *get_default_promoted_type(type_t *orig_type)
5489 type_t *result = orig_type;
5491 type_t *type = skip_typeref(orig_type);
5492 if (is_type_integer(type)) {
5493 result = promote_integer(type);
5494 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
5495 result = type_double;
5501 static void parse_kr_declaration_list(entity_t *entity)
5503 if (entity->kind != ENTITY_FUNCTION)
5506 type_t *type = skip_typeref(entity->declaration.type);
5507 assert(is_type_function(type));
5508 if (!type->function.kr_style_parameters)
5512 add_anchor_token('{');
5514 /* push function parameters */
5515 size_t const top = environment_top();
5516 scope_t *old_scope = scope_push(&entity->function.parameters);
5518 entity_t *parameter = entity->function.parameters.entities;
5519 for ( ; parameter != NULL; parameter = parameter->base.next) {
5520 assert(parameter->base.parent_scope == NULL);
5521 parameter->base.parent_scope = current_scope;
5522 environment_push(parameter);
5525 /* parse declaration list */
5527 switch (token.type) {
5529 case T___extension__:
5530 /* This covers symbols, which are no type, too, and results in
5531 * better error messages. The typical cases are misspelled type
5532 * names and missing includes. */
5534 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
5542 /* pop function parameters */
5543 assert(current_scope == &entity->function.parameters);
5544 scope_pop(old_scope);
5545 environment_pop_to(top);
5547 /* update function type */
5548 type_t *new_type = duplicate_type(type);
5550 function_parameter_t *parameters = NULL;
5551 function_parameter_t **anchor = ¶meters;
5553 parameter = entity->function.parameters.entities;
5554 for (; parameter != NULL; parameter = parameter->base.next) {
5555 if (parameter->kind != ENTITY_PARAMETER)
5558 type_t *parameter_type = parameter->declaration.type;
5559 if (parameter_type == NULL) {
5561 errorf(HERE, "no type specified for function parameter '%Y'",
5562 parameter->base.symbol);
5563 parameter_type = type_error_type;
5565 if (warning.implicit_int) {
5566 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5567 parameter->base.symbol);
5569 parameter_type = type_int;
5571 parameter->declaration.type = parameter_type;
5574 semantic_parameter_incomplete(parameter);
5575 parameter_type = parameter->declaration.type;
5578 * we need the default promoted types for the function type
5580 parameter_type = get_default_promoted_type(parameter_type);
5582 function_parameter_t *const parameter =
5583 allocate_parameter(parameter_type);
5585 *anchor = parameter;
5586 anchor = ¶meter->next;
5589 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
5591 new_type->function.parameters = parameters;
5592 new_type->function.unspecified_parameters = true;
5594 new_type = identify_new_type(new_type);
5596 entity->declaration.type = new_type;
5598 rem_anchor_token('{');
5601 static bool first_err = true;
5604 * When called with first_err set, prints the name of the current function,
5607 static void print_in_function(void)
5611 diagnosticf("%s: In function '%Y':\n",
5612 current_function->base.base.source_position.input_name,
5613 current_function->base.base.symbol);
5618 * Check if all labels are defined in the current function.
5619 * Check if all labels are used in the current function.
5621 static void check_labels(void)
5623 for (const goto_statement_t *goto_statement = goto_first;
5624 goto_statement != NULL;
5625 goto_statement = goto_statement->next) {
5626 /* skip computed gotos */
5627 if (goto_statement->expression != NULL)
5630 label_t *label = goto_statement->label;
5633 if (label->base.source_position.input_name == NULL) {
5634 print_in_function();
5635 errorf(&goto_statement->base.source_position,
5636 "label '%Y' used but not defined", label->base.symbol);
5640 if (warning.unused_label) {
5641 for (const label_statement_t *label_statement = label_first;
5642 label_statement != NULL;
5643 label_statement = label_statement->next) {
5644 label_t *label = label_statement->label;
5646 if (! label->used) {
5647 print_in_function();
5648 warningf(&label_statement->base.source_position,
5649 "label '%Y' defined but not used", label->base.symbol);
5655 static void warn_unused_entity(entity_t *entity, entity_t *last)
5657 entity_t const *const end = last != NULL ? last->base.next : NULL;
5658 for (; entity != end; entity = entity->base.next) {
5659 if (!is_declaration(entity))
5662 declaration_t *declaration = &entity->declaration;
5663 if (declaration->implicit)
5666 if (!declaration->used) {
5667 print_in_function();
5668 const char *what = get_entity_kind_name(entity->kind);
5669 warningf(&entity->base.source_position, "%s '%Y' is unused",
5670 what, entity->base.symbol);
5671 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5672 print_in_function();
5673 const char *what = get_entity_kind_name(entity->kind);
5674 warningf(&entity->base.source_position, "%s '%Y' is never read",
5675 what, entity->base.symbol);
5680 static void check_unused_variables(statement_t *const stmt, void *const env)
5684 switch (stmt->kind) {
5685 case STATEMENT_DECLARATION: {
5686 declaration_statement_t const *const decls = &stmt->declaration;
5687 warn_unused_entity(decls->declarations_begin,
5688 decls->declarations_end);
5693 warn_unused_entity(stmt->fors.scope.entities, NULL);
5702 * Check declarations of current_function for unused entities.
5704 static void check_declarations(void)
5706 if (warning.unused_parameter) {
5707 const scope_t *scope = ¤t_function->parameters;
5709 /* do not issue unused warnings for main */
5710 if (!is_sym_main(current_function->base.base.symbol)) {
5711 warn_unused_entity(scope->entities, NULL);
5714 if (warning.unused_variable) {
5715 walk_statements(current_function->statement, check_unused_variables,
5720 static int determine_truth(expression_t const* const cond)
5723 !is_constant_expression(cond) ? 0 :
5724 fold_constant(cond) != 0 ? 1 :
5728 static void check_reachable(statement_t *);
5729 static bool reaches_end;
5731 static bool expression_returns(expression_t const *const expr)
5733 switch (expr->kind) {
5735 expression_t const *const func = expr->call.function;
5736 if (func->kind == EXPR_REFERENCE) {
5737 entity_t *entity = func->reference.entity;
5738 if (entity->kind == ENTITY_FUNCTION
5739 && entity->declaration.modifiers & DM_NORETURN)
5743 if (!expression_returns(func))
5746 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5747 if (!expression_returns(arg->expression))
5754 case EXPR_REFERENCE:
5755 case EXPR_REFERENCE_ENUM_VALUE:
5757 case EXPR_CHARACTER_CONSTANT:
5758 case EXPR_WIDE_CHARACTER_CONSTANT:
5759 case EXPR_STRING_LITERAL:
5760 case EXPR_WIDE_STRING_LITERAL:
5761 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5762 case EXPR_LABEL_ADDRESS:
5763 case EXPR_CLASSIFY_TYPE:
5764 case EXPR_SIZEOF: // TODO handle obscure VLA case
5767 case EXPR_BUILTIN_CONSTANT_P:
5768 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
5773 case EXPR_STATEMENT: {
5774 bool old_reaches_end = reaches_end;
5775 reaches_end = false;
5776 check_reachable(expr->statement.statement);
5777 bool returns = reaches_end;
5778 reaches_end = old_reaches_end;
5782 case EXPR_CONDITIONAL:
5783 // TODO handle constant expression
5785 if (!expression_returns(expr->conditional.condition))
5788 if (expr->conditional.true_expression != NULL
5789 && expression_returns(expr->conditional.true_expression))
5792 return expression_returns(expr->conditional.false_expression);
5795 return expression_returns(expr->select.compound);
5797 case EXPR_ARRAY_ACCESS:
5799 expression_returns(expr->array_access.array_ref) &&
5800 expression_returns(expr->array_access.index);
5803 return expression_returns(expr->va_starte.ap);
5806 return expression_returns(expr->va_arge.ap);
5809 return expression_returns(expr->va_copye.src);
5811 EXPR_UNARY_CASES_MANDATORY
5812 return expression_returns(expr->unary.value);
5814 case EXPR_UNARY_THROW:
5818 // TODO handle constant lhs of && and ||
5820 expression_returns(expr->binary.left) &&
5821 expression_returns(expr->binary.right);
5827 panic("unhandled expression");
5830 static bool initializer_returns(initializer_t const *const init)
5832 switch (init->kind) {
5833 case INITIALIZER_VALUE:
5834 return expression_returns(init->value.value);
5836 case INITIALIZER_LIST: {
5837 initializer_t * const* i = init->list.initializers;
5838 initializer_t * const* const end = i + init->list.len;
5839 bool returns = true;
5840 for (; i != end; ++i) {
5841 if (!initializer_returns(*i))
5847 case INITIALIZER_STRING:
5848 case INITIALIZER_WIDE_STRING:
5849 case INITIALIZER_DESIGNATOR: // designators have no payload
5852 panic("unhandled initializer");
5855 static bool noreturn_candidate;
5857 static void check_reachable(statement_t *const stmt)
5859 if (stmt->base.reachable)
5861 if (stmt->kind != STATEMENT_DO_WHILE)
5862 stmt->base.reachable = true;
5864 statement_t *last = stmt;
5866 switch (stmt->kind) {
5867 case STATEMENT_INVALID:
5868 case STATEMENT_EMPTY:
5870 next = stmt->base.next;
5873 case STATEMENT_DECLARATION: {
5874 declaration_statement_t const *const decl = &stmt->declaration;
5875 entity_t const * ent = decl->declarations_begin;
5876 entity_t const *const last = decl->declarations_end;
5878 for (;; ent = ent->base.next) {
5879 if (ent->kind == ENTITY_VARIABLE &&
5880 ent->variable.initializer != NULL &&
5881 !initializer_returns(ent->variable.initializer)) {
5888 next = stmt->base.next;
5892 case STATEMENT_COMPOUND:
5893 next = stmt->compound.statements;
5895 next = stmt->base.next;
5898 case STATEMENT_RETURN: {
5899 expression_t const *const val = stmt->returns.value;
5900 if (val == NULL || expression_returns(val))
5901 noreturn_candidate = false;
5905 case STATEMENT_IF: {
5906 if_statement_t const *const ifs = &stmt->ifs;
5907 expression_t const *const cond = ifs->condition;
5909 if (!expression_returns(cond))
5912 int const val = determine_truth(cond);
5915 check_reachable(ifs->true_statement);
5920 if (ifs->false_statement != NULL) {
5921 check_reachable(ifs->false_statement);
5925 next = stmt->base.next;
5929 case STATEMENT_SWITCH: {
5930 switch_statement_t const *const switchs = &stmt->switchs;
5931 expression_t const *const expr = switchs->expression;
5933 if (!expression_returns(expr))
5936 if (is_constant_expression(expr)) {
5937 long const val = fold_constant(expr);
5938 case_label_statement_t * defaults = NULL;
5939 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5940 if (i->expression == NULL) {
5945 if (i->first_case <= val && val <= i->last_case) {
5946 check_reachable((statement_t*)i);
5951 if (defaults != NULL) {
5952 check_reachable((statement_t*)defaults);
5956 bool has_default = false;
5957 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5958 if (i->expression == NULL)
5961 check_reachable((statement_t*)i);
5968 next = stmt->base.next;
5972 case STATEMENT_EXPRESSION: {
5973 /* Check for noreturn function call */
5974 expression_t const *const expr = stmt->expression.expression;
5975 if (!expression_returns(expr))
5978 next = stmt->base.next;
5982 case STATEMENT_CONTINUE: {
5983 statement_t *parent = stmt;
5985 parent = parent->base.parent;
5986 if (parent == NULL) /* continue not within loop */
5990 switch (parent->kind) {
5991 case STATEMENT_WHILE: goto continue_while;
5992 case STATEMENT_DO_WHILE: goto continue_do_while;
5993 case STATEMENT_FOR: goto continue_for;
6000 case STATEMENT_BREAK: {
6001 statement_t *parent = stmt;
6003 parent = parent->base.parent;
6004 if (parent == NULL) /* break not within loop/switch */
6007 switch (parent->kind) {
6008 case STATEMENT_SWITCH:
6009 case STATEMENT_WHILE:
6010 case STATEMENT_DO_WHILE:
6013 next = parent->base.next;
6014 goto found_break_parent;
6023 case STATEMENT_GOTO:
6024 if (stmt->gotos.expression) {
6025 if (!expression_returns(stmt->gotos.expression))
6028 statement_t *parent = stmt->base.parent;
6029 if (parent == NULL) /* top level goto */
6033 next = stmt->gotos.label->statement;
6034 if (next == NULL) /* missing label */
6039 case STATEMENT_LABEL:
6040 next = stmt->label.statement;
6043 case STATEMENT_CASE_LABEL:
6044 next = stmt->case_label.statement;
6047 case STATEMENT_WHILE: {
6048 while_statement_t const *const whiles = &stmt->whiles;
6049 expression_t const *const cond = whiles->condition;
6051 if (!expression_returns(cond))
6054 int const val = determine_truth(cond);
6057 check_reachable(whiles->body);
6062 next = stmt->base.next;
6066 case STATEMENT_DO_WHILE:
6067 next = stmt->do_while.body;
6070 case STATEMENT_FOR: {
6071 for_statement_t *const fors = &stmt->fors;
6073 if (fors->condition_reachable)
6075 fors->condition_reachable = true;
6077 expression_t const *const cond = fors->condition;
6082 } else if (expression_returns(cond)) {
6083 val = determine_truth(cond);
6089 check_reachable(fors->body);
6094 next = stmt->base.next;
6098 case STATEMENT_MS_TRY: {
6099 ms_try_statement_t const *const ms_try = &stmt->ms_try;
6100 check_reachable(ms_try->try_statement);
6101 next = ms_try->final_statement;
6105 case STATEMENT_LEAVE: {
6106 statement_t *parent = stmt;
6108 parent = parent->base.parent;
6109 if (parent == NULL) /* __leave not within __try */
6112 if (parent->kind == STATEMENT_MS_TRY) {
6114 next = parent->ms_try.final_statement;
6122 panic("invalid statement kind");
6125 while (next == NULL) {
6126 next = last->base.parent;
6128 noreturn_candidate = false;
6130 type_t *const type = skip_typeref(current_function->base.type);
6131 assert(is_type_function(type));
6132 type_t *const ret = skip_typeref(type->function.return_type);
6133 if (warning.return_type &&
6134 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
6135 is_type_valid(ret) &&
6136 !is_sym_main(current_function->base.base.symbol)) {
6137 warningf(&stmt->base.source_position,
6138 "control reaches end of non-void function");
6143 switch (next->kind) {
6144 case STATEMENT_INVALID:
6145 case STATEMENT_EMPTY:
6146 case STATEMENT_DECLARATION:
6147 case STATEMENT_EXPRESSION:
6149 case STATEMENT_RETURN:
6150 case STATEMENT_CONTINUE:
6151 case STATEMENT_BREAK:
6152 case STATEMENT_GOTO:
6153 case STATEMENT_LEAVE:
6154 panic("invalid control flow in function");
6156 case STATEMENT_COMPOUND:
6157 if (next->compound.stmt_expr) {
6163 case STATEMENT_SWITCH:
6164 case STATEMENT_LABEL:
6165 case STATEMENT_CASE_LABEL:
6167 next = next->base.next;
6170 case STATEMENT_WHILE: {
6172 if (next->base.reachable)
6174 next->base.reachable = true;
6176 while_statement_t const *const whiles = &next->whiles;
6177 expression_t const *const cond = whiles->condition;
6179 if (!expression_returns(cond))
6182 int const val = determine_truth(cond);
6185 check_reachable(whiles->body);
6191 next = next->base.next;
6195 case STATEMENT_DO_WHILE: {
6197 if (next->base.reachable)
6199 next->base.reachable = true;
6201 do_while_statement_t const *const dw = &next->do_while;
6202 expression_t const *const cond = dw->condition;
6204 if (!expression_returns(cond))
6207 int const val = determine_truth(cond);
6210 check_reachable(dw->body);
6216 next = next->base.next;
6220 case STATEMENT_FOR: {
6222 for_statement_t *const fors = &next->fors;
6224 fors->step_reachable = true;
6226 if (fors->condition_reachable)
6228 fors->condition_reachable = true;
6230 expression_t const *const cond = fors->condition;
6235 } else if (expression_returns(cond)) {
6236 val = determine_truth(cond);
6242 check_reachable(fors->body);
6248 next = next->base.next;
6252 case STATEMENT_MS_TRY:
6254 next = next->ms_try.final_statement;
6259 check_reachable(next);
6262 static void check_unreachable(statement_t* const stmt, void *const env)
6266 switch (stmt->kind) {
6267 case STATEMENT_DO_WHILE:
6268 if (!stmt->base.reachable) {
6269 expression_t const *const cond = stmt->do_while.condition;
6270 if (determine_truth(cond) >= 0) {
6271 warningf(&cond->base.source_position,
6272 "condition of do-while-loop is unreachable");
6277 case STATEMENT_FOR: {
6278 for_statement_t const* const fors = &stmt->fors;
6280 // if init and step are unreachable, cond is unreachable, too
6281 if (!stmt->base.reachable && !fors->step_reachable) {
6282 warningf(&stmt->base.source_position, "statement is unreachable");
6284 if (!stmt->base.reachable && fors->initialisation != NULL) {
6285 warningf(&fors->initialisation->base.source_position,
6286 "initialisation of for-statement is unreachable");
6289 if (!fors->condition_reachable && fors->condition != NULL) {
6290 warningf(&fors->condition->base.source_position,
6291 "condition of for-statement is unreachable");
6294 if (!fors->step_reachable && fors->step != NULL) {
6295 warningf(&fors->step->base.source_position,
6296 "step of for-statement is unreachable");
6302 case STATEMENT_COMPOUND:
6303 if (stmt->compound.statements != NULL)
6305 goto warn_unreachable;
6307 case STATEMENT_DECLARATION: {
6308 /* Only warn if there is at least one declarator with an initializer.
6309 * This typically occurs in switch statements. */
6310 declaration_statement_t const *const decl = &stmt->declaration;
6311 entity_t const * ent = decl->declarations_begin;
6312 entity_t const *const last = decl->declarations_end;
6314 for (;; ent = ent->base.next) {
6315 if (ent->kind == ENTITY_VARIABLE &&
6316 ent->variable.initializer != NULL) {
6317 goto warn_unreachable;
6327 if (!stmt->base.reachable)
6328 warningf(&stmt->base.source_position, "statement is unreachable");
6333 static void parse_external_declaration(void)
6335 /* function-definitions and declarations both start with declaration
6337 declaration_specifiers_t specifiers;
6338 memset(&specifiers, 0, sizeof(specifiers));
6340 add_anchor_token(';');
6341 parse_declaration_specifiers(&specifiers);
6342 rem_anchor_token(';');
6344 /* must be a declaration */
6345 if (token.type == ';') {
6346 parse_anonymous_declaration_rest(&specifiers);
6350 add_anchor_token(',');
6351 add_anchor_token('=');
6352 add_anchor_token(';');
6353 add_anchor_token('{');
6355 /* declarator is common to both function-definitions and declarations */
6356 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
6358 rem_anchor_token('{');
6359 rem_anchor_token(';');
6360 rem_anchor_token('=');
6361 rem_anchor_token(',');
6363 /* must be a declaration */
6364 switch (token.type) {
6368 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
6373 /* must be a function definition */
6374 parse_kr_declaration_list(ndeclaration);
6376 if (token.type != '{') {
6377 parse_error_expected("while parsing function definition", '{', NULL);
6378 eat_until_matching_token(';');
6382 assert(is_declaration(ndeclaration));
6383 type_t *const orig_type = ndeclaration->declaration.type;
6384 type_t * type = skip_typeref(orig_type);
6386 if (!is_type_function(type)) {
6387 if (is_type_valid(type)) {
6388 errorf(HERE, "declarator '%#T' has a body but is not a function type",
6389 type, ndeclaration->base.symbol);
6393 } else if (is_typeref(orig_type)) {
6395 errorf(&ndeclaration->base.source_position,
6396 "type of function definition '%#T' is a typedef",
6397 orig_type, ndeclaration->base.symbol);
6400 if (warning.aggregate_return &&
6401 is_type_compound(skip_typeref(type->function.return_type))) {
6402 warningf(HERE, "function '%Y' returns an aggregate",
6403 ndeclaration->base.symbol);
6405 if (warning.traditional && !type->function.unspecified_parameters) {
6406 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6407 ndeclaration->base.symbol);
6409 if (warning.old_style_definition && type->function.unspecified_parameters) {
6410 warningf(HERE, "old-style function definition '%Y'",
6411 ndeclaration->base.symbol);
6414 /* §6.7.5.3:14 a function definition with () means no
6415 * parameters (and not unspecified parameters) */
6416 if (type->function.unspecified_parameters &&
6417 type->function.parameters == NULL &&
6418 !type->function.kr_style_parameters) {
6419 type_t *copy = duplicate_type(type);
6420 copy->function.unspecified_parameters = false;
6421 type = identify_new_type(copy);
6423 ndeclaration->declaration.type = type;
6426 entity_t *const entity = record_entity(ndeclaration, true);
6427 assert(entity->kind == ENTITY_FUNCTION);
6428 assert(ndeclaration->kind == ENTITY_FUNCTION);
6430 function_t *function = &entity->function;
6431 if (ndeclaration != entity) {
6432 function->parameters = ndeclaration->function.parameters;
6434 assert(is_declaration(entity));
6435 type = skip_typeref(entity->declaration.type);
6437 /* push function parameters and switch scope */
6438 size_t const top = environment_top();
6439 scope_t *old_scope = scope_push(&function->parameters);
6441 entity_t *parameter = function->parameters.entities;
6442 for (; parameter != NULL; parameter = parameter->base.next) {
6443 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6444 parameter->base.parent_scope = current_scope;
6446 assert(parameter->base.parent_scope == NULL
6447 || parameter->base.parent_scope == current_scope);
6448 parameter->base.parent_scope = current_scope;
6449 if (parameter->base.symbol == NULL) {
6450 errorf(¶meter->base.source_position, "parameter name omitted");
6453 environment_push(parameter);
6456 if (function->statement != NULL) {
6457 parser_error_multiple_definition(entity, HERE);
6460 /* parse function body */
6461 int label_stack_top = label_top();
6462 function_t *old_current_function = current_function;
6463 current_function = function;
6464 current_parent = NULL;
6467 goto_anchor = &goto_first;
6469 label_anchor = &label_first;
6471 statement_t *const body = parse_compound_statement(false);
6472 function->statement = body;
6475 check_declarations();
6476 if (warning.return_type ||
6477 warning.unreachable_code ||
6478 (warning.missing_noreturn
6479 && !(function->base.modifiers & DM_NORETURN))) {
6480 noreturn_candidate = true;
6481 check_reachable(body);
6482 if (warning.unreachable_code)
6483 walk_statements(body, check_unreachable, NULL);
6484 if (warning.missing_noreturn &&
6485 noreturn_candidate &&
6486 !(function->base.modifiers & DM_NORETURN)) {
6487 warningf(&body->base.source_position,
6488 "function '%#T' is candidate for attribute 'noreturn'",
6489 type, entity->base.symbol);
6493 assert(current_parent == NULL);
6494 assert(current_function == function);
6495 current_function = old_current_function;
6496 label_pop_to(label_stack_top);
6499 assert(current_scope == &function->parameters);
6500 scope_pop(old_scope);
6501 environment_pop_to(top);
6504 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6505 source_position_t *source_position,
6506 const symbol_t *symbol)
6508 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6510 type->bitfield.base_type = base_type;
6511 type->bitfield.size_expression = size;
6514 type_t *skipped_type = skip_typeref(base_type);
6515 if (!is_type_integer(skipped_type)) {
6516 errorf(HERE, "bitfield base type '%T' is not an integer type",
6520 bit_size = skipped_type->base.size * 8;
6523 if (is_constant_expression(size)) {
6524 long v = fold_constant(size);
6527 errorf(source_position, "negative width in bit-field '%Y'", symbol);
6528 } else if (v == 0) {
6529 errorf(source_position, "zero width for bit-field '%Y'", symbol);
6530 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6531 errorf(source_position, "width of '%Y' exceeds its type", symbol);
6533 type->bitfield.bit_size = v;
6540 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6542 entity_t *iter = compound->members.entities;
6543 for (; iter != NULL; iter = iter->base.next) {
6544 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6547 if (iter->base.symbol == symbol) {
6549 } else if (iter->base.symbol == NULL) {
6550 type_t *type = skip_typeref(iter->declaration.type);
6551 if (is_type_compound(type)) {
6553 = find_compound_entry(type->compound.compound, symbol);
6564 static void parse_compound_declarators(compound_t *compound,
6565 const declaration_specifiers_t *specifiers)
6570 if (token.type == ':') {
6571 source_position_t source_position = *HERE;
6574 type_t *base_type = specifiers->type;
6575 expression_t *size = parse_constant_expression();
6577 type_t *type = make_bitfield_type(base_type, size,
6578 &source_position, sym_anonymous);
6580 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6581 entity->base.namespc = NAMESPACE_NORMAL;
6582 entity->base.source_position = source_position;
6583 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6584 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6585 entity->declaration.modifiers = specifiers->modifiers;
6586 entity->declaration.type = type;
6587 append_entity(&compound->members, entity);
6589 entity = parse_declarator(specifiers,
6590 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
6591 if (entity->kind == ENTITY_TYPEDEF) {
6592 errorf(&entity->base.source_position,
6593 "typedef not allowed as compound member");
6595 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6597 /* make sure we don't define a symbol multiple times */
6598 symbol_t *symbol = entity->base.symbol;
6599 if (symbol != NULL) {
6600 entity_t *prev = find_compound_entry(compound, symbol);
6602 errorf(&entity->base.source_position,
6603 "multiple declarations of symbol '%Y' (declared %P)",
6604 symbol, &prev->base.source_position);
6608 if (token.type == ':') {
6609 source_position_t source_position = *HERE;
6611 expression_t *size = parse_constant_expression();
6613 type_t *type = entity->declaration.type;
6614 type_t *bitfield_type = make_bitfield_type(type, size,
6615 &source_position, entity->base.symbol);
6616 entity->declaration.type = bitfield_type;
6618 type_t *orig_type = entity->declaration.type;
6619 type_t *type = skip_typeref(orig_type);
6620 if (is_type_function(type)) {
6621 errorf(&entity->base.source_position,
6622 "compound member '%Y' must not have function type '%T'",
6623 entity->base.symbol, orig_type);
6624 } else if (is_type_incomplete(type)) {
6625 /* §6.7.2.1:16 flexible array member */
6626 if (!is_type_array(type) ||
6627 token.type != ';' ||
6628 look_ahead(1)->type != '}') {
6629 errorf(&entity->base.source_position,
6630 "compound member '%Y' has incomplete type '%T'",
6631 entity->base.symbol, orig_type);
6636 append_entity(&compound->members, entity);
6640 if (token.type != ',')
6644 expect(';', end_error);
6647 anonymous_entity = NULL;
6650 static void parse_compound_type_entries(compound_t *compound)
6653 add_anchor_token('}');
6655 while (token.type != '}') {
6656 if (token.type == T_EOF) {
6657 errorf(HERE, "EOF while parsing struct");
6660 declaration_specifiers_t specifiers;
6661 memset(&specifiers, 0, sizeof(specifiers));
6662 parse_declaration_specifiers(&specifiers);
6664 parse_compound_declarators(compound, &specifiers);
6666 rem_anchor_token('}');
6670 compound->complete = true;
6673 static type_t *parse_typename(void)
6675 declaration_specifiers_t specifiers;
6676 memset(&specifiers, 0, sizeof(specifiers));
6677 parse_declaration_specifiers(&specifiers);
6678 if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6679 specifiers.thread_local) {
6680 /* TODO: improve error message, user does probably not know what a
6681 * storage class is...
6683 errorf(HERE, "typename may not have a storage class");
6686 type_t *result = parse_abstract_declarator(specifiers.type);
6694 typedef expression_t* (*parse_expression_function)(void);
6695 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6697 typedef struct expression_parser_function_t expression_parser_function_t;
6698 struct expression_parser_function_t {
6699 parse_expression_function parser;
6700 precedence_t infix_precedence;
6701 parse_expression_infix_function infix_parser;
6704 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6707 * Prints an error message if an expression was expected but not read
6709 static expression_t *expected_expression_error(void)
6711 /* skip the error message if the error token was read */
6712 if (token.type != T_ERROR) {
6713 errorf(HERE, "expected expression, got token %K", &token);
6717 return create_invalid_expression();
6721 * Parse a string constant.
6723 static expression_t *parse_string_const(void)
6726 if (token.type == T_STRING_LITERAL) {
6727 string_t res = token.v.string;
6729 while (token.type == T_STRING_LITERAL) {
6730 res = concat_strings(&res, &token.v.string);
6733 if (token.type != T_WIDE_STRING_LITERAL) {
6734 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6735 /* note: that we use type_char_ptr here, which is already the
6736 * automatic converted type. revert_automatic_type_conversion
6737 * will construct the array type */
6738 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6739 cnst->string.value = res;
6743 wres = concat_string_wide_string(&res, &token.v.wide_string);
6745 wres = token.v.wide_string;
6750 switch (token.type) {
6751 case T_WIDE_STRING_LITERAL:
6752 wres = concat_wide_strings(&wres, &token.v.wide_string);
6755 case T_STRING_LITERAL:
6756 wres = concat_wide_string_string(&wres, &token.v.string);
6760 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6761 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6762 cnst->wide_string.value = wres;
6771 * Parse a boolean constant.
6773 static expression_t *parse_bool_const(bool value)
6775 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6776 cnst->base.type = type_bool;
6777 cnst->conste.v.int_value = value;
6785 * Parse an integer constant.
6787 static expression_t *parse_int_const(void)
6789 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6790 cnst->base.type = token.datatype;
6791 cnst->conste.v.int_value = token.v.intvalue;
6799 * Parse a character constant.
6801 static expression_t *parse_character_constant(void)
6803 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6804 cnst->base.type = token.datatype;
6805 cnst->conste.v.character = token.v.string;
6807 if (cnst->conste.v.character.size != 1) {
6809 errorf(HERE, "more than 1 character in character constant");
6810 } else if (warning.multichar) {
6811 warningf(HERE, "multi-character character constant");
6820 * Parse a wide character constant.
6822 static expression_t *parse_wide_character_constant(void)
6824 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6825 cnst->base.type = token.datatype;
6826 cnst->conste.v.wide_character = token.v.wide_string;
6828 if (cnst->conste.v.wide_character.size != 1) {
6830 errorf(HERE, "more than 1 character in character constant");
6831 } else if (warning.multichar) {
6832 warningf(HERE, "multi-character character constant");
6841 * Parse a float constant.
6843 static expression_t *parse_float_const(void)
6845 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6846 cnst->base.type = token.datatype;
6847 cnst->conste.v.float_value = token.v.floatvalue;
6854 static entity_t *create_implicit_function(symbol_t *symbol,
6855 const source_position_t *source_position)
6857 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6858 ntype->function.return_type = type_int;
6859 ntype->function.unspecified_parameters = true;
6860 ntype->function.linkage = LINKAGE_C;
6861 type_t *type = identify_new_type(ntype);
6863 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6864 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6865 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6866 entity->declaration.type = type;
6867 entity->declaration.implicit = true;
6868 entity->base.symbol = symbol;
6869 entity->base.source_position = *source_position;
6871 bool strict_prototypes_old = warning.strict_prototypes;
6872 warning.strict_prototypes = false;
6873 record_entity(entity, false);
6874 warning.strict_prototypes = strict_prototypes_old;
6880 * Creates a return_type (func)(argument_type) function type if not
6883 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6884 type_t *argument_type2)
6886 function_parameter_t *const parameter2 = allocate_parameter(argument_type2);
6887 function_parameter_t *const parameter1 = allocate_parameter(argument_type1);
6888 parameter1->next = parameter2;
6890 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6891 type->function.return_type = return_type;
6892 type->function.parameters = parameter1;
6894 return identify_new_type(type);
6898 * Creates a return_type (func)(argument_type) function type if not
6901 * @param return_type the return type
6902 * @param argument_type the argument type
6904 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6906 function_parameter_t *const parameter = allocate_parameter(argument_type);
6908 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6909 type->function.return_type = return_type;
6910 type->function.parameters = parameter;
6912 return identify_new_type(type);
6915 static type_t *make_function_1_type_variadic(type_t *return_type, type_t *argument_type)
6917 type_t *res = make_function_1_type(return_type, argument_type);
6918 res->function.variadic = 1;
6923 * Creates a return_type (func)(void) function type if not
6926 * @param return_type the return type
6928 static type_t *make_function_0_type(type_t *return_type)
6930 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6931 type->function.return_type = return_type;
6932 type->function.parameters = NULL;
6934 return identify_new_type(type);
6938 * Creates a NO_RETURN return_type (func)(void) function type if not
6941 * @param return_type the return type
6943 static type_t *make_function_0_type_noreturn(type_t *return_type)
6945 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6946 type->function.return_type = return_type;
6947 type->function.parameters = NULL;
6948 type->function.base.modifiers |= DM_NORETURN;
6951 return identify_new_type(type);
6955 * Performs automatic type cast as described in §6.3.2.1.
6957 * @param orig_type the original type
6959 static type_t *automatic_type_conversion(type_t *orig_type)
6961 type_t *type = skip_typeref(orig_type);
6962 if (is_type_array(type)) {
6963 array_type_t *array_type = &type->array;
6964 type_t *element_type = array_type->element_type;
6965 unsigned qualifiers = array_type->base.qualifiers;
6967 return make_pointer_type(element_type, qualifiers);
6970 if (is_type_function(type)) {
6971 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6978 * reverts the automatic casts of array to pointer types and function
6979 * to function-pointer types as defined §6.3.2.1
6981 type_t *revert_automatic_type_conversion(const expression_t *expression)
6983 switch (expression->kind) {
6984 case EXPR_REFERENCE: {
6985 entity_t *entity = expression->reference.entity;
6986 if (is_declaration(entity)) {
6987 return entity->declaration.type;
6988 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6989 return entity->enum_value.enum_type;
6991 panic("no declaration or enum in reference");
6996 entity_t *entity = expression->select.compound_entry;
6997 assert(is_declaration(entity));
6998 type_t *type = entity->declaration.type;
6999 return get_qualified_type(type,
7000 expression->base.type->base.qualifiers);
7003 case EXPR_UNARY_DEREFERENCE: {
7004 const expression_t *const value = expression->unary.value;
7005 type_t *const type = skip_typeref(value->base.type);
7006 if (!is_type_pointer(type))
7007 return type_error_type;
7008 return type->pointer.points_to;
7011 case EXPR_ARRAY_ACCESS: {
7012 const expression_t *array_ref = expression->array_access.array_ref;
7013 type_t *type_left = skip_typeref(array_ref->base.type);
7014 if (!is_type_pointer(type_left))
7015 return type_error_type;
7016 return type_left->pointer.points_to;
7019 case EXPR_STRING_LITERAL: {
7020 size_t size = expression->string.value.size;
7021 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
7024 case EXPR_WIDE_STRING_LITERAL: {
7025 size_t size = expression->wide_string.value.size;
7026 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
7029 case EXPR_COMPOUND_LITERAL:
7030 return expression->compound_literal.type;
7033 return expression->base.type;
7037 static expression_t *parse_reference(void)
7039 symbol_t *const symbol = token.v.symbol;
7041 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
7043 if (entity == NULL) {
7044 if (!strict_mode && look_ahead(1)->type == '(') {
7045 /* an implicitly declared function */
7046 if (warning.error_implicit_function_declaration) {
7047 errorf(HERE, "implicit declaration of function '%Y'", symbol);
7048 } else if (warning.implicit_function_declaration) {
7049 warningf(HERE, "implicit declaration of function '%Y'", symbol);
7052 entity = create_implicit_function(symbol, HERE);
7054 errorf(HERE, "unknown identifier '%Y' found.", symbol);
7055 entity = create_error_entity(symbol, ENTITY_VARIABLE);
7061 if (is_declaration(entity)) {
7062 orig_type = entity->declaration.type;
7063 } else if (entity->kind == ENTITY_ENUM_VALUE) {
7064 orig_type = entity->enum_value.enum_type;
7066 panic("expected declaration or enum value in reference");
7069 /* we always do the auto-type conversions; the & and sizeof parser contains
7070 * code to revert this! */
7071 type_t *type = automatic_type_conversion(orig_type);
7073 expression_kind_t kind = EXPR_REFERENCE;
7074 if (entity->kind == ENTITY_ENUM_VALUE)
7075 kind = EXPR_REFERENCE_ENUM_VALUE;
7077 expression_t *expression = allocate_expression_zero(kind);
7078 expression->reference.entity = entity;
7079 expression->base.type = type;
7081 /* this declaration is used */
7082 if (is_declaration(entity)) {
7083 entity->declaration.used = true;
7086 if (entity->base.parent_scope != file_scope
7087 && entity->base.parent_scope->depth < current_function->parameters.depth
7088 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
7089 if (entity->kind == ENTITY_VARIABLE) {
7090 /* access of a variable from an outer function */
7091 entity->variable.address_taken = true;
7092 } else if (entity->kind == ENTITY_PARAMETER) {
7093 entity->parameter.address_taken = true;
7095 current_function->need_closure = true;
7098 /* check for deprecated functions */
7099 if (warning.deprecated_declarations
7100 && is_declaration(entity)
7101 && entity->declaration.modifiers & DM_DEPRECATED) {
7102 declaration_t *declaration = &entity->declaration;
7104 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
7105 "function" : "variable";
7107 if (declaration->deprecated_string != NULL) {
7108 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
7109 prefix, entity->base.symbol, &entity->base.source_position,
7110 declaration->deprecated_string);
7112 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
7113 entity->base.symbol, &entity->base.source_position);
7117 if (warning.init_self && entity == current_init_decl && !in_type_prop
7118 && entity->kind == ENTITY_VARIABLE) {
7119 current_init_decl = NULL;
7120 warningf(HERE, "variable '%#T' is initialized by itself",
7121 entity->declaration.type, entity->base.symbol);
7128 static bool semantic_cast(expression_t *cast)
7130 expression_t *expression = cast->unary.value;
7131 type_t *orig_dest_type = cast->base.type;
7132 type_t *orig_type_right = expression->base.type;
7133 type_t const *dst_type = skip_typeref(orig_dest_type);
7134 type_t const *src_type = skip_typeref(orig_type_right);
7135 source_position_t const *pos = &cast->base.source_position;
7137 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
7138 if (dst_type == type_void)
7141 /* only integer and pointer can be casted to pointer */
7142 if (is_type_pointer(dst_type) &&
7143 !is_type_pointer(src_type) &&
7144 !is_type_integer(src_type) &&
7145 is_type_valid(src_type)) {
7146 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
7150 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
7151 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
7155 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
7156 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
7160 if (warning.cast_qual &&
7161 is_type_pointer(src_type) &&
7162 is_type_pointer(dst_type)) {
7163 type_t *src = skip_typeref(src_type->pointer.points_to);
7164 type_t *dst = skip_typeref(dst_type->pointer.points_to);
7165 unsigned missing_qualifiers =
7166 src->base.qualifiers & ~dst->base.qualifiers;
7167 if (missing_qualifiers != 0) {
7169 "cast discards qualifiers '%Q' in pointer target type of '%T'",
7170 missing_qualifiers, orig_type_right);
7176 static expression_t *parse_compound_literal(type_t *type)
7178 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
7180 parse_initializer_env_t env;
7183 env.must_be_constant = false;
7184 initializer_t *initializer = parse_initializer(&env);
7187 expression->compound_literal.initializer = initializer;
7188 expression->compound_literal.type = type;
7189 expression->base.type = automatic_type_conversion(type);
7195 * Parse a cast expression.
7197 static expression_t *parse_cast(void)
7199 add_anchor_token(')');
7201 source_position_t source_position = token.source_position;
7203 type_t *type = parse_typename();
7205 rem_anchor_token(')');
7206 expect(')', end_error);
7208 if (token.type == '{') {
7209 return parse_compound_literal(type);
7212 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
7213 cast->base.source_position = source_position;
7215 expression_t *value = parse_sub_expression(PREC_CAST);
7216 cast->base.type = type;
7217 cast->unary.value = value;
7219 if (! semantic_cast(cast)) {
7220 /* TODO: record the error in the AST. else it is impossible to detect it */
7225 return create_invalid_expression();
7229 * Parse a statement expression.
7231 static expression_t *parse_statement_expression(void)
7233 add_anchor_token(')');
7235 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
7237 statement_t *statement = parse_compound_statement(true);
7238 statement->compound.stmt_expr = true;
7239 expression->statement.statement = statement;
7241 /* find last statement and use its type */
7242 type_t *type = type_void;
7243 const statement_t *stmt = statement->compound.statements;
7245 while (stmt->base.next != NULL)
7246 stmt = stmt->base.next;
7248 if (stmt->kind == STATEMENT_EXPRESSION) {
7249 type = stmt->expression.expression->base.type;
7251 } else if (warning.other) {
7252 warningf(&expression->base.source_position, "empty statement expression ({})");
7254 expression->base.type = type;
7256 rem_anchor_token(')');
7257 expect(')', end_error);
7264 * Parse a parenthesized expression.
7266 static expression_t *parse_parenthesized_expression(void)
7270 switch (token.type) {
7272 /* gcc extension: a statement expression */
7273 return parse_statement_expression();
7277 return parse_cast();
7279 if (is_typedef_symbol(token.v.symbol)) {
7280 return parse_cast();
7284 add_anchor_token(')');
7285 expression_t *result = parse_expression();
7286 result->base.parenthesized = true;
7287 rem_anchor_token(')');
7288 expect(')', end_error);
7294 static expression_t *parse_function_keyword(void)
7298 if (current_function == NULL) {
7299 errorf(HERE, "'__func__' used outside of a function");
7302 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7303 expression->base.type = type_char_ptr;
7304 expression->funcname.kind = FUNCNAME_FUNCTION;
7311 static expression_t *parse_pretty_function_keyword(void)
7313 if (current_function == NULL) {
7314 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
7317 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7318 expression->base.type = type_char_ptr;
7319 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
7321 eat(T___PRETTY_FUNCTION__);
7326 static expression_t *parse_funcsig_keyword(void)
7328 if (current_function == NULL) {
7329 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7332 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7333 expression->base.type = type_char_ptr;
7334 expression->funcname.kind = FUNCNAME_FUNCSIG;
7341 static expression_t *parse_funcdname_keyword(void)
7343 if (current_function == NULL) {
7344 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7347 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7348 expression->base.type = type_char_ptr;
7349 expression->funcname.kind = FUNCNAME_FUNCDNAME;
7351 eat(T___FUNCDNAME__);
7356 static designator_t *parse_designator(void)
7358 designator_t *result = allocate_ast_zero(sizeof(result[0]));
7359 result->source_position = *HERE;
7361 if (token.type != T_IDENTIFIER) {
7362 parse_error_expected("while parsing member designator",
7363 T_IDENTIFIER, NULL);
7366 result->symbol = token.v.symbol;
7369 designator_t *last_designator = result;
7371 if (token.type == '.') {
7373 if (token.type != T_IDENTIFIER) {
7374 parse_error_expected("while parsing member designator",
7375 T_IDENTIFIER, NULL);
7378 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7379 designator->source_position = *HERE;
7380 designator->symbol = token.v.symbol;
7383 last_designator->next = designator;
7384 last_designator = designator;
7387 if (token.type == '[') {
7389 add_anchor_token(']');
7390 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7391 designator->source_position = *HERE;
7392 designator->array_index = parse_expression();
7393 rem_anchor_token(']');
7394 expect(']', end_error);
7395 if (designator->array_index == NULL) {
7399 last_designator->next = designator;
7400 last_designator = designator;
7412 * Parse the __builtin_offsetof() expression.
7414 static expression_t *parse_offsetof(void)
7416 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7417 expression->base.type = type_size_t;
7419 eat(T___builtin_offsetof);
7421 expect('(', end_error);
7422 add_anchor_token(',');
7423 type_t *type = parse_typename();
7424 rem_anchor_token(',');
7425 expect(',', end_error);
7426 add_anchor_token(')');
7427 designator_t *designator = parse_designator();
7428 rem_anchor_token(')');
7429 expect(')', end_error);
7431 expression->offsetofe.type = type;
7432 expression->offsetofe.designator = designator;
7435 memset(&path, 0, sizeof(path));
7436 path.top_type = type;
7437 path.path = NEW_ARR_F(type_path_entry_t, 0);
7439 descend_into_subtype(&path);
7441 if (!walk_designator(&path, designator, true)) {
7442 return create_invalid_expression();
7445 DEL_ARR_F(path.path);
7449 return create_invalid_expression();
7453 * Parses a _builtin_va_start() expression.
7455 static expression_t *parse_va_start(void)
7457 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7459 eat(T___builtin_va_start);
7461 expect('(', end_error);
7462 add_anchor_token(',');
7463 expression->va_starte.ap = parse_assignment_expression();
7464 rem_anchor_token(',');
7465 expect(',', end_error);
7466 expression_t *const expr = parse_assignment_expression();
7467 if (expr->kind == EXPR_REFERENCE) {
7468 entity_t *const entity = expr->reference.entity;
7469 if (entity->base.parent_scope != ¤t_function->parameters
7470 || entity->base.next != NULL
7471 || entity->kind != ENTITY_PARAMETER) {
7472 errorf(&expr->base.source_position,
7473 "second argument of 'va_start' must be last parameter of the current function");
7475 expression->va_starte.parameter = &entity->variable;
7477 expect(')', end_error);
7480 expect(')', end_error);
7482 return create_invalid_expression();
7486 * Parses a __builtin_va_arg() expression.
7488 static expression_t *parse_va_arg(void)
7490 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7492 eat(T___builtin_va_arg);
7494 expect('(', end_error);
7496 ap.expression = parse_assignment_expression();
7497 expression->va_arge.ap = ap.expression;
7498 check_call_argument(type_valist, &ap, 1);
7500 expect(',', end_error);
7501 expression->base.type = parse_typename();
7502 expect(')', end_error);
7506 return create_invalid_expression();
7510 * Parses a __builtin_va_copy() expression.
7512 static expression_t *parse_va_copy(void)
7514 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
7516 eat(T___builtin_va_copy);
7518 expect('(', end_error);
7519 expression_t *dst = parse_assignment_expression();
7520 assign_error_t error = semantic_assign(type_valist, dst);
7521 report_assign_error(error, type_valist, dst, "call argument 1",
7522 &dst->base.source_position);
7523 expression->va_copye.dst = dst;
7525 expect(',', end_error);
7527 call_argument_t src;
7528 src.expression = parse_assignment_expression();
7529 check_call_argument(type_valist, &src, 2);
7530 expression->va_copye.src = src.expression;
7531 expect(')', end_error);
7535 return create_invalid_expression();
7539 * Parses a __builtin_constant_p() expression.
7541 static expression_t *parse_builtin_constant(void)
7543 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7545 eat(T___builtin_constant_p);
7547 expect('(', end_error);
7548 add_anchor_token(')');
7549 expression->builtin_constant.value = parse_assignment_expression();
7550 rem_anchor_token(')');
7551 expect(')', end_error);
7552 expression->base.type = type_int;
7556 return create_invalid_expression();
7560 * Parses a __builtin_types_compatible_p() expression.
7562 static expression_t *parse_builtin_types_compatible(void)
7564 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
7566 eat(T___builtin_types_compatible_p);
7568 expect('(', end_error);
7569 add_anchor_token(')');
7570 add_anchor_token(',');
7571 expression->builtin_types_compatible.left = parse_typename();
7572 rem_anchor_token(',');
7573 expect(',', end_error);
7574 expression->builtin_types_compatible.right = parse_typename();
7575 rem_anchor_token(')');
7576 expect(')', end_error);
7577 expression->base.type = type_int;
7581 return create_invalid_expression();
7585 * Parses a __builtin_is_*() compare expression.
7587 static expression_t *parse_compare_builtin(void)
7589 expression_t *expression;
7591 switch (token.type) {
7592 case T___builtin_isgreater:
7593 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7595 case T___builtin_isgreaterequal:
7596 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7598 case T___builtin_isless:
7599 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7601 case T___builtin_islessequal:
7602 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7604 case T___builtin_islessgreater:
7605 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7607 case T___builtin_isunordered:
7608 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7611 internal_errorf(HERE, "invalid compare builtin found");
7613 expression->base.source_position = *HERE;
7616 expect('(', end_error);
7617 expression->binary.left = parse_assignment_expression();
7618 expect(',', end_error);
7619 expression->binary.right = parse_assignment_expression();
7620 expect(')', end_error);
7622 type_t *const orig_type_left = expression->binary.left->base.type;
7623 type_t *const orig_type_right = expression->binary.right->base.type;
7625 type_t *const type_left = skip_typeref(orig_type_left);
7626 type_t *const type_right = skip_typeref(orig_type_right);
7627 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7628 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7629 type_error_incompatible("invalid operands in comparison",
7630 &expression->base.source_position, orig_type_left, orig_type_right);
7633 semantic_comparison(&expression->binary);
7638 return create_invalid_expression();
7643 * Parses a __builtin_expect(, end_error) expression.
7645 static expression_t *parse_builtin_expect(void, end_error)
7647 expression_t *expression
7648 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7650 eat(T___builtin_expect);
7652 expect('(', end_error);
7653 expression->binary.left = parse_assignment_expression();
7654 expect(',', end_error);
7655 expression->binary.right = parse_constant_expression();
7656 expect(')', end_error);
7658 expression->base.type = expression->binary.left->base.type;
7662 return create_invalid_expression();
7667 * Parses a MS assume() expression.
7669 static expression_t *parse_assume(void)
7671 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7675 expect('(', end_error);
7676 add_anchor_token(')');
7677 expression->unary.value = parse_assignment_expression();
7678 rem_anchor_token(')');
7679 expect(')', end_error);
7681 expression->base.type = type_void;
7684 return create_invalid_expression();
7688 * Return the declaration for a given label symbol or create a new one.
7690 * @param symbol the symbol of the label
7692 static label_t *get_label(symbol_t *symbol)
7695 assert(current_function != NULL);
7697 label = get_entity(symbol, NAMESPACE_LABEL);
7698 /* if we found a local label, we already created the declaration */
7699 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7700 if (label->base.parent_scope != current_scope) {
7701 assert(label->base.parent_scope->depth < current_scope->depth);
7702 current_function->goto_to_outer = true;
7704 return &label->label;
7707 label = get_entity(symbol, NAMESPACE_LABEL);
7708 /* if we found a label in the same function, then we already created the
7711 && label->base.parent_scope == ¤t_function->parameters) {
7712 return &label->label;
7715 /* otherwise we need to create a new one */
7716 label = allocate_entity_zero(ENTITY_LABEL);
7717 label->base.namespc = NAMESPACE_LABEL;
7718 label->base.symbol = symbol;
7722 return &label->label;
7726 * Parses a GNU && label address expression.
7728 static expression_t *parse_label_address(void)
7730 source_position_t source_position = token.source_position;
7732 if (token.type != T_IDENTIFIER) {
7733 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7736 symbol_t *symbol = token.v.symbol;
7739 label_t *label = get_label(symbol);
7741 label->address_taken = true;
7743 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7744 expression->base.source_position = source_position;
7746 /* label address is threaten as a void pointer */
7747 expression->base.type = type_void_ptr;
7748 expression->label_address.label = label;
7751 return create_invalid_expression();
7755 * Parse a microsoft __noop expression.
7757 static expression_t *parse_noop_expression(void)
7759 /* the result is a (int)0 */
7760 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7761 cnst->base.type = type_int;
7762 cnst->conste.v.int_value = 0;
7763 cnst->conste.is_ms_noop = true;
7767 if (token.type == '(') {
7768 /* parse arguments */
7770 add_anchor_token(')');
7771 add_anchor_token(',');
7773 if (token.type != ')') {
7775 (void)parse_assignment_expression();
7776 if (token.type != ',')
7782 rem_anchor_token(',');
7783 rem_anchor_token(')');
7784 expect(')', end_error);
7791 * Parses a primary expression.
7793 static expression_t *parse_primary_expression(void)
7795 switch (token.type) {
7796 case T_false: return parse_bool_const(false);
7797 case T_true: return parse_bool_const(true);
7798 case T_INTEGER: return parse_int_const();
7799 case T_CHARACTER_CONSTANT: return parse_character_constant();
7800 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7801 case T_FLOATINGPOINT: return parse_float_const();
7802 case T_STRING_LITERAL:
7803 case T_WIDE_STRING_LITERAL: return parse_string_const();
7804 case T___FUNCTION__:
7805 case T___func__: return parse_function_keyword();
7806 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7807 case T___FUNCSIG__: return parse_funcsig_keyword();
7808 case T___FUNCDNAME__: return parse_funcdname_keyword();
7809 case T___builtin_offsetof: return parse_offsetof();
7810 case T___builtin_va_start: return parse_va_start();
7811 case T___builtin_va_arg: return parse_va_arg();
7812 case T___builtin_va_copy: return parse_va_copy();
7813 case T___builtin_isgreater:
7814 case T___builtin_isgreaterequal:
7815 case T___builtin_isless:
7816 case T___builtin_islessequal:
7817 case T___builtin_islessgreater:
7818 case T___builtin_isunordered: return parse_compare_builtin();
7819 case T___builtin_constant_p: return parse_builtin_constant();
7820 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7821 case T__assume: return parse_assume();
7824 return parse_label_address();
7827 case '(': return parse_parenthesized_expression();
7828 case T___noop: return parse_noop_expression();
7830 /* Gracefully handle type names while parsing expressions. */
7832 if (!is_typedef_symbol(token.v.symbol)) {
7833 return parse_reference();
7837 source_position_t const pos = *HERE;
7838 type_t const *const type = parse_typename();
7839 errorf(&pos, "encountered type '%T' while parsing expression", type);
7840 return create_invalid_expression();
7844 errorf(HERE, "unexpected token %K, expected an expression", &token);
7845 return create_invalid_expression();
7849 * Check if the expression has the character type and issue a warning then.
7851 static void check_for_char_index_type(const expression_t *expression)
7853 type_t *const type = expression->base.type;
7854 const type_t *const base_type = skip_typeref(type);
7856 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7857 warning.char_subscripts) {
7858 warningf(&expression->base.source_position,
7859 "array subscript has type '%T'", type);
7863 static expression_t *parse_array_expression(expression_t *left)
7865 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7868 add_anchor_token(']');
7870 expression_t *inside = parse_expression();
7872 type_t *const orig_type_left = left->base.type;
7873 type_t *const orig_type_inside = inside->base.type;
7875 type_t *const type_left = skip_typeref(orig_type_left);
7876 type_t *const type_inside = skip_typeref(orig_type_inside);
7878 type_t *return_type;
7879 array_access_expression_t *array_access = &expression->array_access;
7880 if (is_type_pointer(type_left)) {
7881 return_type = type_left->pointer.points_to;
7882 array_access->array_ref = left;
7883 array_access->index = inside;
7884 check_for_char_index_type(inside);
7885 } else if (is_type_pointer(type_inside)) {
7886 return_type = type_inside->pointer.points_to;
7887 array_access->array_ref = inside;
7888 array_access->index = left;
7889 array_access->flipped = true;
7890 check_for_char_index_type(left);
7892 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7894 "array access on object with non-pointer types '%T', '%T'",
7895 orig_type_left, orig_type_inside);
7897 return_type = type_error_type;
7898 array_access->array_ref = left;
7899 array_access->index = inside;
7902 expression->base.type = automatic_type_conversion(return_type);
7904 rem_anchor_token(']');
7905 expect(']', end_error);
7910 static expression_t *parse_typeprop(expression_kind_t const kind)
7912 expression_t *tp_expression = allocate_expression_zero(kind);
7913 tp_expression->base.type = type_size_t;
7915 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7917 /* we only refer to a type property, mark this case */
7918 bool old = in_type_prop;
7919 in_type_prop = true;
7922 expression_t *expression;
7923 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7925 add_anchor_token(')');
7926 orig_type = parse_typename();
7927 rem_anchor_token(')');
7928 expect(')', end_error);
7930 if (token.type == '{') {
7931 /* It was not sizeof(type) after all. It is sizeof of an expression
7932 * starting with a compound literal */
7933 expression = parse_compound_literal(orig_type);
7934 goto typeprop_expression;
7937 expression = parse_sub_expression(PREC_UNARY);
7939 typeprop_expression:
7940 tp_expression->typeprop.tp_expression = expression;
7942 orig_type = revert_automatic_type_conversion(expression);
7943 expression->base.type = orig_type;
7946 tp_expression->typeprop.type = orig_type;
7947 type_t const* const type = skip_typeref(orig_type);
7948 char const* const wrong_type =
7949 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7950 is_type_incomplete(type) ? "incomplete" :
7951 type->kind == TYPE_FUNCTION ? "function designator" :
7952 type->kind == TYPE_BITFIELD ? "bitfield" :
7954 if (wrong_type != NULL) {
7955 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7956 errorf(&tp_expression->base.source_position,
7957 "operand of %s expression must not be of %s type '%T'",
7958 what, wrong_type, orig_type);
7963 return tp_expression;
7966 static expression_t *parse_sizeof(void)
7968 return parse_typeprop(EXPR_SIZEOF);
7971 static expression_t *parse_alignof(void)
7973 return parse_typeprop(EXPR_ALIGNOF);
7976 static expression_t *parse_select_expression(expression_t *compound)
7978 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7979 select->select.compound = compound;
7981 assert(token.type == '.' || token.type == T_MINUSGREATER);
7982 bool is_pointer = (token.type == T_MINUSGREATER);
7985 if (token.type != T_IDENTIFIER) {
7986 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7989 symbol_t *symbol = token.v.symbol;
7992 type_t *const orig_type = compound->base.type;
7993 type_t *const type = skip_typeref(orig_type);
7996 bool saw_error = false;
7997 if (is_type_pointer(type)) {
8000 "request for member '%Y' in something not a struct or union, but '%T'",
8004 type_left = skip_typeref(type->pointer.points_to);
8006 if (is_pointer && is_type_valid(type)) {
8007 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
8014 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
8015 type_left->kind == TYPE_COMPOUND_UNION) {
8016 compound_t *compound = type_left->compound.compound;
8018 if (!compound->complete) {
8019 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
8021 goto create_error_entry;
8024 entry = find_compound_entry(compound, symbol);
8025 if (entry == NULL) {
8026 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
8027 goto create_error_entry;
8030 if (is_type_valid(type_left) && !saw_error) {
8032 "request for member '%Y' in something not a struct or union, but '%T'",
8036 entry = create_error_entity(symbol, ENTITY_COMPOUND_MEMBER);
8039 assert(is_declaration(entry));
8040 select->select.compound_entry = entry;
8042 type_t *entry_type = entry->declaration.type;
8044 = get_qualified_type(entry_type, type_left->base.qualifiers);
8046 /* we always do the auto-type conversions; the & and sizeof parser contains
8047 * code to revert this! */
8048 select->base.type = automatic_type_conversion(res_type);
8050 type_t *skipped = skip_typeref(res_type);
8051 if (skipped->kind == TYPE_BITFIELD) {
8052 select->base.type = skipped->bitfield.base_type;
8058 static void check_call_argument(type_t *expected_type,
8059 call_argument_t *argument, unsigned pos)
8061 type_t *expected_type_skip = skip_typeref(expected_type);
8062 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
8063 expression_t *arg_expr = argument->expression;
8064 type_t *arg_type = skip_typeref(arg_expr->base.type);
8066 /* handle transparent union gnu extension */
8067 if (is_type_union(expected_type_skip)
8068 && (expected_type_skip->base.modifiers
8069 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
8070 compound_t *union_decl = expected_type_skip->compound.compound;
8071 type_t *best_type = NULL;
8072 entity_t *entry = union_decl->members.entities;
8073 for ( ; entry != NULL; entry = entry->base.next) {
8074 assert(is_declaration(entry));
8075 type_t *decl_type = entry->declaration.type;
8076 error = semantic_assign(decl_type, arg_expr);
8077 if (error == ASSIGN_ERROR_INCOMPATIBLE
8078 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
8081 if (error == ASSIGN_SUCCESS) {
8082 best_type = decl_type;
8083 } else if (best_type == NULL) {
8084 best_type = decl_type;
8088 if (best_type != NULL) {
8089 expected_type = best_type;
8093 error = semantic_assign(expected_type, arg_expr);
8094 argument->expression = create_implicit_cast(arg_expr, expected_type);
8096 if (error != ASSIGN_SUCCESS) {
8097 /* report exact scope in error messages (like "in argument 3") */
8099 snprintf(buf, sizeof(buf), "call argument %u", pos);
8100 report_assign_error(error, expected_type, arg_expr, buf,
8101 &arg_expr->base.source_position);
8102 } else if (warning.traditional || warning.conversion) {
8103 type_t *const promoted_type = get_default_promoted_type(arg_type);
8104 if (!types_compatible(expected_type_skip, promoted_type) &&
8105 !types_compatible(expected_type_skip, type_void_ptr) &&
8106 !types_compatible(type_void_ptr, promoted_type)) {
8107 /* Deliberately show the skipped types in this warning */
8108 warningf(&arg_expr->base.source_position,
8109 "passing call argument %u as '%T' rather than '%T' due to prototype",
8110 pos, expected_type_skip, promoted_type);
8116 * Handle the semantic restrictions of builtin calls
8118 static void handle_builtin_argument_restrictions(call_expression_t *call) {
8119 switch (call->function->reference.entity->function.btk) {
8120 case bk_gnu_builtin_return_address:
8121 case bk_gnu_builtin_frame_address: {
8122 /* argument must be constant */
8123 call_argument_t *argument = call->arguments;
8125 if (! is_constant_expression(argument->expression)) {
8126 errorf(&call->base.source_position,
8127 "argument of '%Y' must be a constant expression",
8128 call->function->reference.entity->base.symbol);
8132 case bk_gnu_builtin_prefetch: {
8133 /* second and third argument must be constant if existent */
8134 call_argument_t *rw = call->arguments->next;
8135 call_argument_t *locality = NULL;
8138 if (! is_constant_expression(rw->expression)) {
8139 errorf(&call->base.source_position,
8140 "second argument of '%Y' must be a constant expression",
8141 call->function->reference.entity->base.symbol);
8143 locality = rw->next;
8145 if (locality != NULL) {
8146 if (! is_constant_expression(locality->expression)) {
8147 errorf(&call->base.source_position,
8148 "third argument of '%Y' must be a constant expression",
8149 call->function->reference.entity->base.symbol);
8151 locality = rw->next;
8161 * Parse a call expression, ie. expression '( ... )'.
8163 * @param expression the function address
8165 static expression_t *parse_call_expression(expression_t *expression)
8167 expression_t *result = allocate_expression_zero(EXPR_CALL);
8168 call_expression_t *call = &result->call;
8169 call->function = expression;
8171 type_t *const orig_type = expression->base.type;
8172 type_t *const type = skip_typeref(orig_type);
8174 function_type_t *function_type = NULL;
8175 if (is_type_pointer(type)) {
8176 type_t *const to_type = skip_typeref(type->pointer.points_to);
8178 if (is_type_function(to_type)) {
8179 function_type = &to_type->function;
8180 call->base.type = function_type->return_type;
8184 if (function_type == NULL && is_type_valid(type)) {
8185 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
8188 /* parse arguments */
8190 add_anchor_token(')');
8191 add_anchor_token(',');
8193 if (token.type != ')') {
8194 call_argument_t **anchor = &call->arguments;
8196 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
8197 argument->expression = parse_assignment_expression();
8200 anchor = &argument->next;
8202 if (token.type != ',')
8207 rem_anchor_token(',');
8208 rem_anchor_token(')');
8209 expect(')', end_error);
8211 if (function_type == NULL)
8214 function_parameter_t *parameter = function_type->parameters;
8215 call_argument_t *argument = call->arguments;
8216 if (!function_type->unspecified_parameters) {
8217 for (unsigned pos = 0; parameter != NULL && argument != NULL;
8218 parameter = parameter->next, argument = argument->next) {
8219 check_call_argument(parameter->type, argument, ++pos);
8222 if (parameter != NULL) {
8223 errorf(HERE, "too few arguments to function '%E'", expression);
8224 } else if (argument != NULL && !function_type->variadic) {
8225 errorf(HERE, "too many arguments to function '%E'", expression);
8229 /* do default promotion */
8230 for (; argument != NULL; argument = argument->next) {
8231 type_t *type = argument->expression->base.type;
8233 type = get_default_promoted_type(type);
8235 argument->expression
8236 = create_implicit_cast(argument->expression, type);
8239 check_format(&result->call);
8241 if (warning.aggregate_return &&
8242 is_type_compound(skip_typeref(function_type->return_type))) {
8243 warningf(&result->base.source_position,
8244 "function call has aggregate value");
8247 if (call->function->kind == EXPR_REFERENCE) {
8248 reference_expression_t *reference = &call->function->reference;
8249 if (reference->entity->kind == ENTITY_FUNCTION &&
8250 reference->entity->function.btk != bk_none)
8251 handle_builtin_argument_restrictions(call);
8258 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
8260 static bool same_compound_type(const type_t *type1, const type_t *type2)
8263 is_type_compound(type1) &&
8264 type1->kind == type2->kind &&
8265 type1->compound.compound == type2->compound.compound;
8268 static expression_t const *get_reference_address(expression_t const *expr)
8270 bool regular_take_address = true;
8272 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8273 expr = expr->unary.value;
8275 regular_take_address = false;
8278 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8281 expr = expr->unary.value;
8284 if (expr->kind != EXPR_REFERENCE)
8287 /* special case for functions which are automatically converted to a
8288 * pointer to function without an extra TAKE_ADDRESS operation */
8289 if (!regular_take_address &&
8290 expr->reference.entity->kind != ENTITY_FUNCTION) {
8297 static void warn_reference_address_as_bool(expression_t const* expr)
8299 if (!warning.address)
8302 expr = get_reference_address(expr);
8304 warningf(&expr->base.source_position,
8305 "the address of '%Y' will always evaluate as 'true'",
8306 expr->reference.entity->base.symbol);
8310 static void warn_assignment_in_condition(const expression_t *const expr)
8312 if (!warning.parentheses)
8314 if (expr->base.kind != EXPR_BINARY_ASSIGN)
8316 if (expr->base.parenthesized)
8318 warningf(&expr->base.source_position,
8319 "suggest parentheses around assignment used as truth value");
8322 static void semantic_condition(expression_t const *const expr,
8323 char const *const context)
8325 type_t *const type = skip_typeref(expr->base.type);
8326 if (is_type_scalar(type)) {
8327 warn_reference_address_as_bool(expr);
8328 warn_assignment_in_condition(expr);
8329 } else if (is_type_valid(type)) {
8330 errorf(&expr->base.source_position,
8331 "%s must have scalar type", context);
8336 * Parse a conditional expression, ie. 'expression ? ... : ...'.
8338 * @param expression the conditional expression
8340 static expression_t *parse_conditional_expression(expression_t *expression)
8342 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
8344 conditional_expression_t *conditional = &result->conditional;
8345 conditional->condition = expression;
8348 add_anchor_token(':');
8350 /* §6.5.15:2 The first operand shall have scalar type. */
8351 semantic_condition(expression, "condition of conditional operator");
8353 expression_t *true_expression = expression;
8354 bool gnu_cond = false;
8355 if (GNU_MODE && token.type == ':') {
8358 true_expression = parse_expression();
8360 rem_anchor_token(':');
8361 expect(':', end_error);
8363 expression_t *false_expression =
8364 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
8366 type_t *const orig_true_type = true_expression->base.type;
8367 type_t *const orig_false_type = false_expression->base.type;
8368 type_t *const true_type = skip_typeref(orig_true_type);
8369 type_t *const false_type = skip_typeref(orig_false_type);
8372 type_t *result_type;
8373 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8374 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
8375 /* ISO/IEC 14882:1998(E) §5.16:2 */
8376 if (true_expression->kind == EXPR_UNARY_THROW) {
8377 result_type = false_type;
8378 } else if (false_expression->kind == EXPR_UNARY_THROW) {
8379 result_type = true_type;
8381 if (warning.other && (
8382 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8383 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
8385 warningf(&conditional->base.source_position,
8386 "ISO C forbids conditional expression with only one void side");
8388 result_type = type_void;
8390 } else if (is_type_arithmetic(true_type)
8391 && is_type_arithmetic(false_type)) {
8392 result_type = semantic_arithmetic(true_type, false_type);
8394 true_expression = create_implicit_cast(true_expression, result_type);
8395 false_expression = create_implicit_cast(false_expression, result_type);
8397 conditional->true_expression = true_expression;
8398 conditional->false_expression = false_expression;
8399 conditional->base.type = result_type;
8400 } else if (same_compound_type(true_type, false_type)) {
8401 /* just take 1 of the 2 types */
8402 result_type = true_type;
8403 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
8404 type_t *pointer_type;
8406 expression_t *other_expression;
8407 if (is_type_pointer(true_type) &&
8408 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
8409 pointer_type = true_type;
8410 other_type = false_type;
8411 other_expression = false_expression;
8413 pointer_type = false_type;
8414 other_type = true_type;
8415 other_expression = true_expression;
8418 if (is_null_pointer_constant(other_expression)) {
8419 result_type = pointer_type;
8420 } else if (is_type_pointer(other_type)) {
8421 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8422 type_t *to2 = skip_typeref(other_type->pointer.points_to);
8425 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8426 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8428 } else if (types_compatible(get_unqualified_type(to1),
8429 get_unqualified_type(to2))) {
8432 if (warning.other) {
8433 warningf(&conditional->base.source_position,
8434 "pointer types '%T' and '%T' in conditional expression are incompatible",
8435 true_type, false_type);
8440 type_t *const type =
8441 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8442 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8443 } else if (is_type_integer(other_type)) {
8444 if (warning.other) {
8445 warningf(&conditional->base.source_position,
8446 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8448 result_type = pointer_type;
8450 if (is_type_valid(other_type)) {
8451 type_error_incompatible("while parsing conditional",
8452 &expression->base.source_position, true_type, false_type);
8454 result_type = type_error_type;
8457 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8458 type_error_incompatible("while parsing conditional",
8459 &conditional->base.source_position, true_type,
8462 result_type = type_error_type;
8465 conditional->true_expression
8466 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8467 conditional->false_expression
8468 = create_implicit_cast(false_expression, result_type);
8469 conditional->base.type = result_type;
8474 * Parse an extension expression.
8476 static expression_t *parse_extension(void)
8478 eat(T___extension__);
8480 bool old_gcc_extension = in_gcc_extension;
8481 in_gcc_extension = true;
8482 expression_t *expression = parse_sub_expression(PREC_UNARY);
8483 in_gcc_extension = old_gcc_extension;
8488 * Parse a __builtin_classify_type() expression.
8490 static expression_t *parse_builtin_classify_type(void)
8492 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8493 result->base.type = type_int;
8495 eat(T___builtin_classify_type);
8497 expect('(', end_error);
8498 add_anchor_token(')');
8499 expression_t *expression = parse_expression();
8500 rem_anchor_token(')');
8501 expect(')', end_error);
8502 result->classify_type.type_expression = expression;
8506 return create_invalid_expression();
8510 * Parse a delete expression
8511 * ISO/IEC 14882:1998(E) §5.3.5
8513 static expression_t *parse_delete(void)
8515 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8516 result->base.type = type_void;
8520 if (token.type == '[') {
8522 result->kind = EXPR_UNARY_DELETE_ARRAY;
8523 expect(']', end_error);
8527 expression_t *const value = parse_sub_expression(PREC_CAST);
8528 result->unary.value = value;
8530 type_t *const type = skip_typeref(value->base.type);
8531 if (!is_type_pointer(type)) {
8532 if (is_type_valid(type)) {
8533 errorf(&value->base.source_position,
8534 "operand of delete must have pointer type");
8536 } else if (warning.other &&
8537 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8538 warningf(&value->base.source_position,
8539 "deleting 'void*' is undefined");
8546 * Parse a throw expression
8547 * ISO/IEC 14882:1998(E) §15:1
8549 static expression_t *parse_throw(void)
8551 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8552 result->base.type = type_void;
8556 expression_t *value = NULL;
8557 switch (token.type) {
8559 value = parse_assignment_expression();
8560 /* ISO/IEC 14882:1998(E) §15.1:3 */
8561 type_t *const orig_type = value->base.type;
8562 type_t *const type = skip_typeref(orig_type);
8563 if (is_type_incomplete(type)) {
8564 errorf(&value->base.source_position,
8565 "cannot throw object of incomplete type '%T'", orig_type);
8566 } else if (is_type_pointer(type)) {
8567 type_t *const points_to = skip_typeref(type->pointer.points_to);
8568 if (is_type_incomplete(points_to) &&
8569 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8570 errorf(&value->base.source_position,
8571 "cannot throw pointer to incomplete type '%T'", orig_type);
8579 result->unary.value = value;
8584 static bool check_pointer_arithmetic(const source_position_t *source_position,
8585 type_t *pointer_type,
8586 type_t *orig_pointer_type)
8588 type_t *points_to = pointer_type->pointer.points_to;
8589 points_to = skip_typeref(points_to);
8591 if (is_type_incomplete(points_to)) {
8592 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8593 errorf(source_position,
8594 "arithmetic with pointer to incomplete type '%T' not allowed",
8597 } else if (warning.pointer_arith) {
8598 warningf(source_position,
8599 "pointer of type '%T' used in arithmetic",
8602 } else if (is_type_function(points_to)) {
8604 errorf(source_position,
8605 "arithmetic with pointer to function type '%T' not allowed",
8608 } else if (warning.pointer_arith) {
8609 warningf(source_position,
8610 "pointer to a function '%T' used in arithmetic",
8617 static bool is_lvalue(const expression_t *expression)
8619 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
8620 switch (expression->kind) {
8621 case EXPR_ARRAY_ACCESS:
8622 case EXPR_COMPOUND_LITERAL:
8623 case EXPR_REFERENCE:
8625 case EXPR_UNARY_DEREFERENCE:
8629 type_t *type = skip_typeref(expression->base.type);
8631 /* ISO/IEC 14882:1998(E) §3.10:3 */
8632 is_type_reference(type) ||
8633 /* Claim it is an lvalue, if the type is invalid. There was a parse
8634 * error before, which maybe prevented properly recognizing it as
8636 !is_type_valid(type);
8641 static void semantic_incdec(unary_expression_t *expression)
8643 type_t *const orig_type = expression->value->base.type;
8644 type_t *const type = skip_typeref(orig_type);
8645 if (is_type_pointer(type)) {
8646 if (!check_pointer_arithmetic(&expression->base.source_position,
8650 } else if (!is_type_real(type) && is_type_valid(type)) {
8651 /* TODO: improve error message */
8652 errorf(&expression->base.source_position,
8653 "operation needs an arithmetic or pointer type");
8656 if (!is_lvalue(expression->value)) {
8657 /* TODO: improve error message */
8658 errorf(&expression->base.source_position, "lvalue required as operand");
8660 expression->base.type = orig_type;
8663 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8665 type_t *const orig_type = expression->value->base.type;
8666 type_t *const type = skip_typeref(orig_type);
8667 if (!is_type_arithmetic(type)) {
8668 if (is_type_valid(type)) {
8669 /* TODO: improve error message */
8670 errorf(&expression->base.source_position,
8671 "operation needs an arithmetic type");
8676 expression->base.type = orig_type;
8679 static void semantic_unexpr_plus(unary_expression_t *expression)
8681 semantic_unexpr_arithmetic(expression);
8682 if (warning.traditional)
8683 warningf(&expression->base.source_position,
8684 "traditional C rejects the unary plus operator");
8687 static void semantic_not(unary_expression_t *expression)
8689 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8690 semantic_condition(expression->value, "operand of !");
8691 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8694 static void semantic_unexpr_integer(unary_expression_t *expression)
8696 type_t *const orig_type = expression->value->base.type;
8697 type_t *const type = skip_typeref(orig_type);
8698 if (!is_type_integer(type)) {
8699 if (is_type_valid(type)) {
8700 errorf(&expression->base.source_position,
8701 "operand of ~ must be of integer type");
8706 expression->base.type = orig_type;
8709 static void semantic_dereference(unary_expression_t *expression)
8711 type_t *const orig_type = expression->value->base.type;
8712 type_t *const type = skip_typeref(orig_type);
8713 if (!is_type_pointer(type)) {
8714 if (is_type_valid(type)) {
8715 errorf(&expression->base.source_position,
8716 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8721 type_t *result_type = type->pointer.points_to;
8722 result_type = automatic_type_conversion(result_type);
8723 expression->base.type = result_type;
8727 * Record that an address is taken (expression represents an lvalue).
8729 * @param expression the expression
8730 * @param may_be_register if true, the expression might be an register
8732 static void set_address_taken(expression_t *expression, bool may_be_register)
8734 if (expression->kind != EXPR_REFERENCE)
8737 entity_t *const entity = expression->reference.entity;
8739 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8742 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8743 && !may_be_register) {
8744 errorf(&expression->base.source_position,
8745 "address of register %s '%Y' requested",
8746 get_entity_kind_name(entity->kind), entity->base.symbol);
8749 if (entity->kind == ENTITY_VARIABLE) {
8750 entity->variable.address_taken = true;
8752 assert(entity->kind == ENTITY_PARAMETER);
8753 entity->parameter.address_taken = true;
8758 * Check the semantic of the address taken expression.
8760 static void semantic_take_addr(unary_expression_t *expression)
8762 expression_t *value = expression->value;
8763 value->base.type = revert_automatic_type_conversion(value);
8765 type_t *orig_type = value->base.type;
8766 type_t *type = skip_typeref(orig_type);
8767 if (!is_type_valid(type))
8771 if (!is_lvalue(value)) {
8772 errorf(&expression->base.source_position, "'&' requires an lvalue");
8774 if (type->kind == TYPE_BITFIELD) {
8775 errorf(&expression->base.source_position,
8776 "'&' not allowed on object with bitfield type '%T'",
8780 set_address_taken(value, false);
8782 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8785 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8786 static expression_t *parse_##unexpression_type(void) \
8788 expression_t *unary_expression \
8789 = allocate_expression_zero(unexpression_type); \
8791 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8793 sfunc(&unary_expression->unary); \
8795 return unary_expression; \
8798 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8799 semantic_unexpr_arithmetic)
8800 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8801 semantic_unexpr_plus)
8802 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8804 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8805 semantic_dereference)
8806 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8808 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8809 semantic_unexpr_integer)
8810 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8812 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8815 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8817 static expression_t *parse_##unexpression_type(expression_t *left) \
8819 expression_t *unary_expression \
8820 = allocate_expression_zero(unexpression_type); \
8822 unary_expression->unary.value = left; \
8824 sfunc(&unary_expression->unary); \
8826 return unary_expression; \
8829 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8830 EXPR_UNARY_POSTFIX_INCREMENT,
8832 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8833 EXPR_UNARY_POSTFIX_DECREMENT,
8836 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8838 /* TODO: handle complex + imaginary types */
8840 type_left = get_unqualified_type(type_left);
8841 type_right = get_unqualified_type(type_right);
8843 /* §6.3.1.8 Usual arithmetic conversions */
8844 if (type_left == type_long_double || type_right == type_long_double) {
8845 return type_long_double;
8846 } else if (type_left == type_double || type_right == type_double) {
8848 } else if (type_left == type_float || type_right == type_float) {
8852 type_left = promote_integer(type_left);
8853 type_right = promote_integer(type_right);
8855 if (type_left == type_right)
8858 bool const signed_left = is_type_signed(type_left);
8859 bool const signed_right = is_type_signed(type_right);
8860 int const rank_left = get_rank(type_left);
8861 int const rank_right = get_rank(type_right);
8863 if (signed_left == signed_right)
8864 return rank_left >= rank_right ? type_left : type_right;
8873 u_rank = rank_right;
8874 u_type = type_right;
8876 s_rank = rank_right;
8877 s_type = type_right;
8882 if (u_rank >= s_rank)
8885 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8887 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8888 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8892 case ATOMIC_TYPE_INT: return type_unsigned_int;
8893 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8894 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8896 default: panic("invalid atomic type");
8901 * Check the semantic restrictions for a binary expression.
8903 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8905 expression_t *const left = expression->left;
8906 expression_t *const right = expression->right;
8907 type_t *const orig_type_left = left->base.type;
8908 type_t *const orig_type_right = right->base.type;
8909 type_t *const type_left = skip_typeref(orig_type_left);
8910 type_t *const type_right = skip_typeref(orig_type_right);
8912 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8913 /* TODO: improve error message */
8914 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8915 errorf(&expression->base.source_position,
8916 "operation needs arithmetic types");
8921 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8922 expression->left = create_implicit_cast(left, arithmetic_type);
8923 expression->right = create_implicit_cast(right, arithmetic_type);
8924 expression->base.type = arithmetic_type;
8927 static void warn_div_by_zero(binary_expression_t const *const expression)
8929 if (!warning.div_by_zero ||
8930 !is_type_integer(expression->base.type))
8933 expression_t const *const right = expression->right;
8934 /* The type of the right operand can be different for /= */
8935 if (is_type_integer(right->base.type) &&
8936 is_constant_expression(right) &&
8937 fold_constant(right) == 0) {
8938 warningf(&expression->base.source_position, "division by zero");
8943 * Check the semantic restrictions for a div/mod expression.
8945 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8947 semantic_binexpr_arithmetic(expression);
8948 warn_div_by_zero(expression);
8951 static void warn_addsub_in_shift(const expression_t *const expr)
8953 if (expr->base.parenthesized)
8957 switch (expr->kind) {
8958 case EXPR_BINARY_ADD: op = '+'; break;
8959 case EXPR_BINARY_SUB: op = '-'; break;
8963 warningf(&expr->base.source_position,
8964 "suggest parentheses around '%c' inside shift", op);
8967 static void semantic_shift_op(binary_expression_t *expression)
8969 expression_t *const left = expression->left;
8970 expression_t *const right = expression->right;
8971 type_t *const orig_type_left = left->base.type;
8972 type_t *const orig_type_right = right->base.type;
8973 type_t * type_left = skip_typeref(orig_type_left);
8974 type_t * type_right = skip_typeref(orig_type_right);
8976 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8977 /* TODO: improve error message */
8978 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8979 errorf(&expression->base.source_position,
8980 "operands of shift operation must have integer types");
8985 if (warning.parentheses) {
8986 warn_addsub_in_shift(left);
8987 warn_addsub_in_shift(right);
8990 type_left = promote_integer(type_left);
8991 type_right = promote_integer(type_right);
8993 expression->left = create_implicit_cast(left, type_left);
8994 expression->right = create_implicit_cast(right, type_right);
8995 expression->base.type = type_left;
8998 static void semantic_add(binary_expression_t *expression)
9000 expression_t *const left = expression->left;
9001 expression_t *const right = expression->right;
9002 type_t *const orig_type_left = left->base.type;
9003 type_t *const orig_type_right = right->base.type;
9004 type_t *const type_left = skip_typeref(orig_type_left);
9005 type_t *const type_right = skip_typeref(orig_type_right);
9008 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9009 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9010 expression->left = create_implicit_cast(left, arithmetic_type);
9011 expression->right = create_implicit_cast(right, arithmetic_type);
9012 expression->base.type = arithmetic_type;
9013 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9014 check_pointer_arithmetic(&expression->base.source_position,
9015 type_left, orig_type_left);
9016 expression->base.type = type_left;
9017 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
9018 check_pointer_arithmetic(&expression->base.source_position,
9019 type_right, orig_type_right);
9020 expression->base.type = type_right;
9021 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9022 errorf(&expression->base.source_position,
9023 "invalid operands to binary + ('%T', '%T')",
9024 orig_type_left, orig_type_right);
9028 static void semantic_sub(binary_expression_t *expression)
9030 expression_t *const left = expression->left;
9031 expression_t *const right = expression->right;
9032 type_t *const orig_type_left = left->base.type;
9033 type_t *const orig_type_right = right->base.type;
9034 type_t *const type_left = skip_typeref(orig_type_left);
9035 type_t *const type_right = skip_typeref(orig_type_right);
9036 source_position_t const *const pos = &expression->base.source_position;
9039 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9040 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9041 expression->left = create_implicit_cast(left, arithmetic_type);
9042 expression->right = create_implicit_cast(right, arithmetic_type);
9043 expression->base.type = arithmetic_type;
9044 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9045 check_pointer_arithmetic(&expression->base.source_position,
9046 type_left, orig_type_left);
9047 expression->base.type = type_left;
9048 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
9049 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
9050 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
9051 if (!types_compatible(unqual_left, unqual_right)) {
9053 "subtracting pointers to incompatible types '%T' and '%T'",
9054 orig_type_left, orig_type_right);
9055 } else if (!is_type_object(unqual_left)) {
9056 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
9057 errorf(pos, "subtracting pointers to non-object types '%T'",
9059 } else if (warning.other) {
9060 warningf(pos, "subtracting pointers to void");
9063 expression->base.type = type_ptrdiff_t;
9064 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9065 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
9066 orig_type_left, orig_type_right);
9070 static void warn_string_literal_address(expression_t const* expr)
9072 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
9073 expr = expr->unary.value;
9074 if (expr->kind != EXPR_UNARY_DEREFERENCE)
9076 expr = expr->unary.value;
9079 if (expr->kind == EXPR_STRING_LITERAL ||
9080 expr->kind == EXPR_WIDE_STRING_LITERAL) {
9081 warningf(&expr->base.source_position,
9082 "comparison with string literal results in unspecified behaviour");
9086 static void warn_comparison_in_comparison(const expression_t *const expr)
9088 if (expr->base.parenthesized)
9090 switch (expr->base.kind) {
9091 case EXPR_BINARY_LESS:
9092 case EXPR_BINARY_GREATER:
9093 case EXPR_BINARY_LESSEQUAL:
9094 case EXPR_BINARY_GREATEREQUAL:
9095 case EXPR_BINARY_NOTEQUAL:
9096 case EXPR_BINARY_EQUAL:
9097 warningf(&expr->base.source_position,
9098 "comparisons like 'x <= y < z' do not have their mathematical meaning");
9105 static bool maybe_negative(expression_t const *const expr)
9108 !is_constant_expression(expr) ||
9109 fold_constant(expr) < 0;
9113 * Check the semantics of comparison expressions.
9115 * @param expression The expression to check.
9117 static void semantic_comparison(binary_expression_t *expression)
9119 expression_t *left = expression->left;
9120 expression_t *right = expression->right;
9122 if (warning.address) {
9123 warn_string_literal_address(left);
9124 warn_string_literal_address(right);
9126 expression_t const* const func_left = get_reference_address(left);
9127 if (func_left != NULL && is_null_pointer_constant(right)) {
9128 warningf(&expression->base.source_position,
9129 "the address of '%Y' will never be NULL",
9130 func_left->reference.entity->base.symbol);
9133 expression_t const* const func_right = get_reference_address(right);
9134 if (func_right != NULL && is_null_pointer_constant(right)) {
9135 warningf(&expression->base.source_position,
9136 "the address of '%Y' will never be NULL",
9137 func_right->reference.entity->base.symbol);
9141 if (warning.parentheses) {
9142 warn_comparison_in_comparison(left);
9143 warn_comparison_in_comparison(right);
9146 type_t *orig_type_left = left->base.type;
9147 type_t *orig_type_right = right->base.type;
9148 type_t *type_left = skip_typeref(orig_type_left);
9149 type_t *type_right = skip_typeref(orig_type_right);
9151 /* TODO non-arithmetic types */
9152 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9153 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9155 /* test for signed vs unsigned compares */
9156 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
9157 bool const signed_left = is_type_signed(type_left);
9158 bool const signed_right = is_type_signed(type_right);
9159 if (signed_left != signed_right) {
9160 /* FIXME long long needs better const folding magic */
9161 /* TODO check whether constant value can be represented by other type */
9162 if ((signed_left && maybe_negative(left)) ||
9163 (signed_right && maybe_negative(right))) {
9164 warningf(&expression->base.source_position,
9165 "comparison between signed and unsigned");
9170 expression->left = create_implicit_cast(left, arithmetic_type);
9171 expression->right = create_implicit_cast(right, arithmetic_type);
9172 expression->base.type = arithmetic_type;
9173 if (warning.float_equal &&
9174 (expression->base.kind == EXPR_BINARY_EQUAL ||
9175 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
9176 is_type_float(arithmetic_type)) {
9177 warningf(&expression->base.source_position,
9178 "comparing floating point with == or != is unsafe");
9180 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
9181 /* TODO check compatibility */
9182 } else if (is_type_pointer(type_left)) {
9183 expression->right = create_implicit_cast(right, type_left);
9184 } else if (is_type_pointer(type_right)) {
9185 expression->left = create_implicit_cast(left, type_right);
9186 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9187 type_error_incompatible("invalid operands in comparison",
9188 &expression->base.source_position,
9189 type_left, type_right);
9191 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9195 * Checks if a compound type has constant fields.
9197 static bool has_const_fields(const compound_type_t *type)
9199 compound_t *compound = type->compound;
9200 entity_t *entry = compound->members.entities;
9202 for (; entry != NULL; entry = entry->base.next) {
9203 if (!is_declaration(entry))
9206 const type_t *decl_type = skip_typeref(entry->declaration.type);
9207 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
9214 static bool is_valid_assignment_lhs(expression_t const* const left)
9216 type_t *const orig_type_left = revert_automatic_type_conversion(left);
9217 type_t *const type_left = skip_typeref(orig_type_left);
9219 if (!is_lvalue(left)) {
9220 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
9225 if (left->kind == EXPR_REFERENCE
9226 && left->reference.entity->kind == ENTITY_FUNCTION) {
9227 errorf(HERE, "cannot assign to function '%E'", left);
9231 if (is_type_array(type_left)) {
9232 errorf(HERE, "cannot assign to array '%E'", left);
9235 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
9236 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
9240 if (is_type_incomplete(type_left)) {
9241 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
9242 left, orig_type_left);
9245 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
9246 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
9247 left, orig_type_left);
9254 static void semantic_arithmetic_assign(binary_expression_t *expression)
9256 expression_t *left = expression->left;
9257 expression_t *right = expression->right;
9258 type_t *orig_type_left = left->base.type;
9259 type_t *orig_type_right = right->base.type;
9261 if (!is_valid_assignment_lhs(left))
9264 type_t *type_left = skip_typeref(orig_type_left);
9265 type_t *type_right = skip_typeref(orig_type_right);
9267 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
9268 /* TODO: improve error message */
9269 if (is_type_valid(type_left) && is_type_valid(type_right)) {
9270 errorf(&expression->base.source_position,
9271 "operation needs arithmetic types");
9276 /* combined instructions are tricky. We can't create an implicit cast on
9277 * the left side, because we need the uncasted form for the store.
9278 * The ast2firm pass has to know that left_type must be right_type
9279 * for the arithmetic operation and create a cast by itself */
9280 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9281 expression->right = create_implicit_cast(right, arithmetic_type);
9282 expression->base.type = type_left;
9285 static void semantic_divmod_assign(binary_expression_t *expression)
9287 semantic_arithmetic_assign(expression);
9288 warn_div_by_zero(expression);
9291 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
9293 expression_t *const left = expression->left;
9294 expression_t *const right = expression->right;
9295 type_t *const orig_type_left = left->base.type;
9296 type_t *const orig_type_right = right->base.type;
9297 type_t *const type_left = skip_typeref(orig_type_left);
9298 type_t *const type_right = skip_typeref(orig_type_right);
9300 if (!is_valid_assignment_lhs(left))
9303 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9304 /* combined instructions are tricky. We can't create an implicit cast on
9305 * the left side, because we need the uncasted form for the store.
9306 * The ast2firm pass has to know that left_type must be right_type
9307 * for the arithmetic operation and create a cast by itself */
9308 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
9309 expression->right = create_implicit_cast(right, arithmetic_type);
9310 expression->base.type = type_left;
9311 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9312 check_pointer_arithmetic(&expression->base.source_position,
9313 type_left, orig_type_left);
9314 expression->base.type = type_left;
9315 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9316 errorf(&expression->base.source_position,
9317 "incompatible types '%T' and '%T' in assignment",
9318 orig_type_left, orig_type_right);
9322 static void warn_logical_and_within_or(const expression_t *const expr)
9324 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
9326 if (expr->base.parenthesized)
9328 warningf(&expr->base.source_position,
9329 "suggest parentheses around && within ||");
9333 * Check the semantic restrictions of a logical expression.
9335 static void semantic_logical_op(binary_expression_t *expression)
9337 /* §6.5.13:2 Each of the operands shall have scalar type.
9338 * §6.5.14:2 Each of the operands shall have scalar type. */
9339 semantic_condition(expression->left, "left operand of logical operator");
9340 semantic_condition(expression->right, "right operand of logical operator");
9341 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
9342 warning.parentheses) {
9343 warn_logical_and_within_or(expression->left);
9344 warn_logical_and_within_or(expression->right);
9346 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9350 * Check the semantic restrictions of a binary assign expression.
9352 static void semantic_binexpr_assign(binary_expression_t *expression)
9354 expression_t *left = expression->left;
9355 type_t *orig_type_left = left->base.type;
9357 if (!is_valid_assignment_lhs(left))
9360 assign_error_t error = semantic_assign(orig_type_left, expression->right);
9361 report_assign_error(error, orig_type_left, expression->right,
9362 "assignment", &left->base.source_position);
9363 expression->right = create_implicit_cast(expression->right, orig_type_left);
9364 expression->base.type = orig_type_left;
9368 * Determine if the outermost operation (or parts thereof) of the given
9369 * expression has no effect in order to generate a warning about this fact.
9370 * Therefore in some cases this only examines some of the operands of the
9371 * expression (see comments in the function and examples below).
9373 * f() + 23; // warning, because + has no effect
9374 * x || f(); // no warning, because x controls execution of f()
9375 * x ? y : f(); // warning, because y has no effect
9376 * (void)x; // no warning to be able to suppress the warning
9377 * This function can NOT be used for an "expression has definitely no effect"-
9379 static bool expression_has_effect(const expression_t *const expr)
9381 switch (expr->kind) {
9382 case EXPR_UNKNOWN: break;
9383 case EXPR_INVALID: return true; /* do NOT warn */
9384 case EXPR_REFERENCE: return false;
9385 case EXPR_REFERENCE_ENUM_VALUE: return false;
9386 /* suppress the warning for microsoft __noop operations */
9387 case EXPR_CONST: return expr->conste.is_ms_noop;
9388 case EXPR_CHARACTER_CONSTANT: return false;
9389 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
9390 case EXPR_STRING_LITERAL: return false;
9391 case EXPR_WIDE_STRING_LITERAL: return false;
9392 case EXPR_LABEL_ADDRESS: return false;
9395 const call_expression_t *const call = &expr->call;
9396 if (call->function->kind != EXPR_REFERENCE)
9399 switch (call->function->reference.entity->function.btk) {
9400 /* FIXME: which builtins have no effect? */
9401 default: return true;
9405 /* Generate the warning if either the left or right hand side of a
9406 * conditional expression has no effect */
9407 case EXPR_CONDITIONAL: {
9408 conditional_expression_t const *const cond = &expr->conditional;
9409 expression_t const *const t = cond->true_expression;
9411 (t == NULL || expression_has_effect(t)) &&
9412 expression_has_effect(cond->false_expression);
9415 case EXPR_SELECT: return false;
9416 case EXPR_ARRAY_ACCESS: return false;
9417 case EXPR_SIZEOF: return false;
9418 case EXPR_CLASSIFY_TYPE: return false;
9419 case EXPR_ALIGNOF: return false;
9421 case EXPR_FUNCNAME: return false;
9422 case EXPR_BUILTIN_CONSTANT_P: return false;
9423 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
9424 case EXPR_OFFSETOF: return false;
9425 case EXPR_VA_START: return true;
9426 case EXPR_VA_ARG: return true;
9427 case EXPR_VA_COPY: return true;
9428 case EXPR_STATEMENT: return true; // TODO
9429 case EXPR_COMPOUND_LITERAL: return false;
9431 case EXPR_UNARY_NEGATE: return false;
9432 case EXPR_UNARY_PLUS: return false;
9433 case EXPR_UNARY_BITWISE_NEGATE: return false;
9434 case EXPR_UNARY_NOT: return false;
9435 case EXPR_UNARY_DEREFERENCE: return false;
9436 case EXPR_UNARY_TAKE_ADDRESS: return false;
9437 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
9438 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
9439 case EXPR_UNARY_PREFIX_INCREMENT: return true;
9440 case EXPR_UNARY_PREFIX_DECREMENT: return true;
9442 /* Treat void casts as if they have an effect in order to being able to
9443 * suppress the warning */
9444 case EXPR_UNARY_CAST: {
9445 type_t *const type = skip_typeref(expr->base.type);
9446 return is_type_atomic(type, ATOMIC_TYPE_VOID);
9449 case EXPR_UNARY_CAST_IMPLICIT: return true;
9450 case EXPR_UNARY_ASSUME: return true;
9451 case EXPR_UNARY_DELETE: return true;
9452 case EXPR_UNARY_DELETE_ARRAY: return true;
9453 case EXPR_UNARY_THROW: return true;
9455 case EXPR_BINARY_ADD: return false;
9456 case EXPR_BINARY_SUB: return false;
9457 case EXPR_BINARY_MUL: return false;
9458 case EXPR_BINARY_DIV: return false;
9459 case EXPR_BINARY_MOD: return false;
9460 case EXPR_BINARY_EQUAL: return false;
9461 case EXPR_BINARY_NOTEQUAL: return false;
9462 case EXPR_BINARY_LESS: return false;
9463 case EXPR_BINARY_LESSEQUAL: return false;
9464 case EXPR_BINARY_GREATER: return false;
9465 case EXPR_BINARY_GREATEREQUAL: return false;
9466 case EXPR_BINARY_BITWISE_AND: return false;
9467 case EXPR_BINARY_BITWISE_OR: return false;
9468 case EXPR_BINARY_BITWISE_XOR: return false;
9469 case EXPR_BINARY_SHIFTLEFT: return false;
9470 case EXPR_BINARY_SHIFTRIGHT: return false;
9471 case EXPR_BINARY_ASSIGN: return true;
9472 case EXPR_BINARY_MUL_ASSIGN: return true;
9473 case EXPR_BINARY_DIV_ASSIGN: return true;
9474 case EXPR_BINARY_MOD_ASSIGN: return true;
9475 case EXPR_BINARY_ADD_ASSIGN: return true;
9476 case EXPR_BINARY_SUB_ASSIGN: return true;
9477 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
9478 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
9479 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9480 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9481 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
9483 /* Only examine the right hand side of && and ||, because the left hand
9484 * side already has the effect of controlling the execution of the right
9486 case EXPR_BINARY_LOGICAL_AND:
9487 case EXPR_BINARY_LOGICAL_OR:
9488 /* Only examine the right hand side of a comma expression, because the left
9489 * hand side has a separate warning */
9490 case EXPR_BINARY_COMMA:
9491 return expression_has_effect(expr->binary.right);
9493 case EXPR_BINARY_ISGREATER: return false;
9494 case EXPR_BINARY_ISGREATEREQUAL: return false;
9495 case EXPR_BINARY_ISLESS: return false;
9496 case EXPR_BINARY_ISLESSEQUAL: return false;
9497 case EXPR_BINARY_ISLESSGREATER: return false;
9498 case EXPR_BINARY_ISUNORDERED: return false;
9501 internal_errorf(HERE, "unexpected expression");
9504 static void semantic_comma(binary_expression_t *expression)
9506 if (warning.unused_value) {
9507 const expression_t *const left = expression->left;
9508 if (!expression_has_effect(left)) {
9509 warningf(&left->base.source_position,
9510 "left-hand operand of comma expression has no effect");
9513 expression->base.type = expression->right->base.type;
9517 * @param prec_r precedence of the right operand
9519 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9520 static expression_t *parse_##binexpression_type(expression_t *left) \
9522 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9523 binexpr->binary.left = left; \
9526 expression_t *right = parse_sub_expression(prec_r); \
9528 binexpr->binary.right = right; \
9529 sfunc(&binexpr->binary); \
9534 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9535 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9536 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9537 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9538 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9539 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9540 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9541 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9542 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9543 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9544 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9545 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9546 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9547 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9548 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9549 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9550 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9551 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9552 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9553 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9554 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9555 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9556 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9557 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9558 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9559 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9560 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9561 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9562 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9563 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9566 static expression_t *parse_sub_expression(precedence_t precedence)
9568 if (token.type < 0) {
9569 return expected_expression_error();
9572 expression_parser_function_t *parser
9573 = &expression_parsers[token.type];
9574 source_position_t source_position = token.source_position;
9577 if (parser->parser != NULL) {
9578 left = parser->parser();
9580 left = parse_primary_expression();
9582 assert(left != NULL);
9583 left->base.source_position = source_position;
9586 if (token.type < 0) {
9587 return expected_expression_error();
9590 parser = &expression_parsers[token.type];
9591 if (parser->infix_parser == NULL)
9593 if (parser->infix_precedence < precedence)
9596 left = parser->infix_parser(left);
9598 assert(left != NULL);
9599 assert(left->kind != EXPR_UNKNOWN);
9600 left->base.source_position = source_position;
9607 * Parse an expression.
9609 static expression_t *parse_expression(void)
9611 return parse_sub_expression(PREC_EXPRESSION);
9615 * Register a parser for a prefix-like operator.
9617 * @param parser the parser function
9618 * @param token_type the token type of the prefix token
9620 static void register_expression_parser(parse_expression_function parser,
9623 expression_parser_function_t *entry = &expression_parsers[token_type];
9625 if (entry->parser != NULL) {
9626 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9627 panic("trying to register multiple expression parsers for a token");
9629 entry->parser = parser;
9633 * Register a parser for an infix operator with given precedence.
9635 * @param parser the parser function
9636 * @param token_type the token type of the infix operator
9637 * @param precedence the precedence of the operator
9639 static void register_infix_parser(parse_expression_infix_function parser,
9640 int token_type, precedence_t precedence)
9642 expression_parser_function_t *entry = &expression_parsers[token_type];
9644 if (entry->infix_parser != NULL) {
9645 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9646 panic("trying to register multiple infix expression parsers for a "
9649 entry->infix_parser = parser;
9650 entry->infix_precedence = precedence;
9654 * Initialize the expression parsers.
9656 static void init_expression_parsers(void)
9658 memset(&expression_parsers, 0, sizeof(expression_parsers));
9660 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9661 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9662 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9663 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9664 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9665 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9666 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9667 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9668 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9669 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9670 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9671 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9672 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9673 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9674 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9675 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9676 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9677 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9678 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9679 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9680 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9681 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9682 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9683 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9684 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9685 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9686 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9687 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9688 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9689 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9690 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9691 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9692 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9693 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9694 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9695 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9696 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9698 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9699 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9700 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9701 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9702 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9703 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9704 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9705 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9706 register_expression_parser(parse_sizeof, T_sizeof);
9707 register_expression_parser(parse_alignof, T___alignof__);
9708 register_expression_parser(parse_extension, T___extension__);
9709 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9710 register_expression_parser(parse_delete, T_delete);
9711 register_expression_parser(parse_throw, T_throw);
9715 * Parse a asm statement arguments specification.
9717 static asm_argument_t *parse_asm_arguments(bool is_out)
9719 asm_argument_t *result = NULL;
9720 asm_argument_t **anchor = &result;
9722 while (token.type == T_STRING_LITERAL || token.type == '[') {
9723 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9724 memset(argument, 0, sizeof(argument[0]));
9726 if (token.type == '[') {
9728 if (token.type != T_IDENTIFIER) {
9729 parse_error_expected("while parsing asm argument",
9730 T_IDENTIFIER, NULL);
9733 argument->symbol = token.v.symbol;
9735 expect(']', end_error);
9738 argument->constraints = parse_string_literals();
9739 expect('(', end_error);
9740 add_anchor_token(')');
9741 expression_t *expression = parse_expression();
9742 rem_anchor_token(')');
9744 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9745 * change size or type representation (e.g. int -> long is ok, but
9746 * int -> float is not) */
9747 if (expression->kind == EXPR_UNARY_CAST) {
9748 type_t *const type = expression->base.type;
9749 type_kind_t const kind = type->kind;
9750 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9753 if (kind == TYPE_ATOMIC) {
9754 atomic_type_kind_t const akind = type->atomic.akind;
9755 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9756 size = get_atomic_type_size(akind);
9758 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9759 size = get_atomic_type_size(get_intptr_kind());
9763 expression_t *const value = expression->unary.value;
9764 type_t *const value_type = value->base.type;
9765 type_kind_t const value_kind = value_type->kind;
9767 unsigned value_flags;
9768 unsigned value_size;
9769 if (value_kind == TYPE_ATOMIC) {
9770 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9771 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9772 value_size = get_atomic_type_size(value_akind);
9773 } else if (value_kind == TYPE_POINTER) {
9774 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9775 value_size = get_atomic_type_size(get_intptr_kind());
9780 if (value_flags != flags || value_size != size)
9784 } while (expression->kind == EXPR_UNARY_CAST);
9788 if (!is_lvalue(expression)) {
9789 errorf(&expression->base.source_position,
9790 "asm output argument is not an lvalue");
9793 if (argument->constraints.begin[0] == '+')
9794 mark_vars_read(expression, NULL);
9796 mark_vars_read(expression, NULL);
9798 argument->expression = expression;
9799 expect(')', end_error);
9801 set_address_taken(expression, true);
9804 anchor = &argument->next;
9806 if (token.type != ',')
9817 * Parse a asm statement clobber specification.
9819 static asm_clobber_t *parse_asm_clobbers(void)
9821 asm_clobber_t *result = NULL;
9822 asm_clobber_t *last = NULL;
9824 while (token.type == T_STRING_LITERAL) {
9825 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9826 clobber->clobber = parse_string_literals();
9829 last->next = clobber;
9835 if (token.type != ',')
9844 * Parse an asm statement.
9846 static statement_t *parse_asm_statement(void)
9848 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9849 asm_statement_t *asm_statement = &statement->asms;
9853 if (token.type == T_volatile) {
9855 asm_statement->is_volatile = true;
9858 expect('(', end_error);
9859 add_anchor_token(')');
9860 add_anchor_token(':');
9861 asm_statement->asm_text = parse_string_literals();
9863 if (token.type != ':') {
9864 rem_anchor_token(':');
9869 asm_statement->outputs = parse_asm_arguments(true);
9870 if (token.type != ':') {
9871 rem_anchor_token(':');
9876 asm_statement->inputs = parse_asm_arguments(false);
9877 if (token.type != ':') {
9878 rem_anchor_token(':');
9881 rem_anchor_token(':');
9884 asm_statement->clobbers = parse_asm_clobbers();
9887 rem_anchor_token(')');
9888 expect(')', end_error);
9889 expect(';', end_error);
9891 if (asm_statement->outputs == NULL) {
9892 /* GCC: An 'asm' instruction without any output operands will be treated
9893 * identically to a volatile 'asm' instruction. */
9894 asm_statement->is_volatile = true;
9899 return create_invalid_statement();
9903 * Parse a case statement.
9905 static statement_t *parse_case_statement(void)
9907 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9908 source_position_t *const pos = &statement->base.source_position;
9912 expression_t *const expression = parse_expression();
9913 statement->case_label.expression = expression;
9914 if (!is_constant_expression(expression)) {
9915 /* This check does not prevent the error message in all cases of an
9916 * prior error while parsing the expression. At least it catches the
9917 * common case of a mistyped enum entry. */
9918 if (is_type_valid(skip_typeref(expression->base.type))) {
9919 errorf(pos, "case label does not reduce to an integer constant");
9921 statement->case_label.is_bad = true;
9923 long const val = fold_constant(expression);
9924 statement->case_label.first_case = val;
9925 statement->case_label.last_case = val;
9929 if (token.type == T_DOTDOTDOT) {
9931 expression_t *const end_range = parse_expression();
9932 statement->case_label.end_range = end_range;
9933 if (!is_constant_expression(end_range)) {
9934 /* This check does not prevent the error message in all cases of an
9935 * prior error while parsing the expression. At least it catches the
9936 * common case of a mistyped enum entry. */
9937 if (is_type_valid(skip_typeref(end_range->base.type))) {
9938 errorf(pos, "case range does not reduce to an integer constant");
9940 statement->case_label.is_bad = true;
9942 long const val = fold_constant(end_range);
9943 statement->case_label.last_case = val;
9945 if (warning.other && val < statement->case_label.first_case) {
9946 statement->case_label.is_empty_range = true;
9947 warningf(pos, "empty range specified");
9953 PUSH_PARENT(statement);
9955 expect(':', end_error);
9958 if (current_switch != NULL) {
9959 if (! statement->case_label.is_bad) {
9960 /* Check for duplicate case values */
9961 case_label_statement_t *c = &statement->case_label;
9962 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9963 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9966 if (c->last_case < l->first_case || c->first_case > l->last_case)
9969 errorf(pos, "duplicate case value (previously used %P)",
9970 &l->base.source_position);
9974 /* link all cases into the switch statement */
9975 if (current_switch->last_case == NULL) {
9976 current_switch->first_case = &statement->case_label;
9978 current_switch->last_case->next = &statement->case_label;
9980 current_switch->last_case = &statement->case_label;
9982 errorf(pos, "case label not within a switch statement");
9985 statement_t *const inner_stmt = parse_statement();
9986 statement->case_label.statement = inner_stmt;
9987 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9988 errorf(&inner_stmt->base.source_position, "declaration after case label");
9996 * Parse a default statement.
9998 static statement_t *parse_default_statement(void)
10000 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
10004 PUSH_PARENT(statement);
10006 expect(':', end_error);
10007 if (current_switch != NULL) {
10008 const case_label_statement_t *def_label = current_switch->default_label;
10009 if (def_label != NULL) {
10010 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
10011 &def_label->base.source_position);
10013 current_switch->default_label = &statement->case_label;
10015 /* link all cases into the switch statement */
10016 if (current_switch->last_case == NULL) {
10017 current_switch->first_case = &statement->case_label;
10019 current_switch->last_case->next = &statement->case_label;
10021 current_switch->last_case = &statement->case_label;
10024 errorf(&statement->base.source_position,
10025 "'default' label not within a switch statement");
10028 statement_t *const inner_stmt = parse_statement();
10029 statement->case_label.statement = inner_stmt;
10030 if (inner_stmt->kind == STATEMENT_DECLARATION) {
10031 errorf(&inner_stmt->base.source_position, "declaration after default label");
10038 return create_invalid_statement();
10042 * Parse a label statement.
10044 static statement_t *parse_label_statement(void)
10046 assert(token.type == T_IDENTIFIER);
10047 symbol_t *symbol = token.v.symbol;
10048 label_t *label = get_label(symbol);
10050 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
10051 statement->label.label = label;
10055 PUSH_PARENT(statement);
10057 /* if statement is already set then the label is defined twice,
10058 * otherwise it was just mentioned in a goto/local label declaration so far
10060 if (label->statement != NULL) {
10061 errorf(HERE, "duplicate label '%Y' (declared %P)",
10062 symbol, &label->base.source_position);
10064 label->base.source_position = token.source_position;
10065 label->statement = statement;
10070 if (token.type == '}') {
10071 /* TODO only warn? */
10072 if (warning.other && false) {
10073 warningf(HERE, "label at end of compound statement");
10074 statement->label.statement = create_empty_statement();
10076 errorf(HERE, "label at end of compound statement");
10077 statement->label.statement = create_invalid_statement();
10079 } else if (token.type == ';') {
10080 /* Eat an empty statement here, to avoid the warning about an empty
10081 * statement after a label. label:; is commonly used to have a label
10082 * before a closing brace. */
10083 statement->label.statement = create_empty_statement();
10086 statement_t *const inner_stmt = parse_statement();
10087 statement->label.statement = inner_stmt;
10088 if (inner_stmt->kind == STATEMENT_DECLARATION) {
10089 errorf(&inner_stmt->base.source_position, "declaration after label");
10093 /* remember the labels in a list for later checking */
10094 *label_anchor = &statement->label;
10095 label_anchor = &statement->label.next;
10102 * Parse an if statement.
10104 static statement_t *parse_if(void)
10106 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
10110 PUSH_PARENT(statement);
10112 add_anchor_token('{');
10114 expect('(', end_error);
10115 add_anchor_token(')');
10116 expression_t *const expr = parse_expression();
10117 statement->ifs.condition = expr;
10118 /* §6.8.4.1:1 The controlling expression of an if statement shall have
10120 semantic_condition(expr, "condition of 'if'-statment");
10121 mark_vars_read(expr, NULL);
10122 rem_anchor_token(')');
10123 expect(')', end_error);
10126 rem_anchor_token('{');
10128 add_anchor_token(T_else);
10129 statement_t *const true_stmt = parse_statement();
10130 statement->ifs.true_statement = true_stmt;
10131 rem_anchor_token(T_else);
10133 if (token.type == T_else) {
10135 statement->ifs.false_statement = parse_statement();
10136 } else if (warning.parentheses &&
10137 true_stmt->kind == STATEMENT_IF &&
10138 true_stmt->ifs.false_statement != NULL) {
10139 warningf(&true_stmt->base.source_position,
10140 "suggest explicit braces to avoid ambiguous 'else'");
10148 * Check that all enums are handled in a switch.
10150 * @param statement the switch statement to check
10152 static void check_enum_cases(const switch_statement_t *statement)
10154 const type_t *type = skip_typeref(statement->expression->base.type);
10155 if (! is_type_enum(type))
10157 const enum_type_t *enumt = &type->enumt;
10159 /* if we have a default, no warnings */
10160 if (statement->default_label != NULL)
10163 /* FIXME: calculation of value should be done while parsing */
10164 /* TODO: quadratic algorithm here. Change to an n log n one */
10165 long last_value = -1;
10166 const entity_t *entry = enumt->enume->base.next;
10167 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
10168 entry = entry->base.next) {
10169 const expression_t *expression = entry->enum_value.value;
10170 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
10171 bool found = false;
10172 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
10173 if (l->expression == NULL)
10175 if (l->first_case <= value && value <= l->last_case) {
10181 warningf(&statement->base.source_position,
10182 "enumeration value '%Y' not handled in switch",
10183 entry->base.symbol);
10185 last_value = value;
10190 * Parse a switch statement.
10192 static statement_t *parse_switch(void)
10194 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
10198 PUSH_PARENT(statement);
10200 expect('(', end_error);
10201 add_anchor_token(')');
10202 expression_t *const expr = parse_expression();
10203 mark_vars_read(expr, NULL);
10204 type_t * type = skip_typeref(expr->base.type);
10205 if (is_type_integer(type)) {
10206 type = promote_integer(type);
10207 if (warning.traditional) {
10208 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
10209 warningf(&expr->base.source_position,
10210 "'%T' switch expression not converted to '%T' in ISO C",
10214 } else if (is_type_valid(type)) {
10215 errorf(&expr->base.source_position,
10216 "switch quantity is not an integer, but '%T'", type);
10217 type = type_error_type;
10219 statement->switchs.expression = create_implicit_cast(expr, type);
10220 expect(')', end_error);
10221 rem_anchor_token(')');
10223 switch_statement_t *rem = current_switch;
10224 current_switch = &statement->switchs;
10225 statement->switchs.body = parse_statement();
10226 current_switch = rem;
10228 if (warning.switch_default &&
10229 statement->switchs.default_label == NULL) {
10230 warningf(&statement->base.source_position, "switch has no default case");
10232 if (warning.switch_enum)
10233 check_enum_cases(&statement->switchs);
10239 return create_invalid_statement();
10242 static statement_t *parse_loop_body(statement_t *const loop)
10244 statement_t *const rem = current_loop;
10245 current_loop = loop;
10247 statement_t *const body = parse_statement();
10249 current_loop = rem;
10254 * Parse a while statement.
10256 static statement_t *parse_while(void)
10258 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
10262 PUSH_PARENT(statement);
10264 expect('(', end_error);
10265 add_anchor_token(')');
10266 expression_t *const cond = parse_expression();
10267 statement->whiles.condition = cond;
10268 /* §6.8.5:2 The controlling expression of an iteration statement shall
10269 * have scalar type. */
10270 semantic_condition(cond, "condition of 'while'-statement");
10271 mark_vars_read(cond, NULL);
10272 rem_anchor_token(')');
10273 expect(')', end_error);
10275 statement->whiles.body = parse_loop_body(statement);
10281 return create_invalid_statement();
10285 * Parse a do statement.
10287 static statement_t *parse_do(void)
10289 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
10293 PUSH_PARENT(statement);
10295 add_anchor_token(T_while);
10296 statement->do_while.body = parse_loop_body(statement);
10297 rem_anchor_token(T_while);
10299 expect(T_while, end_error);
10300 expect('(', end_error);
10301 add_anchor_token(')');
10302 expression_t *const cond = parse_expression();
10303 statement->do_while.condition = cond;
10304 /* §6.8.5:2 The controlling expression of an iteration statement shall
10305 * have scalar type. */
10306 semantic_condition(cond, "condition of 'do-while'-statement");
10307 mark_vars_read(cond, NULL);
10308 rem_anchor_token(')');
10309 expect(')', end_error);
10310 expect(';', end_error);
10316 return create_invalid_statement();
10320 * Parse a for statement.
10322 static statement_t *parse_for(void)
10324 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
10328 expect('(', end_error1);
10329 add_anchor_token(')');
10331 PUSH_PARENT(statement);
10333 size_t const top = environment_top();
10334 scope_t *old_scope = scope_push(&statement->fors.scope);
10336 if (token.type == ';') {
10338 } else if (is_declaration_specifier(&token, false)) {
10339 parse_declaration(record_entity, DECL_FLAGS_NONE);
10341 add_anchor_token(';');
10342 expression_t *const init = parse_expression();
10343 statement->fors.initialisation = init;
10344 mark_vars_read(init, ENT_ANY);
10345 if (warning.unused_value && !expression_has_effect(init)) {
10346 warningf(&init->base.source_position,
10347 "initialisation of 'for'-statement has no effect");
10349 rem_anchor_token(';');
10350 expect(';', end_error2);
10353 if (token.type != ';') {
10354 add_anchor_token(';');
10355 expression_t *const cond = parse_expression();
10356 statement->fors.condition = cond;
10357 /* §6.8.5:2 The controlling expression of an iteration statement
10358 * shall have scalar type. */
10359 semantic_condition(cond, "condition of 'for'-statement");
10360 mark_vars_read(cond, NULL);
10361 rem_anchor_token(';');
10363 expect(';', end_error2);
10364 if (token.type != ')') {
10365 expression_t *const step = parse_expression();
10366 statement->fors.step = step;
10367 mark_vars_read(step, ENT_ANY);
10368 if (warning.unused_value && !expression_has_effect(step)) {
10369 warningf(&step->base.source_position,
10370 "step of 'for'-statement has no effect");
10373 expect(')', end_error2);
10374 rem_anchor_token(')');
10375 statement->fors.body = parse_loop_body(statement);
10377 assert(current_scope == &statement->fors.scope);
10378 scope_pop(old_scope);
10379 environment_pop_to(top);
10386 rem_anchor_token(')');
10387 assert(current_scope == &statement->fors.scope);
10388 scope_pop(old_scope);
10389 environment_pop_to(top);
10393 return create_invalid_statement();
10397 * Parse a goto statement.
10399 static statement_t *parse_goto(void)
10401 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
10404 if (GNU_MODE && token.type == '*') {
10406 expression_t *expression = parse_expression();
10407 mark_vars_read(expression, NULL);
10409 /* Argh: although documentation says the expression must be of type void*,
10410 * gcc accepts anything that can be casted into void* without error */
10411 type_t *type = expression->base.type;
10413 if (type != type_error_type) {
10414 if (!is_type_pointer(type) && !is_type_integer(type)) {
10415 errorf(&expression->base.source_position,
10416 "cannot convert to a pointer type");
10417 } else if (warning.other && type != type_void_ptr) {
10418 warningf(&expression->base.source_position,
10419 "type of computed goto expression should be 'void*' not '%T'", type);
10421 expression = create_implicit_cast(expression, type_void_ptr);
10424 statement->gotos.expression = expression;
10426 if (token.type != T_IDENTIFIER) {
10428 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
10430 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
10431 eat_until_anchor();
10434 symbol_t *symbol = token.v.symbol;
10437 statement->gotos.label = get_label(symbol);
10440 /* remember the goto's in a list for later checking */
10441 *goto_anchor = &statement->gotos;
10442 goto_anchor = &statement->gotos.next;
10444 expect(';', end_error);
10448 return create_invalid_statement();
10452 * Parse a continue statement.
10454 static statement_t *parse_continue(void)
10456 if (current_loop == NULL) {
10457 errorf(HERE, "continue statement not within loop");
10460 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
10463 expect(';', end_error);
10470 * Parse a break statement.
10472 static statement_t *parse_break(void)
10474 if (current_switch == NULL && current_loop == NULL) {
10475 errorf(HERE, "break statement not within loop or switch");
10478 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10481 expect(';', end_error);
10488 * Parse a __leave statement.
10490 static statement_t *parse_leave_statement(void)
10492 if (current_try == NULL) {
10493 errorf(HERE, "__leave statement not within __try");
10496 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10499 expect(';', end_error);
10506 * Check if a given entity represents a local variable.
10508 static bool is_local_variable(const entity_t *entity)
10510 if (entity->kind != ENTITY_VARIABLE)
10513 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10514 case STORAGE_CLASS_AUTO:
10515 case STORAGE_CLASS_REGISTER: {
10516 const type_t *type = skip_typeref(entity->declaration.type);
10517 if (is_type_function(type)) {
10529 * Check if a given expression represents a local variable.
10531 static bool expression_is_local_variable(const expression_t *expression)
10533 if (expression->base.kind != EXPR_REFERENCE) {
10536 const entity_t *entity = expression->reference.entity;
10537 return is_local_variable(entity);
10541 * Check if a given expression represents a local variable and
10542 * return its declaration then, else return NULL.
10544 entity_t *expression_is_variable(const expression_t *expression)
10546 if (expression->base.kind != EXPR_REFERENCE) {
10549 entity_t *entity = expression->reference.entity;
10550 if (entity->kind != ENTITY_VARIABLE)
10557 * Parse a return statement.
10559 static statement_t *parse_return(void)
10563 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10565 expression_t *return_value = NULL;
10566 if (token.type != ';') {
10567 return_value = parse_expression();
10568 mark_vars_read(return_value, NULL);
10571 const type_t *const func_type = skip_typeref(current_function->base.type);
10572 assert(is_type_function(func_type));
10573 type_t *const return_type = skip_typeref(func_type->function.return_type);
10575 source_position_t const *const pos = &statement->base.source_position;
10576 if (return_value != NULL) {
10577 type_t *return_value_type = skip_typeref(return_value->base.type);
10579 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10580 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10581 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10582 /* Only warn in C mode, because GCC does the same */
10583 if (c_mode & _CXX || strict_mode) {
10585 "'return' with a value, in function returning 'void'");
10586 } else if (warning.other) {
10588 "'return' with a value, in function returning 'void'");
10590 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10591 /* Only warn in C mode, because GCC does the same */
10594 "'return' with expression in function returning 'void'");
10595 } else if (warning.other) {
10597 "'return' with expression in function returning 'void'");
10601 assign_error_t error = semantic_assign(return_type, return_value);
10602 report_assign_error(error, return_type, return_value, "'return'",
10605 return_value = create_implicit_cast(return_value, return_type);
10606 /* check for returning address of a local var */
10607 if (warning.other && return_value != NULL
10608 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10609 const expression_t *expression = return_value->unary.value;
10610 if (expression_is_local_variable(expression)) {
10611 warningf(pos, "function returns address of local variable");
10614 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10615 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10616 if (c_mode & _CXX || strict_mode) {
10618 "'return' without value, in function returning non-void");
10621 "'return' without value, in function returning non-void");
10624 statement->returns.value = return_value;
10626 expect(';', end_error);
10633 * Parse a declaration statement.
10635 static statement_t *parse_declaration_statement(void)
10637 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10639 entity_t *before = current_scope->last_entity;
10641 parse_external_declaration();
10643 parse_declaration(record_entity, DECL_FLAGS_NONE);
10646 declaration_statement_t *const decl = &statement->declaration;
10647 entity_t *const begin =
10648 before != NULL ? before->base.next : current_scope->entities;
10649 decl->declarations_begin = begin;
10650 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
10656 * Parse an expression statement, ie. expr ';'.
10658 static statement_t *parse_expression_statement(void)
10660 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10662 expression_t *const expr = parse_expression();
10663 statement->expression.expression = expr;
10664 mark_vars_read(expr, ENT_ANY);
10666 expect(';', end_error);
10673 * Parse a microsoft __try { } __finally { } or
10674 * __try{ } __except() { }
10676 static statement_t *parse_ms_try_statment(void)
10678 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10681 PUSH_PARENT(statement);
10683 ms_try_statement_t *rem = current_try;
10684 current_try = &statement->ms_try;
10685 statement->ms_try.try_statement = parse_compound_statement(false);
10690 if (token.type == T___except) {
10692 expect('(', end_error);
10693 add_anchor_token(')');
10694 expression_t *const expr = parse_expression();
10695 mark_vars_read(expr, NULL);
10696 type_t * type = skip_typeref(expr->base.type);
10697 if (is_type_integer(type)) {
10698 type = promote_integer(type);
10699 } else if (is_type_valid(type)) {
10700 errorf(&expr->base.source_position,
10701 "__expect expression is not an integer, but '%T'", type);
10702 type = type_error_type;
10704 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10705 rem_anchor_token(')');
10706 expect(')', end_error);
10707 statement->ms_try.final_statement = parse_compound_statement(false);
10708 } else if (token.type == T__finally) {
10710 statement->ms_try.final_statement = parse_compound_statement(false);
10712 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10713 return create_invalid_statement();
10717 return create_invalid_statement();
10720 static statement_t *parse_empty_statement(void)
10722 if (warning.empty_statement) {
10723 warningf(HERE, "statement is empty");
10725 statement_t *const statement = create_empty_statement();
10730 static statement_t *parse_local_label_declaration(void)
10732 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10736 entity_t *begin = NULL, *end = NULL;
10739 if (token.type != T_IDENTIFIER) {
10740 parse_error_expected("while parsing local label declaration",
10741 T_IDENTIFIER, NULL);
10744 symbol_t *symbol = token.v.symbol;
10745 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10746 if (entity != NULL && entity->base.parent_scope == current_scope) {
10747 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10748 symbol, &entity->base.source_position);
10750 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10752 entity->base.parent_scope = current_scope;
10753 entity->base.namespc = NAMESPACE_LABEL;
10754 entity->base.source_position = token.source_position;
10755 entity->base.symbol = symbol;
10758 end->base.next = entity;
10763 environment_push(entity);
10767 if (token.type != ',')
10773 statement->declaration.declarations_begin = begin;
10774 statement->declaration.declarations_end = end;
10778 static void parse_namespace_definition(void)
10782 entity_t *entity = NULL;
10783 symbol_t *symbol = NULL;
10785 if (token.type == T_IDENTIFIER) {
10786 symbol = token.v.symbol;
10789 entity = get_entity(symbol, NAMESPACE_NORMAL);
10790 if (entity != NULL &&
10791 entity->kind != ENTITY_NAMESPACE &&
10792 entity->base.parent_scope == current_scope) {
10793 if (!is_error_entity(entity)) {
10794 error_redefined_as_different_kind(&token.source_position,
10795 entity, ENTITY_NAMESPACE);
10801 if (entity == NULL) {
10802 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10803 entity->base.symbol = symbol;
10804 entity->base.source_position = token.source_position;
10805 entity->base.namespc = NAMESPACE_NORMAL;
10806 entity->base.parent_scope = current_scope;
10809 if (token.type == '=') {
10810 /* TODO: parse namespace alias */
10811 panic("namespace alias definition not supported yet");
10814 environment_push(entity);
10815 append_entity(current_scope, entity);
10817 size_t const top = environment_top();
10818 scope_t *old_scope = scope_push(&entity->namespacee.members);
10820 expect('{', end_error);
10822 expect('}', end_error);
10825 assert(current_scope == &entity->namespacee.members);
10826 scope_pop(old_scope);
10827 environment_pop_to(top);
10831 * Parse a statement.
10832 * There's also parse_statement() which additionally checks for
10833 * "statement has no effect" warnings
10835 static statement_t *intern_parse_statement(void)
10837 statement_t *statement = NULL;
10839 /* declaration or statement */
10840 add_anchor_token(';');
10841 switch (token.type) {
10842 case T_IDENTIFIER: {
10843 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10844 if (la1_type == ':') {
10845 statement = parse_label_statement();
10846 } else if (is_typedef_symbol(token.v.symbol)) {
10847 statement = parse_declaration_statement();
10849 /* it's an identifier, the grammar says this must be an
10850 * expression statement. However it is common that users mistype
10851 * declaration types, so we guess a bit here to improve robustness
10852 * for incorrect programs */
10853 switch (la1_type) {
10856 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10857 goto expression_statment;
10862 statement = parse_declaration_statement();
10866 expression_statment:
10867 statement = parse_expression_statement();
10874 case T___extension__:
10875 /* This can be a prefix to a declaration or an expression statement.
10876 * We simply eat it now and parse the rest with tail recursion. */
10879 } while (token.type == T___extension__);
10880 bool old_gcc_extension = in_gcc_extension;
10881 in_gcc_extension = true;
10882 statement = intern_parse_statement();
10883 in_gcc_extension = old_gcc_extension;
10887 statement = parse_declaration_statement();
10891 statement = parse_local_label_declaration();
10894 case ';': statement = parse_empty_statement(); break;
10895 case '{': statement = parse_compound_statement(false); break;
10896 case T___leave: statement = parse_leave_statement(); break;
10897 case T___try: statement = parse_ms_try_statment(); break;
10898 case T_asm: statement = parse_asm_statement(); break;
10899 case T_break: statement = parse_break(); break;
10900 case T_case: statement = parse_case_statement(); break;
10901 case T_continue: statement = parse_continue(); break;
10902 case T_default: statement = parse_default_statement(); break;
10903 case T_do: statement = parse_do(); break;
10904 case T_for: statement = parse_for(); break;
10905 case T_goto: statement = parse_goto(); break;
10906 case T_if: statement = parse_if(); break;
10907 case T_return: statement = parse_return(); break;
10908 case T_switch: statement = parse_switch(); break;
10909 case T_while: statement = parse_while(); break;
10912 statement = parse_expression_statement();
10916 errorf(HERE, "unexpected token %K while parsing statement", &token);
10917 statement = create_invalid_statement();
10922 rem_anchor_token(';');
10924 assert(statement != NULL
10925 && statement->base.source_position.input_name != NULL);
10931 * parse a statement and emits "statement has no effect" warning if needed
10932 * (This is really a wrapper around intern_parse_statement with check for 1
10933 * single warning. It is needed, because for statement expressions we have
10934 * to avoid the warning on the last statement)
10936 static statement_t *parse_statement(void)
10938 statement_t *statement = intern_parse_statement();
10940 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10941 expression_t *expression = statement->expression.expression;
10942 if (!expression_has_effect(expression)) {
10943 warningf(&expression->base.source_position,
10944 "statement has no effect");
10952 * Parse a compound statement.
10954 static statement_t *parse_compound_statement(bool inside_expression_statement)
10956 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10958 PUSH_PARENT(statement);
10961 add_anchor_token('}');
10962 /* tokens, which can start a statement */
10963 /* TODO MS, __builtin_FOO */
10964 add_anchor_token('!');
10965 add_anchor_token('&');
10966 add_anchor_token('(');
10967 add_anchor_token('*');
10968 add_anchor_token('+');
10969 add_anchor_token('-');
10970 add_anchor_token('{');
10971 add_anchor_token('~');
10972 add_anchor_token(T_CHARACTER_CONSTANT);
10973 add_anchor_token(T_COLONCOLON);
10974 add_anchor_token(T_FLOATINGPOINT);
10975 add_anchor_token(T_IDENTIFIER);
10976 add_anchor_token(T_INTEGER);
10977 add_anchor_token(T_MINUSMINUS);
10978 add_anchor_token(T_PLUSPLUS);
10979 add_anchor_token(T_STRING_LITERAL);
10980 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10981 add_anchor_token(T_WIDE_STRING_LITERAL);
10982 add_anchor_token(T__Bool);
10983 add_anchor_token(T__Complex);
10984 add_anchor_token(T__Imaginary);
10985 add_anchor_token(T___FUNCTION__);
10986 add_anchor_token(T___PRETTY_FUNCTION__);
10987 add_anchor_token(T___alignof__);
10988 add_anchor_token(T___attribute__);
10989 add_anchor_token(T___builtin_va_start);
10990 add_anchor_token(T___extension__);
10991 add_anchor_token(T___func__);
10992 add_anchor_token(T___imag__);
10993 add_anchor_token(T___label__);
10994 add_anchor_token(T___real__);
10995 add_anchor_token(T___thread);
10996 add_anchor_token(T_asm);
10997 add_anchor_token(T_auto);
10998 add_anchor_token(T_bool);
10999 add_anchor_token(T_break);
11000 add_anchor_token(T_case);
11001 add_anchor_token(T_char);
11002 add_anchor_token(T_class);
11003 add_anchor_token(T_const);
11004 add_anchor_token(T_const_cast);
11005 add_anchor_token(T_continue);
11006 add_anchor_token(T_default);
11007 add_anchor_token(T_delete);
11008 add_anchor_token(T_double);
11009 add_anchor_token(T_do);
11010 add_anchor_token(T_dynamic_cast);
11011 add_anchor_token(T_enum);
11012 add_anchor_token(T_extern);
11013 add_anchor_token(T_false);
11014 add_anchor_token(T_float);
11015 add_anchor_token(T_for);
11016 add_anchor_token(T_goto);
11017 add_anchor_token(T_if);
11018 add_anchor_token(T_inline);
11019 add_anchor_token(T_int);
11020 add_anchor_token(T_long);
11021 add_anchor_token(T_new);
11022 add_anchor_token(T_operator);
11023 add_anchor_token(T_register);
11024 add_anchor_token(T_reinterpret_cast);
11025 add_anchor_token(T_restrict);
11026 add_anchor_token(T_return);
11027 add_anchor_token(T_short);
11028 add_anchor_token(T_signed);
11029 add_anchor_token(T_sizeof);
11030 add_anchor_token(T_static);
11031 add_anchor_token(T_static_cast);
11032 add_anchor_token(T_struct);
11033 add_anchor_token(T_switch);
11034 add_anchor_token(T_template);
11035 add_anchor_token(T_this);
11036 add_anchor_token(T_throw);
11037 add_anchor_token(T_true);
11038 add_anchor_token(T_try);
11039 add_anchor_token(T_typedef);
11040 add_anchor_token(T_typeid);
11041 add_anchor_token(T_typename);
11042 add_anchor_token(T_typeof);
11043 add_anchor_token(T_union);
11044 add_anchor_token(T_unsigned);
11045 add_anchor_token(T_using);
11046 add_anchor_token(T_void);
11047 add_anchor_token(T_volatile);
11048 add_anchor_token(T_wchar_t);
11049 add_anchor_token(T_while);
11051 size_t const top = environment_top();
11052 scope_t *old_scope = scope_push(&statement->compound.scope);
11054 statement_t **anchor = &statement->compound.statements;
11055 bool only_decls_so_far = true;
11056 while (token.type != '}') {
11057 if (token.type == T_EOF) {
11058 errorf(&statement->base.source_position,
11059 "EOF while parsing compound statement");
11062 statement_t *sub_statement = intern_parse_statement();
11063 if (is_invalid_statement(sub_statement)) {
11064 /* an error occurred. if we are at an anchor, return */
11070 if (warning.declaration_after_statement) {
11071 if (sub_statement->kind != STATEMENT_DECLARATION) {
11072 only_decls_so_far = false;
11073 } else if (!only_decls_so_far) {
11074 warningf(&sub_statement->base.source_position,
11075 "ISO C90 forbids mixed declarations and code");
11079 *anchor = sub_statement;
11081 while (sub_statement->base.next != NULL)
11082 sub_statement = sub_statement->base.next;
11084 anchor = &sub_statement->base.next;
11088 /* look over all statements again to produce no effect warnings */
11089 if (warning.unused_value) {
11090 statement_t *sub_statement = statement->compound.statements;
11091 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
11092 if (sub_statement->kind != STATEMENT_EXPRESSION)
11094 /* don't emit a warning for the last expression in an expression
11095 * statement as it has always an effect */
11096 if (inside_expression_statement && sub_statement->base.next == NULL)
11099 expression_t *expression = sub_statement->expression.expression;
11100 if (!expression_has_effect(expression)) {
11101 warningf(&expression->base.source_position,
11102 "statement has no effect");
11108 rem_anchor_token(T_while);
11109 rem_anchor_token(T_wchar_t);
11110 rem_anchor_token(T_volatile);
11111 rem_anchor_token(T_void);
11112 rem_anchor_token(T_using);
11113 rem_anchor_token(T_unsigned);
11114 rem_anchor_token(T_union);
11115 rem_anchor_token(T_typeof);
11116 rem_anchor_token(T_typename);
11117 rem_anchor_token(T_typeid);
11118 rem_anchor_token(T_typedef);
11119 rem_anchor_token(T_try);
11120 rem_anchor_token(T_true);
11121 rem_anchor_token(T_throw);
11122 rem_anchor_token(T_this);
11123 rem_anchor_token(T_template);
11124 rem_anchor_token(T_switch);
11125 rem_anchor_token(T_struct);
11126 rem_anchor_token(T_static_cast);
11127 rem_anchor_token(T_static);
11128 rem_anchor_token(T_sizeof);
11129 rem_anchor_token(T_signed);
11130 rem_anchor_token(T_short);
11131 rem_anchor_token(T_return);
11132 rem_anchor_token(T_restrict);
11133 rem_anchor_token(T_reinterpret_cast);
11134 rem_anchor_token(T_register);
11135 rem_anchor_token(T_operator);
11136 rem_anchor_token(T_new);
11137 rem_anchor_token(T_long);
11138 rem_anchor_token(T_int);
11139 rem_anchor_token(T_inline);
11140 rem_anchor_token(T_if);
11141 rem_anchor_token(T_goto);
11142 rem_anchor_token(T_for);
11143 rem_anchor_token(T_float);
11144 rem_anchor_token(T_false);
11145 rem_anchor_token(T_extern);
11146 rem_anchor_token(T_enum);
11147 rem_anchor_token(T_dynamic_cast);
11148 rem_anchor_token(T_do);
11149 rem_anchor_token(T_double);
11150 rem_anchor_token(T_delete);
11151 rem_anchor_token(T_default);
11152 rem_anchor_token(T_continue);
11153 rem_anchor_token(T_const_cast);
11154 rem_anchor_token(T_const);
11155 rem_anchor_token(T_class);
11156 rem_anchor_token(T_char);
11157 rem_anchor_token(T_case);
11158 rem_anchor_token(T_break);
11159 rem_anchor_token(T_bool);
11160 rem_anchor_token(T_auto);
11161 rem_anchor_token(T_asm);
11162 rem_anchor_token(T___thread);
11163 rem_anchor_token(T___real__);
11164 rem_anchor_token(T___label__);
11165 rem_anchor_token(T___imag__);
11166 rem_anchor_token(T___func__);
11167 rem_anchor_token(T___extension__);
11168 rem_anchor_token(T___builtin_va_start);
11169 rem_anchor_token(T___attribute__);
11170 rem_anchor_token(T___alignof__);
11171 rem_anchor_token(T___PRETTY_FUNCTION__);
11172 rem_anchor_token(T___FUNCTION__);
11173 rem_anchor_token(T__Imaginary);
11174 rem_anchor_token(T__Complex);
11175 rem_anchor_token(T__Bool);
11176 rem_anchor_token(T_WIDE_STRING_LITERAL);
11177 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
11178 rem_anchor_token(T_STRING_LITERAL);
11179 rem_anchor_token(T_PLUSPLUS);
11180 rem_anchor_token(T_MINUSMINUS);
11181 rem_anchor_token(T_INTEGER);
11182 rem_anchor_token(T_IDENTIFIER);
11183 rem_anchor_token(T_FLOATINGPOINT);
11184 rem_anchor_token(T_COLONCOLON);
11185 rem_anchor_token(T_CHARACTER_CONSTANT);
11186 rem_anchor_token('~');
11187 rem_anchor_token('{');
11188 rem_anchor_token('-');
11189 rem_anchor_token('+');
11190 rem_anchor_token('*');
11191 rem_anchor_token('(');
11192 rem_anchor_token('&');
11193 rem_anchor_token('!');
11194 rem_anchor_token('}');
11195 assert(current_scope == &statement->compound.scope);
11196 scope_pop(old_scope);
11197 environment_pop_to(top);
11204 * Check for unused global static functions and variables
11206 static void check_unused_globals(void)
11208 if (!warning.unused_function && !warning.unused_variable)
11211 for (const entity_t *entity = file_scope->entities; entity != NULL;
11212 entity = entity->base.next) {
11213 if (!is_declaration(entity))
11216 const declaration_t *declaration = &entity->declaration;
11217 if (declaration->used ||
11218 declaration->modifiers & DM_UNUSED ||
11219 declaration->modifiers & DM_USED ||
11220 declaration->storage_class != STORAGE_CLASS_STATIC)
11223 type_t *const type = declaration->type;
11225 if (entity->kind == ENTITY_FUNCTION) {
11226 /* inhibit warning for static inline functions */
11227 if (entity->function.is_inline)
11230 s = entity->function.statement != NULL ? "defined" : "declared";
11235 warningf(&declaration->base.source_position, "'%#T' %s but not used",
11236 type, declaration->base.symbol, s);
11240 static void parse_global_asm(void)
11242 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
11245 expect('(', end_error);
11247 statement->asms.asm_text = parse_string_literals();
11248 statement->base.next = unit->global_asm;
11249 unit->global_asm = statement;
11251 expect(')', end_error);
11252 expect(';', end_error);
11257 static void parse_linkage_specification(void)
11260 assert(token.type == T_STRING_LITERAL);
11262 const char *linkage = parse_string_literals().begin;
11264 linkage_kind_t old_linkage = current_linkage;
11265 linkage_kind_t new_linkage;
11266 if (strcmp(linkage, "C") == 0) {
11267 new_linkage = LINKAGE_C;
11268 } else if (strcmp(linkage, "C++") == 0) {
11269 new_linkage = LINKAGE_CXX;
11271 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
11272 new_linkage = LINKAGE_INVALID;
11274 current_linkage = new_linkage;
11276 if (token.type == '{') {
11279 expect('}', end_error);
11285 assert(current_linkage == new_linkage);
11286 current_linkage = old_linkage;
11289 static void parse_external(void)
11291 switch (token.type) {
11292 DECLARATION_START_NO_EXTERN
11294 case T___extension__:
11295 /* tokens below are for implicit int */
11296 case '&': /* & x; -> int& x; (and error later, because C++ has no
11298 case '*': /* * x; -> int* x; */
11299 case '(': /* (x); -> int (x); */
11300 parse_external_declaration();
11304 if (look_ahead(1)->type == T_STRING_LITERAL) {
11305 parse_linkage_specification();
11307 parse_external_declaration();
11312 parse_global_asm();
11316 parse_namespace_definition();
11320 if (!strict_mode) {
11322 warningf(HERE, "stray ';' outside of function");
11329 errorf(HERE, "stray %K outside of function", &token);
11330 if (token.type == '(' || token.type == '{' || token.type == '[')
11331 eat_until_matching_token(token.type);
11337 static void parse_externals(void)
11339 add_anchor_token('}');
11340 add_anchor_token(T_EOF);
11343 unsigned char token_anchor_copy[T_LAST_TOKEN];
11344 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
11347 while (token.type != T_EOF && token.type != '}') {
11349 bool anchor_leak = false;
11350 for (int i = 0; i != T_LAST_TOKEN; ++i) {
11351 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
11353 errorf(HERE, "Leaked anchor token %k %d times", i, count);
11354 anchor_leak = true;
11357 if (in_gcc_extension) {
11358 errorf(HERE, "Leaked __extension__");
11359 anchor_leak = true;
11369 rem_anchor_token(T_EOF);
11370 rem_anchor_token('}');
11374 * Parse a translation unit.
11376 static void parse_translation_unit(void)
11378 add_anchor_token(T_EOF);
11383 if (token.type == T_EOF)
11386 errorf(HERE, "stray %K outside of function", &token);
11387 if (token.type == '(' || token.type == '{' || token.type == '[')
11388 eat_until_matching_token(token.type);
11396 * @return the translation unit or NULL if errors occurred.
11398 void start_parsing(void)
11400 environment_stack = NEW_ARR_F(stack_entry_t, 0);
11401 label_stack = NEW_ARR_F(stack_entry_t, 0);
11402 diagnostic_count = 0;
11406 type_set_output(stderr);
11407 ast_set_output(stderr);
11409 assert(unit == NULL);
11410 unit = allocate_ast_zero(sizeof(unit[0]));
11412 assert(file_scope == NULL);
11413 file_scope = &unit->scope;
11415 assert(current_scope == NULL);
11416 scope_push(&unit->scope);
11418 create_gnu_builtins();
11420 create_microsoft_intrinsics();
11423 translation_unit_t *finish_parsing(void)
11425 assert(current_scope == &unit->scope);
11428 assert(file_scope == &unit->scope);
11429 check_unused_globals();
11432 DEL_ARR_F(environment_stack);
11433 DEL_ARR_F(label_stack);
11435 translation_unit_t *result = unit;
11440 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
11441 * are given length one. */
11442 static void complete_incomplete_arrays(void)
11444 size_t n = ARR_LEN(incomplete_arrays);
11445 for (size_t i = 0; i != n; ++i) {
11446 declaration_t *const decl = incomplete_arrays[i];
11447 type_t *const orig_type = decl->type;
11448 type_t *const type = skip_typeref(orig_type);
11450 if (!is_type_incomplete(type))
11453 if (warning.other) {
11454 warningf(&decl->base.source_position,
11455 "array '%#T' assumed to have one element",
11456 orig_type, decl->base.symbol);
11459 type_t *const new_type = duplicate_type(type);
11460 new_type->array.size_constant = true;
11461 new_type->array.has_implicit_size = true;
11462 new_type->array.size = 1;
11464 type_t *const result = identify_new_type(new_type);
11466 decl->type = result;
11472 lookahead_bufpos = 0;
11473 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
11476 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
11477 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
11478 parse_translation_unit();
11479 complete_incomplete_arrays();
11480 DEL_ARR_F(incomplete_arrays);
11481 incomplete_arrays = NULL;
11485 * create a builtin function.
11487 static entity_t *create_builtin_function(builtin_kind_t kind, const char *name, type_t *function_type)
11489 symbol_t *symbol = symbol_table_insert(name);
11490 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
11491 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
11492 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
11493 entity->declaration.type = function_type;
11494 entity->declaration.implicit = true;
11495 entity->base.symbol = symbol;
11496 entity->base.source_position = builtin_source_position;
11498 entity->function.btk = kind;
11500 record_entity(entity, /*is_definition=*/false);
11506 * Create predefined gnu builtins.
11508 static void create_gnu_builtins(void)
11510 #define GNU_BUILTIN(a, b) create_builtin_function(bk_gnu_builtin_##a, "__builtin_" #a, b)
11512 GNU_BUILTIN(alloca, make_function_1_type(type_void_ptr, type_size_t));
11513 GNU_BUILTIN(huge_val, make_function_0_type(type_double));
11514 GNU_BUILTIN(inf, make_function_0_type(type_double));
11515 GNU_BUILTIN(inff, make_function_0_type(type_float));
11516 GNU_BUILTIN(infl, make_function_0_type(type_long_double));
11517 GNU_BUILTIN(nan, make_function_1_type(type_double, type_char_ptr));
11518 GNU_BUILTIN(nanf, make_function_1_type(type_float, type_char_ptr));
11519 GNU_BUILTIN(nanl, make_function_1_type(type_long_double, type_char_ptr));
11520 GNU_BUILTIN(va_end, make_function_1_type(type_void, type_valist));
11521 GNU_BUILTIN(expect, make_function_2_type(type_long, type_long, type_long));
11522 GNU_BUILTIN(return_address, make_function_1_type(type_void_ptr, type_unsigned_int));
11523 GNU_BUILTIN(frame_address, make_function_1_type(type_void_ptr, type_unsigned_int));
11524 GNU_BUILTIN(ffs, make_function_1_type(type_int, type_unsigned_int));
11525 GNU_BUILTIN(clz, make_function_1_type(type_int, type_unsigned_int));
11526 GNU_BUILTIN(ctz, make_function_1_type(type_int, type_unsigned_int));
11527 GNU_BUILTIN(popcount, make_function_1_type(type_int, type_unsigned_int));
11528 GNU_BUILTIN(parity, make_function_1_type(type_int, type_unsigned_int));
11529 GNU_BUILTIN(prefetch, make_function_1_type_variadic(type_float, type_void_ptr));
11530 GNU_BUILTIN(trap, make_function_0_type_noreturn(type_void));
11536 * Create predefined MS intrinsics.
11538 static void create_microsoft_intrinsics(void)
11540 #define MS_BUILTIN(a, b) create_builtin_function(bk_ms##a, #a, b)
11542 /* intrinsics for all architectures */
11543 MS_BUILTIN(_rotl, make_function_2_type(type_unsigned_int, type_unsigned_int, type_int));
11544 MS_BUILTIN(_rotr, make_function_2_type(type_unsigned_int, type_unsigned_int, type_int));
11545 MS_BUILTIN(_rotl64, make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
11546 MS_BUILTIN(_rotr64, make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
11547 MS_BUILTIN(_byteswap_ushort, make_function_1_type(type_unsigned_short, type_unsigned_short));
11548 MS_BUILTIN(_byteswap_ulong, make_function_1_type(type_unsigned_long, type_unsigned_long));
11549 MS_BUILTIN(_byteswap_uint64, make_function_1_type(type_unsigned_int64, type_unsigned_int64));
11551 MS_BUILTIN(__debugbreak, make_function_0_type(type_void));
11552 MS_BUILTIN(_ReturnAddress, make_function_0_type(type_void_ptr));
11553 MS_BUILTIN(_AddressOfReturnAddress, make_function_0_type(type_void_ptr));
11554 MS_BUILTIN(__popcount, make_function_1_type(type_unsigned_int, type_unsigned_int));
11557 MS_BUILTIN(_enable, make_function_0_type(type_void));
11558 MS_BUILTIN(_disable, make_function_0_type(type_void));
11559 MS_BUILTIN(__inbyte, make_function_1_type(type_unsigned_char, type_unsigned_short));
11560 MS_BUILTIN(__inword, make_function_1_type(type_unsigned_short, type_unsigned_short));
11561 MS_BUILTIN(__indword, make_function_1_type(type_unsigned_long, type_unsigned_short));
11562 MS_BUILTIN(__outbyte, make_function_2_type(type_void, type_unsigned_short, type_unsigned_char));
11563 MS_BUILTIN(__outword, make_function_2_type(type_void, type_unsigned_short, type_unsigned_short));
11564 MS_BUILTIN(__outdword, make_function_2_type(type_void, type_unsigned_short, type_unsigned_long));
11565 MS_BUILTIN(__ud2, make_function_0_type_noreturn(type_void));
11566 MS_BUILTIN(_BitScanForward, make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11567 MS_BUILTIN(_BitScanReverse, make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11568 MS_BUILTIN(_InterlockedExchange, make_function_2_type(type_long, type_long_ptr, type_long));
11569 MS_BUILTIN(_InterlockedExchange64, make_function_2_type(type_int64, type_int64_ptr, type_int64));
11571 if (machine_size <= 32) {
11572 MS_BUILTIN(__readeflags, make_function_0_type(type_unsigned_int));
11573 MS_BUILTIN(__writeeflags, make_function_1_type(type_void, type_unsigned_int));
11575 MS_BUILTIN(__readeflags, make_function_0_type(type_unsigned_int64));
11576 MS_BUILTIN(__writeeflags, make_function_1_type(type_void, type_unsigned_int64));
11583 * Initialize the parser.
11585 void init_parser(void)
11587 sym_anonymous = symbol_table_insert("<anonymous>");
11589 if (c_mode & _MS) {
11590 /* add predefined symbols for extended-decl-modifier */
11591 sym_align = symbol_table_insert("align");
11592 sym_allocate = symbol_table_insert("allocate");
11593 sym_dllimport = symbol_table_insert("dllimport");
11594 sym_dllexport = symbol_table_insert("dllexport");
11595 sym_naked = symbol_table_insert("naked");
11596 sym_noinline = symbol_table_insert("noinline");
11597 sym_returns_twice = symbol_table_insert("returns_twice");
11598 sym_noreturn = symbol_table_insert("noreturn");
11599 sym_nothrow = symbol_table_insert("nothrow");
11600 sym_novtable = symbol_table_insert("novtable");
11601 sym_property = symbol_table_insert("property");
11602 sym_get = symbol_table_insert("get");
11603 sym_put = symbol_table_insert("put");
11604 sym_selectany = symbol_table_insert("selectany");
11605 sym_thread = symbol_table_insert("thread");
11606 sym_uuid = symbol_table_insert("uuid");
11607 sym_deprecated = symbol_table_insert("deprecated");
11608 sym_restrict = symbol_table_insert("restrict");
11609 sym_noalias = symbol_table_insert("noalias");
11611 memset(token_anchor_set, 0, sizeof(token_anchor_set));
11613 init_expression_parsers();
11614 obstack_init(&temp_obst);
11616 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11617 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11621 * Terminate the parser.
11623 void exit_parser(void)
11625 obstack_free(&temp_obst, NULL);