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 2
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 have_arguments; /**< True, if this attribute has arguments. */
68 atomic_type_kind_t akind;
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;
102 * Capture a MS __base extension.
104 typedef struct based_spec_t {
105 source_position_t source_position;
106 variable_t *base_variable;
109 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
111 /** The current token. */
112 static token_t token;
113 /** The lookahead ring-buffer. */
114 static token_t lookahead_buffer[MAX_LOOKAHEAD];
115 /** Position of the next token in the lookahead buffer. */
116 static int lookahead_bufpos;
117 static stack_entry_t *environment_stack = NULL;
118 static stack_entry_t *label_stack = NULL;
119 static scope_t *file_scope = NULL;
120 static scope_t *current_scope = NULL;
121 /** Point to the current function declaration if inside a function. */
122 static function_t *current_function = NULL;
123 static entity_t *current_init_decl = NULL;
124 static switch_statement_t *current_switch = NULL;
125 static statement_t *current_loop = NULL;
126 static statement_t *current_parent = NULL;
127 static ms_try_statement_t *current_try = NULL;
128 static linkage_kind_t current_linkage = LINKAGE_INVALID;
129 static goto_statement_t *goto_first = NULL;
130 static goto_statement_t **goto_anchor = NULL;
131 static label_statement_t *label_first = NULL;
132 static label_statement_t **label_anchor = NULL;
133 /** current translation unit. */
134 static translation_unit_t *unit = NULL;
135 /** true if we are in a type property context (evaluation only for type. */
136 static bool in_type_prop = false;
137 /** true in we are in a __extension__ context. */
138 static bool in_gcc_extension = false;
139 static struct obstack temp_obst;
140 static entity_t *anonymous_entity;
143 #define PUSH_PARENT(stmt) \
144 statement_t *const prev_parent = current_parent; \
145 ((void)(current_parent = (stmt)))
146 #define POP_PARENT ((void)(current_parent = prev_parent))
148 /** special symbol used for anonymous entities. */
149 static const symbol_t *sym_anonymous = NULL;
151 /* symbols for Microsoft extended-decl-modifier */
152 static const symbol_t *sym_align = NULL;
153 static const symbol_t *sym_allocate = NULL;
154 static const symbol_t *sym_dllimport = NULL;
155 static const symbol_t *sym_dllexport = NULL;
156 static const symbol_t *sym_naked = NULL;
157 static const symbol_t *sym_noinline = NULL;
158 static const symbol_t *sym_noreturn = NULL;
159 static const symbol_t *sym_nothrow = NULL;
160 static const symbol_t *sym_novtable = NULL;
161 static const symbol_t *sym_property = NULL;
162 static const symbol_t *sym_get = NULL;
163 static const symbol_t *sym_put = NULL;
164 static const symbol_t *sym_selectany = NULL;
165 static const symbol_t *sym_thread = NULL;
166 static const symbol_t *sym_uuid = NULL;
167 static const symbol_t *sym_deprecated = NULL;
168 static const symbol_t *sym_restrict = NULL;
169 static const symbol_t *sym_noalias = NULL;
171 /** The token anchor set */
172 static unsigned char token_anchor_set[T_LAST_TOKEN];
174 /** The current source position. */
175 #define HERE (&token.source_position)
177 /** true if we are in GCC mode. */
178 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
180 static type_t *type_valist;
182 static statement_t *parse_compound_statement(bool inside_expression_statement);
183 static statement_t *parse_statement(void);
185 static expression_t *parse_sub_expression(precedence_t);
186 static expression_t *parse_expression(void);
187 static type_t *parse_typename(void);
188 static void parse_externals(void);
189 static void parse_external(void);
191 static void parse_compound_type_entries(compound_t *compound_declaration);
193 typedef enum declarator_flags_t {
195 DECL_MAY_BE_ABSTRACT = 1U << 0,
196 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
197 DECL_IS_PARAMETER = 1U << 2
198 } declarator_flags_t;
200 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
201 declarator_flags_t flags);
203 static entity_t *record_entity(entity_t *entity, bool is_definition);
205 static void semantic_comparison(binary_expression_t *expression);
207 #define STORAGE_CLASSES \
208 STORAGE_CLASSES_NO_EXTERN \
211 #define STORAGE_CLASSES_NO_EXTERN \
218 #define TYPE_QUALIFIERS \
223 case T__forceinline: \
224 case T___attribute__:
226 #define COMPLEX_SPECIFIERS \
228 #define IMAGINARY_SPECIFIERS \
231 #define TYPE_SPECIFIERS \
233 case T___builtin_va_list: \
252 #define DECLARATION_START \
257 #define DECLARATION_START_NO_EXTERN \
258 STORAGE_CLASSES_NO_EXTERN \
262 #define TYPENAME_START \
266 #define EXPRESSION_START \
275 case T_CHARACTER_CONSTANT: \
276 case T_FLOATINGPOINT: \
280 case T_STRING_LITERAL: \
281 case T_WIDE_CHARACTER_CONSTANT: \
282 case T_WIDE_STRING_LITERAL: \
283 case T___FUNCDNAME__: \
284 case T___FUNCSIG__: \
285 case T___FUNCTION__: \
286 case T___PRETTY_FUNCTION__: \
287 case T___alignof__: \
288 case T___builtin_alloca: \
289 case T___builtin_classify_type: \
290 case T___builtin_constant_p: \
291 case T___builtin_expect: \
292 case T___builtin_huge_val: \
293 case T___builtin_inf: \
294 case T___builtin_inff: \
295 case T___builtin_infl: \
296 case T___builtin_isgreater: \
297 case T___builtin_isgreaterequal: \
298 case T___builtin_isless: \
299 case T___builtin_islessequal: \
300 case T___builtin_islessgreater: \
301 case T___builtin_isunordered: \
302 case T___builtin_nan: \
303 case T___builtin_nanf: \
304 case T___builtin_nanl: \
305 case T___builtin_offsetof: \
306 case T___builtin_prefetch: \
307 case T___builtin_va_arg: \
308 case T___builtin_va_end: \
309 case T___builtin_va_start: \
320 * Allocate an AST node with given size and
321 * initialize all fields with zero.
323 static void *allocate_ast_zero(size_t size)
325 void *res = allocate_ast(size);
326 memset(res, 0, size);
330 static size_t get_entity_struct_size(entity_kind_t kind)
332 static const size_t sizes[] = {
333 [ENTITY_VARIABLE] = sizeof(variable_t),
334 [ENTITY_COMPOUND_MEMBER] = sizeof(variable_t),
335 [ENTITY_FUNCTION] = sizeof(function_t),
336 [ENTITY_TYPEDEF] = sizeof(typedef_t),
337 [ENTITY_STRUCT] = sizeof(compound_t),
338 [ENTITY_UNION] = sizeof(compound_t),
339 [ENTITY_ENUM] = sizeof(enum_t),
340 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
341 [ENTITY_LABEL] = sizeof(label_t),
342 [ENTITY_LOCAL_LABEL] = sizeof(label_t),
343 [ENTITY_NAMESPACE] = sizeof(namespace_t)
345 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
346 assert(sizes[kind] != 0);
350 static entity_t *allocate_entity_zero(entity_kind_t kind)
352 size_t size = get_entity_struct_size(kind);
353 entity_t *entity = allocate_ast_zero(size);
359 * Returns the size of a statement node.
361 * @param kind the statement kind
363 static size_t get_statement_struct_size(statement_kind_t kind)
365 static const size_t sizes[] = {
366 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
367 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
368 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
369 [STATEMENT_RETURN] = sizeof(return_statement_t),
370 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
371 [STATEMENT_LOCAL_LABEL] = sizeof(local_label_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 < sizeof(sizes) / sizeof(sizes[0]));
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_SYMBOL] = sizeof(builtin_symbol_expression_t),
420 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
421 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
422 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
423 [EXPR_VA_START] = sizeof(va_start_expression_t),
424 [EXPR_VA_ARG] = sizeof(va_arg_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 < sizeof(sizes) / sizeof(sizes[0]));
435 assert(sizes[kind] != 0);
440 * Allocate a statement node of given kind and initialize all
443 static statement_t *allocate_statement_zero(statement_kind_t kind)
445 size_t size = get_statement_struct_size(kind);
446 statement_t *res = allocate_ast_zero(size);
448 res->base.kind = kind;
449 res->base.parent = current_parent;
450 res->base.source_position = token.source_position;
455 * Allocate an expression node of given kind and initialize all
458 static expression_t *allocate_expression_zero(expression_kind_t kind)
460 size_t size = get_expression_struct_size(kind);
461 expression_t *res = allocate_ast_zero(size);
463 res->base.kind = kind;
464 res->base.type = type_error_type;
465 res->base.source_position = token.source_position;
470 * Creates a new invalid expression.
472 static expression_t *create_invalid_expression(void)
474 return allocate_expression_zero(EXPR_INVALID);
478 * Creates a new invalid statement.
480 static statement_t *create_invalid_statement(void)
482 return allocate_statement_zero(STATEMENT_INVALID);
486 * Allocate a new empty statement.
488 static statement_t *create_empty_statement(void)
490 return allocate_statement_zero(STATEMENT_EMPTY);
494 * Returns the size of a type node.
496 * @param kind the type kind
498 static size_t get_type_struct_size(type_kind_t kind)
500 static const size_t sizes[] = {
501 [TYPE_ATOMIC] = sizeof(atomic_type_t),
502 [TYPE_COMPLEX] = sizeof(complex_type_t),
503 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
504 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
505 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
506 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
507 [TYPE_ENUM] = sizeof(enum_type_t),
508 [TYPE_FUNCTION] = sizeof(function_type_t),
509 [TYPE_POINTER] = sizeof(pointer_type_t),
510 [TYPE_ARRAY] = sizeof(array_type_t),
511 [TYPE_BUILTIN] = sizeof(builtin_type_t),
512 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
513 [TYPE_TYPEOF] = sizeof(typeof_type_t),
515 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
516 assert(kind <= TYPE_TYPEOF);
517 assert(sizes[kind] != 0);
522 * Allocate a type node of given kind and initialize all
525 * @param kind type kind to allocate
527 static type_t *allocate_type_zero(type_kind_t kind)
529 size_t size = get_type_struct_size(kind);
530 type_t *res = obstack_alloc(type_obst, size);
531 memset(res, 0, size);
532 res->base.kind = kind;
538 * Returns the size of an initializer node.
540 * @param kind the initializer kind
542 static size_t get_initializer_size(initializer_kind_t kind)
544 static const size_t sizes[] = {
545 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
546 [INITIALIZER_STRING] = sizeof(initializer_string_t),
547 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
548 [INITIALIZER_LIST] = sizeof(initializer_list_t),
549 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
551 assert(kind < sizeof(sizes) / sizeof(*sizes));
552 assert(sizes[kind] != 0);
557 * Allocate an initializer node of given kind and initialize all
560 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
562 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
569 * Free a type from the type obstack.
571 static void free_type(void *type)
573 obstack_free(type_obst, type);
577 * Returns the index of the top element of the environment stack.
579 static size_t environment_top(void)
581 return ARR_LEN(environment_stack);
585 * Returns the index of the top element of the global label stack.
587 static size_t label_top(void)
589 return ARR_LEN(label_stack);
593 * Return the next token.
595 static inline void next_token(void)
597 token = lookahead_buffer[lookahead_bufpos];
598 lookahead_buffer[lookahead_bufpos] = lexer_token;
601 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
604 print_token(stderr, &token);
605 fprintf(stderr, "\n");
610 * Return the next token with a given lookahead.
612 static inline const token_t *look_ahead(int num)
614 assert(num > 0 && num <= MAX_LOOKAHEAD);
615 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
616 return &lookahead_buffer[pos];
620 * Adds a token to the token anchor set (a multi-set).
622 static void add_anchor_token(int token_type)
624 assert(0 <= token_type && token_type < T_LAST_TOKEN);
625 ++token_anchor_set[token_type];
628 static int save_and_reset_anchor_state(int token_type)
630 assert(0 <= token_type && token_type < T_LAST_TOKEN);
631 int count = token_anchor_set[token_type];
632 token_anchor_set[token_type] = 0;
636 static void restore_anchor_state(int token_type, int count)
638 assert(0 <= token_type && token_type < T_LAST_TOKEN);
639 token_anchor_set[token_type] = count;
643 * Remove a token from the token anchor set (a multi-set).
645 static void rem_anchor_token(int token_type)
647 assert(0 <= token_type && token_type < T_LAST_TOKEN);
648 assert(token_anchor_set[token_type] != 0);
649 --token_anchor_set[token_type];
652 static bool at_anchor(void)
656 return token_anchor_set[token.type];
660 * Eat tokens until a matching token is found.
662 static void eat_until_matching_token(int type)
666 case '(': end_token = ')'; break;
667 case '{': end_token = '}'; break;
668 case '[': end_token = ']'; break;
669 default: end_token = type; break;
672 unsigned parenthesis_count = 0;
673 unsigned brace_count = 0;
674 unsigned bracket_count = 0;
675 while (token.type != end_token ||
676 parenthesis_count != 0 ||
678 bracket_count != 0) {
679 switch (token.type) {
681 case '(': ++parenthesis_count; break;
682 case '{': ++brace_count; break;
683 case '[': ++bracket_count; break;
686 if (parenthesis_count > 0)
696 if (bracket_count > 0)
699 if (token.type == end_token &&
700 parenthesis_count == 0 &&
714 * Eat input tokens until an anchor is found.
716 static void eat_until_anchor(void)
718 while (token_anchor_set[token.type] == 0) {
719 if (token.type == '(' || token.type == '{' || token.type == '[')
720 eat_until_matching_token(token.type);
725 static void eat_block(void)
727 eat_until_matching_token('{');
728 if (token.type == '}')
732 #define eat(token_type) do { assert(token.type == (token_type)); next_token(); } while (0)
735 * Report a parse error because an expected token was not found.
738 #if defined __GNUC__ && __GNUC__ >= 4
739 __attribute__((sentinel))
741 void parse_error_expected(const char *message, ...)
743 if (message != NULL) {
744 errorf(HERE, "%s", message);
747 va_start(ap, message);
748 errorf(HERE, "got '%K', expected %#k", &token, &ap, ", ");
753 * Report an incompatible type.
755 static void type_error_incompatible(const char *msg,
756 const source_position_t *source_position, type_t *type1, type_t *type2)
758 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
763 * Expect the the current token is the expected token.
764 * If not, generate an error, eat the current statement,
765 * and goto the end_error label.
767 #define expect(expected) \
769 if (UNLIKELY(token.type != (expected))) { \
770 parse_error_expected(NULL, (expected), NULL); \
771 add_anchor_token(expected); \
772 eat_until_anchor(); \
773 if (token.type == expected) \
775 rem_anchor_token(expected); \
781 static scope_t *scope_push(scope_t *new_scope)
783 if (current_scope != NULL) {
784 new_scope->depth = current_scope->depth + 1;
787 scope_t *old_scope = current_scope;
788 current_scope = new_scope;
792 static void scope_pop(scope_t *old_scope)
794 current_scope = old_scope;
798 * Search an entity by its symbol in a given namespace.
800 static entity_t *get_entity(const symbol_t *const symbol,
801 namespace_tag_t namespc)
803 entity_t *entity = symbol->entity;
804 for (; entity != NULL; entity = entity->base.symbol_next) {
805 if (entity->base.namespc == namespc)
813 * pushs an entity on the environment stack and links the corresponding symbol
816 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
818 symbol_t *symbol = entity->base.symbol;
819 entity_namespace_t namespc = entity->base.namespc;
820 assert(namespc != NAMESPACE_INVALID);
822 /* replace/add entity into entity list of the symbol */
825 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
830 /* replace an entry? */
831 if (iter->base.namespc == namespc) {
832 entity->base.symbol_next = iter->base.symbol_next;
838 /* remember old declaration */
840 entry.symbol = symbol;
841 entry.old_entity = iter;
842 entry.namespc = namespc;
843 ARR_APP1(stack_entry_t, *stack_ptr, entry);
847 * Push an entity on the environment stack.
849 static void environment_push(entity_t *entity)
851 assert(entity->base.source_position.input_name != NULL);
852 assert(entity->base.parent_scope != NULL);
853 stack_push(&environment_stack, entity);
857 * Push a declaration on the global label stack.
859 * @param declaration the declaration
861 static void label_push(entity_t *label)
863 /* we abuse the parameters scope as parent for the labels */
864 label->base.parent_scope = ¤t_function->parameters;
865 stack_push(&label_stack, label);
869 * pops symbols from the environment stack until @p new_top is the top element
871 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
873 stack_entry_t *stack = *stack_ptr;
874 size_t top = ARR_LEN(stack);
877 assert(new_top <= top);
881 for (i = top; i > new_top; --i) {
882 stack_entry_t *entry = &stack[i - 1];
884 entity_t *old_entity = entry->old_entity;
885 symbol_t *symbol = entry->symbol;
886 entity_namespace_t namespc = entry->namespc;
888 /* replace with old_entity/remove */
891 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
893 assert(iter != NULL);
894 /* replace an entry? */
895 if (iter->base.namespc == namespc)
899 /* restore definition from outer scopes (if there was one) */
900 if (old_entity != NULL) {
901 old_entity->base.symbol_next = iter->base.symbol_next;
902 *anchor = old_entity;
904 /* remove entry from list */
905 *anchor = iter->base.symbol_next;
909 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
913 * Pop all entries from the environment stack until the new_top
916 * @param new_top the new stack top
918 static void environment_pop_to(size_t new_top)
920 stack_pop_to(&environment_stack, new_top);
924 * Pop all entries from the global label stack until the new_top
927 * @param new_top the new stack top
929 static void label_pop_to(size_t new_top)
931 stack_pop_to(&label_stack, new_top);
934 static int get_akind_rank(atomic_type_kind_t akind)
939 static int get_rank(const type_t *type)
941 assert(!is_typeref(type));
942 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
943 * and esp. footnote 108). However we can't fold constants (yet), so we
944 * can't decide whether unsigned int is possible, while int always works.
945 * (unsigned int would be preferable when possible... for stuff like
946 * struct { enum { ... } bla : 4; } ) */
947 if (type->kind == TYPE_ENUM)
948 return get_akind_rank(ATOMIC_TYPE_INT);
950 assert(type->kind == TYPE_ATOMIC);
951 return get_akind_rank(type->atomic.akind);
954 static type_t *promote_integer(type_t *type)
956 if (type->kind == TYPE_BITFIELD)
957 type = type->bitfield.base_type;
959 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
966 * Create a cast expression.
968 * @param expression the expression to cast
969 * @param dest_type the destination type
971 static expression_t *create_cast_expression(expression_t *expression,
974 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
976 cast->unary.value = expression;
977 cast->base.type = dest_type;
983 * Check if a given expression represents the 0 pointer constant.
985 static bool is_null_pointer_constant(const expression_t *expression)
987 /* skip void* cast */
988 if (expression->kind == EXPR_UNARY_CAST
989 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
990 expression = expression->unary.value;
993 /* TODO: not correct yet, should be any constant integer expression
994 * which evaluates to 0 */
995 if (expression->kind != EXPR_CONST)
998 type_t *const type = skip_typeref(expression->base.type);
999 if (!is_type_integer(type))
1002 return expression->conste.v.int_value == 0;
1006 * Create an implicit cast expression.
1008 * @param expression the expression to cast
1009 * @param dest_type the destination type
1011 static expression_t *create_implicit_cast(expression_t *expression,
1014 type_t *const source_type = expression->base.type;
1016 if (source_type == dest_type)
1019 return create_cast_expression(expression, dest_type);
1022 typedef enum assign_error_t {
1024 ASSIGN_ERROR_INCOMPATIBLE,
1025 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1026 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1027 ASSIGN_WARNING_POINTER_FROM_INT,
1028 ASSIGN_WARNING_INT_FROM_POINTER
1031 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1032 const expression_t *const right,
1033 const char *context,
1034 const source_position_t *source_position)
1036 type_t *const orig_type_right = right->base.type;
1037 type_t *const type_left = skip_typeref(orig_type_left);
1038 type_t *const type_right = skip_typeref(orig_type_right);
1041 case ASSIGN_SUCCESS:
1043 case ASSIGN_ERROR_INCOMPATIBLE:
1044 errorf(source_position,
1045 "destination type '%T' in %s is incompatible with type '%T'",
1046 orig_type_left, context, orig_type_right);
1049 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1050 if (warning.other) {
1051 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1052 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1054 /* the left type has all qualifiers from the right type */
1055 unsigned missing_qualifiers
1056 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1057 warningf(source_position,
1058 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1059 orig_type_left, context, orig_type_right, missing_qualifiers);
1064 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1065 if (warning.other) {
1066 warningf(source_position,
1067 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1068 orig_type_left, context, right, orig_type_right);
1072 case ASSIGN_WARNING_POINTER_FROM_INT:
1073 if (warning.other) {
1074 warningf(source_position,
1075 "%s makes pointer '%T' from integer '%T' without a cast",
1076 context, orig_type_left, orig_type_right);
1080 case ASSIGN_WARNING_INT_FROM_POINTER:
1081 if (warning.other) {
1082 warningf(source_position,
1083 "%s makes integer '%T' from pointer '%T' without a cast",
1084 context, orig_type_left, orig_type_right);
1089 panic("invalid error value");
1093 /** Implements the rules from § 6.5.16.1 */
1094 static assign_error_t semantic_assign(type_t *orig_type_left,
1095 const expression_t *const right)
1097 type_t *const orig_type_right = right->base.type;
1098 type_t *const type_left = skip_typeref(orig_type_left);
1099 type_t *const type_right = skip_typeref(orig_type_right);
1101 if (is_type_pointer(type_left)) {
1102 if (is_null_pointer_constant(right)) {
1103 return ASSIGN_SUCCESS;
1104 } else if (is_type_pointer(type_right)) {
1105 type_t *points_to_left
1106 = skip_typeref(type_left->pointer.points_to);
1107 type_t *points_to_right
1108 = skip_typeref(type_right->pointer.points_to);
1109 assign_error_t res = ASSIGN_SUCCESS;
1111 /* the left type has all qualifiers from the right type */
1112 unsigned missing_qualifiers
1113 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1114 if (missing_qualifiers != 0) {
1115 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1118 points_to_left = get_unqualified_type(points_to_left);
1119 points_to_right = get_unqualified_type(points_to_right);
1121 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1124 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1125 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1126 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1129 if (!types_compatible(points_to_left, points_to_right)) {
1130 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1134 } else if (is_type_integer(type_right)) {
1135 return ASSIGN_WARNING_POINTER_FROM_INT;
1137 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1138 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1139 && is_type_pointer(type_right))) {
1140 return ASSIGN_SUCCESS;
1141 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1142 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1143 type_t *const unqual_type_left = get_unqualified_type(type_left);
1144 type_t *const unqual_type_right = get_unqualified_type(type_right);
1145 if (types_compatible(unqual_type_left, unqual_type_right)) {
1146 return ASSIGN_SUCCESS;
1148 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1149 return ASSIGN_WARNING_INT_FROM_POINTER;
1152 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1153 return ASSIGN_SUCCESS;
1155 return ASSIGN_ERROR_INCOMPATIBLE;
1158 static expression_t *parse_constant_expression(void)
1160 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1162 if (!is_constant_expression(result)) {
1163 errorf(&result->base.source_position,
1164 "expression '%E' is not constant\n", result);
1170 static expression_t *parse_assignment_expression(void)
1172 return parse_sub_expression(PREC_ASSIGNMENT);
1175 static string_t parse_string_literals(void)
1177 assert(token.type == T_STRING_LITERAL);
1178 string_t result = token.v.string;
1182 while (token.type == T_STRING_LITERAL) {
1183 result = concat_strings(&result, &token.v.string);
1190 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1191 [GNU_AK_CONST] = "const",
1192 [GNU_AK_VOLATILE] = "volatile",
1193 [GNU_AK_CDECL] = "cdecl",
1194 [GNU_AK_STDCALL] = "stdcall",
1195 [GNU_AK_FASTCALL] = "fastcall",
1196 [GNU_AK_DEPRECATED] = "deprecated",
1197 [GNU_AK_NOINLINE] = "noinline",
1198 [GNU_AK_NORETURN] = "noreturn",
1199 [GNU_AK_NAKED] = "naked",
1200 [GNU_AK_PURE] = "pure",
1201 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1202 [GNU_AK_MALLOC] = "malloc",
1203 [GNU_AK_WEAK] = "weak",
1204 [GNU_AK_CONSTRUCTOR] = "constructor",
1205 [GNU_AK_DESTRUCTOR] = "destructor",
1206 [GNU_AK_NOTHROW] = "nothrow",
1207 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1208 [GNU_AK_COMMON] = "common",
1209 [GNU_AK_NOCOMMON] = "nocommon",
1210 [GNU_AK_PACKED] = "packed",
1211 [GNU_AK_SHARED] = "shared",
1212 [GNU_AK_NOTSHARED] = "notshared",
1213 [GNU_AK_USED] = "used",
1214 [GNU_AK_UNUSED] = "unused",
1215 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1216 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1217 [GNU_AK_LONGCALL] = "longcall",
1218 [GNU_AK_SHORTCALL] = "shortcall",
1219 [GNU_AK_LONG_CALL] = "long_call",
1220 [GNU_AK_SHORT_CALL] = "short_call",
1221 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1222 [GNU_AK_INTERRUPT] = "interrupt",
1223 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1224 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1225 [GNU_AK_NESTING] = "nesting",
1226 [GNU_AK_NEAR] = "near",
1227 [GNU_AK_FAR] = "far",
1228 [GNU_AK_SIGNAL] = "signal",
1229 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1230 [GNU_AK_TINY_DATA] = "tiny_data",
1231 [GNU_AK_SAVEALL] = "saveall",
1232 [GNU_AK_FLATTEN] = "flatten",
1233 [GNU_AK_SSEREGPARM] = "sseregparm",
1234 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1235 [GNU_AK_RETURN_TWICE] = "return_twice",
1236 [GNU_AK_MAY_ALIAS] = "may_alias",
1237 [GNU_AK_MS_STRUCT] = "ms_struct",
1238 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1239 [GNU_AK_DLLIMPORT] = "dllimport",
1240 [GNU_AK_DLLEXPORT] = "dllexport",
1241 [GNU_AK_ALIGNED] = "aligned",
1242 [GNU_AK_ALIAS] = "alias",
1243 [GNU_AK_SECTION] = "section",
1244 [GNU_AK_FORMAT] = "format",
1245 [GNU_AK_FORMAT_ARG] = "format_arg",
1246 [GNU_AK_WEAKREF] = "weakref",
1247 [GNU_AK_NONNULL] = "nonnull",
1248 [GNU_AK_TLS_MODEL] = "tls_model",
1249 [GNU_AK_VISIBILITY] = "visibility",
1250 [GNU_AK_REGPARM] = "regparm",
1251 [GNU_AK_MODE] = "mode",
1252 [GNU_AK_MODEL] = "model",
1253 [GNU_AK_TRAP_EXIT] = "trap_exit",
1254 [GNU_AK_SP_SWITCH] = "sp_switch",
1255 [GNU_AK_SENTINEL] = "sentinel"
1259 * compare two string, ignoring double underscores on the second.
1261 static int strcmp_underscore(const char *s1, const char *s2)
1263 if (s2[0] == '_' && s2[1] == '_') {
1264 size_t len2 = strlen(s2);
1265 size_t len1 = strlen(s1);
1266 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1267 return strncmp(s1, s2+2, len2-4);
1271 return strcmp(s1, s2);
1275 * Allocate a new gnu temporal attribute.
1277 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1279 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1280 attribute->kind = kind;
1281 attribute->next = NULL;
1282 attribute->invalid = false;
1283 attribute->have_arguments = false;
1289 * parse one constant expression argument.
1291 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1293 expression_t *expression;
1294 add_anchor_token(')');
1295 expression = parse_constant_expression();
1296 rem_anchor_token(')');
1298 attribute->u.argument = fold_constant(expression);
1301 attribute->invalid = true;
1305 * parse a list of constant expressions arguments.
1307 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1309 argument_list_t **list = &attribute->u.arguments;
1310 argument_list_t *entry;
1311 expression_t *expression;
1312 add_anchor_token(')');
1313 add_anchor_token(',');
1315 expression = parse_constant_expression();
1316 entry = obstack_alloc(&temp_obst, sizeof(entry));
1317 entry->argument = fold_constant(expression);
1320 list = &entry->next;
1321 if (token.type != ',')
1325 rem_anchor_token(',');
1326 rem_anchor_token(')');
1330 attribute->invalid = true;
1334 * parse one string literal argument.
1336 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1339 add_anchor_token('(');
1340 if (token.type != T_STRING_LITERAL) {
1341 parse_error_expected("while parsing attribute directive",
1342 T_STRING_LITERAL, NULL);
1345 *string = parse_string_literals();
1346 rem_anchor_token('(');
1350 attribute->invalid = true;
1354 * parse one tls model.
1356 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1358 static const char *const tls_models[] = {
1364 string_t string = { NULL, 0 };
1365 parse_gnu_attribute_string_arg(attribute, &string);
1366 if (string.begin != NULL) {
1367 for (size_t i = 0; i < 4; ++i) {
1368 if (strcmp(tls_models[i], string.begin) == 0) {
1369 attribute->u.value = i;
1373 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1375 attribute->invalid = true;
1379 * parse one tls model.
1381 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1383 static const char *const visibilities[] = {
1389 string_t string = { NULL, 0 };
1390 parse_gnu_attribute_string_arg(attribute, &string);
1391 if (string.begin != NULL) {
1392 for (size_t i = 0; i < 4; ++i) {
1393 if (strcmp(visibilities[i], string.begin) == 0) {
1394 attribute->u.value = i;
1398 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1400 attribute->invalid = true;
1404 * parse one (code) model.
1406 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1408 static const char *const visibilities[] = {
1413 string_t string = { NULL, 0 };
1414 parse_gnu_attribute_string_arg(attribute, &string);
1415 if (string.begin != NULL) {
1416 for (int i = 0; i < 3; ++i) {
1417 if (strcmp(visibilities[i], string.begin) == 0) {
1418 attribute->u.value = i;
1422 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1424 attribute->invalid = true;
1427 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1429 /* TODO: find out what is allowed here... */
1431 /* at least: byte, word, pointer, list of machine modes
1432 * __XXX___ is interpreted as XXX */
1433 add_anchor_token(')');
1435 if (token.type != T_IDENTIFIER) {
1436 expect(T_IDENTIFIER);
1439 /* This isn't really correct, the backend should provide a list of machine
1440 * specific modes (according to gcc philosophy that is...) */
1441 const char *symbol_str = token.v.symbol->string;
1442 if (strcmp_underscore("QI", symbol_str) == 0 ||
1443 strcmp_underscore("byte", symbol_str) == 0) {
1444 attribute->u.akind = ATOMIC_TYPE_CHAR;
1445 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1446 attribute->u.akind = ATOMIC_TYPE_SHORT;
1447 } else if (strcmp_underscore("SI", symbol_str) == 0
1448 || strcmp_underscore("word", symbol_str) == 0
1449 || strcmp_underscore("pointer", symbol_str) == 0) {
1450 attribute->u.akind = ATOMIC_TYPE_INT;
1451 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1452 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1455 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1456 attribute->invalid = true;
1460 rem_anchor_token(')');
1464 attribute->invalid = true;
1468 * parse one interrupt argument.
1470 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1472 static const char *const interrupts[] = {
1479 string_t string = { NULL, 0 };
1480 parse_gnu_attribute_string_arg(attribute, &string);
1481 if (string.begin != NULL) {
1482 for (size_t i = 0; i < 5; ++i) {
1483 if (strcmp(interrupts[i], string.begin) == 0) {
1484 attribute->u.value = i;
1488 errorf(HERE, "'%s' is not an interrupt", string.begin);
1490 attribute->invalid = true;
1494 * parse ( identifier, const expression, const expression )
1496 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1498 static const char *const format_names[] = {
1506 if (token.type != T_IDENTIFIER) {
1507 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1510 const char *name = token.v.symbol->string;
1511 for (i = 0; i < 4; ++i) {
1512 if (strcmp_underscore(format_names[i], name) == 0)
1516 if (warning.attribute)
1517 warningf(HERE, "'%s' is an unrecognized format function type", name);
1522 add_anchor_token(')');
1523 add_anchor_token(',');
1524 parse_constant_expression();
1525 rem_anchor_token(',');
1526 rem_anchor_token(')');
1529 add_anchor_token(')');
1530 parse_constant_expression();
1531 rem_anchor_token(')');
1535 attribute->u.value = true;
1538 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1540 if (!attribute->have_arguments)
1543 /* should have no arguments */
1544 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1545 eat_until_matching_token('(');
1546 /* we have already consumed '(', so we stop before ')', eat it */
1548 attribute->invalid = true;
1552 * Parse one GNU attribute.
1554 * Note that attribute names can be specified WITH or WITHOUT
1555 * double underscores, ie const or __const__.
1557 * The following attributes are parsed without arguments
1582 * no_instrument_function
1583 * warn_unused_result
1600 * externally_visible
1608 * The following attributes are parsed with arguments
1609 * aligned( const expression )
1610 * alias( string literal )
1611 * section( string literal )
1612 * format( identifier, const expression, const expression )
1613 * format_arg( const expression )
1614 * tls_model( string literal )
1615 * visibility( string literal )
1616 * regparm( const expression )
1617 * model( string leteral )
1618 * trap_exit( const expression )
1619 * sp_switch( string literal )
1621 * The following attributes might have arguments
1622 * weak_ref( string literal )
1623 * non_null( const expression // ',' )
1624 * interrupt( string literal )
1625 * sentinel( constant expression )
1627 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1629 gnu_attribute_t *head = *attributes;
1630 gnu_attribute_t *last = *attributes;
1631 decl_modifiers_t modifiers = 0;
1632 gnu_attribute_t *attribute;
1634 eat(T___attribute__);
1638 if (token.type != ')') {
1639 /* find the end of the list */
1641 while (last->next != NULL)
1645 /* non-empty attribute list */
1648 if (token.type == T_const) {
1650 } else if (token.type == T_volatile) {
1652 } else if (token.type == T_cdecl) {
1653 /* __attribute__((cdecl)), WITH ms mode */
1655 } else if (token.type == T_IDENTIFIER) {
1656 const symbol_t *sym = token.v.symbol;
1659 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1666 for (i = 0; i < GNU_AK_LAST; ++i) {
1667 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1670 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1673 if (kind == GNU_AK_LAST) {
1674 if (warning.attribute)
1675 warningf(HERE, "'%s' attribute directive ignored", name);
1677 /* skip possible arguments */
1678 if (token.type == '(') {
1679 eat_until_matching_token(')');
1682 /* check for arguments */
1683 attribute = allocate_gnu_attribute(kind);
1684 if (token.type == '(') {
1686 if (token.type == ')') {
1687 /* empty args are allowed */
1690 attribute->have_arguments = true;
1694 case GNU_AK_VOLATILE:
1699 case GNU_AK_NOCOMMON:
1701 case GNU_AK_NOTSHARED:
1702 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1703 case GNU_AK_WARN_UNUSED_RESULT:
1704 case GNU_AK_LONGCALL:
1705 case GNU_AK_SHORTCALL:
1706 case GNU_AK_LONG_CALL:
1707 case GNU_AK_SHORT_CALL:
1708 case GNU_AK_FUNCTION_VECTOR:
1709 case GNU_AK_INTERRUPT_HANDLER:
1710 case GNU_AK_NMI_HANDLER:
1711 case GNU_AK_NESTING:
1715 case GNU_AK_EIGTHBIT_DATA:
1716 case GNU_AK_TINY_DATA:
1717 case GNU_AK_SAVEALL:
1718 case GNU_AK_FLATTEN:
1719 case GNU_AK_SSEREGPARM:
1720 case GNU_AK_EXTERNALLY_VISIBLE:
1721 case GNU_AK_RETURN_TWICE:
1722 case GNU_AK_MAY_ALIAS:
1723 case GNU_AK_MS_STRUCT:
1724 case GNU_AK_GCC_STRUCT:
1727 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1728 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1729 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1730 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1731 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1732 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1733 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1734 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1735 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1736 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1737 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1738 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1739 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1740 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1741 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1742 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1743 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1744 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1746 case GNU_AK_ALIGNED:
1747 /* __align__ may be used without an argument */
1748 if (attribute->have_arguments) {
1749 parse_gnu_attribute_const_arg(attribute);
1753 case GNU_AK_FORMAT_ARG:
1754 case GNU_AK_REGPARM:
1755 case GNU_AK_TRAP_EXIT:
1756 if (!attribute->have_arguments) {
1757 /* should have arguments */
1758 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1759 attribute->invalid = true;
1761 parse_gnu_attribute_const_arg(attribute);
1764 case GNU_AK_SECTION:
1765 case GNU_AK_SP_SWITCH:
1766 if (!attribute->have_arguments) {
1767 /* should have arguments */
1768 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1769 attribute->invalid = true;
1771 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1774 if (!attribute->have_arguments) {
1775 /* should have arguments */
1776 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1777 attribute->invalid = true;
1779 parse_gnu_attribute_format_args(attribute);
1781 case GNU_AK_WEAKREF:
1782 /* may have one string argument */
1783 if (attribute->have_arguments)
1784 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1786 case GNU_AK_NONNULL:
1787 if (attribute->have_arguments)
1788 parse_gnu_attribute_const_arg_list(attribute);
1790 case GNU_AK_TLS_MODEL:
1791 if (!attribute->have_arguments) {
1792 /* should have arguments */
1793 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1795 parse_gnu_attribute_tls_model_arg(attribute);
1797 case GNU_AK_VISIBILITY:
1798 if (!attribute->have_arguments) {
1799 /* should have arguments */
1800 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1802 parse_gnu_attribute_visibility_arg(attribute);
1805 if (!attribute->have_arguments) {
1806 /* should have arguments */
1807 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1809 parse_gnu_attribute_model_arg(attribute);
1813 if (!attribute->have_arguments) {
1814 /* should have arguments */
1815 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1817 parse_gnu_attribute_mode_arg(attribute);
1820 case GNU_AK_INTERRUPT:
1821 /* may have one string argument */
1822 if (attribute->have_arguments)
1823 parse_gnu_attribute_interrupt_arg(attribute);
1825 case GNU_AK_SENTINEL:
1826 /* may have one string argument */
1827 if (attribute->have_arguments)
1828 parse_gnu_attribute_const_arg(attribute);
1831 /* already handled */
1835 check_no_argument(attribute, name);
1838 if (attribute != NULL) {
1840 last->next = attribute;
1843 head = last = attribute;
1847 if (token.type != ',')
1861 * Parse GNU attributes.
1863 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1865 decl_modifiers_t modifiers = 0;
1868 switch (token.type) {
1869 case T___attribute__:
1870 modifiers |= parse_gnu_attribute(attributes);
1876 if (token.type != T_STRING_LITERAL) {
1877 parse_error_expected("while parsing assembler attribute",
1878 T_STRING_LITERAL, NULL);
1879 eat_until_matching_token('(');
1882 parse_string_literals();
1887 case T_cdecl: modifiers |= DM_CDECL; break;
1888 case T__fastcall: modifiers |= DM_FASTCALL; break;
1889 case T__stdcall: modifiers |= DM_STDCALL; break;
1892 /* TODO record modifier */
1894 warningf(HERE, "Ignoring declaration modifier '%K'", &token);
1898 default: return modifiers;
1905 static void mark_vars_read(expression_t *expr, variable_t *lhs_var);
1907 static variable_t *determine_lhs_var(expression_t *const expr,
1908 variable_t *lhs_var)
1910 switch (expr->kind) {
1911 case EXPR_REFERENCE: {
1912 entity_t *const entity = expr->reference.entity;
1913 /* we should only find variables as lavlues... */
1914 if (entity->base.kind != ENTITY_VARIABLE)
1917 return &entity->variable;
1920 case EXPR_ARRAY_ACCESS: {
1921 expression_t *const ref = expr->array_access.array_ref;
1922 variable_t * var = NULL;
1923 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1924 var = determine_lhs_var(ref, lhs_var);
1927 mark_vars_read(expr->select.compound, lhs_var);
1929 mark_vars_read(expr->array_access.index, lhs_var);
1934 if (is_type_compound(skip_typeref(expr->base.type))) {
1935 return determine_lhs_var(expr->select.compound, lhs_var);
1937 mark_vars_read(expr->select.compound, lhs_var);
1942 case EXPR_UNARY_DEREFERENCE: {
1943 expression_t *const val = expr->unary.value;
1944 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1946 return determine_lhs_var(val->unary.value, lhs_var);
1948 mark_vars_read(val, NULL);
1954 mark_vars_read(expr, NULL);
1959 #define VAR_ANY ((variable_t*)-1)
1962 * Mark declarations, which are read. This is used to deted variables, which
1966 * x is not marked as "read", because it is only read to calculate its own new
1970 * x and y are not detected as "not read", because multiple variables are
1973 static void mark_vars_read(expression_t *const expr, variable_t *lhs_var)
1975 switch (expr->kind) {
1976 case EXPR_REFERENCE: {
1977 entity_t *const entity = expr->reference.entity;
1978 if (entity->kind != ENTITY_VARIABLE)
1981 variable_t *variable = &entity->variable;
1982 if (lhs_var != variable && lhs_var != VAR_ANY) {
1983 variable->read = true;
1989 // TODO respect pure/const
1990 mark_vars_read(expr->call.function, NULL);
1991 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1992 mark_vars_read(arg->expression, NULL);
1996 case EXPR_CONDITIONAL:
1997 // TODO lhs_decl should depend on whether true/false have an effect
1998 mark_vars_read(expr->conditional.condition, NULL);
1999 if (expr->conditional.true_expression != NULL)
2000 mark_vars_read(expr->conditional.true_expression, lhs_var);
2001 mark_vars_read(expr->conditional.false_expression, lhs_var);
2005 if (lhs_var == VAR_ANY && !is_type_compound(skip_typeref(expr->base.type)))
2007 mark_vars_read(expr->select.compound, lhs_var);
2010 case EXPR_ARRAY_ACCESS: {
2011 expression_t *const ref = expr->array_access.array_ref;
2012 mark_vars_read(ref, lhs_var);
2013 lhs_var = determine_lhs_var(ref, lhs_var);
2014 mark_vars_read(expr->array_access.index, lhs_var);
2019 mark_vars_read(expr->va_arge.ap, lhs_var);
2022 case EXPR_UNARY_CAST:
2023 /* Special case: Use void cast to mark a variable as "read" */
2024 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2029 case EXPR_UNARY_THROW:
2030 if (expr->unary.value == NULL)
2033 case EXPR_UNARY_DEREFERENCE:
2034 case EXPR_UNARY_DELETE:
2035 case EXPR_UNARY_DELETE_ARRAY:
2036 if (lhs_var == VAR_ANY)
2040 case EXPR_UNARY_NEGATE:
2041 case EXPR_UNARY_PLUS:
2042 case EXPR_UNARY_BITWISE_NEGATE:
2043 case EXPR_UNARY_NOT:
2044 case EXPR_UNARY_TAKE_ADDRESS:
2045 case EXPR_UNARY_POSTFIX_INCREMENT:
2046 case EXPR_UNARY_POSTFIX_DECREMENT:
2047 case EXPR_UNARY_PREFIX_INCREMENT:
2048 case EXPR_UNARY_PREFIX_DECREMENT:
2049 case EXPR_UNARY_CAST_IMPLICIT:
2050 case EXPR_UNARY_ASSUME:
2052 mark_vars_read(expr->unary.value, lhs_var);
2055 case EXPR_BINARY_ADD:
2056 case EXPR_BINARY_SUB:
2057 case EXPR_BINARY_MUL:
2058 case EXPR_BINARY_DIV:
2059 case EXPR_BINARY_MOD:
2060 case EXPR_BINARY_EQUAL:
2061 case EXPR_BINARY_NOTEQUAL:
2062 case EXPR_BINARY_LESS:
2063 case EXPR_BINARY_LESSEQUAL:
2064 case EXPR_BINARY_GREATER:
2065 case EXPR_BINARY_GREATEREQUAL:
2066 case EXPR_BINARY_BITWISE_AND:
2067 case EXPR_BINARY_BITWISE_OR:
2068 case EXPR_BINARY_BITWISE_XOR:
2069 case EXPR_BINARY_LOGICAL_AND:
2070 case EXPR_BINARY_LOGICAL_OR:
2071 case EXPR_BINARY_SHIFTLEFT:
2072 case EXPR_BINARY_SHIFTRIGHT:
2073 case EXPR_BINARY_COMMA:
2074 case EXPR_BINARY_ISGREATER:
2075 case EXPR_BINARY_ISGREATEREQUAL:
2076 case EXPR_BINARY_ISLESS:
2077 case EXPR_BINARY_ISLESSEQUAL:
2078 case EXPR_BINARY_ISLESSGREATER:
2079 case EXPR_BINARY_ISUNORDERED:
2080 mark_vars_read(expr->binary.left, lhs_var);
2081 mark_vars_read(expr->binary.right, lhs_var);
2084 case EXPR_BINARY_ASSIGN:
2085 case EXPR_BINARY_MUL_ASSIGN:
2086 case EXPR_BINARY_DIV_ASSIGN:
2087 case EXPR_BINARY_MOD_ASSIGN:
2088 case EXPR_BINARY_ADD_ASSIGN:
2089 case EXPR_BINARY_SUB_ASSIGN:
2090 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2091 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2092 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2093 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2094 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2095 if (lhs_var == VAR_ANY)
2097 lhs_var = determine_lhs_var(expr->binary.left, lhs_var);
2098 mark_vars_read(expr->binary.right, lhs_var);
2103 determine_lhs_var(expr->va_starte.ap, lhs_var);
2109 case EXPR_CHARACTER_CONSTANT:
2110 case EXPR_WIDE_CHARACTER_CONSTANT:
2111 case EXPR_STRING_LITERAL:
2112 case EXPR_WIDE_STRING_LITERAL:
2113 case EXPR_COMPOUND_LITERAL: // TODO init?
2115 case EXPR_CLASSIFY_TYPE:
2118 case EXPR_BUILTIN_SYMBOL:
2119 case EXPR_BUILTIN_CONSTANT_P:
2120 case EXPR_BUILTIN_PREFETCH:
2122 case EXPR_STATEMENT: // TODO
2123 case EXPR_LABEL_ADDRESS:
2124 case EXPR_BINARY_BUILTIN_EXPECT:
2125 case EXPR_REFERENCE_ENUM_VALUE:
2129 panic("unhandled expression");
2132 static designator_t *parse_designation(void)
2134 designator_t *result = NULL;
2135 designator_t *last = NULL;
2138 designator_t *designator;
2139 switch (token.type) {
2141 designator = allocate_ast_zero(sizeof(designator[0]));
2142 designator->source_position = token.source_position;
2144 add_anchor_token(']');
2145 designator->array_index = parse_constant_expression();
2146 rem_anchor_token(']');
2150 designator = allocate_ast_zero(sizeof(designator[0]));
2151 designator->source_position = token.source_position;
2153 if (token.type != T_IDENTIFIER) {
2154 parse_error_expected("while parsing designator",
2155 T_IDENTIFIER, NULL);
2158 designator->symbol = token.v.symbol;
2166 assert(designator != NULL);
2168 last->next = designator;
2170 result = designator;
2178 static initializer_t *initializer_from_string(array_type_t *type,
2179 const string_t *const string)
2181 /* TODO: check len vs. size of array type */
2184 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2185 initializer->string.string = *string;
2190 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2191 wide_string_t *const string)
2193 /* TODO: check len vs. size of array type */
2196 initializer_t *const initializer =
2197 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2198 initializer->wide_string.string = *string;
2204 * Build an initializer from a given expression.
2206 static initializer_t *initializer_from_expression(type_t *orig_type,
2207 expression_t *expression)
2209 /* TODO check that expression is a constant expression */
2211 /* § 6.7.8.14/15 char array may be initialized by string literals */
2212 type_t *type = skip_typeref(orig_type);
2213 type_t *expr_type_orig = expression->base.type;
2214 type_t *expr_type = skip_typeref(expr_type_orig);
2215 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2216 array_type_t *const array_type = &type->array;
2217 type_t *const element_type = skip_typeref(array_type->element_type);
2219 if (element_type->kind == TYPE_ATOMIC) {
2220 atomic_type_kind_t akind = element_type->atomic.akind;
2221 switch (expression->kind) {
2222 case EXPR_STRING_LITERAL:
2223 if (akind == ATOMIC_TYPE_CHAR
2224 || akind == ATOMIC_TYPE_SCHAR
2225 || akind == ATOMIC_TYPE_UCHAR) {
2226 return initializer_from_string(array_type,
2227 &expression->string.value);
2230 case EXPR_WIDE_STRING_LITERAL: {
2231 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2232 if (get_unqualified_type(element_type) == bare_wchar_type) {
2233 return initializer_from_wide_string(array_type,
2234 &expression->wide_string.value);
2244 assign_error_t error = semantic_assign(type, expression);
2245 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2247 report_assign_error(error, type, expression, "initializer",
2248 &expression->base.source_position);
2250 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2252 if (type->kind == TYPE_BITFIELD) {
2253 type = type->bitfield.base_type;
2256 result->value.value = create_implicit_cast(expression, type);
2262 * Checks if a given expression can be used as an constant initializer.
2264 static bool is_initializer_constant(const expression_t *expression)
2266 return is_constant_expression(expression)
2267 || is_address_constant(expression);
2271 * Parses an scalar initializer.
2273 * § 6.7.8.11; eat {} without warning
2275 static initializer_t *parse_scalar_initializer(type_t *type,
2276 bool must_be_constant)
2278 /* there might be extra {} hierarchies */
2280 if (token.type == '{') {
2282 warningf(HERE, "extra curly braces around scalar initializer");
2286 } while (token.type == '{');
2289 expression_t *expression = parse_assignment_expression();
2290 mark_vars_read(expression, NULL);
2291 if (must_be_constant && !is_initializer_constant(expression)) {
2292 errorf(&expression->base.source_position,
2293 "Initialisation expression '%E' is not constant\n",
2297 initializer_t *initializer = initializer_from_expression(type, expression);
2299 if (initializer == NULL) {
2300 errorf(&expression->base.source_position,
2301 "expression '%E' (type '%T') doesn't match expected type '%T'",
2302 expression, expression->base.type, type);
2307 bool additional_warning_displayed = false;
2308 while (braces > 0) {
2309 if (token.type == ',') {
2312 if (token.type != '}') {
2313 if (!additional_warning_displayed && warning.other) {
2314 warningf(HERE, "additional elements in scalar initializer");
2315 additional_warning_displayed = true;
2326 * An entry in the type path.
2328 typedef struct type_path_entry_t type_path_entry_t;
2329 struct type_path_entry_t {
2330 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2332 size_t index; /**< For array types: the current index. */
2333 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2338 * A type path expression a position inside compound or array types.
2340 typedef struct type_path_t type_path_t;
2341 struct type_path_t {
2342 type_path_entry_t *path; /**< An flexible array containing the current path. */
2343 type_t *top_type; /**< type of the element the path points */
2344 size_t max_index; /**< largest index in outermost array */
2348 * Prints a type path for debugging.
2350 static __attribute__((unused)) void debug_print_type_path(
2351 const type_path_t *path)
2353 size_t len = ARR_LEN(path->path);
2355 for (size_t i = 0; i < len; ++i) {
2356 const type_path_entry_t *entry = & path->path[i];
2358 type_t *type = skip_typeref(entry->type);
2359 if (is_type_compound(type)) {
2360 /* in gcc mode structs can have no members */
2361 if (entry->v.compound_entry == NULL) {
2365 fprintf(stderr, ".%s",
2366 entry->v.compound_entry->base.symbol->string);
2367 } else if (is_type_array(type)) {
2368 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
2370 fprintf(stderr, "-INVALID-");
2373 if (path->top_type != NULL) {
2374 fprintf(stderr, " (");
2375 print_type(path->top_type);
2376 fprintf(stderr, ")");
2381 * Return the top type path entry, ie. in a path
2382 * (type).a.b returns the b.
2384 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2386 size_t len = ARR_LEN(path->path);
2388 return &path->path[len-1];
2392 * Enlarge the type path by an (empty) element.
2394 static type_path_entry_t *append_to_type_path(type_path_t *path)
2396 size_t len = ARR_LEN(path->path);
2397 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2399 type_path_entry_t *result = & path->path[len];
2400 memset(result, 0, sizeof(result[0]));
2405 * Descending into a sub-type. Enter the scope of the current top_type.
2407 static void descend_into_subtype(type_path_t *path)
2409 type_t *orig_top_type = path->top_type;
2410 type_t *top_type = skip_typeref(orig_top_type);
2412 type_path_entry_t *top = append_to_type_path(path);
2413 top->type = top_type;
2415 if (is_type_compound(top_type)) {
2416 compound_t *compound = top_type->compound.compound;
2417 entity_t *entry = compound->members.entities;
2419 if (entry != NULL) {
2420 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2421 top->v.compound_entry = &entry->declaration;
2422 path->top_type = entry->declaration.type;
2424 path->top_type = NULL;
2426 } else if (is_type_array(top_type)) {
2428 path->top_type = top_type->array.element_type;
2430 assert(!is_type_valid(top_type));
2435 * Pop an entry from the given type path, ie. returning from
2436 * (type).a.b to (type).a
2438 static void ascend_from_subtype(type_path_t *path)
2440 type_path_entry_t *top = get_type_path_top(path);
2442 path->top_type = top->type;
2444 size_t len = ARR_LEN(path->path);
2445 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2449 * Pop entries from the given type path until the given
2450 * path level is reached.
2452 static void ascend_to(type_path_t *path, size_t top_path_level)
2454 size_t len = ARR_LEN(path->path);
2456 while (len > top_path_level) {
2457 ascend_from_subtype(path);
2458 len = ARR_LEN(path->path);
2462 static bool walk_designator(type_path_t *path, const designator_t *designator,
2463 bool used_in_offsetof)
2465 for (; designator != NULL; designator = designator->next) {
2466 type_path_entry_t *top = get_type_path_top(path);
2467 type_t *orig_type = top->type;
2469 type_t *type = skip_typeref(orig_type);
2471 if (designator->symbol != NULL) {
2472 symbol_t *symbol = designator->symbol;
2473 if (!is_type_compound(type)) {
2474 if (is_type_valid(type)) {
2475 errorf(&designator->source_position,
2476 "'.%Y' designator used for non-compound type '%T'",
2480 top->type = type_error_type;
2481 top->v.compound_entry = NULL;
2482 orig_type = type_error_type;
2484 compound_t *compound = type->compound.compound;
2485 entity_t *iter = compound->members.entities;
2486 for (; iter != NULL; iter = iter->base.next) {
2487 if (iter->base.symbol == symbol) {
2492 errorf(&designator->source_position,
2493 "'%T' has no member named '%Y'", orig_type, symbol);
2496 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2497 if (used_in_offsetof) {
2498 type_t *real_type = skip_typeref(iter->declaration.type);
2499 if (real_type->kind == TYPE_BITFIELD) {
2500 errorf(&designator->source_position,
2501 "offsetof designator '%Y' may not specify bitfield",
2507 top->type = orig_type;
2508 top->v.compound_entry = &iter->declaration;
2509 orig_type = iter->declaration.type;
2512 expression_t *array_index = designator->array_index;
2513 assert(designator->array_index != NULL);
2515 if (!is_type_array(type)) {
2516 if (is_type_valid(type)) {
2517 errorf(&designator->source_position,
2518 "[%E] designator used for non-array type '%T'",
2519 array_index, orig_type);
2524 long index = fold_constant(array_index);
2525 if (!used_in_offsetof) {
2527 errorf(&designator->source_position,
2528 "array index [%E] must be positive", array_index);
2529 } else if (type->array.size_constant) {
2530 long array_size = type->array.size;
2531 if (index >= array_size) {
2532 errorf(&designator->source_position,
2533 "designator [%E] (%d) exceeds array size %d",
2534 array_index, index, array_size);
2539 top->type = orig_type;
2540 top->v.index = (size_t) index;
2541 orig_type = type->array.element_type;
2543 path->top_type = orig_type;
2545 if (designator->next != NULL) {
2546 descend_into_subtype(path);
2555 static void advance_current_object(type_path_t *path, size_t top_path_level)
2557 type_path_entry_t *top = get_type_path_top(path);
2559 type_t *type = skip_typeref(top->type);
2560 if (is_type_union(type)) {
2561 /* in unions only the first element is initialized */
2562 top->v.compound_entry = NULL;
2563 } else if (is_type_struct(type)) {
2564 declaration_t *entry = top->v.compound_entry;
2566 entity_t *next_entity = entry->base.next;
2567 if (next_entity != NULL) {
2568 assert(is_declaration(next_entity));
2569 entry = &next_entity->declaration;
2574 top->v.compound_entry = entry;
2575 if (entry != NULL) {
2576 path->top_type = entry->type;
2579 } else if (is_type_array(type)) {
2580 assert(is_type_array(type));
2584 if (!type->array.size_constant || top->v.index < type->array.size) {
2588 assert(!is_type_valid(type));
2592 /* we're past the last member of the current sub-aggregate, try if we
2593 * can ascend in the type hierarchy and continue with another subobject */
2594 size_t len = ARR_LEN(path->path);
2596 if (len > top_path_level) {
2597 ascend_from_subtype(path);
2598 advance_current_object(path, top_path_level);
2600 path->top_type = NULL;
2605 * skip until token is found.
2607 static void skip_until(int type)
2609 while (token.type != type) {
2610 if (token.type == T_EOF)
2617 * skip any {...} blocks until a closing bracket is reached.
2619 static void skip_initializers(void)
2621 if (token.type == '{')
2624 while (token.type != '}') {
2625 if (token.type == T_EOF)
2627 if (token.type == '{') {
2635 static initializer_t *create_empty_initializer(void)
2637 static initializer_t empty_initializer
2638 = { .list = { { INITIALIZER_LIST }, 0 } };
2639 return &empty_initializer;
2643 * Parse a part of an initialiser for a struct or union,
2645 static initializer_t *parse_sub_initializer(type_path_t *path,
2646 type_t *outer_type, size_t top_path_level,
2647 parse_initializer_env_t *env)
2649 if (token.type == '}') {
2650 /* empty initializer */
2651 return create_empty_initializer();
2654 type_t *orig_type = path->top_type;
2655 type_t *type = NULL;
2657 if (orig_type == NULL) {
2658 /* We are initializing an empty compound. */
2660 type = skip_typeref(orig_type);
2663 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2666 designator_t *designator = NULL;
2667 if (token.type == '.' || token.type == '[') {
2668 designator = parse_designation();
2669 goto finish_designator;
2670 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2671 /* GNU-style designator ("identifier: value") */
2672 designator = allocate_ast_zero(sizeof(designator[0]));
2673 designator->source_position = token.source_position;
2674 designator->symbol = token.v.symbol;
2679 /* reset path to toplevel, evaluate designator from there */
2680 ascend_to(path, top_path_level);
2681 if (!walk_designator(path, designator, false)) {
2682 /* can't continue after designation error */
2686 initializer_t *designator_initializer
2687 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2688 designator_initializer->designator.designator = designator;
2689 ARR_APP1(initializer_t*, initializers, designator_initializer);
2691 orig_type = path->top_type;
2692 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2697 if (token.type == '{') {
2698 if (type != NULL && is_type_scalar(type)) {
2699 sub = parse_scalar_initializer(type, env->must_be_constant);
2703 if (env->entity != NULL) {
2705 "extra brace group at end of initializer for '%Y'",
2706 env->entity->base.symbol);
2708 errorf(HERE, "extra brace group at end of initializer");
2711 descend_into_subtype(path);
2713 add_anchor_token('}');
2714 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2716 rem_anchor_token('}');
2719 ascend_from_subtype(path);
2723 goto error_parse_next;
2727 /* must be an expression */
2728 expression_t *expression = parse_assignment_expression();
2730 if (env->must_be_constant && !is_initializer_constant(expression)) {
2731 errorf(&expression->base.source_position,
2732 "Initialisation expression '%E' is not constant\n",
2737 /* we are already outside, ... */
2738 type_t *const outer_type_skip = skip_typeref(outer_type);
2739 if (is_type_compound(outer_type_skip) &&
2740 !outer_type_skip->compound.compound->complete) {
2741 goto error_parse_next;
2746 /* handle { "string" } special case */
2747 if ((expression->kind == EXPR_STRING_LITERAL
2748 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2749 && outer_type != NULL) {
2750 sub = initializer_from_expression(outer_type, expression);
2752 if (token.type == ',') {
2755 if (token.type != '}' && warning.other) {
2756 warningf(HERE, "excessive elements in initializer for type '%T'",
2759 /* TODO: eat , ... */
2764 /* descend into subtypes until expression matches type */
2766 orig_type = path->top_type;
2767 type = skip_typeref(orig_type);
2769 sub = initializer_from_expression(orig_type, expression);
2773 if (!is_type_valid(type)) {
2776 if (is_type_scalar(type)) {
2777 errorf(&expression->base.source_position,
2778 "expression '%E' doesn't match expected type '%T'",
2779 expression, orig_type);
2783 descend_into_subtype(path);
2787 /* update largest index of top array */
2788 const type_path_entry_t *first = &path->path[0];
2789 type_t *first_type = first->type;
2790 first_type = skip_typeref(first_type);
2791 if (is_type_array(first_type)) {
2792 size_t index = first->v.index;
2793 if (index > path->max_index)
2794 path->max_index = index;
2798 /* append to initializers list */
2799 ARR_APP1(initializer_t*, initializers, sub);
2802 if (warning.other) {
2803 if (env->entity != NULL) {
2804 warningf(HERE, "excess elements in struct initializer for '%Y'",
2805 env->entity->base.symbol);
2807 warningf(HERE, "excess elements in struct initializer");
2813 if (token.type == '}') {
2817 if (token.type == '}') {
2822 /* advance to the next declaration if we are not at the end */
2823 advance_current_object(path, top_path_level);
2824 orig_type = path->top_type;
2825 if (orig_type != NULL)
2826 type = skip_typeref(orig_type);
2832 size_t len = ARR_LEN(initializers);
2833 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2834 initializer_t *result = allocate_ast_zero(size);
2835 result->kind = INITIALIZER_LIST;
2836 result->list.len = len;
2837 memcpy(&result->list.initializers, initializers,
2838 len * sizeof(initializers[0]));
2840 DEL_ARR_F(initializers);
2841 ascend_to(path, top_path_level+1);
2846 skip_initializers();
2847 DEL_ARR_F(initializers);
2848 ascend_to(path, top_path_level+1);
2853 * Parses an initializer. Parsers either a compound literal
2854 * (env->declaration == NULL) or an initializer of a declaration.
2856 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2858 type_t *type = skip_typeref(env->type);
2859 initializer_t *result = NULL;
2862 if (is_type_scalar(type)) {
2863 result = parse_scalar_initializer(type, env->must_be_constant);
2864 } else if (token.type == '{') {
2868 memset(&path, 0, sizeof(path));
2869 path.top_type = env->type;
2870 path.path = NEW_ARR_F(type_path_entry_t, 0);
2872 descend_into_subtype(&path);
2874 add_anchor_token('}');
2875 result = parse_sub_initializer(&path, env->type, 1, env);
2876 rem_anchor_token('}');
2878 max_index = path.max_index;
2879 DEL_ARR_F(path.path);
2883 /* parse_scalar_initializer() also works in this case: we simply
2884 * have an expression without {} around it */
2885 result = parse_scalar_initializer(type, env->must_be_constant);
2888 /* § 6.7.8 (22) array initializers for arrays with unknown size determine
2889 * the array type size */
2890 if (is_type_array(type) && type->array.size_expression == NULL
2891 && result != NULL) {
2893 switch (result->kind) {
2894 case INITIALIZER_LIST:
2895 size = max_index + 1;
2898 case INITIALIZER_STRING:
2899 size = result->string.string.size;
2902 case INITIALIZER_WIDE_STRING:
2903 size = result->wide_string.string.size;
2906 case INITIALIZER_DESIGNATOR:
2907 case INITIALIZER_VALUE:
2908 /* can happen for parse errors */
2913 internal_errorf(HERE, "invalid initializer type");
2916 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2917 cnst->base.type = type_size_t;
2918 cnst->conste.v.int_value = size;
2920 type_t *new_type = duplicate_type(type);
2922 new_type->array.size_expression = cnst;
2923 new_type->array.size_constant = true;
2924 new_type->array.has_implicit_size = true;
2925 new_type->array.size = size;
2926 env->type = new_type;
2934 static void append_entity(scope_t *scope, entity_t *entity)
2936 if (scope->last_entity != NULL) {
2937 scope->last_entity->base.next = entity;
2939 scope->entities = entity;
2941 scope->last_entity = entity;
2945 static compound_t *parse_compound_type_specifier(bool is_struct)
2947 gnu_attribute_t *attributes = NULL;
2948 decl_modifiers_t modifiers = 0;
2955 symbol_t *symbol = NULL;
2956 compound_t *compound = NULL;
2958 if (token.type == T___attribute__) {
2959 modifiers |= parse_attributes(&attributes);
2962 if (token.type == T_IDENTIFIER) {
2963 symbol = token.v.symbol;
2966 namespace_tag_t const namespc =
2967 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2968 entity_t *entity = get_entity(symbol, namespc);
2969 if (entity != NULL) {
2970 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
2971 compound = &entity->compound;
2972 if (compound->base.parent_scope != current_scope &&
2973 (token.type == '{' || token.type == ';')) {
2974 /* we're in an inner scope and have a definition. Override
2975 existing definition in outer scope */
2977 } else if (compound->complete && token.type == '{') {
2978 assert(symbol != NULL);
2979 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2980 is_struct ? "struct" : "union", symbol,
2981 &compound->base.source_position);
2982 /* clear members in the hope to avoid further errors */
2983 compound->members.entities = NULL;
2986 } else if (token.type != '{') {
2988 parse_error_expected("while parsing struct type specifier",
2989 T_IDENTIFIER, '{', NULL);
2991 parse_error_expected("while parsing union type specifier",
2992 T_IDENTIFIER, '{', NULL);
2998 if (compound == NULL) {
2999 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
3000 entity_t *entity = allocate_entity_zero(kind);
3001 compound = &entity->compound;
3003 compound->base.namespc =
3004 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
3005 compound->base.source_position = token.source_position;
3006 compound->base.symbol = symbol;
3007 compound->base.parent_scope = current_scope;
3008 if (symbol != NULL) {
3009 environment_push(entity);
3011 append_entity(current_scope, entity);
3014 if (token.type == '{') {
3015 parse_compound_type_entries(compound);
3016 modifiers |= parse_attributes(&attributes);
3018 if (symbol == NULL) {
3019 assert(anonymous_entity == NULL);
3020 anonymous_entity = (entity_t*)compound;
3024 compound->modifiers |= modifiers;
3028 static void parse_enum_entries(type_t *const enum_type)
3032 if (token.type == '}') {
3033 errorf(HERE, "empty enum not allowed");
3038 add_anchor_token('}');
3040 if (token.type != T_IDENTIFIER) {
3041 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3043 rem_anchor_token('}');
3047 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3048 entity->enum_value.enum_type = enum_type;
3049 entity->base.symbol = token.v.symbol;
3050 entity->base.source_position = token.source_position;
3053 if (token.type == '=') {
3055 expression_t *value = parse_constant_expression();
3057 value = create_implicit_cast(value, enum_type);
3058 entity->enum_value.value = value;
3063 record_entity(entity, false);
3065 if (token.type != ',')
3068 } while (token.type != '}');
3069 rem_anchor_token('}');
3077 static type_t *parse_enum_specifier(void)
3079 gnu_attribute_t *attributes = NULL;
3084 if (token.type == T_IDENTIFIER) {
3085 symbol = token.v.symbol;
3088 entity = get_entity(symbol, NAMESPACE_ENUM);
3089 assert(entity == NULL || entity->kind == ENTITY_ENUM);
3090 } else if (token.type != '{') {
3091 parse_error_expected("while parsing enum type specifier",
3092 T_IDENTIFIER, '{', NULL);
3099 if (entity == NULL) {
3100 entity = allocate_entity_zero(ENTITY_ENUM);
3101 entity->base.namespc = NAMESPACE_ENUM;
3102 entity->base.source_position = token.source_position;
3103 entity->base.symbol = symbol;
3104 entity->base.parent_scope = current_scope;
3107 type_t *const type = allocate_type_zero(TYPE_ENUM);
3108 type->enumt.enume = &entity->enume;
3110 if (token.type == '{') {
3111 if (entity->enume.complete) {
3112 errorf(HERE, "multiple definitions of enum %Y (previous definition %P)",
3113 symbol, &entity->base.source_position);
3115 if (symbol != NULL) {
3116 environment_push(entity);
3118 append_entity(current_scope, entity);
3119 entity->enume.complete = true;
3121 parse_enum_entries(type);
3122 parse_attributes(&attributes);
3124 if (symbol == NULL) {
3125 assert(anonymous_entity == NULL);
3126 anonymous_entity = entity;
3128 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
3129 errorf(HERE, "enum %Y used before definition (incomplete enumes are a GNU extension)",
3137 * if a symbol is a typedef to another type, return true
3139 static bool is_typedef_symbol(symbol_t *symbol)
3141 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3142 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3145 static type_t *parse_typeof(void)
3152 add_anchor_token(')');
3154 expression_t *expression = NULL;
3156 bool old_type_prop = in_type_prop;
3157 bool old_gcc_extension = in_gcc_extension;
3158 in_type_prop = true;
3160 while (token.type == T___extension__) {
3161 /* This can be a prefix to a typename or an expression. */
3163 in_gcc_extension = true;
3165 switch (token.type) {
3167 if (is_typedef_symbol(token.v.symbol)) {
3168 type = parse_typename();
3170 expression = parse_expression();
3171 type = expression->base.type;
3176 type = parse_typename();
3180 expression = parse_expression();
3181 type = expression->base.type;
3184 in_type_prop = old_type_prop;
3185 in_gcc_extension = old_gcc_extension;
3187 rem_anchor_token(')');
3190 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3191 typeof_type->typeoft.expression = expression;
3192 typeof_type->typeoft.typeof_type = type;
3199 typedef enum specifiers_t {
3200 SPECIFIER_SIGNED = 1 << 0,
3201 SPECIFIER_UNSIGNED = 1 << 1,
3202 SPECIFIER_LONG = 1 << 2,
3203 SPECIFIER_INT = 1 << 3,
3204 SPECIFIER_DOUBLE = 1 << 4,
3205 SPECIFIER_CHAR = 1 << 5,
3206 SPECIFIER_SHORT = 1 << 6,
3207 SPECIFIER_LONG_LONG = 1 << 7,
3208 SPECIFIER_FLOAT = 1 << 8,
3209 SPECIFIER_BOOL = 1 << 9,
3210 SPECIFIER_VOID = 1 << 10,
3211 SPECIFIER_INT8 = 1 << 11,
3212 SPECIFIER_INT16 = 1 << 12,
3213 SPECIFIER_INT32 = 1 << 13,
3214 SPECIFIER_INT64 = 1 << 14,
3215 SPECIFIER_INT128 = 1 << 15,
3216 SPECIFIER_COMPLEX = 1 << 16,
3217 SPECIFIER_IMAGINARY = 1 << 17,
3220 static type_t *create_builtin_type(symbol_t *const symbol,
3221 type_t *const real_type)
3223 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3224 type->builtin.symbol = symbol;
3225 type->builtin.real_type = real_type;
3227 type_t *result = typehash_insert(type);
3228 if (type != result) {
3235 static type_t *get_typedef_type(symbol_t *symbol)
3237 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3238 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3241 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3242 type->typedeft.typedefe = &entity->typedefe;
3248 * check for the allowed MS alignment values.
3250 static bool check_alignment_value(long long intvalue)
3252 if (intvalue < 1 || intvalue > 8192) {
3253 errorf(HERE, "illegal alignment value");
3256 unsigned v = (unsigned)intvalue;
3257 for (unsigned i = 1; i <= 8192; i += i) {
3261 errorf(HERE, "alignment must be power of two");
3265 #define DET_MOD(name, tag) do { \
3266 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3267 *modifiers |= tag; \
3270 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3272 decl_modifiers_t *modifiers = &specifiers->modifiers;
3275 if (token.type == T_restrict) {
3277 DET_MOD(restrict, DM_RESTRICT);
3279 } else if (token.type != T_IDENTIFIER)
3281 symbol_t *symbol = token.v.symbol;
3282 if (symbol == sym_align) {
3285 if (token.type != T_INTEGER)
3287 if (check_alignment_value(token.v.intvalue)) {
3288 if (specifiers->alignment != 0 && warning.other)
3289 warningf(HERE, "align used more than once");
3290 specifiers->alignment = (unsigned char)token.v.intvalue;
3294 } else if (symbol == sym_allocate) {
3297 if (token.type != T_IDENTIFIER)
3299 (void)token.v.symbol;
3301 } else if (symbol == sym_dllimport) {
3303 DET_MOD(dllimport, DM_DLLIMPORT);
3304 } else if (symbol == sym_dllexport) {
3306 DET_MOD(dllexport, DM_DLLEXPORT);
3307 } else if (symbol == sym_thread) {
3309 DET_MOD(thread, DM_THREAD);
3310 } else if (symbol == sym_naked) {
3312 DET_MOD(naked, DM_NAKED);
3313 } else if (symbol == sym_noinline) {
3315 DET_MOD(noinline, DM_NOINLINE);
3316 } else if (symbol == sym_noreturn) {
3318 DET_MOD(noreturn, DM_NORETURN);
3319 } else if (symbol == sym_nothrow) {
3321 DET_MOD(nothrow, DM_NOTHROW);
3322 } else if (symbol == sym_novtable) {
3324 DET_MOD(novtable, DM_NOVTABLE);
3325 } else if (symbol == sym_property) {
3329 bool is_get = false;
3330 if (token.type != T_IDENTIFIER)
3332 if (token.v.symbol == sym_get) {
3334 } else if (token.v.symbol == sym_put) {
3336 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3341 if (token.type != T_IDENTIFIER)
3344 if (specifiers->get_property_sym != NULL) {
3345 errorf(HERE, "get property name already specified");
3347 specifiers->get_property_sym = token.v.symbol;
3350 if (specifiers->put_property_sym != NULL) {
3351 errorf(HERE, "put property name already specified");
3353 specifiers->put_property_sym = token.v.symbol;
3357 if (token.type == ',') {
3364 } else if (symbol == sym_selectany) {
3366 DET_MOD(selectany, DM_SELECTANY);
3367 } else if (symbol == sym_uuid) {
3370 if (token.type != T_STRING_LITERAL)
3374 } else if (symbol == sym_deprecated) {
3376 if (specifiers->deprecated != 0 && warning.other)
3377 warningf(HERE, "deprecated used more than once");
3378 specifiers->deprecated = true;
3379 if (token.type == '(') {
3381 if (token.type == T_STRING_LITERAL) {
3382 specifiers->deprecated_string = token.v.string.begin;
3385 errorf(HERE, "string literal expected");
3389 } else if (symbol == sym_noalias) {
3391 DET_MOD(noalias, DM_NOALIAS);
3394 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3396 if (token.type == '(')
3400 if (token.type == ',')
3407 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3409 entity_t *entity = allocate_entity_zero(kind);
3410 entity->base.source_position = *HERE;
3411 entity->base.symbol = symbol;
3412 if (is_declaration(entity)) {
3413 entity->declaration.type = type_error_type;
3414 entity->declaration.implicit = true;
3415 } else if (kind == ENTITY_TYPEDEF) {
3416 entity->typedefe.type = type_error_type;
3418 record_entity(entity, false);
3422 static void parse_microsoft_based(based_spec_t *based_spec)
3424 if (token.type != T_IDENTIFIER) {
3425 parse_error_expected("while parsing __based", T_IDENTIFIER, NULL);
3428 symbol_t *symbol = token.v.symbol;
3429 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3431 if (entity == NULL || entity->base.kind != ENTITY_VARIABLE) {
3432 errorf(HERE, "'%Y' is not a variable name.", symbol);
3433 entity = create_error_entity(symbol, ENTITY_VARIABLE);
3435 variable_t *variable = &entity->variable;
3437 if (based_spec->base_variable != NULL) {
3438 errorf(HERE, "__based type qualifier specified more than once");
3440 based_spec->source_position = token.source_position;
3441 based_spec->base_variable = variable;
3443 type_t *const type = variable->base.type;
3445 if (is_type_valid(type)) {
3446 if (! is_type_pointer(skip_typeref(type))) {
3447 errorf(HERE, "variable in __based modifier must have pointer type instead of '%T'", type);
3449 if (variable->base.base.parent_scope != file_scope) {
3450 errorf(HERE, "a nonstatic local variable may not be used in a __based specification");
3458 * Finish the construction of a struct type by calculating
3459 * its size, offsets, alignment.
3461 static void finish_struct_type(compound_type_t *type)
3463 assert(type->compound != NULL);
3465 compound_t *compound = type->compound;
3466 if (!compound->complete)
3471 il_alignment_t alignment = 1;
3472 bool need_pad = false;
3474 entity_t *entry = compound->members.entities;
3475 for (; entry != NULL; entry = entry->base.next) {
3476 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3479 type_t *m_type = skip_typeref(entry->declaration.type);
3480 if (! is_type_valid(m_type)) {
3481 /* simply ignore errors here */
3484 il_alignment_t m_alignment = m_type->base.alignment;
3485 if (m_alignment > alignment)
3486 alignment = m_alignment;
3488 offset = (size + m_alignment - 1) & -m_alignment;
3492 entry->compound_member.offset = offset;
3493 size = offset + m_type->base.size;
3495 if (type->base.alignment != 0) {
3496 alignment = type->base.alignment;
3499 offset = (size + alignment - 1) & -alignment;
3503 if (warning.padded && need_pad) {
3504 warningf(&compound->base.source_position,
3505 "'%#T' needs padding", type, compound->base.symbol);
3507 if (warning.packed && !need_pad) {
3508 warningf(&compound->base.source_position,
3509 "superfluous packed attribute on '%#T'",
3510 type, compound->base.symbol);
3513 type->base.size = offset;
3514 type->base.alignment = alignment;
3518 * Finish the construction of an union type by calculating
3519 * its size and alignment.
3521 static void finish_union_type(compound_type_t *type)
3523 assert(type->compound != NULL);
3525 compound_t *compound = type->compound;
3526 if (! compound->complete)
3530 il_alignment_t alignment = 1;
3532 entity_t *entry = compound->members.entities;
3533 for (; entry != NULL; entry = entry->base.next) {
3534 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3537 type_t *m_type = skip_typeref(entry->declaration.type);
3538 if (! is_type_valid(m_type))
3541 entry->compound_member.offset = 0;
3542 if (m_type->base.size > size)
3543 size = m_type->base.size;
3544 if (m_type->base.alignment > alignment)
3545 alignment = m_type->base.alignment;
3547 if (type->base.alignment != 0) {
3548 alignment = type->base.alignment;
3550 size = (size + alignment - 1) & -alignment;
3551 type->base.size = size;
3552 type->base.alignment = alignment;
3555 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3557 type_t *type = NULL;
3558 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3559 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3560 unsigned type_specifiers = 0;
3561 bool newtype = false;
3562 bool saw_error = false;
3563 bool old_gcc_extension = in_gcc_extension;
3565 specifiers->source_position = token.source_position;
3568 specifiers->modifiers
3569 |= parse_attributes(&specifiers->gnu_attributes);
3570 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3571 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3573 switch (token.type) {
3575 #define MATCH_STORAGE_CLASS(token, class) \
3577 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3578 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3580 specifiers->storage_class = class; \
3581 if (specifiers->thread_local) \
3582 goto check_thread_storage_class; \
3586 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3587 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3588 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3589 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3590 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3595 add_anchor_token(')');
3596 parse_microsoft_extended_decl_modifier(specifiers);
3597 rem_anchor_token(')');
3602 if (specifiers->thread_local) {
3603 errorf(HERE, "duplicate '__thread'");
3605 specifiers->thread_local = true;
3606 check_thread_storage_class:
3607 switch (specifiers->storage_class) {
3608 case STORAGE_CLASS_EXTERN:
3609 case STORAGE_CLASS_NONE:
3610 case STORAGE_CLASS_STATIC:
3614 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
3615 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
3616 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
3617 wrong_thread_stoarge_class:
3618 errorf(HERE, "'__thread' used with '%s'", wrong);
3625 /* type qualifiers */
3626 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3628 qualifiers |= qualifier; \
3632 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3633 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3634 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3635 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3636 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3637 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3638 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3639 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3641 case T___extension__:
3643 in_gcc_extension = true;
3646 /* type specifiers */
3647 #define MATCH_SPECIFIER(token, specifier, name) \
3649 if (type_specifiers & specifier) { \
3650 errorf(HERE, "multiple " name " type specifiers given"); \
3652 type_specifiers |= specifier; \
3657 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3658 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3659 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3660 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3661 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3662 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3663 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3664 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3665 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3666 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3667 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3668 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3669 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3670 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3671 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3672 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3673 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3675 case T__forceinline:
3676 /* only in microsoft mode */
3677 specifiers->modifiers |= DM_FORCEINLINE;
3682 specifiers->is_inline = true;
3686 if (type_specifiers & SPECIFIER_LONG_LONG) {
3687 errorf(HERE, "multiple type specifiers given");
3688 } else if (type_specifiers & SPECIFIER_LONG) {
3689 type_specifiers |= SPECIFIER_LONG_LONG;
3691 type_specifiers |= SPECIFIER_LONG;
3697 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3699 type->compound.compound = parse_compound_type_specifier(true);
3700 finish_struct_type(&type->compound);
3704 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3705 type->compound.compound = parse_compound_type_specifier(false);
3706 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3707 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3708 finish_union_type(&type->compound);
3712 type = parse_enum_specifier();
3715 type = parse_typeof();
3717 case T___builtin_va_list:
3718 type = duplicate_type(type_valist);
3722 case T_IDENTIFIER: {
3723 /* only parse identifier if we haven't found a type yet */
3724 if (type != NULL || type_specifiers != 0) {
3725 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3726 * declaration, so it doesn't generate errors about expecting '(' or
3728 switch (look_ahead(1)->type) {
3735 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3739 errorf(HERE, "discarding stray '%K' in declaration specifier", &token);
3744 goto finish_specifiers;
3748 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3749 if (typedef_type == NULL) {
3750 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3751 * declaration, so it doesn't generate 'implicit int' followed by more
3752 * errors later on. */
3753 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3759 errorf(HERE, "'%K' does not name a type", &token);
3762 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3764 type = allocate_type_zero(TYPE_TYPEDEF);
3765 type->typedeft.typedefe = &entity->typedefe;
3769 if (la1_type == '&' || la1_type == '*')
3770 goto finish_specifiers;
3775 goto finish_specifiers;
3780 type = typedef_type;
3784 /* function specifier */
3786 goto finish_specifiers;
3791 in_gcc_extension = old_gcc_extension;
3793 if (type == NULL || (saw_error && type_specifiers != 0)) {
3794 atomic_type_kind_t atomic_type;
3796 /* match valid basic types */
3797 switch (type_specifiers) {
3798 case SPECIFIER_VOID:
3799 atomic_type = ATOMIC_TYPE_VOID;
3801 case SPECIFIER_CHAR:
3802 atomic_type = ATOMIC_TYPE_CHAR;
3804 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3805 atomic_type = ATOMIC_TYPE_SCHAR;
3807 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3808 atomic_type = ATOMIC_TYPE_UCHAR;
3810 case SPECIFIER_SHORT:
3811 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3812 case SPECIFIER_SHORT | SPECIFIER_INT:
3813 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3814 atomic_type = ATOMIC_TYPE_SHORT;
3816 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3817 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3818 atomic_type = ATOMIC_TYPE_USHORT;
3821 case SPECIFIER_SIGNED:
3822 case SPECIFIER_SIGNED | SPECIFIER_INT:
3823 atomic_type = ATOMIC_TYPE_INT;
3825 case SPECIFIER_UNSIGNED:
3826 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3827 atomic_type = ATOMIC_TYPE_UINT;
3829 case SPECIFIER_LONG:
3830 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3831 case SPECIFIER_LONG | SPECIFIER_INT:
3832 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3833 atomic_type = ATOMIC_TYPE_LONG;
3835 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3836 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3837 atomic_type = ATOMIC_TYPE_ULONG;
3840 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3841 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3842 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3843 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3845 atomic_type = ATOMIC_TYPE_LONGLONG;
3846 goto warn_about_long_long;
3848 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3849 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3851 atomic_type = ATOMIC_TYPE_ULONGLONG;
3852 warn_about_long_long:
3853 if (warning.long_long) {
3854 warningf(&specifiers->source_position,
3855 "ISO C90 does not support 'long long'");
3859 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3860 atomic_type = unsigned_int8_type_kind;
3863 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3864 atomic_type = unsigned_int16_type_kind;
3867 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3868 atomic_type = unsigned_int32_type_kind;
3871 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3872 atomic_type = unsigned_int64_type_kind;
3875 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3876 atomic_type = unsigned_int128_type_kind;
3879 case SPECIFIER_INT8:
3880 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3881 atomic_type = int8_type_kind;
3884 case SPECIFIER_INT16:
3885 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3886 atomic_type = int16_type_kind;
3889 case SPECIFIER_INT32:
3890 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3891 atomic_type = int32_type_kind;
3894 case SPECIFIER_INT64:
3895 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3896 atomic_type = int64_type_kind;
3899 case SPECIFIER_INT128:
3900 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3901 atomic_type = int128_type_kind;
3904 case SPECIFIER_FLOAT:
3905 atomic_type = ATOMIC_TYPE_FLOAT;
3907 case SPECIFIER_DOUBLE:
3908 atomic_type = ATOMIC_TYPE_DOUBLE;
3910 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3911 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3913 case SPECIFIER_BOOL:
3914 atomic_type = ATOMIC_TYPE_BOOL;
3916 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3917 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3918 atomic_type = ATOMIC_TYPE_FLOAT;
3920 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3921 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3922 atomic_type = ATOMIC_TYPE_DOUBLE;
3924 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3925 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3926 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3929 /* invalid specifier combination, give an error message */
3930 if (type_specifiers == 0) {
3934 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3935 if (!(c_mode & _CXX) && !strict_mode) {
3936 if (warning.implicit_int) {
3937 warningf(HERE, "no type specifiers in declaration, using 'int'");
3939 atomic_type = ATOMIC_TYPE_INT;
3942 errorf(HERE, "no type specifiers given in declaration");
3944 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3945 (type_specifiers & SPECIFIER_UNSIGNED)) {
3946 errorf(HERE, "signed and unsigned specifiers given");
3947 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3948 errorf(HERE, "only integer types can be signed or unsigned");
3950 errorf(HERE, "multiple datatypes in declaration");
3955 if (type_specifiers & SPECIFIER_COMPLEX) {
3956 type = allocate_type_zero(TYPE_COMPLEX);
3957 type->complex.akind = atomic_type;
3958 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3959 type = allocate_type_zero(TYPE_IMAGINARY);
3960 type->imaginary.akind = atomic_type;
3962 type = allocate_type_zero(TYPE_ATOMIC);
3963 type->atomic.akind = atomic_type;
3966 } else if (type_specifiers != 0) {
3967 errorf(HERE, "multiple datatypes in declaration");
3970 /* FIXME: check type qualifiers here */
3972 type->base.qualifiers = qualifiers;
3973 type->base.modifiers = modifiers;
3975 type_t *result = typehash_insert(type);
3976 if (newtype && result != type) {
3980 specifiers->type = result;
3984 specifiers->type = type_error_type;
3988 static type_qualifiers_t parse_type_qualifiers(void)
3990 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3993 switch (token.type) {
3994 /* type qualifiers */
3995 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3996 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3997 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3998 /* microsoft extended type modifiers */
3999 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
4000 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
4001 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
4002 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
4003 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
4012 * Parses an K&R identifier list
4014 static void parse_identifier_list(scope_t *scope)
4017 entity_t *entity = allocate_entity_zero(ENTITY_VARIABLE);
4018 entity->base.source_position = token.source_position;
4019 entity->base.namespc = NAMESPACE_NORMAL;
4020 entity->base.symbol = token.v.symbol;
4021 /* a K&R parameter has no type, yet */
4024 append_entity(scope, entity);
4026 if (token.type != ',') {
4030 } while (token.type == T_IDENTIFIER);
4033 static void semantic_parameter(declaration_t *declaration)
4035 /* TODO: improve error messages */
4036 source_position_t const* const pos = &declaration->base.source_position;
4038 /* §6.9.1:6 The declarations in the declaration list shall contain no
4039 * storage-class specifier other than register and no
4040 * initializations. */
4041 switch (declaration->declared_storage_class) {
4042 /* Allowed storage classes */
4043 case STORAGE_CLASS_NONE:
4044 case STORAGE_CLASS_REGISTER:
4048 errorf(pos, "parameter may only have none or register storage class");
4052 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type list in
4053 * a function declarator that is part of a definition of that
4054 * function shall not have incomplete type. */
4055 type_t *type = declaration->type;
4056 if (is_type_incomplete(skip_typeref(type))) {
4057 errorf(pos, "parameter '%#T' has incomplete type",
4058 type, declaration->base.symbol);
4062 static entity_t *parse_parameter(void)
4064 declaration_specifiers_t specifiers;
4065 memset(&specifiers, 0, sizeof(specifiers));
4067 parse_declaration_specifiers(&specifiers);
4069 entity_t *entity = parse_declarator(&specifiers,
4070 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
4071 anonymous_entity = NULL;
4076 * Parses function type parameters (and optionally creates variable_t entities
4077 * for them in a scope)
4079 static void parse_parameters(function_type_t *type, scope_t *scope)
4082 add_anchor_token(')');
4083 int saved_comma_state = save_and_reset_anchor_state(',');
4085 if (token.type == T_IDENTIFIER &&
4086 !is_typedef_symbol(token.v.symbol)) {
4087 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4088 if (la1_type == ',' || la1_type == ')') {
4089 type->kr_style_parameters = true;
4090 parse_identifier_list(scope);
4091 goto parameters_finished;
4095 if (token.type == ')') {
4096 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4097 if (!(c_mode & _CXX))
4098 type->unspecified_parameters = true;
4099 goto parameters_finished;
4102 function_parameter_t *parameter;
4103 function_parameter_t *last_parameter = NULL;
4106 switch (token.type) {
4109 type->variadic = true;
4110 goto parameters_finished;
4113 case T___extension__:
4116 entity_t *entity = parse_parameter();
4117 if (entity->kind == ENTITY_TYPEDEF) {
4118 errorf(&entity->base.source_position,
4119 "typedef not allowed as function parameter");
4122 assert(is_declaration(entity));
4124 /* func(void) is not a parameter */
4125 if (last_parameter == NULL
4126 && token.type == ')'
4127 && entity->base.symbol == NULL
4128 && skip_typeref(entity->declaration.type) == type_void) {
4129 goto parameters_finished;
4131 semantic_parameter(&entity->declaration);
4133 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4134 memset(parameter, 0, sizeof(parameter[0]));
4135 parameter->type = entity->declaration.type;
4137 if (scope != NULL) {
4138 append_entity(scope, entity);
4141 if (last_parameter != NULL) {
4142 last_parameter->next = parameter;
4144 type->parameters = parameter;
4146 last_parameter = parameter;
4151 goto parameters_finished;
4153 if (token.type != ',') {
4154 goto parameters_finished;
4160 parameters_finished:
4161 rem_anchor_token(')');
4165 restore_anchor_state(',', saved_comma_state);
4168 typedef enum construct_type_kind_t {
4171 CONSTRUCT_REFERENCE,
4174 } construct_type_kind_t;
4176 typedef struct construct_type_t construct_type_t;
4177 struct construct_type_t {
4178 construct_type_kind_t kind;
4179 construct_type_t *next;
4182 typedef struct parsed_pointer_t parsed_pointer_t;
4183 struct parsed_pointer_t {
4184 construct_type_t construct_type;
4185 type_qualifiers_t type_qualifiers;
4186 variable_t *base_variable; /**< MS __based extension. */
4189 typedef struct parsed_reference_t parsed_reference_t;
4190 struct parsed_reference_t {
4191 construct_type_t construct_type;
4194 typedef struct construct_function_type_t construct_function_type_t;
4195 struct construct_function_type_t {
4196 construct_type_t construct_type;
4197 type_t *function_type;
4200 typedef struct parsed_array_t parsed_array_t;
4201 struct parsed_array_t {
4202 construct_type_t construct_type;
4203 type_qualifiers_t type_qualifiers;
4209 typedef struct construct_base_type_t construct_base_type_t;
4210 struct construct_base_type_t {
4211 construct_type_t construct_type;
4215 static construct_type_t *parse_pointer_declarator(variable_t *base_variable)
4219 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4220 memset(pointer, 0, sizeof(pointer[0]));
4221 pointer->construct_type.kind = CONSTRUCT_POINTER;
4222 pointer->type_qualifiers = parse_type_qualifiers();
4223 pointer->base_variable = base_variable;
4225 return &pointer->construct_type;
4228 static construct_type_t *parse_reference_declarator(void)
4232 parsed_reference_t *reference = obstack_alloc(&temp_obst, sizeof(reference[0]));
4233 memset(reference, 0, sizeof(reference[0]));
4234 reference->construct_type.kind = CONSTRUCT_REFERENCE;
4236 return (construct_type_t*)reference;
4239 static construct_type_t *parse_array_declarator(void)
4242 add_anchor_token(']');
4244 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4245 memset(array, 0, sizeof(array[0]));
4246 array->construct_type.kind = CONSTRUCT_ARRAY;
4248 if (token.type == T_static) {
4249 array->is_static = true;
4253 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4254 if (type_qualifiers != 0) {
4255 if (token.type == T_static) {
4256 array->is_static = true;
4260 array->type_qualifiers = type_qualifiers;
4262 if (token.type == '*' && look_ahead(1)->type == ']') {
4263 array->is_variable = true;
4265 } else if (token.type != ']') {
4266 array->size = parse_assignment_expression();
4269 rem_anchor_token(']');
4273 return &array->construct_type;
4276 static construct_type_t *parse_function_declarator(scope_t *scope,
4277 decl_modifiers_t modifiers)
4279 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4280 function_type_t *ftype = &type->function;
4282 ftype->linkage = current_linkage;
4284 switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
4285 case DM_NONE: break;
4286 case DM_CDECL: ftype->calling_convention = CC_CDECL; break;
4287 case DM_STDCALL: ftype->calling_convention = CC_STDCALL; break;
4288 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
4289 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
4292 errorf(HERE, "multiple calling conventions in declaration");
4296 parse_parameters(ftype, scope);
4298 construct_function_type_t *construct_function_type =
4299 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4300 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4301 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4302 construct_function_type->function_type = type;
4304 return &construct_function_type->construct_type;
4307 typedef struct parse_declarator_env_t {
4308 decl_modifiers_t modifiers;
4310 source_position_t source_position;
4312 } parse_declarator_env_t;
4314 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4315 bool may_be_abstract)
4317 /* construct a single linked list of construct_type_t's which describe
4318 * how to construct the final declarator type */
4319 construct_type_t *first = NULL;
4320 construct_type_t *last = NULL;
4321 gnu_attribute_t *attributes = NULL;
4323 decl_modifiers_t modifiers = parse_attributes(&attributes);
4325 /* MS __based extension */
4326 based_spec_t base_spec;
4327 base_spec.base_variable = NULL;
4330 construct_type_t *type;
4331 switch (token.type) {
4333 if (!(c_mode & _CXX))
4334 errorf(HERE, "references are only available for C++");
4335 if (base_spec.base_variable != NULL && warning.other) {
4336 warningf(&base_spec.source_position,
4337 "__based does not precede a pointer operator, ignored");
4339 type = parse_reference_declarator();
4341 base_spec.base_variable = NULL;
4345 type = parse_pointer_declarator(base_spec.base_variable);
4347 base_spec.base_variable = NULL;
4353 add_anchor_token(')');
4354 parse_microsoft_based(&base_spec);
4355 rem_anchor_token(')');
4360 goto ptr_operator_end;
4371 /* TODO: find out if this is correct */
4372 modifiers |= parse_attributes(&attributes);
4375 if (base_spec.base_variable != NULL && warning.other) {
4376 warningf(&base_spec.source_position,
4377 "__based does not precede a pointer operator, ignored");
4381 modifiers |= env->modifiers;
4382 env->modifiers = modifiers;
4385 construct_type_t *inner_types = NULL;
4387 switch (token.type) {
4390 errorf(HERE, "no identifier expected in typename");
4392 env->symbol = token.v.symbol;
4393 env->source_position = token.source_position;
4399 add_anchor_token(')');
4400 inner_types = parse_inner_declarator(env, may_be_abstract);
4401 if (inner_types != NULL) {
4402 /* All later declarators only modify the return type */
4405 rem_anchor_token(')');
4409 if (may_be_abstract)
4411 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4416 construct_type_t *p = last;
4419 construct_type_t *type;
4420 switch (token.type) {
4422 scope_t *scope = NULL;
4424 scope = &env->parameters;
4426 type = parse_function_declarator(scope, modifiers);
4430 type = parse_array_declarator();
4433 goto declarator_finished;
4436 /* insert in the middle of the list (behind p) */
4438 type->next = p->next;
4449 declarator_finished:
4450 /* append inner_types at the end of the list, we don't to set last anymore
4451 * as it's not needed anymore */
4453 assert(first == NULL);
4454 first = inner_types;
4456 last->next = inner_types;
4464 static void parse_declaration_attributes(entity_t *entity)
4466 gnu_attribute_t *attributes = NULL;
4467 decl_modifiers_t modifiers = parse_attributes(&attributes);
4473 if (entity->kind == ENTITY_TYPEDEF) {
4474 modifiers |= entity->typedefe.modifiers;
4475 type = entity->typedefe.type;
4477 assert(is_declaration(entity));
4478 modifiers |= entity->declaration.modifiers;
4479 type = entity->declaration.type;
4484 /* handle these strange/stupid mode attributes */
4485 gnu_attribute_t *attribute = attributes;
4486 for ( ; attribute != NULL; attribute = attribute->next) {
4487 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4490 atomic_type_kind_t akind = attribute->u.akind;
4491 if (!is_type_signed(type)) {
4493 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4494 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4495 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4496 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4498 panic("invalid akind in mode attribute");
4502 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_SCHAR; break;
4503 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_SHORT; break;
4504 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_INT; break;
4505 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_LONGLONG; break;
4507 panic("invalid akind in mode attribute");
4511 type = make_atomic_type(akind, type->base.qualifiers);
4514 type_modifiers_t type_modifiers = type->base.modifiers;
4515 if (modifiers & DM_TRANSPARENT_UNION)
4516 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4518 if (type->base.modifiers != type_modifiers) {
4519 type_t *copy = duplicate_type(type);
4520 copy->base.modifiers = type_modifiers;
4522 type = typehash_insert(copy);
4524 obstack_free(type_obst, copy);
4528 if (entity->kind == ENTITY_TYPEDEF) {
4529 entity->typedefe.type = type;
4530 entity->typedefe.modifiers = modifiers;
4532 entity->declaration.type = type;
4533 entity->declaration.modifiers = modifiers;
4537 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
4539 construct_type_t *iter = construct_list;
4540 for (; iter != NULL; iter = iter->next) {
4541 switch (iter->kind) {
4542 case CONSTRUCT_INVALID:
4543 internal_errorf(HERE, "invalid type construction found");
4544 case CONSTRUCT_FUNCTION: {
4545 construct_function_type_t *construct_function_type
4546 = (construct_function_type_t*) iter;
4548 type_t *function_type = construct_function_type->function_type;
4550 function_type->function.return_type = type;
4552 type_t *skipped_return_type = skip_typeref(type);
4554 if (is_type_function(skipped_return_type)) {
4555 errorf(HERE, "function returning function is not allowed");
4556 } else if (is_type_array(skipped_return_type)) {
4557 errorf(HERE, "function returning array is not allowed");
4559 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4561 "type qualifiers in return type of function type are meaningless");
4565 type = function_type;
4569 case CONSTRUCT_POINTER: {
4570 if (is_type_reference(skip_typeref(type)))
4571 errorf(HERE, "cannot declare a pointer to reference");
4573 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4574 type = make_based_pointer_type(type, parsed_pointer->type_qualifiers, parsed_pointer->base_variable);
4578 case CONSTRUCT_REFERENCE:
4579 if (is_type_reference(skip_typeref(type)))
4580 errorf(HERE, "cannot declare a reference to reference");
4582 type = make_reference_type(type);
4585 case CONSTRUCT_ARRAY: {
4586 if (is_type_reference(skip_typeref(type)))
4587 errorf(HERE, "cannot declare an array of references");
4589 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4590 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4592 expression_t *size_expression = parsed_array->size;
4593 if (size_expression != NULL) {
4595 = create_implicit_cast(size_expression, type_size_t);
4598 array_type->base.qualifiers = parsed_array->type_qualifiers;
4599 array_type->array.element_type = type;
4600 array_type->array.is_static = parsed_array->is_static;
4601 array_type->array.is_variable = parsed_array->is_variable;
4602 array_type->array.size_expression = size_expression;
4604 if (size_expression != NULL) {
4605 if (is_constant_expression(size_expression)) {
4606 array_type->array.size_constant = true;
4607 array_type->array.size
4608 = fold_constant(size_expression);
4610 array_type->array.is_vla = true;
4614 type_t *skipped_type = skip_typeref(type);
4616 if (is_type_incomplete(skipped_type)) {
4617 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4618 } else if (is_type_function(skipped_type)) {
4619 errorf(HERE, "array of functions is not allowed");
4626 type_t *hashed_type = typehash_insert(type);
4627 if (hashed_type != type) {
4628 /* the function type was constructed earlier freeing it here will
4629 * destroy other types... */
4630 if (iter->kind != CONSTRUCT_FUNCTION) {
4640 static type_t *automatic_type_conversion(type_t *orig_type);
4642 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4643 declarator_flags_t flags)
4645 parse_declarator_env_t env;
4646 memset(&env, 0, sizeof(env));
4647 env.modifiers = specifiers->modifiers;
4649 construct_type_t *construct_type =
4650 parse_inner_declarator(&env, (flags & DECL_MAY_BE_ABSTRACT) != 0);
4652 construct_declarator_type(construct_type, specifiers->type);
4653 type_t *type = skip_typeref(orig_type);
4655 if (construct_type != NULL) {
4656 obstack_free(&temp_obst, construct_type);
4660 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4661 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4662 entity->base.symbol = env.symbol;
4663 entity->base.source_position = env.source_position;
4664 entity->typedefe.type = orig_type;
4666 if (anonymous_entity != NULL) {
4667 if (is_type_compound(type)) {
4668 assert(anonymous_entity->compound.alias == NULL);
4669 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4670 anonymous_entity->kind == ENTITY_UNION);
4671 anonymous_entity->compound.alias = entity;
4672 anonymous_entity = NULL;
4673 } else if (is_type_enum(type)) {
4674 assert(anonymous_entity->enume.alias == NULL);
4675 assert(anonymous_entity->kind == ENTITY_ENUM);
4676 anonymous_entity->enume.alias = entity;
4677 anonymous_entity = NULL;
4681 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
4682 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4684 if (specifiers->is_inline && is_type_valid(type)) {
4685 errorf(&env.source_position,
4686 "compound member '%Y' declared 'inline'", env.symbol);
4689 if (specifiers->thread_local ||
4690 specifiers->storage_class != STORAGE_CLASS_NONE) {
4691 errorf(&env.source_position,
4692 "compound member '%Y' must have no storage class",
4695 } else if (flags & DECL_IS_PARAMETER) {
4696 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
4697 * shall be adjusted to ``qualified pointer to type'',
4699 * §6.7.5.3:8 A declaration of a parameter as ``function returning
4700 * type'' shall be adjusted to ``pointer to function
4701 * returning type'', as in 6.3.2.1. */
4702 orig_type = automatic_type_conversion(type);
4703 goto create_variable;
4704 } else if (is_type_function(type)) {
4705 entity = allocate_entity_zero(ENTITY_FUNCTION);
4707 entity->function.is_inline = specifiers->is_inline;
4708 entity->function.parameters = env.parameters;
4710 if (specifiers->thread_local || (
4711 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4712 specifiers->storage_class != STORAGE_CLASS_NONE &&
4713 specifiers->storage_class != STORAGE_CLASS_STATIC)
4715 errorf(&env.source_position,
4716 "invalid storage class for function '%Y'", env.symbol);
4720 entity = allocate_entity_zero(ENTITY_VARIABLE);
4722 entity->variable.get_property_sym = specifiers->get_property_sym;
4723 entity->variable.put_property_sym = specifiers->put_property_sym;
4724 if (specifiers->alignment != 0) {
4725 /* TODO: add checks here */
4726 entity->variable.alignment = specifiers->alignment;
4729 if (specifiers->is_inline && is_type_valid(type)) {
4730 errorf(&env.source_position,
4731 "variable '%Y' declared 'inline'", env.symbol);
4734 entity->variable.thread_local = specifiers->thread_local;
4736 bool invalid_storage_class = false;
4737 if (current_scope == file_scope) {
4738 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4739 specifiers->storage_class != STORAGE_CLASS_NONE &&
4740 specifiers->storage_class != STORAGE_CLASS_STATIC) {
4741 invalid_storage_class = true;
4744 if (specifiers->thread_local &&
4745 specifiers->storage_class == STORAGE_CLASS_NONE) {
4746 invalid_storage_class = true;
4749 if (invalid_storage_class) {
4750 errorf(&env.source_position,
4751 "invalid storage class for variable '%Y'", env.symbol);
4755 entity->base.source_position = env.source_position;
4756 entity->base.symbol = env.symbol;
4757 entity->base.namespc = NAMESPACE_NORMAL;
4758 entity->declaration.type = orig_type;
4759 entity->declaration.modifiers = env.modifiers;
4760 entity->declaration.deprecated_string = specifiers->deprecated_string;
4762 storage_class_t storage_class = specifiers->storage_class;
4763 entity->declaration.declared_storage_class = storage_class;
4765 if (storage_class == STORAGE_CLASS_NONE
4766 && current_scope != file_scope) {
4767 storage_class = STORAGE_CLASS_AUTO;
4769 entity->declaration.storage_class = storage_class;
4772 parse_declaration_attributes(entity);
4777 static type_t *parse_abstract_declarator(type_t *base_type)
4779 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4781 type_t *result = construct_declarator_type(construct_type, base_type);
4782 if (construct_type != NULL) {
4783 obstack_free(&temp_obst, construct_type);
4790 * Check if the declaration of main is suspicious. main should be a
4791 * function with external linkage, returning int, taking either zero
4792 * arguments, two, or three arguments of appropriate types, ie.
4794 * int main([ int argc, char **argv [, char **env ] ]).
4796 * @param decl the declaration to check
4797 * @param type the function type of the declaration
4799 static void check_type_of_main(const entity_t *entity)
4801 const source_position_t *pos = &entity->base.source_position;
4802 if (entity->kind != ENTITY_FUNCTION) {
4803 warningf(pos, "'main' is not a function");
4807 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4808 warningf(pos, "'main' is normally a non-static function");
4811 type_t *type = skip_typeref(entity->declaration.type);
4812 assert(is_type_function(type));
4814 function_type_t *func_type = &type->function;
4815 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4816 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4817 func_type->return_type);
4819 const function_parameter_t *parm = func_type->parameters;
4821 type_t *const first_type = parm->type;
4822 if (!types_compatible(skip_typeref(first_type), type_int)) {
4824 "first argument of 'main' should be 'int', but is '%T'",
4829 type_t *const second_type = parm->type;
4830 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4831 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4835 type_t *const third_type = parm->type;
4836 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4837 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4841 goto warn_arg_count;
4845 warningf(pos, "'main' takes only zero, two or three arguments");
4851 * Check if a symbol is the equal to "main".
4853 static bool is_sym_main(const symbol_t *const sym)
4855 return strcmp(sym->string, "main") == 0;
4858 static const char *get_entity_kind_name(entity_kind_t kind)
4860 switch ((entity_kind_tag_t) kind) {
4861 case ENTITY_FUNCTION: return "function";
4862 case ENTITY_VARIABLE: return "variable";
4863 case ENTITY_COMPOUND_MEMBER: return "compound type member";
4864 case ENTITY_STRUCT: return "struct";
4865 case ENTITY_UNION: return "union";
4866 case ENTITY_ENUM: return "enum";
4867 case ENTITY_ENUM_VALUE: return "enum value";
4868 case ENTITY_LABEL: return "label";
4869 case ENTITY_LOCAL_LABEL: return "local label";
4870 case ENTITY_TYPEDEF: return "typedef";
4871 case ENTITY_NAMESPACE: return "namespace";
4872 case ENTITY_INVALID: break;
4875 panic("Invalid entity kind encountered in get_entity_kind_name");
4878 static void error_redefined_as_different_kind(const source_position_t *pos,
4879 const entity_t *old, entity_kind_t new_kind)
4881 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4882 get_entity_kind_name(old->kind), old->base.symbol,
4883 get_entity_kind_name(new_kind), &old->base.source_position);
4887 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4888 * for various problems that occur for multiple definitions
4890 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4892 const symbol_t *const symbol = entity->base.symbol;
4893 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4894 const source_position_t *pos = &entity->base.source_position;
4896 assert(symbol != NULL);
4897 entity_t *previous_entity = get_entity(symbol, namespc);
4898 /* pushing the same entity twice will break the stack structure */
4899 assert(previous_entity != entity);
4901 if (entity->kind == ENTITY_FUNCTION) {
4902 type_t *const orig_type = entity->declaration.type;
4903 type_t *const type = skip_typeref(orig_type);
4905 assert(is_type_function(type));
4906 if (type->function.unspecified_parameters &&
4907 warning.strict_prototypes &&
4908 previous_entity == NULL) {
4909 warningf(pos, "function declaration '%#T' is not a prototype",
4913 if (warning.main && current_scope == file_scope
4914 && is_sym_main(symbol)) {
4915 check_type_of_main(entity);
4919 if (is_declaration(entity)) {
4920 if (warning.nested_externs
4921 && entity->declaration.storage_class == STORAGE_CLASS_EXTERN
4922 && current_scope != file_scope) {
4923 warningf(pos, "nested extern declaration of '%#T'",
4924 entity->declaration.type, symbol);
4928 if (previous_entity != NULL
4929 && previous_entity->base.parent_scope == ¤t_function->parameters
4930 && current_scope->depth == previous_entity->base.parent_scope->depth+1){
4932 assert(previous_entity->kind == ENTITY_VARIABLE);
4934 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4935 entity->declaration.type, symbol,
4936 previous_entity->declaration.type, symbol,
4937 &previous_entity->base.source_position);
4941 if (previous_entity != NULL
4942 && previous_entity->base.parent_scope == current_scope) {
4944 if (previous_entity->kind != entity->kind) {
4945 error_redefined_as_different_kind(pos, previous_entity,
4949 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4951 "redeclaration of enum entry '%Y' (declared %P)",
4952 symbol, &previous_entity->base.source_position);
4955 if (previous_entity->kind == ENTITY_TYPEDEF) {
4956 /* TODO: C++ allows this for exactly the same type */
4958 "redefinition of typedef '%Y' (declared %P)",
4959 symbol, &previous_entity->base.source_position);
4963 /* at this point we should have only VARIABLES or FUNCTIONS */
4964 assert(is_declaration(previous_entity) && is_declaration(entity));
4966 /* can happen for K&R style declarations */
4967 if (previous_entity->kind == ENTITY_VARIABLE
4968 && previous_entity->declaration.type == NULL
4969 && entity->kind == ENTITY_VARIABLE) {
4970 previous_entity->declaration.type = entity->declaration.type;
4971 previous_entity->declaration.storage_class
4972 = entity->declaration.storage_class;
4973 previous_entity->declaration.declared_storage_class
4974 = entity->declaration.declared_storage_class;
4975 previous_entity->declaration.modifiers
4976 = entity->declaration.modifiers;
4977 previous_entity->declaration.deprecated_string
4978 = entity->declaration.deprecated_string;
4980 assert(entity->declaration.type != NULL);
4982 declaration_t *const previous_declaration
4983 = &previous_entity->declaration;
4984 declaration_t *const declaration = &entity->declaration;
4985 type_t *const orig_type = entity->declaration.type;
4986 type_t *const type = skip_typeref(orig_type);
4988 type_t *prev_type = skip_typeref(previous_declaration->type);
4990 if (!types_compatible(type, prev_type)) {
4992 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4993 orig_type, symbol, previous_declaration->type, symbol,
4994 &previous_entity->base.source_position);
4996 unsigned old_storage_class = previous_declaration->storage_class;
4997 if (warning.redundant_decls && is_definition
4998 && previous_declaration->storage_class == STORAGE_CLASS_STATIC
4999 && !(previous_declaration->modifiers & DM_USED)
5000 && !previous_declaration->used) {
5001 warningf(&previous_entity->base.source_position,
5002 "unnecessary static forward declaration for '%#T'",
5003 previous_declaration->type, symbol);
5006 unsigned new_storage_class = declaration->storage_class;
5007 if (is_type_incomplete(prev_type)) {
5008 previous_declaration->type = type;
5012 /* pretend no storage class means extern for function
5013 * declarations (except if the previous declaration is neither
5014 * none nor extern) */
5015 if (entity->kind == ENTITY_FUNCTION) {
5016 if (prev_type->function.unspecified_parameters) {
5017 previous_declaration->type = type;
5021 switch (old_storage_class) {
5022 case STORAGE_CLASS_NONE:
5023 old_storage_class = STORAGE_CLASS_EXTERN;
5026 case STORAGE_CLASS_EXTERN:
5027 if (is_definition) {
5028 if (warning.missing_prototypes &&
5029 prev_type->function.unspecified_parameters &&
5030 !is_sym_main(symbol)) {
5031 warningf(pos, "no previous prototype for '%#T'",
5034 } else if (new_storage_class == STORAGE_CLASS_NONE) {
5035 new_storage_class = STORAGE_CLASS_EXTERN;
5044 if (old_storage_class == STORAGE_CLASS_EXTERN &&
5045 new_storage_class == STORAGE_CLASS_EXTERN) {
5046 warn_redundant_declaration:
5047 if (!is_definition &&
5048 warning.redundant_decls &&
5049 is_type_valid(prev_type) &&
5050 strcmp(previous_entity->base.source_position.input_name, "<builtin>") != 0) {
5052 "redundant declaration for '%Y' (declared %P)",
5053 symbol, &previous_entity->base.source_position);
5055 } else if (current_function == NULL) {
5056 if (old_storage_class != STORAGE_CLASS_STATIC &&
5057 new_storage_class == STORAGE_CLASS_STATIC) {
5059 "static declaration of '%Y' follows non-static declaration (declared %P)",
5060 symbol, &previous_entity->base.source_position);
5061 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
5062 previous_declaration->storage_class = STORAGE_CLASS_NONE;
5063 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
5065 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
5067 goto error_redeclaration;
5068 goto warn_redundant_declaration;
5070 } else if (is_type_valid(prev_type)) {
5071 if (old_storage_class == new_storage_class) {
5072 error_redeclaration:
5073 errorf(pos, "redeclaration of '%Y' (declared %P)",
5074 symbol, &previous_entity->base.source_position);
5077 "redeclaration of '%Y' with different linkage (declared %P)",
5078 symbol, &previous_entity->base.source_position);
5083 previous_declaration->modifiers |= declaration->modifiers;
5084 if (entity->kind == ENTITY_FUNCTION) {
5085 previous_entity->function.is_inline |= entity->function.is_inline;
5087 return previous_entity;
5090 if (entity->kind == ENTITY_FUNCTION) {
5091 if (is_definition &&
5092 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
5093 if (warning.missing_prototypes && !is_sym_main(symbol)) {
5094 warningf(pos, "no previous prototype for '%#T'",
5095 entity->declaration.type, symbol);
5096 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
5097 warningf(pos, "no previous declaration for '%#T'",
5098 entity->declaration.type, symbol);
5101 } else if (warning.missing_declarations
5102 && entity->kind == ENTITY_VARIABLE
5103 && current_scope == file_scope) {
5104 declaration_t *declaration = &entity->declaration;
5105 if (declaration->storage_class == STORAGE_CLASS_NONE) {
5106 warningf(pos, "no previous declaration for '%#T'",
5107 declaration->type, symbol);
5112 assert(entity->base.parent_scope == NULL);
5113 assert(current_scope != NULL);
5115 entity->base.parent_scope = current_scope;
5116 entity->base.namespc = NAMESPACE_NORMAL;
5117 environment_push(entity);
5118 append_entity(current_scope, entity);
5123 static void parser_error_multiple_definition(entity_t *entity,
5124 const source_position_t *source_position)
5126 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
5127 entity->base.symbol, &entity->base.source_position);
5130 static bool is_declaration_specifier(const token_t *token,
5131 bool only_specifiers_qualifiers)
5133 switch (token->type) {
5138 return is_typedef_symbol(token->v.symbol);
5140 case T___extension__:
5142 return !only_specifiers_qualifiers;
5149 static void parse_init_declarator_rest(entity_t *entity)
5151 assert(is_declaration(entity));
5152 declaration_t *const declaration = &entity->declaration;
5156 type_t *orig_type = declaration->type;
5157 type_t *type = skip_typeref(orig_type);
5159 if (entity->kind == ENTITY_VARIABLE
5160 && entity->variable.initializer != NULL) {
5161 parser_error_multiple_definition(entity, HERE);
5164 bool must_be_constant = false;
5165 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5166 entity->base.parent_scope == file_scope) {
5167 must_be_constant = true;
5170 if (is_type_function(type)) {
5171 errorf(&entity->base.source_position,
5172 "function '%#T' is initialized like a variable",
5173 orig_type, entity->base.symbol);
5174 orig_type = type_error_type;
5177 parse_initializer_env_t env;
5178 env.type = orig_type;
5179 env.must_be_constant = must_be_constant;
5180 env.entity = entity;
5181 current_init_decl = entity;
5183 initializer_t *initializer = parse_initializer(&env);
5184 current_init_decl = NULL;
5186 if (entity->kind == ENTITY_VARIABLE) {
5187 /* § 6.7.5 (22) array initializers for arrays with unknown size
5188 * determine the array type size */
5189 declaration->type = env.type;
5190 entity->variable.initializer = initializer;
5194 /* parse rest of a declaration without any declarator */
5195 static void parse_anonymous_declaration_rest(
5196 const declaration_specifiers_t *specifiers)
5199 anonymous_entity = NULL;
5201 if (warning.other) {
5202 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
5203 specifiers->thread_local) {
5204 warningf(&specifiers->source_position,
5205 "useless storage class in empty declaration");
5208 type_t *type = specifiers->type;
5209 switch (type->kind) {
5210 case TYPE_COMPOUND_STRUCT:
5211 case TYPE_COMPOUND_UNION: {
5212 if (type->compound.compound->base.symbol == NULL) {
5213 warningf(&specifiers->source_position,
5214 "unnamed struct/union that defines no instances");
5223 warningf(&specifiers->source_position, "empty declaration");
5229 static void check_variable_type_complete(entity_t *ent)
5231 if (ent->kind != ENTITY_VARIABLE)
5234 /* §6.7:7 If an identifier for an object is declared with no linkage, the
5235 * type for the object shall be complete [...] */
5236 declaration_t *decl = &ent->declaration;
5237 if (decl->storage_class != STORAGE_CLASS_NONE)
5240 type_t *type = decl->type;
5241 if (!is_type_incomplete(skip_typeref(type)))
5244 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
5245 type, ent->base.symbol);
5249 static void parse_declaration_rest(entity_t *ndeclaration,
5250 const declaration_specifiers_t *specifiers,
5251 parsed_declaration_func finished_declaration,
5252 declarator_flags_t flags)
5254 add_anchor_token(';');
5255 add_anchor_token(',');
5257 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5259 if (token.type == '=') {
5260 parse_init_declarator_rest(entity);
5261 } else if (entity->kind == ENTITY_VARIABLE) {
5262 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
5263 * [...] where the extern specifier is explicitly used. */
5264 declaration_t *decl = &entity->declaration;
5265 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
5266 type_t *type = decl->type;
5267 if (is_type_reference(skip_typeref(type))) {
5268 errorf(&entity->base.source_position,
5269 "reference '%#T' must be initialized",
5270 type, entity->base.symbol);
5275 check_variable_type_complete(entity);
5277 if (token.type != ',')
5281 add_anchor_token('=');
5282 ndeclaration = parse_declarator(specifiers, flags);
5283 rem_anchor_token('=');
5288 anonymous_entity = NULL;
5289 rem_anchor_token(';');
5290 rem_anchor_token(',');
5293 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5295 symbol_t *symbol = entity->base.symbol;
5296 if (symbol == NULL) {
5297 errorf(HERE, "anonymous declaration not valid as function parameter");
5301 assert(entity->base.namespc == NAMESPACE_NORMAL);
5302 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5303 if (previous_entity == NULL
5304 || previous_entity->base.parent_scope != current_scope) {
5305 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5310 if (is_definition) {
5311 errorf(HERE, "parameter %Y is initialised", entity->base.symbol);
5314 return record_entity(entity, false);
5317 static void parse_declaration(parsed_declaration_func finished_declaration,
5318 declarator_flags_t flags)
5320 declaration_specifiers_t specifiers;
5321 memset(&specifiers, 0, sizeof(specifiers));
5323 add_anchor_token(';');
5324 parse_declaration_specifiers(&specifiers);
5325 rem_anchor_token(';');
5327 if (token.type == ';') {
5328 parse_anonymous_declaration_rest(&specifiers);
5330 entity_t *entity = parse_declarator(&specifiers, flags);
5331 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
5335 static type_t *get_default_promoted_type(type_t *orig_type)
5337 type_t *result = orig_type;
5339 type_t *type = skip_typeref(orig_type);
5340 if (is_type_integer(type)) {
5341 result = promote_integer(type);
5342 } else if (type == type_float) {
5343 result = type_double;
5349 static void parse_kr_declaration_list(entity_t *entity)
5351 if (entity->kind != ENTITY_FUNCTION)
5354 type_t *type = skip_typeref(entity->declaration.type);
5355 assert(is_type_function(type));
5356 if (!type->function.kr_style_parameters)
5360 add_anchor_token('{');
5362 /* push function parameters */
5363 size_t const top = environment_top();
5364 scope_t *old_scope = scope_push(&entity->function.parameters);
5366 entity_t *parameter = entity->function.parameters.entities;
5367 for ( ; parameter != NULL; parameter = parameter->base.next) {
5368 assert(parameter->base.parent_scope == NULL);
5369 parameter->base.parent_scope = current_scope;
5370 environment_push(parameter);
5373 /* parse declaration list */
5374 while (is_declaration_specifier(&token, false)) {
5375 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
5378 /* pop function parameters */
5379 assert(current_scope == &entity->function.parameters);
5380 scope_pop(old_scope);
5381 environment_pop_to(top);
5383 /* update function type */
5384 type_t *new_type = duplicate_type(type);
5386 function_parameter_t *parameters = NULL;
5387 function_parameter_t *last_parameter = NULL;
5389 entity_t *parameter_declaration = entity->function.parameters.entities;
5390 for (; parameter_declaration != NULL;
5391 parameter_declaration = parameter_declaration->base.next) {
5392 type_t *parameter_type = parameter_declaration->declaration.type;
5393 if (parameter_type == NULL) {
5395 errorf(HERE, "no type specified for function parameter '%Y'",
5396 parameter_declaration->base.symbol);
5398 if (warning.implicit_int) {
5399 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5400 parameter_declaration->base.symbol);
5402 parameter_type = type_int;
5403 parameter_declaration->declaration.type = parameter_type;
5407 semantic_parameter(¶meter_declaration->declaration);
5408 parameter_type = parameter_declaration->declaration.type;
5411 * we need the default promoted types for the function type
5413 parameter_type = get_default_promoted_type(parameter_type);
5415 function_parameter_t *function_parameter
5416 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5417 memset(function_parameter, 0, sizeof(function_parameter[0]));
5419 function_parameter->type = parameter_type;
5420 if (last_parameter != NULL) {
5421 last_parameter->next = function_parameter;
5423 parameters = function_parameter;
5425 last_parameter = function_parameter;
5428 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5430 new_type->function.parameters = parameters;
5431 new_type->function.unspecified_parameters = true;
5433 type = typehash_insert(new_type);
5434 if (type != new_type) {
5435 obstack_free(type_obst, new_type);
5438 entity->declaration.type = type;
5440 rem_anchor_token('{');
5443 static bool first_err = true;
5446 * When called with first_err set, prints the name of the current function,
5449 static void print_in_function(void)
5453 diagnosticf("%s: In function '%Y':\n",
5454 current_function->base.base.source_position.input_name,
5455 current_function->base.base.symbol);
5460 * Check if all labels are defined in the current function.
5461 * Check if all labels are used in the current function.
5463 static void check_labels(void)
5465 for (const goto_statement_t *goto_statement = goto_first;
5466 goto_statement != NULL;
5467 goto_statement = goto_statement->next) {
5468 /* skip computed gotos */
5469 if (goto_statement->expression != NULL)
5472 label_t *label = goto_statement->label;
5475 if (label->base.source_position.input_name == NULL) {
5476 print_in_function();
5477 errorf(&goto_statement->base.source_position,
5478 "label '%Y' used but not defined", label->base.symbol);
5482 if (warning.unused_label) {
5483 for (const label_statement_t *label_statement = label_first;
5484 label_statement != NULL;
5485 label_statement = label_statement->next) {
5486 label_t *label = label_statement->label;
5488 if (! label->used) {
5489 print_in_function();
5490 warningf(&label_statement->base.source_position,
5491 "label '%Y' defined but not used", label->base.symbol);
5497 static void warn_unused_decl(entity_t *entity, entity_t *end,
5498 char const *const what)
5500 for (; entity != NULL; entity = entity->base.next) {
5501 if (!is_declaration(entity))
5504 declaration_t *declaration = &entity->declaration;
5505 if (declaration->implicit)
5508 if (!declaration->used) {
5509 print_in_function();
5510 warningf(&entity->base.source_position, "%s '%Y' is unused",
5511 what, entity->base.symbol);
5512 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5513 print_in_function();
5514 warningf(&entity->base.source_position, "%s '%Y' is never read",
5515 what, entity->base.symbol);
5523 static void check_unused_variables(statement_t *const stmt, void *const env)
5527 switch (stmt->kind) {
5528 case STATEMENT_DECLARATION: {
5529 declaration_statement_t const *const decls = &stmt->declaration;
5530 warn_unused_decl(decls->declarations_begin, decls->declarations_end,
5536 warn_unused_decl(stmt->fors.scope.entities, NULL, "variable");
5545 * Check declarations of current_function for unused entities.
5547 static void check_declarations(void)
5549 if (warning.unused_parameter) {
5550 const scope_t *scope = ¤t_function->parameters;
5552 /* do not issue unused warnings for main */
5553 if (!is_sym_main(current_function->base.base.symbol)) {
5554 warn_unused_decl(scope->entities, NULL, "parameter");
5557 if (warning.unused_variable) {
5558 walk_statements(current_function->statement, check_unused_variables,
5563 static int determine_truth(expression_t const* const cond)
5566 !is_constant_expression(cond) ? 0 :
5567 fold_constant(cond) != 0 ? 1 :
5571 static void check_reachable(statement_t *);
5573 static bool expression_returns(expression_t const *const expr)
5575 switch (expr->kind) {
5577 expression_t const *const func = expr->call.function;
5578 if (func->kind == EXPR_REFERENCE) {
5579 entity_t *entity = func->reference.entity;
5580 if (entity->kind == ENTITY_FUNCTION
5581 && entity->declaration.modifiers & DM_NORETURN)
5585 if (!expression_returns(func))
5588 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5589 if (!expression_returns(arg->expression))
5596 case EXPR_REFERENCE:
5597 case EXPR_REFERENCE_ENUM_VALUE:
5599 case EXPR_CHARACTER_CONSTANT:
5600 case EXPR_WIDE_CHARACTER_CONSTANT:
5601 case EXPR_STRING_LITERAL:
5602 case EXPR_WIDE_STRING_LITERAL:
5603 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5604 case EXPR_LABEL_ADDRESS:
5605 case EXPR_CLASSIFY_TYPE:
5606 case EXPR_SIZEOF: // TODO handle obscure VLA case
5609 case EXPR_BUILTIN_SYMBOL:
5610 case EXPR_BUILTIN_CONSTANT_P:
5611 case EXPR_BUILTIN_PREFETCH:
5616 case EXPR_STATEMENT:
5617 check_reachable(expr->statement.statement);
5618 // TODO check if statement can be left
5621 case EXPR_CONDITIONAL:
5622 // TODO handle constant expression
5624 expression_returns(expr->conditional.condition) && (
5625 expression_returns(expr->conditional.true_expression) ||
5626 expression_returns(expr->conditional.false_expression)
5630 return expression_returns(expr->select.compound);
5632 case EXPR_ARRAY_ACCESS:
5634 expression_returns(expr->array_access.array_ref) &&
5635 expression_returns(expr->array_access.index);
5638 return expression_returns(expr->va_starte.ap);
5641 return expression_returns(expr->va_arge.ap);
5643 EXPR_UNARY_CASES_MANDATORY
5644 return expression_returns(expr->unary.value);
5646 case EXPR_UNARY_THROW:
5650 // TODO handle constant lhs of && and ||
5652 expression_returns(expr->binary.left) &&
5653 expression_returns(expr->binary.right);
5659 panic("unhandled expression");
5662 static bool initializer_returns(initializer_t const *const init)
5664 switch (init->kind) {
5665 case INITIALIZER_VALUE:
5666 return expression_returns(init->value.value);
5668 case INITIALIZER_LIST: {
5669 initializer_t * const* i = init->list.initializers;
5670 initializer_t * const* const end = i + init->list.len;
5671 bool returns = true;
5672 for (; i != end; ++i) {
5673 if (!initializer_returns(*i))
5679 case INITIALIZER_STRING:
5680 case INITIALIZER_WIDE_STRING:
5681 case INITIALIZER_DESIGNATOR: // designators have no payload
5684 panic("unhandled initializer");
5687 static bool noreturn_candidate;
5689 static void check_reachable(statement_t *const stmt)
5691 if (stmt->base.reachable)
5693 if (stmt->kind != STATEMENT_DO_WHILE)
5694 stmt->base.reachable = true;
5696 statement_t *last = stmt;
5698 switch (stmt->kind) {
5699 case STATEMENT_INVALID:
5700 case STATEMENT_EMPTY:
5701 case STATEMENT_LOCAL_LABEL:
5703 next = stmt->base.next;
5706 case STATEMENT_DECLARATION: {
5707 declaration_statement_t const *const decl = &stmt->declaration;
5708 entity_t const * ent = decl->declarations_begin;
5709 entity_t const *const last = decl->declarations_end;
5710 for (;; ent = ent->base.next) {
5711 if (ent->kind == ENTITY_VARIABLE &&
5712 ent->variable.initializer != NULL &&
5713 !initializer_returns(ent->variable.initializer)) {
5719 next = stmt->base.next;
5723 case STATEMENT_COMPOUND:
5724 next = stmt->compound.statements;
5727 case STATEMENT_RETURN: {
5728 expression_t const *const val = stmt->returns.value;
5729 if (val == NULL || expression_returns(val))
5730 noreturn_candidate = false;
5734 case STATEMENT_IF: {
5735 if_statement_t const *const ifs = &stmt->ifs;
5736 expression_t const *const cond = ifs->condition;
5738 if (!expression_returns(cond))
5741 int const val = determine_truth(cond);
5744 check_reachable(ifs->true_statement);
5749 if (ifs->false_statement != NULL) {
5750 check_reachable(ifs->false_statement);
5754 next = stmt->base.next;
5758 case STATEMENT_SWITCH: {
5759 switch_statement_t const *const switchs = &stmt->switchs;
5760 expression_t const *const expr = switchs->expression;
5762 if (!expression_returns(expr))
5765 if (is_constant_expression(expr)) {
5766 long const val = fold_constant(expr);
5767 case_label_statement_t * defaults = NULL;
5768 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5769 if (i->expression == NULL) {
5774 if (i->first_case <= val && val <= i->last_case) {
5775 check_reachable((statement_t*)i);
5780 if (defaults != NULL) {
5781 check_reachable((statement_t*)defaults);
5785 bool has_default = false;
5786 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5787 if (i->expression == NULL)
5790 check_reachable((statement_t*)i);
5797 next = stmt->base.next;
5801 case STATEMENT_EXPRESSION: {
5802 /* Check for noreturn function call */
5803 expression_t const *const expr = stmt->expression.expression;
5804 if (!expression_returns(expr))
5807 next = stmt->base.next;
5811 case STATEMENT_CONTINUE: {
5812 statement_t *parent = stmt;
5814 parent = parent->base.parent;
5815 if (parent == NULL) /* continue not within loop */
5819 switch (parent->kind) {
5820 case STATEMENT_WHILE: goto continue_while;
5821 case STATEMENT_DO_WHILE: goto continue_do_while;
5822 case STATEMENT_FOR: goto continue_for;
5829 case STATEMENT_BREAK: {
5830 statement_t *parent = stmt;
5832 parent = parent->base.parent;
5833 if (parent == NULL) /* break not within loop/switch */
5836 switch (parent->kind) {
5837 case STATEMENT_SWITCH:
5838 case STATEMENT_WHILE:
5839 case STATEMENT_DO_WHILE:
5842 next = parent->base.next;
5843 goto found_break_parent;
5852 case STATEMENT_GOTO:
5853 if (stmt->gotos.expression) {
5854 if (!expression_returns(stmt->gotos.expression))
5857 statement_t *parent = stmt->base.parent;
5858 if (parent == NULL) /* top level goto */
5862 next = stmt->gotos.label->statement;
5863 if (next == NULL) /* missing label */
5868 case STATEMENT_LABEL:
5869 next = stmt->label.statement;
5872 case STATEMENT_CASE_LABEL:
5873 next = stmt->case_label.statement;
5876 case STATEMENT_WHILE: {
5877 while_statement_t const *const whiles = &stmt->whiles;
5878 expression_t const *const cond = whiles->condition;
5880 if (!expression_returns(cond))
5883 int const val = determine_truth(cond);
5886 check_reachable(whiles->body);
5891 next = stmt->base.next;
5895 case STATEMENT_DO_WHILE:
5896 next = stmt->do_while.body;
5899 case STATEMENT_FOR: {
5900 for_statement_t *const fors = &stmt->fors;
5902 if (fors->condition_reachable)
5904 fors->condition_reachable = true;
5906 expression_t const *const cond = fors->condition;
5911 } else if (expression_returns(cond)) {
5912 val = determine_truth(cond);
5918 check_reachable(fors->body);
5923 next = stmt->base.next;
5927 case STATEMENT_MS_TRY: {
5928 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5929 check_reachable(ms_try->try_statement);
5930 next = ms_try->final_statement;
5934 case STATEMENT_LEAVE: {
5935 statement_t *parent = stmt;
5937 parent = parent->base.parent;
5938 if (parent == NULL) /* __leave not within __try */
5941 if (parent->kind == STATEMENT_MS_TRY) {
5943 next = parent->ms_try.final_statement;
5951 while (next == NULL) {
5952 next = last->base.parent;
5954 noreturn_candidate = false;
5956 type_t *const type = current_function->base.type;
5957 assert(is_type_function(type));
5958 type_t *const ret = skip_typeref(type->function.return_type);
5959 if (warning.return_type &&
5960 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5961 is_type_valid(ret) &&
5962 !is_sym_main(current_function->base.base.symbol)) {
5963 warningf(&stmt->base.source_position,
5964 "control reaches end of non-void function");
5969 switch (next->kind) {
5970 case STATEMENT_INVALID:
5971 case STATEMENT_EMPTY:
5972 case STATEMENT_DECLARATION:
5973 case STATEMENT_LOCAL_LABEL:
5974 case STATEMENT_EXPRESSION:
5976 case STATEMENT_RETURN:
5977 case STATEMENT_CONTINUE:
5978 case STATEMENT_BREAK:
5979 case STATEMENT_GOTO:
5980 case STATEMENT_LEAVE:
5981 panic("invalid control flow in function");
5983 case STATEMENT_COMPOUND:
5985 case STATEMENT_SWITCH:
5986 case STATEMENT_LABEL:
5987 case STATEMENT_CASE_LABEL:
5989 next = next->base.next;
5992 case STATEMENT_WHILE: {
5994 if (next->base.reachable)
5996 next->base.reachable = true;
5998 while_statement_t const *const whiles = &next->whiles;
5999 expression_t const *const cond = whiles->condition;
6001 if (!expression_returns(cond))
6004 int const val = determine_truth(cond);
6007 check_reachable(whiles->body);
6013 next = next->base.next;
6017 case STATEMENT_DO_WHILE: {
6019 if (next->base.reachable)
6021 next->base.reachable = true;
6023 do_while_statement_t const *const dw = &next->do_while;
6024 expression_t const *const cond = dw->condition;
6026 if (!expression_returns(cond))
6029 int const val = determine_truth(cond);
6032 check_reachable(dw->body);
6038 next = next->base.next;
6042 case STATEMENT_FOR: {
6044 for_statement_t *const fors = &next->fors;
6046 fors->step_reachable = true;
6048 if (fors->condition_reachable)
6050 fors->condition_reachable = true;
6052 expression_t const *const cond = fors->condition;
6057 } else if (expression_returns(cond)) {
6058 val = determine_truth(cond);
6064 check_reachable(fors->body);
6070 next = next->base.next;
6074 case STATEMENT_MS_TRY:
6076 next = next->ms_try.final_statement;
6081 check_reachable(next);
6084 static void check_unreachable(statement_t* const stmt, void *const env)
6088 switch (stmt->kind) {
6089 case STATEMENT_DO_WHILE:
6090 if (!stmt->base.reachable) {
6091 expression_t const *const cond = stmt->do_while.condition;
6092 if (determine_truth(cond) >= 0) {
6093 warningf(&cond->base.source_position,
6094 "condition of do-while-loop is unreachable");
6099 case STATEMENT_FOR: {
6100 for_statement_t const* const fors = &stmt->fors;
6102 // if init and step are unreachable, cond is unreachable, too
6103 if (!stmt->base.reachable && !fors->step_reachable) {
6104 warningf(&stmt->base.source_position, "statement is unreachable");
6106 if (!stmt->base.reachable && fors->initialisation != NULL) {
6107 warningf(&fors->initialisation->base.source_position,
6108 "initialisation of for-statement is unreachable");
6111 if (!fors->condition_reachable && fors->condition != NULL) {
6112 warningf(&fors->condition->base.source_position,
6113 "condition of for-statement is unreachable");
6116 if (!fors->step_reachable && fors->step != NULL) {
6117 warningf(&fors->step->base.source_position,
6118 "step of for-statement is unreachable");
6124 case STATEMENT_COMPOUND:
6125 if (stmt->compound.statements != NULL)
6127 goto warn_unreachable;
6129 case STATEMENT_DECLARATION: {
6130 /* Only warn if there is at least one declarator with an initializer.
6131 * This typically occurs in switch statements. */
6132 declaration_statement_t const *const decl = &stmt->declaration;
6133 entity_t const * ent = decl->declarations_begin;
6134 entity_t const *const last = decl->declarations_end;
6135 for (;; ent = ent->base.next) {
6136 if (ent->kind == ENTITY_VARIABLE &&
6137 ent->variable.initializer != NULL) {
6138 goto warn_unreachable;
6147 if (!stmt->base.reachable)
6148 warningf(&stmt->base.source_position, "statement is unreachable");
6153 static void parse_external_declaration(void)
6155 /* function-definitions and declarations both start with declaration
6157 declaration_specifiers_t specifiers;
6158 memset(&specifiers, 0, sizeof(specifiers));
6160 add_anchor_token(';');
6161 parse_declaration_specifiers(&specifiers);
6162 rem_anchor_token(';');
6164 /* must be a declaration */
6165 if (token.type == ';') {
6166 parse_anonymous_declaration_rest(&specifiers);
6170 add_anchor_token(',');
6171 add_anchor_token('=');
6172 add_anchor_token(';');
6173 add_anchor_token('{');
6175 /* declarator is common to both function-definitions and declarations */
6176 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
6178 rem_anchor_token('{');
6179 rem_anchor_token(';');
6180 rem_anchor_token('=');
6181 rem_anchor_token(',');
6183 /* must be a declaration */
6184 switch (token.type) {
6188 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
6193 /* must be a function definition */
6194 parse_kr_declaration_list(ndeclaration);
6196 if (token.type != '{') {
6197 parse_error_expected("while parsing function definition", '{', NULL);
6198 eat_until_matching_token(';');
6202 assert(is_declaration(ndeclaration));
6203 type_t *type = skip_typeref(ndeclaration->declaration.type);
6205 if (!is_type_function(type)) {
6206 if (is_type_valid(type)) {
6207 errorf(HERE, "declarator '%#T' has a body but is not a function type",
6208 type, ndeclaration->base.symbol);
6214 if (warning.aggregate_return &&
6215 is_type_compound(skip_typeref(type->function.return_type))) {
6216 warningf(HERE, "function '%Y' returns an aggregate",
6217 ndeclaration->base.symbol);
6219 if (warning.traditional && !type->function.unspecified_parameters) {
6220 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6221 ndeclaration->base.symbol);
6223 if (warning.old_style_definition && type->function.unspecified_parameters) {
6224 warningf(HERE, "old-style function definition '%Y'",
6225 ndeclaration->base.symbol);
6228 /* § 6.7.5.3 (14) a function definition with () means no
6229 * parameters (and not unspecified parameters) */
6230 if (type->function.unspecified_parameters
6231 && type->function.parameters == NULL
6232 && !type->function.kr_style_parameters) {
6233 type_t *duplicate = duplicate_type(type);
6234 duplicate->function.unspecified_parameters = false;
6236 type = typehash_insert(duplicate);
6237 if (type != duplicate) {
6238 obstack_free(type_obst, duplicate);
6240 ndeclaration->declaration.type = type;
6243 entity_t *const entity = record_entity(ndeclaration, true);
6244 assert(entity->kind == ENTITY_FUNCTION);
6245 assert(ndeclaration->kind == ENTITY_FUNCTION);
6247 function_t *function = &entity->function;
6248 if (ndeclaration != entity) {
6249 function->parameters = ndeclaration->function.parameters;
6251 assert(is_declaration(entity));
6252 type = skip_typeref(entity->declaration.type);
6254 /* push function parameters and switch scope */
6255 size_t const top = environment_top();
6256 scope_t *old_scope = scope_push(&function->parameters);
6258 entity_t *parameter = function->parameters.entities;
6259 for (; parameter != NULL; parameter = parameter->base.next) {
6260 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6261 parameter->base.parent_scope = current_scope;
6263 assert(parameter->base.parent_scope == NULL
6264 || parameter->base.parent_scope == current_scope);
6265 parameter->base.parent_scope = current_scope;
6266 if (parameter->base.symbol == NULL) {
6267 errorf(¶meter->base.source_position, "parameter name omitted");
6270 environment_push(parameter);
6273 if (function->statement != NULL) {
6274 parser_error_multiple_definition(entity, HERE);
6277 /* parse function body */
6278 int label_stack_top = label_top();
6279 function_t *old_current_function = current_function;
6280 current_function = function;
6281 current_parent = NULL;
6284 goto_anchor = &goto_first;
6286 label_anchor = &label_first;
6288 statement_t *const body = parse_compound_statement(false);
6289 function->statement = body;
6292 check_declarations();
6293 if (warning.return_type ||
6294 warning.unreachable_code ||
6295 (warning.missing_noreturn
6296 && !(function->base.modifiers & DM_NORETURN))) {
6297 noreturn_candidate = true;
6298 check_reachable(body);
6299 if (warning.unreachable_code)
6300 walk_statements(body, check_unreachable, NULL);
6301 if (warning.missing_noreturn &&
6302 noreturn_candidate &&
6303 !(function->base.modifiers & DM_NORETURN)) {
6304 warningf(&body->base.source_position,
6305 "function '%#T' is candidate for attribute 'noreturn'",
6306 type, entity->base.symbol);
6310 assert(current_parent == NULL);
6311 assert(current_function == function);
6312 current_function = old_current_function;
6313 label_pop_to(label_stack_top);
6316 assert(current_scope == &function->parameters);
6317 scope_pop(old_scope);
6318 environment_pop_to(top);
6321 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6322 source_position_t *source_position,
6323 const symbol_t *symbol)
6325 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6327 type->bitfield.base_type = base_type;
6328 type->bitfield.size_expression = size;
6331 type_t *skipped_type = skip_typeref(base_type);
6332 if (!is_type_integer(skipped_type)) {
6333 errorf(HERE, "bitfield base type '%T' is not an integer type",
6337 bit_size = skipped_type->base.size * 8;
6340 if (is_constant_expression(size)) {
6341 long v = fold_constant(size);
6344 errorf(source_position, "negative width in bit-field '%Y'", symbol);
6345 } else if (v == 0) {
6346 errorf(source_position, "zero width for bit-field '%Y'", symbol);
6347 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6348 errorf(source_position, "width of '%Y' exceeds its type", symbol);
6350 type->bitfield.bit_size = v;
6357 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6359 entity_t *iter = compound->members.entities;
6360 for (; iter != NULL; iter = iter->base.next) {
6361 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6364 if (iter->base.symbol == symbol) {
6366 } else if (iter->base.symbol == NULL) {
6367 type_t *type = skip_typeref(iter->declaration.type);
6368 if (is_type_compound(type)) {
6370 = find_compound_entry(type->compound.compound, symbol);
6381 static void parse_compound_declarators(compound_t *compound,
6382 const declaration_specifiers_t *specifiers)
6387 if (token.type == ':') {
6388 source_position_t source_position = *HERE;
6391 type_t *base_type = specifiers->type;
6392 expression_t *size = parse_constant_expression();
6394 type_t *type = make_bitfield_type(base_type, size,
6395 &source_position, sym_anonymous);
6397 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6398 entity->base.namespc = NAMESPACE_NORMAL;
6399 entity->base.source_position = source_position;
6400 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6401 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6402 entity->declaration.modifiers = specifiers->modifiers;
6403 entity->declaration.type = type;
6405 entity = parse_declarator(specifiers,
6406 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
6407 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6409 if (token.type == ':') {
6410 source_position_t source_position = *HERE;
6412 expression_t *size = parse_constant_expression();
6414 type_t *type = entity->declaration.type;
6415 type_t *bitfield_type = make_bitfield_type(type, size,
6416 &source_position, entity->base.symbol);
6417 entity->declaration.type = bitfield_type;
6421 /* make sure we don't define a symbol multiple times */
6422 symbol_t *symbol = entity->base.symbol;
6423 if (symbol != NULL) {
6424 entity_t *prev = find_compound_entry(compound, symbol);
6427 errorf(&entity->base.source_position,
6428 "multiple declarations of symbol '%Y' (declared %P)",
6429 symbol, &prev->base.source_position);
6433 append_entity(&compound->members, entity);
6435 type_t *orig_type = entity->declaration.type;
6436 type_t *type = skip_typeref(orig_type);
6437 if (is_type_function(type)) {
6438 errorf(&entity->base.source_position,
6439 "compound member '%Y' must not have function type '%T'",
6440 entity->base.symbol, orig_type);
6441 } else if (is_type_incomplete(type)) {
6442 /* §6.7.2.1:16 flexible array member */
6443 if (is_type_array(type) &&
6444 token.type == ';' &&
6445 look_ahead(1)->type == '}') {
6446 compound->has_flexible_member = true;
6448 errorf(&entity->base.source_position,
6449 "compound member '%Y' has incomplete type '%T'",
6450 entity->base.symbol, orig_type);
6454 if (token.type != ',')
6461 anonymous_entity = NULL;
6464 static void parse_compound_type_entries(compound_t *compound)
6467 add_anchor_token('}');
6469 while (token.type != '}') {
6470 if (token.type == T_EOF) {
6471 errorf(HERE, "EOF while parsing struct");
6474 declaration_specifiers_t specifiers;
6475 memset(&specifiers, 0, sizeof(specifiers));
6476 parse_declaration_specifiers(&specifiers);
6478 parse_compound_declarators(compound, &specifiers);
6480 rem_anchor_token('}');
6484 compound->complete = true;
6487 static type_t *parse_typename(void)
6489 declaration_specifiers_t specifiers;
6490 memset(&specifiers, 0, sizeof(specifiers));
6491 parse_declaration_specifiers(&specifiers);
6492 if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6493 specifiers.thread_local) {
6494 /* TODO: improve error message, user does probably not know what a
6495 * storage class is...
6497 errorf(HERE, "typename may not have a storage class");
6500 type_t *result = parse_abstract_declarator(specifiers.type);
6508 typedef expression_t* (*parse_expression_function)(void);
6509 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6511 typedef struct expression_parser_function_t expression_parser_function_t;
6512 struct expression_parser_function_t {
6513 parse_expression_function parser;
6514 unsigned infix_precedence;
6515 parse_expression_infix_function infix_parser;
6518 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6521 * Prints an error message if an expression was expected but not read
6523 static expression_t *expected_expression_error(void)
6525 /* skip the error message if the error token was read */
6526 if (token.type != T_ERROR) {
6527 errorf(HERE, "expected expression, got token '%K'", &token);
6531 return create_invalid_expression();
6535 * Parse a string constant.
6537 static expression_t *parse_string_const(void)
6540 if (token.type == T_STRING_LITERAL) {
6541 string_t res = token.v.string;
6543 while (token.type == T_STRING_LITERAL) {
6544 res = concat_strings(&res, &token.v.string);
6547 if (token.type != T_WIDE_STRING_LITERAL) {
6548 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6549 /* note: that we use type_char_ptr here, which is already the
6550 * automatic converted type. revert_automatic_type_conversion
6551 * will construct the array type */
6552 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6553 cnst->string.value = res;
6557 wres = concat_string_wide_string(&res, &token.v.wide_string);
6559 wres = token.v.wide_string;
6564 switch (token.type) {
6565 case T_WIDE_STRING_LITERAL:
6566 wres = concat_wide_strings(&wres, &token.v.wide_string);
6569 case T_STRING_LITERAL:
6570 wres = concat_wide_string_string(&wres, &token.v.string);
6574 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6575 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6576 cnst->wide_string.value = wres;
6585 * Parse a boolean constant.
6587 static expression_t *parse_bool_const(bool value)
6589 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6590 cnst->base.type = type_bool;
6591 cnst->conste.v.int_value = value;
6599 * Parse an integer constant.
6601 static expression_t *parse_int_const(void)
6603 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6604 cnst->base.type = token.datatype;
6605 cnst->conste.v.int_value = token.v.intvalue;
6613 * Parse a character constant.
6615 static expression_t *parse_character_constant(void)
6617 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6618 cnst->base.type = token.datatype;
6619 cnst->conste.v.character = token.v.string;
6621 if (cnst->conste.v.character.size != 1) {
6623 errorf(HERE, "more than 1 character in character constant");
6624 } else if (warning.multichar) {
6625 warningf(HERE, "multi-character character constant");
6634 * Parse a wide character constant.
6636 static expression_t *parse_wide_character_constant(void)
6638 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6639 cnst->base.type = token.datatype;
6640 cnst->conste.v.wide_character = token.v.wide_string;
6642 if (cnst->conste.v.wide_character.size != 1) {
6644 errorf(HERE, "more than 1 character in character constant");
6645 } else if (warning.multichar) {
6646 warningf(HERE, "multi-character character constant");
6655 * Parse a float constant.
6657 static expression_t *parse_float_const(void)
6659 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6660 cnst->base.type = token.datatype;
6661 cnst->conste.v.float_value = token.v.floatvalue;
6668 static entity_t *create_implicit_function(symbol_t *symbol,
6669 const source_position_t *source_position)
6671 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6672 ntype->function.return_type = type_int;
6673 ntype->function.unspecified_parameters = true;
6675 type_t *type = typehash_insert(ntype);
6676 if (type != ntype) {
6680 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6681 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6682 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6683 entity->declaration.type = type;
6684 entity->declaration.implicit = true;
6685 entity->base.symbol = symbol;
6686 entity->base.source_position = *source_position;
6688 bool strict_prototypes_old = warning.strict_prototypes;
6689 warning.strict_prototypes = false;
6690 record_entity(entity, false);
6691 warning.strict_prototypes = strict_prototypes_old;
6697 * Creates a return_type (func)(argument_type) function type if not
6700 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6701 type_t *argument_type2)
6703 function_parameter_t *parameter2
6704 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6705 memset(parameter2, 0, sizeof(parameter2[0]));
6706 parameter2->type = argument_type2;
6708 function_parameter_t *parameter1
6709 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6710 memset(parameter1, 0, sizeof(parameter1[0]));
6711 parameter1->type = argument_type1;
6712 parameter1->next = parameter2;
6714 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6715 type->function.return_type = return_type;
6716 type->function.parameters = parameter1;
6718 type_t *result = typehash_insert(type);
6719 if (result != type) {
6727 * Creates a return_type (func)(argument_type) function type if not
6730 * @param return_type the return type
6731 * @param argument_type the argument type
6733 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6735 function_parameter_t *parameter
6736 = obstack_alloc(type_obst, sizeof(parameter[0]));
6737 memset(parameter, 0, sizeof(parameter[0]));
6738 parameter->type = argument_type;
6740 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6741 type->function.return_type = return_type;
6742 type->function.parameters = parameter;
6744 type_t *result = typehash_insert(type);
6745 if (result != type) {
6752 static type_t *make_function_0_type(type_t *return_type)
6754 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6755 type->function.return_type = return_type;
6756 type->function.parameters = NULL;
6758 type_t *result = typehash_insert(type);
6759 if (result != type) {
6767 * Creates a function type for some function like builtins.
6769 * @param symbol the symbol describing the builtin
6771 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6773 switch (symbol->ID) {
6774 case T___builtin_alloca:
6775 return make_function_1_type(type_void_ptr, type_size_t);
6776 case T___builtin_huge_val:
6777 return make_function_0_type(type_double);
6778 case T___builtin_inf:
6779 return make_function_0_type(type_double);
6780 case T___builtin_inff:
6781 return make_function_0_type(type_float);
6782 case T___builtin_infl:
6783 return make_function_0_type(type_long_double);
6784 case T___builtin_nan:
6785 return make_function_1_type(type_double, type_char_ptr);
6786 case T___builtin_nanf:
6787 return make_function_1_type(type_float, type_char_ptr);
6788 case T___builtin_nanl:
6789 return make_function_1_type(type_long_double, type_char_ptr);
6790 case T___builtin_va_end:
6791 return make_function_1_type(type_void, type_valist);
6792 case T___builtin_expect:
6793 return make_function_2_type(type_long, type_long, type_long);
6795 internal_errorf(HERE, "not implemented builtin symbol found");
6800 * Performs automatic type cast as described in § 6.3.2.1.
6802 * @param orig_type the original type
6804 static type_t *automatic_type_conversion(type_t *orig_type)
6806 type_t *type = skip_typeref(orig_type);
6807 if (is_type_array(type)) {
6808 array_type_t *array_type = &type->array;
6809 type_t *element_type = array_type->element_type;
6810 unsigned qualifiers = array_type->base.qualifiers;
6812 return make_pointer_type(element_type, qualifiers);
6815 if (is_type_function(type)) {
6816 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6823 * reverts the automatic casts of array to pointer types and function
6824 * to function-pointer types as defined § 6.3.2.1
6826 type_t *revert_automatic_type_conversion(const expression_t *expression)
6828 switch (expression->kind) {
6829 case EXPR_REFERENCE: {
6830 entity_t *entity = expression->reference.entity;
6831 if (is_declaration(entity)) {
6832 return entity->declaration.type;
6833 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6834 return entity->enum_value.enum_type;
6836 panic("no declaration or enum in reference");
6841 entity_t *entity = expression->select.compound_entry;
6842 assert(is_declaration(entity));
6843 type_t *type = entity->declaration.type;
6844 return get_qualified_type(type,
6845 expression->base.type->base.qualifiers);
6848 case EXPR_UNARY_DEREFERENCE: {
6849 const expression_t *const value = expression->unary.value;
6850 type_t *const type = skip_typeref(value->base.type);
6851 assert(is_type_pointer(type));
6852 return type->pointer.points_to;
6855 case EXPR_BUILTIN_SYMBOL:
6856 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6858 case EXPR_ARRAY_ACCESS: {
6859 const expression_t *array_ref = expression->array_access.array_ref;
6860 type_t *type_left = skip_typeref(array_ref->base.type);
6861 if (!is_type_valid(type_left))
6863 assert(is_type_pointer(type_left));
6864 return type_left->pointer.points_to;
6867 case EXPR_STRING_LITERAL: {
6868 size_t size = expression->string.value.size;
6869 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6872 case EXPR_WIDE_STRING_LITERAL: {
6873 size_t size = expression->wide_string.value.size;
6874 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6877 case EXPR_COMPOUND_LITERAL:
6878 return expression->compound_literal.type;
6883 return expression->base.type;
6886 static expression_t *parse_reference(void)
6888 symbol_t *const symbol = token.v.symbol;
6890 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6892 if (entity == NULL) {
6893 if (!strict_mode && look_ahead(1)->type == '(') {
6894 /* an implicitly declared function */
6895 if (warning.implicit_function_declaration) {
6896 warningf(HERE, "implicit declaration of function '%Y'",
6900 entity = create_implicit_function(symbol, HERE);
6902 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6903 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6909 if (is_declaration(entity)) {
6910 orig_type = entity->declaration.type;
6911 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6912 orig_type = entity->enum_value.enum_type;
6913 } else if (entity->kind == ENTITY_TYPEDEF) {
6914 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
6917 return create_invalid_expression();
6919 panic("expected declaration or enum value in reference");
6922 /* we always do the auto-type conversions; the & and sizeof parser contains
6923 * code to revert this! */
6924 type_t *type = automatic_type_conversion(orig_type);
6926 expression_kind_t kind = EXPR_REFERENCE;
6927 if (entity->kind == ENTITY_ENUM_VALUE)
6928 kind = EXPR_REFERENCE_ENUM_VALUE;
6930 expression_t *expression = allocate_expression_zero(kind);
6931 expression->reference.entity = entity;
6932 expression->base.type = type;
6934 /* this declaration is used */
6935 if (is_declaration(entity)) {
6936 entity->declaration.used = true;
6939 if (entity->base.parent_scope != file_scope
6940 && entity->base.parent_scope->depth < current_function->parameters.depth
6941 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
6942 if (entity->kind == ENTITY_VARIABLE) {
6943 /* access of a variable from an outer function */
6944 entity->variable.address_taken = true;
6946 current_function->need_closure = true;
6949 /* check for deprecated functions */
6950 if (warning.deprecated_declarations
6951 && is_declaration(entity)
6952 && entity->declaration.modifiers & DM_DEPRECATED) {
6953 declaration_t *declaration = &entity->declaration;
6955 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
6956 "function" : "variable";
6958 if (declaration->deprecated_string != NULL) {
6959 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6960 prefix, entity->base.symbol, &entity->base.source_position,
6961 declaration->deprecated_string);
6963 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6964 entity->base.symbol, &entity->base.source_position);
6968 if (warning.init_self && entity == current_init_decl && !in_type_prop
6969 && entity->kind == ENTITY_VARIABLE) {
6970 current_init_decl = NULL;
6971 warningf(HERE, "variable '%#T' is initialized by itself",
6972 entity->declaration.type, entity->base.symbol);
6979 static bool semantic_cast(expression_t *cast)
6981 expression_t *expression = cast->unary.value;
6982 type_t *orig_dest_type = cast->base.type;
6983 type_t *orig_type_right = expression->base.type;
6984 type_t const *dst_type = skip_typeref(orig_dest_type);
6985 type_t const *src_type = skip_typeref(orig_type_right);
6986 source_position_t const *pos = &cast->base.source_position;
6988 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6989 if (dst_type == type_void)
6992 /* only integer and pointer can be casted to pointer */
6993 if (is_type_pointer(dst_type) &&
6994 !is_type_pointer(src_type) &&
6995 !is_type_integer(src_type) &&
6996 is_type_valid(src_type)) {
6997 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
7001 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
7002 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
7006 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
7007 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
7011 if (warning.cast_qual &&
7012 is_type_pointer(src_type) &&
7013 is_type_pointer(dst_type)) {
7014 type_t *src = skip_typeref(src_type->pointer.points_to);
7015 type_t *dst = skip_typeref(dst_type->pointer.points_to);
7016 unsigned missing_qualifiers =
7017 src->base.qualifiers & ~dst->base.qualifiers;
7018 if (missing_qualifiers != 0) {
7020 "cast discards qualifiers '%Q' in pointer target type of '%T'",
7021 missing_qualifiers, orig_type_right);
7027 static expression_t *parse_compound_literal(type_t *type)
7029 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
7031 parse_initializer_env_t env;
7034 env.must_be_constant = false;
7035 initializer_t *initializer = parse_initializer(&env);
7038 expression->compound_literal.initializer = initializer;
7039 expression->compound_literal.type = type;
7040 expression->base.type = automatic_type_conversion(type);
7046 * Parse a cast expression.
7048 static expression_t *parse_cast(void)
7050 add_anchor_token(')');
7052 source_position_t source_position = token.source_position;
7054 type_t *type = parse_typename();
7056 rem_anchor_token(')');
7059 if (token.type == '{') {
7060 return parse_compound_literal(type);
7063 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
7064 cast->base.source_position = source_position;
7066 expression_t *value = parse_sub_expression(PREC_CAST);
7067 cast->base.type = type;
7068 cast->unary.value = value;
7070 if (! semantic_cast(cast)) {
7071 /* TODO: record the error in the AST. else it is impossible to detect it */
7076 return create_invalid_expression();
7080 * Parse a statement expression.
7082 static expression_t *parse_statement_expression(void)
7084 add_anchor_token(')');
7086 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
7088 statement_t *statement = parse_compound_statement(true);
7089 expression->statement.statement = statement;
7091 /* find last statement and use its type */
7092 type_t *type = type_void;
7093 const statement_t *stmt = statement->compound.statements;
7095 while (stmt->base.next != NULL)
7096 stmt = stmt->base.next;
7098 if (stmt->kind == STATEMENT_EXPRESSION) {
7099 type = stmt->expression.expression->base.type;
7101 } else if (warning.other) {
7102 warningf(&expression->base.source_position, "empty statement expression ({})");
7104 expression->base.type = type;
7106 rem_anchor_token(')');
7114 * Parse a parenthesized expression.
7116 static expression_t *parse_parenthesized_expression(void)
7120 switch (token.type) {
7122 /* gcc extension: a statement expression */
7123 return parse_statement_expression();
7127 return parse_cast();
7129 if (is_typedef_symbol(token.v.symbol)) {
7130 return parse_cast();
7134 add_anchor_token(')');
7135 expression_t *result = parse_expression();
7136 rem_anchor_token(')');
7143 static expression_t *parse_function_keyword(void)
7147 if (current_function == NULL) {
7148 errorf(HERE, "'__func__' used outside of a function");
7151 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7152 expression->base.type = type_char_ptr;
7153 expression->funcname.kind = FUNCNAME_FUNCTION;
7160 static expression_t *parse_pretty_function_keyword(void)
7162 if (current_function == NULL) {
7163 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
7166 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7167 expression->base.type = type_char_ptr;
7168 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
7170 eat(T___PRETTY_FUNCTION__);
7175 static expression_t *parse_funcsig_keyword(void)
7177 if (current_function == NULL) {
7178 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7181 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7182 expression->base.type = type_char_ptr;
7183 expression->funcname.kind = FUNCNAME_FUNCSIG;
7190 static expression_t *parse_funcdname_keyword(void)
7192 if (current_function == NULL) {
7193 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7196 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7197 expression->base.type = type_char_ptr;
7198 expression->funcname.kind = FUNCNAME_FUNCDNAME;
7200 eat(T___FUNCDNAME__);
7205 static designator_t *parse_designator(void)
7207 designator_t *result = allocate_ast_zero(sizeof(result[0]));
7208 result->source_position = *HERE;
7210 if (token.type != T_IDENTIFIER) {
7211 parse_error_expected("while parsing member designator",
7212 T_IDENTIFIER, NULL);
7215 result->symbol = token.v.symbol;
7218 designator_t *last_designator = result;
7220 if (token.type == '.') {
7222 if (token.type != T_IDENTIFIER) {
7223 parse_error_expected("while parsing member designator",
7224 T_IDENTIFIER, NULL);
7227 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7228 designator->source_position = *HERE;
7229 designator->symbol = token.v.symbol;
7232 last_designator->next = designator;
7233 last_designator = designator;
7236 if (token.type == '[') {
7238 add_anchor_token(']');
7239 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7240 designator->source_position = *HERE;
7241 designator->array_index = parse_expression();
7242 rem_anchor_token(']');
7244 if (designator->array_index == NULL) {
7248 last_designator->next = designator;
7249 last_designator = designator;
7261 * Parse the __builtin_offsetof() expression.
7263 static expression_t *parse_offsetof(void)
7265 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7266 expression->base.type = type_size_t;
7268 eat(T___builtin_offsetof);
7271 add_anchor_token(',');
7272 type_t *type = parse_typename();
7273 rem_anchor_token(',');
7275 add_anchor_token(')');
7276 designator_t *designator = parse_designator();
7277 rem_anchor_token(')');
7280 expression->offsetofe.type = type;
7281 expression->offsetofe.designator = designator;
7284 memset(&path, 0, sizeof(path));
7285 path.top_type = type;
7286 path.path = NEW_ARR_F(type_path_entry_t, 0);
7288 descend_into_subtype(&path);
7290 if (!walk_designator(&path, designator, true)) {
7291 return create_invalid_expression();
7294 DEL_ARR_F(path.path);
7298 return create_invalid_expression();
7302 * Parses a _builtin_va_start() expression.
7304 static expression_t *parse_va_start(void)
7306 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7308 eat(T___builtin_va_start);
7311 add_anchor_token(',');
7312 expression->va_starte.ap = parse_assignment_expression();
7313 rem_anchor_token(',');
7315 expression_t *const expr = parse_assignment_expression();
7316 if (expr->kind == EXPR_REFERENCE) {
7317 entity_t *const entity = expr->reference.entity;
7318 if (entity->base.parent_scope != ¤t_function->parameters
7319 || entity->base.next != NULL
7320 || entity->kind != ENTITY_VARIABLE) {
7321 errorf(&expr->base.source_position,
7322 "second argument of 'va_start' must be last parameter of the current function");
7324 expression->va_starte.parameter = &entity->variable;
7331 return create_invalid_expression();
7335 * Parses a _builtin_va_arg() expression.
7337 static expression_t *parse_va_arg(void)
7339 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7341 eat(T___builtin_va_arg);
7344 expression->va_arge.ap = parse_assignment_expression();
7346 expression->base.type = parse_typename();
7351 return create_invalid_expression();
7354 static expression_t *parse_builtin_symbol(void)
7356 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7358 symbol_t *symbol = token.v.symbol;
7360 expression->builtin_symbol.symbol = symbol;
7363 type_t *type = get_builtin_symbol_type(symbol);
7364 type = automatic_type_conversion(type);
7366 expression->base.type = type;
7371 * Parses a __builtin_constant() expression.
7373 static expression_t *parse_builtin_constant(void)
7375 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7377 eat(T___builtin_constant_p);
7380 add_anchor_token(')');
7381 expression->builtin_constant.value = parse_assignment_expression();
7382 rem_anchor_token(')');
7384 expression->base.type = type_int;
7388 return create_invalid_expression();
7392 * Parses a __builtin_prefetch() expression.
7394 static expression_t *parse_builtin_prefetch(void)
7396 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7398 eat(T___builtin_prefetch);
7401 add_anchor_token(')');
7402 expression->builtin_prefetch.adr = parse_assignment_expression();
7403 if (token.type == ',') {
7405 expression->builtin_prefetch.rw = parse_assignment_expression();
7407 if (token.type == ',') {
7409 expression->builtin_prefetch.locality = parse_assignment_expression();
7411 rem_anchor_token(')');
7413 expression->base.type = type_void;
7417 return create_invalid_expression();
7421 * Parses a __builtin_is_*() compare expression.
7423 static expression_t *parse_compare_builtin(void)
7425 expression_t *expression;
7427 switch (token.type) {
7428 case T___builtin_isgreater:
7429 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7431 case T___builtin_isgreaterequal:
7432 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7434 case T___builtin_isless:
7435 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7437 case T___builtin_islessequal:
7438 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7440 case T___builtin_islessgreater:
7441 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7443 case T___builtin_isunordered:
7444 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7447 internal_errorf(HERE, "invalid compare builtin found");
7449 expression->base.source_position = *HERE;
7453 expression->binary.left = parse_assignment_expression();
7455 expression->binary.right = parse_assignment_expression();
7458 type_t *const orig_type_left = expression->binary.left->base.type;
7459 type_t *const orig_type_right = expression->binary.right->base.type;
7461 type_t *const type_left = skip_typeref(orig_type_left);
7462 type_t *const type_right = skip_typeref(orig_type_right);
7463 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7464 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7465 type_error_incompatible("invalid operands in comparison",
7466 &expression->base.source_position, orig_type_left, orig_type_right);
7469 semantic_comparison(&expression->binary);
7474 return create_invalid_expression();
7479 * Parses a __builtin_expect() expression.
7481 static expression_t *parse_builtin_expect(void)
7483 expression_t *expression
7484 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7486 eat(T___builtin_expect);
7489 expression->binary.left = parse_assignment_expression();
7491 expression->binary.right = parse_constant_expression();
7494 expression->base.type = expression->binary.left->base.type;
7498 return create_invalid_expression();
7503 * Parses a MS assume() expression.
7505 static expression_t *parse_assume(void)
7507 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7512 add_anchor_token(')');
7513 expression->unary.value = parse_assignment_expression();
7514 rem_anchor_token(')');
7517 expression->base.type = type_void;
7520 return create_invalid_expression();
7524 * Return the declaration for a given label symbol or create a new one.
7526 * @param symbol the symbol of the label
7528 static label_t *get_label(symbol_t *symbol)
7531 assert(current_function != NULL);
7533 label = get_entity(symbol, NAMESPACE_LABEL);
7534 /* if we found a local label, we already created the declaration */
7535 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7536 if (label->base.parent_scope != current_scope) {
7537 assert(label->base.parent_scope->depth < current_scope->depth);
7538 current_function->goto_to_outer = true;
7540 return &label->label;
7543 label = get_entity(symbol, NAMESPACE_LABEL);
7544 /* if we found a label in the same function, then we already created the
7547 && label->base.parent_scope == ¤t_function->parameters) {
7548 return &label->label;
7551 /* otherwise we need to create a new one */
7552 label = allocate_entity_zero(ENTITY_LABEL);
7553 label->base.namespc = NAMESPACE_LABEL;
7554 label->base.symbol = symbol;
7558 return &label->label;
7562 * Parses a GNU && label address expression.
7564 static expression_t *parse_label_address(void)
7566 source_position_t source_position = token.source_position;
7568 if (token.type != T_IDENTIFIER) {
7569 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7572 symbol_t *symbol = token.v.symbol;
7575 label_t *label = get_label(symbol);
7577 label->address_taken = true;
7579 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7580 expression->base.source_position = source_position;
7582 /* label address is threaten as a void pointer */
7583 expression->base.type = type_void_ptr;
7584 expression->label_address.label = label;
7587 return create_invalid_expression();
7591 * Parse a microsoft __noop expression.
7593 static expression_t *parse_noop_expression(void)
7595 /* the result is a (int)0 */
7596 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7597 cnst->base.type = type_int;
7598 cnst->conste.v.int_value = 0;
7599 cnst->conste.is_ms_noop = true;
7603 if (token.type == '(') {
7604 /* parse arguments */
7606 add_anchor_token(')');
7607 add_anchor_token(',');
7609 if (token.type != ')') {
7611 (void)parse_assignment_expression();
7612 if (token.type != ',')
7618 rem_anchor_token(',');
7619 rem_anchor_token(')');
7627 * Parses a primary expression.
7629 static expression_t *parse_primary_expression(void)
7631 switch (token.type) {
7632 case T_false: return parse_bool_const(false);
7633 case T_true: return parse_bool_const(true);
7634 case T_INTEGER: return parse_int_const();
7635 case T_CHARACTER_CONSTANT: return parse_character_constant();
7636 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7637 case T_FLOATINGPOINT: return parse_float_const();
7638 case T_STRING_LITERAL:
7639 case T_WIDE_STRING_LITERAL: return parse_string_const();
7640 case T_IDENTIFIER: return parse_reference();
7641 case T___FUNCTION__:
7642 case T___func__: return parse_function_keyword();
7643 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7644 case T___FUNCSIG__: return parse_funcsig_keyword();
7645 case T___FUNCDNAME__: return parse_funcdname_keyword();
7646 case T___builtin_offsetof: return parse_offsetof();
7647 case T___builtin_va_start: return parse_va_start();
7648 case T___builtin_va_arg: return parse_va_arg();
7649 case T___builtin_expect:
7650 case T___builtin_alloca:
7651 case T___builtin_inf:
7652 case T___builtin_inff:
7653 case T___builtin_infl:
7654 case T___builtin_nan:
7655 case T___builtin_nanf:
7656 case T___builtin_nanl:
7657 case T___builtin_huge_val:
7658 case T___builtin_va_end: return parse_builtin_symbol();
7659 case T___builtin_isgreater:
7660 case T___builtin_isgreaterequal:
7661 case T___builtin_isless:
7662 case T___builtin_islessequal:
7663 case T___builtin_islessgreater:
7664 case T___builtin_isunordered: return parse_compare_builtin();
7665 case T___builtin_constant_p: return parse_builtin_constant();
7666 case T___builtin_prefetch: return parse_builtin_prefetch();
7667 case T__assume: return parse_assume();
7670 return parse_label_address();
7673 case '(': return parse_parenthesized_expression();
7674 case T___noop: return parse_noop_expression();
7677 errorf(HERE, "unexpected token '%K', expected an expression", &token);
7678 return create_invalid_expression();
7682 * Check if the expression has the character type and issue a warning then.
7684 static void check_for_char_index_type(const expression_t *expression)
7686 type_t *const type = expression->base.type;
7687 const type_t *const base_type = skip_typeref(type);
7689 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7690 warning.char_subscripts) {
7691 warningf(&expression->base.source_position,
7692 "array subscript has type '%T'", type);
7696 static expression_t *parse_array_expression(expression_t *left)
7698 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7701 add_anchor_token(']');
7703 expression_t *inside = parse_expression();
7705 type_t *const orig_type_left = left->base.type;
7706 type_t *const orig_type_inside = inside->base.type;
7708 type_t *const type_left = skip_typeref(orig_type_left);
7709 type_t *const type_inside = skip_typeref(orig_type_inside);
7711 type_t *return_type;
7712 array_access_expression_t *array_access = &expression->array_access;
7713 if (is_type_pointer(type_left)) {
7714 return_type = type_left->pointer.points_to;
7715 array_access->array_ref = left;
7716 array_access->index = inside;
7717 check_for_char_index_type(inside);
7718 } else if (is_type_pointer(type_inside)) {
7719 return_type = type_inside->pointer.points_to;
7720 array_access->array_ref = inside;
7721 array_access->index = left;
7722 array_access->flipped = true;
7723 check_for_char_index_type(left);
7725 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7727 "array access on object with non-pointer types '%T', '%T'",
7728 orig_type_left, orig_type_inside);
7730 return_type = type_error_type;
7731 array_access->array_ref = left;
7732 array_access->index = inside;
7735 expression->base.type = automatic_type_conversion(return_type);
7737 rem_anchor_token(']');
7743 static expression_t *parse_typeprop(expression_kind_t const kind)
7745 expression_t *tp_expression = allocate_expression_zero(kind);
7746 tp_expression->base.type = type_size_t;
7748 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7750 /* we only refer to a type property, mark this case */
7751 bool old = in_type_prop;
7752 in_type_prop = true;
7755 expression_t *expression;
7756 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7758 add_anchor_token(')');
7759 orig_type = parse_typename();
7760 rem_anchor_token(')');
7763 if (token.type == '{') {
7764 /* It was not sizeof(type) after all. It is sizeof of an expression
7765 * starting with a compound literal */
7766 expression = parse_compound_literal(orig_type);
7767 goto typeprop_expression;
7770 expression = parse_sub_expression(PREC_UNARY);
7772 typeprop_expression:
7773 tp_expression->typeprop.tp_expression = expression;
7775 orig_type = revert_automatic_type_conversion(expression);
7776 expression->base.type = orig_type;
7779 tp_expression->typeprop.type = orig_type;
7780 type_t const* const type = skip_typeref(orig_type);
7781 char const* const wrong_type =
7782 is_type_incomplete(type) ? "incomplete" :
7783 type->kind == TYPE_FUNCTION ? "function designator" :
7784 type->kind == TYPE_BITFIELD ? "bitfield" :
7786 if (wrong_type != NULL) {
7787 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7788 errorf(&tp_expression->base.source_position,
7789 "operand of %s expression must not be of %s type '%T'",
7790 what, wrong_type, orig_type);
7795 return tp_expression;
7798 static expression_t *parse_sizeof(void)
7800 return parse_typeprop(EXPR_SIZEOF);
7803 static expression_t *parse_alignof(void)
7805 return parse_typeprop(EXPR_ALIGNOF);
7808 static expression_t *parse_select_expression(expression_t *compound)
7810 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7811 select->select.compound = compound;
7813 assert(token.type == '.' || token.type == T_MINUSGREATER);
7814 bool is_pointer = (token.type == T_MINUSGREATER);
7817 if (token.type != T_IDENTIFIER) {
7818 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7821 symbol_t *symbol = token.v.symbol;
7824 type_t *const orig_type = compound->base.type;
7825 type_t *const type = skip_typeref(orig_type);
7828 bool saw_error = false;
7829 if (is_type_pointer(type)) {
7832 "request for member '%Y' in something not a struct or union, but '%T'",
7836 type_left = skip_typeref(type->pointer.points_to);
7838 if (is_pointer && is_type_valid(type)) {
7839 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7846 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7847 type_left->kind == TYPE_COMPOUND_UNION) {
7848 compound_t *compound = type_left->compound.compound;
7850 if (!compound->complete) {
7851 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7853 goto create_error_entry;
7856 entry = find_compound_entry(compound, symbol);
7857 if (entry == NULL) {
7858 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7859 goto create_error_entry;
7862 if (is_type_valid(type_left) && !saw_error) {
7864 "request for member '%Y' in something not a struct or union, but '%T'",
7868 return create_invalid_expression();
7871 assert(is_declaration(entry));
7872 select->select.compound_entry = entry;
7874 type_t *entry_type = entry->declaration.type;
7876 = get_qualified_type(entry_type, type_left->base.qualifiers);
7878 /* we always do the auto-type conversions; the & and sizeof parser contains
7879 * code to revert this! */
7880 select->base.type = automatic_type_conversion(res_type);
7882 type_t *skipped = skip_typeref(res_type);
7883 if (skipped->kind == TYPE_BITFIELD) {
7884 select->base.type = skipped->bitfield.base_type;
7890 static void check_call_argument(const function_parameter_t *parameter,
7891 call_argument_t *argument, unsigned pos)
7893 type_t *expected_type = parameter->type;
7894 type_t *expected_type_skip = skip_typeref(expected_type);
7895 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7896 expression_t *arg_expr = argument->expression;
7897 type_t *arg_type = skip_typeref(arg_expr->base.type);
7899 /* handle transparent union gnu extension */
7900 if (is_type_union(expected_type_skip)
7901 && (expected_type_skip->base.modifiers
7902 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7903 compound_t *union_decl = expected_type_skip->compound.compound;
7904 type_t *best_type = NULL;
7905 entity_t *entry = union_decl->members.entities;
7906 for ( ; entry != NULL; entry = entry->base.next) {
7907 assert(is_declaration(entry));
7908 type_t *decl_type = entry->declaration.type;
7909 error = semantic_assign(decl_type, arg_expr);
7910 if (error == ASSIGN_ERROR_INCOMPATIBLE
7911 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7914 if (error == ASSIGN_SUCCESS) {
7915 best_type = decl_type;
7916 } else if (best_type == NULL) {
7917 best_type = decl_type;
7921 if (best_type != NULL) {
7922 expected_type = best_type;
7926 error = semantic_assign(expected_type, arg_expr);
7927 argument->expression = create_implicit_cast(argument->expression,
7930 if (error != ASSIGN_SUCCESS) {
7931 /* report exact scope in error messages (like "in argument 3") */
7933 snprintf(buf, sizeof(buf), "call argument %u", pos);
7934 report_assign_error(error, expected_type, arg_expr, buf,
7935 &arg_expr->base.source_position);
7936 } else if (warning.traditional || warning.conversion) {
7937 type_t *const promoted_type = get_default_promoted_type(arg_type);
7938 if (!types_compatible(expected_type_skip, promoted_type) &&
7939 !types_compatible(expected_type_skip, type_void_ptr) &&
7940 !types_compatible(type_void_ptr, promoted_type)) {
7941 /* Deliberately show the skipped types in this warning */
7942 warningf(&arg_expr->base.source_position,
7943 "passing call argument %u as '%T' rather than '%T' due to prototype",
7944 pos, expected_type_skip, promoted_type);
7950 * Parse a call expression, ie. expression '( ... )'.
7952 * @param expression the function address
7954 static expression_t *parse_call_expression(expression_t *expression)
7956 expression_t *result = allocate_expression_zero(EXPR_CALL);
7957 call_expression_t *call = &result->call;
7958 call->function = expression;
7960 type_t *const orig_type = expression->base.type;
7961 type_t *const type = skip_typeref(orig_type);
7963 function_type_t *function_type = NULL;
7964 if (is_type_pointer(type)) {
7965 type_t *const to_type = skip_typeref(type->pointer.points_to);
7967 if (is_type_function(to_type)) {
7968 function_type = &to_type->function;
7969 call->base.type = function_type->return_type;
7973 if (function_type == NULL && is_type_valid(type)) {
7974 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7977 /* parse arguments */
7979 add_anchor_token(')');
7980 add_anchor_token(',');
7982 if (token.type != ')') {
7983 call_argument_t *last_argument = NULL;
7986 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7988 argument->expression = parse_assignment_expression();
7989 if (last_argument == NULL) {
7990 call->arguments = argument;
7992 last_argument->next = argument;
7994 last_argument = argument;
7996 if (token.type != ',')
8001 rem_anchor_token(',');
8002 rem_anchor_token(')');
8005 if (function_type == NULL)
8008 function_parameter_t *parameter = function_type->parameters;
8009 call_argument_t *argument = call->arguments;
8010 if (!function_type->unspecified_parameters) {
8011 for (unsigned pos = 0; parameter != NULL && argument != NULL;
8012 parameter = parameter->next, argument = argument->next) {
8013 check_call_argument(parameter, argument, ++pos);
8016 if (parameter != NULL) {
8017 errorf(HERE, "too few arguments to function '%E'", expression);
8018 } else if (argument != NULL && !function_type->variadic) {
8019 errorf(HERE, "too many arguments to function '%E'", expression);
8023 /* do default promotion */
8024 for (; argument != NULL; argument = argument->next) {
8025 type_t *type = argument->expression->base.type;
8027 type = get_default_promoted_type(type);
8029 argument->expression
8030 = create_implicit_cast(argument->expression, type);
8033 check_format(&result->call);
8035 if (warning.aggregate_return &&
8036 is_type_compound(skip_typeref(function_type->return_type))) {
8037 warningf(&result->base.source_position,
8038 "function call has aggregate value");
8045 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
8047 static bool same_compound_type(const type_t *type1, const type_t *type2)
8050 is_type_compound(type1) &&
8051 type1->kind == type2->kind &&
8052 type1->compound.compound == type2->compound.compound;
8055 static expression_t const *get_reference_address(expression_t const *expr)
8057 bool regular_take_address = true;
8059 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8060 expr = expr->unary.value;
8062 regular_take_address = false;
8065 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8068 expr = expr->unary.value;
8071 if (expr->kind != EXPR_REFERENCE)
8074 /* special case for functions which are automatically converted to a
8075 * pointer to function without an extra TAKE_ADDRESS operation */
8076 if (!regular_take_address &&
8077 expr->reference.entity->kind != ENTITY_FUNCTION) {
8084 static void warn_reference_address_as_bool(expression_t const* expr)
8086 if (!warning.address)
8089 expr = get_reference_address(expr);
8091 warningf(&expr->base.source_position,
8092 "the address of '%Y' will always evaluate as 'true'",
8093 expr->reference.entity->base.symbol);
8097 static void semantic_condition(expression_t const *const expr,
8098 char const *const context)
8100 type_t *const type = skip_typeref(expr->base.type);
8101 if (is_type_scalar(type)) {
8102 warn_reference_address_as_bool(expr);
8103 } else if (is_type_valid(type)) {
8104 errorf(&expr->base.source_position,
8105 "%s must have scalar type", context);
8110 * Parse a conditional expression, ie. 'expression ? ... : ...'.
8112 * @param expression the conditional expression
8114 static expression_t *parse_conditional_expression(expression_t *expression)
8116 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
8118 conditional_expression_t *conditional = &result->conditional;
8119 conditional->condition = expression;
8122 add_anchor_token(':');
8124 /* §6.5.15:2 The first operand shall have scalar type. */
8125 semantic_condition(expression, "condition of conditional operator");
8127 expression_t *true_expression = expression;
8128 bool gnu_cond = false;
8129 if (GNU_MODE && token.type == ':') {
8132 true_expression = parse_expression();
8134 rem_anchor_token(':');
8136 expression_t *false_expression =
8137 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
8139 type_t *const orig_true_type = true_expression->base.type;
8140 type_t *const orig_false_type = false_expression->base.type;
8141 type_t *const true_type = skip_typeref(orig_true_type);
8142 type_t *const false_type = skip_typeref(orig_false_type);
8145 type_t *result_type;
8146 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8147 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
8148 /* ISO/IEC 14882:1998(E) §5.16:2 */
8149 if (true_expression->kind == EXPR_UNARY_THROW) {
8150 result_type = false_type;
8151 } else if (false_expression->kind == EXPR_UNARY_THROW) {
8152 result_type = true_type;
8154 if (warning.other && (
8155 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8156 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
8158 warningf(&conditional->base.source_position,
8159 "ISO C forbids conditional expression with only one void side");
8161 result_type = type_void;
8163 } else if (is_type_arithmetic(true_type)
8164 && is_type_arithmetic(false_type)) {
8165 result_type = semantic_arithmetic(true_type, false_type);
8167 true_expression = create_implicit_cast(true_expression, result_type);
8168 false_expression = create_implicit_cast(false_expression, result_type);
8170 conditional->true_expression = true_expression;
8171 conditional->false_expression = false_expression;
8172 conditional->base.type = result_type;
8173 } else if (same_compound_type(true_type, false_type)) {
8174 /* just take 1 of the 2 types */
8175 result_type = true_type;
8176 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
8177 type_t *pointer_type;
8179 expression_t *other_expression;
8180 if (is_type_pointer(true_type) &&
8181 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
8182 pointer_type = true_type;
8183 other_type = false_type;
8184 other_expression = false_expression;
8186 pointer_type = false_type;
8187 other_type = true_type;
8188 other_expression = true_expression;
8191 if (is_null_pointer_constant(other_expression)) {
8192 result_type = pointer_type;
8193 } else if (is_type_pointer(other_type)) {
8194 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8195 type_t *to2 = skip_typeref(other_type->pointer.points_to);
8198 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8199 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8201 } else if (types_compatible(get_unqualified_type(to1),
8202 get_unqualified_type(to2))) {
8205 if (warning.other) {
8206 warningf(&conditional->base.source_position,
8207 "pointer types '%T' and '%T' in conditional expression are incompatible",
8208 true_type, false_type);
8213 type_t *const type =
8214 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8215 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8216 } else if (is_type_integer(other_type)) {
8217 if (warning.other) {
8218 warningf(&conditional->base.source_position,
8219 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8221 result_type = pointer_type;
8223 if (is_type_valid(other_type)) {
8224 type_error_incompatible("while parsing conditional",
8225 &expression->base.source_position, true_type, false_type);
8227 result_type = type_error_type;
8230 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8231 type_error_incompatible("while parsing conditional",
8232 &conditional->base.source_position, true_type,
8235 result_type = type_error_type;
8238 conditional->true_expression
8239 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8240 conditional->false_expression
8241 = create_implicit_cast(false_expression, result_type);
8242 conditional->base.type = result_type;
8245 return create_invalid_expression();
8249 * Parse an extension expression.
8251 static expression_t *parse_extension(void)
8253 eat(T___extension__);
8255 bool old_gcc_extension = in_gcc_extension;
8256 in_gcc_extension = true;
8257 expression_t *expression = parse_sub_expression(PREC_UNARY);
8258 in_gcc_extension = old_gcc_extension;
8263 * Parse a __builtin_classify_type() expression.
8265 static expression_t *parse_builtin_classify_type(void)
8267 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8268 result->base.type = type_int;
8270 eat(T___builtin_classify_type);
8273 add_anchor_token(')');
8274 expression_t *expression = parse_expression();
8275 rem_anchor_token(')');
8277 result->classify_type.type_expression = expression;
8281 return create_invalid_expression();
8285 * Parse a delete expression
8286 * ISO/IEC 14882:1998(E) §5.3.5
8288 static expression_t *parse_delete(void)
8290 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8291 result->base.type = type_void;
8295 if (token.type == '[') {
8297 result->kind = EXPR_UNARY_DELETE_ARRAY;
8302 expression_t *const value = parse_sub_expression(PREC_CAST);
8303 result->unary.value = value;
8305 type_t *const type = skip_typeref(value->base.type);
8306 if (!is_type_pointer(type)) {
8307 errorf(&value->base.source_position,
8308 "operand of delete must have pointer type");
8309 } else if (warning.other &&
8310 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8311 warningf(&value->base.source_position,
8312 "deleting 'void*' is undefined");
8319 * Parse a throw expression
8320 * ISO/IEC 14882:1998(E) §15:1
8322 static expression_t *parse_throw(void)
8324 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8325 result->base.type = type_void;
8329 expression_t *value = NULL;
8330 switch (token.type) {
8332 value = parse_assignment_expression();
8333 /* ISO/IEC 14882:1998(E) §15.1:3 */
8334 type_t *const orig_type = value->base.type;
8335 type_t *const type = skip_typeref(orig_type);
8336 if (is_type_incomplete(type)) {
8337 errorf(&value->base.source_position,
8338 "cannot throw object of incomplete type '%T'", orig_type);
8339 } else if (is_type_pointer(type)) {
8340 type_t *const points_to = skip_typeref(type->pointer.points_to);
8341 if (is_type_incomplete(points_to) &&
8342 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8343 errorf(&value->base.source_position,
8344 "cannot throw pointer to incomplete type '%T'", orig_type);
8352 result->unary.value = value;
8357 static bool check_pointer_arithmetic(const source_position_t *source_position,
8358 type_t *pointer_type,
8359 type_t *orig_pointer_type)
8361 type_t *points_to = pointer_type->pointer.points_to;
8362 points_to = skip_typeref(points_to);
8364 if (is_type_incomplete(points_to)) {
8365 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8366 errorf(source_position,
8367 "arithmetic with pointer to incomplete type '%T' not allowed",
8370 } else if (warning.pointer_arith) {
8371 warningf(source_position,
8372 "pointer of type '%T' used in arithmetic",
8375 } else if (is_type_function(points_to)) {
8377 errorf(source_position,
8378 "arithmetic with pointer to function type '%T' not allowed",
8381 } else if (warning.pointer_arith) {
8382 warningf(source_position,
8383 "pointer to a function '%T' used in arithmetic",
8390 static bool is_lvalue(const expression_t *expression)
8392 /* TODO: doesn't seem to be consistent with §6.3.2.1 (1) */
8393 switch (expression->kind) {
8394 case EXPR_REFERENCE:
8395 case EXPR_ARRAY_ACCESS:
8397 case EXPR_UNARY_DEREFERENCE:
8401 type_t *type = skip_typeref(expression->base.type);
8403 /* ISO/IEC 14882:1998(E) §3.10:3 */
8404 is_type_reference(type) ||
8405 /* Claim it is an lvalue, if the type is invalid. There was a parse
8406 * error before, which maybe prevented properly recognizing it as
8408 !is_type_valid(type);
8413 static void semantic_incdec(unary_expression_t *expression)
8415 type_t *const orig_type = expression->value->base.type;
8416 type_t *const type = skip_typeref(orig_type);
8417 if (is_type_pointer(type)) {
8418 if (!check_pointer_arithmetic(&expression->base.source_position,
8422 } else if (!is_type_real(type) && is_type_valid(type)) {
8423 /* TODO: improve error message */
8424 errorf(&expression->base.source_position,
8425 "operation needs an arithmetic or pointer type");
8428 if (!is_lvalue(expression->value)) {
8429 /* TODO: improve error message */
8430 errorf(&expression->base.source_position, "lvalue required as operand");
8432 expression->base.type = orig_type;
8435 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8437 type_t *const orig_type = expression->value->base.type;
8438 type_t *const type = skip_typeref(orig_type);
8439 if (!is_type_arithmetic(type)) {
8440 if (is_type_valid(type)) {
8441 /* TODO: improve error message */
8442 errorf(&expression->base.source_position,
8443 "operation needs an arithmetic type");
8448 expression->base.type = orig_type;
8451 static void semantic_unexpr_plus(unary_expression_t *expression)
8453 semantic_unexpr_arithmetic(expression);
8454 if (warning.traditional)
8455 warningf(&expression->base.source_position,
8456 "traditional C rejects the unary plus operator");
8459 static void semantic_not(unary_expression_t *expression)
8461 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8462 semantic_condition(expression->value, "operand of !");
8463 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8466 static void semantic_unexpr_integer(unary_expression_t *expression)
8468 type_t *const orig_type = expression->value->base.type;
8469 type_t *const type = skip_typeref(orig_type);
8470 if (!is_type_integer(type)) {
8471 if (is_type_valid(type)) {
8472 errorf(&expression->base.source_position,
8473 "operand of ~ must be of integer type");
8478 expression->base.type = orig_type;
8481 static void semantic_dereference(unary_expression_t *expression)
8483 type_t *const orig_type = expression->value->base.type;
8484 type_t *const type = skip_typeref(orig_type);
8485 if (!is_type_pointer(type)) {
8486 if (is_type_valid(type)) {
8487 errorf(&expression->base.source_position,
8488 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8493 type_t *result_type = type->pointer.points_to;
8494 result_type = automatic_type_conversion(result_type);
8495 expression->base.type = result_type;
8499 * Record that an address is taken (expression represents an lvalue).
8501 * @param expression the expression
8502 * @param may_be_register if true, the expression might be an register
8504 static void set_address_taken(expression_t *expression, bool may_be_register)
8506 if (expression->kind != EXPR_REFERENCE)
8509 entity_t *const entity = expression->reference.entity;
8511 if (entity->kind != ENTITY_VARIABLE)
8514 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8515 && !may_be_register) {
8516 errorf(&expression->base.source_position,
8517 "address of register variable '%Y' requested",
8518 entity->base.symbol);
8521 entity->variable.address_taken = true;
8525 * Check the semantic of the address taken expression.
8527 static void semantic_take_addr(unary_expression_t *expression)
8529 expression_t *value = expression->value;
8530 value->base.type = revert_automatic_type_conversion(value);
8532 type_t *orig_type = value->base.type;
8533 type_t *type = skip_typeref(orig_type);
8534 if (!is_type_valid(type))
8538 if (!is_lvalue(value)) {
8539 errorf(&expression->base.source_position, "'&' requires an lvalue");
8541 if (type->kind == TYPE_BITFIELD) {
8542 errorf(&expression->base.source_position,
8543 "'&' not allowed on object with bitfield type '%T'",
8547 set_address_taken(value, false);
8549 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8552 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8553 static expression_t *parse_##unexpression_type(void) \
8555 expression_t *unary_expression \
8556 = allocate_expression_zero(unexpression_type); \
8558 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8560 sfunc(&unary_expression->unary); \
8562 return unary_expression; \
8565 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8566 semantic_unexpr_arithmetic)
8567 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8568 semantic_unexpr_plus)
8569 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8571 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8572 semantic_dereference)
8573 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8575 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8576 semantic_unexpr_integer)
8577 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8579 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8582 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8584 static expression_t *parse_##unexpression_type(expression_t *left) \
8586 expression_t *unary_expression \
8587 = allocate_expression_zero(unexpression_type); \
8589 unary_expression->unary.value = left; \
8591 sfunc(&unary_expression->unary); \
8593 return unary_expression; \
8596 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8597 EXPR_UNARY_POSTFIX_INCREMENT,
8599 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8600 EXPR_UNARY_POSTFIX_DECREMENT,
8603 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8605 /* TODO: handle complex + imaginary types */
8607 type_left = get_unqualified_type(type_left);
8608 type_right = get_unqualified_type(type_right);
8610 /* § 6.3.1.8 Usual arithmetic conversions */
8611 if (type_left == type_long_double || type_right == type_long_double) {
8612 return type_long_double;
8613 } else if (type_left == type_double || type_right == type_double) {
8615 } else if (type_left == type_float || type_right == type_float) {
8619 type_left = promote_integer(type_left);
8620 type_right = promote_integer(type_right);
8622 if (type_left == type_right)
8625 bool const signed_left = is_type_signed(type_left);
8626 bool const signed_right = is_type_signed(type_right);
8627 int const rank_left = get_rank(type_left);
8628 int const rank_right = get_rank(type_right);
8630 if (signed_left == signed_right)
8631 return rank_left >= rank_right ? type_left : type_right;
8640 u_rank = rank_right;
8641 u_type = type_right;
8643 s_rank = rank_right;
8644 s_type = type_right;
8649 if (u_rank >= s_rank)
8652 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8654 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8655 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8659 case ATOMIC_TYPE_INT: return type_unsigned_int;
8660 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8661 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8663 default: panic("invalid atomic type");
8668 * Check the semantic restrictions for a binary expression.
8670 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8672 expression_t *const left = expression->left;
8673 expression_t *const right = expression->right;
8674 type_t *const orig_type_left = left->base.type;
8675 type_t *const orig_type_right = right->base.type;
8676 type_t *const type_left = skip_typeref(orig_type_left);
8677 type_t *const type_right = skip_typeref(orig_type_right);
8679 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8680 /* TODO: improve error message */
8681 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8682 errorf(&expression->base.source_position,
8683 "operation needs arithmetic types");
8688 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8689 expression->left = create_implicit_cast(left, arithmetic_type);
8690 expression->right = create_implicit_cast(right, arithmetic_type);
8691 expression->base.type = arithmetic_type;
8694 static void warn_div_by_zero(binary_expression_t const *const expression)
8696 if (!warning.div_by_zero ||
8697 !is_type_integer(expression->base.type))
8700 expression_t const *const right = expression->right;
8701 /* The type of the right operand can be different for /= */
8702 if (is_type_integer(right->base.type) &&
8703 is_constant_expression(right) &&
8704 fold_constant(right) == 0) {
8705 warningf(&expression->base.source_position, "division by zero");
8710 * Check the semantic restrictions for a div/mod expression.
8712 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8713 semantic_binexpr_arithmetic(expression);
8714 warn_div_by_zero(expression);
8717 static void semantic_shift_op(binary_expression_t *expression)
8719 expression_t *const left = expression->left;
8720 expression_t *const right = expression->right;
8721 type_t *const orig_type_left = left->base.type;
8722 type_t *const orig_type_right = right->base.type;
8723 type_t * type_left = skip_typeref(orig_type_left);
8724 type_t * type_right = skip_typeref(orig_type_right);
8726 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8727 /* TODO: improve error message */
8728 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8729 errorf(&expression->base.source_position,
8730 "operands of shift operation must have integer types");
8735 type_left = promote_integer(type_left);
8736 type_right = promote_integer(type_right);
8738 expression->left = create_implicit_cast(left, type_left);
8739 expression->right = create_implicit_cast(right, type_right);
8740 expression->base.type = type_left;
8743 static void semantic_add(binary_expression_t *expression)
8745 expression_t *const left = expression->left;
8746 expression_t *const right = expression->right;
8747 type_t *const orig_type_left = left->base.type;
8748 type_t *const orig_type_right = right->base.type;
8749 type_t *const type_left = skip_typeref(orig_type_left);
8750 type_t *const type_right = skip_typeref(orig_type_right);
8753 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8754 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8755 expression->left = create_implicit_cast(left, arithmetic_type);
8756 expression->right = create_implicit_cast(right, arithmetic_type);
8757 expression->base.type = arithmetic_type;
8759 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8760 check_pointer_arithmetic(&expression->base.source_position,
8761 type_left, orig_type_left);
8762 expression->base.type = type_left;
8763 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8764 check_pointer_arithmetic(&expression->base.source_position,
8765 type_right, orig_type_right);
8766 expression->base.type = type_right;
8767 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8768 errorf(&expression->base.source_position,
8769 "invalid operands to binary + ('%T', '%T')",
8770 orig_type_left, orig_type_right);
8774 static void semantic_sub(binary_expression_t *expression)
8776 expression_t *const left = expression->left;
8777 expression_t *const right = expression->right;
8778 type_t *const orig_type_left = left->base.type;
8779 type_t *const orig_type_right = right->base.type;
8780 type_t *const type_left = skip_typeref(orig_type_left);
8781 type_t *const type_right = skip_typeref(orig_type_right);
8782 source_position_t const *const pos = &expression->base.source_position;
8785 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8786 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8787 expression->left = create_implicit_cast(left, arithmetic_type);
8788 expression->right = create_implicit_cast(right, arithmetic_type);
8789 expression->base.type = arithmetic_type;
8791 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8792 check_pointer_arithmetic(&expression->base.source_position,
8793 type_left, orig_type_left);
8794 expression->base.type = type_left;
8795 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8796 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8797 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8798 if (!types_compatible(unqual_left, unqual_right)) {
8800 "subtracting pointers to incompatible types '%T' and '%T'",
8801 orig_type_left, orig_type_right);
8802 } else if (!is_type_object(unqual_left)) {
8803 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8804 errorf(pos, "subtracting pointers to non-object types '%T'",
8806 } else if (warning.other) {
8807 warningf(pos, "subtracting pointers to void");
8810 expression->base.type = type_ptrdiff_t;
8811 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8812 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8813 orig_type_left, orig_type_right);
8817 static void warn_string_literal_address(expression_t const* expr)
8819 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8820 expr = expr->unary.value;
8821 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8823 expr = expr->unary.value;
8826 if (expr->kind == EXPR_STRING_LITERAL ||
8827 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8828 warningf(&expr->base.source_position,
8829 "comparison with string literal results in unspecified behaviour");
8834 * Check the semantics of comparison expressions.
8836 * @param expression The expression to check.
8838 static void semantic_comparison(binary_expression_t *expression)
8840 expression_t *left = expression->left;
8841 expression_t *right = expression->right;
8843 if (warning.address) {
8844 warn_string_literal_address(left);
8845 warn_string_literal_address(right);
8847 expression_t const* const func_left = get_reference_address(left);
8848 if (func_left != NULL && is_null_pointer_constant(right)) {
8849 warningf(&expression->base.source_position,
8850 "the address of '%Y' will never be NULL",
8851 func_left->reference.entity->base.symbol);
8854 expression_t const* const func_right = get_reference_address(right);
8855 if (func_right != NULL && is_null_pointer_constant(right)) {
8856 warningf(&expression->base.source_position,
8857 "the address of '%Y' will never be NULL",
8858 func_right->reference.entity->base.symbol);
8862 type_t *orig_type_left = left->base.type;
8863 type_t *orig_type_right = right->base.type;
8864 type_t *type_left = skip_typeref(orig_type_left);
8865 type_t *type_right = skip_typeref(orig_type_right);
8867 /* TODO non-arithmetic types */
8868 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8869 /* test for signed vs unsigned compares */
8870 if (warning.sign_compare &&
8871 (expression->base.kind != EXPR_BINARY_EQUAL &&
8872 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
8873 (is_type_signed(type_left) != is_type_signed(type_right))) {
8875 /* check if 1 of the operands is a constant, in this case we just
8876 * check wether we can safely represent the resulting constant in
8877 * the type of the other operand. */
8878 expression_t *const_expr = NULL;
8879 expression_t *other_expr = NULL;
8881 if (is_constant_expression(left)) {
8884 } else if (is_constant_expression(right)) {
8889 if (const_expr != NULL) {
8890 type_t *other_type = skip_typeref(other_expr->base.type);
8891 long val = fold_constant(const_expr);
8892 /* TODO: check if val can be represented by other_type */
8896 warningf(&expression->base.source_position,
8897 "comparison between signed and unsigned");
8899 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8900 expression->left = create_implicit_cast(left, arithmetic_type);
8901 expression->right = create_implicit_cast(right, arithmetic_type);
8902 expression->base.type = arithmetic_type;
8903 if (warning.float_equal &&
8904 (expression->base.kind == EXPR_BINARY_EQUAL ||
8905 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8906 is_type_float(arithmetic_type)) {
8907 warningf(&expression->base.source_position,
8908 "comparing floating point with == or != is unsafe");
8910 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8911 /* TODO check compatibility */
8912 } else if (is_type_pointer(type_left)) {
8913 expression->right = create_implicit_cast(right, type_left);
8914 } else if (is_type_pointer(type_right)) {
8915 expression->left = create_implicit_cast(left, type_right);
8916 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8917 type_error_incompatible("invalid operands in comparison",
8918 &expression->base.source_position,
8919 type_left, type_right);
8921 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8925 * Checks if a compound type has constant fields.
8927 static bool has_const_fields(const compound_type_t *type)
8929 compound_t *compound = type->compound;
8930 entity_t *entry = compound->members.entities;
8932 for (; entry != NULL; entry = entry->base.next) {
8933 if (!is_declaration(entry))
8936 const type_t *decl_type = skip_typeref(entry->declaration.type);
8937 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8944 static bool is_valid_assignment_lhs(expression_t const* const left)
8946 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8947 type_t *const type_left = skip_typeref(orig_type_left);
8949 if (!is_lvalue(left)) {
8950 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8955 if (is_type_array(type_left)) {
8956 errorf(HERE, "cannot assign to arrays ('%E')", left);
8959 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8960 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8964 if (is_type_incomplete(type_left)) {
8965 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8966 left, orig_type_left);
8969 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8970 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8971 left, orig_type_left);
8978 static void semantic_arithmetic_assign(binary_expression_t *expression)
8980 expression_t *left = expression->left;
8981 expression_t *right = expression->right;
8982 type_t *orig_type_left = left->base.type;
8983 type_t *orig_type_right = right->base.type;
8985 if (!is_valid_assignment_lhs(left))
8988 type_t *type_left = skip_typeref(orig_type_left);
8989 type_t *type_right = skip_typeref(orig_type_right);
8991 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8992 /* TODO: improve error message */
8993 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8994 errorf(&expression->base.source_position,
8995 "operation needs arithmetic types");
9000 /* combined instructions are tricky. We can't create an implicit cast on
9001 * the left side, because we need the uncasted form for the store.
9002 * The ast2firm pass has to know that left_type must be right_type
9003 * for the arithmetic operation and create a cast by itself */
9004 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9005 expression->right = create_implicit_cast(right, arithmetic_type);
9006 expression->base.type = type_left;
9009 static void semantic_divmod_assign(binary_expression_t *expression)
9011 semantic_arithmetic_assign(expression);
9012 warn_div_by_zero(expression);
9015 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
9017 expression_t *const left = expression->left;
9018 expression_t *const right = expression->right;
9019 type_t *const orig_type_left = left->base.type;
9020 type_t *const orig_type_right = right->base.type;
9021 type_t *const type_left = skip_typeref(orig_type_left);
9022 type_t *const type_right = skip_typeref(orig_type_right);
9024 if (!is_valid_assignment_lhs(left))
9027 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9028 /* combined instructions are tricky. We can't create an implicit cast on
9029 * the left side, because we need the uncasted form for the store.
9030 * The ast2firm pass has to know that left_type must be right_type
9031 * for the arithmetic operation and create a cast by itself */
9032 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
9033 expression->right = create_implicit_cast(right, arithmetic_type);
9034 expression->base.type = type_left;
9035 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9036 check_pointer_arithmetic(&expression->base.source_position,
9037 type_left, orig_type_left);
9038 expression->base.type = type_left;
9039 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9040 errorf(&expression->base.source_position,
9041 "incompatible types '%T' and '%T' in assignment",
9042 orig_type_left, orig_type_right);
9047 * Check the semantic restrictions of a logical expression.
9049 static void semantic_logical_op(binary_expression_t *expression)
9051 /* §6.5.13:2 Each of the operands shall have scalar type.
9052 * §6.5.14:2 Each of the operands shall have scalar type. */
9053 semantic_condition(expression->left, "left operand of logical operator");
9054 semantic_condition(expression->right, "right operand of logical operator");
9055 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9059 * Check the semantic restrictions of a binary assign expression.
9061 static void semantic_binexpr_assign(binary_expression_t *expression)
9063 expression_t *left = expression->left;
9064 type_t *orig_type_left = left->base.type;
9066 if (!is_valid_assignment_lhs(left))
9069 assign_error_t error = semantic_assign(orig_type_left, expression->right);
9070 report_assign_error(error, orig_type_left, expression->right,
9071 "assignment", &left->base.source_position);
9072 expression->right = create_implicit_cast(expression->right, orig_type_left);
9073 expression->base.type = orig_type_left;
9077 * Determine if the outermost operation (or parts thereof) of the given
9078 * expression has no effect in order to generate a warning about this fact.
9079 * Therefore in some cases this only examines some of the operands of the
9080 * expression (see comments in the function and examples below).
9082 * f() + 23; // warning, because + has no effect
9083 * x || f(); // no warning, because x controls execution of f()
9084 * x ? y : f(); // warning, because y has no effect
9085 * (void)x; // no warning to be able to suppress the warning
9086 * This function can NOT be used for an "expression has definitely no effect"-
9088 static bool expression_has_effect(const expression_t *const expr)
9090 switch (expr->kind) {
9091 case EXPR_UNKNOWN: break;
9092 case EXPR_INVALID: return true; /* do NOT warn */
9093 case EXPR_REFERENCE: return false;
9094 case EXPR_REFERENCE_ENUM_VALUE: return false;
9095 /* suppress the warning for microsoft __noop operations */
9096 case EXPR_CONST: return expr->conste.is_ms_noop;
9097 case EXPR_CHARACTER_CONSTANT: return false;
9098 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
9099 case EXPR_STRING_LITERAL: return false;
9100 case EXPR_WIDE_STRING_LITERAL: return false;
9101 case EXPR_LABEL_ADDRESS: return false;
9104 const call_expression_t *const call = &expr->call;
9105 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
9108 switch (call->function->builtin_symbol.symbol->ID) {
9109 case T___builtin_va_end: return true;
9110 default: return false;
9114 /* Generate the warning if either the left or right hand side of a
9115 * conditional expression has no effect */
9116 case EXPR_CONDITIONAL: {
9117 const conditional_expression_t *const cond = &expr->conditional;
9119 expression_has_effect(cond->true_expression) &&
9120 expression_has_effect(cond->false_expression);
9123 case EXPR_SELECT: return false;
9124 case EXPR_ARRAY_ACCESS: return false;
9125 case EXPR_SIZEOF: return false;
9126 case EXPR_CLASSIFY_TYPE: return false;
9127 case EXPR_ALIGNOF: return false;
9129 case EXPR_FUNCNAME: return false;
9130 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
9131 case EXPR_BUILTIN_CONSTANT_P: return false;
9132 case EXPR_BUILTIN_PREFETCH: return true;
9133 case EXPR_OFFSETOF: return false;
9134 case EXPR_VA_START: return true;
9135 case EXPR_VA_ARG: return true;
9136 case EXPR_STATEMENT: return true; // TODO
9137 case EXPR_COMPOUND_LITERAL: return false;
9139 case EXPR_UNARY_NEGATE: return false;
9140 case EXPR_UNARY_PLUS: return false;
9141 case EXPR_UNARY_BITWISE_NEGATE: return false;
9142 case EXPR_UNARY_NOT: return false;
9143 case EXPR_UNARY_DEREFERENCE: return false;
9144 case EXPR_UNARY_TAKE_ADDRESS: return false;
9145 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
9146 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
9147 case EXPR_UNARY_PREFIX_INCREMENT: return true;
9148 case EXPR_UNARY_PREFIX_DECREMENT: return true;
9150 /* Treat void casts as if they have an effect in order to being able to
9151 * suppress the warning */
9152 case EXPR_UNARY_CAST: {
9153 type_t *const type = skip_typeref(expr->base.type);
9154 return is_type_atomic(type, ATOMIC_TYPE_VOID);
9157 case EXPR_UNARY_CAST_IMPLICIT: return true;
9158 case EXPR_UNARY_ASSUME: return true;
9159 case EXPR_UNARY_DELETE: return true;
9160 case EXPR_UNARY_DELETE_ARRAY: return true;
9161 case EXPR_UNARY_THROW: return true;
9163 case EXPR_BINARY_ADD: return false;
9164 case EXPR_BINARY_SUB: return false;
9165 case EXPR_BINARY_MUL: return false;
9166 case EXPR_BINARY_DIV: return false;
9167 case EXPR_BINARY_MOD: return false;
9168 case EXPR_BINARY_EQUAL: return false;
9169 case EXPR_BINARY_NOTEQUAL: return false;
9170 case EXPR_BINARY_LESS: return false;
9171 case EXPR_BINARY_LESSEQUAL: return false;
9172 case EXPR_BINARY_GREATER: return false;
9173 case EXPR_BINARY_GREATEREQUAL: return false;
9174 case EXPR_BINARY_BITWISE_AND: return false;
9175 case EXPR_BINARY_BITWISE_OR: return false;
9176 case EXPR_BINARY_BITWISE_XOR: return false;
9177 case EXPR_BINARY_SHIFTLEFT: return false;
9178 case EXPR_BINARY_SHIFTRIGHT: return false;
9179 case EXPR_BINARY_ASSIGN: return true;
9180 case EXPR_BINARY_MUL_ASSIGN: return true;
9181 case EXPR_BINARY_DIV_ASSIGN: return true;
9182 case EXPR_BINARY_MOD_ASSIGN: return true;
9183 case EXPR_BINARY_ADD_ASSIGN: return true;
9184 case EXPR_BINARY_SUB_ASSIGN: return true;
9185 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
9186 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
9187 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9188 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9189 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
9191 /* Only examine the right hand side of && and ||, because the left hand
9192 * side already has the effect of controlling the execution of the right
9194 case EXPR_BINARY_LOGICAL_AND:
9195 case EXPR_BINARY_LOGICAL_OR:
9196 /* Only examine the right hand side of a comma expression, because the left
9197 * hand side has a separate warning */
9198 case EXPR_BINARY_COMMA:
9199 return expression_has_effect(expr->binary.right);
9201 case EXPR_BINARY_BUILTIN_EXPECT: return true;
9202 case EXPR_BINARY_ISGREATER: return false;
9203 case EXPR_BINARY_ISGREATEREQUAL: return false;
9204 case EXPR_BINARY_ISLESS: return false;
9205 case EXPR_BINARY_ISLESSEQUAL: return false;
9206 case EXPR_BINARY_ISLESSGREATER: return false;
9207 case EXPR_BINARY_ISUNORDERED: return false;
9210 internal_errorf(HERE, "unexpected expression");
9213 static void semantic_comma(binary_expression_t *expression)
9215 if (warning.unused_value) {
9216 const expression_t *const left = expression->left;
9217 if (!expression_has_effect(left)) {
9218 warningf(&left->base.source_position,
9219 "left-hand operand of comma expression has no effect");
9222 expression->base.type = expression->right->base.type;
9226 * @param prec_r precedence of the right operand
9228 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9229 static expression_t *parse_##binexpression_type(expression_t *left) \
9231 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9232 binexpr->binary.left = left; \
9235 expression_t *right = parse_sub_expression(prec_r); \
9237 binexpr->binary.right = right; \
9238 sfunc(&binexpr->binary); \
9243 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9244 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9245 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9246 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9247 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9248 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9249 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9250 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9251 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9252 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9253 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9254 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9255 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9256 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9257 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9258 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9259 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9260 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9261 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9262 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9263 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9264 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9265 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9266 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9267 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9268 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9269 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9270 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9271 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9272 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9275 static expression_t *parse_sub_expression(precedence_t precedence)
9277 if (token.type < 0) {
9278 return expected_expression_error();
9281 expression_parser_function_t *parser
9282 = &expression_parsers[token.type];
9283 source_position_t source_position = token.source_position;
9286 if (parser->parser != NULL) {
9287 left = parser->parser();
9289 left = parse_primary_expression();
9291 assert(left != NULL);
9292 left->base.source_position = source_position;
9295 if (token.type < 0) {
9296 return expected_expression_error();
9299 parser = &expression_parsers[token.type];
9300 if (parser->infix_parser == NULL)
9302 if (parser->infix_precedence < precedence)
9305 left = parser->infix_parser(left);
9307 assert(left != NULL);
9308 assert(left->kind != EXPR_UNKNOWN);
9309 left->base.source_position = source_position;
9316 * Parse an expression.
9318 static expression_t *parse_expression(void)
9320 return parse_sub_expression(PREC_EXPRESSION);
9324 * Register a parser for a prefix-like operator.
9326 * @param parser the parser function
9327 * @param token_type the token type of the prefix token
9329 static void register_expression_parser(parse_expression_function parser,
9332 expression_parser_function_t *entry = &expression_parsers[token_type];
9334 if (entry->parser != NULL) {
9335 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9336 panic("trying to register multiple expression parsers for a token");
9338 entry->parser = parser;
9342 * Register a parser for an infix operator with given precedence.
9344 * @param parser the parser function
9345 * @param token_type the token type of the infix operator
9346 * @param precedence the precedence of the operator
9348 static void register_infix_parser(parse_expression_infix_function parser,
9349 int token_type, unsigned precedence)
9351 expression_parser_function_t *entry = &expression_parsers[token_type];
9353 if (entry->infix_parser != NULL) {
9354 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9355 panic("trying to register multiple infix expression parsers for a "
9358 entry->infix_parser = parser;
9359 entry->infix_precedence = precedence;
9363 * Initialize the expression parsers.
9365 static void init_expression_parsers(void)
9367 memset(&expression_parsers, 0, sizeof(expression_parsers));
9369 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9370 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9371 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9372 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9373 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9374 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9375 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9376 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9377 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9378 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9379 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9380 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9381 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9382 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9383 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9384 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9385 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9386 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9387 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9388 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9389 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9390 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9391 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9392 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9393 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9394 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9395 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9396 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9397 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9398 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9399 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9400 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9401 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9402 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9403 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9404 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9405 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9407 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9408 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9409 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9410 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9411 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9412 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9413 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9414 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9415 register_expression_parser(parse_sizeof, T_sizeof);
9416 register_expression_parser(parse_alignof, T___alignof__);
9417 register_expression_parser(parse_extension, T___extension__);
9418 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9419 register_expression_parser(parse_delete, T_delete);
9420 register_expression_parser(parse_throw, T_throw);
9424 * Parse a asm statement arguments specification.
9426 static asm_argument_t *parse_asm_arguments(bool is_out)
9428 asm_argument_t *result = NULL;
9429 asm_argument_t **anchor = &result;
9431 while (token.type == T_STRING_LITERAL || token.type == '[') {
9432 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9433 memset(argument, 0, sizeof(argument[0]));
9435 if (token.type == '[') {
9437 if (token.type != T_IDENTIFIER) {
9438 parse_error_expected("while parsing asm argument",
9439 T_IDENTIFIER, NULL);
9442 argument->symbol = token.v.symbol;
9447 argument->constraints = parse_string_literals();
9449 add_anchor_token(')');
9450 expression_t *expression = parse_expression();
9451 rem_anchor_token(')');
9453 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9454 * change size or type representation (e.g. int -> long is ok, but
9455 * int -> float is not) */
9456 if (expression->kind == EXPR_UNARY_CAST) {
9457 type_t *const type = expression->base.type;
9458 type_kind_t const kind = type->kind;
9459 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9462 if (kind == TYPE_ATOMIC) {
9463 atomic_type_kind_t const akind = type->atomic.akind;
9464 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9465 size = get_atomic_type_size(akind);
9467 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9468 size = get_atomic_type_size(get_intptr_kind());
9472 expression_t *const value = expression->unary.value;
9473 type_t *const value_type = value->base.type;
9474 type_kind_t const value_kind = value_type->kind;
9476 unsigned value_flags;
9477 unsigned value_size;
9478 if (value_kind == TYPE_ATOMIC) {
9479 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9480 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9481 value_size = get_atomic_type_size(value_akind);
9482 } else if (value_kind == TYPE_POINTER) {
9483 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9484 value_size = get_atomic_type_size(get_intptr_kind());
9489 if (value_flags != flags || value_size != size)
9493 } while (expression->kind == EXPR_UNARY_CAST);
9497 if (!is_lvalue(expression)) {
9498 errorf(&expression->base.source_position,
9499 "asm output argument is not an lvalue");
9502 if (argument->constraints.begin[0] == '+')
9503 mark_vars_read(expression, NULL);
9505 mark_vars_read(expression, NULL);
9507 argument->expression = expression;
9510 set_address_taken(expression, true);
9513 anchor = &argument->next;
9515 if (token.type != ',')
9526 * Parse a asm statement clobber specification.
9528 static asm_clobber_t *parse_asm_clobbers(void)
9530 asm_clobber_t *result = NULL;
9531 asm_clobber_t *last = NULL;
9533 while (token.type == T_STRING_LITERAL) {
9534 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9535 clobber->clobber = parse_string_literals();
9538 last->next = clobber;
9544 if (token.type != ',')
9553 * Parse an asm statement.
9555 static statement_t *parse_asm_statement(void)
9557 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9558 asm_statement_t *asm_statement = &statement->asms;
9562 if (token.type == T_volatile) {
9564 asm_statement->is_volatile = true;
9568 add_anchor_token(')');
9569 add_anchor_token(':');
9570 asm_statement->asm_text = parse_string_literals();
9572 if (token.type != ':') {
9573 rem_anchor_token(':');
9578 asm_statement->outputs = parse_asm_arguments(true);
9579 if (token.type != ':') {
9580 rem_anchor_token(':');
9585 asm_statement->inputs = parse_asm_arguments(false);
9586 if (token.type != ':') {
9587 rem_anchor_token(':');
9590 rem_anchor_token(':');
9593 asm_statement->clobbers = parse_asm_clobbers();
9596 rem_anchor_token(')');
9600 if (asm_statement->outputs == NULL) {
9601 /* GCC: An 'asm' instruction without any output operands will be treated
9602 * identically to a volatile 'asm' instruction. */
9603 asm_statement->is_volatile = true;
9608 return create_invalid_statement();
9612 * Parse a case statement.
9614 static statement_t *parse_case_statement(void)
9616 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9617 source_position_t *const pos = &statement->base.source_position;
9621 expression_t *const expression = parse_expression();
9622 statement->case_label.expression = expression;
9623 if (!is_constant_expression(expression)) {
9624 /* This check does not prevent the error message in all cases of an
9625 * prior error while parsing the expression. At least it catches the
9626 * common case of a mistyped enum entry. */
9627 if (is_type_valid(skip_typeref(expression->base.type))) {
9628 errorf(pos, "case label does not reduce to an integer constant");
9630 statement->case_label.is_bad = true;
9632 long const val = fold_constant(expression);
9633 statement->case_label.first_case = val;
9634 statement->case_label.last_case = val;
9638 if (token.type == T_DOTDOTDOT) {
9640 expression_t *const end_range = parse_expression();
9641 statement->case_label.end_range = end_range;
9642 if (!is_constant_expression(end_range)) {
9643 /* This check does not prevent the error message in all cases of an
9644 * prior error while parsing the expression. At least it catches the
9645 * common case of a mistyped enum entry. */
9646 if (is_type_valid(skip_typeref(end_range->base.type))) {
9647 errorf(pos, "case range does not reduce to an integer constant");
9649 statement->case_label.is_bad = true;
9651 long const val = fold_constant(end_range);
9652 statement->case_label.last_case = val;
9654 if (warning.other && val < statement->case_label.first_case) {
9655 statement->case_label.is_empty_range = true;
9656 warningf(pos, "empty range specified");
9662 PUSH_PARENT(statement);
9667 if (current_switch != NULL) {
9668 if (! statement->case_label.is_bad) {
9669 /* Check for duplicate case values */
9670 case_label_statement_t *c = &statement->case_label;
9671 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9672 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9675 if (c->last_case < l->first_case || c->first_case > l->last_case)
9678 errorf(pos, "duplicate case value (previously used %P)",
9679 &l->base.source_position);
9683 /* link all cases into the switch statement */
9684 if (current_switch->last_case == NULL) {
9685 current_switch->first_case = &statement->case_label;
9687 current_switch->last_case->next = &statement->case_label;
9689 current_switch->last_case = &statement->case_label;
9691 errorf(pos, "case label not within a switch statement");
9694 statement_t *const inner_stmt = parse_statement();
9695 statement->case_label.statement = inner_stmt;
9696 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9697 errorf(&inner_stmt->base.source_position, "declaration after case label");
9705 * Parse a default statement.
9707 static statement_t *parse_default_statement(void)
9709 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9713 PUSH_PARENT(statement);
9716 if (current_switch != NULL) {
9717 const case_label_statement_t *def_label = current_switch->default_label;
9718 if (def_label != NULL) {
9719 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9720 &def_label->base.source_position);
9722 current_switch->default_label = &statement->case_label;
9724 /* link all cases into the switch statement */
9725 if (current_switch->last_case == NULL) {
9726 current_switch->first_case = &statement->case_label;
9728 current_switch->last_case->next = &statement->case_label;
9730 current_switch->last_case = &statement->case_label;
9733 errorf(&statement->base.source_position,
9734 "'default' label not within a switch statement");
9737 statement_t *const inner_stmt = parse_statement();
9738 statement->case_label.statement = inner_stmt;
9739 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9740 errorf(&inner_stmt->base.source_position, "declaration after default label");
9747 return create_invalid_statement();
9751 * Parse a label statement.
9753 static statement_t *parse_label_statement(void)
9755 assert(token.type == T_IDENTIFIER);
9756 symbol_t *symbol = token.v.symbol;
9757 label_t *label = get_label(symbol);
9759 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9760 statement->label.label = label;
9764 PUSH_PARENT(statement);
9766 /* if statement is already set then the label is defined twice,
9767 * otherwise it was just mentioned in a goto/local label declaration so far
9769 if (label->statement != NULL) {
9770 errorf(HERE, "duplicate label '%Y' (declared %P)",
9771 symbol, &label->base.source_position);
9773 label->base.source_position = token.source_position;
9774 label->statement = statement;
9779 if (token.type == '}') {
9780 /* TODO only warn? */
9781 if (warning.other && false) {
9782 warningf(HERE, "label at end of compound statement");
9783 statement->label.statement = create_empty_statement();
9785 errorf(HERE, "label at end of compound statement");
9786 statement->label.statement = create_invalid_statement();
9788 } else if (token.type == ';') {
9789 /* Eat an empty statement here, to avoid the warning about an empty
9790 * statement after a label. label:; is commonly used to have a label
9791 * before a closing brace. */
9792 statement->label.statement = create_empty_statement();
9795 statement_t *const inner_stmt = parse_statement();
9796 statement->label.statement = inner_stmt;
9797 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9798 errorf(&inner_stmt->base.source_position, "declaration after label");
9802 /* remember the labels in a list for later checking */
9803 *label_anchor = &statement->label;
9804 label_anchor = &statement->label.next;
9811 * Parse an if statement.
9813 static statement_t *parse_if(void)
9815 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9819 PUSH_PARENT(statement);
9821 add_anchor_token('{');
9824 add_anchor_token(')');
9825 expression_t *const expr = parse_expression();
9826 statement->ifs.condition = expr;
9827 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9829 semantic_condition(expr, "condition of 'if'-statment");
9830 mark_vars_read(expr, NULL);
9831 rem_anchor_token(')');
9835 rem_anchor_token('{');
9837 add_anchor_token(T_else);
9838 statement->ifs.true_statement = parse_statement();
9839 rem_anchor_token(T_else);
9841 if (token.type == T_else) {
9843 statement->ifs.false_statement = parse_statement();
9851 * Check that all enums are handled in a switch.
9853 * @param statement the switch statement to check
9855 static void check_enum_cases(const switch_statement_t *statement) {
9856 const type_t *type = skip_typeref(statement->expression->base.type);
9857 if (! is_type_enum(type))
9859 const enum_type_t *enumt = &type->enumt;
9861 /* if we have a default, no warnings */
9862 if (statement->default_label != NULL)
9865 /* FIXME: calculation of value should be done while parsing */
9866 /* TODO: quadratic algorithm here. Change to an n log n one */
9867 long last_value = -1;
9868 const entity_t *entry = enumt->enume->base.next;
9869 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9870 entry = entry->base.next) {
9871 const expression_t *expression = entry->enum_value.value;
9872 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9874 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9875 if (l->expression == NULL)
9877 if (l->first_case <= value && value <= l->last_case) {
9883 warningf(&statement->base.source_position,
9884 "enumeration value '%Y' not handled in switch",
9885 entry->base.symbol);
9892 * Parse a switch statement.
9894 static statement_t *parse_switch(void)
9896 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9900 PUSH_PARENT(statement);
9903 add_anchor_token(')');
9904 expression_t *const expr = parse_expression();
9905 mark_vars_read(expr, NULL);
9906 type_t * type = skip_typeref(expr->base.type);
9907 if (is_type_integer(type)) {
9908 type = promote_integer(type);
9909 if (warning.traditional) {
9910 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9911 warningf(&expr->base.source_position,
9912 "'%T' switch expression not converted to '%T' in ISO C",
9916 } else if (is_type_valid(type)) {
9917 errorf(&expr->base.source_position,
9918 "switch quantity is not an integer, but '%T'", type);
9919 type = type_error_type;
9921 statement->switchs.expression = create_implicit_cast(expr, type);
9923 rem_anchor_token(')');
9925 switch_statement_t *rem = current_switch;
9926 current_switch = &statement->switchs;
9927 statement->switchs.body = parse_statement();
9928 current_switch = rem;
9930 if (warning.switch_default &&
9931 statement->switchs.default_label == NULL) {
9932 warningf(&statement->base.source_position, "switch has no default case");
9934 if (warning.switch_enum)
9935 check_enum_cases(&statement->switchs);
9941 return create_invalid_statement();
9944 static statement_t *parse_loop_body(statement_t *const loop)
9946 statement_t *const rem = current_loop;
9947 current_loop = loop;
9949 statement_t *const body = parse_statement();
9956 * Parse a while statement.
9958 static statement_t *parse_while(void)
9960 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9964 PUSH_PARENT(statement);
9967 add_anchor_token(')');
9968 expression_t *const cond = parse_expression();
9969 statement->whiles.condition = cond;
9970 /* §6.8.5:2 The controlling expression of an iteration statement shall
9971 * have scalar type. */
9972 semantic_condition(cond, "condition of 'while'-statement");
9973 mark_vars_read(cond, NULL);
9974 rem_anchor_token(')');
9977 statement->whiles.body = parse_loop_body(statement);
9983 return create_invalid_statement();
9987 * Parse a do statement.
9989 static statement_t *parse_do(void)
9991 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9995 PUSH_PARENT(statement);
9997 add_anchor_token(T_while);
9998 statement->do_while.body = parse_loop_body(statement);
9999 rem_anchor_token(T_while);
10003 add_anchor_token(')');
10004 expression_t *const cond = parse_expression();
10005 statement->do_while.condition = cond;
10006 /* §6.8.5:2 The controlling expression of an iteration statement shall
10007 * have scalar type. */
10008 semantic_condition(cond, "condition of 'do-while'-statement");
10009 mark_vars_read(cond, NULL);
10010 rem_anchor_token(')');
10018 return create_invalid_statement();
10022 * Parse a for statement.
10024 static statement_t *parse_for(void)
10026 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
10030 PUSH_PARENT(statement);
10032 size_t const top = environment_top();
10033 scope_t *old_scope = scope_push(&statement->fors.scope);
10036 add_anchor_token(')');
10038 if (token.type == ';') {
10040 } else if (is_declaration_specifier(&token, false)) {
10041 parse_declaration(record_entity, DECL_FLAGS_NONE);
10043 add_anchor_token(';');
10044 expression_t *const init = parse_expression();
10045 statement->fors.initialisation = init;
10046 mark_vars_read(init, VAR_ANY);
10047 if (warning.unused_value && !expression_has_effect(init)) {
10048 warningf(&init->base.source_position,
10049 "initialisation of 'for'-statement has no effect");
10051 rem_anchor_token(';');
10055 if (token.type != ';') {
10056 add_anchor_token(';');
10057 expression_t *const cond = parse_expression();
10058 statement->fors.condition = cond;
10059 /* §6.8.5:2 The controlling expression of an iteration statement shall
10060 * have scalar type. */
10061 semantic_condition(cond, "condition of 'for'-statement");
10062 mark_vars_read(cond, NULL);
10063 rem_anchor_token(';');
10066 if (token.type != ')') {
10067 expression_t *const step = parse_expression();
10068 statement->fors.step = step;
10069 mark_vars_read(step, VAR_ANY);
10070 if (warning.unused_value && !expression_has_effect(step)) {
10071 warningf(&step->base.source_position,
10072 "step of 'for'-statement has no effect");
10076 rem_anchor_token(')');
10077 statement->fors.body = parse_loop_body(statement);
10079 assert(current_scope == &statement->fors.scope);
10080 scope_pop(old_scope);
10081 environment_pop_to(top);
10088 rem_anchor_token(')');
10089 assert(current_scope == &statement->fors.scope);
10090 scope_pop(old_scope);
10091 environment_pop_to(top);
10093 return create_invalid_statement();
10097 * Parse a goto statement.
10099 static statement_t *parse_goto(void)
10101 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
10104 if (GNU_MODE && token.type == '*') {
10106 expression_t *expression = parse_expression();
10107 mark_vars_read(expression, NULL);
10109 /* Argh: although documentation says the expression must be of type void*,
10110 * gcc accepts anything that can be casted into void* without error */
10111 type_t *type = expression->base.type;
10113 if (type != type_error_type) {
10114 if (!is_type_pointer(type) && !is_type_integer(type)) {
10115 errorf(&expression->base.source_position,
10116 "cannot convert to a pointer type");
10117 } else if (warning.other && type != type_void_ptr) {
10118 warningf(&expression->base.source_position,
10119 "type of computed goto expression should be 'void*' not '%T'", type);
10121 expression = create_implicit_cast(expression, type_void_ptr);
10124 statement->gotos.expression = expression;
10126 if (token.type != T_IDENTIFIER) {
10128 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
10130 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
10131 eat_until_anchor();
10134 symbol_t *symbol = token.v.symbol;
10137 statement->gotos.label = get_label(symbol);
10140 /* remember the goto's in a list for later checking */
10141 *goto_anchor = &statement->gotos;
10142 goto_anchor = &statement->gotos.next;
10148 return create_invalid_statement();
10152 * Parse a continue statement.
10154 static statement_t *parse_continue(void)
10156 if (current_loop == NULL) {
10157 errorf(HERE, "continue statement not within loop");
10160 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
10170 * Parse a break statement.
10172 static statement_t *parse_break(void)
10174 if (current_switch == NULL && current_loop == NULL) {
10175 errorf(HERE, "break statement not within loop or switch");
10178 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10188 * Parse a __leave statement.
10190 static statement_t *parse_leave_statement(void)
10192 if (current_try == NULL) {
10193 errorf(HERE, "__leave statement not within __try");
10196 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10206 * Check if a given entity represents a local variable.
10208 static bool is_local_variable(const entity_t *entity)
10210 if (entity->kind != ENTITY_VARIABLE)
10213 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10214 case STORAGE_CLASS_AUTO:
10215 case STORAGE_CLASS_REGISTER: {
10216 const type_t *type = skip_typeref(entity->declaration.type);
10217 if (is_type_function(type)) {
10229 * Check if a given expression represents a local variable.
10231 static bool expression_is_local_variable(const expression_t *expression)
10233 if (expression->base.kind != EXPR_REFERENCE) {
10236 const entity_t *entity = expression->reference.entity;
10237 return is_local_variable(entity);
10241 * Check if a given expression represents a local variable and
10242 * return its declaration then, else return NULL.
10244 entity_t *expression_is_variable(const expression_t *expression)
10246 if (expression->base.kind != EXPR_REFERENCE) {
10249 entity_t *entity = expression->reference.entity;
10250 if (entity->kind != ENTITY_VARIABLE)
10257 * Parse a return statement.
10259 static statement_t *parse_return(void)
10263 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10265 expression_t *return_value = NULL;
10266 if (token.type != ';') {
10267 return_value = parse_expression();
10268 mark_vars_read(return_value, NULL);
10271 const type_t *const func_type = skip_typeref(current_function->base.type);
10272 assert(is_type_function(func_type));
10273 type_t *const return_type = skip_typeref(func_type->function.return_type);
10275 if (return_value != NULL) {
10276 type_t *return_value_type = skip_typeref(return_value->base.type);
10278 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID) &&
10279 !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10280 if (warning.other) {
10281 warningf(&statement->base.source_position,
10282 "'return' with a value, in function returning void");
10284 return_value = NULL;
10286 assign_error_t error = semantic_assign(return_type, return_value);
10287 report_assign_error(error, return_type, return_value, "'return'",
10288 &statement->base.source_position);
10289 return_value = create_implicit_cast(return_value, return_type);
10291 /* check for returning address of a local var */
10292 if (warning.other && return_value != NULL
10293 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10294 const expression_t *expression = return_value->unary.value;
10295 if (expression_is_local_variable(expression)) {
10296 warningf(&statement->base.source_position,
10297 "function returns address of local variable");
10300 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10301 warningf(&statement->base.source_position,
10302 "'return' without value, in function returning non-void");
10304 statement->returns.value = return_value;
10313 * Parse a declaration statement.
10315 static statement_t *parse_declaration_statement(void)
10317 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10319 entity_t *before = current_scope->last_entity;
10321 parse_external_declaration();
10323 parse_declaration(record_entity, DECL_FLAGS_NONE);
10326 if (before == NULL) {
10327 statement->declaration.declarations_begin = current_scope->entities;
10329 statement->declaration.declarations_begin = before->base.next;
10331 statement->declaration.declarations_end = current_scope->last_entity;
10337 * Parse an expression statement, ie. expr ';'.
10339 static statement_t *parse_expression_statement(void)
10341 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10343 expression_t *const expr = parse_expression();
10344 statement->expression.expression = expr;
10345 mark_vars_read(expr, VAR_ANY);
10354 * Parse a microsoft __try { } __finally { } or
10355 * __try{ } __except() { }
10357 static statement_t *parse_ms_try_statment(void)
10359 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10362 PUSH_PARENT(statement);
10364 ms_try_statement_t *rem = current_try;
10365 current_try = &statement->ms_try;
10366 statement->ms_try.try_statement = parse_compound_statement(false);
10371 if (token.type == T___except) {
10374 add_anchor_token(')');
10375 expression_t *const expr = parse_expression();
10376 mark_vars_read(expr, NULL);
10377 type_t * type = skip_typeref(expr->base.type);
10378 if (is_type_integer(type)) {
10379 type = promote_integer(type);
10380 } else if (is_type_valid(type)) {
10381 errorf(&expr->base.source_position,
10382 "__expect expression is not an integer, but '%T'", type);
10383 type = type_error_type;
10385 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10386 rem_anchor_token(')');
10388 statement->ms_try.final_statement = parse_compound_statement(false);
10389 } else if (token.type == T__finally) {
10391 statement->ms_try.final_statement = parse_compound_statement(false);
10393 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10394 return create_invalid_statement();
10398 return create_invalid_statement();
10401 static statement_t *parse_empty_statement(void)
10403 if (warning.empty_statement) {
10404 warningf(HERE, "statement is empty");
10406 statement_t *const statement = create_empty_statement();
10411 static statement_t *parse_local_label_declaration(void)
10413 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10417 entity_t *begin = NULL, *end = NULL;
10420 if (token.type != T_IDENTIFIER) {
10421 parse_error_expected("while parsing local label declaration",
10422 T_IDENTIFIER, NULL);
10425 symbol_t *symbol = token.v.symbol;
10426 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10427 if (entity != NULL && entity->base.parent_scope == current_scope) {
10428 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10429 symbol, &entity->base.source_position);
10431 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10433 entity->base.parent_scope = current_scope;
10434 entity->base.namespc = NAMESPACE_LABEL;
10435 entity->base.source_position = token.source_position;
10436 entity->base.symbol = symbol;
10439 end->base.next = entity;
10444 environment_push(entity);
10448 if (token.type != ',')
10454 statement->declaration.declarations_begin = begin;
10455 statement->declaration.declarations_end = end;
10459 static void parse_namespace_definition(void)
10463 entity_t *entity = NULL;
10464 symbol_t *symbol = NULL;
10466 if (token.type == T_IDENTIFIER) {
10467 symbol = token.v.symbol;
10470 entity = get_entity(symbol, NAMESPACE_NORMAL);
10471 if (entity != NULL && entity->kind != ENTITY_NAMESPACE
10472 && entity->base.parent_scope == current_scope) {
10473 error_redefined_as_different_kind(&token.source_position,
10474 entity, ENTITY_NAMESPACE);
10479 if (entity == NULL) {
10480 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10481 entity->base.symbol = symbol;
10482 entity->base.source_position = token.source_position;
10483 entity->base.namespc = NAMESPACE_NORMAL;
10484 entity->base.parent_scope = current_scope;
10487 if (token.type == '=') {
10488 /* TODO: parse namespace alias */
10489 panic("namespace alias definition not supported yet");
10492 environment_push(entity);
10493 append_entity(current_scope, entity);
10495 size_t const top = environment_top();
10496 scope_t *old_scope = scope_push(&entity->namespacee.members);
10503 assert(current_scope == &entity->namespacee.members);
10504 scope_pop(old_scope);
10505 environment_pop_to(top);
10509 * Parse a statement.
10510 * There's also parse_statement() which additionally checks for
10511 * "statement has no effect" warnings
10513 static statement_t *intern_parse_statement(void)
10515 statement_t *statement = NULL;
10517 /* declaration or statement */
10518 add_anchor_token(';');
10519 switch (token.type) {
10520 case T_IDENTIFIER: {
10521 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10522 if (la1_type == ':') {
10523 statement = parse_label_statement();
10524 } else if (is_typedef_symbol(token.v.symbol)) {
10525 statement = parse_declaration_statement();
10527 /* it's an identifier, the grammar says this must be an
10528 * expression statement. However it is common that users mistype
10529 * declaration types, so we guess a bit here to improve robustness
10530 * for incorrect programs */
10531 switch (la1_type) {
10534 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10535 goto expression_statment;
10540 statement = parse_declaration_statement();
10544 expression_statment:
10545 statement = parse_expression_statement();
10552 case T___extension__:
10553 /* This can be a prefix to a declaration or an expression statement.
10554 * We simply eat it now and parse the rest with tail recursion. */
10557 } while (token.type == T___extension__);
10558 bool old_gcc_extension = in_gcc_extension;
10559 in_gcc_extension = true;
10560 statement = intern_parse_statement();
10561 in_gcc_extension = old_gcc_extension;
10565 statement = parse_declaration_statement();
10569 statement = parse_local_label_declaration();
10572 case ';': statement = parse_empty_statement(); break;
10573 case '{': statement = parse_compound_statement(false); break;
10574 case T___leave: statement = parse_leave_statement(); break;
10575 case T___try: statement = parse_ms_try_statment(); break;
10576 case T_asm: statement = parse_asm_statement(); break;
10577 case T_break: statement = parse_break(); break;
10578 case T_case: statement = parse_case_statement(); break;
10579 case T_continue: statement = parse_continue(); break;
10580 case T_default: statement = parse_default_statement(); break;
10581 case T_do: statement = parse_do(); break;
10582 case T_for: statement = parse_for(); break;
10583 case T_goto: statement = parse_goto(); break;
10584 case T_if: statement = parse_if(); break;
10585 case T_return: statement = parse_return(); break;
10586 case T_switch: statement = parse_switch(); break;
10587 case T_while: statement = parse_while(); break;
10590 statement = parse_expression_statement();
10594 errorf(HERE, "unexpected token '%K' while parsing statement", &token);
10595 statement = create_invalid_statement();
10600 rem_anchor_token(';');
10602 assert(statement != NULL
10603 && statement->base.source_position.input_name != NULL);
10609 * parse a statement and emits "statement has no effect" warning if needed
10610 * (This is really a wrapper around intern_parse_statement with check for 1
10611 * single warning. It is needed, because for statement expressions we have
10612 * to avoid the warning on the last statement)
10614 static statement_t *parse_statement(void)
10616 statement_t *statement = intern_parse_statement();
10618 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10619 expression_t *expression = statement->expression.expression;
10620 if (!expression_has_effect(expression)) {
10621 warningf(&expression->base.source_position,
10622 "statement has no effect");
10630 * Parse a compound statement.
10632 static statement_t *parse_compound_statement(bool inside_expression_statement)
10634 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10636 PUSH_PARENT(statement);
10639 add_anchor_token('}');
10641 size_t const top = environment_top();
10642 scope_t *old_scope = scope_push(&statement->compound.scope);
10644 statement_t **anchor = &statement->compound.statements;
10645 bool only_decls_so_far = true;
10646 while (token.type != '}') {
10647 if (token.type == T_EOF) {
10648 errorf(&statement->base.source_position,
10649 "EOF while parsing compound statement");
10652 statement_t *sub_statement = intern_parse_statement();
10653 if (is_invalid_statement(sub_statement)) {
10654 /* an error occurred. if we are at an anchor, return */
10660 if (warning.declaration_after_statement) {
10661 if (sub_statement->kind != STATEMENT_DECLARATION) {
10662 only_decls_so_far = false;
10663 } else if (!only_decls_so_far) {
10664 warningf(&sub_statement->base.source_position,
10665 "ISO C90 forbids mixed declarations and code");
10669 *anchor = sub_statement;
10671 while (sub_statement->base.next != NULL)
10672 sub_statement = sub_statement->base.next;
10674 anchor = &sub_statement->base.next;
10678 /* look over all statements again to produce no effect warnings */
10679 if (warning.unused_value) {
10680 statement_t *sub_statement = statement->compound.statements;
10681 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10682 if (sub_statement->kind != STATEMENT_EXPRESSION)
10684 /* don't emit a warning for the last expression in an expression
10685 * statement as it has always an effect */
10686 if (inside_expression_statement && sub_statement->base.next == NULL)
10689 expression_t *expression = sub_statement->expression.expression;
10690 if (!expression_has_effect(expression)) {
10691 warningf(&expression->base.source_position,
10692 "statement has no effect");
10698 rem_anchor_token('}');
10699 assert(current_scope == &statement->compound.scope);
10700 scope_pop(old_scope);
10701 environment_pop_to(top);
10708 * Check for unused global static functions and variables
10710 static void check_unused_globals(void)
10712 if (!warning.unused_function && !warning.unused_variable)
10715 for (const entity_t *entity = file_scope->entities; entity != NULL;
10716 entity = entity->base.next) {
10717 if (!is_declaration(entity))
10720 const declaration_t *declaration = &entity->declaration;
10721 if (declaration->used ||
10722 declaration->modifiers & DM_UNUSED ||
10723 declaration->modifiers & DM_USED ||
10724 declaration->storage_class != STORAGE_CLASS_STATIC)
10727 type_t *const type = declaration->type;
10729 if (entity->kind == ENTITY_FUNCTION) {
10730 /* inhibit warning for static inline functions */
10731 if (entity->function.is_inline)
10734 s = entity->function.statement != NULL ? "defined" : "declared";
10739 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10740 type, declaration->base.symbol, s);
10744 static void parse_global_asm(void)
10746 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10751 statement->asms.asm_text = parse_string_literals();
10752 statement->base.next = unit->global_asm;
10753 unit->global_asm = statement;
10761 static void parse_linkage_specification(void)
10764 assert(token.type == T_STRING_LITERAL);
10766 const char *linkage = parse_string_literals().begin;
10768 linkage_kind_t old_linkage = current_linkage;
10769 linkage_kind_t new_linkage;
10770 if (strcmp(linkage, "C") == 0) {
10771 new_linkage = LINKAGE_C;
10772 } else if (strcmp(linkage, "C++") == 0) {
10773 new_linkage = LINKAGE_CXX;
10775 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10776 new_linkage = LINKAGE_INVALID;
10778 current_linkage = new_linkage;
10780 if (token.type == '{') {
10789 assert(current_linkage == new_linkage);
10790 current_linkage = old_linkage;
10793 static void parse_external(void)
10795 switch (token.type) {
10796 DECLARATION_START_NO_EXTERN
10798 case T___extension__:
10799 /* tokens below are for implicit int */
10800 case '&': /* & x; -> int& x; (and error later, because C++ has no
10802 case '*': /* * x; -> int* x; */
10803 case '(': /* (x); -> int (x); */
10804 parse_external_declaration();
10808 if (look_ahead(1)->type == T_STRING_LITERAL) {
10809 parse_linkage_specification();
10811 parse_external_declaration();
10816 parse_global_asm();
10820 parse_namespace_definition();
10824 if (!strict_mode) {
10826 warningf(HERE, "stray ';' outside of function");
10833 errorf(HERE, "stray '%K' outside of function", &token);
10834 if (token.type == '(' || token.type == '{' || token.type == '[')
10835 eat_until_matching_token(token.type);
10841 static void parse_externals(void)
10843 add_anchor_token('}');
10844 add_anchor_token(T_EOF);
10847 unsigned char token_anchor_copy[T_LAST_TOKEN];
10848 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10851 while (token.type != T_EOF && token.type != '}') {
10853 bool anchor_leak = false;
10854 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10855 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10857 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10858 anchor_leak = true;
10861 if (in_gcc_extension) {
10862 errorf(HERE, "Leaked __extension__");
10863 anchor_leak = true;
10873 rem_anchor_token(T_EOF);
10874 rem_anchor_token('}');
10878 * Parse a translation unit.
10880 static void parse_translation_unit(void)
10882 add_anchor_token(T_EOF);
10887 if (token.type == T_EOF)
10890 errorf(HERE, "stray '%K' outside of function", &token);
10891 if (token.type == '(' || token.type == '{' || token.type == '[')
10892 eat_until_matching_token(token.type);
10900 * @return the translation unit or NULL if errors occurred.
10902 void start_parsing(void)
10904 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10905 label_stack = NEW_ARR_F(stack_entry_t, 0);
10906 diagnostic_count = 0;
10910 type_set_output(stderr);
10911 ast_set_output(stderr);
10913 assert(unit == NULL);
10914 unit = allocate_ast_zero(sizeof(unit[0]));
10916 assert(file_scope == NULL);
10917 file_scope = &unit->scope;
10919 assert(current_scope == NULL);
10920 scope_push(&unit->scope);
10923 translation_unit_t *finish_parsing(void)
10925 assert(current_scope == &unit->scope);
10928 assert(file_scope == &unit->scope);
10929 check_unused_globals();
10932 DEL_ARR_F(environment_stack);
10933 DEL_ARR_F(label_stack);
10935 translation_unit_t *result = unit;
10942 lookahead_bufpos = 0;
10943 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10946 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10947 parse_translation_unit();
10951 * Initialize the parser.
10953 void init_parser(void)
10955 sym_anonymous = symbol_table_insert("<anonymous>");
10957 if (c_mode & _MS) {
10958 /* add predefined symbols for extended-decl-modifier */
10959 sym_align = symbol_table_insert("align");
10960 sym_allocate = symbol_table_insert("allocate");
10961 sym_dllimport = symbol_table_insert("dllimport");
10962 sym_dllexport = symbol_table_insert("dllexport");
10963 sym_naked = symbol_table_insert("naked");
10964 sym_noinline = symbol_table_insert("noinline");
10965 sym_noreturn = symbol_table_insert("noreturn");
10966 sym_nothrow = symbol_table_insert("nothrow");
10967 sym_novtable = symbol_table_insert("novtable");
10968 sym_property = symbol_table_insert("property");
10969 sym_get = symbol_table_insert("get");
10970 sym_put = symbol_table_insert("put");
10971 sym_selectany = symbol_table_insert("selectany");
10972 sym_thread = symbol_table_insert("thread");
10973 sym_uuid = symbol_table_insert("uuid");
10974 sym_deprecated = symbol_table_insert("deprecated");
10975 sym_restrict = symbol_table_insert("restrict");
10976 sym_noalias = symbol_table_insert("noalias");
10978 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10980 init_expression_parsers();
10981 obstack_init(&temp_obst);
10983 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10984 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10988 * Terminate the parser.
10990 void exit_parser(void)
10992 obstack_free(&temp_obst, NULL);