2 * This file is part of cparser.
3 * Copyright (C) 2007-2008 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
37 #include "lang_features.h"
38 #include "walk_statements.h"
40 #include "adt/bitfiddle.h"
41 #include "adt/error.h"
42 #include "adt/array.h"
44 //#define PRINT_TOKENS
45 #define MAX_LOOKAHEAD 2
50 entity_namespace_t namespc;
53 typedef struct argument_list_t argument_list_t;
54 struct argument_list_t {
56 argument_list_t *next;
59 typedef struct gnu_attribute_t gnu_attribute_t;
60 struct gnu_attribute_t {
61 gnu_attribute_kind_t kind; /**< The kind of the GNU attribute. */
62 gnu_attribute_t *next;
63 bool invalid; /**< Set if this attribute had argument errors, */
64 bool have_arguments; /**< True, if this attribute has arguments. */
68 atomic_type_kind_t akind;
69 long argument; /**< Single argument. */
70 argument_list_t *arguments; /**< List of argument expressions. */
74 typedef struct declaration_specifiers_t declaration_specifiers_t;
75 struct declaration_specifiers_t {
76 source_position_t source_position;
77 storage_class_t storage_class;
78 unsigned char alignment; /**< Alignment, 0 if not set. */
80 bool thread_local : 1; /**< GCC __thread */
82 decl_modifiers_t modifiers; /**< declaration modifiers */
83 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
84 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
85 symbol_t *get_property_sym; /**< the name of the get property if set. */
86 symbol_t *put_property_sym; /**< the name of the put property if set. */
91 * An environment for parsing initializers (and compound literals).
93 typedef struct parse_initializer_env_t {
94 type_t *type; /**< the type of the initializer. In case of an
95 array type with unspecified size this gets
96 adjusted to the actual size. */
97 entity_t *entity; /**< the variable that is initialized if any */
98 bool must_be_constant;
99 } parse_initializer_env_t;
102 * Capture a MS __base extension.
104 typedef struct based_spec_t {
105 source_position_t source_position;
106 variable_t *base_variable;
109 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
111 /** The current token. */
112 static token_t token;
113 /** The lookahead ring-buffer. */
114 static token_t lookahead_buffer[MAX_LOOKAHEAD];
115 /** Position of the next token in the lookahead buffer. */
116 static int lookahead_bufpos;
117 static stack_entry_t *environment_stack = NULL;
118 static stack_entry_t *label_stack = NULL;
119 static scope_t *file_scope = NULL;
120 static scope_t *current_scope = NULL;
121 /** Point to the current function declaration if inside a function. */
122 static function_t *current_function = NULL;
123 static entity_t *current_init_decl = NULL;
124 static switch_statement_t *current_switch = NULL;
125 static statement_t *current_loop = NULL;
126 static statement_t *current_parent = NULL;
127 static ms_try_statement_t *current_try = NULL;
128 static linkage_kind_t current_linkage = LINKAGE_INVALID;
129 static goto_statement_t *goto_first = NULL;
130 static goto_statement_t **goto_anchor = NULL;
131 static label_statement_t *label_first = NULL;
132 static label_statement_t **label_anchor = NULL;
133 /** current translation unit. */
134 static translation_unit_t *unit = NULL;
135 /** true if we are in a type property context (evaluation only for type. */
136 static bool in_type_prop = false;
137 /** true in we are in a __extension__ context. */
138 static bool in_gcc_extension = false;
139 static struct obstack temp_obst;
140 static entity_t *anonymous_entity;
143 #define PUSH_PARENT(stmt) \
144 statement_t *const prev_parent = current_parent; \
145 ((void)(current_parent = (stmt)))
146 #define POP_PARENT ((void)(current_parent = prev_parent))
148 /** special symbol used for anonymous entities. */
149 static const symbol_t *sym_anonymous = NULL;
151 /* symbols for Microsoft extended-decl-modifier */
152 static const symbol_t *sym_align = NULL;
153 static const symbol_t *sym_allocate = NULL;
154 static const symbol_t *sym_dllimport = NULL;
155 static const symbol_t *sym_dllexport = NULL;
156 static const symbol_t *sym_naked = NULL;
157 static const symbol_t *sym_noinline = NULL;
158 static const symbol_t *sym_noreturn = NULL;
159 static const symbol_t *sym_nothrow = NULL;
160 static const symbol_t *sym_novtable = NULL;
161 static const symbol_t *sym_property = NULL;
162 static const symbol_t *sym_get = NULL;
163 static const symbol_t *sym_put = NULL;
164 static const symbol_t *sym_selectany = NULL;
165 static const symbol_t *sym_thread = NULL;
166 static const symbol_t *sym_uuid = NULL;
167 static const symbol_t *sym_deprecated = NULL;
168 static const symbol_t *sym_restrict = NULL;
169 static const symbol_t *sym_noalias = NULL;
171 /** The token anchor set */
172 static unsigned char token_anchor_set[T_LAST_TOKEN];
174 /** The current source position. */
175 #define HERE (&token.source_position)
177 /** true if we are in GCC mode. */
178 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
180 static type_t *type_valist;
182 static statement_t *parse_compound_statement(bool inside_expression_statement);
183 static statement_t *parse_statement(void);
185 static expression_t *parse_sub_expression(precedence_t);
186 static expression_t *parse_expression(void);
187 static type_t *parse_typename(void);
188 static void parse_externals(void);
189 static void parse_external(void);
191 static void parse_compound_type_entries(compound_t *compound_declaration);
193 typedef enum declarator_flags_t {
195 DECL_MAY_BE_ABSTRACT = 1U << 0,
196 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
197 DECL_IS_PARAMETER = 1U << 2
198 } declarator_flags_t;
200 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
201 declarator_flags_t flags);
203 static entity_t *record_entity(entity_t *entity, bool is_definition);
205 static void semantic_comparison(binary_expression_t *expression);
207 #define STORAGE_CLASSES \
208 STORAGE_CLASSES_NO_EXTERN \
211 #define STORAGE_CLASSES_NO_EXTERN \
218 #define TYPE_QUALIFIERS \
223 case T__forceinline: \
224 case T___attribute__:
226 #define COMPLEX_SPECIFIERS \
228 #define IMAGINARY_SPECIFIERS \
231 #define TYPE_SPECIFIERS \
233 case T___builtin_va_list: \
252 #define DECLARATION_START \
257 #define DECLARATION_START_NO_EXTERN \
258 STORAGE_CLASSES_NO_EXTERN \
262 #define TYPENAME_START \
266 #define EXPRESSION_START \
275 case T_CHARACTER_CONSTANT: \
276 case T_FLOATINGPOINT: \
280 case T_STRING_LITERAL: \
281 case T_WIDE_CHARACTER_CONSTANT: \
282 case T_WIDE_STRING_LITERAL: \
283 case T___FUNCDNAME__: \
284 case T___FUNCSIG__: \
285 case T___FUNCTION__: \
286 case T___PRETTY_FUNCTION__: \
287 case T___alignof__: \
288 case T___builtin_alloca: \
289 case T___builtin_classify_type: \
290 case T___builtin_constant_p: \
291 case T___builtin_expect: \
292 case T___builtin_huge_val: \
293 case T___builtin_inf: \
294 case T___builtin_inff: \
295 case T___builtin_infl: \
296 case T___builtin_isgreater: \
297 case T___builtin_isgreaterequal: \
298 case T___builtin_isless: \
299 case T___builtin_islessequal: \
300 case T___builtin_islessgreater: \
301 case T___builtin_isunordered: \
302 case T___builtin_nan: \
303 case T___builtin_nanf: \
304 case T___builtin_nanl: \
305 case T___builtin_offsetof: \
306 case T___builtin_prefetch: \
307 case T___builtin_va_arg: \
308 case T___builtin_va_end: \
309 case T___builtin_va_start: \
320 * Allocate an AST node with given size and
321 * initialize all fields with zero.
323 static void *allocate_ast_zero(size_t size)
325 void *res = allocate_ast(size);
326 memset(res, 0, size);
330 static size_t get_entity_struct_size(entity_kind_t kind)
332 static const size_t sizes[] = {
333 [ENTITY_VARIABLE] = sizeof(variable_t),
334 [ENTITY_COMPOUND_MEMBER] = sizeof(variable_t),
335 [ENTITY_FUNCTION] = sizeof(function_t),
336 [ENTITY_TYPEDEF] = sizeof(typedef_t),
337 [ENTITY_STRUCT] = sizeof(compound_t),
338 [ENTITY_UNION] = sizeof(compound_t),
339 [ENTITY_ENUM] = sizeof(enum_t),
340 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
341 [ENTITY_LABEL] = sizeof(label_t),
342 [ENTITY_LOCAL_LABEL] = sizeof(label_t),
343 [ENTITY_NAMESPACE] = sizeof(namespace_t)
345 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
346 assert(sizes[kind] != 0);
350 static entity_t *allocate_entity_zero(entity_kind_t kind)
352 size_t size = get_entity_struct_size(kind);
353 entity_t *entity = allocate_ast_zero(size);
359 * Returns the size of a statement node.
361 * @param kind the statement kind
363 static size_t get_statement_struct_size(statement_kind_t kind)
365 static const size_t sizes[] = {
366 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
367 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
368 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
369 [STATEMENT_RETURN] = sizeof(return_statement_t),
370 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
371 [STATEMENT_LOCAL_LABEL] = sizeof(local_label_statement_t),
372 [STATEMENT_IF] = sizeof(if_statement_t),
373 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
374 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
375 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
376 [STATEMENT_BREAK] = sizeof(statement_base_t),
377 [STATEMENT_GOTO] = sizeof(goto_statement_t),
378 [STATEMENT_LABEL] = sizeof(label_statement_t),
379 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
380 [STATEMENT_WHILE] = sizeof(while_statement_t),
381 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
382 [STATEMENT_FOR] = sizeof(for_statement_t),
383 [STATEMENT_ASM] = sizeof(asm_statement_t),
384 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
385 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
387 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
388 assert(sizes[kind] != 0);
393 * Returns the size of an expression node.
395 * @param kind the expression kind
397 static size_t get_expression_struct_size(expression_kind_t kind)
399 static const size_t sizes[] = {
400 [EXPR_INVALID] = sizeof(expression_base_t),
401 [EXPR_REFERENCE] = sizeof(reference_expression_t),
402 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
403 [EXPR_CONST] = sizeof(const_expression_t),
404 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
405 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
406 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
407 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
408 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
409 [EXPR_CALL] = sizeof(call_expression_t),
410 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
411 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
412 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
413 [EXPR_SELECT] = sizeof(select_expression_t),
414 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
415 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
416 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
417 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
418 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
419 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
420 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
421 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
422 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
423 [EXPR_VA_START] = sizeof(va_start_expression_t),
424 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
425 [EXPR_STATEMENT] = sizeof(statement_expression_t),
426 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
428 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
429 return sizes[EXPR_UNARY_FIRST];
431 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
432 return sizes[EXPR_BINARY_FIRST];
434 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
435 assert(sizes[kind] != 0);
440 * Allocate a statement node of given kind and initialize all
443 static statement_t *allocate_statement_zero(statement_kind_t kind)
445 size_t size = get_statement_struct_size(kind);
446 statement_t *res = allocate_ast_zero(size);
448 res->base.kind = kind;
449 res->base.parent = current_parent;
450 res->base.source_position = token.source_position;
455 * Allocate an expression node of given kind and initialize all
458 static expression_t *allocate_expression_zero(expression_kind_t kind)
460 size_t size = get_expression_struct_size(kind);
461 expression_t *res = allocate_ast_zero(size);
463 res->base.kind = kind;
464 res->base.type = type_error_type;
465 res->base.source_position = token.source_position;
470 * Creates a new invalid expression.
472 static expression_t *create_invalid_expression(void)
474 return allocate_expression_zero(EXPR_INVALID);
478 * Creates a new invalid statement.
480 static statement_t *create_invalid_statement(void)
482 return allocate_statement_zero(STATEMENT_INVALID);
486 * Allocate a new empty statement.
488 static statement_t *create_empty_statement(void)
490 return allocate_statement_zero(STATEMENT_EMPTY);
494 * Returns the size of a type node.
496 * @param kind the type kind
498 static size_t get_type_struct_size(type_kind_t kind)
500 static const size_t sizes[] = {
501 [TYPE_ATOMIC] = sizeof(atomic_type_t),
502 [TYPE_COMPLEX] = sizeof(complex_type_t),
503 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
504 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
505 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
506 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
507 [TYPE_ENUM] = sizeof(enum_type_t),
508 [TYPE_FUNCTION] = sizeof(function_type_t),
509 [TYPE_POINTER] = sizeof(pointer_type_t),
510 [TYPE_ARRAY] = sizeof(array_type_t),
511 [TYPE_BUILTIN] = sizeof(builtin_type_t),
512 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
513 [TYPE_TYPEOF] = sizeof(typeof_type_t),
515 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
516 assert(kind <= TYPE_TYPEOF);
517 assert(sizes[kind] != 0);
522 * Allocate a type node of given kind and initialize all
525 * @param kind type kind to allocate
527 static type_t *allocate_type_zero(type_kind_t kind)
529 size_t size = get_type_struct_size(kind);
530 type_t *res = obstack_alloc(type_obst, size);
531 memset(res, 0, size);
532 res->base.kind = kind;
538 * Returns the size of an initializer node.
540 * @param kind the initializer kind
542 static size_t get_initializer_size(initializer_kind_t kind)
544 static const size_t sizes[] = {
545 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
546 [INITIALIZER_STRING] = sizeof(initializer_string_t),
547 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
548 [INITIALIZER_LIST] = sizeof(initializer_list_t),
549 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
551 assert(kind < sizeof(sizes) / sizeof(*sizes));
552 assert(sizes[kind] != 0);
557 * Allocate an initializer node of given kind and initialize all
560 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
562 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
569 * Free a type from the type obstack.
571 static void free_type(void *type)
573 obstack_free(type_obst, type);
577 * Returns the index of the top element of the environment stack.
579 static size_t environment_top(void)
581 return ARR_LEN(environment_stack);
585 * Returns the index of the top element of the global label stack.
587 static size_t label_top(void)
589 return ARR_LEN(label_stack);
593 * Return the next token.
595 static inline void next_token(void)
597 token = lookahead_buffer[lookahead_bufpos];
598 lookahead_buffer[lookahead_bufpos] = lexer_token;
601 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
604 print_token(stderr, &token);
605 fprintf(stderr, "\n");
610 * Return the next token with a given lookahead.
612 static inline const token_t *look_ahead(int num)
614 assert(num > 0 && num <= MAX_LOOKAHEAD);
615 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
616 return &lookahead_buffer[pos];
620 * Adds a token to the token anchor set (a multi-set).
622 static void add_anchor_token(int token_type)
624 assert(0 <= token_type && token_type < T_LAST_TOKEN);
625 ++token_anchor_set[token_type];
628 static int save_and_reset_anchor_state(int token_type)
630 assert(0 <= token_type && token_type < T_LAST_TOKEN);
631 int count = token_anchor_set[token_type];
632 token_anchor_set[token_type] = 0;
636 static void restore_anchor_state(int token_type, int count)
638 assert(0 <= token_type && token_type < T_LAST_TOKEN);
639 token_anchor_set[token_type] = count;
643 * Remove a token from the token anchor set (a multi-set).
645 static void rem_anchor_token(int token_type)
647 assert(0 <= token_type && token_type < T_LAST_TOKEN);
648 assert(token_anchor_set[token_type] != 0);
649 --token_anchor_set[token_type];
652 static bool at_anchor(void)
656 return token_anchor_set[token.type];
660 * Eat tokens until a matching token is found.
662 static void eat_until_matching_token(int type)
666 case '(': end_token = ')'; break;
667 case '{': end_token = '}'; break;
668 case '[': end_token = ']'; break;
669 default: end_token = type; break;
672 unsigned parenthesis_count = 0;
673 unsigned brace_count = 0;
674 unsigned bracket_count = 0;
675 while (token.type != end_token ||
676 parenthesis_count != 0 ||
678 bracket_count != 0) {
679 switch (token.type) {
681 case '(': ++parenthesis_count; break;
682 case '{': ++brace_count; break;
683 case '[': ++bracket_count; break;
686 if (parenthesis_count > 0)
696 if (bracket_count > 0)
699 if (token.type == end_token &&
700 parenthesis_count == 0 &&
714 * Eat input tokens until an anchor is found.
716 static void eat_until_anchor(void)
718 while (token_anchor_set[token.type] == 0) {
719 if (token.type == '(' || token.type == '{' || token.type == '[')
720 eat_until_matching_token(token.type);
725 static void eat_block(void)
727 eat_until_matching_token('{');
728 if (token.type == '}')
732 #define eat(token_type) do { assert(token.type == (token_type)); next_token(); } while (0)
735 * Report a parse error because an expected token was not found.
738 #if defined __GNUC__ && __GNUC__ >= 4
739 __attribute__((sentinel))
741 void parse_error_expected(const char *message, ...)
743 if (message != NULL) {
744 errorf(HERE, "%s", message);
747 va_start(ap, message);
748 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
753 * Report an incompatible type.
755 static void type_error_incompatible(const char *msg,
756 const source_position_t *source_position, type_t *type1, type_t *type2)
758 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
763 * Expect the the current token is the expected token.
764 * If not, generate an error, eat the current statement,
765 * and goto the end_error label.
767 #define expect(expected) \
769 if (UNLIKELY(token.type != (expected))) { \
770 parse_error_expected(NULL, (expected), NULL); \
771 add_anchor_token(expected); \
772 eat_until_anchor(); \
773 if (token.type == expected) \
775 rem_anchor_token(expected); \
781 static void scope_push(scope_t *new_scope)
783 if (current_scope != NULL) {
784 new_scope->depth = current_scope->depth + 1;
786 new_scope->parent = current_scope;
787 current_scope = new_scope;
790 static void scope_pop(void)
792 current_scope = current_scope->parent;
796 * Search an entity by its symbol in a given namespace.
798 static entity_t *get_entity(const symbol_t *const symbol,
799 namespace_tag_t namespc)
801 entity_t *entity = symbol->entity;
802 for (; entity != NULL; entity = entity->base.symbol_next) {
803 if (entity->base.namespc == namespc)
811 * pushs an entity on the environment stack and links the corresponding symbol
814 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
816 symbol_t *symbol = entity->base.symbol;
817 entity_namespace_t namespc = entity->base.namespc;
818 assert(namespc != NAMESPACE_INVALID);
820 /* replace/add entity into entity list of the symbol */
823 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
828 /* replace an entry? */
829 if (iter->base.namespc == namespc) {
830 entity->base.symbol_next = iter->base.symbol_next;
836 /* remember old declaration */
838 entry.symbol = symbol;
839 entry.old_entity = iter;
840 entry.namespc = namespc;
841 ARR_APP1(stack_entry_t, *stack_ptr, entry);
845 * Push an entity on the environment stack.
847 static void environment_push(entity_t *entity)
849 assert(entity->base.source_position.input_name != NULL);
850 assert(entity->base.parent_scope != NULL);
851 stack_push(&environment_stack, entity);
855 * Push a declaration on the global label stack.
857 * @param declaration the declaration
859 static void label_push(entity_t *label)
861 /* we abuse the parameters scope as parent for the labels */
862 label->base.parent_scope = ¤t_function->parameters;
863 stack_push(&label_stack, label);
867 * pops symbols from the environment stack until @p new_top is the top element
869 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
871 stack_entry_t *stack = *stack_ptr;
872 size_t top = ARR_LEN(stack);
875 assert(new_top <= top);
879 for (i = top; i > new_top; --i) {
880 stack_entry_t *entry = &stack[i - 1];
882 entity_t *old_entity = entry->old_entity;
883 symbol_t *symbol = entry->symbol;
884 entity_namespace_t namespc = entry->namespc;
886 /* replace with old_entity/remove */
889 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
891 assert(iter != NULL);
892 /* replace an entry? */
893 if (iter->base.namespc == namespc)
897 /* restore definition from outer scopes (if there was one) */
898 if (old_entity != NULL) {
899 old_entity->base.symbol_next = iter->base.symbol_next;
900 *anchor = old_entity;
902 /* remove entry from list */
903 *anchor = iter->base.symbol_next;
907 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
911 * Pop all entries from the environment stack until the new_top
914 * @param new_top the new stack top
916 static void environment_pop_to(size_t new_top)
918 stack_pop_to(&environment_stack, new_top);
922 * Pop all entries from the global label stack until the new_top
925 * @param new_top the new stack top
927 static void label_pop_to(size_t new_top)
929 stack_pop_to(&label_stack, new_top);
932 static int get_akind_rank(atomic_type_kind_t akind)
937 static int get_rank(const type_t *type)
939 assert(!is_typeref(type));
940 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
941 * and esp. footnote 108). However we can't fold constants (yet), so we
942 * can't decide whether unsigned int is possible, while int always works.
943 * (unsigned int would be preferable when possible... for stuff like
944 * struct { enum { ... } bla : 4; } ) */
945 if (type->kind == TYPE_ENUM)
946 return get_akind_rank(ATOMIC_TYPE_INT);
948 assert(type->kind == TYPE_ATOMIC);
949 return get_akind_rank(type->atomic.akind);
952 static type_t *promote_integer(type_t *type)
954 if (type->kind == TYPE_BITFIELD)
955 type = type->bitfield.base_type;
957 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
964 * Create a cast expression.
966 * @param expression the expression to cast
967 * @param dest_type the destination type
969 static expression_t *create_cast_expression(expression_t *expression,
972 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
974 cast->unary.value = expression;
975 cast->base.type = dest_type;
981 * Check if a given expression represents the 0 pointer constant.
983 static bool is_null_pointer_constant(const expression_t *expression)
985 /* skip void* cast */
986 if (expression->kind == EXPR_UNARY_CAST
987 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
988 expression = expression->unary.value;
991 /* TODO: not correct yet, should be any constant integer expression
992 * which evaluates to 0 */
993 if (expression->kind != EXPR_CONST)
996 type_t *const type = skip_typeref(expression->base.type);
997 if (!is_type_integer(type))
1000 return expression->conste.v.int_value == 0;
1004 * Create an implicit cast expression.
1006 * @param expression the expression to cast
1007 * @param dest_type the destination type
1009 static expression_t *create_implicit_cast(expression_t *expression,
1012 type_t *const source_type = expression->base.type;
1014 if (source_type == dest_type)
1017 return create_cast_expression(expression, dest_type);
1020 typedef enum assign_error_t {
1022 ASSIGN_ERROR_INCOMPATIBLE,
1023 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1024 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1025 ASSIGN_WARNING_POINTER_FROM_INT,
1026 ASSIGN_WARNING_INT_FROM_POINTER
1029 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1030 const expression_t *const right,
1031 const char *context,
1032 const source_position_t *source_position)
1034 type_t *const orig_type_right = right->base.type;
1035 type_t *const type_left = skip_typeref(orig_type_left);
1036 type_t *const type_right = skip_typeref(orig_type_right);
1039 case ASSIGN_SUCCESS:
1041 case ASSIGN_ERROR_INCOMPATIBLE:
1042 errorf(source_position,
1043 "destination type '%T' in %s is incompatible with type '%T'",
1044 orig_type_left, context, orig_type_right);
1047 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1048 if (warning.other) {
1049 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1050 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1052 /* the left type has all qualifiers from the right type */
1053 unsigned missing_qualifiers
1054 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1055 warningf(source_position,
1056 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1057 orig_type_left, context, orig_type_right, missing_qualifiers);
1062 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1063 if (warning.other) {
1064 warningf(source_position,
1065 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1066 orig_type_left, context, right, orig_type_right);
1070 case ASSIGN_WARNING_POINTER_FROM_INT:
1071 if (warning.other) {
1072 warningf(source_position,
1073 "%s makes pointer '%T' from integer '%T' without a cast",
1074 context, orig_type_left, orig_type_right);
1078 case ASSIGN_WARNING_INT_FROM_POINTER:
1079 if (warning.other) {
1080 warningf(source_position,
1081 "%s makes integer '%T' from pointer '%T' without a cast",
1082 context, orig_type_left, orig_type_right);
1087 panic("invalid error value");
1091 /** Implements the rules from § 6.5.16.1 */
1092 static assign_error_t semantic_assign(type_t *orig_type_left,
1093 const expression_t *const right)
1095 type_t *const orig_type_right = right->base.type;
1096 type_t *const type_left = skip_typeref(orig_type_left);
1097 type_t *const type_right = skip_typeref(orig_type_right);
1099 if (is_type_pointer(type_left)) {
1100 if (is_null_pointer_constant(right)) {
1101 return ASSIGN_SUCCESS;
1102 } else if (is_type_pointer(type_right)) {
1103 type_t *points_to_left
1104 = skip_typeref(type_left->pointer.points_to);
1105 type_t *points_to_right
1106 = skip_typeref(type_right->pointer.points_to);
1107 assign_error_t res = ASSIGN_SUCCESS;
1109 /* the left type has all qualifiers from the right type */
1110 unsigned missing_qualifiers
1111 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1112 if (missing_qualifiers != 0) {
1113 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1116 points_to_left = get_unqualified_type(points_to_left);
1117 points_to_right = get_unqualified_type(points_to_right);
1119 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1122 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1123 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1124 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1127 if (!types_compatible(points_to_left, points_to_right)) {
1128 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1132 } else if (is_type_integer(type_right)) {
1133 return ASSIGN_WARNING_POINTER_FROM_INT;
1135 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1136 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1137 && is_type_pointer(type_right))) {
1138 return ASSIGN_SUCCESS;
1139 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1140 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1141 type_t *const unqual_type_left = get_unqualified_type(type_left);
1142 type_t *const unqual_type_right = get_unqualified_type(type_right);
1143 if (types_compatible(unqual_type_left, unqual_type_right)) {
1144 return ASSIGN_SUCCESS;
1146 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1147 return ASSIGN_WARNING_INT_FROM_POINTER;
1150 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1151 return ASSIGN_SUCCESS;
1153 return ASSIGN_ERROR_INCOMPATIBLE;
1156 static expression_t *parse_constant_expression(void)
1158 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1160 if (!is_constant_expression(result)) {
1161 errorf(&result->base.source_position,
1162 "expression '%E' is not constant\n", result);
1168 static expression_t *parse_assignment_expression(void)
1170 return parse_sub_expression(PREC_ASSIGNMENT);
1173 static string_t parse_string_literals(void)
1175 assert(token.type == T_STRING_LITERAL);
1176 string_t result = token.v.string;
1180 while (token.type == T_STRING_LITERAL) {
1181 result = concat_strings(&result, &token.v.string);
1188 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1189 [GNU_AK_CONST] = "const",
1190 [GNU_AK_VOLATILE] = "volatile",
1191 [GNU_AK_CDECL] = "cdecl",
1192 [GNU_AK_STDCALL] = "stdcall",
1193 [GNU_AK_FASTCALL] = "fastcall",
1194 [GNU_AK_DEPRECATED] = "deprecated",
1195 [GNU_AK_NOINLINE] = "noinline",
1196 [GNU_AK_NORETURN] = "noreturn",
1197 [GNU_AK_NAKED] = "naked",
1198 [GNU_AK_PURE] = "pure",
1199 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1200 [GNU_AK_MALLOC] = "malloc",
1201 [GNU_AK_WEAK] = "weak",
1202 [GNU_AK_CONSTRUCTOR] = "constructor",
1203 [GNU_AK_DESTRUCTOR] = "destructor",
1204 [GNU_AK_NOTHROW] = "nothrow",
1205 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1206 [GNU_AK_COMMON] = "common",
1207 [GNU_AK_NOCOMMON] = "nocommon",
1208 [GNU_AK_PACKED] = "packed",
1209 [GNU_AK_SHARED] = "shared",
1210 [GNU_AK_NOTSHARED] = "notshared",
1211 [GNU_AK_USED] = "used",
1212 [GNU_AK_UNUSED] = "unused",
1213 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1214 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1215 [GNU_AK_LONGCALL] = "longcall",
1216 [GNU_AK_SHORTCALL] = "shortcall",
1217 [GNU_AK_LONG_CALL] = "long_call",
1218 [GNU_AK_SHORT_CALL] = "short_call",
1219 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1220 [GNU_AK_INTERRUPT] = "interrupt",
1221 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1222 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1223 [GNU_AK_NESTING] = "nesting",
1224 [GNU_AK_NEAR] = "near",
1225 [GNU_AK_FAR] = "far",
1226 [GNU_AK_SIGNAL] = "signal",
1227 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1228 [GNU_AK_TINY_DATA] = "tiny_data",
1229 [GNU_AK_SAVEALL] = "saveall",
1230 [GNU_AK_FLATTEN] = "flatten",
1231 [GNU_AK_SSEREGPARM] = "sseregparm",
1232 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1233 [GNU_AK_RETURN_TWICE] = "return_twice",
1234 [GNU_AK_MAY_ALIAS] = "may_alias",
1235 [GNU_AK_MS_STRUCT] = "ms_struct",
1236 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1237 [GNU_AK_DLLIMPORT] = "dllimport",
1238 [GNU_AK_DLLEXPORT] = "dllexport",
1239 [GNU_AK_ALIGNED] = "aligned",
1240 [GNU_AK_ALIAS] = "alias",
1241 [GNU_AK_SECTION] = "section",
1242 [GNU_AK_FORMAT] = "format",
1243 [GNU_AK_FORMAT_ARG] = "format_arg",
1244 [GNU_AK_WEAKREF] = "weakref",
1245 [GNU_AK_NONNULL] = "nonnull",
1246 [GNU_AK_TLS_MODEL] = "tls_model",
1247 [GNU_AK_VISIBILITY] = "visibility",
1248 [GNU_AK_REGPARM] = "regparm",
1249 [GNU_AK_MODE] = "mode",
1250 [GNU_AK_MODEL] = "model",
1251 [GNU_AK_TRAP_EXIT] = "trap_exit",
1252 [GNU_AK_SP_SWITCH] = "sp_switch",
1253 [GNU_AK_SENTINEL] = "sentinel"
1257 * compare two string, ignoring double underscores on the second.
1259 static int strcmp_underscore(const char *s1, const char *s2)
1261 if (s2[0] == '_' && s2[1] == '_') {
1262 size_t len2 = strlen(s2);
1263 size_t len1 = strlen(s1);
1264 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1265 return strncmp(s1, s2+2, len2-4);
1269 return strcmp(s1, s2);
1273 * Allocate a new gnu temporal attribute.
1275 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1277 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1278 attribute->kind = kind;
1279 attribute->next = NULL;
1280 attribute->invalid = false;
1281 attribute->have_arguments = false;
1287 * parse one constant expression argument.
1289 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1291 expression_t *expression;
1292 add_anchor_token(')');
1293 expression = parse_constant_expression();
1294 rem_anchor_token(')');
1296 attribute->u.argument = fold_constant(expression);
1299 attribute->invalid = true;
1303 * parse a list of constant expressions arguments.
1305 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1307 argument_list_t **list = &attribute->u.arguments;
1308 argument_list_t *entry;
1309 expression_t *expression;
1310 add_anchor_token(')');
1311 add_anchor_token(',');
1313 expression = parse_constant_expression();
1314 entry = obstack_alloc(&temp_obst, sizeof(entry));
1315 entry->argument = fold_constant(expression);
1318 list = &entry->next;
1319 if (token.type != ',')
1323 rem_anchor_token(',');
1324 rem_anchor_token(')');
1328 attribute->invalid = true;
1332 * parse one string literal argument.
1334 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1337 add_anchor_token('(');
1338 if (token.type != T_STRING_LITERAL) {
1339 parse_error_expected("while parsing attribute directive",
1340 T_STRING_LITERAL, NULL);
1343 *string = parse_string_literals();
1344 rem_anchor_token('(');
1348 attribute->invalid = true;
1352 * parse one tls model.
1354 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1356 static const char *const tls_models[] = {
1362 string_t string = { NULL, 0 };
1363 parse_gnu_attribute_string_arg(attribute, &string);
1364 if (string.begin != NULL) {
1365 for (size_t i = 0; i < 4; ++i) {
1366 if (strcmp(tls_models[i], string.begin) == 0) {
1367 attribute->u.value = i;
1371 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1373 attribute->invalid = true;
1377 * parse one tls model.
1379 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1381 static const char *const visibilities[] = {
1387 string_t string = { NULL, 0 };
1388 parse_gnu_attribute_string_arg(attribute, &string);
1389 if (string.begin != NULL) {
1390 for (size_t i = 0; i < 4; ++i) {
1391 if (strcmp(visibilities[i], string.begin) == 0) {
1392 attribute->u.value = i;
1396 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1398 attribute->invalid = true;
1402 * parse one (code) model.
1404 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1406 static const char *const visibilities[] = {
1411 string_t string = { NULL, 0 };
1412 parse_gnu_attribute_string_arg(attribute, &string);
1413 if (string.begin != NULL) {
1414 for (int i = 0; i < 3; ++i) {
1415 if (strcmp(visibilities[i], string.begin) == 0) {
1416 attribute->u.value = i;
1420 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1422 attribute->invalid = true;
1425 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1427 /* TODO: find out what is allowed here... */
1429 /* at least: byte, word, pointer, list of machine modes
1430 * __XXX___ is interpreted as XXX */
1431 add_anchor_token(')');
1433 if (token.type != T_IDENTIFIER) {
1434 expect(T_IDENTIFIER);
1437 /* This isn't really correct, the backend should provide a list of machine
1438 * specific modes (according to gcc philosophy that is...) */
1439 const char *symbol_str = token.v.symbol->string;
1440 if (strcmp_underscore("QI", symbol_str) == 0 ||
1441 strcmp_underscore("byte", symbol_str) == 0) {
1442 attribute->u.akind = ATOMIC_TYPE_CHAR;
1443 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1444 attribute->u.akind = ATOMIC_TYPE_SHORT;
1445 } else if (strcmp_underscore("SI", symbol_str) == 0
1446 || strcmp_underscore("word", symbol_str) == 0
1447 || strcmp_underscore("pointer", symbol_str) == 0) {
1448 attribute->u.akind = ATOMIC_TYPE_INT;
1449 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1450 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1453 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1454 attribute->invalid = true;
1458 rem_anchor_token(')');
1462 attribute->invalid = true;
1466 * parse one interrupt argument.
1468 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1470 static const char *const interrupts[] = {
1477 string_t string = { NULL, 0 };
1478 parse_gnu_attribute_string_arg(attribute, &string);
1479 if (string.begin != NULL) {
1480 for (size_t i = 0; i < 5; ++i) {
1481 if (strcmp(interrupts[i], string.begin) == 0) {
1482 attribute->u.value = i;
1486 errorf(HERE, "'%s' is not an interrupt", string.begin);
1488 attribute->invalid = true;
1492 * parse ( identifier, const expression, const expression )
1494 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1496 static const char *const format_names[] = {
1504 if (token.type != T_IDENTIFIER) {
1505 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1508 const char *name = token.v.symbol->string;
1509 for (i = 0; i < 4; ++i) {
1510 if (strcmp_underscore(format_names[i], name) == 0)
1514 if (warning.attribute)
1515 warningf(HERE, "'%s' is an unrecognized format function type", name);
1520 add_anchor_token(')');
1521 add_anchor_token(',');
1522 parse_constant_expression();
1523 rem_anchor_token(',');
1524 rem_anchor_token(')');
1527 add_anchor_token(')');
1528 parse_constant_expression();
1529 rem_anchor_token(')');
1533 attribute->u.value = true;
1536 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1538 if (!attribute->have_arguments)
1541 /* should have no arguments */
1542 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1543 eat_until_matching_token('(');
1544 /* we have already consumed '(', so we stop before ')', eat it */
1546 attribute->invalid = true;
1550 * Parse one GNU attribute.
1552 * Note that attribute names can be specified WITH or WITHOUT
1553 * double underscores, ie const or __const__.
1555 * The following attributes are parsed without arguments
1580 * no_instrument_function
1581 * warn_unused_result
1598 * externally_visible
1606 * The following attributes are parsed with arguments
1607 * aligned( const expression )
1608 * alias( string literal )
1609 * section( string literal )
1610 * format( identifier, const expression, const expression )
1611 * format_arg( const expression )
1612 * tls_model( string literal )
1613 * visibility( string literal )
1614 * regparm( const expression )
1615 * model( string leteral )
1616 * trap_exit( const expression )
1617 * sp_switch( string literal )
1619 * The following attributes might have arguments
1620 * weak_ref( string literal )
1621 * non_null( const expression // ',' )
1622 * interrupt( string literal )
1623 * sentinel( constant expression )
1625 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1627 gnu_attribute_t *head = *attributes;
1628 gnu_attribute_t *last = *attributes;
1629 decl_modifiers_t modifiers = 0;
1630 gnu_attribute_t *attribute;
1632 eat(T___attribute__);
1636 if (token.type != ')') {
1637 /* find the end of the list */
1639 while (last->next != NULL)
1643 /* non-empty attribute list */
1646 if (token.type == T_const) {
1648 } else if (token.type == T_volatile) {
1650 } else if (token.type == T_cdecl) {
1651 /* __attribute__((cdecl)), WITH ms mode */
1653 } else if (token.type == T_IDENTIFIER) {
1654 const symbol_t *sym = token.v.symbol;
1657 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1664 for (i = 0; i < GNU_AK_LAST; ++i) {
1665 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1668 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1671 if (kind == GNU_AK_LAST) {
1672 if (warning.attribute)
1673 warningf(HERE, "'%s' attribute directive ignored", name);
1675 /* skip possible arguments */
1676 if (token.type == '(') {
1677 eat_until_matching_token(')');
1680 /* check for arguments */
1681 attribute = allocate_gnu_attribute(kind);
1682 if (token.type == '(') {
1684 if (token.type == ')') {
1685 /* empty args are allowed */
1688 attribute->have_arguments = true;
1692 case GNU_AK_VOLATILE:
1697 case GNU_AK_NOCOMMON:
1699 case GNU_AK_NOTSHARED:
1700 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1701 case GNU_AK_WARN_UNUSED_RESULT:
1702 case GNU_AK_LONGCALL:
1703 case GNU_AK_SHORTCALL:
1704 case GNU_AK_LONG_CALL:
1705 case GNU_AK_SHORT_CALL:
1706 case GNU_AK_FUNCTION_VECTOR:
1707 case GNU_AK_INTERRUPT_HANDLER:
1708 case GNU_AK_NMI_HANDLER:
1709 case GNU_AK_NESTING:
1713 case GNU_AK_EIGTHBIT_DATA:
1714 case GNU_AK_TINY_DATA:
1715 case GNU_AK_SAVEALL:
1716 case GNU_AK_FLATTEN:
1717 case GNU_AK_SSEREGPARM:
1718 case GNU_AK_EXTERNALLY_VISIBLE:
1719 case GNU_AK_RETURN_TWICE:
1720 case GNU_AK_MAY_ALIAS:
1721 case GNU_AK_MS_STRUCT:
1722 case GNU_AK_GCC_STRUCT:
1725 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1726 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1727 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1728 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1729 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1730 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1731 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1732 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1733 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1734 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1735 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1736 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1737 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1738 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1739 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1740 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1741 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1742 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1744 case GNU_AK_ALIGNED:
1745 /* __align__ may be used without an argument */
1746 if (attribute->have_arguments) {
1747 parse_gnu_attribute_const_arg(attribute);
1751 case GNU_AK_FORMAT_ARG:
1752 case GNU_AK_REGPARM:
1753 case GNU_AK_TRAP_EXIT:
1754 if (!attribute->have_arguments) {
1755 /* should have arguments */
1756 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1757 attribute->invalid = true;
1759 parse_gnu_attribute_const_arg(attribute);
1762 case GNU_AK_SECTION:
1763 case GNU_AK_SP_SWITCH:
1764 if (!attribute->have_arguments) {
1765 /* should have arguments */
1766 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1767 attribute->invalid = true;
1769 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1772 if (!attribute->have_arguments) {
1773 /* should have arguments */
1774 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1775 attribute->invalid = true;
1777 parse_gnu_attribute_format_args(attribute);
1779 case GNU_AK_WEAKREF:
1780 /* may have one string argument */
1781 if (attribute->have_arguments)
1782 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1784 case GNU_AK_NONNULL:
1785 if (attribute->have_arguments)
1786 parse_gnu_attribute_const_arg_list(attribute);
1788 case GNU_AK_TLS_MODEL:
1789 if (!attribute->have_arguments) {
1790 /* should have arguments */
1791 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1793 parse_gnu_attribute_tls_model_arg(attribute);
1795 case GNU_AK_VISIBILITY:
1796 if (!attribute->have_arguments) {
1797 /* should have arguments */
1798 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1800 parse_gnu_attribute_visibility_arg(attribute);
1803 if (!attribute->have_arguments) {
1804 /* should have arguments */
1805 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1807 parse_gnu_attribute_model_arg(attribute);
1811 if (!attribute->have_arguments) {
1812 /* should have arguments */
1813 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1815 parse_gnu_attribute_mode_arg(attribute);
1818 case GNU_AK_INTERRUPT:
1819 /* may have one string argument */
1820 if (attribute->have_arguments)
1821 parse_gnu_attribute_interrupt_arg(attribute);
1823 case GNU_AK_SENTINEL:
1824 /* may have one string argument */
1825 if (attribute->have_arguments)
1826 parse_gnu_attribute_const_arg(attribute);
1829 /* already handled */
1833 check_no_argument(attribute, name);
1836 if (attribute != NULL) {
1838 last->next = attribute;
1841 head = last = attribute;
1845 if (token.type != ',')
1859 * Parse GNU attributes.
1861 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1863 decl_modifiers_t modifiers = 0;
1866 switch (token.type) {
1867 case T___attribute__:
1868 modifiers |= parse_gnu_attribute(attributes);
1874 if (token.type != T_STRING_LITERAL) {
1875 parse_error_expected("while parsing assembler attribute",
1876 T_STRING_LITERAL, NULL);
1877 eat_until_matching_token('(');
1880 parse_string_literals();
1885 case T_cdecl: modifiers |= DM_CDECL; break;
1886 case T__fastcall: modifiers |= DM_FASTCALL; break;
1887 case T__stdcall: modifiers |= DM_STDCALL; break;
1890 /* TODO record modifier */
1892 warningf(HERE, "Ignoring declaration modifier %K", &token);
1896 default: return modifiers;
1903 static void mark_vars_read(expression_t *expr, variable_t *lhs_var);
1905 static variable_t *determine_lhs_var(expression_t *const expr,
1906 variable_t *lhs_var)
1908 switch (expr->kind) {
1909 case EXPR_REFERENCE: {
1910 entity_t *const entity = expr->reference.entity;
1911 /* we should only find variables as lavlues... */
1912 if (entity->base.kind != ENTITY_VARIABLE)
1915 return &entity->variable;
1918 case EXPR_ARRAY_ACCESS: {
1919 expression_t *const ref = expr->array_access.array_ref;
1920 variable_t * var = NULL;
1921 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1922 var = determine_lhs_var(ref, lhs_var);
1925 mark_vars_read(expr->select.compound, lhs_var);
1927 mark_vars_read(expr->array_access.index, lhs_var);
1932 if (is_type_compound(skip_typeref(expr->base.type))) {
1933 return determine_lhs_var(expr->select.compound, lhs_var);
1935 mark_vars_read(expr->select.compound, lhs_var);
1940 case EXPR_UNARY_DEREFERENCE: {
1941 expression_t *const val = expr->unary.value;
1942 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1944 return determine_lhs_var(val->unary.value, lhs_var);
1946 mark_vars_read(val, NULL);
1952 mark_vars_read(expr, NULL);
1957 #define VAR_ANY ((variable_t*)-1)
1960 * Mark declarations, which are read. This is used to deted variables, which
1964 * x is not marked as "read", because it is only read to calculate its own new
1968 * x and y are not detected as "not read", because multiple variables are
1971 static void mark_vars_read(expression_t *const expr, variable_t *lhs_var)
1973 switch (expr->kind) {
1974 case EXPR_REFERENCE: {
1975 entity_t *const entity = expr->reference.entity;
1976 if (entity->kind != ENTITY_VARIABLE)
1979 variable_t *variable = &entity->variable;
1980 if (lhs_var != variable && lhs_var != VAR_ANY) {
1981 variable->read = true;
1987 // TODO respect pure/const
1988 mark_vars_read(expr->call.function, NULL);
1989 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1990 mark_vars_read(arg->expression, NULL);
1994 case EXPR_CONDITIONAL:
1995 // TODO lhs_decl should depend on whether true/false have an effect
1996 mark_vars_read(expr->conditional.condition, NULL);
1997 if (expr->conditional.true_expression != NULL)
1998 mark_vars_read(expr->conditional.true_expression, lhs_var);
1999 mark_vars_read(expr->conditional.false_expression, lhs_var);
2003 if (lhs_var == VAR_ANY && !is_type_compound(skip_typeref(expr->base.type)))
2005 mark_vars_read(expr->select.compound, lhs_var);
2008 case EXPR_ARRAY_ACCESS: {
2009 expression_t *const ref = expr->array_access.array_ref;
2010 mark_vars_read(ref, lhs_var);
2011 lhs_var = determine_lhs_var(ref, lhs_var);
2012 mark_vars_read(expr->array_access.index, lhs_var);
2017 mark_vars_read(expr->va_arge.ap, lhs_var);
2020 case EXPR_UNARY_CAST:
2021 /* Special case: Use void cast to mark a variable as "read" */
2022 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2027 case EXPR_UNARY_THROW:
2028 if (expr->unary.value == NULL)
2031 case EXPR_UNARY_DEREFERENCE:
2032 case EXPR_UNARY_DELETE:
2033 case EXPR_UNARY_DELETE_ARRAY:
2034 if (lhs_var == VAR_ANY)
2038 case EXPR_UNARY_NEGATE:
2039 case EXPR_UNARY_PLUS:
2040 case EXPR_UNARY_BITWISE_NEGATE:
2041 case EXPR_UNARY_NOT:
2042 case EXPR_UNARY_TAKE_ADDRESS:
2043 case EXPR_UNARY_POSTFIX_INCREMENT:
2044 case EXPR_UNARY_POSTFIX_DECREMENT:
2045 case EXPR_UNARY_PREFIX_INCREMENT:
2046 case EXPR_UNARY_PREFIX_DECREMENT:
2047 case EXPR_UNARY_CAST_IMPLICIT:
2048 case EXPR_UNARY_ASSUME:
2050 mark_vars_read(expr->unary.value, lhs_var);
2053 case EXPR_BINARY_ADD:
2054 case EXPR_BINARY_SUB:
2055 case EXPR_BINARY_MUL:
2056 case EXPR_BINARY_DIV:
2057 case EXPR_BINARY_MOD:
2058 case EXPR_BINARY_EQUAL:
2059 case EXPR_BINARY_NOTEQUAL:
2060 case EXPR_BINARY_LESS:
2061 case EXPR_BINARY_LESSEQUAL:
2062 case EXPR_BINARY_GREATER:
2063 case EXPR_BINARY_GREATEREQUAL:
2064 case EXPR_BINARY_BITWISE_AND:
2065 case EXPR_BINARY_BITWISE_OR:
2066 case EXPR_BINARY_BITWISE_XOR:
2067 case EXPR_BINARY_LOGICAL_AND:
2068 case EXPR_BINARY_LOGICAL_OR:
2069 case EXPR_BINARY_SHIFTLEFT:
2070 case EXPR_BINARY_SHIFTRIGHT:
2071 case EXPR_BINARY_COMMA:
2072 case EXPR_BINARY_ISGREATER:
2073 case EXPR_BINARY_ISGREATEREQUAL:
2074 case EXPR_BINARY_ISLESS:
2075 case EXPR_BINARY_ISLESSEQUAL:
2076 case EXPR_BINARY_ISLESSGREATER:
2077 case EXPR_BINARY_ISUNORDERED:
2078 mark_vars_read(expr->binary.left, lhs_var);
2079 mark_vars_read(expr->binary.right, lhs_var);
2082 case EXPR_BINARY_ASSIGN:
2083 case EXPR_BINARY_MUL_ASSIGN:
2084 case EXPR_BINARY_DIV_ASSIGN:
2085 case EXPR_BINARY_MOD_ASSIGN:
2086 case EXPR_BINARY_ADD_ASSIGN:
2087 case EXPR_BINARY_SUB_ASSIGN:
2088 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2089 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2090 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2091 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2092 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2093 if (lhs_var == VAR_ANY)
2095 lhs_var = determine_lhs_var(expr->binary.left, lhs_var);
2096 mark_vars_read(expr->binary.right, lhs_var);
2101 determine_lhs_var(expr->va_starte.ap, lhs_var);
2107 case EXPR_CHARACTER_CONSTANT:
2108 case EXPR_WIDE_CHARACTER_CONSTANT:
2109 case EXPR_STRING_LITERAL:
2110 case EXPR_WIDE_STRING_LITERAL:
2111 case EXPR_COMPOUND_LITERAL: // TODO init?
2113 case EXPR_CLASSIFY_TYPE:
2116 case EXPR_BUILTIN_SYMBOL:
2117 case EXPR_BUILTIN_CONSTANT_P:
2118 case EXPR_BUILTIN_PREFETCH:
2120 case EXPR_STATEMENT: // TODO
2121 case EXPR_LABEL_ADDRESS:
2122 case EXPR_BINARY_BUILTIN_EXPECT:
2123 case EXPR_REFERENCE_ENUM_VALUE:
2127 panic("unhandled expression");
2130 static designator_t *parse_designation(void)
2132 designator_t *result = NULL;
2133 designator_t *last = NULL;
2136 designator_t *designator;
2137 switch (token.type) {
2139 designator = allocate_ast_zero(sizeof(designator[0]));
2140 designator->source_position = token.source_position;
2142 add_anchor_token(']');
2143 designator->array_index = parse_constant_expression();
2144 rem_anchor_token(']');
2148 designator = allocate_ast_zero(sizeof(designator[0]));
2149 designator->source_position = token.source_position;
2151 if (token.type != T_IDENTIFIER) {
2152 parse_error_expected("while parsing designator",
2153 T_IDENTIFIER, NULL);
2156 designator->symbol = token.v.symbol;
2164 assert(designator != NULL);
2166 last->next = designator;
2168 result = designator;
2176 static initializer_t *initializer_from_string(array_type_t *type,
2177 const string_t *const string)
2179 /* TODO: check len vs. size of array type */
2182 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2183 initializer->string.string = *string;
2188 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2189 wide_string_t *const string)
2191 /* TODO: check len vs. size of array type */
2194 initializer_t *const initializer =
2195 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2196 initializer->wide_string.string = *string;
2202 * Build an initializer from a given expression.
2204 static initializer_t *initializer_from_expression(type_t *orig_type,
2205 expression_t *expression)
2207 /* TODO check that expression is a constant expression */
2209 /* § 6.7.8.14/15 char array may be initialized by string literals */
2210 type_t *type = skip_typeref(orig_type);
2211 type_t *expr_type_orig = expression->base.type;
2212 type_t *expr_type = skip_typeref(expr_type_orig);
2213 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2214 array_type_t *const array_type = &type->array;
2215 type_t *const element_type = skip_typeref(array_type->element_type);
2217 if (element_type->kind == TYPE_ATOMIC) {
2218 atomic_type_kind_t akind = element_type->atomic.akind;
2219 switch (expression->kind) {
2220 case EXPR_STRING_LITERAL:
2221 if (akind == ATOMIC_TYPE_CHAR
2222 || akind == ATOMIC_TYPE_SCHAR
2223 || akind == ATOMIC_TYPE_UCHAR) {
2224 return initializer_from_string(array_type,
2225 &expression->string.value);
2228 case EXPR_WIDE_STRING_LITERAL: {
2229 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2230 if (get_unqualified_type(element_type) == bare_wchar_type) {
2231 return initializer_from_wide_string(array_type,
2232 &expression->wide_string.value);
2242 assign_error_t error = semantic_assign(type, expression);
2243 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2245 report_assign_error(error, type, expression, "initializer",
2246 &expression->base.source_position);
2248 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2250 if (type->kind == TYPE_BITFIELD) {
2251 type = type->bitfield.base_type;
2254 result->value.value = create_implicit_cast(expression, type);
2260 * Checks if a given expression can be used as an constant initializer.
2262 static bool is_initializer_constant(const expression_t *expression)
2264 return is_constant_expression(expression)
2265 || is_address_constant(expression);
2269 * Parses an scalar initializer.
2271 * § 6.7.8.11; eat {} without warning
2273 static initializer_t *parse_scalar_initializer(type_t *type,
2274 bool must_be_constant)
2276 /* there might be extra {} hierarchies */
2278 if (token.type == '{') {
2280 warningf(HERE, "extra curly braces around scalar initializer");
2284 } while (token.type == '{');
2287 expression_t *expression = parse_assignment_expression();
2288 mark_vars_read(expression, NULL);
2289 if (must_be_constant && !is_initializer_constant(expression)) {
2290 errorf(&expression->base.source_position,
2291 "Initialisation expression '%E' is not constant\n",
2295 initializer_t *initializer = initializer_from_expression(type, expression);
2297 if (initializer == NULL) {
2298 errorf(&expression->base.source_position,
2299 "expression '%E' (type '%T') doesn't match expected type '%T'",
2300 expression, expression->base.type, type);
2305 bool additional_warning_displayed = false;
2306 while (braces > 0) {
2307 if (token.type == ',') {
2310 if (token.type != '}') {
2311 if (!additional_warning_displayed && warning.other) {
2312 warningf(HERE, "additional elements in scalar initializer");
2313 additional_warning_displayed = true;
2324 * An entry in the type path.
2326 typedef struct type_path_entry_t type_path_entry_t;
2327 struct type_path_entry_t {
2328 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2330 size_t index; /**< For array types: the current index. */
2331 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2336 * A type path expression a position inside compound or array types.
2338 typedef struct type_path_t type_path_t;
2339 struct type_path_t {
2340 type_path_entry_t *path; /**< An flexible array containing the current path. */
2341 type_t *top_type; /**< type of the element the path points */
2342 size_t max_index; /**< largest index in outermost array */
2346 * Prints a type path for debugging.
2348 static __attribute__((unused)) void debug_print_type_path(
2349 const type_path_t *path)
2351 size_t len = ARR_LEN(path->path);
2353 for (size_t i = 0; i < len; ++i) {
2354 const type_path_entry_t *entry = & path->path[i];
2356 type_t *type = skip_typeref(entry->type);
2357 if (is_type_compound(type)) {
2358 /* in gcc mode structs can have no members */
2359 if (entry->v.compound_entry == NULL) {
2363 fprintf(stderr, ".%s",
2364 entry->v.compound_entry->base.symbol->string);
2365 } else if (is_type_array(type)) {
2366 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
2368 fprintf(stderr, "-INVALID-");
2371 if (path->top_type != NULL) {
2372 fprintf(stderr, " (");
2373 print_type(path->top_type);
2374 fprintf(stderr, ")");
2379 * Return the top type path entry, ie. in a path
2380 * (type).a.b returns the b.
2382 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2384 size_t len = ARR_LEN(path->path);
2386 return &path->path[len-1];
2390 * Enlarge the type path by an (empty) element.
2392 static type_path_entry_t *append_to_type_path(type_path_t *path)
2394 size_t len = ARR_LEN(path->path);
2395 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2397 type_path_entry_t *result = & path->path[len];
2398 memset(result, 0, sizeof(result[0]));
2403 * Descending into a sub-type. Enter the scope of the current top_type.
2405 static void descend_into_subtype(type_path_t *path)
2407 type_t *orig_top_type = path->top_type;
2408 type_t *top_type = skip_typeref(orig_top_type);
2410 type_path_entry_t *top = append_to_type_path(path);
2411 top->type = top_type;
2413 if (is_type_compound(top_type)) {
2414 compound_t *compound = top_type->compound.compound;
2415 entity_t *entry = compound->members.entities;
2417 if (entry != NULL) {
2418 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2419 top->v.compound_entry = &entry->declaration;
2420 path->top_type = entry->declaration.type;
2422 path->top_type = NULL;
2424 } else if (is_type_array(top_type)) {
2426 path->top_type = top_type->array.element_type;
2428 assert(!is_type_valid(top_type));
2433 * Pop an entry from the given type path, ie. returning from
2434 * (type).a.b to (type).a
2436 static void ascend_from_subtype(type_path_t *path)
2438 type_path_entry_t *top = get_type_path_top(path);
2440 path->top_type = top->type;
2442 size_t len = ARR_LEN(path->path);
2443 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2447 * Pop entries from the given type path until the given
2448 * path level is reached.
2450 static void ascend_to(type_path_t *path, size_t top_path_level)
2452 size_t len = ARR_LEN(path->path);
2454 while (len > top_path_level) {
2455 ascend_from_subtype(path);
2456 len = ARR_LEN(path->path);
2460 static bool walk_designator(type_path_t *path, const designator_t *designator,
2461 bool used_in_offsetof)
2463 for (; designator != NULL; designator = designator->next) {
2464 type_path_entry_t *top = get_type_path_top(path);
2465 type_t *orig_type = top->type;
2467 type_t *type = skip_typeref(orig_type);
2469 if (designator->symbol != NULL) {
2470 symbol_t *symbol = designator->symbol;
2471 if (!is_type_compound(type)) {
2472 if (is_type_valid(type)) {
2473 errorf(&designator->source_position,
2474 "'.%Y' designator used for non-compound type '%T'",
2478 top->type = type_error_type;
2479 top->v.compound_entry = NULL;
2480 orig_type = type_error_type;
2482 compound_t *compound = type->compound.compound;
2483 entity_t *iter = compound->members.entities;
2484 for (; iter != NULL; iter = iter->base.next) {
2485 if (iter->base.symbol == symbol) {
2490 errorf(&designator->source_position,
2491 "'%T' has no member named '%Y'", orig_type, symbol);
2494 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2495 if (used_in_offsetof) {
2496 type_t *real_type = skip_typeref(iter->declaration.type);
2497 if (real_type->kind == TYPE_BITFIELD) {
2498 errorf(&designator->source_position,
2499 "offsetof designator '%Y' may not specify bitfield",
2505 top->type = orig_type;
2506 top->v.compound_entry = &iter->declaration;
2507 orig_type = iter->declaration.type;
2510 expression_t *array_index = designator->array_index;
2511 assert(designator->array_index != NULL);
2513 if (!is_type_array(type)) {
2514 if (is_type_valid(type)) {
2515 errorf(&designator->source_position,
2516 "[%E] designator used for non-array type '%T'",
2517 array_index, orig_type);
2522 long index = fold_constant(array_index);
2523 if (!used_in_offsetof) {
2525 errorf(&designator->source_position,
2526 "array index [%E] must be positive", array_index);
2527 } else if (type->array.size_constant) {
2528 long array_size = type->array.size;
2529 if (index >= array_size) {
2530 errorf(&designator->source_position,
2531 "designator [%E] (%d) exceeds array size %d",
2532 array_index, index, array_size);
2537 top->type = orig_type;
2538 top->v.index = (size_t) index;
2539 orig_type = type->array.element_type;
2541 path->top_type = orig_type;
2543 if (designator->next != NULL) {
2544 descend_into_subtype(path);
2553 static void advance_current_object(type_path_t *path, size_t top_path_level)
2555 type_path_entry_t *top = get_type_path_top(path);
2557 type_t *type = skip_typeref(top->type);
2558 if (is_type_union(type)) {
2559 /* in unions only the first element is initialized */
2560 top->v.compound_entry = NULL;
2561 } else if (is_type_struct(type)) {
2562 declaration_t *entry = top->v.compound_entry;
2564 entity_t *next_entity = entry->base.next;
2565 if (next_entity != NULL) {
2566 assert(is_declaration(next_entity));
2567 entry = &next_entity->declaration;
2572 top->v.compound_entry = entry;
2573 if (entry != NULL) {
2574 path->top_type = entry->type;
2577 } else if (is_type_array(type)) {
2578 assert(is_type_array(type));
2582 if (!type->array.size_constant || top->v.index < type->array.size) {
2586 assert(!is_type_valid(type));
2590 /* we're past the last member of the current sub-aggregate, try if we
2591 * can ascend in the type hierarchy and continue with another subobject */
2592 size_t len = ARR_LEN(path->path);
2594 if (len > top_path_level) {
2595 ascend_from_subtype(path);
2596 advance_current_object(path, top_path_level);
2598 path->top_type = NULL;
2603 * skip until token is found.
2605 static void skip_until(int type)
2607 while (token.type != type) {
2608 if (token.type == T_EOF)
2615 * skip any {...} blocks until a closing bracket is reached.
2617 static void skip_initializers(void)
2619 if (token.type == '{')
2622 while (token.type != '}') {
2623 if (token.type == T_EOF)
2625 if (token.type == '{') {
2633 static initializer_t *create_empty_initializer(void)
2635 static initializer_t empty_initializer
2636 = { .list = { { INITIALIZER_LIST }, 0 } };
2637 return &empty_initializer;
2641 * Parse a part of an initialiser for a struct or union,
2643 static initializer_t *parse_sub_initializer(type_path_t *path,
2644 type_t *outer_type, size_t top_path_level,
2645 parse_initializer_env_t *env)
2647 if (token.type == '}') {
2648 /* empty initializer */
2649 return create_empty_initializer();
2652 type_t *orig_type = path->top_type;
2653 type_t *type = NULL;
2655 if (orig_type == NULL) {
2656 /* We are initializing an empty compound. */
2658 type = skip_typeref(orig_type);
2661 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2664 designator_t *designator = NULL;
2665 if (token.type == '.' || token.type == '[') {
2666 designator = parse_designation();
2667 goto finish_designator;
2668 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2669 /* GNU-style designator ("identifier: value") */
2670 designator = allocate_ast_zero(sizeof(designator[0]));
2671 designator->source_position = token.source_position;
2672 designator->symbol = token.v.symbol;
2677 /* reset path to toplevel, evaluate designator from there */
2678 ascend_to(path, top_path_level);
2679 if (!walk_designator(path, designator, false)) {
2680 /* can't continue after designation error */
2684 initializer_t *designator_initializer
2685 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2686 designator_initializer->designator.designator = designator;
2687 ARR_APP1(initializer_t*, initializers, designator_initializer);
2689 orig_type = path->top_type;
2690 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2695 if (token.type == '{') {
2696 if (type != NULL && is_type_scalar(type)) {
2697 sub = parse_scalar_initializer(type, env->must_be_constant);
2701 if (env->entity != NULL) {
2703 "extra brace group at end of initializer for '%Y'",
2704 env->entity->base.symbol);
2706 errorf(HERE, "extra brace group at end of initializer");
2709 descend_into_subtype(path);
2711 add_anchor_token('}');
2712 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2714 rem_anchor_token('}');
2717 ascend_from_subtype(path);
2721 goto error_parse_next;
2725 /* must be an expression */
2726 expression_t *expression = parse_assignment_expression();
2728 if (env->must_be_constant && !is_initializer_constant(expression)) {
2729 errorf(&expression->base.source_position,
2730 "Initialisation expression '%E' is not constant\n",
2735 /* we are already outside, ... */
2736 type_t *const outer_type_skip = skip_typeref(outer_type);
2737 if (is_type_compound(outer_type_skip) &&
2738 !outer_type_skip->compound.compound->complete) {
2739 goto error_parse_next;
2744 /* handle { "string" } special case */
2745 if ((expression->kind == EXPR_STRING_LITERAL
2746 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2747 && outer_type != NULL) {
2748 sub = initializer_from_expression(outer_type, expression);
2750 if (token.type == ',') {
2753 if (token.type != '}' && warning.other) {
2754 warningf(HERE, "excessive elements in initializer for type '%T'",
2757 /* TODO: eat , ... */
2762 /* descend into subtypes until expression matches type */
2764 orig_type = path->top_type;
2765 type = skip_typeref(orig_type);
2767 sub = initializer_from_expression(orig_type, expression);
2771 if (!is_type_valid(type)) {
2774 if (is_type_scalar(type)) {
2775 errorf(&expression->base.source_position,
2776 "expression '%E' doesn't match expected type '%T'",
2777 expression, orig_type);
2781 descend_into_subtype(path);
2785 /* update largest index of top array */
2786 const type_path_entry_t *first = &path->path[0];
2787 type_t *first_type = first->type;
2788 first_type = skip_typeref(first_type);
2789 if (is_type_array(first_type)) {
2790 size_t index = first->v.index;
2791 if (index > path->max_index)
2792 path->max_index = index;
2796 /* append to initializers list */
2797 ARR_APP1(initializer_t*, initializers, sub);
2800 if (warning.other) {
2801 if (env->entity != NULL) {
2802 warningf(HERE, "excess elements in struct initializer for '%Y'",
2803 env->entity->base.symbol);
2805 warningf(HERE, "excess elements in struct initializer");
2811 if (token.type == '}') {
2815 if (token.type == '}') {
2820 /* advance to the next declaration if we are not at the end */
2821 advance_current_object(path, top_path_level);
2822 orig_type = path->top_type;
2823 if (orig_type != NULL)
2824 type = skip_typeref(orig_type);
2830 size_t len = ARR_LEN(initializers);
2831 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2832 initializer_t *result = allocate_ast_zero(size);
2833 result->kind = INITIALIZER_LIST;
2834 result->list.len = len;
2835 memcpy(&result->list.initializers, initializers,
2836 len * sizeof(initializers[0]));
2838 DEL_ARR_F(initializers);
2839 ascend_to(path, top_path_level+1);
2844 skip_initializers();
2845 DEL_ARR_F(initializers);
2846 ascend_to(path, top_path_level+1);
2851 * Parses an initializer. Parsers either a compound literal
2852 * (env->declaration == NULL) or an initializer of a declaration.
2854 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2856 type_t *type = skip_typeref(env->type);
2857 initializer_t *result = NULL;
2860 if (is_type_scalar(type)) {
2861 result = parse_scalar_initializer(type, env->must_be_constant);
2862 } else if (token.type == '{') {
2866 memset(&path, 0, sizeof(path));
2867 path.top_type = env->type;
2868 path.path = NEW_ARR_F(type_path_entry_t, 0);
2870 descend_into_subtype(&path);
2872 add_anchor_token('}');
2873 result = parse_sub_initializer(&path, env->type, 1, env);
2874 rem_anchor_token('}');
2876 max_index = path.max_index;
2877 DEL_ARR_F(path.path);
2881 /* parse_scalar_initializer() also works in this case: we simply
2882 * have an expression without {} around it */
2883 result = parse_scalar_initializer(type, env->must_be_constant);
2886 /* § 6.7.8 (22) array initializers for arrays with unknown size determine
2887 * the array type size */
2888 if (is_type_array(type) && type->array.size_expression == NULL
2889 && result != NULL) {
2891 switch (result->kind) {
2892 case INITIALIZER_LIST:
2893 size = max_index + 1;
2896 case INITIALIZER_STRING:
2897 size = result->string.string.size;
2900 case INITIALIZER_WIDE_STRING:
2901 size = result->wide_string.string.size;
2904 case INITIALIZER_DESIGNATOR:
2905 case INITIALIZER_VALUE:
2906 /* can happen for parse errors */
2911 internal_errorf(HERE, "invalid initializer type");
2914 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2915 cnst->base.type = type_size_t;
2916 cnst->conste.v.int_value = size;
2918 type_t *new_type = duplicate_type(type);
2920 new_type->array.size_expression = cnst;
2921 new_type->array.size_constant = true;
2922 new_type->array.has_implicit_size = true;
2923 new_type->array.size = size;
2924 env->type = new_type;
2932 static void append_entity(scope_t *scope, entity_t *entity)
2934 if (scope->last_entity != NULL) {
2935 scope->last_entity->base.next = entity;
2937 scope->entities = entity;
2939 scope->last_entity = entity;
2943 static compound_t *parse_compound_type_specifier(bool is_struct)
2945 gnu_attribute_t *attributes = NULL;
2946 decl_modifiers_t modifiers = 0;
2953 symbol_t *symbol = NULL;
2954 compound_t *compound = NULL;
2956 if (token.type == T___attribute__) {
2957 modifiers |= parse_attributes(&attributes);
2960 if (token.type == T_IDENTIFIER) {
2961 symbol = token.v.symbol;
2964 namespace_tag_t const namespc =
2965 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2966 entity_t *entity = get_entity(symbol, namespc);
2967 if (entity != NULL) {
2968 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
2969 compound = &entity->compound;
2970 if (compound->base.parent_scope != current_scope &&
2971 (token.type == '{' || token.type == ';')) {
2972 /* we're in an inner scope and have a definition. Override
2973 existing definition in outer scope */
2975 } else if (compound->complete && token.type == '{') {
2976 assert(symbol != NULL);
2977 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2978 is_struct ? "struct" : "union", symbol,
2979 &compound->base.source_position);
2980 /* clear members in the hope to avoid further errors */
2981 compound->members.entities = NULL;
2984 } else if (token.type != '{') {
2986 parse_error_expected("while parsing struct type specifier",
2987 T_IDENTIFIER, '{', NULL);
2989 parse_error_expected("while parsing union type specifier",
2990 T_IDENTIFIER, '{', NULL);
2996 if (compound == NULL) {
2997 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2998 entity_t *entity = allocate_entity_zero(kind);
2999 compound = &entity->compound;
3001 compound->base.namespc =
3002 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
3003 compound->base.source_position = token.source_position;
3004 compound->base.symbol = symbol;
3005 compound->base.parent_scope = current_scope;
3006 if (symbol != NULL) {
3007 environment_push(entity);
3009 append_entity(current_scope, entity);
3012 if (token.type == '{') {
3013 parse_compound_type_entries(compound);
3014 modifiers |= parse_attributes(&attributes);
3016 if (symbol == NULL) {
3017 assert(anonymous_entity == NULL);
3018 anonymous_entity = (entity_t*)compound;
3022 compound->modifiers |= modifiers;
3026 static void parse_enum_entries(type_t *const enum_type)
3030 if (token.type == '}') {
3031 errorf(HERE, "empty enum not allowed");
3036 add_anchor_token('}');
3038 if (token.type != T_IDENTIFIER) {
3039 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3041 rem_anchor_token('}');
3045 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3046 entity->enum_value.enum_type = enum_type;
3047 entity->base.symbol = token.v.symbol;
3048 entity->base.source_position = token.source_position;
3051 if (token.type == '=') {
3053 expression_t *value = parse_constant_expression();
3055 value = create_implicit_cast(value, enum_type);
3056 entity->enum_value.value = value;
3061 record_entity(entity, false);
3063 if (token.type != ',')
3066 } while (token.type != '}');
3067 rem_anchor_token('}');
3075 static type_t *parse_enum_specifier(void)
3077 gnu_attribute_t *attributes = NULL;
3082 if (token.type == T_IDENTIFIER) {
3083 symbol = token.v.symbol;
3086 entity = get_entity(symbol, NAMESPACE_ENUM);
3087 assert(entity == NULL || entity->kind == ENTITY_ENUM);
3088 } else if (token.type != '{') {
3089 parse_error_expected("while parsing enum type specifier",
3090 T_IDENTIFIER, '{', NULL);
3097 if (entity == NULL) {
3098 entity = allocate_entity_zero(ENTITY_ENUM);
3099 entity->base.namespc = NAMESPACE_ENUM;
3100 entity->base.source_position = token.source_position;
3101 entity->base.symbol = symbol;
3102 entity->base.parent_scope = current_scope;
3105 type_t *const type = allocate_type_zero(TYPE_ENUM);
3106 type->enumt.enume = &entity->enume;
3108 if (token.type == '{') {
3109 if (entity->enume.complete) {
3110 errorf(HERE, "multiple definitions of enum %Y (previous definition %P)",
3111 symbol, &entity->base.source_position);
3113 if (symbol != NULL) {
3114 environment_push(entity);
3116 append_entity(current_scope, entity);
3117 entity->enume.complete = true;
3119 parse_enum_entries(type);
3120 parse_attributes(&attributes);
3122 if (symbol == NULL) {
3123 assert(anonymous_entity == NULL);
3124 anonymous_entity = entity;
3126 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
3127 errorf(HERE, "enum %Y used before definition (incomplete enumes are a GNU extension)",
3135 * if a symbol is a typedef to another type, return true
3137 static bool is_typedef_symbol(symbol_t *symbol)
3139 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3140 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3143 static type_t *parse_typeof(void)
3150 add_anchor_token(')');
3152 expression_t *expression = NULL;
3154 bool old_type_prop = in_type_prop;
3155 bool old_gcc_extension = in_gcc_extension;
3156 in_type_prop = true;
3158 while (token.type == T___extension__) {
3159 /* This can be a prefix to a typename or an expression. */
3161 in_gcc_extension = true;
3163 switch (token.type) {
3165 if (is_typedef_symbol(token.v.symbol)) {
3166 type = parse_typename();
3168 expression = parse_expression();
3169 type = expression->base.type;
3174 type = parse_typename();
3178 expression = parse_expression();
3179 type = expression->base.type;
3182 in_type_prop = old_type_prop;
3183 in_gcc_extension = old_gcc_extension;
3185 rem_anchor_token(')');
3188 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3189 typeof_type->typeoft.expression = expression;
3190 typeof_type->typeoft.typeof_type = type;
3197 typedef enum specifiers_t {
3198 SPECIFIER_SIGNED = 1 << 0,
3199 SPECIFIER_UNSIGNED = 1 << 1,
3200 SPECIFIER_LONG = 1 << 2,
3201 SPECIFIER_INT = 1 << 3,
3202 SPECIFIER_DOUBLE = 1 << 4,
3203 SPECIFIER_CHAR = 1 << 5,
3204 SPECIFIER_SHORT = 1 << 6,
3205 SPECIFIER_LONG_LONG = 1 << 7,
3206 SPECIFIER_FLOAT = 1 << 8,
3207 SPECIFIER_BOOL = 1 << 9,
3208 SPECIFIER_VOID = 1 << 10,
3209 SPECIFIER_INT8 = 1 << 11,
3210 SPECIFIER_INT16 = 1 << 12,
3211 SPECIFIER_INT32 = 1 << 13,
3212 SPECIFIER_INT64 = 1 << 14,
3213 SPECIFIER_INT128 = 1 << 15,
3214 SPECIFIER_COMPLEX = 1 << 16,
3215 SPECIFIER_IMAGINARY = 1 << 17,
3218 static type_t *create_builtin_type(symbol_t *const symbol,
3219 type_t *const real_type)
3221 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3222 type->builtin.symbol = symbol;
3223 type->builtin.real_type = real_type;
3225 type_t *result = typehash_insert(type);
3226 if (type != result) {
3233 static type_t *get_typedef_type(symbol_t *symbol)
3235 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3236 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3239 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3240 type->typedeft.typedefe = &entity->typedefe;
3246 * check for the allowed MS alignment values.
3248 static bool check_alignment_value(long long intvalue)
3250 if (intvalue < 1 || intvalue > 8192) {
3251 errorf(HERE, "illegal alignment value");
3254 unsigned v = (unsigned)intvalue;
3255 for (unsigned i = 1; i <= 8192; i += i) {
3259 errorf(HERE, "alignment must be power of two");
3263 #define DET_MOD(name, tag) do { \
3264 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3265 *modifiers |= tag; \
3268 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3270 decl_modifiers_t *modifiers = &specifiers->modifiers;
3273 if (token.type == T_restrict) {
3275 DET_MOD(restrict, DM_RESTRICT);
3277 } else if (token.type != T_IDENTIFIER)
3279 symbol_t *symbol = token.v.symbol;
3280 if (symbol == sym_align) {
3283 if (token.type != T_INTEGER)
3285 if (check_alignment_value(token.v.intvalue)) {
3286 if (specifiers->alignment != 0 && warning.other)
3287 warningf(HERE, "align used more than once");
3288 specifiers->alignment = (unsigned char)token.v.intvalue;
3292 } else if (symbol == sym_allocate) {
3295 if (token.type != T_IDENTIFIER)
3297 (void)token.v.symbol;
3299 } else if (symbol == sym_dllimport) {
3301 DET_MOD(dllimport, DM_DLLIMPORT);
3302 } else if (symbol == sym_dllexport) {
3304 DET_MOD(dllexport, DM_DLLEXPORT);
3305 } else if (symbol == sym_thread) {
3307 DET_MOD(thread, DM_THREAD);
3308 } else if (symbol == sym_naked) {
3310 DET_MOD(naked, DM_NAKED);
3311 } else if (symbol == sym_noinline) {
3313 DET_MOD(noinline, DM_NOINLINE);
3314 } else if (symbol == sym_noreturn) {
3316 DET_MOD(noreturn, DM_NORETURN);
3317 } else if (symbol == sym_nothrow) {
3319 DET_MOD(nothrow, DM_NOTHROW);
3320 } else if (symbol == sym_novtable) {
3322 DET_MOD(novtable, DM_NOVTABLE);
3323 } else if (symbol == sym_property) {
3327 bool is_get = false;
3328 if (token.type != T_IDENTIFIER)
3330 if (token.v.symbol == sym_get) {
3332 } else if (token.v.symbol == sym_put) {
3334 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3339 if (token.type != T_IDENTIFIER)
3342 if (specifiers->get_property_sym != NULL) {
3343 errorf(HERE, "get property name already specified");
3345 specifiers->get_property_sym = token.v.symbol;
3348 if (specifiers->put_property_sym != NULL) {
3349 errorf(HERE, "put property name already specified");
3351 specifiers->put_property_sym = token.v.symbol;
3355 if (token.type == ',') {
3362 } else if (symbol == sym_selectany) {
3364 DET_MOD(selectany, DM_SELECTANY);
3365 } else if (symbol == sym_uuid) {
3368 if (token.type != T_STRING_LITERAL)
3372 } else if (symbol == sym_deprecated) {
3374 if (specifiers->deprecated != 0 && warning.other)
3375 warningf(HERE, "deprecated used more than once");
3376 specifiers->deprecated = true;
3377 if (token.type == '(') {
3379 if (token.type == T_STRING_LITERAL) {
3380 specifiers->deprecated_string = token.v.string.begin;
3383 errorf(HERE, "string literal expected");
3387 } else if (symbol == sym_noalias) {
3389 DET_MOD(noalias, DM_NOALIAS);
3392 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3394 if (token.type == '(')
3398 if (token.type == ',')
3405 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3407 entity_t *entity = allocate_entity_zero(kind);
3408 entity->base.source_position = *HERE;
3409 entity->base.symbol = symbol;
3410 if (is_declaration(entity)) {
3411 entity->declaration.type = type_error_type;
3412 entity->declaration.implicit = true;
3413 } else if (kind == ENTITY_TYPEDEF) {
3414 entity->typedefe.type = type_error_type;
3416 record_entity(entity, false);
3420 static void parse_microsoft_based(based_spec_t *based_spec)
3422 if (token.type != T_IDENTIFIER) {
3423 parse_error_expected("while parsing __based", T_IDENTIFIER, NULL);
3426 symbol_t *symbol = token.v.symbol;
3427 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3429 if (entity == NULL || entity->base.kind != ENTITY_VARIABLE) {
3430 errorf(HERE, "'%Y' is not a variable name.", symbol);
3431 entity = create_error_entity(symbol, ENTITY_VARIABLE);
3433 variable_t *variable = &entity->variable;
3435 if (based_spec->base_variable != NULL) {
3436 errorf(HERE, "__based type qualifier specified more than once");
3438 based_spec->source_position = token.source_position;
3439 based_spec->base_variable = variable;
3441 type_t *const type = variable->base.type;
3443 if (is_type_valid(type)) {
3444 if (! is_type_pointer(skip_typeref(type))) {
3445 errorf(HERE, "variable in __based modifier must have pointer type instead of %T", type);
3447 if (variable->base.base.parent_scope != file_scope) {
3448 errorf(HERE, "a nonstatic local variable may not be used in a __based specification");
3456 * Finish the construction of a struct type by calculating
3457 * its size, offsets, alignment.
3459 static void finish_struct_type(compound_type_t *type)
3461 assert(type->compound != NULL);
3463 compound_t *compound = type->compound;
3464 if (!compound->complete)
3469 il_alignment_t alignment = 1;
3470 bool need_pad = false;
3472 entity_t *entry = compound->members.entities;
3473 for (; entry != NULL; entry = entry->base.next) {
3474 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3477 type_t *m_type = skip_typeref(entry->declaration.type);
3478 if (! is_type_valid(m_type)) {
3479 /* simply ignore errors here */
3482 il_alignment_t m_alignment = m_type->base.alignment;
3483 if (m_alignment > alignment)
3484 alignment = m_alignment;
3486 offset = (size + m_alignment - 1) & -m_alignment;
3490 entry->compound_member.offset = offset;
3491 size = offset + m_type->base.size;
3493 if (type->base.alignment != 0) {
3494 alignment = type->base.alignment;
3497 offset = (size + alignment - 1) & -alignment;
3501 if (warning.padded && need_pad) {
3502 warningf(&compound->base.source_position,
3503 "'%#T' needs padding", type, compound->base.symbol);
3505 if (warning.packed && !need_pad) {
3506 warningf(&compound->base.source_position,
3507 "superfluous packed attribute on '%#T'",
3508 type, compound->base.symbol);
3511 type->base.size = offset;
3512 type->base.alignment = alignment;
3516 * Finish the construction of an union type by calculating
3517 * its size and alignment.
3519 static void finish_union_type(compound_type_t *type)
3521 assert(type->compound != NULL);
3523 compound_t *compound = type->compound;
3524 if (! compound->complete)
3528 il_alignment_t alignment = 1;
3530 entity_t *entry = compound->members.entities;
3531 for (; entry != NULL; entry = entry->base.next) {
3532 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3535 type_t *m_type = skip_typeref(entry->declaration.type);
3536 if (! is_type_valid(m_type))
3539 entry->compound_member.offset = 0;
3540 if (m_type->base.size > size)
3541 size = m_type->base.size;
3542 if (m_type->base.alignment > alignment)
3543 alignment = m_type->base.alignment;
3545 if (type->base.alignment != 0) {
3546 alignment = type->base.alignment;
3548 size = (size + alignment - 1) & -alignment;
3549 type->base.size = size;
3550 type->base.alignment = alignment;
3553 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3555 type_t *type = NULL;
3556 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3557 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3558 unsigned type_specifiers = 0;
3559 bool newtype = false;
3560 bool saw_error = false;
3561 bool old_gcc_extension = in_gcc_extension;
3563 specifiers->source_position = token.source_position;
3566 specifiers->modifiers
3567 |= parse_attributes(&specifiers->gnu_attributes);
3568 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3569 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3571 switch (token.type) {
3573 #define MATCH_STORAGE_CLASS(token, class) \
3575 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3576 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3578 specifiers->storage_class = class; \
3579 if (specifiers->thread_local) \
3580 goto check_thread_storage_class; \
3584 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3585 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3586 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3587 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3588 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3593 add_anchor_token(')');
3594 parse_microsoft_extended_decl_modifier(specifiers);
3595 rem_anchor_token(')');
3600 if (specifiers->thread_local) {
3601 errorf(HERE, "duplicate '__thread'");
3603 specifiers->thread_local = true;
3604 check_thread_storage_class:
3605 switch (specifiers->storage_class) {
3606 case STORAGE_CLASS_EXTERN:
3607 case STORAGE_CLASS_NONE:
3608 case STORAGE_CLASS_STATIC:
3612 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
3613 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
3614 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
3615 wrong_thread_stoarge_class:
3616 errorf(HERE, "'__thread' used with '%s'", wrong);
3623 /* type qualifiers */
3624 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3626 qualifiers |= qualifier; \
3630 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3631 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3632 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3633 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3634 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3635 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3636 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3637 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3639 case T___extension__:
3641 in_gcc_extension = true;
3644 /* type specifiers */
3645 #define MATCH_SPECIFIER(token, specifier, name) \
3647 if (type_specifiers & specifier) { \
3648 errorf(HERE, "multiple " name " type specifiers given"); \
3650 type_specifiers |= specifier; \
3655 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3656 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3657 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3658 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3659 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3660 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3661 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3662 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3663 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3664 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3665 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3666 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3667 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3668 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3669 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3670 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3671 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3673 case T__forceinline:
3674 /* only in microsoft mode */
3675 specifiers->modifiers |= DM_FORCEINLINE;
3680 specifiers->is_inline = true;
3684 if (type_specifiers & SPECIFIER_LONG_LONG) {
3685 errorf(HERE, "multiple type specifiers given");
3686 } else if (type_specifiers & SPECIFIER_LONG) {
3687 type_specifiers |= SPECIFIER_LONG_LONG;
3689 type_specifiers |= SPECIFIER_LONG;
3695 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3697 type->compound.compound = parse_compound_type_specifier(true);
3698 finish_struct_type(&type->compound);
3702 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3703 type->compound.compound = parse_compound_type_specifier(false);
3704 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3705 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3706 finish_union_type(&type->compound);
3710 type = parse_enum_specifier();
3713 type = parse_typeof();
3715 case T___builtin_va_list:
3716 type = duplicate_type(type_valist);
3720 case T_IDENTIFIER: {
3721 /* only parse identifier if we haven't found a type yet */
3722 if (type != NULL || type_specifiers != 0) {
3723 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3724 * declaration, so it doesn't generate errors about expecting '(' or
3726 switch (look_ahead(1)->type) {
3733 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3737 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3742 goto finish_specifiers;
3746 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3747 if (typedef_type == NULL) {
3748 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3749 * declaration, so it doesn't generate 'implicit int' followed by more
3750 * errors later on. */
3751 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3757 errorf(HERE, "%K does not name a type", &token);
3760 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3762 type = allocate_type_zero(TYPE_TYPEDEF);
3763 type->typedeft.typedefe = &entity->typedefe;
3767 if (la1_type == '&' || la1_type == '*')
3768 goto finish_specifiers;
3773 goto finish_specifiers;
3778 type = typedef_type;
3782 /* function specifier */
3784 goto finish_specifiers;
3789 in_gcc_extension = old_gcc_extension;
3791 if (type == NULL || (saw_error && type_specifiers != 0)) {
3792 atomic_type_kind_t atomic_type;
3794 /* match valid basic types */
3795 switch (type_specifiers) {
3796 case SPECIFIER_VOID:
3797 atomic_type = ATOMIC_TYPE_VOID;
3799 case SPECIFIER_CHAR:
3800 atomic_type = ATOMIC_TYPE_CHAR;
3802 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3803 atomic_type = ATOMIC_TYPE_SCHAR;
3805 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3806 atomic_type = ATOMIC_TYPE_UCHAR;
3808 case SPECIFIER_SHORT:
3809 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3810 case SPECIFIER_SHORT | SPECIFIER_INT:
3811 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3812 atomic_type = ATOMIC_TYPE_SHORT;
3814 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3815 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3816 atomic_type = ATOMIC_TYPE_USHORT;
3819 case SPECIFIER_SIGNED:
3820 case SPECIFIER_SIGNED | SPECIFIER_INT:
3821 atomic_type = ATOMIC_TYPE_INT;
3823 case SPECIFIER_UNSIGNED:
3824 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3825 atomic_type = ATOMIC_TYPE_UINT;
3827 case SPECIFIER_LONG:
3828 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3829 case SPECIFIER_LONG | SPECIFIER_INT:
3830 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3831 atomic_type = ATOMIC_TYPE_LONG;
3833 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3834 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3835 atomic_type = ATOMIC_TYPE_ULONG;
3838 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3839 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3840 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3841 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3843 atomic_type = ATOMIC_TYPE_LONGLONG;
3844 goto warn_about_long_long;
3846 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3847 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3849 atomic_type = ATOMIC_TYPE_ULONGLONG;
3850 warn_about_long_long:
3851 if (warning.long_long) {
3852 warningf(&specifiers->source_position,
3853 "ISO C90 does not support 'long long'");
3857 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3858 atomic_type = unsigned_int8_type_kind;
3861 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3862 atomic_type = unsigned_int16_type_kind;
3865 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3866 atomic_type = unsigned_int32_type_kind;
3869 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3870 atomic_type = unsigned_int64_type_kind;
3873 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3874 atomic_type = unsigned_int128_type_kind;
3877 case SPECIFIER_INT8:
3878 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3879 atomic_type = int8_type_kind;
3882 case SPECIFIER_INT16:
3883 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3884 atomic_type = int16_type_kind;
3887 case SPECIFIER_INT32:
3888 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3889 atomic_type = int32_type_kind;
3892 case SPECIFIER_INT64:
3893 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3894 atomic_type = int64_type_kind;
3897 case SPECIFIER_INT128:
3898 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3899 atomic_type = int128_type_kind;
3902 case SPECIFIER_FLOAT:
3903 atomic_type = ATOMIC_TYPE_FLOAT;
3905 case SPECIFIER_DOUBLE:
3906 atomic_type = ATOMIC_TYPE_DOUBLE;
3908 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3909 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3911 case SPECIFIER_BOOL:
3912 atomic_type = ATOMIC_TYPE_BOOL;
3914 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3915 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3916 atomic_type = ATOMIC_TYPE_FLOAT;
3918 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3919 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3920 atomic_type = ATOMIC_TYPE_DOUBLE;
3922 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3923 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3924 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3927 /* invalid specifier combination, give an error message */
3928 if (type_specifiers == 0) {
3932 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3933 if (!(c_mode & _CXX) && !strict_mode) {
3934 if (warning.implicit_int) {
3935 warningf(HERE, "no type specifiers in declaration, using 'int'");
3937 atomic_type = ATOMIC_TYPE_INT;
3940 errorf(HERE, "no type specifiers given in declaration");
3942 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3943 (type_specifiers & SPECIFIER_UNSIGNED)) {
3944 errorf(HERE, "signed and unsigned specifiers given");
3945 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3946 errorf(HERE, "only integer types can be signed or unsigned");
3948 errorf(HERE, "multiple datatypes in declaration");
3953 if (type_specifiers & SPECIFIER_COMPLEX) {
3954 type = allocate_type_zero(TYPE_COMPLEX);
3955 type->complex.akind = atomic_type;
3956 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3957 type = allocate_type_zero(TYPE_IMAGINARY);
3958 type->imaginary.akind = atomic_type;
3960 type = allocate_type_zero(TYPE_ATOMIC);
3961 type->atomic.akind = atomic_type;
3964 } else if (type_specifiers != 0) {
3965 errorf(HERE, "multiple datatypes in declaration");
3968 /* FIXME: check type qualifiers here */
3970 type->base.qualifiers = qualifiers;
3971 type->base.modifiers = modifiers;
3973 type_t *result = typehash_insert(type);
3974 if (newtype && result != type) {
3978 specifiers->type = result;
3982 specifiers->type = type_error_type;
3986 static type_qualifiers_t parse_type_qualifiers(void)
3988 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3991 switch (token.type) {
3992 /* type qualifiers */
3993 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3994 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3995 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3996 /* microsoft extended type modifiers */
3997 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3998 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3999 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
4000 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
4001 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
4010 * Parses an K&R identifier list
4012 static void parse_identifier_list(scope_t *scope)
4015 entity_t *entity = allocate_entity_zero(ENTITY_VARIABLE);
4016 entity->base.source_position = token.source_position;
4017 entity->base.namespc = NAMESPACE_NORMAL;
4018 entity->base.symbol = token.v.symbol;
4019 /* a K&R parameter has no type, yet */
4022 append_entity(scope, entity);
4024 if (token.type != ',') {
4028 } while (token.type == T_IDENTIFIER);
4031 static void semantic_parameter(declaration_t *declaration)
4033 /* TODO: improve error messages */
4034 source_position_t const* const pos = &declaration->base.source_position;
4036 /* §6.9.1:6 The declarations in the declaration list shall contain no
4037 * storage-class specifier other than register and no
4038 * initializations. */
4039 switch (declaration->declared_storage_class) {
4040 /* Allowed storage classes */
4041 case STORAGE_CLASS_NONE:
4042 case STORAGE_CLASS_REGISTER:
4046 errorf(pos, "parameter may only have none or register storage class");
4050 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type list in
4051 * a function declarator that is part of a definition of that
4052 * function shall not have incomplete type. */
4053 type_t *type = declaration->type;
4054 if (is_type_incomplete(skip_typeref(type))) {
4055 errorf(pos, "parameter '%#T' has incomplete type",
4056 type, declaration->base.symbol);
4060 static entity_t *parse_parameter(void)
4062 declaration_specifiers_t specifiers;
4063 memset(&specifiers, 0, sizeof(specifiers));
4065 parse_declaration_specifiers(&specifiers);
4067 entity_t *entity = parse_declarator(&specifiers,
4068 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
4069 anonymous_entity = NULL;
4074 * Parses function type parameters (and optionally creates variable_t entities
4075 * for them in a scope)
4077 static void parse_parameters(function_type_t *type, scope_t *scope)
4080 add_anchor_token(')');
4081 int saved_comma_state = save_and_reset_anchor_state(',');
4083 if (token.type == T_IDENTIFIER &&
4084 !is_typedef_symbol(token.v.symbol)) {
4085 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4086 if (la1_type == ',' || la1_type == ')') {
4087 type->kr_style_parameters = true;
4088 parse_identifier_list(scope);
4089 goto parameters_finished;
4093 if (token.type == ')') {
4094 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4095 if (!(c_mode & _CXX))
4096 type->unspecified_parameters = true;
4097 goto parameters_finished;
4100 function_parameter_t *parameter;
4101 function_parameter_t *last_parameter = NULL;
4104 switch (token.type) {
4107 type->variadic = true;
4108 goto parameters_finished;
4111 case T___extension__:
4114 entity_t *entity = parse_parameter();
4115 if (entity->kind == ENTITY_TYPEDEF) {
4116 errorf(&entity->base.source_position,
4117 "typedef not allowed as function parameter");
4120 assert(is_declaration(entity));
4122 /* func(void) is not a parameter */
4123 if (last_parameter == NULL
4124 && token.type == ')'
4125 && entity->base.symbol == NULL
4126 && skip_typeref(entity->declaration.type) == type_void) {
4127 goto parameters_finished;
4129 semantic_parameter(&entity->declaration);
4131 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4132 memset(parameter, 0, sizeof(parameter[0]));
4133 parameter->type = entity->declaration.type;
4135 if (scope != NULL) {
4136 append_entity(scope, entity);
4139 if (last_parameter != NULL) {
4140 last_parameter->next = parameter;
4142 type->parameters = parameter;
4144 last_parameter = parameter;
4149 goto parameters_finished;
4151 if (token.type != ',') {
4152 goto parameters_finished;
4158 parameters_finished:
4159 rem_anchor_token(')');
4163 restore_anchor_state(',', saved_comma_state);
4166 typedef enum construct_type_kind_t {
4169 CONSTRUCT_REFERENCE,
4172 } construct_type_kind_t;
4174 typedef struct construct_type_t construct_type_t;
4175 struct construct_type_t {
4176 construct_type_kind_t kind;
4177 construct_type_t *next;
4180 typedef struct parsed_pointer_t parsed_pointer_t;
4181 struct parsed_pointer_t {
4182 construct_type_t construct_type;
4183 type_qualifiers_t type_qualifiers;
4184 variable_t *base_variable; /**< MS __based extension. */
4187 typedef struct parsed_reference_t parsed_reference_t;
4188 struct parsed_reference_t {
4189 construct_type_t construct_type;
4192 typedef struct construct_function_type_t construct_function_type_t;
4193 struct construct_function_type_t {
4194 construct_type_t construct_type;
4195 type_t *function_type;
4198 typedef struct parsed_array_t parsed_array_t;
4199 struct parsed_array_t {
4200 construct_type_t construct_type;
4201 type_qualifiers_t type_qualifiers;
4207 typedef struct construct_base_type_t construct_base_type_t;
4208 struct construct_base_type_t {
4209 construct_type_t construct_type;
4213 static construct_type_t *parse_pointer_declarator(variable_t *base_variable)
4217 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4218 memset(pointer, 0, sizeof(pointer[0]));
4219 pointer->construct_type.kind = CONSTRUCT_POINTER;
4220 pointer->type_qualifiers = parse_type_qualifiers();
4221 pointer->base_variable = base_variable;
4223 return &pointer->construct_type;
4226 static construct_type_t *parse_reference_declarator(void)
4230 parsed_reference_t *reference = obstack_alloc(&temp_obst, sizeof(reference[0]));
4231 memset(reference, 0, sizeof(reference[0]));
4232 reference->construct_type.kind = CONSTRUCT_REFERENCE;
4234 return (construct_type_t*)reference;
4237 static construct_type_t *parse_array_declarator(void)
4240 add_anchor_token(']');
4242 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4243 memset(array, 0, sizeof(array[0]));
4244 array->construct_type.kind = CONSTRUCT_ARRAY;
4246 if (token.type == T_static) {
4247 array->is_static = true;
4251 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4252 if (type_qualifiers != 0) {
4253 if (token.type == T_static) {
4254 array->is_static = true;
4258 array->type_qualifiers = type_qualifiers;
4260 if (token.type == '*' && look_ahead(1)->type == ']') {
4261 array->is_variable = true;
4263 } else if (token.type != ']') {
4264 array->size = parse_assignment_expression();
4267 rem_anchor_token(']');
4271 return &array->construct_type;
4274 static construct_type_t *parse_function_declarator(scope_t *scope,
4275 decl_modifiers_t modifiers)
4277 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4278 function_type_t *ftype = &type->function;
4280 ftype->linkage = current_linkage;
4282 switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
4283 case DM_NONE: break;
4284 case DM_CDECL: ftype->calling_convention = CC_CDECL; break;
4285 case DM_STDCALL: ftype->calling_convention = CC_STDCALL; break;
4286 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
4287 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
4290 errorf(HERE, "multiple calling conventions in declaration");
4294 parse_parameters(ftype, scope);
4296 construct_function_type_t *construct_function_type =
4297 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4298 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4299 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4300 construct_function_type->function_type = type;
4302 return &construct_function_type->construct_type;
4305 typedef struct parse_declarator_env_t {
4306 decl_modifiers_t modifiers;
4308 source_position_t source_position;
4310 } parse_declarator_env_t;
4312 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4313 bool may_be_abstract)
4315 /* construct a single linked list of construct_type_t's which describe
4316 * how to construct the final declarator type */
4317 construct_type_t *first = NULL;
4318 construct_type_t *last = NULL;
4319 gnu_attribute_t *attributes = NULL;
4321 decl_modifiers_t modifiers = parse_attributes(&attributes);
4323 /* MS __based extension */
4324 based_spec_t base_spec;
4325 base_spec.base_variable = NULL;
4328 construct_type_t *type;
4329 switch (token.type) {
4331 if (!(c_mode & _CXX))
4332 errorf(HERE, "references are only available for C++");
4333 if (base_spec.base_variable != NULL && warning.other) {
4334 warningf(&base_spec.source_position,
4335 "__based does not precede a pointer operator, ignored");
4337 type = parse_reference_declarator();
4339 base_spec.base_variable = NULL;
4343 type = parse_pointer_declarator(base_spec.base_variable);
4345 base_spec.base_variable = NULL;
4351 add_anchor_token(')');
4352 parse_microsoft_based(&base_spec);
4353 rem_anchor_token(')');
4358 goto ptr_operator_end;
4369 /* TODO: find out if this is correct */
4370 modifiers |= parse_attributes(&attributes);
4373 if (base_spec.base_variable != NULL && warning.other) {
4374 warningf(&base_spec.source_position,
4375 "__based does not precede a pointer operator, ignored");
4379 modifiers |= env->modifiers;
4380 env->modifiers = modifiers;
4383 construct_type_t *inner_types = NULL;
4385 switch (token.type) {
4388 errorf(HERE, "no identifier expected in typename");
4390 env->symbol = token.v.symbol;
4391 env->source_position = token.source_position;
4397 add_anchor_token(')');
4398 inner_types = parse_inner_declarator(env, may_be_abstract);
4399 if (inner_types != NULL) {
4400 /* All later declarators only modify the return type */
4403 rem_anchor_token(')');
4407 if (may_be_abstract)
4409 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4414 construct_type_t *p = last;
4417 construct_type_t *type;
4418 switch (token.type) {
4420 scope_t *scope = NULL;
4422 scope = &env->parameters;
4424 type = parse_function_declarator(scope, modifiers);
4428 type = parse_array_declarator();
4431 goto declarator_finished;
4434 /* insert in the middle of the list (behind p) */
4436 type->next = p->next;
4447 declarator_finished:
4448 /* append inner_types at the end of the list, we don't to set last anymore
4449 * as it's not needed anymore */
4451 assert(first == NULL);
4452 first = inner_types;
4454 last->next = inner_types;
4462 static void parse_declaration_attributes(entity_t *entity)
4464 gnu_attribute_t *attributes = NULL;
4465 decl_modifiers_t modifiers = parse_attributes(&attributes);
4471 if (entity->kind == ENTITY_TYPEDEF) {
4472 modifiers |= entity->typedefe.modifiers;
4473 type = entity->typedefe.type;
4475 assert(is_declaration(entity));
4476 modifiers |= entity->declaration.modifiers;
4477 type = entity->declaration.type;
4482 /* handle these strange/stupid mode attributes */
4483 gnu_attribute_t *attribute = attributes;
4484 for ( ; attribute != NULL; attribute = attribute->next) {
4485 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4488 atomic_type_kind_t akind = attribute->u.akind;
4489 if (!is_type_signed(type)) {
4491 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4492 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4493 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4494 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4496 panic("invalid akind in mode attribute");
4500 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_SCHAR; break;
4501 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_SHORT; break;
4502 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_INT; break;
4503 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_LONGLONG; break;
4505 panic("invalid akind in mode attribute");
4509 type = make_atomic_type(akind, type->base.qualifiers);
4512 type_modifiers_t type_modifiers = type->base.modifiers;
4513 if (modifiers & DM_TRANSPARENT_UNION)
4514 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4516 if (type->base.modifiers != type_modifiers) {
4517 type_t *copy = duplicate_type(type);
4518 copy->base.modifiers = type_modifiers;
4520 type = typehash_insert(copy);
4522 obstack_free(type_obst, copy);
4526 if (entity->kind == ENTITY_TYPEDEF) {
4527 entity->typedefe.type = type;
4528 entity->typedefe.modifiers = modifiers;
4530 entity->declaration.type = type;
4531 entity->declaration.modifiers = modifiers;
4535 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
4537 construct_type_t *iter = construct_list;
4538 for (; iter != NULL; iter = iter->next) {
4539 switch (iter->kind) {
4540 case CONSTRUCT_INVALID:
4541 internal_errorf(HERE, "invalid type construction found");
4542 case CONSTRUCT_FUNCTION: {
4543 construct_function_type_t *construct_function_type
4544 = (construct_function_type_t*) iter;
4546 type_t *function_type = construct_function_type->function_type;
4548 function_type->function.return_type = type;
4550 type_t *skipped_return_type = skip_typeref(type);
4552 if (is_type_function(skipped_return_type)) {
4553 errorf(HERE, "function returning function is not allowed");
4554 } else if (is_type_array(skipped_return_type)) {
4555 errorf(HERE, "function returning array is not allowed");
4557 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4559 "type qualifiers in return type of function type are meaningless");
4563 type = function_type;
4567 case CONSTRUCT_POINTER: {
4568 if (is_type_reference(skip_typeref(type)))
4569 errorf(HERE, "cannot declare a pointer to reference");
4571 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4572 type = make_based_pointer_type(type, parsed_pointer->type_qualifiers, parsed_pointer->base_variable);
4576 case CONSTRUCT_REFERENCE:
4577 if (is_type_reference(skip_typeref(type)))
4578 errorf(HERE, "cannot declare a reference to reference");
4580 type = make_reference_type(type);
4583 case CONSTRUCT_ARRAY: {
4584 if (is_type_reference(skip_typeref(type)))
4585 errorf(HERE, "cannot declare an array of references");
4587 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4588 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4590 expression_t *size_expression = parsed_array->size;
4591 if (size_expression != NULL) {
4593 = create_implicit_cast(size_expression, type_size_t);
4596 array_type->base.qualifiers = parsed_array->type_qualifiers;
4597 array_type->array.element_type = type;
4598 array_type->array.is_static = parsed_array->is_static;
4599 array_type->array.is_variable = parsed_array->is_variable;
4600 array_type->array.size_expression = size_expression;
4602 if (size_expression != NULL) {
4603 if (is_constant_expression(size_expression)) {
4604 array_type->array.size_constant = true;
4605 array_type->array.size
4606 = fold_constant(size_expression);
4608 array_type->array.is_vla = true;
4612 type_t *skipped_type = skip_typeref(type);
4614 if (is_type_incomplete(skipped_type)) {
4615 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4616 } else if (is_type_function(skipped_type)) {
4617 errorf(HERE, "array of functions is not allowed");
4624 type_t *hashed_type = typehash_insert(type);
4625 if (hashed_type != type) {
4626 /* the function type was constructed earlier freeing it here will
4627 * destroy other types... */
4628 if (iter->kind != CONSTRUCT_FUNCTION) {
4638 static type_t *automatic_type_conversion(type_t *orig_type);
4640 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4641 declarator_flags_t flags)
4643 parse_declarator_env_t env;
4644 memset(&env, 0, sizeof(env));
4645 env.modifiers = specifiers->modifiers;
4647 construct_type_t *construct_type =
4648 parse_inner_declarator(&env, (flags & DECL_MAY_BE_ABSTRACT) != 0);
4650 construct_declarator_type(construct_type, specifiers->type);
4651 type_t *type = skip_typeref(orig_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 = orig_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);
4682 if (specifiers->is_inline && is_type_valid(type)) {
4683 errorf(&env.source_position,
4684 "compound member '%Y' declared 'inline'", env.symbol);
4687 if (specifiers->thread_local ||
4688 specifiers->storage_class != STORAGE_CLASS_NONE) {
4689 errorf(&env.source_position,
4690 "compound member '%Y' must have no storage class",
4693 } else if (flags & DECL_IS_PARAMETER) {
4694 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
4695 * shall be adjusted to ``qualified pointer to type'',
4697 * §6.7.5.3:8 A declaration of a parameter as ``function returning
4698 * type'' shall be adjusted to ``pointer to function
4699 * returning type'', as in 6.3.2.1. */
4700 orig_type = automatic_type_conversion(type);
4701 goto create_variable;
4702 } else if (is_type_function(type)) {
4703 entity = allocate_entity_zero(ENTITY_FUNCTION);
4705 entity->function.is_inline = specifiers->is_inline;
4706 entity->function.parameters = env.parameters;
4708 if (specifiers->thread_local || (
4709 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4710 specifiers->storage_class != STORAGE_CLASS_NONE &&
4711 specifiers->storage_class != STORAGE_CLASS_STATIC)
4713 errorf(&env.source_position,
4714 "invalid storage class for function '%Y'", env.symbol);
4718 entity = allocate_entity_zero(ENTITY_VARIABLE);
4720 entity->variable.get_property_sym = specifiers->get_property_sym;
4721 entity->variable.put_property_sym = specifiers->put_property_sym;
4722 if (specifiers->alignment != 0) {
4723 /* TODO: add checks here */
4724 entity->variable.alignment = specifiers->alignment;
4727 if (specifiers->is_inline && is_type_valid(type)) {
4728 errorf(&env.source_position,
4729 "variable '%Y' declared 'inline'", env.symbol);
4732 entity->variable.thread_local = specifiers->thread_local;
4734 bool invalid_storage_class = false;
4735 if (current_scope == file_scope) {
4736 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4737 specifiers->storage_class != STORAGE_CLASS_NONE &&
4738 specifiers->storage_class != STORAGE_CLASS_STATIC) {
4739 invalid_storage_class = true;
4742 if (specifiers->thread_local &&
4743 specifiers->storage_class == STORAGE_CLASS_NONE) {
4744 invalid_storage_class = true;
4747 if (invalid_storage_class) {
4748 errorf(&env.source_position,
4749 "invalid storage class for variable '%Y'", env.symbol);
4753 entity->base.source_position = env.source_position;
4754 entity->base.symbol = env.symbol;
4755 entity->base.namespc = NAMESPACE_NORMAL;
4756 entity->declaration.type = orig_type;
4757 entity->declaration.modifiers = env.modifiers;
4758 entity->declaration.deprecated_string = specifiers->deprecated_string;
4760 storage_class_t storage_class = specifiers->storage_class;
4761 entity->declaration.declared_storage_class = storage_class;
4763 if (storage_class == STORAGE_CLASS_NONE
4764 && current_scope != file_scope) {
4765 storage_class = STORAGE_CLASS_AUTO;
4767 entity->declaration.storage_class = storage_class;
4770 parse_declaration_attributes(entity);
4775 static type_t *parse_abstract_declarator(type_t *base_type)
4777 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4779 type_t *result = construct_declarator_type(construct_type, base_type);
4780 if (construct_type != NULL) {
4781 obstack_free(&temp_obst, construct_type);
4788 * Check if the declaration of main is suspicious. main should be a
4789 * function with external linkage, returning int, taking either zero
4790 * arguments, two, or three arguments of appropriate types, ie.
4792 * int main([ int argc, char **argv [, char **env ] ]).
4794 * @param decl the declaration to check
4795 * @param type the function type of the declaration
4797 static void check_type_of_main(const entity_t *entity)
4799 const source_position_t *pos = &entity->base.source_position;
4800 if (entity->kind != ENTITY_FUNCTION) {
4801 warningf(pos, "'main' is not a function");
4805 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4806 warningf(pos, "'main' is normally a non-static function");
4809 type_t *type = skip_typeref(entity->declaration.type);
4810 assert(is_type_function(type));
4812 function_type_t *func_type = &type->function;
4813 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4814 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4815 func_type->return_type);
4817 const function_parameter_t *parm = func_type->parameters;
4819 type_t *const first_type = parm->type;
4820 if (!types_compatible(skip_typeref(first_type), type_int)) {
4822 "first argument of 'main' should be 'int', but is '%T'",
4827 type_t *const second_type = parm->type;
4828 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4829 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4833 type_t *const third_type = parm->type;
4834 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4835 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4839 goto warn_arg_count;
4843 warningf(pos, "'main' takes only zero, two or three arguments");
4849 * Check if a symbol is the equal to "main".
4851 static bool is_sym_main(const symbol_t *const sym)
4853 return strcmp(sym->string, "main") == 0;
4856 static const char *get_entity_kind_name(entity_kind_t kind)
4858 switch ((entity_kind_tag_t) kind) {
4859 case ENTITY_FUNCTION: return "function";
4860 case ENTITY_VARIABLE: return "variable";
4861 case ENTITY_COMPOUND_MEMBER: return "compound type member";
4862 case ENTITY_STRUCT: return "struct";
4863 case ENTITY_UNION: return "union";
4864 case ENTITY_ENUM: return "enum";
4865 case ENTITY_ENUM_VALUE: return "enum value";
4866 case ENTITY_LABEL: return "label";
4867 case ENTITY_LOCAL_LABEL: return "local label";
4868 case ENTITY_TYPEDEF: return "typedef";
4869 case ENTITY_NAMESPACE: return "namespace";
4870 case ENTITY_INVALID: break;
4873 panic("Invalid entity kind encountered in get_entity_kind_name");
4876 static void error_redefined_as_different_kind(const source_position_t *pos,
4877 const entity_t *old, entity_kind_t new_kind)
4879 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4880 get_entity_kind_name(old->kind), old->base.symbol,
4881 get_entity_kind_name(new_kind), &old->base.source_position);
4885 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4886 * for various problems that occur for multiple definitions
4888 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4890 const symbol_t *const symbol = entity->base.symbol;
4891 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4892 const source_position_t *pos = &entity->base.source_position;
4894 assert(symbol != NULL);
4895 entity_t *previous_entity = get_entity(symbol, namespc);
4896 /* pushing the same entity twice will break the stack structure */
4897 assert(previous_entity != entity);
4899 if (entity->kind == ENTITY_FUNCTION) {
4900 type_t *const orig_type = entity->declaration.type;
4901 type_t *const type = skip_typeref(orig_type);
4903 assert(is_type_function(type));
4904 if (type->function.unspecified_parameters &&
4905 warning.strict_prototypes &&
4906 previous_entity == NULL) {
4907 warningf(pos, "function declaration '%#T' is not a prototype",
4911 if (warning.main && current_scope == file_scope
4912 && is_sym_main(symbol)) {
4913 check_type_of_main(entity);
4917 if (is_declaration(entity)) {
4918 if (warning.nested_externs
4919 && entity->declaration.storage_class == STORAGE_CLASS_EXTERN
4920 && current_scope != file_scope) {
4921 warningf(pos, "nested extern declaration of '%#T'",
4922 entity->declaration.type, symbol);
4926 if (previous_entity != NULL
4927 && previous_entity->base.parent_scope == ¤t_function->parameters
4928 && current_scope->depth == previous_entity->base.parent_scope->depth+1){
4930 assert(previous_entity->kind == ENTITY_VARIABLE);
4932 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4933 entity->declaration.type, symbol,
4934 previous_entity->declaration.type, symbol,
4935 &previous_entity->base.source_position);
4939 if (previous_entity != NULL
4940 && previous_entity->base.parent_scope == current_scope) {
4942 if (previous_entity->kind != entity->kind) {
4943 error_redefined_as_different_kind(pos, previous_entity,
4947 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4949 "redeclaration of enum entry '%Y' (declared %P)",
4950 symbol, &previous_entity->base.source_position);
4953 if (previous_entity->kind == ENTITY_TYPEDEF) {
4954 /* TODO: C++ allows this for exactly the same type */
4956 "redefinition of typedef '%Y' (declared %P)",
4957 symbol, &previous_entity->base.source_position);
4961 /* at this point we should have only VARIABLES or FUNCTIONS */
4962 assert(is_declaration(previous_entity) && is_declaration(entity));
4964 /* can happen for K&R style declarations */
4965 if (previous_entity->kind == ENTITY_VARIABLE
4966 && previous_entity->declaration.type == NULL
4967 && entity->kind == ENTITY_VARIABLE) {
4968 previous_entity->declaration.type = entity->declaration.type;
4969 previous_entity->declaration.storage_class
4970 = entity->declaration.storage_class;
4971 previous_entity->declaration.declared_storage_class
4972 = entity->declaration.declared_storage_class;
4973 previous_entity->declaration.modifiers
4974 = entity->declaration.modifiers;
4975 previous_entity->declaration.deprecated_string
4976 = entity->declaration.deprecated_string;
4978 assert(entity->declaration.type != NULL);
4980 declaration_t *const previous_declaration
4981 = &previous_entity->declaration;
4982 declaration_t *const declaration = &entity->declaration;
4983 type_t *const orig_type = entity->declaration.type;
4984 type_t *const type = skip_typeref(orig_type);
4986 type_t *prev_type = skip_typeref(previous_declaration->type);
4988 if (!types_compatible(type, prev_type)) {
4990 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4991 orig_type, symbol, previous_declaration->type, symbol,
4992 &previous_entity->base.source_position);
4994 unsigned old_storage_class = previous_declaration->storage_class;
4995 if (warning.redundant_decls && is_definition
4996 && previous_declaration->storage_class == STORAGE_CLASS_STATIC
4997 && !(previous_declaration->modifiers & DM_USED)
4998 && !previous_declaration->used) {
4999 warningf(&previous_entity->base.source_position,
5000 "unnecessary static forward declaration for '%#T'",
5001 previous_declaration->type, symbol);
5004 unsigned new_storage_class = declaration->storage_class;
5005 if (is_type_incomplete(prev_type)) {
5006 previous_declaration->type = type;
5010 /* pretend no storage class means extern for function
5011 * declarations (except if the previous declaration is neither
5012 * none nor extern) */
5013 if (entity->kind == ENTITY_FUNCTION) {
5014 if (prev_type->function.unspecified_parameters) {
5015 previous_declaration->type = type;
5019 switch (old_storage_class) {
5020 case STORAGE_CLASS_NONE:
5021 old_storage_class = STORAGE_CLASS_EXTERN;
5024 case STORAGE_CLASS_EXTERN:
5025 if (is_definition) {
5026 if (warning.missing_prototypes &&
5027 prev_type->function.unspecified_parameters &&
5028 !is_sym_main(symbol)) {
5029 warningf(pos, "no previous prototype for '%#T'",
5032 } else if (new_storage_class == STORAGE_CLASS_NONE) {
5033 new_storage_class = STORAGE_CLASS_EXTERN;
5042 if (old_storage_class == STORAGE_CLASS_EXTERN &&
5043 new_storage_class == STORAGE_CLASS_EXTERN) {
5044 warn_redundant_declaration:
5045 if (!is_definition &&
5046 warning.redundant_decls &&
5047 is_type_valid(prev_type) &&
5048 strcmp(previous_entity->base.source_position.input_name, "<builtin>") != 0) {
5050 "redundant declaration for '%Y' (declared %P)",
5051 symbol, &previous_entity->base.source_position);
5053 } else if (current_function == NULL) {
5054 if (old_storage_class != STORAGE_CLASS_STATIC &&
5055 new_storage_class == STORAGE_CLASS_STATIC) {
5057 "static declaration of '%Y' follows non-static declaration (declared %P)",
5058 symbol, &previous_entity->base.source_position);
5059 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
5060 previous_declaration->storage_class = STORAGE_CLASS_NONE;
5061 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
5063 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
5065 goto error_redeclaration;
5066 goto warn_redundant_declaration;
5068 } else if (is_type_valid(prev_type)) {
5069 if (old_storage_class == new_storage_class) {
5070 error_redeclaration:
5071 errorf(pos, "redeclaration of '%Y' (declared %P)",
5072 symbol, &previous_entity->base.source_position);
5075 "redeclaration of '%Y' with different linkage (declared %P)",
5076 symbol, &previous_entity->base.source_position);
5081 previous_declaration->modifiers |= declaration->modifiers;
5082 if (entity->kind == ENTITY_FUNCTION) {
5083 previous_entity->function.is_inline |= entity->function.is_inline;
5085 return previous_entity;
5088 if (entity->kind == ENTITY_FUNCTION) {
5089 if (is_definition &&
5090 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
5091 if (warning.missing_prototypes && !is_sym_main(symbol)) {
5092 warningf(pos, "no previous prototype for '%#T'",
5093 entity->declaration.type, symbol);
5094 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
5095 warningf(pos, "no previous declaration for '%#T'",
5096 entity->declaration.type, symbol);
5099 } else if (warning.missing_declarations
5100 && entity->kind == ENTITY_VARIABLE
5101 && current_scope == file_scope) {
5102 declaration_t *declaration = &entity->declaration;
5103 if (declaration->storage_class == STORAGE_CLASS_NONE) {
5104 warningf(pos, "no previous declaration for '%#T'",
5105 declaration->type, symbol);
5110 assert(entity->base.parent_scope == NULL);
5111 assert(current_scope != NULL);
5113 entity->base.parent_scope = current_scope;
5114 entity->base.namespc = NAMESPACE_NORMAL;
5115 environment_push(entity);
5116 append_entity(current_scope, entity);
5121 static void parser_error_multiple_definition(entity_t *entity,
5122 const source_position_t *source_position)
5124 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
5125 entity->base.symbol, &entity->base.source_position);
5128 static bool is_declaration_specifier(const token_t *token,
5129 bool only_specifiers_qualifiers)
5131 switch (token->type) {
5136 return is_typedef_symbol(token->v.symbol);
5138 case T___extension__:
5140 return !only_specifiers_qualifiers;
5147 static void parse_init_declarator_rest(entity_t *entity)
5149 assert(is_declaration(entity));
5150 declaration_t *const declaration = &entity->declaration;
5154 type_t *orig_type = declaration->type;
5155 type_t *type = skip_typeref(orig_type);
5157 if (entity->kind == ENTITY_VARIABLE
5158 && entity->variable.initializer != NULL) {
5159 parser_error_multiple_definition(entity, HERE);
5162 bool must_be_constant = false;
5163 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5164 entity->base.parent_scope == file_scope) {
5165 must_be_constant = true;
5168 if (is_type_function(type)) {
5169 errorf(&entity->base.source_position,
5170 "function '%#T' is initialized like a variable",
5171 orig_type, entity->base.symbol);
5172 orig_type = type_error_type;
5175 parse_initializer_env_t env;
5176 env.type = orig_type;
5177 env.must_be_constant = must_be_constant;
5178 env.entity = entity;
5179 current_init_decl = entity;
5181 initializer_t *initializer = parse_initializer(&env);
5182 current_init_decl = NULL;
5184 if (entity->kind == ENTITY_VARIABLE) {
5185 /* § 6.7.5 (22) array initializers for arrays with unknown size
5186 * determine the array type size */
5187 declaration->type = env.type;
5188 entity->variable.initializer = initializer;
5192 /* parse rest of a declaration without any declarator */
5193 static void parse_anonymous_declaration_rest(
5194 const declaration_specifiers_t *specifiers)
5197 anonymous_entity = NULL;
5199 if (warning.other) {
5200 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
5201 specifiers->thread_local) {
5202 warningf(&specifiers->source_position,
5203 "useless storage class in empty declaration");
5206 type_t *type = specifiers->type;
5207 switch (type->kind) {
5208 case TYPE_COMPOUND_STRUCT:
5209 case TYPE_COMPOUND_UNION: {
5210 if (type->compound.compound->base.symbol == NULL) {
5211 warningf(&specifiers->source_position,
5212 "unnamed struct/union that defines no instances");
5221 warningf(&specifiers->source_position, "empty declaration");
5227 static void check_variable_type_complete(entity_t *ent)
5229 if (ent->kind != ENTITY_VARIABLE)
5232 /* §6.7:7 If an identifier for an object is declared with no linkage, the
5233 * type for the object shall be complete [...] */
5234 declaration_t *decl = &ent->declaration;
5235 if (decl->storage_class != STORAGE_CLASS_NONE)
5238 type_t *type = decl->type;
5239 if (!is_type_incomplete(skip_typeref(type)))
5242 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
5243 type, ent->base.symbol);
5247 static void parse_declaration_rest(entity_t *ndeclaration,
5248 const declaration_specifiers_t *specifiers,
5249 parsed_declaration_func finished_declaration)
5251 add_anchor_token(';');
5252 add_anchor_token(',');
5254 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5256 if (token.type == '=') {
5257 parse_init_declarator_rest(entity);
5258 } else if (entity->kind == ENTITY_VARIABLE) {
5259 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
5260 * [...] where the extern specifier is explicitly used. */
5261 declaration_t *decl = &entity->declaration;
5262 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
5263 type_t *type = decl->type;
5264 if (is_type_reference(skip_typeref(type))) {
5265 errorf(&entity->base.source_position,
5266 "reference '%#T' must be initialized",
5267 type, entity->base.symbol);
5272 check_variable_type_complete(entity);
5274 if (token.type != ',')
5278 add_anchor_token('=');
5279 ndeclaration = parse_declarator(specifiers, DECL_FLAGS_NONE);
5280 rem_anchor_token('=');
5285 anonymous_entity = NULL;
5286 rem_anchor_token(';');
5287 rem_anchor_token(',');
5290 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5292 symbol_t *symbol = entity->base.symbol;
5293 if (symbol == NULL) {
5294 errorf(HERE, "anonymous declaration not valid as function parameter");
5298 assert(entity->base.namespc == NAMESPACE_NORMAL);
5299 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5300 if (previous_entity == NULL
5301 || previous_entity->base.parent_scope != current_scope) {
5302 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5307 if (is_definition) {
5308 errorf(HERE, "parameter %Y is initialised", entity->base.symbol);
5311 return record_entity(entity, false);
5314 static void parse_declaration(parsed_declaration_func finished_declaration)
5316 declaration_specifiers_t specifiers;
5317 memset(&specifiers, 0, sizeof(specifiers));
5319 add_anchor_token(';');
5320 parse_declaration_specifiers(&specifiers);
5321 rem_anchor_token(';');
5323 if (token.type == ';') {
5324 parse_anonymous_declaration_rest(&specifiers);
5326 entity_t *entity = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5327 parse_declaration_rest(entity, &specifiers, finished_declaration);
5331 static type_t *get_default_promoted_type(type_t *orig_type)
5333 type_t *result = orig_type;
5335 type_t *type = skip_typeref(orig_type);
5336 if (is_type_integer(type)) {
5337 result = promote_integer(type);
5338 } else if (type == type_float) {
5339 result = type_double;
5345 static void parse_kr_declaration_list(entity_t *entity)
5347 if (entity->kind != ENTITY_FUNCTION)
5350 type_t *type = skip_typeref(entity->declaration.type);
5351 assert(is_type_function(type));
5352 if (!type->function.kr_style_parameters)
5356 add_anchor_token('{');
5358 /* push function parameters */
5359 size_t const top = environment_top();
5360 scope_push(&entity->function.parameters);
5362 entity_t *parameter = entity->function.parameters.entities;
5363 for ( ; parameter != NULL; parameter = parameter->base.next) {
5364 assert(parameter->base.parent_scope == NULL);
5365 parameter->base.parent_scope = current_scope;
5366 environment_push(parameter);
5369 /* parse declaration list */
5370 while (is_declaration_specifier(&token, false)) {
5371 parse_declaration(finished_kr_declaration);
5374 /* pop function parameters */
5375 assert(current_scope == &entity->function.parameters);
5377 environment_pop_to(top);
5379 /* update function type */
5380 type_t *new_type = duplicate_type(type);
5382 function_parameter_t *parameters = NULL;
5383 function_parameter_t *last_parameter = NULL;
5385 entity_t *parameter_declaration = entity->function.parameters.entities;
5386 for (; parameter_declaration != NULL;
5387 parameter_declaration = parameter_declaration->base.next) {
5388 type_t *parameter_type = parameter_declaration->declaration.type;
5389 if (parameter_type == NULL) {
5391 errorf(HERE, "no type specified for function parameter '%Y'",
5392 parameter_declaration->base.symbol);
5394 if (warning.implicit_int) {
5395 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5396 parameter_declaration->base.symbol);
5398 parameter_type = type_int;
5399 parameter_declaration->declaration.type = parameter_type;
5403 semantic_parameter(¶meter_declaration->declaration);
5404 parameter_type = parameter_declaration->declaration.type;
5407 * we need the default promoted types for the function type
5409 parameter_type = get_default_promoted_type(parameter_type);
5411 function_parameter_t *function_parameter
5412 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5413 memset(function_parameter, 0, sizeof(function_parameter[0]));
5415 function_parameter->type = parameter_type;
5416 if (last_parameter != NULL) {
5417 last_parameter->next = function_parameter;
5419 parameters = function_parameter;
5421 last_parameter = function_parameter;
5424 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5426 new_type->function.parameters = parameters;
5427 new_type->function.unspecified_parameters = true;
5429 type = typehash_insert(new_type);
5430 if (type != new_type) {
5431 obstack_free(type_obst, new_type);
5434 entity->declaration.type = type;
5436 rem_anchor_token('{');
5439 static bool first_err = true;
5442 * When called with first_err set, prints the name of the current function,
5445 static void print_in_function(void)
5449 diagnosticf("%s: In function '%Y':\n",
5450 current_function->base.base.source_position.input_name,
5451 current_function->base.base.symbol);
5456 * Check if all labels are defined in the current function.
5457 * Check if all labels are used in the current function.
5459 static void check_labels(void)
5461 for (const goto_statement_t *goto_statement = goto_first;
5462 goto_statement != NULL;
5463 goto_statement = goto_statement->next) {
5464 /* skip computed gotos */
5465 if (goto_statement->expression != NULL)
5468 label_t *label = goto_statement->label;
5471 if (label->base.source_position.input_name == NULL) {
5472 print_in_function();
5473 errorf(&goto_statement->base.source_position,
5474 "label '%Y' used but not defined", label->base.symbol);
5478 if (warning.unused_label) {
5479 for (const label_statement_t *label_statement = label_first;
5480 label_statement != NULL;
5481 label_statement = label_statement->next) {
5482 label_t *label = label_statement->label;
5484 if (! label->used) {
5485 print_in_function();
5486 warningf(&label_statement->base.source_position,
5487 "label '%Y' defined but not used", label->base.symbol);
5493 static void warn_unused_decl(entity_t *entity, entity_t *end,
5494 char const *const what)
5496 for (; entity != NULL; entity = entity->base.next) {
5497 if (!is_declaration(entity))
5500 declaration_t *declaration = &entity->declaration;
5501 if (declaration->implicit)
5504 if (!declaration->used) {
5505 print_in_function();
5506 warningf(&entity->base.source_position, "%s '%Y' is unused",
5507 what, entity->base.symbol);
5508 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5509 print_in_function();
5510 warningf(&entity->base.source_position, "%s '%Y' is never read",
5511 what, entity->base.symbol);
5519 static void check_unused_variables(statement_t *const stmt, void *const env)
5523 switch (stmt->kind) {
5524 case STATEMENT_DECLARATION: {
5525 declaration_statement_t const *const decls = &stmt->declaration;
5526 warn_unused_decl(decls->declarations_begin, decls->declarations_end,
5532 warn_unused_decl(stmt->fors.scope.entities, NULL, "variable");
5541 * Check declarations of current_function for unused entities.
5543 static void check_declarations(void)
5545 if (warning.unused_parameter) {
5546 const scope_t *scope = ¤t_function->parameters;
5548 /* do not issue unused warnings for main */
5549 if (!is_sym_main(current_function->base.base.symbol)) {
5550 warn_unused_decl(scope->entities, NULL, "parameter");
5553 if (warning.unused_variable) {
5554 walk_statements(current_function->statement, check_unused_variables,
5559 static int determine_truth(expression_t const* const cond)
5562 !is_constant_expression(cond) ? 0 :
5563 fold_constant(cond) != 0 ? 1 :
5567 static void check_reachable(statement_t *);
5569 static bool expression_returns(expression_t const *const expr)
5571 switch (expr->kind) {
5573 expression_t const *const func = expr->call.function;
5574 if (func->kind == EXPR_REFERENCE) {
5575 entity_t *entity = func->reference.entity;
5576 if (entity->kind == ENTITY_FUNCTION
5577 && entity->declaration.modifiers & DM_NORETURN)
5581 if (!expression_returns(func))
5584 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5585 if (!expression_returns(arg->expression))
5592 case EXPR_REFERENCE:
5593 case EXPR_REFERENCE_ENUM_VALUE:
5595 case EXPR_CHARACTER_CONSTANT:
5596 case EXPR_WIDE_CHARACTER_CONSTANT:
5597 case EXPR_STRING_LITERAL:
5598 case EXPR_WIDE_STRING_LITERAL:
5599 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5600 case EXPR_LABEL_ADDRESS:
5601 case EXPR_CLASSIFY_TYPE:
5602 case EXPR_SIZEOF: // TODO handle obscure VLA case
5605 case EXPR_BUILTIN_SYMBOL:
5606 case EXPR_BUILTIN_CONSTANT_P:
5607 case EXPR_BUILTIN_PREFETCH:
5612 case EXPR_STATEMENT:
5613 check_reachable(expr->statement.statement);
5614 // TODO check if statement can be left
5617 case EXPR_CONDITIONAL:
5618 // TODO handle constant expression
5620 expression_returns(expr->conditional.condition) && (
5621 expression_returns(expr->conditional.true_expression) ||
5622 expression_returns(expr->conditional.false_expression)
5626 return expression_returns(expr->select.compound);
5628 case EXPR_ARRAY_ACCESS:
5630 expression_returns(expr->array_access.array_ref) &&
5631 expression_returns(expr->array_access.index);
5634 return expression_returns(expr->va_starte.ap);
5637 return expression_returns(expr->va_arge.ap);
5639 EXPR_UNARY_CASES_MANDATORY
5640 return expression_returns(expr->unary.value);
5642 case EXPR_UNARY_THROW:
5646 // TODO handle constant lhs of && and ||
5648 expression_returns(expr->binary.left) &&
5649 expression_returns(expr->binary.right);
5655 panic("unhandled expression");
5658 static bool initializer_returns(initializer_t const *const init)
5660 switch (init->kind) {
5661 case INITIALIZER_VALUE:
5662 return expression_returns(init->value.value);
5664 case INITIALIZER_LIST: {
5665 initializer_t * const* i = init->list.initializers;
5666 initializer_t * const* const end = i + init->list.len;
5667 bool returns = true;
5668 for (; i != end; ++i) {
5669 if (!initializer_returns(*i))
5675 case INITIALIZER_STRING:
5676 case INITIALIZER_WIDE_STRING:
5677 case INITIALIZER_DESIGNATOR: // designators have no payload
5680 panic("unhandled initializer");
5683 static bool noreturn_candidate;
5685 static void check_reachable(statement_t *const stmt)
5687 if (stmt->base.reachable)
5689 if (stmt->kind != STATEMENT_DO_WHILE)
5690 stmt->base.reachable = true;
5692 statement_t *last = stmt;
5694 switch (stmt->kind) {
5695 case STATEMENT_INVALID:
5696 case STATEMENT_EMPTY:
5697 case STATEMENT_LOCAL_LABEL:
5699 next = stmt->base.next;
5702 case STATEMENT_DECLARATION: {
5703 declaration_statement_t const *const decl = &stmt->declaration;
5704 entity_t const * ent = decl->declarations_begin;
5705 entity_t const *const last = decl->declarations_end;
5706 for (;; ent = ent->base.next) {
5707 if (ent->kind == ENTITY_VARIABLE &&
5708 ent->variable.initializer != NULL &&
5709 !initializer_returns(ent->variable.initializer)) {
5715 next = stmt->base.next;
5719 case STATEMENT_COMPOUND:
5720 next = stmt->compound.statements;
5723 case STATEMENT_RETURN: {
5724 expression_t const *const val = stmt->returns.value;
5725 if (val == NULL || expression_returns(val))
5726 noreturn_candidate = false;
5730 case STATEMENT_IF: {
5731 if_statement_t const *const ifs = &stmt->ifs;
5732 expression_t const *const cond = ifs->condition;
5734 if (!expression_returns(cond))
5737 int const val = determine_truth(cond);
5740 check_reachable(ifs->true_statement);
5745 if (ifs->false_statement != NULL) {
5746 check_reachable(ifs->false_statement);
5750 next = stmt->base.next;
5754 case STATEMENT_SWITCH: {
5755 switch_statement_t const *const switchs = &stmt->switchs;
5756 expression_t const *const expr = switchs->expression;
5758 if (!expression_returns(expr))
5761 if (is_constant_expression(expr)) {
5762 long const val = fold_constant(expr);
5763 case_label_statement_t * defaults = NULL;
5764 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5765 if (i->expression == NULL) {
5770 if (i->first_case <= val && val <= i->last_case) {
5771 check_reachable((statement_t*)i);
5776 if (defaults != NULL) {
5777 check_reachable((statement_t*)defaults);
5781 bool has_default = false;
5782 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5783 if (i->expression == NULL)
5786 check_reachable((statement_t*)i);
5793 next = stmt->base.next;
5797 case STATEMENT_EXPRESSION: {
5798 /* Check for noreturn function call */
5799 expression_t const *const expr = stmt->expression.expression;
5800 if (!expression_returns(expr))
5803 next = stmt->base.next;
5807 case STATEMENT_CONTINUE: {
5808 statement_t *parent = stmt;
5810 parent = parent->base.parent;
5811 if (parent == NULL) /* continue not within loop */
5815 switch (parent->kind) {
5816 case STATEMENT_WHILE: goto continue_while;
5817 case STATEMENT_DO_WHILE: goto continue_do_while;
5818 case STATEMENT_FOR: goto continue_for;
5825 case STATEMENT_BREAK: {
5826 statement_t *parent = stmt;
5828 parent = parent->base.parent;
5829 if (parent == NULL) /* break not within loop/switch */
5832 switch (parent->kind) {
5833 case STATEMENT_SWITCH:
5834 case STATEMENT_WHILE:
5835 case STATEMENT_DO_WHILE:
5838 next = parent->base.next;
5839 goto found_break_parent;
5848 case STATEMENT_GOTO:
5849 if (stmt->gotos.expression) {
5850 if (!expression_returns(stmt->gotos.expression))
5853 statement_t *parent = stmt->base.parent;
5854 if (parent == NULL) /* top level goto */
5858 next = stmt->gotos.label->statement;
5859 if (next == NULL) /* missing label */
5864 case STATEMENT_LABEL:
5865 next = stmt->label.statement;
5868 case STATEMENT_CASE_LABEL:
5869 next = stmt->case_label.statement;
5872 case STATEMENT_WHILE: {
5873 while_statement_t const *const whiles = &stmt->whiles;
5874 expression_t const *const cond = whiles->condition;
5876 if (!expression_returns(cond))
5879 int const val = determine_truth(cond);
5882 check_reachable(whiles->body);
5887 next = stmt->base.next;
5891 case STATEMENT_DO_WHILE:
5892 next = stmt->do_while.body;
5895 case STATEMENT_FOR: {
5896 for_statement_t *const fors = &stmt->fors;
5898 if (fors->condition_reachable)
5900 fors->condition_reachable = true;
5902 expression_t const *const cond = fors->condition;
5907 } else if (expression_returns(cond)) {
5908 val = determine_truth(cond);
5914 check_reachable(fors->body);
5919 next = stmt->base.next;
5923 case STATEMENT_MS_TRY: {
5924 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5925 check_reachable(ms_try->try_statement);
5926 next = ms_try->final_statement;
5930 case STATEMENT_LEAVE: {
5931 statement_t *parent = stmt;
5933 parent = parent->base.parent;
5934 if (parent == NULL) /* __leave not within __try */
5937 if (parent->kind == STATEMENT_MS_TRY) {
5939 next = parent->ms_try.final_statement;
5947 while (next == NULL) {
5948 next = last->base.parent;
5950 noreturn_candidate = false;
5952 type_t *const type = current_function->base.type;
5953 assert(is_type_function(type));
5954 type_t *const ret = skip_typeref(type->function.return_type);
5955 if (warning.return_type &&
5956 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5957 is_type_valid(ret) &&
5958 !is_sym_main(current_function->base.base.symbol)) {
5959 warningf(&stmt->base.source_position,
5960 "control reaches end of non-void function");
5965 switch (next->kind) {
5966 case STATEMENT_INVALID:
5967 case STATEMENT_EMPTY:
5968 case STATEMENT_DECLARATION:
5969 case STATEMENT_LOCAL_LABEL:
5970 case STATEMENT_EXPRESSION:
5972 case STATEMENT_RETURN:
5973 case STATEMENT_CONTINUE:
5974 case STATEMENT_BREAK:
5975 case STATEMENT_GOTO:
5976 case STATEMENT_LEAVE:
5977 panic("invalid control flow in function");
5979 case STATEMENT_COMPOUND:
5981 case STATEMENT_SWITCH:
5982 case STATEMENT_LABEL:
5983 case STATEMENT_CASE_LABEL:
5985 next = next->base.next;
5988 case STATEMENT_WHILE: {
5990 if (next->base.reachable)
5992 next->base.reachable = true;
5994 while_statement_t const *const whiles = &next->whiles;
5995 expression_t const *const cond = whiles->condition;
5997 if (!expression_returns(cond))
6000 int const val = determine_truth(cond);
6003 check_reachable(whiles->body);
6009 next = next->base.next;
6013 case STATEMENT_DO_WHILE: {
6015 if (next->base.reachable)
6017 next->base.reachable = true;
6019 do_while_statement_t const *const dw = &next->do_while;
6020 expression_t const *const cond = dw->condition;
6022 if (!expression_returns(cond))
6025 int const val = determine_truth(cond);
6028 check_reachable(dw->body);
6034 next = next->base.next;
6038 case STATEMENT_FOR: {
6040 for_statement_t *const fors = &next->fors;
6042 fors->step_reachable = true;
6044 if (fors->condition_reachable)
6046 fors->condition_reachable = true;
6048 expression_t const *const cond = fors->condition;
6050 if (!expression_returns(cond))
6053 int const val = cond == NULL ? 1 : determine_truth(cond);
6056 check_reachable(fors->body);
6062 next = next->base.next;
6066 case STATEMENT_MS_TRY:
6068 next = next->ms_try.final_statement;
6073 check_reachable(next);
6076 static void check_unreachable(statement_t* const stmt, void *const env)
6080 switch (stmt->kind) {
6081 case STATEMENT_DO_WHILE:
6082 if (!stmt->base.reachable) {
6083 expression_t const *const cond = stmt->do_while.condition;
6084 if (determine_truth(cond) >= 0) {
6085 warningf(&cond->base.source_position,
6086 "condition of do-while-loop is unreachable");
6091 case STATEMENT_FOR: {
6092 for_statement_t const* const fors = &stmt->fors;
6094 // if init and step are unreachable, cond is unreachable, too
6095 if (!stmt->base.reachable && !fors->step_reachable) {
6096 warningf(&stmt->base.source_position, "statement is unreachable");
6098 if (!stmt->base.reachable && fors->initialisation != NULL) {
6099 warningf(&fors->initialisation->base.source_position,
6100 "initialisation of for-statement is unreachable");
6103 if (!fors->condition_reachable && fors->condition != NULL) {
6104 warningf(&fors->condition->base.source_position,
6105 "condition of for-statement is unreachable");
6108 if (!fors->step_reachable && fors->step != NULL) {
6109 warningf(&fors->step->base.source_position,
6110 "step of for-statement is unreachable");
6116 case STATEMENT_COMPOUND:
6117 if (stmt->compound.statements != NULL)
6122 if (!stmt->base.reachable)
6123 warningf(&stmt->base.source_position, "statement is unreachable");
6128 static void parse_external_declaration(void)
6130 /* function-definitions and declarations both start with declaration
6132 declaration_specifiers_t specifiers;
6133 memset(&specifiers, 0, sizeof(specifiers));
6135 add_anchor_token(';');
6136 parse_declaration_specifiers(&specifiers);
6137 rem_anchor_token(';');
6139 /* must be a declaration */
6140 if (token.type == ';') {
6141 parse_anonymous_declaration_rest(&specifiers);
6145 add_anchor_token(',');
6146 add_anchor_token('=');
6147 add_anchor_token(';');
6148 add_anchor_token('{');
6150 /* declarator is common to both function-definitions and declarations */
6151 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
6153 rem_anchor_token('{');
6154 rem_anchor_token(';');
6155 rem_anchor_token('=');
6156 rem_anchor_token(',');
6158 /* must be a declaration */
6159 switch (token.type) {
6163 parse_declaration_rest(ndeclaration, &specifiers, record_entity);
6167 /* must be a function definition */
6168 parse_kr_declaration_list(ndeclaration);
6170 if (token.type != '{') {
6171 parse_error_expected("while parsing function definition", '{', NULL);
6172 eat_until_matching_token(';');
6176 assert(is_declaration(ndeclaration));
6177 type_t *type = skip_typeref(ndeclaration->declaration.type);
6179 if (!is_type_function(type)) {
6180 if (is_type_valid(type)) {
6181 errorf(HERE, "declarator '%#T' has a body but is not a function type",
6182 type, ndeclaration->base.symbol);
6188 if (warning.aggregate_return &&
6189 is_type_compound(skip_typeref(type->function.return_type))) {
6190 warningf(HERE, "function '%Y' returns an aggregate",
6191 ndeclaration->base.symbol);
6193 if (warning.traditional && !type->function.unspecified_parameters) {
6194 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6195 ndeclaration->base.symbol);
6197 if (warning.old_style_definition && type->function.unspecified_parameters) {
6198 warningf(HERE, "old-style function definition '%Y'",
6199 ndeclaration->base.symbol);
6202 /* § 6.7.5.3 (14) a function definition with () means no
6203 * parameters (and not unspecified parameters) */
6204 if (type->function.unspecified_parameters
6205 && type->function.parameters == NULL
6206 && !type->function.kr_style_parameters) {
6207 type_t *duplicate = duplicate_type(type);
6208 duplicate->function.unspecified_parameters = false;
6210 type = typehash_insert(duplicate);
6211 if (type != duplicate) {
6212 obstack_free(type_obst, duplicate);
6214 ndeclaration->declaration.type = type;
6217 entity_t *const entity = record_entity(ndeclaration, true);
6218 assert(entity->kind == ENTITY_FUNCTION);
6219 assert(ndeclaration->kind == ENTITY_FUNCTION);
6221 function_t *function = &entity->function;
6222 if (ndeclaration != entity) {
6223 function->parameters = ndeclaration->function.parameters;
6225 assert(is_declaration(entity));
6226 type = skip_typeref(entity->declaration.type);
6228 /* push function parameters and switch scope */
6229 size_t const top = environment_top();
6230 scope_push(&function->parameters);
6232 entity_t *parameter = function->parameters.entities;
6233 for (; parameter != NULL; parameter = parameter->base.next) {
6234 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6235 parameter->base.parent_scope = current_scope;
6237 assert(parameter->base.parent_scope == NULL
6238 || parameter->base.parent_scope == current_scope);
6239 parameter->base.parent_scope = current_scope;
6240 if (parameter->base.symbol == NULL) {
6241 errorf(¶meter->base.source_position, "parameter name omitted");
6244 environment_push(parameter);
6247 if (function->statement != NULL) {
6248 parser_error_multiple_definition(entity, HERE);
6251 /* parse function body */
6252 int label_stack_top = label_top();
6253 function_t *old_current_function = current_function;
6254 current_function = function;
6255 current_parent = NULL;
6258 goto_anchor = &goto_first;
6260 label_anchor = &label_first;
6262 statement_t *const body = parse_compound_statement(false);
6263 function->statement = body;
6266 check_declarations();
6267 if (warning.return_type ||
6268 warning.unreachable_code ||
6269 (warning.missing_noreturn
6270 && !(function->base.modifiers & DM_NORETURN))) {
6271 noreturn_candidate = true;
6272 check_reachable(body);
6273 if (warning.unreachable_code)
6274 walk_statements(body, check_unreachable, NULL);
6275 if (warning.missing_noreturn &&
6276 noreturn_candidate &&
6277 !(function->base.modifiers & DM_NORETURN)) {
6278 warningf(&body->base.source_position,
6279 "function '%#T' is candidate for attribute 'noreturn'",
6280 type, entity->base.symbol);
6284 assert(current_parent == NULL);
6285 assert(current_function == function);
6286 current_function = old_current_function;
6287 label_pop_to(label_stack_top);
6290 assert(current_scope == &function->parameters);
6292 environment_pop_to(top);
6295 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6296 source_position_t *source_position,
6297 const symbol_t *symbol)
6299 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6301 type->bitfield.base_type = base_type;
6302 type->bitfield.size_expression = size;
6305 type_t *skipped_type = skip_typeref(base_type);
6306 if (!is_type_integer(skipped_type)) {
6307 errorf(HERE, "bitfield base type '%T' is not an integer type",
6311 bit_size = skipped_type->base.size * 8;
6314 if (is_constant_expression(size)) {
6315 long v = fold_constant(size);
6318 errorf(source_position, "negative width in bit-field '%Y'", symbol);
6319 } else if (v == 0) {
6320 errorf(source_position, "zero width for bit-field '%Y'", symbol);
6321 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6322 errorf(source_position, "width of '%Y' exceeds its type", symbol);
6324 type->bitfield.bit_size = v;
6331 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6333 entity_t *iter = compound->members.entities;
6334 for (; iter != NULL; iter = iter->base.next) {
6335 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6338 if (iter->base.symbol == symbol) {
6340 } else if (iter->base.symbol == NULL) {
6341 type_t *type = skip_typeref(iter->declaration.type);
6342 if (is_type_compound(type)) {
6344 = find_compound_entry(type->compound.compound, symbol);
6355 static void parse_compound_declarators(compound_t *compound,
6356 const declaration_specifiers_t *specifiers)
6361 if (token.type == ':') {
6362 source_position_t source_position = *HERE;
6365 type_t *base_type = specifiers->type;
6366 expression_t *size = parse_constant_expression();
6368 type_t *type = make_bitfield_type(base_type, size,
6369 &source_position, sym_anonymous);
6371 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6372 entity->base.namespc = NAMESPACE_NORMAL;
6373 entity->base.source_position = source_position;
6374 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6375 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6376 entity->declaration.modifiers = specifiers->modifiers;
6377 entity->declaration.type = type;
6379 entity = parse_declarator(specifiers,
6380 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
6381 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6383 if (token.type == ':') {
6384 source_position_t source_position = *HERE;
6386 expression_t *size = parse_constant_expression();
6388 type_t *type = entity->declaration.type;
6389 type_t *bitfield_type = make_bitfield_type(type, size,
6390 &source_position, entity->base.symbol);
6391 entity->declaration.type = bitfield_type;
6395 /* make sure we don't define a symbol multiple times */
6396 symbol_t *symbol = entity->base.symbol;
6397 if (symbol != NULL) {
6398 entity_t *prev = find_compound_entry(compound, symbol);
6401 errorf(&entity->base.source_position,
6402 "multiple declarations of symbol '%Y' (declared %P)",
6403 symbol, &prev->base.source_position);
6407 append_entity(&compound->members, entity);
6409 type_t *orig_type = entity->declaration.type;
6410 type_t *type = skip_typeref(orig_type);
6411 if (is_type_function(type)) {
6412 errorf(&entity->base.source_position,
6413 "compound member '%Y' must not have function type '%T'",
6414 entity->base.symbol, orig_type);
6415 } else if (is_type_incomplete(type)) {
6416 /* §6.7.2.1:16 flexible array member */
6417 if (is_type_array(type) &&
6418 token.type == ';' &&
6419 look_ahead(1)->type == '}') {
6420 compound->has_flexible_member = true;
6422 errorf(&entity->base.source_position,
6423 "compound member '%Y' has incomplete type '%T'",
6424 entity->base.symbol, orig_type);
6428 if (token.type != ',')
6435 anonymous_entity = NULL;
6438 static void parse_compound_type_entries(compound_t *compound)
6441 add_anchor_token('}');
6443 while (token.type != '}') {
6444 if (token.type == T_EOF) {
6445 errorf(HERE, "EOF while parsing struct");
6448 declaration_specifiers_t specifiers;
6449 memset(&specifiers, 0, sizeof(specifiers));
6450 parse_declaration_specifiers(&specifiers);
6452 parse_compound_declarators(compound, &specifiers);
6454 rem_anchor_token('}');
6458 compound->complete = true;
6461 static type_t *parse_typename(void)
6463 declaration_specifiers_t specifiers;
6464 memset(&specifiers, 0, sizeof(specifiers));
6465 parse_declaration_specifiers(&specifiers);
6466 if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6467 specifiers.thread_local) {
6468 /* TODO: improve error message, user does probably not know what a
6469 * storage class is...
6471 errorf(HERE, "typename may not have a storage class");
6474 type_t *result = parse_abstract_declarator(specifiers.type);
6482 typedef expression_t* (*parse_expression_function)(void);
6483 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6485 typedef struct expression_parser_function_t expression_parser_function_t;
6486 struct expression_parser_function_t {
6487 parse_expression_function parser;
6488 unsigned infix_precedence;
6489 parse_expression_infix_function infix_parser;
6492 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6495 * Prints an error message if an expression was expected but not read
6497 static expression_t *expected_expression_error(void)
6499 /* skip the error message if the error token was read */
6500 if (token.type != T_ERROR) {
6501 errorf(HERE, "expected expression, got token '%K'", &token);
6505 return create_invalid_expression();
6509 * Parse a string constant.
6511 static expression_t *parse_string_const(void)
6514 if (token.type == T_STRING_LITERAL) {
6515 string_t res = token.v.string;
6517 while (token.type == T_STRING_LITERAL) {
6518 res = concat_strings(&res, &token.v.string);
6521 if (token.type != T_WIDE_STRING_LITERAL) {
6522 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6523 /* note: that we use type_char_ptr here, which is already the
6524 * automatic converted type. revert_automatic_type_conversion
6525 * will construct the array type */
6526 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6527 cnst->string.value = res;
6531 wres = concat_string_wide_string(&res, &token.v.wide_string);
6533 wres = token.v.wide_string;
6538 switch (token.type) {
6539 case T_WIDE_STRING_LITERAL:
6540 wres = concat_wide_strings(&wres, &token.v.wide_string);
6543 case T_STRING_LITERAL:
6544 wres = concat_wide_string_string(&wres, &token.v.string);
6548 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6549 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6550 cnst->wide_string.value = wres;
6559 * Parse a boolean constant.
6561 static expression_t *parse_bool_const(bool value)
6563 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6564 cnst->base.type = type_bool;
6565 cnst->conste.v.int_value = value;
6573 * Parse an integer constant.
6575 static expression_t *parse_int_const(void)
6577 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6578 cnst->base.type = token.datatype;
6579 cnst->conste.v.int_value = token.v.intvalue;
6587 * Parse a character constant.
6589 static expression_t *parse_character_constant(void)
6591 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6592 cnst->base.type = token.datatype;
6593 cnst->conste.v.character = token.v.string;
6595 if (cnst->conste.v.character.size != 1) {
6597 errorf(HERE, "more than 1 character in character constant");
6598 } else if (warning.multichar) {
6599 warningf(HERE, "multi-character character constant");
6608 * Parse a wide character constant.
6610 static expression_t *parse_wide_character_constant(void)
6612 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6613 cnst->base.type = token.datatype;
6614 cnst->conste.v.wide_character = token.v.wide_string;
6616 if (cnst->conste.v.wide_character.size != 1) {
6618 errorf(HERE, "more than 1 character in character constant");
6619 } else if (warning.multichar) {
6620 warningf(HERE, "multi-character character constant");
6629 * Parse a float constant.
6631 static expression_t *parse_float_const(void)
6633 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6634 cnst->base.type = token.datatype;
6635 cnst->conste.v.float_value = token.v.floatvalue;
6642 static entity_t *create_implicit_function(symbol_t *symbol,
6643 const source_position_t *source_position)
6645 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6646 ntype->function.return_type = type_int;
6647 ntype->function.unspecified_parameters = true;
6649 type_t *type = typehash_insert(ntype);
6650 if (type != ntype) {
6654 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6655 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6656 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6657 entity->declaration.type = type;
6658 entity->declaration.implicit = true;
6659 entity->base.symbol = symbol;
6660 entity->base.source_position = *source_position;
6662 bool strict_prototypes_old = warning.strict_prototypes;
6663 warning.strict_prototypes = false;
6664 record_entity(entity, false);
6665 warning.strict_prototypes = strict_prototypes_old;
6671 * Creates a return_type (func)(argument_type) function type if not
6674 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6675 type_t *argument_type2)
6677 function_parameter_t *parameter2
6678 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6679 memset(parameter2, 0, sizeof(parameter2[0]));
6680 parameter2->type = argument_type2;
6682 function_parameter_t *parameter1
6683 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6684 memset(parameter1, 0, sizeof(parameter1[0]));
6685 parameter1->type = argument_type1;
6686 parameter1->next = parameter2;
6688 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6689 type->function.return_type = return_type;
6690 type->function.parameters = parameter1;
6692 type_t *result = typehash_insert(type);
6693 if (result != type) {
6701 * Creates a return_type (func)(argument_type) function type if not
6704 * @param return_type the return type
6705 * @param argument_type the argument type
6707 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6709 function_parameter_t *parameter
6710 = obstack_alloc(type_obst, sizeof(parameter[0]));
6711 memset(parameter, 0, sizeof(parameter[0]));
6712 parameter->type = argument_type;
6714 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6715 type->function.return_type = return_type;
6716 type->function.parameters = parameter;
6718 type_t *result = typehash_insert(type);
6719 if (result != type) {
6726 static type_t *make_function_0_type(type_t *return_type)
6728 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6729 type->function.return_type = return_type;
6730 type->function.parameters = NULL;
6732 type_t *result = typehash_insert(type);
6733 if (result != type) {
6741 * Creates a function type for some function like builtins.
6743 * @param symbol the symbol describing the builtin
6745 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6747 switch (symbol->ID) {
6748 case T___builtin_alloca:
6749 return make_function_1_type(type_void_ptr, type_size_t);
6750 case T___builtin_huge_val:
6751 return make_function_0_type(type_double);
6752 case T___builtin_inf:
6753 return make_function_0_type(type_double);
6754 case T___builtin_inff:
6755 return make_function_0_type(type_float);
6756 case T___builtin_infl:
6757 return make_function_0_type(type_long_double);
6758 case T___builtin_nan:
6759 return make_function_1_type(type_double, type_char_ptr);
6760 case T___builtin_nanf:
6761 return make_function_1_type(type_float, type_char_ptr);
6762 case T___builtin_nanl:
6763 return make_function_1_type(type_long_double, type_char_ptr);
6764 case T___builtin_va_end:
6765 return make_function_1_type(type_void, type_valist);
6766 case T___builtin_expect:
6767 return make_function_2_type(type_long, type_long, type_long);
6769 internal_errorf(HERE, "not implemented builtin symbol found");
6774 * Performs automatic type cast as described in § 6.3.2.1.
6776 * @param orig_type the original type
6778 static type_t *automatic_type_conversion(type_t *orig_type)
6780 type_t *type = skip_typeref(orig_type);
6781 if (is_type_array(type)) {
6782 array_type_t *array_type = &type->array;
6783 type_t *element_type = array_type->element_type;
6784 unsigned qualifiers = array_type->base.qualifiers;
6786 return make_pointer_type(element_type, qualifiers);
6789 if (is_type_function(type)) {
6790 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6797 * reverts the automatic casts of array to pointer types and function
6798 * to function-pointer types as defined § 6.3.2.1
6800 type_t *revert_automatic_type_conversion(const expression_t *expression)
6802 switch (expression->kind) {
6803 case EXPR_REFERENCE: {
6804 entity_t *entity = expression->reference.entity;
6805 if (is_declaration(entity)) {
6806 return entity->declaration.type;
6807 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6808 return entity->enum_value.enum_type;
6810 panic("no declaration or enum in reference");
6815 entity_t *entity = expression->select.compound_entry;
6816 assert(is_declaration(entity));
6817 type_t *type = entity->declaration.type;
6818 return get_qualified_type(type,
6819 expression->base.type->base.qualifiers);
6822 case EXPR_UNARY_DEREFERENCE: {
6823 const expression_t *const value = expression->unary.value;
6824 type_t *const type = skip_typeref(value->base.type);
6825 assert(is_type_pointer(type));
6826 return type->pointer.points_to;
6829 case EXPR_BUILTIN_SYMBOL:
6830 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6832 case EXPR_ARRAY_ACCESS: {
6833 const expression_t *array_ref = expression->array_access.array_ref;
6834 type_t *type_left = skip_typeref(array_ref->base.type);
6835 if (!is_type_valid(type_left))
6837 assert(is_type_pointer(type_left));
6838 return type_left->pointer.points_to;
6841 case EXPR_STRING_LITERAL: {
6842 size_t size = expression->string.value.size;
6843 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6846 case EXPR_WIDE_STRING_LITERAL: {
6847 size_t size = expression->wide_string.value.size;
6848 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6851 case EXPR_COMPOUND_LITERAL:
6852 return expression->compound_literal.type;
6857 return expression->base.type;
6860 static expression_t *parse_reference(void)
6862 symbol_t *const symbol = token.v.symbol;
6864 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6866 if (entity == NULL) {
6867 if (!strict_mode && look_ahead(1)->type == '(') {
6868 /* an implicitly declared function */
6869 if (warning.implicit_function_declaration) {
6870 warningf(HERE, "implicit declaration of function '%Y'",
6874 entity = create_implicit_function(symbol, HERE);
6876 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6877 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6883 if (is_declaration(entity)) {
6884 orig_type = entity->declaration.type;
6885 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6886 orig_type = entity->enum_value.enum_type;
6887 } else if (entity->kind == ENTITY_TYPEDEF) {
6888 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
6891 return create_invalid_expression();
6893 panic("expected declaration or enum value in reference");
6896 /* we always do the auto-type conversions; the & and sizeof parser contains
6897 * code to revert this! */
6898 type_t *type = automatic_type_conversion(orig_type);
6900 expression_kind_t kind = EXPR_REFERENCE;
6901 if (entity->kind == ENTITY_ENUM_VALUE)
6902 kind = EXPR_REFERENCE_ENUM_VALUE;
6904 expression_t *expression = allocate_expression_zero(kind);
6905 expression->reference.entity = entity;
6906 expression->base.type = type;
6908 /* this declaration is used */
6909 if (is_declaration(entity)) {
6910 entity->declaration.used = true;
6913 if (entity->base.parent_scope != file_scope
6914 && entity->base.parent_scope->depth < current_function->parameters.depth
6915 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
6916 if (entity->kind == ENTITY_VARIABLE) {
6917 /* access of a variable from an outer function */
6918 entity->variable.address_taken = true;
6920 current_function->need_closure = true;
6923 /* check for deprecated functions */
6924 if (warning.deprecated_declarations
6925 && is_declaration(entity)
6926 && entity->declaration.modifiers & DM_DEPRECATED) {
6927 declaration_t *declaration = &entity->declaration;
6929 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
6930 "function" : "variable";
6932 if (declaration->deprecated_string != NULL) {
6933 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6934 prefix, entity->base.symbol, &entity->base.source_position,
6935 declaration->deprecated_string);
6937 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6938 entity->base.symbol, &entity->base.source_position);
6942 if (warning.init_self && entity == current_init_decl && !in_type_prop
6943 && entity->kind == ENTITY_VARIABLE) {
6944 current_init_decl = NULL;
6945 warningf(HERE, "variable '%#T' is initialized by itself",
6946 entity->declaration.type, entity->base.symbol);
6953 static bool semantic_cast(expression_t *cast)
6955 expression_t *expression = cast->unary.value;
6956 type_t *orig_dest_type = cast->base.type;
6957 type_t *orig_type_right = expression->base.type;
6958 type_t const *dst_type = skip_typeref(orig_dest_type);
6959 type_t const *src_type = skip_typeref(orig_type_right);
6960 source_position_t const *pos = &cast->base.source_position;
6962 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6963 if (dst_type == type_void)
6966 /* only integer and pointer can be casted to pointer */
6967 if (is_type_pointer(dst_type) &&
6968 !is_type_pointer(src_type) &&
6969 !is_type_integer(src_type) &&
6970 is_type_valid(src_type)) {
6971 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6975 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6976 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6980 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6981 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6985 if (warning.cast_qual &&
6986 is_type_pointer(src_type) &&
6987 is_type_pointer(dst_type)) {
6988 type_t *src = skip_typeref(src_type->pointer.points_to);
6989 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6990 unsigned missing_qualifiers =
6991 src->base.qualifiers & ~dst->base.qualifiers;
6992 if (missing_qualifiers != 0) {
6994 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6995 missing_qualifiers, orig_type_right);
7001 static expression_t *parse_compound_literal(type_t *type)
7003 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
7005 parse_initializer_env_t env;
7008 env.must_be_constant = false;
7009 initializer_t *initializer = parse_initializer(&env);
7012 expression->compound_literal.initializer = initializer;
7013 expression->compound_literal.type = type;
7014 expression->base.type = automatic_type_conversion(type);
7020 * Parse a cast expression.
7022 static expression_t *parse_cast(void)
7024 add_anchor_token(')');
7026 source_position_t source_position = token.source_position;
7028 type_t *type = parse_typename();
7030 rem_anchor_token(')');
7033 if (token.type == '{') {
7034 return parse_compound_literal(type);
7037 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
7038 cast->base.source_position = source_position;
7040 expression_t *value = parse_sub_expression(PREC_CAST);
7041 cast->base.type = type;
7042 cast->unary.value = value;
7044 if (! semantic_cast(cast)) {
7045 /* TODO: record the error in the AST. else it is impossible to detect it */
7050 return create_invalid_expression();
7054 * Parse a statement expression.
7056 static expression_t *parse_statement_expression(void)
7058 add_anchor_token(')');
7060 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
7062 statement_t *statement = parse_compound_statement(true);
7063 expression->statement.statement = statement;
7065 /* find last statement and use its type */
7066 type_t *type = type_void;
7067 const statement_t *stmt = statement->compound.statements;
7069 while (stmt->base.next != NULL)
7070 stmt = stmt->base.next;
7072 if (stmt->kind == STATEMENT_EXPRESSION) {
7073 type = stmt->expression.expression->base.type;
7075 } else if (warning.other) {
7076 warningf(&expression->base.source_position, "empty statement expression ({})");
7078 expression->base.type = type;
7080 rem_anchor_token(')');
7088 * Parse a parenthesized expression.
7090 static expression_t *parse_parenthesized_expression(void)
7094 switch (token.type) {
7096 /* gcc extension: a statement expression */
7097 return parse_statement_expression();
7101 return parse_cast();
7103 if (is_typedef_symbol(token.v.symbol)) {
7104 return parse_cast();
7108 add_anchor_token(')');
7109 expression_t *result = parse_expression();
7110 rem_anchor_token(')');
7117 static expression_t *parse_function_keyword(void)
7121 if (current_function == NULL) {
7122 errorf(HERE, "'__func__' used outside of a function");
7125 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7126 expression->base.type = type_char_ptr;
7127 expression->funcname.kind = FUNCNAME_FUNCTION;
7134 static expression_t *parse_pretty_function_keyword(void)
7136 if (current_function == NULL) {
7137 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
7140 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7141 expression->base.type = type_char_ptr;
7142 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
7144 eat(T___PRETTY_FUNCTION__);
7149 static expression_t *parse_funcsig_keyword(void)
7151 if (current_function == NULL) {
7152 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7155 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7156 expression->base.type = type_char_ptr;
7157 expression->funcname.kind = FUNCNAME_FUNCSIG;
7164 static expression_t *parse_funcdname_keyword(void)
7166 if (current_function == NULL) {
7167 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7170 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7171 expression->base.type = type_char_ptr;
7172 expression->funcname.kind = FUNCNAME_FUNCDNAME;
7174 eat(T___FUNCDNAME__);
7179 static designator_t *parse_designator(void)
7181 designator_t *result = allocate_ast_zero(sizeof(result[0]));
7182 result->source_position = *HERE;
7184 if (token.type != T_IDENTIFIER) {
7185 parse_error_expected("while parsing member designator",
7186 T_IDENTIFIER, NULL);
7189 result->symbol = token.v.symbol;
7192 designator_t *last_designator = result;
7194 if (token.type == '.') {
7196 if (token.type != T_IDENTIFIER) {
7197 parse_error_expected("while parsing member designator",
7198 T_IDENTIFIER, NULL);
7201 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7202 designator->source_position = *HERE;
7203 designator->symbol = token.v.symbol;
7206 last_designator->next = designator;
7207 last_designator = designator;
7210 if (token.type == '[') {
7212 add_anchor_token(']');
7213 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7214 designator->source_position = *HERE;
7215 designator->array_index = parse_expression();
7216 rem_anchor_token(']');
7218 if (designator->array_index == NULL) {
7222 last_designator->next = designator;
7223 last_designator = designator;
7235 * Parse the __builtin_offsetof() expression.
7237 static expression_t *parse_offsetof(void)
7239 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7240 expression->base.type = type_size_t;
7242 eat(T___builtin_offsetof);
7245 add_anchor_token(',');
7246 type_t *type = parse_typename();
7247 rem_anchor_token(',');
7249 add_anchor_token(')');
7250 designator_t *designator = parse_designator();
7251 rem_anchor_token(')');
7254 expression->offsetofe.type = type;
7255 expression->offsetofe.designator = designator;
7258 memset(&path, 0, sizeof(path));
7259 path.top_type = type;
7260 path.path = NEW_ARR_F(type_path_entry_t, 0);
7262 descend_into_subtype(&path);
7264 if (!walk_designator(&path, designator, true)) {
7265 return create_invalid_expression();
7268 DEL_ARR_F(path.path);
7272 return create_invalid_expression();
7276 * Parses a _builtin_va_start() expression.
7278 static expression_t *parse_va_start(void)
7280 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7282 eat(T___builtin_va_start);
7285 add_anchor_token(',');
7286 expression->va_starte.ap = parse_assignment_expression();
7287 rem_anchor_token(',');
7289 expression_t *const expr = parse_assignment_expression();
7290 if (expr->kind == EXPR_REFERENCE) {
7291 entity_t *const entity = expr->reference.entity;
7292 if (entity->base.parent_scope != ¤t_function->parameters
7293 || entity->base.next != NULL
7294 || entity->kind != ENTITY_VARIABLE) {
7295 errorf(&expr->base.source_position,
7296 "second argument of 'va_start' must be last parameter of the current function");
7298 expression->va_starte.parameter = &entity->variable;
7305 return create_invalid_expression();
7309 * Parses a _builtin_va_arg() expression.
7311 static expression_t *parse_va_arg(void)
7313 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7315 eat(T___builtin_va_arg);
7318 expression->va_arge.ap = parse_assignment_expression();
7320 expression->base.type = parse_typename();
7325 return create_invalid_expression();
7328 static expression_t *parse_builtin_symbol(void)
7330 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7332 symbol_t *symbol = token.v.symbol;
7334 expression->builtin_symbol.symbol = symbol;
7337 type_t *type = get_builtin_symbol_type(symbol);
7338 type = automatic_type_conversion(type);
7340 expression->base.type = type;
7345 * Parses a __builtin_constant() expression.
7347 static expression_t *parse_builtin_constant(void)
7349 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7351 eat(T___builtin_constant_p);
7354 add_anchor_token(')');
7355 expression->builtin_constant.value = parse_assignment_expression();
7356 rem_anchor_token(')');
7358 expression->base.type = type_int;
7362 return create_invalid_expression();
7366 * Parses a __builtin_prefetch() expression.
7368 static expression_t *parse_builtin_prefetch(void)
7370 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7372 eat(T___builtin_prefetch);
7375 add_anchor_token(')');
7376 expression->builtin_prefetch.adr = parse_assignment_expression();
7377 if (token.type == ',') {
7379 expression->builtin_prefetch.rw = parse_assignment_expression();
7381 if (token.type == ',') {
7383 expression->builtin_prefetch.locality = parse_assignment_expression();
7385 rem_anchor_token(')');
7387 expression->base.type = type_void;
7391 return create_invalid_expression();
7395 * Parses a __builtin_is_*() compare expression.
7397 static expression_t *parse_compare_builtin(void)
7399 expression_t *expression;
7401 switch (token.type) {
7402 case T___builtin_isgreater:
7403 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7405 case T___builtin_isgreaterequal:
7406 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7408 case T___builtin_isless:
7409 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7411 case T___builtin_islessequal:
7412 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7414 case T___builtin_islessgreater:
7415 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7417 case T___builtin_isunordered:
7418 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7421 internal_errorf(HERE, "invalid compare builtin found");
7423 expression->base.source_position = *HERE;
7427 expression->binary.left = parse_assignment_expression();
7429 expression->binary.right = parse_assignment_expression();
7432 type_t *const orig_type_left = expression->binary.left->base.type;
7433 type_t *const orig_type_right = expression->binary.right->base.type;
7435 type_t *const type_left = skip_typeref(orig_type_left);
7436 type_t *const type_right = skip_typeref(orig_type_right);
7437 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7438 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7439 type_error_incompatible("invalid operands in comparison",
7440 &expression->base.source_position, orig_type_left, orig_type_right);
7443 semantic_comparison(&expression->binary);
7448 return create_invalid_expression();
7453 * Parses a __builtin_expect() expression.
7455 static expression_t *parse_builtin_expect(void)
7457 expression_t *expression
7458 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7460 eat(T___builtin_expect);
7463 expression->binary.left = parse_assignment_expression();
7465 expression->binary.right = parse_constant_expression();
7468 expression->base.type = expression->binary.left->base.type;
7472 return create_invalid_expression();
7477 * Parses a MS assume() expression.
7479 static expression_t *parse_assume(void)
7481 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7486 add_anchor_token(')');
7487 expression->unary.value = parse_assignment_expression();
7488 rem_anchor_token(')');
7491 expression->base.type = type_void;
7494 return create_invalid_expression();
7498 * Return the declaration for a given label symbol or create a new one.
7500 * @param symbol the symbol of the label
7502 static label_t *get_label(symbol_t *symbol)
7505 assert(current_function != NULL);
7507 label = get_entity(symbol, NAMESPACE_LABEL);
7508 /* if we found a local label, we already created the declaration */
7509 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7510 if (label->base.parent_scope != current_scope) {
7511 assert(label->base.parent_scope->depth < current_scope->depth);
7512 current_function->goto_to_outer = true;
7514 return &label->label;
7517 label = get_entity(symbol, NAMESPACE_LABEL);
7518 /* if we found a label in the same function, then we already created the
7521 && label->base.parent_scope == ¤t_function->parameters) {
7522 return &label->label;
7525 /* otherwise we need to create a new one */
7526 label = allocate_entity_zero(ENTITY_LABEL);
7527 label->base.namespc = NAMESPACE_LABEL;
7528 label->base.symbol = symbol;
7532 return &label->label;
7536 * Parses a GNU && label address expression.
7538 static expression_t *parse_label_address(void)
7540 source_position_t source_position = token.source_position;
7542 if (token.type != T_IDENTIFIER) {
7543 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7546 symbol_t *symbol = token.v.symbol;
7549 label_t *label = get_label(symbol);
7551 label->address_taken = true;
7553 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7554 expression->base.source_position = source_position;
7556 /* label address is threaten as a void pointer */
7557 expression->base.type = type_void_ptr;
7558 expression->label_address.label = label;
7561 return create_invalid_expression();
7565 * Parse a microsoft __noop expression.
7567 static expression_t *parse_noop_expression(void)
7569 /* the result is a (int)0 */
7570 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7571 cnst->base.type = type_int;
7572 cnst->conste.v.int_value = 0;
7573 cnst->conste.is_ms_noop = true;
7577 if (token.type == '(') {
7578 /* parse arguments */
7580 add_anchor_token(')');
7581 add_anchor_token(',');
7583 if (token.type != ')') {
7585 (void)parse_assignment_expression();
7586 if (token.type != ',')
7592 rem_anchor_token(',');
7593 rem_anchor_token(')');
7601 * Parses a primary expression.
7603 static expression_t *parse_primary_expression(void)
7605 switch (token.type) {
7606 case T_false: return parse_bool_const(false);
7607 case T_true: return parse_bool_const(true);
7608 case T_INTEGER: return parse_int_const();
7609 case T_CHARACTER_CONSTANT: return parse_character_constant();
7610 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7611 case T_FLOATINGPOINT: return parse_float_const();
7612 case T_STRING_LITERAL:
7613 case T_WIDE_STRING_LITERAL: return parse_string_const();
7614 case T_IDENTIFIER: return parse_reference();
7615 case T___FUNCTION__:
7616 case T___func__: return parse_function_keyword();
7617 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7618 case T___FUNCSIG__: return parse_funcsig_keyword();
7619 case T___FUNCDNAME__: return parse_funcdname_keyword();
7620 case T___builtin_offsetof: return parse_offsetof();
7621 case T___builtin_va_start: return parse_va_start();
7622 case T___builtin_va_arg: return parse_va_arg();
7623 case T___builtin_expect:
7624 case T___builtin_alloca:
7625 case T___builtin_inf:
7626 case T___builtin_inff:
7627 case T___builtin_infl:
7628 case T___builtin_nan:
7629 case T___builtin_nanf:
7630 case T___builtin_nanl:
7631 case T___builtin_huge_val:
7632 case T___builtin_va_end: return parse_builtin_symbol();
7633 case T___builtin_isgreater:
7634 case T___builtin_isgreaterequal:
7635 case T___builtin_isless:
7636 case T___builtin_islessequal:
7637 case T___builtin_islessgreater:
7638 case T___builtin_isunordered: return parse_compare_builtin();
7639 case T___builtin_constant_p: return parse_builtin_constant();
7640 case T___builtin_prefetch: return parse_builtin_prefetch();
7641 case T__assume: return parse_assume();
7644 return parse_label_address();
7647 case '(': return parse_parenthesized_expression();
7648 case T___noop: return parse_noop_expression();
7651 errorf(HERE, "unexpected token %K, expected an expression", &token);
7652 return create_invalid_expression();
7656 * Check if the expression has the character type and issue a warning then.
7658 static void check_for_char_index_type(const expression_t *expression)
7660 type_t *const type = expression->base.type;
7661 const type_t *const base_type = skip_typeref(type);
7663 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7664 warning.char_subscripts) {
7665 warningf(&expression->base.source_position,
7666 "array subscript has type '%T'", type);
7670 static expression_t *parse_array_expression(expression_t *left)
7672 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7675 add_anchor_token(']');
7677 expression_t *inside = parse_expression();
7679 type_t *const orig_type_left = left->base.type;
7680 type_t *const orig_type_inside = inside->base.type;
7682 type_t *const type_left = skip_typeref(orig_type_left);
7683 type_t *const type_inside = skip_typeref(orig_type_inside);
7685 type_t *return_type;
7686 array_access_expression_t *array_access = &expression->array_access;
7687 if (is_type_pointer(type_left)) {
7688 return_type = type_left->pointer.points_to;
7689 array_access->array_ref = left;
7690 array_access->index = inside;
7691 check_for_char_index_type(inside);
7692 } else if (is_type_pointer(type_inside)) {
7693 return_type = type_inside->pointer.points_to;
7694 array_access->array_ref = inside;
7695 array_access->index = left;
7696 array_access->flipped = true;
7697 check_for_char_index_type(left);
7699 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7701 "array access on object with non-pointer types '%T', '%T'",
7702 orig_type_left, orig_type_inside);
7704 return_type = type_error_type;
7705 array_access->array_ref = left;
7706 array_access->index = inside;
7709 expression->base.type = automatic_type_conversion(return_type);
7711 rem_anchor_token(']');
7717 static expression_t *parse_typeprop(expression_kind_t const kind)
7719 expression_t *tp_expression = allocate_expression_zero(kind);
7720 tp_expression->base.type = type_size_t;
7722 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7724 /* we only refer to a type property, mark this case */
7725 bool old = in_type_prop;
7726 in_type_prop = true;
7729 expression_t *expression;
7730 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7732 add_anchor_token(')');
7733 orig_type = parse_typename();
7734 rem_anchor_token(')');
7737 if (token.type == '{') {
7738 /* It was not sizeof(type) after all. It is sizeof of an expression
7739 * starting with a compound literal */
7740 expression = parse_compound_literal(orig_type);
7741 goto typeprop_expression;
7744 expression = parse_sub_expression(PREC_UNARY);
7746 typeprop_expression:
7747 tp_expression->typeprop.tp_expression = expression;
7749 orig_type = revert_automatic_type_conversion(expression);
7750 expression->base.type = orig_type;
7753 tp_expression->typeprop.type = orig_type;
7754 type_t const* const type = skip_typeref(orig_type);
7755 char const* const wrong_type =
7756 is_type_incomplete(type) ? "incomplete" :
7757 type->kind == TYPE_FUNCTION ? "function designator" :
7758 type->kind == TYPE_BITFIELD ? "bitfield" :
7760 if (wrong_type != NULL) {
7761 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7762 errorf(&tp_expression->base.source_position,
7763 "operand of %s expression must not be of %s type '%T'",
7764 what, wrong_type, orig_type);
7769 return tp_expression;
7772 static expression_t *parse_sizeof(void)
7774 return parse_typeprop(EXPR_SIZEOF);
7777 static expression_t *parse_alignof(void)
7779 return parse_typeprop(EXPR_ALIGNOF);
7782 static expression_t *parse_select_expression(expression_t *compound)
7784 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7785 select->select.compound = compound;
7787 assert(token.type == '.' || token.type == T_MINUSGREATER);
7788 bool is_pointer = (token.type == T_MINUSGREATER);
7791 if (token.type != T_IDENTIFIER) {
7792 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7795 symbol_t *symbol = token.v.symbol;
7798 type_t *const orig_type = compound->base.type;
7799 type_t *const type = skip_typeref(orig_type);
7802 bool saw_error = false;
7803 if (is_type_pointer(type)) {
7806 "request for member '%Y' in something not a struct or union, but '%T'",
7810 type_left = skip_typeref(type->pointer.points_to);
7812 if (is_pointer && is_type_valid(type)) {
7813 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7820 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7821 type_left->kind == TYPE_COMPOUND_UNION) {
7822 compound_t *compound = type_left->compound.compound;
7824 if (!compound->complete) {
7825 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7827 goto create_error_entry;
7830 entry = find_compound_entry(compound, symbol);
7831 if (entry == NULL) {
7832 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7833 goto create_error_entry;
7836 if (is_type_valid(type_left) && !saw_error) {
7838 "request for member '%Y' in something not a struct or union, but '%T'",
7842 return create_invalid_expression();
7845 assert(is_declaration(entry));
7846 select->select.compound_entry = entry;
7848 type_t *entry_type = entry->declaration.type;
7850 = get_qualified_type(entry_type, type_left->base.qualifiers);
7852 /* we always do the auto-type conversions; the & and sizeof parser contains
7853 * code to revert this! */
7854 select->base.type = automatic_type_conversion(res_type);
7856 type_t *skipped = skip_typeref(res_type);
7857 if (skipped->kind == TYPE_BITFIELD) {
7858 select->base.type = skipped->bitfield.base_type;
7864 static void check_call_argument(const function_parameter_t *parameter,
7865 call_argument_t *argument, unsigned pos)
7867 type_t *expected_type = parameter->type;
7868 type_t *expected_type_skip = skip_typeref(expected_type);
7869 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7870 expression_t *arg_expr = argument->expression;
7871 type_t *arg_type = skip_typeref(arg_expr->base.type);
7873 /* handle transparent union gnu extension */
7874 if (is_type_union(expected_type_skip)
7875 && (expected_type_skip->base.modifiers
7876 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7877 compound_t *union_decl = expected_type_skip->compound.compound;
7878 type_t *best_type = NULL;
7879 entity_t *entry = union_decl->members.entities;
7880 for ( ; entry != NULL; entry = entry->base.next) {
7881 assert(is_declaration(entry));
7882 type_t *decl_type = entry->declaration.type;
7883 error = semantic_assign(decl_type, arg_expr);
7884 if (error == ASSIGN_ERROR_INCOMPATIBLE
7885 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7888 if (error == ASSIGN_SUCCESS) {
7889 best_type = decl_type;
7890 } else if (best_type == NULL) {
7891 best_type = decl_type;
7895 if (best_type != NULL) {
7896 expected_type = best_type;
7900 error = semantic_assign(expected_type, arg_expr);
7901 argument->expression = create_implicit_cast(argument->expression,
7904 if (error != ASSIGN_SUCCESS) {
7905 /* report exact scope in error messages (like "in argument 3") */
7907 snprintf(buf, sizeof(buf), "call argument %u", pos);
7908 report_assign_error(error, expected_type, arg_expr, buf,
7909 &arg_expr->base.source_position);
7910 } else if (warning.traditional || warning.conversion) {
7911 type_t *const promoted_type = get_default_promoted_type(arg_type);
7912 if (!types_compatible(expected_type_skip, promoted_type) &&
7913 !types_compatible(expected_type_skip, type_void_ptr) &&
7914 !types_compatible(type_void_ptr, promoted_type)) {
7915 /* Deliberately show the skipped types in this warning */
7916 warningf(&arg_expr->base.source_position,
7917 "passing call argument %u as '%T' rather than '%T' due to prototype",
7918 pos, expected_type_skip, promoted_type);
7924 * Parse a call expression, ie. expression '( ... )'.
7926 * @param expression the function address
7928 static expression_t *parse_call_expression(expression_t *expression)
7930 expression_t *result = allocate_expression_zero(EXPR_CALL);
7931 call_expression_t *call = &result->call;
7932 call->function = expression;
7934 type_t *const orig_type = expression->base.type;
7935 type_t *const type = skip_typeref(orig_type);
7937 function_type_t *function_type = NULL;
7938 if (is_type_pointer(type)) {
7939 type_t *const to_type = skip_typeref(type->pointer.points_to);
7941 if (is_type_function(to_type)) {
7942 function_type = &to_type->function;
7943 call->base.type = function_type->return_type;
7947 if (function_type == NULL && is_type_valid(type)) {
7948 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7951 /* parse arguments */
7953 add_anchor_token(')');
7954 add_anchor_token(',');
7956 if (token.type != ')') {
7957 call_argument_t *last_argument = NULL;
7960 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7962 argument->expression = parse_assignment_expression();
7963 if (last_argument == NULL) {
7964 call->arguments = argument;
7966 last_argument->next = argument;
7968 last_argument = argument;
7970 if (token.type != ',')
7975 rem_anchor_token(',');
7976 rem_anchor_token(')');
7979 if (function_type == NULL)
7982 function_parameter_t *parameter = function_type->parameters;
7983 call_argument_t *argument = call->arguments;
7984 if (!function_type->unspecified_parameters) {
7985 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7986 parameter = parameter->next, argument = argument->next) {
7987 check_call_argument(parameter, argument, ++pos);
7990 if (parameter != NULL) {
7991 errorf(HERE, "too few arguments to function '%E'", expression);
7992 } else if (argument != NULL && !function_type->variadic) {
7993 errorf(HERE, "too many arguments to function '%E'", expression);
7997 /* do default promotion */
7998 for (; argument != NULL; argument = argument->next) {
7999 type_t *type = argument->expression->base.type;
8001 type = get_default_promoted_type(type);
8003 argument->expression
8004 = create_implicit_cast(argument->expression, type);
8007 check_format(&result->call);
8009 if (warning.aggregate_return &&
8010 is_type_compound(skip_typeref(function_type->return_type))) {
8011 warningf(&result->base.source_position,
8012 "function call has aggregate value");
8019 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
8021 static bool same_compound_type(const type_t *type1, const type_t *type2)
8024 is_type_compound(type1) &&
8025 type1->kind == type2->kind &&
8026 type1->compound.compound == type2->compound.compound;
8029 static expression_t const *get_reference_address(expression_t const *expr)
8031 bool regular_take_address = true;
8033 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8034 expr = expr->unary.value;
8036 regular_take_address = false;
8039 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8042 expr = expr->unary.value;
8045 if (expr->kind != EXPR_REFERENCE)
8048 /* special case for functions which are automatically converted to a
8049 * pointer to function without an extra TAKE_ADDRESS operation */
8050 if (!regular_take_address &&
8051 expr->reference.entity->kind != ENTITY_FUNCTION) {
8058 static void warn_reference_address_as_bool(expression_t const* expr)
8060 if (!warning.address)
8063 expr = get_reference_address(expr);
8065 warningf(&expr->base.source_position,
8066 "the address of '%Y' will always evaluate as 'true'",
8067 expr->reference.entity->base.symbol);
8071 static void semantic_condition(expression_t const *const expr,
8072 char const *const context)
8074 type_t *const type = skip_typeref(expr->base.type);
8075 if (is_type_scalar(type)) {
8076 warn_reference_address_as_bool(expr);
8077 } else if (is_type_valid(type)) {
8078 errorf(&expr->base.source_position,
8079 "%s must have scalar type", context);
8084 * Parse a conditional expression, ie. 'expression ? ... : ...'.
8086 * @param expression the conditional expression
8088 static expression_t *parse_conditional_expression(expression_t *expression)
8090 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
8092 conditional_expression_t *conditional = &result->conditional;
8093 conditional->condition = expression;
8096 add_anchor_token(':');
8098 /* §6.5.15:2 The first operand shall have scalar type. */
8099 semantic_condition(expression, "condition of conditional operator");
8101 expression_t *true_expression = expression;
8102 bool gnu_cond = false;
8103 if (GNU_MODE && token.type == ':') {
8106 true_expression = parse_expression();
8108 rem_anchor_token(':');
8110 expression_t *false_expression =
8111 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
8113 type_t *const orig_true_type = true_expression->base.type;
8114 type_t *const orig_false_type = false_expression->base.type;
8115 type_t *const true_type = skip_typeref(orig_true_type);
8116 type_t *const false_type = skip_typeref(orig_false_type);
8119 type_t *result_type;
8120 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8121 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
8122 /* ISO/IEC 14882:1998(E) §5.16:2 */
8123 if (true_expression->kind == EXPR_UNARY_THROW) {
8124 result_type = false_type;
8125 } else if (false_expression->kind == EXPR_UNARY_THROW) {
8126 result_type = true_type;
8128 if (warning.other && (
8129 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8130 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
8132 warningf(&conditional->base.source_position,
8133 "ISO C forbids conditional expression with only one void side");
8135 result_type = type_void;
8137 } else if (is_type_arithmetic(true_type)
8138 && is_type_arithmetic(false_type)) {
8139 result_type = semantic_arithmetic(true_type, false_type);
8141 true_expression = create_implicit_cast(true_expression, result_type);
8142 false_expression = create_implicit_cast(false_expression, result_type);
8144 conditional->true_expression = true_expression;
8145 conditional->false_expression = false_expression;
8146 conditional->base.type = result_type;
8147 } else if (same_compound_type(true_type, false_type)) {
8148 /* just take 1 of the 2 types */
8149 result_type = true_type;
8150 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
8151 type_t *pointer_type;
8153 expression_t *other_expression;
8154 if (is_type_pointer(true_type) &&
8155 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
8156 pointer_type = true_type;
8157 other_type = false_type;
8158 other_expression = false_expression;
8160 pointer_type = false_type;
8161 other_type = true_type;
8162 other_expression = true_expression;
8165 if (is_null_pointer_constant(other_expression)) {
8166 result_type = pointer_type;
8167 } else if (is_type_pointer(other_type)) {
8168 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8169 type_t *to2 = skip_typeref(other_type->pointer.points_to);
8172 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8173 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8175 } else if (types_compatible(get_unqualified_type(to1),
8176 get_unqualified_type(to2))) {
8179 if (warning.other) {
8180 warningf(&conditional->base.source_position,
8181 "pointer types '%T' and '%T' in conditional expression are incompatible",
8182 true_type, false_type);
8187 type_t *const type =
8188 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8189 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8190 } else if (is_type_integer(other_type)) {
8191 if (warning.other) {
8192 warningf(&conditional->base.source_position,
8193 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8195 result_type = pointer_type;
8197 if (is_type_valid(other_type)) {
8198 type_error_incompatible("while parsing conditional",
8199 &expression->base.source_position, true_type, false_type);
8201 result_type = type_error_type;
8204 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8205 type_error_incompatible("while parsing conditional",
8206 &conditional->base.source_position, true_type,
8209 result_type = type_error_type;
8212 conditional->true_expression
8213 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8214 conditional->false_expression
8215 = create_implicit_cast(false_expression, result_type);
8216 conditional->base.type = result_type;
8219 return create_invalid_expression();
8223 * Parse an extension expression.
8225 static expression_t *parse_extension(void)
8227 eat(T___extension__);
8229 bool old_gcc_extension = in_gcc_extension;
8230 in_gcc_extension = true;
8231 expression_t *expression = parse_sub_expression(PREC_UNARY);
8232 in_gcc_extension = old_gcc_extension;
8237 * Parse a __builtin_classify_type() expression.
8239 static expression_t *parse_builtin_classify_type(void)
8241 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8242 result->base.type = type_int;
8244 eat(T___builtin_classify_type);
8247 add_anchor_token(')');
8248 expression_t *expression = parse_expression();
8249 rem_anchor_token(')');
8251 result->classify_type.type_expression = expression;
8255 return create_invalid_expression();
8259 * Parse a delete expression
8260 * ISO/IEC 14882:1998(E) §5.3.5
8262 static expression_t *parse_delete(void)
8264 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8265 result->base.type = type_void;
8269 if (token.type == '[') {
8271 result->kind = EXPR_UNARY_DELETE_ARRAY;
8276 expression_t *const value = parse_sub_expression(PREC_CAST);
8277 result->unary.value = value;
8279 type_t *const type = skip_typeref(value->base.type);
8280 if (!is_type_pointer(type)) {
8281 errorf(&value->base.source_position,
8282 "operand of delete must have pointer type");
8283 } else if (warning.other &&
8284 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8285 warningf(&value->base.source_position,
8286 "deleting 'void*' is undefined");
8293 * Parse a throw expression
8294 * ISO/IEC 14882:1998(E) §15:1
8296 static expression_t *parse_throw(void)
8298 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8299 result->base.type = type_void;
8303 expression_t *value = NULL;
8304 switch (token.type) {
8306 value = parse_assignment_expression();
8307 /* ISO/IEC 14882:1998(E) §15.1:3 */
8308 type_t *const orig_type = value->base.type;
8309 type_t *const type = skip_typeref(orig_type);
8310 if (is_type_incomplete(type)) {
8311 errorf(&value->base.source_position,
8312 "cannot throw object of incomplete type '%T'", orig_type);
8313 } else if (is_type_pointer(type)) {
8314 type_t *const points_to = skip_typeref(type->pointer.points_to);
8315 if (is_type_incomplete(points_to) &&
8316 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8317 errorf(&value->base.source_position,
8318 "cannot throw pointer to incomplete type '%T'", orig_type);
8326 result->unary.value = value;
8331 static bool check_pointer_arithmetic(const source_position_t *source_position,
8332 type_t *pointer_type,
8333 type_t *orig_pointer_type)
8335 type_t *points_to = pointer_type->pointer.points_to;
8336 points_to = skip_typeref(points_to);
8338 if (is_type_incomplete(points_to)) {
8339 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8340 errorf(source_position,
8341 "arithmetic with pointer to incomplete type '%T' not allowed",
8344 } else if (warning.pointer_arith) {
8345 warningf(source_position,
8346 "pointer of type '%T' used in arithmetic",
8349 } else if (is_type_function(points_to)) {
8351 errorf(source_position,
8352 "arithmetic with pointer to function type '%T' not allowed",
8355 } else if (warning.pointer_arith) {
8356 warningf(source_position,
8357 "pointer to a function '%T' used in arithmetic",
8364 static bool is_lvalue(const expression_t *expression)
8366 /* TODO: doesn't seem to be consistent with §6.3.2.1 (1) */
8367 switch (expression->kind) {
8368 case EXPR_REFERENCE:
8369 case EXPR_ARRAY_ACCESS:
8371 case EXPR_UNARY_DEREFERENCE:
8375 type_t *type = skip_typeref(expression->base.type);
8377 /* ISO/IEC 14882:1998(E) §3.10:3 */
8378 is_type_reference(type) ||
8379 /* Claim it is an lvalue, if the type is invalid. There was a parse
8380 * error before, which maybe prevented properly recognizing it as
8382 !is_type_valid(type);
8387 static void semantic_incdec(unary_expression_t *expression)
8389 type_t *const orig_type = expression->value->base.type;
8390 type_t *const type = skip_typeref(orig_type);
8391 if (is_type_pointer(type)) {
8392 if (!check_pointer_arithmetic(&expression->base.source_position,
8396 } else if (!is_type_real(type) && is_type_valid(type)) {
8397 /* TODO: improve error message */
8398 errorf(&expression->base.source_position,
8399 "operation needs an arithmetic or pointer type");
8402 if (!is_lvalue(expression->value)) {
8403 /* TODO: improve error message */
8404 errorf(&expression->base.source_position, "lvalue required as operand");
8406 expression->base.type = orig_type;
8409 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8411 type_t *const orig_type = expression->value->base.type;
8412 type_t *const type = skip_typeref(orig_type);
8413 if (!is_type_arithmetic(type)) {
8414 if (is_type_valid(type)) {
8415 /* TODO: improve error message */
8416 errorf(&expression->base.source_position,
8417 "operation needs an arithmetic type");
8422 expression->base.type = orig_type;
8425 static void semantic_unexpr_plus(unary_expression_t *expression)
8427 semantic_unexpr_arithmetic(expression);
8428 if (warning.traditional)
8429 warningf(&expression->base.source_position,
8430 "traditional C rejects the unary plus operator");
8433 static void semantic_not(unary_expression_t *expression)
8435 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8436 semantic_condition(expression->value, "operand of !");
8437 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8440 static void semantic_unexpr_integer(unary_expression_t *expression)
8442 type_t *const orig_type = expression->value->base.type;
8443 type_t *const type = skip_typeref(orig_type);
8444 if (!is_type_integer(type)) {
8445 if (is_type_valid(type)) {
8446 errorf(&expression->base.source_position,
8447 "operand of ~ must be of integer type");
8452 expression->base.type = orig_type;
8455 static void semantic_dereference(unary_expression_t *expression)
8457 type_t *const orig_type = expression->value->base.type;
8458 type_t *const type = skip_typeref(orig_type);
8459 if (!is_type_pointer(type)) {
8460 if (is_type_valid(type)) {
8461 errorf(&expression->base.source_position,
8462 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8467 type_t *result_type = type->pointer.points_to;
8468 result_type = automatic_type_conversion(result_type);
8469 expression->base.type = result_type;
8473 * Record that an address is taken (expression represents an lvalue).
8475 * @param expression the expression
8476 * @param may_be_register if true, the expression might be an register
8478 static void set_address_taken(expression_t *expression, bool may_be_register)
8480 if (expression->kind != EXPR_REFERENCE)
8483 entity_t *const entity = expression->reference.entity;
8485 if (entity->kind != ENTITY_VARIABLE)
8488 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8489 && !may_be_register) {
8490 errorf(&expression->base.source_position,
8491 "address of register variable '%Y' requested",
8492 entity->base.symbol);
8495 entity->variable.address_taken = true;
8499 * Check the semantic of the address taken expression.
8501 static void semantic_take_addr(unary_expression_t *expression)
8503 expression_t *value = expression->value;
8504 value->base.type = revert_automatic_type_conversion(value);
8506 type_t *orig_type = value->base.type;
8507 type_t *type = skip_typeref(orig_type);
8508 if (!is_type_valid(type))
8512 if (!is_lvalue(value)) {
8513 errorf(&expression->base.source_position, "'&' requires an lvalue");
8515 if (type->kind == TYPE_BITFIELD) {
8516 errorf(&expression->base.source_position,
8517 "'&' not allowed on object with bitfield type '%T'",
8521 set_address_taken(value, false);
8523 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8526 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8527 static expression_t *parse_##unexpression_type(void) \
8529 expression_t *unary_expression \
8530 = allocate_expression_zero(unexpression_type); \
8532 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8534 sfunc(&unary_expression->unary); \
8536 return unary_expression; \
8539 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8540 semantic_unexpr_arithmetic)
8541 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8542 semantic_unexpr_plus)
8543 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8545 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8546 semantic_dereference)
8547 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8549 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8550 semantic_unexpr_integer)
8551 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8553 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8556 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8558 static expression_t *parse_##unexpression_type(expression_t *left) \
8560 expression_t *unary_expression \
8561 = allocate_expression_zero(unexpression_type); \
8563 unary_expression->unary.value = left; \
8565 sfunc(&unary_expression->unary); \
8567 return unary_expression; \
8570 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8571 EXPR_UNARY_POSTFIX_INCREMENT,
8573 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8574 EXPR_UNARY_POSTFIX_DECREMENT,
8577 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8579 /* TODO: handle complex + imaginary types */
8581 type_left = get_unqualified_type(type_left);
8582 type_right = get_unqualified_type(type_right);
8584 /* § 6.3.1.8 Usual arithmetic conversions */
8585 if (type_left == type_long_double || type_right == type_long_double) {
8586 return type_long_double;
8587 } else if (type_left == type_double || type_right == type_double) {
8589 } else if (type_left == type_float || type_right == type_float) {
8593 type_left = promote_integer(type_left);
8594 type_right = promote_integer(type_right);
8596 if (type_left == type_right)
8599 bool const signed_left = is_type_signed(type_left);
8600 bool const signed_right = is_type_signed(type_right);
8601 int const rank_left = get_rank(type_left);
8602 int const rank_right = get_rank(type_right);
8604 if (signed_left == signed_right)
8605 return rank_left >= rank_right ? type_left : type_right;
8614 u_rank = rank_right;
8615 u_type = type_right;
8617 s_rank = rank_right;
8618 s_type = type_right;
8623 if (u_rank >= s_rank)
8626 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8628 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8629 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8633 case ATOMIC_TYPE_INT: return type_unsigned_int;
8634 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8635 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8637 default: panic("invalid atomic type");
8642 * Check the semantic restrictions for a binary expression.
8644 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8646 expression_t *const left = expression->left;
8647 expression_t *const right = expression->right;
8648 type_t *const orig_type_left = left->base.type;
8649 type_t *const orig_type_right = right->base.type;
8650 type_t *const type_left = skip_typeref(orig_type_left);
8651 type_t *const type_right = skip_typeref(orig_type_right);
8653 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8654 /* TODO: improve error message */
8655 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8656 errorf(&expression->base.source_position,
8657 "operation needs arithmetic types");
8662 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8663 expression->left = create_implicit_cast(left, arithmetic_type);
8664 expression->right = create_implicit_cast(right, arithmetic_type);
8665 expression->base.type = arithmetic_type;
8668 static void warn_div_by_zero(binary_expression_t const *const expression)
8670 if (!warning.div_by_zero ||
8671 !is_type_integer(expression->base.type))
8674 expression_t const *const right = expression->right;
8675 /* The type of the right operand can be different for /= */
8676 if (is_type_integer(right->base.type) &&
8677 is_constant_expression(right) &&
8678 fold_constant(right) == 0) {
8679 warningf(&expression->base.source_position, "division by zero");
8684 * Check the semantic restrictions for a div/mod expression.
8686 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8687 semantic_binexpr_arithmetic(expression);
8688 warn_div_by_zero(expression);
8691 static void semantic_shift_op(binary_expression_t *expression)
8693 expression_t *const left = expression->left;
8694 expression_t *const right = expression->right;
8695 type_t *const orig_type_left = left->base.type;
8696 type_t *const orig_type_right = right->base.type;
8697 type_t * type_left = skip_typeref(orig_type_left);
8698 type_t * type_right = skip_typeref(orig_type_right);
8700 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8701 /* TODO: improve error message */
8702 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8703 errorf(&expression->base.source_position,
8704 "operands of shift operation must have integer types");
8709 type_left = promote_integer(type_left);
8710 type_right = promote_integer(type_right);
8712 expression->left = create_implicit_cast(left, type_left);
8713 expression->right = create_implicit_cast(right, type_right);
8714 expression->base.type = type_left;
8717 static void semantic_add(binary_expression_t *expression)
8719 expression_t *const left = expression->left;
8720 expression_t *const right = expression->right;
8721 type_t *const orig_type_left = left->base.type;
8722 type_t *const orig_type_right = right->base.type;
8723 type_t *const type_left = skip_typeref(orig_type_left);
8724 type_t *const type_right = skip_typeref(orig_type_right);
8727 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8728 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8729 expression->left = create_implicit_cast(left, arithmetic_type);
8730 expression->right = create_implicit_cast(right, arithmetic_type);
8731 expression->base.type = arithmetic_type;
8733 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8734 check_pointer_arithmetic(&expression->base.source_position,
8735 type_left, orig_type_left);
8736 expression->base.type = type_left;
8737 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8738 check_pointer_arithmetic(&expression->base.source_position,
8739 type_right, orig_type_right);
8740 expression->base.type = type_right;
8741 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8742 errorf(&expression->base.source_position,
8743 "invalid operands to binary + ('%T', '%T')",
8744 orig_type_left, orig_type_right);
8748 static void semantic_sub(binary_expression_t *expression)
8750 expression_t *const left = expression->left;
8751 expression_t *const right = expression->right;
8752 type_t *const orig_type_left = left->base.type;
8753 type_t *const orig_type_right = right->base.type;
8754 type_t *const type_left = skip_typeref(orig_type_left);
8755 type_t *const type_right = skip_typeref(orig_type_right);
8756 source_position_t const *const pos = &expression->base.source_position;
8759 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8760 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8761 expression->left = create_implicit_cast(left, arithmetic_type);
8762 expression->right = create_implicit_cast(right, arithmetic_type);
8763 expression->base.type = arithmetic_type;
8765 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8766 check_pointer_arithmetic(&expression->base.source_position,
8767 type_left, orig_type_left);
8768 expression->base.type = type_left;
8769 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8770 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8771 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8772 if (!types_compatible(unqual_left, unqual_right)) {
8774 "subtracting pointers to incompatible types '%T' and '%T'",
8775 orig_type_left, orig_type_right);
8776 } else if (!is_type_object(unqual_left)) {
8777 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8778 errorf(pos, "subtracting pointers to non-object types '%T'",
8780 } else if (warning.other) {
8781 warningf(pos, "subtracting pointers to void");
8784 expression->base.type = type_ptrdiff_t;
8785 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8786 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8787 orig_type_left, orig_type_right);
8791 static void warn_string_literal_address(expression_t const* expr)
8793 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8794 expr = expr->unary.value;
8795 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8797 expr = expr->unary.value;
8800 if (expr->kind == EXPR_STRING_LITERAL ||
8801 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8802 warningf(&expr->base.source_position,
8803 "comparison with string literal results in unspecified behaviour");
8808 * Check the semantics of comparison expressions.
8810 * @param expression The expression to check.
8812 static void semantic_comparison(binary_expression_t *expression)
8814 expression_t *left = expression->left;
8815 expression_t *right = expression->right;
8817 if (warning.address) {
8818 warn_string_literal_address(left);
8819 warn_string_literal_address(right);
8821 expression_t const* const func_left = get_reference_address(left);
8822 if (func_left != NULL && is_null_pointer_constant(right)) {
8823 warningf(&expression->base.source_position,
8824 "the address of '%Y' will never be NULL",
8825 func_left->reference.entity->base.symbol);
8828 expression_t const* const func_right = get_reference_address(right);
8829 if (func_right != NULL && is_null_pointer_constant(right)) {
8830 warningf(&expression->base.source_position,
8831 "the address of '%Y' will never be NULL",
8832 func_right->reference.entity->base.symbol);
8836 type_t *orig_type_left = left->base.type;
8837 type_t *orig_type_right = right->base.type;
8838 type_t *type_left = skip_typeref(orig_type_left);
8839 type_t *type_right = skip_typeref(orig_type_right);
8841 /* TODO non-arithmetic types */
8842 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8843 /* test for signed vs unsigned compares */
8844 if (warning.sign_compare &&
8845 (expression->base.kind != EXPR_BINARY_EQUAL &&
8846 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
8847 (is_type_signed(type_left) != is_type_signed(type_right))) {
8849 /* check if 1 of the operands is a constant, in this case we just
8850 * check wether we can safely represent the resulting constant in
8851 * the type of the other operand. */
8852 expression_t *const_expr = NULL;
8853 expression_t *other_expr = NULL;
8855 if (is_constant_expression(left)) {
8858 } else if (is_constant_expression(right)) {
8863 if (const_expr != NULL) {
8864 type_t *other_type = skip_typeref(other_expr->base.type);
8865 long val = fold_constant(const_expr);
8866 /* TODO: check if val can be represented by other_type */
8870 warningf(&expression->base.source_position,
8871 "comparison between signed and unsigned");
8873 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8874 expression->left = create_implicit_cast(left, arithmetic_type);
8875 expression->right = create_implicit_cast(right, arithmetic_type);
8876 expression->base.type = arithmetic_type;
8877 if (warning.float_equal &&
8878 (expression->base.kind == EXPR_BINARY_EQUAL ||
8879 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8880 is_type_float(arithmetic_type)) {
8881 warningf(&expression->base.source_position,
8882 "comparing floating point with == or != is unsafe");
8884 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8885 /* TODO check compatibility */
8886 } else if (is_type_pointer(type_left)) {
8887 expression->right = create_implicit_cast(right, type_left);
8888 } else if (is_type_pointer(type_right)) {
8889 expression->left = create_implicit_cast(left, type_right);
8890 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8891 type_error_incompatible("invalid operands in comparison",
8892 &expression->base.source_position,
8893 type_left, type_right);
8895 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8899 * Checks if a compound type has constant fields.
8901 static bool has_const_fields(const compound_type_t *type)
8903 compound_t *compound = type->compound;
8904 entity_t *entry = compound->members.entities;
8906 for (; entry != NULL; entry = entry->base.next) {
8907 if (!is_declaration(entry))
8910 const type_t *decl_type = skip_typeref(entry->declaration.type);
8911 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8918 static bool is_valid_assignment_lhs(expression_t const* const left)
8920 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8921 type_t *const type_left = skip_typeref(orig_type_left);
8923 if (!is_lvalue(left)) {
8924 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8929 if (is_type_array(type_left)) {
8930 errorf(HERE, "cannot assign to arrays ('%E')", left);
8933 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8934 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8938 if (is_type_incomplete(type_left)) {
8939 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8940 left, orig_type_left);
8943 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8944 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8945 left, orig_type_left);
8952 static void semantic_arithmetic_assign(binary_expression_t *expression)
8954 expression_t *left = expression->left;
8955 expression_t *right = expression->right;
8956 type_t *orig_type_left = left->base.type;
8957 type_t *orig_type_right = right->base.type;
8959 if (!is_valid_assignment_lhs(left))
8962 type_t *type_left = skip_typeref(orig_type_left);
8963 type_t *type_right = skip_typeref(orig_type_right);
8965 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8966 /* TODO: improve error message */
8967 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8968 errorf(&expression->base.source_position,
8969 "operation needs arithmetic types");
8974 /* combined instructions are tricky. We can't create an implicit cast on
8975 * the left side, because we need the uncasted form for the store.
8976 * The ast2firm pass has to know that left_type must be right_type
8977 * for the arithmetic operation and create a cast by itself */
8978 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8979 expression->right = create_implicit_cast(right, arithmetic_type);
8980 expression->base.type = type_left;
8983 static void semantic_divmod_assign(binary_expression_t *expression)
8985 semantic_arithmetic_assign(expression);
8986 warn_div_by_zero(expression);
8989 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8991 expression_t *const left = expression->left;
8992 expression_t *const right = expression->right;
8993 type_t *const orig_type_left = left->base.type;
8994 type_t *const orig_type_right = right->base.type;
8995 type_t *const type_left = skip_typeref(orig_type_left);
8996 type_t *const type_right = skip_typeref(orig_type_right);
8998 if (!is_valid_assignment_lhs(left))
9001 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9002 /* combined instructions are tricky. We can't create an implicit cast on
9003 * the left side, because we need the uncasted form for the store.
9004 * The ast2firm pass has to know that left_type must be right_type
9005 * for the arithmetic operation and create a cast by itself */
9006 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
9007 expression->right = create_implicit_cast(right, arithmetic_type);
9008 expression->base.type = type_left;
9009 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9010 check_pointer_arithmetic(&expression->base.source_position,
9011 type_left, orig_type_left);
9012 expression->base.type = type_left;
9013 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9014 errorf(&expression->base.source_position,
9015 "incompatible types '%T' and '%T' in assignment",
9016 orig_type_left, orig_type_right);
9021 * Check the semantic restrictions of a logical expression.
9023 static void semantic_logical_op(binary_expression_t *expression)
9025 /* §6.5.13:2 Each of the operands shall have scalar type.
9026 * §6.5.14:2 Each of the operands shall have scalar type. */
9027 semantic_condition(expression->left, "left operand of logical operator");
9028 semantic_condition(expression->right, "right operand of logical operator");
9029 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9033 * Check the semantic restrictions of a binary assign expression.
9035 static void semantic_binexpr_assign(binary_expression_t *expression)
9037 expression_t *left = expression->left;
9038 type_t *orig_type_left = left->base.type;
9040 if (!is_valid_assignment_lhs(left))
9043 assign_error_t error = semantic_assign(orig_type_left, expression->right);
9044 report_assign_error(error, orig_type_left, expression->right,
9045 "assignment", &left->base.source_position);
9046 expression->right = create_implicit_cast(expression->right, orig_type_left);
9047 expression->base.type = orig_type_left;
9051 * Determine if the outermost operation (or parts thereof) of the given
9052 * expression has no effect in order to generate a warning about this fact.
9053 * Therefore in some cases this only examines some of the operands of the
9054 * expression (see comments in the function and examples below).
9056 * f() + 23; // warning, because + has no effect
9057 * x || f(); // no warning, because x controls execution of f()
9058 * x ? y : f(); // warning, because y has no effect
9059 * (void)x; // no warning to be able to suppress the warning
9060 * This function can NOT be used for an "expression has definitely no effect"-
9062 static bool expression_has_effect(const expression_t *const expr)
9064 switch (expr->kind) {
9065 case EXPR_UNKNOWN: break;
9066 case EXPR_INVALID: return true; /* do NOT warn */
9067 case EXPR_REFERENCE: return false;
9068 case EXPR_REFERENCE_ENUM_VALUE: return false;
9069 /* suppress the warning for microsoft __noop operations */
9070 case EXPR_CONST: return expr->conste.is_ms_noop;
9071 case EXPR_CHARACTER_CONSTANT: return false;
9072 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
9073 case EXPR_STRING_LITERAL: return false;
9074 case EXPR_WIDE_STRING_LITERAL: return false;
9075 case EXPR_LABEL_ADDRESS: return false;
9078 const call_expression_t *const call = &expr->call;
9079 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
9082 switch (call->function->builtin_symbol.symbol->ID) {
9083 case T___builtin_va_end: return true;
9084 default: return false;
9088 /* Generate the warning if either the left or right hand side of a
9089 * conditional expression has no effect */
9090 case EXPR_CONDITIONAL: {
9091 const conditional_expression_t *const cond = &expr->conditional;
9093 expression_has_effect(cond->true_expression) &&
9094 expression_has_effect(cond->false_expression);
9097 case EXPR_SELECT: return false;
9098 case EXPR_ARRAY_ACCESS: return false;
9099 case EXPR_SIZEOF: return false;
9100 case EXPR_CLASSIFY_TYPE: return false;
9101 case EXPR_ALIGNOF: return false;
9103 case EXPR_FUNCNAME: return false;
9104 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
9105 case EXPR_BUILTIN_CONSTANT_P: return false;
9106 case EXPR_BUILTIN_PREFETCH: return true;
9107 case EXPR_OFFSETOF: return false;
9108 case EXPR_VA_START: return true;
9109 case EXPR_VA_ARG: return true;
9110 case EXPR_STATEMENT: return true; // TODO
9111 case EXPR_COMPOUND_LITERAL: return false;
9113 case EXPR_UNARY_NEGATE: return false;
9114 case EXPR_UNARY_PLUS: return false;
9115 case EXPR_UNARY_BITWISE_NEGATE: return false;
9116 case EXPR_UNARY_NOT: return false;
9117 case EXPR_UNARY_DEREFERENCE: return false;
9118 case EXPR_UNARY_TAKE_ADDRESS: return false;
9119 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
9120 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
9121 case EXPR_UNARY_PREFIX_INCREMENT: return true;
9122 case EXPR_UNARY_PREFIX_DECREMENT: return true;
9124 /* Treat void casts as if they have an effect in order to being able to
9125 * suppress the warning */
9126 case EXPR_UNARY_CAST: {
9127 type_t *const type = skip_typeref(expr->base.type);
9128 return is_type_atomic(type, ATOMIC_TYPE_VOID);
9131 case EXPR_UNARY_CAST_IMPLICIT: return true;
9132 case EXPR_UNARY_ASSUME: return true;
9133 case EXPR_UNARY_DELETE: return true;
9134 case EXPR_UNARY_DELETE_ARRAY: return true;
9135 case EXPR_UNARY_THROW: return true;
9137 case EXPR_BINARY_ADD: return false;
9138 case EXPR_BINARY_SUB: return false;
9139 case EXPR_BINARY_MUL: return false;
9140 case EXPR_BINARY_DIV: return false;
9141 case EXPR_BINARY_MOD: return false;
9142 case EXPR_BINARY_EQUAL: return false;
9143 case EXPR_BINARY_NOTEQUAL: return false;
9144 case EXPR_BINARY_LESS: return false;
9145 case EXPR_BINARY_LESSEQUAL: return false;
9146 case EXPR_BINARY_GREATER: return false;
9147 case EXPR_BINARY_GREATEREQUAL: return false;
9148 case EXPR_BINARY_BITWISE_AND: return false;
9149 case EXPR_BINARY_BITWISE_OR: return false;
9150 case EXPR_BINARY_BITWISE_XOR: return false;
9151 case EXPR_BINARY_SHIFTLEFT: return false;
9152 case EXPR_BINARY_SHIFTRIGHT: return false;
9153 case EXPR_BINARY_ASSIGN: return true;
9154 case EXPR_BINARY_MUL_ASSIGN: return true;
9155 case EXPR_BINARY_DIV_ASSIGN: return true;
9156 case EXPR_BINARY_MOD_ASSIGN: return true;
9157 case EXPR_BINARY_ADD_ASSIGN: return true;
9158 case EXPR_BINARY_SUB_ASSIGN: return true;
9159 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
9160 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
9161 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9162 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9163 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
9165 /* Only examine the right hand side of && and ||, because the left hand
9166 * side already has the effect of controlling the execution of the right
9168 case EXPR_BINARY_LOGICAL_AND:
9169 case EXPR_BINARY_LOGICAL_OR:
9170 /* Only examine the right hand side of a comma expression, because the left
9171 * hand side has a separate warning */
9172 case EXPR_BINARY_COMMA:
9173 return expression_has_effect(expr->binary.right);
9175 case EXPR_BINARY_BUILTIN_EXPECT: return true;
9176 case EXPR_BINARY_ISGREATER: return false;
9177 case EXPR_BINARY_ISGREATEREQUAL: return false;
9178 case EXPR_BINARY_ISLESS: return false;
9179 case EXPR_BINARY_ISLESSEQUAL: return false;
9180 case EXPR_BINARY_ISLESSGREATER: return false;
9181 case EXPR_BINARY_ISUNORDERED: return false;
9184 internal_errorf(HERE, "unexpected expression");
9187 static void semantic_comma(binary_expression_t *expression)
9189 if (warning.unused_value) {
9190 const expression_t *const left = expression->left;
9191 if (!expression_has_effect(left)) {
9192 warningf(&left->base.source_position,
9193 "left-hand operand of comma expression has no effect");
9196 expression->base.type = expression->right->base.type;
9200 * @param prec_r precedence of the right operand
9202 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9203 static expression_t *parse_##binexpression_type(expression_t *left) \
9205 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9206 binexpr->binary.left = left; \
9209 expression_t *right = parse_sub_expression(prec_r); \
9211 binexpr->binary.right = right; \
9212 sfunc(&binexpr->binary); \
9217 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9218 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9219 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9220 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9221 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9222 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9223 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9224 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9225 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9226 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9227 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9228 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9229 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9230 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9231 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9232 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9233 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9234 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9235 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9236 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9237 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9238 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9239 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9240 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9241 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9242 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9243 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9244 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9245 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9246 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9249 static expression_t *parse_sub_expression(precedence_t precedence)
9251 if (token.type < 0) {
9252 return expected_expression_error();
9255 expression_parser_function_t *parser
9256 = &expression_parsers[token.type];
9257 source_position_t source_position = token.source_position;
9260 if (parser->parser != NULL) {
9261 left = parser->parser();
9263 left = parse_primary_expression();
9265 assert(left != NULL);
9266 left->base.source_position = source_position;
9269 if (token.type < 0) {
9270 return expected_expression_error();
9273 parser = &expression_parsers[token.type];
9274 if (parser->infix_parser == NULL)
9276 if (parser->infix_precedence < precedence)
9279 left = parser->infix_parser(left);
9281 assert(left != NULL);
9282 assert(left->kind != EXPR_UNKNOWN);
9283 left->base.source_position = source_position;
9290 * Parse an expression.
9292 static expression_t *parse_expression(void)
9294 return parse_sub_expression(PREC_EXPRESSION);
9298 * Register a parser for a prefix-like operator.
9300 * @param parser the parser function
9301 * @param token_type the token type of the prefix token
9303 static void register_expression_parser(parse_expression_function parser,
9306 expression_parser_function_t *entry = &expression_parsers[token_type];
9308 if (entry->parser != NULL) {
9309 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9310 panic("trying to register multiple expression parsers for a token");
9312 entry->parser = parser;
9316 * Register a parser for an infix operator with given precedence.
9318 * @param parser the parser function
9319 * @param token_type the token type of the infix operator
9320 * @param precedence the precedence of the operator
9322 static void register_infix_parser(parse_expression_infix_function parser,
9323 int token_type, unsigned precedence)
9325 expression_parser_function_t *entry = &expression_parsers[token_type];
9327 if (entry->infix_parser != NULL) {
9328 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9329 panic("trying to register multiple infix expression parsers for a "
9332 entry->infix_parser = parser;
9333 entry->infix_precedence = precedence;
9337 * Initialize the expression parsers.
9339 static void init_expression_parsers(void)
9341 memset(&expression_parsers, 0, sizeof(expression_parsers));
9343 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9344 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9345 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9346 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9347 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9348 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9349 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9350 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9351 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9352 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9353 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9354 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9355 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9356 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9357 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9358 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9359 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9360 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9361 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9362 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9363 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9364 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9365 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9366 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9367 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9368 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9369 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9370 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9371 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9372 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9373 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9374 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9375 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9376 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9377 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9378 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9379 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9381 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9382 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9383 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9384 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9385 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9386 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9387 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9388 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9389 register_expression_parser(parse_sizeof, T_sizeof);
9390 register_expression_parser(parse_alignof, T___alignof__);
9391 register_expression_parser(parse_extension, T___extension__);
9392 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9393 register_expression_parser(parse_delete, T_delete);
9394 register_expression_parser(parse_throw, T_throw);
9398 * Parse a asm statement arguments specification.
9400 static asm_argument_t *parse_asm_arguments(bool is_out)
9402 asm_argument_t *result = NULL;
9403 asm_argument_t **anchor = &result;
9405 while (token.type == T_STRING_LITERAL || token.type == '[') {
9406 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9407 memset(argument, 0, sizeof(argument[0]));
9409 if (token.type == '[') {
9411 if (token.type != T_IDENTIFIER) {
9412 parse_error_expected("while parsing asm argument",
9413 T_IDENTIFIER, NULL);
9416 argument->symbol = token.v.symbol;
9421 argument->constraints = parse_string_literals();
9423 add_anchor_token(')');
9424 expression_t *expression = parse_expression();
9425 rem_anchor_token(')');
9427 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9428 * change size or type representation (e.g. int -> long is ok, but
9429 * int -> float is not) */
9430 if (expression->kind == EXPR_UNARY_CAST) {
9431 type_t *const type = expression->base.type;
9432 type_kind_t const kind = type->kind;
9433 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9436 if (kind == TYPE_ATOMIC) {
9437 atomic_type_kind_t const akind = type->atomic.akind;
9438 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9439 size = get_atomic_type_size(akind);
9441 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9442 size = get_atomic_type_size(get_intptr_kind());
9446 expression_t *const value = expression->unary.value;
9447 type_t *const value_type = value->base.type;
9448 type_kind_t const value_kind = value_type->kind;
9450 unsigned value_flags;
9451 unsigned value_size;
9452 if (value_kind == TYPE_ATOMIC) {
9453 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9454 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9455 value_size = get_atomic_type_size(value_akind);
9456 } else if (value_kind == TYPE_POINTER) {
9457 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9458 value_size = get_atomic_type_size(get_intptr_kind());
9463 if (value_flags != flags || value_size != size)
9467 } while (expression->kind == EXPR_UNARY_CAST);
9471 if (!is_lvalue(expression)) {
9472 errorf(&expression->base.source_position,
9473 "asm output argument is not an lvalue");
9476 if (argument->constraints.begin[0] == '+')
9477 mark_vars_read(expression, NULL);
9479 mark_vars_read(expression, NULL);
9481 argument->expression = expression;
9484 set_address_taken(expression, true);
9487 anchor = &argument->next;
9489 if (token.type != ',')
9500 * Parse a asm statement clobber specification.
9502 static asm_clobber_t *parse_asm_clobbers(void)
9504 asm_clobber_t *result = NULL;
9505 asm_clobber_t *last = NULL;
9507 while (token.type == T_STRING_LITERAL) {
9508 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9509 clobber->clobber = parse_string_literals();
9512 last->next = clobber;
9518 if (token.type != ',')
9527 * Parse an asm statement.
9529 static statement_t *parse_asm_statement(void)
9531 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9532 asm_statement_t *asm_statement = &statement->asms;
9536 if (token.type == T_volatile) {
9538 asm_statement->is_volatile = true;
9542 add_anchor_token(')');
9543 add_anchor_token(':');
9544 asm_statement->asm_text = parse_string_literals();
9546 if (token.type != ':') {
9547 rem_anchor_token(':');
9552 asm_statement->outputs = parse_asm_arguments(true);
9553 if (token.type != ':') {
9554 rem_anchor_token(':');
9559 asm_statement->inputs = parse_asm_arguments(false);
9560 if (token.type != ':') {
9561 rem_anchor_token(':');
9564 rem_anchor_token(':');
9567 asm_statement->clobbers = parse_asm_clobbers();
9570 rem_anchor_token(')');
9574 if (asm_statement->outputs == NULL) {
9575 /* GCC: An 'asm' instruction without any output operands will be treated
9576 * identically to a volatile 'asm' instruction. */
9577 asm_statement->is_volatile = true;
9582 return create_invalid_statement();
9586 * Parse a case statement.
9588 static statement_t *parse_case_statement(void)
9590 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9591 source_position_t *const pos = &statement->base.source_position;
9595 expression_t *const expression = parse_expression();
9596 statement->case_label.expression = expression;
9597 if (!is_constant_expression(expression)) {
9598 /* This check does not prevent the error message in all cases of an
9599 * prior error while parsing the expression. At least it catches the
9600 * common case of a mistyped enum entry. */
9601 if (is_type_valid(skip_typeref(expression->base.type))) {
9602 errorf(pos, "case label does not reduce to an integer constant");
9604 statement->case_label.is_bad = true;
9606 long const val = fold_constant(expression);
9607 statement->case_label.first_case = val;
9608 statement->case_label.last_case = val;
9612 if (token.type == T_DOTDOTDOT) {
9614 expression_t *const end_range = parse_expression();
9615 statement->case_label.end_range = end_range;
9616 if (!is_constant_expression(end_range)) {
9617 /* This check does not prevent the error message in all cases of an
9618 * prior error while parsing the expression. At least it catches the
9619 * common case of a mistyped enum entry. */
9620 if (is_type_valid(skip_typeref(end_range->base.type))) {
9621 errorf(pos, "case range does not reduce to an integer constant");
9623 statement->case_label.is_bad = true;
9625 long const val = fold_constant(end_range);
9626 statement->case_label.last_case = val;
9628 if (warning.other && val < statement->case_label.first_case) {
9629 statement->case_label.is_empty_range = true;
9630 warningf(pos, "empty range specified");
9636 PUSH_PARENT(statement);
9640 if (current_switch != NULL) {
9641 if (! statement->case_label.is_bad) {
9642 /* Check for duplicate case values */
9643 case_label_statement_t *c = &statement->case_label;
9644 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9645 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9648 if (c->last_case < l->first_case || c->first_case > l->last_case)
9651 errorf(pos, "duplicate case value (previously used %P)",
9652 &l->base.source_position);
9656 /* link all cases into the switch statement */
9657 if (current_switch->last_case == NULL) {
9658 current_switch->first_case = &statement->case_label;
9660 current_switch->last_case->next = &statement->case_label;
9662 current_switch->last_case = &statement->case_label;
9664 errorf(pos, "case label not within a switch statement");
9667 statement_t *const inner_stmt = parse_statement();
9668 statement->case_label.statement = inner_stmt;
9669 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9670 errorf(&inner_stmt->base.source_position, "declaration after case label");
9677 return create_invalid_statement();
9681 * Parse a default statement.
9683 static statement_t *parse_default_statement(void)
9685 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9689 PUSH_PARENT(statement);
9692 if (current_switch != NULL) {
9693 const case_label_statement_t *def_label = current_switch->default_label;
9694 if (def_label != NULL) {
9695 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9696 &def_label->base.source_position);
9698 current_switch->default_label = &statement->case_label;
9700 /* link all cases into the switch statement */
9701 if (current_switch->last_case == NULL) {
9702 current_switch->first_case = &statement->case_label;
9704 current_switch->last_case->next = &statement->case_label;
9706 current_switch->last_case = &statement->case_label;
9709 errorf(&statement->base.source_position,
9710 "'default' label not within a switch statement");
9713 statement_t *const inner_stmt = parse_statement();
9714 statement->case_label.statement = inner_stmt;
9715 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9716 errorf(&inner_stmt->base.source_position, "declaration after default label");
9723 return create_invalid_statement();
9727 * Parse a label statement.
9729 static statement_t *parse_label_statement(void)
9731 assert(token.type == T_IDENTIFIER);
9732 symbol_t *symbol = token.v.symbol;
9733 label_t *label = get_label(symbol);
9735 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9736 statement->label.label = label;
9740 PUSH_PARENT(statement);
9742 /* if statement is already set then the label is defined twice,
9743 * otherwise it was just mentioned in a goto/local label declaration so far
9745 if (label->statement != NULL) {
9746 errorf(HERE, "duplicate label '%Y' (declared %P)",
9747 symbol, &label->base.source_position);
9749 label->base.source_position = token.source_position;
9750 label->statement = statement;
9755 if (token.type == '}') {
9756 /* TODO only warn? */
9757 if (warning.other && false) {
9758 warningf(HERE, "label at end of compound statement");
9759 statement->label.statement = create_empty_statement();
9761 errorf(HERE, "label at end of compound statement");
9762 statement->label.statement = create_invalid_statement();
9764 } else if (token.type == ';') {
9765 /* Eat an empty statement here, to avoid the warning about an empty
9766 * statement after a label. label:; is commonly used to have a label
9767 * before a closing brace. */
9768 statement->label.statement = create_empty_statement();
9771 statement_t *const inner_stmt = parse_statement();
9772 statement->label.statement = inner_stmt;
9773 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9774 errorf(&inner_stmt->base.source_position, "declaration after label");
9778 /* remember the labels in a list for later checking */
9779 *label_anchor = &statement->label;
9780 label_anchor = &statement->label.next;
9787 * Parse an if statement.
9789 static statement_t *parse_if(void)
9791 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9795 PUSH_PARENT(statement);
9797 add_anchor_token('{');
9800 add_anchor_token(')');
9801 expression_t *const expr = parse_expression();
9802 statement->ifs.condition = expr;
9803 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9805 semantic_condition(expr, "condition of 'if'-statment");
9806 mark_vars_read(expr, NULL);
9807 rem_anchor_token(')');
9811 rem_anchor_token('{');
9813 add_anchor_token(T_else);
9814 statement->ifs.true_statement = parse_statement();
9815 rem_anchor_token(T_else);
9817 if (token.type == T_else) {
9819 statement->ifs.false_statement = parse_statement();
9827 * Check that all enums are handled in a switch.
9829 * @param statement the switch statement to check
9831 static void check_enum_cases(const switch_statement_t *statement) {
9832 const type_t *type = skip_typeref(statement->expression->base.type);
9833 if (! is_type_enum(type))
9835 const enum_type_t *enumt = &type->enumt;
9837 /* if we have a default, no warnings */
9838 if (statement->default_label != NULL)
9841 /* FIXME: calculation of value should be done while parsing */
9842 /* TODO: quadratic algorithm here. Change to an n log n one */
9843 long last_value = -1;
9844 const entity_t *entry = enumt->enume->base.next;
9845 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9846 entry = entry->base.next) {
9847 const expression_t *expression = entry->enum_value.value;
9848 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9850 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9851 if (l->expression == NULL)
9853 if (l->first_case <= value && value <= l->last_case) {
9859 warningf(&statement->base.source_position,
9860 "enumeration value '%Y' not handled in switch",
9861 entry->base.symbol);
9868 * Parse a switch statement.
9870 static statement_t *parse_switch(void)
9872 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9876 PUSH_PARENT(statement);
9879 add_anchor_token(')');
9880 expression_t *const expr = parse_expression();
9881 mark_vars_read(expr, NULL);
9882 type_t * type = skip_typeref(expr->base.type);
9883 if (is_type_integer(type)) {
9884 type = promote_integer(type);
9885 if (warning.traditional) {
9886 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9887 warningf(&expr->base.source_position,
9888 "'%T' switch expression not converted to '%T' in ISO C",
9892 } else if (is_type_valid(type)) {
9893 errorf(&expr->base.source_position,
9894 "switch quantity is not an integer, but '%T'", type);
9895 type = type_error_type;
9897 statement->switchs.expression = create_implicit_cast(expr, type);
9899 rem_anchor_token(')');
9901 switch_statement_t *rem = current_switch;
9902 current_switch = &statement->switchs;
9903 statement->switchs.body = parse_statement();
9904 current_switch = rem;
9906 if (warning.switch_default &&
9907 statement->switchs.default_label == NULL) {
9908 warningf(&statement->base.source_position, "switch has no default case");
9910 if (warning.switch_enum)
9911 check_enum_cases(&statement->switchs);
9917 return create_invalid_statement();
9920 static statement_t *parse_loop_body(statement_t *const loop)
9922 statement_t *const rem = current_loop;
9923 current_loop = loop;
9925 statement_t *const body = parse_statement();
9932 * Parse a while statement.
9934 static statement_t *parse_while(void)
9936 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9940 PUSH_PARENT(statement);
9943 add_anchor_token(')');
9944 expression_t *const cond = parse_expression();
9945 statement->whiles.condition = cond;
9946 /* §6.8.5:2 The controlling expression of an iteration statement shall
9947 * have scalar type. */
9948 semantic_condition(cond, "condition of 'while'-statement");
9949 mark_vars_read(cond, NULL);
9950 rem_anchor_token(')');
9953 statement->whiles.body = parse_loop_body(statement);
9959 return create_invalid_statement();
9963 * Parse a do statement.
9965 static statement_t *parse_do(void)
9967 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9971 PUSH_PARENT(statement);
9973 add_anchor_token(T_while);
9974 statement->do_while.body = parse_loop_body(statement);
9975 rem_anchor_token(T_while);
9979 add_anchor_token(')');
9980 expression_t *const cond = parse_expression();
9981 statement->do_while.condition = cond;
9982 /* §6.8.5:2 The controlling expression of an iteration statement shall
9983 * have scalar type. */
9984 semantic_condition(cond, "condition of 'do-while'-statement");
9985 mark_vars_read(cond, NULL);
9986 rem_anchor_token(')');
9994 return create_invalid_statement();
9998 * Parse a for statement.
10000 static statement_t *parse_for(void)
10002 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
10006 PUSH_PARENT(statement);
10008 size_t const top = environment_top();
10009 scope_push(&statement->fors.scope);
10012 add_anchor_token(')');
10014 if (token.type == ';') {
10016 } else if (is_declaration_specifier(&token, false)) {
10017 parse_declaration(record_entity);
10019 add_anchor_token(';');
10020 expression_t *const init = parse_expression();
10021 statement->fors.initialisation = init;
10022 mark_vars_read(init, VAR_ANY);
10023 if (warning.unused_value && !expression_has_effect(init)) {
10024 warningf(&init->base.source_position,
10025 "initialisation of 'for'-statement has no effect");
10027 rem_anchor_token(';');
10031 if (token.type != ';') {
10032 add_anchor_token(';');
10033 expression_t *const cond = parse_expression();
10034 statement->fors.condition = cond;
10035 /* §6.8.5:2 The controlling expression of an iteration statement shall
10036 * have scalar type. */
10037 semantic_condition(cond, "condition of 'for'-statement");
10038 mark_vars_read(cond, NULL);
10039 rem_anchor_token(';');
10042 if (token.type != ')') {
10043 expression_t *const step = parse_expression();
10044 statement->fors.step = step;
10045 mark_vars_read(step, VAR_ANY);
10046 if (warning.unused_value && !expression_has_effect(step)) {
10047 warningf(&step->base.source_position,
10048 "step of 'for'-statement has no effect");
10052 rem_anchor_token(')');
10053 statement->fors.body = parse_loop_body(statement);
10055 assert(current_scope == &statement->fors.scope);
10057 environment_pop_to(top);
10064 rem_anchor_token(')');
10065 assert(current_scope == &statement->fors.scope);
10067 environment_pop_to(top);
10069 return create_invalid_statement();
10073 * Parse a goto statement.
10075 static statement_t *parse_goto(void)
10077 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
10080 if (GNU_MODE && token.type == '*') {
10082 expression_t *expression = parse_expression();
10083 mark_vars_read(expression, NULL);
10085 /* Argh: although documentation says the expression must be of type void*,
10086 * gcc accepts anything that can be casted into void* without error */
10087 type_t *type = expression->base.type;
10089 if (type != type_error_type) {
10090 if (!is_type_pointer(type) && !is_type_integer(type)) {
10091 errorf(&expression->base.source_position,
10092 "cannot convert to a pointer type");
10093 } else if (warning.other && type != type_void_ptr) {
10094 warningf(&expression->base.source_position,
10095 "type of computed goto expression should be 'void*' not '%T'", type);
10097 expression = create_implicit_cast(expression, type_void_ptr);
10100 statement->gotos.expression = expression;
10102 if (token.type != T_IDENTIFIER) {
10104 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
10106 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
10107 eat_until_anchor();
10110 symbol_t *symbol = token.v.symbol;
10113 statement->gotos.label = get_label(symbol);
10116 /* remember the goto's in a list for later checking */
10117 *goto_anchor = &statement->gotos;
10118 goto_anchor = &statement->gotos.next;
10124 return create_invalid_statement();
10128 * Parse a continue statement.
10130 static statement_t *parse_continue(void)
10132 if (current_loop == NULL) {
10133 errorf(HERE, "continue statement not within loop");
10136 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
10146 * Parse a break statement.
10148 static statement_t *parse_break(void)
10150 if (current_switch == NULL && current_loop == NULL) {
10151 errorf(HERE, "break statement not within loop or switch");
10154 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10164 * Parse a __leave statement.
10166 static statement_t *parse_leave_statement(void)
10168 if (current_try == NULL) {
10169 errorf(HERE, "__leave statement not within __try");
10172 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10182 * Check if a given entity represents a local variable.
10184 static bool is_local_variable(const entity_t *entity)
10186 if (entity->kind != ENTITY_VARIABLE)
10189 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10190 case STORAGE_CLASS_AUTO:
10191 case STORAGE_CLASS_REGISTER: {
10192 const type_t *type = skip_typeref(entity->declaration.type);
10193 if (is_type_function(type)) {
10205 * Check if a given expression represents a local variable.
10207 static bool expression_is_local_variable(const expression_t *expression)
10209 if (expression->base.kind != EXPR_REFERENCE) {
10212 const entity_t *entity = expression->reference.entity;
10213 return is_local_variable(entity);
10217 * Check if a given expression represents a local variable and
10218 * return its declaration then, else return NULL.
10220 entity_t *expression_is_variable(const expression_t *expression)
10222 if (expression->base.kind != EXPR_REFERENCE) {
10225 entity_t *entity = expression->reference.entity;
10226 if (entity->kind != ENTITY_VARIABLE)
10233 * Parse a return statement.
10235 static statement_t *parse_return(void)
10239 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10241 expression_t *return_value = NULL;
10242 if (token.type != ';') {
10243 return_value = parse_expression();
10244 mark_vars_read(return_value, NULL);
10247 const type_t *const func_type = skip_typeref(current_function->base.type);
10248 assert(is_type_function(func_type));
10249 type_t *const return_type = skip_typeref(func_type->function.return_type);
10251 if (return_value != NULL) {
10252 type_t *return_value_type = skip_typeref(return_value->base.type);
10254 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID) &&
10255 !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10256 if (warning.other) {
10257 warningf(&statement->base.source_position,
10258 "'return' with a value, in function returning void");
10260 return_value = NULL;
10262 assign_error_t error = semantic_assign(return_type, return_value);
10263 report_assign_error(error, return_type, return_value, "'return'",
10264 &statement->base.source_position);
10265 return_value = create_implicit_cast(return_value, return_type);
10267 /* check for returning address of a local var */
10268 if (warning.other && return_value != NULL
10269 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10270 const expression_t *expression = return_value->unary.value;
10271 if (expression_is_local_variable(expression)) {
10272 warningf(&statement->base.source_position,
10273 "function returns address of local variable");
10276 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10277 warningf(&statement->base.source_position,
10278 "'return' without value, in function returning non-void");
10280 statement->returns.value = return_value;
10289 * Parse a declaration statement.
10291 static statement_t *parse_declaration_statement(void)
10293 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10295 entity_t *before = current_scope->last_entity;
10297 parse_external_declaration();
10299 parse_declaration(record_entity);
10301 if (before == NULL) {
10302 statement->declaration.declarations_begin = current_scope->entities;
10304 statement->declaration.declarations_begin = before->base.next;
10306 statement->declaration.declarations_end = current_scope->last_entity;
10312 * Parse an expression statement, ie. expr ';'.
10314 static statement_t *parse_expression_statement(void)
10316 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10318 expression_t *const expr = parse_expression();
10319 statement->expression.expression = expr;
10320 mark_vars_read(expr, VAR_ANY);
10329 * Parse a microsoft __try { } __finally { } or
10330 * __try{ } __except() { }
10332 static statement_t *parse_ms_try_statment(void)
10334 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10337 PUSH_PARENT(statement);
10339 ms_try_statement_t *rem = current_try;
10340 current_try = &statement->ms_try;
10341 statement->ms_try.try_statement = parse_compound_statement(false);
10346 if (token.type == T___except) {
10349 add_anchor_token(')');
10350 expression_t *const expr = parse_expression();
10351 mark_vars_read(expr, NULL);
10352 type_t * type = skip_typeref(expr->base.type);
10353 if (is_type_integer(type)) {
10354 type = promote_integer(type);
10355 } else if (is_type_valid(type)) {
10356 errorf(&expr->base.source_position,
10357 "__expect expression is not an integer, but '%T'", type);
10358 type = type_error_type;
10360 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10361 rem_anchor_token(')');
10363 statement->ms_try.final_statement = parse_compound_statement(false);
10364 } else if (token.type == T__finally) {
10366 statement->ms_try.final_statement = parse_compound_statement(false);
10368 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10369 return create_invalid_statement();
10373 return create_invalid_statement();
10376 static statement_t *parse_empty_statement(void)
10378 if (warning.empty_statement) {
10379 warningf(HERE, "statement is empty");
10381 statement_t *const statement = create_empty_statement();
10386 static statement_t *parse_local_label_declaration(void)
10388 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10392 entity_t *begin = NULL, *end = NULL;
10395 if (token.type != T_IDENTIFIER) {
10396 parse_error_expected("while parsing local label declaration",
10397 T_IDENTIFIER, NULL);
10400 symbol_t *symbol = token.v.symbol;
10401 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10402 if (entity != NULL && entity->base.parent_scope == current_scope) {
10403 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10404 symbol, &entity->base.source_position);
10406 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10408 entity->base.parent_scope = current_scope;
10409 entity->base.namespc = NAMESPACE_LABEL;
10410 entity->base.source_position = token.source_position;
10411 entity->base.symbol = symbol;
10414 end->base.next = entity;
10419 environment_push(entity);
10423 if (token.type != ',')
10429 statement->declaration.declarations_begin = begin;
10430 statement->declaration.declarations_end = end;
10434 static void parse_namespace_definition(void)
10438 entity_t *entity = NULL;
10439 symbol_t *symbol = NULL;
10441 if (token.type == T_IDENTIFIER) {
10442 symbol = token.v.symbol;
10445 entity = get_entity(symbol, NAMESPACE_NORMAL);
10446 if (entity != NULL && entity->kind != ENTITY_NAMESPACE
10447 && entity->base.parent_scope == current_scope) {
10448 error_redefined_as_different_kind(&token.source_position,
10449 entity, ENTITY_NAMESPACE);
10454 if (entity == NULL) {
10455 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10456 entity->base.symbol = symbol;
10457 entity->base.source_position = token.source_position;
10458 entity->base.namespc = NAMESPACE_NORMAL;
10459 entity->base.parent_scope = current_scope;
10462 if (token.type == '=') {
10463 /* TODO: parse namespace alias */
10464 panic("namespace alias definition not supported yet");
10467 environment_push(entity);
10468 append_entity(current_scope, entity);
10470 size_t const top = environment_top();
10471 scope_push(&entity->namespacee.members);
10478 assert(current_scope == &entity->namespacee.members);
10480 environment_pop_to(top);
10484 * Parse a statement.
10485 * There's also parse_statement() which additionally checks for
10486 * "statement has no effect" warnings
10488 static statement_t *intern_parse_statement(void)
10490 statement_t *statement = NULL;
10492 /* declaration or statement */
10493 add_anchor_token(';');
10494 switch (token.type) {
10495 case T_IDENTIFIER: {
10496 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10497 if (la1_type == ':') {
10498 statement = parse_label_statement();
10499 } else if (is_typedef_symbol(token.v.symbol)) {
10500 statement = parse_declaration_statement();
10502 /* it's an identifier, the grammar says this must be an
10503 * expression statement. However it is common that users mistype
10504 * declaration types, so we guess a bit here to improve robustness
10505 * for incorrect programs */
10506 switch (la1_type) {
10509 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10510 goto expression_statment;
10515 statement = parse_declaration_statement();
10519 expression_statment:
10520 statement = parse_expression_statement();
10527 case T___extension__:
10528 /* This can be a prefix to a declaration or an expression statement.
10529 * We simply eat it now and parse the rest with tail recursion. */
10532 } while (token.type == T___extension__);
10533 bool old_gcc_extension = in_gcc_extension;
10534 in_gcc_extension = true;
10535 statement = intern_parse_statement();
10536 in_gcc_extension = old_gcc_extension;
10540 statement = parse_declaration_statement();
10544 statement = parse_local_label_declaration();
10547 case ';': statement = parse_empty_statement(); break;
10548 case '{': statement = parse_compound_statement(false); break;
10549 case T___leave: statement = parse_leave_statement(); break;
10550 case T___try: statement = parse_ms_try_statment(); break;
10551 case T_asm: statement = parse_asm_statement(); break;
10552 case T_break: statement = parse_break(); break;
10553 case T_case: statement = parse_case_statement(); break;
10554 case T_continue: statement = parse_continue(); break;
10555 case T_default: statement = parse_default_statement(); break;
10556 case T_do: statement = parse_do(); break;
10557 case T_for: statement = parse_for(); break;
10558 case T_goto: statement = parse_goto(); break;
10559 case T_if: statement = parse_if(); break;
10560 case T_return: statement = parse_return(); break;
10561 case T_switch: statement = parse_switch(); break;
10562 case T_while: statement = parse_while(); break;
10565 statement = parse_expression_statement();
10569 errorf(HERE, "unexpected token %K while parsing statement", &token);
10570 statement = create_invalid_statement();
10575 rem_anchor_token(';');
10577 assert(statement != NULL
10578 && statement->base.source_position.input_name != NULL);
10584 * parse a statement and emits "statement has no effect" warning if needed
10585 * (This is really a wrapper around intern_parse_statement with check for 1
10586 * single warning. It is needed, because for statement expressions we have
10587 * to avoid the warning on the last statement)
10589 static statement_t *parse_statement(void)
10591 statement_t *statement = intern_parse_statement();
10593 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10594 expression_t *expression = statement->expression.expression;
10595 if (!expression_has_effect(expression)) {
10596 warningf(&expression->base.source_position,
10597 "statement has no effect");
10605 * Parse a compound statement.
10607 static statement_t *parse_compound_statement(bool inside_expression_statement)
10609 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10611 PUSH_PARENT(statement);
10614 add_anchor_token('}');
10616 size_t const top = environment_top();
10617 scope_push(&statement->compound.scope);
10619 statement_t **anchor = &statement->compound.statements;
10620 bool only_decls_so_far = true;
10621 while (token.type != '}') {
10622 if (token.type == T_EOF) {
10623 errorf(&statement->base.source_position,
10624 "EOF while parsing compound statement");
10627 statement_t *sub_statement = intern_parse_statement();
10628 if (is_invalid_statement(sub_statement)) {
10629 /* an error occurred. if we are at an anchor, return */
10635 if (warning.declaration_after_statement) {
10636 if (sub_statement->kind != STATEMENT_DECLARATION) {
10637 only_decls_so_far = false;
10638 } else if (!only_decls_so_far) {
10639 warningf(&sub_statement->base.source_position,
10640 "ISO C90 forbids mixed declarations and code");
10644 *anchor = sub_statement;
10646 while (sub_statement->base.next != NULL)
10647 sub_statement = sub_statement->base.next;
10649 anchor = &sub_statement->base.next;
10653 /* look over all statements again to produce no effect warnings */
10654 if (warning.unused_value) {
10655 statement_t *sub_statement = statement->compound.statements;
10656 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10657 if (sub_statement->kind != STATEMENT_EXPRESSION)
10659 /* don't emit a warning for the last expression in an expression
10660 * statement as it has always an effect */
10661 if (inside_expression_statement && sub_statement->base.next == NULL)
10664 expression_t *expression = sub_statement->expression.expression;
10665 if (!expression_has_effect(expression)) {
10666 warningf(&expression->base.source_position,
10667 "statement has no effect");
10673 rem_anchor_token('}');
10674 assert(current_scope == &statement->compound.scope);
10676 environment_pop_to(top);
10683 * Check for unused global static functions and variables
10685 static void check_unused_globals(void)
10687 if (!warning.unused_function && !warning.unused_variable)
10690 for (const entity_t *entity = file_scope->entities; entity != NULL;
10691 entity = entity->base.next) {
10692 if (!is_declaration(entity))
10695 const declaration_t *declaration = &entity->declaration;
10696 if (declaration->used ||
10697 declaration->modifiers & DM_UNUSED ||
10698 declaration->modifiers & DM_USED ||
10699 declaration->storage_class != STORAGE_CLASS_STATIC)
10702 type_t *const type = declaration->type;
10704 if (entity->kind == ENTITY_FUNCTION) {
10705 /* inhibit warning for static inline functions */
10706 if (entity->function.is_inline)
10709 s = entity->function.statement != NULL ? "defined" : "declared";
10714 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10715 type, declaration->base.symbol, s);
10719 static void parse_global_asm(void)
10721 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10726 statement->asms.asm_text = parse_string_literals();
10727 statement->base.next = unit->global_asm;
10728 unit->global_asm = statement;
10736 static void parse_linkage_specification(void)
10739 assert(token.type == T_STRING_LITERAL);
10741 const char *linkage = parse_string_literals().begin;
10743 linkage_kind_t old_linkage = current_linkage;
10744 linkage_kind_t new_linkage;
10745 if (strcmp(linkage, "C") == 0) {
10746 new_linkage = LINKAGE_C;
10747 } else if (strcmp(linkage, "C++") == 0) {
10748 new_linkage = LINKAGE_CXX;
10750 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10751 new_linkage = LINKAGE_INVALID;
10753 current_linkage = new_linkage;
10755 if (token.type == '{') {
10764 assert(current_linkage == new_linkage);
10765 current_linkage = old_linkage;
10768 static void parse_external(void)
10770 switch (token.type) {
10771 DECLARATION_START_NO_EXTERN
10773 case T___extension__:
10774 case '(': /* for function declarations with implicit return type and
10775 * parenthesized declarator, i.e. (f)(void); */
10776 parse_external_declaration();
10780 if (look_ahead(1)->type == T_STRING_LITERAL) {
10781 parse_linkage_specification();
10783 parse_external_declaration();
10788 parse_global_asm();
10792 parse_namespace_definition();
10796 if (!strict_mode) {
10798 warningf(HERE, "stray ';' outside of function");
10805 errorf(HERE, "stray %K outside of function", &token);
10806 if (token.type == '(' || token.type == '{' || token.type == '[')
10807 eat_until_matching_token(token.type);
10813 static void parse_externals(void)
10815 add_anchor_token('}');
10816 add_anchor_token(T_EOF);
10819 unsigned char token_anchor_copy[T_LAST_TOKEN];
10820 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10823 while (token.type != T_EOF && token.type != '}') {
10825 bool anchor_leak = false;
10826 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10827 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10829 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10830 anchor_leak = true;
10833 if (in_gcc_extension) {
10834 errorf(HERE, "Leaked __extension__");
10835 anchor_leak = true;
10845 rem_anchor_token(T_EOF);
10846 rem_anchor_token('}');
10850 * Parse a translation unit.
10852 static void parse_translation_unit(void)
10854 add_anchor_token(T_EOF);
10859 if (token.type == T_EOF)
10862 errorf(HERE, "stray %K outside of function", &token);
10863 if (token.type == '(' || token.type == '{' || token.type == '[')
10864 eat_until_matching_token(token.type);
10872 * @return the translation unit or NULL if errors occurred.
10874 void start_parsing(void)
10876 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10877 label_stack = NEW_ARR_F(stack_entry_t, 0);
10878 diagnostic_count = 0;
10882 type_set_output(stderr);
10883 ast_set_output(stderr);
10885 assert(unit == NULL);
10886 unit = allocate_ast_zero(sizeof(unit[0]));
10888 assert(file_scope == NULL);
10889 file_scope = &unit->scope;
10891 assert(current_scope == NULL);
10892 scope_push(&unit->scope);
10895 translation_unit_t *finish_parsing(void)
10897 /* do NOT use scope_pop() here, this will crash, will it by hand */
10898 assert(current_scope == &unit->scope);
10899 current_scope = NULL;
10901 assert(file_scope == &unit->scope);
10902 check_unused_globals();
10905 DEL_ARR_F(environment_stack);
10906 DEL_ARR_F(label_stack);
10908 translation_unit_t *result = unit;
10915 lookahead_bufpos = 0;
10916 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10919 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10920 parse_translation_unit();
10924 * Initialize the parser.
10926 void init_parser(void)
10928 sym_anonymous = symbol_table_insert("<anonymous>");
10930 if (c_mode & _MS) {
10931 /* add predefined symbols for extended-decl-modifier */
10932 sym_align = symbol_table_insert("align");
10933 sym_allocate = symbol_table_insert("allocate");
10934 sym_dllimport = symbol_table_insert("dllimport");
10935 sym_dllexport = symbol_table_insert("dllexport");
10936 sym_naked = symbol_table_insert("naked");
10937 sym_noinline = symbol_table_insert("noinline");
10938 sym_noreturn = symbol_table_insert("noreturn");
10939 sym_nothrow = symbol_table_insert("nothrow");
10940 sym_novtable = symbol_table_insert("novtable");
10941 sym_property = symbol_table_insert("property");
10942 sym_get = symbol_table_insert("get");
10943 sym_put = symbol_table_insert("put");
10944 sym_selectany = symbol_table_insert("selectany");
10945 sym_thread = symbol_table_insert("thread");
10946 sym_uuid = symbol_table_insert("uuid");
10947 sym_deprecated = symbol_table_insert("deprecated");
10948 sym_restrict = symbol_table_insert("restrict");
10949 sym_noalias = symbol_table_insert("noalias");
10951 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10953 init_expression_parsers();
10954 obstack_init(&temp_obst);
10956 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10957 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10961 * Terminate the parser.
10963 void exit_parser(void)
10965 obstack_free(&temp_obst, NULL);