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_PARAMETER] = sizeof(parameter_t),
335 [ENTITY_COMPOUND_MEMBER] = sizeof(compound_member_t),
336 [ENTITY_FUNCTION] = sizeof(function_t),
337 [ENTITY_TYPEDEF] = sizeof(typedef_t),
338 [ENTITY_STRUCT] = sizeof(compound_t),
339 [ENTITY_UNION] = sizeof(compound_t),
340 [ENTITY_ENUM] = sizeof(enum_t),
341 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
342 [ENTITY_LABEL] = sizeof(label_t),
343 [ENTITY_LOCAL_LABEL] = sizeof(label_t),
344 [ENTITY_NAMESPACE] = sizeof(namespace_t)
346 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
347 assert(sizes[kind] != 0);
351 static entity_t *allocate_entity_zero(entity_kind_t kind)
353 size_t size = get_entity_struct_size(kind);
354 entity_t *entity = allocate_ast_zero(size);
360 * Returns the size of a statement node.
362 * @param kind the statement kind
364 static size_t get_statement_struct_size(statement_kind_t kind)
366 static const size_t sizes[] = {
367 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
368 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
369 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
370 [STATEMENT_RETURN] = sizeof(return_statement_t),
371 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
372 [STATEMENT_LOCAL_LABEL] = sizeof(local_label_statement_t),
373 [STATEMENT_IF] = sizeof(if_statement_t),
374 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
375 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
376 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
377 [STATEMENT_BREAK] = sizeof(statement_base_t),
378 [STATEMENT_GOTO] = sizeof(goto_statement_t),
379 [STATEMENT_LABEL] = sizeof(label_statement_t),
380 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
381 [STATEMENT_WHILE] = sizeof(while_statement_t),
382 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
383 [STATEMENT_FOR] = sizeof(for_statement_t),
384 [STATEMENT_ASM] = sizeof(asm_statement_t),
385 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
386 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
388 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
389 assert(sizes[kind] != 0);
394 * Returns the size of an expression node.
396 * @param kind the expression kind
398 static size_t get_expression_struct_size(expression_kind_t kind)
400 static const size_t sizes[] = {
401 [EXPR_INVALID] = sizeof(expression_base_t),
402 [EXPR_REFERENCE] = sizeof(reference_expression_t),
403 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
404 [EXPR_CONST] = sizeof(const_expression_t),
405 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
406 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
407 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
408 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
409 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
410 [EXPR_CALL] = sizeof(call_expression_t),
411 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
412 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
413 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
414 [EXPR_SELECT] = sizeof(select_expression_t),
415 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
416 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
417 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
418 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
419 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
420 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
421 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
422 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
423 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
424 [EXPR_VA_START] = sizeof(va_start_expression_t),
425 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
426 [EXPR_STATEMENT] = sizeof(statement_expression_t),
427 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
429 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
430 return sizes[EXPR_UNARY_FIRST];
432 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
433 return sizes[EXPR_BINARY_FIRST];
435 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
436 assert(sizes[kind] != 0);
441 * Allocate a statement node of given kind and initialize all
444 static statement_t *allocate_statement_zero(statement_kind_t kind)
446 size_t size = get_statement_struct_size(kind);
447 statement_t *res = allocate_ast_zero(size);
449 res->base.kind = kind;
450 res->base.parent = current_parent;
451 res->base.source_position = token.source_position;
456 * Allocate an expression node of given kind and initialize all
459 static expression_t *allocate_expression_zero(expression_kind_t kind)
461 size_t size = get_expression_struct_size(kind);
462 expression_t *res = allocate_ast_zero(size);
464 res->base.kind = kind;
465 res->base.type = type_error_type;
466 res->base.source_position = token.source_position;
471 * Creates a new invalid expression.
473 static expression_t *create_invalid_expression(void)
475 return allocate_expression_zero(EXPR_INVALID);
479 * Creates a new invalid statement.
481 static statement_t *create_invalid_statement(void)
483 return allocate_statement_zero(STATEMENT_INVALID);
487 * Allocate a new empty statement.
489 static statement_t *create_empty_statement(void)
491 return allocate_statement_zero(STATEMENT_EMPTY);
495 * Returns the size of a type node.
497 * @param kind the type kind
499 static size_t get_type_struct_size(type_kind_t kind)
501 static const size_t sizes[] = {
502 [TYPE_ATOMIC] = sizeof(atomic_type_t),
503 [TYPE_COMPLEX] = sizeof(complex_type_t),
504 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
505 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
506 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
507 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
508 [TYPE_ENUM] = sizeof(enum_type_t),
509 [TYPE_FUNCTION] = sizeof(function_type_t),
510 [TYPE_POINTER] = sizeof(pointer_type_t),
511 [TYPE_ARRAY] = sizeof(array_type_t),
512 [TYPE_BUILTIN] = sizeof(builtin_type_t),
513 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
514 [TYPE_TYPEOF] = sizeof(typeof_type_t),
516 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
517 assert(kind <= TYPE_TYPEOF);
518 assert(sizes[kind] != 0);
523 * Allocate a type node of given kind and initialize all
526 * @param kind type kind to allocate
528 static type_t *allocate_type_zero(type_kind_t kind)
530 size_t size = get_type_struct_size(kind);
531 type_t *res = obstack_alloc(type_obst, size);
532 memset(res, 0, size);
533 res->base.kind = kind;
539 * Returns the size of an initializer node.
541 * @param kind the initializer kind
543 static size_t get_initializer_size(initializer_kind_t kind)
545 static const size_t sizes[] = {
546 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
547 [INITIALIZER_STRING] = sizeof(initializer_string_t),
548 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
549 [INITIALIZER_LIST] = sizeof(initializer_list_t),
550 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
552 assert(kind < sizeof(sizes) / sizeof(*sizes));
553 assert(sizes[kind] != 0);
558 * Allocate an initializer node of given kind and initialize all
561 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
563 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
570 * Free a type from the type obstack.
572 static void free_type(void *type)
574 obstack_free(type_obst, type);
578 * Returns the index of the top element of the environment stack.
580 static size_t environment_top(void)
582 return ARR_LEN(environment_stack);
586 * Returns the index of the top element of the global label stack.
588 static size_t label_top(void)
590 return ARR_LEN(label_stack);
594 * Return the next token.
596 static inline void next_token(void)
598 token = lookahead_buffer[lookahead_bufpos];
599 lookahead_buffer[lookahead_bufpos] = lexer_token;
602 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
605 print_token(stderr, &token);
606 fprintf(stderr, "\n");
611 * Return the next token with a given lookahead.
613 static inline const token_t *look_ahead(int num)
615 assert(num > 0 && num <= MAX_LOOKAHEAD);
616 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
617 return &lookahead_buffer[pos];
621 * Adds a token to the token anchor set (a multi-set).
623 static void add_anchor_token(int token_type)
625 assert(0 <= token_type && token_type < T_LAST_TOKEN);
626 ++token_anchor_set[token_type];
629 static int save_and_reset_anchor_state(int token_type)
631 assert(0 <= token_type && token_type < T_LAST_TOKEN);
632 int count = token_anchor_set[token_type];
633 token_anchor_set[token_type] = 0;
637 static void restore_anchor_state(int token_type, int count)
639 assert(0 <= token_type && token_type < T_LAST_TOKEN);
640 token_anchor_set[token_type] = count;
644 * Remove a token from the token anchor set (a multi-set).
646 static void rem_anchor_token(int token_type)
648 assert(0 <= token_type && token_type < T_LAST_TOKEN);
649 assert(token_anchor_set[token_type] != 0);
650 --token_anchor_set[token_type];
653 static bool at_anchor(void)
657 return token_anchor_set[token.type];
661 * Eat tokens until a matching token is found.
663 static void eat_until_matching_token(int type)
667 case '(': end_token = ')'; break;
668 case '{': end_token = '}'; break;
669 case '[': end_token = ']'; break;
670 default: end_token = type; break;
673 unsigned parenthesis_count = 0;
674 unsigned brace_count = 0;
675 unsigned bracket_count = 0;
676 while (token.type != end_token ||
677 parenthesis_count != 0 ||
679 bracket_count != 0) {
680 switch (token.type) {
682 case '(': ++parenthesis_count; break;
683 case '{': ++brace_count; break;
684 case '[': ++bracket_count; break;
687 if (parenthesis_count > 0)
697 if (bracket_count > 0)
700 if (token.type == end_token &&
701 parenthesis_count == 0 &&
715 * Eat input tokens until an anchor is found.
717 static void eat_until_anchor(void)
719 while (token_anchor_set[token.type] == 0) {
720 if (token.type == '(' || token.type == '{' || token.type == '[')
721 eat_until_matching_token(token.type);
726 static void eat_block(void)
728 eat_until_matching_token('{');
729 if (token.type == '}')
733 #define eat(token_type) do { assert(token.type == (token_type)); next_token(); } while (0)
736 * Report a parse error because an expected token was not found.
739 #if defined __GNUC__ && __GNUC__ >= 4
740 __attribute__((sentinel))
742 void parse_error_expected(const char *message, ...)
744 if (message != NULL) {
745 errorf(HERE, "%s", message);
748 va_start(ap, message);
749 errorf(HERE, "got '%K', expected %#k", &token, &ap, ", ");
754 * Report an incompatible type.
756 static void type_error_incompatible(const char *msg,
757 const source_position_t *source_position, type_t *type1, type_t *type2)
759 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
764 * Expect the the current token is the expected token.
765 * If not, generate an error, eat the current statement,
766 * and goto the end_error label.
768 #define expect(expected) \
770 if (UNLIKELY(token.type != (expected))) { \
771 parse_error_expected(NULL, (expected), NULL); \
772 add_anchor_token(expected); \
773 eat_until_anchor(); \
774 if (token.type == expected) \
776 rem_anchor_token(expected); \
782 static scope_t *scope_push(scope_t *new_scope)
784 if (current_scope != NULL) {
785 new_scope->depth = current_scope->depth + 1;
788 scope_t *old_scope = current_scope;
789 current_scope = new_scope;
793 static void scope_pop(scope_t *old_scope)
795 current_scope = old_scope;
799 * Search an entity by its symbol in a given namespace.
801 static entity_t *get_entity(const symbol_t *const symbol,
802 namespace_tag_t namespc)
804 entity_t *entity = symbol->entity;
805 for (; entity != NULL; entity = entity->base.symbol_next) {
806 if (entity->base.namespc == namespc)
814 * pushs an entity on the environment stack and links the corresponding symbol
817 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
819 symbol_t *symbol = entity->base.symbol;
820 entity_namespace_t namespc = entity->base.namespc;
821 assert(namespc != NAMESPACE_INVALID);
823 /* replace/add entity into entity list of the symbol */
826 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
831 /* replace an entry? */
832 if (iter->base.namespc == namespc) {
833 entity->base.symbol_next = iter->base.symbol_next;
839 /* remember old declaration */
841 entry.symbol = symbol;
842 entry.old_entity = iter;
843 entry.namespc = namespc;
844 ARR_APP1(stack_entry_t, *stack_ptr, entry);
848 * Push an entity on the environment stack.
850 static void environment_push(entity_t *entity)
852 assert(entity->base.source_position.input_name != NULL);
853 assert(entity->base.parent_scope != NULL);
854 stack_push(&environment_stack, entity);
858 * Push a declaration on the global label stack.
860 * @param declaration the declaration
862 static void label_push(entity_t *label)
864 /* we abuse the parameters scope as parent for the labels */
865 label->base.parent_scope = ¤t_function->parameters;
866 stack_push(&label_stack, label);
870 * pops symbols from the environment stack until @p new_top is the top element
872 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
874 stack_entry_t *stack = *stack_ptr;
875 size_t top = ARR_LEN(stack);
878 assert(new_top <= top);
882 for (i = top; i > new_top; --i) {
883 stack_entry_t *entry = &stack[i - 1];
885 entity_t *old_entity = entry->old_entity;
886 symbol_t *symbol = entry->symbol;
887 entity_namespace_t namespc = entry->namespc;
889 /* replace with old_entity/remove */
892 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
894 assert(iter != NULL);
895 /* replace an entry? */
896 if (iter->base.namespc == namespc)
900 /* restore definition from outer scopes (if there was one) */
901 if (old_entity != NULL) {
902 old_entity->base.symbol_next = iter->base.symbol_next;
903 *anchor = old_entity;
905 /* remove entry from list */
906 *anchor = iter->base.symbol_next;
910 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
914 * Pop all entries from the environment stack until the new_top
917 * @param new_top the new stack top
919 static void environment_pop_to(size_t new_top)
921 stack_pop_to(&environment_stack, new_top);
925 * Pop all entries from the global label stack until the new_top
928 * @param new_top the new stack top
930 static void label_pop_to(size_t new_top)
932 stack_pop_to(&label_stack, new_top);
935 static int get_akind_rank(atomic_type_kind_t akind)
940 static int get_rank(const type_t *type)
942 assert(!is_typeref(type));
943 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
944 * and esp. footnote 108). However we can't fold constants (yet), so we
945 * can't decide whether unsigned int is possible, while int always works.
946 * (unsigned int would be preferable when possible... for stuff like
947 * struct { enum { ... } bla : 4; } ) */
948 if (type->kind == TYPE_ENUM)
949 return get_akind_rank(ATOMIC_TYPE_INT);
951 assert(type->kind == TYPE_ATOMIC);
952 return get_akind_rank(type->atomic.akind);
955 static type_t *promote_integer(type_t *type)
957 if (type->kind == TYPE_BITFIELD)
958 type = type->bitfield.base_type;
960 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
967 * Create a cast expression.
969 * @param expression the expression to cast
970 * @param dest_type the destination type
972 static expression_t *create_cast_expression(expression_t *expression,
975 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
977 cast->unary.value = expression;
978 cast->base.type = dest_type;
984 * Check if a given expression represents the 0 pointer constant.
986 static bool is_null_pointer_constant(const expression_t *expression)
988 /* skip void* cast */
989 if (expression->kind == EXPR_UNARY_CAST
990 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
991 expression = expression->unary.value;
994 /* TODO: not correct yet, should be any constant integer expression
995 * which evaluates to 0 */
996 if (expression->kind != EXPR_CONST)
999 type_t *const type = skip_typeref(expression->base.type);
1000 if (!is_type_integer(type))
1003 return expression->conste.v.int_value == 0;
1007 * Create an implicit cast expression.
1009 * @param expression the expression to cast
1010 * @param dest_type the destination type
1012 static expression_t *create_implicit_cast(expression_t *expression,
1015 type_t *const source_type = expression->base.type;
1017 if (source_type == dest_type)
1020 return create_cast_expression(expression, dest_type);
1023 typedef enum assign_error_t {
1025 ASSIGN_ERROR_INCOMPATIBLE,
1026 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1027 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1028 ASSIGN_WARNING_POINTER_FROM_INT,
1029 ASSIGN_WARNING_INT_FROM_POINTER
1032 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1033 const expression_t *const right,
1034 const char *context,
1035 const source_position_t *source_position)
1037 type_t *const orig_type_right = right->base.type;
1038 type_t *const type_left = skip_typeref(orig_type_left);
1039 type_t *const type_right = skip_typeref(orig_type_right);
1042 case ASSIGN_SUCCESS:
1044 case ASSIGN_ERROR_INCOMPATIBLE:
1045 errorf(source_position,
1046 "destination type '%T' in %s is incompatible with type '%T'",
1047 orig_type_left, context, orig_type_right);
1050 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1051 if (warning.other) {
1052 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1053 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1055 /* the left type has all qualifiers from the right type */
1056 unsigned missing_qualifiers
1057 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1058 warningf(source_position,
1059 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1060 orig_type_left, context, orig_type_right, missing_qualifiers);
1065 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1066 if (warning.other) {
1067 warningf(source_position,
1068 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1069 orig_type_left, context, right, orig_type_right);
1073 case ASSIGN_WARNING_POINTER_FROM_INT:
1074 if (warning.other) {
1075 warningf(source_position,
1076 "%s makes pointer '%T' from integer '%T' without a cast",
1077 context, orig_type_left, orig_type_right);
1081 case ASSIGN_WARNING_INT_FROM_POINTER:
1082 if (warning.other) {
1083 warningf(source_position,
1084 "%s makes integer '%T' from pointer '%T' without a cast",
1085 context, orig_type_left, orig_type_right);
1090 panic("invalid error value");
1094 /** Implements the rules from § 6.5.16.1 */
1095 static assign_error_t semantic_assign(type_t *orig_type_left,
1096 const expression_t *const right)
1098 type_t *const orig_type_right = right->base.type;
1099 type_t *const type_left = skip_typeref(orig_type_left);
1100 type_t *const type_right = skip_typeref(orig_type_right);
1102 if (is_type_pointer(type_left)) {
1103 if (is_null_pointer_constant(right)) {
1104 return ASSIGN_SUCCESS;
1105 } else if (is_type_pointer(type_right)) {
1106 type_t *points_to_left
1107 = skip_typeref(type_left->pointer.points_to);
1108 type_t *points_to_right
1109 = skip_typeref(type_right->pointer.points_to);
1110 assign_error_t res = ASSIGN_SUCCESS;
1112 /* the left type has all qualifiers from the right type */
1113 unsigned missing_qualifiers
1114 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1115 if (missing_qualifiers != 0) {
1116 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1119 points_to_left = get_unqualified_type(points_to_left);
1120 points_to_right = get_unqualified_type(points_to_right);
1122 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1125 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1126 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1127 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1130 if (!types_compatible(points_to_left, points_to_right)) {
1131 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1135 } else if (is_type_integer(type_right)) {
1136 return ASSIGN_WARNING_POINTER_FROM_INT;
1138 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1139 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1140 && is_type_pointer(type_right))) {
1141 return ASSIGN_SUCCESS;
1142 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1143 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1144 type_t *const unqual_type_left = get_unqualified_type(type_left);
1145 type_t *const unqual_type_right = get_unqualified_type(type_right);
1146 if (types_compatible(unqual_type_left, unqual_type_right)) {
1147 return ASSIGN_SUCCESS;
1149 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1150 return ASSIGN_WARNING_INT_FROM_POINTER;
1153 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1154 return ASSIGN_SUCCESS;
1156 return ASSIGN_ERROR_INCOMPATIBLE;
1159 static expression_t *parse_constant_expression(void)
1161 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1163 if (!is_constant_expression(result)) {
1164 errorf(&result->base.source_position,
1165 "expression '%E' is not constant", result);
1171 static expression_t *parse_assignment_expression(void)
1173 return parse_sub_expression(PREC_ASSIGNMENT);
1176 static string_t parse_string_literals(void)
1178 assert(token.type == T_STRING_LITERAL);
1179 string_t result = token.v.string;
1183 while (token.type == T_STRING_LITERAL) {
1184 result = concat_strings(&result, &token.v.string);
1191 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1192 [GNU_AK_CONST] = "const",
1193 [GNU_AK_VOLATILE] = "volatile",
1194 [GNU_AK_CDECL] = "cdecl",
1195 [GNU_AK_STDCALL] = "stdcall",
1196 [GNU_AK_FASTCALL] = "fastcall",
1197 [GNU_AK_DEPRECATED] = "deprecated",
1198 [GNU_AK_NOINLINE] = "noinline",
1199 [GNU_AK_NORETURN] = "noreturn",
1200 [GNU_AK_NAKED] = "naked",
1201 [GNU_AK_PURE] = "pure",
1202 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1203 [GNU_AK_MALLOC] = "malloc",
1204 [GNU_AK_WEAK] = "weak",
1205 [GNU_AK_CONSTRUCTOR] = "constructor",
1206 [GNU_AK_DESTRUCTOR] = "destructor",
1207 [GNU_AK_NOTHROW] = "nothrow",
1208 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1209 [GNU_AK_COMMON] = "common",
1210 [GNU_AK_NOCOMMON] = "nocommon",
1211 [GNU_AK_PACKED] = "packed",
1212 [GNU_AK_SHARED] = "shared",
1213 [GNU_AK_NOTSHARED] = "notshared",
1214 [GNU_AK_USED] = "used",
1215 [GNU_AK_UNUSED] = "unused",
1216 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1217 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1218 [GNU_AK_LONGCALL] = "longcall",
1219 [GNU_AK_SHORTCALL] = "shortcall",
1220 [GNU_AK_LONG_CALL] = "long_call",
1221 [GNU_AK_SHORT_CALL] = "short_call",
1222 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1223 [GNU_AK_INTERRUPT] = "interrupt",
1224 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1225 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1226 [GNU_AK_NESTING] = "nesting",
1227 [GNU_AK_NEAR] = "near",
1228 [GNU_AK_FAR] = "far",
1229 [GNU_AK_SIGNAL] = "signal",
1230 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1231 [GNU_AK_TINY_DATA] = "tiny_data",
1232 [GNU_AK_SAVEALL] = "saveall",
1233 [GNU_AK_FLATTEN] = "flatten",
1234 [GNU_AK_SSEREGPARM] = "sseregparm",
1235 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1236 [GNU_AK_RETURN_TWICE] = "return_twice",
1237 [GNU_AK_MAY_ALIAS] = "may_alias",
1238 [GNU_AK_MS_STRUCT] = "ms_struct",
1239 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1240 [GNU_AK_DLLIMPORT] = "dllimport",
1241 [GNU_AK_DLLEXPORT] = "dllexport",
1242 [GNU_AK_ALIGNED] = "aligned",
1243 [GNU_AK_ALIAS] = "alias",
1244 [GNU_AK_SECTION] = "section",
1245 [GNU_AK_FORMAT] = "format",
1246 [GNU_AK_FORMAT_ARG] = "format_arg",
1247 [GNU_AK_WEAKREF] = "weakref",
1248 [GNU_AK_NONNULL] = "nonnull",
1249 [GNU_AK_TLS_MODEL] = "tls_model",
1250 [GNU_AK_VISIBILITY] = "visibility",
1251 [GNU_AK_REGPARM] = "regparm",
1252 [GNU_AK_MODE] = "mode",
1253 [GNU_AK_MODEL] = "model",
1254 [GNU_AK_TRAP_EXIT] = "trap_exit",
1255 [GNU_AK_SP_SWITCH] = "sp_switch",
1256 [GNU_AK_SENTINEL] = "sentinel"
1260 * compare two string, ignoring double underscores on the second.
1262 static int strcmp_underscore(const char *s1, const char *s2)
1264 if (s2[0] == '_' && s2[1] == '_') {
1265 size_t len2 = strlen(s2);
1266 size_t len1 = strlen(s1);
1267 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1268 return strncmp(s1, s2+2, len2-4);
1272 return strcmp(s1, s2);
1276 * Allocate a new gnu temporal attribute.
1278 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1280 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1281 attribute->kind = kind;
1282 attribute->next = NULL;
1283 attribute->invalid = false;
1284 attribute->have_arguments = false;
1290 * parse one constant expression argument.
1292 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1294 expression_t *expression;
1295 add_anchor_token(')');
1296 expression = parse_constant_expression();
1297 rem_anchor_token(')');
1299 attribute->u.argument = fold_constant(expression);
1302 attribute->invalid = true;
1306 * parse a list of constant expressions arguments.
1308 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1310 argument_list_t **list = &attribute->u.arguments;
1311 argument_list_t *entry;
1312 expression_t *expression;
1313 add_anchor_token(')');
1314 add_anchor_token(',');
1316 expression = parse_constant_expression();
1317 entry = obstack_alloc(&temp_obst, sizeof(entry));
1318 entry->argument = fold_constant(expression);
1321 list = &entry->next;
1322 if (token.type != ',')
1326 rem_anchor_token(',');
1327 rem_anchor_token(')');
1331 attribute->invalid = true;
1335 * parse one string literal argument.
1337 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1340 add_anchor_token('(');
1341 if (token.type != T_STRING_LITERAL) {
1342 parse_error_expected("while parsing attribute directive",
1343 T_STRING_LITERAL, NULL);
1346 *string = parse_string_literals();
1347 rem_anchor_token('(');
1351 attribute->invalid = true;
1355 * parse one tls model.
1357 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1359 static const char *const tls_models[] = {
1365 string_t string = { NULL, 0 };
1366 parse_gnu_attribute_string_arg(attribute, &string);
1367 if (string.begin != NULL) {
1368 for (size_t i = 0; i < 4; ++i) {
1369 if (strcmp(tls_models[i], string.begin) == 0) {
1370 attribute->u.value = i;
1374 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1376 attribute->invalid = true;
1380 * parse one tls model.
1382 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1384 static const char *const visibilities[] = {
1390 string_t string = { NULL, 0 };
1391 parse_gnu_attribute_string_arg(attribute, &string);
1392 if (string.begin != NULL) {
1393 for (size_t i = 0; i < 4; ++i) {
1394 if (strcmp(visibilities[i], string.begin) == 0) {
1395 attribute->u.value = i;
1399 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1401 attribute->invalid = true;
1405 * parse one (code) model.
1407 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1409 static const char *const visibilities[] = {
1414 string_t string = { NULL, 0 };
1415 parse_gnu_attribute_string_arg(attribute, &string);
1416 if (string.begin != NULL) {
1417 for (int i = 0; i < 3; ++i) {
1418 if (strcmp(visibilities[i], string.begin) == 0) {
1419 attribute->u.value = i;
1423 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1425 attribute->invalid = true;
1428 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1430 /* TODO: find out what is allowed here... */
1432 /* at least: byte, word, pointer, list of machine modes
1433 * __XXX___ is interpreted as XXX */
1434 add_anchor_token(')');
1436 if (token.type != T_IDENTIFIER) {
1437 expect(T_IDENTIFIER);
1440 /* This isn't really correct, the backend should provide a list of machine
1441 * specific modes (according to gcc philosophy that is...) */
1442 const char *symbol_str = token.v.symbol->string;
1443 if (strcmp_underscore("QI", symbol_str) == 0 ||
1444 strcmp_underscore("byte", symbol_str) == 0) {
1445 attribute->u.akind = ATOMIC_TYPE_CHAR;
1446 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1447 attribute->u.akind = ATOMIC_TYPE_SHORT;
1448 } else if (strcmp_underscore("SI", symbol_str) == 0
1449 || strcmp_underscore("word", symbol_str) == 0
1450 || strcmp_underscore("pointer", symbol_str) == 0) {
1451 attribute->u.akind = ATOMIC_TYPE_INT;
1452 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1453 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1456 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1457 attribute->invalid = true;
1461 rem_anchor_token(')');
1465 attribute->invalid = true;
1469 * parse one interrupt argument.
1471 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1473 static const char *const interrupts[] = {
1480 string_t string = { NULL, 0 };
1481 parse_gnu_attribute_string_arg(attribute, &string);
1482 if (string.begin != NULL) {
1483 for (size_t i = 0; i < 5; ++i) {
1484 if (strcmp(interrupts[i], string.begin) == 0) {
1485 attribute->u.value = i;
1489 errorf(HERE, "'%s' is not an interrupt", string.begin);
1491 attribute->invalid = true;
1495 * parse ( identifier, const expression, const expression )
1497 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1499 static const char *const format_names[] = {
1507 if (token.type != T_IDENTIFIER) {
1508 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1511 const char *name = token.v.symbol->string;
1512 for (i = 0; i < 4; ++i) {
1513 if (strcmp_underscore(format_names[i], name) == 0)
1517 if (warning.attribute)
1518 warningf(HERE, "'%s' is an unrecognized format function type", name);
1523 add_anchor_token(')');
1524 add_anchor_token(',');
1525 parse_constant_expression();
1526 rem_anchor_token(',');
1527 rem_anchor_token(')');
1530 add_anchor_token(')');
1531 parse_constant_expression();
1532 rem_anchor_token(')');
1536 attribute->u.value = true;
1539 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1541 if (!attribute->have_arguments)
1544 /* should have no arguments */
1545 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1546 eat_until_matching_token('(');
1547 /* we have already consumed '(', so we stop before ')', eat it */
1549 attribute->invalid = true;
1553 * Parse one GNU attribute.
1555 * Note that attribute names can be specified WITH or WITHOUT
1556 * double underscores, ie const or __const__.
1558 * The following attributes are parsed without arguments
1583 * no_instrument_function
1584 * warn_unused_result
1601 * externally_visible
1609 * The following attributes are parsed with arguments
1610 * aligned( const expression )
1611 * alias( string literal )
1612 * section( string literal )
1613 * format( identifier, const expression, const expression )
1614 * format_arg( const expression )
1615 * tls_model( string literal )
1616 * visibility( string literal )
1617 * regparm( const expression )
1618 * model( string leteral )
1619 * trap_exit( const expression )
1620 * sp_switch( string literal )
1622 * The following attributes might have arguments
1623 * weak_ref( string literal )
1624 * non_null( const expression // ',' )
1625 * interrupt( string literal )
1626 * sentinel( constant expression )
1628 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1630 gnu_attribute_t *head = *attributes;
1631 gnu_attribute_t *last = *attributes;
1632 decl_modifiers_t modifiers = 0;
1633 gnu_attribute_t *attribute;
1635 eat(T___attribute__);
1639 if (token.type != ')') {
1640 /* find the end of the list */
1642 while (last->next != NULL)
1646 /* non-empty attribute list */
1649 if (token.type == T_const) {
1651 } else if (token.type == T_volatile) {
1653 } else if (token.type == T_cdecl) {
1654 /* __attribute__((cdecl)), WITH ms mode */
1656 } else if (token.type == T_IDENTIFIER) {
1657 const symbol_t *sym = token.v.symbol;
1660 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1667 for (i = 0; i < GNU_AK_LAST; ++i) {
1668 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1671 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1674 if (kind == GNU_AK_LAST) {
1675 if (warning.attribute)
1676 warningf(HERE, "'%s' attribute directive ignored", name);
1678 /* skip possible arguments */
1679 if (token.type == '(') {
1680 eat_until_matching_token(')');
1683 /* check for arguments */
1684 attribute = allocate_gnu_attribute(kind);
1685 if (token.type == '(') {
1687 if (token.type == ')') {
1688 /* empty args are allowed */
1691 attribute->have_arguments = true;
1695 case GNU_AK_VOLATILE:
1700 case GNU_AK_NOCOMMON:
1702 case GNU_AK_NOTSHARED:
1703 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1704 case GNU_AK_WARN_UNUSED_RESULT:
1705 case GNU_AK_LONGCALL:
1706 case GNU_AK_SHORTCALL:
1707 case GNU_AK_LONG_CALL:
1708 case GNU_AK_SHORT_CALL:
1709 case GNU_AK_FUNCTION_VECTOR:
1710 case GNU_AK_INTERRUPT_HANDLER:
1711 case GNU_AK_NMI_HANDLER:
1712 case GNU_AK_NESTING:
1716 case GNU_AK_EIGTHBIT_DATA:
1717 case GNU_AK_TINY_DATA:
1718 case GNU_AK_SAVEALL:
1719 case GNU_AK_FLATTEN:
1720 case GNU_AK_SSEREGPARM:
1721 case GNU_AK_EXTERNALLY_VISIBLE:
1722 case GNU_AK_RETURN_TWICE:
1723 case GNU_AK_MAY_ALIAS:
1724 case GNU_AK_MS_STRUCT:
1725 case GNU_AK_GCC_STRUCT:
1728 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1729 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1730 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1731 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1732 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1733 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1734 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1735 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1736 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1737 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1738 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1739 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1740 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1741 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1742 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1743 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1744 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1745 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1747 case GNU_AK_ALIGNED:
1748 /* __align__ may be used without an argument */
1749 if (attribute->have_arguments) {
1750 parse_gnu_attribute_const_arg(attribute);
1754 case GNU_AK_FORMAT_ARG:
1755 case GNU_AK_REGPARM:
1756 case GNU_AK_TRAP_EXIT:
1757 if (!attribute->have_arguments) {
1758 /* should have arguments */
1759 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1760 attribute->invalid = true;
1762 parse_gnu_attribute_const_arg(attribute);
1765 case GNU_AK_SECTION:
1766 case GNU_AK_SP_SWITCH:
1767 if (!attribute->have_arguments) {
1768 /* should have arguments */
1769 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1770 attribute->invalid = true;
1772 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1775 if (!attribute->have_arguments) {
1776 /* should have arguments */
1777 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1778 attribute->invalid = true;
1780 parse_gnu_attribute_format_args(attribute);
1782 case GNU_AK_WEAKREF:
1783 /* may have one string argument */
1784 if (attribute->have_arguments)
1785 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1787 case GNU_AK_NONNULL:
1788 if (attribute->have_arguments)
1789 parse_gnu_attribute_const_arg_list(attribute);
1791 case GNU_AK_TLS_MODEL:
1792 if (!attribute->have_arguments) {
1793 /* should have arguments */
1794 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1796 parse_gnu_attribute_tls_model_arg(attribute);
1798 case GNU_AK_VISIBILITY:
1799 if (!attribute->have_arguments) {
1800 /* should have arguments */
1801 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1803 parse_gnu_attribute_visibility_arg(attribute);
1806 if (!attribute->have_arguments) {
1807 /* should have arguments */
1808 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1810 parse_gnu_attribute_model_arg(attribute);
1814 if (!attribute->have_arguments) {
1815 /* should have arguments */
1816 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1818 parse_gnu_attribute_mode_arg(attribute);
1821 case GNU_AK_INTERRUPT:
1822 /* may have one string argument */
1823 if (attribute->have_arguments)
1824 parse_gnu_attribute_interrupt_arg(attribute);
1826 case GNU_AK_SENTINEL:
1827 /* may have one string argument */
1828 if (attribute->have_arguments)
1829 parse_gnu_attribute_const_arg(attribute);
1832 /* already handled */
1836 check_no_argument(attribute, name);
1839 if (attribute != NULL) {
1841 last->next = attribute;
1844 head = last = attribute;
1848 if (token.type != ',')
1862 * Parse GNU attributes.
1864 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1866 decl_modifiers_t modifiers = 0;
1869 switch (token.type) {
1870 case T___attribute__:
1871 modifiers |= parse_gnu_attribute(attributes);
1877 if (token.type != T_STRING_LITERAL) {
1878 parse_error_expected("while parsing assembler attribute",
1879 T_STRING_LITERAL, NULL);
1880 eat_until_matching_token('(');
1883 parse_string_literals();
1888 case T_cdecl: modifiers |= DM_CDECL; break;
1889 case T__fastcall: modifiers |= DM_FASTCALL; break;
1890 case T__stdcall: modifiers |= DM_STDCALL; break;
1893 /* TODO record modifier */
1895 warningf(HERE, "Ignoring declaration modifier '%K'", &token);
1899 default: return modifiers;
1906 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1908 static entity_t *determine_lhs_ent(expression_t *const expr,
1911 switch (expr->kind) {
1912 case EXPR_REFERENCE: {
1913 entity_t *const entity = expr->reference.entity;
1914 /* we should only find variables as lvalues... */
1915 if (entity->base.kind != ENTITY_VARIABLE
1916 && entity->base.kind != ENTITY_PARAMETER)
1922 case EXPR_ARRAY_ACCESS: {
1923 expression_t *const ref = expr->array_access.array_ref;
1924 entity_t * ent = NULL;
1925 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1926 ent = determine_lhs_ent(ref, lhs_ent);
1929 mark_vars_read(expr->select.compound, lhs_ent);
1931 mark_vars_read(expr->array_access.index, lhs_ent);
1936 if (is_type_compound(skip_typeref(expr->base.type))) {
1937 return determine_lhs_ent(expr->select.compound, lhs_ent);
1939 mark_vars_read(expr->select.compound, lhs_ent);
1944 case EXPR_UNARY_DEREFERENCE: {
1945 expression_t *const val = expr->unary.value;
1946 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1948 return determine_lhs_ent(val->unary.value, lhs_ent);
1950 mark_vars_read(val, NULL);
1956 mark_vars_read(expr, NULL);
1961 #define ENT_ANY ((entity_t*)-1)
1964 * Mark declarations, which are read. This is used to detect variables, which
1968 * x is not marked as "read", because it is only read to calculate its own new
1972 * x and y are not detected as "not read", because multiple variables are
1975 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1977 switch (expr->kind) {
1978 case EXPR_REFERENCE: {
1979 entity_t *const entity = expr->reference.entity;
1980 if (entity->kind != ENTITY_VARIABLE
1981 && entity->kind != ENTITY_PARAMETER)
1984 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1985 if (entity->kind == ENTITY_VARIABLE) {
1986 entity->variable.read = true;
1988 entity->parameter.read = true;
1995 // TODO respect pure/const
1996 mark_vars_read(expr->call.function, NULL);
1997 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1998 mark_vars_read(arg->expression, NULL);
2002 case EXPR_CONDITIONAL:
2003 // TODO lhs_decl should depend on whether true/false have an effect
2004 mark_vars_read(expr->conditional.condition, NULL);
2005 if (expr->conditional.true_expression != NULL)
2006 mark_vars_read(expr->conditional.true_expression, lhs_ent);
2007 mark_vars_read(expr->conditional.false_expression, lhs_ent);
2011 if (lhs_ent == ENT_ANY
2012 && !is_type_compound(skip_typeref(expr->base.type)))
2014 mark_vars_read(expr->select.compound, lhs_ent);
2017 case EXPR_ARRAY_ACCESS: {
2018 expression_t *const ref = expr->array_access.array_ref;
2019 mark_vars_read(ref, lhs_ent);
2020 lhs_ent = determine_lhs_ent(ref, lhs_ent);
2021 mark_vars_read(expr->array_access.index, lhs_ent);
2026 mark_vars_read(expr->va_arge.ap, lhs_ent);
2029 case EXPR_UNARY_CAST:
2030 /* Special case: Use void cast to mark a variable as "read" */
2031 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2036 case EXPR_UNARY_THROW:
2037 if (expr->unary.value == NULL)
2040 case EXPR_UNARY_DEREFERENCE:
2041 case EXPR_UNARY_DELETE:
2042 case EXPR_UNARY_DELETE_ARRAY:
2043 if (lhs_ent == ENT_ANY)
2047 case EXPR_UNARY_NEGATE:
2048 case EXPR_UNARY_PLUS:
2049 case EXPR_UNARY_BITWISE_NEGATE:
2050 case EXPR_UNARY_NOT:
2051 case EXPR_UNARY_TAKE_ADDRESS:
2052 case EXPR_UNARY_POSTFIX_INCREMENT:
2053 case EXPR_UNARY_POSTFIX_DECREMENT:
2054 case EXPR_UNARY_PREFIX_INCREMENT:
2055 case EXPR_UNARY_PREFIX_DECREMENT:
2056 case EXPR_UNARY_CAST_IMPLICIT:
2057 case EXPR_UNARY_ASSUME:
2059 mark_vars_read(expr->unary.value, lhs_ent);
2062 case EXPR_BINARY_ADD:
2063 case EXPR_BINARY_SUB:
2064 case EXPR_BINARY_MUL:
2065 case EXPR_BINARY_DIV:
2066 case EXPR_BINARY_MOD:
2067 case EXPR_BINARY_EQUAL:
2068 case EXPR_BINARY_NOTEQUAL:
2069 case EXPR_BINARY_LESS:
2070 case EXPR_BINARY_LESSEQUAL:
2071 case EXPR_BINARY_GREATER:
2072 case EXPR_BINARY_GREATEREQUAL:
2073 case EXPR_BINARY_BITWISE_AND:
2074 case EXPR_BINARY_BITWISE_OR:
2075 case EXPR_BINARY_BITWISE_XOR:
2076 case EXPR_BINARY_LOGICAL_AND:
2077 case EXPR_BINARY_LOGICAL_OR:
2078 case EXPR_BINARY_SHIFTLEFT:
2079 case EXPR_BINARY_SHIFTRIGHT:
2080 case EXPR_BINARY_COMMA:
2081 case EXPR_BINARY_ISGREATER:
2082 case EXPR_BINARY_ISGREATEREQUAL:
2083 case EXPR_BINARY_ISLESS:
2084 case EXPR_BINARY_ISLESSEQUAL:
2085 case EXPR_BINARY_ISLESSGREATER:
2086 case EXPR_BINARY_ISUNORDERED:
2087 mark_vars_read(expr->binary.left, lhs_ent);
2088 mark_vars_read(expr->binary.right, lhs_ent);
2091 case EXPR_BINARY_ASSIGN:
2092 case EXPR_BINARY_MUL_ASSIGN:
2093 case EXPR_BINARY_DIV_ASSIGN:
2094 case EXPR_BINARY_MOD_ASSIGN:
2095 case EXPR_BINARY_ADD_ASSIGN:
2096 case EXPR_BINARY_SUB_ASSIGN:
2097 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2098 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2099 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2100 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2101 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2102 if (lhs_ent == ENT_ANY)
2104 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
2105 mark_vars_read(expr->binary.right, lhs_ent);
2110 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
2116 case EXPR_CHARACTER_CONSTANT:
2117 case EXPR_WIDE_CHARACTER_CONSTANT:
2118 case EXPR_STRING_LITERAL:
2119 case EXPR_WIDE_STRING_LITERAL:
2120 case EXPR_COMPOUND_LITERAL: // TODO init?
2122 case EXPR_CLASSIFY_TYPE:
2125 case EXPR_BUILTIN_SYMBOL:
2126 case EXPR_BUILTIN_CONSTANT_P:
2127 case EXPR_BUILTIN_PREFETCH:
2129 case EXPR_STATEMENT: // TODO
2130 case EXPR_LABEL_ADDRESS:
2131 case EXPR_REFERENCE_ENUM_VALUE:
2135 panic("unhandled expression");
2138 static designator_t *parse_designation(void)
2140 designator_t *result = NULL;
2141 designator_t *last = NULL;
2144 designator_t *designator;
2145 switch (token.type) {
2147 designator = allocate_ast_zero(sizeof(designator[0]));
2148 designator->source_position = token.source_position;
2150 add_anchor_token(']');
2151 designator->array_index = parse_constant_expression();
2152 rem_anchor_token(']');
2156 designator = allocate_ast_zero(sizeof(designator[0]));
2157 designator->source_position = token.source_position;
2159 if (token.type != T_IDENTIFIER) {
2160 parse_error_expected("while parsing designator",
2161 T_IDENTIFIER, NULL);
2164 designator->symbol = token.v.symbol;
2172 assert(designator != NULL);
2174 last->next = designator;
2176 result = designator;
2184 static initializer_t *initializer_from_string(array_type_t *type,
2185 const string_t *const string)
2187 /* TODO: check len vs. size of array type */
2190 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2191 initializer->string.string = *string;
2196 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2197 wide_string_t *const string)
2199 /* TODO: check len vs. size of array type */
2202 initializer_t *const initializer =
2203 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2204 initializer->wide_string.string = *string;
2210 * Build an initializer from a given expression.
2212 static initializer_t *initializer_from_expression(type_t *orig_type,
2213 expression_t *expression)
2215 /* TODO check that expression is a constant expression */
2217 /* § 6.7.8.14/15 char array may be initialized by string literals */
2218 type_t *type = skip_typeref(orig_type);
2219 type_t *expr_type_orig = expression->base.type;
2220 type_t *expr_type = skip_typeref(expr_type_orig);
2221 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2222 array_type_t *const array_type = &type->array;
2223 type_t *const element_type = skip_typeref(array_type->element_type);
2225 if (element_type->kind == TYPE_ATOMIC) {
2226 atomic_type_kind_t akind = element_type->atomic.akind;
2227 switch (expression->kind) {
2228 case EXPR_STRING_LITERAL:
2229 if (akind == ATOMIC_TYPE_CHAR
2230 || akind == ATOMIC_TYPE_SCHAR
2231 || akind == ATOMIC_TYPE_UCHAR) {
2232 return initializer_from_string(array_type,
2233 &expression->string.value);
2236 case EXPR_WIDE_STRING_LITERAL: {
2237 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2238 if (get_unqualified_type(element_type) == bare_wchar_type) {
2239 return initializer_from_wide_string(array_type,
2240 &expression->wide_string.value);
2250 assign_error_t error = semantic_assign(type, expression);
2251 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2253 report_assign_error(error, type, expression, "initializer",
2254 &expression->base.source_position);
2256 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2258 if (type->kind == TYPE_BITFIELD) {
2259 type = type->bitfield.base_type;
2262 result->value.value = create_implicit_cast(expression, type);
2268 * Checks if a given expression can be used as an constant initializer.
2270 static bool is_initializer_constant(const expression_t *expression)
2272 return is_constant_expression(expression)
2273 || is_address_constant(expression);
2277 * Parses an scalar initializer.
2279 * § 6.7.8.11; eat {} without warning
2281 static initializer_t *parse_scalar_initializer(type_t *type,
2282 bool must_be_constant)
2284 /* there might be extra {} hierarchies */
2286 if (token.type == '{') {
2288 warningf(HERE, "extra curly braces around scalar initializer");
2292 } while (token.type == '{');
2295 expression_t *expression = parse_assignment_expression();
2296 mark_vars_read(expression, NULL);
2297 if (must_be_constant && !is_initializer_constant(expression)) {
2298 errorf(&expression->base.source_position,
2299 "Initialisation expression '%E' is not constant",
2303 initializer_t *initializer = initializer_from_expression(type, expression);
2305 if (initializer == NULL) {
2306 errorf(&expression->base.source_position,
2307 "expression '%E' (type '%T') doesn't match expected type '%T'",
2308 expression, expression->base.type, type);
2313 bool additional_warning_displayed = false;
2314 while (braces > 0) {
2315 if (token.type == ',') {
2318 if (token.type != '}') {
2319 if (!additional_warning_displayed && warning.other) {
2320 warningf(HERE, "additional elements in scalar initializer");
2321 additional_warning_displayed = true;
2332 * An entry in the type path.
2334 typedef struct type_path_entry_t type_path_entry_t;
2335 struct type_path_entry_t {
2336 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2338 size_t index; /**< For array types: the current index. */
2339 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2344 * A type path expression a position inside compound or array types.
2346 typedef struct type_path_t type_path_t;
2347 struct type_path_t {
2348 type_path_entry_t *path; /**< An flexible array containing the current path. */
2349 type_t *top_type; /**< type of the element the path points */
2350 size_t max_index; /**< largest index in outermost array */
2354 * Prints a type path for debugging.
2356 static __attribute__((unused)) void debug_print_type_path(
2357 const type_path_t *path)
2359 size_t len = ARR_LEN(path->path);
2361 for (size_t i = 0; i < len; ++i) {
2362 const type_path_entry_t *entry = & path->path[i];
2364 type_t *type = skip_typeref(entry->type);
2365 if (is_type_compound(type)) {
2366 /* in gcc mode structs can have no members */
2367 if (entry->v.compound_entry == NULL) {
2371 fprintf(stderr, ".%s",
2372 entry->v.compound_entry->base.symbol->string);
2373 } else if (is_type_array(type)) {
2374 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
2376 fprintf(stderr, "-INVALID-");
2379 if (path->top_type != NULL) {
2380 fprintf(stderr, " (");
2381 print_type(path->top_type);
2382 fprintf(stderr, ")");
2387 * Return the top type path entry, ie. in a path
2388 * (type).a.b returns the b.
2390 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2392 size_t len = ARR_LEN(path->path);
2394 return &path->path[len-1];
2398 * Enlarge the type path by an (empty) element.
2400 static type_path_entry_t *append_to_type_path(type_path_t *path)
2402 size_t len = ARR_LEN(path->path);
2403 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2405 type_path_entry_t *result = & path->path[len];
2406 memset(result, 0, sizeof(result[0]));
2411 * Descending into a sub-type. Enter the scope of the current top_type.
2413 static void descend_into_subtype(type_path_t *path)
2415 type_t *orig_top_type = path->top_type;
2416 type_t *top_type = skip_typeref(orig_top_type);
2418 type_path_entry_t *top = append_to_type_path(path);
2419 top->type = top_type;
2421 if (is_type_compound(top_type)) {
2422 compound_t *compound = top_type->compound.compound;
2423 entity_t *entry = compound->members.entities;
2425 if (entry != NULL) {
2426 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2427 top->v.compound_entry = &entry->declaration;
2428 path->top_type = entry->declaration.type;
2430 path->top_type = NULL;
2432 } else if (is_type_array(top_type)) {
2434 path->top_type = top_type->array.element_type;
2436 assert(!is_type_valid(top_type));
2441 * Pop an entry from the given type path, ie. returning from
2442 * (type).a.b to (type).a
2444 static void ascend_from_subtype(type_path_t *path)
2446 type_path_entry_t *top = get_type_path_top(path);
2448 path->top_type = top->type;
2450 size_t len = ARR_LEN(path->path);
2451 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2455 * Pop entries from the given type path until the given
2456 * path level is reached.
2458 static void ascend_to(type_path_t *path, size_t top_path_level)
2460 size_t len = ARR_LEN(path->path);
2462 while (len > top_path_level) {
2463 ascend_from_subtype(path);
2464 len = ARR_LEN(path->path);
2468 static bool walk_designator(type_path_t *path, const designator_t *designator,
2469 bool used_in_offsetof)
2471 for (; designator != NULL; designator = designator->next) {
2472 type_path_entry_t *top = get_type_path_top(path);
2473 type_t *orig_type = top->type;
2475 type_t *type = skip_typeref(orig_type);
2477 if (designator->symbol != NULL) {
2478 symbol_t *symbol = designator->symbol;
2479 if (!is_type_compound(type)) {
2480 if (is_type_valid(type)) {
2481 errorf(&designator->source_position,
2482 "'.%Y' designator used for non-compound type '%T'",
2486 top->type = type_error_type;
2487 top->v.compound_entry = NULL;
2488 orig_type = type_error_type;
2490 compound_t *compound = type->compound.compound;
2491 entity_t *iter = compound->members.entities;
2492 for (; iter != NULL; iter = iter->base.next) {
2493 if (iter->base.symbol == symbol) {
2498 errorf(&designator->source_position,
2499 "'%T' has no member named '%Y'", orig_type, symbol);
2502 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2503 if (used_in_offsetof) {
2504 type_t *real_type = skip_typeref(iter->declaration.type);
2505 if (real_type->kind == TYPE_BITFIELD) {
2506 errorf(&designator->source_position,
2507 "offsetof designator '%Y' may not specify bitfield",
2513 top->type = orig_type;
2514 top->v.compound_entry = &iter->declaration;
2515 orig_type = iter->declaration.type;
2518 expression_t *array_index = designator->array_index;
2519 assert(designator->array_index != NULL);
2521 if (!is_type_array(type)) {
2522 if (is_type_valid(type)) {
2523 errorf(&designator->source_position,
2524 "[%E] designator used for non-array type '%T'",
2525 array_index, orig_type);
2530 long index = fold_constant(array_index);
2531 if (!used_in_offsetof) {
2533 errorf(&designator->source_position,
2534 "array index [%E] must be positive", array_index);
2535 } else if (type->array.size_constant) {
2536 long array_size = type->array.size;
2537 if (index >= array_size) {
2538 errorf(&designator->source_position,
2539 "designator [%E] (%d) exceeds array size %d",
2540 array_index, index, array_size);
2545 top->type = orig_type;
2546 top->v.index = (size_t) index;
2547 orig_type = type->array.element_type;
2549 path->top_type = orig_type;
2551 if (designator->next != NULL) {
2552 descend_into_subtype(path);
2561 static void advance_current_object(type_path_t *path, size_t top_path_level)
2563 type_path_entry_t *top = get_type_path_top(path);
2565 type_t *type = skip_typeref(top->type);
2566 if (is_type_union(type)) {
2567 /* in unions only the first element is initialized */
2568 top->v.compound_entry = NULL;
2569 } else if (is_type_struct(type)) {
2570 declaration_t *entry = top->v.compound_entry;
2572 entity_t *next_entity = entry->base.next;
2573 if (next_entity != NULL) {
2574 assert(is_declaration(next_entity));
2575 entry = &next_entity->declaration;
2580 top->v.compound_entry = entry;
2581 if (entry != NULL) {
2582 path->top_type = entry->type;
2585 } else if (is_type_array(type)) {
2586 assert(is_type_array(type));
2590 if (!type->array.size_constant || top->v.index < type->array.size) {
2594 assert(!is_type_valid(type));
2598 /* we're past the last member of the current sub-aggregate, try if we
2599 * can ascend in the type hierarchy and continue with another subobject */
2600 size_t len = ARR_LEN(path->path);
2602 if (len > top_path_level) {
2603 ascend_from_subtype(path);
2604 advance_current_object(path, top_path_level);
2606 path->top_type = NULL;
2611 * skip until token is found.
2613 static void skip_until(int type)
2615 while (token.type != type) {
2616 if (token.type == T_EOF)
2623 * skip any {...} blocks until a closing bracket is reached.
2625 static void skip_initializers(void)
2627 if (token.type == '{')
2630 while (token.type != '}') {
2631 if (token.type == T_EOF)
2633 if (token.type == '{') {
2641 static initializer_t *create_empty_initializer(void)
2643 static initializer_t empty_initializer
2644 = { .list = { { INITIALIZER_LIST }, 0 } };
2645 return &empty_initializer;
2649 * Parse a part of an initialiser for a struct or union,
2651 static initializer_t *parse_sub_initializer(type_path_t *path,
2652 type_t *outer_type, size_t top_path_level,
2653 parse_initializer_env_t *env)
2655 if (token.type == '}') {
2656 /* empty initializer */
2657 return create_empty_initializer();
2660 type_t *orig_type = path->top_type;
2661 type_t *type = NULL;
2663 if (orig_type == NULL) {
2664 /* We are initializing an empty compound. */
2666 type = skip_typeref(orig_type);
2669 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2672 designator_t *designator = NULL;
2673 if (token.type == '.' || token.type == '[') {
2674 designator = parse_designation();
2675 goto finish_designator;
2676 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2677 /* GNU-style designator ("identifier: value") */
2678 designator = allocate_ast_zero(sizeof(designator[0]));
2679 designator->source_position = token.source_position;
2680 designator->symbol = token.v.symbol;
2685 /* reset path to toplevel, evaluate designator from there */
2686 ascend_to(path, top_path_level);
2687 if (!walk_designator(path, designator, false)) {
2688 /* can't continue after designation error */
2692 initializer_t *designator_initializer
2693 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2694 designator_initializer->designator.designator = designator;
2695 ARR_APP1(initializer_t*, initializers, designator_initializer);
2697 orig_type = path->top_type;
2698 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2703 if (token.type == '{') {
2704 if (type != NULL && is_type_scalar(type)) {
2705 sub = parse_scalar_initializer(type, env->must_be_constant);
2709 if (env->entity != NULL) {
2711 "extra brace group at end of initializer for '%Y'",
2712 env->entity->base.symbol);
2714 errorf(HERE, "extra brace group at end of initializer");
2717 descend_into_subtype(path);
2719 add_anchor_token('}');
2720 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2722 rem_anchor_token('}');
2725 ascend_from_subtype(path);
2729 goto error_parse_next;
2733 /* must be an expression */
2734 expression_t *expression = parse_assignment_expression();
2736 if (env->must_be_constant && !is_initializer_constant(expression)) {
2737 errorf(&expression->base.source_position,
2738 "Initialisation expression '%E' is not constant",
2743 /* we are already outside, ... */
2744 type_t *const outer_type_skip = skip_typeref(outer_type);
2745 if (is_type_compound(outer_type_skip) &&
2746 !outer_type_skip->compound.compound->complete) {
2747 goto error_parse_next;
2752 /* handle { "string" } special case */
2753 if ((expression->kind == EXPR_STRING_LITERAL
2754 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2755 && outer_type != NULL) {
2756 sub = initializer_from_expression(outer_type, expression);
2758 if (token.type == ',') {
2761 if (token.type != '}' && warning.other) {
2762 warningf(HERE, "excessive elements in initializer for type '%T'",
2765 /* TODO: eat , ... */
2770 /* descend into subtypes until expression matches type */
2772 orig_type = path->top_type;
2773 type = skip_typeref(orig_type);
2775 sub = initializer_from_expression(orig_type, expression);
2779 if (!is_type_valid(type)) {
2782 if (is_type_scalar(type)) {
2783 errorf(&expression->base.source_position,
2784 "expression '%E' doesn't match expected type '%T'",
2785 expression, orig_type);
2789 descend_into_subtype(path);
2793 /* update largest index of top array */
2794 const type_path_entry_t *first = &path->path[0];
2795 type_t *first_type = first->type;
2796 first_type = skip_typeref(first_type);
2797 if (is_type_array(first_type)) {
2798 size_t index = first->v.index;
2799 if (index > path->max_index)
2800 path->max_index = index;
2804 /* append to initializers list */
2805 ARR_APP1(initializer_t*, initializers, sub);
2808 if (warning.other) {
2809 if (env->entity != NULL) {
2810 warningf(HERE, "excess elements in struct initializer for '%Y'",
2811 env->entity->base.symbol);
2813 warningf(HERE, "excess elements in struct initializer");
2819 if (token.type == '}') {
2823 if (token.type == '}') {
2828 /* advance to the next declaration if we are not at the end */
2829 advance_current_object(path, top_path_level);
2830 orig_type = path->top_type;
2831 if (orig_type != NULL)
2832 type = skip_typeref(orig_type);
2838 size_t len = ARR_LEN(initializers);
2839 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2840 initializer_t *result = allocate_ast_zero(size);
2841 result->kind = INITIALIZER_LIST;
2842 result->list.len = len;
2843 memcpy(&result->list.initializers, initializers,
2844 len * sizeof(initializers[0]));
2846 DEL_ARR_F(initializers);
2847 ascend_to(path, top_path_level+1);
2852 skip_initializers();
2853 DEL_ARR_F(initializers);
2854 ascend_to(path, top_path_level+1);
2859 * Parses an initializer. Parsers either a compound literal
2860 * (env->declaration == NULL) or an initializer of a declaration.
2862 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2864 type_t *type = skip_typeref(env->type);
2865 initializer_t *result = NULL;
2868 if (is_type_scalar(type)) {
2869 result = parse_scalar_initializer(type, env->must_be_constant);
2870 } else if (token.type == '{') {
2874 memset(&path, 0, sizeof(path));
2875 path.top_type = env->type;
2876 path.path = NEW_ARR_F(type_path_entry_t, 0);
2878 descend_into_subtype(&path);
2880 add_anchor_token('}');
2881 result = parse_sub_initializer(&path, env->type, 1, env);
2882 rem_anchor_token('}');
2884 max_index = path.max_index;
2885 DEL_ARR_F(path.path);
2889 /* parse_scalar_initializer() also works in this case: we simply
2890 * have an expression without {} around it */
2891 result = parse_scalar_initializer(type, env->must_be_constant);
2894 /* § 6.7.8 (22) array initializers for arrays with unknown size determine
2895 * the array type size */
2896 if (is_type_array(type) && type->array.size_expression == NULL
2897 && result != NULL) {
2899 switch (result->kind) {
2900 case INITIALIZER_LIST:
2901 size = max_index + 1;
2904 case INITIALIZER_STRING:
2905 size = result->string.string.size;
2908 case INITIALIZER_WIDE_STRING:
2909 size = result->wide_string.string.size;
2912 case INITIALIZER_DESIGNATOR:
2913 case INITIALIZER_VALUE:
2914 /* can happen for parse errors */
2919 internal_errorf(HERE, "invalid initializer type");
2922 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2923 cnst->base.type = type_size_t;
2924 cnst->conste.v.int_value = size;
2926 type_t *new_type = duplicate_type(type);
2928 new_type->array.size_expression = cnst;
2929 new_type->array.size_constant = true;
2930 new_type->array.has_implicit_size = true;
2931 new_type->array.size = size;
2932 env->type = new_type;
2940 static void append_entity(scope_t *scope, entity_t *entity)
2942 if (scope->last_entity != NULL) {
2943 scope->last_entity->base.next = entity;
2945 scope->entities = entity;
2947 scope->last_entity = entity;
2951 static compound_t *parse_compound_type_specifier(bool is_struct)
2953 gnu_attribute_t *attributes = NULL;
2954 decl_modifiers_t modifiers = 0;
2961 symbol_t *symbol = NULL;
2962 compound_t *compound = NULL;
2964 if (token.type == T___attribute__) {
2965 modifiers |= parse_attributes(&attributes);
2968 if (token.type == T_IDENTIFIER) {
2969 symbol = token.v.symbol;
2972 namespace_tag_t const namespc =
2973 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2974 entity_t *entity = get_entity(symbol, namespc);
2975 if (entity != NULL) {
2976 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
2977 compound = &entity->compound;
2978 if (compound->base.parent_scope != current_scope &&
2979 (token.type == '{' || token.type == ';')) {
2980 /* we're in an inner scope and have a definition. Override
2981 existing definition in outer scope */
2983 } else if (compound->complete && token.type == '{') {
2984 assert(symbol != NULL);
2985 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2986 is_struct ? "struct" : "union", symbol,
2987 &compound->base.source_position);
2988 /* clear members in the hope to avoid further errors */
2989 compound->members.entities = NULL;
2992 } else if (token.type != '{') {
2994 parse_error_expected("while parsing struct type specifier",
2995 T_IDENTIFIER, '{', NULL);
2997 parse_error_expected("while parsing union type specifier",
2998 T_IDENTIFIER, '{', NULL);
3004 if (compound == NULL) {
3005 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
3006 entity_t *entity = allocate_entity_zero(kind);
3007 compound = &entity->compound;
3009 compound->base.namespc =
3010 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
3011 compound->base.source_position = token.source_position;
3012 compound->base.symbol = symbol;
3013 compound->base.parent_scope = current_scope;
3014 if (symbol != NULL) {
3015 environment_push(entity);
3017 append_entity(current_scope, entity);
3020 if (token.type == '{') {
3021 parse_compound_type_entries(compound);
3022 modifiers |= parse_attributes(&attributes);
3024 if (symbol == NULL) {
3025 assert(anonymous_entity == NULL);
3026 anonymous_entity = (entity_t*)compound;
3030 compound->modifiers |= modifiers;
3034 static void parse_enum_entries(type_t *const enum_type)
3038 if (token.type == '}') {
3039 errorf(HERE, "empty enum not allowed");
3044 add_anchor_token('}');
3046 if (token.type != T_IDENTIFIER) {
3047 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3049 rem_anchor_token('}');
3053 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3054 entity->enum_value.enum_type = enum_type;
3055 entity->base.symbol = token.v.symbol;
3056 entity->base.source_position = token.source_position;
3059 if (token.type == '=') {
3061 expression_t *value = parse_constant_expression();
3063 value = create_implicit_cast(value, enum_type);
3064 entity->enum_value.value = value;
3069 record_entity(entity, false);
3071 if (token.type != ',')
3074 } while (token.type != '}');
3075 rem_anchor_token('}');
3083 static type_t *parse_enum_specifier(void)
3085 gnu_attribute_t *attributes = NULL;
3090 if (token.type == T_IDENTIFIER) {
3091 symbol = token.v.symbol;
3094 entity = get_entity(symbol, NAMESPACE_ENUM);
3095 assert(entity == NULL || entity->kind == ENTITY_ENUM);
3096 } else if (token.type != '{') {
3097 parse_error_expected("while parsing enum type specifier",
3098 T_IDENTIFIER, '{', NULL);
3105 if (entity == NULL) {
3106 entity = allocate_entity_zero(ENTITY_ENUM);
3107 entity->base.namespc = NAMESPACE_ENUM;
3108 entity->base.source_position = token.source_position;
3109 entity->base.symbol = symbol;
3110 entity->base.parent_scope = current_scope;
3113 type_t *const type = allocate_type_zero(TYPE_ENUM);
3114 type->enumt.enume = &entity->enume;
3116 if (token.type == '{') {
3117 if (entity->enume.complete) {
3118 errorf(HERE, "multiple definitions of enum %Y (previous definition %P)",
3119 symbol, &entity->base.source_position);
3121 if (symbol != NULL) {
3122 environment_push(entity);
3124 append_entity(current_scope, entity);
3125 entity->enume.complete = true;
3127 parse_enum_entries(type);
3128 parse_attributes(&attributes);
3130 if (symbol == NULL) {
3131 assert(anonymous_entity == NULL);
3132 anonymous_entity = entity;
3134 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
3135 errorf(HERE, "enum %Y used before definition (incomplete enumes are a GNU extension)",
3143 * if a symbol is a typedef to another type, return true
3145 static bool is_typedef_symbol(symbol_t *symbol)
3147 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3148 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3151 static type_t *parse_typeof(void)
3158 add_anchor_token(')');
3160 expression_t *expression = NULL;
3162 bool old_type_prop = in_type_prop;
3163 bool old_gcc_extension = in_gcc_extension;
3164 in_type_prop = true;
3166 while (token.type == T___extension__) {
3167 /* This can be a prefix to a typename or an expression. */
3169 in_gcc_extension = true;
3171 switch (token.type) {
3173 if (is_typedef_symbol(token.v.symbol)) {
3174 type = parse_typename();
3176 expression = parse_expression();
3177 type = expression->base.type;
3182 type = parse_typename();
3186 expression = parse_expression();
3187 type = expression->base.type;
3190 in_type_prop = old_type_prop;
3191 in_gcc_extension = old_gcc_extension;
3193 rem_anchor_token(')');
3196 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3197 typeof_type->typeoft.expression = expression;
3198 typeof_type->typeoft.typeof_type = type;
3205 typedef enum specifiers_t {
3206 SPECIFIER_SIGNED = 1 << 0,
3207 SPECIFIER_UNSIGNED = 1 << 1,
3208 SPECIFIER_LONG = 1 << 2,
3209 SPECIFIER_INT = 1 << 3,
3210 SPECIFIER_DOUBLE = 1 << 4,
3211 SPECIFIER_CHAR = 1 << 5,
3212 SPECIFIER_SHORT = 1 << 6,
3213 SPECIFIER_LONG_LONG = 1 << 7,
3214 SPECIFIER_FLOAT = 1 << 8,
3215 SPECIFIER_BOOL = 1 << 9,
3216 SPECIFIER_VOID = 1 << 10,
3217 SPECIFIER_INT8 = 1 << 11,
3218 SPECIFIER_INT16 = 1 << 12,
3219 SPECIFIER_INT32 = 1 << 13,
3220 SPECIFIER_INT64 = 1 << 14,
3221 SPECIFIER_INT128 = 1 << 15,
3222 SPECIFIER_COMPLEX = 1 << 16,
3223 SPECIFIER_IMAGINARY = 1 << 17,
3226 static type_t *create_builtin_type(symbol_t *const symbol,
3227 type_t *const real_type)
3229 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3230 type->builtin.symbol = symbol;
3231 type->builtin.real_type = real_type;
3233 type_t *result = typehash_insert(type);
3234 if (type != result) {
3241 static type_t *get_typedef_type(symbol_t *symbol)
3243 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3244 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3247 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3248 type->typedeft.typedefe = &entity->typedefe;
3254 * check for the allowed MS alignment values.
3256 static bool check_alignment_value(long long intvalue)
3258 if (intvalue < 1 || intvalue > 8192) {
3259 errorf(HERE, "illegal alignment value");
3262 unsigned v = (unsigned)intvalue;
3263 for (unsigned i = 1; i <= 8192; i += i) {
3267 errorf(HERE, "alignment must be power of two");
3271 #define DET_MOD(name, tag) do { \
3272 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3273 *modifiers |= tag; \
3276 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3278 decl_modifiers_t *modifiers = &specifiers->modifiers;
3281 if (token.type == T_restrict) {
3283 DET_MOD(restrict, DM_RESTRICT);
3285 } else if (token.type != T_IDENTIFIER)
3287 symbol_t *symbol = token.v.symbol;
3288 if (symbol == sym_align) {
3291 if (token.type != T_INTEGER)
3293 if (check_alignment_value(token.v.intvalue)) {
3294 if (specifiers->alignment != 0 && warning.other)
3295 warningf(HERE, "align used more than once");
3296 specifiers->alignment = (unsigned char)token.v.intvalue;
3300 } else if (symbol == sym_allocate) {
3303 if (token.type != T_IDENTIFIER)
3305 (void)token.v.symbol;
3307 } else if (symbol == sym_dllimport) {
3309 DET_MOD(dllimport, DM_DLLIMPORT);
3310 } else if (symbol == sym_dllexport) {
3312 DET_MOD(dllexport, DM_DLLEXPORT);
3313 } else if (symbol == sym_thread) {
3315 DET_MOD(thread, DM_THREAD);
3316 } else if (symbol == sym_naked) {
3318 DET_MOD(naked, DM_NAKED);
3319 } else if (symbol == sym_noinline) {
3321 DET_MOD(noinline, DM_NOINLINE);
3322 } else if (symbol == sym_noreturn) {
3324 DET_MOD(noreturn, DM_NORETURN);
3325 } else if (symbol == sym_nothrow) {
3327 DET_MOD(nothrow, DM_NOTHROW);
3328 } else if (symbol == sym_novtable) {
3330 DET_MOD(novtable, DM_NOVTABLE);
3331 } else if (symbol == sym_property) {
3335 bool is_get = false;
3336 if (token.type != T_IDENTIFIER)
3338 if (token.v.symbol == sym_get) {
3340 } else if (token.v.symbol == sym_put) {
3342 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3347 if (token.type != T_IDENTIFIER)
3350 if (specifiers->get_property_sym != NULL) {
3351 errorf(HERE, "get property name already specified");
3353 specifiers->get_property_sym = token.v.symbol;
3356 if (specifiers->put_property_sym != NULL) {
3357 errorf(HERE, "put property name already specified");
3359 specifiers->put_property_sym = token.v.symbol;
3363 if (token.type == ',') {
3370 } else if (symbol == sym_selectany) {
3372 DET_MOD(selectany, DM_SELECTANY);
3373 } else if (symbol == sym_uuid) {
3376 if (token.type != T_STRING_LITERAL)
3380 } else if (symbol == sym_deprecated) {
3382 if (specifiers->deprecated != 0 && warning.other)
3383 warningf(HERE, "deprecated used more than once");
3384 specifiers->deprecated = true;
3385 if (token.type == '(') {
3387 if (token.type == T_STRING_LITERAL) {
3388 specifiers->deprecated_string = token.v.string.begin;
3391 errorf(HERE, "string literal expected");
3395 } else if (symbol == sym_noalias) {
3397 DET_MOD(noalias, DM_NOALIAS);
3400 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3402 if (token.type == '(')
3406 if (token.type == ',')
3413 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3415 entity_t *entity = allocate_entity_zero(kind);
3416 entity->base.source_position = *HERE;
3417 entity->base.symbol = symbol;
3418 if (is_declaration(entity)) {
3419 entity->declaration.type = type_error_type;
3420 entity->declaration.implicit = true;
3421 } else if (kind == ENTITY_TYPEDEF) {
3422 entity->typedefe.type = type_error_type;
3424 record_entity(entity, false);
3428 static void parse_microsoft_based(based_spec_t *based_spec)
3430 if (token.type != T_IDENTIFIER) {
3431 parse_error_expected("while parsing __based", T_IDENTIFIER, NULL);
3434 symbol_t *symbol = token.v.symbol;
3435 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3437 if (entity == NULL || entity->base.kind != ENTITY_VARIABLE) {
3438 errorf(HERE, "'%Y' is not a variable name.", symbol);
3439 entity = create_error_entity(symbol, ENTITY_VARIABLE);
3441 variable_t *variable = &entity->variable;
3443 if (based_spec->base_variable != NULL) {
3444 errorf(HERE, "__based type qualifier specified more than once");
3446 based_spec->source_position = token.source_position;
3447 based_spec->base_variable = variable;
3449 type_t *const type = variable->base.type;
3451 if (is_type_valid(type)) {
3452 if (! is_type_pointer(skip_typeref(type))) {
3453 errorf(HERE, "variable in __based modifier must have pointer type instead of '%T'", type);
3455 if (variable->base.base.parent_scope != file_scope) {
3456 errorf(HERE, "a nonstatic local variable may not be used in a __based specification");
3464 * Finish the construction of a struct type by calculating
3465 * its size, offsets, alignment.
3467 static void finish_struct_type(compound_type_t *type)
3469 assert(type->compound != NULL);
3471 compound_t *compound = type->compound;
3472 if (!compound->complete)
3477 il_alignment_t alignment = 1;
3478 bool need_pad = false;
3480 entity_t *entry = compound->members.entities;
3481 for (; entry != NULL; entry = entry->base.next) {
3482 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3485 type_t *m_type = skip_typeref(entry->declaration.type);
3486 if (! is_type_valid(m_type)) {
3487 /* simply ignore errors here */
3490 il_alignment_t m_alignment = m_type->base.alignment;
3491 if (m_alignment > alignment)
3492 alignment = m_alignment;
3494 offset = (size + m_alignment - 1) & -m_alignment;
3498 entry->compound_member.offset = offset;
3499 size = offset + m_type->base.size;
3501 if (type->base.alignment != 0) {
3502 alignment = type->base.alignment;
3505 offset = (size + alignment - 1) & -alignment;
3509 if (warning.padded && need_pad) {
3510 warningf(&compound->base.source_position,
3511 "'%#T' needs padding", type, compound->base.symbol);
3513 if (warning.packed && !need_pad) {
3514 warningf(&compound->base.source_position,
3515 "superfluous packed attribute on '%#T'",
3516 type, compound->base.symbol);
3519 type->base.size = offset;
3520 type->base.alignment = alignment;
3524 * Finish the construction of an union type by calculating
3525 * its size and alignment.
3527 static void finish_union_type(compound_type_t *type)
3529 assert(type->compound != NULL);
3531 compound_t *compound = type->compound;
3532 if (! compound->complete)
3536 il_alignment_t alignment = 1;
3538 entity_t *entry = compound->members.entities;
3539 for (; entry != NULL; entry = entry->base.next) {
3540 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3543 type_t *m_type = skip_typeref(entry->declaration.type);
3544 if (! is_type_valid(m_type))
3547 entry->compound_member.offset = 0;
3548 if (m_type->base.size > size)
3549 size = m_type->base.size;
3550 if (m_type->base.alignment > alignment)
3551 alignment = m_type->base.alignment;
3553 if (type->base.alignment != 0) {
3554 alignment = type->base.alignment;
3556 size = (size + alignment - 1) & -alignment;
3557 type->base.size = size;
3558 type->base.alignment = alignment;
3561 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3563 type_t *type = NULL;
3564 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3565 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3566 unsigned type_specifiers = 0;
3567 bool newtype = false;
3568 bool saw_error = false;
3569 bool old_gcc_extension = in_gcc_extension;
3571 specifiers->source_position = token.source_position;
3574 specifiers->modifiers
3575 |= parse_attributes(&specifiers->gnu_attributes);
3576 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3577 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3579 switch (token.type) {
3581 #define MATCH_STORAGE_CLASS(token, class) \
3583 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3584 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3586 specifiers->storage_class = class; \
3587 if (specifiers->thread_local) \
3588 goto check_thread_storage_class; \
3592 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3593 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3594 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3595 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3596 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3601 add_anchor_token(')');
3602 parse_microsoft_extended_decl_modifier(specifiers);
3603 rem_anchor_token(')');
3608 if (specifiers->thread_local) {
3609 errorf(HERE, "duplicate '__thread'");
3611 specifiers->thread_local = true;
3612 check_thread_storage_class:
3613 switch (specifiers->storage_class) {
3614 case STORAGE_CLASS_EXTERN:
3615 case STORAGE_CLASS_NONE:
3616 case STORAGE_CLASS_STATIC:
3620 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
3621 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
3622 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
3623 wrong_thread_stoarge_class:
3624 errorf(HERE, "'__thread' used with '%s'", wrong);
3631 /* type qualifiers */
3632 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3634 qualifiers |= qualifier; \
3638 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3639 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3640 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3641 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3642 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3643 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3644 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3645 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3647 case T___extension__:
3649 in_gcc_extension = true;
3652 /* type specifiers */
3653 #define MATCH_SPECIFIER(token, specifier, name) \
3655 if (type_specifiers & specifier) { \
3656 errorf(HERE, "multiple " name " type specifiers given"); \
3658 type_specifiers |= specifier; \
3663 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3664 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3665 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3666 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3667 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3668 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3669 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3670 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3671 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3672 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3673 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3674 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3675 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3676 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3677 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3678 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3679 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3681 case T__forceinline:
3682 /* only in microsoft mode */
3683 specifiers->modifiers |= DM_FORCEINLINE;
3688 specifiers->is_inline = true;
3692 if (type_specifiers & SPECIFIER_LONG_LONG) {
3693 errorf(HERE, "multiple type specifiers given");
3694 } else if (type_specifiers & SPECIFIER_LONG) {
3695 type_specifiers |= SPECIFIER_LONG_LONG;
3697 type_specifiers |= SPECIFIER_LONG;
3703 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3705 type->compound.compound = parse_compound_type_specifier(true);
3706 finish_struct_type(&type->compound);
3710 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3711 type->compound.compound = parse_compound_type_specifier(false);
3712 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3713 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3714 finish_union_type(&type->compound);
3718 type = parse_enum_specifier();
3721 type = parse_typeof();
3723 case T___builtin_va_list:
3724 type = duplicate_type(type_valist);
3728 case T_IDENTIFIER: {
3729 /* only parse identifier if we haven't found a type yet */
3730 if (type != NULL || type_specifiers != 0) {
3731 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3732 * declaration, so it doesn't generate errors about expecting '(' or
3734 switch (look_ahead(1)->type) {
3741 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3745 errorf(HERE, "discarding stray '%K' in declaration specifier", &token);
3750 goto finish_specifiers;
3754 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3755 if (typedef_type == NULL) {
3756 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3757 * declaration, so it doesn't generate 'implicit int' followed by more
3758 * errors later on. */
3759 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3765 errorf(HERE, "'%K' does not name a type", &token);
3768 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3770 type = allocate_type_zero(TYPE_TYPEDEF);
3771 type->typedeft.typedefe = &entity->typedefe;
3775 if (la1_type == '&' || la1_type == '*')
3776 goto finish_specifiers;
3781 goto finish_specifiers;
3786 type = typedef_type;
3790 /* function specifier */
3792 goto finish_specifiers;
3797 in_gcc_extension = old_gcc_extension;
3799 if (type == NULL || (saw_error && type_specifiers != 0)) {
3800 atomic_type_kind_t atomic_type;
3802 /* match valid basic types */
3803 switch (type_specifiers) {
3804 case SPECIFIER_VOID:
3805 atomic_type = ATOMIC_TYPE_VOID;
3807 case SPECIFIER_CHAR:
3808 atomic_type = ATOMIC_TYPE_CHAR;
3810 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3811 atomic_type = ATOMIC_TYPE_SCHAR;
3813 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3814 atomic_type = ATOMIC_TYPE_UCHAR;
3816 case SPECIFIER_SHORT:
3817 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3818 case SPECIFIER_SHORT | SPECIFIER_INT:
3819 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3820 atomic_type = ATOMIC_TYPE_SHORT;
3822 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3823 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3824 atomic_type = ATOMIC_TYPE_USHORT;
3827 case SPECIFIER_SIGNED:
3828 case SPECIFIER_SIGNED | SPECIFIER_INT:
3829 atomic_type = ATOMIC_TYPE_INT;
3831 case SPECIFIER_UNSIGNED:
3832 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3833 atomic_type = ATOMIC_TYPE_UINT;
3835 case SPECIFIER_LONG:
3836 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3837 case SPECIFIER_LONG | SPECIFIER_INT:
3838 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3839 atomic_type = ATOMIC_TYPE_LONG;
3841 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3842 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3843 atomic_type = ATOMIC_TYPE_ULONG;
3846 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3847 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3848 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3849 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3851 atomic_type = ATOMIC_TYPE_LONGLONG;
3852 goto warn_about_long_long;
3854 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3855 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3857 atomic_type = ATOMIC_TYPE_ULONGLONG;
3858 warn_about_long_long:
3859 if (warning.long_long) {
3860 warningf(&specifiers->source_position,
3861 "ISO C90 does not support 'long long'");
3865 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3866 atomic_type = unsigned_int8_type_kind;
3869 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3870 atomic_type = unsigned_int16_type_kind;
3873 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3874 atomic_type = unsigned_int32_type_kind;
3877 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3878 atomic_type = unsigned_int64_type_kind;
3881 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3882 atomic_type = unsigned_int128_type_kind;
3885 case SPECIFIER_INT8:
3886 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3887 atomic_type = int8_type_kind;
3890 case SPECIFIER_INT16:
3891 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3892 atomic_type = int16_type_kind;
3895 case SPECIFIER_INT32:
3896 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3897 atomic_type = int32_type_kind;
3900 case SPECIFIER_INT64:
3901 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3902 atomic_type = int64_type_kind;
3905 case SPECIFIER_INT128:
3906 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3907 atomic_type = int128_type_kind;
3910 case SPECIFIER_FLOAT:
3911 atomic_type = ATOMIC_TYPE_FLOAT;
3913 case SPECIFIER_DOUBLE:
3914 atomic_type = ATOMIC_TYPE_DOUBLE;
3916 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3917 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3919 case SPECIFIER_BOOL:
3920 atomic_type = ATOMIC_TYPE_BOOL;
3922 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3923 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3924 atomic_type = ATOMIC_TYPE_FLOAT;
3926 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3927 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3928 atomic_type = ATOMIC_TYPE_DOUBLE;
3930 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3931 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3932 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3935 /* invalid specifier combination, give an error message */
3936 if (type_specifiers == 0) {
3940 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3941 if (!(c_mode & _CXX) && !strict_mode) {
3942 if (warning.implicit_int) {
3943 warningf(HERE, "no type specifiers in declaration, using 'int'");
3945 atomic_type = ATOMIC_TYPE_INT;
3948 errorf(HERE, "no type specifiers given in declaration");
3950 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3951 (type_specifiers & SPECIFIER_UNSIGNED)) {
3952 errorf(HERE, "signed and unsigned specifiers given");
3953 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3954 errorf(HERE, "only integer types can be signed or unsigned");
3956 errorf(HERE, "multiple datatypes in declaration");
3961 if (type_specifiers & SPECIFIER_COMPLEX) {
3962 type = allocate_type_zero(TYPE_COMPLEX);
3963 type->complex.akind = atomic_type;
3964 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3965 type = allocate_type_zero(TYPE_IMAGINARY);
3966 type->imaginary.akind = atomic_type;
3968 type = allocate_type_zero(TYPE_ATOMIC);
3969 type->atomic.akind = atomic_type;
3972 } else if (type_specifiers != 0) {
3973 errorf(HERE, "multiple datatypes in declaration");
3976 /* FIXME: check type qualifiers here */
3978 type->base.qualifiers = qualifiers;
3979 type->base.modifiers = modifiers;
3981 type_t *result = typehash_insert(type);
3982 if (newtype && result != type) {
3986 specifiers->type = result;
3990 specifiers->type = type_error_type;
3994 static type_qualifiers_t parse_type_qualifiers(void)
3996 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3999 switch (token.type) {
4000 /* type qualifiers */
4001 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
4002 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
4003 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
4004 /* microsoft extended type modifiers */
4005 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
4006 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
4007 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
4008 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
4009 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
4018 * Parses an K&R identifier list
4020 static void parse_identifier_list(scope_t *scope)
4023 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
4024 entity->base.source_position = token.source_position;
4025 entity->base.namespc = NAMESPACE_NORMAL;
4026 entity->base.symbol = token.v.symbol;
4027 /* a K&R parameter has no type, yet */
4030 append_entity(scope, entity);
4032 if (token.type != ',') {
4036 } while (token.type == T_IDENTIFIER);
4039 static entity_t *parse_parameter(void)
4041 declaration_specifiers_t specifiers;
4042 memset(&specifiers, 0, sizeof(specifiers));
4044 parse_declaration_specifiers(&specifiers);
4046 entity_t *entity = parse_declarator(&specifiers,
4047 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
4048 anonymous_entity = NULL;
4052 static void semantic_parameter_incomplete(const entity_t *entity)
4054 assert(entity->kind == ENTITY_PARAMETER);
4056 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
4057 * list in a function declarator that is part of a
4058 * definition of that function shall not have
4059 * incomplete type. */
4060 type_t *type = skip_typeref(entity->declaration.type);
4061 if (is_type_incomplete(type)) {
4062 errorf(&entity->base.source_position,
4063 "parameter '%Y' has incomplete type %T", entity->base.symbol,
4064 entity->declaration.type);
4069 * Parses function type parameters (and optionally creates variable_t entities
4070 * for them in a scope)
4072 static void parse_parameters(function_type_t *type, scope_t *scope)
4075 add_anchor_token(')');
4076 int saved_comma_state = save_and_reset_anchor_state(',');
4078 if (token.type == T_IDENTIFIER &&
4079 !is_typedef_symbol(token.v.symbol)) {
4080 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4081 if (la1_type == ',' || la1_type == ')') {
4082 type->kr_style_parameters = true;
4083 parse_identifier_list(scope);
4084 goto parameters_finished;
4088 if (token.type == ')') {
4089 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4090 if (!(c_mode & _CXX))
4091 type->unspecified_parameters = true;
4092 goto parameters_finished;
4095 function_parameter_t *parameter;
4096 function_parameter_t *last_parameter = NULL;
4099 switch (token.type) {
4102 type->variadic = true;
4103 goto parameters_finished;
4106 case T___extension__:
4109 entity_t *entity = parse_parameter();
4110 if (entity->kind == ENTITY_TYPEDEF) {
4111 errorf(&entity->base.source_position,
4112 "typedef not allowed as function parameter");
4115 assert(is_declaration(entity));
4117 /* func(void) is not a parameter */
4118 if (last_parameter == NULL
4119 && token.type == ')'
4120 && entity->base.symbol == NULL
4121 && skip_typeref(entity->declaration.type) == type_void) {
4122 goto parameters_finished;
4124 semantic_parameter_incomplete(entity);
4126 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4127 memset(parameter, 0, sizeof(parameter[0]));
4128 parameter->type = entity->declaration.type;
4130 if (scope != NULL) {
4131 append_entity(scope, entity);
4134 if (last_parameter != NULL) {
4135 last_parameter->next = parameter;
4137 type->parameters = parameter;
4139 last_parameter = parameter;
4144 goto parameters_finished;
4146 if (token.type != ',') {
4147 goto parameters_finished;
4153 parameters_finished:
4154 rem_anchor_token(')');
4158 restore_anchor_state(',', saved_comma_state);
4161 typedef enum construct_type_kind_t {
4164 CONSTRUCT_REFERENCE,
4167 } construct_type_kind_t;
4169 typedef struct construct_type_t construct_type_t;
4170 struct construct_type_t {
4171 construct_type_kind_t kind;
4172 construct_type_t *next;
4175 typedef struct parsed_pointer_t parsed_pointer_t;
4176 struct parsed_pointer_t {
4177 construct_type_t construct_type;
4178 type_qualifiers_t type_qualifiers;
4179 variable_t *base_variable; /**< MS __based extension. */
4182 typedef struct parsed_reference_t parsed_reference_t;
4183 struct parsed_reference_t {
4184 construct_type_t construct_type;
4187 typedef struct construct_function_type_t construct_function_type_t;
4188 struct construct_function_type_t {
4189 construct_type_t construct_type;
4190 type_t *function_type;
4193 typedef struct parsed_array_t parsed_array_t;
4194 struct parsed_array_t {
4195 construct_type_t construct_type;
4196 type_qualifiers_t type_qualifiers;
4202 typedef struct construct_base_type_t construct_base_type_t;
4203 struct construct_base_type_t {
4204 construct_type_t construct_type;
4208 static construct_type_t *parse_pointer_declarator(variable_t *base_variable)
4212 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4213 memset(pointer, 0, sizeof(pointer[0]));
4214 pointer->construct_type.kind = CONSTRUCT_POINTER;
4215 pointer->type_qualifiers = parse_type_qualifiers();
4216 pointer->base_variable = base_variable;
4218 return &pointer->construct_type;
4221 static construct_type_t *parse_reference_declarator(void)
4225 parsed_reference_t *reference = obstack_alloc(&temp_obst, sizeof(reference[0]));
4226 memset(reference, 0, sizeof(reference[0]));
4227 reference->construct_type.kind = CONSTRUCT_REFERENCE;
4229 return (construct_type_t*)reference;
4232 static construct_type_t *parse_array_declarator(void)
4235 add_anchor_token(']');
4237 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4238 memset(array, 0, sizeof(array[0]));
4239 array->construct_type.kind = CONSTRUCT_ARRAY;
4241 if (token.type == T_static) {
4242 array->is_static = true;
4246 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4247 if (type_qualifiers != 0) {
4248 if (token.type == T_static) {
4249 array->is_static = true;
4253 array->type_qualifiers = type_qualifiers;
4255 if (token.type == '*' && look_ahead(1)->type == ']') {
4256 array->is_variable = true;
4258 } else if (token.type != ']') {
4259 array->size = parse_assignment_expression();
4262 rem_anchor_token(']');
4266 return &array->construct_type;
4269 static construct_type_t *parse_function_declarator(scope_t *scope,
4270 decl_modifiers_t modifiers)
4272 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4273 function_type_t *ftype = &type->function;
4275 ftype->linkage = current_linkage;
4277 switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
4278 case DM_NONE: break;
4279 case DM_CDECL: ftype->calling_convention = CC_CDECL; break;
4280 case DM_STDCALL: ftype->calling_convention = CC_STDCALL; break;
4281 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
4282 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
4285 errorf(HERE, "multiple calling conventions in declaration");
4289 parse_parameters(ftype, scope);
4291 construct_function_type_t *construct_function_type =
4292 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4293 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4294 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4295 construct_function_type->function_type = type;
4297 return &construct_function_type->construct_type;
4300 typedef struct parse_declarator_env_t {
4301 decl_modifiers_t modifiers;
4303 source_position_t source_position;
4305 } parse_declarator_env_t;
4307 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4308 bool may_be_abstract)
4310 /* construct a single linked list of construct_type_t's which describe
4311 * how to construct the final declarator type */
4312 construct_type_t *first = NULL;
4313 construct_type_t *last = NULL;
4314 gnu_attribute_t *attributes = NULL;
4316 decl_modifiers_t modifiers = parse_attributes(&attributes);
4318 /* MS __based extension */
4319 based_spec_t base_spec;
4320 base_spec.base_variable = NULL;
4323 construct_type_t *type;
4324 switch (token.type) {
4326 if (!(c_mode & _CXX))
4327 errorf(HERE, "references are only available for C++");
4328 if (base_spec.base_variable != NULL && warning.other) {
4329 warningf(&base_spec.source_position,
4330 "__based does not precede a pointer operator, ignored");
4332 type = parse_reference_declarator();
4334 base_spec.base_variable = NULL;
4338 type = parse_pointer_declarator(base_spec.base_variable);
4340 base_spec.base_variable = NULL;
4346 add_anchor_token(')');
4347 parse_microsoft_based(&base_spec);
4348 rem_anchor_token(')');
4353 goto ptr_operator_end;
4364 /* TODO: find out if this is correct */
4365 modifiers |= parse_attributes(&attributes);
4368 if (base_spec.base_variable != NULL && warning.other) {
4369 warningf(&base_spec.source_position,
4370 "__based does not precede a pointer operator, ignored");
4374 modifiers |= env->modifiers;
4375 env->modifiers = modifiers;
4378 construct_type_t *inner_types = NULL;
4380 switch (token.type) {
4383 errorf(HERE, "no identifier expected in typename");
4385 env->symbol = token.v.symbol;
4386 env->source_position = token.source_position;
4392 add_anchor_token(')');
4393 inner_types = parse_inner_declarator(env, may_be_abstract);
4394 if (inner_types != NULL) {
4395 /* All later declarators only modify the return type */
4398 rem_anchor_token(')');
4402 if (may_be_abstract)
4404 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4409 construct_type_t *p = last;
4412 construct_type_t *type;
4413 switch (token.type) {
4415 scope_t *scope = NULL;
4417 scope = &env->parameters;
4419 type = parse_function_declarator(scope, modifiers);
4423 type = parse_array_declarator();
4426 goto declarator_finished;
4429 /* insert in the middle of the list (behind p) */
4431 type->next = p->next;
4442 declarator_finished:
4443 /* append inner_types at the end of the list, we don't to set last anymore
4444 * as it's not needed anymore */
4446 assert(first == NULL);
4447 first = inner_types;
4449 last->next = inner_types;
4457 static void parse_declaration_attributes(entity_t *entity)
4459 gnu_attribute_t *attributes = NULL;
4460 decl_modifiers_t modifiers = parse_attributes(&attributes);
4466 if (entity->kind == ENTITY_TYPEDEF) {
4467 modifiers |= entity->typedefe.modifiers;
4468 type = entity->typedefe.type;
4470 assert(is_declaration(entity));
4471 modifiers |= entity->declaration.modifiers;
4472 type = entity->declaration.type;
4477 /* handle these strange/stupid mode attributes */
4478 gnu_attribute_t *attribute = attributes;
4479 for ( ; attribute != NULL; attribute = attribute->next) {
4480 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4483 atomic_type_kind_t akind = attribute->u.akind;
4484 if (!is_type_signed(type)) {
4486 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4487 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4488 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4489 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4491 panic("invalid akind in mode attribute");
4495 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_SCHAR; break;
4496 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_SHORT; break;
4497 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_INT; break;
4498 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_LONGLONG; break;
4500 panic("invalid akind in mode attribute");
4504 type = make_atomic_type(akind, type->base.qualifiers);
4507 type_modifiers_t type_modifiers = type->base.modifiers;
4508 if (modifiers & DM_TRANSPARENT_UNION)
4509 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4511 if (type->base.modifiers != type_modifiers) {
4512 type_t *copy = duplicate_type(type);
4513 copy->base.modifiers = type_modifiers;
4515 type = typehash_insert(copy);
4517 obstack_free(type_obst, copy);
4521 if (entity->kind == ENTITY_TYPEDEF) {
4522 entity->typedefe.type = type;
4523 entity->typedefe.modifiers = modifiers;
4525 entity->declaration.type = type;
4526 entity->declaration.modifiers = modifiers;
4530 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
4532 construct_type_t *iter = construct_list;
4533 for (; iter != NULL; iter = iter->next) {
4534 switch (iter->kind) {
4535 case CONSTRUCT_INVALID:
4536 internal_errorf(HERE, "invalid type construction found");
4537 case CONSTRUCT_FUNCTION: {
4538 construct_function_type_t *construct_function_type
4539 = (construct_function_type_t*) iter;
4541 type_t *function_type = construct_function_type->function_type;
4543 function_type->function.return_type = type;
4545 type_t *skipped_return_type = skip_typeref(type);
4547 if (is_type_function(skipped_return_type)) {
4548 errorf(HERE, "function returning function is not allowed");
4549 } else if (is_type_array(skipped_return_type)) {
4550 errorf(HERE, "function returning array is not allowed");
4552 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4554 "type qualifiers in return type of function type are meaningless");
4558 type = function_type;
4562 case CONSTRUCT_POINTER: {
4563 if (is_type_reference(skip_typeref(type)))
4564 errorf(HERE, "cannot declare a pointer to reference");
4566 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4567 type = make_based_pointer_type(type, parsed_pointer->type_qualifiers, parsed_pointer->base_variable);
4571 case CONSTRUCT_REFERENCE:
4572 if (is_type_reference(skip_typeref(type)))
4573 errorf(HERE, "cannot declare a reference to reference");
4575 type = make_reference_type(type);
4578 case CONSTRUCT_ARRAY: {
4579 if (is_type_reference(skip_typeref(type)))
4580 errorf(HERE, "cannot declare an array of references");
4582 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4583 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4585 expression_t *size_expression = parsed_array->size;
4586 if (size_expression != NULL) {
4588 = create_implicit_cast(size_expression, type_size_t);
4591 array_type->base.qualifiers = parsed_array->type_qualifiers;
4592 array_type->array.element_type = type;
4593 array_type->array.is_static = parsed_array->is_static;
4594 array_type->array.is_variable = parsed_array->is_variable;
4595 array_type->array.size_expression = size_expression;
4597 if (size_expression != NULL) {
4598 if (is_constant_expression(size_expression)) {
4599 array_type->array.size_constant = true;
4600 array_type->array.size
4601 = fold_constant(size_expression);
4603 array_type->array.is_vla = true;
4607 type_t *skipped_type = skip_typeref(type);
4609 if (is_type_incomplete(skipped_type)) {
4610 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4611 } else if (is_type_function(skipped_type)) {
4612 errorf(HERE, "array of functions is not allowed");
4619 type_t *hashed_type = typehash_insert(type);
4620 if (hashed_type != type) {
4621 /* the function type was constructed earlier freeing it here will
4622 * destroy other types... */
4623 if (iter->kind != CONSTRUCT_FUNCTION) {
4633 static type_t *automatic_type_conversion(type_t *orig_type);
4635 static type_t *semantic_parameter(const source_position_t *pos,
4637 const declaration_specifiers_t *specifiers,
4640 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
4641 * shall be adjusted to ``qualified pointer to type'',
4643 * §6.7.5.3:8 A declaration of a parameter as ``function returning
4644 * type'' shall be adjusted to ``pointer to function
4645 * returning type'', as in 6.3.2.1. */
4646 type = automatic_type_conversion(type);
4648 if (specifiers->is_inline && is_type_valid(type)) {
4649 errorf(pos, "parameter '%Y' declared 'inline'", symbol);
4652 /* §6.9.1:6 The declarations in the declaration list shall contain
4653 * no storage-class specifier other than register and no
4654 * initializations. */
4655 if (specifiers->thread_local || (
4656 specifiers->storage_class != STORAGE_CLASS_NONE &&
4657 specifiers->storage_class != STORAGE_CLASS_REGISTER)
4659 errorf(pos, "invalid storage class for parameter '%Y'", symbol);
4662 /* delay test for incomplete type, because we might have (void)
4663 * which is legal but incomplete... */
4668 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4669 declarator_flags_t flags)
4671 parse_declarator_env_t env;
4672 memset(&env, 0, sizeof(env));
4673 env.modifiers = specifiers->modifiers;
4675 construct_type_t *construct_type =
4676 parse_inner_declarator(&env, (flags & DECL_MAY_BE_ABSTRACT) != 0);
4678 construct_declarator_type(construct_type, specifiers->type);
4679 type_t *type = skip_typeref(orig_type);
4681 if (construct_type != NULL) {
4682 obstack_free(&temp_obst, construct_type);
4686 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4687 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4688 entity->base.symbol = env.symbol;
4689 entity->base.source_position = env.source_position;
4690 entity->typedefe.type = orig_type;
4692 if (anonymous_entity != NULL) {
4693 if (is_type_compound(type)) {
4694 assert(anonymous_entity->compound.alias == NULL);
4695 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4696 anonymous_entity->kind == ENTITY_UNION);
4697 anonymous_entity->compound.alias = entity;
4698 anonymous_entity = NULL;
4699 } else if (is_type_enum(type)) {
4700 assert(anonymous_entity->enume.alias == NULL);
4701 assert(anonymous_entity->kind == ENTITY_ENUM);
4702 anonymous_entity->enume.alias = entity;
4703 anonymous_entity = NULL;
4707 /* create a declaration type entity */
4708 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
4709 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4711 if (specifiers->is_inline && is_type_valid(type)) {
4712 errorf(&env.source_position,
4713 "compound member '%Y' declared 'inline'", env.symbol);
4716 if (specifiers->thread_local ||
4717 specifiers->storage_class != STORAGE_CLASS_NONE) {
4718 errorf(&env.source_position,
4719 "compound member '%Y' must have no storage class",
4722 } else if (flags & DECL_IS_PARAMETER) {
4723 orig_type = semantic_parameter(&env.source_position, type,
4724 specifiers, env.symbol);
4726 entity = allocate_entity_zero(ENTITY_PARAMETER);
4727 } else if (is_type_function(type)) {
4728 entity = allocate_entity_zero(ENTITY_FUNCTION);
4730 entity->function.is_inline = specifiers->is_inline;
4731 entity->function.parameters = env.parameters;
4733 if (specifiers->thread_local || (
4734 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4735 specifiers->storage_class != STORAGE_CLASS_NONE &&
4736 specifiers->storage_class != STORAGE_CLASS_STATIC)
4738 errorf(&env.source_position,
4739 "invalid storage class for function '%Y'", env.symbol);
4742 entity = allocate_entity_zero(ENTITY_VARIABLE);
4744 entity->variable.get_property_sym = specifiers->get_property_sym;
4745 entity->variable.put_property_sym = specifiers->put_property_sym;
4746 if (specifiers->alignment != 0) {
4747 /* TODO: add checks here */
4748 entity->variable.alignment = specifiers->alignment;
4751 if (specifiers->is_inline && is_type_valid(type)) {
4752 errorf(&env.source_position,
4753 "variable '%Y' declared 'inline'", env.symbol);
4756 entity->variable.thread_local = specifiers->thread_local;
4758 bool invalid_storage_class = false;
4759 if (current_scope == file_scope) {
4760 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4761 specifiers->storage_class != STORAGE_CLASS_NONE &&
4762 specifiers->storage_class != STORAGE_CLASS_STATIC) {
4763 invalid_storage_class = true;
4766 if (specifiers->thread_local &&
4767 specifiers->storage_class == STORAGE_CLASS_NONE) {
4768 invalid_storage_class = true;
4771 if (invalid_storage_class) {
4772 errorf(&env.source_position,
4773 "invalid storage class for variable '%Y'", env.symbol);
4777 entity->base.source_position = env.source_position;
4778 entity->base.symbol = env.symbol;
4779 entity->base.namespc = NAMESPACE_NORMAL;
4780 entity->declaration.type = orig_type;
4781 entity->declaration.modifiers = env.modifiers;
4782 entity->declaration.deprecated_string = specifiers->deprecated_string;
4784 storage_class_t storage_class = specifiers->storage_class;
4785 entity->declaration.declared_storage_class = storage_class;
4787 if (storage_class == STORAGE_CLASS_NONE && current_scope != file_scope)
4788 storage_class = STORAGE_CLASS_AUTO;
4789 entity->declaration.storage_class = storage_class;
4792 parse_declaration_attributes(entity);
4797 static type_t *parse_abstract_declarator(type_t *base_type)
4799 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4801 type_t *result = construct_declarator_type(construct_type, base_type);
4802 if (construct_type != NULL) {
4803 obstack_free(&temp_obst, construct_type);
4810 * Check if the declaration of main is suspicious. main should be a
4811 * function with external linkage, returning int, taking either zero
4812 * arguments, two, or three arguments of appropriate types, ie.
4814 * int main([ int argc, char **argv [, char **env ] ]).
4816 * @param decl the declaration to check
4817 * @param type the function type of the declaration
4819 static void check_type_of_main(const entity_t *entity)
4821 const source_position_t *pos = &entity->base.source_position;
4822 if (entity->kind != ENTITY_FUNCTION) {
4823 warningf(pos, "'main' is not a function");
4827 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4828 warningf(pos, "'main' is normally a non-static function");
4831 type_t *type = skip_typeref(entity->declaration.type);
4832 assert(is_type_function(type));
4834 function_type_t *func_type = &type->function;
4835 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4836 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4837 func_type->return_type);
4839 const function_parameter_t *parm = func_type->parameters;
4841 type_t *const first_type = parm->type;
4842 if (!types_compatible(skip_typeref(first_type), type_int)) {
4844 "first argument of 'main' should be 'int', but is '%T'",
4849 type_t *const second_type = parm->type;
4850 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4851 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4855 type_t *const third_type = parm->type;
4856 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4857 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4861 goto warn_arg_count;
4865 warningf(pos, "'main' takes only zero, two or three arguments");
4871 * Check if a symbol is the equal to "main".
4873 static bool is_sym_main(const symbol_t *const sym)
4875 return strcmp(sym->string, "main") == 0;
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 /* can happen in error cases */
4900 entity_t *previous_entity = get_entity(symbol, namespc);
4901 /* pushing the same entity twice will break the stack structure */
4902 assert(previous_entity != entity);
4904 if (entity->kind == ENTITY_FUNCTION) {
4905 type_t *const orig_type = entity->declaration.type;
4906 type_t *const type = skip_typeref(orig_type);
4908 assert(is_type_function(type));
4909 if (type->function.unspecified_parameters &&
4910 warning.strict_prototypes &&
4911 previous_entity == NULL) {
4912 warningf(pos, "function declaration '%#T' is not a prototype",
4916 if (warning.main && current_scope == file_scope
4917 && is_sym_main(symbol)) {
4918 check_type_of_main(entity);
4922 if (is_declaration(entity) &&
4923 warning.nested_externs &&
4924 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4925 current_scope != file_scope) {
4926 warningf(pos, "nested extern declaration of '%#T'",
4927 entity->declaration.type, symbol);
4930 if (previous_entity != NULL &&
4931 previous_entity->base.parent_scope == ¤t_function->parameters &&
4932 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4933 assert(previous_entity->kind == ENTITY_PARAMETER);
4935 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4936 entity->declaration.type, symbol,
4937 previous_entity->declaration.type, symbol,
4938 &previous_entity->base.source_position);
4942 if (previous_entity != NULL &&
4943 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) {
4950 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
4951 symbol, &previous_entity->base.source_position);
4954 if (previous_entity->kind == ENTITY_TYPEDEF) {
4955 /* TODO: C++ allows this for exactly the same type */
4956 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
4957 symbol, &previous_entity->base.source_position);
4961 /* at this point we should have only VARIABLES or FUNCTIONS */
4962 assert(is_declaration(previous_entity) && is_declaration(entity));
4964 declaration_t *const prev_decl = &previous_entity->declaration;
4965 declaration_t *const decl = &entity->declaration;
4967 /* can happen for K&R style declarations */
4968 if (prev_decl->type == NULL &&
4969 previous_entity->kind == ENTITY_PARAMETER &&
4970 entity->kind == ENTITY_PARAMETER) {
4971 prev_decl->type = decl->type;
4972 prev_decl->storage_class = decl->storage_class;
4973 prev_decl->declared_storage_class = decl->declared_storage_class;
4974 prev_decl->modifiers = decl->modifiers;
4975 prev_decl->deprecated_string = decl->deprecated_string;
4976 return previous_entity;
4979 type_t *const orig_type = decl->type;
4980 assert(orig_type != NULL);
4981 type_t *const type = skip_typeref(orig_type);
4982 type_t * prev_type = skip_typeref(prev_decl->type);
4984 if (!types_compatible(type, prev_type)) {
4986 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4987 orig_type, symbol, prev_decl->type, symbol,
4988 &previous_entity->base.source_position);
4990 unsigned old_storage_class = prev_decl->storage_class;
4991 if (warning.redundant_decls &&
4994 !(prev_decl->modifiers & DM_USED) &&
4995 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4996 warningf(&previous_entity->base.source_position,
4997 "unnecessary static forward declaration for '%#T'",
4998 prev_decl->type, symbol);
5001 unsigned new_storage_class = decl->storage_class;
5002 if (is_type_incomplete(prev_type)) {
5003 prev_decl->type = type;
5007 /* pretend no storage class means extern for function
5008 * declarations (except if the previous declaration is neither
5009 * none nor extern) */
5010 if (entity->kind == ENTITY_FUNCTION) {
5011 if (prev_type->function.unspecified_parameters) {
5012 prev_decl->type = type;
5016 switch (old_storage_class) {
5017 case STORAGE_CLASS_NONE:
5018 old_storage_class = STORAGE_CLASS_EXTERN;
5021 case STORAGE_CLASS_EXTERN:
5022 if (is_definition) {
5023 if (warning.missing_prototypes &&
5024 prev_type->function.unspecified_parameters &&
5025 !is_sym_main(symbol)) {
5026 warningf(pos, "no previous prototype for '%#T'",
5029 } else if (new_storage_class == STORAGE_CLASS_NONE) {
5030 new_storage_class = STORAGE_CLASS_EXTERN;
5039 if (old_storage_class == STORAGE_CLASS_EXTERN &&
5040 new_storage_class == STORAGE_CLASS_EXTERN) {
5041 warn_redundant_declaration:
5042 if (!is_definition &&
5043 warning.redundant_decls &&
5044 is_type_valid(prev_type) &&
5045 strcmp(previous_entity->base.source_position.input_name,
5046 "<builtin>") != 0) {
5048 "redundant declaration for '%Y' (declared %P)",
5049 symbol, &previous_entity->base.source_position);
5051 } else if (current_function == NULL) {
5052 if (old_storage_class != STORAGE_CLASS_STATIC &&
5053 new_storage_class == STORAGE_CLASS_STATIC) {
5055 "static declaration of '%Y' follows non-static declaration (declared %P)",
5056 symbol, &previous_entity->base.source_position);
5057 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
5058 prev_decl->storage_class = STORAGE_CLASS_NONE;
5059 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
5061 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
5063 goto error_redeclaration;
5064 goto warn_redundant_declaration;
5066 } else if (is_type_valid(prev_type)) {
5067 if (old_storage_class == new_storage_class) {
5068 error_redeclaration:
5069 errorf(pos, "redeclaration of '%Y' (declared %P)",
5070 symbol, &previous_entity->base.source_position);
5073 "redeclaration of '%Y' with different linkage (declared %P)",
5074 symbol, &previous_entity->base.source_position);
5079 prev_decl->modifiers |= decl->modifiers;
5080 if (entity->kind == ENTITY_FUNCTION) {
5081 previous_entity->function.is_inline |= entity->function.is_inline;
5083 return previous_entity;
5086 if (entity->kind == ENTITY_FUNCTION) {
5087 if (is_definition &&
5088 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
5089 if (warning.missing_prototypes && !is_sym_main(symbol)) {
5090 warningf(pos, "no previous prototype for '%#T'",
5091 entity->declaration.type, symbol);
5092 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
5093 warningf(pos, "no previous declaration for '%#T'",
5094 entity->declaration.type, symbol);
5097 } else if (warning.missing_declarations &&
5098 entity->kind == ENTITY_VARIABLE &&
5099 current_scope == file_scope) {
5100 declaration_t *declaration = &entity->declaration;
5101 if (declaration->storage_class == STORAGE_CLASS_NONE) {
5102 warningf(pos, "no previous declaration for '%#T'",
5103 declaration->type, symbol);
5108 assert(entity->base.parent_scope == NULL);
5109 assert(current_scope != NULL);
5111 entity->base.parent_scope = current_scope;
5112 entity->base.namespc = NAMESPACE_NORMAL;
5113 environment_push(entity);
5114 append_entity(current_scope, entity);
5119 static void parser_error_multiple_definition(entity_t *entity,
5120 const source_position_t *source_position)
5122 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
5123 entity->base.symbol, &entity->base.source_position);
5126 static bool is_declaration_specifier(const token_t *token,
5127 bool only_specifiers_qualifiers)
5129 switch (token->type) {
5134 return is_typedef_symbol(token->v.symbol);
5136 case T___extension__:
5138 return !only_specifiers_qualifiers;
5145 static void parse_init_declarator_rest(entity_t *entity)
5147 assert(is_declaration(entity));
5148 declaration_t *const declaration = &entity->declaration;
5152 type_t *orig_type = declaration->type;
5153 type_t *type = skip_typeref(orig_type);
5155 if (entity->kind == ENTITY_VARIABLE
5156 && entity->variable.initializer != NULL) {
5157 parser_error_multiple_definition(entity, HERE);
5160 bool must_be_constant = false;
5161 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5162 entity->base.parent_scope == file_scope) {
5163 must_be_constant = true;
5166 if (is_type_function(type)) {
5167 errorf(&entity->base.source_position,
5168 "function '%#T' is initialized like a variable",
5169 orig_type, entity->base.symbol);
5170 orig_type = type_error_type;
5173 parse_initializer_env_t env;
5174 env.type = orig_type;
5175 env.must_be_constant = must_be_constant;
5176 env.entity = entity;
5177 current_init_decl = entity;
5179 initializer_t *initializer = parse_initializer(&env);
5180 current_init_decl = NULL;
5182 if (entity->kind == ENTITY_VARIABLE) {
5183 /* § 6.7.5 (22) array initializers for arrays with unknown size
5184 * determine the array type size */
5185 declaration->type = env.type;
5186 entity->variable.initializer = initializer;
5190 /* parse rest of a declaration without any declarator */
5191 static void parse_anonymous_declaration_rest(
5192 const declaration_specifiers_t *specifiers)
5195 anonymous_entity = NULL;
5197 if (warning.other) {
5198 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
5199 specifiers->thread_local) {
5200 warningf(&specifiers->source_position,
5201 "useless storage class in empty declaration");
5204 type_t *type = specifiers->type;
5205 switch (type->kind) {
5206 case TYPE_COMPOUND_STRUCT:
5207 case TYPE_COMPOUND_UNION: {
5208 if (type->compound.compound->base.symbol == NULL) {
5209 warningf(&specifiers->source_position,
5210 "unnamed struct/union that defines no instances");
5219 warningf(&specifiers->source_position, "empty declaration");
5225 static void check_variable_type_complete(entity_t *ent)
5227 if (ent->kind != ENTITY_VARIABLE)
5230 /* §6.7:7 If an identifier for an object is declared with no linkage, the
5231 * type for the object shall be complete [...] */
5232 declaration_t *decl = &ent->declaration;
5233 if (decl->storage_class != STORAGE_CLASS_NONE)
5236 type_t *type = decl->type;
5237 if (!is_type_incomplete(skip_typeref(type)))
5240 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
5241 type, ent->base.symbol);
5245 static void parse_declaration_rest(entity_t *ndeclaration,
5246 const declaration_specifiers_t *specifiers,
5247 parsed_declaration_func finished_declaration,
5248 declarator_flags_t flags)
5250 add_anchor_token(';');
5251 add_anchor_token(',');
5253 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5255 if (token.type == '=') {
5256 parse_init_declarator_rest(entity);
5257 } else if (entity->kind == ENTITY_VARIABLE) {
5258 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
5259 * [...] where the extern specifier is explicitly used. */
5260 declaration_t *decl = &entity->declaration;
5261 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
5262 type_t *type = decl->type;
5263 if (is_type_reference(skip_typeref(type))) {
5264 errorf(&entity->base.source_position,
5265 "reference '%#T' must be initialized",
5266 type, entity->base.symbol);
5271 check_variable_type_complete(entity);
5273 if (token.type != ',')
5277 add_anchor_token('=');
5278 ndeclaration = parse_declarator(specifiers, flags);
5279 rem_anchor_token('=');
5284 anonymous_entity = NULL;
5285 rem_anchor_token(';');
5286 rem_anchor_token(',');
5289 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5291 symbol_t *symbol = entity->base.symbol;
5292 if (symbol == NULL) {
5293 errorf(HERE, "anonymous declaration not valid as function parameter");
5297 assert(entity->base.namespc == NAMESPACE_NORMAL);
5298 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5299 if (previous_entity == NULL
5300 || previous_entity->base.parent_scope != current_scope) {
5301 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5306 if (is_definition) {
5307 errorf(HERE, "parameter %Y is initialised", entity->base.symbol);
5310 return record_entity(entity, false);
5313 static void parse_declaration(parsed_declaration_func finished_declaration,
5314 declarator_flags_t flags)
5316 declaration_specifiers_t specifiers;
5317 memset(&specifiers, 0, sizeof(specifiers));
5319 add_anchor_token(';');
5320 parse_declaration_specifiers(&specifiers);
5321 rem_anchor_token(';');
5323 if (token.type == ';') {
5324 parse_anonymous_declaration_rest(&specifiers);
5326 entity_t *entity = parse_declarator(&specifiers, flags);
5327 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
5331 static type_t *get_default_promoted_type(type_t *orig_type)
5333 type_t *result = orig_type;
5335 type_t *type = skip_typeref(orig_type);
5336 if (is_type_integer(type)) {
5337 result = promote_integer(type);
5338 } else if (type == type_float) {
5339 result = type_double;
5345 static void parse_kr_declaration_list(entity_t *entity)
5347 if (entity->kind != ENTITY_FUNCTION)
5350 type_t *type = skip_typeref(entity->declaration.type);
5351 assert(is_type_function(type));
5352 if (!type->function.kr_style_parameters)
5356 add_anchor_token('{');
5358 /* push function parameters */
5359 size_t const top = environment_top();
5360 scope_t *old_scope = scope_push(&entity->function.parameters);
5362 entity_t *parameter = entity->function.parameters.entities;
5363 for ( ; parameter != NULL; parameter = parameter->base.next) {
5364 assert(parameter->base.parent_scope == NULL);
5365 parameter->base.parent_scope = current_scope;
5366 environment_push(parameter);
5369 /* parse declaration list */
5371 switch (token.type) {
5373 case T___extension__:
5374 /* This covers symbols, which are no type, too, and results in
5375 * better error messages. The typical cases are misspelled type
5376 * names and missing includes. */
5378 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
5386 /* pop function parameters */
5387 assert(current_scope == &entity->function.parameters);
5388 scope_pop(old_scope);
5389 environment_pop_to(top);
5391 /* update function type */
5392 type_t *new_type = duplicate_type(type);
5394 function_parameter_t *parameters = NULL;
5395 function_parameter_t *last_parameter = NULL;
5397 parameter = entity->function.parameters.entities;
5398 for (; parameter != NULL; parameter = parameter->base.next) {
5399 type_t *parameter_type = parameter->declaration.type;
5400 if (parameter_type == NULL) {
5402 errorf(HERE, "no type specified for function parameter '%Y'",
5403 parameter->base.symbol);
5405 if (warning.implicit_int) {
5406 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5407 parameter->base.symbol);
5409 parameter_type = type_int;
5410 parameter->declaration.type = parameter_type;
5414 semantic_parameter_incomplete(parameter);
5415 parameter_type = parameter->declaration.type;
5418 * we need the default promoted types for the function type
5420 parameter_type = get_default_promoted_type(parameter_type);
5422 function_parameter_t *function_parameter
5423 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5424 memset(function_parameter, 0, sizeof(function_parameter[0]));
5426 function_parameter->type = parameter_type;
5427 if (last_parameter != NULL) {
5428 last_parameter->next = function_parameter;
5430 parameters = function_parameter;
5432 last_parameter = function_parameter;
5435 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5437 new_type->function.parameters = parameters;
5438 new_type->function.unspecified_parameters = true;
5440 type = typehash_insert(new_type);
5441 if (type != new_type) {
5442 obstack_free(type_obst, new_type);
5445 entity->declaration.type = type;
5447 rem_anchor_token('{');
5450 static bool first_err = true;
5453 * When called with first_err set, prints the name of the current function,
5456 static void print_in_function(void)
5460 diagnosticf("%s: In function '%Y':\n",
5461 current_function->base.base.source_position.input_name,
5462 current_function->base.base.symbol);
5467 * Check if all labels are defined in the current function.
5468 * Check if all labels are used in the current function.
5470 static void check_labels(void)
5472 for (const goto_statement_t *goto_statement = goto_first;
5473 goto_statement != NULL;
5474 goto_statement = goto_statement->next) {
5475 /* skip computed gotos */
5476 if (goto_statement->expression != NULL)
5479 label_t *label = goto_statement->label;
5482 if (label->base.source_position.input_name == NULL) {
5483 print_in_function();
5484 errorf(&goto_statement->base.source_position,
5485 "label '%Y' used but not defined", label->base.symbol);
5489 if (warning.unused_label) {
5490 for (const label_statement_t *label_statement = label_first;
5491 label_statement != NULL;
5492 label_statement = label_statement->next) {
5493 label_t *label = label_statement->label;
5495 if (! label->used) {
5496 print_in_function();
5497 warningf(&label_statement->base.source_position,
5498 "label '%Y' defined but not used", label->base.symbol);
5504 static void warn_unused_entity(entity_t *entity, entity_t *end)
5506 for (; entity != NULL; entity = entity->base.next) {
5507 if (!is_declaration(entity))
5510 declaration_t *declaration = &entity->declaration;
5511 if (declaration->implicit)
5514 if (!declaration->used) {
5515 print_in_function();
5516 const char *what = get_entity_kind_name(entity->kind);
5517 warningf(&entity->base.source_position, "%s '%Y' is unused",
5518 what, entity->base.symbol);
5519 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5520 print_in_function();
5521 const char *what = get_entity_kind_name(entity->kind);
5522 warningf(&entity->base.source_position, "%s '%Y' is never read",
5523 what, entity->base.symbol);
5531 static void check_unused_variables(statement_t *const stmt, void *const env)
5535 switch (stmt->kind) {
5536 case STATEMENT_DECLARATION: {
5537 declaration_statement_t const *const decls = &stmt->declaration;
5538 warn_unused_entity(decls->declarations_begin,
5539 decls->declarations_end);
5544 warn_unused_entity(stmt->fors.scope.entities, NULL);
5553 * Check declarations of current_function for unused entities.
5555 static void check_declarations(void)
5557 if (warning.unused_parameter) {
5558 const scope_t *scope = ¤t_function->parameters;
5560 /* do not issue unused warnings for main */
5561 if (!is_sym_main(current_function->base.base.symbol)) {
5562 warn_unused_entity(scope->entities, NULL);
5565 if (warning.unused_variable) {
5566 walk_statements(current_function->statement, check_unused_variables,
5571 static int determine_truth(expression_t const* const cond)
5574 !is_constant_expression(cond) ? 0 :
5575 fold_constant(cond) != 0 ? 1 :
5579 static void check_reachable(statement_t *);
5581 static bool expression_returns(expression_t const *const expr)
5583 switch (expr->kind) {
5585 expression_t const *const func = expr->call.function;
5586 if (func->kind == EXPR_REFERENCE) {
5587 entity_t *entity = func->reference.entity;
5588 if (entity->kind == ENTITY_FUNCTION
5589 && entity->declaration.modifiers & DM_NORETURN)
5593 if (!expression_returns(func))
5596 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5597 if (!expression_returns(arg->expression))
5604 case EXPR_REFERENCE:
5605 case EXPR_REFERENCE_ENUM_VALUE:
5607 case EXPR_CHARACTER_CONSTANT:
5608 case EXPR_WIDE_CHARACTER_CONSTANT:
5609 case EXPR_STRING_LITERAL:
5610 case EXPR_WIDE_STRING_LITERAL:
5611 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5612 case EXPR_LABEL_ADDRESS:
5613 case EXPR_CLASSIFY_TYPE:
5614 case EXPR_SIZEOF: // TODO handle obscure VLA case
5617 case EXPR_BUILTIN_SYMBOL:
5618 case EXPR_BUILTIN_CONSTANT_P:
5619 case EXPR_BUILTIN_PREFETCH:
5624 case EXPR_STATEMENT:
5625 check_reachable(expr->statement.statement);
5626 // TODO check if statement can be left
5629 case EXPR_CONDITIONAL:
5630 // TODO handle constant expression
5632 if (!expression_returns(expr->conditional.condition))
5635 if (expr->conditional.true_expression != NULL
5636 && expression_returns(expr->conditional.true_expression))
5639 return expression_returns(expr->conditional.false_expression);
5642 return expression_returns(expr->select.compound);
5644 case EXPR_ARRAY_ACCESS:
5646 expression_returns(expr->array_access.array_ref) &&
5647 expression_returns(expr->array_access.index);
5650 return expression_returns(expr->va_starte.ap);
5653 return expression_returns(expr->va_arge.ap);
5655 EXPR_UNARY_CASES_MANDATORY
5656 return expression_returns(expr->unary.value);
5658 case EXPR_UNARY_THROW:
5662 // TODO handle constant lhs of && and ||
5664 expression_returns(expr->binary.left) &&
5665 expression_returns(expr->binary.right);
5671 panic("unhandled expression");
5674 static bool initializer_returns(initializer_t const *const init)
5676 switch (init->kind) {
5677 case INITIALIZER_VALUE:
5678 return expression_returns(init->value.value);
5680 case INITIALIZER_LIST: {
5681 initializer_t * const* i = init->list.initializers;
5682 initializer_t * const* const end = i + init->list.len;
5683 bool returns = true;
5684 for (; i != end; ++i) {
5685 if (!initializer_returns(*i))
5691 case INITIALIZER_STRING:
5692 case INITIALIZER_WIDE_STRING:
5693 case INITIALIZER_DESIGNATOR: // designators have no payload
5696 panic("unhandled initializer");
5699 static bool noreturn_candidate;
5701 static void check_reachable(statement_t *const stmt)
5703 if (stmt->base.reachable)
5705 if (stmt->kind != STATEMENT_DO_WHILE)
5706 stmt->base.reachable = true;
5708 statement_t *last = stmt;
5710 switch (stmt->kind) {
5711 case STATEMENT_INVALID:
5712 case STATEMENT_EMPTY:
5713 case STATEMENT_LOCAL_LABEL:
5715 next = stmt->base.next;
5718 case STATEMENT_DECLARATION: {
5719 declaration_statement_t const *const decl = &stmt->declaration;
5720 entity_t const * ent = decl->declarations_begin;
5721 entity_t const *const last = decl->declarations_end;
5722 for (;; ent = ent->base.next) {
5723 if (ent->kind == ENTITY_VARIABLE &&
5724 ent->variable.initializer != NULL &&
5725 !initializer_returns(ent->variable.initializer)) {
5731 next = stmt->base.next;
5735 case STATEMENT_COMPOUND:
5736 next = stmt->compound.statements;
5739 case STATEMENT_RETURN: {
5740 expression_t const *const val = stmt->returns.value;
5741 if (val == NULL || expression_returns(val))
5742 noreturn_candidate = false;
5746 case STATEMENT_IF: {
5747 if_statement_t const *const ifs = &stmt->ifs;
5748 expression_t const *const cond = ifs->condition;
5750 if (!expression_returns(cond))
5753 int const val = determine_truth(cond);
5756 check_reachable(ifs->true_statement);
5761 if (ifs->false_statement != NULL) {
5762 check_reachable(ifs->false_statement);
5766 next = stmt->base.next;
5770 case STATEMENT_SWITCH: {
5771 switch_statement_t const *const switchs = &stmt->switchs;
5772 expression_t const *const expr = switchs->expression;
5774 if (!expression_returns(expr))
5777 if (is_constant_expression(expr)) {
5778 long const val = fold_constant(expr);
5779 case_label_statement_t * defaults = NULL;
5780 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5781 if (i->expression == NULL) {
5786 if (i->first_case <= val && val <= i->last_case) {
5787 check_reachable((statement_t*)i);
5792 if (defaults != NULL) {
5793 check_reachable((statement_t*)defaults);
5797 bool has_default = false;
5798 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5799 if (i->expression == NULL)
5802 check_reachable((statement_t*)i);
5809 next = stmt->base.next;
5813 case STATEMENT_EXPRESSION: {
5814 /* Check for noreturn function call */
5815 expression_t const *const expr = stmt->expression.expression;
5816 if (!expression_returns(expr))
5819 next = stmt->base.next;
5823 case STATEMENT_CONTINUE: {
5824 statement_t *parent = stmt;
5826 parent = parent->base.parent;
5827 if (parent == NULL) /* continue not within loop */
5831 switch (parent->kind) {
5832 case STATEMENT_WHILE: goto continue_while;
5833 case STATEMENT_DO_WHILE: goto continue_do_while;
5834 case STATEMENT_FOR: goto continue_for;
5841 case STATEMENT_BREAK: {
5842 statement_t *parent = stmt;
5844 parent = parent->base.parent;
5845 if (parent == NULL) /* break not within loop/switch */
5848 switch (parent->kind) {
5849 case STATEMENT_SWITCH:
5850 case STATEMENT_WHILE:
5851 case STATEMENT_DO_WHILE:
5854 next = parent->base.next;
5855 goto found_break_parent;
5864 case STATEMENT_GOTO:
5865 if (stmt->gotos.expression) {
5866 if (!expression_returns(stmt->gotos.expression))
5869 statement_t *parent = stmt->base.parent;
5870 if (parent == NULL) /* top level goto */
5874 next = stmt->gotos.label->statement;
5875 if (next == NULL) /* missing label */
5880 case STATEMENT_LABEL:
5881 next = stmt->label.statement;
5884 case STATEMENT_CASE_LABEL:
5885 next = stmt->case_label.statement;
5888 case STATEMENT_WHILE: {
5889 while_statement_t const *const whiles = &stmt->whiles;
5890 expression_t const *const cond = whiles->condition;
5892 if (!expression_returns(cond))
5895 int const val = determine_truth(cond);
5898 check_reachable(whiles->body);
5903 next = stmt->base.next;
5907 case STATEMENT_DO_WHILE:
5908 next = stmt->do_while.body;
5911 case STATEMENT_FOR: {
5912 for_statement_t *const fors = &stmt->fors;
5914 if (fors->condition_reachable)
5916 fors->condition_reachable = true;
5918 expression_t const *const cond = fors->condition;
5923 } else if (expression_returns(cond)) {
5924 val = determine_truth(cond);
5930 check_reachable(fors->body);
5935 next = stmt->base.next;
5939 case STATEMENT_MS_TRY: {
5940 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5941 check_reachable(ms_try->try_statement);
5942 next = ms_try->final_statement;
5946 case STATEMENT_LEAVE: {
5947 statement_t *parent = stmt;
5949 parent = parent->base.parent;
5950 if (parent == NULL) /* __leave not within __try */
5953 if (parent->kind == STATEMENT_MS_TRY) {
5955 next = parent->ms_try.final_statement;
5963 while (next == NULL) {
5964 next = last->base.parent;
5966 noreturn_candidate = false;
5968 type_t *const type = current_function->base.type;
5969 assert(is_type_function(type));
5970 type_t *const ret = skip_typeref(type->function.return_type);
5971 if (warning.return_type &&
5972 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5973 is_type_valid(ret) &&
5974 !is_sym_main(current_function->base.base.symbol)) {
5975 warningf(&stmt->base.source_position,
5976 "control reaches end of non-void function");
5981 switch (next->kind) {
5982 case STATEMENT_INVALID:
5983 case STATEMENT_EMPTY:
5984 case STATEMENT_DECLARATION:
5985 case STATEMENT_LOCAL_LABEL:
5986 case STATEMENT_EXPRESSION:
5988 case STATEMENT_RETURN:
5989 case STATEMENT_CONTINUE:
5990 case STATEMENT_BREAK:
5991 case STATEMENT_GOTO:
5992 case STATEMENT_LEAVE:
5993 panic("invalid control flow in function");
5995 case STATEMENT_COMPOUND:
5997 case STATEMENT_SWITCH:
5998 case STATEMENT_LABEL:
5999 case STATEMENT_CASE_LABEL:
6001 next = next->base.next;
6004 case STATEMENT_WHILE: {
6006 if (next->base.reachable)
6008 next->base.reachable = true;
6010 while_statement_t const *const whiles = &next->whiles;
6011 expression_t const *const cond = whiles->condition;
6013 if (!expression_returns(cond))
6016 int const val = determine_truth(cond);
6019 check_reachable(whiles->body);
6025 next = next->base.next;
6029 case STATEMENT_DO_WHILE: {
6031 if (next->base.reachable)
6033 next->base.reachable = true;
6035 do_while_statement_t const *const dw = &next->do_while;
6036 expression_t const *const cond = dw->condition;
6038 if (!expression_returns(cond))
6041 int const val = determine_truth(cond);
6044 check_reachable(dw->body);
6050 next = next->base.next;
6054 case STATEMENT_FOR: {
6056 for_statement_t *const fors = &next->fors;
6058 fors->step_reachable = true;
6060 if (fors->condition_reachable)
6062 fors->condition_reachable = true;
6064 expression_t const *const cond = fors->condition;
6069 } else if (expression_returns(cond)) {
6070 val = determine_truth(cond);
6076 check_reachable(fors->body);
6082 next = next->base.next;
6086 case STATEMENT_MS_TRY:
6088 next = next->ms_try.final_statement;
6093 check_reachable(next);
6096 static void check_unreachable(statement_t* const stmt, void *const env)
6100 switch (stmt->kind) {
6101 case STATEMENT_DO_WHILE:
6102 if (!stmt->base.reachable) {
6103 expression_t const *const cond = stmt->do_while.condition;
6104 if (determine_truth(cond) >= 0) {
6105 warningf(&cond->base.source_position,
6106 "condition of do-while-loop is unreachable");
6111 case STATEMENT_FOR: {
6112 for_statement_t const* const fors = &stmt->fors;
6114 // if init and step are unreachable, cond is unreachable, too
6115 if (!stmt->base.reachable && !fors->step_reachable) {
6116 warningf(&stmt->base.source_position, "statement is unreachable");
6118 if (!stmt->base.reachable && fors->initialisation != NULL) {
6119 warningf(&fors->initialisation->base.source_position,
6120 "initialisation of for-statement is unreachable");
6123 if (!fors->condition_reachable && fors->condition != NULL) {
6124 warningf(&fors->condition->base.source_position,
6125 "condition of for-statement is unreachable");
6128 if (!fors->step_reachable && fors->step != NULL) {
6129 warningf(&fors->step->base.source_position,
6130 "step of for-statement is unreachable");
6136 case STATEMENT_COMPOUND:
6137 if (stmt->compound.statements != NULL)
6139 goto warn_unreachable;
6141 case STATEMENT_DECLARATION: {
6142 /* Only warn if there is at least one declarator with an initializer.
6143 * This typically occurs in switch statements. */
6144 declaration_statement_t const *const decl = &stmt->declaration;
6145 entity_t const * ent = decl->declarations_begin;
6146 entity_t const *const last = decl->declarations_end;
6147 for (;; ent = ent->base.next) {
6148 if (ent->kind == ENTITY_VARIABLE &&
6149 ent->variable.initializer != NULL) {
6150 goto warn_unreachable;
6159 if (!stmt->base.reachable)
6160 warningf(&stmt->base.source_position, "statement is unreachable");
6165 static void parse_external_declaration(void)
6167 /* function-definitions and declarations both start with declaration
6169 declaration_specifiers_t specifiers;
6170 memset(&specifiers, 0, sizeof(specifiers));
6172 add_anchor_token(';');
6173 parse_declaration_specifiers(&specifiers);
6174 rem_anchor_token(';');
6176 /* must be a declaration */
6177 if (token.type == ';') {
6178 parse_anonymous_declaration_rest(&specifiers);
6182 add_anchor_token(',');
6183 add_anchor_token('=');
6184 add_anchor_token(';');
6185 add_anchor_token('{');
6187 /* declarator is common to both function-definitions and declarations */
6188 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
6190 rem_anchor_token('{');
6191 rem_anchor_token(';');
6192 rem_anchor_token('=');
6193 rem_anchor_token(',');
6195 /* must be a declaration */
6196 switch (token.type) {
6200 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
6205 /* must be a function definition */
6206 parse_kr_declaration_list(ndeclaration);
6208 if (token.type != '{') {
6209 parse_error_expected("while parsing function definition", '{', NULL);
6210 eat_until_matching_token(';');
6214 assert(is_declaration(ndeclaration));
6215 type_t *type = skip_typeref(ndeclaration->declaration.type);
6217 if (!is_type_function(type)) {
6218 if (is_type_valid(type)) {
6219 errorf(HERE, "declarator '%#T' has a body but is not a function type",
6220 type, ndeclaration->base.symbol);
6226 if (warning.aggregate_return &&
6227 is_type_compound(skip_typeref(type->function.return_type))) {
6228 warningf(HERE, "function '%Y' returns an aggregate",
6229 ndeclaration->base.symbol);
6231 if (warning.traditional && !type->function.unspecified_parameters) {
6232 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6233 ndeclaration->base.symbol);
6235 if (warning.old_style_definition && type->function.unspecified_parameters) {
6236 warningf(HERE, "old-style function definition '%Y'",
6237 ndeclaration->base.symbol);
6240 /* § 6.7.5.3 (14) a function definition with () means no
6241 * parameters (and not unspecified parameters) */
6242 if (type->function.unspecified_parameters
6243 && type->function.parameters == NULL
6244 && !type->function.kr_style_parameters) {
6245 type_t *duplicate = duplicate_type(type);
6246 duplicate->function.unspecified_parameters = false;
6248 type = typehash_insert(duplicate);
6249 if (type != duplicate) {
6250 obstack_free(type_obst, duplicate);
6252 ndeclaration->declaration.type = type;
6255 entity_t *const entity = record_entity(ndeclaration, true);
6256 assert(entity->kind == ENTITY_FUNCTION);
6257 assert(ndeclaration->kind == ENTITY_FUNCTION);
6259 function_t *function = &entity->function;
6260 if (ndeclaration != entity) {
6261 function->parameters = ndeclaration->function.parameters;
6263 assert(is_declaration(entity));
6264 type = skip_typeref(entity->declaration.type);
6266 /* push function parameters and switch scope */
6267 size_t const top = environment_top();
6268 scope_t *old_scope = scope_push(&function->parameters);
6270 entity_t *parameter = function->parameters.entities;
6271 for (; parameter != NULL; parameter = parameter->base.next) {
6272 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6273 parameter->base.parent_scope = current_scope;
6275 assert(parameter->base.parent_scope == NULL
6276 || parameter->base.parent_scope == current_scope);
6277 parameter->base.parent_scope = current_scope;
6278 if (parameter->base.symbol == NULL) {
6279 errorf(¶meter->base.source_position, "parameter name omitted");
6282 environment_push(parameter);
6285 if (function->statement != NULL) {
6286 parser_error_multiple_definition(entity, HERE);
6289 /* parse function body */
6290 int label_stack_top = label_top();
6291 function_t *old_current_function = current_function;
6292 current_function = function;
6293 current_parent = NULL;
6296 goto_anchor = &goto_first;
6298 label_anchor = &label_first;
6300 statement_t *const body = parse_compound_statement(false);
6301 function->statement = body;
6304 check_declarations();
6305 if (warning.return_type ||
6306 warning.unreachable_code ||
6307 (warning.missing_noreturn
6308 && !(function->base.modifiers & DM_NORETURN))) {
6309 noreturn_candidate = true;
6310 check_reachable(body);
6311 if (warning.unreachable_code)
6312 walk_statements(body, check_unreachable, NULL);
6313 if (warning.missing_noreturn &&
6314 noreturn_candidate &&
6315 !(function->base.modifiers & DM_NORETURN)) {
6316 warningf(&body->base.source_position,
6317 "function '%#T' is candidate for attribute 'noreturn'",
6318 type, entity->base.symbol);
6322 assert(current_parent == NULL);
6323 assert(current_function == function);
6324 current_function = old_current_function;
6325 label_pop_to(label_stack_top);
6328 assert(current_scope == &function->parameters);
6329 scope_pop(old_scope);
6330 environment_pop_to(top);
6333 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6334 source_position_t *source_position,
6335 const symbol_t *symbol)
6337 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6339 type->bitfield.base_type = base_type;
6340 type->bitfield.size_expression = size;
6343 type_t *skipped_type = skip_typeref(base_type);
6344 if (!is_type_integer(skipped_type)) {
6345 errorf(HERE, "bitfield base type '%T' is not an integer type",
6349 bit_size = skipped_type->base.size * 8;
6352 if (is_constant_expression(size)) {
6353 long v = fold_constant(size);
6356 errorf(source_position, "negative width in bit-field '%Y'", symbol);
6357 } else if (v == 0) {
6358 errorf(source_position, "zero width for bit-field '%Y'", symbol);
6359 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6360 errorf(source_position, "width of '%Y' exceeds its type", symbol);
6362 type->bitfield.bit_size = v;
6369 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6371 entity_t *iter = compound->members.entities;
6372 for (; iter != NULL; iter = iter->base.next) {
6373 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6376 if (iter->base.symbol == symbol) {
6378 } else if (iter->base.symbol == NULL) {
6379 type_t *type = skip_typeref(iter->declaration.type);
6380 if (is_type_compound(type)) {
6382 = find_compound_entry(type->compound.compound, symbol);
6393 static void parse_compound_declarators(compound_t *compound,
6394 const declaration_specifiers_t *specifiers)
6399 if (token.type == ':') {
6400 source_position_t source_position = *HERE;
6403 type_t *base_type = specifiers->type;
6404 expression_t *size = parse_constant_expression();
6406 type_t *type = make_bitfield_type(base_type, size,
6407 &source_position, sym_anonymous);
6409 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6410 entity->base.namespc = NAMESPACE_NORMAL;
6411 entity->base.source_position = source_position;
6412 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6413 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6414 entity->declaration.modifiers = specifiers->modifiers;
6415 entity->declaration.type = type;
6417 entity = parse_declarator(specifiers,
6418 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
6419 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6421 if (token.type == ':') {
6422 source_position_t source_position = *HERE;
6424 expression_t *size = parse_constant_expression();
6426 type_t *type = entity->declaration.type;
6427 type_t *bitfield_type = make_bitfield_type(type, size,
6428 &source_position, entity->base.symbol);
6429 entity->declaration.type = bitfield_type;
6433 /* make sure we don't define a symbol multiple times */
6434 symbol_t *symbol = entity->base.symbol;
6435 if (symbol != NULL) {
6436 entity_t *prev = find_compound_entry(compound, symbol);
6439 errorf(&entity->base.source_position,
6440 "multiple declarations of symbol '%Y' (declared %P)",
6441 symbol, &prev->base.source_position);
6445 append_entity(&compound->members, entity);
6447 type_t *orig_type = entity->declaration.type;
6448 type_t *type = skip_typeref(orig_type);
6449 if (is_type_function(type)) {
6450 errorf(&entity->base.source_position,
6451 "compound member '%Y' must not have function type '%T'",
6452 entity->base.symbol, orig_type);
6453 } else if (is_type_incomplete(type)) {
6454 /* §6.7.2.1:16 flexible array member */
6455 if (is_type_array(type) &&
6456 token.type == ';' &&
6457 look_ahead(1)->type == '}') {
6458 compound->has_flexible_member = true;
6460 errorf(&entity->base.source_position,
6461 "compound member '%Y' has incomplete type '%T'",
6462 entity->base.symbol, orig_type);
6466 if (token.type != ',')
6473 anonymous_entity = NULL;
6476 static void parse_compound_type_entries(compound_t *compound)
6479 add_anchor_token('}');
6481 while (token.type != '}') {
6482 if (token.type == T_EOF) {
6483 errorf(HERE, "EOF while parsing struct");
6486 declaration_specifiers_t specifiers;
6487 memset(&specifiers, 0, sizeof(specifiers));
6488 parse_declaration_specifiers(&specifiers);
6490 parse_compound_declarators(compound, &specifiers);
6492 rem_anchor_token('}');
6496 compound->complete = true;
6499 static type_t *parse_typename(void)
6501 declaration_specifiers_t specifiers;
6502 memset(&specifiers, 0, sizeof(specifiers));
6503 parse_declaration_specifiers(&specifiers);
6504 if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6505 specifiers.thread_local) {
6506 /* TODO: improve error message, user does probably not know what a
6507 * storage class is...
6509 errorf(HERE, "typename may not have a storage class");
6512 type_t *result = parse_abstract_declarator(specifiers.type);
6520 typedef expression_t* (*parse_expression_function)(void);
6521 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6523 typedef struct expression_parser_function_t expression_parser_function_t;
6524 struct expression_parser_function_t {
6525 parse_expression_function parser;
6526 unsigned infix_precedence;
6527 parse_expression_infix_function infix_parser;
6530 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6533 * Prints an error message if an expression was expected but not read
6535 static expression_t *expected_expression_error(void)
6537 /* skip the error message if the error token was read */
6538 if (token.type != T_ERROR) {
6539 errorf(HERE, "expected expression, got token '%K'", &token);
6543 return create_invalid_expression();
6547 * Parse a string constant.
6549 static expression_t *parse_string_const(void)
6552 if (token.type == T_STRING_LITERAL) {
6553 string_t res = token.v.string;
6555 while (token.type == T_STRING_LITERAL) {
6556 res = concat_strings(&res, &token.v.string);
6559 if (token.type != T_WIDE_STRING_LITERAL) {
6560 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6561 /* note: that we use type_char_ptr here, which is already the
6562 * automatic converted type. revert_automatic_type_conversion
6563 * will construct the array type */
6564 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6565 cnst->string.value = res;
6569 wres = concat_string_wide_string(&res, &token.v.wide_string);
6571 wres = token.v.wide_string;
6576 switch (token.type) {
6577 case T_WIDE_STRING_LITERAL:
6578 wres = concat_wide_strings(&wres, &token.v.wide_string);
6581 case T_STRING_LITERAL:
6582 wres = concat_wide_string_string(&wres, &token.v.string);
6586 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6587 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6588 cnst->wide_string.value = wres;
6597 * Parse a boolean constant.
6599 static expression_t *parse_bool_const(bool value)
6601 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6602 cnst->base.type = type_bool;
6603 cnst->conste.v.int_value = value;
6611 * Parse an integer constant.
6613 static expression_t *parse_int_const(void)
6615 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6616 cnst->base.type = token.datatype;
6617 cnst->conste.v.int_value = token.v.intvalue;
6625 * Parse a character constant.
6627 static expression_t *parse_character_constant(void)
6629 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6630 cnst->base.type = token.datatype;
6631 cnst->conste.v.character = token.v.string;
6633 if (cnst->conste.v.character.size != 1) {
6635 errorf(HERE, "more than 1 character in character constant");
6636 } else if (warning.multichar) {
6637 warningf(HERE, "multi-character character constant");
6646 * Parse a wide character constant.
6648 static expression_t *parse_wide_character_constant(void)
6650 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6651 cnst->base.type = token.datatype;
6652 cnst->conste.v.wide_character = token.v.wide_string;
6654 if (cnst->conste.v.wide_character.size != 1) {
6656 errorf(HERE, "more than 1 character in character constant");
6657 } else if (warning.multichar) {
6658 warningf(HERE, "multi-character character constant");
6667 * Parse a float constant.
6669 static expression_t *parse_float_const(void)
6671 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6672 cnst->base.type = token.datatype;
6673 cnst->conste.v.float_value = token.v.floatvalue;
6680 static entity_t *create_implicit_function(symbol_t *symbol,
6681 const source_position_t *source_position)
6683 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6684 ntype->function.return_type = type_int;
6685 ntype->function.unspecified_parameters = true;
6687 type_t *type = typehash_insert(ntype);
6688 if (type != ntype) {
6692 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6693 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6694 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6695 entity->declaration.type = type;
6696 entity->declaration.implicit = true;
6697 entity->base.symbol = symbol;
6698 entity->base.source_position = *source_position;
6700 bool strict_prototypes_old = warning.strict_prototypes;
6701 warning.strict_prototypes = false;
6702 record_entity(entity, false);
6703 warning.strict_prototypes = strict_prototypes_old;
6709 * Creates a return_type (func)(argument_type) function type if not
6712 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6713 type_t *argument_type2)
6715 function_parameter_t *parameter2
6716 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6717 memset(parameter2, 0, sizeof(parameter2[0]));
6718 parameter2->type = argument_type2;
6720 function_parameter_t *parameter1
6721 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6722 memset(parameter1, 0, sizeof(parameter1[0]));
6723 parameter1->type = argument_type1;
6724 parameter1->next = parameter2;
6726 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6727 type->function.return_type = return_type;
6728 type->function.parameters = parameter1;
6730 type_t *result = typehash_insert(type);
6731 if (result != type) {
6739 * Creates a return_type (func)(argument_type) function type if not
6742 * @param return_type the return type
6743 * @param argument_type the argument type
6745 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6747 function_parameter_t *parameter
6748 = obstack_alloc(type_obst, sizeof(parameter[0]));
6749 memset(parameter, 0, sizeof(parameter[0]));
6750 parameter->type = argument_type;
6752 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6753 type->function.return_type = return_type;
6754 type->function.parameters = parameter;
6756 type_t *result = typehash_insert(type);
6757 if (result != type) {
6764 static type_t *make_function_0_type(type_t *return_type)
6766 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6767 type->function.return_type = return_type;
6768 type->function.parameters = NULL;
6770 type_t *result = typehash_insert(type);
6771 if (result != type) {
6779 * Creates a function type for some function like builtins.
6781 * @param symbol the symbol describing the builtin
6783 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6785 switch (symbol->ID) {
6786 case T___builtin_alloca:
6787 return make_function_1_type(type_void_ptr, type_size_t);
6788 case T___builtin_huge_val:
6789 return make_function_0_type(type_double);
6790 case T___builtin_inf:
6791 return make_function_0_type(type_double);
6792 case T___builtin_inff:
6793 return make_function_0_type(type_float);
6794 case T___builtin_infl:
6795 return make_function_0_type(type_long_double);
6796 case T___builtin_nan:
6797 return make_function_1_type(type_double, type_char_ptr);
6798 case T___builtin_nanf:
6799 return make_function_1_type(type_float, type_char_ptr);
6800 case T___builtin_nanl:
6801 return make_function_1_type(type_long_double, type_char_ptr);
6802 case T___builtin_va_end:
6803 return make_function_1_type(type_void, type_valist);
6804 case T___builtin_expect:
6805 return make_function_2_type(type_long, type_long, type_long);
6807 internal_errorf(HERE, "not implemented builtin symbol found");
6812 * Performs automatic type cast as described in § 6.3.2.1.
6814 * @param orig_type the original type
6816 static type_t *automatic_type_conversion(type_t *orig_type)
6818 type_t *type = skip_typeref(orig_type);
6819 if (is_type_array(type)) {
6820 array_type_t *array_type = &type->array;
6821 type_t *element_type = array_type->element_type;
6822 unsigned qualifiers = array_type->base.qualifiers;
6824 return make_pointer_type(element_type, qualifiers);
6827 if (is_type_function(type)) {
6828 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6835 * reverts the automatic casts of array to pointer types and function
6836 * to function-pointer types as defined § 6.3.2.1
6838 type_t *revert_automatic_type_conversion(const expression_t *expression)
6840 switch (expression->kind) {
6841 case EXPR_REFERENCE: {
6842 entity_t *entity = expression->reference.entity;
6843 if (is_declaration(entity)) {
6844 return entity->declaration.type;
6845 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6846 return entity->enum_value.enum_type;
6848 panic("no declaration or enum in reference");
6853 entity_t *entity = expression->select.compound_entry;
6854 assert(is_declaration(entity));
6855 type_t *type = entity->declaration.type;
6856 return get_qualified_type(type,
6857 expression->base.type->base.qualifiers);
6860 case EXPR_UNARY_DEREFERENCE: {
6861 const expression_t *const value = expression->unary.value;
6862 type_t *const type = skip_typeref(value->base.type);
6863 assert(is_type_pointer(type));
6864 return type->pointer.points_to;
6867 case EXPR_BUILTIN_SYMBOL:
6868 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6870 case EXPR_ARRAY_ACCESS: {
6871 const expression_t *array_ref = expression->array_access.array_ref;
6872 type_t *type_left = skip_typeref(array_ref->base.type);
6873 if (!is_type_valid(type_left))
6875 assert(is_type_pointer(type_left));
6876 return type_left->pointer.points_to;
6879 case EXPR_STRING_LITERAL: {
6880 size_t size = expression->string.value.size;
6881 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6884 case EXPR_WIDE_STRING_LITERAL: {
6885 size_t size = expression->wide_string.value.size;
6886 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6889 case EXPR_COMPOUND_LITERAL:
6890 return expression->compound_literal.type;
6895 return expression->base.type;
6898 static expression_t *parse_reference(void)
6900 symbol_t *const symbol = token.v.symbol;
6902 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6904 if (entity == NULL) {
6905 if (!strict_mode && look_ahead(1)->type == '(') {
6906 /* an implicitly declared function */
6907 if (warning.implicit_function_declaration) {
6908 warningf(HERE, "implicit declaration of function '%Y'",
6912 entity = create_implicit_function(symbol, HERE);
6914 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6915 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6921 if (is_declaration(entity)) {
6922 orig_type = entity->declaration.type;
6923 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6924 orig_type = entity->enum_value.enum_type;
6925 } else if (entity->kind == ENTITY_TYPEDEF) {
6926 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
6929 return create_invalid_expression();
6931 panic("expected declaration or enum value in reference");
6934 /* we always do the auto-type conversions; the & and sizeof parser contains
6935 * code to revert this! */
6936 type_t *type = automatic_type_conversion(orig_type);
6938 expression_kind_t kind = EXPR_REFERENCE;
6939 if (entity->kind == ENTITY_ENUM_VALUE)
6940 kind = EXPR_REFERENCE_ENUM_VALUE;
6942 expression_t *expression = allocate_expression_zero(kind);
6943 expression->reference.entity = entity;
6944 expression->base.type = type;
6946 /* this declaration is used */
6947 if (is_declaration(entity)) {
6948 entity->declaration.used = true;
6951 if (entity->base.parent_scope != file_scope
6952 && entity->base.parent_scope->depth < current_function->parameters.depth
6953 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
6954 if (entity->kind == ENTITY_VARIABLE) {
6955 /* access of a variable from an outer function */
6956 entity->variable.address_taken = true;
6957 } else if (entity->kind == ENTITY_PARAMETER) {
6958 entity->parameter.address_taken = true;
6960 current_function->need_closure = true;
6963 /* check for deprecated functions */
6964 if (warning.deprecated_declarations
6965 && is_declaration(entity)
6966 && entity->declaration.modifiers & DM_DEPRECATED) {
6967 declaration_t *declaration = &entity->declaration;
6969 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
6970 "function" : "variable";
6972 if (declaration->deprecated_string != NULL) {
6973 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6974 prefix, entity->base.symbol, &entity->base.source_position,
6975 declaration->deprecated_string);
6977 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6978 entity->base.symbol, &entity->base.source_position);
6982 if (warning.init_self && entity == current_init_decl && !in_type_prop
6983 && entity->kind == ENTITY_VARIABLE) {
6984 current_init_decl = NULL;
6985 warningf(HERE, "variable '%#T' is initialized by itself",
6986 entity->declaration.type, entity->base.symbol);
6993 static bool semantic_cast(expression_t *cast)
6995 expression_t *expression = cast->unary.value;
6996 type_t *orig_dest_type = cast->base.type;
6997 type_t *orig_type_right = expression->base.type;
6998 type_t const *dst_type = skip_typeref(orig_dest_type);
6999 type_t const *src_type = skip_typeref(orig_type_right);
7000 source_position_t const *pos = &cast->base.source_position;
7002 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
7003 if (dst_type == type_void)
7006 /* only integer and pointer can be casted to pointer */
7007 if (is_type_pointer(dst_type) &&
7008 !is_type_pointer(src_type) &&
7009 !is_type_integer(src_type) &&
7010 is_type_valid(src_type)) {
7011 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
7015 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
7016 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
7020 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
7021 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
7025 if (warning.cast_qual &&
7026 is_type_pointer(src_type) &&
7027 is_type_pointer(dst_type)) {
7028 type_t *src = skip_typeref(src_type->pointer.points_to);
7029 type_t *dst = skip_typeref(dst_type->pointer.points_to);
7030 unsigned missing_qualifiers =
7031 src->base.qualifiers & ~dst->base.qualifiers;
7032 if (missing_qualifiers != 0) {
7034 "cast discards qualifiers '%Q' in pointer target type of '%T'",
7035 missing_qualifiers, orig_type_right);
7041 static expression_t *parse_compound_literal(type_t *type)
7043 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
7045 parse_initializer_env_t env;
7048 env.must_be_constant = false;
7049 initializer_t *initializer = parse_initializer(&env);
7052 expression->compound_literal.initializer = initializer;
7053 expression->compound_literal.type = type;
7054 expression->base.type = automatic_type_conversion(type);
7060 * Parse a cast expression.
7062 static expression_t *parse_cast(void)
7064 add_anchor_token(')');
7066 source_position_t source_position = token.source_position;
7068 type_t *type = parse_typename();
7070 rem_anchor_token(')');
7073 if (token.type == '{') {
7074 return parse_compound_literal(type);
7077 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
7078 cast->base.source_position = source_position;
7080 expression_t *value = parse_sub_expression(PREC_CAST);
7081 cast->base.type = type;
7082 cast->unary.value = value;
7084 if (! semantic_cast(cast)) {
7085 /* TODO: record the error in the AST. else it is impossible to detect it */
7090 return create_invalid_expression();
7094 * Parse a statement expression.
7096 static expression_t *parse_statement_expression(void)
7098 add_anchor_token(')');
7100 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
7102 statement_t *statement = parse_compound_statement(true);
7103 expression->statement.statement = statement;
7105 /* find last statement and use its type */
7106 type_t *type = type_void;
7107 const statement_t *stmt = statement->compound.statements;
7109 while (stmt->base.next != NULL)
7110 stmt = stmt->base.next;
7112 if (stmt->kind == STATEMENT_EXPRESSION) {
7113 type = stmt->expression.expression->base.type;
7115 } else if (warning.other) {
7116 warningf(&expression->base.source_position, "empty statement expression ({})");
7118 expression->base.type = type;
7120 rem_anchor_token(')');
7128 * Parse a parenthesized expression.
7130 static expression_t *parse_parenthesized_expression(void)
7134 switch (token.type) {
7136 /* gcc extension: a statement expression */
7137 return parse_statement_expression();
7141 return parse_cast();
7143 if (is_typedef_symbol(token.v.symbol)) {
7144 return parse_cast();
7148 add_anchor_token(')');
7149 expression_t *result = parse_expression();
7150 rem_anchor_token(')');
7157 static expression_t *parse_function_keyword(void)
7161 if (current_function == NULL) {
7162 errorf(HERE, "'__func__' used outside of a function");
7165 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7166 expression->base.type = type_char_ptr;
7167 expression->funcname.kind = FUNCNAME_FUNCTION;
7174 static expression_t *parse_pretty_function_keyword(void)
7176 if (current_function == NULL) {
7177 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
7180 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7181 expression->base.type = type_char_ptr;
7182 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
7184 eat(T___PRETTY_FUNCTION__);
7189 static expression_t *parse_funcsig_keyword(void)
7191 if (current_function == NULL) {
7192 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7195 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7196 expression->base.type = type_char_ptr;
7197 expression->funcname.kind = FUNCNAME_FUNCSIG;
7204 static expression_t *parse_funcdname_keyword(void)
7206 if (current_function == NULL) {
7207 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7210 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7211 expression->base.type = type_char_ptr;
7212 expression->funcname.kind = FUNCNAME_FUNCDNAME;
7214 eat(T___FUNCDNAME__);
7219 static designator_t *parse_designator(void)
7221 designator_t *result = allocate_ast_zero(sizeof(result[0]));
7222 result->source_position = *HERE;
7224 if (token.type != T_IDENTIFIER) {
7225 parse_error_expected("while parsing member designator",
7226 T_IDENTIFIER, NULL);
7229 result->symbol = token.v.symbol;
7232 designator_t *last_designator = result;
7234 if (token.type == '.') {
7236 if (token.type != T_IDENTIFIER) {
7237 parse_error_expected("while parsing member designator",
7238 T_IDENTIFIER, NULL);
7241 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7242 designator->source_position = *HERE;
7243 designator->symbol = token.v.symbol;
7246 last_designator->next = designator;
7247 last_designator = designator;
7250 if (token.type == '[') {
7252 add_anchor_token(']');
7253 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7254 designator->source_position = *HERE;
7255 designator->array_index = parse_expression();
7256 rem_anchor_token(']');
7258 if (designator->array_index == NULL) {
7262 last_designator->next = designator;
7263 last_designator = designator;
7275 * Parse the __builtin_offsetof() expression.
7277 static expression_t *parse_offsetof(void)
7279 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7280 expression->base.type = type_size_t;
7282 eat(T___builtin_offsetof);
7285 add_anchor_token(',');
7286 type_t *type = parse_typename();
7287 rem_anchor_token(',');
7289 add_anchor_token(')');
7290 designator_t *designator = parse_designator();
7291 rem_anchor_token(')');
7294 expression->offsetofe.type = type;
7295 expression->offsetofe.designator = designator;
7298 memset(&path, 0, sizeof(path));
7299 path.top_type = type;
7300 path.path = NEW_ARR_F(type_path_entry_t, 0);
7302 descend_into_subtype(&path);
7304 if (!walk_designator(&path, designator, true)) {
7305 return create_invalid_expression();
7308 DEL_ARR_F(path.path);
7312 return create_invalid_expression();
7316 * Parses a _builtin_va_start() expression.
7318 static expression_t *parse_va_start(void)
7320 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7322 eat(T___builtin_va_start);
7325 add_anchor_token(',');
7326 expression->va_starte.ap = parse_assignment_expression();
7327 rem_anchor_token(',');
7329 expression_t *const expr = parse_assignment_expression();
7330 if (expr->kind == EXPR_REFERENCE) {
7331 entity_t *const entity = expr->reference.entity;
7332 if (entity->base.parent_scope != ¤t_function->parameters
7333 || entity->base.next != NULL
7334 || entity->kind != ENTITY_PARAMETER) {
7335 errorf(&expr->base.source_position,
7336 "second argument of 'va_start' must be last parameter of the current function");
7338 expression->va_starte.parameter = &entity->variable;
7345 return create_invalid_expression();
7349 * Parses a _builtin_va_arg() expression.
7351 static expression_t *parse_va_arg(void)
7353 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7355 eat(T___builtin_va_arg);
7358 expression->va_arge.ap = parse_assignment_expression();
7360 expression->base.type = parse_typename();
7365 return create_invalid_expression();
7368 static expression_t *parse_builtin_symbol(void)
7370 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7372 symbol_t *symbol = token.v.symbol;
7374 expression->builtin_symbol.symbol = symbol;
7377 type_t *type = get_builtin_symbol_type(symbol);
7378 type = automatic_type_conversion(type);
7380 expression->base.type = type;
7385 * Parses a __builtin_constant() expression.
7387 static expression_t *parse_builtin_constant(void)
7389 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7391 eat(T___builtin_constant_p);
7394 add_anchor_token(')');
7395 expression->builtin_constant.value = parse_assignment_expression();
7396 rem_anchor_token(')');
7398 expression->base.type = type_int;
7402 return create_invalid_expression();
7406 * Parses a __builtin_prefetch() expression.
7408 static expression_t *parse_builtin_prefetch(void)
7410 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7412 eat(T___builtin_prefetch);
7415 add_anchor_token(')');
7416 expression->builtin_prefetch.adr = parse_assignment_expression();
7417 if (token.type == ',') {
7419 expression->builtin_prefetch.rw = parse_assignment_expression();
7421 if (token.type == ',') {
7423 expression->builtin_prefetch.locality = parse_assignment_expression();
7425 rem_anchor_token(')');
7427 expression->base.type = type_void;
7431 return create_invalid_expression();
7435 * Parses a __builtin_is_*() compare expression.
7437 static expression_t *parse_compare_builtin(void)
7439 expression_t *expression;
7441 switch (token.type) {
7442 case T___builtin_isgreater:
7443 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7445 case T___builtin_isgreaterequal:
7446 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7448 case T___builtin_isless:
7449 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7451 case T___builtin_islessequal:
7452 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7454 case T___builtin_islessgreater:
7455 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7457 case T___builtin_isunordered:
7458 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7461 internal_errorf(HERE, "invalid compare builtin found");
7463 expression->base.source_position = *HERE;
7467 expression->binary.left = parse_assignment_expression();
7469 expression->binary.right = parse_assignment_expression();
7472 type_t *const orig_type_left = expression->binary.left->base.type;
7473 type_t *const orig_type_right = expression->binary.right->base.type;
7475 type_t *const type_left = skip_typeref(orig_type_left);
7476 type_t *const type_right = skip_typeref(orig_type_right);
7477 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7478 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7479 type_error_incompatible("invalid operands in comparison",
7480 &expression->base.source_position, orig_type_left, orig_type_right);
7483 semantic_comparison(&expression->binary);
7488 return create_invalid_expression();
7493 * Parses a __builtin_expect() expression.
7495 static expression_t *parse_builtin_expect(void)
7497 expression_t *expression
7498 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7500 eat(T___builtin_expect);
7503 expression->binary.left = parse_assignment_expression();
7505 expression->binary.right = parse_constant_expression();
7508 expression->base.type = expression->binary.left->base.type;
7512 return create_invalid_expression();
7517 * Parses a MS assume() expression.
7519 static expression_t *parse_assume(void)
7521 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7526 add_anchor_token(')');
7527 expression->unary.value = parse_assignment_expression();
7528 rem_anchor_token(')');
7531 expression->base.type = type_void;
7534 return create_invalid_expression();
7538 * Return the declaration for a given label symbol or create a new one.
7540 * @param symbol the symbol of the label
7542 static label_t *get_label(symbol_t *symbol)
7545 assert(current_function != NULL);
7547 label = get_entity(symbol, NAMESPACE_LABEL);
7548 /* if we found a local label, we already created the declaration */
7549 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7550 if (label->base.parent_scope != current_scope) {
7551 assert(label->base.parent_scope->depth < current_scope->depth);
7552 current_function->goto_to_outer = true;
7554 return &label->label;
7557 label = get_entity(symbol, NAMESPACE_LABEL);
7558 /* if we found a label in the same function, then we already created the
7561 && label->base.parent_scope == ¤t_function->parameters) {
7562 return &label->label;
7565 /* otherwise we need to create a new one */
7566 label = allocate_entity_zero(ENTITY_LABEL);
7567 label->base.namespc = NAMESPACE_LABEL;
7568 label->base.symbol = symbol;
7572 return &label->label;
7576 * Parses a GNU && label address expression.
7578 static expression_t *parse_label_address(void)
7580 source_position_t source_position = token.source_position;
7582 if (token.type != T_IDENTIFIER) {
7583 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7586 symbol_t *symbol = token.v.symbol;
7589 label_t *label = get_label(symbol);
7591 label->address_taken = true;
7593 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7594 expression->base.source_position = source_position;
7596 /* label address is threaten as a void pointer */
7597 expression->base.type = type_void_ptr;
7598 expression->label_address.label = label;
7601 return create_invalid_expression();
7605 * Parse a microsoft __noop expression.
7607 static expression_t *parse_noop_expression(void)
7609 /* the result is a (int)0 */
7610 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7611 cnst->base.type = type_int;
7612 cnst->conste.v.int_value = 0;
7613 cnst->conste.is_ms_noop = true;
7617 if (token.type == '(') {
7618 /* parse arguments */
7620 add_anchor_token(')');
7621 add_anchor_token(',');
7623 if (token.type != ')') {
7625 (void)parse_assignment_expression();
7626 if (token.type != ',')
7632 rem_anchor_token(',');
7633 rem_anchor_token(')');
7641 * Parses a primary expression.
7643 static expression_t *parse_primary_expression(void)
7645 switch (token.type) {
7646 case T_false: return parse_bool_const(false);
7647 case T_true: return parse_bool_const(true);
7648 case T_INTEGER: return parse_int_const();
7649 case T_CHARACTER_CONSTANT: return parse_character_constant();
7650 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7651 case T_FLOATINGPOINT: return parse_float_const();
7652 case T_STRING_LITERAL:
7653 case T_WIDE_STRING_LITERAL: return parse_string_const();
7654 case T_IDENTIFIER: return parse_reference();
7655 case T___FUNCTION__:
7656 case T___func__: return parse_function_keyword();
7657 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7658 case T___FUNCSIG__: return parse_funcsig_keyword();
7659 case T___FUNCDNAME__: return parse_funcdname_keyword();
7660 case T___builtin_offsetof: return parse_offsetof();
7661 case T___builtin_va_start: return parse_va_start();
7662 case T___builtin_va_arg: return parse_va_arg();
7663 case T___builtin_expect:
7664 case T___builtin_alloca:
7665 case T___builtin_inf:
7666 case T___builtin_inff:
7667 case T___builtin_infl:
7668 case T___builtin_nan:
7669 case T___builtin_nanf:
7670 case T___builtin_nanl:
7671 case T___builtin_huge_val:
7672 case T___builtin_va_end: return parse_builtin_symbol();
7673 case T___builtin_isgreater:
7674 case T___builtin_isgreaterequal:
7675 case T___builtin_isless:
7676 case T___builtin_islessequal:
7677 case T___builtin_islessgreater:
7678 case T___builtin_isunordered: return parse_compare_builtin();
7679 case T___builtin_constant_p: return parse_builtin_constant();
7680 case T___builtin_prefetch: return parse_builtin_prefetch();
7681 case T__assume: return parse_assume();
7684 return parse_label_address();
7687 case '(': return parse_parenthesized_expression();
7688 case T___noop: return parse_noop_expression();
7691 errorf(HERE, "unexpected token '%K', expected an expression", &token);
7692 return create_invalid_expression();
7696 * Check if the expression has the character type and issue a warning then.
7698 static void check_for_char_index_type(const expression_t *expression)
7700 type_t *const type = expression->base.type;
7701 const type_t *const base_type = skip_typeref(type);
7703 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7704 warning.char_subscripts) {
7705 warningf(&expression->base.source_position,
7706 "array subscript has type '%T'", type);
7710 static expression_t *parse_array_expression(expression_t *left)
7712 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7715 add_anchor_token(']');
7717 expression_t *inside = parse_expression();
7719 type_t *const orig_type_left = left->base.type;
7720 type_t *const orig_type_inside = inside->base.type;
7722 type_t *const type_left = skip_typeref(orig_type_left);
7723 type_t *const type_inside = skip_typeref(orig_type_inside);
7725 type_t *return_type;
7726 array_access_expression_t *array_access = &expression->array_access;
7727 if (is_type_pointer(type_left)) {
7728 return_type = type_left->pointer.points_to;
7729 array_access->array_ref = left;
7730 array_access->index = inside;
7731 check_for_char_index_type(inside);
7732 } else if (is_type_pointer(type_inside)) {
7733 return_type = type_inside->pointer.points_to;
7734 array_access->array_ref = inside;
7735 array_access->index = left;
7736 array_access->flipped = true;
7737 check_for_char_index_type(left);
7739 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7741 "array access on object with non-pointer types '%T', '%T'",
7742 orig_type_left, orig_type_inside);
7744 return_type = type_error_type;
7745 array_access->array_ref = left;
7746 array_access->index = inside;
7749 expression->base.type = automatic_type_conversion(return_type);
7751 rem_anchor_token(']');
7757 static expression_t *parse_typeprop(expression_kind_t const kind)
7759 expression_t *tp_expression = allocate_expression_zero(kind);
7760 tp_expression->base.type = type_size_t;
7762 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7764 /* we only refer to a type property, mark this case */
7765 bool old = in_type_prop;
7766 in_type_prop = true;
7769 expression_t *expression;
7770 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7772 add_anchor_token(')');
7773 orig_type = parse_typename();
7774 rem_anchor_token(')');
7777 if (token.type == '{') {
7778 /* It was not sizeof(type) after all. It is sizeof of an expression
7779 * starting with a compound literal */
7780 expression = parse_compound_literal(orig_type);
7781 goto typeprop_expression;
7784 expression = parse_sub_expression(PREC_UNARY);
7786 typeprop_expression:
7787 tp_expression->typeprop.tp_expression = expression;
7789 orig_type = revert_automatic_type_conversion(expression);
7790 expression->base.type = orig_type;
7793 tp_expression->typeprop.type = orig_type;
7794 type_t const* const type = skip_typeref(orig_type);
7795 char const* const wrong_type =
7796 is_type_incomplete(type) ? "incomplete" :
7797 type->kind == TYPE_FUNCTION ? "function designator" :
7798 type->kind == TYPE_BITFIELD ? "bitfield" :
7800 if (wrong_type != NULL) {
7801 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7802 errorf(&tp_expression->base.source_position,
7803 "operand of %s expression must not be of %s type '%T'",
7804 what, wrong_type, orig_type);
7809 return tp_expression;
7812 static expression_t *parse_sizeof(void)
7814 return parse_typeprop(EXPR_SIZEOF);
7817 static expression_t *parse_alignof(void)
7819 return parse_typeprop(EXPR_ALIGNOF);
7822 static expression_t *parse_select_expression(expression_t *compound)
7824 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7825 select->select.compound = compound;
7827 assert(token.type == '.' || token.type == T_MINUSGREATER);
7828 bool is_pointer = (token.type == T_MINUSGREATER);
7831 if (token.type != T_IDENTIFIER) {
7832 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7835 symbol_t *symbol = token.v.symbol;
7838 type_t *const orig_type = compound->base.type;
7839 type_t *const type = skip_typeref(orig_type);
7842 bool saw_error = false;
7843 if (is_type_pointer(type)) {
7846 "request for member '%Y' in something not a struct or union, but '%T'",
7850 type_left = skip_typeref(type->pointer.points_to);
7852 if (is_pointer && is_type_valid(type)) {
7853 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7860 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7861 type_left->kind == TYPE_COMPOUND_UNION) {
7862 compound_t *compound = type_left->compound.compound;
7864 if (!compound->complete) {
7865 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7867 goto create_error_entry;
7870 entry = find_compound_entry(compound, symbol);
7871 if (entry == NULL) {
7872 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7873 goto create_error_entry;
7876 if (is_type_valid(type_left) && !saw_error) {
7878 "request for member '%Y' in something not a struct or union, but '%T'",
7882 return create_invalid_expression();
7885 assert(is_declaration(entry));
7886 select->select.compound_entry = entry;
7888 type_t *entry_type = entry->declaration.type;
7890 = get_qualified_type(entry_type, type_left->base.qualifiers);
7892 /* we always do the auto-type conversions; the & and sizeof parser contains
7893 * code to revert this! */
7894 select->base.type = automatic_type_conversion(res_type);
7896 type_t *skipped = skip_typeref(res_type);
7897 if (skipped->kind == TYPE_BITFIELD) {
7898 select->base.type = skipped->bitfield.base_type;
7904 static void check_call_argument(const function_parameter_t *parameter,
7905 call_argument_t *argument, unsigned pos)
7907 type_t *expected_type = parameter->type;
7908 type_t *expected_type_skip = skip_typeref(expected_type);
7909 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7910 expression_t *arg_expr = argument->expression;
7911 type_t *arg_type = skip_typeref(arg_expr->base.type);
7913 /* handle transparent union gnu extension */
7914 if (is_type_union(expected_type_skip)
7915 && (expected_type_skip->base.modifiers
7916 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7917 compound_t *union_decl = expected_type_skip->compound.compound;
7918 type_t *best_type = NULL;
7919 entity_t *entry = union_decl->members.entities;
7920 for ( ; entry != NULL; entry = entry->base.next) {
7921 assert(is_declaration(entry));
7922 type_t *decl_type = entry->declaration.type;
7923 error = semantic_assign(decl_type, arg_expr);
7924 if (error == ASSIGN_ERROR_INCOMPATIBLE
7925 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7928 if (error == ASSIGN_SUCCESS) {
7929 best_type = decl_type;
7930 } else if (best_type == NULL) {
7931 best_type = decl_type;
7935 if (best_type != NULL) {
7936 expected_type = best_type;
7940 error = semantic_assign(expected_type, arg_expr);
7941 argument->expression = create_implicit_cast(argument->expression,
7944 if (error != ASSIGN_SUCCESS) {
7945 /* report exact scope in error messages (like "in argument 3") */
7947 snprintf(buf, sizeof(buf), "call argument %u", pos);
7948 report_assign_error(error, expected_type, arg_expr, buf,
7949 &arg_expr->base.source_position);
7950 } else if (warning.traditional || warning.conversion) {
7951 type_t *const promoted_type = get_default_promoted_type(arg_type);
7952 if (!types_compatible(expected_type_skip, promoted_type) &&
7953 !types_compatible(expected_type_skip, type_void_ptr) &&
7954 !types_compatible(type_void_ptr, promoted_type)) {
7955 /* Deliberately show the skipped types in this warning */
7956 warningf(&arg_expr->base.source_position,
7957 "passing call argument %u as '%T' rather than '%T' due to prototype",
7958 pos, expected_type_skip, promoted_type);
7964 * Parse a call expression, ie. expression '( ... )'.
7966 * @param expression the function address
7968 static expression_t *parse_call_expression(expression_t *expression)
7970 expression_t *result = allocate_expression_zero(EXPR_CALL);
7971 call_expression_t *call = &result->call;
7972 call->function = expression;
7974 type_t *const orig_type = expression->base.type;
7975 type_t *const type = skip_typeref(orig_type);
7977 function_type_t *function_type = NULL;
7978 if (is_type_pointer(type)) {
7979 type_t *const to_type = skip_typeref(type->pointer.points_to);
7981 if (is_type_function(to_type)) {
7982 function_type = &to_type->function;
7983 call->base.type = function_type->return_type;
7987 if (function_type == NULL && is_type_valid(type)) {
7988 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7991 /* parse arguments */
7993 add_anchor_token(')');
7994 add_anchor_token(',');
7996 if (token.type != ')') {
7997 call_argument_t *last_argument = NULL;
8000 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8002 argument->expression = parse_assignment_expression();
8003 if (last_argument == NULL) {
8004 call->arguments = argument;
8006 last_argument->next = argument;
8008 last_argument = argument;
8010 if (token.type != ',')
8015 rem_anchor_token(',');
8016 rem_anchor_token(')');
8019 if (function_type == NULL)
8022 function_parameter_t *parameter = function_type->parameters;
8023 call_argument_t *argument = call->arguments;
8024 if (!function_type->unspecified_parameters) {
8025 for (unsigned pos = 0; parameter != NULL && argument != NULL;
8026 parameter = parameter->next, argument = argument->next) {
8027 check_call_argument(parameter, argument, ++pos);
8030 if (parameter != NULL) {
8031 errorf(HERE, "too few arguments to function '%E'", expression);
8032 } else if (argument != NULL && !function_type->variadic) {
8033 errorf(HERE, "too many arguments to function '%E'", expression);
8037 /* do default promotion */
8038 for (; argument != NULL; argument = argument->next) {
8039 type_t *type = argument->expression->base.type;
8041 type = get_default_promoted_type(type);
8043 argument->expression
8044 = create_implicit_cast(argument->expression, type);
8047 check_format(&result->call);
8049 if (warning.aggregate_return &&
8050 is_type_compound(skip_typeref(function_type->return_type))) {
8051 warningf(&result->base.source_position,
8052 "function call has aggregate value");
8059 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
8061 static bool same_compound_type(const type_t *type1, const type_t *type2)
8064 is_type_compound(type1) &&
8065 type1->kind == type2->kind &&
8066 type1->compound.compound == type2->compound.compound;
8069 static expression_t const *get_reference_address(expression_t const *expr)
8071 bool regular_take_address = true;
8073 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8074 expr = expr->unary.value;
8076 regular_take_address = false;
8079 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8082 expr = expr->unary.value;
8085 if (expr->kind != EXPR_REFERENCE)
8088 /* special case for functions which are automatically converted to a
8089 * pointer to function without an extra TAKE_ADDRESS operation */
8090 if (!regular_take_address &&
8091 expr->reference.entity->kind != ENTITY_FUNCTION) {
8098 static void warn_reference_address_as_bool(expression_t const* expr)
8100 if (!warning.address)
8103 expr = get_reference_address(expr);
8105 warningf(&expr->base.source_position,
8106 "the address of '%Y' will always evaluate as 'true'",
8107 expr->reference.entity->base.symbol);
8111 static void semantic_condition(expression_t const *const expr,
8112 char const *const context)
8114 type_t *const type = skip_typeref(expr->base.type);
8115 if (is_type_scalar(type)) {
8116 warn_reference_address_as_bool(expr);
8117 } else if (is_type_valid(type)) {
8118 errorf(&expr->base.source_position,
8119 "%s must have scalar type", context);
8124 * Parse a conditional expression, ie. 'expression ? ... : ...'.
8126 * @param expression the conditional expression
8128 static expression_t *parse_conditional_expression(expression_t *expression)
8130 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
8132 conditional_expression_t *conditional = &result->conditional;
8133 conditional->condition = expression;
8136 add_anchor_token(':');
8138 /* §6.5.15:2 The first operand shall have scalar type. */
8139 semantic_condition(expression, "condition of conditional operator");
8141 expression_t *true_expression = expression;
8142 bool gnu_cond = false;
8143 if (GNU_MODE && token.type == ':') {
8146 true_expression = parse_expression();
8148 rem_anchor_token(':');
8150 expression_t *false_expression =
8151 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
8153 type_t *const orig_true_type = true_expression->base.type;
8154 type_t *const orig_false_type = false_expression->base.type;
8155 type_t *const true_type = skip_typeref(orig_true_type);
8156 type_t *const false_type = skip_typeref(orig_false_type);
8159 type_t *result_type;
8160 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8161 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
8162 /* ISO/IEC 14882:1998(E) §5.16:2 */
8163 if (true_expression->kind == EXPR_UNARY_THROW) {
8164 result_type = false_type;
8165 } else if (false_expression->kind == EXPR_UNARY_THROW) {
8166 result_type = true_type;
8168 if (warning.other && (
8169 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8170 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
8172 warningf(&conditional->base.source_position,
8173 "ISO C forbids conditional expression with only one void side");
8175 result_type = type_void;
8177 } else if (is_type_arithmetic(true_type)
8178 && is_type_arithmetic(false_type)) {
8179 result_type = semantic_arithmetic(true_type, false_type);
8181 true_expression = create_implicit_cast(true_expression, result_type);
8182 false_expression = create_implicit_cast(false_expression, result_type);
8184 conditional->true_expression = true_expression;
8185 conditional->false_expression = false_expression;
8186 conditional->base.type = result_type;
8187 } else if (same_compound_type(true_type, false_type)) {
8188 /* just take 1 of the 2 types */
8189 result_type = true_type;
8190 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
8191 type_t *pointer_type;
8193 expression_t *other_expression;
8194 if (is_type_pointer(true_type) &&
8195 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
8196 pointer_type = true_type;
8197 other_type = false_type;
8198 other_expression = false_expression;
8200 pointer_type = false_type;
8201 other_type = true_type;
8202 other_expression = true_expression;
8205 if (is_null_pointer_constant(other_expression)) {
8206 result_type = pointer_type;
8207 } else if (is_type_pointer(other_type)) {
8208 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8209 type_t *to2 = skip_typeref(other_type->pointer.points_to);
8212 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8213 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8215 } else if (types_compatible(get_unqualified_type(to1),
8216 get_unqualified_type(to2))) {
8219 if (warning.other) {
8220 warningf(&conditional->base.source_position,
8221 "pointer types '%T' and '%T' in conditional expression are incompatible",
8222 true_type, false_type);
8227 type_t *const type =
8228 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8229 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8230 } else if (is_type_integer(other_type)) {
8231 if (warning.other) {
8232 warningf(&conditional->base.source_position,
8233 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8235 result_type = pointer_type;
8237 if (is_type_valid(other_type)) {
8238 type_error_incompatible("while parsing conditional",
8239 &expression->base.source_position, true_type, false_type);
8241 result_type = type_error_type;
8244 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8245 type_error_incompatible("while parsing conditional",
8246 &conditional->base.source_position, true_type,
8249 result_type = type_error_type;
8252 conditional->true_expression
8253 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8254 conditional->false_expression
8255 = create_implicit_cast(false_expression, result_type);
8256 conditional->base.type = result_type;
8259 return create_invalid_expression();
8263 * Parse an extension expression.
8265 static expression_t *parse_extension(void)
8267 eat(T___extension__);
8269 bool old_gcc_extension = in_gcc_extension;
8270 in_gcc_extension = true;
8271 expression_t *expression = parse_sub_expression(PREC_UNARY);
8272 in_gcc_extension = old_gcc_extension;
8277 * Parse a __builtin_classify_type() expression.
8279 static expression_t *parse_builtin_classify_type(void)
8281 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8282 result->base.type = type_int;
8284 eat(T___builtin_classify_type);
8287 add_anchor_token(')');
8288 expression_t *expression = parse_expression();
8289 rem_anchor_token(')');
8291 result->classify_type.type_expression = expression;
8295 return create_invalid_expression();
8299 * Parse a delete expression
8300 * ISO/IEC 14882:1998(E) §5.3.5
8302 static expression_t *parse_delete(void)
8304 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8305 result->base.type = type_void;
8309 if (token.type == '[') {
8311 result->kind = EXPR_UNARY_DELETE_ARRAY;
8316 expression_t *const value = parse_sub_expression(PREC_CAST);
8317 result->unary.value = value;
8319 type_t *const type = skip_typeref(value->base.type);
8320 if (!is_type_pointer(type)) {
8321 errorf(&value->base.source_position,
8322 "operand of delete must have pointer type");
8323 } else if (warning.other &&
8324 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8325 warningf(&value->base.source_position,
8326 "deleting 'void*' is undefined");
8333 * Parse a throw expression
8334 * ISO/IEC 14882:1998(E) §15:1
8336 static expression_t *parse_throw(void)
8338 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8339 result->base.type = type_void;
8343 expression_t *value = NULL;
8344 switch (token.type) {
8346 value = parse_assignment_expression();
8347 /* ISO/IEC 14882:1998(E) §15.1:3 */
8348 type_t *const orig_type = value->base.type;
8349 type_t *const type = skip_typeref(orig_type);
8350 if (is_type_incomplete(type)) {
8351 errorf(&value->base.source_position,
8352 "cannot throw object of incomplete type '%T'", orig_type);
8353 } else if (is_type_pointer(type)) {
8354 type_t *const points_to = skip_typeref(type->pointer.points_to);
8355 if (is_type_incomplete(points_to) &&
8356 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8357 errorf(&value->base.source_position,
8358 "cannot throw pointer to incomplete type '%T'", orig_type);
8366 result->unary.value = value;
8371 static bool check_pointer_arithmetic(const source_position_t *source_position,
8372 type_t *pointer_type,
8373 type_t *orig_pointer_type)
8375 type_t *points_to = pointer_type->pointer.points_to;
8376 points_to = skip_typeref(points_to);
8378 if (is_type_incomplete(points_to)) {
8379 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8380 errorf(source_position,
8381 "arithmetic with pointer to incomplete type '%T' not allowed",
8384 } else if (warning.pointer_arith) {
8385 warningf(source_position,
8386 "pointer of type '%T' used in arithmetic",
8389 } else if (is_type_function(points_to)) {
8391 errorf(source_position,
8392 "arithmetic with pointer to function type '%T' not allowed",
8395 } else if (warning.pointer_arith) {
8396 warningf(source_position,
8397 "pointer to a function '%T' used in arithmetic",
8404 static bool is_lvalue(const expression_t *expression)
8406 /* TODO: doesn't seem to be consistent with §6.3.2.1 (1) */
8407 switch (expression->kind) {
8408 case EXPR_REFERENCE:
8409 case EXPR_ARRAY_ACCESS:
8411 case EXPR_UNARY_DEREFERENCE:
8415 type_t *type = skip_typeref(expression->base.type);
8417 /* ISO/IEC 14882:1998(E) §3.10:3 */
8418 is_type_reference(type) ||
8419 /* Claim it is an lvalue, if the type is invalid. There was a parse
8420 * error before, which maybe prevented properly recognizing it as
8422 !is_type_valid(type);
8427 static void semantic_incdec(unary_expression_t *expression)
8429 type_t *const orig_type = expression->value->base.type;
8430 type_t *const type = skip_typeref(orig_type);
8431 if (is_type_pointer(type)) {
8432 if (!check_pointer_arithmetic(&expression->base.source_position,
8436 } else if (!is_type_real(type) && is_type_valid(type)) {
8437 /* TODO: improve error message */
8438 errorf(&expression->base.source_position,
8439 "operation needs an arithmetic or pointer type");
8442 if (!is_lvalue(expression->value)) {
8443 /* TODO: improve error message */
8444 errorf(&expression->base.source_position, "lvalue required as operand");
8446 expression->base.type = orig_type;
8449 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8451 type_t *const orig_type = expression->value->base.type;
8452 type_t *const type = skip_typeref(orig_type);
8453 if (!is_type_arithmetic(type)) {
8454 if (is_type_valid(type)) {
8455 /* TODO: improve error message */
8456 errorf(&expression->base.source_position,
8457 "operation needs an arithmetic type");
8462 expression->base.type = orig_type;
8465 static void semantic_unexpr_plus(unary_expression_t *expression)
8467 semantic_unexpr_arithmetic(expression);
8468 if (warning.traditional)
8469 warningf(&expression->base.source_position,
8470 "traditional C rejects the unary plus operator");
8473 static void semantic_not(unary_expression_t *expression)
8475 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8476 semantic_condition(expression->value, "operand of !");
8477 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8480 static void semantic_unexpr_integer(unary_expression_t *expression)
8482 type_t *const orig_type = expression->value->base.type;
8483 type_t *const type = skip_typeref(orig_type);
8484 if (!is_type_integer(type)) {
8485 if (is_type_valid(type)) {
8486 errorf(&expression->base.source_position,
8487 "operand of ~ must be of integer type");
8492 expression->base.type = orig_type;
8495 static void semantic_dereference(unary_expression_t *expression)
8497 type_t *const orig_type = expression->value->base.type;
8498 type_t *const type = skip_typeref(orig_type);
8499 if (!is_type_pointer(type)) {
8500 if (is_type_valid(type)) {
8501 errorf(&expression->base.source_position,
8502 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8507 type_t *result_type = type->pointer.points_to;
8508 result_type = automatic_type_conversion(result_type);
8509 expression->base.type = result_type;
8513 * Record that an address is taken (expression represents an lvalue).
8515 * @param expression the expression
8516 * @param may_be_register if true, the expression might be an register
8518 static void set_address_taken(expression_t *expression, bool may_be_register)
8520 if (expression->kind != EXPR_REFERENCE)
8523 entity_t *const entity = expression->reference.entity;
8525 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8528 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8529 && !may_be_register) {
8530 errorf(&expression->base.source_position,
8531 "address of register %s '%Y' requested",
8532 get_entity_kind_name(entity->kind), entity->base.symbol);
8535 if (entity->kind == ENTITY_VARIABLE) {
8536 entity->variable.address_taken = true;
8538 assert(entity->kind == ENTITY_PARAMETER);
8539 entity->parameter.address_taken = true;
8544 * Check the semantic of the address taken expression.
8546 static void semantic_take_addr(unary_expression_t *expression)
8548 expression_t *value = expression->value;
8549 value->base.type = revert_automatic_type_conversion(value);
8551 type_t *orig_type = value->base.type;
8552 type_t *type = skip_typeref(orig_type);
8553 if (!is_type_valid(type))
8557 if (!is_lvalue(value)) {
8558 errorf(&expression->base.source_position, "'&' requires an lvalue");
8560 if (type->kind == TYPE_BITFIELD) {
8561 errorf(&expression->base.source_position,
8562 "'&' not allowed on object with bitfield type '%T'",
8566 set_address_taken(value, false);
8568 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8571 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8572 static expression_t *parse_##unexpression_type(void) \
8574 expression_t *unary_expression \
8575 = allocate_expression_zero(unexpression_type); \
8577 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8579 sfunc(&unary_expression->unary); \
8581 return unary_expression; \
8584 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8585 semantic_unexpr_arithmetic)
8586 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8587 semantic_unexpr_plus)
8588 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8590 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8591 semantic_dereference)
8592 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8594 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8595 semantic_unexpr_integer)
8596 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8598 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8601 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8603 static expression_t *parse_##unexpression_type(expression_t *left) \
8605 expression_t *unary_expression \
8606 = allocate_expression_zero(unexpression_type); \
8608 unary_expression->unary.value = left; \
8610 sfunc(&unary_expression->unary); \
8612 return unary_expression; \
8615 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8616 EXPR_UNARY_POSTFIX_INCREMENT,
8618 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8619 EXPR_UNARY_POSTFIX_DECREMENT,
8622 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8624 /* TODO: handle complex + imaginary types */
8626 type_left = get_unqualified_type(type_left);
8627 type_right = get_unqualified_type(type_right);
8629 /* § 6.3.1.8 Usual arithmetic conversions */
8630 if (type_left == type_long_double || type_right == type_long_double) {
8631 return type_long_double;
8632 } else if (type_left == type_double || type_right == type_double) {
8634 } else if (type_left == type_float || type_right == type_float) {
8638 type_left = promote_integer(type_left);
8639 type_right = promote_integer(type_right);
8641 if (type_left == type_right)
8644 bool const signed_left = is_type_signed(type_left);
8645 bool const signed_right = is_type_signed(type_right);
8646 int const rank_left = get_rank(type_left);
8647 int const rank_right = get_rank(type_right);
8649 if (signed_left == signed_right)
8650 return rank_left >= rank_right ? type_left : type_right;
8659 u_rank = rank_right;
8660 u_type = type_right;
8662 s_rank = rank_right;
8663 s_type = type_right;
8668 if (u_rank >= s_rank)
8671 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8673 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8674 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8678 case ATOMIC_TYPE_INT: return type_unsigned_int;
8679 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8680 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8682 default: panic("invalid atomic type");
8687 * Check the semantic restrictions for a binary expression.
8689 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8691 expression_t *const left = expression->left;
8692 expression_t *const right = expression->right;
8693 type_t *const orig_type_left = left->base.type;
8694 type_t *const orig_type_right = right->base.type;
8695 type_t *const type_left = skip_typeref(orig_type_left);
8696 type_t *const type_right = skip_typeref(orig_type_right);
8698 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8699 /* TODO: improve error message */
8700 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8701 errorf(&expression->base.source_position,
8702 "operation needs arithmetic types");
8707 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8708 expression->left = create_implicit_cast(left, arithmetic_type);
8709 expression->right = create_implicit_cast(right, arithmetic_type);
8710 expression->base.type = arithmetic_type;
8713 static void warn_div_by_zero(binary_expression_t const *const expression)
8715 if (!warning.div_by_zero ||
8716 !is_type_integer(expression->base.type))
8719 expression_t const *const right = expression->right;
8720 /* The type of the right operand can be different for /= */
8721 if (is_type_integer(right->base.type) &&
8722 is_constant_expression(right) &&
8723 fold_constant(right) == 0) {
8724 warningf(&expression->base.source_position, "division by zero");
8729 * Check the semantic restrictions for a div/mod expression.
8731 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8732 semantic_binexpr_arithmetic(expression);
8733 warn_div_by_zero(expression);
8736 static void semantic_shift_op(binary_expression_t *expression)
8738 expression_t *const left = expression->left;
8739 expression_t *const right = expression->right;
8740 type_t *const orig_type_left = left->base.type;
8741 type_t *const orig_type_right = right->base.type;
8742 type_t * type_left = skip_typeref(orig_type_left);
8743 type_t * type_right = skip_typeref(orig_type_right);
8745 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8746 /* TODO: improve error message */
8747 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8748 errorf(&expression->base.source_position,
8749 "operands of shift operation must have integer types");
8754 type_left = promote_integer(type_left);
8755 type_right = promote_integer(type_right);
8757 expression->left = create_implicit_cast(left, type_left);
8758 expression->right = create_implicit_cast(right, type_right);
8759 expression->base.type = type_left;
8762 static void semantic_add(binary_expression_t *expression)
8764 expression_t *const left = expression->left;
8765 expression_t *const right = expression->right;
8766 type_t *const orig_type_left = left->base.type;
8767 type_t *const orig_type_right = right->base.type;
8768 type_t *const type_left = skip_typeref(orig_type_left);
8769 type_t *const type_right = skip_typeref(orig_type_right);
8772 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8773 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8774 expression->left = create_implicit_cast(left, arithmetic_type);
8775 expression->right = create_implicit_cast(right, arithmetic_type);
8776 expression->base.type = arithmetic_type;
8778 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8779 check_pointer_arithmetic(&expression->base.source_position,
8780 type_left, orig_type_left);
8781 expression->base.type = type_left;
8782 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8783 check_pointer_arithmetic(&expression->base.source_position,
8784 type_right, orig_type_right);
8785 expression->base.type = type_right;
8786 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8787 errorf(&expression->base.source_position,
8788 "invalid operands to binary + ('%T', '%T')",
8789 orig_type_left, orig_type_right);
8793 static void semantic_sub(binary_expression_t *expression)
8795 expression_t *const left = expression->left;
8796 expression_t *const right = expression->right;
8797 type_t *const orig_type_left = left->base.type;
8798 type_t *const orig_type_right = right->base.type;
8799 type_t *const type_left = skip_typeref(orig_type_left);
8800 type_t *const type_right = skip_typeref(orig_type_right);
8801 source_position_t const *const pos = &expression->base.source_position;
8804 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8805 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8806 expression->left = create_implicit_cast(left, arithmetic_type);
8807 expression->right = create_implicit_cast(right, arithmetic_type);
8808 expression->base.type = arithmetic_type;
8810 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8811 check_pointer_arithmetic(&expression->base.source_position,
8812 type_left, orig_type_left);
8813 expression->base.type = type_left;
8814 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8815 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8816 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8817 if (!types_compatible(unqual_left, unqual_right)) {
8819 "subtracting pointers to incompatible types '%T' and '%T'",
8820 orig_type_left, orig_type_right);
8821 } else if (!is_type_object(unqual_left)) {
8822 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8823 errorf(pos, "subtracting pointers to non-object types '%T'",
8825 } else if (warning.other) {
8826 warningf(pos, "subtracting pointers to void");
8829 expression->base.type = type_ptrdiff_t;
8830 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8831 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8832 orig_type_left, orig_type_right);
8836 static void warn_string_literal_address(expression_t const* expr)
8838 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8839 expr = expr->unary.value;
8840 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8842 expr = expr->unary.value;
8845 if (expr->kind == EXPR_STRING_LITERAL ||
8846 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8847 warningf(&expr->base.source_position,
8848 "comparison with string literal results in unspecified behaviour");
8853 * Check the semantics of comparison expressions.
8855 * @param expression The expression to check.
8857 static void semantic_comparison(binary_expression_t *expression)
8859 expression_t *left = expression->left;
8860 expression_t *right = expression->right;
8862 if (warning.address) {
8863 warn_string_literal_address(left);
8864 warn_string_literal_address(right);
8866 expression_t const* const func_left = get_reference_address(left);
8867 if (func_left != NULL && is_null_pointer_constant(right)) {
8868 warningf(&expression->base.source_position,
8869 "the address of '%Y' will never be NULL",
8870 func_left->reference.entity->base.symbol);
8873 expression_t const* const func_right = get_reference_address(right);
8874 if (func_right != NULL && is_null_pointer_constant(right)) {
8875 warningf(&expression->base.source_position,
8876 "the address of '%Y' will never be NULL",
8877 func_right->reference.entity->base.symbol);
8881 type_t *orig_type_left = left->base.type;
8882 type_t *orig_type_right = right->base.type;
8883 type_t *type_left = skip_typeref(orig_type_left);
8884 type_t *type_right = skip_typeref(orig_type_right);
8886 /* TODO non-arithmetic types */
8887 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8888 /* test for signed vs unsigned compares */
8889 if (warning.sign_compare &&
8890 (expression->base.kind != EXPR_BINARY_EQUAL &&
8891 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
8892 (is_type_signed(type_left) != is_type_signed(type_right))) {
8894 /* check if 1 of the operands is a constant, in this case we just
8895 * check wether we can safely represent the resulting constant in
8896 * the type of the other operand. */
8897 expression_t *const_expr = NULL;
8898 expression_t *other_expr = NULL;
8900 if (is_constant_expression(left)) {
8903 } else if (is_constant_expression(right)) {
8908 if (const_expr != NULL) {
8909 type_t *other_type = skip_typeref(other_expr->base.type);
8910 long val = fold_constant(const_expr);
8911 /* TODO: check if val can be represented by other_type */
8915 warningf(&expression->base.source_position,
8916 "comparison between signed and unsigned");
8918 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8919 expression->left = create_implicit_cast(left, arithmetic_type);
8920 expression->right = create_implicit_cast(right, arithmetic_type);
8921 expression->base.type = arithmetic_type;
8922 if (warning.float_equal &&
8923 (expression->base.kind == EXPR_BINARY_EQUAL ||
8924 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8925 is_type_float(arithmetic_type)) {
8926 warningf(&expression->base.source_position,
8927 "comparing floating point with == or != is unsafe");
8929 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8930 /* TODO check compatibility */
8931 } else if (is_type_pointer(type_left)) {
8932 expression->right = create_implicit_cast(right, type_left);
8933 } else if (is_type_pointer(type_right)) {
8934 expression->left = create_implicit_cast(left, type_right);
8935 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8936 type_error_incompatible("invalid operands in comparison",
8937 &expression->base.source_position,
8938 type_left, type_right);
8940 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8944 * Checks if a compound type has constant fields.
8946 static bool has_const_fields(const compound_type_t *type)
8948 compound_t *compound = type->compound;
8949 entity_t *entry = compound->members.entities;
8951 for (; entry != NULL; entry = entry->base.next) {
8952 if (!is_declaration(entry))
8955 const type_t *decl_type = skip_typeref(entry->declaration.type);
8956 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8963 static bool is_valid_assignment_lhs(expression_t const* const left)
8965 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8966 type_t *const type_left = skip_typeref(orig_type_left);
8968 if (!is_lvalue(left)) {
8969 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8974 if (left->kind == EXPR_REFERENCE
8975 && left->reference.entity->kind == ENTITY_FUNCTION) {
8976 errorf(HERE, "cannot assign to function '%E'", left);
8980 if (is_type_array(type_left)) {
8981 errorf(HERE, "cannot assign to array '%E'", left);
8984 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8985 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8989 if (is_type_incomplete(type_left)) {
8990 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8991 left, orig_type_left);
8994 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8995 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8996 left, orig_type_left);
9003 static void semantic_arithmetic_assign(binary_expression_t *expression)
9005 expression_t *left = expression->left;
9006 expression_t *right = expression->right;
9007 type_t *orig_type_left = left->base.type;
9008 type_t *orig_type_right = right->base.type;
9010 if (!is_valid_assignment_lhs(left))
9013 type_t *type_left = skip_typeref(orig_type_left);
9014 type_t *type_right = skip_typeref(orig_type_right);
9016 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
9017 /* TODO: improve error message */
9018 if (is_type_valid(type_left) && is_type_valid(type_right)) {
9019 errorf(&expression->base.source_position,
9020 "operation needs arithmetic types");
9025 /* combined instructions are tricky. We can't create an implicit cast on
9026 * the left side, because we need the uncasted form for the store.
9027 * The ast2firm pass has to know that left_type must be right_type
9028 * for the arithmetic operation and create a cast by itself */
9029 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9030 expression->right = create_implicit_cast(right, arithmetic_type);
9031 expression->base.type = type_left;
9034 static void semantic_divmod_assign(binary_expression_t *expression)
9036 semantic_arithmetic_assign(expression);
9037 warn_div_by_zero(expression);
9040 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
9042 expression_t *const left = expression->left;
9043 expression_t *const right = expression->right;
9044 type_t *const orig_type_left = left->base.type;
9045 type_t *const orig_type_right = right->base.type;
9046 type_t *const type_left = skip_typeref(orig_type_left);
9047 type_t *const type_right = skip_typeref(orig_type_right);
9049 if (!is_valid_assignment_lhs(left))
9052 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9053 /* combined instructions are tricky. We can't create an implicit cast on
9054 * the left side, because we need the uncasted form for the store.
9055 * The ast2firm pass has to know that left_type must be right_type
9056 * for the arithmetic operation and create a cast by itself */
9057 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
9058 expression->right = create_implicit_cast(right, arithmetic_type);
9059 expression->base.type = type_left;
9060 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9061 check_pointer_arithmetic(&expression->base.source_position,
9062 type_left, orig_type_left);
9063 expression->base.type = type_left;
9064 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9065 errorf(&expression->base.source_position,
9066 "incompatible types '%T' and '%T' in assignment",
9067 orig_type_left, orig_type_right);
9072 * Check the semantic restrictions of a logical expression.
9074 static void semantic_logical_op(binary_expression_t *expression)
9076 /* §6.5.13:2 Each of the operands shall have scalar type.
9077 * §6.5.14:2 Each of the operands shall have scalar type. */
9078 semantic_condition(expression->left, "left operand of logical operator");
9079 semantic_condition(expression->right, "right operand of logical operator");
9080 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9084 * Check the semantic restrictions of a binary assign expression.
9086 static void semantic_binexpr_assign(binary_expression_t *expression)
9088 expression_t *left = expression->left;
9089 type_t *orig_type_left = left->base.type;
9091 if (!is_valid_assignment_lhs(left))
9094 assign_error_t error = semantic_assign(orig_type_left, expression->right);
9095 report_assign_error(error, orig_type_left, expression->right,
9096 "assignment", &left->base.source_position);
9097 expression->right = create_implicit_cast(expression->right, orig_type_left);
9098 expression->base.type = orig_type_left;
9102 * Determine if the outermost operation (or parts thereof) of the given
9103 * expression has no effect in order to generate a warning about this fact.
9104 * Therefore in some cases this only examines some of the operands of the
9105 * expression (see comments in the function and examples below).
9107 * f() + 23; // warning, because + has no effect
9108 * x || f(); // no warning, because x controls execution of f()
9109 * x ? y : f(); // warning, because y has no effect
9110 * (void)x; // no warning to be able to suppress the warning
9111 * This function can NOT be used for an "expression has definitely no effect"-
9113 static bool expression_has_effect(const expression_t *const expr)
9115 switch (expr->kind) {
9116 case EXPR_UNKNOWN: break;
9117 case EXPR_INVALID: return true; /* do NOT warn */
9118 case EXPR_REFERENCE: return false;
9119 case EXPR_REFERENCE_ENUM_VALUE: return false;
9120 /* suppress the warning for microsoft __noop operations */
9121 case EXPR_CONST: return expr->conste.is_ms_noop;
9122 case EXPR_CHARACTER_CONSTANT: return false;
9123 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
9124 case EXPR_STRING_LITERAL: return false;
9125 case EXPR_WIDE_STRING_LITERAL: return false;
9126 case EXPR_LABEL_ADDRESS: return false;
9129 const call_expression_t *const call = &expr->call;
9130 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
9133 switch (call->function->builtin_symbol.symbol->ID) {
9134 case T___builtin_va_end: return true;
9135 default: return false;
9139 /* Generate the warning if either the left or right hand side of a
9140 * conditional expression has no effect */
9141 case EXPR_CONDITIONAL: {
9142 const conditional_expression_t *const cond = &expr->conditional;
9144 expression_has_effect(cond->true_expression) &&
9145 expression_has_effect(cond->false_expression);
9148 case EXPR_SELECT: return false;
9149 case EXPR_ARRAY_ACCESS: return false;
9150 case EXPR_SIZEOF: return false;
9151 case EXPR_CLASSIFY_TYPE: return false;
9152 case EXPR_ALIGNOF: return false;
9154 case EXPR_FUNCNAME: return false;
9155 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
9156 case EXPR_BUILTIN_CONSTANT_P: return false;
9157 case EXPR_BUILTIN_PREFETCH: return true;
9158 case EXPR_OFFSETOF: return false;
9159 case EXPR_VA_START: return true;
9160 case EXPR_VA_ARG: return true;
9161 case EXPR_STATEMENT: return true; // TODO
9162 case EXPR_COMPOUND_LITERAL: return false;
9164 case EXPR_UNARY_NEGATE: return false;
9165 case EXPR_UNARY_PLUS: return false;
9166 case EXPR_UNARY_BITWISE_NEGATE: return false;
9167 case EXPR_UNARY_NOT: return false;
9168 case EXPR_UNARY_DEREFERENCE: return false;
9169 case EXPR_UNARY_TAKE_ADDRESS: return false;
9170 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
9171 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
9172 case EXPR_UNARY_PREFIX_INCREMENT: return true;
9173 case EXPR_UNARY_PREFIX_DECREMENT: return true;
9175 /* Treat void casts as if they have an effect in order to being able to
9176 * suppress the warning */
9177 case EXPR_UNARY_CAST: {
9178 type_t *const type = skip_typeref(expr->base.type);
9179 return is_type_atomic(type, ATOMIC_TYPE_VOID);
9182 case EXPR_UNARY_CAST_IMPLICIT: return true;
9183 case EXPR_UNARY_ASSUME: return true;
9184 case EXPR_UNARY_DELETE: return true;
9185 case EXPR_UNARY_DELETE_ARRAY: return true;
9186 case EXPR_UNARY_THROW: return true;
9188 case EXPR_BINARY_ADD: return false;
9189 case EXPR_BINARY_SUB: return false;
9190 case EXPR_BINARY_MUL: return false;
9191 case EXPR_BINARY_DIV: return false;
9192 case EXPR_BINARY_MOD: return false;
9193 case EXPR_BINARY_EQUAL: return false;
9194 case EXPR_BINARY_NOTEQUAL: return false;
9195 case EXPR_BINARY_LESS: return false;
9196 case EXPR_BINARY_LESSEQUAL: return false;
9197 case EXPR_BINARY_GREATER: return false;
9198 case EXPR_BINARY_GREATEREQUAL: return false;
9199 case EXPR_BINARY_BITWISE_AND: return false;
9200 case EXPR_BINARY_BITWISE_OR: return false;
9201 case EXPR_BINARY_BITWISE_XOR: return false;
9202 case EXPR_BINARY_SHIFTLEFT: return false;
9203 case EXPR_BINARY_SHIFTRIGHT: return false;
9204 case EXPR_BINARY_ASSIGN: return true;
9205 case EXPR_BINARY_MUL_ASSIGN: return true;
9206 case EXPR_BINARY_DIV_ASSIGN: return true;
9207 case EXPR_BINARY_MOD_ASSIGN: return true;
9208 case EXPR_BINARY_ADD_ASSIGN: return true;
9209 case EXPR_BINARY_SUB_ASSIGN: return true;
9210 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
9211 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
9212 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9213 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9214 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
9216 /* Only examine the right hand side of && and ||, because the left hand
9217 * side already has the effect of controlling the execution of the right
9219 case EXPR_BINARY_LOGICAL_AND:
9220 case EXPR_BINARY_LOGICAL_OR:
9221 /* Only examine the right hand side of a comma expression, because the left
9222 * hand side has a separate warning */
9223 case EXPR_BINARY_COMMA:
9224 return expression_has_effect(expr->binary.right);
9226 case EXPR_BINARY_ISGREATER: return false;
9227 case EXPR_BINARY_ISGREATEREQUAL: return false;
9228 case EXPR_BINARY_ISLESS: return false;
9229 case EXPR_BINARY_ISLESSEQUAL: return false;
9230 case EXPR_BINARY_ISLESSGREATER: return false;
9231 case EXPR_BINARY_ISUNORDERED: return false;
9234 internal_errorf(HERE, "unexpected expression");
9237 static void semantic_comma(binary_expression_t *expression)
9239 if (warning.unused_value) {
9240 const expression_t *const left = expression->left;
9241 if (!expression_has_effect(left)) {
9242 warningf(&left->base.source_position,
9243 "left-hand operand of comma expression has no effect");
9246 expression->base.type = expression->right->base.type;
9250 * @param prec_r precedence of the right operand
9252 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9253 static expression_t *parse_##binexpression_type(expression_t *left) \
9255 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9256 binexpr->binary.left = left; \
9259 expression_t *right = parse_sub_expression(prec_r); \
9261 binexpr->binary.right = right; \
9262 sfunc(&binexpr->binary); \
9267 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9268 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9269 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9270 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9271 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9272 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9273 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9274 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9275 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9276 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9277 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9278 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9279 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9280 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9281 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9282 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9283 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9284 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9285 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9286 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9287 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9288 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9289 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9290 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9291 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9292 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9293 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9294 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9295 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9296 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9299 static expression_t *parse_sub_expression(precedence_t precedence)
9301 if (token.type < 0) {
9302 return expected_expression_error();
9305 expression_parser_function_t *parser
9306 = &expression_parsers[token.type];
9307 source_position_t source_position = token.source_position;
9310 if (parser->parser != NULL) {
9311 left = parser->parser();
9313 left = parse_primary_expression();
9315 assert(left != NULL);
9316 left->base.source_position = source_position;
9319 if (token.type < 0) {
9320 return expected_expression_error();
9323 parser = &expression_parsers[token.type];
9324 if (parser->infix_parser == NULL)
9326 if (parser->infix_precedence < precedence)
9329 left = parser->infix_parser(left);
9331 assert(left != NULL);
9332 assert(left->kind != EXPR_UNKNOWN);
9333 left->base.source_position = source_position;
9340 * Parse an expression.
9342 static expression_t *parse_expression(void)
9344 return parse_sub_expression(PREC_EXPRESSION);
9348 * Register a parser for a prefix-like operator.
9350 * @param parser the parser function
9351 * @param token_type the token type of the prefix token
9353 static void register_expression_parser(parse_expression_function parser,
9356 expression_parser_function_t *entry = &expression_parsers[token_type];
9358 if (entry->parser != NULL) {
9359 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9360 panic("trying to register multiple expression parsers for a token");
9362 entry->parser = parser;
9366 * Register a parser for an infix operator with given precedence.
9368 * @param parser the parser function
9369 * @param token_type the token type of the infix operator
9370 * @param precedence the precedence of the operator
9372 static void register_infix_parser(parse_expression_infix_function parser,
9373 int token_type, unsigned precedence)
9375 expression_parser_function_t *entry = &expression_parsers[token_type];
9377 if (entry->infix_parser != NULL) {
9378 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9379 panic("trying to register multiple infix expression parsers for a "
9382 entry->infix_parser = parser;
9383 entry->infix_precedence = precedence;
9387 * Initialize the expression parsers.
9389 static void init_expression_parsers(void)
9391 memset(&expression_parsers, 0, sizeof(expression_parsers));
9393 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9394 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9395 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9396 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9397 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9398 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9399 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9400 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9401 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9402 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9403 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9404 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9405 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9406 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9407 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9408 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9409 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9410 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9411 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9412 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9413 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9414 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9415 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9416 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9417 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9418 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9419 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9420 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9421 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9422 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9423 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9424 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9425 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9426 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9427 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9428 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9429 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9431 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9432 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9433 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9434 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9435 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9436 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9437 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9438 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9439 register_expression_parser(parse_sizeof, T_sizeof);
9440 register_expression_parser(parse_alignof, T___alignof__);
9441 register_expression_parser(parse_extension, T___extension__);
9442 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9443 register_expression_parser(parse_delete, T_delete);
9444 register_expression_parser(parse_throw, T_throw);
9448 * Parse a asm statement arguments specification.
9450 static asm_argument_t *parse_asm_arguments(bool is_out)
9452 asm_argument_t *result = NULL;
9453 asm_argument_t **anchor = &result;
9455 while (token.type == T_STRING_LITERAL || token.type == '[') {
9456 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9457 memset(argument, 0, sizeof(argument[0]));
9459 if (token.type == '[') {
9461 if (token.type != T_IDENTIFIER) {
9462 parse_error_expected("while parsing asm argument",
9463 T_IDENTIFIER, NULL);
9466 argument->symbol = token.v.symbol;
9471 argument->constraints = parse_string_literals();
9473 add_anchor_token(')');
9474 expression_t *expression = parse_expression();
9475 rem_anchor_token(')');
9477 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9478 * change size or type representation (e.g. int -> long is ok, but
9479 * int -> float is not) */
9480 if (expression->kind == EXPR_UNARY_CAST) {
9481 type_t *const type = expression->base.type;
9482 type_kind_t const kind = type->kind;
9483 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9486 if (kind == TYPE_ATOMIC) {
9487 atomic_type_kind_t const akind = type->atomic.akind;
9488 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9489 size = get_atomic_type_size(akind);
9491 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9492 size = get_atomic_type_size(get_intptr_kind());
9496 expression_t *const value = expression->unary.value;
9497 type_t *const value_type = value->base.type;
9498 type_kind_t const value_kind = value_type->kind;
9500 unsigned value_flags;
9501 unsigned value_size;
9502 if (value_kind == TYPE_ATOMIC) {
9503 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9504 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9505 value_size = get_atomic_type_size(value_akind);
9506 } else if (value_kind == TYPE_POINTER) {
9507 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9508 value_size = get_atomic_type_size(get_intptr_kind());
9513 if (value_flags != flags || value_size != size)
9517 } while (expression->kind == EXPR_UNARY_CAST);
9521 if (!is_lvalue(expression)) {
9522 errorf(&expression->base.source_position,
9523 "asm output argument is not an lvalue");
9526 if (argument->constraints.begin[0] == '+')
9527 mark_vars_read(expression, NULL);
9529 mark_vars_read(expression, NULL);
9531 argument->expression = expression;
9534 set_address_taken(expression, true);
9537 anchor = &argument->next;
9539 if (token.type != ',')
9550 * Parse a asm statement clobber specification.
9552 static asm_clobber_t *parse_asm_clobbers(void)
9554 asm_clobber_t *result = NULL;
9555 asm_clobber_t *last = NULL;
9557 while (token.type == T_STRING_LITERAL) {
9558 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9559 clobber->clobber = parse_string_literals();
9562 last->next = clobber;
9568 if (token.type != ',')
9577 * Parse an asm statement.
9579 static statement_t *parse_asm_statement(void)
9581 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9582 asm_statement_t *asm_statement = &statement->asms;
9586 if (token.type == T_volatile) {
9588 asm_statement->is_volatile = true;
9592 add_anchor_token(')');
9593 add_anchor_token(':');
9594 asm_statement->asm_text = parse_string_literals();
9596 if (token.type != ':') {
9597 rem_anchor_token(':');
9602 asm_statement->outputs = parse_asm_arguments(true);
9603 if (token.type != ':') {
9604 rem_anchor_token(':');
9609 asm_statement->inputs = parse_asm_arguments(false);
9610 if (token.type != ':') {
9611 rem_anchor_token(':');
9614 rem_anchor_token(':');
9617 asm_statement->clobbers = parse_asm_clobbers();
9620 rem_anchor_token(')');
9624 if (asm_statement->outputs == NULL) {
9625 /* GCC: An 'asm' instruction without any output operands will be treated
9626 * identically to a volatile 'asm' instruction. */
9627 asm_statement->is_volatile = true;
9632 return create_invalid_statement();
9636 * Parse a case statement.
9638 static statement_t *parse_case_statement(void)
9640 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9641 source_position_t *const pos = &statement->base.source_position;
9645 expression_t *const expression = parse_expression();
9646 statement->case_label.expression = expression;
9647 if (!is_constant_expression(expression)) {
9648 /* This check does not prevent the error message in all cases of an
9649 * prior error while parsing the expression. At least it catches the
9650 * common case of a mistyped enum entry. */
9651 if (is_type_valid(skip_typeref(expression->base.type))) {
9652 errorf(pos, "case label does not reduce to an integer constant");
9654 statement->case_label.is_bad = true;
9656 long const val = fold_constant(expression);
9657 statement->case_label.first_case = val;
9658 statement->case_label.last_case = val;
9662 if (token.type == T_DOTDOTDOT) {
9664 expression_t *const end_range = parse_expression();
9665 statement->case_label.end_range = end_range;
9666 if (!is_constant_expression(end_range)) {
9667 /* This check does not prevent the error message in all cases of an
9668 * prior error while parsing the expression. At least it catches the
9669 * common case of a mistyped enum entry. */
9670 if (is_type_valid(skip_typeref(end_range->base.type))) {
9671 errorf(pos, "case range does not reduce to an integer constant");
9673 statement->case_label.is_bad = true;
9675 long const val = fold_constant(end_range);
9676 statement->case_label.last_case = val;
9678 if (warning.other && val < statement->case_label.first_case) {
9679 statement->case_label.is_empty_range = true;
9680 warningf(pos, "empty range specified");
9686 PUSH_PARENT(statement);
9691 if (current_switch != NULL) {
9692 if (! statement->case_label.is_bad) {
9693 /* Check for duplicate case values */
9694 case_label_statement_t *c = &statement->case_label;
9695 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9696 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9699 if (c->last_case < l->first_case || c->first_case > l->last_case)
9702 errorf(pos, "duplicate case value (previously used %P)",
9703 &l->base.source_position);
9707 /* link all cases into the switch statement */
9708 if (current_switch->last_case == NULL) {
9709 current_switch->first_case = &statement->case_label;
9711 current_switch->last_case->next = &statement->case_label;
9713 current_switch->last_case = &statement->case_label;
9715 errorf(pos, "case label not within a switch statement");
9718 statement_t *const inner_stmt = parse_statement();
9719 statement->case_label.statement = inner_stmt;
9720 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9721 errorf(&inner_stmt->base.source_position, "declaration after case label");
9729 * Parse a default statement.
9731 static statement_t *parse_default_statement(void)
9733 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9737 PUSH_PARENT(statement);
9740 if (current_switch != NULL) {
9741 const case_label_statement_t *def_label = current_switch->default_label;
9742 if (def_label != NULL) {
9743 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9744 &def_label->base.source_position);
9746 current_switch->default_label = &statement->case_label;
9748 /* link all cases into the switch statement */
9749 if (current_switch->last_case == NULL) {
9750 current_switch->first_case = &statement->case_label;
9752 current_switch->last_case->next = &statement->case_label;
9754 current_switch->last_case = &statement->case_label;
9757 errorf(&statement->base.source_position,
9758 "'default' label not within a switch statement");
9761 statement_t *const inner_stmt = parse_statement();
9762 statement->case_label.statement = inner_stmt;
9763 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9764 errorf(&inner_stmt->base.source_position, "declaration after default label");
9771 return create_invalid_statement();
9775 * Parse a label statement.
9777 static statement_t *parse_label_statement(void)
9779 assert(token.type == T_IDENTIFIER);
9780 symbol_t *symbol = token.v.symbol;
9781 label_t *label = get_label(symbol);
9783 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9784 statement->label.label = label;
9788 PUSH_PARENT(statement);
9790 /* if statement is already set then the label is defined twice,
9791 * otherwise it was just mentioned in a goto/local label declaration so far
9793 if (label->statement != NULL) {
9794 errorf(HERE, "duplicate label '%Y' (declared %P)",
9795 symbol, &label->base.source_position);
9797 label->base.source_position = token.source_position;
9798 label->statement = statement;
9803 if (token.type == '}') {
9804 /* TODO only warn? */
9805 if (warning.other && false) {
9806 warningf(HERE, "label at end of compound statement");
9807 statement->label.statement = create_empty_statement();
9809 errorf(HERE, "label at end of compound statement");
9810 statement->label.statement = create_invalid_statement();
9812 } else if (token.type == ';') {
9813 /* Eat an empty statement here, to avoid the warning about an empty
9814 * statement after a label. label:; is commonly used to have a label
9815 * before a closing brace. */
9816 statement->label.statement = create_empty_statement();
9819 statement_t *const inner_stmt = parse_statement();
9820 statement->label.statement = inner_stmt;
9821 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9822 errorf(&inner_stmt->base.source_position, "declaration after label");
9826 /* remember the labels in a list for later checking */
9827 *label_anchor = &statement->label;
9828 label_anchor = &statement->label.next;
9835 * Parse an if statement.
9837 static statement_t *parse_if(void)
9839 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9843 PUSH_PARENT(statement);
9845 add_anchor_token('{');
9848 add_anchor_token(')');
9849 expression_t *const expr = parse_expression();
9850 statement->ifs.condition = expr;
9851 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9853 semantic_condition(expr, "condition of 'if'-statment");
9854 mark_vars_read(expr, NULL);
9855 rem_anchor_token(')');
9859 rem_anchor_token('{');
9861 add_anchor_token(T_else);
9862 statement->ifs.true_statement = parse_statement();
9863 rem_anchor_token(T_else);
9865 if (token.type == T_else) {
9867 statement->ifs.false_statement = parse_statement();
9875 * Check that all enums are handled in a switch.
9877 * @param statement the switch statement to check
9879 static void check_enum_cases(const switch_statement_t *statement) {
9880 const type_t *type = skip_typeref(statement->expression->base.type);
9881 if (! is_type_enum(type))
9883 const enum_type_t *enumt = &type->enumt;
9885 /* if we have a default, no warnings */
9886 if (statement->default_label != NULL)
9889 /* FIXME: calculation of value should be done while parsing */
9890 /* TODO: quadratic algorithm here. Change to an n log n one */
9891 long last_value = -1;
9892 const entity_t *entry = enumt->enume->base.next;
9893 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9894 entry = entry->base.next) {
9895 const expression_t *expression = entry->enum_value.value;
9896 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9898 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9899 if (l->expression == NULL)
9901 if (l->first_case <= value && value <= l->last_case) {
9907 warningf(&statement->base.source_position,
9908 "enumeration value '%Y' not handled in switch",
9909 entry->base.symbol);
9916 * Parse a switch statement.
9918 static statement_t *parse_switch(void)
9920 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9924 PUSH_PARENT(statement);
9927 add_anchor_token(')');
9928 expression_t *const expr = parse_expression();
9929 mark_vars_read(expr, NULL);
9930 type_t * type = skip_typeref(expr->base.type);
9931 if (is_type_integer(type)) {
9932 type = promote_integer(type);
9933 if (warning.traditional) {
9934 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9935 warningf(&expr->base.source_position,
9936 "'%T' switch expression not converted to '%T' in ISO C",
9940 } else if (is_type_valid(type)) {
9941 errorf(&expr->base.source_position,
9942 "switch quantity is not an integer, but '%T'", type);
9943 type = type_error_type;
9945 statement->switchs.expression = create_implicit_cast(expr, type);
9947 rem_anchor_token(')');
9949 switch_statement_t *rem = current_switch;
9950 current_switch = &statement->switchs;
9951 statement->switchs.body = parse_statement();
9952 current_switch = rem;
9954 if (warning.switch_default &&
9955 statement->switchs.default_label == NULL) {
9956 warningf(&statement->base.source_position, "switch has no default case");
9958 if (warning.switch_enum)
9959 check_enum_cases(&statement->switchs);
9965 return create_invalid_statement();
9968 static statement_t *parse_loop_body(statement_t *const loop)
9970 statement_t *const rem = current_loop;
9971 current_loop = loop;
9973 statement_t *const body = parse_statement();
9980 * Parse a while statement.
9982 static statement_t *parse_while(void)
9984 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9988 PUSH_PARENT(statement);
9991 add_anchor_token(')');
9992 expression_t *const cond = parse_expression();
9993 statement->whiles.condition = cond;
9994 /* §6.8.5:2 The controlling expression of an iteration statement shall
9995 * have scalar type. */
9996 semantic_condition(cond, "condition of 'while'-statement");
9997 mark_vars_read(cond, NULL);
9998 rem_anchor_token(')');
10001 statement->whiles.body = parse_loop_body(statement);
10007 return create_invalid_statement();
10011 * Parse a do statement.
10013 static statement_t *parse_do(void)
10015 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
10019 PUSH_PARENT(statement);
10021 add_anchor_token(T_while);
10022 statement->do_while.body = parse_loop_body(statement);
10023 rem_anchor_token(T_while);
10027 add_anchor_token(')');
10028 expression_t *const cond = parse_expression();
10029 statement->do_while.condition = cond;
10030 /* §6.8.5:2 The controlling expression of an iteration statement shall
10031 * have scalar type. */
10032 semantic_condition(cond, "condition of 'do-while'-statement");
10033 mark_vars_read(cond, NULL);
10034 rem_anchor_token(')');
10042 return create_invalid_statement();
10046 * Parse a for statement.
10048 static statement_t *parse_for(void)
10050 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
10054 PUSH_PARENT(statement);
10056 size_t const top = environment_top();
10057 scope_t *old_scope = scope_push(&statement->fors.scope);
10060 add_anchor_token(')');
10062 if (token.type == ';') {
10064 } else if (is_declaration_specifier(&token, false)) {
10065 parse_declaration(record_entity, DECL_FLAGS_NONE);
10067 add_anchor_token(';');
10068 expression_t *const init = parse_expression();
10069 statement->fors.initialisation = init;
10070 mark_vars_read(init, ENT_ANY);
10071 if (warning.unused_value && !expression_has_effect(init)) {
10072 warningf(&init->base.source_position,
10073 "initialisation of 'for'-statement has no effect");
10075 rem_anchor_token(';');
10079 if (token.type != ';') {
10080 add_anchor_token(';');
10081 expression_t *const cond = parse_expression();
10082 statement->fors.condition = cond;
10083 /* §6.8.5:2 The controlling expression of an iteration statement
10084 * shall have scalar type. */
10085 semantic_condition(cond, "condition of 'for'-statement");
10086 mark_vars_read(cond, NULL);
10087 rem_anchor_token(';');
10090 if (token.type != ')') {
10091 expression_t *const step = parse_expression();
10092 statement->fors.step = step;
10093 mark_vars_read(step, ENT_ANY);
10094 if (warning.unused_value && !expression_has_effect(step)) {
10095 warningf(&step->base.source_position,
10096 "step of 'for'-statement has no effect");
10100 rem_anchor_token(')');
10101 statement->fors.body = parse_loop_body(statement);
10103 assert(current_scope == &statement->fors.scope);
10104 scope_pop(old_scope);
10105 environment_pop_to(top);
10112 rem_anchor_token(')');
10113 assert(current_scope == &statement->fors.scope);
10114 scope_pop(old_scope);
10115 environment_pop_to(top);
10117 return create_invalid_statement();
10121 * Parse a goto statement.
10123 static statement_t *parse_goto(void)
10125 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
10128 if (GNU_MODE && token.type == '*') {
10130 expression_t *expression = parse_expression();
10131 mark_vars_read(expression, NULL);
10133 /* Argh: although documentation says the expression must be of type void*,
10134 * gcc accepts anything that can be casted into void* without error */
10135 type_t *type = expression->base.type;
10137 if (type != type_error_type) {
10138 if (!is_type_pointer(type) && !is_type_integer(type)) {
10139 errorf(&expression->base.source_position,
10140 "cannot convert to a pointer type");
10141 } else if (warning.other && type != type_void_ptr) {
10142 warningf(&expression->base.source_position,
10143 "type of computed goto expression should be 'void*' not '%T'", type);
10145 expression = create_implicit_cast(expression, type_void_ptr);
10148 statement->gotos.expression = expression;
10150 if (token.type != T_IDENTIFIER) {
10152 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
10154 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
10155 eat_until_anchor();
10158 symbol_t *symbol = token.v.symbol;
10161 statement->gotos.label = get_label(symbol);
10164 /* remember the goto's in a list for later checking */
10165 *goto_anchor = &statement->gotos;
10166 goto_anchor = &statement->gotos.next;
10172 return create_invalid_statement();
10176 * Parse a continue statement.
10178 static statement_t *parse_continue(void)
10180 if (current_loop == NULL) {
10181 errorf(HERE, "continue statement not within loop");
10184 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
10194 * Parse a break statement.
10196 static statement_t *parse_break(void)
10198 if (current_switch == NULL && current_loop == NULL) {
10199 errorf(HERE, "break statement not within loop or switch");
10202 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10212 * Parse a __leave statement.
10214 static statement_t *parse_leave_statement(void)
10216 if (current_try == NULL) {
10217 errorf(HERE, "__leave statement not within __try");
10220 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10230 * Check if a given entity represents a local variable.
10232 static bool is_local_variable(const entity_t *entity)
10234 if (entity->kind != ENTITY_VARIABLE)
10237 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10238 case STORAGE_CLASS_AUTO:
10239 case STORAGE_CLASS_REGISTER: {
10240 const type_t *type = skip_typeref(entity->declaration.type);
10241 if (is_type_function(type)) {
10253 * Check if a given expression represents a local variable.
10255 static bool expression_is_local_variable(const expression_t *expression)
10257 if (expression->base.kind != EXPR_REFERENCE) {
10260 const entity_t *entity = expression->reference.entity;
10261 return is_local_variable(entity);
10265 * Check if a given expression represents a local variable and
10266 * return its declaration then, else return NULL.
10268 entity_t *expression_is_variable(const expression_t *expression)
10270 if (expression->base.kind != EXPR_REFERENCE) {
10273 entity_t *entity = expression->reference.entity;
10274 if (entity->kind != ENTITY_VARIABLE)
10281 * Parse a return statement.
10283 static statement_t *parse_return(void)
10287 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10289 expression_t *return_value = NULL;
10290 if (token.type != ';') {
10291 return_value = parse_expression();
10292 mark_vars_read(return_value, NULL);
10295 const type_t *const func_type = skip_typeref(current_function->base.type);
10296 assert(is_type_function(func_type));
10297 type_t *const return_type = skip_typeref(func_type->function.return_type);
10299 if (return_value != NULL) {
10300 type_t *return_value_type = skip_typeref(return_value->base.type);
10302 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID) &&
10303 !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10304 if (warning.other) {
10305 warningf(&statement->base.source_position,
10306 "'return' with a value, in function returning void");
10308 return_value = NULL;
10310 assign_error_t error = semantic_assign(return_type, return_value);
10311 report_assign_error(error, return_type, return_value, "'return'",
10312 &statement->base.source_position);
10313 return_value = create_implicit_cast(return_value, return_type);
10315 /* check for returning address of a local var */
10316 if (warning.other && return_value != NULL
10317 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10318 const expression_t *expression = return_value->unary.value;
10319 if (expression_is_local_variable(expression)) {
10320 warningf(&statement->base.source_position,
10321 "function returns address of local variable");
10324 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10325 warningf(&statement->base.source_position,
10326 "'return' without value, in function returning non-void");
10328 statement->returns.value = return_value;
10337 * Parse a declaration statement.
10339 static statement_t *parse_declaration_statement(void)
10341 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10343 entity_t *before = current_scope->last_entity;
10345 parse_external_declaration();
10347 parse_declaration(record_entity, DECL_FLAGS_NONE);
10350 if (before == NULL) {
10351 statement->declaration.declarations_begin = current_scope->entities;
10353 statement->declaration.declarations_begin = before->base.next;
10355 statement->declaration.declarations_end = current_scope->last_entity;
10361 * Parse an expression statement, ie. expr ';'.
10363 static statement_t *parse_expression_statement(void)
10365 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10367 expression_t *const expr = parse_expression();
10368 statement->expression.expression = expr;
10369 mark_vars_read(expr, ENT_ANY);
10378 * Parse a microsoft __try { } __finally { } or
10379 * __try{ } __except() { }
10381 static statement_t *parse_ms_try_statment(void)
10383 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10386 PUSH_PARENT(statement);
10388 ms_try_statement_t *rem = current_try;
10389 current_try = &statement->ms_try;
10390 statement->ms_try.try_statement = parse_compound_statement(false);
10395 if (token.type == T___except) {
10398 add_anchor_token(')');
10399 expression_t *const expr = parse_expression();
10400 mark_vars_read(expr, NULL);
10401 type_t * type = skip_typeref(expr->base.type);
10402 if (is_type_integer(type)) {
10403 type = promote_integer(type);
10404 } else if (is_type_valid(type)) {
10405 errorf(&expr->base.source_position,
10406 "__expect expression is not an integer, but '%T'", type);
10407 type = type_error_type;
10409 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10410 rem_anchor_token(')');
10412 statement->ms_try.final_statement = parse_compound_statement(false);
10413 } else if (token.type == T__finally) {
10415 statement->ms_try.final_statement = parse_compound_statement(false);
10417 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10418 return create_invalid_statement();
10422 return create_invalid_statement();
10425 static statement_t *parse_empty_statement(void)
10427 if (warning.empty_statement) {
10428 warningf(HERE, "statement is empty");
10430 statement_t *const statement = create_empty_statement();
10435 static statement_t *parse_local_label_declaration(void)
10437 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10441 entity_t *begin = NULL, *end = NULL;
10444 if (token.type != T_IDENTIFIER) {
10445 parse_error_expected("while parsing local label declaration",
10446 T_IDENTIFIER, NULL);
10449 symbol_t *symbol = token.v.symbol;
10450 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10451 if (entity != NULL && entity->base.parent_scope == current_scope) {
10452 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10453 symbol, &entity->base.source_position);
10455 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10457 entity->base.parent_scope = current_scope;
10458 entity->base.namespc = NAMESPACE_LABEL;
10459 entity->base.source_position = token.source_position;
10460 entity->base.symbol = symbol;
10463 end->base.next = entity;
10468 environment_push(entity);
10472 if (token.type != ',')
10478 statement->declaration.declarations_begin = begin;
10479 statement->declaration.declarations_end = end;
10483 static void parse_namespace_definition(void)
10487 entity_t *entity = NULL;
10488 symbol_t *symbol = NULL;
10490 if (token.type == T_IDENTIFIER) {
10491 symbol = token.v.symbol;
10494 entity = get_entity(symbol, NAMESPACE_NORMAL);
10495 if (entity != NULL && entity->kind != ENTITY_NAMESPACE
10496 && entity->base.parent_scope == current_scope) {
10497 error_redefined_as_different_kind(&token.source_position,
10498 entity, ENTITY_NAMESPACE);
10503 if (entity == NULL) {
10504 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10505 entity->base.symbol = symbol;
10506 entity->base.source_position = token.source_position;
10507 entity->base.namespc = NAMESPACE_NORMAL;
10508 entity->base.parent_scope = current_scope;
10511 if (token.type == '=') {
10512 /* TODO: parse namespace alias */
10513 panic("namespace alias definition not supported yet");
10516 environment_push(entity);
10517 append_entity(current_scope, entity);
10519 size_t const top = environment_top();
10520 scope_t *old_scope = scope_push(&entity->namespacee.members);
10527 assert(current_scope == &entity->namespacee.members);
10528 scope_pop(old_scope);
10529 environment_pop_to(top);
10533 * Parse a statement.
10534 * There's also parse_statement() which additionally checks for
10535 * "statement has no effect" warnings
10537 static statement_t *intern_parse_statement(void)
10539 statement_t *statement = NULL;
10541 /* declaration or statement */
10542 add_anchor_token(';');
10543 switch (token.type) {
10544 case T_IDENTIFIER: {
10545 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10546 if (la1_type == ':') {
10547 statement = parse_label_statement();
10548 } else if (is_typedef_symbol(token.v.symbol)) {
10549 statement = parse_declaration_statement();
10551 /* it's an identifier, the grammar says this must be an
10552 * expression statement. However it is common that users mistype
10553 * declaration types, so we guess a bit here to improve robustness
10554 * for incorrect programs */
10555 switch (la1_type) {
10558 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10559 goto expression_statment;
10564 statement = parse_declaration_statement();
10568 expression_statment:
10569 statement = parse_expression_statement();
10576 case T___extension__:
10577 /* This can be a prefix to a declaration or an expression statement.
10578 * We simply eat it now and parse the rest with tail recursion. */
10581 } while (token.type == T___extension__);
10582 bool old_gcc_extension = in_gcc_extension;
10583 in_gcc_extension = true;
10584 statement = intern_parse_statement();
10585 in_gcc_extension = old_gcc_extension;
10589 statement = parse_declaration_statement();
10593 statement = parse_local_label_declaration();
10596 case ';': statement = parse_empty_statement(); break;
10597 case '{': statement = parse_compound_statement(false); break;
10598 case T___leave: statement = parse_leave_statement(); break;
10599 case T___try: statement = parse_ms_try_statment(); break;
10600 case T_asm: statement = parse_asm_statement(); break;
10601 case T_break: statement = parse_break(); break;
10602 case T_case: statement = parse_case_statement(); break;
10603 case T_continue: statement = parse_continue(); break;
10604 case T_default: statement = parse_default_statement(); break;
10605 case T_do: statement = parse_do(); break;
10606 case T_for: statement = parse_for(); break;
10607 case T_goto: statement = parse_goto(); break;
10608 case T_if: statement = parse_if(); break;
10609 case T_return: statement = parse_return(); break;
10610 case T_switch: statement = parse_switch(); break;
10611 case T_while: statement = parse_while(); break;
10614 statement = parse_expression_statement();
10618 errorf(HERE, "unexpected token '%K' while parsing statement", &token);
10619 statement = create_invalid_statement();
10624 rem_anchor_token(';');
10626 assert(statement != NULL
10627 && statement->base.source_position.input_name != NULL);
10633 * parse a statement and emits "statement has no effect" warning if needed
10634 * (This is really a wrapper around intern_parse_statement with check for 1
10635 * single warning. It is needed, because for statement expressions we have
10636 * to avoid the warning on the last statement)
10638 static statement_t *parse_statement(void)
10640 statement_t *statement = intern_parse_statement();
10642 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10643 expression_t *expression = statement->expression.expression;
10644 if (!expression_has_effect(expression)) {
10645 warningf(&expression->base.source_position,
10646 "statement has no effect");
10654 * Parse a compound statement.
10656 static statement_t *parse_compound_statement(bool inside_expression_statement)
10658 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10660 PUSH_PARENT(statement);
10663 add_anchor_token('}');
10665 size_t const top = environment_top();
10666 scope_t *old_scope = scope_push(&statement->compound.scope);
10668 statement_t **anchor = &statement->compound.statements;
10669 bool only_decls_so_far = true;
10670 while (token.type != '}') {
10671 if (token.type == T_EOF) {
10672 errorf(&statement->base.source_position,
10673 "EOF while parsing compound statement");
10676 statement_t *sub_statement = intern_parse_statement();
10677 if (is_invalid_statement(sub_statement)) {
10678 /* an error occurred. if we are at an anchor, return */
10684 if (warning.declaration_after_statement) {
10685 if (sub_statement->kind != STATEMENT_DECLARATION) {
10686 only_decls_so_far = false;
10687 } else if (!only_decls_so_far) {
10688 warningf(&sub_statement->base.source_position,
10689 "ISO C90 forbids mixed declarations and code");
10693 *anchor = sub_statement;
10695 while (sub_statement->base.next != NULL)
10696 sub_statement = sub_statement->base.next;
10698 anchor = &sub_statement->base.next;
10702 /* look over all statements again to produce no effect warnings */
10703 if (warning.unused_value) {
10704 statement_t *sub_statement = statement->compound.statements;
10705 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10706 if (sub_statement->kind != STATEMENT_EXPRESSION)
10708 /* don't emit a warning for the last expression in an expression
10709 * statement as it has always an effect */
10710 if (inside_expression_statement && sub_statement->base.next == NULL)
10713 expression_t *expression = sub_statement->expression.expression;
10714 if (!expression_has_effect(expression)) {
10715 warningf(&expression->base.source_position,
10716 "statement has no effect");
10722 rem_anchor_token('}');
10723 assert(current_scope == &statement->compound.scope);
10724 scope_pop(old_scope);
10725 environment_pop_to(top);
10732 * Check for unused global static functions and variables
10734 static void check_unused_globals(void)
10736 if (!warning.unused_function && !warning.unused_variable)
10739 for (const entity_t *entity = file_scope->entities; entity != NULL;
10740 entity = entity->base.next) {
10741 if (!is_declaration(entity))
10744 const declaration_t *declaration = &entity->declaration;
10745 if (declaration->used ||
10746 declaration->modifiers & DM_UNUSED ||
10747 declaration->modifiers & DM_USED ||
10748 declaration->storage_class != STORAGE_CLASS_STATIC)
10751 type_t *const type = declaration->type;
10753 if (entity->kind == ENTITY_FUNCTION) {
10754 /* inhibit warning for static inline functions */
10755 if (entity->function.is_inline)
10758 s = entity->function.statement != NULL ? "defined" : "declared";
10763 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10764 type, declaration->base.symbol, s);
10768 static void parse_global_asm(void)
10770 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10775 statement->asms.asm_text = parse_string_literals();
10776 statement->base.next = unit->global_asm;
10777 unit->global_asm = statement;
10785 static void parse_linkage_specification(void)
10788 assert(token.type == T_STRING_LITERAL);
10790 const char *linkage = parse_string_literals().begin;
10792 linkage_kind_t old_linkage = current_linkage;
10793 linkage_kind_t new_linkage;
10794 if (strcmp(linkage, "C") == 0) {
10795 new_linkage = LINKAGE_C;
10796 } else if (strcmp(linkage, "C++") == 0) {
10797 new_linkage = LINKAGE_CXX;
10799 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10800 new_linkage = LINKAGE_INVALID;
10802 current_linkage = new_linkage;
10804 if (token.type == '{') {
10813 assert(current_linkage == new_linkage);
10814 current_linkage = old_linkage;
10817 static void parse_external(void)
10819 switch (token.type) {
10820 DECLARATION_START_NO_EXTERN
10822 case T___extension__:
10823 /* tokens below are for implicit int */
10824 case '&': /* & x; -> int& x; (and error later, because C++ has no
10826 case '*': /* * x; -> int* x; */
10827 case '(': /* (x); -> int (x); */
10828 parse_external_declaration();
10832 if (look_ahead(1)->type == T_STRING_LITERAL) {
10833 parse_linkage_specification();
10835 parse_external_declaration();
10840 parse_global_asm();
10844 parse_namespace_definition();
10848 if (!strict_mode) {
10850 warningf(HERE, "stray ';' outside of function");
10857 errorf(HERE, "stray '%K' outside of function", &token);
10858 if (token.type == '(' || token.type == '{' || token.type == '[')
10859 eat_until_matching_token(token.type);
10865 static void parse_externals(void)
10867 add_anchor_token('}');
10868 add_anchor_token(T_EOF);
10871 unsigned char token_anchor_copy[T_LAST_TOKEN];
10872 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10875 while (token.type != T_EOF && token.type != '}') {
10877 bool anchor_leak = false;
10878 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10879 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10881 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10882 anchor_leak = true;
10885 if (in_gcc_extension) {
10886 errorf(HERE, "Leaked __extension__");
10887 anchor_leak = true;
10897 rem_anchor_token(T_EOF);
10898 rem_anchor_token('}');
10902 * Parse a translation unit.
10904 static void parse_translation_unit(void)
10906 add_anchor_token(T_EOF);
10911 if (token.type == T_EOF)
10914 errorf(HERE, "stray '%K' outside of function", &token);
10915 if (token.type == '(' || token.type == '{' || token.type == '[')
10916 eat_until_matching_token(token.type);
10924 * @return the translation unit or NULL if errors occurred.
10926 void start_parsing(void)
10928 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10929 label_stack = NEW_ARR_F(stack_entry_t, 0);
10930 diagnostic_count = 0;
10934 type_set_output(stderr);
10935 ast_set_output(stderr);
10937 assert(unit == NULL);
10938 unit = allocate_ast_zero(sizeof(unit[0]));
10940 assert(file_scope == NULL);
10941 file_scope = &unit->scope;
10943 assert(current_scope == NULL);
10944 scope_push(&unit->scope);
10947 translation_unit_t *finish_parsing(void)
10949 assert(current_scope == &unit->scope);
10952 assert(file_scope == &unit->scope);
10953 check_unused_globals();
10956 DEL_ARR_F(environment_stack);
10957 DEL_ARR_F(label_stack);
10959 translation_unit_t *result = unit;
10966 lookahead_bufpos = 0;
10967 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10970 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10971 parse_translation_unit();
10975 * Initialize the parser.
10977 void init_parser(void)
10979 sym_anonymous = symbol_table_insert("<anonymous>");
10981 if (c_mode & _MS) {
10982 /* add predefined symbols for extended-decl-modifier */
10983 sym_align = symbol_table_insert("align");
10984 sym_allocate = symbol_table_insert("allocate");
10985 sym_dllimport = symbol_table_insert("dllimport");
10986 sym_dllexport = symbol_table_insert("dllexport");
10987 sym_naked = symbol_table_insert("naked");
10988 sym_noinline = symbol_table_insert("noinline");
10989 sym_noreturn = symbol_table_insert("noreturn");
10990 sym_nothrow = symbol_table_insert("nothrow");
10991 sym_novtable = symbol_table_insert("novtable");
10992 sym_property = symbol_table_insert("property");
10993 sym_get = symbol_table_insert("get");
10994 sym_put = symbol_table_insert("put");
10995 sym_selectany = symbol_table_insert("selectany");
10996 sym_thread = symbol_table_insert("thread");
10997 sym_uuid = symbol_table_insert("uuid");
10998 sym_deprecated = symbol_table_insert("deprecated");
10999 sym_restrict = symbol_table_insert("restrict");
11000 sym_noalias = symbol_table_insert("noalias");
11002 memset(token_anchor_set, 0, sizeof(token_anchor_set));
11004 init_expression_parsers();
11005 obstack_init(&temp_obst);
11007 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11008 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11012 * Terminate the parser.
11014 void exit_parser(void)
11016 obstack_free(&temp_obst, NULL);