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. */
81 decl_modifiers_t modifiers; /**< declaration modifiers */
82 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
83 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
84 symbol_t *get_property_sym; /**< the name of the get property if set. */
85 symbol_t *put_property_sym; /**< the name of the put property if set. */
90 * An environment for parsing initializers (and compound literals).
92 typedef struct parse_initializer_env_t {
93 type_t *type; /**< the type of the initializer. In case of an
94 array type with unspecified size this gets
95 adjusted to the actual size. */
96 entity_t *entity; /**< the variable that is initialized if any */
97 bool must_be_constant;
98 } parse_initializer_env_t;
101 * Capture a MS __base extension.
103 typedef struct based_spec_t {
104 source_position_t source_position;
105 variable_t *base_variable;
108 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
110 /** The current token. */
111 static token_t token;
112 /** The lookahead ring-buffer. */
113 static token_t lookahead_buffer[MAX_LOOKAHEAD];
114 /** Position of the next token in the lookahead buffer. */
115 static int lookahead_bufpos;
116 static stack_entry_t *environment_stack = NULL;
117 static stack_entry_t *label_stack = NULL;
118 static scope_t *file_scope = NULL;
119 static scope_t *current_scope = NULL;
120 /** Point to the current function declaration if inside a function. */
121 static function_t *current_function = NULL;
122 static entity_t *current_init_decl = NULL;
123 static switch_statement_t *current_switch = NULL;
124 static statement_t *current_loop = NULL;
125 static statement_t *current_parent = NULL;
126 static ms_try_statement_t *current_try = NULL;
127 static linkage_kind_t current_linkage = LINKAGE_INVALID;
128 static goto_statement_t *goto_first = NULL;
129 static goto_statement_t **goto_anchor = NULL;
130 static label_statement_t *label_first = NULL;
131 static label_statement_t **label_anchor = NULL;
132 /** current translation unit. */
133 static translation_unit_t *unit = NULL;
134 /** true if we are in a type property context (evaluation only for type. */
135 static bool in_type_prop = false;
136 /** true in we are in a __extension__ context. */
137 static bool in_gcc_extension = false;
138 static struct obstack temp_obst;
139 static entity_t *anonymous_entity;
142 #define PUSH_PARENT(stmt) \
143 statement_t *const prev_parent = current_parent; \
144 ((void)(current_parent = (stmt)))
145 #define POP_PARENT ((void)(current_parent = prev_parent))
147 /** special symbol used for anonymous entities. */
148 static const symbol_t *sym_anonymous = NULL;
150 /* symbols for Microsoft extended-decl-modifier */
151 static const symbol_t *sym_align = NULL;
152 static const symbol_t *sym_allocate = NULL;
153 static const symbol_t *sym_dllimport = NULL;
154 static const symbol_t *sym_dllexport = NULL;
155 static const symbol_t *sym_naked = NULL;
156 static const symbol_t *sym_noinline = NULL;
157 static const symbol_t *sym_noreturn = NULL;
158 static const symbol_t *sym_nothrow = NULL;
159 static const symbol_t *sym_novtable = NULL;
160 static const symbol_t *sym_property = NULL;
161 static const symbol_t *sym_get = NULL;
162 static const symbol_t *sym_put = NULL;
163 static const symbol_t *sym_selectany = NULL;
164 static const symbol_t *sym_thread = NULL;
165 static const symbol_t *sym_uuid = NULL;
166 static const symbol_t *sym_deprecated = NULL;
167 static const symbol_t *sym_restrict = NULL;
168 static const symbol_t *sym_noalias = NULL;
170 /** The token anchor set */
171 static unsigned char token_anchor_set[T_LAST_TOKEN];
173 /** The current source position. */
174 #define HERE (&token.source_position)
176 /** true if we are in GCC mode. */
177 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
179 static type_t *type_valist;
181 static statement_t *parse_compound_statement(bool inside_expression_statement);
182 static statement_t *parse_statement(void);
184 static expression_t *parse_sub_expression(precedence_t);
185 static expression_t *parse_expression(void);
186 static type_t *parse_typename(void);
187 static void parse_externals(void);
188 static void parse_external(void);
190 static void parse_compound_type_entries(compound_t *compound_declaration);
192 typedef enum declarator_flags_t {
194 DECL_MAY_BE_ABSTRACT = 1U << 0,
195 DECL_CREATE_COMPOUND_MEMBER = 1U << 1
196 } declarator_flags_t;
198 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
199 declarator_flags_t flags);
201 static entity_t *record_entity(entity_t *entity, bool is_definition);
203 static void semantic_comparison(binary_expression_t *expression);
205 #define STORAGE_CLASSES \
206 STORAGE_CLASSES_NO_EXTERN \
209 #define STORAGE_CLASSES_NO_EXTERN \
216 #define TYPE_QUALIFIERS \
221 case T__forceinline: \
222 case T___attribute__:
224 #define COMPLEX_SPECIFIERS \
226 #define IMAGINARY_SPECIFIERS \
229 #define TYPE_SPECIFIERS \
231 case T___builtin_va_list: \
250 #define DECLARATION_START \
255 #define DECLARATION_START_NO_EXTERN \
256 STORAGE_CLASSES_NO_EXTERN \
260 #define TYPENAME_START \
264 #define EXPRESSION_START \
273 case T_CHARACTER_CONSTANT: \
274 case T_FLOATINGPOINT: \
278 case T_STRING_LITERAL: \
279 case T_WIDE_CHARACTER_CONSTANT: \
280 case T_WIDE_STRING_LITERAL: \
281 case T___FUNCDNAME__: \
282 case T___FUNCSIG__: \
283 case T___FUNCTION__: \
284 case T___PRETTY_FUNCTION__: \
285 case T___alignof__: \
286 case T___builtin_alloca: \
287 case T___builtin_classify_type: \
288 case T___builtin_constant_p: \
289 case T___builtin_expect: \
290 case T___builtin_huge_val: \
291 case T___builtin_inf: \
292 case T___builtin_inff: \
293 case T___builtin_infl: \
294 case T___builtin_isgreater: \
295 case T___builtin_isgreaterequal: \
296 case T___builtin_isless: \
297 case T___builtin_islessequal: \
298 case T___builtin_islessgreater: \
299 case T___builtin_isunordered: \
300 case T___builtin_nan: \
301 case T___builtin_nanf: \
302 case T___builtin_nanl: \
303 case T___builtin_offsetof: \
304 case T___builtin_prefetch: \
305 case T___builtin_va_arg: \
306 case T___builtin_va_end: \
307 case T___builtin_va_start: \
318 * Allocate an AST node with given size and
319 * initialize all fields with zero.
321 static void *allocate_ast_zero(size_t size)
323 void *res = allocate_ast(size);
324 memset(res, 0, size);
328 static size_t get_entity_struct_size(entity_kind_t kind)
330 static const size_t sizes[] = {
331 [ENTITY_VARIABLE] = sizeof(variable_t),
332 [ENTITY_COMPOUND_MEMBER] = sizeof(variable_t),
333 [ENTITY_FUNCTION] = sizeof(function_t),
334 [ENTITY_TYPEDEF] = sizeof(typedef_t),
335 [ENTITY_STRUCT] = sizeof(compound_t),
336 [ENTITY_UNION] = sizeof(compound_t),
337 [ENTITY_ENUM] = sizeof(enum_t),
338 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
339 [ENTITY_LABEL] = sizeof(label_t),
340 [ENTITY_LOCAL_LABEL] = sizeof(label_t),
341 [ENTITY_NAMESPACE] = sizeof(namespace_t)
343 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
344 assert(sizes[kind] != 0);
348 static entity_t *allocate_entity_zero(entity_kind_t kind)
350 size_t size = get_entity_struct_size(kind);
351 entity_t *entity = allocate_ast_zero(size);
357 * Returns the size of a statement node.
359 * @param kind the statement kind
361 static size_t get_statement_struct_size(statement_kind_t kind)
363 static const size_t sizes[] = {
364 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
365 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
366 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
367 [STATEMENT_RETURN] = sizeof(return_statement_t),
368 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
369 [STATEMENT_LOCAL_LABEL] = sizeof(local_label_statement_t),
370 [STATEMENT_IF] = sizeof(if_statement_t),
371 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
372 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
373 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
374 [STATEMENT_BREAK] = sizeof(statement_base_t),
375 [STATEMENT_GOTO] = sizeof(goto_statement_t),
376 [STATEMENT_LABEL] = sizeof(label_statement_t),
377 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
378 [STATEMENT_WHILE] = sizeof(while_statement_t),
379 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
380 [STATEMENT_FOR] = sizeof(for_statement_t),
381 [STATEMENT_ASM] = sizeof(asm_statement_t),
382 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
383 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
385 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
386 assert(sizes[kind] != 0);
391 * Returns the size of an expression node.
393 * @param kind the expression kind
395 static size_t get_expression_struct_size(expression_kind_t kind)
397 static const size_t sizes[] = {
398 [EXPR_INVALID] = sizeof(expression_base_t),
399 [EXPR_REFERENCE] = sizeof(reference_expression_t),
400 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
401 [EXPR_CONST] = sizeof(const_expression_t),
402 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
403 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
404 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
405 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
406 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
407 [EXPR_CALL] = sizeof(call_expression_t),
408 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
409 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
410 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
411 [EXPR_SELECT] = sizeof(select_expression_t),
412 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
413 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
414 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
415 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
416 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
417 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
418 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
419 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
420 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
421 [EXPR_VA_START] = sizeof(va_start_expression_t),
422 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
423 [EXPR_STATEMENT] = sizeof(statement_expression_t),
424 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
426 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
427 return sizes[EXPR_UNARY_FIRST];
429 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
430 return sizes[EXPR_BINARY_FIRST];
432 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
433 assert(sizes[kind] != 0);
438 * Allocate a statement node of given kind and initialize all
441 static statement_t *allocate_statement_zero(statement_kind_t kind)
443 size_t size = get_statement_struct_size(kind);
444 statement_t *res = allocate_ast_zero(size);
446 res->base.kind = kind;
447 res->base.parent = current_parent;
448 res->base.source_position = token.source_position;
453 * Allocate an expression node of given kind and initialize all
456 static expression_t *allocate_expression_zero(expression_kind_t kind)
458 size_t size = get_expression_struct_size(kind);
459 expression_t *res = allocate_ast_zero(size);
461 res->base.kind = kind;
462 res->base.type = type_error_type;
463 res->base.source_position = token.source_position;
468 * Creates a new invalid expression.
470 static expression_t *create_invalid_expression(void)
472 return allocate_expression_zero(EXPR_INVALID);
476 * Creates a new invalid statement.
478 static statement_t *create_invalid_statement(void)
480 return allocate_statement_zero(STATEMENT_INVALID);
484 * Allocate a new empty statement.
486 static statement_t *create_empty_statement(void)
488 return allocate_statement_zero(STATEMENT_EMPTY);
492 * Returns the size of a type node.
494 * @param kind the type kind
496 static size_t get_type_struct_size(type_kind_t kind)
498 static const size_t sizes[] = {
499 [TYPE_ATOMIC] = sizeof(atomic_type_t),
500 [TYPE_COMPLEX] = sizeof(complex_type_t),
501 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
502 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
503 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
504 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
505 [TYPE_ENUM] = sizeof(enum_type_t),
506 [TYPE_FUNCTION] = sizeof(function_type_t),
507 [TYPE_POINTER] = sizeof(pointer_type_t),
508 [TYPE_ARRAY] = sizeof(array_type_t),
509 [TYPE_BUILTIN] = sizeof(builtin_type_t),
510 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
511 [TYPE_TYPEOF] = sizeof(typeof_type_t),
513 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
514 assert(kind <= TYPE_TYPEOF);
515 assert(sizes[kind] != 0);
520 * Allocate a type node of given kind and initialize all
523 * @param kind type kind to allocate
525 static type_t *allocate_type_zero(type_kind_t kind)
527 size_t size = get_type_struct_size(kind);
528 type_t *res = obstack_alloc(type_obst, size);
529 memset(res, 0, size);
530 res->base.kind = kind;
536 * Returns the size of an initializer node.
538 * @param kind the initializer kind
540 static size_t get_initializer_size(initializer_kind_t kind)
542 static const size_t sizes[] = {
543 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
544 [INITIALIZER_STRING] = sizeof(initializer_string_t),
545 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
546 [INITIALIZER_LIST] = sizeof(initializer_list_t),
547 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
549 assert(kind < sizeof(sizes) / sizeof(*sizes));
550 assert(sizes[kind] != 0);
555 * Allocate an initializer node of given kind and initialize all
558 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
560 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
567 * Free a type from the type obstack.
569 static void free_type(void *type)
571 obstack_free(type_obst, type);
575 * Returns the index of the top element of the environment stack.
577 static size_t environment_top(void)
579 return ARR_LEN(environment_stack);
583 * Returns the index of the top element of the global label stack.
585 static size_t label_top(void)
587 return ARR_LEN(label_stack);
591 * Return the next token.
593 static inline void next_token(void)
595 token = lookahead_buffer[lookahead_bufpos];
596 lookahead_buffer[lookahead_bufpos] = lexer_token;
599 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
602 print_token(stderr, &token);
603 fprintf(stderr, "\n");
608 * Return the next token with a given lookahead.
610 static inline const token_t *look_ahead(int num)
612 assert(num > 0 && num <= MAX_LOOKAHEAD);
613 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
614 return &lookahead_buffer[pos];
618 * Adds a token to the token anchor set (a multi-set).
620 static void add_anchor_token(int token_type)
622 assert(0 <= token_type && token_type < T_LAST_TOKEN);
623 ++token_anchor_set[token_type];
626 static int save_and_reset_anchor_state(int token_type)
628 assert(0 <= token_type && token_type < T_LAST_TOKEN);
629 int count = token_anchor_set[token_type];
630 token_anchor_set[token_type] = 0;
634 static void restore_anchor_state(int token_type, int count)
636 assert(0 <= token_type && token_type < T_LAST_TOKEN);
637 token_anchor_set[token_type] = count;
641 * Remove a token from the token anchor set (a multi-set).
643 static void rem_anchor_token(int token_type)
645 assert(0 <= token_type && token_type < T_LAST_TOKEN);
646 assert(token_anchor_set[token_type] != 0);
647 --token_anchor_set[token_type];
650 static bool at_anchor(void)
654 return token_anchor_set[token.type];
658 * Eat tokens until a matching token is found.
660 static void eat_until_matching_token(int type)
664 case '(': end_token = ')'; break;
665 case '{': end_token = '}'; break;
666 case '[': end_token = ']'; break;
667 default: end_token = type; break;
670 unsigned parenthesis_count = 0;
671 unsigned brace_count = 0;
672 unsigned bracket_count = 0;
673 while (token.type != end_token ||
674 parenthesis_count != 0 ||
676 bracket_count != 0) {
677 switch (token.type) {
679 case '(': ++parenthesis_count; break;
680 case '{': ++brace_count; break;
681 case '[': ++bracket_count; break;
684 if (parenthesis_count > 0)
694 if (bracket_count > 0)
697 if (token.type == end_token &&
698 parenthesis_count == 0 &&
712 * Eat input tokens until an anchor is found.
714 static void eat_until_anchor(void)
716 while (token_anchor_set[token.type] == 0) {
717 if (token.type == '(' || token.type == '{' || token.type == '[')
718 eat_until_matching_token(token.type);
723 static void eat_block(void)
725 eat_until_matching_token('{');
726 if (token.type == '}')
730 #define eat(token_type) do { assert(token.type == (token_type)); next_token(); } while (0)
733 * Report a parse error because an expected token was not found.
736 #if defined __GNUC__ && __GNUC__ >= 4
737 __attribute__((sentinel))
739 void parse_error_expected(const char *message, ...)
741 if (message != NULL) {
742 errorf(HERE, "%s", message);
745 va_start(ap, message);
746 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
751 * Report an incompatible type.
753 static void type_error_incompatible(const char *msg,
754 const source_position_t *source_position, type_t *type1, type_t *type2)
756 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
761 * Expect the the current token is the expected token.
762 * If not, generate an error, eat the current statement,
763 * and goto the end_error label.
765 #define expect(expected) \
767 if (UNLIKELY(token.type != (expected))) { \
768 parse_error_expected(NULL, (expected), NULL); \
769 add_anchor_token(expected); \
770 eat_until_anchor(); \
771 if (token.type == expected) \
773 rem_anchor_token(expected); \
779 static void scope_push(scope_t *new_scope)
781 if (current_scope != NULL) {
782 new_scope->depth = current_scope->depth + 1;
784 new_scope->parent = current_scope;
785 current_scope = new_scope;
788 static void scope_pop(void)
790 current_scope = current_scope->parent;
794 * Search an entity by its symbol in a given namespace.
796 static entity_t *get_entity(const symbol_t *const symbol,
797 namespace_tag_t namespc)
799 entity_t *entity = symbol->entity;
800 for (; entity != NULL; entity = entity->base.symbol_next) {
801 if (entity->base.namespc == namespc)
809 * pushs an entity on the environment stack and links the corresponding symbol
812 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
814 symbol_t *symbol = entity->base.symbol;
815 entity_namespace_t namespc = entity->base.namespc;
816 assert(namespc != NAMESPACE_INVALID);
818 /* replace/add entity into entity list of the symbol */
821 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
826 /* replace an entry? */
827 if (iter->base.namespc == namespc) {
828 entity->base.symbol_next = iter->base.symbol_next;
834 /* remember old declaration */
836 entry.symbol = symbol;
837 entry.old_entity = iter;
838 entry.namespc = namespc;
839 ARR_APP1(stack_entry_t, *stack_ptr, entry);
843 * Push an entity on the environment stack.
845 static void environment_push(entity_t *entity)
847 assert(entity->base.source_position.input_name != NULL);
848 assert(entity->base.parent_scope != NULL);
849 stack_push(&environment_stack, entity);
853 * Push a declaration on the global label stack.
855 * @param declaration the declaration
857 static void label_push(entity_t *label)
859 /* we abuse the parameters scope as parent for the labels */
860 label->base.parent_scope = ¤t_function->parameters;
861 stack_push(&label_stack, label);
865 * pops symbols from the environment stack until @p new_top is the top element
867 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
869 stack_entry_t *stack = *stack_ptr;
870 size_t top = ARR_LEN(stack);
873 assert(new_top <= top);
877 for (i = top; i > new_top; --i) {
878 stack_entry_t *entry = &stack[i - 1];
880 entity_t *old_entity = entry->old_entity;
881 symbol_t *symbol = entry->symbol;
882 entity_namespace_t namespc = entry->namespc;
884 /* replace with old_entity/remove */
887 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
889 assert(iter != NULL);
890 /* replace an entry? */
891 if (iter->base.namespc == namespc)
895 /* restore definition from outer scopes (if there was one) */
896 if (old_entity != NULL) {
897 old_entity->base.symbol_next = iter->base.symbol_next;
898 *anchor = old_entity;
900 /* remove entry from list */
901 *anchor = iter->base.symbol_next;
905 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
909 * Pop all entries from the environment stack until the new_top
912 * @param new_top the new stack top
914 static void environment_pop_to(size_t new_top)
916 stack_pop_to(&environment_stack, new_top);
920 * Pop all entries from the global label stack until the new_top
923 * @param new_top the new stack top
925 static void label_pop_to(size_t new_top)
927 stack_pop_to(&label_stack, new_top);
930 static int get_akind_rank(atomic_type_kind_t akind)
935 static int get_rank(const type_t *type)
937 assert(!is_typeref(type));
938 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
939 * and esp. footnote 108). However we can't fold constants (yet), so we
940 * can't decide whether unsigned int is possible, while int always works.
941 * (unsigned int would be preferable when possible... for stuff like
942 * struct { enum { ... } bla : 4; } ) */
943 if (type->kind == TYPE_ENUM)
944 return get_akind_rank(ATOMIC_TYPE_INT);
946 assert(type->kind == TYPE_ATOMIC);
947 return get_akind_rank(type->atomic.akind);
950 static type_t *promote_integer(type_t *type)
952 if (type->kind == TYPE_BITFIELD)
953 type = type->bitfield.base_type;
955 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
962 * Create a cast expression.
964 * @param expression the expression to cast
965 * @param dest_type the destination type
967 static expression_t *create_cast_expression(expression_t *expression,
970 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
972 cast->unary.value = expression;
973 cast->base.type = dest_type;
979 * Check if a given expression represents the 0 pointer constant.
981 static bool is_null_pointer_constant(const expression_t *expression)
983 /* skip void* cast */
984 if (expression->kind == EXPR_UNARY_CAST
985 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
986 expression = expression->unary.value;
989 /* TODO: not correct yet, should be any constant integer expression
990 * which evaluates to 0 */
991 if (expression->kind != EXPR_CONST)
994 type_t *const type = skip_typeref(expression->base.type);
995 if (!is_type_integer(type))
998 return expression->conste.v.int_value == 0;
1002 * Create an implicit cast expression.
1004 * @param expression the expression to cast
1005 * @param dest_type the destination type
1007 static expression_t *create_implicit_cast(expression_t *expression,
1010 type_t *const source_type = expression->base.type;
1012 if (source_type == dest_type)
1015 return create_cast_expression(expression, dest_type);
1018 typedef enum assign_error_t {
1020 ASSIGN_ERROR_INCOMPATIBLE,
1021 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1022 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1023 ASSIGN_WARNING_POINTER_FROM_INT,
1024 ASSIGN_WARNING_INT_FROM_POINTER
1027 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1028 const expression_t *const right,
1029 const char *context,
1030 const source_position_t *source_position)
1032 type_t *const orig_type_right = right->base.type;
1033 type_t *const type_left = skip_typeref(orig_type_left);
1034 type_t *const type_right = skip_typeref(orig_type_right);
1037 case ASSIGN_SUCCESS:
1039 case ASSIGN_ERROR_INCOMPATIBLE:
1040 errorf(source_position,
1041 "destination type '%T' in %s is incompatible with type '%T'",
1042 orig_type_left, context, orig_type_right);
1045 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1046 if (warning.other) {
1047 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1048 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1050 /* the left type has all qualifiers from the right type */
1051 unsigned missing_qualifiers
1052 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1053 warningf(source_position,
1054 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1055 orig_type_left, context, orig_type_right, missing_qualifiers);
1060 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1061 if (warning.other) {
1062 warningf(source_position,
1063 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1064 orig_type_left, context, right, orig_type_right);
1068 case ASSIGN_WARNING_POINTER_FROM_INT:
1069 if (warning.other) {
1070 warningf(source_position,
1071 "%s makes pointer '%T' from integer '%T' without a cast",
1072 context, orig_type_left, orig_type_right);
1076 case ASSIGN_WARNING_INT_FROM_POINTER:
1077 if (warning.other) {
1078 warningf(source_position,
1079 "%s makes integer '%T' from pointer '%T' without a cast",
1080 context, orig_type_left, orig_type_right);
1085 panic("invalid error value");
1089 /** Implements the rules from § 6.5.16.1 */
1090 static assign_error_t semantic_assign(type_t *orig_type_left,
1091 const expression_t *const right)
1093 type_t *const orig_type_right = right->base.type;
1094 type_t *const type_left = skip_typeref(orig_type_left);
1095 type_t *const type_right = skip_typeref(orig_type_right);
1097 if (is_type_pointer(type_left)) {
1098 if (is_null_pointer_constant(right)) {
1099 return ASSIGN_SUCCESS;
1100 } else if (is_type_pointer(type_right)) {
1101 type_t *points_to_left
1102 = skip_typeref(type_left->pointer.points_to);
1103 type_t *points_to_right
1104 = skip_typeref(type_right->pointer.points_to);
1105 assign_error_t res = ASSIGN_SUCCESS;
1107 /* the left type has all qualifiers from the right type */
1108 unsigned missing_qualifiers
1109 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1110 if (missing_qualifiers != 0) {
1111 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1114 points_to_left = get_unqualified_type(points_to_left);
1115 points_to_right = get_unqualified_type(points_to_right);
1117 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1120 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1121 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1122 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1125 if (!types_compatible(points_to_left, points_to_right)) {
1126 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1130 } else if (is_type_integer(type_right)) {
1131 return ASSIGN_WARNING_POINTER_FROM_INT;
1133 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1134 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1135 && is_type_pointer(type_right))) {
1136 return ASSIGN_SUCCESS;
1137 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1138 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1139 type_t *const unqual_type_left = get_unqualified_type(type_left);
1140 type_t *const unqual_type_right = get_unqualified_type(type_right);
1141 if (types_compatible(unqual_type_left, unqual_type_right)) {
1142 return ASSIGN_SUCCESS;
1144 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1145 return ASSIGN_WARNING_INT_FROM_POINTER;
1148 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1149 return ASSIGN_SUCCESS;
1151 return ASSIGN_ERROR_INCOMPATIBLE;
1154 static expression_t *parse_constant_expression(void)
1156 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1158 if (!is_constant_expression(result)) {
1159 errorf(&result->base.source_position,
1160 "expression '%E' is not constant\n", result);
1166 static expression_t *parse_assignment_expression(void)
1168 return parse_sub_expression(PREC_ASSIGNMENT);
1171 static string_t parse_string_literals(void)
1173 assert(token.type == T_STRING_LITERAL);
1174 string_t result = token.v.string;
1178 while (token.type == T_STRING_LITERAL) {
1179 result = concat_strings(&result, &token.v.string);
1186 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1187 [GNU_AK_CONST] = "const",
1188 [GNU_AK_VOLATILE] = "volatile",
1189 [GNU_AK_CDECL] = "cdecl",
1190 [GNU_AK_STDCALL] = "stdcall",
1191 [GNU_AK_FASTCALL] = "fastcall",
1192 [GNU_AK_DEPRECATED] = "deprecated",
1193 [GNU_AK_NOINLINE] = "noinline",
1194 [GNU_AK_NORETURN] = "noreturn",
1195 [GNU_AK_NAKED] = "naked",
1196 [GNU_AK_PURE] = "pure",
1197 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1198 [GNU_AK_MALLOC] = "malloc",
1199 [GNU_AK_WEAK] = "weak",
1200 [GNU_AK_CONSTRUCTOR] = "constructor",
1201 [GNU_AK_DESTRUCTOR] = "destructor",
1202 [GNU_AK_NOTHROW] = "nothrow",
1203 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1204 [GNU_AK_COMMON] = "common",
1205 [GNU_AK_NOCOMMON] = "nocommon",
1206 [GNU_AK_PACKED] = "packed",
1207 [GNU_AK_SHARED] = "shared",
1208 [GNU_AK_NOTSHARED] = "notshared",
1209 [GNU_AK_USED] = "used",
1210 [GNU_AK_UNUSED] = "unused",
1211 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1212 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1213 [GNU_AK_LONGCALL] = "longcall",
1214 [GNU_AK_SHORTCALL] = "shortcall",
1215 [GNU_AK_LONG_CALL] = "long_call",
1216 [GNU_AK_SHORT_CALL] = "short_call",
1217 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1218 [GNU_AK_INTERRUPT] = "interrupt",
1219 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1220 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1221 [GNU_AK_NESTING] = "nesting",
1222 [GNU_AK_NEAR] = "near",
1223 [GNU_AK_FAR] = "far",
1224 [GNU_AK_SIGNAL] = "signal",
1225 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1226 [GNU_AK_TINY_DATA] = "tiny_data",
1227 [GNU_AK_SAVEALL] = "saveall",
1228 [GNU_AK_FLATTEN] = "flatten",
1229 [GNU_AK_SSEREGPARM] = "sseregparm",
1230 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1231 [GNU_AK_RETURN_TWICE] = "return_twice",
1232 [GNU_AK_MAY_ALIAS] = "may_alias",
1233 [GNU_AK_MS_STRUCT] = "ms_struct",
1234 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1235 [GNU_AK_DLLIMPORT] = "dllimport",
1236 [GNU_AK_DLLEXPORT] = "dllexport",
1237 [GNU_AK_ALIGNED] = "aligned",
1238 [GNU_AK_ALIAS] = "alias",
1239 [GNU_AK_SECTION] = "section",
1240 [GNU_AK_FORMAT] = "format",
1241 [GNU_AK_FORMAT_ARG] = "format_arg",
1242 [GNU_AK_WEAKREF] = "weakref",
1243 [GNU_AK_NONNULL] = "nonnull",
1244 [GNU_AK_TLS_MODEL] = "tls_model",
1245 [GNU_AK_VISIBILITY] = "visibility",
1246 [GNU_AK_REGPARM] = "regparm",
1247 [GNU_AK_MODE] = "mode",
1248 [GNU_AK_MODEL] = "model",
1249 [GNU_AK_TRAP_EXIT] = "trap_exit",
1250 [GNU_AK_SP_SWITCH] = "sp_switch",
1251 [GNU_AK_SENTINEL] = "sentinel"
1255 * compare two string, ignoring double underscores on the second.
1257 static int strcmp_underscore(const char *s1, const char *s2)
1259 if (s2[0] == '_' && s2[1] == '_') {
1260 size_t len2 = strlen(s2);
1261 size_t len1 = strlen(s1);
1262 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1263 return strncmp(s1, s2+2, len2-4);
1267 return strcmp(s1, s2);
1271 * Allocate a new gnu temporal attribute.
1273 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1275 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1276 attribute->kind = kind;
1277 attribute->next = NULL;
1278 attribute->invalid = false;
1279 attribute->have_arguments = false;
1285 * parse one constant expression argument.
1287 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1289 expression_t *expression;
1290 add_anchor_token(')');
1291 expression = parse_constant_expression();
1292 rem_anchor_token(')');
1294 attribute->u.argument = fold_constant(expression);
1297 attribute->invalid = true;
1301 * parse a list of constant expressions arguments.
1303 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1305 argument_list_t **list = &attribute->u.arguments;
1306 argument_list_t *entry;
1307 expression_t *expression;
1308 add_anchor_token(')');
1309 add_anchor_token(',');
1311 expression = parse_constant_expression();
1312 entry = obstack_alloc(&temp_obst, sizeof(entry));
1313 entry->argument = fold_constant(expression);
1316 list = &entry->next;
1317 if (token.type != ',')
1321 rem_anchor_token(',');
1322 rem_anchor_token(')');
1326 attribute->invalid = true;
1330 * parse one string literal argument.
1332 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1335 add_anchor_token('(');
1336 if (token.type != T_STRING_LITERAL) {
1337 parse_error_expected("while parsing attribute directive",
1338 T_STRING_LITERAL, NULL);
1341 *string = parse_string_literals();
1342 rem_anchor_token('(');
1346 attribute->invalid = true;
1350 * parse one tls model.
1352 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1354 static const char *const tls_models[] = {
1360 string_t string = { NULL, 0 };
1361 parse_gnu_attribute_string_arg(attribute, &string);
1362 if (string.begin != NULL) {
1363 for (size_t i = 0; i < 4; ++i) {
1364 if (strcmp(tls_models[i], string.begin) == 0) {
1365 attribute->u.value = i;
1369 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1371 attribute->invalid = true;
1375 * parse one tls model.
1377 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1379 static const char *const visibilities[] = {
1385 string_t string = { NULL, 0 };
1386 parse_gnu_attribute_string_arg(attribute, &string);
1387 if (string.begin != NULL) {
1388 for (size_t i = 0; i < 4; ++i) {
1389 if (strcmp(visibilities[i], string.begin) == 0) {
1390 attribute->u.value = i;
1394 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1396 attribute->invalid = true;
1400 * parse one (code) model.
1402 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1404 static const char *const visibilities[] = {
1409 string_t string = { NULL, 0 };
1410 parse_gnu_attribute_string_arg(attribute, &string);
1411 if (string.begin != NULL) {
1412 for (int i = 0; i < 3; ++i) {
1413 if (strcmp(visibilities[i], string.begin) == 0) {
1414 attribute->u.value = i;
1418 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1420 attribute->invalid = true;
1423 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1425 /* TODO: find out what is allowed here... */
1427 /* at least: byte, word, pointer, list of machine modes
1428 * __XXX___ is interpreted as XXX */
1429 add_anchor_token(')');
1431 if (token.type != T_IDENTIFIER) {
1432 expect(T_IDENTIFIER);
1435 /* This isn't really correct, the backend should provide a list of machine
1436 * specific modes (according to gcc philosophy that is...) */
1437 const char *symbol_str = token.v.symbol->string;
1438 if (strcmp_underscore("QI", symbol_str) == 0 ||
1439 strcmp_underscore("byte", symbol_str) == 0) {
1440 attribute->u.akind = ATOMIC_TYPE_CHAR;
1441 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1442 attribute->u.akind = ATOMIC_TYPE_SHORT;
1443 } else if (strcmp_underscore("SI", symbol_str) == 0
1444 || strcmp_underscore("word", symbol_str) == 0
1445 || strcmp_underscore("pointer", symbol_str) == 0) {
1446 attribute->u.akind = ATOMIC_TYPE_INT;
1447 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1448 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1451 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1452 attribute->invalid = true;
1456 rem_anchor_token(')');
1460 attribute->invalid = true;
1464 * parse one interrupt argument.
1466 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1468 static const char *const interrupts[] = {
1475 string_t string = { NULL, 0 };
1476 parse_gnu_attribute_string_arg(attribute, &string);
1477 if (string.begin != NULL) {
1478 for (size_t i = 0; i < 5; ++i) {
1479 if (strcmp(interrupts[i], string.begin) == 0) {
1480 attribute->u.value = i;
1484 errorf(HERE, "'%s' is not an interrupt", string.begin);
1486 attribute->invalid = true;
1490 * parse ( identifier, const expression, const expression )
1492 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1494 static const char *const format_names[] = {
1502 if (token.type != T_IDENTIFIER) {
1503 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1506 const char *name = token.v.symbol->string;
1507 for (i = 0; i < 4; ++i) {
1508 if (strcmp_underscore(format_names[i], name) == 0)
1512 if (warning.attribute)
1513 warningf(HERE, "'%s' is an unrecognized format function type", name);
1518 add_anchor_token(')');
1519 add_anchor_token(',');
1520 parse_constant_expression();
1521 rem_anchor_token(',');
1522 rem_anchor_token(')');
1525 add_anchor_token(')');
1526 parse_constant_expression();
1527 rem_anchor_token(')');
1531 attribute->u.value = true;
1534 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1536 if (!attribute->have_arguments)
1539 /* should have no arguments */
1540 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1541 eat_until_matching_token('(');
1542 /* we have already consumed '(', so we stop before ')', eat it */
1544 attribute->invalid = true;
1548 * Parse one GNU attribute.
1550 * Note that attribute names can be specified WITH or WITHOUT
1551 * double underscores, ie const or __const__.
1553 * The following attributes are parsed without arguments
1578 * no_instrument_function
1579 * warn_unused_result
1596 * externally_visible
1604 * The following attributes are parsed with arguments
1605 * aligned( const expression )
1606 * alias( string literal )
1607 * section( string literal )
1608 * format( identifier, const expression, const expression )
1609 * format_arg( const expression )
1610 * tls_model( string literal )
1611 * visibility( string literal )
1612 * regparm( const expression )
1613 * model( string leteral )
1614 * trap_exit( const expression )
1615 * sp_switch( string literal )
1617 * The following attributes might have arguments
1618 * weak_ref( string literal )
1619 * non_null( const expression // ',' )
1620 * interrupt( string literal )
1621 * sentinel( constant expression )
1623 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1625 gnu_attribute_t *head = *attributes;
1626 gnu_attribute_t *last = *attributes;
1627 decl_modifiers_t modifiers = 0;
1628 gnu_attribute_t *attribute;
1630 eat(T___attribute__);
1634 if (token.type != ')') {
1635 /* find the end of the list */
1637 while (last->next != NULL)
1641 /* non-empty attribute list */
1644 if (token.type == T_const) {
1646 } else if (token.type == T_volatile) {
1648 } else if (token.type == T_cdecl) {
1649 /* __attribute__((cdecl)), WITH ms mode */
1651 } else if (token.type == T_IDENTIFIER) {
1652 const symbol_t *sym = token.v.symbol;
1655 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1662 for (i = 0; i < GNU_AK_LAST; ++i) {
1663 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1666 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1669 if (kind == GNU_AK_LAST) {
1670 if (warning.attribute)
1671 warningf(HERE, "'%s' attribute directive ignored", name);
1673 /* skip possible arguments */
1674 if (token.type == '(') {
1675 eat_until_matching_token(')');
1678 /* check for arguments */
1679 attribute = allocate_gnu_attribute(kind);
1680 if (token.type == '(') {
1682 if (token.type == ')') {
1683 /* empty args are allowed */
1686 attribute->have_arguments = true;
1690 case GNU_AK_VOLATILE:
1695 case GNU_AK_NOCOMMON:
1697 case GNU_AK_NOTSHARED:
1698 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1699 case GNU_AK_WARN_UNUSED_RESULT:
1700 case GNU_AK_LONGCALL:
1701 case GNU_AK_SHORTCALL:
1702 case GNU_AK_LONG_CALL:
1703 case GNU_AK_SHORT_CALL:
1704 case GNU_AK_FUNCTION_VECTOR:
1705 case GNU_AK_INTERRUPT_HANDLER:
1706 case GNU_AK_NMI_HANDLER:
1707 case GNU_AK_NESTING:
1711 case GNU_AK_EIGTHBIT_DATA:
1712 case GNU_AK_TINY_DATA:
1713 case GNU_AK_SAVEALL:
1714 case GNU_AK_FLATTEN:
1715 case GNU_AK_SSEREGPARM:
1716 case GNU_AK_EXTERNALLY_VISIBLE:
1717 case GNU_AK_RETURN_TWICE:
1718 case GNU_AK_MAY_ALIAS:
1719 case GNU_AK_MS_STRUCT:
1720 case GNU_AK_GCC_STRUCT:
1723 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1724 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1725 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1726 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1727 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1728 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1729 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1730 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1731 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1732 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1733 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1734 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1735 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1736 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1737 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1738 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1739 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1740 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1742 case GNU_AK_ALIGNED:
1743 /* __align__ may be used without an argument */
1744 if (attribute->have_arguments) {
1745 parse_gnu_attribute_const_arg(attribute);
1749 case GNU_AK_FORMAT_ARG:
1750 case GNU_AK_REGPARM:
1751 case GNU_AK_TRAP_EXIT:
1752 if (!attribute->have_arguments) {
1753 /* should have arguments */
1754 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1755 attribute->invalid = true;
1757 parse_gnu_attribute_const_arg(attribute);
1760 case GNU_AK_SECTION:
1761 case GNU_AK_SP_SWITCH:
1762 if (!attribute->have_arguments) {
1763 /* should have arguments */
1764 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1765 attribute->invalid = true;
1767 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1770 if (!attribute->have_arguments) {
1771 /* should have arguments */
1772 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1773 attribute->invalid = true;
1775 parse_gnu_attribute_format_args(attribute);
1777 case GNU_AK_WEAKREF:
1778 /* may have one string argument */
1779 if (attribute->have_arguments)
1780 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1782 case GNU_AK_NONNULL:
1783 if (attribute->have_arguments)
1784 parse_gnu_attribute_const_arg_list(attribute);
1786 case GNU_AK_TLS_MODEL:
1787 if (!attribute->have_arguments) {
1788 /* should have arguments */
1789 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1791 parse_gnu_attribute_tls_model_arg(attribute);
1793 case GNU_AK_VISIBILITY:
1794 if (!attribute->have_arguments) {
1795 /* should have arguments */
1796 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1798 parse_gnu_attribute_visibility_arg(attribute);
1801 if (!attribute->have_arguments) {
1802 /* should have arguments */
1803 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1805 parse_gnu_attribute_model_arg(attribute);
1809 if (!attribute->have_arguments) {
1810 /* should have arguments */
1811 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1813 parse_gnu_attribute_mode_arg(attribute);
1816 case GNU_AK_INTERRUPT:
1817 /* may have one string argument */
1818 if (attribute->have_arguments)
1819 parse_gnu_attribute_interrupt_arg(attribute);
1821 case GNU_AK_SENTINEL:
1822 /* may have one string argument */
1823 if (attribute->have_arguments)
1824 parse_gnu_attribute_const_arg(attribute);
1827 /* already handled */
1831 check_no_argument(attribute, name);
1834 if (attribute != NULL) {
1836 last->next = attribute;
1839 head = last = attribute;
1843 if (token.type != ',')
1857 * Parse GNU attributes.
1859 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1861 decl_modifiers_t modifiers = 0;
1864 switch (token.type) {
1865 case T___attribute__:
1866 modifiers |= parse_gnu_attribute(attributes);
1872 if (token.type != T_STRING_LITERAL) {
1873 parse_error_expected("while parsing assembler attribute",
1874 T_STRING_LITERAL, NULL);
1875 eat_until_matching_token('(');
1878 parse_string_literals();
1883 case T_cdecl: modifiers |= DM_CDECL; break;
1884 case T__fastcall: modifiers |= DM_FASTCALL; break;
1885 case T__stdcall: modifiers |= DM_STDCALL; break;
1888 /* TODO record modifier */
1890 warningf(HERE, "Ignoring declaration modifier %K", &token);
1894 default: return modifiers;
1901 static void mark_vars_read(expression_t *expr, variable_t *lhs_var);
1903 static variable_t *determine_lhs_var(expression_t *const expr,
1904 variable_t *lhs_var)
1906 switch (expr->kind) {
1907 case EXPR_REFERENCE: {
1908 entity_t *const entity = expr->reference.entity;
1909 /* we should only find variables as lavlues... */
1910 if (entity->base.kind != ENTITY_VARIABLE)
1913 return &entity->variable;
1916 case EXPR_ARRAY_ACCESS: {
1917 expression_t *const ref = expr->array_access.array_ref;
1918 variable_t * var = NULL;
1919 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1920 var = determine_lhs_var(ref, lhs_var);
1923 mark_vars_read(expr->select.compound, lhs_var);
1925 mark_vars_read(expr->array_access.index, lhs_var);
1930 if (is_type_compound(skip_typeref(expr->base.type))) {
1931 return determine_lhs_var(expr->select.compound, lhs_var);
1933 mark_vars_read(expr->select.compound, lhs_var);
1938 case EXPR_UNARY_DEREFERENCE: {
1939 expression_t *const val = expr->unary.value;
1940 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1942 return determine_lhs_var(val->unary.value, lhs_var);
1944 mark_vars_read(val, NULL);
1950 mark_vars_read(expr, NULL);
1955 #define VAR_ANY ((variable_t*)-1)
1958 * Mark declarations, which are read. This is used to deted variables, which
1962 * x is not marked as "read", because it is only read to calculate its own new
1966 * x and y are not detected as "not read", because multiple variables are
1969 static void mark_vars_read(expression_t *const expr, variable_t *lhs_var)
1971 switch (expr->kind) {
1972 case EXPR_REFERENCE: {
1973 entity_t *const entity = expr->reference.entity;
1974 if (entity->kind != ENTITY_VARIABLE)
1977 variable_t *variable = &entity->variable;
1978 if (lhs_var != variable && lhs_var != VAR_ANY) {
1979 variable->read = true;
1985 // TODO respect pure/const
1986 mark_vars_read(expr->call.function, NULL);
1987 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1988 mark_vars_read(arg->expression, NULL);
1992 case EXPR_CONDITIONAL:
1993 // TODO lhs_decl should depend on whether true/false have an effect
1994 mark_vars_read(expr->conditional.condition, NULL);
1995 if (expr->conditional.true_expression != NULL)
1996 mark_vars_read(expr->conditional.true_expression, lhs_var);
1997 mark_vars_read(expr->conditional.false_expression, lhs_var);
2001 if (lhs_var == VAR_ANY && !is_type_compound(skip_typeref(expr->base.type)))
2003 mark_vars_read(expr->select.compound, lhs_var);
2006 case EXPR_ARRAY_ACCESS: {
2007 expression_t *const ref = expr->array_access.array_ref;
2008 mark_vars_read(ref, lhs_var);
2009 lhs_var = determine_lhs_var(ref, lhs_var);
2010 mark_vars_read(expr->array_access.index, lhs_var);
2015 mark_vars_read(expr->va_arge.ap, lhs_var);
2018 case EXPR_UNARY_CAST:
2019 /* Special case: Use void cast to mark a variable as "read" */
2020 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2025 case EXPR_UNARY_THROW:
2026 if (expr->unary.value == NULL)
2029 case EXPR_UNARY_DEREFERENCE:
2030 case EXPR_UNARY_DELETE:
2031 case EXPR_UNARY_DELETE_ARRAY:
2032 if (lhs_var == VAR_ANY)
2036 case EXPR_UNARY_NEGATE:
2037 case EXPR_UNARY_PLUS:
2038 case EXPR_UNARY_BITWISE_NEGATE:
2039 case EXPR_UNARY_NOT:
2040 case EXPR_UNARY_TAKE_ADDRESS:
2041 case EXPR_UNARY_POSTFIX_INCREMENT:
2042 case EXPR_UNARY_POSTFIX_DECREMENT:
2043 case EXPR_UNARY_PREFIX_INCREMENT:
2044 case EXPR_UNARY_PREFIX_DECREMENT:
2045 case EXPR_UNARY_CAST_IMPLICIT:
2046 case EXPR_UNARY_ASSUME:
2048 mark_vars_read(expr->unary.value, lhs_var);
2051 case EXPR_BINARY_ADD:
2052 case EXPR_BINARY_SUB:
2053 case EXPR_BINARY_MUL:
2054 case EXPR_BINARY_DIV:
2055 case EXPR_BINARY_MOD:
2056 case EXPR_BINARY_EQUAL:
2057 case EXPR_BINARY_NOTEQUAL:
2058 case EXPR_BINARY_LESS:
2059 case EXPR_BINARY_LESSEQUAL:
2060 case EXPR_BINARY_GREATER:
2061 case EXPR_BINARY_GREATEREQUAL:
2062 case EXPR_BINARY_BITWISE_AND:
2063 case EXPR_BINARY_BITWISE_OR:
2064 case EXPR_BINARY_BITWISE_XOR:
2065 case EXPR_BINARY_LOGICAL_AND:
2066 case EXPR_BINARY_LOGICAL_OR:
2067 case EXPR_BINARY_SHIFTLEFT:
2068 case EXPR_BINARY_SHIFTRIGHT:
2069 case EXPR_BINARY_COMMA:
2070 case EXPR_BINARY_ISGREATER:
2071 case EXPR_BINARY_ISGREATEREQUAL:
2072 case EXPR_BINARY_ISLESS:
2073 case EXPR_BINARY_ISLESSEQUAL:
2074 case EXPR_BINARY_ISLESSGREATER:
2075 case EXPR_BINARY_ISUNORDERED:
2076 mark_vars_read(expr->binary.left, lhs_var);
2077 mark_vars_read(expr->binary.right, lhs_var);
2080 case EXPR_BINARY_ASSIGN:
2081 case EXPR_BINARY_MUL_ASSIGN:
2082 case EXPR_BINARY_DIV_ASSIGN:
2083 case EXPR_BINARY_MOD_ASSIGN:
2084 case EXPR_BINARY_ADD_ASSIGN:
2085 case EXPR_BINARY_SUB_ASSIGN:
2086 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2087 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2088 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2089 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2090 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2091 if (lhs_var == VAR_ANY)
2093 lhs_var = determine_lhs_var(expr->binary.left, lhs_var);
2094 mark_vars_read(expr->binary.right, lhs_var);
2099 determine_lhs_var(expr->va_starte.ap, lhs_var);
2105 case EXPR_CHARACTER_CONSTANT:
2106 case EXPR_WIDE_CHARACTER_CONSTANT:
2107 case EXPR_STRING_LITERAL:
2108 case EXPR_WIDE_STRING_LITERAL:
2109 case EXPR_COMPOUND_LITERAL: // TODO init?
2111 case EXPR_CLASSIFY_TYPE:
2114 case EXPR_BUILTIN_SYMBOL:
2115 case EXPR_BUILTIN_CONSTANT_P:
2116 case EXPR_BUILTIN_PREFETCH:
2118 case EXPR_STATEMENT: // TODO
2119 case EXPR_LABEL_ADDRESS:
2120 case EXPR_BINARY_BUILTIN_EXPECT:
2121 case EXPR_REFERENCE_ENUM_VALUE:
2125 panic("unhandled expression");
2128 static designator_t *parse_designation(void)
2130 designator_t *result = NULL;
2131 designator_t *last = NULL;
2134 designator_t *designator;
2135 switch (token.type) {
2137 designator = allocate_ast_zero(sizeof(designator[0]));
2138 designator->source_position = token.source_position;
2140 add_anchor_token(']');
2141 designator->array_index = parse_constant_expression();
2142 rem_anchor_token(']');
2146 designator = allocate_ast_zero(sizeof(designator[0]));
2147 designator->source_position = token.source_position;
2149 if (token.type != T_IDENTIFIER) {
2150 parse_error_expected("while parsing designator",
2151 T_IDENTIFIER, NULL);
2154 designator->symbol = token.v.symbol;
2162 assert(designator != NULL);
2164 last->next = designator;
2166 result = designator;
2174 static initializer_t *initializer_from_string(array_type_t *type,
2175 const string_t *const string)
2177 /* TODO: check len vs. size of array type */
2180 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2181 initializer->string.string = *string;
2186 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2187 wide_string_t *const string)
2189 /* TODO: check len vs. size of array type */
2192 initializer_t *const initializer =
2193 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2194 initializer->wide_string.string = *string;
2200 * Build an initializer from a given expression.
2202 static initializer_t *initializer_from_expression(type_t *orig_type,
2203 expression_t *expression)
2205 /* TODO check that expression is a constant expression */
2207 /* § 6.7.8.14/15 char array may be initialized by string literals */
2208 type_t *type = skip_typeref(orig_type);
2209 type_t *expr_type_orig = expression->base.type;
2210 type_t *expr_type = skip_typeref(expr_type_orig);
2211 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2212 array_type_t *const array_type = &type->array;
2213 type_t *const element_type = skip_typeref(array_type->element_type);
2215 if (element_type->kind == TYPE_ATOMIC) {
2216 atomic_type_kind_t akind = element_type->atomic.akind;
2217 switch (expression->kind) {
2218 case EXPR_STRING_LITERAL:
2219 if (akind == ATOMIC_TYPE_CHAR
2220 || akind == ATOMIC_TYPE_SCHAR
2221 || akind == ATOMIC_TYPE_UCHAR) {
2222 return initializer_from_string(array_type,
2223 &expression->string.value);
2226 case EXPR_WIDE_STRING_LITERAL: {
2227 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2228 if (get_unqualified_type(element_type) == bare_wchar_type) {
2229 return initializer_from_wide_string(array_type,
2230 &expression->wide_string.value);
2240 assign_error_t error = semantic_assign(type, expression);
2241 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2243 report_assign_error(error, type, expression, "initializer",
2244 &expression->base.source_position);
2246 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2248 if (type->kind == TYPE_BITFIELD) {
2249 type = type->bitfield.base_type;
2252 result->value.value = create_implicit_cast(expression, type);
2258 * Checks if a given expression can be used as an constant initializer.
2260 static bool is_initializer_constant(const expression_t *expression)
2262 return is_constant_expression(expression)
2263 || is_address_constant(expression);
2267 * Parses an scalar initializer.
2269 * § 6.7.8.11; eat {} without warning
2271 static initializer_t *parse_scalar_initializer(type_t *type,
2272 bool must_be_constant)
2274 /* there might be extra {} hierarchies */
2276 if (token.type == '{') {
2278 warningf(HERE, "extra curly braces around scalar initializer");
2282 } while (token.type == '{');
2285 expression_t *expression = parse_assignment_expression();
2286 mark_vars_read(expression, NULL);
2287 if (must_be_constant && !is_initializer_constant(expression)) {
2288 errorf(&expression->base.source_position,
2289 "Initialisation expression '%E' is not constant\n",
2293 initializer_t *initializer = initializer_from_expression(type, expression);
2295 if (initializer == NULL) {
2296 errorf(&expression->base.source_position,
2297 "expression '%E' (type '%T') doesn't match expected type '%T'",
2298 expression, expression->base.type, type);
2303 bool additional_warning_displayed = false;
2304 while (braces > 0) {
2305 if (token.type == ',') {
2308 if (token.type != '}') {
2309 if (!additional_warning_displayed && warning.other) {
2310 warningf(HERE, "additional elements in scalar initializer");
2311 additional_warning_displayed = true;
2322 * An entry in the type path.
2324 typedef struct type_path_entry_t type_path_entry_t;
2325 struct type_path_entry_t {
2326 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2328 size_t index; /**< For array types: the current index. */
2329 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2334 * A type path expression a position inside compound or array types.
2336 typedef struct type_path_t type_path_t;
2337 struct type_path_t {
2338 type_path_entry_t *path; /**< An flexible array containing the current path. */
2339 type_t *top_type; /**< type of the element the path points */
2340 size_t max_index; /**< largest index in outermost array */
2344 * Prints a type path for debugging.
2346 static __attribute__((unused)) void debug_print_type_path(
2347 const type_path_t *path)
2349 size_t len = ARR_LEN(path->path);
2351 for (size_t i = 0; i < len; ++i) {
2352 const type_path_entry_t *entry = & path->path[i];
2354 type_t *type = skip_typeref(entry->type);
2355 if (is_type_compound(type)) {
2356 /* in gcc mode structs can have no members */
2357 if (entry->v.compound_entry == NULL) {
2361 fprintf(stderr, ".%s",
2362 entry->v.compound_entry->base.symbol->string);
2363 } else if (is_type_array(type)) {
2364 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
2366 fprintf(stderr, "-INVALID-");
2369 if (path->top_type != NULL) {
2370 fprintf(stderr, " (");
2371 print_type(path->top_type);
2372 fprintf(stderr, ")");
2377 * Return the top type path entry, ie. in a path
2378 * (type).a.b returns the b.
2380 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2382 size_t len = ARR_LEN(path->path);
2384 return &path->path[len-1];
2388 * Enlarge the type path by an (empty) element.
2390 static type_path_entry_t *append_to_type_path(type_path_t *path)
2392 size_t len = ARR_LEN(path->path);
2393 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2395 type_path_entry_t *result = & path->path[len];
2396 memset(result, 0, sizeof(result[0]));
2401 * Descending into a sub-type. Enter the scope of the current top_type.
2403 static void descend_into_subtype(type_path_t *path)
2405 type_t *orig_top_type = path->top_type;
2406 type_t *top_type = skip_typeref(orig_top_type);
2408 type_path_entry_t *top = append_to_type_path(path);
2409 top->type = top_type;
2411 if (is_type_compound(top_type)) {
2412 compound_t *compound = top_type->compound.compound;
2413 entity_t *entry = compound->members.entities;
2415 if (entry != NULL) {
2416 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2417 top->v.compound_entry = &entry->declaration;
2418 path->top_type = entry->declaration.type;
2420 path->top_type = NULL;
2422 } else if (is_type_array(top_type)) {
2424 path->top_type = top_type->array.element_type;
2426 assert(!is_type_valid(top_type));
2431 * Pop an entry from the given type path, ie. returning from
2432 * (type).a.b to (type).a
2434 static void ascend_from_subtype(type_path_t *path)
2436 type_path_entry_t *top = get_type_path_top(path);
2438 path->top_type = top->type;
2440 size_t len = ARR_LEN(path->path);
2441 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2445 * Pop entries from the given type path until the given
2446 * path level is reached.
2448 static void ascend_to(type_path_t *path, size_t top_path_level)
2450 size_t len = ARR_LEN(path->path);
2452 while (len > top_path_level) {
2453 ascend_from_subtype(path);
2454 len = ARR_LEN(path->path);
2458 static bool walk_designator(type_path_t *path, const designator_t *designator,
2459 bool used_in_offsetof)
2461 for (; designator != NULL; designator = designator->next) {
2462 type_path_entry_t *top = get_type_path_top(path);
2463 type_t *orig_type = top->type;
2465 type_t *type = skip_typeref(orig_type);
2467 if (designator->symbol != NULL) {
2468 symbol_t *symbol = designator->symbol;
2469 if (!is_type_compound(type)) {
2470 if (is_type_valid(type)) {
2471 errorf(&designator->source_position,
2472 "'.%Y' designator used for non-compound type '%T'",
2476 top->type = type_error_type;
2477 top->v.compound_entry = NULL;
2478 orig_type = type_error_type;
2480 compound_t *compound = type->compound.compound;
2481 entity_t *iter = compound->members.entities;
2482 for (; iter != NULL; iter = iter->base.next) {
2483 if (iter->base.symbol == symbol) {
2488 errorf(&designator->source_position,
2489 "'%T' has no member named '%Y'", orig_type, symbol);
2492 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2493 if (used_in_offsetof) {
2494 type_t *real_type = skip_typeref(iter->declaration.type);
2495 if (real_type->kind == TYPE_BITFIELD) {
2496 errorf(&designator->source_position,
2497 "offsetof designator '%Y' may not specify bitfield",
2503 top->type = orig_type;
2504 top->v.compound_entry = &iter->declaration;
2505 orig_type = iter->declaration.type;
2508 expression_t *array_index = designator->array_index;
2509 assert(designator->array_index != NULL);
2511 if (!is_type_array(type)) {
2512 if (is_type_valid(type)) {
2513 errorf(&designator->source_position,
2514 "[%E] designator used for non-array type '%T'",
2515 array_index, orig_type);
2520 long index = fold_constant(array_index);
2521 if (!used_in_offsetof) {
2523 errorf(&designator->source_position,
2524 "array index [%E] must be positive", array_index);
2525 } else if (type->array.size_constant) {
2526 long array_size = type->array.size;
2527 if (index >= array_size) {
2528 errorf(&designator->source_position,
2529 "designator [%E] (%d) exceeds array size %d",
2530 array_index, index, array_size);
2535 top->type = orig_type;
2536 top->v.index = (size_t) index;
2537 orig_type = type->array.element_type;
2539 path->top_type = orig_type;
2541 if (designator->next != NULL) {
2542 descend_into_subtype(path);
2551 static void advance_current_object(type_path_t *path, size_t top_path_level)
2553 type_path_entry_t *top = get_type_path_top(path);
2555 type_t *type = skip_typeref(top->type);
2556 if (is_type_union(type)) {
2557 /* in unions only the first element is initialized */
2558 top->v.compound_entry = NULL;
2559 } else if (is_type_struct(type)) {
2560 declaration_t *entry = top->v.compound_entry;
2562 entity_t *next_entity = entry->base.next;
2563 if (next_entity != NULL) {
2564 assert(is_declaration(next_entity));
2565 entry = &next_entity->declaration;
2570 top->v.compound_entry = entry;
2571 if (entry != NULL) {
2572 path->top_type = entry->type;
2575 } else if (is_type_array(type)) {
2576 assert(is_type_array(type));
2580 if (!type->array.size_constant || top->v.index < type->array.size) {
2584 assert(!is_type_valid(type));
2588 /* we're past the last member of the current sub-aggregate, try if we
2589 * can ascend in the type hierarchy and continue with another subobject */
2590 size_t len = ARR_LEN(path->path);
2592 if (len > top_path_level) {
2593 ascend_from_subtype(path);
2594 advance_current_object(path, top_path_level);
2596 path->top_type = NULL;
2601 * skip until token is found.
2603 static void skip_until(int type)
2605 while (token.type != type) {
2606 if (token.type == T_EOF)
2613 * skip any {...} blocks until a closing bracket is reached.
2615 static void skip_initializers(void)
2617 if (token.type == '{')
2620 while (token.type != '}') {
2621 if (token.type == T_EOF)
2623 if (token.type == '{') {
2631 static initializer_t *create_empty_initializer(void)
2633 static initializer_t empty_initializer
2634 = { .list = { { INITIALIZER_LIST }, 0 } };
2635 return &empty_initializer;
2639 * Parse a part of an initialiser for a struct or union,
2641 static initializer_t *parse_sub_initializer(type_path_t *path,
2642 type_t *outer_type, size_t top_path_level,
2643 parse_initializer_env_t *env)
2645 if (token.type == '}') {
2646 /* empty initializer */
2647 return create_empty_initializer();
2650 type_t *orig_type = path->top_type;
2651 type_t *type = NULL;
2653 if (orig_type == NULL) {
2654 /* We are initializing an empty compound. */
2656 type = skip_typeref(orig_type);
2659 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2662 designator_t *designator = NULL;
2663 if (token.type == '.' || token.type == '[') {
2664 designator = parse_designation();
2665 goto finish_designator;
2666 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2667 /* GNU-style designator ("identifier: value") */
2668 designator = allocate_ast_zero(sizeof(designator[0]));
2669 designator->source_position = token.source_position;
2670 designator->symbol = token.v.symbol;
2675 /* reset path to toplevel, evaluate designator from there */
2676 ascend_to(path, top_path_level);
2677 if (!walk_designator(path, designator, false)) {
2678 /* can't continue after designation error */
2682 initializer_t *designator_initializer
2683 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2684 designator_initializer->designator.designator = designator;
2685 ARR_APP1(initializer_t*, initializers, designator_initializer);
2687 orig_type = path->top_type;
2688 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2693 if (token.type == '{') {
2694 if (type != NULL && is_type_scalar(type)) {
2695 sub = parse_scalar_initializer(type, env->must_be_constant);
2699 if (env->entity != NULL) {
2701 "extra brace group at end of initializer for '%Y'",
2702 env->entity->base.symbol);
2704 errorf(HERE, "extra brace group at end of initializer");
2707 descend_into_subtype(path);
2709 add_anchor_token('}');
2710 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2712 rem_anchor_token('}');
2715 ascend_from_subtype(path);
2719 goto error_parse_next;
2723 /* must be an expression */
2724 expression_t *expression = parse_assignment_expression();
2726 if (env->must_be_constant && !is_initializer_constant(expression)) {
2727 errorf(&expression->base.source_position,
2728 "Initialisation expression '%E' is not constant\n",
2733 /* we are already outside, ... */
2734 type_t *const outer_type_skip = skip_typeref(outer_type);
2735 if (is_type_compound(outer_type_skip) &&
2736 !outer_type_skip->compound.compound->complete) {
2737 goto error_parse_next;
2742 /* handle { "string" } special case */
2743 if ((expression->kind == EXPR_STRING_LITERAL
2744 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2745 && outer_type != NULL) {
2746 sub = initializer_from_expression(outer_type, expression);
2748 if (token.type == ',') {
2751 if (token.type != '}' && warning.other) {
2752 warningf(HERE, "excessive elements in initializer for type '%T'",
2755 /* TODO: eat , ... */
2760 /* descend into subtypes until expression matches type */
2762 orig_type = path->top_type;
2763 type = skip_typeref(orig_type);
2765 sub = initializer_from_expression(orig_type, expression);
2769 if (!is_type_valid(type)) {
2772 if (is_type_scalar(type)) {
2773 errorf(&expression->base.source_position,
2774 "expression '%E' doesn't match expected type '%T'",
2775 expression, orig_type);
2779 descend_into_subtype(path);
2783 /* update largest index of top array */
2784 const type_path_entry_t *first = &path->path[0];
2785 type_t *first_type = first->type;
2786 first_type = skip_typeref(first_type);
2787 if (is_type_array(first_type)) {
2788 size_t index = first->v.index;
2789 if (index > path->max_index)
2790 path->max_index = index;
2794 /* append to initializers list */
2795 ARR_APP1(initializer_t*, initializers, sub);
2798 if (warning.other) {
2799 if (env->entity != NULL) {
2800 warningf(HERE, "excess elements in struct initializer for '%Y'",
2801 env->entity->base.symbol);
2803 warningf(HERE, "excess elements in struct initializer");
2809 if (token.type == '}') {
2813 if (token.type == '}') {
2818 /* advance to the next declaration if we are not at the end */
2819 advance_current_object(path, top_path_level);
2820 orig_type = path->top_type;
2821 if (orig_type != NULL)
2822 type = skip_typeref(orig_type);
2828 size_t len = ARR_LEN(initializers);
2829 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2830 initializer_t *result = allocate_ast_zero(size);
2831 result->kind = INITIALIZER_LIST;
2832 result->list.len = len;
2833 memcpy(&result->list.initializers, initializers,
2834 len * sizeof(initializers[0]));
2836 DEL_ARR_F(initializers);
2837 ascend_to(path, top_path_level+1);
2842 skip_initializers();
2843 DEL_ARR_F(initializers);
2844 ascend_to(path, top_path_level+1);
2849 * Parses an initializer. Parsers either a compound literal
2850 * (env->declaration == NULL) or an initializer of a declaration.
2852 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2854 type_t *type = skip_typeref(env->type);
2855 initializer_t *result = NULL;
2858 if (is_type_scalar(type)) {
2859 result = parse_scalar_initializer(type, env->must_be_constant);
2860 } else if (token.type == '{') {
2864 memset(&path, 0, sizeof(path));
2865 path.top_type = env->type;
2866 path.path = NEW_ARR_F(type_path_entry_t, 0);
2868 descend_into_subtype(&path);
2870 add_anchor_token('}');
2871 result = parse_sub_initializer(&path, env->type, 1, env);
2872 rem_anchor_token('}');
2874 max_index = path.max_index;
2875 DEL_ARR_F(path.path);
2879 /* parse_scalar_initializer() also works in this case: we simply
2880 * have an expression without {} around it */
2881 result = parse_scalar_initializer(type, env->must_be_constant);
2884 /* § 6.7.8 (22) array initializers for arrays with unknown size determine
2885 * the array type size */
2886 if (is_type_array(type) && type->array.size_expression == NULL
2887 && result != NULL) {
2889 switch (result->kind) {
2890 case INITIALIZER_LIST:
2891 size = max_index + 1;
2894 case INITIALIZER_STRING:
2895 size = result->string.string.size;
2898 case INITIALIZER_WIDE_STRING:
2899 size = result->wide_string.string.size;
2902 case INITIALIZER_DESIGNATOR:
2903 case INITIALIZER_VALUE:
2904 /* can happen for parse errors */
2909 internal_errorf(HERE, "invalid initializer type");
2912 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2913 cnst->base.type = type_size_t;
2914 cnst->conste.v.int_value = size;
2916 type_t *new_type = duplicate_type(type);
2918 new_type->array.size_expression = cnst;
2919 new_type->array.size_constant = true;
2920 new_type->array.has_implicit_size = true;
2921 new_type->array.size = size;
2922 env->type = new_type;
2930 static void append_entity(scope_t *scope, entity_t *entity)
2932 if (scope->last_entity != NULL) {
2933 scope->last_entity->base.next = entity;
2935 scope->entities = entity;
2937 scope->last_entity = entity;
2941 static compound_t *parse_compound_type_specifier(bool is_struct)
2943 gnu_attribute_t *attributes = NULL;
2944 decl_modifiers_t modifiers = 0;
2951 symbol_t *symbol = NULL;
2952 compound_t *compound = NULL;
2954 if (token.type == T___attribute__) {
2955 modifiers |= parse_attributes(&attributes);
2958 if (token.type == T_IDENTIFIER) {
2959 symbol = token.v.symbol;
2962 namespace_tag_t const namespc =
2963 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2964 entity_t *entity = get_entity(symbol, namespc);
2965 if (entity != NULL) {
2966 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
2967 compound = &entity->compound;
2968 if (compound->base.parent_scope != current_scope &&
2969 (token.type == '{' || token.type == ';')) {
2970 /* we're in an inner scope and have a definition. Override
2971 existing definition in outer scope */
2973 } else if (compound->complete && token.type == '{') {
2974 assert(symbol != NULL);
2975 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2976 is_struct ? "struct" : "union", symbol,
2977 &compound->base.source_position);
2978 /* clear members in the hope to avoid further errors */
2979 compound->members.entities = NULL;
2982 } else if (token.type != '{') {
2984 parse_error_expected("while parsing struct type specifier",
2985 T_IDENTIFIER, '{', NULL);
2987 parse_error_expected("while parsing union type specifier",
2988 T_IDENTIFIER, '{', NULL);
2994 if (compound == NULL) {
2995 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2996 entity_t *entity = allocate_entity_zero(kind);
2997 compound = &entity->compound;
2999 compound->base.namespc =
3000 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
3001 compound->base.source_position = token.source_position;
3002 compound->base.symbol = symbol;
3003 compound->base.parent_scope = current_scope;
3004 if (symbol != NULL) {
3005 environment_push(entity);
3007 append_entity(current_scope, entity);
3010 if (token.type == '{') {
3011 parse_compound_type_entries(compound);
3012 modifiers |= parse_attributes(&attributes);
3014 if (symbol == NULL) {
3015 assert(anonymous_entity == NULL);
3016 anonymous_entity = (entity_t*)compound;
3020 compound->modifiers |= modifiers;
3024 static void parse_enum_entries(type_t *const enum_type)
3028 if (token.type == '}') {
3029 errorf(HERE, "empty enum not allowed");
3034 add_anchor_token('}');
3036 if (token.type != T_IDENTIFIER) {
3037 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3039 rem_anchor_token('}');
3043 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3044 entity->enum_value.enum_type = enum_type;
3045 entity->base.symbol = token.v.symbol;
3046 entity->base.source_position = token.source_position;
3049 if (token.type == '=') {
3051 expression_t *value = parse_constant_expression();
3053 value = create_implicit_cast(value, enum_type);
3054 entity->enum_value.value = value;
3059 record_entity(entity, false);
3061 if (token.type != ',')
3064 } while (token.type != '}');
3065 rem_anchor_token('}');
3073 static type_t *parse_enum_specifier(void)
3075 gnu_attribute_t *attributes = NULL;
3080 if (token.type == T_IDENTIFIER) {
3081 symbol = token.v.symbol;
3084 entity = get_entity(symbol, NAMESPACE_ENUM);
3085 assert(entity == NULL || entity->kind == ENTITY_ENUM);
3086 } else if (token.type != '{') {
3087 parse_error_expected("while parsing enum type specifier",
3088 T_IDENTIFIER, '{', NULL);
3095 if (entity == NULL) {
3096 entity = allocate_entity_zero(ENTITY_ENUM);
3097 entity->base.namespc = NAMESPACE_ENUM;
3098 entity->base.source_position = token.source_position;
3099 entity->base.symbol = symbol;
3100 entity->base.parent_scope = current_scope;
3103 type_t *const type = allocate_type_zero(TYPE_ENUM);
3104 type->enumt.enume = &entity->enume;
3106 if (token.type == '{') {
3107 if (entity->enume.complete) {
3108 errorf(HERE, "multiple definitions of enum %Y (previous definition %P)",
3109 symbol, &entity->base.source_position);
3111 if (symbol != NULL) {
3112 environment_push(entity);
3114 append_entity(current_scope, entity);
3115 entity->enume.complete = true;
3117 parse_enum_entries(type);
3118 parse_attributes(&attributes);
3120 if (symbol == NULL) {
3121 assert(anonymous_entity == NULL);
3122 anonymous_entity = entity;
3124 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
3125 errorf(HERE, "enum %Y used before definition (incomplete enumes are a GNU extension)",
3133 * if a symbol is a typedef to another type, return true
3135 static bool is_typedef_symbol(symbol_t *symbol)
3137 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3138 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3141 static type_t *parse_typeof(void)
3148 add_anchor_token(')');
3150 expression_t *expression = NULL;
3152 bool old_type_prop = in_type_prop;
3153 bool old_gcc_extension = in_gcc_extension;
3154 in_type_prop = true;
3156 while (token.type == T___extension__) {
3157 /* This can be a prefix to a typename or an expression. */
3159 in_gcc_extension = true;
3161 switch (token.type) {
3163 if (is_typedef_symbol(token.v.symbol)) {
3164 type = parse_typename();
3166 expression = parse_expression();
3167 type = expression->base.type;
3172 type = parse_typename();
3176 expression = parse_expression();
3177 type = expression->base.type;
3180 in_type_prop = old_type_prop;
3181 in_gcc_extension = old_gcc_extension;
3183 rem_anchor_token(')');
3186 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3187 typeof_type->typeoft.expression = expression;
3188 typeof_type->typeoft.typeof_type = type;
3195 typedef enum specifiers_t {
3196 SPECIFIER_SIGNED = 1 << 0,
3197 SPECIFIER_UNSIGNED = 1 << 1,
3198 SPECIFIER_LONG = 1 << 2,
3199 SPECIFIER_INT = 1 << 3,
3200 SPECIFIER_DOUBLE = 1 << 4,
3201 SPECIFIER_CHAR = 1 << 5,
3202 SPECIFIER_SHORT = 1 << 6,
3203 SPECIFIER_LONG_LONG = 1 << 7,
3204 SPECIFIER_FLOAT = 1 << 8,
3205 SPECIFIER_BOOL = 1 << 9,
3206 SPECIFIER_VOID = 1 << 10,
3207 SPECIFIER_INT8 = 1 << 11,
3208 SPECIFIER_INT16 = 1 << 12,
3209 SPECIFIER_INT32 = 1 << 13,
3210 SPECIFIER_INT64 = 1 << 14,
3211 SPECIFIER_INT128 = 1 << 15,
3212 SPECIFIER_COMPLEX = 1 << 16,
3213 SPECIFIER_IMAGINARY = 1 << 17,
3216 static type_t *create_builtin_type(symbol_t *const symbol,
3217 type_t *const real_type)
3219 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3220 type->builtin.symbol = symbol;
3221 type->builtin.real_type = real_type;
3223 type_t *result = typehash_insert(type);
3224 if (type != result) {
3231 static type_t *get_typedef_type(symbol_t *symbol)
3233 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3234 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3237 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3238 type->typedeft.typedefe = &entity->typedefe;
3244 * check for the allowed MS alignment values.
3246 static bool check_alignment_value(long long intvalue)
3248 if (intvalue < 1 || intvalue > 8192) {
3249 errorf(HERE, "illegal alignment value");
3252 unsigned v = (unsigned)intvalue;
3253 for (unsigned i = 1; i <= 8192; i += i) {
3257 errorf(HERE, "alignment must be power of two");
3261 #define DET_MOD(name, tag) do { \
3262 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3263 *modifiers |= tag; \
3266 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3268 decl_modifiers_t *modifiers = &specifiers->modifiers;
3271 if (token.type == T_restrict) {
3273 DET_MOD(restrict, DM_RESTRICT);
3275 } else if (token.type != T_IDENTIFIER)
3277 symbol_t *symbol = token.v.symbol;
3278 if (symbol == sym_align) {
3281 if (token.type != T_INTEGER)
3283 if (check_alignment_value(token.v.intvalue)) {
3284 if (specifiers->alignment != 0 && warning.other)
3285 warningf(HERE, "align used more than once");
3286 specifiers->alignment = (unsigned char)token.v.intvalue;
3290 } else if (symbol == sym_allocate) {
3293 if (token.type != T_IDENTIFIER)
3295 (void)token.v.symbol;
3297 } else if (symbol == sym_dllimport) {
3299 DET_MOD(dllimport, DM_DLLIMPORT);
3300 } else if (symbol == sym_dllexport) {
3302 DET_MOD(dllexport, DM_DLLEXPORT);
3303 } else if (symbol == sym_thread) {
3305 DET_MOD(thread, DM_THREAD);
3306 } else if (symbol == sym_naked) {
3308 DET_MOD(naked, DM_NAKED);
3309 } else if (symbol == sym_noinline) {
3311 DET_MOD(noinline, DM_NOINLINE);
3312 } else if (symbol == sym_noreturn) {
3314 DET_MOD(noreturn, DM_NORETURN);
3315 } else if (symbol == sym_nothrow) {
3317 DET_MOD(nothrow, DM_NOTHROW);
3318 } else if (symbol == sym_novtable) {
3320 DET_MOD(novtable, DM_NOVTABLE);
3321 } else if (symbol == sym_property) {
3325 bool is_get = false;
3326 if (token.type != T_IDENTIFIER)
3328 if (token.v.symbol == sym_get) {
3330 } else if (token.v.symbol == sym_put) {
3332 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3337 if (token.type != T_IDENTIFIER)
3340 if (specifiers->get_property_sym != NULL) {
3341 errorf(HERE, "get property name already specified");
3343 specifiers->get_property_sym = token.v.symbol;
3346 if (specifiers->put_property_sym != NULL) {
3347 errorf(HERE, "put property name already specified");
3349 specifiers->put_property_sym = token.v.symbol;
3353 if (token.type == ',') {
3360 } else if (symbol == sym_selectany) {
3362 DET_MOD(selectany, DM_SELECTANY);
3363 } else if (symbol == sym_uuid) {
3366 if (token.type != T_STRING_LITERAL)
3370 } else if (symbol == sym_deprecated) {
3372 if (specifiers->deprecated != 0 && warning.other)
3373 warningf(HERE, "deprecated used more than once");
3374 specifiers->deprecated = true;
3375 if (token.type == '(') {
3377 if (token.type == T_STRING_LITERAL) {
3378 specifiers->deprecated_string = token.v.string.begin;
3381 errorf(HERE, "string literal expected");
3385 } else if (symbol == sym_noalias) {
3387 DET_MOD(noalias, DM_NOALIAS);
3390 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3392 if (token.type == '(')
3396 if (token.type == ',')
3403 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3405 entity_t *entity = allocate_entity_zero(kind);
3406 entity->base.source_position = *HERE;
3407 entity->base.symbol = symbol;
3408 if (is_declaration(entity)) {
3409 entity->declaration.type = type_error_type;
3410 entity->declaration.implicit = true;
3411 } else if (kind == ENTITY_TYPEDEF) {
3412 entity->typedefe.type = type_error_type;
3414 record_entity(entity, false);
3418 static void parse_microsoft_based(based_spec_t *based_spec)
3420 if (token.type != T_IDENTIFIER) {
3421 parse_error_expected("while parsing __based", T_IDENTIFIER, NULL);
3424 symbol_t *symbol = token.v.symbol;
3425 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3427 if (entity == NULL || entity->base.kind != ENTITY_VARIABLE) {
3428 errorf(HERE, "'%Y' is not a variable name.", symbol);
3429 entity = create_error_entity(symbol, ENTITY_VARIABLE);
3431 variable_t *variable = &entity->variable;
3433 if (based_spec->base_variable != NULL) {
3434 errorf(HERE, "__based type qualifier specified more than once");
3436 based_spec->source_position = token.source_position;
3437 based_spec->base_variable = variable;
3439 type_t *const type = variable->base.type;
3441 if (is_type_valid(type)) {
3442 if (! is_type_pointer(skip_typeref(type))) {
3443 errorf(HERE, "variable in __based modifier must have pointer type instead of %T", type);
3445 if (variable->base.base.parent_scope != file_scope) {
3446 errorf(HERE, "a nonstatic local variable may not be used in a __based specification");
3454 * Finish the construction of a struct type by calculating
3455 * its size, offsets, alignment.
3457 static void finish_struct_type(compound_type_t *type)
3459 assert(type->compound != NULL);
3461 compound_t *compound = type->compound;
3462 if (!compound->complete)
3467 il_alignment_t alignment = 1;
3468 bool need_pad = false;
3470 entity_t *entry = compound->members.entities;
3471 for (; entry != NULL; entry = entry->base.next) {
3472 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3475 type_t *m_type = skip_typeref(entry->declaration.type);
3476 if (! is_type_valid(m_type)) {
3477 /* simply ignore errors here */
3480 il_alignment_t m_alignment = m_type->base.alignment;
3481 if (m_alignment > alignment)
3482 alignment = m_alignment;
3484 offset = (size + m_alignment - 1) & -m_alignment;
3488 entry->compound_member.offset = offset;
3489 size = offset + m_type->base.size;
3491 if (type->base.alignment != 0) {
3492 alignment = type->base.alignment;
3495 offset = (size + alignment - 1) & -alignment;
3499 if (warning.padded && need_pad) {
3500 warningf(&compound->base.source_position,
3501 "'%#T' needs padding", type, compound->base.symbol);
3503 if (warning.packed && !need_pad) {
3504 warningf(&compound->base.source_position,
3505 "superfluous packed attribute on '%#T'",
3506 type, compound->base.symbol);
3509 type->base.size = offset;
3510 type->base.alignment = alignment;
3514 * Finish the construction of an union type by calculating
3515 * its size and alignment.
3517 static void finish_union_type(compound_type_t *type)
3519 assert(type->compound != NULL);
3521 compound_t *compound = type->compound;
3522 if (! compound->complete)
3526 il_alignment_t alignment = 1;
3528 entity_t *entry = compound->members.entities;
3529 for (; entry != NULL; entry = entry->base.next) {
3530 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3533 type_t *m_type = skip_typeref(entry->declaration.type);
3534 if (! is_type_valid(m_type))
3537 entry->compound_member.offset = 0;
3538 if (m_type->base.size > size)
3539 size = m_type->base.size;
3540 if (m_type->base.alignment > alignment)
3541 alignment = m_type->base.alignment;
3543 if (type->base.alignment != 0) {
3544 alignment = type->base.alignment;
3546 size = (size + alignment - 1) & -alignment;
3547 type->base.size = size;
3548 type->base.alignment = alignment;
3551 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3553 type_t *type = NULL;
3554 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3555 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3556 unsigned type_specifiers = 0;
3557 bool newtype = false;
3558 bool saw_error = false;
3559 bool old_gcc_extension = in_gcc_extension;
3561 specifiers->source_position = token.source_position;
3564 specifiers->modifiers
3565 |= parse_attributes(&specifiers->gnu_attributes);
3566 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3567 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3569 switch (token.type) {
3572 #define MATCH_STORAGE_CLASS(token, class) \
3574 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3575 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3577 specifiers->storage_class = class; \
3581 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3582 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3583 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3584 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3585 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3590 add_anchor_token(')');
3591 parse_microsoft_extended_decl_modifier(specifiers);
3592 rem_anchor_token(')');
3597 switch (specifiers->storage_class) {
3598 case STORAGE_CLASS_NONE:
3599 specifiers->storage_class = STORAGE_CLASS_THREAD;
3602 case STORAGE_CLASS_EXTERN:
3603 specifiers->storage_class = STORAGE_CLASS_THREAD_EXTERN;
3606 case STORAGE_CLASS_STATIC:
3607 specifiers->storage_class = STORAGE_CLASS_THREAD_STATIC;
3611 errorf(HERE, "multiple storage classes in declaration specifiers");
3617 /* type qualifiers */
3618 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3620 qualifiers |= qualifier; \
3624 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3625 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3626 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3627 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3628 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3629 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3630 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3631 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3633 case T___extension__:
3635 in_gcc_extension = true;
3638 /* type specifiers */
3639 #define MATCH_SPECIFIER(token, specifier, name) \
3641 if (type_specifiers & specifier) { \
3642 errorf(HERE, "multiple " name " type specifiers given"); \
3644 type_specifiers |= specifier; \
3649 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3650 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3651 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3652 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3653 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3654 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3655 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3656 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3657 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3658 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3659 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3660 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3661 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3662 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3663 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3664 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3665 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3667 case T__forceinline:
3668 /* only in microsoft mode */
3669 specifiers->modifiers |= DM_FORCEINLINE;
3674 specifiers->is_inline = true;
3678 if (type_specifiers & SPECIFIER_LONG_LONG) {
3679 errorf(HERE, "multiple type specifiers given");
3680 } else if (type_specifiers & SPECIFIER_LONG) {
3681 type_specifiers |= SPECIFIER_LONG_LONG;
3683 type_specifiers |= SPECIFIER_LONG;
3689 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3691 type->compound.compound = parse_compound_type_specifier(true);
3692 finish_struct_type(&type->compound);
3696 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3697 type->compound.compound = parse_compound_type_specifier(false);
3698 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3699 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3700 finish_union_type(&type->compound);
3704 type = parse_enum_specifier();
3707 type = parse_typeof();
3709 case T___builtin_va_list:
3710 type = duplicate_type(type_valist);
3714 case T_IDENTIFIER: {
3715 /* only parse identifier if we haven't found a type yet */
3716 if (type != NULL || type_specifiers != 0) {
3717 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3718 * declaration, so it doesn't generate errors about expecting '(' or
3720 switch (look_ahead(1)->type) {
3727 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3731 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3736 goto finish_specifiers;
3740 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3741 if (typedef_type == NULL) {
3742 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3743 * declaration, so it doesn't generate 'implicit int' followed by more
3744 * errors later on. */
3745 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3751 errorf(HERE, "%K does not name a type", &token);
3754 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3756 type = allocate_type_zero(TYPE_TYPEDEF);
3757 type->typedeft.typedefe = &entity->typedefe;
3761 if (la1_type == '&' || la1_type == '*')
3762 goto finish_specifiers;
3767 goto finish_specifiers;
3772 type = typedef_type;
3776 /* function specifier */
3778 goto finish_specifiers;
3783 in_gcc_extension = old_gcc_extension;
3785 if (type == NULL || (saw_error && type_specifiers != 0)) {
3786 atomic_type_kind_t atomic_type;
3788 /* match valid basic types */
3789 switch (type_specifiers) {
3790 case SPECIFIER_VOID:
3791 atomic_type = ATOMIC_TYPE_VOID;
3793 case SPECIFIER_CHAR:
3794 atomic_type = ATOMIC_TYPE_CHAR;
3796 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3797 atomic_type = ATOMIC_TYPE_SCHAR;
3799 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3800 atomic_type = ATOMIC_TYPE_UCHAR;
3802 case SPECIFIER_SHORT:
3803 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3804 case SPECIFIER_SHORT | SPECIFIER_INT:
3805 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3806 atomic_type = ATOMIC_TYPE_SHORT;
3808 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3809 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3810 atomic_type = ATOMIC_TYPE_USHORT;
3813 case SPECIFIER_SIGNED:
3814 case SPECIFIER_SIGNED | SPECIFIER_INT:
3815 atomic_type = ATOMIC_TYPE_INT;
3817 case SPECIFIER_UNSIGNED:
3818 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3819 atomic_type = ATOMIC_TYPE_UINT;
3821 case SPECIFIER_LONG:
3822 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3823 case SPECIFIER_LONG | SPECIFIER_INT:
3824 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3825 atomic_type = ATOMIC_TYPE_LONG;
3827 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3828 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3829 atomic_type = ATOMIC_TYPE_ULONG;
3832 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3833 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3834 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3835 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3837 atomic_type = ATOMIC_TYPE_LONGLONG;
3838 goto warn_about_long_long;
3840 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3841 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3843 atomic_type = ATOMIC_TYPE_ULONGLONG;
3844 warn_about_long_long:
3845 if (warning.long_long) {
3846 warningf(&specifiers->source_position,
3847 "ISO C90 does not support 'long long'");
3851 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3852 atomic_type = unsigned_int8_type_kind;
3855 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3856 atomic_type = unsigned_int16_type_kind;
3859 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3860 atomic_type = unsigned_int32_type_kind;
3863 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3864 atomic_type = unsigned_int64_type_kind;
3867 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3868 atomic_type = unsigned_int128_type_kind;
3871 case SPECIFIER_INT8:
3872 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3873 atomic_type = int8_type_kind;
3876 case SPECIFIER_INT16:
3877 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3878 atomic_type = int16_type_kind;
3881 case SPECIFIER_INT32:
3882 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3883 atomic_type = int32_type_kind;
3886 case SPECIFIER_INT64:
3887 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3888 atomic_type = int64_type_kind;
3891 case SPECIFIER_INT128:
3892 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3893 atomic_type = int128_type_kind;
3896 case SPECIFIER_FLOAT:
3897 atomic_type = ATOMIC_TYPE_FLOAT;
3899 case SPECIFIER_DOUBLE:
3900 atomic_type = ATOMIC_TYPE_DOUBLE;
3902 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3903 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3905 case SPECIFIER_BOOL:
3906 atomic_type = ATOMIC_TYPE_BOOL;
3908 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3909 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3910 atomic_type = ATOMIC_TYPE_FLOAT;
3912 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3913 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3914 atomic_type = ATOMIC_TYPE_DOUBLE;
3916 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3917 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3918 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3921 /* invalid specifier combination, give an error message */
3922 if (type_specifiers == 0) {
3926 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3927 if (!(c_mode & _CXX) && !strict_mode) {
3928 if (warning.implicit_int) {
3929 warningf(HERE, "no type specifiers in declaration, using 'int'");
3931 atomic_type = ATOMIC_TYPE_INT;
3934 errorf(HERE, "no type specifiers given in declaration");
3936 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3937 (type_specifiers & SPECIFIER_UNSIGNED)) {
3938 errorf(HERE, "signed and unsigned specifiers given");
3939 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3940 errorf(HERE, "only integer types can be signed or unsigned");
3942 errorf(HERE, "multiple datatypes in declaration");
3947 if (type_specifiers & SPECIFIER_COMPLEX) {
3948 type = allocate_type_zero(TYPE_COMPLEX);
3949 type->complex.akind = atomic_type;
3950 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3951 type = allocate_type_zero(TYPE_IMAGINARY);
3952 type->imaginary.akind = atomic_type;
3954 type = allocate_type_zero(TYPE_ATOMIC);
3955 type->atomic.akind = atomic_type;
3958 } else if (type_specifiers != 0) {
3959 errorf(HERE, "multiple datatypes in declaration");
3962 /* FIXME: check type qualifiers here */
3964 type->base.qualifiers = qualifiers;
3965 type->base.modifiers = modifiers;
3967 type_t *result = typehash_insert(type);
3968 if (newtype && result != type) {
3972 specifiers->type = result;
3976 specifiers->type = type_error_type;
3980 static type_qualifiers_t parse_type_qualifiers(void)
3982 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3985 switch (token.type) {
3986 /* type qualifiers */
3987 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3988 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3989 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3990 /* microsoft extended type modifiers */
3991 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3992 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3993 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3994 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3995 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
4004 * Parses an K&R identifier list
4006 static void parse_identifier_list(scope_t *scope)
4009 entity_t *entity = allocate_entity_zero(ENTITY_VARIABLE);
4010 entity->base.source_position = token.source_position;
4011 entity->base.namespc = NAMESPACE_NORMAL;
4012 entity->base.symbol = token.v.symbol;
4013 /* a K&R parameter has no type, yet */
4016 append_entity(scope, entity);
4018 if (token.type != ',') {
4022 } while (token.type == T_IDENTIFIER);
4025 static type_t *automatic_type_conversion(type_t *orig_type);
4027 static void semantic_parameter(declaration_t *declaration)
4029 /* TODO: improve error messages */
4030 source_position_t const* const pos = &declaration->base.source_position;
4032 /* §6.9.1:6 The declarations in the declaration list shall contain no
4033 * storage-class specifier other than register and no
4034 * initializations. */
4035 switch (declaration->declared_storage_class) {
4036 /* Allowed storage classes */
4037 case STORAGE_CLASS_NONE:
4038 case STORAGE_CLASS_REGISTER:
4042 errorf(pos, "parameter may only have none or register storage class");
4046 type_t *const orig_type = declaration->type;
4047 /* §6.7.5.3:7 A declaration of a parameter as ``array of type'' shall be
4048 * adjusted to ``qualified pointer to type'', [...]
4049 * §6.7.5.3:8 A declaration of a parameter as ``function returning type''
4050 * shall be adjusted to ``pointer to function returning type'',
4053 type_t *const type = automatic_type_conversion(orig_type);
4054 declaration->type = type;
4056 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type list in
4057 * a function declarator that is part of a definition of that
4058 * function shall not have incomplete type. */
4059 if (is_type_incomplete(skip_typeref(type))) {
4060 errorf(pos, "parameter '%#T' has incomplete type",
4061 orig_type, declaration->base.symbol);
4065 static entity_t *parse_parameter(void)
4067 declaration_specifiers_t specifiers;
4068 memset(&specifiers, 0, sizeof(specifiers));
4070 parse_declaration_specifiers(&specifiers);
4072 entity_t *entity = parse_declarator(&specifiers, DECL_MAY_BE_ABSTRACT);
4073 anonymous_entity = NULL;
4078 * Parses function type parameters (and optionally creates variable_t entities
4079 * for them in a scope)
4081 static void parse_parameters(function_type_t *type, scope_t *scope)
4084 add_anchor_token(')');
4085 int saved_comma_state = save_and_reset_anchor_state(',');
4087 if (token.type == T_IDENTIFIER &&
4088 !is_typedef_symbol(token.v.symbol)) {
4089 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4090 if (la1_type == ',' || la1_type == ')') {
4091 type->kr_style_parameters = true;
4092 parse_identifier_list(scope);
4093 goto parameters_finished;
4097 if (token.type == ')') {
4098 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4099 if (!(c_mode & _CXX))
4100 type->unspecified_parameters = true;
4101 goto parameters_finished;
4104 function_parameter_t *parameter;
4105 function_parameter_t *last_parameter = NULL;
4108 switch (token.type) {
4111 type->variadic = true;
4112 goto parameters_finished;
4115 case T___extension__:
4118 entity_t *entity = parse_parameter();
4119 if (entity->kind == ENTITY_TYPEDEF) {
4120 errorf(&entity->base.source_position,
4121 "typedef not allowed as function parameter");
4124 assert(is_declaration(entity));
4126 /* func(void) is not a parameter */
4127 if (last_parameter == NULL
4128 && token.type == ')'
4129 && entity->base.symbol == NULL
4130 && skip_typeref(entity->declaration.type) == type_void) {
4131 goto parameters_finished;
4133 semantic_parameter(&entity->declaration);
4135 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4136 memset(parameter, 0, sizeof(parameter[0]));
4137 parameter->type = entity->declaration.type;
4139 if (scope != NULL) {
4140 append_entity(scope, entity);
4143 if (last_parameter != NULL) {
4144 last_parameter->next = parameter;
4146 type->parameters = parameter;
4148 last_parameter = parameter;
4153 goto parameters_finished;
4155 if (token.type != ',') {
4156 goto parameters_finished;
4162 parameters_finished:
4163 rem_anchor_token(')');
4167 restore_anchor_state(',', saved_comma_state);
4170 typedef enum construct_type_kind_t {
4173 CONSTRUCT_REFERENCE,
4176 } construct_type_kind_t;
4178 typedef struct construct_type_t construct_type_t;
4179 struct construct_type_t {
4180 construct_type_kind_t kind;
4181 construct_type_t *next;
4184 typedef struct parsed_pointer_t parsed_pointer_t;
4185 struct parsed_pointer_t {
4186 construct_type_t construct_type;
4187 type_qualifiers_t type_qualifiers;
4188 variable_t *base_variable; /**< MS __based extension. */
4191 typedef struct parsed_reference_t parsed_reference_t;
4192 struct parsed_reference_t {
4193 construct_type_t construct_type;
4196 typedef struct construct_function_type_t construct_function_type_t;
4197 struct construct_function_type_t {
4198 construct_type_t construct_type;
4199 type_t *function_type;
4202 typedef struct parsed_array_t parsed_array_t;
4203 struct parsed_array_t {
4204 construct_type_t construct_type;
4205 type_qualifiers_t type_qualifiers;
4211 typedef struct construct_base_type_t construct_base_type_t;
4212 struct construct_base_type_t {
4213 construct_type_t construct_type;
4217 static construct_type_t *parse_pointer_declarator(variable_t *base_variable)
4221 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4222 memset(pointer, 0, sizeof(pointer[0]));
4223 pointer->construct_type.kind = CONSTRUCT_POINTER;
4224 pointer->type_qualifiers = parse_type_qualifiers();
4225 pointer->base_variable = base_variable;
4227 return &pointer->construct_type;
4230 static construct_type_t *parse_reference_declarator(void)
4234 parsed_reference_t *reference = obstack_alloc(&temp_obst, sizeof(reference[0]));
4235 memset(reference, 0, sizeof(reference[0]));
4236 reference->construct_type.kind = CONSTRUCT_REFERENCE;
4238 return (construct_type_t*)reference;
4241 static construct_type_t *parse_array_declarator(void)
4244 add_anchor_token(']');
4246 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4247 memset(array, 0, sizeof(array[0]));
4248 array->construct_type.kind = CONSTRUCT_ARRAY;
4250 if (token.type == T_static) {
4251 array->is_static = true;
4255 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4256 if (type_qualifiers != 0) {
4257 if (token.type == T_static) {
4258 array->is_static = true;
4262 array->type_qualifiers = type_qualifiers;
4264 if (token.type == '*' && look_ahead(1)->type == ']') {
4265 array->is_variable = true;
4267 } else if (token.type != ']') {
4268 array->size = parse_assignment_expression();
4271 rem_anchor_token(']');
4275 return &array->construct_type;
4278 static construct_type_t *parse_function_declarator(scope_t *scope,
4279 decl_modifiers_t modifiers)
4281 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4282 function_type_t *ftype = &type->function;
4284 ftype->linkage = current_linkage;
4286 switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
4287 case DM_NONE: break;
4288 case DM_CDECL: ftype->calling_convention = CC_CDECL; break;
4289 case DM_STDCALL: ftype->calling_convention = CC_STDCALL; break;
4290 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
4291 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
4294 errorf(HERE, "multiple calling conventions in declaration");
4298 parse_parameters(ftype, scope);
4300 construct_function_type_t *construct_function_type =
4301 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4302 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4303 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4304 construct_function_type->function_type = type;
4306 return &construct_function_type->construct_type;
4309 typedef struct parse_declarator_env_t {
4310 decl_modifiers_t modifiers;
4312 source_position_t source_position;
4314 } parse_declarator_env_t;
4316 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4317 bool may_be_abstract)
4319 /* construct a single linked list of construct_type_t's which describe
4320 * how to construct the final declarator type */
4321 construct_type_t *first = NULL;
4322 construct_type_t *last = NULL;
4323 gnu_attribute_t *attributes = NULL;
4325 decl_modifiers_t modifiers = parse_attributes(&attributes);
4327 /* MS __based extension */
4328 based_spec_t base_spec;
4329 base_spec.base_variable = NULL;
4332 construct_type_t *type;
4333 switch (token.type) {
4335 if (!(c_mode & _CXX))
4336 errorf(HERE, "references are only available for C++");
4337 if (base_spec.base_variable != NULL && warning.other) {
4338 warningf(&base_spec.source_position,
4339 "__based does not precede a pointer operator, ignored");
4341 type = parse_reference_declarator();
4343 base_spec.base_variable = NULL;
4347 type = parse_pointer_declarator(base_spec.base_variable);
4349 base_spec.base_variable = NULL;
4355 add_anchor_token(')');
4356 parse_microsoft_based(&base_spec);
4357 rem_anchor_token(')');
4362 goto ptr_operator_end;
4373 /* TODO: find out if this is correct */
4374 modifiers |= parse_attributes(&attributes);
4377 if (base_spec.base_variable != NULL && warning.other) {
4378 warningf(&base_spec.source_position,
4379 "__based does not precede a pointer operator, ignored");
4383 modifiers |= env->modifiers;
4384 env->modifiers = modifiers;
4387 construct_type_t *inner_types = NULL;
4389 switch (token.type) {
4392 errorf(HERE, "no identifier expected in typename");
4394 env->symbol = token.v.symbol;
4395 env->source_position = token.source_position;
4401 add_anchor_token(')');
4402 inner_types = parse_inner_declarator(env, may_be_abstract);
4403 if (inner_types != NULL) {
4404 /* All later declarators only modify the return type */
4407 rem_anchor_token(')');
4411 if (may_be_abstract)
4413 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4418 construct_type_t *p = last;
4421 construct_type_t *type;
4422 switch (token.type) {
4424 scope_t *scope = NULL;
4426 scope = &env->parameters;
4428 type = parse_function_declarator(scope, modifiers);
4432 type = parse_array_declarator();
4435 goto declarator_finished;
4438 /* insert in the middle of the list (behind p) */
4440 type->next = p->next;
4451 declarator_finished:
4452 /* append inner_types at the end of the list, we don't to set last anymore
4453 * as it's not needed anymore */
4455 assert(first == NULL);
4456 first = inner_types;
4458 last->next = inner_types;
4466 static void parse_declaration_attributes(entity_t *entity)
4468 gnu_attribute_t *attributes = NULL;
4469 decl_modifiers_t modifiers = parse_attributes(&attributes);
4475 if (entity->kind == ENTITY_TYPEDEF) {
4476 modifiers |= entity->typedefe.modifiers;
4477 type = entity->typedefe.type;
4479 assert(is_declaration(entity));
4480 modifiers |= entity->declaration.modifiers;
4481 type = entity->declaration.type;
4486 /* handle these strange/stupid mode attributes */
4487 gnu_attribute_t *attribute = attributes;
4488 for ( ; attribute != NULL; attribute = attribute->next) {
4489 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4492 atomic_type_kind_t akind = attribute->u.akind;
4493 if (!is_type_signed(type)) {
4495 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4496 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4497 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4498 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4500 panic("invalid akind in mode attribute");
4504 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_SCHAR; break;
4505 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_SHORT; break;
4506 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_INT; break;
4507 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_LONGLONG; break;
4509 panic("invalid akind in mode attribute");
4513 type = make_atomic_type(akind, type->base.qualifiers);
4516 type_modifiers_t type_modifiers = type->base.modifiers;
4517 if (modifiers & DM_TRANSPARENT_UNION)
4518 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4520 if (type->base.modifiers != type_modifiers) {
4521 type_t *copy = duplicate_type(type);
4522 copy->base.modifiers = type_modifiers;
4524 type = typehash_insert(copy);
4526 obstack_free(type_obst, copy);
4530 if (entity->kind == ENTITY_TYPEDEF) {
4531 entity->typedefe.type = type;
4532 entity->typedefe.modifiers = modifiers;
4534 entity->declaration.type = type;
4535 entity->declaration.modifiers = modifiers;
4539 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
4541 construct_type_t *iter = construct_list;
4542 for (; iter != NULL; iter = iter->next) {
4543 switch (iter->kind) {
4544 case CONSTRUCT_INVALID:
4545 internal_errorf(HERE, "invalid type construction found");
4546 case CONSTRUCT_FUNCTION: {
4547 construct_function_type_t *construct_function_type
4548 = (construct_function_type_t*) iter;
4550 type_t *function_type = construct_function_type->function_type;
4552 function_type->function.return_type = type;
4554 type_t *skipped_return_type = skip_typeref(type);
4556 if (is_type_function(skipped_return_type)) {
4557 errorf(HERE, "function returning function is not allowed");
4558 } else if (is_type_array(skipped_return_type)) {
4559 errorf(HERE, "function returning array is not allowed");
4561 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4563 "type qualifiers in return type of function type are meaningless");
4567 type = function_type;
4571 case CONSTRUCT_POINTER: {
4572 if (is_type_reference(skip_typeref(type)))
4573 errorf(HERE, "cannot declare a pointer to reference");
4575 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4576 type = make_based_pointer_type(type, parsed_pointer->type_qualifiers, parsed_pointer->base_variable);
4580 case CONSTRUCT_REFERENCE:
4581 if (is_type_reference(skip_typeref(type)))
4582 errorf(HERE, "cannot declare a reference to reference");
4584 type = make_reference_type(type);
4587 case CONSTRUCT_ARRAY: {
4588 if (is_type_reference(skip_typeref(type)))
4589 errorf(HERE, "cannot declare an array of references");
4591 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4592 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4594 expression_t *size_expression = parsed_array->size;
4595 if (size_expression != NULL) {
4597 = create_implicit_cast(size_expression, type_size_t);
4600 array_type->base.qualifiers = parsed_array->type_qualifiers;
4601 array_type->array.element_type = type;
4602 array_type->array.is_static = parsed_array->is_static;
4603 array_type->array.is_variable = parsed_array->is_variable;
4604 array_type->array.size_expression = size_expression;
4606 if (size_expression != NULL) {
4607 if (is_constant_expression(size_expression)) {
4608 array_type->array.size_constant = true;
4609 array_type->array.size
4610 = fold_constant(size_expression);
4612 array_type->array.is_vla = true;
4616 type_t *skipped_type = skip_typeref(type);
4618 if (is_type_incomplete(skipped_type)) {
4619 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4620 } else if (is_type_function(skipped_type)) {
4621 errorf(HERE, "array of functions is not allowed");
4628 type_t *hashed_type = typehash_insert(type);
4629 if (hashed_type != type) {
4630 /* the function type was constructed earlier freeing it here will
4631 * destroy other types... */
4632 if (iter->kind != CONSTRUCT_FUNCTION) {
4642 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4643 declarator_flags_t flags)
4645 parse_declarator_env_t env;
4646 memset(&env, 0, sizeof(env));
4647 env.modifiers = specifiers->modifiers;
4649 construct_type_t *construct_type
4650 = parse_inner_declarator(&env, (flags & DECL_MAY_BE_ABSTRACT) != 0);
4651 type_t *type = construct_declarator_type(construct_type, specifiers->type);
4653 if (construct_type != NULL) {
4654 obstack_free(&temp_obst, construct_type);
4658 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4659 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4660 entity->base.symbol = env.symbol;
4661 entity->base.source_position = env.source_position;
4662 entity->typedefe.type = type;
4664 if (anonymous_entity != NULL) {
4665 if (is_type_compound(type)) {
4666 assert(anonymous_entity->compound.alias == NULL);
4667 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4668 anonymous_entity->kind == ENTITY_UNION);
4669 anonymous_entity->compound.alias = entity;
4670 anonymous_entity = NULL;
4671 } else if (is_type_enum(type)) {
4672 assert(anonymous_entity->enume.alias == NULL);
4673 assert(anonymous_entity->kind == ENTITY_ENUM);
4674 anonymous_entity->enume.alias = entity;
4675 anonymous_entity = NULL;
4679 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
4680 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4681 } else if (is_type_function(skip_typeref(type))) {
4682 entity = allocate_entity_zero(ENTITY_FUNCTION);
4684 entity->function.is_inline = specifiers->is_inline;
4685 entity->function.parameters = env.parameters;
4687 entity = allocate_entity_zero(ENTITY_VARIABLE);
4689 entity->variable.get_property_sym = specifiers->get_property_sym;
4690 entity->variable.put_property_sym = specifiers->put_property_sym;
4691 if (specifiers->alignment != 0) {
4692 /* TODO: add checks here */
4693 entity->variable.alignment = specifiers->alignment;
4696 if (warning.other && specifiers->is_inline && is_type_valid(type)) {
4697 warningf(&env.source_position,
4698 "variable '%Y' declared 'inline'\n", env.symbol);
4702 entity->base.source_position = env.source_position;
4703 entity->base.symbol = env.symbol;
4704 entity->base.namespc = NAMESPACE_NORMAL;
4705 entity->declaration.type = type;
4706 entity->declaration.modifiers = env.modifiers;
4707 entity->declaration.deprecated_string = specifiers->deprecated_string;
4709 storage_class_t storage_class = specifiers->storage_class;
4710 entity->declaration.declared_storage_class = storage_class;
4712 if (storage_class == STORAGE_CLASS_NONE
4713 && current_scope != file_scope) {
4714 storage_class = STORAGE_CLASS_AUTO;
4716 entity->declaration.storage_class = storage_class;
4719 parse_declaration_attributes(entity);
4724 static type_t *parse_abstract_declarator(type_t *base_type)
4726 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4728 type_t *result = construct_declarator_type(construct_type, base_type);
4729 if (construct_type != NULL) {
4730 obstack_free(&temp_obst, construct_type);
4737 * Check if the declaration of main is suspicious. main should be a
4738 * function with external linkage, returning int, taking either zero
4739 * arguments, two, or three arguments of appropriate types, ie.
4741 * int main([ int argc, char **argv [, char **env ] ]).
4743 * @param decl the declaration to check
4744 * @param type the function type of the declaration
4746 static void check_type_of_main(const entity_t *entity)
4748 const source_position_t *pos = &entity->base.source_position;
4749 if (entity->kind != ENTITY_FUNCTION) {
4750 warningf(pos, "'main' is not a function");
4754 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4755 warningf(pos, "'main' is normally a non-static function");
4758 type_t *type = skip_typeref(entity->declaration.type);
4759 assert(is_type_function(type));
4761 function_type_t *func_type = &type->function;
4762 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4763 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4764 func_type->return_type);
4766 const function_parameter_t *parm = func_type->parameters;
4768 type_t *const first_type = parm->type;
4769 if (!types_compatible(skip_typeref(first_type), type_int)) {
4771 "first argument of 'main' should be 'int', but is '%T'",
4776 type_t *const second_type = parm->type;
4777 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4778 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4782 type_t *const third_type = parm->type;
4783 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4784 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4788 goto warn_arg_count;
4792 warningf(pos, "'main' takes only zero, two or three arguments");
4798 * Check if a symbol is the equal to "main".
4800 static bool is_sym_main(const symbol_t *const sym)
4802 return strcmp(sym->string, "main") == 0;
4805 static const char *get_entity_kind_name(entity_kind_t kind)
4807 switch ((entity_kind_tag_t) kind) {
4808 case ENTITY_FUNCTION: return "function";
4809 case ENTITY_VARIABLE: return "variable";
4810 case ENTITY_COMPOUND_MEMBER: return "compound type member";
4811 case ENTITY_STRUCT: return "struct";
4812 case ENTITY_UNION: return "union";
4813 case ENTITY_ENUM: return "enum";
4814 case ENTITY_ENUM_VALUE: return "enum value";
4815 case ENTITY_LABEL: return "label";
4816 case ENTITY_LOCAL_LABEL: return "local label";
4817 case ENTITY_TYPEDEF: return "typedef";
4818 case ENTITY_NAMESPACE: return "namespace";
4819 case ENTITY_INVALID: break;
4822 panic("Invalid entity kind encountered in get_entity_kind_name");
4825 static void error_redefined_as_different_kind(const source_position_t *pos,
4826 const entity_t *old, entity_kind_t new_kind)
4828 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4829 get_entity_kind_name(old->kind), old->base.symbol,
4830 get_entity_kind_name(new_kind), &old->base.source_position);
4834 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4835 * for various problems that occur for multiple definitions
4837 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4839 const symbol_t *const symbol = entity->base.symbol;
4840 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4841 const source_position_t *pos = &entity->base.source_position;
4843 assert(symbol != NULL);
4844 entity_t *previous_entity = get_entity(symbol, namespc);
4845 /* pushing the same entity twice will break the stack structure */
4846 assert(previous_entity != entity);
4848 if (entity->kind == ENTITY_FUNCTION) {
4849 type_t *const orig_type = entity->declaration.type;
4850 type_t *const type = skip_typeref(orig_type);
4852 assert(is_type_function(type));
4853 if (type->function.unspecified_parameters &&
4854 warning.strict_prototypes &&
4855 previous_entity == NULL) {
4856 warningf(pos, "function declaration '%#T' is not a prototype",
4860 if (warning.main && current_scope == file_scope
4861 && is_sym_main(symbol)) {
4862 check_type_of_main(entity);
4866 if (is_declaration(entity)) {
4867 if (warning.nested_externs
4868 && entity->declaration.storage_class == STORAGE_CLASS_EXTERN
4869 && current_scope != file_scope) {
4870 warningf(pos, "nested extern declaration of '%#T'",
4871 entity->declaration.type, symbol);
4875 if (previous_entity != NULL
4876 && previous_entity->base.parent_scope == ¤t_function->parameters
4877 && current_scope->depth == previous_entity->base.parent_scope->depth+1){
4879 assert(previous_entity->kind == ENTITY_VARIABLE);
4881 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4882 entity->declaration.type, symbol,
4883 previous_entity->declaration.type, symbol,
4884 &previous_entity->base.source_position);
4888 if (previous_entity != NULL
4889 && previous_entity->base.parent_scope == current_scope) {
4891 if (previous_entity->kind != entity->kind) {
4892 error_redefined_as_different_kind(pos, previous_entity,
4896 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4898 "redeclaration of enum entry '%Y' (declared %P)",
4899 symbol, &previous_entity->base.source_position);
4902 if (previous_entity->kind == ENTITY_TYPEDEF) {
4903 /* TODO: C++ allows this for exactly the same type */
4905 "redefinition of typedef '%Y' (declared %P)",
4906 symbol, &previous_entity->base.source_position);
4910 /* at this point we should have only VARIABLES or FUNCTIONS */
4911 assert(is_declaration(previous_entity) && is_declaration(entity));
4913 /* can happen for K&R style declarations */
4914 if (previous_entity->kind == ENTITY_VARIABLE
4915 && previous_entity->declaration.type == NULL
4916 && entity->kind == ENTITY_VARIABLE) {
4917 previous_entity->declaration.type = entity->declaration.type;
4918 previous_entity->declaration.storage_class
4919 = entity->declaration.storage_class;
4920 previous_entity->declaration.declared_storage_class
4921 = entity->declaration.declared_storage_class;
4922 previous_entity->declaration.modifiers
4923 = entity->declaration.modifiers;
4924 previous_entity->declaration.deprecated_string
4925 = entity->declaration.deprecated_string;
4927 assert(entity->declaration.type != NULL);
4929 declaration_t *const previous_declaration
4930 = &previous_entity->declaration;
4931 declaration_t *const declaration = &entity->declaration;
4932 type_t *const orig_type = entity->declaration.type;
4933 type_t *const type = skip_typeref(orig_type);
4935 type_t *prev_type = skip_typeref(previous_declaration->type);
4937 if (!types_compatible(type, prev_type)) {
4939 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4940 orig_type, symbol, previous_declaration->type, symbol,
4941 &previous_entity->base.source_position);
4943 unsigned old_storage_class = previous_declaration->storage_class;
4944 if (warning.redundant_decls && is_definition
4945 && previous_declaration->storage_class == STORAGE_CLASS_STATIC
4946 && !(previous_declaration->modifiers & DM_USED)
4947 && !previous_declaration->used) {
4948 warningf(&previous_entity->base.source_position,
4949 "unnecessary static forward declaration for '%#T'",
4950 previous_declaration->type, symbol);
4953 unsigned new_storage_class = declaration->storage_class;
4954 if (is_type_incomplete(prev_type)) {
4955 previous_declaration->type = type;
4959 /* pretend no storage class means extern for function
4960 * declarations (except if the previous declaration is neither
4961 * none nor extern) */
4962 if (entity->kind == ENTITY_FUNCTION) {
4963 if (prev_type->function.unspecified_parameters) {
4964 previous_declaration->type = type;
4968 switch (old_storage_class) {
4969 case STORAGE_CLASS_NONE:
4970 old_storage_class = STORAGE_CLASS_EXTERN;
4973 case STORAGE_CLASS_EXTERN:
4974 if (is_definition) {
4975 if (warning.missing_prototypes &&
4976 prev_type->function.unspecified_parameters &&
4977 !is_sym_main(symbol)) {
4978 warningf(pos, "no previous prototype for '%#T'",
4981 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4982 new_storage_class = STORAGE_CLASS_EXTERN;
4991 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4992 new_storage_class == STORAGE_CLASS_EXTERN) {
4993 warn_redundant_declaration:
4994 if (!is_definition &&
4995 warning.redundant_decls &&
4996 is_type_valid(prev_type) &&
4997 strcmp(previous_entity->base.source_position.input_name, "<builtin>") != 0) {
4999 "redundant declaration for '%Y' (declared %P)",
5000 symbol, &previous_entity->base.source_position);
5002 } else if (current_function == NULL) {
5003 if (old_storage_class != STORAGE_CLASS_STATIC &&
5004 new_storage_class == STORAGE_CLASS_STATIC) {
5006 "static declaration of '%Y' follows non-static declaration (declared %P)",
5007 symbol, &previous_entity->base.source_position);
5008 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
5009 previous_declaration->storage_class = STORAGE_CLASS_NONE;
5010 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
5012 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
5014 goto error_redeclaration;
5015 goto warn_redundant_declaration;
5017 } else if (is_type_valid(prev_type)) {
5018 if (old_storage_class == new_storage_class) {
5019 error_redeclaration:
5020 errorf(pos, "redeclaration of '%Y' (declared %P)",
5021 symbol, &previous_entity->base.source_position);
5024 "redeclaration of '%Y' with different linkage (declared %P)",
5025 symbol, &previous_entity->base.source_position);
5030 previous_declaration->modifiers |= declaration->modifiers;
5031 if (entity->kind == ENTITY_FUNCTION) {
5032 previous_entity->function.is_inline |= entity->function.is_inline;
5034 return previous_entity;
5037 if (entity->kind == ENTITY_FUNCTION) {
5038 if (is_definition &&
5039 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
5040 if (warning.missing_prototypes && !is_sym_main(symbol)) {
5041 warningf(pos, "no previous prototype for '%#T'",
5042 entity->declaration.type, symbol);
5043 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
5044 warningf(pos, "no previous declaration for '%#T'",
5045 entity->declaration.type, symbol);
5048 } else if (warning.missing_declarations
5049 && entity->kind == ENTITY_VARIABLE
5050 && current_scope == file_scope) {
5051 declaration_t *declaration = &entity->declaration;
5052 if (declaration->storage_class == STORAGE_CLASS_NONE ||
5053 declaration->storage_class == STORAGE_CLASS_THREAD) {
5054 warningf(pos, "no previous declaration for '%#T'",
5055 declaration->type, symbol);
5060 assert(entity->base.parent_scope == NULL);
5061 assert(current_scope != NULL);
5063 entity->base.parent_scope = current_scope;
5064 entity->base.namespc = NAMESPACE_NORMAL;
5065 environment_push(entity);
5066 append_entity(current_scope, entity);
5071 static void parser_error_multiple_definition(entity_t *entity,
5072 const source_position_t *source_position)
5074 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
5075 entity->base.symbol, &entity->base.source_position);
5078 static bool is_declaration_specifier(const token_t *token,
5079 bool only_specifiers_qualifiers)
5081 switch (token->type) {
5086 return is_typedef_symbol(token->v.symbol);
5088 case T___extension__:
5090 return !only_specifiers_qualifiers;
5097 static void parse_init_declarator_rest(entity_t *entity)
5099 assert(is_declaration(entity));
5100 declaration_t *const declaration = &entity->declaration;
5104 type_t *orig_type = declaration->type;
5105 type_t *type = skip_typeref(orig_type);
5107 if (entity->kind == ENTITY_VARIABLE
5108 && entity->variable.initializer != NULL) {
5109 parser_error_multiple_definition(entity, HERE);
5112 bool must_be_constant = false;
5113 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5114 declaration->storage_class == STORAGE_CLASS_THREAD_STATIC ||
5115 entity->base.parent_scope == file_scope) {
5116 must_be_constant = true;
5119 if (is_type_function(type)) {
5120 errorf(&entity->base.source_position,
5121 "function '%#T' is initialized like a variable",
5122 orig_type, entity->base.symbol);
5123 orig_type = type_error_type;
5126 parse_initializer_env_t env;
5127 env.type = orig_type;
5128 env.must_be_constant = must_be_constant;
5129 env.entity = entity;
5130 current_init_decl = entity;
5132 initializer_t *initializer = parse_initializer(&env);
5133 current_init_decl = NULL;
5135 if (entity->kind == ENTITY_VARIABLE) {
5136 /* § 6.7.5 (22) array initializers for arrays with unknown size
5137 * determine the array type size */
5138 declaration->type = env.type;
5139 entity->variable.initializer = initializer;
5143 /* parse rest of a declaration without any declarator */
5144 static void parse_anonymous_declaration_rest(
5145 const declaration_specifiers_t *specifiers)
5148 anonymous_entity = NULL;
5150 if (warning.other) {
5151 if (specifiers->storage_class != STORAGE_CLASS_NONE) {
5152 warningf(&specifiers->source_position,
5153 "useless storage class in empty declaration");
5156 type_t *type = specifiers->type;
5157 switch (type->kind) {
5158 case TYPE_COMPOUND_STRUCT:
5159 case TYPE_COMPOUND_UNION: {
5160 if (type->compound.compound->base.symbol == NULL) {
5161 warningf(&specifiers->source_position,
5162 "unnamed struct/union that defines no instances");
5171 warningf(&specifiers->source_position, "empty declaration");
5177 static void check_variable_type_complete(entity_t *ent)
5179 if (ent->kind != ENTITY_VARIABLE)
5182 /* §6.7:7 If an identifier for an object is declared with no linkage, the
5183 * type for the object shall be complete [...] */
5184 declaration_t *decl = &ent->declaration;
5185 if (decl->storage_class != STORAGE_CLASS_NONE)
5188 type_t *type = decl->type;
5189 if (!is_type_incomplete(skip_typeref(type)))
5192 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
5193 type, ent->base.symbol);
5197 static void parse_declaration_rest(entity_t *ndeclaration,
5198 const declaration_specifiers_t *specifiers,
5199 parsed_declaration_func finished_declaration)
5201 add_anchor_token(';');
5202 add_anchor_token(',');
5204 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5206 if (token.type == '=') {
5207 parse_init_declarator_rest(entity);
5208 } else if (entity->kind == ENTITY_VARIABLE) {
5209 type_t *type = entity->declaration.type;
5210 if (is_type_reference(skip_typeref(type))) {
5211 errorf(&entity->base.source_position,
5212 "reference '%#T' must be initialized",
5213 type, entity->base.symbol);
5217 check_variable_type_complete(entity);
5219 if (token.type != ',')
5223 add_anchor_token('=');
5224 ndeclaration = parse_declarator(specifiers, DECL_FLAGS_NONE);
5225 rem_anchor_token('=');
5230 anonymous_entity = NULL;
5231 rem_anchor_token(';');
5232 rem_anchor_token(',');
5235 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5237 symbol_t *symbol = entity->base.symbol;
5238 if (symbol == NULL) {
5239 errorf(HERE, "anonymous declaration not valid as function parameter");
5243 assert(entity->base.namespc == NAMESPACE_NORMAL);
5244 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5245 if (previous_entity == NULL
5246 || previous_entity->base.parent_scope != current_scope) {
5247 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5252 if (is_definition) {
5253 errorf(HERE, "parameter %Y is initialised", entity->base.symbol);
5256 return record_entity(entity, false);
5259 static void parse_declaration(parsed_declaration_func finished_declaration)
5261 declaration_specifiers_t specifiers;
5262 memset(&specifiers, 0, sizeof(specifiers));
5264 add_anchor_token(';');
5265 parse_declaration_specifiers(&specifiers);
5266 rem_anchor_token(';');
5268 if (token.type == ';') {
5269 parse_anonymous_declaration_rest(&specifiers);
5271 entity_t *entity = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5272 parse_declaration_rest(entity, &specifiers, finished_declaration);
5276 static type_t *get_default_promoted_type(type_t *orig_type)
5278 type_t *result = orig_type;
5280 type_t *type = skip_typeref(orig_type);
5281 if (is_type_integer(type)) {
5282 result = promote_integer(type);
5283 } else if (type == type_float) {
5284 result = type_double;
5290 static void parse_kr_declaration_list(entity_t *entity)
5292 if (entity->kind != ENTITY_FUNCTION)
5295 type_t *type = skip_typeref(entity->declaration.type);
5296 assert(is_type_function(type));
5297 if (!type->function.kr_style_parameters)
5301 add_anchor_token('{');
5303 /* push function parameters */
5304 size_t const top = environment_top();
5305 scope_push(&entity->function.parameters);
5307 entity_t *parameter = entity->function.parameters.entities;
5308 for ( ; parameter != NULL; parameter = parameter->base.next) {
5309 assert(parameter->base.parent_scope == NULL);
5310 parameter->base.parent_scope = current_scope;
5311 environment_push(parameter);
5314 /* parse declaration list */
5315 while (is_declaration_specifier(&token, false)) {
5316 parse_declaration(finished_kr_declaration);
5319 /* pop function parameters */
5320 assert(current_scope == &entity->function.parameters);
5322 environment_pop_to(top);
5324 /* update function type */
5325 type_t *new_type = duplicate_type(type);
5327 function_parameter_t *parameters = NULL;
5328 function_parameter_t *last_parameter = NULL;
5330 entity_t *parameter_declaration = entity->function.parameters.entities;
5331 for (; parameter_declaration != NULL;
5332 parameter_declaration = parameter_declaration->base.next) {
5333 type_t *parameter_type = parameter_declaration->declaration.type;
5334 if (parameter_type == NULL) {
5336 errorf(HERE, "no type specified for function parameter '%Y'",
5337 parameter_declaration->base.symbol);
5339 if (warning.implicit_int) {
5340 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5341 parameter_declaration->base.symbol);
5343 parameter_type = type_int;
5344 parameter_declaration->declaration.type = parameter_type;
5348 semantic_parameter(¶meter_declaration->declaration);
5349 parameter_type = parameter_declaration->declaration.type;
5352 * we need the default promoted types for the function type
5354 parameter_type = get_default_promoted_type(parameter_type);
5356 function_parameter_t *function_parameter
5357 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5358 memset(function_parameter, 0, sizeof(function_parameter[0]));
5360 function_parameter->type = parameter_type;
5361 if (last_parameter != NULL) {
5362 last_parameter->next = function_parameter;
5364 parameters = function_parameter;
5366 last_parameter = function_parameter;
5369 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5371 new_type->function.parameters = parameters;
5372 new_type->function.unspecified_parameters = true;
5374 type = typehash_insert(new_type);
5375 if (type != new_type) {
5376 obstack_free(type_obst, new_type);
5379 entity->declaration.type = type;
5381 rem_anchor_token('{');
5384 static bool first_err = true;
5387 * When called with first_err set, prints the name of the current function,
5390 static void print_in_function(void)
5394 diagnosticf("%s: In function '%Y':\n",
5395 current_function->base.base.source_position.input_name,
5396 current_function->base.base.symbol);
5401 * Check if all labels are defined in the current function.
5402 * Check if all labels are used in the current function.
5404 static void check_labels(void)
5406 for (const goto_statement_t *goto_statement = goto_first;
5407 goto_statement != NULL;
5408 goto_statement = goto_statement->next) {
5409 /* skip computed gotos */
5410 if (goto_statement->expression != NULL)
5413 label_t *label = goto_statement->label;
5416 if (label->base.source_position.input_name == NULL) {
5417 print_in_function();
5418 errorf(&goto_statement->base.source_position,
5419 "label '%Y' used but not defined", label->base.symbol);
5423 if (warning.unused_label) {
5424 for (const label_statement_t *label_statement = label_first;
5425 label_statement != NULL;
5426 label_statement = label_statement->next) {
5427 label_t *label = label_statement->label;
5429 if (! label->used) {
5430 print_in_function();
5431 warningf(&label_statement->base.source_position,
5432 "label '%Y' defined but not used", label->base.symbol);
5438 static void warn_unused_decl(entity_t *entity, entity_t *end,
5439 char const *const what)
5441 for (; entity != NULL; entity = entity->base.next) {
5442 if (!is_declaration(entity))
5445 declaration_t *declaration = &entity->declaration;
5446 if (declaration->implicit)
5449 if (!declaration->used) {
5450 print_in_function();
5451 warningf(&entity->base.source_position, "%s '%Y' is unused",
5452 what, entity->base.symbol);
5453 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5454 print_in_function();
5455 warningf(&entity->base.source_position, "%s '%Y' is never read",
5456 what, entity->base.symbol);
5464 static void check_unused_variables(statement_t *const stmt, void *const env)
5468 switch (stmt->kind) {
5469 case STATEMENT_DECLARATION: {
5470 declaration_statement_t const *const decls = &stmt->declaration;
5471 warn_unused_decl(decls->declarations_begin, decls->declarations_end,
5477 warn_unused_decl(stmt->fors.scope.entities, NULL, "variable");
5486 * Check declarations of current_function for unused entities.
5488 static void check_declarations(void)
5490 if (warning.unused_parameter) {
5491 const scope_t *scope = ¤t_function->parameters;
5493 /* do not issue unused warnings for main */
5494 if (!is_sym_main(current_function->base.base.symbol)) {
5495 warn_unused_decl(scope->entities, NULL, "parameter");
5498 if (warning.unused_variable) {
5499 walk_statements(current_function->statement, check_unused_variables,
5504 static int determine_truth(expression_t const* const cond)
5507 !is_constant_expression(cond) ? 0 :
5508 fold_constant(cond) != 0 ? 1 :
5512 static bool expression_returns(expression_t const *const expr)
5514 switch (expr->kind) {
5516 expression_t const *const func = expr->call.function;
5517 if (func->kind == EXPR_REFERENCE) {
5518 entity_t *entity = func->reference.entity;
5519 if (entity->kind == ENTITY_FUNCTION
5520 && entity->declaration.modifiers & DM_NORETURN)
5524 if (!expression_returns(func))
5527 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5528 if (!expression_returns(arg->expression))
5535 case EXPR_REFERENCE:
5536 case EXPR_REFERENCE_ENUM_VALUE:
5538 case EXPR_CHARACTER_CONSTANT:
5539 case EXPR_WIDE_CHARACTER_CONSTANT:
5540 case EXPR_STRING_LITERAL:
5541 case EXPR_WIDE_STRING_LITERAL:
5542 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5543 case EXPR_LABEL_ADDRESS:
5544 case EXPR_CLASSIFY_TYPE:
5545 case EXPR_SIZEOF: // TODO handle obscure VLA case
5548 case EXPR_BUILTIN_SYMBOL:
5549 case EXPR_BUILTIN_CONSTANT_P:
5550 case EXPR_BUILTIN_PREFETCH:
5553 case EXPR_STATEMENT: // TODO implement
5556 case EXPR_CONDITIONAL:
5557 // TODO handle constant expression
5559 expression_returns(expr->conditional.condition) && (
5560 expression_returns(expr->conditional.true_expression) ||
5561 expression_returns(expr->conditional.false_expression)
5565 return expression_returns(expr->select.compound);
5567 case EXPR_ARRAY_ACCESS:
5569 expression_returns(expr->array_access.array_ref) &&
5570 expression_returns(expr->array_access.index);
5573 return expression_returns(expr->va_starte.ap);
5576 return expression_returns(expr->va_arge.ap);
5578 EXPR_UNARY_CASES_MANDATORY
5579 return expression_returns(expr->unary.value);
5581 case EXPR_UNARY_THROW:
5585 // TODO handle constant lhs of && and ||
5587 expression_returns(expr->binary.left) &&
5588 expression_returns(expr->binary.right);
5594 panic("unhandled expression");
5597 static bool noreturn_candidate;
5599 static void check_reachable(statement_t *const stmt)
5601 if (stmt->base.reachable)
5603 if (stmt->kind != STATEMENT_DO_WHILE)
5604 stmt->base.reachable = true;
5606 statement_t *last = stmt;
5608 switch (stmt->kind) {
5609 case STATEMENT_INVALID:
5610 case STATEMENT_EMPTY:
5611 case STATEMENT_DECLARATION:
5612 case STATEMENT_LOCAL_LABEL:
5614 next = stmt->base.next;
5617 case STATEMENT_COMPOUND:
5618 next = stmt->compound.statements;
5621 case STATEMENT_RETURN:
5622 noreturn_candidate = false;
5625 case STATEMENT_IF: {
5626 if_statement_t const* const ifs = &stmt->ifs;
5627 int const val = determine_truth(ifs->condition);
5630 check_reachable(ifs->true_statement);
5635 if (ifs->false_statement != NULL) {
5636 check_reachable(ifs->false_statement);
5640 next = stmt->base.next;
5644 case STATEMENT_SWITCH: {
5645 switch_statement_t const *const switchs = &stmt->switchs;
5646 expression_t const *const expr = switchs->expression;
5648 if (is_constant_expression(expr)) {
5649 long const val = fold_constant(expr);
5650 case_label_statement_t * defaults = NULL;
5651 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5652 if (i->expression == NULL) {
5657 if (i->first_case <= val && val <= i->last_case) {
5658 check_reachable((statement_t*)i);
5663 if (defaults != NULL) {
5664 check_reachable((statement_t*)defaults);
5668 bool has_default = false;
5669 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5670 if (i->expression == NULL)
5673 check_reachable((statement_t*)i);
5680 next = stmt->base.next;
5684 case STATEMENT_EXPRESSION: {
5685 /* Check for noreturn function call */
5686 expression_t const *const expr = stmt->expression.expression;
5687 if (!expression_returns(expr))
5690 next = stmt->base.next;
5694 case STATEMENT_CONTINUE: {
5695 statement_t *parent = stmt;
5697 parent = parent->base.parent;
5698 if (parent == NULL) /* continue not within loop */
5702 switch (parent->kind) {
5703 case STATEMENT_WHILE: goto continue_while;
5704 case STATEMENT_DO_WHILE: goto continue_do_while;
5705 case STATEMENT_FOR: goto continue_for;
5712 case STATEMENT_BREAK: {
5713 statement_t *parent = stmt;
5715 parent = parent->base.parent;
5716 if (parent == NULL) /* break not within loop/switch */
5719 switch (parent->kind) {
5720 case STATEMENT_SWITCH:
5721 case STATEMENT_WHILE:
5722 case STATEMENT_DO_WHILE:
5725 next = parent->base.next;
5726 goto found_break_parent;
5735 case STATEMENT_GOTO:
5736 if (stmt->gotos.expression) {
5737 statement_t *parent = stmt->base.parent;
5738 if (parent == NULL) /* top level goto */
5742 next = stmt->gotos.label->statement;
5743 if (next == NULL) /* missing label */
5748 case STATEMENT_LABEL:
5749 next = stmt->label.statement;
5752 case STATEMENT_CASE_LABEL:
5753 next = stmt->case_label.statement;
5756 case STATEMENT_WHILE: {
5757 while_statement_t const *const whiles = &stmt->whiles;
5758 int const val = determine_truth(whiles->condition);
5761 check_reachable(whiles->body);
5766 next = stmt->base.next;
5770 case STATEMENT_DO_WHILE:
5771 next = stmt->do_while.body;
5774 case STATEMENT_FOR: {
5775 for_statement_t *const fors = &stmt->fors;
5777 if (fors->condition_reachable)
5779 fors->condition_reachable = true;
5781 expression_t const *const cond = fors->condition;
5783 cond == NULL ? 1 : determine_truth(cond);
5786 check_reachable(fors->body);
5791 next = stmt->base.next;
5795 case STATEMENT_MS_TRY: {
5796 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5797 check_reachable(ms_try->try_statement);
5798 next = ms_try->final_statement;
5802 case STATEMENT_LEAVE: {
5803 statement_t *parent = stmt;
5805 parent = parent->base.parent;
5806 if (parent == NULL) /* __leave not within __try */
5809 if (parent->kind == STATEMENT_MS_TRY) {
5811 next = parent->ms_try.final_statement;
5819 while (next == NULL) {
5820 next = last->base.parent;
5822 noreturn_candidate = false;
5824 type_t *const type = current_function->base.type;
5825 assert(is_type_function(type));
5826 type_t *const ret = skip_typeref(type->function.return_type);
5827 if (warning.return_type &&
5828 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5829 is_type_valid(ret) &&
5830 !is_sym_main(current_function->base.base.symbol)) {
5831 warningf(&stmt->base.source_position,
5832 "control reaches end of non-void function");
5837 switch (next->kind) {
5838 case STATEMENT_INVALID:
5839 case STATEMENT_EMPTY:
5840 case STATEMENT_DECLARATION:
5841 case STATEMENT_LOCAL_LABEL:
5842 case STATEMENT_EXPRESSION:
5844 case STATEMENT_RETURN:
5845 case STATEMENT_CONTINUE:
5846 case STATEMENT_BREAK:
5847 case STATEMENT_GOTO:
5848 case STATEMENT_LEAVE:
5849 panic("invalid control flow in function");
5851 case STATEMENT_COMPOUND:
5853 case STATEMENT_SWITCH:
5854 case STATEMENT_LABEL:
5855 case STATEMENT_CASE_LABEL:
5857 next = next->base.next;
5860 case STATEMENT_WHILE: {
5862 if (next->base.reachable)
5864 next->base.reachable = true;
5866 while_statement_t const *const whiles = &next->whiles;
5867 int const val = determine_truth(whiles->condition);
5870 check_reachable(whiles->body);
5876 next = next->base.next;
5880 case STATEMENT_DO_WHILE: {
5882 if (next->base.reachable)
5884 next->base.reachable = true;
5886 do_while_statement_t const *const dw = &next->do_while;
5887 int const val = determine_truth(dw->condition);
5890 check_reachable(dw->body);
5896 next = next->base.next;
5900 case STATEMENT_FOR: {
5902 for_statement_t *const fors = &next->fors;
5904 fors->step_reachable = true;
5906 if (fors->condition_reachable)
5908 fors->condition_reachable = true;
5910 expression_t const *const cond = fors->condition;
5912 cond == NULL ? 1 : determine_truth(cond);
5915 check_reachable(fors->body);
5921 next = next->base.next;
5925 case STATEMENT_MS_TRY:
5927 next = next->ms_try.final_statement;
5932 check_reachable(next);
5935 static void check_unreachable(statement_t* const stmt, void *const env)
5939 switch (stmt->kind) {
5940 case STATEMENT_DO_WHILE:
5941 if (!stmt->base.reachable) {
5942 expression_t const *const cond = stmt->do_while.condition;
5943 if (determine_truth(cond) >= 0) {
5944 warningf(&cond->base.source_position,
5945 "condition of do-while-loop is unreachable");
5950 case STATEMENT_FOR: {
5951 for_statement_t const* const fors = &stmt->fors;
5953 // if init and step are unreachable, cond is unreachable, too
5954 if (!stmt->base.reachable && !fors->step_reachable) {
5955 warningf(&stmt->base.source_position, "statement is unreachable");
5957 if (!stmt->base.reachable && fors->initialisation != NULL) {
5958 warningf(&fors->initialisation->base.source_position,
5959 "initialisation of for-statement is unreachable");
5962 if (!fors->condition_reachable && fors->condition != NULL) {
5963 warningf(&fors->condition->base.source_position,
5964 "condition of for-statement is unreachable");
5967 if (!fors->step_reachable && fors->step != NULL) {
5968 warningf(&fors->step->base.source_position,
5969 "step of for-statement is unreachable");
5975 case STATEMENT_COMPOUND:
5976 if (stmt->compound.statements != NULL)
5981 if (!stmt->base.reachable)
5982 warningf(&stmt->base.source_position, "statement is unreachable");
5987 static void parse_external_declaration(void)
5989 /* function-definitions and declarations both start with declaration
5991 declaration_specifiers_t specifiers;
5992 memset(&specifiers, 0, sizeof(specifiers));
5994 add_anchor_token(';');
5995 parse_declaration_specifiers(&specifiers);
5996 rem_anchor_token(';');
5998 /* must be a declaration */
5999 if (token.type == ';') {
6000 parse_anonymous_declaration_rest(&specifiers);
6004 add_anchor_token(',');
6005 add_anchor_token('=');
6006 add_anchor_token(';');
6007 add_anchor_token('{');
6009 /* declarator is common to both function-definitions and declarations */
6010 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
6012 rem_anchor_token('{');
6013 rem_anchor_token(';');
6014 rem_anchor_token('=');
6015 rem_anchor_token(',');
6017 /* must be a declaration */
6018 switch (token.type) {
6022 parse_declaration_rest(ndeclaration, &specifiers, record_entity);
6026 /* must be a function definition */
6027 parse_kr_declaration_list(ndeclaration);
6029 if (token.type != '{') {
6030 parse_error_expected("while parsing function definition", '{', NULL);
6031 eat_until_matching_token(';');
6035 assert(is_declaration(ndeclaration));
6036 type_t *type = skip_typeref(ndeclaration->declaration.type);
6038 if (!is_type_function(type)) {
6039 if (is_type_valid(type)) {
6040 errorf(HERE, "declarator '%#T' has a body but is not a function type",
6041 type, ndeclaration->base.symbol);
6047 if (warning.aggregate_return &&
6048 is_type_compound(skip_typeref(type->function.return_type))) {
6049 warningf(HERE, "function '%Y' returns an aggregate",
6050 ndeclaration->base.symbol);
6052 if (warning.traditional && !type->function.unspecified_parameters) {
6053 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6054 ndeclaration->base.symbol);
6056 if (warning.old_style_definition && type->function.unspecified_parameters) {
6057 warningf(HERE, "old-style function definition '%Y'",
6058 ndeclaration->base.symbol);
6061 /* § 6.7.5.3 (14) a function definition with () means no
6062 * parameters (and not unspecified parameters) */
6063 if (type->function.unspecified_parameters
6064 && type->function.parameters == NULL
6065 && !type->function.kr_style_parameters) {
6066 type_t *duplicate = duplicate_type(type);
6067 duplicate->function.unspecified_parameters = false;
6069 type = typehash_insert(duplicate);
6070 if (type != duplicate) {
6071 obstack_free(type_obst, duplicate);
6073 ndeclaration->declaration.type = type;
6076 entity_t *const entity = record_entity(ndeclaration, true);
6077 assert(entity->kind == ENTITY_FUNCTION);
6078 assert(ndeclaration->kind == ENTITY_FUNCTION);
6080 function_t *function = &entity->function;
6081 if (ndeclaration != entity) {
6082 function->parameters = ndeclaration->function.parameters;
6084 assert(is_declaration(entity));
6085 type = skip_typeref(entity->declaration.type);
6087 /* push function parameters and switch scope */
6088 size_t const top = environment_top();
6089 scope_push(&function->parameters);
6091 entity_t *parameter = function->parameters.entities;
6092 for (; parameter != NULL; parameter = parameter->base.next) {
6093 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6094 parameter->base.parent_scope = current_scope;
6096 assert(parameter->base.parent_scope == NULL
6097 || parameter->base.parent_scope == current_scope);
6098 parameter->base.parent_scope = current_scope;
6099 if (parameter->base.symbol == NULL) {
6100 errorf(¶meter->base.source_position, "parameter name omitted");
6103 environment_push(parameter);
6106 if (function->statement != NULL) {
6107 parser_error_multiple_definition(entity, HERE);
6110 /* parse function body */
6111 int label_stack_top = label_top();
6112 function_t *old_current_function = current_function;
6113 current_function = function;
6114 current_parent = NULL;
6117 goto_anchor = &goto_first;
6119 label_anchor = &label_first;
6121 statement_t *const body = parse_compound_statement(false);
6122 function->statement = body;
6125 check_declarations();
6126 if (warning.return_type ||
6127 warning.unreachable_code ||
6128 (warning.missing_noreturn
6129 && !(function->base.modifiers & DM_NORETURN))) {
6130 noreturn_candidate = true;
6131 check_reachable(body);
6132 if (warning.unreachable_code)
6133 walk_statements(body, check_unreachable, NULL);
6134 if (warning.missing_noreturn &&
6135 noreturn_candidate &&
6136 !(function->base.modifiers & DM_NORETURN)) {
6137 warningf(&body->base.source_position,
6138 "function '%#T' is candidate for attribute 'noreturn'",
6139 type, entity->base.symbol);
6143 assert(current_parent == NULL);
6144 assert(current_function == function);
6145 current_function = old_current_function;
6146 label_pop_to(label_stack_top);
6149 assert(current_scope == &function->parameters);
6151 environment_pop_to(top);
6154 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6155 source_position_t *source_position,
6156 const symbol_t *symbol)
6158 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6160 type->bitfield.base_type = base_type;
6161 type->bitfield.size_expression = size;
6164 type_t *skipped_type = skip_typeref(base_type);
6165 if (!is_type_integer(skipped_type)) {
6166 errorf(HERE, "bitfield base type '%T' is not an integer type",
6170 bit_size = skipped_type->base.size * 8;
6173 if (is_constant_expression(size)) {
6174 long v = fold_constant(size);
6177 errorf(source_position, "negative width in bit-field '%Y'", symbol);
6178 } else if (v == 0) {
6179 errorf(source_position, "zero width for bit-field '%Y'", symbol);
6180 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6181 errorf(source_position, "width of '%Y' exceeds its type", symbol);
6183 type->bitfield.bit_size = v;
6190 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6192 entity_t *iter = compound->members.entities;
6193 for (; iter != NULL; iter = iter->base.next) {
6194 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6197 if (iter->base.symbol == symbol) {
6199 } else if (iter->base.symbol == NULL) {
6200 type_t *type = skip_typeref(iter->declaration.type);
6201 if (is_type_compound(type)) {
6203 = find_compound_entry(type->compound.compound, symbol);
6214 static void parse_compound_declarators(compound_t *compound,
6215 const declaration_specifiers_t *specifiers)
6220 if (token.type == ':') {
6221 source_position_t source_position = *HERE;
6224 type_t *base_type = specifiers->type;
6225 expression_t *size = parse_constant_expression();
6227 type_t *type = make_bitfield_type(base_type, size,
6228 &source_position, sym_anonymous);
6230 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6231 entity->base.namespc = NAMESPACE_NORMAL;
6232 entity->base.source_position = source_position;
6233 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6234 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6235 entity->declaration.modifiers = specifiers->modifiers;
6236 entity->declaration.type = type;
6238 entity = parse_declarator(specifiers,
6239 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
6240 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6242 if (token.type == ':') {
6243 source_position_t source_position = *HERE;
6245 expression_t *size = parse_constant_expression();
6247 type_t *type = entity->declaration.type;
6248 type_t *bitfield_type = make_bitfield_type(type, size,
6249 &source_position, entity->base.symbol);
6250 entity->declaration.type = bitfield_type;
6254 /* make sure we don't define a symbol multiple times */
6255 symbol_t *symbol = entity->base.symbol;
6256 if (symbol != NULL) {
6257 entity_t *prev = find_compound_entry(compound, symbol);
6260 errorf(&entity->base.source_position,
6261 "multiple declarations of symbol '%Y' (declared %P)",
6262 symbol, &prev->base.source_position);
6266 append_entity(&compound->members, entity);
6268 type_t *orig_type = entity->declaration.type;
6269 type_t *type = skip_typeref(orig_type);
6270 if (is_type_function(type)) {
6271 errorf(&entity->base.source_position,
6272 "compound member '%Y' must not have function type '%T'",
6273 entity->base.symbol, orig_type);
6274 } else if (is_type_incomplete(type)) {
6275 /* §6.7.2.1:16 flexible array member */
6276 if (is_type_array(type) &&
6277 token.type == ';' &&
6278 look_ahead(1)->type == '}') {
6279 compound->has_flexible_member = true;
6281 errorf(&entity->base.source_position,
6282 "compound member '%Y' has incomplete type '%T'",
6283 entity->base.symbol, orig_type);
6287 if (token.type != ',')
6294 anonymous_entity = NULL;
6297 static void parse_compound_type_entries(compound_t *compound)
6300 add_anchor_token('}');
6302 while (token.type != '}') {
6303 if (token.type == T_EOF) {
6304 errorf(HERE, "EOF while parsing struct");
6307 declaration_specifiers_t specifiers;
6308 memset(&specifiers, 0, sizeof(specifiers));
6309 parse_declaration_specifiers(&specifiers);
6311 parse_compound_declarators(compound, &specifiers);
6313 rem_anchor_token('}');
6317 compound->complete = true;
6320 static type_t *parse_typename(void)
6322 declaration_specifiers_t specifiers;
6323 memset(&specifiers, 0, sizeof(specifiers));
6324 parse_declaration_specifiers(&specifiers);
6325 if (specifiers.storage_class != STORAGE_CLASS_NONE) {
6326 /* TODO: improve error message, user does probably not know what a
6327 * storage class is...
6329 errorf(HERE, "typename may not have a storage class");
6332 type_t *result = parse_abstract_declarator(specifiers.type);
6340 typedef expression_t* (*parse_expression_function)(void);
6341 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6343 typedef struct expression_parser_function_t expression_parser_function_t;
6344 struct expression_parser_function_t {
6345 parse_expression_function parser;
6346 unsigned infix_precedence;
6347 parse_expression_infix_function infix_parser;
6350 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6353 * Prints an error message if an expression was expected but not read
6355 static expression_t *expected_expression_error(void)
6357 /* skip the error message if the error token was read */
6358 if (token.type != T_ERROR) {
6359 errorf(HERE, "expected expression, got token '%K'", &token);
6363 return create_invalid_expression();
6367 * Parse a string constant.
6369 static expression_t *parse_string_const(void)
6372 if (token.type == T_STRING_LITERAL) {
6373 string_t res = token.v.string;
6375 while (token.type == T_STRING_LITERAL) {
6376 res = concat_strings(&res, &token.v.string);
6379 if (token.type != T_WIDE_STRING_LITERAL) {
6380 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6381 /* note: that we use type_char_ptr here, which is already the
6382 * automatic converted type. revert_automatic_type_conversion
6383 * will construct the array type */
6384 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6385 cnst->string.value = res;
6389 wres = concat_string_wide_string(&res, &token.v.wide_string);
6391 wres = token.v.wide_string;
6396 switch (token.type) {
6397 case T_WIDE_STRING_LITERAL:
6398 wres = concat_wide_strings(&wres, &token.v.wide_string);
6401 case T_STRING_LITERAL:
6402 wres = concat_wide_string_string(&wres, &token.v.string);
6406 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6407 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6408 cnst->wide_string.value = wres;
6417 * Parse a boolean constant.
6419 static expression_t *parse_bool_const(bool value)
6421 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6422 cnst->base.type = type_bool;
6423 cnst->conste.v.int_value = value;
6431 * Parse an integer constant.
6433 static expression_t *parse_int_const(void)
6435 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6436 cnst->base.type = token.datatype;
6437 cnst->conste.v.int_value = token.v.intvalue;
6445 * Parse a character constant.
6447 static expression_t *parse_character_constant(void)
6449 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6450 cnst->base.type = token.datatype;
6451 cnst->conste.v.character = token.v.string;
6453 if (cnst->conste.v.character.size != 1) {
6455 errorf(HERE, "more than 1 character in character constant");
6456 } else if (warning.multichar) {
6457 warningf(HERE, "multi-character character constant");
6466 * Parse a wide character constant.
6468 static expression_t *parse_wide_character_constant(void)
6470 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6471 cnst->base.type = token.datatype;
6472 cnst->conste.v.wide_character = token.v.wide_string;
6474 if (cnst->conste.v.wide_character.size != 1) {
6476 errorf(HERE, "more than 1 character in character constant");
6477 } else if (warning.multichar) {
6478 warningf(HERE, "multi-character character constant");
6487 * Parse a float constant.
6489 static expression_t *parse_float_const(void)
6491 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6492 cnst->base.type = token.datatype;
6493 cnst->conste.v.float_value = token.v.floatvalue;
6500 static entity_t *create_implicit_function(symbol_t *symbol,
6501 const source_position_t *source_position)
6503 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6504 ntype->function.return_type = type_int;
6505 ntype->function.unspecified_parameters = true;
6507 type_t *type = typehash_insert(ntype);
6508 if (type != ntype) {
6512 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6513 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6514 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6515 entity->declaration.type = type;
6516 entity->declaration.implicit = true;
6517 entity->base.symbol = symbol;
6518 entity->base.source_position = *source_position;
6520 bool strict_prototypes_old = warning.strict_prototypes;
6521 warning.strict_prototypes = false;
6522 record_entity(entity, false);
6523 warning.strict_prototypes = strict_prototypes_old;
6529 * Creates a return_type (func)(argument_type) function type if not
6532 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6533 type_t *argument_type2)
6535 function_parameter_t *parameter2
6536 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6537 memset(parameter2, 0, sizeof(parameter2[0]));
6538 parameter2->type = argument_type2;
6540 function_parameter_t *parameter1
6541 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6542 memset(parameter1, 0, sizeof(parameter1[0]));
6543 parameter1->type = argument_type1;
6544 parameter1->next = parameter2;
6546 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6547 type->function.return_type = return_type;
6548 type->function.parameters = parameter1;
6550 type_t *result = typehash_insert(type);
6551 if (result != type) {
6559 * Creates a return_type (func)(argument_type) function type if not
6562 * @param return_type the return type
6563 * @param argument_type the argument type
6565 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6567 function_parameter_t *parameter
6568 = obstack_alloc(type_obst, sizeof(parameter[0]));
6569 memset(parameter, 0, sizeof(parameter[0]));
6570 parameter->type = argument_type;
6572 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6573 type->function.return_type = return_type;
6574 type->function.parameters = parameter;
6576 type_t *result = typehash_insert(type);
6577 if (result != type) {
6584 static type_t *make_function_0_type(type_t *return_type)
6586 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6587 type->function.return_type = return_type;
6588 type->function.parameters = NULL;
6590 type_t *result = typehash_insert(type);
6591 if (result != type) {
6599 * Creates a function type for some function like builtins.
6601 * @param symbol the symbol describing the builtin
6603 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6605 switch (symbol->ID) {
6606 case T___builtin_alloca:
6607 return make_function_1_type(type_void_ptr, type_size_t);
6608 case T___builtin_huge_val:
6609 return make_function_0_type(type_double);
6610 case T___builtin_inf:
6611 return make_function_0_type(type_double);
6612 case T___builtin_inff:
6613 return make_function_0_type(type_float);
6614 case T___builtin_infl:
6615 return make_function_0_type(type_long_double);
6616 case T___builtin_nan:
6617 return make_function_1_type(type_double, type_char_ptr);
6618 case T___builtin_nanf:
6619 return make_function_1_type(type_float, type_char_ptr);
6620 case T___builtin_nanl:
6621 return make_function_1_type(type_long_double, type_char_ptr);
6622 case T___builtin_va_end:
6623 return make_function_1_type(type_void, type_valist);
6624 case T___builtin_expect:
6625 return make_function_2_type(type_long, type_long, type_long);
6627 internal_errorf(HERE, "not implemented builtin symbol found");
6632 * Performs automatic type cast as described in § 6.3.2.1.
6634 * @param orig_type the original type
6636 static type_t *automatic_type_conversion(type_t *orig_type)
6638 type_t *type = skip_typeref(orig_type);
6639 if (is_type_array(type)) {
6640 array_type_t *array_type = &type->array;
6641 type_t *element_type = array_type->element_type;
6642 unsigned qualifiers = array_type->base.qualifiers;
6644 return make_pointer_type(element_type, qualifiers);
6647 if (is_type_function(type)) {
6648 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6655 * reverts the automatic casts of array to pointer types and function
6656 * to function-pointer types as defined § 6.3.2.1
6658 type_t *revert_automatic_type_conversion(const expression_t *expression)
6660 switch (expression->kind) {
6661 case EXPR_REFERENCE: {
6662 entity_t *entity = expression->reference.entity;
6663 if (is_declaration(entity)) {
6664 return entity->declaration.type;
6665 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6666 return entity->enum_value.enum_type;
6668 panic("no declaration or enum in reference");
6673 entity_t *entity = expression->select.compound_entry;
6674 assert(is_declaration(entity));
6675 type_t *type = entity->declaration.type;
6676 return get_qualified_type(type,
6677 expression->base.type->base.qualifiers);
6680 case EXPR_UNARY_DEREFERENCE: {
6681 const expression_t *const value = expression->unary.value;
6682 type_t *const type = skip_typeref(value->base.type);
6683 assert(is_type_pointer(type));
6684 return type->pointer.points_to;
6687 case EXPR_BUILTIN_SYMBOL:
6688 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6690 case EXPR_ARRAY_ACCESS: {
6691 const expression_t *array_ref = expression->array_access.array_ref;
6692 type_t *type_left = skip_typeref(array_ref->base.type);
6693 if (!is_type_valid(type_left))
6695 assert(is_type_pointer(type_left));
6696 return type_left->pointer.points_to;
6699 case EXPR_STRING_LITERAL: {
6700 size_t size = expression->string.value.size;
6701 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6704 case EXPR_WIDE_STRING_LITERAL: {
6705 size_t size = expression->wide_string.value.size;
6706 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6709 case EXPR_COMPOUND_LITERAL:
6710 return expression->compound_literal.type;
6715 return expression->base.type;
6718 static expression_t *parse_reference(void)
6720 symbol_t *const symbol = token.v.symbol;
6722 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6724 if (entity == NULL) {
6725 if (!strict_mode && look_ahead(1)->type == '(') {
6726 /* an implicitly declared function */
6727 if (warning.implicit_function_declaration) {
6728 warningf(HERE, "implicit declaration of function '%Y'",
6732 entity = create_implicit_function(symbol, HERE);
6734 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6735 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6741 if (is_declaration(entity)) {
6742 orig_type = entity->declaration.type;
6743 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6744 orig_type = entity->enum_value.enum_type;
6745 } else if (entity->kind == ENTITY_TYPEDEF) {
6746 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
6749 return create_invalid_expression();
6751 panic("expected declaration or enum value in reference");
6754 /* we always do the auto-type conversions; the & and sizeof parser contains
6755 * code to revert this! */
6756 type_t *type = automatic_type_conversion(orig_type);
6758 expression_kind_t kind = EXPR_REFERENCE;
6759 if (entity->kind == ENTITY_ENUM_VALUE)
6760 kind = EXPR_REFERENCE_ENUM_VALUE;
6762 expression_t *expression = allocate_expression_zero(kind);
6763 expression->reference.entity = entity;
6764 expression->base.type = type;
6766 /* this declaration is used */
6767 if (is_declaration(entity)) {
6768 entity->declaration.used = true;
6771 if (entity->base.parent_scope != file_scope
6772 && entity->base.parent_scope->depth < current_function->parameters.depth
6773 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
6774 if (entity->kind == ENTITY_VARIABLE) {
6775 /* access of a variable from an outer function */
6776 entity->variable.address_taken = true;
6778 current_function->need_closure = true;
6781 /* check for deprecated functions */
6782 if (warning.deprecated_declarations
6783 && is_declaration(entity)
6784 && entity->declaration.modifiers & DM_DEPRECATED) {
6785 declaration_t *declaration = &entity->declaration;
6787 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
6788 "function" : "variable";
6790 if (declaration->deprecated_string != NULL) {
6791 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6792 prefix, entity->base.symbol, &entity->base.source_position,
6793 declaration->deprecated_string);
6795 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6796 entity->base.symbol, &entity->base.source_position);
6800 if (warning.init_self && entity == current_init_decl && !in_type_prop
6801 && entity->kind == ENTITY_VARIABLE) {
6802 current_init_decl = NULL;
6803 warningf(HERE, "variable '%#T' is initialized by itself",
6804 entity->declaration.type, entity->base.symbol);
6811 static bool semantic_cast(expression_t *cast)
6813 expression_t *expression = cast->unary.value;
6814 type_t *orig_dest_type = cast->base.type;
6815 type_t *orig_type_right = expression->base.type;
6816 type_t const *dst_type = skip_typeref(orig_dest_type);
6817 type_t const *src_type = skip_typeref(orig_type_right);
6818 source_position_t const *pos = &cast->base.source_position;
6820 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6821 if (dst_type == type_void)
6824 /* only integer and pointer can be casted to pointer */
6825 if (is_type_pointer(dst_type) &&
6826 !is_type_pointer(src_type) &&
6827 !is_type_integer(src_type) &&
6828 is_type_valid(src_type)) {
6829 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6833 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6834 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6838 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6839 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6843 if (warning.cast_qual &&
6844 is_type_pointer(src_type) &&
6845 is_type_pointer(dst_type)) {
6846 type_t *src = skip_typeref(src_type->pointer.points_to);
6847 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6848 unsigned missing_qualifiers =
6849 src->base.qualifiers & ~dst->base.qualifiers;
6850 if (missing_qualifiers != 0) {
6852 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6853 missing_qualifiers, orig_type_right);
6859 static expression_t *parse_compound_literal(type_t *type)
6861 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6863 parse_initializer_env_t env;
6866 env.must_be_constant = false;
6867 initializer_t *initializer = parse_initializer(&env);
6870 expression->compound_literal.initializer = initializer;
6871 expression->compound_literal.type = type;
6872 expression->base.type = automatic_type_conversion(type);
6878 * Parse a cast expression.
6880 static expression_t *parse_cast(void)
6882 add_anchor_token(')');
6884 source_position_t source_position = token.source_position;
6886 type_t *type = parse_typename();
6888 rem_anchor_token(')');
6891 if (token.type == '{') {
6892 return parse_compound_literal(type);
6895 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6896 cast->base.source_position = source_position;
6898 expression_t *value = parse_sub_expression(PREC_CAST);
6899 cast->base.type = type;
6900 cast->unary.value = value;
6902 if (! semantic_cast(cast)) {
6903 /* TODO: record the error in the AST. else it is impossible to detect it */
6908 return create_invalid_expression();
6912 * Parse a statement expression.
6914 static expression_t *parse_statement_expression(void)
6916 add_anchor_token(')');
6918 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6920 statement_t *statement = parse_compound_statement(true);
6921 expression->statement.statement = statement;
6923 /* find last statement and use its type */
6924 type_t *type = type_void;
6925 const statement_t *stmt = statement->compound.statements;
6927 while (stmt->base.next != NULL)
6928 stmt = stmt->base.next;
6930 if (stmt->kind == STATEMENT_EXPRESSION) {
6931 type = stmt->expression.expression->base.type;
6933 } else if (warning.other) {
6934 warningf(&expression->base.source_position, "empty statement expression ({})");
6936 expression->base.type = type;
6938 rem_anchor_token(')');
6946 * Parse a parenthesized expression.
6948 static expression_t *parse_parenthesized_expression(void)
6952 switch (token.type) {
6954 /* gcc extension: a statement expression */
6955 return parse_statement_expression();
6959 return parse_cast();
6961 if (is_typedef_symbol(token.v.symbol)) {
6962 return parse_cast();
6966 add_anchor_token(')');
6967 expression_t *result = parse_expression();
6968 rem_anchor_token(')');
6975 static expression_t *parse_function_keyword(void)
6979 if (current_function == NULL) {
6980 errorf(HERE, "'__func__' used outside of a function");
6983 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6984 expression->base.type = type_char_ptr;
6985 expression->funcname.kind = FUNCNAME_FUNCTION;
6992 static expression_t *parse_pretty_function_keyword(void)
6994 if (current_function == NULL) {
6995 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6998 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6999 expression->base.type = type_char_ptr;
7000 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
7002 eat(T___PRETTY_FUNCTION__);
7007 static expression_t *parse_funcsig_keyword(void)
7009 if (current_function == NULL) {
7010 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7013 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7014 expression->base.type = type_char_ptr;
7015 expression->funcname.kind = FUNCNAME_FUNCSIG;
7022 static expression_t *parse_funcdname_keyword(void)
7024 if (current_function == NULL) {
7025 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7028 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7029 expression->base.type = type_char_ptr;
7030 expression->funcname.kind = FUNCNAME_FUNCDNAME;
7032 eat(T___FUNCDNAME__);
7037 static designator_t *parse_designator(void)
7039 designator_t *result = allocate_ast_zero(sizeof(result[0]));
7040 result->source_position = *HERE;
7042 if (token.type != T_IDENTIFIER) {
7043 parse_error_expected("while parsing member designator",
7044 T_IDENTIFIER, NULL);
7047 result->symbol = token.v.symbol;
7050 designator_t *last_designator = result;
7052 if (token.type == '.') {
7054 if (token.type != T_IDENTIFIER) {
7055 parse_error_expected("while parsing member designator",
7056 T_IDENTIFIER, NULL);
7059 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7060 designator->source_position = *HERE;
7061 designator->symbol = token.v.symbol;
7064 last_designator->next = designator;
7065 last_designator = designator;
7068 if (token.type == '[') {
7070 add_anchor_token(']');
7071 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7072 designator->source_position = *HERE;
7073 designator->array_index = parse_expression();
7074 rem_anchor_token(']');
7076 if (designator->array_index == NULL) {
7080 last_designator->next = designator;
7081 last_designator = designator;
7093 * Parse the __builtin_offsetof() expression.
7095 static expression_t *parse_offsetof(void)
7097 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7098 expression->base.type = type_size_t;
7100 eat(T___builtin_offsetof);
7103 add_anchor_token(',');
7104 type_t *type = parse_typename();
7105 rem_anchor_token(',');
7107 add_anchor_token(')');
7108 designator_t *designator = parse_designator();
7109 rem_anchor_token(')');
7112 expression->offsetofe.type = type;
7113 expression->offsetofe.designator = designator;
7116 memset(&path, 0, sizeof(path));
7117 path.top_type = type;
7118 path.path = NEW_ARR_F(type_path_entry_t, 0);
7120 descend_into_subtype(&path);
7122 if (!walk_designator(&path, designator, true)) {
7123 return create_invalid_expression();
7126 DEL_ARR_F(path.path);
7130 return create_invalid_expression();
7134 * Parses a _builtin_va_start() expression.
7136 static expression_t *parse_va_start(void)
7138 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7140 eat(T___builtin_va_start);
7143 add_anchor_token(',');
7144 expression->va_starte.ap = parse_assignment_expression();
7145 rem_anchor_token(',');
7147 expression_t *const expr = parse_assignment_expression();
7148 if (expr->kind == EXPR_REFERENCE) {
7149 entity_t *const entity = expr->reference.entity;
7150 if (entity->base.parent_scope != ¤t_function->parameters
7151 || entity->base.next != NULL
7152 || entity->kind != ENTITY_VARIABLE) {
7153 errorf(&expr->base.source_position,
7154 "second argument of 'va_start' must be last parameter of the current function");
7156 expression->va_starte.parameter = &entity->variable;
7163 return create_invalid_expression();
7167 * Parses a _builtin_va_arg() expression.
7169 static expression_t *parse_va_arg(void)
7171 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7173 eat(T___builtin_va_arg);
7176 expression->va_arge.ap = parse_assignment_expression();
7178 expression->base.type = parse_typename();
7183 return create_invalid_expression();
7186 static expression_t *parse_builtin_symbol(void)
7188 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7190 symbol_t *symbol = token.v.symbol;
7192 expression->builtin_symbol.symbol = symbol;
7195 type_t *type = get_builtin_symbol_type(symbol);
7196 type = automatic_type_conversion(type);
7198 expression->base.type = type;
7203 * Parses a __builtin_constant() expression.
7205 static expression_t *parse_builtin_constant(void)
7207 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7209 eat(T___builtin_constant_p);
7212 add_anchor_token(')');
7213 expression->builtin_constant.value = parse_assignment_expression();
7214 rem_anchor_token(')');
7216 expression->base.type = type_int;
7220 return create_invalid_expression();
7224 * Parses a __builtin_prefetch() expression.
7226 static expression_t *parse_builtin_prefetch(void)
7228 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7230 eat(T___builtin_prefetch);
7233 add_anchor_token(')');
7234 expression->builtin_prefetch.adr = parse_assignment_expression();
7235 if (token.type == ',') {
7237 expression->builtin_prefetch.rw = parse_assignment_expression();
7239 if (token.type == ',') {
7241 expression->builtin_prefetch.locality = parse_assignment_expression();
7243 rem_anchor_token(')');
7245 expression->base.type = type_void;
7249 return create_invalid_expression();
7253 * Parses a __builtin_is_*() compare expression.
7255 static expression_t *parse_compare_builtin(void)
7257 expression_t *expression;
7259 switch (token.type) {
7260 case T___builtin_isgreater:
7261 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7263 case T___builtin_isgreaterequal:
7264 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7266 case T___builtin_isless:
7267 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7269 case T___builtin_islessequal:
7270 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7272 case T___builtin_islessgreater:
7273 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7275 case T___builtin_isunordered:
7276 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7279 internal_errorf(HERE, "invalid compare builtin found");
7281 expression->base.source_position = *HERE;
7285 expression->binary.left = parse_assignment_expression();
7287 expression->binary.right = parse_assignment_expression();
7290 type_t *const orig_type_left = expression->binary.left->base.type;
7291 type_t *const orig_type_right = expression->binary.right->base.type;
7293 type_t *const type_left = skip_typeref(orig_type_left);
7294 type_t *const type_right = skip_typeref(orig_type_right);
7295 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7296 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7297 type_error_incompatible("invalid operands in comparison",
7298 &expression->base.source_position, orig_type_left, orig_type_right);
7301 semantic_comparison(&expression->binary);
7306 return create_invalid_expression();
7311 * Parses a __builtin_expect() expression.
7313 static expression_t *parse_builtin_expect(void)
7315 expression_t *expression
7316 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7318 eat(T___builtin_expect);
7321 expression->binary.left = parse_assignment_expression();
7323 expression->binary.right = parse_constant_expression();
7326 expression->base.type = expression->binary.left->base.type;
7330 return create_invalid_expression();
7335 * Parses a MS assume() expression.
7337 static expression_t *parse_assume(void)
7339 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7344 add_anchor_token(')');
7345 expression->unary.value = parse_assignment_expression();
7346 rem_anchor_token(')');
7349 expression->base.type = type_void;
7352 return create_invalid_expression();
7356 * Return the declaration for a given label symbol or create a new one.
7358 * @param symbol the symbol of the label
7360 static label_t *get_label(symbol_t *symbol)
7363 assert(current_function != NULL);
7365 label = get_entity(symbol, NAMESPACE_LABEL);
7366 /* if we found a local label, we already created the declaration */
7367 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7368 if (label->base.parent_scope != current_scope) {
7369 assert(label->base.parent_scope->depth < current_scope->depth);
7370 current_function->goto_to_outer = true;
7372 return &label->label;
7375 label = get_entity(symbol, NAMESPACE_LABEL);
7376 /* if we found a label in the same function, then we already created the
7379 && label->base.parent_scope == ¤t_function->parameters) {
7380 return &label->label;
7383 /* otherwise we need to create a new one */
7384 label = allocate_entity_zero(ENTITY_LABEL);
7385 label->base.namespc = NAMESPACE_LABEL;
7386 label->base.symbol = symbol;
7390 return &label->label;
7394 * Parses a GNU && label address expression.
7396 static expression_t *parse_label_address(void)
7398 source_position_t source_position = token.source_position;
7400 if (token.type != T_IDENTIFIER) {
7401 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7404 symbol_t *symbol = token.v.symbol;
7407 label_t *label = get_label(symbol);
7409 label->address_taken = true;
7411 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7412 expression->base.source_position = source_position;
7414 /* label address is threaten as a void pointer */
7415 expression->base.type = type_void_ptr;
7416 expression->label_address.label = label;
7419 return create_invalid_expression();
7423 * Parse a microsoft __noop expression.
7425 static expression_t *parse_noop_expression(void)
7427 /* the result is a (int)0 */
7428 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7429 cnst->base.type = type_int;
7430 cnst->conste.v.int_value = 0;
7431 cnst->conste.is_ms_noop = true;
7435 if (token.type == '(') {
7436 /* parse arguments */
7438 add_anchor_token(')');
7439 add_anchor_token(',');
7441 if (token.type != ')') {
7443 (void)parse_assignment_expression();
7444 if (token.type != ',')
7450 rem_anchor_token(',');
7451 rem_anchor_token(')');
7459 * Parses a primary expression.
7461 static expression_t *parse_primary_expression(void)
7463 switch (token.type) {
7464 case T_false: return parse_bool_const(false);
7465 case T_true: return parse_bool_const(true);
7466 case T_INTEGER: return parse_int_const();
7467 case T_CHARACTER_CONSTANT: return parse_character_constant();
7468 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7469 case T_FLOATINGPOINT: return parse_float_const();
7470 case T_STRING_LITERAL:
7471 case T_WIDE_STRING_LITERAL: return parse_string_const();
7472 case T_IDENTIFIER: return parse_reference();
7473 case T___FUNCTION__:
7474 case T___func__: return parse_function_keyword();
7475 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7476 case T___FUNCSIG__: return parse_funcsig_keyword();
7477 case T___FUNCDNAME__: return parse_funcdname_keyword();
7478 case T___builtin_offsetof: return parse_offsetof();
7479 case T___builtin_va_start: return parse_va_start();
7480 case T___builtin_va_arg: return parse_va_arg();
7481 case T___builtin_expect:
7482 case T___builtin_alloca:
7483 case T___builtin_inf:
7484 case T___builtin_inff:
7485 case T___builtin_infl:
7486 case T___builtin_nan:
7487 case T___builtin_nanf:
7488 case T___builtin_nanl:
7489 case T___builtin_huge_val:
7490 case T___builtin_va_end: return parse_builtin_symbol();
7491 case T___builtin_isgreater:
7492 case T___builtin_isgreaterequal:
7493 case T___builtin_isless:
7494 case T___builtin_islessequal:
7495 case T___builtin_islessgreater:
7496 case T___builtin_isunordered: return parse_compare_builtin();
7497 case T___builtin_constant_p: return parse_builtin_constant();
7498 case T___builtin_prefetch: return parse_builtin_prefetch();
7499 case T__assume: return parse_assume();
7502 return parse_label_address();
7505 case '(': return parse_parenthesized_expression();
7506 case T___noop: return parse_noop_expression();
7509 errorf(HERE, "unexpected token %K, expected an expression", &token);
7510 return create_invalid_expression();
7514 * Check if the expression has the character type and issue a warning then.
7516 static void check_for_char_index_type(const expression_t *expression)
7518 type_t *const type = expression->base.type;
7519 const type_t *const base_type = skip_typeref(type);
7521 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7522 warning.char_subscripts) {
7523 warningf(&expression->base.source_position,
7524 "array subscript has type '%T'", type);
7528 static expression_t *parse_array_expression(expression_t *left)
7530 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7533 add_anchor_token(']');
7535 expression_t *inside = parse_expression();
7537 type_t *const orig_type_left = left->base.type;
7538 type_t *const orig_type_inside = inside->base.type;
7540 type_t *const type_left = skip_typeref(orig_type_left);
7541 type_t *const type_inside = skip_typeref(orig_type_inside);
7543 type_t *return_type;
7544 array_access_expression_t *array_access = &expression->array_access;
7545 if (is_type_pointer(type_left)) {
7546 return_type = type_left->pointer.points_to;
7547 array_access->array_ref = left;
7548 array_access->index = inside;
7549 check_for_char_index_type(inside);
7550 } else if (is_type_pointer(type_inside)) {
7551 return_type = type_inside->pointer.points_to;
7552 array_access->array_ref = inside;
7553 array_access->index = left;
7554 array_access->flipped = true;
7555 check_for_char_index_type(left);
7557 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7559 "array access on object with non-pointer types '%T', '%T'",
7560 orig_type_left, orig_type_inside);
7562 return_type = type_error_type;
7563 array_access->array_ref = left;
7564 array_access->index = inside;
7567 expression->base.type = automatic_type_conversion(return_type);
7569 rem_anchor_token(']');
7575 static expression_t *parse_typeprop(expression_kind_t const kind)
7577 expression_t *tp_expression = allocate_expression_zero(kind);
7578 tp_expression->base.type = type_size_t;
7580 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7582 /* we only refer to a type property, mark this case */
7583 bool old = in_type_prop;
7584 in_type_prop = true;
7587 expression_t *expression;
7588 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7590 add_anchor_token(')');
7591 orig_type = parse_typename();
7592 rem_anchor_token(')');
7595 if (token.type == '{') {
7596 /* It was not sizeof(type) after all. It is sizeof of an expression
7597 * starting with a compound literal */
7598 expression = parse_compound_literal(orig_type);
7599 goto typeprop_expression;
7602 expression = parse_sub_expression(PREC_UNARY);
7604 typeprop_expression:
7605 tp_expression->typeprop.tp_expression = expression;
7607 orig_type = revert_automatic_type_conversion(expression);
7608 expression->base.type = orig_type;
7611 tp_expression->typeprop.type = orig_type;
7612 type_t const* const type = skip_typeref(orig_type);
7613 char const* const wrong_type =
7614 is_type_incomplete(type) ? "incomplete" :
7615 type->kind == TYPE_FUNCTION ? "function designator" :
7616 type->kind == TYPE_BITFIELD ? "bitfield" :
7618 if (wrong_type != NULL) {
7619 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7620 errorf(&tp_expression->base.source_position,
7621 "operand of %s expression must not be of %s type '%T'",
7622 what, wrong_type, orig_type);
7627 return tp_expression;
7630 static expression_t *parse_sizeof(void)
7632 return parse_typeprop(EXPR_SIZEOF);
7635 static expression_t *parse_alignof(void)
7637 return parse_typeprop(EXPR_ALIGNOF);
7640 static expression_t *parse_select_expression(expression_t *compound)
7642 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7643 select->select.compound = compound;
7645 assert(token.type == '.' || token.type == T_MINUSGREATER);
7646 bool is_pointer = (token.type == T_MINUSGREATER);
7649 if (token.type != T_IDENTIFIER) {
7650 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7653 symbol_t *symbol = token.v.symbol;
7656 type_t *const orig_type = compound->base.type;
7657 type_t *const type = skip_typeref(orig_type);
7660 bool saw_error = false;
7661 if (is_type_pointer(type)) {
7664 "request for member '%Y' in something not a struct or union, but '%T'",
7668 type_left = skip_typeref(type->pointer.points_to);
7670 if (is_pointer && is_type_valid(type)) {
7671 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7678 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7679 type_left->kind == TYPE_COMPOUND_UNION) {
7680 compound_t *compound = type_left->compound.compound;
7682 if (!compound->complete) {
7683 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7685 goto create_error_entry;
7688 entry = find_compound_entry(compound, symbol);
7689 if (entry == NULL) {
7690 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7691 goto create_error_entry;
7694 if (is_type_valid(type_left) && !saw_error) {
7696 "request for member '%Y' in something not a struct or union, but '%T'",
7700 return create_invalid_expression();
7703 assert(is_declaration(entry));
7704 select->select.compound_entry = entry;
7706 type_t *entry_type = entry->declaration.type;
7708 = get_qualified_type(entry_type, type_left->base.qualifiers);
7710 /* we always do the auto-type conversions; the & and sizeof parser contains
7711 * code to revert this! */
7712 select->base.type = automatic_type_conversion(res_type);
7714 type_t *skipped = skip_typeref(res_type);
7715 if (skipped->kind == TYPE_BITFIELD) {
7716 select->base.type = skipped->bitfield.base_type;
7722 static void check_call_argument(const function_parameter_t *parameter,
7723 call_argument_t *argument, unsigned pos)
7725 type_t *expected_type = parameter->type;
7726 type_t *expected_type_skip = skip_typeref(expected_type);
7727 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7728 expression_t *arg_expr = argument->expression;
7729 type_t *arg_type = skip_typeref(arg_expr->base.type);
7731 /* handle transparent union gnu extension */
7732 if (is_type_union(expected_type_skip)
7733 && (expected_type_skip->base.modifiers
7734 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7735 compound_t *union_decl = expected_type_skip->compound.compound;
7736 type_t *best_type = NULL;
7737 entity_t *entry = union_decl->members.entities;
7738 for ( ; entry != NULL; entry = entry->base.next) {
7739 assert(is_declaration(entry));
7740 type_t *decl_type = entry->declaration.type;
7741 error = semantic_assign(decl_type, arg_expr);
7742 if (error == ASSIGN_ERROR_INCOMPATIBLE
7743 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7746 if (error == ASSIGN_SUCCESS) {
7747 best_type = decl_type;
7748 } else if (best_type == NULL) {
7749 best_type = decl_type;
7753 if (best_type != NULL) {
7754 expected_type = best_type;
7758 error = semantic_assign(expected_type, arg_expr);
7759 argument->expression = create_implicit_cast(argument->expression,
7762 if (error != ASSIGN_SUCCESS) {
7763 /* report exact scope in error messages (like "in argument 3") */
7765 snprintf(buf, sizeof(buf), "call argument %u", pos);
7766 report_assign_error(error, expected_type, arg_expr, buf,
7767 &arg_expr->base.source_position);
7768 } else if (warning.traditional || warning.conversion) {
7769 type_t *const promoted_type = get_default_promoted_type(arg_type);
7770 if (!types_compatible(expected_type_skip, promoted_type) &&
7771 !types_compatible(expected_type_skip, type_void_ptr) &&
7772 !types_compatible(type_void_ptr, promoted_type)) {
7773 /* Deliberately show the skipped types in this warning */
7774 warningf(&arg_expr->base.source_position,
7775 "passing call argument %u as '%T' rather than '%T' due to prototype",
7776 pos, expected_type_skip, promoted_type);
7782 * Parse a call expression, ie. expression '( ... )'.
7784 * @param expression the function address
7786 static expression_t *parse_call_expression(expression_t *expression)
7788 expression_t *result = allocate_expression_zero(EXPR_CALL);
7789 call_expression_t *call = &result->call;
7790 call->function = expression;
7792 type_t *const orig_type = expression->base.type;
7793 type_t *const type = skip_typeref(orig_type);
7795 function_type_t *function_type = NULL;
7796 if (is_type_pointer(type)) {
7797 type_t *const to_type = skip_typeref(type->pointer.points_to);
7799 if (is_type_function(to_type)) {
7800 function_type = &to_type->function;
7801 call->base.type = function_type->return_type;
7805 if (function_type == NULL && is_type_valid(type)) {
7806 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7809 /* parse arguments */
7811 add_anchor_token(')');
7812 add_anchor_token(',');
7814 if (token.type != ')') {
7815 call_argument_t *last_argument = NULL;
7818 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7820 argument->expression = parse_assignment_expression();
7821 if (last_argument == NULL) {
7822 call->arguments = argument;
7824 last_argument->next = argument;
7826 last_argument = argument;
7828 if (token.type != ',')
7833 rem_anchor_token(',');
7834 rem_anchor_token(')');
7837 if (function_type == NULL)
7840 function_parameter_t *parameter = function_type->parameters;
7841 call_argument_t *argument = call->arguments;
7842 if (!function_type->unspecified_parameters) {
7843 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7844 parameter = parameter->next, argument = argument->next) {
7845 check_call_argument(parameter, argument, ++pos);
7848 if (parameter != NULL) {
7849 errorf(HERE, "too few arguments to function '%E'", expression);
7850 } else if (argument != NULL && !function_type->variadic) {
7851 errorf(HERE, "too many arguments to function '%E'", expression);
7855 /* do default promotion */
7856 for (; argument != NULL; argument = argument->next) {
7857 type_t *type = argument->expression->base.type;
7859 type = get_default_promoted_type(type);
7861 argument->expression
7862 = create_implicit_cast(argument->expression, type);
7865 check_format(&result->call);
7867 if (warning.aggregate_return &&
7868 is_type_compound(skip_typeref(function_type->return_type))) {
7869 warningf(&result->base.source_position,
7870 "function call has aggregate value");
7877 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7879 static bool same_compound_type(const type_t *type1, const type_t *type2)
7882 is_type_compound(type1) &&
7883 type1->kind == type2->kind &&
7884 type1->compound.compound == type2->compound.compound;
7887 static expression_t const *get_reference_address(expression_t const *expr)
7889 bool regular_take_address = true;
7891 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7892 expr = expr->unary.value;
7894 regular_take_address = false;
7897 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7900 expr = expr->unary.value;
7903 if (expr->kind != EXPR_REFERENCE)
7906 /* special case for functions which are automatically converted to a
7907 * pointer to function without an extra TAKE_ADDRESS operation */
7908 if (!regular_take_address &&
7909 expr->reference.entity->kind != ENTITY_FUNCTION) {
7916 static void warn_reference_address_as_bool(expression_t const* expr)
7918 if (!warning.address)
7921 expr = get_reference_address(expr);
7923 warningf(&expr->base.source_position,
7924 "the address of '%Y' will always evaluate as 'true'",
7925 expr->reference.entity->base.symbol);
7929 static void semantic_condition(expression_t const *const expr,
7930 char const *const context)
7932 type_t *const type = skip_typeref(expr->base.type);
7933 if (is_type_scalar(type)) {
7934 warn_reference_address_as_bool(expr);
7935 } else if (is_type_valid(type)) {
7936 errorf(&expr->base.source_position,
7937 "%s must have scalar type", context);
7942 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7944 * @param expression the conditional expression
7946 static expression_t *parse_conditional_expression(expression_t *expression)
7948 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7950 conditional_expression_t *conditional = &result->conditional;
7951 conditional->condition = expression;
7954 add_anchor_token(':');
7956 /* §6.5.15:2 The first operand shall have scalar type. */
7957 semantic_condition(expression, "condition of conditional operator");
7959 expression_t *true_expression = expression;
7960 bool gnu_cond = false;
7961 if (GNU_MODE && token.type == ':') {
7964 true_expression = parse_expression();
7966 rem_anchor_token(':');
7968 expression_t *false_expression =
7969 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7971 type_t *const orig_true_type = true_expression->base.type;
7972 type_t *const orig_false_type = false_expression->base.type;
7973 type_t *const true_type = skip_typeref(orig_true_type);
7974 type_t *const false_type = skip_typeref(orig_false_type);
7977 type_t *result_type;
7978 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7979 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7980 /* ISO/IEC 14882:1998(E) §5.16:2 */
7981 if (true_expression->kind == EXPR_UNARY_THROW) {
7982 result_type = false_type;
7983 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7984 result_type = true_type;
7986 if (warning.other && (
7987 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7988 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7990 warningf(&conditional->base.source_position,
7991 "ISO C forbids conditional expression with only one void side");
7993 result_type = type_void;
7995 } else if (is_type_arithmetic(true_type)
7996 && is_type_arithmetic(false_type)) {
7997 result_type = semantic_arithmetic(true_type, false_type);
7999 true_expression = create_implicit_cast(true_expression, result_type);
8000 false_expression = create_implicit_cast(false_expression, result_type);
8002 conditional->true_expression = true_expression;
8003 conditional->false_expression = false_expression;
8004 conditional->base.type = result_type;
8005 } else if (same_compound_type(true_type, false_type)) {
8006 /* just take 1 of the 2 types */
8007 result_type = true_type;
8008 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
8009 type_t *pointer_type;
8011 expression_t *other_expression;
8012 if (is_type_pointer(true_type) &&
8013 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
8014 pointer_type = true_type;
8015 other_type = false_type;
8016 other_expression = false_expression;
8018 pointer_type = false_type;
8019 other_type = true_type;
8020 other_expression = true_expression;
8023 if (is_null_pointer_constant(other_expression)) {
8024 result_type = pointer_type;
8025 } else if (is_type_pointer(other_type)) {
8026 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8027 type_t *to2 = skip_typeref(other_type->pointer.points_to);
8030 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8031 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8033 } else if (types_compatible(get_unqualified_type(to1),
8034 get_unqualified_type(to2))) {
8037 if (warning.other) {
8038 warningf(&conditional->base.source_position,
8039 "pointer types '%T' and '%T' in conditional expression are incompatible",
8040 true_type, false_type);
8045 type_t *const type =
8046 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8047 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8048 } else if (is_type_integer(other_type)) {
8049 if (warning.other) {
8050 warningf(&conditional->base.source_position,
8051 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8053 result_type = pointer_type;
8055 if (is_type_valid(other_type)) {
8056 type_error_incompatible("while parsing conditional",
8057 &expression->base.source_position, true_type, false_type);
8059 result_type = type_error_type;
8062 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8063 type_error_incompatible("while parsing conditional",
8064 &conditional->base.source_position, true_type,
8067 result_type = type_error_type;
8070 conditional->true_expression
8071 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8072 conditional->false_expression
8073 = create_implicit_cast(false_expression, result_type);
8074 conditional->base.type = result_type;
8077 return create_invalid_expression();
8081 * Parse an extension expression.
8083 static expression_t *parse_extension(void)
8085 eat(T___extension__);
8087 bool old_gcc_extension = in_gcc_extension;
8088 in_gcc_extension = true;
8089 expression_t *expression = parse_sub_expression(PREC_UNARY);
8090 in_gcc_extension = old_gcc_extension;
8095 * Parse a __builtin_classify_type() expression.
8097 static expression_t *parse_builtin_classify_type(void)
8099 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8100 result->base.type = type_int;
8102 eat(T___builtin_classify_type);
8105 add_anchor_token(')');
8106 expression_t *expression = parse_expression();
8107 rem_anchor_token(')');
8109 result->classify_type.type_expression = expression;
8113 return create_invalid_expression();
8117 * Parse a delete expression
8118 * ISO/IEC 14882:1998(E) §5.3.5
8120 static expression_t *parse_delete(void)
8122 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8123 result->base.type = type_void;
8127 if (token.type == '[') {
8129 result->kind = EXPR_UNARY_DELETE_ARRAY;
8134 expression_t *const value = parse_sub_expression(PREC_CAST);
8135 result->unary.value = value;
8137 type_t *const type = skip_typeref(value->base.type);
8138 if (!is_type_pointer(type)) {
8139 errorf(&value->base.source_position,
8140 "operand of delete must have pointer type");
8141 } else if (warning.other &&
8142 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8143 warningf(&value->base.source_position,
8144 "deleting 'void*' is undefined");
8151 * Parse a throw expression
8152 * ISO/IEC 14882:1998(E) §15:1
8154 static expression_t *parse_throw(void)
8156 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8157 result->base.type = type_void;
8161 expression_t *value = NULL;
8162 switch (token.type) {
8164 value = parse_assignment_expression();
8165 /* ISO/IEC 14882:1998(E) §15.1:3 */
8166 type_t *const orig_type = value->base.type;
8167 type_t *const type = skip_typeref(orig_type);
8168 if (is_type_incomplete(type)) {
8169 errorf(&value->base.source_position,
8170 "cannot throw object of incomplete type '%T'", orig_type);
8171 } else if (is_type_pointer(type)) {
8172 type_t *const points_to = skip_typeref(type->pointer.points_to);
8173 if (is_type_incomplete(points_to) &&
8174 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8175 errorf(&value->base.source_position,
8176 "cannot throw pointer to incomplete type '%T'", orig_type);
8184 result->unary.value = value;
8189 static bool check_pointer_arithmetic(const source_position_t *source_position,
8190 type_t *pointer_type,
8191 type_t *orig_pointer_type)
8193 type_t *points_to = pointer_type->pointer.points_to;
8194 points_to = skip_typeref(points_to);
8196 if (is_type_incomplete(points_to)) {
8197 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8198 errorf(source_position,
8199 "arithmetic with pointer to incomplete type '%T' not allowed",
8202 } else if (warning.pointer_arith) {
8203 warningf(source_position,
8204 "pointer of type '%T' used in arithmetic",
8207 } else if (is_type_function(points_to)) {
8209 errorf(source_position,
8210 "arithmetic with pointer to function type '%T' not allowed",
8213 } else if (warning.pointer_arith) {
8214 warningf(source_position,
8215 "pointer to a function '%T' used in arithmetic",
8222 static bool is_lvalue(const expression_t *expression)
8224 /* TODO: doesn't seem to be consistent with §6.3.2.1 (1) */
8225 switch (expression->kind) {
8226 case EXPR_REFERENCE:
8227 case EXPR_ARRAY_ACCESS:
8229 case EXPR_UNARY_DEREFERENCE:
8233 /* Claim it is an lvalue, if the type is invalid. There was a parse
8234 * error before, which maybe prevented properly recognizing it as
8236 return !is_type_valid(skip_typeref(expression->base.type));
8240 static void semantic_incdec(unary_expression_t *expression)
8242 type_t *const orig_type = expression->value->base.type;
8243 type_t *const type = skip_typeref(orig_type);
8244 if (is_type_pointer(type)) {
8245 if (!check_pointer_arithmetic(&expression->base.source_position,
8249 } else if (!is_type_real(type) && is_type_valid(type)) {
8250 /* TODO: improve error message */
8251 errorf(&expression->base.source_position,
8252 "operation needs an arithmetic or pointer type");
8255 if (!is_lvalue(expression->value)) {
8256 /* TODO: improve error message */
8257 errorf(&expression->base.source_position, "lvalue required as operand");
8259 expression->base.type = orig_type;
8262 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8264 type_t *const orig_type = expression->value->base.type;
8265 type_t *const type = skip_typeref(orig_type);
8266 if (!is_type_arithmetic(type)) {
8267 if (is_type_valid(type)) {
8268 /* TODO: improve error message */
8269 errorf(&expression->base.source_position,
8270 "operation needs an arithmetic type");
8275 expression->base.type = orig_type;
8278 static void semantic_unexpr_plus(unary_expression_t *expression)
8280 semantic_unexpr_arithmetic(expression);
8281 if (warning.traditional)
8282 warningf(&expression->base.source_position,
8283 "traditional C rejects the unary plus operator");
8286 static void semantic_not(unary_expression_t *expression)
8288 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8289 semantic_condition(expression->value, "operand of !");
8290 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8293 static void semantic_unexpr_integer(unary_expression_t *expression)
8295 type_t *const orig_type = expression->value->base.type;
8296 type_t *const type = skip_typeref(orig_type);
8297 if (!is_type_integer(type)) {
8298 if (is_type_valid(type)) {
8299 errorf(&expression->base.source_position,
8300 "operand of ~ must be of integer type");
8305 expression->base.type = orig_type;
8308 static void semantic_dereference(unary_expression_t *expression)
8310 type_t *const orig_type = expression->value->base.type;
8311 type_t *const type = skip_typeref(orig_type);
8312 if (!is_type_pointer(type)) {
8313 if (is_type_valid(type)) {
8314 errorf(&expression->base.source_position,
8315 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8320 type_t *result_type = type->pointer.points_to;
8321 result_type = automatic_type_conversion(result_type);
8322 expression->base.type = result_type;
8326 * Record that an address is taken (expression represents an lvalue).
8328 * @param expression the expression
8329 * @param may_be_register if true, the expression might be an register
8331 static void set_address_taken(expression_t *expression, bool may_be_register)
8333 if (expression->kind != EXPR_REFERENCE)
8336 entity_t *const entity = expression->reference.entity;
8338 if (entity->kind != ENTITY_VARIABLE)
8341 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8342 && !may_be_register) {
8343 errorf(&expression->base.source_position,
8344 "address of register variable '%Y' requested",
8345 entity->base.symbol);
8348 entity->variable.address_taken = true;
8352 * Check the semantic of the address taken expression.
8354 static void semantic_take_addr(unary_expression_t *expression)
8356 expression_t *value = expression->value;
8357 value->base.type = revert_automatic_type_conversion(value);
8359 type_t *orig_type = value->base.type;
8360 type_t *type = skip_typeref(orig_type);
8361 if (!is_type_valid(type))
8365 if (!is_lvalue(value)) {
8366 errorf(&expression->base.source_position, "'&' requires an lvalue");
8368 if (type->kind == TYPE_BITFIELD) {
8369 errorf(&expression->base.source_position,
8370 "'&' not allowed on object with bitfield type '%T'",
8374 set_address_taken(value, false);
8376 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8379 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8380 static expression_t *parse_##unexpression_type(void) \
8382 expression_t *unary_expression \
8383 = allocate_expression_zero(unexpression_type); \
8385 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8387 sfunc(&unary_expression->unary); \
8389 return unary_expression; \
8392 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8393 semantic_unexpr_arithmetic)
8394 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8395 semantic_unexpr_plus)
8396 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8398 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8399 semantic_dereference)
8400 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8402 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8403 semantic_unexpr_integer)
8404 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8406 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8409 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8411 static expression_t *parse_##unexpression_type(expression_t *left) \
8413 expression_t *unary_expression \
8414 = allocate_expression_zero(unexpression_type); \
8416 unary_expression->unary.value = left; \
8418 sfunc(&unary_expression->unary); \
8420 return unary_expression; \
8423 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8424 EXPR_UNARY_POSTFIX_INCREMENT,
8426 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8427 EXPR_UNARY_POSTFIX_DECREMENT,
8430 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8432 /* TODO: handle complex + imaginary types */
8434 type_left = get_unqualified_type(type_left);
8435 type_right = get_unqualified_type(type_right);
8437 /* § 6.3.1.8 Usual arithmetic conversions */
8438 if (type_left == type_long_double || type_right == type_long_double) {
8439 return type_long_double;
8440 } else if (type_left == type_double || type_right == type_double) {
8442 } else if (type_left == type_float || type_right == type_float) {
8446 type_left = promote_integer(type_left);
8447 type_right = promote_integer(type_right);
8449 if (type_left == type_right)
8452 bool const signed_left = is_type_signed(type_left);
8453 bool const signed_right = is_type_signed(type_right);
8454 int const rank_left = get_rank(type_left);
8455 int const rank_right = get_rank(type_right);
8457 if (signed_left == signed_right)
8458 return rank_left >= rank_right ? type_left : type_right;
8467 u_rank = rank_right;
8468 u_type = type_right;
8470 s_rank = rank_right;
8471 s_type = type_right;
8476 if (u_rank >= s_rank)
8479 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8481 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8482 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8486 case ATOMIC_TYPE_INT: return type_unsigned_int;
8487 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8488 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8490 default: panic("invalid atomic type");
8495 * Check the semantic restrictions for a binary expression.
8497 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8499 expression_t *const left = expression->left;
8500 expression_t *const right = expression->right;
8501 type_t *const orig_type_left = left->base.type;
8502 type_t *const orig_type_right = right->base.type;
8503 type_t *const type_left = skip_typeref(orig_type_left);
8504 type_t *const type_right = skip_typeref(orig_type_right);
8506 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8507 /* TODO: improve error message */
8508 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8509 errorf(&expression->base.source_position,
8510 "operation needs arithmetic types");
8515 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8516 expression->left = create_implicit_cast(left, arithmetic_type);
8517 expression->right = create_implicit_cast(right, arithmetic_type);
8518 expression->base.type = arithmetic_type;
8521 static void warn_div_by_zero(binary_expression_t const *const expression)
8523 if (!warning.div_by_zero ||
8524 !is_type_integer(expression->base.type))
8527 expression_t const *const right = expression->right;
8528 /* The type of the right operand can be different for /= */
8529 if (is_type_integer(right->base.type) &&
8530 is_constant_expression(right) &&
8531 fold_constant(right) == 0) {
8532 warningf(&expression->base.source_position, "division by zero");
8537 * Check the semantic restrictions for a div/mod expression.
8539 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8540 semantic_binexpr_arithmetic(expression);
8541 warn_div_by_zero(expression);
8544 static void semantic_shift_op(binary_expression_t *expression)
8546 expression_t *const left = expression->left;
8547 expression_t *const right = expression->right;
8548 type_t *const orig_type_left = left->base.type;
8549 type_t *const orig_type_right = right->base.type;
8550 type_t * type_left = skip_typeref(orig_type_left);
8551 type_t * type_right = skip_typeref(orig_type_right);
8553 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8554 /* TODO: improve error message */
8555 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8556 errorf(&expression->base.source_position,
8557 "operands of shift operation must have integer types");
8562 type_left = promote_integer(type_left);
8563 type_right = promote_integer(type_right);
8565 expression->left = create_implicit_cast(left, type_left);
8566 expression->right = create_implicit_cast(right, type_right);
8567 expression->base.type = type_left;
8570 static void semantic_add(binary_expression_t *expression)
8572 expression_t *const left = expression->left;
8573 expression_t *const right = expression->right;
8574 type_t *const orig_type_left = left->base.type;
8575 type_t *const orig_type_right = right->base.type;
8576 type_t *const type_left = skip_typeref(orig_type_left);
8577 type_t *const type_right = skip_typeref(orig_type_right);
8580 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8581 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8582 expression->left = create_implicit_cast(left, arithmetic_type);
8583 expression->right = create_implicit_cast(right, arithmetic_type);
8584 expression->base.type = arithmetic_type;
8586 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8587 check_pointer_arithmetic(&expression->base.source_position,
8588 type_left, orig_type_left);
8589 expression->base.type = type_left;
8590 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8591 check_pointer_arithmetic(&expression->base.source_position,
8592 type_right, orig_type_right);
8593 expression->base.type = type_right;
8594 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8595 errorf(&expression->base.source_position,
8596 "invalid operands to binary + ('%T', '%T')",
8597 orig_type_left, orig_type_right);
8601 static void semantic_sub(binary_expression_t *expression)
8603 expression_t *const left = expression->left;
8604 expression_t *const right = expression->right;
8605 type_t *const orig_type_left = left->base.type;
8606 type_t *const orig_type_right = right->base.type;
8607 type_t *const type_left = skip_typeref(orig_type_left);
8608 type_t *const type_right = skip_typeref(orig_type_right);
8609 source_position_t const *const pos = &expression->base.source_position;
8612 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8613 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8614 expression->left = create_implicit_cast(left, arithmetic_type);
8615 expression->right = create_implicit_cast(right, arithmetic_type);
8616 expression->base.type = arithmetic_type;
8618 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8619 check_pointer_arithmetic(&expression->base.source_position,
8620 type_left, orig_type_left);
8621 expression->base.type = type_left;
8622 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8623 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8624 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8625 if (!types_compatible(unqual_left, unqual_right)) {
8627 "subtracting pointers to incompatible types '%T' and '%T'",
8628 orig_type_left, orig_type_right);
8629 } else if (!is_type_object(unqual_left)) {
8630 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8631 errorf(pos, "subtracting pointers to non-object types '%T'",
8633 } else if (warning.other) {
8634 warningf(pos, "subtracting pointers to void");
8637 expression->base.type = type_ptrdiff_t;
8638 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8639 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8640 orig_type_left, orig_type_right);
8644 static void warn_string_literal_address(expression_t const* expr)
8646 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8647 expr = expr->unary.value;
8648 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8650 expr = expr->unary.value;
8653 if (expr->kind == EXPR_STRING_LITERAL ||
8654 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8655 warningf(&expr->base.source_position,
8656 "comparison with string literal results in unspecified behaviour");
8661 * Check the semantics of comparison expressions.
8663 * @param expression The expression to check.
8665 static void semantic_comparison(binary_expression_t *expression)
8667 expression_t *left = expression->left;
8668 expression_t *right = expression->right;
8670 if (warning.address) {
8671 warn_string_literal_address(left);
8672 warn_string_literal_address(right);
8674 expression_t const* const func_left = get_reference_address(left);
8675 if (func_left != NULL && is_null_pointer_constant(right)) {
8676 warningf(&expression->base.source_position,
8677 "the address of '%Y' will never be NULL",
8678 func_left->reference.entity->base.symbol);
8681 expression_t const* const func_right = get_reference_address(right);
8682 if (func_right != NULL && is_null_pointer_constant(right)) {
8683 warningf(&expression->base.source_position,
8684 "the address of '%Y' will never be NULL",
8685 func_right->reference.entity->base.symbol);
8689 type_t *orig_type_left = left->base.type;
8690 type_t *orig_type_right = right->base.type;
8691 type_t *type_left = skip_typeref(orig_type_left);
8692 type_t *type_right = skip_typeref(orig_type_right);
8694 /* TODO non-arithmetic types */
8695 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8696 /* test for signed vs unsigned compares */
8697 if (warning.sign_compare &&
8698 (expression->base.kind != EXPR_BINARY_EQUAL &&
8699 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
8700 (is_type_signed(type_left) != is_type_signed(type_right))) {
8702 /* check if 1 of the operands is a constant, in this case we just
8703 * check wether we can safely represent the resulting constant in
8704 * the type of the other operand. */
8705 expression_t *const_expr = NULL;
8706 expression_t *other_expr = NULL;
8708 if (is_constant_expression(left)) {
8711 } else if (is_constant_expression(right)) {
8716 if (const_expr != NULL) {
8717 type_t *other_type = skip_typeref(other_expr->base.type);
8718 long val = fold_constant(const_expr);
8719 /* TODO: check if val can be represented by other_type */
8723 warningf(&expression->base.source_position,
8724 "comparison between signed and unsigned");
8726 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8727 expression->left = create_implicit_cast(left, arithmetic_type);
8728 expression->right = create_implicit_cast(right, arithmetic_type);
8729 expression->base.type = arithmetic_type;
8730 if (warning.float_equal &&
8731 (expression->base.kind == EXPR_BINARY_EQUAL ||
8732 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8733 is_type_float(arithmetic_type)) {
8734 warningf(&expression->base.source_position,
8735 "comparing floating point with == or != is unsafe");
8737 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8738 /* TODO check compatibility */
8739 } else if (is_type_pointer(type_left)) {
8740 expression->right = create_implicit_cast(right, type_left);
8741 } else if (is_type_pointer(type_right)) {
8742 expression->left = create_implicit_cast(left, type_right);
8743 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8744 type_error_incompatible("invalid operands in comparison",
8745 &expression->base.source_position,
8746 type_left, type_right);
8748 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8752 * Checks if a compound type has constant fields.
8754 static bool has_const_fields(const compound_type_t *type)
8756 compound_t *compound = type->compound;
8757 entity_t *entry = compound->members.entities;
8759 for (; entry != NULL; entry = entry->base.next) {
8760 if (!is_declaration(entry))
8763 const type_t *decl_type = skip_typeref(entry->declaration.type);
8764 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8771 static bool is_valid_assignment_lhs(expression_t const* const left)
8773 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8774 type_t *const type_left = skip_typeref(orig_type_left);
8776 if (!is_lvalue(left)) {
8777 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8782 if (is_type_array(type_left)) {
8783 errorf(HERE, "cannot assign to arrays ('%E')", left);
8786 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8787 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8791 if (is_type_incomplete(type_left)) {
8792 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8793 left, orig_type_left);
8796 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8797 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8798 left, orig_type_left);
8805 static void semantic_arithmetic_assign(binary_expression_t *expression)
8807 expression_t *left = expression->left;
8808 expression_t *right = expression->right;
8809 type_t *orig_type_left = left->base.type;
8810 type_t *orig_type_right = right->base.type;
8812 if (!is_valid_assignment_lhs(left))
8815 type_t *type_left = skip_typeref(orig_type_left);
8816 type_t *type_right = skip_typeref(orig_type_right);
8818 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8819 /* TODO: improve error message */
8820 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8821 errorf(&expression->base.source_position,
8822 "operation needs arithmetic types");
8827 /* combined instructions are tricky. We can't create an implicit cast on
8828 * the left side, because we need the uncasted form for the store.
8829 * The ast2firm pass has to know that left_type must be right_type
8830 * for the arithmetic operation and create a cast by itself */
8831 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8832 expression->right = create_implicit_cast(right, arithmetic_type);
8833 expression->base.type = type_left;
8836 static void semantic_divmod_assign(binary_expression_t *expression)
8838 semantic_arithmetic_assign(expression);
8839 warn_div_by_zero(expression);
8842 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8844 expression_t *const left = expression->left;
8845 expression_t *const right = expression->right;
8846 type_t *const orig_type_left = left->base.type;
8847 type_t *const orig_type_right = right->base.type;
8848 type_t *const type_left = skip_typeref(orig_type_left);
8849 type_t *const type_right = skip_typeref(orig_type_right);
8851 if (!is_valid_assignment_lhs(left))
8854 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8855 /* combined instructions are tricky. We can't create an implicit cast on
8856 * the left side, because we need the uncasted form for the store.
8857 * The ast2firm pass has to know that left_type must be right_type
8858 * for the arithmetic operation and create a cast by itself */
8859 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8860 expression->right = create_implicit_cast(right, arithmetic_type);
8861 expression->base.type = type_left;
8862 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8863 check_pointer_arithmetic(&expression->base.source_position,
8864 type_left, orig_type_left);
8865 expression->base.type = type_left;
8866 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8867 errorf(&expression->base.source_position,
8868 "incompatible types '%T' and '%T' in assignment",
8869 orig_type_left, orig_type_right);
8874 * Check the semantic restrictions of a logical expression.
8876 static void semantic_logical_op(binary_expression_t *expression)
8878 /* §6.5.13:2 Each of the operands shall have scalar type.
8879 * §6.5.14:2 Each of the operands shall have scalar type. */
8880 semantic_condition(expression->left, "left operand of logical operator");
8881 semantic_condition(expression->right, "right operand of logical operator");
8882 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8886 * Check the semantic restrictions of a binary assign expression.
8888 static void semantic_binexpr_assign(binary_expression_t *expression)
8890 expression_t *left = expression->left;
8891 type_t *orig_type_left = left->base.type;
8893 if (!is_valid_assignment_lhs(left))
8896 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8897 report_assign_error(error, orig_type_left, expression->right,
8898 "assignment", &left->base.source_position);
8899 expression->right = create_implicit_cast(expression->right, orig_type_left);
8900 expression->base.type = orig_type_left;
8904 * Determine if the outermost operation (or parts thereof) of the given
8905 * expression has no effect in order to generate a warning about this fact.
8906 * Therefore in some cases this only examines some of the operands of the
8907 * expression (see comments in the function and examples below).
8909 * f() + 23; // warning, because + has no effect
8910 * x || f(); // no warning, because x controls execution of f()
8911 * x ? y : f(); // warning, because y has no effect
8912 * (void)x; // no warning to be able to suppress the warning
8913 * This function can NOT be used for an "expression has definitely no effect"-
8915 static bool expression_has_effect(const expression_t *const expr)
8917 switch (expr->kind) {
8918 case EXPR_UNKNOWN: break;
8919 case EXPR_INVALID: return true; /* do NOT warn */
8920 case EXPR_REFERENCE: return false;
8921 case EXPR_REFERENCE_ENUM_VALUE: return false;
8922 /* suppress the warning for microsoft __noop operations */
8923 case EXPR_CONST: return expr->conste.is_ms_noop;
8924 case EXPR_CHARACTER_CONSTANT: return false;
8925 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8926 case EXPR_STRING_LITERAL: return false;
8927 case EXPR_WIDE_STRING_LITERAL: return false;
8928 case EXPR_LABEL_ADDRESS: return false;
8931 const call_expression_t *const call = &expr->call;
8932 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8935 switch (call->function->builtin_symbol.symbol->ID) {
8936 case T___builtin_va_end: return true;
8937 default: return false;
8941 /* Generate the warning if either the left or right hand side of a
8942 * conditional expression has no effect */
8943 case EXPR_CONDITIONAL: {
8944 const conditional_expression_t *const cond = &expr->conditional;
8946 expression_has_effect(cond->true_expression) &&
8947 expression_has_effect(cond->false_expression);
8950 case EXPR_SELECT: return false;
8951 case EXPR_ARRAY_ACCESS: return false;
8952 case EXPR_SIZEOF: return false;
8953 case EXPR_CLASSIFY_TYPE: return false;
8954 case EXPR_ALIGNOF: return false;
8956 case EXPR_FUNCNAME: return false;
8957 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8958 case EXPR_BUILTIN_CONSTANT_P: return false;
8959 case EXPR_BUILTIN_PREFETCH: return true;
8960 case EXPR_OFFSETOF: return false;
8961 case EXPR_VA_START: return true;
8962 case EXPR_VA_ARG: return true;
8963 case EXPR_STATEMENT: return true; // TODO
8964 case EXPR_COMPOUND_LITERAL: return false;
8966 case EXPR_UNARY_NEGATE: return false;
8967 case EXPR_UNARY_PLUS: return false;
8968 case EXPR_UNARY_BITWISE_NEGATE: return false;
8969 case EXPR_UNARY_NOT: return false;
8970 case EXPR_UNARY_DEREFERENCE: return false;
8971 case EXPR_UNARY_TAKE_ADDRESS: return false;
8972 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8973 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8974 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8975 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8977 /* Treat void casts as if they have an effect in order to being able to
8978 * suppress the warning */
8979 case EXPR_UNARY_CAST: {
8980 type_t *const type = skip_typeref(expr->base.type);
8981 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8984 case EXPR_UNARY_CAST_IMPLICIT: return true;
8985 case EXPR_UNARY_ASSUME: return true;
8986 case EXPR_UNARY_DELETE: return true;
8987 case EXPR_UNARY_DELETE_ARRAY: return true;
8988 case EXPR_UNARY_THROW: return true;
8990 case EXPR_BINARY_ADD: return false;
8991 case EXPR_BINARY_SUB: return false;
8992 case EXPR_BINARY_MUL: return false;
8993 case EXPR_BINARY_DIV: return false;
8994 case EXPR_BINARY_MOD: return false;
8995 case EXPR_BINARY_EQUAL: return false;
8996 case EXPR_BINARY_NOTEQUAL: return false;
8997 case EXPR_BINARY_LESS: return false;
8998 case EXPR_BINARY_LESSEQUAL: return false;
8999 case EXPR_BINARY_GREATER: return false;
9000 case EXPR_BINARY_GREATEREQUAL: return false;
9001 case EXPR_BINARY_BITWISE_AND: return false;
9002 case EXPR_BINARY_BITWISE_OR: return false;
9003 case EXPR_BINARY_BITWISE_XOR: return false;
9004 case EXPR_BINARY_SHIFTLEFT: return false;
9005 case EXPR_BINARY_SHIFTRIGHT: return false;
9006 case EXPR_BINARY_ASSIGN: return true;
9007 case EXPR_BINARY_MUL_ASSIGN: return true;
9008 case EXPR_BINARY_DIV_ASSIGN: return true;
9009 case EXPR_BINARY_MOD_ASSIGN: return true;
9010 case EXPR_BINARY_ADD_ASSIGN: return true;
9011 case EXPR_BINARY_SUB_ASSIGN: return true;
9012 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
9013 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
9014 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9015 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9016 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
9018 /* Only examine the right hand side of && and ||, because the left hand
9019 * side already has the effect of controlling the execution of the right
9021 case EXPR_BINARY_LOGICAL_AND:
9022 case EXPR_BINARY_LOGICAL_OR:
9023 /* Only examine the right hand side of a comma expression, because the left
9024 * hand side has a separate warning */
9025 case EXPR_BINARY_COMMA:
9026 return expression_has_effect(expr->binary.right);
9028 case EXPR_BINARY_BUILTIN_EXPECT: return true;
9029 case EXPR_BINARY_ISGREATER: return false;
9030 case EXPR_BINARY_ISGREATEREQUAL: return false;
9031 case EXPR_BINARY_ISLESS: return false;
9032 case EXPR_BINARY_ISLESSEQUAL: return false;
9033 case EXPR_BINARY_ISLESSGREATER: return false;
9034 case EXPR_BINARY_ISUNORDERED: return false;
9037 internal_errorf(HERE, "unexpected expression");
9040 static void semantic_comma(binary_expression_t *expression)
9042 if (warning.unused_value) {
9043 const expression_t *const left = expression->left;
9044 if (!expression_has_effect(left)) {
9045 warningf(&left->base.source_position,
9046 "left-hand operand of comma expression has no effect");
9049 expression->base.type = expression->right->base.type;
9053 * @param prec_r precedence of the right operand
9055 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9056 static expression_t *parse_##binexpression_type(expression_t *left) \
9058 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9059 binexpr->binary.left = left; \
9062 expression_t *right = parse_sub_expression(prec_r); \
9064 binexpr->binary.right = right; \
9065 sfunc(&binexpr->binary); \
9070 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9071 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9072 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9073 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9074 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9075 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9076 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9077 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9078 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9079 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9080 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9081 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9082 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9083 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9084 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9085 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9086 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9087 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9088 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9089 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9090 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9091 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9092 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9093 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9094 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9095 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9096 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9097 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9098 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9099 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9102 static expression_t *parse_sub_expression(precedence_t precedence)
9104 if (token.type < 0) {
9105 return expected_expression_error();
9108 expression_parser_function_t *parser
9109 = &expression_parsers[token.type];
9110 source_position_t source_position = token.source_position;
9113 if (parser->parser != NULL) {
9114 left = parser->parser();
9116 left = parse_primary_expression();
9118 assert(left != NULL);
9119 left->base.source_position = source_position;
9122 if (token.type < 0) {
9123 return expected_expression_error();
9126 parser = &expression_parsers[token.type];
9127 if (parser->infix_parser == NULL)
9129 if (parser->infix_precedence < precedence)
9132 left = parser->infix_parser(left);
9134 assert(left != NULL);
9135 assert(left->kind != EXPR_UNKNOWN);
9136 left->base.source_position = source_position;
9143 * Parse an expression.
9145 static expression_t *parse_expression(void)
9147 return parse_sub_expression(PREC_EXPRESSION);
9151 * Register a parser for a prefix-like operator.
9153 * @param parser the parser function
9154 * @param token_type the token type of the prefix token
9156 static void register_expression_parser(parse_expression_function parser,
9159 expression_parser_function_t *entry = &expression_parsers[token_type];
9161 if (entry->parser != NULL) {
9162 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9163 panic("trying to register multiple expression parsers for a token");
9165 entry->parser = parser;
9169 * Register a parser for an infix operator with given precedence.
9171 * @param parser the parser function
9172 * @param token_type the token type of the infix operator
9173 * @param precedence the precedence of the operator
9175 static void register_infix_parser(parse_expression_infix_function parser,
9176 int token_type, unsigned precedence)
9178 expression_parser_function_t *entry = &expression_parsers[token_type];
9180 if (entry->infix_parser != NULL) {
9181 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9182 panic("trying to register multiple infix expression parsers for a "
9185 entry->infix_parser = parser;
9186 entry->infix_precedence = precedence;
9190 * Initialize the expression parsers.
9192 static void init_expression_parsers(void)
9194 memset(&expression_parsers, 0, sizeof(expression_parsers));
9196 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9197 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9198 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9199 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9200 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9201 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9202 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9203 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9204 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9205 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9206 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9207 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9208 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9209 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9210 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9211 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9212 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9213 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9214 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9215 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9216 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9217 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9218 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9219 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9220 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9221 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9222 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9223 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9224 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9225 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9226 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9227 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9228 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9229 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9230 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9231 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9232 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9234 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9235 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9236 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9237 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9238 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9239 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9240 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9241 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9242 register_expression_parser(parse_sizeof, T_sizeof);
9243 register_expression_parser(parse_alignof, T___alignof__);
9244 register_expression_parser(parse_extension, T___extension__);
9245 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9246 register_expression_parser(parse_delete, T_delete);
9247 register_expression_parser(parse_throw, T_throw);
9251 * Parse a asm statement arguments specification.
9253 static asm_argument_t *parse_asm_arguments(bool is_out)
9255 asm_argument_t *result = NULL;
9256 asm_argument_t **anchor = &result;
9258 while (token.type == T_STRING_LITERAL || token.type == '[') {
9259 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9260 memset(argument, 0, sizeof(argument[0]));
9262 if (token.type == '[') {
9264 if (token.type != T_IDENTIFIER) {
9265 parse_error_expected("while parsing asm argument",
9266 T_IDENTIFIER, NULL);
9269 argument->symbol = token.v.symbol;
9274 argument->constraints = parse_string_literals();
9276 add_anchor_token(')');
9277 expression_t *expression = parse_expression();
9278 rem_anchor_token(')');
9280 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9281 * change size or type representation (e.g. int -> long is ok, but
9282 * int -> float is not) */
9283 if (expression->kind == EXPR_UNARY_CAST) {
9284 type_t *const type = expression->base.type;
9285 type_kind_t const kind = type->kind;
9286 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9289 if (kind == TYPE_ATOMIC) {
9290 atomic_type_kind_t const akind = type->atomic.akind;
9291 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9292 size = get_atomic_type_size(akind);
9294 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9295 size = get_atomic_type_size(get_intptr_kind());
9299 expression_t *const value = expression->unary.value;
9300 type_t *const value_type = value->base.type;
9301 type_kind_t const value_kind = value_type->kind;
9303 unsigned value_flags;
9304 unsigned value_size;
9305 if (value_kind == TYPE_ATOMIC) {
9306 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9307 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9308 value_size = get_atomic_type_size(value_akind);
9309 } else if (value_kind == TYPE_POINTER) {
9310 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9311 value_size = get_atomic_type_size(get_intptr_kind());
9316 if (value_flags != flags || value_size != size)
9320 } while (expression->kind == EXPR_UNARY_CAST);
9324 if (!is_lvalue(expression)) {
9325 errorf(&expression->base.source_position,
9326 "asm output argument is not an lvalue");
9329 if (argument->constraints.begin[0] == '+')
9330 mark_vars_read(expression, NULL);
9332 mark_vars_read(expression, NULL);
9334 argument->expression = expression;
9337 set_address_taken(expression, true);
9340 anchor = &argument->next;
9342 if (token.type != ',')
9353 * Parse a asm statement clobber specification.
9355 static asm_clobber_t *parse_asm_clobbers(void)
9357 asm_clobber_t *result = NULL;
9358 asm_clobber_t *last = NULL;
9360 while (token.type == T_STRING_LITERAL) {
9361 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9362 clobber->clobber = parse_string_literals();
9365 last->next = clobber;
9371 if (token.type != ',')
9380 * Parse an asm statement.
9382 static statement_t *parse_asm_statement(void)
9384 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9385 asm_statement_t *asm_statement = &statement->asms;
9389 if (token.type == T_volatile) {
9391 asm_statement->is_volatile = true;
9395 add_anchor_token(')');
9396 add_anchor_token(':');
9397 asm_statement->asm_text = parse_string_literals();
9399 if (token.type != ':') {
9400 rem_anchor_token(':');
9405 asm_statement->outputs = parse_asm_arguments(true);
9406 if (token.type != ':') {
9407 rem_anchor_token(':');
9412 asm_statement->inputs = parse_asm_arguments(false);
9413 if (token.type != ':') {
9414 rem_anchor_token(':');
9417 rem_anchor_token(':');
9420 asm_statement->clobbers = parse_asm_clobbers();
9423 rem_anchor_token(')');
9427 if (asm_statement->outputs == NULL) {
9428 /* GCC: An 'asm' instruction without any output operands will be treated
9429 * identically to a volatile 'asm' instruction. */
9430 asm_statement->is_volatile = true;
9435 return create_invalid_statement();
9439 * Parse a case statement.
9441 static statement_t *parse_case_statement(void)
9443 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9444 source_position_t *const pos = &statement->base.source_position;
9448 expression_t *const expression = parse_expression();
9449 statement->case_label.expression = expression;
9450 if (!is_constant_expression(expression)) {
9451 /* This check does not prevent the error message in all cases of an
9452 * prior error while parsing the expression. At least it catches the
9453 * common case of a mistyped enum entry. */
9454 if (is_type_valid(skip_typeref(expression->base.type))) {
9455 errorf(pos, "case label does not reduce to an integer constant");
9457 statement->case_label.is_bad = true;
9459 long const val = fold_constant(expression);
9460 statement->case_label.first_case = val;
9461 statement->case_label.last_case = val;
9465 if (token.type == T_DOTDOTDOT) {
9467 expression_t *const end_range = parse_expression();
9468 statement->case_label.end_range = end_range;
9469 if (!is_constant_expression(end_range)) {
9470 /* This check does not prevent the error message in all cases of an
9471 * prior error while parsing the expression. At least it catches the
9472 * common case of a mistyped enum entry. */
9473 if (is_type_valid(skip_typeref(end_range->base.type))) {
9474 errorf(pos, "case range does not reduce to an integer constant");
9476 statement->case_label.is_bad = true;
9478 long const val = fold_constant(end_range);
9479 statement->case_label.last_case = val;
9481 if (warning.other && val < statement->case_label.first_case) {
9482 statement->case_label.is_empty_range = true;
9483 warningf(pos, "empty range specified");
9489 PUSH_PARENT(statement);
9493 if (current_switch != NULL) {
9494 if (! statement->case_label.is_bad) {
9495 /* Check for duplicate case values */
9496 case_label_statement_t *c = &statement->case_label;
9497 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9498 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9501 if (c->last_case < l->first_case || c->first_case > l->last_case)
9504 errorf(pos, "duplicate case value (previously used %P)",
9505 &l->base.source_position);
9509 /* link all cases into the switch statement */
9510 if (current_switch->last_case == NULL) {
9511 current_switch->first_case = &statement->case_label;
9513 current_switch->last_case->next = &statement->case_label;
9515 current_switch->last_case = &statement->case_label;
9517 errorf(pos, "case label not within a switch statement");
9520 statement_t *const inner_stmt = parse_statement();
9521 statement->case_label.statement = inner_stmt;
9522 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9523 errorf(&inner_stmt->base.source_position, "declaration after case label");
9530 return create_invalid_statement();
9534 * Parse a default statement.
9536 static statement_t *parse_default_statement(void)
9538 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9542 PUSH_PARENT(statement);
9545 if (current_switch != NULL) {
9546 const case_label_statement_t *def_label = current_switch->default_label;
9547 if (def_label != NULL) {
9548 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9549 &def_label->base.source_position);
9551 current_switch->default_label = &statement->case_label;
9553 /* link all cases into the switch statement */
9554 if (current_switch->last_case == NULL) {
9555 current_switch->first_case = &statement->case_label;
9557 current_switch->last_case->next = &statement->case_label;
9559 current_switch->last_case = &statement->case_label;
9562 errorf(&statement->base.source_position,
9563 "'default' label not within a switch statement");
9566 statement_t *const inner_stmt = parse_statement();
9567 statement->case_label.statement = inner_stmt;
9568 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9569 errorf(&inner_stmt->base.source_position, "declaration after default label");
9576 return create_invalid_statement();
9580 * Parse a label statement.
9582 static statement_t *parse_label_statement(void)
9584 assert(token.type == T_IDENTIFIER);
9585 symbol_t *symbol = token.v.symbol;
9586 label_t *label = get_label(symbol);
9588 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9589 statement->label.label = label;
9593 PUSH_PARENT(statement);
9595 /* if statement is already set then the label is defined twice,
9596 * otherwise it was just mentioned in a goto/local label declaration so far
9598 if (label->statement != NULL) {
9599 errorf(HERE, "duplicate label '%Y' (declared %P)",
9600 symbol, &label->base.source_position);
9602 label->base.source_position = token.source_position;
9603 label->statement = statement;
9608 if (token.type == '}') {
9609 /* TODO only warn? */
9610 if (warning.other && false) {
9611 warningf(HERE, "label at end of compound statement");
9612 statement->label.statement = create_empty_statement();
9614 errorf(HERE, "label at end of compound statement");
9615 statement->label.statement = create_invalid_statement();
9617 } else if (token.type == ';') {
9618 /* Eat an empty statement here, to avoid the warning about an empty
9619 * statement after a label. label:; is commonly used to have a label
9620 * before a closing brace. */
9621 statement->label.statement = create_empty_statement();
9624 statement_t *const inner_stmt = parse_statement();
9625 statement->label.statement = inner_stmt;
9626 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9627 errorf(&inner_stmt->base.source_position, "declaration after label");
9631 /* remember the labels in a list for later checking */
9632 *label_anchor = &statement->label;
9633 label_anchor = &statement->label.next;
9640 * Parse an if statement.
9642 static statement_t *parse_if(void)
9644 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9648 PUSH_PARENT(statement);
9650 add_anchor_token('{');
9653 add_anchor_token(')');
9654 expression_t *const expr = parse_expression();
9655 statement->ifs.condition = expr;
9656 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9658 semantic_condition(expr, "condition of 'if'-statment");
9659 mark_vars_read(expr, NULL);
9660 rem_anchor_token(')');
9664 rem_anchor_token('{');
9666 add_anchor_token(T_else);
9667 statement->ifs.true_statement = parse_statement();
9668 rem_anchor_token(T_else);
9670 if (token.type == T_else) {
9672 statement->ifs.false_statement = parse_statement();
9680 * Check that all enums are handled in a switch.
9682 * @param statement the switch statement to check
9684 static void check_enum_cases(const switch_statement_t *statement) {
9685 const type_t *type = skip_typeref(statement->expression->base.type);
9686 if (! is_type_enum(type))
9688 const enum_type_t *enumt = &type->enumt;
9690 /* if we have a default, no warnings */
9691 if (statement->default_label != NULL)
9694 /* FIXME: calculation of value should be done while parsing */
9695 /* TODO: quadratic algorithm here. Change to an n log n one */
9696 long last_value = -1;
9697 const entity_t *entry = enumt->enume->base.next;
9698 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9699 entry = entry->base.next) {
9700 const expression_t *expression = entry->enum_value.value;
9701 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9703 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9704 if (l->expression == NULL)
9706 if (l->first_case <= value && value <= l->last_case) {
9712 warningf(&statement->base.source_position,
9713 "enumeration value '%Y' not handled in switch",
9714 entry->base.symbol);
9721 * Parse a switch statement.
9723 static statement_t *parse_switch(void)
9725 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9729 PUSH_PARENT(statement);
9732 add_anchor_token(')');
9733 expression_t *const expr = parse_expression();
9734 mark_vars_read(expr, NULL);
9735 type_t * type = skip_typeref(expr->base.type);
9736 if (is_type_integer(type)) {
9737 type = promote_integer(type);
9738 if (warning.traditional) {
9739 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9740 warningf(&expr->base.source_position,
9741 "'%T' switch expression not converted to '%T' in ISO C",
9745 } else if (is_type_valid(type)) {
9746 errorf(&expr->base.source_position,
9747 "switch quantity is not an integer, but '%T'", type);
9748 type = type_error_type;
9750 statement->switchs.expression = create_implicit_cast(expr, type);
9752 rem_anchor_token(')');
9754 switch_statement_t *rem = current_switch;
9755 current_switch = &statement->switchs;
9756 statement->switchs.body = parse_statement();
9757 current_switch = rem;
9759 if (warning.switch_default &&
9760 statement->switchs.default_label == NULL) {
9761 warningf(&statement->base.source_position, "switch has no default case");
9763 if (warning.switch_enum)
9764 check_enum_cases(&statement->switchs);
9770 return create_invalid_statement();
9773 static statement_t *parse_loop_body(statement_t *const loop)
9775 statement_t *const rem = current_loop;
9776 current_loop = loop;
9778 statement_t *const body = parse_statement();
9785 * Parse a while statement.
9787 static statement_t *parse_while(void)
9789 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9793 PUSH_PARENT(statement);
9796 add_anchor_token(')');
9797 expression_t *const cond = parse_expression();
9798 statement->whiles.condition = cond;
9799 /* §6.8.5:2 The controlling expression of an iteration statement shall
9800 * have scalar type. */
9801 semantic_condition(cond, "condition of 'while'-statement");
9802 mark_vars_read(cond, NULL);
9803 rem_anchor_token(')');
9806 statement->whiles.body = parse_loop_body(statement);
9812 return create_invalid_statement();
9816 * Parse a do statement.
9818 static statement_t *parse_do(void)
9820 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9824 PUSH_PARENT(statement);
9826 add_anchor_token(T_while);
9827 statement->do_while.body = parse_loop_body(statement);
9828 rem_anchor_token(T_while);
9832 add_anchor_token(')');
9833 expression_t *const cond = parse_expression();
9834 statement->do_while.condition = cond;
9835 /* §6.8.5:2 The controlling expression of an iteration statement shall
9836 * have scalar type. */
9837 semantic_condition(cond, "condition of 'do-while'-statement");
9838 mark_vars_read(cond, NULL);
9839 rem_anchor_token(')');
9847 return create_invalid_statement();
9851 * Parse a for statement.
9853 static statement_t *parse_for(void)
9855 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9859 PUSH_PARENT(statement);
9861 size_t const top = environment_top();
9862 scope_push(&statement->fors.scope);
9865 add_anchor_token(')');
9867 if (token.type == ';') {
9869 } else if (is_declaration_specifier(&token, false)) {
9870 parse_declaration(record_entity);
9872 add_anchor_token(';');
9873 expression_t *const init = parse_expression();
9874 statement->fors.initialisation = init;
9875 mark_vars_read(init, VAR_ANY);
9876 if (warning.unused_value && !expression_has_effect(init)) {
9877 warningf(&init->base.source_position,
9878 "initialisation of 'for'-statement has no effect");
9880 rem_anchor_token(';');
9884 if (token.type != ';') {
9885 add_anchor_token(';');
9886 expression_t *const cond = parse_expression();
9887 statement->fors.condition = cond;
9888 /* §6.8.5:2 The controlling expression of an iteration statement shall
9889 * have scalar type. */
9890 semantic_condition(cond, "condition of 'for'-statement");
9891 mark_vars_read(cond, NULL);
9892 rem_anchor_token(';');
9895 if (token.type != ')') {
9896 expression_t *const step = parse_expression();
9897 statement->fors.step = step;
9898 mark_vars_read(step, VAR_ANY);
9899 if (warning.unused_value && !expression_has_effect(step)) {
9900 warningf(&step->base.source_position,
9901 "step of 'for'-statement has no effect");
9905 rem_anchor_token(')');
9906 statement->fors.body = parse_loop_body(statement);
9908 assert(current_scope == &statement->fors.scope);
9910 environment_pop_to(top);
9917 rem_anchor_token(')');
9918 assert(current_scope == &statement->fors.scope);
9920 environment_pop_to(top);
9922 return create_invalid_statement();
9926 * Parse a goto statement.
9928 static statement_t *parse_goto(void)
9930 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9933 if (GNU_MODE && token.type == '*') {
9935 expression_t *expression = parse_expression();
9936 mark_vars_read(expression, NULL);
9938 /* Argh: although documentation says the expression must be of type void*,
9939 * gcc accepts anything that can be casted into void* without error */
9940 type_t *type = expression->base.type;
9942 if (type != type_error_type) {
9943 if (!is_type_pointer(type) && !is_type_integer(type)) {
9944 errorf(&expression->base.source_position,
9945 "cannot convert to a pointer type");
9946 } else if (warning.other && type != type_void_ptr) {
9947 warningf(&expression->base.source_position,
9948 "type of computed goto expression should be 'void*' not '%T'", type);
9950 expression = create_implicit_cast(expression, type_void_ptr);
9953 statement->gotos.expression = expression;
9955 if (token.type != T_IDENTIFIER) {
9957 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9959 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9963 symbol_t *symbol = token.v.symbol;
9966 statement->gotos.label = get_label(symbol);
9969 /* remember the goto's in a list for later checking */
9970 *goto_anchor = &statement->gotos;
9971 goto_anchor = &statement->gotos.next;
9977 return create_invalid_statement();
9981 * Parse a continue statement.
9983 static statement_t *parse_continue(void)
9985 if (current_loop == NULL) {
9986 errorf(HERE, "continue statement not within loop");
9989 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9999 * Parse a break statement.
10001 static statement_t *parse_break(void)
10003 if (current_switch == NULL && current_loop == NULL) {
10004 errorf(HERE, "break statement not within loop or switch");
10007 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10017 * Parse a __leave statement.
10019 static statement_t *parse_leave_statement(void)
10021 if (current_try == NULL) {
10022 errorf(HERE, "__leave statement not within __try");
10025 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10035 * Check if a given entity represents a local variable.
10037 static bool is_local_variable(const entity_t *entity)
10039 if (entity->kind != ENTITY_VARIABLE)
10042 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10043 case STORAGE_CLASS_AUTO:
10044 case STORAGE_CLASS_REGISTER: {
10045 const type_t *type = skip_typeref(entity->declaration.type);
10046 if (is_type_function(type)) {
10058 * Check if a given expression represents a local variable.
10060 static bool expression_is_local_variable(const expression_t *expression)
10062 if (expression->base.kind != EXPR_REFERENCE) {
10065 const entity_t *entity = expression->reference.entity;
10066 return is_local_variable(entity);
10070 * Check if a given expression represents a local variable and
10071 * return its declaration then, else return NULL.
10073 entity_t *expression_is_variable(const expression_t *expression)
10075 if (expression->base.kind != EXPR_REFERENCE) {
10078 entity_t *entity = expression->reference.entity;
10079 if (entity->kind != ENTITY_VARIABLE)
10086 * Parse a return statement.
10088 static statement_t *parse_return(void)
10092 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10094 expression_t *return_value = NULL;
10095 if (token.type != ';') {
10096 return_value = parse_expression();
10097 mark_vars_read(return_value, NULL);
10100 const type_t *const func_type = skip_typeref(current_function->base.type);
10101 assert(is_type_function(func_type));
10102 type_t *const return_type = skip_typeref(func_type->function.return_type);
10104 if (return_value != NULL) {
10105 type_t *return_value_type = skip_typeref(return_value->base.type);
10107 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID) &&
10108 !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10109 if (warning.other) {
10110 warningf(&statement->base.source_position,
10111 "'return' with a value, in function returning void");
10113 return_value = NULL;
10115 assign_error_t error = semantic_assign(return_type, return_value);
10116 report_assign_error(error, return_type, return_value, "'return'",
10117 &statement->base.source_position);
10118 return_value = create_implicit_cast(return_value, return_type);
10120 /* check for returning address of a local var */
10121 if (warning.other && return_value != NULL
10122 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10123 const expression_t *expression = return_value->unary.value;
10124 if (expression_is_local_variable(expression)) {
10125 warningf(&statement->base.source_position,
10126 "function returns address of local variable");
10129 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10130 warningf(&statement->base.source_position,
10131 "'return' without value, in function returning non-void");
10133 statement->returns.value = return_value;
10142 * Parse a declaration statement.
10144 static statement_t *parse_declaration_statement(void)
10146 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10148 entity_t *before = current_scope->last_entity;
10150 parse_external_declaration();
10152 parse_declaration(record_entity);
10154 if (before == NULL) {
10155 statement->declaration.declarations_begin = current_scope->entities;
10157 statement->declaration.declarations_begin = before->base.next;
10159 statement->declaration.declarations_end = current_scope->last_entity;
10165 * Parse an expression statement, ie. expr ';'.
10167 static statement_t *parse_expression_statement(void)
10169 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10171 expression_t *const expr = parse_expression();
10172 statement->expression.expression = expr;
10173 mark_vars_read(expr, VAR_ANY);
10182 * Parse a microsoft __try { } __finally { } or
10183 * __try{ } __except() { }
10185 static statement_t *parse_ms_try_statment(void)
10187 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10190 PUSH_PARENT(statement);
10192 ms_try_statement_t *rem = current_try;
10193 current_try = &statement->ms_try;
10194 statement->ms_try.try_statement = parse_compound_statement(false);
10199 if (token.type == T___except) {
10202 add_anchor_token(')');
10203 expression_t *const expr = parse_expression();
10204 mark_vars_read(expr, NULL);
10205 type_t * type = skip_typeref(expr->base.type);
10206 if (is_type_integer(type)) {
10207 type = promote_integer(type);
10208 } else if (is_type_valid(type)) {
10209 errorf(&expr->base.source_position,
10210 "__expect expression is not an integer, but '%T'", type);
10211 type = type_error_type;
10213 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10214 rem_anchor_token(')');
10216 statement->ms_try.final_statement = parse_compound_statement(false);
10217 } else if (token.type == T__finally) {
10219 statement->ms_try.final_statement = parse_compound_statement(false);
10221 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10222 return create_invalid_statement();
10226 return create_invalid_statement();
10229 static statement_t *parse_empty_statement(void)
10231 if (warning.empty_statement) {
10232 warningf(HERE, "statement is empty");
10234 statement_t *const statement = create_empty_statement();
10239 static statement_t *parse_local_label_declaration(void)
10241 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10245 entity_t *begin = NULL, *end = NULL;
10248 if (token.type != T_IDENTIFIER) {
10249 parse_error_expected("while parsing local label declaration",
10250 T_IDENTIFIER, NULL);
10253 symbol_t *symbol = token.v.symbol;
10254 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10255 if (entity != NULL && entity->base.parent_scope == current_scope) {
10256 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10257 symbol, &entity->base.source_position);
10259 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10261 entity->base.parent_scope = current_scope;
10262 entity->base.namespc = NAMESPACE_LABEL;
10263 entity->base.source_position = token.source_position;
10264 entity->base.symbol = symbol;
10267 end->base.next = entity;
10272 environment_push(entity);
10276 if (token.type != ',')
10282 statement->declaration.declarations_begin = begin;
10283 statement->declaration.declarations_end = end;
10287 static void parse_namespace_definition(void)
10291 entity_t *entity = NULL;
10292 symbol_t *symbol = NULL;
10294 if (token.type == T_IDENTIFIER) {
10295 symbol = token.v.symbol;
10298 entity = get_entity(symbol, NAMESPACE_NORMAL);
10299 if (entity != NULL && entity->kind != ENTITY_NAMESPACE
10300 && entity->base.parent_scope == current_scope) {
10301 error_redefined_as_different_kind(&token.source_position,
10302 entity, ENTITY_NAMESPACE);
10307 if (entity == NULL) {
10308 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10309 entity->base.symbol = symbol;
10310 entity->base.source_position = token.source_position;
10311 entity->base.namespc = NAMESPACE_NORMAL;
10312 entity->base.parent_scope = current_scope;
10315 if (token.type == '=') {
10316 /* TODO: parse namespace alias */
10317 panic("namespace alias definition not supported yet");
10320 environment_push(entity);
10321 append_entity(current_scope, entity);
10323 size_t const top = environment_top();
10324 scope_push(&entity->namespacee.members);
10331 assert(current_scope == &entity->namespacee.members);
10333 environment_pop_to(top);
10337 * Parse a statement.
10338 * There's also parse_statement() which additionally checks for
10339 * "statement has no effect" warnings
10341 static statement_t *intern_parse_statement(void)
10343 statement_t *statement = NULL;
10345 /* declaration or statement */
10346 add_anchor_token(';');
10347 switch (token.type) {
10348 case T_IDENTIFIER: {
10349 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10350 if (la1_type == ':') {
10351 statement = parse_label_statement();
10352 } else if (is_typedef_symbol(token.v.symbol)) {
10353 statement = parse_declaration_statement();
10355 /* it's an identifier, the grammar says this must be an
10356 * expression statement. However it is common that users mistype
10357 * declaration types, so we guess a bit here to improve robustness
10358 * for incorrect programs */
10359 switch (la1_type) {
10362 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10363 goto expression_statment;
10368 statement = parse_declaration_statement();
10372 expression_statment:
10373 statement = parse_expression_statement();
10380 case T___extension__:
10381 /* This can be a prefix to a declaration or an expression statement.
10382 * We simply eat it now and parse the rest with tail recursion. */
10385 } while (token.type == T___extension__);
10386 bool old_gcc_extension = in_gcc_extension;
10387 in_gcc_extension = true;
10388 statement = intern_parse_statement();
10389 in_gcc_extension = old_gcc_extension;
10393 statement = parse_declaration_statement();
10397 statement = parse_local_label_declaration();
10400 case ';': statement = parse_empty_statement(); break;
10401 case '{': statement = parse_compound_statement(false); break;
10402 case T___leave: statement = parse_leave_statement(); break;
10403 case T___try: statement = parse_ms_try_statment(); break;
10404 case T_asm: statement = parse_asm_statement(); break;
10405 case T_break: statement = parse_break(); break;
10406 case T_case: statement = parse_case_statement(); break;
10407 case T_continue: statement = parse_continue(); break;
10408 case T_default: statement = parse_default_statement(); break;
10409 case T_do: statement = parse_do(); break;
10410 case T_for: statement = parse_for(); break;
10411 case T_goto: statement = parse_goto(); break;
10412 case T_if: statement = parse_if(); break;
10413 case T_return: statement = parse_return(); break;
10414 case T_switch: statement = parse_switch(); break;
10415 case T_while: statement = parse_while(); break;
10418 statement = parse_expression_statement();
10422 errorf(HERE, "unexpected token %K while parsing statement", &token);
10423 statement = create_invalid_statement();
10428 rem_anchor_token(';');
10430 assert(statement != NULL
10431 && statement->base.source_position.input_name != NULL);
10437 * parse a statement and emits "statement has no effect" warning if needed
10438 * (This is really a wrapper around intern_parse_statement with check for 1
10439 * single warning. It is needed, because for statement expressions we have
10440 * to avoid the warning on the last statement)
10442 static statement_t *parse_statement(void)
10444 statement_t *statement = intern_parse_statement();
10446 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10447 expression_t *expression = statement->expression.expression;
10448 if (!expression_has_effect(expression)) {
10449 warningf(&expression->base.source_position,
10450 "statement has no effect");
10458 * Parse a compound statement.
10460 static statement_t *parse_compound_statement(bool inside_expression_statement)
10462 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10464 PUSH_PARENT(statement);
10467 add_anchor_token('}');
10469 size_t const top = environment_top();
10470 scope_push(&statement->compound.scope);
10472 statement_t **anchor = &statement->compound.statements;
10473 bool only_decls_so_far = true;
10474 while (token.type != '}') {
10475 if (token.type == T_EOF) {
10476 errorf(&statement->base.source_position,
10477 "EOF while parsing compound statement");
10480 statement_t *sub_statement = intern_parse_statement();
10481 if (is_invalid_statement(sub_statement)) {
10482 /* an error occurred. if we are at an anchor, return */
10488 if (warning.declaration_after_statement) {
10489 if (sub_statement->kind != STATEMENT_DECLARATION) {
10490 only_decls_so_far = false;
10491 } else if (!only_decls_so_far) {
10492 warningf(&sub_statement->base.source_position,
10493 "ISO C90 forbids mixed declarations and code");
10497 *anchor = sub_statement;
10499 while (sub_statement->base.next != NULL)
10500 sub_statement = sub_statement->base.next;
10502 anchor = &sub_statement->base.next;
10506 /* look over all statements again to produce no effect warnings */
10507 if (warning.unused_value) {
10508 statement_t *sub_statement = statement->compound.statements;
10509 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10510 if (sub_statement->kind != STATEMENT_EXPRESSION)
10512 /* don't emit a warning for the last expression in an expression
10513 * statement as it has always an effect */
10514 if (inside_expression_statement && sub_statement->base.next == NULL)
10517 expression_t *expression = sub_statement->expression.expression;
10518 if (!expression_has_effect(expression)) {
10519 warningf(&expression->base.source_position,
10520 "statement has no effect");
10526 rem_anchor_token('}');
10527 assert(current_scope == &statement->compound.scope);
10529 environment_pop_to(top);
10536 * Check for unused global static functions and variables
10538 static void check_unused_globals(void)
10540 if (!warning.unused_function && !warning.unused_variable)
10543 for (const entity_t *entity = file_scope->entities; entity != NULL;
10544 entity = entity->base.next) {
10545 if (!is_declaration(entity))
10548 const declaration_t *declaration = &entity->declaration;
10549 if (declaration->used ||
10550 declaration->modifiers & DM_UNUSED ||
10551 declaration->modifiers & DM_USED ||
10552 declaration->storage_class != STORAGE_CLASS_STATIC)
10555 type_t *const type = declaration->type;
10557 if (entity->kind == ENTITY_FUNCTION) {
10558 /* inhibit warning for static inline functions */
10559 if (entity->function.is_inline)
10562 s = entity->function.statement != NULL ? "defined" : "declared";
10567 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10568 type, declaration->base.symbol, s);
10572 static void parse_global_asm(void)
10574 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10579 statement->asms.asm_text = parse_string_literals();
10580 statement->base.next = unit->global_asm;
10581 unit->global_asm = statement;
10589 static void parse_linkage_specification(void)
10592 assert(token.type == T_STRING_LITERAL);
10594 const char *linkage = parse_string_literals().begin;
10596 linkage_kind_t old_linkage = current_linkage;
10597 linkage_kind_t new_linkage;
10598 if (strcmp(linkage, "C") == 0) {
10599 new_linkage = LINKAGE_C;
10600 } else if (strcmp(linkage, "C++") == 0) {
10601 new_linkage = LINKAGE_CXX;
10603 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10604 new_linkage = LINKAGE_INVALID;
10606 current_linkage = new_linkage;
10608 if (token.type == '{') {
10617 assert(current_linkage == new_linkage);
10618 current_linkage = old_linkage;
10621 static void parse_external(void)
10623 switch (token.type) {
10624 DECLARATION_START_NO_EXTERN
10626 case T___extension__:
10627 case '(': /* for function declarations with implicit return type and
10628 * parenthesized declarator, i.e. (f)(void); */
10629 parse_external_declaration();
10633 if (look_ahead(1)->type == T_STRING_LITERAL) {
10634 parse_linkage_specification();
10636 parse_external_declaration();
10641 parse_global_asm();
10645 parse_namespace_definition();
10649 if (!strict_mode) {
10651 warningf(HERE, "stray ';' outside of function");
10658 errorf(HERE, "stray %K outside of function", &token);
10659 if (token.type == '(' || token.type == '{' || token.type == '[')
10660 eat_until_matching_token(token.type);
10666 static void parse_externals(void)
10668 add_anchor_token('}');
10669 add_anchor_token(T_EOF);
10672 unsigned char token_anchor_copy[T_LAST_TOKEN];
10673 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10676 while (token.type != T_EOF && token.type != '}') {
10678 bool anchor_leak = false;
10679 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10680 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10682 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10683 anchor_leak = true;
10686 if (in_gcc_extension) {
10687 errorf(HERE, "Leaked __extension__");
10688 anchor_leak = true;
10698 rem_anchor_token(T_EOF);
10699 rem_anchor_token('}');
10703 * Parse a translation unit.
10705 static void parse_translation_unit(void)
10707 add_anchor_token(T_EOF);
10712 if (token.type == T_EOF)
10715 errorf(HERE, "stray %K outside of function", &token);
10716 if (token.type == '(' || token.type == '{' || token.type == '[')
10717 eat_until_matching_token(token.type);
10725 * @return the translation unit or NULL if errors occurred.
10727 void start_parsing(void)
10729 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10730 label_stack = NEW_ARR_F(stack_entry_t, 0);
10731 diagnostic_count = 0;
10735 type_set_output(stderr);
10736 ast_set_output(stderr);
10738 assert(unit == NULL);
10739 unit = allocate_ast_zero(sizeof(unit[0]));
10741 assert(file_scope == NULL);
10742 file_scope = &unit->scope;
10744 assert(current_scope == NULL);
10745 scope_push(&unit->scope);
10748 translation_unit_t *finish_parsing(void)
10750 /* do NOT use scope_pop() here, this will crash, will it by hand */
10751 assert(current_scope == &unit->scope);
10752 current_scope = NULL;
10754 assert(file_scope == &unit->scope);
10755 check_unused_globals();
10758 DEL_ARR_F(environment_stack);
10759 DEL_ARR_F(label_stack);
10761 translation_unit_t *result = unit;
10768 lookahead_bufpos = 0;
10769 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10772 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10773 parse_translation_unit();
10777 * Initialize the parser.
10779 void init_parser(void)
10781 sym_anonymous = symbol_table_insert("<anonymous>");
10783 if (c_mode & _MS) {
10784 /* add predefined symbols for extended-decl-modifier */
10785 sym_align = symbol_table_insert("align");
10786 sym_allocate = symbol_table_insert("allocate");
10787 sym_dllimport = symbol_table_insert("dllimport");
10788 sym_dllexport = symbol_table_insert("dllexport");
10789 sym_naked = symbol_table_insert("naked");
10790 sym_noinline = symbol_table_insert("noinline");
10791 sym_noreturn = symbol_table_insert("noreturn");
10792 sym_nothrow = symbol_table_insert("nothrow");
10793 sym_novtable = symbol_table_insert("novtable");
10794 sym_property = symbol_table_insert("property");
10795 sym_get = symbol_table_insert("get");
10796 sym_put = symbol_table_insert("put");
10797 sym_selectany = symbol_table_insert("selectany");
10798 sym_thread = symbol_table_insert("thread");
10799 sym_uuid = symbol_table_insert("uuid");
10800 sym_deprecated = symbol_table_insert("deprecated");
10801 sym_restrict = symbol_table_insert("restrict");
10802 sym_noalias = symbol_table_insert("noalias");
10804 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10806 init_expression_parsers();
10807 obstack_init(&temp_obst);
10809 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10810 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10814 * Terminate the parser.
10816 void exit_parser(void)
10818 obstack_free(&temp_obst, NULL);