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;
141 static declaration_t **incomplete_arrays;
144 #define PUSH_PARENT(stmt) \
145 statement_t *const prev_parent = current_parent; \
146 ((void)(current_parent = (stmt)))
147 #define POP_PARENT ((void)(current_parent = prev_parent))
149 /** special symbol used for anonymous entities. */
150 static const symbol_t *sym_anonymous = NULL;
152 /* symbols for Microsoft extended-decl-modifier */
153 static const symbol_t *sym_align = NULL;
154 static const symbol_t *sym_allocate = NULL;
155 static const symbol_t *sym_dllimport = NULL;
156 static const symbol_t *sym_dllexport = NULL;
157 static const symbol_t *sym_naked = NULL;
158 static const symbol_t *sym_noinline = NULL;
159 static const symbol_t *sym_returns_twice = NULL;
160 static const symbol_t *sym_noreturn = NULL;
161 static const symbol_t *sym_nothrow = NULL;
162 static const symbol_t *sym_novtable = NULL;
163 static const symbol_t *sym_property = NULL;
164 static const symbol_t *sym_get = NULL;
165 static const symbol_t *sym_put = NULL;
166 static const symbol_t *sym_selectany = NULL;
167 static const symbol_t *sym_thread = NULL;
168 static const symbol_t *sym_uuid = NULL;
169 static const symbol_t *sym_deprecated = NULL;
170 static const symbol_t *sym_restrict = NULL;
171 static const symbol_t *sym_noalias = NULL;
173 /** The token anchor set */
174 static unsigned char token_anchor_set[T_LAST_TOKEN];
176 /** The current source position. */
177 #define HERE (&token.source_position)
179 /** true if we are in GCC mode. */
180 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
182 static type_t *type_valist;
184 static statement_t *parse_compound_statement(bool inside_expression_statement);
185 static statement_t *parse_statement(void);
187 static expression_t *parse_sub_expression(precedence_t);
188 static expression_t *parse_expression(void);
189 static type_t *parse_typename(void);
190 static void parse_externals(void);
191 static void parse_external(void);
193 static void parse_compound_type_entries(compound_t *compound_declaration);
195 typedef enum declarator_flags_t {
197 DECL_MAY_BE_ABSTRACT = 1U << 0,
198 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
199 DECL_IS_PARAMETER = 1U << 2
200 } declarator_flags_t;
202 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
203 declarator_flags_t flags);
205 static entity_t *record_entity(entity_t *entity, bool is_definition);
207 static void semantic_comparison(binary_expression_t *expression);
209 #define STORAGE_CLASSES \
210 STORAGE_CLASSES_NO_EXTERN \
213 #define STORAGE_CLASSES_NO_EXTERN \
220 #define TYPE_QUALIFIERS \
225 case T__forceinline: \
226 case T___attribute__:
228 #define COMPLEX_SPECIFIERS \
230 #define IMAGINARY_SPECIFIERS \
233 #define TYPE_SPECIFIERS \
235 case T___builtin_va_list: \
255 #define DECLARATION_START \
260 #define DECLARATION_START_NO_EXTERN \
261 STORAGE_CLASSES_NO_EXTERN \
265 #define TYPENAME_START \
269 #define EXPRESSION_START \
278 case T_CHARACTER_CONSTANT: \
279 case T_FLOATINGPOINT: \
283 case T_STRING_LITERAL: \
284 case T_WIDE_CHARACTER_CONSTANT: \
285 case T_WIDE_STRING_LITERAL: \
286 case T___FUNCDNAME__: \
287 case T___FUNCSIG__: \
288 case T___FUNCTION__: \
289 case T___PRETTY_FUNCTION__: \
290 case T___alignof__: \
291 case T___builtin_alloca: \
292 case T___builtin_classify_type: \
293 case T___builtin_constant_p: \
294 case T___builtin_expect: \
295 case T___builtin_huge_val: \
296 case T___builtin_inf: \
297 case T___builtin_inff: \
298 case T___builtin_infl: \
299 case T___builtin_isgreater: \
300 case T___builtin_isgreaterequal: \
301 case T___builtin_isless: \
302 case T___builtin_islessequal: \
303 case T___builtin_islessgreater: \
304 case T___builtin_isunordered: \
305 case T___builtin_nan: \
306 case T___builtin_nanf: \
307 case T___builtin_nanl: \
308 case T___builtin_offsetof: \
309 case T___builtin_prefetch: \
310 case T___builtin_va_arg: \
311 case T___builtin_va_end: \
312 case T___builtin_va_start: \
323 * Allocate an AST node with given size and
324 * initialize all fields with zero.
326 static void *allocate_ast_zero(size_t size)
328 void *res = allocate_ast(size);
329 memset(res, 0, size);
334 * Returns the size of an entity node.
336 * @param kind the entity kind
338 static size_t get_entity_struct_size(entity_kind_t kind)
340 static const size_t sizes[] = {
341 [ENTITY_VARIABLE] = sizeof(variable_t),
342 [ENTITY_PARAMETER] = sizeof(parameter_t),
343 [ENTITY_COMPOUND_MEMBER] = sizeof(compound_member_t),
344 [ENTITY_FUNCTION] = sizeof(function_t),
345 [ENTITY_TYPEDEF] = sizeof(typedef_t),
346 [ENTITY_STRUCT] = sizeof(compound_t),
347 [ENTITY_UNION] = sizeof(compound_t),
348 [ENTITY_ENUM] = sizeof(enum_t),
349 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
350 [ENTITY_LABEL] = sizeof(label_t),
351 [ENTITY_LOCAL_LABEL] = sizeof(label_t),
352 [ENTITY_NAMESPACE] = sizeof(namespace_t)
354 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
355 assert(sizes[kind] != 0);
360 * Allocate an entity of given kind and initialize all
363 static entity_t *allocate_entity_zero(entity_kind_t kind)
365 size_t size = get_entity_struct_size(kind);
366 entity_t *entity = allocate_ast_zero(size);
372 * Returns the size of a statement node.
374 * @param kind the statement kind
376 static size_t get_statement_struct_size(statement_kind_t kind)
378 static const size_t sizes[] = {
379 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
380 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
381 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
382 [STATEMENT_RETURN] = sizeof(return_statement_t),
383 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
384 [STATEMENT_IF] = sizeof(if_statement_t),
385 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
386 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
387 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
388 [STATEMENT_BREAK] = sizeof(statement_base_t),
389 [STATEMENT_GOTO] = sizeof(goto_statement_t),
390 [STATEMENT_LABEL] = sizeof(label_statement_t),
391 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
392 [STATEMENT_WHILE] = sizeof(while_statement_t),
393 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
394 [STATEMENT_FOR] = sizeof(for_statement_t),
395 [STATEMENT_ASM] = sizeof(asm_statement_t),
396 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
397 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
399 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
400 assert(sizes[kind] != 0);
405 * Returns the size of an expression node.
407 * @param kind the expression kind
409 static size_t get_expression_struct_size(expression_kind_t kind)
411 static const size_t sizes[] = {
412 [EXPR_INVALID] = sizeof(expression_base_t),
413 [EXPR_REFERENCE] = sizeof(reference_expression_t),
414 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
415 [EXPR_CONST] = sizeof(const_expression_t),
416 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
417 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
418 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
419 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
420 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
421 [EXPR_CALL] = sizeof(call_expression_t),
422 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
423 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
424 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
425 [EXPR_SELECT] = sizeof(select_expression_t),
426 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
427 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
428 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
429 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
430 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
431 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
432 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
433 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
434 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
435 [EXPR_VA_START] = sizeof(va_start_expression_t),
436 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
437 [EXPR_STATEMENT] = sizeof(statement_expression_t),
438 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
440 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
441 return sizes[EXPR_UNARY_FIRST];
443 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
444 return sizes[EXPR_BINARY_FIRST];
446 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
447 assert(sizes[kind] != 0);
452 * Allocate a statement node of given kind and initialize all
453 * fields with zero. Sets its source position to the position
454 * of the current token.
456 static statement_t *allocate_statement_zero(statement_kind_t kind)
458 size_t size = get_statement_struct_size(kind);
459 statement_t *res = allocate_ast_zero(size);
461 res->base.kind = kind;
462 res->base.parent = current_parent;
463 res->base.source_position = token.source_position;
468 * Allocate an expression node of given kind and initialize all
471 static expression_t *allocate_expression_zero(expression_kind_t kind)
473 size_t size = get_expression_struct_size(kind);
474 expression_t *res = allocate_ast_zero(size);
476 res->base.kind = kind;
477 res->base.type = type_error_type;
478 res->base.source_position = token.source_position;
483 * Creates a new invalid expression at the source position
484 * of the current token.
486 static expression_t *create_invalid_expression(void)
488 return allocate_expression_zero(EXPR_INVALID);
492 * Creates a new invalid statement.
494 static statement_t *create_invalid_statement(void)
496 return allocate_statement_zero(STATEMENT_INVALID);
500 * Allocate a new empty statement.
502 static statement_t *create_empty_statement(void)
504 return allocate_statement_zero(STATEMENT_EMPTY);
508 * Returns the size of a type node.
510 * @param kind the type kind
512 static size_t get_type_struct_size(type_kind_t kind)
514 static const size_t sizes[] = {
515 [TYPE_ATOMIC] = sizeof(atomic_type_t),
516 [TYPE_COMPLEX] = sizeof(complex_type_t),
517 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
518 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
519 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
520 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
521 [TYPE_ENUM] = sizeof(enum_type_t),
522 [TYPE_FUNCTION] = sizeof(function_type_t),
523 [TYPE_POINTER] = sizeof(pointer_type_t),
524 [TYPE_ARRAY] = sizeof(array_type_t),
525 [TYPE_BUILTIN] = sizeof(builtin_type_t),
526 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
527 [TYPE_TYPEOF] = sizeof(typeof_type_t),
529 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
530 assert(kind <= TYPE_TYPEOF);
531 assert(sizes[kind] != 0);
536 * Allocate a type node of given kind and initialize all
539 * @param kind type kind to allocate
541 static type_t *allocate_type_zero(type_kind_t kind)
543 size_t size = get_type_struct_size(kind);
544 type_t *res = obstack_alloc(type_obst, size);
545 memset(res, 0, size);
546 res->base.kind = kind;
552 * Returns the size of an initializer node.
554 * @param kind the initializer kind
556 static size_t get_initializer_size(initializer_kind_t kind)
558 static const size_t sizes[] = {
559 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
560 [INITIALIZER_STRING] = sizeof(initializer_string_t),
561 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
562 [INITIALIZER_LIST] = sizeof(initializer_list_t),
563 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
565 assert(kind < sizeof(sizes) / sizeof(*sizes));
566 assert(sizes[kind] != 0);
571 * Allocate an initializer node of given kind and initialize all
574 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
576 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
583 * Free a type from the type obstack.
585 static void free_type(void *type)
587 obstack_free(type_obst, type);
591 * Returns the index of the top element of the environment stack.
593 static size_t environment_top(void)
595 return ARR_LEN(environment_stack);
599 * Returns the index of the top element of the global label stack.
601 static size_t label_top(void)
603 return ARR_LEN(label_stack);
607 * Return the next token.
609 static inline void next_token(void)
611 token = lookahead_buffer[lookahead_bufpos];
612 lookahead_buffer[lookahead_bufpos] = lexer_token;
615 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
618 print_token(stderr, &token);
619 fprintf(stderr, "\n");
624 * Return the next token with a given lookahead.
626 static inline const token_t *look_ahead(int num)
628 assert(num > 0 && num <= MAX_LOOKAHEAD);
629 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
630 return &lookahead_buffer[pos];
634 * Adds a token type to the token type anchor set (a multi-set).
636 static void add_anchor_token(int token_type)
638 assert(0 <= token_type && token_type < T_LAST_TOKEN);
639 ++token_anchor_set[token_type];
643 * Set the number of tokens types of the given type
644 * to zero and return the old count.
646 static int save_and_reset_anchor_state(int token_type)
648 assert(0 <= token_type && token_type < T_LAST_TOKEN);
649 int count = token_anchor_set[token_type];
650 token_anchor_set[token_type] = 0;
655 * Restore the number of token types to the given count.
657 static void restore_anchor_state(int token_type, int count)
659 assert(0 <= token_type && token_type < T_LAST_TOKEN);
660 token_anchor_set[token_type] = count;
664 * Remove a token type from the token type anchor set (a multi-set).
666 static void rem_anchor_token(int token_type)
668 assert(0 <= token_type && token_type < T_LAST_TOKEN);
669 assert(token_anchor_set[token_type] != 0);
670 --token_anchor_set[token_type];
674 * Return true if the token type of the current token is
677 static bool at_anchor(void)
681 return token_anchor_set[token.type];
685 * Eat tokens until a matching token type is found.
687 static void eat_until_matching_token(int type)
691 case '(': end_token = ')'; break;
692 case '{': end_token = '}'; break;
693 case '[': end_token = ']'; break;
694 default: end_token = type; break;
697 unsigned parenthesis_count = 0;
698 unsigned brace_count = 0;
699 unsigned bracket_count = 0;
700 while (token.type != end_token ||
701 parenthesis_count != 0 ||
703 bracket_count != 0) {
704 switch (token.type) {
706 case '(': ++parenthesis_count; break;
707 case '{': ++brace_count; break;
708 case '[': ++bracket_count; break;
711 if (parenthesis_count > 0)
721 if (bracket_count > 0)
724 if (token.type == end_token &&
725 parenthesis_count == 0 &&
739 * Eat input tokens until an anchor is found.
741 static void eat_until_anchor(void)
743 while (token_anchor_set[token.type] == 0) {
744 if (token.type == '(' || token.type == '{' || token.type == '[')
745 eat_until_matching_token(token.type);
751 * Eat a whole block from input tokens.
753 static void eat_block(void)
755 eat_until_matching_token('{');
756 if (token.type == '}')
760 #define eat(token_type) do { assert(token.type == (token_type)); next_token(); } while (0)
763 * Report a parse error because an expected token was not found.
766 #if defined __GNUC__ && __GNUC__ >= 4
767 __attribute__((sentinel))
769 void parse_error_expected(const char *message, ...)
771 if (message != NULL) {
772 errorf(HERE, "%s", message);
775 va_start(ap, message);
776 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
781 * Report an incompatible type.
783 static void type_error_incompatible(const char *msg,
784 const source_position_t *source_position, type_t *type1, type_t *type2)
786 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
791 * Expect the current token is the expected token.
792 * If not, generate an error, eat the current statement,
793 * and goto the end_error label.
795 #define expect(expected, error_label) \
797 if (UNLIKELY(token.type != (expected))) { \
798 parse_error_expected(NULL, (expected), NULL); \
799 add_anchor_token(expected); \
800 eat_until_anchor(); \
801 if (token.type == expected) \
803 rem_anchor_token(expected); \
810 * Push a given scope on the scope stack and make it the
813 static scope_t *scope_push(scope_t *new_scope)
815 if (current_scope != NULL) {
816 new_scope->depth = current_scope->depth + 1;
819 scope_t *old_scope = current_scope;
820 current_scope = new_scope;
825 * Pop the current scope from the scope stack.
827 static void scope_pop(scope_t *old_scope)
829 current_scope = old_scope;
833 * Search an entity by its symbol in a given namespace.
835 static entity_t *get_entity(const symbol_t *const symbol,
836 namespace_tag_t namespc)
838 entity_t *entity = symbol->entity;
839 for (; entity != NULL; entity = entity->base.symbol_next) {
840 if (entity->base.namespc == namespc)
848 * pushs an entity on the environment stack and links the corresponding symbol
851 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
853 symbol_t *symbol = entity->base.symbol;
854 entity_namespace_t namespc = entity->base.namespc;
855 assert(namespc != NAMESPACE_INVALID);
857 /* replace/add entity into entity list of the symbol */
860 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
865 /* replace an entry? */
866 if (iter->base.namespc == namespc) {
867 entity->base.symbol_next = iter->base.symbol_next;
873 /* remember old declaration */
875 entry.symbol = symbol;
876 entry.old_entity = iter;
877 entry.namespc = namespc;
878 ARR_APP1(stack_entry_t, *stack_ptr, entry);
882 * Push an entity on the environment stack.
884 static void environment_push(entity_t *entity)
886 assert(entity->base.source_position.input_name != NULL);
887 assert(entity->base.parent_scope != NULL);
888 stack_push(&environment_stack, entity);
892 * Push a declaration on the global label stack.
894 * @param declaration the declaration
896 static void label_push(entity_t *label)
898 /* we abuse the parameters scope as parent for the labels */
899 label->base.parent_scope = ¤t_function->parameters;
900 stack_push(&label_stack, label);
904 * pops symbols from the environment stack until @p new_top is the top element
906 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
908 stack_entry_t *stack = *stack_ptr;
909 size_t top = ARR_LEN(stack);
912 assert(new_top <= top);
916 for (i = top; i > new_top; --i) {
917 stack_entry_t *entry = &stack[i - 1];
919 entity_t *old_entity = entry->old_entity;
920 symbol_t *symbol = entry->symbol;
921 entity_namespace_t namespc = entry->namespc;
923 /* replace with old_entity/remove */
926 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
928 assert(iter != NULL);
929 /* replace an entry? */
930 if (iter->base.namespc == namespc)
934 /* restore definition from outer scopes (if there was one) */
935 if (old_entity != NULL) {
936 old_entity->base.symbol_next = iter->base.symbol_next;
937 *anchor = old_entity;
939 /* remove entry from list */
940 *anchor = iter->base.symbol_next;
944 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
948 * Pop all entries from the environment stack until the new_top
951 * @param new_top the new stack top
953 static void environment_pop_to(size_t new_top)
955 stack_pop_to(&environment_stack, new_top);
959 * Pop all entries from the global label stack until the new_top
962 * @param new_top the new stack top
964 static void label_pop_to(size_t new_top)
966 stack_pop_to(&label_stack, new_top);
969 static int get_akind_rank(atomic_type_kind_t akind)
975 * Return the type rank for an atomic type.
977 static int get_rank(const type_t *type)
979 assert(!is_typeref(type));
980 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
981 * and esp. footnote 108). However we can't fold constants (yet), so we
982 * can't decide whether unsigned int is possible, while int always works.
983 * (unsigned int would be preferable when possible... for stuff like
984 * struct { enum { ... } bla : 4; } ) */
985 if (type->kind == TYPE_ENUM)
986 return get_akind_rank(ATOMIC_TYPE_INT);
988 assert(type->kind == TYPE_ATOMIC);
989 return get_akind_rank(type->atomic.akind);
993 * Do integer promotion for a given type.
995 * @param type the type to promote
996 * @return the promoted type
998 static type_t *promote_integer(type_t *type)
1000 if (type->kind == TYPE_BITFIELD)
1001 type = type->bitfield.base_type;
1003 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
1010 * Create a cast expression.
1012 * @param expression the expression to cast
1013 * @param dest_type the destination type
1015 static expression_t *create_cast_expression(expression_t *expression,
1018 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
1020 cast->unary.value = expression;
1021 cast->base.type = dest_type;
1027 * Check if a given expression represents a null pointer constant.
1029 * @param expression the expression to check
1031 static bool is_null_pointer_constant(const expression_t *expression)
1033 /* skip void* cast */
1034 if (expression->kind == EXPR_UNARY_CAST ||
1035 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
1036 type_t *const type = skip_typeref(expression->base.type);
1037 if (types_compatible(type, type_void_ptr))
1038 expression = expression->unary.value;
1041 type_t *const type = skip_typeref(expression->base.type);
1043 is_type_integer(type) &&
1044 is_constant_expression(expression) &&
1045 fold_constant(expression) == 0;
1049 * Create an implicit cast expression.
1051 * @param expression the expression to cast
1052 * @param dest_type the destination type
1054 static expression_t *create_implicit_cast(expression_t *expression,
1057 type_t *const source_type = expression->base.type;
1059 if (source_type == dest_type)
1062 return create_cast_expression(expression, dest_type);
1065 typedef enum assign_error_t {
1067 ASSIGN_ERROR_INCOMPATIBLE,
1068 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1069 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1070 ASSIGN_WARNING_POINTER_FROM_INT,
1071 ASSIGN_WARNING_INT_FROM_POINTER
1074 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1075 const expression_t *const right,
1076 const char *context,
1077 const source_position_t *source_position)
1079 type_t *const orig_type_right = right->base.type;
1080 type_t *const type_left = skip_typeref(orig_type_left);
1081 type_t *const type_right = skip_typeref(orig_type_right);
1084 case ASSIGN_SUCCESS:
1086 case ASSIGN_ERROR_INCOMPATIBLE:
1087 errorf(source_position,
1088 "destination type '%T' in %s is incompatible with type '%T'",
1089 orig_type_left, context, orig_type_right);
1092 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1093 if (warning.other) {
1094 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1095 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1097 /* the left type has all qualifiers from the right type */
1098 unsigned missing_qualifiers
1099 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1100 warningf(source_position,
1101 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1102 orig_type_left, context, orig_type_right, missing_qualifiers);
1107 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1108 if (warning.other) {
1109 warningf(source_position,
1110 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1111 orig_type_left, context, right, orig_type_right);
1115 case ASSIGN_WARNING_POINTER_FROM_INT:
1116 if (warning.other) {
1117 warningf(source_position,
1118 "%s makes pointer '%T' from integer '%T' without a cast",
1119 context, orig_type_left, orig_type_right);
1123 case ASSIGN_WARNING_INT_FROM_POINTER:
1124 if (warning.other) {
1125 warningf(source_position,
1126 "%s makes integer '%T' from pointer '%T' without a cast",
1127 context, orig_type_left, orig_type_right);
1132 panic("invalid error value");
1136 /** Implements the rules from § 6.5.16.1 */
1137 static assign_error_t semantic_assign(type_t *orig_type_left,
1138 const expression_t *const right)
1140 type_t *const orig_type_right = right->base.type;
1141 type_t *const type_left = skip_typeref(orig_type_left);
1142 type_t *const type_right = skip_typeref(orig_type_right);
1144 if (is_type_pointer(type_left)) {
1145 if (is_null_pointer_constant(right)) {
1146 return ASSIGN_SUCCESS;
1147 } else if (is_type_pointer(type_right)) {
1148 type_t *points_to_left
1149 = skip_typeref(type_left->pointer.points_to);
1150 type_t *points_to_right
1151 = skip_typeref(type_right->pointer.points_to);
1152 assign_error_t res = ASSIGN_SUCCESS;
1154 /* the left type has all qualifiers from the right type */
1155 unsigned missing_qualifiers
1156 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1157 if (missing_qualifiers != 0) {
1158 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1161 points_to_left = get_unqualified_type(points_to_left);
1162 points_to_right = get_unqualified_type(points_to_right);
1164 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1167 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1168 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1169 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1172 if (!types_compatible(points_to_left, points_to_right)) {
1173 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1177 } else if (is_type_integer(type_right)) {
1178 return ASSIGN_WARNING_POINTER_FROM_INT;
1180 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1181 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1182 && is_type_pointer(type_right))) {
1183 return ASSIGN_SUCCESS;
1184 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1185 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1186 type_t *const unqual_type_left = get_unqualified_type(type_left);
1187 type_t *const unqual_type_right = get_unqualified_type(type_right);
1188 if (types_compatible(unqual_type_left, unqual_type_right)) {
1189 return ASSIGN_SUCCESS;
1191 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1192 return ASSIGN_WARNING_INT_FROM_POINTER;
1195 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1196 return ASSIGN_SUCCESS;
1198 return ASSIGN_ERROR_INCOMPATIBLE;
1201 static expression_t *parse_constant_expression(void)
1203 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1205 if (!is_constant_expression(result)) {
1206 errorf(&result->base.source_position,
1207 "expression '%E' is not constant", result);
1213 static expression_t *parse_assignment_expression(void)
1215 return parse_sub_expression(PREC_ASSIGNMENT);
1218 static string_t parse_string_literals(void)
1220 assert(token.type == T_STRING_LITERAL);
1221 string_t result = token.v.string;
1225 while (token.type == T_STRING_LITERAL) {
1226 result = concat_strings(&result, &token.v.string);
1233 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1234 [GNU_AK_CONST] = "const",
1235 [GNU_AK_VOLATILE] = "volatile",
1236 [GNU_AK_CDECL] = "cdecl",
1237 [GNU_AK_STDCALL] = "stdcall",
1238 [GNU_AK_FASTCALL] = "fastcall",
1239 [GNU_AK_DEPRECATED] = "deprecated",
1240 [GNU_AK_NOINLINE] = "noinline",
1241 [GNU_AK_RETURNS_TWICE] = "returns_twice",
1242 [GNU_AK_NORETURN] = "noreturn",
1243 [GNU_AK_NAKED] = "naked",
1244 [GNU_AK_PURE] = "pure",
1245 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1246 [GNU_AK_MALLOC] = "malloc",
1247 [GNU_AK_WEAK] = "weak",
1248 [GNU_AK_CONSTRUCTOR] = "constructor",
1249 [GNU_AK_DESTRUCTOR] = "destructor",
1250 [GNU_AK_NOTHROW] = "nothrow",
1251 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1252 [GNU_AK_COMMON] = "common",
1253 [GNU_AK_NOCOMMON] = "nocommon",
1254 [GNU_AK_PACKED] = "packed",
1255 [GNU_AK_SHARED] = "shared",
1256 [GNU_AK_NOTSHARED] = "notshared",
1257 [GNU_AK_USED] = "used",
1258 [GNU_AK_UNUSED] = "unused",
1259 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1260 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1261 [GNU_AK_LONGCALL] = "longcall",
1262 [GNU_AK_SHORTCALL] = "shortcall",
1263 [GNU_AK_LONG_CALL] = "long_call",
1264 [GNU_AK_SHORT_CALL] = "short_call",
1265 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1266 [GNU_AK_INTERRUPT] = "interrupt",
1267 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1268 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1269 [GNU_AK_NESTING] = "nesting",
1270 [GNU_AK_NEAR] = "near",
1271 [GNU_AK_FAR] = "far",
1272 [GNU_AK_SIGNAL] = "signal",
1273 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1274 [GNU_AK_TINY_DATA] = "tiny_data",
1275 [GNU_AK_SAVEALL] = "saveall",
1276 [GNU_AK_FLATTEN] = "flatten",
1277 [GNU_AK_SSEREGPARM] = "sseregparm",
1278 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1279 [GNU_AK_RETURN_TWICE] = "return_twice",
1280 [GNU_AK_MAY_ALIAS] = "may_alias",
1281 [GNU_AK_MS_STRUCT] = "ms_struct",
1282 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1283 [GNU_AK_DLLIMPORT] = "dllimport",
1284 [GNU_AK_DLLEXPORT] = "dllexport",
1285 [GNU_AK_ALIGNED] = "aligned",
1286 [GNU_AK_ALIAS] = "alias",
1287 [GNU_AK_SECTION] = "section",
1288 [GNU_AK_FORMAT] = "format",
1289 [GNU_AK_FORMAT_ARG] = "format_arg",
1290 [GNU_AK_WEAKREF] = "weakref",
1291 [GNU_AK_NONNULL] = "nonnull",
1292 [GNU_AK_TLS_MODEL] = "tls_model",
1293 [GNU_AK_VISIBILITY] = "visibility",
1294 [GNU_AK_REGPARM] = "regparm",
1295 [GNU_AK_MODE] = "mode",
1296 [GNU_AK_MODEL] = "model",
1297 [GNU_AK_TRAP_EXIT] = "trap_exit",
1298 [GNU_AK_SP_SWITCH] = "sp_switch",
1299 [GNU_AK_SENTINEL] = "sentinel"
1303 * compare two string, ignoring double underscores on the second.
1305 static int strcmp_underscore(const char *s1, const char *s2)
1307 if (s2[0] == '_' && s2[1] == '_') {
1308 size_t len2 = strlen(s2);
1309 size_t len1 = strlen(s1);
1310 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1311 return strncmp(s1, s2+2, len2-4);
1315 return strcmp(s1, s2);
1319 * Allocate a new gnu temporal attribute of given kind.
1321 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1323 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1324 attribute->kind = kind;
1325 attribute->next = NULL;
1326 attribute->invalid = false;
1327 attribute->have_arguments = false;
1333 * Parse one constant expression argument of the given attribute.
1335 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1337 expression_t *expression;
1338 add_anchor_token(')');
1339 expression = parse_constant_expression();
1340 rem_anchor_token(')');
1341 expect(')', end_error);
1342 attribute->u.argument = fold_constant(expression);
1345 attribute->invalid = true;
1349 * Parse a list of constant expressions arguments of the given attribute.
1351 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1353 argument_list_t **list = &attribute->u.arguments;
1354 argument_list_t *entry;
1355 expression_t *expression;
1356 add_anchor_token(')');
1357 add_anchor_token(',');
1359 expression = parse_constant_expression();
1360 entry = obstack_alloc(&temp_obst, sizeof(entry));
1361 entry->argument = fold_constant(expression);
1364 list = &entry->next;
1365 if (token.type != ',')
1369 rem_anchor_token(',');
1370 rem_anchor_token(')');
1371 expect(')', end_error);
1374 attribute->invalid = true;
1378 * Parse one string literal argument of the given attribute.
1380 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1383 add_anchor_token('(');
1384 if (token.type != T_STRING_LITERAL) {
1385 parse_error_expected("while parsing attribute directive",
1386 T_STRING_LITERAL, NULL);
1389 *string = parse_string_literals();
1390 rem_anchor_token('(');
1391 expect(')', end_error);
1394 attribute->invalid = true;
1398 * Parse one tls model of the given attribute.
1400 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1402 static const char *const tls_models[] = {
1408 string_t string = { NULL, 0 };
1409 parse_gnu_attribute_string_arg(attribute, &string);
1410 if (string.begin != NULL) {
1411 for (size_t i = 0; i < 4; ++i) {
1412 if (strcmp(tls_models[i], string.begin) == 0) {
1413 attribute->u.value = i;
1417 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1419 attribute->invalid = true;
1423 * Parse one tls model of the given attribute.
1425 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1427 static const char *const visibilities[] = {
1433 string_t string = { NULL, 0 };
1434 parse_gnu_attribute_string_arg(attribute, &string);
1435 if (string.begin != NULL) {
1436 for (size_t i = 0; i < 4; ++i) {
1437 if (strcmp(visibilities[i], string.begin) == 0) {
1438 attribute->u.value = i;
1442 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1444 attribute->invalid = true;
1448 * Parse one (code) model of the given attribute.
1450 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1452 static const char *const visibilities[] = {
1457 string_t string = { NULL, 0 };
1458 parse_gnu_attribute_string_arg(attribute, &string);
1459 if (string.begin != NULL) {
1460 for (int i = 0; i < 3; ++i) {
1461 if (strcmp(visibilities[i], string.begin) == 0) {
1462 attribute->u.value = i;
1466 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1468 attribute->invalid = true;
1472 * Parse one mode of the given attribute.
1474 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1476 /* TODO: find out what is allowed here... */
1478 /* at least: byte, word, pointer, list of machine modes
1479 * __XXX___ is interpreted as XXX */
1480 add_anchor_token(')');
1482 if (token.type != T_IDENTIFIER) {
1483 expect(T_IDENTIFIER, end_error);
1486 /* This isn't really correct, the backend should provide a list of machine
1487 * specific modes (according to gcc philosophy that is...) */
1488 const char *symbol_str = token.v.symbol->string;
1489 if (strcmp_underscore("QI", symbol_str) == 0 ||
1490 strcmp_underscore("byte", symbol_str) == 0) {
1491 attribute->u.akind = ATOMIC_TYPE_CHAR;
1492 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1493 attribute->u.akind = ATOMIC_TYPE_SHORT;
1494 } else if (strcmp_underscore("SI", symbol_str) == 0
1495 || strcmp_underscore("word", symbol_str) == 0
1496 || strcmp_underscore("pointer", symbol_str) == 0) {
1497 attribute->u.akind = ATOMIC_TYPE_INT;
1498 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1499 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1502 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1503 attribute->invalid = true;
1507 rem_anchor_token(')');
1508 expect(')', end_error);
1511 attribute->invalid = true;
1515 * Parse one interrupt argument of the given attribute.
1517 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1519 static const char *const interrupts[] = {
1526 string_t string = { NULL, 0 };
1527 parse_gnu_attribute_string_arg(attribute, &string);
1528 if (string.begin != NULL) {
1529 for (size_t i = 0; i < 5; ++i) {
1530 if (strcmp(interrupts[i], string.begin) == 0) {
1531 attribute->u.value = i;
1535 errorf(HERE, "'%s' is not an interrupt", string.begin);
1537 attribute->invalid = true;
1541 * Parse ( identifier, const expression, const expression )
1543 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1545 static const char *const format_names[] = {
1553 if (token.type != T_IDENTIFIER) {
1554 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1557 const char *name = token.v.symbol->string;
1558 for (i = 0; i < 4; ++i) {
1559 if (strcmp_underscore(format_names[i], name) == 0)
1563 if (warning.attribute)
1564 warningf(HERE, "'%s' is an unrecognized format function type", name);
1568 expect(',', end_error);
1569 add_anchor_token(')');
1570 add_anchor_token(',');
1571 parse_constant_expression();
1572 rem_anchor_token(',');
1573 rem_anchor_token(')');
1575 expect(',', end_error);
1576 add_anchor_token(')');
1577 parse_constant_expression();
1578 rem_anchor_token(')');
1579 expect(')', end_error);
1582 attribute->u.value = true;
1586 * Check that a given GNU attribute has no arguments.
1588 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1590 if (!attribute->have_arguments)
1593 /* should have no arguments */
1594 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1595 eat_until_matching_token('(');
1596 /* we have already consumed '(', so we stop before ')', eat it */
1598 attribute->invalid = true;
1602 * Parse one GNU attribute.
1604 * Note that attribute names can be specified WITH or WITHOUT
1605 * double underscores, ie const or __const__.
1607 * The following attributes are parsed without arguments
1632 * no_instrument_function
1633 * warn_unused_result
1650 * externally_visible
1658 * The following attributes are parsed with arguments
1659 * aligned( const expression )
1660 * alias( string literal )
1661 * section( string literal )
1662 * format( identifier, const expression, const expression )
1663 * format_arg( const expression )
1664 * tls_model( string literal )
1665 * visibility( string literal )
1666 * regparm( const expression )
1667 * model( string leteral )
1668 * trap_exit( const expression )
1669 * sp_switch( string literal )
1671 * The following attributes might have arguments
1672 * weak_ref( string literal )
1673 * non_null( const expression // ',' )
1674 * interrupt( string literal )
1675 * sentinel( constant expression )
1677 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1679 gnu_attribute_t *head = *attributes;
1680 gnu_attribute_t *last = *attributes;
1681 decl_modifiers_t modifiers = 0;
1682 gnu_attribute_t *attribute;
1684 eat(T___attribute__);
1685 expect('(', end_error);
1686 expect('(', end_error);
1688 if (token.type != ')') {
1689 /* find the end of the list */
1691 while (last->next != NULL)
1695 /* non-empty attribute list */
1698 if (token.type == T_const) {
1700 } else if (token.type == T_volatile) {
1702 } else if (token.type == T_cdecl) {
1703 /* __attribute__((cdecl)), WITH ms mode */
1705 } else if (token.type == T_IDENTIFIER) {
1706 const symbol_t *sym = token.v.symbol;
1709 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1716 for (i = 0; i < GNU_AK_LAST; ++i) {
1717 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1720 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1723 if (kind == GNU_AK_LAST) {
1724 if (warning.attribute)
1725 warningf(HERE, "'%s' attribute directive ignored", name);
1727 /* skip possible arguments */
1728 if (token.type == '(') {
1729 eat_until_matching_token(')');
1732 /* check for arguments */
1733 attribute = allocate_gnu_attribute(kind);
1734 if (token.type == '(') {
1736 if (token.type == ')') {
1737 /* empty args are allowed */
1740 attribute->have_arguments = true;
1744 case GNU_AK_VOLATILE:
1749 case GNU_AK_NOCOMMON:
1751 case GNU_AK_NOTSHARED:
1752 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1753 case GNU_AK_WARN_UNUSED_RESULT:
1754 case GNU_AK_LONGCALL:
1755 case GNU_AK_SHORTCALL:
1756 case GNU_AK_LONG_CALL:
1757 case GNU_AK_SHORT_CALL:
1758 case GNU_AK_FUNCTION_VECTOR:
1759 case GNU_AK_INTERRUPT_HANDLER:
1760 case GNU_AK_NMI_HANDLER:
1761 case GNU_AK_NESTING:
1765 case GNU_AK_EIGTHBIT_DATA:
1766 case GNU_AK_TINY_DATA:
1767 case GNU_AK_SAVEALL:
1768 case GNU_AK_FLATTEN:
1769 case GNU_AK_SSEREGPARM:
1770 case GNU_AK_EXTERNALLY_VISIBLE:
1771 case GNU_AK_RETURN_TWICE:
1772 case GNU_AK_MAY_ALIAS:
1773 case GNU_AK_MS_STRUCT:
1774 case GNU_AK_GCC_STRUCT:
1777 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1778 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1779 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1780 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1781 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1782 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1783 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1784 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1785 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1786 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1787 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1788 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1789 case GNU_AK_RETURNS_TWICE: modifiers |= DM_RETURNS_TWICE; goto no_arg;
1790 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1791 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1792 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1793 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1794 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1795 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1797 case GNU_AK_ALIGNED:
1798 /* __align__ may be used without an argument */
1799 if (attribute->have_arguments) {
1800 parse_gnu_attribute_const_arg(attribute);
1804 case GNU_AK_FORMAT_ARG:
1805 case GNU_AK_REGPARM:
1806 case GNU_AK_TRAP_EXIT:
1807 if (!attribute->have_arguments) {
1808 /* should have arguments */
1809 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1810 attribute->invalid = true;
1812 parse_gnu_attribute_const_arg(attribute);
1815 case GNU_AK_SECTION:
1816 case GNU_AK_SP_SWITCH:
1817 if (!attribute->have_arguments) {
1818 /* should have arguments */
1819 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1820 attribute->invalid = true;
1822 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1825 if (!attribute->have_arguments) {
1826 /* should have arguments */
1827 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1828 attribute->invalid = true;
1830 parse_gnu_attribute_format_args(attribute);
1832 case GNU_AK_WEAKREF:
1833 /* may have one string argument */
1834 if (attribute->have_arguments)
1835 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1837 case GNU_AK_NONNULL:
1838 if (attribute->have_arguments)
1839 parse_gnu_attribute_const_arg_list(attribute);
1841 case GNU_AK_TLS_MODEL:
1842 if (!attribute->have_arguments) {
1843 /* should have arguments */
1844 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1846 parse_gnu_attribute_tls_model_arg(attribute);
1848 case GNU_AK_VISIBILITY:
1849 if (!attribute->have_arguments) {
1850 /* should have arguments */
1851 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1853 parse_gnu_attribute_visibility_arg(attribute);
1856 if (!attribute->have_arguments) {
1857 /* should have arguments */
1858 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1860 parse_gnu_attribute_model_arg(attribute);
1864 if (!attribute->have_arguments) {
1865 /* should have arguments */
1866 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1868 parse_gnu_attribute_mode_arg(attribute);
1871 case GNU_AK_INTERRUPT:
1872 /* may have one string argument */
1873 if (attribute->have_arguments)
1874 parse_gnu_attribute_interrupt_arg(attribute);
1876 case GNU_AK_SENTINEL:
1877 /* may have one string argument */
1878 if (attribute->have_arguments)
1879 parse_gnu_attribute_const_arg(attribute);
1882 /* already handled */
1886 check_no_argument(attribute, name);
1889 if (attribute != NULL) {
1891 last->next = attribute;
1894 head = last = attribute;
1898 if (token.type != ',')
1903 expect(')', end_error);
1904 expect(')', end_error);
1912 * Parse GNU attributes.
1914 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1916 decl_modifiers_t modifiers = 0;
1919 switch (token.type) {
1920 case T___attribute__:
1921 modifiers |= parse_gnu_attribute(attributes);
1926 expect('(', end_error);
1927 if (token.type != T_STRING_LITERAL) {
1928 parse_error_expected("while parsing assembler attribute",
1929 T_STRING_LITERAL, NULL);
1930 eat_until_matching_token('(');
1933 parse_string_literals();
1935 expect(')', end_error);
1938 case T_cdecl: modifiers |= DM_CDECL; break;
1939 case T__fastcall: modifiers |= DM_FASTCALL; break;
1940 case T__stdcall: modifiers |= DM_STDCALL; break;
1943 /* TODO record modifier */
1945 warningf(HERE, "Ignoring declaration modifier %K", &token);
1949 default: return modifiers;
1956 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1958 static entity_t *determine_lhs_ent(expression_t *const expr,
1961 switch (expr->kind) {
1962 case EXPR_REFERENCE: {
1963 entity_t *const entity = expr->reference.entity;
1964 /* we should only find variables as lvalues... */
1965 if (entity->base.kind != ENTITY_VARIABLE
1966 && entity->base.kind != ENTITY_PARAMETER)
1972 case EXPR_ARRAY_ACCESS: {
1973 expression_t *const ref = expr->array_access.array_ref;
1974 entity_t * ent = NULL;
1975 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1976 ent = determine_lhs_ent(ref, lhs_ent);
1979 mark_vars_read(expr->select.compound, lhs_ent);
1981 mark_vars_read(expr->array_access.index, lhs_ent);
1986 if (is_type_compound(skip_typeref(expr->base.type))) {
1987 return determine_lhs_ent(expr->select.compound, lhs_ent);
1989 mark_vars_read(expr->select.compound, lhs_ent);
1994 case EXPR_UNARY_DEREFERENCE: {
1995 expression_t *const val = expr->unary.value;
1996 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1998 return determine_lhs_ent(val->unary.value, lhs_ent);
2000 mark_vars_read(val, NULL);
2006 mark_vars_read(expr, NULL);
2011 #define ENT_ANY ((entity_t*)-1)
2014 * Mark declarations, which are read. This is used to detect variables, which
2018 * x is not marked as "read", because it is only read to calculate its own new
2022 * x and y are not detected as "not read", because multiple variables are
2025 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
2027 switch (expr->kind) {
2028 case EXPR_REFERENCE: {
2029 entity_t *const entity = expr->reference.entity;
2030 if (entity->kind != ENTITY_VARIABLE
2031 && entity->kind != ENTITY_PARAMETER)
2034 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
2035 if (entity->kind == ENTITY_VARIABLE) {
2036 entity->variable.read = true;
2038 entity->parameter.read = true;
2045 // TODO respect pure/const
2046 mark_vars_read(expr->call.function, NULL);
2047 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
2048 mark_vars_read(arg->expression, NULL);
2052 case EXPR_CONDITIONAL:
2053 // TODO lhs_decl should depend on whether true/false have an effect
2054 mark_vars_read(expr->conditional.condition, NULL);
2055 if (expr->conditional.true_expression != NULL)
2056 mark_vars_read(expr->conditional.true_expression, lhs_ent);
2057 mark_vars_read(expr->conditional.false_expression, lhs_ent);
2061 if (lhs_ent == ENT_ANY
2062 && !is_type_compound(skip_typeref(expr->base.type)))
2064 mark_vars_read(expr->select.compound, lhs_ent);
2067 case EXPR_ARRAY_ACCESS: {
2068 expression_t *const ref = expr->array_access.array_ref;
2069 mark_vars_read(ref, lhs_ent);
2070 lhs_ent = determine_lhs_ent(ref, lhs_ent);
2071 mark_vars_read(expr->array_access.index, lhs_ent);
2076 mark_vars_read(expr->va_arge.ap, lhs_ent);
2079 case EXPR_UNARY_CAST:
2080 /* Special case: Use void cast to mark a variable as "read" */
2081 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2086 case EXPR_UNARY_THROW:
2087 if (expr->unary.value == NULL)
2090 case EXPR_UNARY_DEREFERENCE:
2091 case EXPR_UNARY_DELETE:
2092 case EXPR_UNARY_DELETE_ARRAY:
2093 if (lhs_ent == ENT_ANY)
2097 case EXPR_UNARY_NEGATE:
2098 case EXPR_UNARY_PLUS:
2099 case EXPR_UNARY_BITWISE_NEGATE:
2100 case EXPR_UNARY_NOT:
2101 case EXPR_UNARY_TAKE_ADDRESS:
2102 case EXPR_UNARY_POSTFIX_INCREMENT:
2103 case EXPR_UNARY_POSTFIX_DECREMENT:
2104 case EXPR_UNARY_PREFIX_INCREMENT:
2105 case EXPR_UNARY_PREFIX_DECREMENT:
2106 case EXPR_UNARY_CAST_IMPLICIT:
2107 case EXPR_UNARY_ASSUME:
2109 mark_vars_read(expr->unary.value, lhs_ent);
2112 case EXPR_BINARY_ADD:
2113 case EXPR_BINARY_SUB:
2114 case EXPR_BINARY_MUL:
2115 case EXPR_BINARY_DIV:
2116 case EXPR_BINARY_MOD:
2117 case EXPR_BINARY_EQUAL:
2118 case EXPR_BINARY_NOTEQUAL:
2119 case EXPR_BINARY_LESS:
2120 case EXPR_BINARY_LESSEQUAL:
2121 case EXPR_BINARY_GREATER:
2122 case EXPR_BINARY_GREATEREQUAL:
2123 case EXPR_BINARY_BITWISE_AND:
2124 case EXPR_BINARY_BITWISE_OR:
2125 case EXPR_BINARY_BITWISE_XOR:
2126 case EXPR_BINARY_LOGICAL_AND:
2127 case EXPR_BINARY_LOGICAL_OR:
2128 case EXPR_BINARY_SHIFTLEFT:
2129 case EXPR_BINARY_SHIFTRIGHT:
2130 case EXPR_BINARY_COMMA:
2131 case EXPR_BINARY_ISGREATER:
2132 case EXPR_BINARY_ISGREATEREQUAL:
2133 case EXPR_BINARY_ISLESS:
2134 case EXPR_BINARY_ISLESSEQUAL:
2135 case EXPR_BINARY_ISLESSGREATER:
2136 case EXPR_BINARY_ISUNORDERED:
2137 mark_vars_read(expr->binary.left, lhs_ent);
2138 mark_vars_read(expr->binary.right, lhs_ent);
2141 case EXPR_BINARY_ASSIGN:
2142 case EXPR_BINARY_MUL_ASSIGN:
2143 case EXPR_BINARY_DIV_ASSIGN:
2144 case EXPR_BINARY_MOD_ASSIGN:
2145 case EXPR_BINARY_ADD_ASSIGN:
2146 case EXPR_BINARY_SUB_ASSIGN:
2147 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2148 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2149 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2150 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2151 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2152 if (lhs_ent == ENT_ANY)
2154 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
2155 mark_vars_read(expr->binary.right, lhs_ent);
2160 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
2166 case EXPR_CHARACTER_CONSTANT:
2167 case EXPR_WIDE_CHARACTER_CONSTANT:
2168 case EXPR_STRING_LITERAL:
2169 case EXPR_WIDE_STRING_LITERAL:
2170 case EXPR_COMPOUND_LITERAL: // TODO init?
2172 case EXPR_CLASSIFY_TYPE:
2175 case EXPR_BUILTIN_SYMBOL:
2176 case EXPR_BUILTIN_CONSTANT_P:
2177 case EXPR_BUILTIN_PREFETCH:
2179 case EXPR_STATEMENT: // TODO
2180 case EXPR_LABEL_ADDRESS:
2181 case EXPR_REFERENCE_ENUM_VALUE:
2185 panic("unhandled expression");
2188 static designator_t *parse_designation(void)
2190 designator_t *result = NULL;
2191 designator_t *last = NULL;
2194 designator_t *designator;
2195 switch (token.type) {
2197 designator = allocate_ast_zero(sizeof(designator[0]));
2198 designator->source_position = token.source_position;
2200 add_anchor_token(']');
2201 designator->array_index = parse_constant_expression();
2202 rem_anchor_token(']');
2203 expect(']', end_error);
2206 designator = allocate_ast_zero(sizeof(designator[0]));
2207 designator->source_position = token.source_position;
2209 if (token.type != T_IDENTIFIER) {
2210 parse_error_expected("while parsing designator",
2211 T_IDENTIFIER, NULL);
2214 designator->symbol = token.v.symbol;
2218 expect('=', end_error);
2222 assert(designator != NULL);
2224 last->next = designator;
2226 result = designator;
2234 static initializer_t *initializer_from_string(array_type_t *type,
2235 const string_t *const string)
2237 /* TODO: check len vs. size of array type */
2240 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2241 initializer->string.string = *string;
2246 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2247 wide_string_t *const string)
2249 /* TODO: check len vs. size of array type */
2252 initializer_t *const initializer =
2253 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2254 initializer->wide_string.string = *string;
2260 * Build an initializer from a given expression.
2262 static initializer_t *initializer_from_expression(type_t *orig_type,
2263 expression_t *expression)
2265 /* TODO check that expression is a constant expression */
2267 /* § 6.7.8.14/15 char array may be initialized by string literals */
2268 type_t *type = skip_typeref(orig_type);
2269 type_t *expr_type_orig = expression->base.type;
2270 type_t *expr_type = skip_typeref(expr_type_orig);
2271 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2272 array_type_t *const array_type = &type->array;
2273 type_t *const element_type = skip_typeref(array_type->element_type);
2275 if (element_type->kind == TYPE_ATOMIC) {
2276 atomic_type_kind_t akind = element_type->atomic.akind;
2277 switch (expression->kind) {
2278 case EXPR_STRING_LITERAL:
2279 if (akind == ATOMIC_TYPE_CHAR
2280 || akind == ATOMIC_TYPE_SCHAR
2281 || akind == ATOMIC_TYPE_UCHAR) {
2282 return initializer_from_string(array_type,
2283 &expression->string.value);
2286 case EXPR_WIDE_STRING_LITERAL: {
2287 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2288 if (get_unqualified_type(element_type) == bare_wchar_type) {
2289 return initializer_from_wide_string(array_type,
2290 &expression->wide_string.value);
2300 assign_error_t error = semantic_assign(type, expression);
2301 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2303 report_assign_error(error, type, expression, "initializer",
2304 &expression->base.source_position);
2306 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2308 if (type->kind == TYPE_BITFIELD) {
2309 type = type->bitfield.base_type;
2312 result->value.value = create_implicit_cast(expression, type);
2318 * Checks if a given expression can be used as an constant initializer.
2320 static bool is_initializer_constant(const expression_t *expression)
2322 return is_constant_expression(expression)
2323 || is_address_constant(expression);
2327 * Parses an scalar initializer.
2329 * § 6.7.8.11; eat {} without warning
2331 static initializer_t *parse_scalar_initializer(type_t *type,
2332 bool must_be_constant)
2334 /* there might be extra {} hierarchies */
2336 if (token.type == '{') {
2338 warningf(HERE, "extra curly braces around scalar initializer");
2342 } while (token.type == '{');
2345 expression_t *expression = parse_assignment_expression();
2346 mark_vars_read(expression, NULL);
2347 if (must_be_constant && !is_initializer_constant(expression)) {
2348 errorf(&expression->base.source_position,
2349 "Initialisation expression '%E' is not constant",
2353 initializer_t *initializer = initializer_from_expression(type, expression);
2355 if (initializer == NULL) {
2356 errorf(&expression->base.source_position,
2357 "expression '%E' (type '%T') doesn't match expected type '%T'",
2358 expression, expression->base.type, type);
2363 bool additional_warning_displayed = false;
2364 while (braces > 0) {
2365 if (token.type == ',') {
2368 if (token.type != '}') {
2369 if (!additional_warning_displayed && warning.other) {
2370 warningf(HERE, "additional elements in scalar initializer");
2371 additional_warning_displayed = true;
2382 * An entry in the type path.
2384 typedef struct type_path_entry_t type_path_entry_t;
2385 struct type_path_entry_t {
2386 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2388 size_t index; /**< For array types: the current index. */
2389 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2394 * A type path expression a position inside compound or array types.
2396 typedef struct type_path_t type_path_t;
2397 struct type_path_t {
2398 type_path_entry_t *path; /**< An flexible array containing the current path. */
2399 type_t *top_type; /**< type of the element the path points */
2400 size_t max_index; /**< largest index in outermost array */
2404 * Prints a type path for debugging.
2406 static __attribute__((unused)) void debug_print_type_path(
2407 const type_path_t *path)
2409 size_t len = ARR_LEN(path->path);
2411 for (size_t i = 0; i < len; ++i) {
2412 const type_path_entry_t *entry = & path->path[i];
2414 type_t *type = skip_typeref(entry->type);
2415 if (is_type_compound(type)) {
2416 /* in gcc mode structs can have no members */
2417 if (entry->v.compound_entry == NULL) {
2421 fprintf(stderr, ".%s",
2422 entry->v.compound_entry->base.symbol->string);
2423 } else if (is_type_array(type)) {
2424 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
2426 fprintf(stderr, "-INVALID-");
2429 if (path->top_type != NULL) {
2430 fprintf(stderr, " (");
2431 print_type(path->top_type);
2432 fprintf(stderr, ")");
2437 * Return the top type path entry, ie. in a path
2438 * (type).a.b returns the b.
2440 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2442 size_t len = ARR_LEN(path->path);
2444 return &path->path[len-1];
2448 * Enlarge the type path by an (empty) element.
2450 static type_path_entry_t *append_to_type_path(type_path_t *path)
2452 size_t len = ARR_LEN(path->path);
2453 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2455 type_path_entry_t *result = & path->path[len];
2456 memset(result, 0, sizeof(result[0]));
2461 * Descending into a sub-type. Enter the scope of the current top_type.
2463 static void descend_into_subtype(type_path_t *path)
2465 type_t *orig_top_type = path->top_type;
2466 type_t *top_type = skip_typeref(orig_top_type);
2468 type_path_entry_t *top = append_to_type_path(path);
2469 top->type = top_type;
2471 if (is_type_compound(top_type)) {
2472 compound_t *compound = top_type->compound.compound;
2473 entity_t *entry = compound->members.entities;
2475 if (entry != NULL) {
2476 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2477 top->v.compound_entry = &entry->declaration;
2478 path->top_type = entry->declaration.type;
2480 path->top_type = NULL;
2482 } else if (is_type_array(top_type)) {
2484 path->top_type = top_type->array.element_type;
2486 assert(!is_type_valid(top_type));
2491 * Pop an entry from the given type path, ie. returning from
2492 * (type).a.b to (type).a
2494 static void ascend_from_subtype(type_path_t *path)
2496 type_path_entry_t *top = get_type_path_top(path);
2498 path->top_type = top->type;
2500 size_t len = ARR_LEN(path->path);
2501 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2505 * Pop entries from the given type path until the given
2506 * path level is reached.
2508 static void ascend_to(type_path_t *path, size_t top_path_level)
2510 size_t len = ARR_LEN(path->path);
2512 while (len > top_path_level) {
2513 ascend_from_subtype(path);
2514 len = ARR_LEN(path->path);
2518 static bool walk_designator(type_path_t *path, const designator_t *designator,
2519 bool used_in_offsetof)
2521 for (; designator != NULL; designator = designator->next) {
2522 type_path_entry_t *top = get_type_path_top(path);
2523 type_t *orig_type = top->type;
2525 type_t *type = skip_typeref(orig_type);
2527 if (designator->symbol != NULL) {
2528 symbol_t *symbol = designator->symbol;
2529 if (!is_type_compound(type)) {
2530 if (is_type_valid(type)) {
2531 errorf(&designator->source_position,
2532 "'.%Y' designator used for non-compound type '%T'",
2536 top->type = type_error_type;
2537 top->v.compound_entry = NULL;
2538 orig_type = type_error_type;
2540 compound_t *compound = type->compound.compound;
2541 entity_t *iter = compound->members.entities;
2542 for (; iter != NULL; iter = iter->base.next) {
2543 if (iter->base.symbol == symbol) {
2548 errorf(&designator->source_position,
2549 "'%T' has no member named '%Y'", orig_type, symbol);
2552 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2553 if (used_in_offsetof) {
2554 type_t *real_type = skip_typeref(iter->declaration.type);
2555 if (real_type->kind == TYPE_BITFIELD) {
2556 errorf(&designator->source_position,
2557 "offsetof designator '%Y' may not specify bitfield",
2563 top->type = orig_type;
2564 top->v.compound_entry = &iter->declaration;
2565 orig_type = iter->declaration.type;
2568 expression_t *array_index = designator->array_index;
2569 assert(designator->array_index != NULL);
2571 if (!is_type_array(type)) {
2572 if (is_type_valid(type)) {
2573 errorf(&designator->source_position,
2574 "[%E] designator used for non-array type '%T'",
2575 array_index, orig_type);
2580 long index = fold_constant(array_index);
2581 if (!used_in_offsetof) {
2583 errorf(&designator->source_position,
2584 "array index [%E] must be positive", array_index);
2585 } else if (type->array.size_constant) {
2586 long array_size = type->array.size;
2587 if (index >= array_size) {
2588 errorf(&designator->source_position,
2589 "designator [%E] (%d) exceeds array size %d",
2590 array_index, index, array_size);
2595 top->type = orig_type;
2596 top->v.index = (size_t) index;
2597 orig_type = type->array.element_type;
2599 path->top_type = orig_type;
2601 if (designator->next != NULL) {
2602 descend_into_subtype(path);
2611 static void advance_current_object(type_path_t *path, size_t top_path_level)
2613 type_path_entry_t *top = get_type_path_top(path);
2615 type_t *type = skip_typeref(top->type);
2616 if (is_type_union(type)) {
2617 /* in unions only the first element is initialized */
2618 top->v.compound_entry = NULL;
2619 } else if (is_type_struct(type)) {
2620 declaration_t *entry = top->v.compound_entry;
2622 entity_t *next_entity = entry->base.next;
2623 if (next_entity != NULL) {
2624 assert(is_declaration(next_entity));
2625 entry = &next_entity->declaration;
2630 top->v.compound_entry = entry;
2631 if (entry != NULL) {
2632 path->top_type = entry->type;
2635 } else if (is_type_array(type)) {
2636 assert(is_type_array(type));
2640 if (!type->array.size_constant || top->v.index < type->array.size) {
2644 assert(!is_type_valid(type));
2648 /* we're past the last member of the current sub-aggregate, try if we
2649 * can ascend in the type hierarchy and continue with another subobject */
2650 size_t len = ARR_LEN(path->path);
2652 if (len > top_path_level) {
2653 ascend_from_subtype(path);
2654 advance_current_object(path, top_path_level);
2656 path->top_type = NULL;
2661 * skip until token is found.
2663 static void skip_until(int type)
2665 while (token.type != type) {
2666 if (token.type == T_EOF)
2673 * skip any {...} blocks until a closing bracket is reached.
2675 static void skip_initializers(void)
2677 if (token.type == '{')
2680 while (token.type != '}') {
2681 if (token.type == T_EOF)
2683 if (token.type == '{') {
2691 static initializer_t *create_empty_initializer(void)
2693 static initializer_t empty_initializer
2694 = { .list = { { INITIALIZER_LIST }, 0 } };
2695 return &empty_initializer;
2699 * Parse a part of an initialiser for a struct or union,
2701 static initializer_t *parse_sub_initializer(type_path_t *path,
2702 type_t *outer_type, size_t top_path_level,
2703 parse_initializer_env_t *env)
2705 if (token.type == '}') {
2706 /* empty initializer */
2707 return create_empty_initializer();
2710 type_t *orig_type = path->top_type;
2711 type_t *type = NULL;
2713 if (orig_type == NULL) {
2714 /* We are initializing an empty compound. */
2716 type = skip_typeref(orig_type);
2719 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2722 designator_t *designator = NULL;
2723 if (token.type == '.' || token.type == '[') {
2724 designator = parse_designation();
2725 goto finish_designator;
2726 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2727 /* GNU-style designator ("identifier: value") */
2728 designator = allocate_ast_zero(sizeof(designator[0]));
2729 designator->source_position = token.source_position;
2730 designator->symbol = token.v.symbol;
2735 /* reset path to toplevel, evaluate designator from there */
2736 ascend_to(path, top_path_level);
2737 if (!walk_designator(path, designator, false)) {
2738 /* can't continue after designation error */
2742 initializer_t *designator_initializer
2743 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2744 designator_initializer->designator.designator = designator;
2745 ARR_APP1(initializer_t*, initializers, designator_initializer);
2747 orig_type = path->top_type;
2748 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2753 if (token.type == '{') {
2754 if (type != NULL && is_type_scalar(type)) {
2755 sub = parse_scalar_initializer(type, env->must_be_constant);
2759 if (env->entity != NULL) {
2761 "extra brace group at end of initializer for '%Y'",
2762 env->entity->base.symbol);
2764 errorf(HERE, "extra brace group at end of initializer");
2767 descend_into_subtype(path);
2769 add_anchor_token('}');
2770 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2772 rem_anchor_token('}');
2775 ascend_from_subtype(path);
2776 expect('}', end_error);
2778 expect('}', end_error);
2779 goto error_parse_next;
2783 /* must be an expression */
2784 expression_t *expression = parse_assignment_expression();
2785 mark_vars_read(expression, NULL);
2787 if (env->must_be_constant && !is_initializer_constant(expression)) {
2788 errorf(&expression->base.source_position,
2789 "Initialisation expression '%E' is not constant",
2794 /* we are already outside, ... */
2795 type_t *const outer_type_skip = skip_typeref(outer_type);
2796 if (is_type_compound(outer_type_skip) &&
2797 !outer_type_skip->compound.compound->complete) {
2798 goto error_parse_next;
2803 /* handle { "string" } special case */
2804 if ((expression->kind == EXPR_STRING_LITERAL
2805 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2806 && outer_type != NULL) {
2807 sub = initializer_from_expression(outer_type, expression);
2809 if (token.type == ',') {
2812 if (token.type != '}' && warning.other) {
2813 warningf(HERE, "excessive elements in initializer for type '%T'",
2816 /* TODO: eat , ... */
2821 /* descend into subtypes until expression matches type */
2823 orig_type = path->top_type;
2824 type = skip_typeref(orig_type);
2826 sub = initializer_from_expression(orig_type, expression);
2830 if (!is_type_valid(type)) {
2833 if (is_type_scalar(type)) {
2834 errorf(&expression->base.source_position,
2835 "expression '%E' doesn't match expected type '%T'",
2836 expression, orig_type);
2840 descend_into_subtype(path);
2844 /* update largest index of top array */
2845 const type_path_entry_t *first = &path->path[0];
2846 type_t *first_type = first->type;
2847 first_type = skip_typeref(first_type);
2848 if (is_type_array(first_type)) {
2849 size_t index = first->v.index;
2850 if (index > path->max_index)
2851 path->max_index = index;
2855 /* append to initializers list */
2856 ARR_APP1(initializer_t*, initializers, sub);
2859 if (warning.other) {
2860 if (env->entity != NULL) {
2861 warningf(HERE, "excess elements in struct initializer for '%Y'",
2862 env->entity->base.symbol);
2864 warningf(HERE, "excess elements in struct initializer");
2870 if (token.type == '}') {
2873 expect(',', end_error);
2874 if (token.type == '}') {
2879 /* advance to the next declaration if we are not at the end */
2880 advance_current_object(path, top_path_level);
2881 orig_type = path->top_type;
2882 if (orig_type != NULL)
2883 type = skip_typeref(orig_type);
2889 size_t len = ARR_LEN(initializers);
2890 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2891 initializer_t *result = allocate_ast_zero(size);
2892 result->kind = INITIALIZER_LIST;
2893 result->list.len = len;
2894 memcpy(&result->list.initializers, initializers,
2895 len * sizeof(initializers[0]));
2897 DEL_ARR_F(initializers);
2898 ascend_to(path, top_path_level+1);
2903 skip_initializers();
2904 DEL_ARR_F(initializers);
2905 ascend_to(path, top_path_level+1);
2910 * Parses an initializer. Parsers either a compound literal
2911 * (env->declaration == NULL) or an initializer of a declaration.
2913 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2915 type_t *type = skip_typeref(env->type);
2916 size_t max_index = 0xdeadbeaf; // TODO: Resolve this uninitialized variable problem
2917 initializer_t *result;
2919 if (is_type_scalar(type)) {
2920 result = parse_scalar_initializer(type, env->must_be_constant);
2921 } else if (token.type == '{') {
2925 memset(&path, 0, sizeof(path));
2926 path.top_type = env->type;
2927 path.path = NEW_ARR_F(type_path_entry_t, 0);
2929 descend_into_subtype(&path);
2931 add_anchor_token('}');
2932 result = parse_sub_initializer(&path, env->type, 1, env);
2933 rem_anchor_token('}');
2935 max_index = path.max_index;
2936 DEL_ARR_F(path.path);
2938 expect('}', end_error);
2940 /* parse_scalar_initializer() also works in this case: we simply
2941 * have an expression without {} around it */
2942 result = parse_scalar_initializer(type, env->must_be_constant);
2945 /* § 6.7.8 (22) array initializers for arrays with unknown size determine
2946 * the array type size */
2947 if (is_type_array(type) && type->array.size_expression == NULL
2948 && result != NULL) {
2950 switch (result->kind) {
2951 case INITIALIZER_LIST:
2952 assert(max_index != 0xdeadbeaf);
2953 size = max_index + 1;
2956 case INITIALIZER_STRING:
2957 size = result->string.string.size;
2960 case INITIALIZER_WIDE_STRING:
2961 size = result->wide_string.string.size;
2964 case INITIALIZER_DESIGNATOR:
2965 case INITIALIZER_VALUE:
2966 /* can happen for parse errors */
2971 internal_errorf(HERE, "invalid initializer type");
2974 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2975 cnst->base.type = type_size_t;
2976 cnst->conste.v.int_value = size;
2978 type_t *new_type = duplicate_type(type);
2980 new_type->array.size_expression = cnst;
2981 new_type->array.size_constant = true;
2982 new_type->array.has_implicit_size = true;
2983 new_type->array.size = size;
2984 env->type = new_type;
2992 static void append_entity(scope_t *scope, entity_t *entity)
2994 if (scope->last_entity != NULL) {
2995 scope->last_entity->base.next = entity;
2997 scope->entities = entity;
2999 scope->last_entity = entity;
3003 static compound_t *parse_compound_type_specifier(bool is_struct)
3005 gnu_attribute_t *attributes = NULL;
3006 decl_modifiers_t modifiers = 0;
3013 symbol_t *symbol = NULL;
3014 compound_t *compound = NULL;
3016 if (token.type == T___attribute__) {
3017 modifiers |= parse_attributes(&attributes);
3020 if (token.type == T_IDENTIFIER) {
3021 symbol = token.v.symbol;
3024 namespace_tag_t const namespc =
3025 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
3026 entity_t *entity = get_entity(symbol, namespc);
3027 if (entity != NULL) {
3028 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
3029 compound = &entity->compound;
3030 if (compound->base.parent_scope != current_scope &&
3031 (token.type == '{' || token.type == ';')) {
3032 /* we're in an inner scope and have a definition. Override
3033 existing definition in outer scope */
3035 } else if (compound->complete && token.type == '{') {
3036 assert(symbol != NULL);
3037 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
3038 is_struct ? "struct" : "union", symbol,
3039 &compound->base.source_position);
3040 /* clear members in the hope to avoid further errors */
3041 compound->members.entities = NULL;
3044 } else if (token.type != '{') {
3046 parse_error_expected("while parsing struct type specifier",
3047 T_IDENTIFIER, '{', NULL);
3049 parse_error_expected("while parsing union type specifier",
3050 T_IDENTIFIER, '{', NULL);
3056 if (compound == NULL) {
3057 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
3058 entity_t *entity = allocate_entity_zero(kind);
3059 compound = &entity->compound;
3061 compound->base.namespc =
3062 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
3063 compound->base.source_position = token.source_position;
3064 compound->base.symbol = symbol;
3065 compound->base.parent_scope = current_scope;
3066 if (symbol != NULL) {
3067 environment_push(entity);
3069 append_entity(current_scope, entity);
3072 if (token.type == '{') {
3073 parse_compound_type_entries(compound);
3074 modifiers |= parse_attributes(&attributes);
3076 if (symbol == NULL) {
3077 assert(anonymous_entity == NULL);
3078 anonymous_entity = (entity_t*)compound;
3082 compound->modifiers |= modifiers;
3086 static void parse_enum_entries(type_t *const enum_type)
3090 if (token.type == '}') {
3091 errorf(HERE, "empty enum not allowed");
3096 add_anchor_token('}');
3098 if (token.type != T_IDENTIFIER) {
3099 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3101 rem_anchor_token('}');
3105 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3106 entity->enum_value.enum_type = enum_type;
3107 entity->base.symbol = token.v.symbol;
3108 entity->base.source_position = token.source_position;
3111 if (token.type == '=') {
3113 expression_t *value = parse_constant_expression();
3115 value = create_implicit_cast(value, enum_type);
3116 entity->enum_value.value = value;
3121 record_entity(entity, false);
3123 if (token.type != ',')
3126 } while (token.type != '}');
3127 rem_anchor_token('}');
3129 expect('}', end_error);
3135 static type_t *parse_enum_specifier(void)
3137 gnu_attribute_t *attributes = NULL;
3142 if (token.type == T_IDENTIFIER) {
3143 symbol = token.v.symbol;
3146 entity = get_entity(symbol, NAMESPACE_ENUM);
3147 assert(entity == NULL || entity->kind == ENTITY_ENUM);
3148 } else if (token.type != '{') {
3149 parse_error_expected("while parsing enum type specifier",
3150 T_IDENTIFIER, '{', NULL);
3157 if (entity == NULL) {
3158 entity = allocate_entity_zero(ENTITY_ENUM);
3159 entity->base.namespc = NAMESPACE_ENUM;
3160 entity->base.source_position = token.source_position;
3161 entity->base.symbol = symbol;
3162 entity->base.parent_scope = current_scope;
3165 type_t *const type = allocate_type_zero(TYPE_ENUM);
3166 type->enumt.enume = &entity->enume;
3168 if (token.type == '{') {
3169 if (entity->enume.complete) {
3170 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
3171 symbol, &entity->base.source_position);
3173 if (symbol != NULL) {
3174 environment_push(entity);
3176 append_entity(current_scope, entity);
3177 entity->enume.complete = true;
3179 parse_enum_entries(type);
3180 parse_attributes(&attributes);
3182 if (symbol == NULL) {
3183 assert(anonymous_entity == NULL);
3184 anonymous_entity = entity;
3186 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
3187 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
3195 * if a symbol is a typedef to another type, return true
3197 static bool is_typedef_symbol(symbol_t *symbol)
3199 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3200 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3203 static type_t *parse_typeof(void)
3209 expect('(', end_error);
3210 add_anchor_token(')');
3212 expression_t *expression = NULL;
3214 bool old_type_prop = in_type_prop;
3215 bool old_gcc_extension = in_gcc_extension;
3216 in_type_prop = true;
3218 while (token.type == T___extension__) {
3219 /* This can be a prefix to a typename or an expression. */
3221 in_gcc_extension = true;
3223 switch (token.type) {
3225 if (is_typedef_symbol(token.v.symbol)) {
3226 type = parse_typename();
3228 expression = parse_expression();
3229 type = expression->base.type;
3234 type = parse_typename();
3238 expression = parse_expression();
3239 type = expression->base.type;
3242 in_type_prop = old_type_prop;
3243 in_gcc_extension = old_gcc_extension;
3245 rem_anchor_token(')');
3246 expect(')', end_error);
3248 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3249 typeof_type->typeoft.expression = expression;
3250 typeof_type->typeoft.typeof_type = type;
3257 typedef enum specifiers_t {
3258 SPECIFIER_SIGNED = 1 << 0,
3259 SPECIFIER_UNSIGNED = 1 << 1,
3260 SPECIFIER_LONG = 1 << 2,
3261 SPECIFIER_INT = 1 << 3,
3262 SPECIFIER_DOUBLE = 1 << 4,
3263 SPECIFIER_CHAR = 1 << 5,
3264 SPECIFIER_WCHAR_T = 1 << 6,
3265 SPECIFIER_SHORT = 1 << 7,
3266 SPECIFIER_LONG_LONG = 1 << 8,
3267 SPECIFIER_FLOAT = 1 << 9,
3268 SPECIFIER_BOOL = 1 << 10,
3269 SPECIFIER_VOID = 1 << 11,
3270 SPECIFIER_INT8 = 1 << 12,
3271 SPECIFIER_INT16 = 1 << 13,
3272 SPECIFIER_INT32 = 1 << 14,
3273 SPECIFIER_INT64 = 1 << 15,
3274 SPECIFIER_INT128 = 1 << 16,
3275 SPECIFIER_COMPLEX = 1 << 17,
3276 SPECIFIER_IMAGINARY = 1 << 18,
3279 static type_t *create_builtin_type(symbol_t *const symbol,
3280 type_t *const real_type)
3282 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3283 type->builtin.symbol = symbol;
3284 type->builtin.real_type = real_type;
3286 type_t *result = typehash_insert(type);
3287 if (type != result) {
3294 static type_t *get_typedef_type(symbol_t *symbol)
3296 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3297 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3300 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3301 type->typedeft.typedefe = &entity->typedefe;
3307 * check for the allowed MS alignment values.
3309 static bool check_alignment_value(long long intvalue)
3311 if (intvalue < 1 || intvalue > 8192) {
3312 errorf(HERE, "illegal alignment value");
3315 unsigned v = (unsigned)intvalue;
3316 for (unsigned i = 1; i <= 8192; i += i) {
3320 errorf(HERE, "alignment must be power of two");
3324 #define DET_MOD(name, tag) do { \
3325 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3326 *modifiers |= tag; \
3329 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3331 decl_modifiers_t *modifiers = &specifiers->modifiers;
3334 if (token.type == T_restrict) {
3336 DET_MOD(restrict, DM_RESTRICT);
3338 } else if (token.type != T_IDENTIFIER)
3340 symbol_t *symbol = token.v.symbol;
3341 if (symbol == sym_align) {
3343 expect('(', end_error);
3344 if (token.type != T_INTEGER)
3346 if (check_alignment_value(token.v.intvalue)) {
3347 if (specifiers->alignment != 0 && warning.other)
3348 warningf(HERE, "align used more than once");
3349 specifiers->alignment = (unsigned char)token.v.intvalue;
3352 expect(')', end_error);
3353 } else if (symbol == sym_allocate) {
3355 expect('(', end_error);
3356 if (token.type != T_IDENTIFIER)
3358 (void)token.v.symbol;
3359 expect(')', end_error);
3360 } else if (symbol == sym_dllimport) {
3362 DET_MOD(dllimport, DM_DLLIMPORT);
3363 } else if (symbol == sym_dllexport) {
3365 DET_MOD(dllexport, DM_DLLEXPORT);
3366 } else if (symbol == sym_thread) {
3368 DET_MOD(thread, DM_THREAD);
3369 } else if (symbol == sym_naked) {
3371 DET_MOD(naked, DM_NAKED);
3372 } else if (symbol == sym_noinline) {
3374 DET_MOD(noinline, DM_NOINLINE);
3375 } else if (symbol == sym_returns_twice) {
3377 DET_MOD(returns_twice, DM_RETURNS_TWICE);
3378 } else if (symbol == sym_noreturn) {
3380 DET_MOD(noreturn, DM_NORETURN);
3381 } else if (symbol == sym_nothrow) {
3383 DET_MOD(nothrow, DM_NOTHROW);
3384 } else if (symbol == sym_novtable) {
3386 DET_MOD(novtable, DM_NOVTABLE);
3387 } else if (symbol == sym_property) {
3389 expect('(', end_error);
3391 bool is_get = false;
3392 if (token.type != T_IDENTIFIER)
3394 if (token.v.symbol == sym_get) {
3396 } else if (token.v.symbol == sym_put) {
3398 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3402 expect('=', end_error);
3403 if (token.type != T_IDENTIFIER)
3406 if (specifiers->get_property_sym != NULL) {
3407 errorf(HERE, "get property name already specified");
3409 specifiers->get_property_sym = token.v.symbol;
3412 if (specifiers->put_property_sym != NULL) {
3413 errorf(HERE, "put property name already specified");
3415 specifiers->put_property_sym = token.v.symbol;
3419 if (token.type == ',') {
3425 expect(')', end_error);
3426 } else if (symbol == sym_selectany) {
3428 DET_MOD(selectany, DM_SELECTANY);
3429 } else if (symbol == sym_uuid) {
3431 expect('(', end_error);
3432 if (token.type != T_STRING_LITERAL)
3435 expect(')', end_error);
3436 } else if (symbol == sym_deprecated) {
3438 if (specifiers->deprecated != 0 && warning.other)
3439 warningf(HERE, "deprecated used more than once");
3440 specifiers->deprecated = true;
3441 if (token.type == '(') {
3443 if (token.type == T_STRING_LITERAL) {
3444 specifiers->deprecated_string = token.v.string.begin;
3447 errorf(HERE, "string literal expected");
3449 expect(')', end_error);
3451 } else if (symbol == sym_noalias) {
3453 DET_MOD(noalias, DM_NOALIAS);
3456 warningf(HERE, "Unknown modifier '%Y' ignored", token.v.symbol);
3458 if (token.type == '(')
3462 if (token.type == ',')
3469 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3471 entity_t *entity = allocate_entity_zero(kind);
3472 entity->base.source_position = *HERE;
3473 entity->base.symbol = symbol;
3474 if (is_declaration(entity)) {
3475 entity->declaration.type = type_error_type;
3476 entity->declaration.implicit = true;
3477 } else if (kind == ENTITY_TYPEDEF) {
3478 entity->typedefe.type = type_error_type;
3479 entity->typedefe.builtin = true;
3481 if (kind != ENTITY_COMPOUND_MEMBER)
3482 record_entity(entity, false);
3486 static void parse_microsoft_based(based_spec_t *based_spec)
3488 if (token.type != T_IDENTIFIER) {
3489 parse_error_expected("while parsing __based", T_IDENTIFIER, NULL);
3492 symbol_t *symbol = token.v.symbol;
3493 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3495 if (entity == NULL || entity->base.kind != ENTITY_VARIABLE) {
3496 errorf(HERE, "'%Y' is not a variable name.", symbol);
3497 entity = create_error_entity(symbol, ENTITY_VARIABLE);
3499 variable_t *variable = &entity->variable;
3501 if (based_spec->base_variable != NULL) {
3502 errorf(HERE, "__based type qualifier specified more than once");
3504 based_spec->source_position = token.source_position;
3505 based_spec->base_variable = variable;
3507 type_t *const type = variable->base.type;
3509 if (is_type_valid(type)) {
3510 if (! is_type_pointer(skip_typeref(type))) {
3511 errorf(HERE, "variable in __based modifier must have pointer type instead of '%T'", type);
3513 if (variable->base.base.parent_scope != file_scope) {
3514 errorf(HERE, "a nonstatic local variable may not be used in a __based specification");
3522 * Finish the construction of a struct type by calculating
3523 * its size, offsets, alignment.
3525 static void finish_struct_type(compound_type_t *type)
3527 assert(type->compound != NULL);
3529 compound_t *compound = type->compound;
3530 if (!compound->complete)
3535 il_alignment_t alignment = 1;
3536 bool need_pad = false;
3538 entity_t *entry = compound->members.entities;
3539 for (; entry != NULL; entry = entry->base.next) {
3540 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3543 type_t *m_type = skip_typeref(entry->declaration.type);
3544 if (! is_type_valid(m_type)) {
3545 /* simply ignore errors here */
3548 il_alignment_t m_alignment = m_type->base.alignment;
3549 if (m_alignment > alignment)
3550 alignment = m_alignment;
3552 offset = (size + m_alignment - 1) & -m_alignment;
3556 entry->compound_member.offset = offset;
3557 size = offset + m_type->base.size;
3559 if (type->base.alignment != 0) {
3560 alignment = type->base.alignment;
3563 offset = (size + alignment - 1) & -alignment;
3568 if (warning.padded) {
3569 warningf(&compound->base.source_position, "'%T' needs padding", type);
3572 if (compound->modifiers & DM_PACKED && warning.packed) {
3573 warningf(&compound->base.source_position,
3574 "superfluous packed attribute on '%T'", type);
3578 type->base.size = offset;
3579 type->base.alignment = alignment;
3583 * Finish the construction of an union type by calculating
3584 * its size and alignment.
3586 static void finish_union_type(compound_type_t *type)
3588 assert(type->compound != NULL);
3590 compound_t *compound = type->compound;
3591 if (! compound->complete)
3595 il_alignment_t alignment = 1;
3597 entity_t *entry = compound->members.entities;
3598 for (; entry != NULL; entry = entry->base.next) {
3599 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3602 type_t *m_type = skip_typeref(entry->declaration.type);
3603 if (! is_type_valid(m_type))
3606 entry->compound_member.offset = 0;
3607 if (m_type->base.size > size)
3608 size = m_type->base.size;
3609 if (m_type->base.alignment > alignment)
3610 alignment = m_type->base.alignment;
3612 if (type->base.alignment != 0) {
3613 alignment = type->base.alignment;
3615 size = (size + alignment - 1) & -alignment;
3616 type->base.size = size;
3617 type->base.alignment = alignment;
3620 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3622 type_t *type = NULL;
3623 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3624 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3625 unsigned type_specifiers = 0;
3626 bool newtype = false;
3627 bool saw_error = false;
3628 bool old_gcc_extension = in_gcc_extension;
3630 specifiers->source_position = token.source_position;
3633 specifiers->modifiers
3634 |= parse_attributes(&specifiers->gnu_attributes);
3635 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3636 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3638 switch (token.type) {
3640 #define MATCH_STORAGE_CLASS(token, class) \
3642 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3643 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3645 specifiers->storage_class = class; \
3646 if (specifiers->thread_local) \
3647 goto check_thread_storage_class; \
3651 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3652 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3653 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3654 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3655 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3659 expect('(', end_error);
3660 add_anchor_token(')');
3661 parse_microsoft_extended_decl_modifier(specifiers);
3662 rem_anchor_token(')');
3663 expect(')', end_error);
3667 if (specifiers->thread_local) {
3668 errorf(HERE, "duplicate '__thread'");
3670 specifiers->thread_local = true;
3671 check_thread_storage_class:
3672 switch (specifiers->storage_class) {
3673 case STORAGE_CLASS_EXTERN:
3674 case STORAGE_CLASS_NONE:
3675 case STORAGE_CLASS_STATIC:
3679 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
3680 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
3681 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
3682 wrong_thread_stoarge_class:
3683 errorf(HERE, "'__thread' used with '%s'", wrong);
3690 /* type qualifiers */
3691 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3693 qualifiers |= qualifier; \
3697 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3698 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3699 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3700 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3701 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3702 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3703 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3704 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3706 case T___extension__:
3708 in_gcc_extension = true;
3711 /* type specifiers */
3712 #define MATCH_SPECIFIER(token, specifier, name) \
3714 if (type_specifiers & specifier) { \
3715 errorf(HERE, "multiple " name " type specifiers given"); \
3717 type_specifiers |= specifier; \
3722 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3723 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3724 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3725 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3726 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3727 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3728 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3729 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3730 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3731 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3732 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3733 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3734 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3735 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3736 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3737 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3738 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3739 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
3741 case T__forceinline:
3742 /* only in microsoft mode */
3743 specifiers->modifiers |= DM_FORCEINLINE;
3748 specifiers->is_inline = true;
3752 if (type_specifiers & SPECIFIER_LONG_LONG) {
3753 errorf(HERE, "multiple type specifiers given");
3754 } else if (type_specifiers & SPECIFIER_LONG) {
3755 type_specifiers |= SPECIFIER_LONG_LONG;
3757 type_specifiers |= SPECIFIER_LONG;
3763 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3765 type->compound.compound = parse_compound_type_specifier(true);
3766 finish_struct_type(&type->compound);
3770 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3771 type->compound.compound = parse_compound_type_specifier(false);
3772 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3773 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3774 finish_union_type(&type->compound);
3778 type = parse_enum_specifier();
3781 type = parse_typeof();
3783 case T___builtin_va_list:
3784 type = duplicate_type(type_valist);
3788 case T_IDENTIFIER: {
3789 /* only parse identifier if we haven't found a type yet */
3790 if (type != NULL || type_specifiers != 0) {
3791 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3792 * declaration, so it doesn't generate errors about expecting '(' or
3794 switch (look_ahead(1)->type) {
3801 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3805 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3810 goto finish_specifiers;
3814 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3815 if (typedef_type == NULL) {
3816 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3817 * declaration, so it doesn't generate 'implicit int' followed by more
3818 * errors later on. */
3819 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3825 errorf(HERE, "%K does not name a type", &token);
3828 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3830 type = allocate_type_zero(TYPE_TYPEDEF);
3831 type->typedeft.typedefe = &entity->typedefe;
3835 if (la1_type == '&' || la1_type == '*')
3836 goto finish_specifiers;
3841 goto finish_specifiers;
3846 type = typedef_type;
3850 /* function specifier */
3852 goto finish_specifiers;
3857 in_gcc_extension = old_gcc_extension;
3859 if (type == NULL || (saw_error && type_specifiers != 0)) {
3860 atomic_type_kind_t atomic_type;
3862 /* match valid basic types */
3863 switch (type_specifiers) {
3864 case SPECIFIER_VOID:
3865 atomic_type = ATOMIC_TYPE_VOID;
3867 case SPECIFIER_WCHAR_T:
3868 atomic_type = ATOMIC_TYPE_WCHAR_T;
3870 case SPECIFIER_CHAR:
3871 atomic_type = ATOMIC_TYPE_CHAR;
3873 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3874 atomic_type = ATOMIC_TYPE_SCHAR;
3876 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3877 atomic_type = ATOMIC_TYPE_UCHAR;
3879 case SPECIFIER_SHORT:
3880 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3881 case SPECIFIER_SHORT | SPECIFIER_INT:
3882 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3883 atomic_type = ATOMIC_TYPE_SHORT;
3885 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3886 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3887 atomic_type = ATOMIC_TYPE_USHORT;
3890 case SPECIFIER_SIGNED:
3891 case SPECIFIER_SIGNED | SPECIFIER_INT:
3892 atomic_type = ATOMIC_TYPE_INT;
3894 case SPECIFIER_UNSIGNED:
3895 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3896 atomic_type = ATOMIC_TYPE_UINT;
3898 case SPECIFIER_LONG:
3899 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3900 case SPECIFIER_LONG | SPECIFIER_INT:
3901 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3902 atomic_type = ATOMIC_TYPE_LONG;
3904 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3905 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3906 atomic_type = ATOMIC_TYPE_ULONG;
3909 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3910 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3911 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3912 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3914 atomic_type = ATOMIC_TYPE_LONGLONG;
3915 goto warn_about_long_long;
3917 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3918 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3920 atomic_type = ATOMIC_TYPE_ULONGLONG;
3921 warn_about_long_long:
3922 if (warning.long_long) {
3923 warningf(&specifiers->source_position,
3924 "ISO C90 does not support 'long long'");
3928 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3929 atomic_type = unsigned_int8_type_kind;
3932 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3933 atomic_type = unsigned_int16_type_kind;
3936 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3937 atomic_type = unsigned_int32_type_kind;
3940 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3941 atomic_type = unsigned_int64_type_kind;
3944 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3945 atomic_type = unsigned_int128_type_kind;
3948 case SPECIFIER_INT8:
3949 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3950 atomic_type = int8_type_kind;
3953 case SPECIFIER_INT16:
3954 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3955 atomic_type = int16_type_kind;
3958 case SPECIFIER_INT32:
3959 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3960 atomic_type = int32_type_kind;
3963 case SPECIFIER_INT64:
3964 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3965 atomic_type = int64_type_kind;
3968 case SPECIFIER_INT128:
3969 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3970 atomic_type = int128_type_kind;
3973 case SPECIFIER_FLOAT:
3974 atomic_type = ATOMIC_TYPE_FLOAT;
3976 case SPECIFIER_DOUBLE:
3977 atomic_type = ATOMIC_TYPE_DOUBLE;
3979 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3980 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3982 case SPECIFIER_BOOL:
3983 atomic_type = ATOMIC_TYPE_BOOL;
3985 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3986 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3987 atomic_type = ATOMIC_TYPE_FLOAT;
3989 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3990 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3991 atomic_type = ATOMIC_TYPE_DOUBLE;
3993 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3994 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3995 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3998 /* invalid specifier combination, give an error message */
3999 if (type_specifiers == 0) {
4003 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
4004 if (!(c_mode & _CXX) && !strict_mode) {
4005 if (warning.implicit_int) {
4006 warningf(HERE, "no type specifiers in declaration, using 'int'");
4008 atomic_type = ATOMIC_TYPE_INT;
4011 errorf(HERE, "no type specifiers given in declaration");
4013 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
4014 (type_specifiers & SPECIFIER_UNSIGNED)) {
4015 errorf(HERE, "signed and unsigned specifiers given");
4016 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
4017 errorf(HERE, "only integer types can be signed or unsigned");
4019 errorf(HERE, "multiple datatypes in declaration");
4024 if (type_specifiers & SPECIFIER_COMPLEX) {
4025 type = allocate_type_zero(TYPE_COMPLEX);
4026 type->complex.akind = atomic_type;
4027 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
4028 type = allocate_type_zero(TYPE_IMAGINARY);
4029 type->imaginary.akind = atomic_type;
4031 type = allocate_type_zero(TYPE_ATOMIC);
4032 type->atomic.akind = atomic_type;
4035 } else if (type_specifiers != 0) {
4036 errorf(HERE, "multiple datatypes in declaration");
4039 /* FIXME: check type qualifiers here */
4041 type->base.qualifiers = qualifiers;
4042 type->base.modifiers = modifiers;
4044 type_t *result = typehash_insert(type);
4045 if (newtype && result != type) {
4049 specifiers->type = result;
4053 specifiers->type = type_error_type;
4057 static type_qualifiers_t parse_type_qualifiers(void)
4059 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
4062 switch (token.type) {
4063 /* type qualifiers */
4064 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
4065 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
4066 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
4067 /* microsoft extended type modifiers */
4068 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
4069 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
4070 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
4071 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
4072 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
4081 * Parses an K&R identifier list
4083 static void parse_identifier_list(scope_t *scope)
4086 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
4087 entity->base.source_position = token.source_position;
4088 entity->base.namespc = NAMESPACE_NORMAL;
4089 entity->base.symbol = token.v.symbol;
4090 /* a K&R parameter has no type, yet */
4094 append_entity(scope, entity);
4096 if (token.type != ',') {
4100 } while (token.type == T_IDENTIFIER);
4103 static entity_t *parse_parameter(void)
4105 declaration_specifiers_t specifiers;
4106 memset(&specifiers, 0, sizeof(specifiers));
4108 parse_declaration_specifiers(&specifiers);
4110 entity_t *entity = parse_declarator(&specifiers,
4111 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
4112 anonymous_entity = NULL;
4116 static void semantic_parameter_incomplete(const entity_t *entity)
4118 assert(entity->kind == ENTITY_PARAMETER);
4120 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
4121 * list in a function declarator that is part of a
4122 * definition of that function shall not have
4123 * incomplete type. */
4124 type_t *type = skip_typeref(entity->declaration.type);
4125 if (is_type_incomplete(type)) {
4126 errorf(&entity->base.source_position,
4127 "parameter '%Y' has incomplete type '%T'", entity->base.symbol,
4128 entity->declaration.type);
4133 * Parses function type parameters (and optionally creates variable_t entities
4134 * for them in a scope)
4136 static void parse_parameters(function_type_t *type, scope_t *scope)
4139 add_anchor_token(')');
4140 int saved_comma_state = save_and_reset_anchor_state(',');
4142 if (token.type == T_IDENTIFIER &&
4143 !is_typedef_symbol(token.v.symbol)) {
4144 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4145 if (la1_type == ',' || la1_type == ')') {
4146 type->kr_style_parameters = true;
4147 type->unspecified_parameters = true;
4148 parse_identifier_list(scope);
4149 goto parameters_finished;
4153 if (token.type == ')') {
4154 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4155 if (!(c_mode & _CXX))
4156 type->unspecified_parameters = true;
4157 goto parameters_finished;
4160 function_parameter_t *parameter;
4161 function_parameter_t *last_parameter = NULL;
4164 switch (token.type) {
4167 type->variadic = true;
4168 goto parameters_finished;
4171 case T___extension__:
4174 entity_t *entity = parse_parameter();
4175 if (entity->kind == ENTITY_TYPEDEF) {
4176 errorf(&entity->base.source_position,
4177 "typedef not allowed as function parameter");
4180 assert(is_declaration(entity));
4182 /* func(void) is not a parameter */
4183 if (last_parameter == NULL
4184 && token.type == ')'
4185 && entity->base.symbol == NULL
4186 && skip_typeref(entity->declaration.type) == type_void) {
4187 goto parameters_finished;
4189 semantic_parameter_incomplete(entity);
4191 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4192 memset(parameter, 0, sizeof(parameter[0]));
4193 parameter->type = entity->declaration.type;
4195 if (scope != NULL) {
4196 append_entity(scope, entity);
4199 if (last_parameter != NULL) {
4200 last_parameter->next = parameter;
4202 type->parameters = parameter;
4204 last_parameter = parameter;
4209 goto parameters_finished;
4211 if (token.type != ',') {
4212 goto parameters_finished;
4218 parameters_finished:
4219 rem_anchor_token(')');
4220 expect(')', end_error);
4223 restore_anchor_state(',', saved_comma_state);
4226 typedef enum construct_type_kind_t {
4229 CONSTRUCT_REFERENCE,
4232 } construct_type_kind_t;
4234 typedef struct construct_type_t construct_type_t;
4235 struct construct_type_t {
4236 construct_type_kind_t kind;
4237 construct_type_t *next;
4240 typedef struct parsed_pointer_t parsed_pointer_t;
4241 struct parsed_pointer_t {
4242 construct_type_t construct_type;
4243 type_qualifiers_t type_qualifiers;
4244 variable_t *base_variable; /**< MS __based extension. */
4247 typedef struct parsed_reference_t parsed_reference_t;
4248 struct parsed_reference_t {
4249 construct_type_t construct_type;
4252 typedef struct construct_function_type_t construct_function_type_t;
4253 struct construct_function_type_t {
4254 construct_type_t construct_type;
4255 type_t *function_type;
4258 typedef struct parsed_array_t parsed_array_t;
4259 struct parsed_array_t {
4260 construct_type_t construct_type;
4261 type_qualifiers_t type_qualifiers;
4267 typedef struct construct_base_type_t construct_base_type_t;
4268 struct construct_base_type_t {
4269 construct_type_t construct_type;
4273 static construct_type_t *parse_pointer_declarator(variable_t *base_variable)
4277 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4278 memset(pointer, 0, sizeof(pointer[0]));
4279 pointer->construct_type.kind = CONSTRUCT_POINTER;
4280 pointer->type_qualifiers = parse_type_qualifiers();
4281 pointer->base_variable = base_variable;
4283 return &pointer->construct_type;
4286 static construct_type_t *parse_reference_declarator(void)
4290 parsed_reference_t *reference = obstack_alloc(&temp_obst, sizeof(reference[0]));
4291 memset(reference, 0, sizeof(reference[0]));
4292 reference->construct_type.kind = CONSTRUCT_REFERENCE;
4294 return (construct_type_t*)reference;
4297 static construct_type_t *parse_array_declarator(void)
4300 add_anchor_token(']');
4302 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4303 memset(array, 0, sizeof(array[0]));
4304 array->construct_type.kind = CONSTRUCT_ARRAY;
4306 if (token.type == T_static) {
4307 array->is_static = true;
4311 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4312 if (type_qualifiers != 0) {
4313 if (token.type == T_static) {
4314 array->is_static = true;
4318 array->type_qualifiers = type_qualifiers;
4320 if (token.type == '*' && look_ahead(1)->type == ']') {
4321 array->is_variable = true;
4323 } else if (token.type != ']') {
4324 expression_t *const size = parse_assignment_expression();
4326 mark_vars_read(size, NULL);
4329 rem_anchor_token(']');
4330 expect(']', end_error);
4333 return &array->construct_type;
4336 static construct_type_t *parse_function_declarator(scope_t *scope,
4337 decl_modifiers_t modifiers)
4339 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4340 function_type_t *ftype = &type->function;
4342 ftype->linkage = current_linkage;
4344 switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
4345 case DM_NONE: break;
4346 case DM_CDECL: ftype->calling_convention = CC_CDECL; break;
4347 case DM_STDCALL: ftype->calling_convention = CC_STDCALL; break;
4348 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
4349 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
4352 errorf(HERE, "multiple calling conventions in declaration");
4356 parse_parameters(ftype, scope);
4358 construct_function_type_t *construct_function_type =
4359 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4360 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4361 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4362 construct_function_type->function_type = type;
4364 return &construct_function_type->construct_type;
4367 typedef struct parse_declarator_env_t {
4368 decl_modifiers_t modifiers;
4370 source_position_t source_position;
4372 } parse_declarator_env_t;
4374 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4375 bool may_be_abstract)
4377 /* construct a single linked list of construct_type_t's which describe
4378 * how to construct the final declarator type */
4379 construct_type_t *first = NULL;
4380 construct_type_t *last = NULL;
4381 gnu_attribute_t *attributes = NULL;
4383 decl_modifiers_t modifiers = parse_attributes(&attributes);
4385 /* MS __based extension */
4386 based_spec_t base_spec;
4387 base_spec.base_variable = NULL;
4390 construct_type_t *type;
4391 switch (token.type) {
4393 if (!(c_mode & _CXX))
4394 errorf(HERE, "references are only available for C++");
4395 if (base_spec.base_variable != NULL && warning.other) {
4396 warningf(&base_spec.source_position,
4397 "__based does not precede a pointer operator, ignored");
4399 type = parse_reference_declarator();
4401 base_spec.base_variable = NULL;
4405 type = parse_pointer_declarator(base_spec.base_variable);
4407 base_spec.base_variable = NULL;
4412 expect('(', end_error);
4413 add_anchor_token(')');
4414 parse_microsoft_based(&base_spec);
4415 rem_anchor_token(')');
4416 expect(')', end_error);
4420 goto ptr_operator_end;
4431 /* TODO: find out if this is correct */
4432 modifiers |= parse_attributes(&attributes);
4435 if (base_spec.base_variable != NULL && warning.other) {
4436 warningf(&base_spec.source_position,
4437 "__based does not precede a pointer operator, ignored");
4441 modifiers |= env->modifiers;
4442 env->modifiers = modifiers;
4445 construct_type_t *inner_types = NULL;
4447 switch (token.type) {
4450 errorf(HERE, "no identifier expected in typename");
4452 env->symbol = token.v.symbol;
4453 env->source_position = token.source_position;
4458 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
4459 * interpreted as ``function with no parameter specification'', rather
4460 * than redundant parentheses around the omitted identifier. */
4461 if (look_ahead(1)->type != ')') {
4463 add_anchor_token(')');
4464 inner_types = parse_inner_declarator(env, may_be_abstract);
4465 if (inner_types != NULL) {
4466 /* All later declarators only modify the return type */
4469 rem_anchor_token(')');
4470 expect(')', end_error);
4474 if (may_be_abstract)
4476 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4481 construct_type_t *p = last;
4484 construct_type_t *type;
4485 switch (token.type) {
4487 scope_t *scope = NULL;
4489 scope = &env->parameters;
4491 type = parse_function_declarator(scope, modifiers);
4495 type = parse_array_declarator();
4498 goto declarator_finished;
4501 /* insert in the middle of the list (behind p) */
4503 type->next = p->next;
4514 declarator_finished:
4515 /* append inner_types at the end of the list, we don't to set last anymore
4516 * as it's not needed anymore */
4518 assert(first == NULL);
4519 first = inner_types;
4521 last->next = inner_types;
4529 static void parse_declaration_attributes(entity_t *entity)
4531 gnu_attribute_t *attributes = NULL;
4532 decl_modifiers_t modifiers = parse_attributes(&attributes);
4538 if (entity->kind == ENTITY_TYPEDEF) {
4539 modifiers |= entity->typedefe.modifiers;
4540 type = entity->typedefe.type;
4542 assert(is_declaration(entity));
4543 modifiers |= entity->declaration.modifiers;
4544 type = entity->declaration.type;
4549 /* handle these strange/stupid mode attributes */
4550 gnu_attribute_t *attribute = attributes;
4551 for ( ; attribute != NULL; attribute = attribute->next) {
4552 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4555 atomic_type_kind_t akind = attribute->u.akind;
4556 if (!is_type_signed(type)) {
4558 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4559 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4560 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4561 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4563 panic("invalid akind in mode attribute");
4567 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_SCHAR; break;
4568 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_SHORT; break;
4569 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_INT; break;
4570 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_LONGLONG; break;
4572 panic("invalid akind in mode attribute");
4576 type = make_atomic_type(akind, type->base.qualifiers);
4579 type_modifiers_t type_modifiers = type->base.modifiers;
4580 if (modifiers & DM_TRANSPARENT_UNION)
4581 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4583 if (type->base.modifiers != type_modifiers) {
4584 type_t *copy = duplicate_type(type);
4585 copy->base.modifiers = type_modifiers;
4587 type = typehash_insert(copy);
4589 obstack_free(type_obst, copy);
4593 if (entity->kind == ENTITY_TYPEDEF) {
4594 entity->typedefe.type = type;
4595 entity->typedefe.modifiers = modifiers;
4597 entity->declaration.type = type;
4598 entity->declaration.modifiers = modifiers;
4602 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
4604 construct_type_t *iter = construct_list;
4605 for (; iter != NULL; iter = iter->next) {
4606 switch (iter->kind) {
4607 case CONSTRUCT_INVALID:
4608 internal_errorf(HERE, "invalid type construction found");
4609 case CONSTRUCT_FUNCTION: {
4610 construct_function_type_t *construct_function_type
4611 = (construct_function_type_t*) iter;
4613 type_t *function_type = construct_function_type->function_type;
4615 function_type->function.return_type = type;
4617 type_t *skipped_return_type = skip_typeref(type);
4619 if (is_type_function(skipped_return_type)) {
4620 errorf(HERE, "function returning function is not allowed");
4621 } else if (is_type_array(skipped_return_type)) {
4622 errorf(HERE, "function returning array is not allowed");
4624 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4626 "type qualifiers in return type of function type are meaningless");
4630 type = function_type;
4634 case CONSTRUCT_POINTER: {
4635 if (is_type_reference(skip_typeref(type)))
4636 errorf(HERE, "cannot declare a pointer to reference");
4638 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4639 type = make_based_pointer_type(type, parsed_pointer->type_qualifiers, parsed_pointer->base_variable);
4643 case CONSTRUCT_REFERENCE:
4644 if (is_type_reference(skip_typeref(type)))
4645 errorf(HERE, "cannot declare a reference to reference");
4647 type = make_reference_type(type);
4650 case CONSTRUCT_ARRAY: {
4651 if (is_type_reference(skip_typeref(type)))
4652 errorf(HERE, "cannot declare an array of references");
4654 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4655 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4657 expression_t *size_expression = parsed_array->size;
4658 if (size_expression != NULL) {
4660 = create_implicit_cast(size_expression, type_size_t);
4663 array_type->base.qualifiers = parsed_array->type_qualifiers;
4664 array_type->array.element_type = type;
4665 array_type->array.is_static = parsed_array->is_static;
4666 array_type->array.is_variable = parsed_array->is_variable;
4667 array_type->array.size_expression = size_expression;
4669 if (size_expression != NULL) {
4670 if (is_constant_expression(size_expression)) {
4671 array_type->array.size_constant = true;
4672 array_type->array.size
4673 = fold_constant(size_expression);
4675 array_type->array.is_vla = true;
4679 type_t *skipped_type = skip_typeref(type);
4681 if (is_type_incomplete(skipped_type)) {
4682 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4683 } else if (is_type_function(skipped_type)) {
4684 errorf(HERE, "array of functions is not allowed");
4691 type_t *hashed_type = typehash_insert(type);
4692 if (hashed_type != type) {
4693 /* the function type was constructed earlier freeing it here will
4694 * destroy other types... */
4695 if (iter->kind != CONSTRUCT_FUNCTION) {
4705 static type_t *automatic_type_conversion(type_t *orig_type);
4707 static type_t *semantic_parameter(const source_position_t *pos,
4709 const declaration_specifiers_t *specifiers,
4712 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
4713 * shall be adjusted to ``qualified pointer to type'',
4715 * §6.7.5.3:8 A declaration of a parameter as ``function returning
4716 * type'' shall be adjusted to ``pointer to function
4717 * returning type'', as in 6.3.2.1. */
4718 type = automatic_type_conversion(type);
4720 if (specifiers->is_inline && is_type_valid(type)) {
4721 errorf(pos, "parameter '%Y' declared 'inline'", symbol);
4724 /* §6.9.1:6 The declarations in the declaration list shall contain
4725 * no storage-class specifier other than register and no
4726 * initializations. */
4727 if (specifiers->thread_local || (
4728 specifiers->storage_class != STORAGE_CLASS_NONE &&
4729 specifiers->storage_class != STORAGE_CLASS_REGISTER)
4731 errorf(pos, "invalid storage class for parameter '%Y'", symbol);
4734 /* delay test for incomplete type, because we might have (void)
4735 * which is legal but incomplete... */
4740 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4741 declarator_flags_t flags)
4743 parse_declarator_env_t env;
4744 memset(&env, 0, sizeof(env));
4745 env.modifiers = specifiers->modifiers;
4747 construct_type_t *construct_type =
4748 parse_inner_declarator(&env, (flags & DECL_MAY_BE_ABSTRACT) != 0);
4750 construct_declarator_type(construct_type, specifiers->type);
4751 type_t *type = skip_typeref(orig_type);
4753 if (construct_type != NULL) {
4754 obstack_free(&temp_obst, construct_type);
4758 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4759 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4760 entity->base.symbol = env.symbol;
4761 entity->base.source_position = env.source_position;
4762 entity->typedefe.type = orig_type;
4764 if (anonymous_entity != NULL) {
4765 if (is_type_compound(type)) {
4766 assert(anonymous_entity->compound.alias == NULL);
4767 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4768 anonymous_entity->kind == ENTITY_UNION);
4769 anonymous_entity->compound.alias = entity;
4770 anonymous_entity = NULL;
4771 } else if (is_type_enum(type)) {
4772 assert(anonymous_entity->enume.alias == NULL);
4773 assert(anonymous_entity->kind == ENTITY_ENUM);
4774 anonymous_entity->enume.alias = entity;
4775 anonymous_entity = NULL;
4779 /* create a declaration type entity */
4780 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
4781 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4783 if (env.symbol != NULL) {
4784 if (specifiers->is_inline && is_type_valid(type)) {
4785 errorf(&env.source_position,
4786 "compound member '%Y' declared 'inline'", env.symbol);
4789 if (specifiers->thread_local ||
4790 specifiers->storage_class != STORAGE_CLASS_NONE) {
4791 errorf(&env.source_position,
4792 "compound member '%Y' must have no storage class",
4796 } else if (flags & DECL_IS_PARAMETER) {
4797 orig_type = semantic_parameter(&env.source_position, orig_type,
4798 specifiers, env.symbol);
4800 entity = allocate_entity_zero(ENTITY_PARAMETER);
4801 } else if (is_type_function(type)) {
4802 entity = allocate_entity_zero(ENTITY_FUNCTION);
4804 entity->function.is_inline = specifiers->is_inline;
4805 entity->function.parameters = env.parameters;
4807 if (env.symbol != NULL) {
4808 if (specifiers->thread_local || (
4809 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4810 specifiers->storage_class != STORAGE_CLASS_NONE &&
4811 specifiers->storage_class != STORAGE_CLASS_STATIC
4813 errorf(&env.source_position,
4814 "invalid storage class for function '%Y'", env.symbol);
4818 entity = allocate_entity_zero(ENTITY_VARIABLE);
4820 entity->variable.get_property_sym = specifiers->get_property_sym;
4821 entity->variable.put_property_sym = specifiers->put_property_sym;
4822 if (specifiers->alignment != 0) {
4823 /* TODO: add checks here */
4824 entity->variable.alignment = specifiers->alignment;
4827 entity->variable.thread_local = specifiers->thread_local;
4829 if (env.symbol != NULL) {
4830 if (specifiers->is_inline && is_type_valid(type)) {
4831 errorf(&env.source_position,
4832 "variable '%Y' declared 'inline'", env.symbol);
4835 bool invalid_storage_class = false;
4836 if (current_scope == file_scope) {
4837 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4838 specifiers->storage_class != STORAGE_CLASS_NONE &&
4839 specifiers->storage_class != STORAGE_CLASS_STATIC) {
4840 invalid_storage_class = true;
4843 if (specifiers->thread_local &&
4844 specifiers->storage_class == STORAGE_CLASS_NONE) {
4845 invalid_storage_class = true;
4848 if (invalid_storage_class) {
4849 errorf(&env.source_position,
4850 "invalid storage class for variable '%Y'", env.symbol);
4855 if (env.symbol != NULL) {
4856 entity->base.symbol = env.symbol;
4857 entity->base.source_position = env.source_position;
4859 entity->base.source_position = specifiers->source_position;
4861 entity->base.namespc = NAMESPACE_NORMAL;
4862 entity->declaration.type = orig_type;
4863 entity->declaration.modifiers = env.modifiers;
4864 entity->declaration.deprecated_string = specifiers->deprecated_string;
4866 storage_class_t storage_class = specifiers->storage_class;
4867 entity->declaration.declared_storage_class = storage_class;
4869 if (storage_class == STORAGE_CLASS_NONE && current_scope != file_scope)
4870 storage_class = STORAGE_CLASS_AUTO;
4871 entity->declaration.storage_class = storage_class;
4874 parse_declaration_attributes(entity);
4879 static type_t *parse_abstract_declarator(type_t *base_type)
4881 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4883 type_t *result = construct_declarator_type(construct_type, base_type);
4884 if (construct_type != NULL) {
4885 obstack_free(&temp_obst, construct_type);
4892 * Check if the declaration of main is suspicious. main should be a
4893 * function with external linkage, returning int, taking either zero
4894 * arguments, two, or three arguments of appropriate types, ie.
4896 * int main([ int argc, char **argv [, char **env ] ]).
4898 * @param decl the declaration to check
4899 * @param type the function type of the declaration
4901 static void check_type_of_main(const entity_t *entity)
4903 const source_position_t *pos = &entity->base.source_position;
4904 if (entity->kind != ENTITY_FUNCTION) {
4905 warningf(pos, "'main' is not a function");
4909 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4910 warningf(pos, "'main' is normally a non-static function");
4913 type_t *type = skip_typeref(entity->declaration.type);
4914 assert(is_type_function(type));
4916 function_type_t *func_type = &type->function;
4917 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4918 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4919 func_type->return_type);
4921 const function_parameter_t *parm = func_type->parameters;
4923 type_t *const first_type = parm->type;
4924 if (!types_compatible(skip_typeref(first_type), type_int)) {
4926 "first argument of 'main' should be 'int', but is '%T'",
4931 type_t *const second_type = parm->type;
4932 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4933 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4937 type_t *const third_type = parm->type;
4938 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4939 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4943 goto warn_arg_count;
4947 warningf(pos, "'main' takes only zero, two or three arguments");
4953 * Check if a symbol is the equal to "main".
4955 static bool is_sym_main(const symbol_t *const sym)
4957 return strcmp(sym->string, "main") == 0;
4960 static void error_redefined_as_different_kind(const source_position_t *pos,
4961 const entity_t *old, entity_kind_t new_kind)
4963 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4964 get_entity_kind_name(old->kind), old->base.symbol,
4965 get_entity_kind_name(new_kind), &old->base.source_position);
4969 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4970 * for various problems that occur for multiple definitions
4972 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4974 const symbol_t *const symbol = entity->base.symbol;
4975 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4976 const source_position_t *pos = &entity->base.source_position;
4978 /* can happen in error cases */
4982 entity_t *previous_entity = get_entity(symbol, namespc);
4983 /* pushing the same entity twice will break the stack structure */
4984 assert(previous_entity != entity);
4986 if (entity->kind == ENTITY_FUNCTION) {
4987 type_t *const orig_type = entity->declaration.type;
4988 type_t *const type = skip_typeref(orig_type);
4990 assert(is_type_function(type));
4991 if (type->function.unspecified_parameters &&
4992 warning.strict_prototypes &&
4993 previous_entity == NULL) {
4994 warningf(pos, "function declaration '%#T' is not a prototype",
4998 if (warning.main && current_scope == file_scope
4999 && is_sym_main(symbol)) {
5000 check_type_of_main(entity);
5004 if (is_declaration(entity) &&
5005 warning.nested_externs &&
5006 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
5007 current_scope != file_scope) {
5008 warningf(pos, "nested extern declaration of '%#T'",
5009 entity->declaration.type, symbol);
5012 if (previous_entity != NULL &&
5013 previous_entity->base.parent_scope == ¤t_function->parameters &&
5014 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
5015 assert(previous_entity->kind == ENTITY_PARAMETER);
5017 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
5018 entity->declaration.type, symbol,
5019 previous_entity->declaration.type, symbol,
5020 &previous_entity->base.source_position);
5024 if (previous_entity != NULL &&
5025 previous_entity->base.parent_scope == current_scope) {
5026 if (previous_entity->kind != entity->kind) {
5027 error_redefined_as_different_kind(pos, previous_entity,
5031 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
5032 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
5033 symbol, &previous_entity->base.source_position);
5036 if (previous_entity->kind == ENTITY_TYPEDEF) {
5037 /* TODO: C++ allows this for exactly the same type */
5038 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
5039 symbol, &previous_entity->base.source_position);
5043 /* at this point we should have only VARIABLES or FUNCTIONS */
5044 assert(is_declaration(previous_entity) && is_declaration(entity));
5046 declaration_t *const prev_decl = &previous_entity->declaration;
5047 declaration_t *const decl = &entity->declaration;
5049 /* can happen for K&R style declarations */
5050 if (prev_decl->type == NULL &&
5051 previous_entity->kind == ENTITY_PARAMETER &&
5052 entity->kind == ENTITY_PARAMETER) {
5053 prev_decl->type = decl->type;
5054 prev_decl->storage_class = decl->storage_class;
5055 prev_decl->declared_storage_class = decl->declared_storage_class;
5056 prev_decl->modifiers = decl->modifiers;
5057 prev_decl->deprecated_string = decl->deprecated_string;
5058 return previous_entity;
5061 type_t *const orig_type = decl->type;
5062 assert(orig_type != NULL);
5063 type_t *const type = skip_typeref(orig_type);
5064 type_t * prev_type = skip_typeref(prev_decl->type);
5066 if (!types_compatible(type, prev_type)) {
5068 "declaration '%#T' is incompatible with '%#T' (declared %P)",
5069 orig_type, symbol, prev_decl->type, symbol,
5070 &previous_entity->base.source_position);
5072 unsigned old_storage_class = prev_decl->storage_class;
5073 if (warning.redundant_decls &&
5076 !(prev_decl->modifiers & DM_USED) &&
5077 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
5078 warningf(&previous_entity->base.source_position,
5079 "unnecessary static forward declaration for '%#T'",
5080 prev_decl->type, symbol);
5083 unsigned new_storage_class = decl->storage_class;
5084 if (is_type_incomplete(prev_type)) {
5085 prev_decl->type = type;
5089 /* pretend no storage class means extern for function
5090 * declarations (except if the previous declaration is neither
5091 * none nor extern) */
5092 if (entity->kind == ENTITY_FUNCTION) {
5093 if (prev_type->function.unspecified_parameters) {
5094 prev_decl->type = type;
5098 switch (old_storage_class) {
5099 case STORAGE_CLASS_NONE:
5100 old_storage_class = STORAGE_CLASS_EXTERN;
5103 case STORAGE_CLASS_EXTERN:
5104 if (is_definition) {
5105 if (warning.missing_prototypes &&
5106 prev_type->function.unspecified_parameters &&
5107 !is_sym_main(symbol)) {
5108 warningf(pos, "no previous prototype for '%#T'",
5111 } else if (new_storage_class == STORAGE_CLASS_NONE) {
5112 new_storage_class = STORAGE_CLASS_EXTERN;
5121 if (old_storage_class == STORAGE_CLASS_EXTERN &&
5122 new_storage_class == STORAGE_CLASS_EXTERN) {
5123 warn_redundant_declaration:
5124 if (!is_definition &&
5125 warning.redundant_decls &&
5126 is_type_valid(prev_type) &&
5127 strcmp(previous_entity->base.source_position.input_name,
5128 "<builtin>") != 0) {
5130 "redundant declaration for '%Y' (declared %P)",
5131 symbol, &previous_entity->base.source_position);
5133 } else if (current_function == NULL) {
5134 if (old_storage_class != STORAGE_CLASS_STATIC &&
5135 new_storage_class == STORAGE_CLASS_STATIC) {
5137 "static declaration of '%Y' follows non-static declaration (declared %P)",
5138 symbol, &previous_entity->base.source_position);
5139 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
5140 prev_decl->storage_class = STORAGE_CLASS_NONE;
5141 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
5143 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
5145 goto error_redeclaration;
5146 goto warn_redundant_declaration;
5148 } else if (is_type_valid(prev_type)) {
5149 if (old_storage_class == new_storage_class) {
5150 error_redeclaration:
5151 errorf(pos, "redeclaration of '%Y' (declared %P)",
5152 symbol, &previous_entity->base.source_position);
5155 "redeclaration of '%Y' with different linkage (declared %P)",
5156 symbol, &previous_entity->base.source_position);
5161 prev_decl->modifiers |= decl->modifiers;
5162 if (entity->kind == ENTITY_FUNCTION) {
5163 previous_entity->function.is_inline |= entity->function.is_inline;
5165 return previous_entity;
5168 if (entity->kind == ENTITY_FUNCTION) {
5169 if (is_definition &&
5170 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
5171 if (warning.missing_prototypes && !is_sym_main(symbol)) {
5172 warningf(pos, "no previous prototype for '%#T'",
5173 entity->declaration.type, symbol);
5174 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
5175 warningf(pos, "no previous declaration for '%#T'",
5176 entity->declaration.type, symbol);
5179 } else if (warning.missing_declarations &&
5180 entity->kind == ENTITY_VARIABLE &&
5181 current_scope == file_scope) {
5182 declaration_t *declaration = &entity->declaration;
5183 if (declaration->storage_class == STORAGE_CLASS_NONE) {
5184 warningf(pos, "no previous declaration for '%#T'",
5185 declaration->type, symbol);
5190 assert(entity->base.parent_scope == NULL);
5191 assert(current_scope != NULL);
5193 entity->base.parent_scope = current_scope;
5194 entity->base.namespc = NAMESPACE_NORMAL;
5195 environment_push(entity);
5196 append_entity(current_scope, entity);
5201 static void parser_error_multiple_definition(entity_t *entity,
5202 const source_position_t *source_position)
5204 errorf(source_position, "multiple definition of '%Y' (declared %P)",
5205 entity->base.symbol, &entity->base.source_position);
5208 static bool is_declaration_specifier(const token_t *token,
5209 bool only_specifiers_qualifiers)
5211 switch (token->type) {
5216 return is_typedef_symbol(token->v.symbol);
5218 case T___extension__:
5220 return !only_specifiers_qualifiers;
5227 static void parse_init_declarator_rest(entity_t *entity)
5229 assert(is_declaration(entity));
5230 declaration_t *const declaration = &entity->declaration;
5234 type_t *orig_type = declaration->type;
5235 type_t *type = skip_typeref(orig_type);
5237 if (entity->kind == ENTITY_VARIABLE
5238 && entity->variable.initializer != NULL) {
5239 parser_error_multiple_definition(entity, HERE);
5242 bool must_be_constant = false;
5243 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5244 entity->base.parent_scope == file_scope) {
5245 must_be_constant = true;
5248 if (is_type_function(type)) {
5249 errorf(&entity->base.source_position,
5250 "function '%#T' is initialized like a variable",
5251 orig_type, entity->base.symbol);
5252 orig_type = type_error_type;
5255 parse_initializer_env_t env;
5256 env.type = orig_type;
5257 env.must_be_constant = must_be_constant;
5258 env.entity = entity;
5259 current_init_decl = entity;
5261 initializer_t *initializer = parse_initializer(&env);
5262 current_init_decl = NULL;
5264 if (entity->kind == ENTITY_VARIABLE) {
5265 /* § 6.7.5 (22) array initializers for arrays with unknown size
5266 * determine the array type size */
5267 declaration->type = env.type;
5268 entity->variable.initializer = initializer;
5272 /* parse rest of a declaration without any declarator */
5273 static void parse_anonymous_declaration_rest(
5274 const declaration_specifiers_t *specifiers)
5277 anonymous_entity = NULL;
5279 if (warning.other) {
5280 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
5281 specifiers->thread_local) {
5282 warningf(&specifiers->source_position,
5283 "useless storage class in empty declaration");
5286 type_t *type = specifiers->type;
5287 switch (type->kind) {
5288 case TYPE_COMPOUND_STRUCT:
5289 case TYPE_COMPOUND_UNION: {
5290 if (type->compound.compound->base.symbol == NULL) {
5291 warningf(&specifiers->source_position,
5292 "unnamed struct/union that defines no instances");
5301 warningf(&specifiers->source_position, "empty declaration");
5307 static void check_variable_type_complete(entity_t *ent)
5309 if (ent->kind != ENTITY_VARIABLE)
5312 /* §6.7:7 If an identifier for an object is declared with no linkage, the
5313 * type for the object shall be complete [...] */
5314 declaration_t *decl = &ent->declaration;
5315 if (decl->storage_class != STORAGE_CLASS_NONE)
5318 type_t *const orig_type = decl->type;
5319 type_t *const type = skip_typeref(orig_type);
5320 if (!is_type_incomplete(type))
5323 /* GCC allows global arrays without size and assigns them a length of one,
5324 * if no different declaration follows */
5325 if (is_type_array(type) &&
5327 ent->base.parent_scope == file_scope) {
5328 ARR_APP1(declaration_t*, incomplete_arrays, decl);
5332 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
5333 orig_type, ent->base.symbol);
5337 static void parse_declaration_rest(entity_t *ndeclaration,
5338 const declaration_specifiers_t *specifiers,
5339 parsed_declaration_func finished_declaration,
5340 declarator_flags_t flags)
5342 add_anchor_token(';');
5343 add_anchor_token(',');
5345 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5347 if (token.type == '=') {
5348 parse_init_declarator_rest(entity);
5349 } else if (entity->kind == ENTITY_VARIABLE) {
5350 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
5351 * [...] where the extern specifier is explicitly used. */
5352 declaration_t *decl = &entity->declaration;
5353 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
5354 type_t *type = decl->type;
5355 if (is_type_reference(skip_typeref(type))) {
5356 errorf(&entity->base.source_position,
5357 "reference '%#T' must be initialized",
5358 type, entity->base.symbol);
5363 check_variable_type_complete(entity);
5365 if (token.type != ',')
5369 add_anchor_token('=');
5370 ndeclaration = parse_declarator(specifiers, flags);
5371 rem_anchor_token('=');
5373 expect(';', end_error);
5376 anonymous_entity = NULL;
5377 rem_anchor_token(';');
5378 rem_anchor_token(',');
5381 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5383 symbol_t *symbol = entity->base.symbol;
5384 if (symbol == NULL) {
5385 errorf(HERE, "anonymous declaration not valid as function parameter");
5389 assert(entity->base.namespc == NAMESPACE_NORMAL);
5390 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5391 if (previous_entity == NULL
5392 || previous_entity->base.parent_scope != current_scope) {
5393 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5398 if (is_definition) {
5399 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
5402 return record_entity(entity, false);
5405 static void parse_declaration(parsed_declaration_func finished_declaration,
5406 declarator_flags_t flags)
5408 declaration_specifiers_t specifiers;
5409 memset(&specifiers, 0, sizeof(specifiers));
5411 add_anchor_token(';');
5412 parse_declaration_specifiers(&specifiers);
5413 rem_anchor_token(';');
5415 if (token.type == ';') {
5416 parse_anonymous_declaration_rest(&specifiers);
5418 entity_t *entity = parse_declarator(&specifiers, flags);
5419 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
5423 static type_t *get_default_promoted_type(type_t *orig_type)
5425 type_t *result = orig_type;
5427 type_t *type = skip_typeref(orig_type);
5428 if (is_type_integer(type)) {
5429 result = promote_integer(type);
5430 } else if (type == type_float) {
5431 result = type_double;
5437 static void parse_kr_declaration_list(entity_t *entity)
5439 if (entity->kind != ENTITY_FUNCTION)
5442 type_t *type = skip_typeref(entity->declaration.type);
5443 assert(is_type_function(type));
5444 if (!type->function.kr_style_parameters)
5448 add_anchor_token('{');
5450 /* push function parameters */
5451 size_t const top = environment_top();
5452 scope_t *old_scope = scope_push(&entity->function.parameters);
5454 entity_t *parameter = entity->function.parameters.entities;
5455 for ( ; parameter != NULL; parameter = parameter->base.next) {
5456 assert(parameter->base.parent_scope == NULL);
5457 parameter->base.parent_scope = current_scope;
5458 environment_push(parameter);
5461 /* parse declaration list */
5463 switch (token.type) {
5465 case T___extension__:
5466 /* This covers symbols, which are no type, too, and results in
5467 * better error messages. The typical cases are misspelled type
5468 * names and missing includes. */
5470 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
5478 /* pop function parameters */
5479 assert(current_scope == &entity->function.parameters);
5480 scope_pop(old_scope);
5481 environment_pop_to(top);
5483 /* update function type */
5484 type_t *new_type = duplicate_type(type);
5486 function_parameter_t *parameters = NULL;
5487 function_parameter_t *last_parameter = NULL;
5489 parameter = entity->function.parameters.entities;
5490 for (; parameter != NULL; parameter = parameter->base.next) {
5491 type_t *parameter_type = parameter->declaration.type;
5492 if (parameter_type == NULL) {
5494 errorf(HERE, "no type specified for function parameter '%Y'",
5495 parameter->base.symbol);
5497 if (warning.implicit_int) {
5498 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5499 parameter->base.symbol);
5501 parameter_type = type_int;
5502 parameter->declaration.type = parameter_type;
5506 semantic_parameter_incomplete(parameter);
5507 parameter_type = parameter->declaration.type;
5510 * we need the default promoted types for the function type
5512 parameter_type = get_default_promoted_type(parameter_type);
5514 function_parameter_t *function_parameter
5515 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5516 memset(function_parameter, 0, sizeof(function_parameter[0]));
5518 function_parameter->type = parameter_type;
5519 if (last_parameter != NULL) {
5520 last_parameter->next = function_parameter;
5522 parameters = function_parameter;
5524 last_parameter = function_parameter;
5527 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5529 new_type->function.parameters = parameters;
5530 new_type->function.unspecified_parameters = true;
5532 type = typehash_insert(new_type);
5533 if (type != new_type) {
5534 obstack_free(type_obst, new_type);
5537 entity->declaration.type = type;
5539 rem_anchor_token('{');
5542 static bool first_err = true;
5545 * When called with first_err set, prints the name of the current function,
5548 static void print_in_function(void)
5552 diagnosticf("%s: In function '%Y':\n",
5553 current_function->base.base.source_position.input_name,
5554 current_function->base.base.symbol);
5559 * Check if all labels are defined in the current function.
5560 * Check if all labels are used in the current function.
5562 static void check_labels(void)
5564 for (const goto_statement_t *goto_statement = goto_first;
5565 goto_statement != NULL;
5566 goto_statement = goto_statement->next) {
5567 /* skip computed gotos */
5568 if (goto_statement->expression != NULL)
5571 label_t *label = goto_statement->label;
5574 if (label->base.source_position.input_name == NULL) {
5575 print_in_function();
5576 errorf(&goto_statement->base.source_position,
5577 "label '%Y' used but not defined", label->base.symbol);
5581 if (warning.unused_label) {
5582 for (const label_statement_t *label_statement = label_first;
5583 label_statement != NULL;
5584 label_statement = label_statement->next) {
5585 label_t *label = label_statement->label;
5587 if (! label->used) {
5588 print_in_function();
5589 warningf(&label_statement->base.source_position,
5590 "label '%Y' defined but not used", label->base.symbol);
5596 static void warn_unused_entity(entity_t *entity, entity_t *last)
5598 entity_t const *const end = last != NULL ? last->base.next : NULL;
5599 for (; entity != end; entity = entity->base.next) {
5600 if (!is_declaration(entity))
5603 declaration_t *declaration = &entity->declaration;
5604 if (declaration->implicit)
5607 if (!declaration->used) {
5608 print_in_function();
5609 const char *what = get_entity_kind_name(entity->kind);
5610 warningf(&entity->base.source_position, "%s '%Y' is unused",
5611 what, entity->base.symbol);
5612 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5613 print_in_function();
5614 const char *what = get_entity_kind_name(entity->kind);
5615 warningf(&entity->base.source_position, "%s '%Y' is never read",
5616 what, entity->base.symbol);
5621 static void check_unused_variables(statement_t *const stmt, void *const env)
5625 switch (stmt->kind) {
5626 case STATEMENT_DECLARATION: {
5627 declaration_statement_t const *const decls = &stmt->declaration;
5628 warn_unused_entity(decls->declarations_begin,
5629 decls->declarations_end);
5634 warn_unused_entity(stmt->fors.scope.entities, NULL);
5643 * Check declarations of current_function for unused entities.
5645 static void check_declarations(void)
5647 if (warning.unused_parameter) {
5648 const scope_t *scope = ¤t_function->parameters;
5650 /* do not issue unused warnings for main */
5651 if (!is_sym_main(current_function->base.base.symbol)) {
5652 warn_unused_entity(scope->entities, NULL);
5655 if (warning.unused_variable) {
5656 walk_statements(current_function->statement, check_unused_variables,
5661 static int determine_truth(expression_t const* const cond)
5664 !is_constant_expression(cond) ? 0 :
5665 fold_constant(cond) != 0 ? 1 :
5669 static void check_reachable(statement_t *);
5670 static bool reaches_end;
5672 static bool expression_returns(expression_t const *const expr)
5674 switch (expr->kind) {
5676 expression_t const *const func = expr->call.function;
5677 if (func->kind == EXPR_REFERENCE) {
5678 entity_t *entity = func->reference.entity;
5679 if (entity->kind == ENTITY_FUNCTION
5680 && entity->declaration.modifiers & DM_NORETURN)
5684 if (!expression_returns(func))
5687 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5688 if (!expression_returns(arg->expression))
5695 case EXPR_REFERENCE:
5696 case EXPR_REFERENCE_ENUM_VALUE:
5698 case EXPR_CHARACTER_CONSTANT:
5699 case EXPR_WIDE_CHARACTER_CONSTANT:
5700 case EXPR_STRING_LITERAL:
5701 case EXPR_WIDE_STRING_LITERAL:
5702 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5703 case EXPR_LABEL_ADDRESS:
5704 case EXPR_CLASSIFY_TYPE:
5705 case EXPR_SIZEOF: // TODO handle obscure VLA case
5708 case EXPR_BUILTIN_SYMBOL:
5709 case EXPR_BUILTIN_CONSTANT_P:
5710 case EXPR_BUILTIN_PREFETCH:
5715 case EXPR_STATEMENT: {
5716 bool old_reaches_end = reaches_end;
5717 reaches_end = false;
5718 check_reachable(expr->statement.statement);
5719 bool returns = reaches_end;
5720 reaches_end = old_reaches_end;
5724 case EXPR_CONDITIONAL:
5725 // TODO handle constant expression
5727 if (!expression_returns(expr->conditional.condition))
5730 if (expr->conditional.true_expression != NULL
5731 && expression_returns(expr->conditional.true_expression))
5734 return expression_returns(expr->conditional.false_expression);
5737 return expression_returns(expr->select.compound);
5739 case EXPR_ARRAY_ACCESS:
5741 expression_returns(expr->array_access.array_ref) &&
5742 expression_returns(expr->array_access.index);
5745 return expression_returns(expr->va_starte.ap);
5748 return expression_returns(expr->va_arge.ap);
5750 EXPR_UNARY_CASES_MANDATORY
5751 return expression_returns(expr->unary.value);
5753 case EXPR_UNARY_THROW:
5757 // TODO handle constant lhs of && and ||
5759 expression_returns(expr->binary.left) &&
5760 expression_returns(expr->binary.right);
5766 panic("unhandled expression");
5769 static bool initializer_returns(initializer_t const *const init)
5771 switch (init->kind) {
5772 case INITIALIZER_VALUE:
5773 return expression_returns(init->value.value);
5775 case INITIALIZER_LIST: {
5776 initializer_t * const* i = init->list.initializers;
5777 initializer_t * const* const end = i + init->list.len;
5778 bool returns = true;
5779 for (; i != end; ++i) {
5780 if (!initializer_returns(*i))
5786 case INITIALIZER_STRING:
5787 case INITIALIZER_WIDE_STRING:
5788 case INITIALIZER_DESIGNATOR: // designators have no payload
5791 panic("unhandled initializer");
5794 static bool noreturn_candidate;
5796 static void check_reachable(statement_t *const stmt)
5798 if (stmt->base.reachable)
5800 if (stmt->kind != STATEMENT_DO_WHILE)
5801 stmt->base.reachable = true;
5803 statement_t *last = stmt;
5805 switch (stmt->kind) {
5806 case STATEMENT_INVALID:
5807 case STATEMENT_EMPTY:
5809 next = stmt->base.next;
5812 case STATEMENT_DECLARATION: {
5813 declaration_statement_t const *const decl = &stmt->declaration;
5814 entity_t const * ent = decl->declarations_begin;
5815 entity_t const *const last = decl->declarations_end;
5817 for (;; ent = ent->base.next) {
5818 if (ent->kind == ENTITY_VARIABLE &&
5819 ent->variable.initializer != NULL &&
5820 !initializer_returns(ent->variable.initializer)) {
5827 next = stmt->base.next;
5831 case STATEMENT_COMPOUND:
5832 next = stmt->compound.statements;
5834 next = stmt->base.next;
5837 case STATEMENT_RETURN: {
5838 expression_t const *const val = stmt->returns.value;
5839 if (val == NULL || expression_returns(val))
5840 noreturn_candidate = false;
5844 case STATEMENT_IF: {
5845 if_statement_t const *const ifs = &stmt->ifs;
5846 expression_t const *const cond = ifs->condition;
5848 if (!expression_returns(cond))
5851 int const val = determine_truth(cond);
5854 check_reachable(ifs->true_statement);
5859 if (ifs->false_statement != NULL) {
5860 check_reachable(ifs->false_statement);
5864 next = stmt->base.next;
5868 case STATEMENT_SWITCH: {
5869 switch_statement_t const *const switchs = &stmt->switchs;
5870 expression_t const *const expr = switchs->expression;
5872 if (!expression_returns(expr))
5875 if (is_constant_expression(expr)) {
5876 long const val = fold_constant(expr);
5877 case_label_statement_t * defaults = NULL;
5878 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5879 if (i->expression == NULL) {
5884 if (i->first_case <= val && val <= i->last_case) {
5885 check_reachable((statement_t*)i);
5890 if (defaults != NULL) {
5891 check_reachable((statement_t*)defaults);
5895 bool has_default = false;
5896 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5897 if (i->expression == NULL)
5900 check_reachable((statement_t*)i);
5907 next = stmt->base.next;
5911 case STATEMENT_EXPRESSION: {
5912 /* Check for noreturn function call */
5913 expression_t const *const expr = stmt->expression.expression;
5914 if (!expression_returns(expr))
5917 next = stmt->base.next;
5921 case STATEMENT_CONTINUE: {
5922 statement_t *parent = stmt;
5924 parent = parent->base.parent;
5925 if (parent == NULL) /* continue not within loop */
5929 switch (parent->kind) {
5930 case STATEMENT_WHILE: goto continue_while;
5931 case STATEMENT_DO_WHILE: goto continue_do_while;
5932 case STATEMENT_FOR: goto continue_for;
5939 case STATEMENT_BREAK: {
5940 statement_t *parent = stmt;
5942 parent = parent->base.parent;
5943 if (parent == NULL) /* break not within loop/switch */
5946 switch (parent->kind) {
5947 case STATEMENT_SWITCH:
5948 case STATEMENT_WHILE:
5949 case STATEMENT_DO_WHILE:
5952 next = parent->base.next;
5953 goto found_break_parent;
5962 case STATEMENT_GOTO:
5963 if (stmt->gotos.expression) {
5964 if (!expression_returns(stmt->gotos.expression))
5967 statement_t *parent = stmt->base.parent;
5968 if (parent == NULL) /* top level goto */
5972 next = stmt->gotos.label->statement;
5973 if (next == NULL) /* missing label */
5978 case STATEMENT_LABEL:
5979 next = stmt->label.statement;
5982 case STATEMENT_CASE_LABEL:
5983 next = stmt->case_label.statement;
5986 case STATEMENT_WHILE: {
5987 while_statement_t const *const whiles = &stmt->whiles;
5988 expression_t const *const cond = whiles->condition;
5990 if (!expression_returns(cond))
5993 int const val = determine_truth(cond);
5996 check_reachable(whiles->body);
6001 next = stmt->base.next;
6005 case STATEMENT_DO_WHILE:
6006 next = stmt->do_while.body;
6009 case STATEMENT_FOR: {
6010 for_statement_t *const fors = &stmt->fors;
6012 if (fors->condition_reachable)
6014 fors->condition_reachable = true;
6016 expression_t const *const cond = fors->condition;
6021 } else if (expression_returns(cond)) {
6022 val = determine_truth(cond);
6028 check_reachable(fors->body);
6033 next = stmt->base.next;
6037 case STATEMENT_MS_TRY: {
6038 ms_try_statement_t const *const ms_try = &stmt->ms_try;
6039 check_reachable(ms_try->try_statement);
6040 next = ms_try->final_statement;
6044 case STATEMENT_LEAVE: {
6045 statement_t *parent = stmt;
6047 parent = parent->base.parent;
6048 if (parent == NULL) /* __leave not within __try */
6051 if (parent->kind == STATEMENT_MS_TRY) {
6053 next = parent->ms_try.final_statement;
6061 panic("invalid statement kind");
6064 while (next == NULL) {
6065 next = last->base.parent;
6067 noreturn_candidate = false;
6069 type_t *const type = current_function->base.type;
6070 assert(is_type_function(type));
6071 type_t *const ret = skip_typeref(type->function.return_type);
6072 if (warning.return_type &&
6073 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
6074 is_type_valid(ret) &&
6075 !is_sym_main(current_function->base.base.symbol)) {
6076 warningf(&stmt->base.source_position,
6077 "control reaches end of non-void function");
6082 switch (next->kind) {
6083 case STATEMENT_INVALID:
6084 case STATEMENT_EMPTY:
6085 case STATEMENT_DECLARATION:
6086 case STATEMENT_EXPRESSION:
6088 case STATEMENT_RETURN:
6089 case STATEMENT_CONTINUE:
6090 case STATEMENT_BREAK:
6091 case STATEMENT_GOTO:
6092 case STATEMENT_LEAVE:
6093 panic("invalid control flow in function");
6095 case STATEMENT_COMPOUND:
6096 if (next->compound.stmt_expr) {
6102 case STATEMENT_SWITCH:
6103 case STATEMENT_LABEL:
6104 case STATEMENT_CASE_LABEL:
6106 next = next->base.next;
6109 case STATEMENT_WHILE: {
6111 if (next->base.reachable)
6113 next->base.reachable = true;
6115 while_statement_t const *const whiles = &next->whiles;
6116 expression_t const *const cond = whiles->condition;
6118 if (!expression_returns(cond))
6121 int const val = determine_truth(cond);
6124 check_reachable(whiles->body);
6130 next = next->base.next;
6134 case STATEMENT_DO_WHILE: {
6136 if (next->base.reachable)
6138 next->base.reachable = true;
6140 do_while_statement_t const *const dw = &next->do_while;
6141 expression_t const *const cond = dw->condition;
6143 if (!expression_returns(cond))
6146 int const val = determine_truth(cond);
6149 check_reachable(dw->body);
6155 next = next->base.next;
6159 case STATEMENT_FOR: {
6161 for_statement_t *const fors = &next->fors;
6163 fors->step_reachable = true;
6165 if (fors->condition_reachable)
6167 fors->condition_reachable = true;
6169 expression_t const *const cond = fors->condition;
6174 } else if (expression_returns(cond)) {
6175 val = determine_truth(cond);
6181 check_reachable(fors->body);
6187 next = next->base.next;
6191 case STATEMENT_MS_TRY:
6193 next = next->ms_try.final_statement;
6198 check_reachable(next);
6201 static void check_unreachable(statement_t* const stmt, void *const env)
6205 switch (stmt->kind) {
6206 case STATEMENT_DO_WHILE:
6207 if (!stmt->base.reachable) {
6208 expression_t const *const cond = stmt->do_while.condition;
6209 if (determine_truth(cond) >= 0) {
6210 warningf(&cond->base.source_position,
6211 "condition of do-while-loop is unreachable");
6216 case STATEMENT_FOR: {
6217 for_statement_t const* const fors = &stmt->fors;
6219 // if init and step are unreachable, cond is unreachable, too
6220 if (!stmt->base.reachable && !fors->step_reachable) {
6221 warningf(&stmt->base.source_position, "statement is unreachable");
6223 if (!stmt->base.reachable && fors->initialisation != NULL) {
6224 warningf(&fors->initialisation->base.source_position,
6225 "initialisation of for-statement is unreachable");
6228 if (!fors->condition_reachable && fors->condition != NULL) {
6229 warningf(&fors->condition->base.source_position,
6230 "condition of for-statement is unreachable");
6233 if (!fors->step_reachable && fors->step != NULL) {
6234 warningf(&fors->step->base.source_position,
6235 "step of for-statement is unreachable");
6241 case STATEMENT_COMPOUND:
6242 if (stmt->compound.statements != NULL)
6244 goto warn_unreachable;
6246 case STATEMENT_DECLARATION: {
6247 /* Only warn if there is at least one declarator with an initializer.
6248 * This typically occurs in switch statements. */
6249 declaration_statement_t const *const decl = &stmt->declaration;
6250 entity_t const * ent = decl->declarations_begin;
6251 entity_t const *const last = decl->declarations_end;
6253 for (;; ent = ent->base.next) {
6254 if (ent->kind == ENTITY_VARIABLE &&
6255 ent->variable.initializer != NULL) {
6256 goto warn_unreachable;
6266 if (!stmt->base.reachable)
6267 warningf(&stmt->base.source_position, "statement is unreachable");
6272 static void parse_external_declaration(void)
6274 /* function-definitions and declarations both start with declaration
6276 declaration_specifiers_t specifiers;
6277 memset(&specifiers, 0, sizeof(specifiers));
6279 add_anchor_token(';');
6280 parse_declaration_specifiers(&specifiers);
6281 rem_anchor_token(';');
6283 /* must be a declaration */
6284 if (token.type == ';') {
6285 parse_anonymous_declaration_rest(&specifiers);
6289 add_anchor_token(',');
6290 add_anchor_token('=');
6291 add_anchor_token(';');
6292 add_anchor_token('{');
6294 /* declarator is common to both function-definitions and declarations */
6295 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
6297 rem_anchor_token('{');
6298 rem_anchor_token(';');
6299 rem_anchor_token('=');
6300 rem_anchor_token(',');
6302 /* must be a declaration */
6303 switch (token.type) {
6307 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
6312 /* must be a function definition */
6313 parse_kr_declaration_list(ndeclaration);
6315 if (token.type != '{') {
6316 parse_error_expected("while parsing function definition", '{', NULL);
6317 eat_until_matching_token(';');
6321 assert(is_declaration(ndeclaration));
6322 type_t *type = skip_typeref(ndeclaration->declaration.type);
6324 if (!is_type_function(type)) {
6325 if (is_type_valid(type)) {
6326 errorf(HERE, "declarator '%#T' has a body but is not a function type",
6327 type, ndeclaration->base.symbol);
6333 if (warning.aggregate_return &&
6334 is_type_compound(skip_typeref(type->function.return_type))) {
6335 warningf(HERE, "function '%Y' returns an aggregate",
6336 ndeclaration->base.symbol);
6338 if (warning.traditional && !type->function.unspecified_parameters) {
6339 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6340 ndeclaration->base.symbol);
6342 if (warning.old_style_definition && type->function.unspecified_parameters) {
6343 warningf(HERE, "old-style function definition '%Y'",
6344 ndeclaration->base.symbol);
6347 /* § 6.7.5.3 (14) a function definition with () means no
6348 * parameters (and not unspecified parameters) */
6349 if (type->function.unspecified_parameters
6350 && type->function.parameters == NULL
6351 && !type->function.kr_style_parameters) {
6352 type_t *duplicate = duplicate_type(type);
6353 duplicate->function.unspecified_parameters = false;
6355 type = typehash_insert(duplicate);
6356 if (type != duplicate) {
6357 obstack_free(type_obst, duplicate);
6359 ndeclaration->declaration.type = type;
6362 entity_t *const entity = record_entity(ndeclaration, true);
6363 assert(entity->kind == ENTITY_FUNCTION);
6364 assert(ndeclaration->kind == ENTITY_FUNCTION);
6366 function_t *function = &entity->function;
6367 if (ndeclaration != entity) {
6368 function->parameters = ndeclaration->function.parameters;
6370 assert(is_declaration(entity));
6371 type = skip_typeref(entity->declaration.type);
6373 /* push function parameters and switch scope */
6374 size_t const top = environment_top();
6375 scope_t *old_scope = scope_push(&function->parameters);
6377 entity_t *parameter = function->parameters.entities;
6378 for (; parameter != NULL; parameter = parameter->base.next) {
6379 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6380 parameter->base.parent_scope = current_scope;
6382 assert(parameter->base.parent_scope == NULL
6383 || parameter->base.parent_scope == current_scope);
6384 parameter->base.parent_scope = current_scope;
6385 if (parameter->base.symbol == NULL) {
6386 errorf(¶meter->base.source_position, "parameter name omitted");
6389 environment_push(parameter);
6392 if (function->statement != NULL) {
6393 parser_error_multiple_definition(entity, HERE);
6396 /* parse function body */
6397 int label_stack_top = label_top();
6398 function_t *old_current_function = current_function;
6399 current_function = function;
6400 current_parent = NULL;
6403 goto_anchor = &goto_first;
6405 label_anchor = &label_first;
6407 statement_t *const body = parse_compound_statement(false);
6408 function->statement = body;
6411 check_declarations();
6412 if (warning.return_type ||
6413 warning.unreachable_code ||
6414 (warning.missing_noreturn
6415 && !(function->base.modifiers & DM_NORETURN))) {
6416 noreturn_candidate = true;
6417 check_reachable(body);
6418 if (warning.unreachable_code)
6419 walk_statements(body, check_unreachable, NULL);
6420 if (warning.missing_noreturn &&
6421 noreturn_candidate &&
6422 !(function->base.modifiers & DM_NORETURN)) {
6423 warningf(&body->base.source_position,
6424 "function '%#T' is candidate for attribute 'noreturn'",
6425 type, entity->base.symbol);
6429 assert(current_parent == NULL);
6430 assert(current_function == function);
6431 current_function = old_current_function;
6432 label_pop_to(label_stack_top);
6435 assert(current_scope == &function->parameters);
6436 scope_pop(old_scope);
6437 environment_pop_to(top);
6440 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6441 source_position_t *source_position,
6442 const symbol_t *symbol)
6444 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6446 type->bitfield.base_type = base_type;
6447 type->bitfield.size_expression = size;
6450 type_t *skipped_type = skip_typeref(base_type);
6451 if (!is_type_integer(skipped_type)) {
6452 errorf(HERE, "bitfield base type '%T' is not an integer type",
6456 bit_size = skipped_type->base.size * 8;
6459 if (is_constant_expression(size)) {
6460 long v = fold_constant(size);
6463 errorf(source_position, "negative width in bit-field '%Y'", symbol);
6464 } else if (v == 0) {
6465 errorf(source_position, "zero width for bit-field '%Y'", symbol);
6466 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6467 errorf(source_position, "width of '%Y' exceeds its type", symbol);
6469 type->bitfield.bit_size = v;
6476 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6478 entity_t *iter = compound->members.entities;
6479 for (; iter != NULL; iter = iter->base.next) {
6480 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6483 if (iter->base.symbol == symbol) {
6485 } else if (iter->base.symbol == NULL) {
6486 type_t *type = skip_typeref(iter->declaration.type);
6487 if (is_type_compound(type)) {
6489 = find_compound_entry(type->compound.compound, symbol);
6500 static void parse_compound_declarators(compound_t *compound,
6501 const declaration_specifiers_t *specifiers)
6506 if (token.type == ':') {
6507 source_position_t source_position = *HERE;
6510 type_t *base_type = specifiers->type;
6511 expression_t *size = parse_constant_expression();
6513 type_t *type = make_bitfield_type(base_type, size,
6514 &source_position, sym_anonymous);
6516 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6517 entity->base.namespc = NAMESPACE_NORMAL;
6518 entity->base.source_position = source_position;
6519 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6520 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6521 entity->declaration.modifiers = specifiers->modifiers;
6522 entity->declaration.type = type;
6523 append_entity(&compound->members, entity);
6525 entity = parse_declarator(specifiers,
6526 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
6527 if (entity->kind == ENTITY_TYPEDEF) {
6528 errorf(&entity->base.source_position,
6529 "typedef not allowed as compound member");
6531 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6533 /* make sure we don't define a symbol multiple times */
6534 symbol_t *symbol = entity->base.symbol;
6535 if (symbol != NULL) {
6536 entity_t *prev = find_compound_entry(compound, symbol);
6538 errorf(&entity->base.source_position,
6539 "multiple declarations of symbol '%Y' (declared %P)",
6540 symbol, &prev->base.source_position);
6544 if (token.type == ':') {
6545 source_position_t source_position = *HERE;
6547 expression_t *size = parse_constant_expression();
6549 type_t *type = entity->declaration.type;
6550 type_t *bitfield_type = make_bitfield_type(type, size,
6551 &source_position, entity->base.symbol);
6552 entity->declaration.type = bitfield_type;
6554 type_t *orig_type = entity->declaration.type;
6555 type_t *type = skip_typeref(orig_type);
6556 if (is_type_function(type)) {
6557 errorf(&entity->base.source_position,
6558 "compound member '%Y' must not have function type '%T'",
6559 entity->base.symbol, orig_type);
6560 } else if (is_type_incomplete(type)) {
6561 /* §6.7.2.1:16 flexible array member */
6562 if (is_type_array(type) &&
6563 token.type == ';' &&
6564 look_ahead(1)->type == '}') {
6565 compound->has_flexible_member = true;
6567 errorf(&entity->base.source_position,
6568 "compound member '%Y' has incomplete type '%T'",
6569 entity->base.symbol, orig_type);
6574 append_entity(&compound->members, entity);
6578 if (token.type != ',')
6582 expect(';', end_error);
6585 anonymous_entity = NULL;
6588 static void parse_compound_type_entries(compound_t *compound)
6591 add_anchor_token('}');
6593 while (token.type != '}') {
6594 if (token.type == T_EOF) {
6595 errorf(HERE, "EOF while parsing struct");
6598 declaration_specifiers_t specifiers;
6599 memset(&specifiers, 0, sizeof(specifiers));
6600 parse_declaration_specifiers(&specifiers);
6602 parse_compound_declarators(compound, &specifiers);
6604 rem_anchor_token('}');
6608 compound->complete = true;
6611 static type_t *parse_typename(void)
6613 declaration_specifiers_t specifiers;
6614 memset(&specifiers, 0, sizeof(specifiers));
6615 parse_declaration_specifiers(&specifiers);
6616 if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6617 specifiers.thread_local) {
6618 /* TODO: improve error message, user does probably not know what a
6619 * storage class is...
6621 errorf(HERE, "typename may not have a storage class");
6624 type_t *result = parse_abstract_declarator(specifiers.type);
6632 typedef expression_t* (*parse_expression_function)(void);
6633 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6635 typedef struct expression_parser_function_t expression_parser_function_t;
6636 struct expression_parser_function_t {
6637 parse_expression_function parser;
6638 precedence_t infix_precedence;
6639 parse_expression_infix_function infix_parser;
6642 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6645 * Prints an error message if an expression was expected but not read
6647 static expression_t *expected_expression_error(void)
6649 /* skip the error message if the error token was read */
6650 if (token.type != T_ERROR) {
6651 errorf(HERE, "expected expression, got token %K", &token);
6655 return create_invalid_expression();
6659 * Parse a string constant.
6661 static expression_t *parse_string_const(void)
6664 if (token.type == T_STRING_LITERAL) {
6665 string_t res = token.v.string;
6667 while (token.type == T_STRING_LITERAL) {
6668 res = concat_strings(&res, &token.v.string);
6671 if (token.type != T_WIDE_STRING_LITERAL) {
6672 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6673 /* note: that we use type_char_ptr here, which is already the
6674 * automatic converted type. revert_automatic_type_conversion
6675 * will construct the array type */
6676 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6677 cnst->string.value = res;
6681 wres = concat_string_wide_string(&res, &token.v.wide_string);
6683 wres = token.v.wide_string;
6688 switch (token.type) {
6689 case T_WIDE_STRING_LITERAL:
6690 wres = concat_wide_strings(&wres, &token.v.wide_string);
6693 case T_STRING_LITERAL:
6694 wres = concat_wide_string_string(&wres, &token.v.string);
6698 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6699 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6700 cnst->wide_string.value = wres;
6709 * Parse a boolean constant.
6711 static expression_t *parse_bool_const(bool value)
6713 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6714 cnst->base.type = type_bool;
6715 cnst->conste.v.int_value = value;
6723 * Parse an integer constant.
6725 static expression_t *parse_int_const(void)
6727 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6728 cnst->base.type = token.datatype;
6729 cnst->conste.v.int_value = token.v.intvalue;
6737 * Parse a character constant.
6739 static expression_t *parse_character_constant(void)
6741 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6742 cnst->base.type = token.datatype;
6743 cnst->conste.v.character = token.v.string;
6745 if (cnst->conste.v.character.size != 1) {
6747 errorf(HERE, "more than 1 character in character constant");
6748 } else if (warning.multichar) {
6749 warningf(HERE, "multi-character character constant");
6758 * Parse a wide character constant.
6760 static expression_t *parse_wide_character_constant(void)
6762 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6763 cnst->base.type = token.datatype;
6764 cnst->conste.v.wide_character = token.v.wide_string;
6766 if (cnst->conste.v.wide_character.size != 1) {
6768 errorf(HERE, "more than 1 character in character constant");
6769 } else if (warning.multichar) {
6770 warningf(HERE, "multi-character character constant");
6779 * Parse a float constant.
6781 static expression_t *parse_float_const(void)
6783 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6784 cnst->base.type = token.datatype;
6785 cnst->conste.v.float_value = token.v.floatvalue;
6792 static entity_t *create_implicit_function(symbol_t *symbol,
6793 const source_position_t *source_position)
6795 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6796 ntype->function.return_type = type_int;
6797 ntype->function.unspecified_parameters = true;
6798 ntype->function.linkage = LINKAGE_C;
6800 type_t *type = typehash_insert(ntype);
6801 if (type != ntype) {
6805 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6806 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6807 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6808 entity->declaration.type = type;
6809 entity->declaration.implicit = true;
6810 entity->base.symbol = symbol;
6811 entity->base.source_position = *source_position;
6813 bool strict_prototypes_old = warning.strict_prototypes;
6814 warning.strict_prototypes = false;
6815 record_entity(entity, false);
6816 warning.strict_prototypes = strict_prototypes_old;
6822 * Creates a return_type (func)(argument_type) function type if not
6825 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6826 type_t *argument_type2)
6828 function_parameter_t *parameter2
6829 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6830 memset(parameter2, 0, sizeof(parameter2[0]));
6831 parameter2->type = argument_type2;
6833 function_parameter_t *parameter1
6834 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6835 memset(parameter1, 0, sizeof(parameter1[0]));
6836 parameter1->type = argument_type1;
6837 parameter1->next = parameter2;
6839 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6840 type->function.return_type = return_type;
6841 type->function.parameters = parameter1;
6843 type_t *result = typehash_insert(type);
6844 if (result != type) {
6852 * Creates a return_type (func)(argument_type) function type if not
6855 * @param return_type the return type
6856 * @param argument_type the argument type
6858 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6860 function_parameter_t *parameter
6861 = obstack_alloc(type_obst, sizeof(parameter[0]));
6862 memset(parameter, 0, sizeof(parameter[0]));
6863 parameter->type = argument_type;
6865 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6866 type->function.return_type = return_type;
6867 type->function.parameters = parameter;
6869 type_t *result = typehash_insert(type);
6870 if (result != type) {
6877 static type_t *make_function_0_type(type_t *return_type)
6879 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6880 type->function.return_type = return_type;
6881 type->function.parameters = NULL;
6883 type_t *result = typehash_insert(type);
6884 if (result != type) {
6892 * Creates a function type for some function like builtins.
6894 * @param symbol the symbol describing the builtin
6896 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6898 switch (symbol->ID) {
6899 case T___builtin_alloca:
6900 return make_function_1_type(type_void_ptr, type_size_t);
6901 case T___builtin_huge_val:
6902 return make_function_0_type(type_double);
6903 case T___builtin_inf:
6904 return make_function_0_type(type_double);
6905 case T___builtin_inff:
6906 return make_function_0_type(type_float);
6907 case T___builtin_infl:
6908 return make_function_0_type(type_long_double);
6909 case T___builtin_nan:
6910 return make_function_1_type(type_double, type_char_ptr);
6911 case T___builtin_nanf:
6912 return make_function_1_type(type_float, type_char_ptr);
6913 case T___builtin_nanl:
6914 return make_function_1_type(type_long_double, type_char_ptr);
6915 case T___builtin_va_end:
6916 return make_function_1_type(type_void, type_valist);
6917 case T___builtin_expect:
6918 return make_function_2_type(type_long, type_long, type_long);
6920 internal_errorf(HERE, "not implemented builtin identifier found");
6925 * Performs automatic type cast as described in § 6.3.2.1.
6927 * @param orig_type the original type
6929 static type_t *automatic_type_conversion(type_t *orig_type)
6931 type_t *type = skip_typeref(orig_type);
6932 if (is_type_array(type)) {
6933 array_type_t *array_type = &type->array;
6934 type_t *element_type = array_type->element_type;
6935 unsigned qualifiers = array_type->base.qualifiers;
6937 return make_pointer_type(element_type, qualifiers);
6940 if (is_type_function(type)) {
6941 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6948 * reverts the automatic casts of array to pointer types and function
6949 * to function-pointer types as defined § 6.3.2.1
6951 type_t *revert_automatic_type_conversion(const expression_t *expression)
6953 switch (expression->kind) {
6954 case EXPR_REFERENCE: {
6955 entity_t *entity = expression->reference.entity;
6956 if (is_declaration(entity)) {
6957 return entity->declaration.type;
6958 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6959 return entity->enum_value.enum_type;
6961 panic("no declaration or enum in reference");
6966 entity_t *entity = expression->select.compound_entry;
6967 assert(is_declaration(entity));
6968 type_t *type = entity->declaration.type;
6969 return get_qualified_type(type,
6970 expression->base.type->base.qualifiers);
6973 case EXPR_UNARY_DEREFERENCE: {
6974 const expression_t *const value = expression->unary.value;
6975 type_t *const type = skip_typeref(value->base.type);
6976 if (!is_type_pointer(type))
6977 return type_error_type;
6978 return type->pointer.points_to;
6981 case EXPR_BUILTIN_SYMBOL:
6982 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6984 case EXPR_ARRAY_ACCESS: {
6985 const expression_t *array_ref = expression->array_access.array_ref;
6986 type_t *type_left = skip_typeref(array_ref->base.type);
6987 if (!is_type_pointer(type_left))
6988 return type_error_type;
6989 return type_left->pointer.points_to;
6992 case EXPR_STRING_LITERAL: {
6993 size_t size = expression->string.value.size;
6994 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6997 case EXPR_WIDE_STRING_LITERAL: {
6998 size_t size = expression->wide_string.value.size;
6999 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
7002 case EXPR_COMPOUND_LITERAL:
7003 return expression->compound_literal.type;
7006 return expression->base.type;
7010 static expression_t *parse_reference(void)
7012 symbol_t *const symbol = token.v.symbol;
7014 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
7016 if (entity == NULL) {
7017 if (!strict_mode && look_ahead(1)->type == '(') {
7018 /* an implicitly declared function */
7019 if (warning.error_implicit_function_declaration) {
7020 errorf(HERE, "implicit declaration of function '%Y'", symbol);
7021 } else if (warning.implicit_function_declaration) {
7022 warningf(HERE, "implicit declaration of function '%Y'", symbol);
7025 entity = create_implicit_function(symbol, HERE);
7027 errorf(HERE, "unknown identifier '%Y' found.", symbol);
7028 entity = create_error_entity(symbol, ENTITY_VARIABLE);
7034 if (is_declaration(entity)) {
7035 orig_type = entity->declaration.type;
7036 } else if (entity->kind == ENTITY_ENUM_VALUE) {
7037 orig_type = entity->enum_value.enum_type;
7038 } else if (entity->kind == ENTITY_TYPEDEF) {
7039 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
7042 return create_invalid_expression();
7044 panic("expected declaration or enum value in reference");
7047 /* we always do the auto-type conversions; the & and sizeof parser contains
7048 * code to revert this! */
7049 type_t *type = automatic_type_conversion(orig_type);
7051 expression_kind_t kind = EXPR_REFERENCE;
7052 if (entity->kind == ENTITY_ENUM_VALUE)
7053 kind = EXPR_REFERENCE_ENUM_VALUE;
7055 expression_t *expression = allocate_expression_zero(kind);
7056 expression->reference.entity = entity;
7057 expression->base.type = type;
7059 /* this declaration is used */
7060 if (is_declaration(entity)) {
7061 entity->declaration.used = true;
7064 if (entity->base.parent_scope != file_scope
7065 && entity->base.parent_scope->depth < current_function->parameters.depth
7066 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
7067 if (entity->kind == ENTITY_VARIABLE) {
7068 /* access of a variable from an outer function */
7069 entity->variable.address_taken = true;
7070 } else if (entity->kind == ENTITY_PARAMETER) {
7071 entity->parameter.address_taken = true;
7073 current_function->need_closure = true;
7076 /* check for deprecated functions */
7077 if (warning.deprecated_declarations
7078 && is_declaration(entity)
7079 && entity->declaration.modifiers & DM_DEPRECATED) {
7080 declaration_t *declaration = &entity->declaration;
7082 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
7083 "function" : "variable";
7085 if (declaration->deprecated_string != NULL) {
7086 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
7087 prefix, entity->base.symbol, &entity->base.source_position,
7088 declaration->deprecated_string);
7090 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
7091 entity->base.symbol, &entity->base.source_position);
7095 if (warning.init_self && entity == current_init_decl && !in_type_prop
7096 && entity->kind == ENTITY_VARIABLE) {
7097 current_init_decl = NULL;
7098 warningf(HERE, "variable '%#T' is initialized by itself",
7099 entity->declaration.type, entity->base.symbol);
7106 static bool semantic_cast(expression_t *cast)
7108 expression_t *expression = cast->unary.value;
7109 type_t *orig_dest_type = cast->base.type;
7110 type_t *orig_type_right = expression->base.type;
7111 type_t const *dst_type = skip_typeref(orig_dest_type);
7112 type_t const *src_type = skip_typeref(orig_type_right);
7113 source_position_t const *pos = &cast->base.source_position;
7115 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
7116 if (dst_type == type_void)
7119 /* only integer and pointer can be casted to pointer */
7120 if (is_type_pointer(dst_type) &&
7121 !is_type_pointer(src_type) &&
7122 !is_type_integer(src_type) &&
7123 is_type_valid(src_type)) {
7124 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
7128 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
7129 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
7133 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
7134 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
7138 if (warning.cast_qual &&
7139 is_type_pointer(src_type) &&
7140 is_type_pointer(dst_type)) {
7141 type_t *src = skip_typeref(src_type->pointer.points_to);
7142 type_t *dst = skip_typeref(dst_type->pointer.points_to);
7143 unsigned missing_qualifiers =
7144 src->base.qualifiers & ~dst->base.qualifiers;
7145 if (missing_qualifiers != 0) {
7147 "cast discards qualifiers '%Q' in pointer target type of '%T'",
7148 missing_qualifiers, orig_type_right);
7154 static expression_t *parse_compound_literal(type_t *type)
7156 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
7158 parse_initializer_env_t env;
7161 env.must_be_constant = false;
7162 initializer_t *initializer = parse_initializer(&env);
7165 expression->compound_literal.initializer = initializer;
7166 expression->compound_literal.type = type;
7167 expression->base.type = automatic_type_conversion(type);
7173 * Parse a cast expression.
7175 static expression_t *parse_cast(void)
7177 add_anchor_token(')');
7179 source_position_t source_position = token.source_position;
7181 type_t *type = parse_typename();
7183 rem_anchor_token(')');
7184 expect(')', end_error);
7186 if (token.type == '{') {
7187 return parse_compound_literal(type);
7190 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
7191 cast->base.source_position = source_position;
7193 expression_t *value = parse_sub_expression(PREC_CAST);
7194 cast->base.type = type;
7195 cast->unary.value = value;
7197 if (! semantic_cast(cast)) {
7198 /* TODO: record the error in the AST. else it is impossible to detect it */
7203 return create_invalid_expression();
7207 * Parse a statement expression.
7209 static expression_t *parse_statement_expression(void)
7211 add_anchor_token(')');
7213 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
7215 statement_t *statement = parse_compound_statement(true);
7216 statement->compound.stmt_expr = true;
7217 expression->statement.statement = statement;
7219 /* find last statement and use its type */
7220 type_t *type = type_void;
7221 const statement_t *stmt = statement->compound.statements;
7223 while (stmt->base.next != NULL)
7224 stmt = stmt->base.next;
7226 if (stmt->kind == STATEMENT_EXPRESSION) {
7227 type = stmt->expression.expression->base.type;
7229 } else if (warning.other) {
7230 warningf(&expression->base.source_position, "empty statement expression ({})");
7232 expression->base.type = type;
7234 rem_anchor_token(')');
7235 expect(')', end_error);
7242 * Parse a parenthesized expression.
7244 static expression_t *parse_parenthesized_expression(void)
7248 switch (token.type) {
7250 /* gcc extension: a statement expression */
7251 return parse_statement_expression();
7255 return parse_cast();
7257 if (is_typedef_symbol(token.v.symbol)) {
7258 return parse_cast();
7262 add_anchor_token(')');
7263 expression_t *result = parse_expression();
7264 result->base.parenthesized = true;
7265 rem_anchor_token(')');
7266 expect(')', end_error);
7272 static expression_t *parse_function_keyword(void)
7276 if (current_function == NULL) {
7277 errorf(HERE, "'__func__' used outside of a function");
7280 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7281 expression->base.type = type_char_ptr;
7282 expression->funcname.kind = FUNCNAME_FUNCTION;
7289 static expression_t *parse_pretty_function_keyword(void)
7291 if (current_function == NULL) {
7292 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
7295 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7296 expression->base.type = type_char_ptr;
7297 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
7299 eat(T___PRETTY_FUNCTION__);
7304 static expression_t *parse_funcsig_keyword(void)
7306 if (current_function == NULL) {
7307 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7310 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7311 expression->base.type = type_char_ptr;
7312 expression->funcname.kind = FUNCNAME_FUNCSIG;
7319 static expression_t *parse_funcdname_keyword(void)
7321 if (current_function == NULL) {
7322 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7325 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7326 expression->base.type = type_char_ptr;
7327 expression->funcname.kind = FUNCNAME_FUNCDNAME;
7329 eat(T___FUNCDNAME__);
7334 static designator_t *parse_designator(void)
7336 designator_t *result = allocate_ast_zero(sizeof(result[0]));
7337 result->source_position = *HERE;
7339 if (token.type != T_IDENTIFIER) {
7340 parse_error_expected("while parsing member designator",
7341 T_IDENTIFIER, NULL);
7344 result->symbol = token.v.symbol;
7347 designator_t *last_designator = result;
7349 if (token.type == '.') {
7351 if (token.type != T_IDENTIFIER) {
7352 parse_error_expected("while parsing member designator",
7353 T_IDENTIFIER, NULL);
7356 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7357 designator->source_position = *HERE;
7358 designator->symbol = token.v.symbol;
7361 last_designator->next = designator;
7362 last_designator = designator;
7365 if (token.type == '[') {
7367 add_anchor_token(']');
7368 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7369 designator->source_position = *HERE;
7370 designator->array_index = parse_expression();
7371 rem_anchor_token(']');
7372 expect(']', end_error);
7373 if (designator->array_index == NULL) {
7377 last_designator->next = designator;
7378 last_designator = designator;
7390 * Parse the __builtin_offsetof() expression.
7392 static expression_t *parse_offsetof(void)
7394 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7395 expression->base.type = type_size_t;
7397 eat(T___builtin_offsetof);
7399 expect('(', end_error);
7400 add_anchor_token(',');
7401 type_t *type = parse_typename();
7402 rem_anchor_token(',');
7403 expect(',', end_error);
7404 add_anchor_token(')');
7405 designator_t *designator = parse_designator();
7406 rem_anchor_token(')');
7407 expect(')', end_error);
7409 expression->offsetofe.type = type;
7410 expression->offsetofe.designator = designator;
7413 memset(&path, 0, sizeof(path));
7414 path.top_type = type;
7415 path.path = NEW_ARR_F(type_path_entry_t, 0);
7417 descend_into_subtype(&path);
7419 if (!walk_designator(&path, designator, true)) {
7420 return create_invalid_expression();
7423 DEL_ARR_F(path.path);
7427 return create_invalid_expression();
7431 * Parses a _builtin_va_start() expression.
7433 static expression_t *parse_va_start(void)
7435 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7437 eat(T___builtin_va_start);
7439 expect('(', end_error);
7440 add_anchor_token(',');
7441 expression->va_starte.ap = parse_assignment_expression();
7442 rem_anchor_token(',');
7443 expect(',', end_error);
7444 expression_t *const expr = parse_assignment_expression();
7445 if (expr->kind == EXPR_REFERENCE) {
7446 entity_t *const entity = expr->reference.entity;
7447 if (entity->base.parent_scope != ¤t_function->parameters
7448 || entity->base.next != NULL
7449 || entity->kind != ENTITY_PARAMETER) {
7450 errorf(&expr->base.source_position,
7451 "second argument of 'va_start' must be last parameter of the current function");
7453 expression->va_starte.parameter = &entity->variable;
7455 expect(')', end_error);
7458 expect(')', end_error);
7460 return create_invalid_expression();
7464 * Parses a _builtin_va_arg() expression.
7466 static expression_t *parse_va_arg(void)
7468 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7470 eat(T___builtin_va_arg);
7472 expect('(', end_error);
7473 expression->va_arge.ap = parse_assignment_expression();
7474 expect(',', end_error);
7475 expression->base.type = parse_typename();
7476 expect(')', end_error);
7480 return create_invalid_expression();
7483 static expression_t *parse_builtin_symbol(void)
7485 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7487 symbol_t *symbol = token.v.symbol;
7489 expression->builtin_symbol.symbol = symbol;
7492 type_t *type = get_builtin_symbol_type(symbol);
7493 type = automatic_type_conversion(type);
7495 expression->base.type = type;
7500 * Parses a __builtin_constant() expression.
7502 static expression_t *parse_builtin_constant(void)
7504 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7506 eat(T___builtin_constant_p);
7508 expect('(', end_error);
7509 add_anchor_token(')');
7510 expression->builtin_constant.value = parse_assignment_expression();
7511 rem_anchor_token(')');
7512 expect(')', end_error);
7513 expression->base.type = type_int;
7517 return create_invalid_expression();
7521 * Parses a __builtin_prefetch() expression.
7523 static expression_t *parse_builtin_prefetch(void)
7525 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7527 eat(T___builtin_prefetch);
7529 expect('(', end_error);
7530 add_anchor_token(')');
7531 expression->builtin_prefetch.adr = parse_assignment_expression();
7532 if (token.type == ',') {
7534 expression->builtin_prefetch.rw = parse_assignment_expression();
7536 if (token.type == ',') {
7538 expression->builtin_prefetch.locality = parse_assignment_expression();
7540 rem_anchor_token(')');
7541 expect(')', end_error);
7542 expression->base.type = type_void;
7546 return create_invalid_expression();
7550 * Parses a __builtin_is_*() compare expression.
7552 static expression_t *parse_compare_builtin(void)
7554 expression_t *expression;
7556 switch (token.type) {
7557 case T___builtin_isgreater:
7558 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7560 case T___builtin_isgreaterequal:
7561 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7563 case T___builtin_isless:
7564 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7566 case T___builtin_islessequal:
7567 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7569 case T___builtin_islessgreater:
7570 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7572 case T___builtin_isunordered:
7573 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7576 internal_errorf(HERE, "invalid compare builtin found");
7578 expression->base.source_position = *HERE;
7581 expect('(', end_error);
7582 expression->binary.left = parse_assignment_expression();
7583 expect(',', end_error);
7584 expression->binary.right = parse_assignment_expression();
7585 expect(')', end_error);
7587 type_t *const orig_type_left = expression->binary.left->base.type;
7588 type_t *const orig_type_right = expression->binary.right->base.type;
7590 type_t *const type_left = skip_typeref(orig_type_left);
7591 type_t *const type_right = skip_typeref(orig_type_right);
7592 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7593 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7594 type_error_incompatible("invalid operands in comparison",
7595 &expression->base.source_position, orig_type_left, orig_type_right);
7598 semantic_comparison(&expression->binary);
7603 return create_invalid_expression();
7608 * Parses a __builtin_expect(, end_error) expression.
7610 static expression_t *parse_builtin_expect(void, end_error)
7612 expression_t *expression
7613 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7615 eat(T___builtin_expect);
7617 expect('(', end_error);
7618 expression->binary.left = parse_assignment_expression();
7619 expect(',', end_error);
7620 expression->binary.right = parse_constant_expression();
7621 expect(')', end_error);
7623 expression->base.type = expression->binary.left->base.type;
7627 return create_invalid_expression();
7632 * Parses a MS assume() expression.
7634 static expression_t *parse_assume(void)
7636 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7640 expect('(', end_error);
7641 add_anchor_token(')');
7642 expression->unary.value = parse_assignment_expression();
7643 rem_anchor_token(')');
7644 expect(')', end_error);
7646 expression->base.type = type_void;
7649 return create_invalid_expression();
7653 * Return the declaration for a given label symbol or create a new one.
7655 * @param symbol the symbol of the label
7657 static label_t *get_label(symbol_t *symbol)
7660 assert(current_function != NULL);
7662 label = get_entity(symbol, NAMESPACE_LABEL);
7663 /* if we found a local label, we already created the declaration */
7664 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7665 if (label->base.parent_scope != current_scope) {
7666 assert(label->base.parent_scope->depth < current_scope->depth);
7667 current_function->goto_to_outer = true;
7669 return &label->label;
7672 label = get_entity(symbol, NAMESPACE_LABEL);
7673 /* if we found a label in the same function, then we already created the
7676 && label->base.parent_scope == ¤t_function->parameters) {
7677 return &label->label;
7680 /* otherwise we need to create a new one */
7681 label = allocate_entity_zero(ENTITY_LABEL);
7682 label->base.namespc = NAMESPACE_LABEL;
7683 label->base.symbol = symbol;
7687 return &label->label;
7691 * Parses a GNU && label address expression.
7693 static expression_t *parse_label_address(void)
7695 source_position_t source_position = token.source_position;
7697 if (token.type != T_IDENTIFIER) {
7698 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7701 symbol_t *symbol = token.v.symbol;
7704 label_t *label = get_label(symbol);
7706 label->address_taken = true;
7708 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7709 expression->base.source_position = source_position;
7711 /* label address is threaten as a void pointer */
7712 expression->base.type = type_void_ptr;
7713 expression->label_address.label = label;
7716 return create_invalid_expression();
7720 * Parse a microsoft __noop expression.
7722 static expression_t *parse_noop_expression(void)
7724 /* the result is a (int)0 */
7725 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7726 cnst->base.type = type_int;
7727 cnst->conste.v.int_value = 0;
7728 cnst->conste.is_ms_noop = true;
7732 if (token.type == '(') {
7733 /* parse arguments */
7735 add_anchor_token(')');
7736 add_anchor_token(',');
7738 if (token.type != ')') {
7740 (void)parse_assignment_expression();
7741 if (token.type != ',')
7747 rem_anchor_token(',');
7748 rem_anchor_token(')');
7749 expect(')', end_error);
7756 * Parses a primary expression.
7758 static expression_t *parse_primary_expression(void)
7760 switch (token.type) {
7761 case T_false: return parse_bool_const(false);
7762 case T_true: return parse_bool_const(true);
7763 case T_INTEGER: return parse_int_const();
7764 case T_CHARACTER_CONSTANT: return parse_character_constant();
7765 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7766 case T_FLOATINGPOINT: return parse_float_const();
7767 case T_STRING_LITERAL:
7768 case T_WIDE_STRING_LITERAL: return parse_string_const();
7769 case T_IDENTIFIER: return parse_reference();
7770 case T___FUNCTION__:
7771 case T___func__: return parse_function_keyword();
7772 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7773 case T___FUNCSIG__: return parse_funcsig_keyword();
7774 case T___FUNCDNAME__: return parse_funcdname_keyword();
7775 case T___builtin_offsetof: return parse_offsetof();
7776 case T___builtin_va_start: return parse_va_start();
7777 case T___builtin_va_arg: return parse_va_arg();
7778 case T___builtin_expect:
7779 case T___builtin_alloca:
7780 case T___builtin_inf:
7781 case T___builtin_inff:
7782 case T___builtin_infl:
7783 case T___builtin_nan:
7784 case T___builtin_nanf:
7785 case T___builtin_nanl:
7786 case T___builtin_huge_val:
7787 case T___builtin_va_end: return parse_builtin_symbol();
7788 case T___builtin_isgreater:
7789 case T___builtin_isgreaterequal:
7790 case T___builtin_isless:
7791 case T___builtin_islessequal:
7792 case T___builtin_islessgreater:
7793 case T___builtin_isunordered: return parse_compare_builtin();
7794 case T___builtin_constant_p: return parse_builtin_constant();
7795 case T___builtin_prefetch: return parse_builtin_prefetch();
7796 case T__assume: return parse_assume();
7799 return parse_label_address();
7802 case '(': return parse_parenthesized_expression();
7803 case T___noop: return parse_noop_expression();
7806 errorf(HERE, "unexpected token %K, expected an expression", &token);
7807 return create_invalid_expression();
7811 * Check if the expression has the character type and issue a warning then.
7813 static void check_for_char_index_type(const expression_t *expression)
7815 type_t *const type = expression->base.type;
7816 const type_t *const base_type = skip_typeref(type);
7818 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7819 warning.char_subscripts) {
7820 warningf(&expression->base.source_position,
7821 "array subscript has type '%T'", type);
7825 static expression_t *parse_array_expression(expression_t *left)
7827 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7830 add_anchor_token(']');
7832 expression_t *inside = parse_expression();
7834 type_t *const orig_type_left = left->base.type;
7835 type_t *const orig_type_inside = inside->base.type;
7837 type_t *const type_left = skip_typeref(orig_type_left);
7838 type_t *const type_inside = skip_typeref(orig_type_inside);
7840 type_t *return_type;
7841 array_access_expression_t *array_access = &expression->array_access;
7842 if (is_type_pointer(type_left)) {
7843 return_type = type_left->pointer.points_to;
7844 array_access->array_ref = left;
7845 array_access->index = inside;
7846 check_for_char_index_type(inside);
7847 } else if (is_type_pointer(type_inside)) {
7848 return_type = type_inside->pointer.points_to;
7849 array_access->array_ref = inside;
7850 array_access->index = left;
7851 array_access->flipped = true;
7852 check_for_char_index_type(left);
7854 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7856 "array access on object with non-pointer types '%T', '%T'",
7857 orig_type_left, orig_type_inside);
7859 return_type = type_error_type;
7860 array_access->array_ref = left;
7861 array_access->index = inside;
7864 expression->base.type = automatic_type_conversion(return_type);
7866 rem_anchor_token(']');
7867 expect(']', end_error);
7872 static expression_t *parse_typeprop(expression_kind_t const kind)
7874 expression_t *tp_expression = allocate_expression_zero(kind);
7875 tp_expression->base.type = type_size_t;
7877 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7879 /* we only refer to a type property, mark this case */
7880 bool old = in_type_prop;
7881 in_type_prop = true;
7884 expression_t *expression;
7885 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7887 add_anchor_token(')');
7888 orig_type = parse_typename();
7889 rem_anchor_token(')');
7890 expect(')', end_error);
7892 if (token.type == '{') {
7893 /* It was not sizeof(type) after all. It is sizeof of an expression
7894 * starting with a compound literal */
7895 expression = parse_compound_literal(orig_type);
7896 goto typeprop_expression;
7899 expression = parse_sub_expression(PREC_UNARY);
7901 typeprop_expression:
7902 tp_expression->typeprop.tp_expression = expression;
7904 orig_type = revert_automatic_type_conversion(expression);
7905 expression->base.type = orig_type;
7908 tp_expression->typeprop.type = orig_type;
7909 type_t const* const type = skip_typeref(orig_type);
7910 char const* const wrong_type =
7911 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7912 is_type_incomplete(type) ? "incomplete" :
7913 type->kind == TYPE_FUNCTION ? "function designator" :
7914 type->kind == TYPE_BITFIELD ? "bitfield" :
7916 if (wrong_type != NULL) {
7917 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7918 errorf(&tp_expression->base.source_position,
7919 "operand of %s expression must not be of %s type '%T'",
7920 what, wrong_type, orig_type);
7925 return tp_expression;
7928 static expression_t *parse_sizeof(void)
7930 return parse_typeprop(EXPR_SIZEOF);
7933 static expression_t *parse_alignof(void)
7935 return parse_typeprop(EXPR_ALIGNOF);
7938 static expression_t *parse_select_expression(expression_t *compound)
7940 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7941 select->select.compound = compound;
7943 assert(token.type == '.' || token.type == T_MINUSGREATER);
7944 bool is_pointer = (token.type == T_MINUSGREATER);
7947 if (token.type != T_IDENTIFIER) {
7948 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7951 symbol_t *symbol = token.v.symbol;
7954 type_t *const orig_type = compound->base.type;
7955 type_t *const type = skip_typeref(orig_type);
7958 bool saw_error = false;
7959 if (is_type_pointer(type)) {
7962 "request for member '%Y' in something not a struct or union, but '%T'",
7966 type_left = skip_typeref(type->pointer.points_to);
7968 if (is_pointer && is_type_valid(type)) {
7969 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7976 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7977 type_left->kind == TYPE_COMPOUND_UNION) {
7978 compound_t *compound = type_left->compound.compound;
7980 if (!compound->complete) {
7981 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7983 goto create_error_entry;
7986 entry = find_compound_entry(compound, symbol);
7987 if (entry == NULL) {
7988 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7989 goto create_error_entry;
7992 if (is_type_valid(type_left) && !saw_error) {
7994 "request for member '%Y' in something not a struct or union, but '%T'",
7998 entry = create_error_entity(symbol, ENTITY_COMPOUND_MEMBER);
8001 assert(is_declaration(entry));
8002 select->select.compound_entry = entry;
8004 type_t *entry_type = entry->declaration.type;
8006 = get_qualified_type(entry_type, type_left->base.qualifiers);
8008 /* we always do the auto-type conversions; the & and sizeof parser contains
8009 * code to revert this! */
8010 select->base.type = automatic_type_conversion(res_type);
8012 type_t *skipped = skip_typeref(res_type);
8013 if (skipped->kind == TYPE_BITFIELD) {
8014 select->base.type = skipped->bitfield.base_type;
8020 static void check_call_argument(const function_parameter_t *parameter,
8021 call_argument_t *argument, unsigned pos)
8023 type_t *expected_type = parameter->type;
8024 type_t *expected_type_skip = skip_typeref(expected_type);
8025 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
8026 expression_t *arg_expr = argument->expression;
8027 type_t *arg_type = skip_typeref(arg_expr->base.type);
8029 /* handle transparent union gnu extension */
8030 if (is_type_union(expected_type_skip)
8031 && (expected_type_skip->base.modifiers
8032 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
8033 compound_t *union_decl = expected_type_skip->compound.compound;
8034 type_t *best_type = NULL;
8035 entity_t *entry = union_decl->members.entities;
8036 for ( ; entry != NULL; entry = entry->base.next) {
8037 assert(is_declaration(entry));
8038 type_t *decl_type = entry->declaration.type;
8039 error = semantic_assign(decl_type, arg_expr);
8040 if (error == ASSIGN_ERROR_INCOMPATIBLE
8041 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
8044 if (error == ASSIGN_SUCCESS) {
8045 best_type = decl_type;
8046 } else if (best_type == NULL) {
8047 best_type = decl_type;
8051 if (best_type != NULL) {
8052 expected_type = best_type;
8056 error = semantic_assign(expected_type, arg_expr);
8057 argument->expression = create_implicit_cast(argument->expression,
8060 if (error != ASSIGN_SUCCESS) {
8061 /* report exact scope in error messages (like "in argument 3") */
8063 snprintf(buf, sizeof(buf), "call argument %u", pos);
8064 report_assign_error(error, expected_type, arg_expr, buf,
8065 &arg_expr->base.source_position);
8066 } else if (warning.traditional || warning.conversion) {
8067 type_t *const promoted_type = get_default_promoted_type(arg_type);
8068 if (!types_compatible(expected_type_skip, promoted_type) &&
8069 !types_compatible(expected_type_skip, type_void_ptr) &&
8070 !types_compatible(type_void_ptr, promoted_type)) {
8071 /* Deliberately show the skipped types in this warning */
8072 warningf(&arg_expr->base.source_position,
8073 "passing call argument %u as '%T' rather than '%T' due to prototype",
8074 pos, expected_type_skip, promoted_type);
8080 * Parse a call expression, ie. expression '( ... )'.
8082 * @param expression the function address
8084 static expression_t *parse_call_expression(expression_t *expression)
8086 expression_t *result = allocate_expression_zero(EXPR_CALL);
8087 call_expression_t *call = &result->call;
8088 call->function = expression;
8090 type_t *const orig_type = expression->base.type;
8091 type_t *const type = skip_typeref(orig_type);
8093 function_type_t *function_type = NULL;
8094 if (is_type_pointer(type)) {
8095 type_t *const to_type = skip_typeref(type->pointer.points_to);
8097 if (is_type_function(to_type)) {
8098 function_type = &to_type->function;
8099 call->base.type = function_type->return_type;
8103 if (function_type == NULL && is_type_valid(type)) {
8104 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
8107 /* parse arguments */
8109 add_anchor_token(')');
8110 add_anchor_token(',');
8112 if (token.type != ')') {
8113 call_argument_t *last_argument = NULL;
8116 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8118 argument->expression = parse_assignment_expression();
8119 if (last_argument == NULL) {
8120 call->arguments = argument;
8122 last_argument->next = argument;
8124 last_argument = argument;
8126 if (token.type != ',')
8131 rem_anchor_token(',');
8132 rem_anchor_token(')');
8133 expect(')', end_error);
8135 if (function_type == NULL)
8138 function_parameter_t *parameter = function_type->parameters;
8139 call_argument_t *argument = call->arguments;
8140 if (!function_type->unspecified_parameters) {
8141 for (unsigned pos = 0; parameter != NULL && argument != NULL;
8142 parameter = parameter->next, argument = argument->next) {
8143 check_call_argument(parameter, argument, ++pos);
8146 if (parameter != NULL) {
8147 errorf(HERE, "too few arguments to function '%E'", expression);
8148 } else if (argument != NULL && !function_type->variadic) {
8149 errorf(HERE, "too many arguments to function '%E'", expression);
8153 /* do default promotion */
8154 for (; argument != NULL; argument = argument->next) {
8155 type_t *type = argument->expression->base.type;
8157 type = get_default_promoted_type(type);
8159 argument->expression
8160 = create_implicit_cast(argument->expression, type);
8163 check_format(&result->call);
8165 if (warning.aggregate_return &&
8166 is_type_compound(skip_typeref(function_type->return_type))) {
8167 warningf(&result->base.source_position,
8168 "function call has aggregate value");
8175 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
8177 static bool same_compound_type(const type_t *type1, const type_t *type2)
8180 is_type_compound(type1) &&
8181 type1->kind == type2->kind &&
8182 type1->compound.compound == type2->compound.compound;
8185 static expression_t const *get_reference_address(expression_t const *expr)
8187 bool regular_take_address = true;
8189 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8190 expr = expr->unary.value;
8192 regular_take_address = false;
8195 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8198 expr = expr->unary.value;
8201 if (expr->kind != EXPR_REFERENCE)
8204 /* special case for functions which are automatically converted to a
8205 * pointer to function without an extra TAKE_ADDRESS operation */
8206 if (!regular_take_address &&
8207 expr->reference.entity->kind != ENTITY_FUNCTION) {
8214 static void warn_reference_address_as_bool(expression_t const* expr)
8216 if (!warning.address)
8219 expr = get_reference_address(expr);
8221 warningf(&expr->base.source_position,
8222 "the address of '%Y' will always evaluate as 'true'",
8223 expr->reference.entity->base.symbol);
8227 static void warn_assignment_in_condition(const expression_t *const expr)
8229 if (!warning.parentheses)
8231 if (expr->base.kind != EXPR_BINARY_ASSIGN)
8233 if (expr->base.parenthesized)
8235 warningf(&expr->base.source_position,
8236 "suggest parentheses around assignment used as truth value");
8239 static void semantic_condition(expression_t const *const expr,
8240 char const *const context)
8242 type_t *const type = skip_typeref(expr->base.type);
8243 if (is_type_scalar(type)) {
8244 warn_reference_address_as_bool(expr);
8245 warn_assignment_in_condition(expr);
8246 } else if (is_type_valid(type)) {
8247 errorf(&expr->base.source_position,
8248 "%s must have scalar type", context);
8253 * Parse a conditional expression, ie. 'expression ? ... : ...'.
8255 * @param expression the conditional expression
8257 static expression_t *parse_conditional_expression(expression_t *expression)
8259 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
8261 conditional_expression_t *conditional = &result->conditional;
8262 conditional->condition = expression;
8265 add_anchor_token(':');
8267 /* §6.5.15:2 The first operand shall have scalar type. */
8268 semantic_condition(expression, "condition of conditional operator");
8270 expression_t *true_expression = expression;
8271 bool gnu_cond = false;
8272 if (GNU_MODE && token.type == ':') {
8275 true_expression = parse_expression();
8277 rem_anchor_token(':');
8278 expect(':', end_error);
8280 expression_t *false_expression =
8281 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
8283 type_t *const orig_true_type = true_expression->base.type;
8284 type_t *const orig_false_type = false_expression->base.type;
8285 type_t *const true_type = skip_typeref(orig_true_type);
8286 type_t *const false_type = skip_typeref(orig_false_type);
8289 type_t *result_type;
8290 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8291 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
8292 /* ISO/IEC 14882:1998(E) §5.16:2 */
8293 if (true_expression->kind == EXPR_UNARY_THROW) {
8294 result_type = false_type;
8295 } else if (false_expression->kind == EXPR_UNARY_THROW) {
8296 result_type = true_type;
8298 if (warning.other && (
8299 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8300 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
8302 warningf(&conditional->base.source_position,
8303 "ISO C forbids conditional expression with only one void side");
8305 result_type = type_void;
8307 } else if (is_type_arithmetic(true_type)
8308 && is_type_arithmetic(false_type)) {
8309 result_type = semantic_arithmetic(true_type, false_type);
8311 true_expression = create_implicit_cast(true_expression, result_type);
8312 false_expression = create_implicit_cast(false_expression, result_type);
8314 conditional->true_expression = true_expression;
8315 conditional->false_expression = false_expression;
8316 conditional->base.type = result_type;
8317 } else if (same_compound_type(true_type, false_type)) {
8318 /* just take 1 of the 2 types */
8319 result_type = true_type;
8320 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
8321 type_t *pointer_type;
8323 expression_t *other_expression;
8324 if (is_type_pointer(true_type) &&
8325 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
8326 pointer_type = true_type;
8327 other_type = false_type;
8328 other_expression = false_expression;
8330 pointer_type = false_type;
8331 other_type = true_type;
8332 other_expression = true_expression;
8335 if (is_null_pointer_constant(other_expression)) {
8336 result_type = pointer_type;
8337 } else if (is_type_pointer(other_type)) {
8338 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8339 type_t *to2 = skip_typeref(other_type->pointer.points_to);
8342 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8343 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8345 } else if (types_compatible(get_unqualified_type(to1),
8346 get_unqualified_type(to2))) {
8349 if (warning.other) {
8350 warningf(&conditional->base.source_position,
8351 "pointer types '%T' and '%T' in conditional expression are incompatible",
8352 true_type, false_type);
8357 type_t *const type =
8358 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8359 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8360 } else if (is_type_integer(other_type)) {
8361 if (warning.other) {
8362 warningf(&conditional->base.source_position,
8363 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8365 result_type = pointer_type;
8367 if (is_type_valid(other_type)) {
8368 type_error_incompatible("while parsing conditional",
8369 &expression->base.source_position, true_type, false_type);
8371 result_type = type_error_type;
8374 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8375 type_error_incompatible("while parsing conditional",
8376 &conditional->base.source_position, true_type,
8379 result_type = type_error_type;
8382 conditional->true_expression
8383 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8384 conditional->false_expression
8385 = create_implicit_cast(false_expression, result_type);
8386 conditional->base.type = result_type;
8391 * Parse an extension expression.
8393 static expression_t *parse_extension(void)
8395 eat(T___extension__);
8397 bool old_gcc_extension = in_gcc_extension;
8398 in_gcc_extension = true;
8399 expression_t *expression = parse_sub_expression(PREC_UNARY);
8400 in_gcc_extension = old_gcc_extension;
8405 * Parse a __builtin_classify_type() expression.
8407 static expression_t *parse_builtin_classify_type(void)
8409 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8410 result->base.type = type_int;
8412 eat(T___builtin_classify_type);
8414 expect('(', end_error);
8415 add_anchor_token(')');
8416 expression_t *expression = parse_expression();
8417 rem_anchor_token(')');
8418 expect(')', end_error);
8419 result->classify_type.type_expression = expression;
8423 return create_invalid_expression();
8427 * Parse a delete expression
8428 * ISO/IEC 14882:1998(E) §5.3.5
8430 static expression_t *parse_delete(void)
8432 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8433 result->base.type = type_void;
8437 if (token.type == '[') {
8439 result->kind = EXPR_UNARY_DELETE_ARRAY;
8440 expect(']', end_error);
8444 expression_t *const value = parse_sub_expression(PREC_CAST);
8445 result->unary.value = value;
8447 type_t *const type = skip_typeref(value->base.type);
8448 if (!is_type_pointer(type)) {
8449 if (is_type_valid(type)) {
8450 errorf(&value->base.source_position,
8451 "operand of delete must have pointer type");
8453 } else if (warning.other &&
8454 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8455 warningf(&value->base.source_position,
8456 "deleting 'void*' is undefined");
8463 * Parse a throw expression
8464 * ISO/IEC 14882:1998(E) §15:1
8466 static expression_t *parse_throw(void)
8468 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8469 result->base.type = type_void;
8473 expression_t *value = NULL;
8474 switch (token.type) {
8476 value = parse_assignment_expression();
8477 /* ISO/IEC 14882:1998(E) §15.1:3 */
8478 type_t *const orig_type = value->base.type;
8479 type_t *const type = skip_typeref(orig_type);
8480 if (is_type_incomplete(type)) {
8481 errorf(&value->base.source_position,
8482 "cannot throw object of incomplete type '%T'", orig_type);
8483 } else if (is_type_pointer(type)) {
8484 type_t *const points_to = skip_typeref(type->pointer.points_to);
8485 if (is_type_incomplete(points_to) &&
8486 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8487 errorf(&value->base.source_position,
8488 "cannot throw pointer to incomplete type '%T'", orig_type);
8496 result->unary.value = value;
8501 static bool check_pointer_arithmetic(const source_position_t *source_position,
8502 type_t *pointer_type,
8503 type_t *orig_pointer_type)
8505 type_t *points_to = pointer_type->pointer.points_to;
8506 points_to = skip_typeref(points_to);
8508 if (is_type_incomplete(points_to)) {
8509 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8510 errorf(source_position,
8511 "arithmetic with pointer to incomplete type '%T' not allowed",
8514 } else if (warning.pointer_arith) {
8515 warningf(source_position,
8516 "pointer of type '%T' used in arithmetic",
8519 } else if (is_type_function(points_to)) {
8521 errorf(source_position,
8522 "arithmetic with pointer to function type '%T' not allowed",
8525 } else if (warning.pointer_arith) {
8526 warningf(source_position,
8527 "pointer to a function '%T' used in arithmetic",
8534 static bool is_lvalue(const expression_t *expression)
8536 /* TODO: doesn't seem to be consistent with §6.3.2.1 (1) */
8537 switch (expression->kind) {
8538 case EXPR_ARRAY_ACCESS:
8539 case EXPR_COMPOUND_LITERAL:
8540 case EXPR_REFERENCE:
8542 case EXPR_UNARY_DEREFERENCE:
8546 type_t *type = skip_typeref(expression->base.type);
8548 /* ISO/IEC 14882:1998(E) §3.10:3 */
8549 is_type_reference(type) ||
8550 /* Claim it is an lvalue, if the type is invalid. There was a parse
8551 * error before, which maybe prevented properly recognizing it as
8553 !is_type_valid(type);
8558 static void semantic_incdec(unary_expression_t *expression)
8560 type_t *const orig_type = expression->value->base.type;
8561 type_t *const type = skip_typeref(orig_type);
8562 if (is_type_pointer(type)) {
8563 if (!check_pointer_arithmetic(&expression->base.source_position,
8567 } else if (!is_type_real(type) && is_type_valid(type)) {
8568 /* TODO: improve error message */
8569 errorf(&expression->base.source_position,
8570 "operation needs an arithmetic or pointer type");
8573 if (!is_lvalue(expression->value)) {
8574 /* TODO: improve error message */
8575 errorf(&expression->base.source_position, "lvalue required as operand");
8577 expression->base.type = orig_type;
8580 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8582 type_t *const orig_type = expression->value->base.type;
8583 type_t *const type = skip_typeref(orig_type);
8584 if (!is_type_arithmetic(type)) {
8585 if (is_type_valid(type)) {
8586 /* TODO: improve error message */
8587 errorf(&expression->base.source_position,
8588 "operation needs an arithmetic type");
8593 expression->base.type = orig_type;
8596 static void semantic_unexpr_plus(unary_expression_t *expression)
8598 semantic_unexpr_arithmetic(expression);
8599 if (warning.traditional)
8600 warningf(&expression->base.source_position,
8601 "traditional C rejects the unary plus operator");
8604 static void semantic_not(unary_expression_t *expression)
8606 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8607 semantic_condition(expression->value, "operand of !");
8608 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8611 static void semantic_unexpr_integer(unary_expression_t *expression)
8613 type_t *const orig_type = expression->value->base.type;
8614 type_t *const type = skip_typeref(orig_type);
8615 if (!is_type_integer(type)) {
8616 if (is_type_valid(type)) {
8617 errorf(&expression->base.source_position,
8618 "operand of ~ must be of integer type");
8623 expression->base.type = orig_type;
8626 static void semantic_dereference(unary_expression_t *expression)
8628 type_t *const orig_type = expression->value->base.type;
8629 type_t *const type = skip_typeref(orig_type);
8630 if (!is_type_pointer(type)) {
8631 if (is_type_valid(type)) {
8632 errorf(&expression->base.source_position,
8633 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8638 type_t *result_type = type->pointer.points_to;
8639 result_type = automatic_type_conversion(result_type);
8640 expression->base.type = result_type;
8644 * Record that an address is taken (expression represents an lvalue).
8646 * @param expression the expression
8647 * @param may_be_register if true, the expression might be an register
8649 static void set_address_taken(expression_t *expression, bool may_be_register)
8651 if (expression->kind != EXPR_REFERENCE)
8654 entity_t *const entity = expression->reference.entity;
8656 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8659 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8660 && !may_be_register) {
8661 errorf(&expression->base.source_position,
8662 "address of register %s '%Y' requested",
8663 get_entity_kind_name(entity->kind), entity->base.symbol);
8666 if (entity->kind == ENTITY_VARIABLE) {
8667 entity->variable.address_taken = true;
8669 assert(entity->kind == ENTITY_PARAMETER);
8670 entity->parameter.address_taken = true;
8675 * Check the semantic of the address taken expression.
8677 static void semantic_take_addr(unary_expression_t *expression)
8679 expression_t *value = expression->value;
8680 value->base.type = revert_automatic_type_conversion(value);
8682 type_t *orig_type = value->base.type;
8683 type_t *type = skip_typeref(orig_type);
8684 if (!is_type_valid(type))
8688 if (!is_lvalue(value)) {
8689 errorf(&expression->base.source_position, "'&' requires an lvalue");
8691 if (type->kind == TYPE_BITFIELD) {
8692 errorf(&expression->base.source_position,
8693 "'&' not allowed on object with bitfield type '%T'",
8697 set_address_taken(value, false);
8699 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8702 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8703 static expression_t *parse_##unexpression_type(void) \
8705 expression_t *unary_expression \
8706 = allocate_expression_zero(unexpression_type); \
8708 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8710 sfunc(&unary_expression->unary); \
8712 return unary_expression; \
8715 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8716 semantic_unexpr_arithmetic)
8717 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8718 semantic_unexpr_plus)
8719 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8721 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8722 semantic_dereference)
8723 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8725 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8726 semantic_unexpr_integer)
8727 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8729 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8732 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8734 static expression_t *parse_##unexpression_type(expression_t *left) \
8736 expression_t *unary_expression \
8737 = allocate_expression_zero(unexpression_type); \
8739 unary_expression->unary.value = left; \
8741 sfunc(&unary_expression->unary); \
8743 return unary_expression; \
8746 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8747 EXPR_UNARY_POSTFIX_INCREMENT,
8749 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8750 EXPR_UNARY_POSTFIX_DECREMENT,
8753 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8755 /* TODO: handle complex + imaginary types */
8757 type_left = get_unqualified_type(type_left);
8758 type_right = get_unqualified_type(type_right);
8760 /* § 6.3.1.8 Usual arithmetic conversions */
8761 if (type_left == type_long_double || type_right == type_long_double) {
8762 return type_long_double;
8763 } else if (type_left == type_double || type_right == type_double) {
8765 } else if (type_left == type_float || type_right == type_float) {
8769 type_left = promote_integer(type_left);
8770 type_right = promote_integer(type_right);
8772 if (type_left == type_right)
8775 bool const signed_left = is_type_signed(type_left);
8776 bool const signed_right = is_type_signed(type_right);
8777 int const rank_left = get_rank(type_left);
8778 int const rank_right = get_rank(type_right);
8780 if (signed_left == signed_right)
8781 return rank_left >= rank_right ? type_left : type_right;
8790 u_rank = rank_right;
8791 u_type = type_right;
8793 s_rank = rank_right;
8794 s_type = type_right;
8799 if (u_rank >= s_rank)
8802 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8804 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8805 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8809 case ATOMIC_TYPE_INT: return type_unsigned_int;
8810 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8811 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8813 default: panic("invalid atomic type");
8818 * Check the semantic restrictions for a binary expression.
8820 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8822 expression_t *const left = expression->left;
8823 expression_t *const right = expression->right;
8824 type_t *const orig_type_left = left->base.type;
8825 type_t *const orig_type_right = right->base.type;
8826 type_t *const type_left = skip_typeref(orig_type_left);
8827 type_t *const type_right = skip_typeref(orig_type_right);
8829 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8830 /* TODO: improve error message */
8831 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8832 errorf(&expression->base.source_position,
8833 "operation needs arithmetic types");
8838 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8839 expression->left = create_implicit_cast(left, arithmetic_type);
8840 expression->right = create_implicit_cast(right, arithmetic_type);
8841 expression->base.type = arithmetic_type;
8844 static void warn_div_by_zero(binary_expression_t const *const expression)
8846 if (!warning.div_by_zero ||
8847 !is_type_integer(expression->base.type))
8850 expression_t const *const right = expression->right;
8851 /* The type of the right operand can be different for /= */
8852 if (is_type_integer(right->base.type) &&
8853 is_constant_expression(right) &&
8854 fold_constant(right) == 0) {
8855 warningf(&expression->base.source_position, "division by zero");
8860 * Check the semantic restrictions for a div/mod expression.
8862 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8863 semantic_binexpr_arithmetic(expression);
8864 warn_div_by_zero(expression);
8867 static void warn_addsub_in_shift(const expression_t *const expr)
8869 if (expr->base.parenthesized)
8873 switch (expr->kind) {
8874 case EXPR_BINARY_ADD: op = '+'; break;
8875 case EXPR_BINARY_SUB: op = '-'; break;
8879 warningf(&expr->base.source_position,
8880 "suggest parentheses around '%c' inside shift", op);
8883 static void semantic_shift_op(binary_expression_t *expression)
8885 expression_t *const left = expression->left;
8886 expression_t *const right = expression->right;
8887 type_t *const orig_type_left = left->base.type;
8888 type_t *const orig_type_right = right->base.type;
8889 type_t * type_left = skip_typeref(orig_type_left);
8890 type_t * type_right = skip_typeref(orig_type_right);
8892 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8893 /* TODO: improve error message */
8894 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8895 errorf(&expression->base.source_position,
8896 "operands of shift operation must have integer types");
8901 if (warning.parentheses) {
8902 warn_addsub_in_shift(left);
8903 warn_addsub_in_shift(right);
8906 type_left = promote_integer(type_left);
8907 type_right = promote_integer(type_right);
8909 expression->left = create_implicit_cast(left, type_left);
8910 expression->right = create_implicit_cast(right, type_right);
8911 expression->base.type = type_left;
8914 static void semantic_add(binary_expression_t *expression)
8916 expression_t *const left = expression->left;
8917 expression_t *const right = expression->right;
8918 type_t *const orig_type_left = left->base.type;
8919 type_t *const orig_type_right = right->base.type;
8920 type_t *const type_left = skip_typeref(orig_type_left);
8921 type_t *const type_right = skip_typeref(orig_type_right);
8924 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8925 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8926 expression->left = create_implicit_cast(left, arithmetic_type);
8927 expression->right = create_implicit_cast(right, arithmetic_type);
8928 expression->base.type = arithmetic_type;
8929 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8930 check_pointer_arithmetic(&expression->base.source_position,
8931 type_left, orig_type_left);
8932 expression->base.type = type_left;
8933 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8934 check_pointer_arithmetic(&expression->base.source_position,
8935 type_right, orig_type_right);
8936 expression->base.type = type_right;
8937 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8938 errorf(&expression->base.source_position,
8939 "invalid operands to binary + ('%T', '%T')",
8940 orig_type_left, orig_type_right);
8944 static void semantic_sub(binary_expression_t *expression)
8946 expression_t *const left = expression->left;
8947 expression_t *const right = expression->right;
8948 type_t *const orig_type_left = left->base.type;
8949 type_t *const orig_type_right = right->base.type;
8950 type_t *const type_left = skip_typeref(orig_type_left);
8951 type_t *const type_right = skip_typeref(orig_type_right);
8952 source_position_t const *const pos = &expression->base.source_position;
8955 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8956 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8957 expression->left = create_implicit_cast(left, arithmetic_type);
8958 expression->right = create_implicit_cast(right, arithmetic_type);
8959 expression->base.type = arithmetic_type;
8960 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8961 check_pointer_arithmetic(&expression->base.source_position,
8962 type_left, orig_type_left);
8963 expression->base.type = type_left;
8964 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8965 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8966 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8967 if (!types_compatible(unqual_left, unqual_right)) {
8969 "subtracting pointers to incompatible types '%T' and '%T'",
8970 orig_type_left, orig_type_right);
8971 } else if (!is_type_object(unqual_left)) {
8972 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8973 errorf(pos, "subtracting pointers to non-object types '%T'",
8975 } else if (warning.other) {
8976 warningf(pos, "subtracting pointers to void");
8979 expression->base.type = type_ptrdiff_t;
8980 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8981 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8982 orig_type_left, orig_type_right);
8986 static void warn_string_literal_address(expression_t const* expr)
8988 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8989 expr = expr->unary.value;
8990 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8992 expr = expr->unary.value;
8995 if (expr->kind == EXPR_STRING_LITERAL ||
8996 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8997 warningf(&expr->base.source_position,
8998 "comparison with string literal results in unspecified behaviour");
9002 static void warn_comparison_in_comparison(const expression_t *const expr)
9004 if (expr->base.parenthesized)
9006 switch (expr->base.kind) {
9007 case EXPR_BINARY_LESS:
9008 case EXPR_BINARY_GREATER:
9009 case EXPR_BINARY_LESSEQUAL:
9010 case EXPR_BINARY_GREATEREQUAL:
9011 case EXPR_BINARY_NOTEQUAL:
9012 case EXPR_BINARY_EQUAL:
9013 warningf(&expr->base.source_position,
9014 "comparisons like 'x <= y < z' do not have their mathematical meaning");
9021 static bool maybe_negative(expression_t const *const expr)
9024 !is_constant_expression(expr) ||
9025 fold_constant(expr) < 0;
9029 * Check the semantics of comparison expressions.
9031 * @param expression The expression to check.
9033 static void semantic_comparison(binary_expression_t *expression)
9035 expression_t *left = expression->left;
9036 expression_t *right = expression->right;
9038 if (warning.address) {
9039 warn_string_literal_address(left);
9040 warn_string_literal_address(right);
9042 expression_t const* const func_left = get_reference_address(left);
9043 if (func_left != NULL && is_null_pointer_constant(right)) {
9044 warningf(&expression->base.source_position,
9045 "the address of '%Y' will never be NULL",
9046 func_left->reference.entity->base.symbol);
9049 expression_t const* const func_right = get_reference_address(right);
9050 if (func_right != NULL && is_null_pointer_constant(right)) {
9051 warningf(&expression->base.source_position,
9052 "the address of '%Y' will never be NULL",
9053 func_right->reference.entity->base.symbol);
9057 if (warning.parentheses) {
9058 warn_comparison_in_comparison(left);
9059 warn_comparison_in_comparison(right);
9062 type_t *orig_type_left = left->base.type;
9063 type_t *orig_type_right = right->base.type;
9064 type_t *type_left = skip_typeref(orig_type_left);
9065 type_t *type_right = skip_typeref(orig_type_right);
9067 /* TODO non-arithmetic types */
9068 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9069 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9071 /* test for signed vs unsigned compares */
9072 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
9073 bool const signed_left = is_type_signed(type_left);
9074 bool const signed_right = is_type_signed(type_right);
9075 if (signed_left != signed_right) {
9076 /* FIXME long long needs better const folding magic */
9077 /* TODO check whether constant value can be represented by other type */
9078 if ((signed_left && maybe_negative(left)) ||
9079 (signed_right && maybe_negative(right))) {
9080 warningf(&expression->base.source_position,
9081 "comparison between signed and unsigned");
9086 expression->left = create_implicit_cast(left, arithmetic_type);
9087 expression->right = create_implicit_cast(right, arithmetic_type);
9088 expression->base.type = arithmetic_type;
9089 if (warning.float_equal &&
9090 (expression->base.kind == EXPR_BINARY_EQUAL ||
9091 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
9092 is_type_float(arithmetic_type)) {
9093 warningf(&expression->base.source_position,
9094 "comparing floating point with == or != is unsafe");
9096 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
9097 /* TODO check compatibility */
9098 } else if (is_type_pointer(type_left)) {
9099 expression->right = create_implicit_cast(right, type_left);
9100 } else if (is_type_pointer(type_right)) {
9101 expression->left = create_implicit_cast(left, type_right);
9102 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9103 type_error_incompatible("invalid operands in comparison",
9104 &expression->base.source_position,
9105 type_left, type_right);
9107 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9111 * Checks if a compound type has constant fields.
9113 static bool has_const_fields(const compound_type_t *type)
9115 compound_t *compound = type->compound;
9116 entity_t *entry = compound->members.entities;
9118 for (; entry != NULL; entry = entry->base.next) {
9119 if (!is_declaration(entry))
9122 const type_t *decl_type = skip_typeref(entry->declaration.type);
9123 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
9130 static bool is_valid_assignment_lhs(expression_t const* const left)
9132 type_t *const orig_type_left = revert_automatic_type_conversion(left);
9133 type_t *const type_left = skip_typeref(orig_type_left);
9135 if (!is_lvalue(left)) {
9136 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
9141 if (left->kind == EXPR_REFERENCE
9142 && left->reference.entity->kind == ENTITY_FUNCTION) {
9143 errorf(HERE, "cannot assign to function '%E'", left);
9147 if (is_type_array(type_left)) {
9148 errorf(HERE, "cannot assign to array '%E'", left);
9151 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
9152 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
9156 if (is_type_incomplete(type_left)) {
9157 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
9158 left, orig_type_left);
9161 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
9162 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
9163 left, orig_type_left);
9170 static void semantic_arithmetic_assign(binary_expression_t *expression)
9172 expression_t *left = expression->left;
9173 expression_t *right = expression->right;
9174 type_t *orig_type_left = left->base.type;
9175 type_t *orig_type_right = right->base.type;
9177 if (!is_valid_assignment_lhs(left))
9180 type_t *type_left = skip_typeref(orig_type_left);
9181 type_t *type_right = skip_typeref(orig_type_right);
9183 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
9184 /* TODO: improve error message */
9185 if (is_type_valid(type_left) && is_type_valid(type_right)) {
9186 errorf(&expression->base.source_position,
9187 "operation needs arithmetic types");
9192 /* combined instructions are tricky. We can't create an implicit cast on
9193 * the left side, because we need the uncasted form for the store.
9194 * The ast2firm pass has to know that left_type must be right_type
9195 * for the arithmetic operation and create a cast by itself */
9196 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9197 expression->right = create_implicit_cast(right, arithmetic_type);
9198 expression->base.type = type_left;
9201 static void semantic_divmod_assign(binary_expression_t *expression)
9203 semantic_arithmetic_assign(expression);
9204 warn_div_by_zero(expression);
9207 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
9209 expression_t *const left = expression->left;
9210 expression_t *const right = expression->right;
9211 type_t *const orig_type_left = left->base.type;
9212 type_t *const orig_type_right = right->base.type;
9213 type_t *const type_left = skip_typeref(orig_type_left);
9214 type_t *const type_right = skip_typeref(orig_type_right);
9216 if (!is_valid_assignment_lhs(left))
9219 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9220 /* combined instructions are tricky. We can't create an implicit cast on
9221 * the left side, because we need the uncasted form for the store.
9222 * The ast2firm pass has to know that left_type must be right_type
9223 * for the arithmetic operation and create a cast by itself */
9224 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
9225 expression->right = create_implicit_cast(right, arithmetic_type);
9226 expression->base.type = type_left;
9227 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9228 check_pointer_arithmetic(&expression->base.source_position,
9229 type_left, orig_type_left);
9230 expression->base.type = type_left;
9231 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9232 errorf(&expression->base.source_position,
9233 "incompatible types '%T' and '%T' in assignment",
9234 orig_type_left, orig_type_right);
9238 static void warn_logical_and_within_or(const expression_t *const expr)
9240 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
9242 if (expr->base.parenthesized)
9244 warningf(&expr->base.source_position,
9245 "suggest parentheses around && within ||");
9249 * Check the semantic restrictions of a logical expression.
9251 static void semantic_logical_op(binary_expression_t *expression)
9253 /* §6.5.13:2 Each of the operands shall have scalar type.
9254 * §6.5.14:2 Each of the operands shall have scalar type. */
9255 semantic_condition(expression->left, "left operand of logical operator");
9256 semantic_condition(expression->right, "right operand of logical operator");
9257 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
9258 warning.parentheses) {
9259 warn_logical_and_within_or(expression->left);
9260 warn_logical_and_within_or(expression->right);
9262 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9266 * Check the semantic restrictions of a binary assign expression.
9268 static void semantic_binexpr_assign(binary_expression_t *expression)
9270 expression_t *left = expression->left;
9271 type_t *orig_type_left = left->base.type;
9273 if (!is_valid_assignment_lhs(left))
9276 assign_error_t error = semantic_assign(orig_type_left, expression->right);
9277 report_assign_error(error, orig_type_left, expression->right,
9278 "assignment", &left->base.source_position);
9279 expression->right = create_implicit_cast(expression->right, orig_type_left);
9280 expression->base.type = orig_type_left;
9284 * Determine if the outermost operation (or parts thereof) of the given
9285 * expression has no effect in order to generate a warning about this fact.
9286 * Therefore in some cases this only examines some of the operands of the
9287 * expression (see comments in the function and examples below).
9289 * f() + 23; // warning, because + has no effect
9290 * x || f(); // no warning, because x controls execution of f()
9291 * x ? y : f(); // warning, because y has no effect
9292 * (void)x; // no warning to be able to suppress the warning
9293 * This function can NOT be used for an "expression has definitely no effect"-
9295 static bool expression_has_effect(const expression_t *const expr)
9297 switch (expr->kind) {
9298 case EXPR_UNKNOWN: break;
9299 case EXPR_INVALID: return true; /* do NOT warn */
9300 case EXPR_REFERENCE: return false;
9301 case EXPR_REFERENCE_ENUM_VALUE: return false;
9302 /* suppress the warning for microsoft __noop operations */
9303 case EXPR_CONST: return expr->conste.is_ms_noop;
9304 case EXPR_CHARACTER_CONSTANT: return false;
9305 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
9306 case EXPR_STRING_LITERAL: return false;
9307 case EXPR_WIDE_STRING_LITERAL: return false;
9308 case EXPR_LABEL_ADDRESS: return false;
9311 const call_expression_t *const call = &expr->call;
9312 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
9315 switch (call->function->builtin_symbol.symbol->ID) {
9316 case T___builtin_va_end: return true;
9317 default: return false;
9321 /* Generate the warning if either the left or right hand side of a
9322 * conditional expression has no effect */
9323 case EXPR_CONDITIONAL: {
9324 const conditional_expression_t *const cond = &expr->conditional;
9326 expression_has_effect(cond->true_expression) &&
9327 expression_has_effect(cond->false_expression);
9330 case EXPR_SELECT: return false;
9331 case EXPR_ARRAY_ACCESS: return false;
9332 case EXPR_SIZEOF: return false;
9333 case EXPR_CLASSIFY_TYPE: return false;
9334 case EXPR_ALIGNOF: return false;
9336 case EXPR_FUNCNAME: return false;
9337 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
9338 case EXPR_BUILTIN_CONSTANT_P: return false;
9339 case EXPR_BUILTIN_PREFETCH: return true;
9340 case EXPR_OFFSETOF: return false;
9341 case EXPR_VA_START: return true;
9342 case EXPR_VA_ARG: return true;
9343 case EXPR_STATEMENT: return true; // TODO
9344 case EXPR_COMPOUND_LITERAL: return false;
9346 case EXPR_UNARY_NEGATE: return false;
9347 case EXPR_UNARY_PLUS: return false;
9348 case EXPR_UNARY_BITWISE_NEGATE: return false;
9349 case EXPR_UNARY_NOT: return false;
9350 case EXPR_UNARY_DEREFERENCE: return false;
9351 case EXPR_UNARY_TAKE_ADDRESS: return false;
9352 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
9353 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
9354 case EXPR_UNARY_PREFIX_INCREMENT: return true;
9355 case EXPR_UNARY_PREFIX_DECREMENT: return true;
9357 /* Treat void casts as if they have an effect in order to being able to
9358 * suppress the warning */
9359 case EXPR_UNARY_CAST: {
9360 type_t *const type = skip_typeref(expr->base.type);
9361 return is_type_atomic(type, ATOMIC_TYPE_VOID);
9364 case EXPR_UNARY_CAST_IMPLICIT: return true;
9365 case EXPR_UNARY_ASSUME: return true;
9366 case EXPR_UNARY_DELETE: return true;
9367 case EXPR_UNARY_DELETE_ARRAY: return true;
9368 case EXPR_UNARY_THROW: return true;
9370 case EXPR_BINARY_ADD: return false;
9371 case EXPR_BINARY_SUB: return false;
9372 case EXPR_BINARY_MUL: return false;
9373 case EXPR_BINARY_DIV: return false;
9374 case EXPR_BINARY_MOD: return false;
9375 case EXPR_BINARY_EQUAL: return false;
9376 case EXPR_BINARY_NOTEQUAL: return false;
9377 case EXPR_BINARY_LESS: return false;
9378 case EXPR_BINARY_LESSEQUAL: return false;
9379 case EXPR_BINARY_GREATER: return false;
9380 case EXPR_BINARY_GREATEREQUAL: return false;
9381 case EXPR_BINARY_BITWISE_AND: return false;
9382 case EXPR_BINARY_BITWISE_OR: return false;
9383 case EXPR_BINARY_BITWISE_XOR: return false;
9384 case EXPR_BINARY_SHIFTLEFT: return false;
9385 case EXPR_BINARY_SHIFTRIGHT: return false;
9386 case EXPR_BINARY_ASSIGN: return true;
9387 case EXPR_BINARY_MUL_ASSIGN: return true;
9388 case EXPR_BINARY_DIV_ASSIGN: return true;
9389 case EXPR_BINARY_MOD_ASSIGN: return true;
9390 case EXPR_BINARY_ADD_ASSIGN: return true;
9391 case EXPR_BINARY_SUB_ASSIGN: return true;
9392 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
9393 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
9394 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9395 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9396 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
9398 /* Only examine the right hand side of && and ||, because the left hand
9399 * side already has the effect of controlling the execution of the right
9401 case EXPR_BINARY_LOGICAL_AND:
9402 case EXPR_BINARY_LOGICAL_OR:
9403 /* Only examine the right hand side of a comma expression, because the left
9404 * hand side has a separate warning */
9405 case EXPR_BINARY_COMMA:
9406 return expression_has_effect(expr->binary.right);
9408 case EXPR_BINARY_ISGREATER: return false;
9409 case EXPR_BINARY_ISGREATEREQUAL: return false;
9410 case EXPR_BINARY_ISLESS: return false;
9411 case EXPR_BINARY_ISLESSEQUAL: return false;
9412 case EXPR_BINARY_ISLESSGREATER: return false;
9413 case EXPR_BINARY_ISUNORDERED: return false;
9416 internal_errorf(HERE, "unexpected expression");
9419 static void semantic_comma(binary_expression_t *expression)
9421 if (warning.unused_value) {
9422 const expression_t *const left = expression->left;
9423 if (!expression_has_effect(left)) {
9424 warningf(&left->base.source_position,
9425 "left-hand operand of comma expression has no effect");
9428 expression->base.type = expression->right->base.type;
9432 * @param prec_r precedence of the right operand
9434 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9435 static expression_t *parse_##binexpression_type(expression_t *left) \
9437 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9438 binexpr->binary.left = left; \
9441 expression_t *right = parse_sub_expression(prec_r); \
9443 binexpr->binary.right = right; \
9444 sfunc(&binexpr->binary); \
9449 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9450 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9451 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9452 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9453 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9454 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9455 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9456 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9457 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9458 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9459 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9460 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9461 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9462 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9463 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9464 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9465 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9466 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9467 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9468 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9469 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9470 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9471 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9472 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9473 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9474 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9475 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9476 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9477 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9478 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9481 static expression_t *parse_sub_expression(precedence_t precedence)
9483 if (token.type < 0) {
9484 return expected_expression_error();
9487 expression_parser_function_t *parser
9488 = &expression_parsers[token.type];
9489 source_position_t source_position = token.source_position;
9492 if (parser->parser != NULL) {
9493 left = parser->parser();
9495 left = parse_primary_expression();
9497 assert(left != NULL);
9498 left->base.source_position = source_position;
9501 if (token.type < 0) {
9502 return expected_expression_error();
9505 parser = &expression_parsers[token.type];
9506 if (parser->infix_parser == NULL)
9508 if (parser->infix_precedence < precedence)
9511 left = parser->infix_parser(left);
9513 assert(left != NULL);
9514 assert(left->kind != EXPR_UNKNOWN);
9515 left->base.source_position = source_position;
9522 * Parse an expression.
9524 static expression_t *parse_expression(void)
9526 return parse_sub_expression(PREC_EXPRESSION);
9530 * Register a parser for a prefix-like operator.
9532 * @param parser the parser function
9533 * @param token_type the token type of the prefix token
9535 static void register_expression_parser(parse_expression_function parser,
9538 expression_parser_function_t *entry = &expression_parsers[token_type];
9540 if (entry->parser != NULL) {
9541 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9542 panic("trying to register multiple expression parsers for a token");
9544 entry->parser = parser;
9548 * Register a parser for an infix operator with given precedence.
9550 * @param parser the parser function
9551 * @param token_type the token type of the infix operator
9552 * @param precedence the precedence of the operator
9554 static void register_infix_parser(parse_expression_infix_function parser,
9555 int token_type, precedence_t precedence)
9557 expression_parser_function_t *entry = &expression_parsers[token_type];
9559 if (entry->infix_parser != NULL) {
9560 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9561 panic("trying to register multiple infix expression parsers for a "
9564 entry->infix_parser = parser;
9565 entry->infix_precedence = precedence;
9569 * Initialize the expression parsers.
9571 static void init_expression_parsers(void)
9573 memset(&expression_parsers, 0, sizeof(expression_parsers));
9575 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9576 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9577 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9578 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9579 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9580 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9581 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9582 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9583 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9584 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9585 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9586 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9587 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9588 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9589 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9590 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9591 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9592 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9593 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9594 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9595 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9596 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9597 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9598 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9599 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9600 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9601 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9602 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9603 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9604 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9605 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9606 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9607 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9608 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9609 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9610 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9611 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9613 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9614 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9615 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9616 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9617 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9618 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9619 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9620 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9621 register_expression_parser(parse_sizeof, T_sizeof);
9622 register_expression_parser(parse_alignof, T___alignof__);
9623 register_expression_parser(parse_extension, T___extension__);
9624 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9625 register_expression_parser(parse_delete, T_delete);
9626 register_expression_parser(parse_throw, T_throw);
9630 * Parse a asm statement arguments specification.
9632 static asm_argument_t *parse_asm_arguments(bool is_out)
9634 asm_argument_t *result = NULL;
9635 asm_argument_t **anchor = &result;
9637 while (token.type == T_STRING_LITERAL || token.type == '[') {
9638 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9639 memset(argument, 0, sizeof(argument[0]));
9641 if (token.type == '[') {
9643 if (token.type != T_IDENTIFIER) {
9644 parse_error_expected("while parsing asm argument",
9645 T_IDENTIFIER, NULL);
9648 argument->symbol = token.v.symbol;
9650 expect(']', end_error);
9653 argument->constraints = parse_string_literals();
9654 expect('(', end_error);
9655 add_anchor_token(')');
9656 expression_t *expression = parse_expression();
9657 rem_anchor_token(')');
9659 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9660 * change size or type representation (e.g. int -> long is ok, but
9661 * int -> float is not) */
9662 if (expression->kind == EXPR_UNARY_CAST) {
9663 type_t *const type = expression->base.type;
9664 type_kind_t const kind = type->kind;
9665 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9668 if (kind == TYPE_ATOMIC) {
9669 atomic_type_kind_t const akind = type->atomic.akind;
9670 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9671 size = get_atomic_type_size(akind);
9673 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9674 size = get_atomic_type_size(get_intptr_kind());
9678 expression_t *const value = expression->unary.value;
9679 type_t *const value_type = value->base.type;
9680 type_kind_t const value_kind = value_type->kind;
9682 unsigned value_flags;
9683 unsigned value_size;
9684 if (value_kind == TYPE_ATOMIC) {
9685 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9686 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9687 value_size = get_atomic_type_size(value_akind);
9688 } else if (value_kind == TYPE_POINTER) {
9689 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9690 value_size = get_atomic_type_size(get_intptr_kind());
9695 if (value_flags != flags || value_size != size)
9699 } while (expression->kind == EXPR_UNARY_CAST);
9703 if (!is_lvalue(expression)) {
9704 errorf(&expression->base.source_position,
9705 "asm output argument is not an lvalue");
9708 if (argument->constraints.begin[0] == '+')
9709 mark_vars_read(expression, NULL);
9711 mark_vars_read(expression, NULL);
9713 argument->expression = expression;
9714 expect(')', end_error);
9716 set_address_taken(expression, true);
9719 anchor = &argument->next;
9721 if (token.type != ',')
9732 * Parse a asm statement clobber specification.
9734 static asm_clobber_t *parse_asm_clobbers(void)
9736 asm_clobber_t *result = NULL;
9737 asm_clobber_t *last = NULL;
9739 while (token.type == T_STRING_LITERAL) {
9740 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9741 clobber->clobber = parse_string_literals();
9744 last->next = clobber;
9750 if (token.type != ',')
9759 * Parse an asm statement.
9761 static statement_t *parse_asm_statement(void)
9763 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9764 asm_statement_t *asm_statement = &statement->asms;
9768 if (token.type == T_volatile) {
9770 asm_statement->is_volatile = true;
9773 expect('(', end_error);
9774 add_anchor_token(')');
9775 add_anchor_token(':');
9776 asm_statement->asm_text = parse_string_literals();
9778 if (token.type != ':') {
9779 rem_anchor_token(':');
9784 asm_statement->outputs = parse_asm_arguments(true);
9785 if (token.type != ':') {
9786 rem_anchor_token(':');
9791 asm_statement->inputs = parse_asm_arguments(false);
9792 if (token.type != ':') {
9793 rem_anchor_token(':');
9796 rem_anchor_token(':');
9799 asm_statement->clobbers = parse_asm_clobbers();
9802 rem_anchor_token(')');
9803 expect(')', end_error);
9804 expect(';', end_error);
9806 if (asm_statement->outputs == NULL) {
9807 /* GCC: An 'asm' instruction without any output operands will be treated
9808 * identically to a volatile 'asm' instruction. */
9809 asm_statement->is_volatile = true;
9814 return create_invalid_statement();
9818 * Parse a case statement.
9820 static statement_t *parse_case_statement(void)
9822 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9823 source_position_t *const pos = &statement->base.source_position;
9827 expression_t *const expression = parse_expression();
9828 statement->case_label.expression = expression;
9829 if (!is_constant_expression(expression)) {
9830 /* This check does not prevent the error message in all cases of an
9831 * prior error while parsing the expression. At least it catches the
9832 * common case of a mistyped enum entry. */
9833 if (is_type_valid(skip_typeref(expression->base.type))) {
9834 errorf(pos, "case label does not reduce to an integer constant");
9836 statement->case_label.is_bad = true;
9838 long const val = fold_constant(expression);
9839 statement->case_label.first_case = val;
9840 statement->case_label.last_case = val;
9844 if (token.type == T_DOTDOTDOT) {
9846 expression_t *const end_range = parse_expression();
9847 statement->case_label.end_range = end_range;
9848 if (!is_constant_expression(end_range)) {
9849 /* This check does not prevent the error message in all cases of an
9850 * prior error while parsing the expression. At least it catches the
9851 * common case of a mistyped enum entry. */
9852 if (is_type_valid(skip_typeref(end_range->base.type))) {
9853 errorf(pos, "case range does not reduce to an integer constant");
9855 statement->case_label.is_bad = true;
9857 long const val = fold_constant(end_range);
9858 statement->case_label.last_case = val;
9860 if (warning.other && val < statement->case_label.first_case) {
9861 statement->case_label.is_empty_range = true;
9862 warningf(pos, "empty range specified");
9868 PUSH_PARENT(statement);
9870 expect(':', end_error);
9873 if (current_switch != NULL) {
9874 if (! statement->case_label.is_bad) {
9875 /* Check for duplicate case values */
9876 case_label_statement_t *c = &statement->case_label;
9877 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9878 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9881 if (c->last_case < l->first_case || c->first_case > l->last_case)
9884 errorf(pos, "duplicate case value (previously used %P)",
9885 &l->base.source_position);
9889 /* link all cases into the switch statement */
9890 if (current_switch->last_case == NULL) {
9891 current_switch->first_case = &statement->case_label;
9893 current_switch->last_case->next = &statement->case_label;
9895 current_switch->last_case = &statement->case_label;
9897 errorf(pos, "case label not within a switch statement");
9900 statement_t *const inner_stmt = parse_statement();
9901 statement->case_label.statement = inner_stmt;
9902 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9903 errorf(&inner_stmt->base.source_position, "declaration after case label");
9911 * Parse a default statement.
9913 static statement_t *parse_default_statement(void)
9915 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9919 PUSH_PARENT(statement);
9921 expect(':', end_error);
9922 if (current_switch != NULL) {
9923 const case_label_statement_t *def_label = current_switch->default_label;
9924 if (def_label != NULL) {
9925 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9926 &def_label->base.source_position);
9928 current_switch->default_label = &statement->case_label;
9930 /* link all cases into the switch statement */
9931 if (current_switch->last_case == NULL) {
9932 current_switch->first_case = &statement->case_label;
9934 current_switch->last_case->next = &statement->case_label;
9936 current_switch->last_case = &statement->case_label;
9939 errorf(&statement->base.source_position,
9940 "'default' label not within a switch statement");
9943 statement_t *const inner_stmt = parse_statement();
9944 statement->case_label.statement = inner_stmt;
9945 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9946 errorf(&inner_stmt->base.source_position, "declaration after default label");
9953 return create_invalid_statement();
9957 * Parse a label statement.
9959 static statement_t *parse_label_statement(void)
9961 assert(token.type == T_IDENTIFIER);
9962 symbol_t *symbol = token.v.symbol;
9963 label_t *label = get_label(symbol);
9965 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9966 statement->label.label = label;
9970 PUSH_PARENT(statement);
9972 /* if statement is already set then the label is defined twice,
9973 * otherwise it was just mentioned in a goto/local label declaration so far
9975 if (label->statement != NULL) {
9976 errorf(HERE, "duplicate label '%Y' (declared %P)",
9977 symbol, &label->base.source_position);
9979 label->base.source_position = token.source_position;
9980 label->statement = statement;
9985 if (token.type == '}') {
9986 /* TODO only warn? */
9987 if (warning.other && false) {
9988 warningf(HERE, "label at end of compound statement");
9989 statement->label.statement = create_empty_statement();
9991 errorf(HERE, "label at end of compound statement");
9992 statement->label.statement = create_invalid_statement();
9994 } else if (token.type == ';') {
9995 /* Eat an empty statement here, to avoid the warning about an empty
9996 * statement after a label. label:; is commonly used to have a label
9997 * before a closing brace. */
9998 statement->label.statement = create_empty_statement();
10001 statement_t *const inner_stmt = parse_statement();
10002 statement->label.statement = inner_stmt;
10003 if (inner_stmt->kind == STATEMENT_DECLARATION) {
10004 errorf(&inner_stmt->base.source_position, "declaration after label");
10008 /* remember the labels in a list for later checking */
10009 *label_anchor = &statement->label;
10010 label_anchor = &statement->label.next;
10017 * Parse an if statement.
10019 static statement_t *parse_if(void)
10021 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
10025 PUSH_PARENT(statement);
10027 add_anchor_token('{');
10029 expect('(', end_error);
10030 add_anchor_token(')');
10031 expression_t *const expr = parse_expression();
10032 statement->ifs.condition = expr;
10033 /* §6.8.4.1:1 The controlling expression of an if statement shall have
10035 semantic_condition(expr, "condition of 'if'-statment");
10036 mark_vars_read(expr, NULL);
10037 rem_anchor_token(')');
10038 expect(')', end_error);
10041 rem_anchor_token('{');
10043 add_anchor_token(T_else);
10044 statement_t *const true_stmt = parse_statement();
10045 statement->ifs.true_statement = true_stmt;
10046 rem_anchor_token(T_else);
10048 if (token.type == T_else) {
10050 statement->ifs.false_statement = parse_statement();
10051 } else if (warning.parentheses &&
10052 true_stmt->kind == STATEMENT_IF &&
10053 true_stmt->ifs.false_statement != NULL) {
10054 warningf(&true_stmt->base.source_position,
10055 "suggest explicit braces to avoid ambiguous 'else'");
10063 * Check that all enums are handled in a switch.
10065 * @param statement the switch statement to check
10067 static void check_enum_cases(const switch_statement_t *statement) {
10068 const type_t *type = skip_typeref(statement->expression->base.type);
10069 if (! is_type_enum(type))
10071 const enum_type_t *enumt = &type->enumt;
10073 /* if we have a default, no warnings */
10074 if (statement->default_label != NULL)
10077 /* FIXME: calculation of value should be done while parsing */
10078 /* TODO: quadratic algorithm here. Change to an n log n one */
10079 long last_value = -1;
10080 const entity_t *entry = enumt->enume->base.next;
10081 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
10082 entry = entry->base.next) {
10083 const expression_t *expression = entry->enum_value.value;
10084 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
10085 bool found = false;
10086 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
10087 if (l->expression == NULL)
10089 if (l->first_case <= value && value <= l->last_case) {
10095 warningf(&statement->base.source_position,
10096 "enumeration value '%Y' not handled in switch",
10097 entry->base.symbol);
10099 last_value = value;
10104 * Parse a switch statement.
10106 static statement_t *parse_switch(void)
10108 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
10112 PUSH_PARENT(statement);
10114 expect('(', end_error);
10115 add_anchor_token(')');
10116 expression_t *const expr = parse_expression();
10117 mark_vars_read(expr, NULL);
10118 type_t * type = skip_typeref(expr->base.type);
10119 if (is_type_integer(type)) {
10120 type = promote_integer(type);
10121 if (warning.traditional) {
10122 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
10123 warningf(&expr->base.source_position,
10124 "'%T' switch expression not converted to '%T' in ISO C",
10128 } else if (is_type_valid(type)) {
10129 errorf(&expr->base.source_position,
10130 "switch quantity is not an integer, but '%T'", type);
10131 type = type_error_type;
10133 statement->switchs.expression = create_implicit_cast(expr, type);
10134 expect(')', end_error);
10135 rem_anchor_token(')');
10137 switch_statement_t *rem = current_switch;
10138 current_switch = &statement->switchs;
10139 statement->switchs.body = parse_statement();
10140 current_switch = rem;
10142 if (warning.switch_default &&
10143 statement->switchs.default_label == NULL) {
10144 warningf(&statement->base.source_position, "switch has no default case");
10146 if (warning.switch_enum)
10147 check_enum_cases(&statement->switchs);
10153 return create_invalid_statement();
10156 static statement_t *parse_loop_body(statement_t *const loop)
10158 statement_t *const rem = current_loop;
10159 current_loop = loop;
10161 statement_t *const body = parse_statement();
10163 current_loop = rem;
10168 * Parse a while statement.
10170 static statement_t *parse_while(void)
10172 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
10176 PUSH_PARENT(statement);
10178 expect('(', end_error);
10179 add_anchor_token(')');
10180 expression_t *const cond = parse_expression();
10181 statement->whiles.condition = cond;
10182 /* §6.8.5:2 The controlling expression of an iteration statement shall
10183 * have scalar type. */
10184 semantic_condition(cond, "condition of 'while'-statement");
10185 mark_vars_read(cond, NULL);
10186 rem_anchor_token(')');
10187 expect(')', end_error);
10189 statement->whiles.body = parse_loop_body(statement);
10195 return create_invalid_statement();
10199 * Parse a do statement.
10201 static statement_t *parse_do(void)
10203 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
10207 PUSH_PARENT(statement);
10209 add_anchor_token(T_while);
10210 statement->do_while.body = parse_loop_body(statement);
10211 rem_anchor_token(T_while);
10213 expect(T_while, end_error);
10214 expect('(', end_error);
10215 add_anchor_token(')');
10216 expression_t *const cond = parse_expression();
10217 statement->do_while.condition = cond;
10218 /* §6.8.5:2 The controlling expression of an iteration statement shall
10219 * have scalar type. */
10220 semantic_condition(cond, "condition of 'do-while'-statement");
10221 mark_vars_read(cond, NULL);
10222 rem_anchor_token(')');
10223 expect(')', end_error);
10224 expect(';', end_error);
10230 return create_invalid_statement();
10234 * Parse a for statement.
10236 static statement_t *parse_for(void)
10238 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
10242 expect('(', end_error1);
10243 add_anchor_token(')');
10245 PUSH_PARENT(statement);
10247 size_t const top = environment_top();
10248 scope_t *old_scope = scope_push(&statement->fors.scope);
10250 if (token.type == ';') {
10252 } else if (is_declaration_specifier(&token, false)) {
10253 parse_declaration(record_entity, DECL_FLAGS_NONE);
10255 add_anchor_token(';');
10256 expression_t *const init = parse_expression();
10257 statement->fors.initialisation = init;
10258 mark_vars_read(init, ENT_ANY);
10259 if (warning.unused_value && !expression_has_effect(init)) {
10260 warningf(&init->base.source_position,
10261 "initialisation of 'for'-statement has no effect");
10263 rem_anchor_token(';');
10264 expect(';', end_error2);
10267 if (token.type != ';') {
10268 add_anchor_token(';');
10269 expression_t *const cond = parse_expression();
10270 statement->fors.condition = cond;
10271 /* §6.8.5:2 The controlling expression of an iteration statement
10272 * shall have scalar type. */
10273 semantic_condition(cond, "condition of 'for'-statement");
10274 mark_vars_read(cond, NULL);
10275 rem_anchor_token(';');
10277 expect(';', end_error2);
10278 if (token.type != ')') {
10279 expression_t *const step = parse_expression();
10280 statement->fors.step = step;
10281 mark_vars_read(step, ENT_ANY);
10282 if (warning.unused_value && !expression_has_effect(step)) {
10283 warningf(&step->base.source_position,
10284 "step of 'for'-statement has no effect");
10287 expect(')', end_error2);
10288 rem_anchor_token(')');
10289 statement->fors.body = parse_loop_body(statement);
10291 assert(current_scope == &statement->fors.scope);
10292 scope_pop(old_scope);
10293 environment_pop_to(top);
10300 rem_anchor_token(')');
10301 assert(current_scope == &statement->fors.scope);
10302 scope_pop(old_scope);
10303 environment_pop_to(top);
10307 return create_invalid_statement();
10311 * Parse a goto statement.
10313 static statement_t *parse_goto(void)
10315 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
10318 if (GNU_MODE && token.type == '*') {
10320 expression_t *expression = parse_expression();
10321 mark_vars_read(expression, NULL);
10323 /* Argh: although documentation says the expression must be of type void*,
10324 * gcc accepts anything that can be casted into void* without error */
10325 type_t *type = expression->base.type;
10327 if (type != type_error_type) {
10328 if (!is_type_pointer(type) && !is_type_integer(type)) {
10329 errorf(&expression->base.source_position,
10330 "cannot convert to a pointer type");
10331 } else if (warning.other && type != type_void_ptr) {
10332 warningf(&expression->base.source_position,
10333 "type of computed goto expression should be 'void*' not '%T'", type);
10335 expression = create_implicit_cast(expression, type_void_ptr);
10338 statement->gotos.expression = expression;
10340 if (token.type != T_IDENTIFIER) {
10342 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
10344 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
10345 eat_until_anchor();
10348 symbol_t *symbol = token.v.symbol;
10351 statement->gotos.label = get_label(symbol);
10354 /* remember the goto's in a list for later checking */
10355 *goto_anchor = &statement->gotos;
10356 goto_anchor = &statement->gotos.next;
10358 expect(';', end_error);
10362 return create_invalid_statement();
10366 * Parse a continue statement.
10368 static statement_t *parse_continue(void)
10370 if (current_loop == NULL) {
10371 errorf(HERE, "continue statement not within loop");
10374 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
10377 expect(';', end_error);
10384 * Parse a break statement.
10386 static statement_t *parse_break(void)
10388 if (current_switch == NULL && current_loop == NULL) {
10389 errorf(HERE, "break statement not within loop or switch");
10392 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10395 expect(';', end_error);
10402 * Parse a __leave statement.
10404 static statement_t *parse_leave_statement(void)
10406 if (current_try == NULL) {
10407 errorf(HERE, "__leave statement not within __try");
10410 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10413 expect(';', end_error);
10420 * Check if a given entity represents a local variable.
10422 static bool is_local_variable(const entity_t *entity)
10424 if (entity->kind != ENTITY_VARIABLE)
10427 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10428 case STORAGE_CLASS_AUTO:
10429 case STORAGE_CLASS_REGISTER: {
10430 const type_t *type = skip_typeref(entity->declaration.type);
10431 if (is_type_function(type)) {
10443 * Check if a given expression represents a local variable.
10445 static bool expression_is_local_variable(const expression_t *expression)
10447 if (expression->base.kind != EXPR_REFERENCE) {
10450 const entity_t *entity = expression->reference.entity;
10451 return is_local_variable(entity);
10455 * Check if a given expression represents a local variable and
10456 * return its declaration then, else return NULL.
10458 entity_t *expression_is_variable(const expression_t *expression)
10460 if (expression->base.kind != EXPR_REFERENCE) {
10463 entity_t *entity = expression->reference.entity;
10464 if (entity->kind != ENTITY_VARIABLE)
10471 * Parse a return statement.
10473 static statement_t *parse_return(void)
10477 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10479 expression_t *return_value = NULL;
10480 if (token.type != ';') {
10481 return_value = parse_expression();
10482 mark_vars_read(return_value, NULL);
10485 const type_t *const func_type = skip_typeref(current_function->base.type);
10486 assert(is_type_function(func_type));
10487 type_t *const return_type = skip_typeref(func_type->function.return_type);
10489 source_position_t const *const pos = &statement->base.source_position;
10490 if (return_value != NULL) {
10491 type_t *return_value_type = skip_typeref(return_value->base.type);
10493 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10494 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10495 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10496 /* Only warn in C mode, because GCC does the same */
10497 if (c_mode & _CXX || strict_mode) {
10499 "'return' with a value, in function returning 'void'");
10500 } else if (warning.other) {
10502 "'return' with a value, in function returning 'void'");
10504 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10505 /* Only warn in C mode, because GCC does the same */
10508 "'return' with expression in function return 'void'");
10509 } else if (warning.other) {
10511 "'return' with expression in function return 'void'");
10515 assign_error_t error = semantic_assign(return_type, return_value);
10516 report_assign_error(error, return_type, return_value, "'return'",
10519 return_value = create_implicit_cast(return_value, return_type);
10520 /* check for returning address of a local var */
10521 if (warning.other && return_value != NULL
10522 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10523 const expression_t *expression = return_value->unary.value;
10524 if (expression_is_local_variable(expression)) {
10525 warningf(pos, "function returns address of local variable");
10528 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10529 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10530 if (c_mode & _CXX || strict_mode) {
10532 "'return' without value, in function returning non-void");
10535 "'return' without value, in function returning non-void");
10538 statement->returns.value = return_value;
10540 expect(';', end_error);
10547 * Parse a declaration statement.
10549 static statement_t *parse_declaration_statement(void)
10551 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10553 entity_t *before = current_scope->last_entity;
10555 parse_external_declaration();
10557 parse_declaration(record_entity, DECL_FLAGS_NONE);
10560 if (before == NULL) {
10561 statement->declaration.declarations_begin = current_scope->entities;
10563 statement->declaration.declarations_begin = before->base.next;
10565 statement->declaration.declarations_end = current_scope->last_entity;
10571 * Parse an expression statement, ie. expr ';'.
10573 static statement_t *parse_expression_statement(void)
10575 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10577 expression_t *const expr = parse_expression();
10578 statement->expression.expression = expr;
10579 mark_vars_read(expr, ENT_ANY);
10581 expect(';', end_error);
10588 * Parse a microsoft __try { } __finally { } or
10589 * __try{ } __except() { }
10591 static statement_t *parse_ms_try_statment(void)
10593 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10596 PUSH_PARENT(statement);
10598 ms_try_statement_t *rem = current_try;
10599 current_try = &statement->ms_try;
10600 statement->ms_try.try_statement = parse_compound_statement(false);
10605 if (token.type == T___except) {
10607 expect('(', end_error);
10608 add_anchor_token(')');
10609 expression_t *const expr = parse_expression();
10610 mark_vars_read(expr, NULL);
10611 type_t * type = skip_typeref(expr->base.type);
10612 if (is_type_integer(type)) {
10613 type = promote_integer(type);
10614 } else if (is_type_valid(type)) {
10615 errorf(&expr->base.source_position,
10616 "__expect expression is not an integer, but '%T'", type);
10617 type = type_error_type;
10619 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10620 rem_anchor_token(')');
10621 expect(')', end_error);
10622 statement->ms_try.final_statement = parse_compound_statement(false);
10623 } else if (token.type == T__finally) {
10625 statement->ms_try.final_statement = parse_compound_statement(false);
10627 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10628 return create_invalid_statement();
10632 return create_invalid_statement();
10635 static statement_t *parse_empty_statement(void)
10637 if (warning.empty_statement) {
10638 warningf(HERE, "statement is empty");
10640 statement_t *const statement = create_empty_statement();
10645 static statement_t *parse_local_label_declaration(void)
10647 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10651 entity_t *begin = NULL, *end = NULL;
10654 if (token.type != T_IDENTIFIER) {
10655 parse_error_expected("while parsing local label declaration",
10656 T_IDENTIFIER, NULL);
10659 symbol_t *symbol = token.v.symbol;
10660 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10661 if (entity != NULL && entity->base.parent_scope == current_scope) {
10662 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10663 symbol, &entity->base.source_position);
10665 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10667 entity->base.parent_scope = current_scope;
10668 entity->base.namespc = NAMESPACE_LABEL;
10669 entity->base.source_position = token.source_position;
10670 entity->base.symbol = symbol;
10673 end->base.next = entity;
10678 environment_push(entity);
10682 if (token.type != ',')
10688 statement->declaration.declarations_begin = begin;
10689 statement->declaration.declarations_end = end;
10693 static void parse_namespace_definition(void)
10697 entity_t *entity = NULL;
10698 symbol_t *symbol = NULL;
10700 if (token.type == T_IDENTIFIER) {
10701 symbol = token.v.symbol;
10704 entity = get_entity(symbol, NAMESPACE_NORMAL);
10705 if (entity != NULL && entity->kind != ENTITY_NAMESPACE
10706 && entity->base.parent_scope == current_scope) {
10707 error_redefined_as_different_kind(&token.source_position,
10708 entity, ENTITY_NAMESPACE);
10713 if (entity == NULL) {
10714 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10715 entity->base.symbol = symbol;
10716 entity->base.source_position = token.source_position;
10717 entity->base.namespc = NAMESPACE_NORMAL;
10718 entity->base.parent_scope = current_scope;
10721 if (token.type == '=') {
10722 /* TODO: parse namespace alias */
10723 panic("namespace alias definition not supported yet");
10726 environment_push(entity);
10727 append_entity(current_scope, entity);
10729 size_t const top = environment_top();
10730 scope_t *old_scope = scope_push(&entity->namespacee.members);
10732 expect('{', end_error);
10734 expect('}', end_error);
10737 assert(current_scope == &entity->namespacee.members);
10738 scope_pop(old_scope);
10739 environment_pop_to(top);
10743 * Parse a statement.
10744 * There's also parse_statement() which additionally checks for
10745 * "statement has no effect" warnings
10747 static statement_t *intern_parse_statement(void)
10749 statement_t *statement = NULL;
10751 /* declaration or statement */
10752 add_anchor_token(';');
10753 switch (token.type) {
10754 case T_IDENTIFIER: {
10755 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10756 if (la1_type == ':') {
10757 statement = parse_label_statement();
10758 } else if (is_typedef_symbol(token.v.symbol)) {
10759 statement = parse_declaration_statement();
10761 /* it's an identifier, the grammar says this must be an
10762 * expression statement. However it is common that users mistype
10763 * declaration types, so we guess a bit here to improve robustness
10764 * for incorrect programs */
10765 switch (la1_type) {
10768 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10769 goto expression_statment;
10774 statement = parse_declaration_statement();
10778 expression_statment:
10779 statement = parse_expression_statement();
10786 case T___extension__:
10787 /* This can be a prefix to a declaration or an expression statement.
10788 * We simply eat it now and parse the rest with tail recursion. */
10791 } while (token.type == T___extension__);
10792 bool old_gcc_extension = in_gcc_extension;
10793 in_gcc_extension = true;
10794 statement = intern_parse_statement();
10795 in_gcc_extension = old_gcc_extension;
10799 statement = parse_declaration_statement();
10803 statement = parse_local_label_declaration();
10806 case ';': statement = parse_empty_statement(); break;
10807 case '{': statement = parse_compound_statement(false); break;
10808 case T___leave: statement = parse_leave_statement(); break;
10809 case T___try: statement = parse_ms_try_statment(); break;
10810 case T_asm: statement = parse_asm_statement(); break;
10811 case T_break: statement = parse_break(); break;
10812 case T_case: statement = parse_case_statement(); break;
10813 case T_continue: statement = parse_continue(); break;
10814 case T_default: statement = parse_default_statement(); break;
10815 case T_do: statement = parse_do(); break;
10816 case T_for: statement = parse_for(); break;
10817 case T_goto: statement = parse_goto(); break;
10818 case T_if: statement = parse_if(); break;
10819 case T_return: statement = parse_return(); break;
10820 case T_switch: statement = parse_switch(); break;
10821 case T_while: statement = parse_while(); break;
10824 statement = parse_expression_statement();
10828 errorf(HERE, "unexpected token %K while parsing statement", &token);
10829 statement = create_invalid_statement();
10834 rem_anchor_token(';');
10836 assert(statement != NULL
10837 && statement->base.source_position.input_name != NULL);
10843 * parse a statement and emits "statement has no effect" warning if needed
10844 * (This is really a wrapper around intern_parse_statement with check for 1
10845 * single warning. It is needed, because for statement expressions we have
10846 * to avoid the warning on the last statement)
10848 static statement_t *parse_statement(void)
10850 statement_t *statement = intern_parse_statement();
10852 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10853 expression_t *expression = statement->expression.expression;
10854 if (!expression_has_effect(expression)) {
10855 warningf(&expression->base.source_position,
10856 "statement has no effect");
10864 * Parse a compound statement.
10866 static statement_t *parse_compound_statement(bool inside_expression_statement)
10868 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10870 PUSH_PARENT(statement);
10873 add_anchor_token('}');
10874 /* tokens, which can start a statement */
10875 /* TODO MS, __builtin_FOO */
10876 add_anchor_token('!');
10877 add_anchor_token('&');
10878 add_anchor_token('(');
10879 add_anchor_token('*');
10880 add_anchor_token('+');
10881 add_anchor_token('-');
10882 add_anchor_token('{');
10883 add_anchor_token('~');
10884 add_anchor_token(T_CHARACTER_CONSTANT);
10885 add_anchor_token(T_COLONCOLON);
10886 add_anchor_token(T_FLOATINGPOINT);
10887 add_anchor_token(T_IDENTIFIER);
10888 add_anchor_token(T_INTEGER);
10889 add_anchor_token(T_MINUSMINUS);
10890 add_anchor_token(T_PLUSPLUS);
10891 add_anchor_token(T_STRING_LITERAL);
10892 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10893 add_anchor_token(T_WIDE_STRING_LITERAL);
10894 add_anchor_token(T__Bool);
10895 add_anchor_token(T__Complex);
10896 add_anchor_token(T__Imaginary);
10897 add_anchor_token(T___FUNCTION__);
10898 add_anchor_token(T___PRETTY_FUNCTION__);
10899 add_anchor_token(T___alignof__);
10900 add_anchor_token(T___attribute__);
10901 add_anchor_token(T___builtin_va_start);
10902 add_anchor_token(T___extension__);
10903 add_anchor_token(T___func__);
10904 add_anchor_token(T___imag__);
10905 add_anchor_token(T___label__);
10906 add_anchor_token(T___real__);
10907 add_anchor_token(T___thread);
10908 add_anchor_token(T_asm);
10909 add_anchor_token(T_auto);
10910 add_anchor_token(T_bool);
10911 add_anchor_token(T_break);
10912 add_anchor_token(T_case);
10913 add_anchor_token(T_char);
10914 add_anchor_token(T_class);
10915 add_anchor_token(T_const);
10916 add_anchor_token(T_const_cast);
10917 add_anchor_token(T_continue);
10918 add_anchor_token(T_default);
10919 add_anchor_token(T_delete);
10920 add_anchor_token(T_double);
10921 add_anchor_token(T_do);
10922 add_anchor_token(T_dynamic_cast);
10923 add_anchor_token(T_enum);
10924 add_anchor_token(T_extern);
10925 add_anchor_token(T_false);
10926 add_anchor_token(T_float);
10927 add_anchor_token(T_for);
10928 add_anchor_token(T_goto);
10929 add_anchor_token(T_if);
10930 add_anchor_token(T_inline);
10931 add_anchor_token(T_int);
10932 add_anchor_token(T_long);
10933 add_anchor_token(T_new);
10934 add_anchor_token(T_operator);
10935 add_anchor_token(T_register);
10936 add_anchor_token(T_reinterpret_cast);
10937 add_anchor_token(T_restrict);
10938 add_anchor_token(T_return);
10939 add_anchor_token(T_short);
10940 add_anchor_token(T_signed);
10941 add_anchor_token(T_sizeof);
10942 add_anchor_token(T_static);
10943 add_anchor_token(T_static_cast);
10944 add_anchor_token(T_struct);
10945 add_anchor_token(T_switch);
10946 add_anchor_token(T_template);
10947 add_anchor_token(T_this);
10948 add_anchor_token(T_throw);
10949 add_anchor_token(T_true);
10950 add_anchor_token(T_try);
10951 add_anchor_token(T_typedef);
10952 add_anchor_token(T_typeid);
10953 add_anchor_token(T_typename);
10954 add_anchor_token(T_typeof);
10955 add_anchor_token(T_union);
10956 add_anchor_token(T_unsigned);
10957 add_anchor_token(T_using);
10958 add_anchor_token(T_void);
10959 add_anchor_token(T_volatile);
10960 add_anchor_token(T_wchar_t);
10961 add_anchor_token(T_while);
10963 size_t const top = environment_top();
10964 scope_t *old_scope = scope_push(&statement->compound.scope);
10966 statement_t **anchor = &statement->compound.statements;
10967 bool only_decls_so_far = true;
10968 while (token.type != '}') {
10969 if (token.type == T_EOF) {
10970 errorf(&statement->base.source_position,
10971 "EOF while parsing compound statement");
10974 statement_t *sub_statement = intern_parse_statement();
10975 if (is_invalid_statement(sub_statement)) {
10976 /* an error occurred. if we are at an anchor, return */
10982 if (warning.declaration_after_statement) {
10983 if (sub_statement->kind != STATEMENT_DECLARATION) {
10984 only_decls_so_far = false;
10985 } else if (!only_decls_so_far) {
10986 warningf(&sub_statement->base.source_position,
10987 "ISO C90 forbids mixed declarations and code");
10991 *anchor = sub_statement;
10993 while (sub_statement->base.next != NULL)
10994 sub_statement = sub_statement->base.next;
10996 anchor = &sub_statement->base.next;
11000 /* look over all statements again to produce no effect warnings */
11001 if (warning.unused_value) {
11002 statement_t *sub_statement = statement->compound.statements;
11003 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
11004 if (sub_statement->kind != STATEMENT_EXPRESSION)
11006 /* don't emit a warning for the last expression in an expression
11007 * statement as it has always an effect */
11008 if (inside_expression_statement && sub_statement->base.next == NULL)
11011 expression_t *expression = sub_statement->expression.expression;
11012 if (!expression_has_effect(expression)) {
11013 warningf(&expression->base.source_position,
11014 "statement has no effect");
11020 rem_anchor_token(T_while);
11021 rem_anchor_token(T_wchar_t);
11022 rem_anchor_token(T_volatile);
11023 rem_anchor_token(T_void);
11024 rem_anchor_token(T_using);
11025 rem_anchor_token(T_unsigned);
11026 rem_anchor_token(T_union);
11027 rem_anchor_token(T_typeof);
11028 rem_anchor_token(T_typename);
11029 rem_anchor_token(T_typeid);
11030 rem_anchor_token(T_typedef);
11031 rem_anchor_token(T_try);
11032 rem_anchor_token(T_true);
11033 rem_anchor_token(T_throw);
11034 rem_anchor_token(T_this);
11035 rem_anchor_token(T_template);
11036 rem_anchor_token(T_switch);
11037 rem_anchor_token(T_struct);
11038 rem_anchor_token(T_static_cast);
11039 rem_anchor_token(T_static);
11040 rem_anchor_token(T_sizeof);
11041 rem_anchor_token(T_signed);
11042 rem_anchor_token(T_short);
11043 rem_anchor_token(T_return);
11044 rem_anchor_token(T_restrict);
11045 rem_anchor_token(T_reinterpret_cast);
11046 rem_anchor_token(T_register);
11047 rem_anchor_token(T_operator);
11048 rem_anchor_token(T_new);
11049 rem_anchor_token(T_long);
11050 rem_anchor_token(T_int);
11051 rem_anchor_token(T_inline);
11052 rem_anchor_token(T_if);
11053 rem_anchor_token(T_goto);
11054 rem_anchor_token(T_for);
11055 rem_anchor_token(T_float);
11056 rem_anchor_token(T_false);
11057 rem_anchor_token(T_extern);
11058 rem_anchor_token(T_enum);
11059 rem_anchor_token(T_dynamic_cast);
11060 rem_anchor_token(T_do);
11061 rem_anchor_token(T_double);
11062 rem_anchor_token(T_delete);
11063 rem_anchor_token(T_default);
11064 rem_anchor_token(T_continue);
11065 rem_anchor_token(T_const_cast);
11066 rem_anchor_token(T_const);
11067 rem_anchor_token(T_class);
11068 rem_anchor_token(T_char);
11069 rem_anchor_token(T_case);
11070 rem_anchor_token(T_break);
11071 rem_anchor_token(T_bool);
11072 rem_anchor_token(T_auto);
11073 rem_anchor_token(T_asm);
11074 rem_anchor_token(T___thread);
11075 rem_anchor_token(T___real__);
11076 rem_anchor_token(T___label__);
11077 rem_anchor_token(T___imag__);
11078 rem_anchor_token(T___func__);
11079 rem_anchor_token(T___extension__);
11080 rem_anchor_token(T___builtin_va_start);
11081 rem_anchor_token(T___attribute__);
11082 rem_anchor_token(T___alignof__);
11083 rem_anchor_token(T___PRETTY_FUNCTION__);
11084 rem_anchor_token(T___FUNCTION__);
11085 rem_anchor_token(T__Imaginary);
11086 rem_anchor_token(T__Complex);
11087 rem_anchor_token(T__Bool);
11088 rem_anchor_token(T_WIDE_STRING_LITERAL);
11089 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
11090 rem_anchor_token(T_STRING_LITERAL);
11091 rem_anchor_token(T_PLUSPLUS);
11092 rem_anchor_token(T_MINUSMINUS);
11093 rem_anchor_token(T_INTEGER);
11094 rem_anchor_token(T_IDENTIFIER);
11095 rem_anchor_token(T_FLOATINGPOINT);
11096 rem_anchor_token(T_COLONCOLON);
11097 rem_anchor_token(T_CHARACTER_CONSTANT);
11098 rem_anchor_token('~');
11099 rem_anchor_token('{');
11100 rem_anchor_token('-');
11101 rem_anchor_token('+');
11102 rem_anchor_token('*');
11103 rem_anchor_token('(');
11104 rem_anchor_token('&');
11105 rem_anchor_token('!');
11106 rem_anchor_token('}');
11107 assert(current_scope == &statement->compound.scope);
11108 scope_pop(old_scope);
11109 environment_pop_to(top);
11116 * Check for unused global static functions and variables
11118 static void check_unused_globals(void)
11120 if (!warning.unused_function && !warning.unused_variable)
11123 for (const entity_t *entity = file_scope->entities; entity != NULL;
11124 entity = entity->base.next) {
11125 if (!is_declaration(entity))
11128 const declaration_t *declaration = &entity->declaration;
11129 if (declaration->used ||
11130 declaration->modifiers & DM_UNUSED ||
11131 declaration->modifiers & DM_USED ||
11132 declaration->storage_class != STORAGE_CLASS_STATIC)
11135 type_t *const type = declaration->type;
11137 if (entity->kind == ENTITY_FUNCTION) {
11138 /* inhibit warning for static inline functions */
11139 if (entity->function.is_inline)
11142 s = entity->function.statement != NULL ? "defined" : "declared";
11147 warningf(&declaration->base.source_position, "'%#T' %s but not used",
11148 type, declaration->base.symbol, s);
11152 static void parse_global_asm(void)
11154 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
11157 expect('(', end_error);
11159 statement->asms.asm_text = parse_string_literals();
11160 statement->base.next = unit->global_asm;
11161 unit->global_asm = statement;
11163 expect(')', end_error);
11164 expect(';', end_error);
11169 static void parse_linkage_specification(void)
11172 assert(token.type == T_STRING_LITERAL);
11174 const char *linkage = parse_string_literals().begin;
11176 linkage_kind_t old_linkage = current_linkage;
11177 linkage_kind_t new_linkage;
11178 if (strcmp(linkage, "C") == 0) {
11179 new_linkage = LINKAGE_C;
11180 } else if (strcmp(linkage, "C++") == 0) {
11181 new_linkage = LINKAGE_CXX;
11183 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
11184 new_linkage = LINKAGE_INVALID;
11186 current_linkage = new_linkage;
11188 if (token.type == '{') {
11191 expect('}', end_error);
11197 assert(current_linkage == new_linkage);
11198 current_linkage = old_linkage;
11201 static void parse_external(void)
11203 switch (token.type) {
11204 DECLARATION_START_NO_EXTERN
11206 case T___extension__:
11207 /* tokens below are for implicit int */
11208 case '&': /* & x; -> int& x; (and error later, because C++ has no
11210 case '*': /* * x; -> int* x; */
11211 case '(': /* (x); -> int (x); */
11212 parse_external_declaration();
11216 if (look_ahead(1)->type == T_STRING_LITERAL) {
11217 parse_linkage_specification();
11219 parse_external_declaration();
11224 parse_global_asm();
11228 parse_namespace_definition();
11232 if (!strict_mode) {
11234 warningf(HERE, "stray ';' outside of function");
11241 errorf(HERE, "stray %K outside of function", &token);
11242 if (token.type == '(' || token.type == '{' || token.type == '[')
11243 eat_until_matching_token(token.type);
11249 static void parse_externals(void)
11251 add_anchor_token('}');
11252 add_anchor_token(T_EOF);
11255 unsigned char token_anchor_copy[T_LAST_TOKEN];
11256 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
11259 while (token.type != T_EOF && token.type != '}') {
11261 bool anchor_leak = false;
11262 for (int i = 0; i != T_LAST_TOKEN; ++i) {
11263 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
11265 errorf(HERE, "Leaked anchor token %k %d times", i, count);
11266 anchor_leak = true;
11269 if (in_gcc_extension) {
11270 errorf(HERE, "Leaked __extension__");
11271 anchor_leak = true;
11281 rem_anchor_token(T_EOF);
11282 rem_anchor_token('}');
11286 * Parse a translation unit.
11288 static void parse_translation_unit(void)
11290 add_anchor_token(T_EOF);
11295 if (token.type == T_EOF)
11298 errorf(HERE, "stray %K outside of function", &token);
11299 if (token.type == '(' || token.type == '{' || token.type == '[')
11300 eat_until_matching_token(token.type);
11308 * @return the translation unit or NULL if errors occurred.
11310 void start_parsing(void)
11312 environment_stack = NEW_ARR_F(stack_entry_t, 0);
11313 label_stack = NEW_ARR_F(stack_entry_t, 0);
11314 diagnostic_count = 0;
11318 type_set_output(stderr);
11319 ast_set_output(stderr);
11321 assert(unit == NULL);
11322 unit = allocate_ast_zero(sizeof(unit[0]));
11324 assert(file_scope == NULL);
11325 file_scope = &unit->scope;
11327 assert(current_scope == NULL);
11328 scope_push(&unit->scope);
11331 translation_unit_t *finish_parsing(void)
11333 assert(current_scope == &unit->scope);
11336 assert(file_scope == &unit->scope);
11337 check_unused_globals();
11340 DEL_ARR_F(environment_stack);
11341 DEL_ARR_F(label_stack);
11343 translation_unit_t *result = unit;
11348 /* GCC allows global arrays without size and assigns them a length of one,
11349 * if no different declaration follows */
11350 static void complete_incomplete_arrays(void)
11352 size_t n = ARR_LEN(incomplete_arrays);
11353 for (size_t i = 0; i != n; ++i) {
11354 declaration_t *const decl = incomplete_arrays[i];
11355 type_t *const orig_type = decl->type;
11356 type_t *const type = skip_typeref(orig_type);
11358 if (!is_type_incomplete(type))
11361 if (warning.other) {
11362 warningf(&decl->base.source_position,
11363 "array '%#T' assumed to have one element",
11364 orig_type, decl->base.symbol);
11367 type_t *const new_type = duplicate_type(type);
11368 new_type->array.size_constant = true;
11369 new_type->array.has_implicit_size = true;
11370 new_type->array.size = 1;
11372 type_t *const result = typehash_insert(new_type);
11373 if (type != result)
11376 decl->type = result;
11382 lookahead_bufpos = 0;
11383 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
11386 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
11387 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
11388 parse_translation_unit();
11389 complete_incomplete_arrays();
11390 DEL_ARR_F(incomplete_arrays);
11391 incomplete_arrays = NULL;
11395 * Initialize the parser.
11397 void init_parser(void)
11399 sym_anonymous = symbol_table_insert("<anonymous>");
11401 if (c_mode & _MS) {
11402 /* add predefined symbols for extended-decl-modifier */
11403 sym_align = symbol_table_insert("align");
11404 sym_allocate = symbol_table_insert("allocate");
11405 sym_dllimport = symbol_table_insert("dllimport");
11406 sym_dllexport = symbol_table_insert("dllexport");
11407 sym_naked = symbol_table_insert("naked");
11408 sym_noinline = symbol_table_insert("noinline");
11409 sym_returns_twice = symbol_table_insert("returns_twice");
11410 sym_noreturn = symbol_table_insert("noreturn");
11411 sym_nothrow = symbol_table_insert("nothrow");
11412 sym_novtable = symbol_table_insert("novtable");
11413 sym_property = symbol_table_insert("property");
11414 sym_get = symbol_table_insert("get");
11415 sym_put = symbol_table_insert("put");
11416 sym_selectany = symbol_table_insert("selectany");
11417 sym_thread = symbol_table_insert("thread");
11418 sym_uuid = symbol_table_insert("uuid");
11419 sym_deprecated = symbol_table_insert("deprecated");
11420 sym_restrict = symbol_table_insert("restrict");
11421 sym_noalias = symbol_table_insert("noalias");
11423 memset(token_anchor_set, 0, sizeof(token_anchor_set));
11425 init_expression_parsers();
11426 obstack_init(&temp_obst);
11428 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11429 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11433 * Terminate the parser.
11435 void exit_parser(void)
11437 obstack_free(&temp_obst, NULL);