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 expression = expression->unary.value;
1039 /* TODO: not correct yet, should be any constant integer expression
1040 * which evaluates to 0 */
1041 if (expression->kind != EXPR_CONST)
1044 type_t *const type = skip_typeref(expression->base.type);
1045 if (!is_type_integer(type))
1048 return expression->conste.v.int_value == 0;
1052 * Create an implicit cast expression.
1054 * @param expression the expression to cast
1055 * @param dest_type the destination type
1057 static expression_t *create_implicit_cast(expression_t *expression,
1060 type_t *const source_type = expression->base.type;
1062 if (source_type == dest_type)
1065 return create_cast_expression(expression, dest_type);
1068 typedef enum assign_error_t {
1070 ASSIGN_ERROR_INCOMPATIBLE,
1071 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1072 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1073 ASSIGN_WARNING_POINTER_FROM_INT,
1074 ASSIGN_WARNING_INT_FROM_POINTER
1077 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1078 const expression_t *const right,
1079 const char *context,
1080 const source_position_t *source_position)
1082 type_t *const orig_type_right = right->base.type;
1083 type_t *const type_left = skip_typeref(orig_type_left);
1084 type_t *const type_right = skip_typeref(orig_type_right);
1087 case ASSIGN_SUCCESS:
1089 case ASSIGN_ERROR_INCOMPATIBLE:
1090 errorf(source_position,
1091 "destination type '%T' in %s is incompatible with type '%T'",
1092 orig_type_left, context, orig_type_right);
1095 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1096 if (warning.other) {
1097 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1098 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1100 /* the left type has all qualifiers from the right type */
1101 unsigned missing_qualifiers
1102 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1103 warningf(source_position,
1104 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1105 orig_type_left, context, orig_type_right, missing_qualifiers);
1110 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1111 if (warning.other) {
1112 warningf(source_position,
1113 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1114 orig_type_left, context, right, orig_type_right);
1118 case ASSIGN_WARNING_POINTER_FROM_INT:
1119 if (warning.other) {
1120 warningf(source_position,
1121 "%s makes pointer '%T' from integer '%T' without a cast",
1122 context, orig_type_left, orig_type_right);
1126 case ASSIGN_WARNING_INT_FROM_POINTER:
1127 if (warning.other) {
1128 warningf(source_position,
1129 "%s makes integer '%T' from pointer '%T' without a cast",
1130 context, orig_type_left, orig_type_right);
1135 panic("invalid error value");
1139 /** Implements the rules from § 6.5.16.1 */
1140 static assign_error_t semantic_assign(type_t *orig_type_left,
1141 const expression_t *const right)
1143 type_t *const orig_type_right = right->base.type;
1144 type_t *const type_left = skip_typeref(orig_type_left);
1145 type_t *const type_right = skip_typeref(orig_type_right);
1147 if (is_type_pointer(type_left)) {
1148 if (is_null_pointer_constant(right)) {
1149 return ASSIGN_SUCCESS;
1150 } else if (is_type_pointer(type_right)) {
1151 type_t *points_to_left
1152 = skip_typeref(type_left->pointer.points_to);
1153 type_t *points_to_right
1154 = skip_typeref(type_right->pointer.points_to);
1155 assign_error_t res = ASSIGN_SUCCESS;
1157 /* the left type has all qualifiers from the right type */
1158 unsigned missing_qualifiers
1159 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1160 if (missing_qualifiers != 0) {
1161 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1164 points_to_left = get_unqualified_type(points_to_left);
1165 points_to_right = get_unqualified_type(points_to_right);
1167 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1170 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1171 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1172 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1175 if (!types_compatible(points_to_left, points_to_right)) {
1176 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1180 } else if (is_type_integer(type_right)) {
1181 return ASSIGN_WARNING_POINTER_FROM_INT;
1183 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1184 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1185 && is_type_pointer(type_right))) {
1186 return ASSIGN_SUCCESS;
1187 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1188 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1189 type_t *const unqual_type_left = get_unqualified_type(type_left);
1190 type_t *const unqual_type_right = get_unqualified_type(type_right);
1191 if (types_compatible(unqual_type_left, unqual_type_right)) {
1192 return ASSIGN_SUCCESS;
1194 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1195 return ASSIGN_WARNING_INT_FROM_POINTER;
1198 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1199 return ASSIGN_SUCCESS;
1201 return ASSIGN_ERROR_INCOMPATIBLE;
1204 static expression_t *parse_constant_expression(void)
1206 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1208 if (!is_constant_expression(result)) {
1209 errorf(&result->base.source_position,
1210 "expression '%E' is not constant", result);
1216 static expression_t *parse_assignment_expression(void)
1218 return parse_sub_expression(PREC_ASSIGNMENT);
1221 static string_t parse_string_literals(void)
1223 assert(token.type == T_STRING_LITERAL);
1224 string_t result = token.v.string;
1228 while (token.type == T_STRING_LITERAL) {
1229 result = concat_strings(&result, &token.v.string);
1236 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1237 [GNU_AK_CONST] = "const",
1238 [GNU_AK_VOLATILE] = "volatile",
1239 [GNU_AK_CDECL] = "cdecl",
1240 [GNU_AK_STDCALL] = "stdcall",
1241 [GNU_AK_FASTCALL] = "fastcall",
1242 [GNU_AK_DEPRECATED] = "deprecated",
1243 [GNU_AK_NOINLINE] = "noinline",
1244 [GNU_AK_RETURNS_TWICE] = "returns_twice",
1245 [GNU_AK_NORETURN] = "noreturn",
1246 [GNU_AK_NAKED] = "naked",
1247 [GNU_AK_PURE] = "pure",
1248 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1249 [GNU_AK_MALLOC] = "malloc",
1250 [GNU_AK_WEAK] = "weak",
1251 [GNU_AK_CONSTRUCTOR] = "constructor",
1252 [GNU_AK_DESTRUCTOR] = "destructor",
1253 [GNU_AK_NOTHROW] = "nothrow",
1254 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1255 [GNU_AK_COMMON] = "common",
1256 [GNU_AK_NOCOMMON] = "nocommon",
1257 [GNU_AK_PACKED] = "packed",
1258 [GNU_AK_SHARED] = "shared",
1259 [GNU_AK_NOTSHARED] = "notshared",
1260 [GNU_AK_USED] = "used",
1261 [GNU_AK_UNUSED] = "unused",
1262 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1263 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1264 [GNU_AK_LONGCALL] = "longcall",
1265 [GNU_AK_SHORTCALL] = "shortcall",
1266 [GNU_AK_LONG_CALL] = "long_call",
1267 [GNU_AK_SHORT_CALL] = "short_call",
1268 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1269 [GNU_AK_INTERRUPT] = "interrupt",
1270 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1271 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1272 [GNU_AK_NESTING] = "nesting",
1273 [GNU_AK_NEAR] = "near",
1274 [GNU_AK_FAR] = "far",
1275 [GNU_AK_SIGNAL] = "signal",
1276 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1277 [GNU_AK_TINY_DATA] = "tiny_data",
1278 [GNU_AK_SAVEALL] = "saveall",
1279 [GNU_AK_FLATTEN] = "flatten",
1280 [GNU_AK_SSEREGPARM] = "sseregparm",
1281 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1282 [GNU_AK_RETURN_TWICE] = "return_twice",
1283 [GNU_AK_MAY_ALIAS] = "may_alias",
1284 [GNU_AK_MS_STRUCT] = "ms_struct",
1285 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1286 [GNU_AK_DLLIMPORT] = "dllimport",
1287 [GNU_AK_DLLEXPORT] = "dllexport",
1288 [GNU_AK_ALIGNED] = "aligned",
1289 [GNU_AK_ALIAS] = "alias",
1290 [GNU_AK_SECTION] = "section",
1291 [GNU_AK_FORMAT] = "format",
1292 [GNU_AK_FORMAT_ARG] = "format_arg",
1293 [GNU_AK_WEAKREF] = "weakref",
1294 [GNU_AK_NONNULL] = "nonnull",
1295 [GNU_AK_TLS_MODEL] = "tls_model",
1296 [GNU_AK_VISIBILITY] = "visibility",
1297 [GNU_AK_REGPARM] = "regparm",
1298 [GNU_AK_MODE] = "mode",
1299 [GNU_AK_MODEL] = "model",
1300 [GNU_AK_TRAP_EXIT] = "trap_exit",
1301 [GNU_AK_SP_SWITCH] = "sp_switch",
1302 [GNU_AK_SENTINEL] = "sentinel"
1306 * compare two string, ignoring double underscores on the second.
1308 static int strcmp_underscore(const char *s1, const char *s2)
1310 if (s2[0] == '_' && s2[1] == '_') {
1311 size_t len2 = strlen(s2);
1312 size_t len1 = strlen(s1);
1313 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1314 return strncmp(s1, s2+2, len2-4);
1318 return strcmp(s1, s2);
1322 * Allocate a new gnu temporal attribute of given kind.
1324 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1326 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1327 attribute->kind = kind;
1328 attribute->next = NULL;
1329 attribute->invalid = false;
1330 attribute->have_arguments = false;
1336 * Parse one constant expression argument of the given attribute.
1338 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1340 expression_t *expression;
1341 add_anchor_token(')');
1342 expression = parse_constant_expression();
1343 rem_anchor_token(')');
1344 expect(')', end_error);
1345 attribute->u.argument = fold_constant(expression);
1348 attribute->invalid = true;
1352 * Parse a list of constant expressions arguments of the given attribute.
1354 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1356 argument_list_t **list = &attribute->u.arguments;
1357 argument_list_t *entry;
1358 expression_t *expression;
1359 add_anchor_token(')');
1360 add_anchor_token(',');
1362 expression = parse_constant_expression();
1363 entry = obstack_alloc(&temp_obst, sizeof(entry));
1364 entry->argument = fold_constant(expression);
1367 list = &entry->next;
1368 if (token.type != ',')
1372 rem_anchor_token(',');
1373 rem_anchor_token(')');
1374 expect(')', end_error);
1377 attribute->invalid = true;
1381 * Parse one string literal argument of the given attribute.
1383 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1386 add_anchor_token('(');
1387 if (token.type != T_STRING_LITERAL) {
1388 parse_error_expected("while parsing attribute directive",
1389 T_STRING_LITERAL, NULL);
1392 *string = parse_string_literals();
1393 rem_anchor_token('(');
1394 expect(')', end_error);
1397 attribute->invalid = true;
1401 * Parse one tls model of the given attribute.
1403 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1405 static const char *const tls_models[] = {
1411 string_t string = { NULL, 0 };
1412 parse_gnu_attribute_string_arg(attribute, &string);
1413 if (string.begin != NULL) {
1414 for (size_t i = 0; i < 4; ++i) {
1415 if (strcmp(tls_models[i], string.begin) == 0) {
1416 attribute->u.value = i;
1420 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1422 attribute->invalid = true;
1426 * Parse one tls model of the given attribute.
1428 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1430 static const char *const visibilities[] = {
1436 string_t string = { NULL, 0 };
1437 parse_gnu_attribute_string_arg(attribute, &string);
1438 if (string.begin != NULL) {
1439 for (size_t i = 0; i < 4; ++i) {
1440 if (strcmp(visibilities[i], string.begin) == 0) {
1441 attribute->u.value = i;
1445 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1447 attribute->invalid = true;
1451 * Parse one (code) model of the given attribute.
1453 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1455 static const char *const visibilities[] = {
1460 string_t string = { NULL, 0 };
1461 parse_gnu_attribute_string_arg(attribute, &string);
1462 if (string.begin != NULL) {
1463 for (int i = 0; i < 3; ++i) {
1464 if (strcmp(visibilities[i], string.begin) == 0) {
1465 attribute->u.value = i;
1469 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1471 attribute->invalid = true;
1475 * Parse one mode of the given attribute.
1477 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1479 /* TODO: find out what is allowed here... */
1481 /* at least: byte, word, pointer, list of machine modes
1482 * __XXX___ is interpreted as XXX */
1483 add_anchor_token(')');
1485 if (token.type != T_IDENTIFIER) {
1486 expect(T_IDENTIFIER, end_error);
1489 /* This isn't really correct, the backend should provide a list of machine
1490 * specific modes (according to gcc philosophy that is...) */
1491 const char *symbol_str = token.v.symbol->string;
1492 if (strcmp_underscore("QI", symbol_str) == 0 ||
1493 strcmp_underscore("byte", symbol_str) == 0) {
1494 attribute->u.akind = ATOMIC_TYPE_CHAR;
1495 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1496 attribute->u.akind = ATOMIC_TYPE_SHORT;
1497 } else if (strcmp_underscore("SI", symbol_str) == 0
1498 || strcmp_underscore("word", symbol_str) == 0
1499 || strcmp_underscore("pointer", symbol_str) == 0) {
1500 attribute->u.akind = ATOMIC_TYPE_INT;
1501 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1502 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1505 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1506 attribute->invalid = true;
1510 rem_anchor_token(')');
1511 expect(')', end_error);
1514 attribute->invalid = true;
1518 * Parse one interrupt argument of the given attribute.
1520 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1522 static const char *const interrupts[] = {
1529 string_t string = { NULL, 0 };
1530 parse_gnu_attribute_string_arg(attribute, &string);
1531 if (string.begin != NULL) {
1532 for (size_t i = 0; i < 5; ++i) {
1533 if (strcmp(interrupts[i], string.begin) == 0) {
1534 attribute->u.value = i;
1538 errorf(HERE, "'%s' is not an interrupt", string.begin);
1540 attribute->invalid = true;
1544 * Parse ( identifier, const expression, const expression )
1546 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1548 static const char *const format_names[] = {
1556 if (token.type != T_IDENTIFIER) {
1557 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1560 const char *name = token.v.symbol->string;
1561 for (i = 0; i < 4; ++i) {
1562 if (strcmp_underscore(format_names[i], name) == 0)
1566 if (warning.attribute)
1567 warningf(HERE, "'%s' is an unrecognized format function type", name);
1571 expect(',', end_error);
1572 add_anchor_token(')');
1573 add_anchor_token(',');
1574 parse_constant_expression();
1575 rem_anchor_token(',');
1576 rem_anchor_token(')');
1578 expect(',', end_error);
1579 add_anchor_token(')');
1580 parse_constant_expression();
1581 rem_anchor_token(')');
1582 expect(')', end_error);
1585 attribute->u.value = true;
1589 * Check that a given GNU attribute has no arguments.
1591 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1593 if (!attribute->have_arguments)
1596 /* should have no arguments */
1597 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1598 eat_until_matching_token('(');
1599 /* we have already consumed '(', so we stop before ')', eat it */
1601 attribute->invalid = true;
1605 * Parse one GNU attribute.
1607 * Note that attribute names can be specified WITH or WITHOUT
1608 * double underscores, ie const or __const__.
1610 * The following attributes are parsed without arguments
1635 * no_instrument_function
1636 * warn_unused_result
1653 * externally_visible
1661 * The following attributes are parsed with arguments
1662 * aligned( const expression )
1663 * alias( string literal )
1664 * section( string literal )
1665 * format( identifier, const expression, const expression )
1666 * format_arg( const expression )
1667 * tls_model( string literal )
1668 * visibility( string literal )
1669 * regparm( const expression )
1670 * model( string leteral )
1671 * trap_exit( const expression )
1672 * sp_switch( string literal )
1674 * The following attributes might have arguments
1675 * weak_ref( string literal )
1676 * non_null( const expression // ',' )
1677 * interrupt( string literal )
1678 * sentinel( constant expression )
1680 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1682 gnu_attribute_t *head = *attributes;
1683 gnu_attribute_t *last = *attributes;
1684 decl_modifiers_t modifiers = 0;
1685 gnu_attribute_t *attribute;
1687 eat(T___attribute__);
1688 expect('(', end_error);
1689 expect('(', end_error);
1691 if (token.type != ')') {
1692 /* find the end of the list */
1694 while (last->next != NULL)
1698 /* non-empty attribute list */
1701 if (token.type == T_const) {
1703 } else if (token.type == T_volatile) {
1705 } else if (token.type == T_cdecl) {
1706 /* __attribute__((cdecl)), WITH ms mode */
1708 } else if (token.type == T_IDENTIFIER) {
1709 const symbol_t *sym = token.v.symbol;
1712 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1719 for (i = 0; i < GNU_AK_LAST; ++i) {
1720 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1723 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1726 if (kind == GNU_AK_LAST) {
1727 if (warning.attribute)
1728 warningf(HERE, "'%s' attribute directive ignored", name);
1730 /* skip possible arguments */
1731 if (token.type == '(') {
1732 eat_until_matching_token(')');
1735 /* check for arguments */
1736 attribute = allocate_gnu_attribute(kind);
1737 if (token.type == '(') {
1739 if (token.type == ')') {
1740 /* empty args are allowed */
1743 attribute->have_arguments = true;
1747 case GNU_AK_VOLATILE:
1752 case GNU_AK_NOCOMMON:
1754 case GNU_AK_NOTSHARED:
1755 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1756 case GNU_AK_WARN_UNUSED_RESULT:
1757 case GNU_AK_LONGCALL:
1758 case GNU_AK_SHORTCALL:
1759 case GNU_AK_LONG_CALL:
1760 case GNU_AK_SHORT_CALL:
1761 case GNU_AK_FUNCTION_VECTOR:
1762 case GNU_AK_INTERRUPT_HANDLER:
1763 case GNU_AK_NMI_HANDLER:
1764 case GNU_AK_NESTING:
1768 case GNU_AK_EIGTHBIT_DATA:
1769 case GNU_AK_TINY_DATA:
1770 case GNU_AK_SAVEALL:
1771 case GNU_AK_FLATTEN:
1772 case GNU_AK_SSEREGPARM:
1773 case GNU_AK_EXTERNALLY_VISIBLE:
1774 case GNU_AK_RETURN_TWICE:
1775 case GNU_AK_MAY_ALIAS:
1776 case GNU_AK_MS_STRUCT:
1777 case GNU_AK_GCC_STRUCT:
1780 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1781 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1782 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1783 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1784 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1785 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1786 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1787 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1788 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1789 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1790 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1791 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1792 case GNU_AK_RETURNS_TWICE: modifiers |= DM_RETURNS_TWICE; goto no_arg;
1793 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1794 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1795 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1796 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1797 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1798 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1800 case GNU_AK_ALIGNED:
1801 /* __align__ may be used without an argument */
1802 if (attribute->have_arguments) {
1803 parse_gnu_attribute_const_arg(attribute);
1807 case GNU_AK_FORMAT_ARG:
1808 case GNU_AK_REGPARM:
1809 case GNU_AK_TRAP_EXIT:
1810 if (!attribute->have_arguments) {
1811 /* should have arguments */
1812 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1813 attribute->invalid = true;
1815 parse_gnu_attribute_const_arg(attribute);
1818 case GNU_AK_SECTION:
1819 case GNU_AK_SP_SWITCH:
1820 if (!attribute->have_arguments) {
1821 /* should have arguments */
1822 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1823 attribute->invalid = true;
1825 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1828 if (!attribute->have_arguments) {
1829 /* should have arguments */
1830 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1831 attribute->invalid = true;
1833 parse_gnu_attribute_format_args(attribute);
1835 case GNU_AK_WEAKREF:
1836 /* may have one string argument */
1837 if (attribute->have_arguments)
1838 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1840 case GNU_AK_NONNULL:
1841 if (attribute->have_arguments)
1842 parse_gnu_attribute_const_arg_list(attribute);
1844 case GNU_AK_TLS_MODEL:
1845 if (!attribute->have_arguments) {
1846 /* should have arguments */
1847 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1849 parse_gnu_attribute_tls_model_arg(attribute);
1851 case GNU_AK_VISIBILITY:
1852 if (!attribute->have_arguments) {
1853 /* should have arguments */
1854 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1856 parse_gnu_attribute_visibility_arg(attribute);
1859 if (!attribute->have_arguments) {
1860 /* should have arguments */
1861 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1863 parse_gnu_attribute_model_arg(attribute);
1867 if (!attribute->have_arguments) {
1868 /* should have arguments */
1869 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1871 parse_gnu_attribute_mode_arg(attribute);
1874 case GNU_AK_INTERRUPT:
1875 /* may have one string argument */
1876 if (attribute->have_arguments)
1877 parse_gnu_attribute_interrupt_arg(attribute);
1879 case GNU_AK_SENTINEL:
1880 /* may have one string argument */
1881 if (attribute->have_arguments)
1882 parse_gnu_attribute_const_arg(attribute);
1885 /* already handled */
1889 check_no_argument(attribute, name);
1892 if (attribute != NULL) {
1894 last->next = attribute;
1897 head = last = attribute;
1901 if (token.type != ',')
1906 expect(')', end_error);
1907 expect(')', end_error);
1915 * Parse GNU attributes.
1917 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1919 decl_modifiers_t modifiers = 0;
1922 switch (token.type) {
1923 case T___attribute__:
1924 modifiers |= parse_gnu_attribute(attributes);
1929 expect('(', end_error);
1930 if (token.type != T_STRING_LITERAL) {
1931 parse_error_expected("while parsing assembler attribute",
1932 T_STRING_LITERAL, NULL);
1933 eat_until_matching_token('(');
1936 parse_string_literals();
1938 expect(')', end_error);
1941 case T_cdecl: modifiers |= DM_CDECL; break;
1942 case T__fastcall: modifiers |= DM_FASTCALL; break;
1943 case T__stdcall: modifiers |= DM_STDCALL; break;
1946 /* TODO record modifier */
1948 warningf(HERE, "Ignoring declaration modifier %K", &token);
1952 default: return modifiers;
1959 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1961 static entity_t *determine_lhs_ent(expression_t *const expr,
1964 switch (expr->kind) {
1965 case EXPR_REFERENCE: {
1966 entity_t *const entity = expr->reference.entity;
1967 /* we should only find variables as lvalues... */
1968 if (entity->base.kind != ENTITY_VARIABLE
1969 && entity->base.kind != ENTITY_PARAMETER)
1975 case EXPR_ARRAY_ACCESS: {
1976 expression_t *const ref = expr->array_access.array_ref;
1977 entity_t * ent = NULL;
1978 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1979 ent = determine_lhs_ent(ref, lhs_ent);
1982 mark_vars_read(expr->select.compound, lhs_ent);
1984 mark_vars_read(expr->array_access.index, lhs_ent);
1989 if (is_type_compound(skip_typeref(expr->base.type))) {
1990 return determine_lhs_ent(expr->select.compound, lhs_ent);
1992 mark_vars_read(expr->select.compound, lhs_ent);
1997 case EXPR_UNARY_DEREFERENCE: {
1998 expression_t *const val = expr->unary.value;
1999 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
2001 return determine_lhs_ent(val->unary.value, lhs_ent);
2003 mark_vars_read(val, NULL);
2009 mark_vars_read(expr, NULL);
2014 #define ENT_ANY ((entity_t*)-1)
2017 * Mark declarations, which are read. This is used to detect variables, which
2021 * x is not marked as "read", because it is only read to calculate its own new
2025 * x and y are not detected as "not read", because multiple variables are
2028 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
2030 switch (expr->kind) {
2031 case EXPR_REFERENCE: {
2032 entity_t *const entity = expr->reference.entity;
2033 if (entity->kind != ENTITY_VARIABLE
2034 && entity->kind != ENTITY_PARAMETER)
2037 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
2038 if (entity->kind == ENTITY_VARIABLE) {
2039 entity->variable.read = true;
2041 entity->parameter.read = true;
2048 // TODO respect pure/const
2049 mark_vars_read(expr->call.function, NULL);
2050 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
2051 mark_vars_read(arg->expression, NULL);
2055 case EXPR_CONDITIONAL:
2056 // TODO lhs_decl should depend on whether true/false have an effect
2057 mark_vars_read(expr->conditional.condition, NULL);
2058 if (expr->conditional.true_expression != NULL)
2059 mark_vars_read(expr->conditional.true_expression, lhs_ent);
2060 mark_vars_read(expr->conditional.false_expression, lhs_ent);
2064 if (lhs_ent == ENT_ANY
2065 && !is_type_compound(skip_typeref(expr->base.type)))
2067 mark_vars_read(expr->select.compound, lhs_ent);
2070 case EXPR_ARRAY_ACCESS: {
2071 expression_t *const ref = expr->array_access.array_ref;
2072 mark_vars_read(ref, lhs_ent);
2073 lhs_ent = determine_lhs_ent(ref, lhs_ent);
2074 mark_vars_read(expr->array_access.index, lhs_ent);
2079 mark_vars_read(expr->va_arge.ap, lhs_ent);
2082 case EXPR_UNARY_CAST:
2083 /* Special case: Use void cast to mark a variable as "read" */
2084 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2089 case EXPR_UNARY_THROW:
2090 if (expr->unary.value == NULL)
2093 case EXPR_UNARY_DEREFERENCE:
2094 case EXPR_UNARY_DELETE:
2095 case EXPR_UNARY_DELETE_ARRAY:
2096 if (lhs_ent == ENT_ANY)
2100 case EXPR_UNARY_NEGATE:
2101 case EXPR_UNARY_PLUS:
2102 case EXPR_UNARY_BITWISE_NEGATE:
2103 case EXPR_UNARY_NOT:
2104 case EXPR_UNARY_TAKE_ADDRESS:
2105 case EXPR_UNARY_POSTFIX_INCREMENT:
2106 case EXPR_UNARY_POSTFIX_DECREMENT:
2107 case EXPR_UNARY_PREFIX_INCREMENT:
2108 case EXPR_UNARY_PREFIX_DECREMENT:
2109 case EXPR_UNARY_CAST_IMPLICIT:
2110 case EXPR_UNARY_ASSUME:
2112 mark_vars_read(expr->unary.value, lhs_ent);
2115 case EXPR_BINARY_ADD:
2116 case EXPR_BINARY_SUB:
2117 case EXPR_BINARY_MUL:
2118 case EXPR_BINARY_DIV:
2119 case EXPR_BINARY_MOD:
2120 case EXPR_BINARY_EQUAL:
2121 case EXPR_BINARY_NOTEQUAL:
2122 case EXPR_BINARY_LESS:
2123 case EXPR_BINARY_LESSEQUAL:
2124 case EXPR_BINARY_GREATER:
2125 case EXPR_BINARY_GREATEREQUAL:
2126 case EXPR_BINARY_BITWISE_AND:
2127 case EXPR_BINARY_BITWISE_OR:
2128 case EXPR_BINARY_BITWISE_XOR:
2129 case EXPR_BINARY_LOGICAL_AND:
2130 case EXPR_BINARY_LOGICAL_OR:
2131 case EXPR_BINARY_SHIFTLEFT:
2132 case EXPR_BINARY_SHIFTRIGHT:
2133 case EXPR_BINARY_COMMA:
2134 case EXPR_BINARY_ISGREATER:
2135 case EXPR_BINARY_ISGREATEREQUAL:
2136 case EXPR_BINARY_ISLESS:
2137 case EXPR_BINARY_ISLESSEQUAL:
2138 case EXPR_BINARY_ISLESSGREATER:
2139 case EXPR_BINARY_ISUNORDERED:
2140 mark_vars_read(expr->binary.left, lhs_ent);
2141 mark_vars_read(expr->binary.right, lhs_ent);
2144 case EXPR_BINARY_ASSIGN:
2145 case EXPR_BINARY_MUL_ASSIGN:
2146 case EXPR_BINARY_DIV_ASSIGN:
2147 case EXPR_BINARY_MOD_ASSIGN:
2148 case EXPR_BINARY_ADD_ASSIGN:
2149 case EXPR_BINARY_SUB_ASSIGN:
2150 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2151 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2152 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2153 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2154 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2155 if (lhs_ent == ENT_ANY)
2157 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
2158 mark_vars_read(expr->binary.right, lhs_ent);
2163 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
2169 case EXPR_CHARACTER_CONSTANT:
2170 case EXPR_WIDE_CHARACTER_CONSTANT:
2171 case EXPR_STRING_LITERAL:
2172 case EXPR_WIDE_STRING_LITERAL:
2173 case EXPR_COMPOUND_LITERAL: // TODO init?
2175 case EXPR_CLASSIFY_TYPE:
2178 case EXPR_BUILTIN_SYMBOL:
2179 case EXPR_BUILTIN_CONSTANT_P:
2180 case EXPR_BUILTIN_PREFETCH:
2182 case EXPR_STATEMENT: // TODO
2183 case EXPR_LABEL_ADDRESS:
2184 case EXPR_REFERENCE_ENUM_VALUE:
2188 panic("unhandled expression");
2191 static designator_t *parse_designation(void)
2193 designator_t *result = NULL;
2194 designator_t *last = NULL;
2197 designator_t *designator;
2198 switch (token.type) {
2200 designator = allocate_ast_zero(sizeof(designator[0]));
2201 designator->source_position = token.source_position;
2203 add_anchor_token(']');
2204 designator->array_index = parse_constant_expression();
2205 rem_anchor_token(']');
2206 expect(']', end_error);
2209 designator = allocate_ast_zero(sizeof(designator[0]));
2210 designator->source_position = token.source_position;
2212 if (token.type != T_IDENTIFIER) {
2213 parse_error_expected("while parsing designator",
2214 T_IDENTIFIER, NULL);
2217 designator->symbol = token.v.symbol;
2221 expect('=', end_error);
2225 assert(designator != NULL);
2227 last->next = designator;
2229 result = designator;
2237 static initializer_t *initializer_from_string(array_type_t *type,
2238 const string_t *const string)
2240 /* TODO: check len vs. size of array type */
2243 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2244 initializer->string.string = *string;
2249 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2250 wide_string_t *const string)
2252 /* TODO: check len vs. size of array type */
2255 initializer_t *const initializer =
2256 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2257 initializer->wide_string.string = *string;
2263 * Build an initializer from a given expression.
2265 static initializer_t *initializer_from_expression(type_t *orig_type,
2266 expression_t *expression)
2268 /* TODO check that expression is a constant expression */
2270 /* § 6.7.8.14/15 char array may be initialized by string literals */
2271 type_t *type = skip_typeref(orig_type);
2272 type_t *expr_type_orig = expression->base.type;
2273 type_t *expr_type = skip_typeref(expr_type_orig);
2274 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2275 array_type_t *const array_type = &type->array;
2276 type_t *const element_type = skip_typeref(array_type->element_type);
2278 if (element_type->kind == TYPE_ATOMIC) {
2279 atomic_type_kind_t akind = element_type->atomic.akind;
2280 switch (expression->kind) {
2281 case EXPR_STRING_LITERAL:
2282 if (akind == ATOMIC_TYPE_CHAR
2283 || akind == ATOMIC_TYPE_SCHAR
2284 || akind == ATOMIC_TYPE_UCHAR) {
2285 return initializer_from_string(array_type,
2286 &expression->string.value);
2289 case EXPR_WIDE_STRING_LITERAL: {
2290 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2291 if (get_unqualified_type(element_type) == bare_wchar_type) {
2292 return initializer_from_wide_string(array_type,
2293 &expression->wide_string.value);
2303 assign_error_t error = semantic_assign(type, expression);
2304 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2306 report_assign_error(error, type, expression, "initializer",
2307 &expression->base.source_position);
2309 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2311 if (type->kind == TYPE_BITFIELD) {
2312 type = type->bitfield.base_type;
2315 result->value.value = create_implicit_cast(expression, type);
2321 * Checks if a given expression can be used as an constant initializer.
2323 static bool is_initializer_constant(const expression_t *expression)
2325 return is_constant_expression(expression)
2326 || is_address_constant(expression);
2330 * Parses an scalar initializer.
2332 * § 6.7.8.11; eat {} without warning
2334 static initializer_t *parse_scalar_initializer(type_t *type,
2335 bool must_be_constant)
2337 /* there might be extra {} hierarchies */
2339 if (token.type == '{') {
2341 warningf(HERE, "extra curly braces around scalar initializer");
2345 } while (token.type == '{');
2348 expression_t *expression = parse_assignment_expression();
2349 mark_vars_read(expression, NULL);
2350 if (must_be_constant && !is_initializer_constant(expression)) {
2351 errorf(&expression->base.source_position,
2352 "Initialisation expression '%E' is not constant",
2356 initializer_t *initializer = initializer_from_expression(type, expression);
2358 if (initializer == NULL) {
2359 errorf(&expression->base.source_position,
2360 "expression '%E' (type '%T') doesn't match expected type '%T'",
2361 expression, expression->base.type, type);
2366 bool additional_warning_displayed = false;
2367 while (braces > 0) {
2368 if (token.type == ',') {
2371 if (token.type != '}') {
2372 if (!additional_warning_displayed && warning.other) {
2373 warningf(HERE, "additional elements in scalar initializer");
2374 additional_warning_displayed = true;
2385 * An entry in the type path.
2387 typedef struct type_path_entry_t type_path_entry_t;
2388 struct type_path_entry_t {
2389 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2391 size_t index; /**< For array types: the current index. */
2392 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2397 * A type path expression a position inside compound or array types.
2399 typedef struct type_path_t type_path_t;
2400 struct type_path_t {
2401 type_path_entry_t *path; /**< An flexible array containing the current path. */
2402 type_t *top_type; /**< type of the element the path points */
2403 size_t max_index; /**< largest index in outermost array */
2407 * Prints a type path for debugging.
2409 static __attribute__((unused)) void debug_print_type_path(
2410 const type_path_t *path)
2412 size_t len = ARR_LEN(path->path);
2414 for (size_t i = 0; i < len; ++i) {
2415 const type_path_entry_t *entry = & path->path[i];
2417 type_t *type = skip_typeref(entry->type);
2418 if (is_type_compound(type)) {
2419 /* in gcc mode structs can have no members */
2420 if (entry->v.compound_entry == NULL) {
2424 fprintf(stderr, ".%s",
2425 entry->v.compound_entry->base.symbol->string);
2426 } else if (is_type_array(type)) {
2427 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
2429 fprintf(stderr, "-INVALID-");
2432 if (path->top_type != NULL) {
2433 fprintf(stderr, " (");
2434 print_type(path->top_type);
2435 fprintf(stderr, ")");
2440 * Return the top type path entry, ie. in a path
2441 * (type).a.b returns the b.
2443 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2445 size_t len = ARR_LEN(path->path);
2447 return &path->path[len-1];
2451 * Enlarge the type path by an (empty) element.
2453 static type_path_entry_t *append_to_type_path(type_path_t *path)
2455 size_t len = ARR_LEN(path->path);
2456 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2458 type_path_entry_t *result = & path->path[len];
2459 memset(result, 0, sizeof(result[0]));
2464 * Descending into a sub-type. Enter the scope of the current top_type.
2466 static void descend_into_subtype(type_path_t *path)
2468 type_t *orig_top_type = path->top_type;
2469 type_t *top_type = skip_typeref(orig_top_type);
2471 type_path_entry_t *top = append_to_type_path(path);
2472 top->type = top_type;
2474 if (is_type_compound(top_type)) {
2475 compound_t *compound = top_type->compound.compound;
2476 entity_t *entry = compound->members.entities;
2478 if (entry != NULL) {
2479 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2480 top->v.compound_entry = &entry->declaration;
2481 path->top_type = entry->declaration.type;
2483 path->top_type = NULL;
2485 } else if (is_type_array(top_type)) {
2487 path->top_type = top_type->array.element_type;
2489 assert(!is_type_valid(top_type));
2494 * Pop an entry from the given type path, ie. returning from
2495 * (type).a.b to (type).a
2497 static void ascend_from_subtype(type_path_t *path)
2499 type_path_entry_t *top = get_type_path_top(path);
2501 path->top_type = top->type;
2503 size_t len = ARR_LEN(path->path);
2504 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2508 * Pop entries from the given type path until the given
2509 * path level is reached.
2511 static void ascend_to(type_path_t *path, size_t top_path_level)
2513 size_t len = ARR_LEN(path->path);
2515 while (len > top_path_level) {
2516 ascend_from_subtype(path);
2517 len = ARR_LEN(path->path);
2521 static bool walk_designator(type_path_t *path, const designator_t *designator,
2522 bool used_in_offsetof)
2524 for (; designator != NULL; designator = designator->next) {
2525 type_path_entry_t *top = get_type_path_top(path);
2526 type_t *orig_type = top->type;
2528 type_t *type = skip_typeref(orig_type);
2530 if (designator->symbol != NULL) {
2531 symbol_t *symbol = designator->symbol;
2532 if (!is_type_compound(type)) {
2533 if (is_type_valid(type)) {
2534 errorf(&designator->source_position,
2535 "'.%Y' designator used for non-compound type '%T'",
2539 top->type = type_error_type;
2540 top->v.compound_entry = NULL;
2541 orig_type = type_error_type;
2543 compound_t *compound = type->compound.compound;
2544 entity_t *iter = compound->members.entities;
2545 for (; iter != NULL; iter = iter->base.next) {
2546 if (iter->base.symbol == symbol) {
2551 errorf(&designator->source_position,
2552 "'%T' has no member named '%Y'", orig_type, symbol);
2555 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2556 if (used_in_offsetof) {
2557 type_t *real_type = skip_typeref(iter->declaration.type);
2558 if (real_type->kind == TYPE_BITFIELD) {
2559 errorf(&designator->source_position,
2560 "offsetof designator '%Y' may not specify bitfield",
2566 top->type = orig_type;
2567 top->v.compound_entry = &iter->declaration;
2568 orig_type = iter->declaration.type;
2571 expression_t *array_index = designator->array_index;
2572 assert(designator->array_index != NULL);
2574 if (!is_type_array(type)) {
2575 if (is_type_valid(type)) {
2576 errorf(&designator->source_position,
2577 "[%E] designator used for non-array type '%T'",
2578 array_index, orig_type);
2583 long index = fold_constant(array_index);
2584 if (!used_in_offsetof) {
2586 errorf(&designator->source_position,
2587 "array index [%E] must be positive", array_index);
2588 } else if (type->array.size_constant) {
2589 long array_size = type->array.size;
2590 if (index >= array_size) {
2591 errorf(&designator->source_position,
2592 "designator [%E] (%d) exceeds array size %d",
2593 array_index, index, array_size);
2598 top->type = orig_type;
2599 top->v.index = (size_t) index;
2600 orig_type = type->array.element_type;
2602 path->top_type = orig_type;
2604 if (designator->next != NULL) {
2605 descend_into_subtype(path);
2614 static void advance_current_object(type_path_t *path, size_t top_path_level)
2616 type_path_entry_t *top = get_type_path_top(path);
2618 type_t *type = skip_typeref(top->type);
2619 if (is_type_union(type)) {
2620 /* in unions only the first element is initialized */
2621 top->v.compound_entry = NULL;
2622 } else if (is_type_struct(type)) {
2623 declaration_t *entry = top->v.compound_entry;
2625 entity_t *next_entity = entry->base.next;
2626 if (next_entity != NULL) {
2627 assert(is_declaration(next_entity));
2628 entry = &next_entity->declaration;
2633 top->v.compound_entry = entry;
2634 if (entry != NULL) {
2635 path->top_type = entry->type;
2638 } else if (is_type_array(type)) {
2639 assert(is_type_array(type));
2643 if (!type->array.size_constant || top->v.index < type->array.size) {
2647 assert(!is_type_valid(type));
2651 /* we're past the last member of the current sub-aggregate, try if we
2652 * can ascend in the type hierarchy and continue with another subobject */
2653 size_t len = ARR_LEN(path->path);
2655 if (len > top_path_level) {
2656 ascend_from_subtype(path);
2657 advance_current_object(path, top_path_level);
2659 path->top_type = NULL;
2664 * skip until token is found.
2666 static void skip_until(int type)
2668 while (token.type != type) {
2669 if (token.type == T_EOF)
2676 * skip any {...} blocks until a closing bracket is reached.
2678 static void skip_initializers(void)
2680 if (token.type == '{')
2683 while (token.type != '}') {
2684 if (token.type == T_EOF)
2686 if (token.type == '{') {
2694 static initializer_t *create_empty_initializer(void)
2696 static initializer_t empty_initializer
2697 = { .list = { { INITIALIZER_LIST }, 0 } };
2698 return &empty_initializer;
2702 * Parse a part of an initialiser for a struct or union,
2704 static initializer_t *parse_sub_initializer(type_path_t *path,
2705 type_t *outer_type, size_t top_path_level,
2706 parse_initializer_env_t *env)
2708 if (token.type == '}') {
2709 /* empty initializer */
2710 return create_empty_initializer();
2713 type_t *orig_type = path->top_type;
2714 type_t *type = NULL;
2716 if (orig_type == NULL) {
2717 /* We are initializing an empty compound. */
2719 type = skip_typeref(orig_type);
2722 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2725 designator_t *designator = NULL;
2726 if (token.type == '.' || token.type == '[') {
2727 designator = parse_designation();
2728 goto finish_designator;
2729 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2730 /* GNU-style designator ("identifier: value") */
2731 designator = allocate_ast_zero(sizeof(designator[0]));
2732 designator->source_position = token.source_position;
2733 designator->symbol = token.v.symbol;
2738 /* reset path to toplevel, evaluate designator from there */
2739 ascend_to(path, top_path_level);
2740 if (!walk_designator(path, designator, false)) {
2741 /* can't continue after designation error */
2745 initializer_t *designator_initializer
2746 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2747 designator_initializer->designator.designator = designator;
2748 ARR_APP1(initializer_t*, initializers, designator_initializer);
2750 orig_type = path->top_type;
2751 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2756 if (token.type == '{') {
2757 if (type != NULL && is_type_scalar(type)) {
2758 sub = parse_scalar_initializer(type, env->must_be_constant);
2762 if (env->entity != NULL) {
2764 "extra brace group at end of initializer for '%Y'",
2765 env->entity->base.symbol);
2767 errorf(HERE, "extra brace group at end of initializer");
2770 descend_into_subtype(path);
2772 add_anchor_token('}');
2773 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2775 rem_anchor_token('}');
2778 ascend_from_subtype(path);
2779 expect('}', end_error);
2781 expect('}', end_error);
2782 goto error_parse_next;
2786 /* must be an expression */
2787 expression_t *expression = parse_assignment_expression();
2788 mark_vars_read(expression, NULL);
2790 if (env->must_be_constant && !is_initializer_constant(expression)) {
2791 errorf(&expression->base.source_position,
2792 "Initialisation expression '%E' is not constant",
2797 /* we are already outside, ... */
2798 type_t *const outer_type_skip = skip_typeref(outer_type);
2799 if (is_type_compound(outer_type_skip) &&
2800 !outer_type_skip->compound.compound->complete) {
2801 goto error_parse_next;
2806 /* handle { "string" } special case */
2807 if ((expression->kind == EXPR_STRING_LITERAL
2808 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2809 && outer_type != NULL) {
2810 sub = initializer_from_expression(outer_type, expression);
2812 if (token.type == ',') {
2815 if (token.type != '}' && warning.other) {
2816 warningf(HERE, "excessive elements in initializer for type '%T'",
2819 /* TODO: eat , ... */
2824 /* descend into subtypes until expression matches type */
2826 orig_type = path->top_type;
2827 type = skip_typeref(orig_type);
2829 sub = initializer_from_expression(orig_type, expression);
2833 if (!is_type_valid(type)) {
2836 if (is_type_scalar(type)) {
2837 errorf(&expression->base.source_position,
2838 "expression '%E' doesn't match expected type '%T'",
2839 expression, orig_type);
2843 descend_into_subtype(path);
2847 /* update largest index of top array */
2848 const type_path_entry_t *first = &path->path[0];
2849 type_t *first_type = first->type;
2850 first_type = skip_typeref(first_type);
2851 if (is_type_array(first_type)) {
2852 size_t index = first->v.index;
2853 if (index > path->max_index)
2854 path->max_index = index;
2858 /* append to initializers list */
2859 ARR_APP1(initializer_t*, initializers, sub);
2862 if (warning.other) {
2863 if (env->entity != NULL) {
2864 warningf(HERE, "excess elements in struct initializer for '%Y'",
2865 env->entity->base.symbol);
2867 warningf(HERE, "excess elements in struct initializer");
2873 if (token.type == '}') {
2876 expect(',', end_error);
2877 if (token.type == '}') {
2882 /* advance to the next declaration if we are not at the end */
2883 advance_current_object(path, top_path_level);
2884 orig_type = path->top_type;
2885 if (orig_type != NULL)
2886 type = skip_typeref(orig_type);
2892 size_t len = ARR_LEN(initializers);
2893 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2894 initializer_t *result = allocate_ast_zero(size);
2895 result->kind = INITIALIZER_LIST;
2896 result->list.len = len;
2897 memcpy(&result->list.initializers, initializers,
2898 len * sizeof(initializers[0]));
2900 DEL_ARR_F(initializers);
2901 ascend_to(path, top_path_level+1);
2906 skip_initializers();
2907 DEL_ARR_F(initializers);
2908 ascend_to(path, top_path_level+1);
2913 * Parses an initializer. Parsers either a compound literal
2914 * (env->declaration == NULL) or an initializer of a declaration.
2916 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2918 type_t *type = skip_typeref(env->type);
2919 size_t max_index = 0xdeadbeaf; // TODO: Resolve this uninitialized variable problem
2920 initializer_t *result;
2922 if (is_type_scalar(type)) {
2923 result = parse_scalar_initializer(type, env->must_be_constant);
2924 } else if (token.type == '{') {
2928 memset(&path, 0, sizeof(path));
2929 path.top_type = env->type;
2930 path.path = NEW_ARR_F(type_path_entry_t, 0);
2932 descend_into_subtype(&path);
2934 add_anchor_token('}');
2935 result = parse_sub_initializer(&path, env->type, 1, env);
2936 rem_anchor_token('}');
2938 max_index = path.max_index;
2939 DEL_ARR_F(path.path);
2941 expect('}', end_error);
2943 /* parse_scalar_initializer() also works in this case: we simply
2944 * have an expression without {} around it */
2945 result = parse_scalar_initializer(type, env->must_be_constant);
2948 /* § 6.7.8 (22) array initializers for arrays with unknown size determine
2949 * the array type size */
2950 if (is_type_array(type) && type->array.size_expression == NULL
2951 && result != NULL) {
2953 switch (result->kind) {
2954 case INITIALIZER_LIST:
2955 assert(max_index != 0xdeadbeaf);
2956 size = max_index + 1;
2959 case INITIALIZER_STRING:
2960 size = result->string.string.size;
2963 case INITIALIZER_WIDE_STRING:
2964 size = result->wide_string.string.size;
2967 case INITIALIZER_DESIGNATOR:
2968 case INITIALIZER_VALUE:
2969 /* can happen for parse errors */
2974 internal_errorf(HERE, "invalid initializer type");
2977 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2978 cnst->base.type = type_size_t;
2979 cnst->conste.v.int_value = size;
2981 type_t *new_type = duplicate_type(type);
2983 new_type->array.size_expression = cnst;
2984 new_type->array.size_constant = true;
2985 new_type->array.has_implicit_size = true;
2986 new_type->array.size = size;
2987 env->type = new_type;
2995 static void append_entity(scope_t *scope, entity_t *entity)
2997 if (scope->last_entity != NULL) {
2998 scope->last_entity->base.next = entity;
3000 scope->entities = entity;
3002 scope->last_entity = entity;
3006 static compound_t *parse_compound_type_specifier(bool is_struct)
3008 gnu_attribute_t *attributes = NULL;
3009 decl_modifiers_t modifiers = 0;
3016 symbol_t *symbol = NULL;
3017 compound_t *compound = NULL;
3019 if (token.type == T___attribute__) {
3020 modifiers |= parse_attributes(&attributes);
3023 if (token.type == T_IDENTIFIER) {
3024 symbol = token.v.symbol;
3027 namespace_tag_t const namespc =
3028 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
3029 entity_t *entity = get_entity(symbol, namespc);
3030 if (entity != NULL) {
3031 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
3032 compound = &entity->compound;
3033 if (compound->base.parent_scope != current_scope &&
3034 (token.type == '{' || token.type == ';')) {
3035 /* we're in an inner scope and have a definition. Override
3036 existing definition in outer scope */
3038 } else if (compound->complete && token.type == '{') {
3039 assert(symbol != NULL);
3040 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
3041 is_struct ? "struct" : "union", symbol,
3042 &compound->base.source_position);
3043 /* clear members in the hope to avoid further errors */
3044 compound->members.entities = NULL;
3047 } else if (token.type != '{') {
3049 parse_error_expected("while parsing struct type specifier",
3050 T_IDENTIFIER, '{', NULL);
3052 parse_error_expected("while parsing union type specifier",
3053 T_IDENTIFIER, '{', NULL);
3059 if (compound == NULL) {
3060 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
3061 entity_t *entity = allocate_entity_zero(kind);
3062 compound = &entity->compound;
3064 compound->base.namespc =
3065 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
3066 compound->base.source_position = token.source_position;
3067 compound->base.symbol = symbol;
3068 compound->base.parent_scope = current_scope;
3069 if (symbol != NULL) {
3070 environment_push(entity);
3072 append_entity(current_scope, entity);
3075 if (token.type == '{') {
3076 parse_compound_type_entries(compound);
3077 modifiers |= parse_attributes(&attributes);
3079 if (symbol == NULL) {
3080 assert(anonymous_entity == NULL);
3081 anonymous_entity = (entity_t*)compound;
3085 compound->modifiers |= modifiers;
3089 static void parse_enum_entries(type_t *const enum_type)
3093 if (token.type == '}') {
3094 errorf(HERE, "empty enum not allowed");
3099 add_anchor_token('}');
3101 if (token.type != T_IDENTIFIER) {
3102 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3104 rem_anchor_token('}');
3108 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3109 entity->enum_value.enum_type = enum_type;
3110 entity->base.symbol = token.v.symbol;
3111 entity->base.source_position = token.source_position;
3114 if (token.type == '=') {
3116 expression_t *value = parse_constant_expression();
3118 value = create_implicit_cast(value, enum_type);
3119 entity->enum_value.value = value;
3124 record_entity(entity, false);
3126 if (token.type != ',')
3129 } while (token.type != '}');
3130 rem_anchor_token('}');
3132 expect('}', end_error);
3138 static type_t *parse_enum_specifier(void)
3140 gnu_attribute_t *attributes = NULL;
3145 if (token.type == T_IDENTIFIER) {
3146 symbol = token.v.symbol;
3149 entity = get_entity(symbol, NAMESPACE_ENUM);
3150 assert(entity == NULL || entity->kind == ENTITY_ENUM);
3151 } else if (token.type != '{') {
3152 parse_error_expected("while parsing enum type specifier",
3153 T_IDENTIFIER, '{', NULL);
3160 if (entity == NULL) {
3161 entity = allocate_entity_zero(ENTITY_ENUM);
3162 entity->base.namespc = NAMESPACE_ENUM;
3163 entity->base.source_position = token.source_position;
3164 entity->base.symbol = symbol;
3165 entity->base.parent_scope = current_scope;
3168 type_t *const type = allocate_type_zero(TYPE_ENUM);
3169 type->enumt.enume = &entity->enume;
3171 if (token.type == '{') {
3172 if (entity->enume.complete) {
3173 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
3174 symbol, &entity->base.source_position);
3176 if (symbol != NULL) {
3177 environment_push(entity);
3179 append_entity(current_scope, entity);
3180 entity->enume.complete = true;
3182 parse_enum_entries(type);
3183 parse_attributes(&attributes);
3185 if (symbol == NULL) {
3186 assert(anonymous_entity == NULL);
3187 anonymous_entity = entity;
3189 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
3190 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
3198 * if a symbol is a typedef to another type, return true
3200 static bool is_typedef_symbol(symbol_t *symbol)
3202 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3203 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3206 static type_t *parse_typeof(void)
3212 expect('(', end_error);
3213 add_anchor_token(')');
3215 expression_t *expression = NULL;
3217 bool old_type_prop = in_type_prop;
3218 bool old_gcc_extension = in_gcc_extension;
3219 in_type_prop = true;
3221 while (token.type == T___extension__) {
3222 /* This can be a prefix to a typename or an expression. */
3224 in_gcc_extension = true;
3226 switch (token.type) {
3228 if (is_typedef_symbol(token.v.symbol)) {
3229 type = parse_typename();
3231 expression = parse_expression();
3232 type = expression->base.type;
3237 type = parse_typename();
3241 expression = parse_expression();
3242 type = expression->base.type;
3245 in_type_prop = old_type_prop;
3246 in_gcc_extension = old_gcc_extension;
3248 rem_anchor_token(')');
3249 expect(')', end_error);
3251 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3252 typeof_type->typeoft.expression = expression;
3253 typeof_type->typeoft.typeof_type = type;
3260 typedef enum specifiers_t {
3261 SPECIFIER_SIGNED = 1 << 0,
3262 SPECIFIER_UNSIGNED = 1 << 1,
3263 SPECIFIER_LONG = 1 << 2,
3264 SPECIFIER_INT = 1 << 3,
3265 SPECIFIER_DOUBLE = 1 << 4,
3266 SPECIFIER_CHAR = 1 << 5,
3267 SPECIFIER_WCHAR_T = 1 << 6,
3268 SPECIFIER_SHORT = 1 << 7,
3269 SPECIFIER_LONG_LONG = 1 << 8,
3270 SPECIFIER_FLOAT = 1 << 9,
3271 SPECIFIER_BOOL = 1 << 10,
3272 SPECIFIER_VOID = 1 << 11,
3273 SPECIFIER_INT8 = 1 << 12,
3274 SPECIFIER_INT16 = 1 << 13,
3275 SPECIFIER_INT32 = 1 << 14,
3276 SPECIFIER_INT64 = 1 << 15,
3277 SPECIFIER_INT128 = 1 << 16,
3278 SPECIFIER_COMPLEX = 1 << 17,
3279 SPECIFIER_IMAGINARY = 1 << 18,
3282 static type_t *create_builtin_type(symbol_t *const symbol,
3283 type_t *const real_type)
3285 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3286 type->builtin.symbol = symbol;
3287 type->builtin.real_type = real_type;
3289 type_t *result = typehash_insert(type);
3290 if (type != result) {
3297 static type_t *get_typedef_type(symbol_t *symbol)
3299 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3300 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3303 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3304 type->typedeft.typedefe = &entity->typedefe;
3310 * check for the allowed MS alignment values.
3312 static bool check_alignment_value(long long intvalue)
3314 if (intvalue < 1 || intvalue > 8192) {
3315 errorf(HERE, "illegal alignment value");
3318 unsigned v = (unsigned)intvalue;
3319 for (unsigned i = 1; i <= 8192; i += i) {
3323 errorf(HERE, "alignment must be power of two");
3327 #define DET_MOD(name, tag) do { \
3328 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3329 *modifiers |= tag; \
3332 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3334 decl_modifiers_t *modifiers = &specifiers->modifiers;
3337 if (token.type == T_restrict) {
3339 DET_MOD(restrict, DM_RESTRICT);
3341 } else if (token.type != T_IDENTIFIER)
3343 symbol_t *symbol = token.v.symbol;
3344 if (symbol == sym_align) {
3346 expect('(', end_error);
3347 if (token.type != T_INTEGER)
3349 if (check_alignment_value(token.v.intvalue)) {
3350 if (specifiers->alignment != 0 && warning.other)
3351 warningf(HERE, "align used more than once");
3352 specifiers->alignment = (unsigned char)token.v.intvalue;
3355 expect(')', end_error);
3356 } else if (symbol == sym_allocate) {
3358 expect('(', end_error);
3359 if (token.type != T_IDENTIFIER)
3361 (void)token.v.symbol;
3362 expect(')', end_error);
3363 } else if (symbol == sym_dllimport) {
3365 DET_MOD(dllimport, DM_DLLIMPORT);
3366 } else if (symbol == sym_dllexport) {
3368 DET_MOD(dllexport, DM_DLLEXPORT);
3369 } else if (symbol == sym_thread) {
3371 DET_MOD(thread, DM_THREAD);
3372 } else if (symbol == sym_naked) {
3374 DET_MOD(naked, DM_NAKED);
3375 } else if (symbol == sym_noinline) {
3377 DET_MOD(noinline, DM_NOINLINE);
3378 } else if (symbol == sym_returns_twice) {
3380 DET_MOD(returns_twice, DM_RETURNS_TWICE);
3381 } else if (symbol == sym_noreturn) {
3383 DET_MOD(noreturn, DM_NORETURN);
3384 } else if (symbol == sym_nothrow) {
3386 DET_MOD(nothrow, DM_NOTHROW);
3387 } else if (symbol == sym_novtable) {
3389 DET_MOD(novtable, DM_NOVTABLE);
3390 } else if (symbol == sym_property) {
3392 expect('(', end_error);
3394 bool is_get = false;
3395 if (token.type != T_IDENTIFIER)
3397 if (token.v.symbol == sym_get) {
3399 } else if (token.v.symbol == sym_put) {
3401 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3405 expect('=', end_error);
3406 if (token.type != T_IDENTIFIER)
3409 if (specifiers->get_property_sym != NULL) {
3410 errorf(HERE, "get property name already specified");
3412 specifiers->get_property_sym = token.v.symbol;
3415 if (specifiers->put_property_sym != NULL) {
3416 errorf(HERE, "put property name already specified");
3418 specifiers->put_property_sym = token.v.symbol;
3422 if (token.type == ',') {
3428 expect(')', end_error);
3429 } else if (symbol == sym_selectany) {
3431 DET_MOD(selectany, DM_SELECTANY);
3432 } else if (symbol == sym_uuid) {
3434 expect('(', end_error);
3435 if (token.type != T_STRING_LITERAL)
3438 expect(')', end_error);
3439 } else if (symbol == sym_deprecated) {
3441 if (specifiers->deprecated != 0 && warning.other)
3442 warningf(HERE, "deprecated used more than once");
3443 specifiers->deprecated = true;
3444 if (token.type == '(') {
3446 if (token.type == T_STRING_LITERAL) {
3447 specifiers->deprecated_string = token.v.string.begin;
3450 errorf(HERE, "string literal expected");
3452 expect(')', end_error);
3454 } else if (symbol == sym_noalias) {
3456 DET_MOD(noalias, DM_NOALIAS);
3459 warningf(HERE, "Unknown modifier '%Y' ignored", token.v.symbol);
3461 if (token.type == '(')
3465 if (token.type == ',')
3472 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3474 entity_t *entity = allocate_entity_zero(kind);
3475 entity->base.source_position = *HERE;
3476 entity->base.symbol = symbol;
3477 if (is_declaration(entity)) {
3478 entity->declaration.type = type_error_type;
3479 entity->declaration.implicit = true;
3480 } else if (kind == ENTITY_TYPEDEF) {
3481 entity->typedefe.type = type_error_type;
3482 entity->typedefe.builtin = true;
3484 if (kind != ENTITY_COMPOUND_MEMBER)
3485 record_entity(entity, false);
3489 static void parse_microsoft_based(based_spec_t *based_spec)
3491 if (token.type != T_IDENTIFIER) {
3492 parse_error_expected("while parsing __based", T_IDENTIFIER, NULL);
3495 symbol_t *symbol = token.v.symbol;
3496 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3498 if (entity == NULL || entity->base.kind != ENTITY_VARIABLE) {
3499 errorf(HERE, "'%Y' is not a variable name.", symbol);
3500 entity = create_error_entity(symbol, ENTITY_VARIABLE);
3502 variable_t *variable = &entity->variable;
3504 if (based_spec->base_variable != NULL) {
3505 errorf(HERE, "__based type qualifier specified more than once");
3507 based_spec->source_position = token.source_position;
3508 based_spec->base_variable = variable;
3510 type_t *const type = variable->base.type;
3512 if (is_type_valid(type)) {
3513 if (! is_type_pointer(skip_typeref(type))) {
3514 errorf(HERE, "variable in __based modifier must have pointer type instead of '%T'", type);
3516 if (variable->base.base.parent_scope != file_scope) {
3517 errorf(HERE, "a nonstatic local variable may not be used in a __based specification");
3525 * Finish the construction of a struct type by calculating
3526 * its size, offsets, alignment.
3528 static void finish_struct_type(compound_type_t *type)
3530 assert(type->compound != NULL);
3532 compound_t *compound = type->compound;
3533 if (!compound->complete)
3538 il_alignment_t alignment = 1;
3539 bool need_pad = false;
3541 entity_t *entry = compound->members.entities;
3542 for (; entry != NULL; entry = entry->base.next) {
3543 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3546 type_t *m_type = skip_typeref(entry->declaration.type);
3547 if (! is_type_valid(m_type)) {
3548 /* simply ignore errors here */
3551 il_alignment_t m_alignment = m_type->base.alignment;
3552 if (m_alignment > alignment)
3553 alignment = m_alignment;
3555 offset = (size + m_alignment - 1) & -m_alignment;
3559 entry->compound_member.offset = offset;
3560 size = offset + m_type->base.size;
3562 if (type->base.alignment != 0) {
3563 alignment = type->base.alignment;
3566 offset = (size + alignment - 1) & -alignment;
3571 if (warning.padded) {
3572 warningf(&compound->base.source_position, "'%T' needs padding", type);
3575 if (compound->modifiers & DM_PACKED && warning.packed) {
3576 warningf(&compound->base.source_position,
3577 "superfluous packed attribute on '%T'", type);
3581 type->base.size = offset;
3582 type->base.alignment = alignment;
3586 * Finish the construction of an union type by calculating
3587 * its size and alignment.
3589 static void finish_union_type(compound_type_t *type)
3591 assert(type->compound != NULL);
3593 compound_t *compound = type->compound;
3594 if (! compound->complete)
3598 il_alignment_t alignment = 1;
3600 entity_t *entry = compound->members.entities;
3601 for (; entry != NULL; entry = entry->base.next) {
3602 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3605 type_t *m_type = skip_typeref(entry->declaration.type);
3606 if (! is_type_valid(m_type))
3609 entry->compound_member.offset = 0;
3610 if (m_type->base.size > size)
3611 size = m_type->base.size;
3612 if (m_type->base.alignment > alignment)
3613 alignment = m_type->base.alignment;
3615 if (type->base.alignment != 0) {
3616 alignment = type->base.alignment;
3618 size = (size + alignment - 1) & -alignment;
3619 type->base.size = size;
3620 type->base.alignment = alignment;
3623 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3625 type_t *type = NULL;
3626 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3627 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3628 unsigned type_specifiers = 0;
3629 bool newtype = false;
3630 bool saw_error = false;
3631 bool old_gcc_extension = in_gcc_extension;
3633 specifiers->source_position = token.source_position;
3636 specifiers->modifiers
3637 |= parse_attributes(&specifiers->gnu_attributes);
3638 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3639 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3641 switch (token.type) {
3643 #define MATCH_STORAGE_CLASS(token, class) \
3645 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3646 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3648 specifiers->storage_class = class; \
3649 if (specifiers->thread_local) \
3650 goto check_thread_storage_class; \
3654 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3655 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3656 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3657 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3658 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3662 expect('(', end_error);
3663 add_anchor_token(')');
3664 parse_microsoft_extended_decl_modifier(specifiers);
3665 rem_anchor_token(')');
3666 expect(')', end_error);
3670 if (specifiers->thread_local) {
3671 errorf(HERE, "duplicate '__thread'");
3673 specifiers->thread_local = true;
3674 check_thread_storage_class:
3675 switch (specifiers->storage_class) {
3676 case STORAGE_CLASS_EXTERN:
3677 case STORAGE_CLASS_NONE:
3678 case STORAGE_CLASS_STATIC:
3682 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
3683 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
3684 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
3685 wrong_thread_stoarge_class:
3686 errorf(HERE, "'__thread' used with '%s'", wrong);
3693 /* type qualifiers */
3694 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3696 qualifiers |= qualifier; \
3700 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3701 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3702 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3703 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3704 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3705 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3706 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3707 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3709 case T___extension__:
3711 in_gcc_extension = true;
3714 /* type specifiers */
3715 #define MATCH_SPECIFIER(token, specifier, name) \
3717 if (type_specifiers & specifier) { \
3718 errorf(HERE, "multiple " name " type specifiers given"); \
3720 type_specifiers |= specifier; \
3725 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3726 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3727 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3728 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3729 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3730 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3731 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3732 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3733 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3734 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3735 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3736 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3737 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3738 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3739 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3740 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3741 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3742 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
3744 case T__forceinline:
3745 /* only in microsoft mode */
3746 specifiers->modifiers |= DM_FORCEINLINE;
3751 specifiers->is_inline = true;
3755 if (type_specifiers & SPECIFIER_LONG_LONG) {
3756 errorf(HERE, "multiple type specifiers given");
3757 } else if (type_specifiers & SPECIFIER_LONG) {
3758 type_specifiers |= SPECIFIER_LONG_LONG;
3760 type_specifiers |= SPECIFIER_LONG;
3766 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3768 type->compound.compound = parse_compound_type_specifier(true);
3769 finish_struct_type(&type->compound);
3773 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3774 type->compound.compound = parse_compound_type_specifier(false);
3775 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3776 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3777 finish_union_type(&type->compound);
3781 type = parse_enum_specifier();
3784 type = parse_typeof();
3786 case T___builtin_va_list:
3787 type = duplicate_type(type_valist);
3791 case T_IDENTIFIER: {
3792 /* only parse identifier if we haven't found a type yet */
3793 if (type != NULL || type_specifiers != 0) {
3794 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3795 * declaration, so it doesn't generate errors about expecting '(' or
3797 switch (look_ahead(1)->type) {
3804 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3808 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3813 goto finish_specifiers;
3817 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3818 if (typedef_type == NULL) {
3819 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3820 * declaration, so it doesn't generate 'implicit int' followed by more
3821 * errors later on. */
3822 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3828 errorf(HERE, "%K does not name a type", &token);
3831 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3833 type = allocate_type_zero(TYPE_TYPEDEF);
3834 type->typedeft.typedefe = &entity->typedefe;
3838 if (la1_type == '&' || la1_type == '*')
3839 goto finish_specifiers;
3844 goto finish_specifiers;
3849 type = typedef_type;
3853 /* function specifier */
3855 goto finish_specifiers;
3860 in_gcc_extension = old_gcc_extension;
3862 if (type == NULL || (saw_error && type_specifiers != 0)) {
3863 atomic_type_kind_t atomic_type;
3865 /* match valid basic types */
3866 switch (type_specifiers) {
3867 case SPECIFIER_VOID:
3868 atomic_type = ATOMIC_TYPE_VOID;
3870 case SPECIFIER_WCHAR_T:
3871 atomic_type = ATOMIC_TYPE_WCHAR_T;
3873 case SPECIFIER_CHAR:
3874 atomic_type = ATOMIC_TYPE_CHAR;
3876 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3877 atomic_type = ATOMIC_TYPE_SCHAR;
3879 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3880 atomic_type = ATOMIC_TYPE_UCHAR;
3882 case SPECIFIER_SHORT:
3883 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3884 case SPECIFIER_SHORT | SPECIFIER_INT:
3885 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3886 atomic_type = ATOMIC_TYPE_SHORT;
3888 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3889 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3890 atomic_type = ATOMIC_TYPE_USHORT;
3893 case SPECIFIER_SIGNED:
3894 case SPECIFIER_SIGNED | SPECIFIER_INT:
3895 atomic_type = ATOMIC_TYPE_INT;
3897 case SPECIFIER_UNSIGNED:
3898 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3899 atomic_type = ATOMIC_TYPE_UINT;
3901 case SPECIFIER_LONG:
3902 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3903 case SPECIFIER_LONG | SPECIFIER_INT:
3904 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3905 atomic_type = ATOMIC_TYPE_LONG;
3907 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3908 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3909 atomic_type = ATOMIC_TYPE_ULONG;
3912 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3913 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3914 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3915 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3917 atomic_type = ATOMIC_TYPE_LONGLONG;
3918 goto warn_about_long_long;
3920 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3921 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3923 atomic_type = ATOMIC_TYPE_ULONGLONG;
3924 warn_about_long_long:
3925 if (warning.long_long) {
3926 warningf(&specifiers->source_position,
3927 "ISO C90 does not support 'long long'");
3931 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3932 atomic_type = unsigned_int8_type_kind;
3935 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3936 atomic_type = unsigned_int16_type_kind;
3939 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3940 atomic_type = unsigned_int32_type_kind;
3943 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3944 atomic_type = unsigned_int64_type_kind;
3947 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3948 atomic_type = unsigned_int128_type_kind;
3951 case SPECIFIER_INT8:
3952 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3953 atomic_type = int8_type_kind;
3956 case SPECIFIER_INT16:
3957 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3958 atomic_type = int16_type_kind;
3961 case SPECIFIER_INT32:
3962 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3963 atomic_type = int32_type_kind;
3966 case SPECIFIER_INT64:
3967 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3968 atomic_type = int64_type_kind;
3971 case SPECIFIER_INT128:
3972 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3973 atomic_type = int128_type_kind;
3976 case SPECIFIER_FLOAT:
3977 atomic_type = ATOMIC_TYPE_FLOAT;
3979 case SPECIFIER_DOUBLE:
3980 atomic_type = ATOMIC_TYPE_DOUBLE;
3982 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3983 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3985 case SPECIFIER_BOOL:
3986 atomic_type = ATOMIC_TYPE_BOOL;
3988 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3989 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3990 atomic_type = ATOMIC_TYPE_FLOAT;
3992 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3993 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3994 atomic_type = ATOMIC_TYPE_DOUBLE;
3996 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3997 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3998 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
4001 /* invalid specifier combination, give an error message */
4002 if (type_specifiers == 0) {
4006 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
4007 if (!(c_mode & _CXX) && !strict_mode) {
4008 if (warning.implicit_int) {
4009 warningf(HERE, "no type specifiers in declaration, using 'int'");
4011 atomic_type = ATOMIC_TYPE_INT;
4014 errorf(HERE, "no type specifiers given in declaration");
4016 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
4017 (type_specifiers & SPECIFIER_UNSIGNED)) {
4018 errorf(HERE, "signed and unsigned specifiers given");
4019 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
4020 errorf(HERE, "only integer types can be signed or unsigned");
4022 errorf(HERE, "multiple datatypes in declaration");
4027 if (type_specifiers & SPECIFIER_COMPLEX) {
4028 type = allocate_type_zero(TYPE_COMPLEX);
4029 type->complex.akind = atomic_type;
4030 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
4031 type = allocate_type_zero(TYPE_IMAGINARY);
4032 type->imaginary.akind = atomic_type;
4034 type = allocate_type_zero(TYPE_ATOMIC);
4035 type->atomic.akind = atomic_type;
4038 } else if (type_specifiers != 0) {
4039 errorf(HERE, "multiple datatypes in declaration");
4042 /* FIXME: check type qualifiers here */
4044 type->base.qualifiers = qualifiers;
4045 type->base.modifiers = modifiers;
4047 type_t *result = typehash_insert(type);
4048 if (newtype && result != type) {
4052 specifiers->type = result;
4056 specifiers->type = type_error_type;
4060 static type_qualifiers_t parse_type_qualifiers(void)
4062 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
4065 switch (token.type) {
4066 /* type qualifiers */
4067 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
4068 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
4069 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
4070 /* microsoft extended type modifiers */
4071 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
4072 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
4073 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
4074 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
4075 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
4084 * Parses an K&R identifier list
4086 static void parse_identifier_list(scope_t *scope)
4089 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
4090 entity->base.source_position = token.source_position;
4091 entity->base.namespc = NAMESPACE_NORMAL;
4092 entity->base.symbol = token.v.symbol;
4093 /* a K&R parameter has no type, yet */
4097 append_entity(scope, entity);
4099 if (token.type != ',') {
4103 } while (token.type == T_IDENTIFIER);
4106 static entity_t *parse_parameter(void)
4108 declaration_specifiers_t specifiers;
4109 memset(&specifiers, 0, sizeof(specifiers));
4111 parse_declaration_specifiers(&specifiers);
4113 entity_t *entity = parse_declarator(&specifiers,
4114 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
4115 anonymous_entity = NULL;
4119 static void semantic_parameter_incomplete(const entity_t *entity)
4121 assert(entity->kind == ENTITY_PARAMETER);
4123 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
4124 * list in a function declarator that is part of a
4125 * definition of that function shall not have
4126 * incomplete type. */
4127 type_t *type = skip_typeref(entity->declaration.type);
4128 if (is_type_incomplete(type)) {
4129 errorf(&entity->base.source_position,
4130 "parameter '%Y' has incomplete type '%T'", entity->base.symbol,
4131 entity->declaration.type);
4136 * Parses function type parameters (and optionally creates variable_t entities
4137 * for them in a scope)
4139 static void parse_parameters(function_type_t *type, scope_t *scope)
4142 add_anchor_token(')');
4143 int saved_comma_state = save_and_reset_anchor_state(',');
4145 if (token.type == T_IDENTIFIER &&
4146 !is_typedef_symbol(token.v.symbol)) {
4147 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4148 if (la1_type == ',' || la1_type == ')') {
4149 type->kr_style_parameters = true;
4150 type->unspecified_parameters = true;
4151 parse_identifier_list(scope);
4152 goto parameters_finished;
4156 if (token.type == ')') {
4157 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4158 if (!(c_mode & _CXX))
4159 type->unspecified_parameters = true;
4160 goto parameters_finished;
4163 function_parameter_t *parameter;
4164 function_parameter_t *last_parameter = NULL;
4167 switch (token.type) {
4170 type->variadic = true;
4171 goto parameters_finished;
4174 case T___extension__:
4177 entity_t *entity = parse_parameter();
4178 if (entity->kind == ENTITY_TYPEDEF) {
4179 errorf(&entity->base.source_position,
4180 "typedef not allowed as function parameter");
4183 assert(is_declaration(entity));
4185 /* func(void) is not a parameter */
4186 if (last_parameter == NULL
4187 && token.type == ')'
4188 && entity->base.symbol == NULL
4189 && skip_typeref(entity->declaration.type) == type_void) {
4190 goto parameters_finished;
4192 semantic_parameter_incomplete(entity);
4194 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4195 memset(parameter, 0, sizeof(parameter[0]));
4196 parameter->type = entity->declaration.type;
4198 if (scope != NULL) {
4199 append_entity(scope, entity);
4202 if (last_parameter != NULL) {
4203 last_parameter->next = parameter;
4205 type->parameters = parameter;
4207 last_parameter = parameter;
4212 goto parameters_finished;
4214 if (token.type != ',') {
4215 goto parameters_finished;
4221 parameters_finished:
4222 rem_anchor_token(')');
4223 expect(')', end_error);
4226 restore_anchor_state(',', saved_comma_state);
4229 typedef enum construct_type_kind_t {
4232 CONSTRUCT_REFERENCE,
4235 } construct_type_kind_t;
4237 typedef struct construct_type_t construct_type_t;
4238 struct construct_type_t {
4239 construct_type_kind_t kind;
4240 construct_type_t *next;
4243 typedef struct parsed_pointer_t parsed_pointer_t;
4244 struct parsed_pointer_t {
4245 construct_type_t construct_type;
4246 type_qualifiers_t type_qualifiers;
4247 variable_t *base_variable; /**< MS __based extension. */
4250 typedef struct parsed_reference_t parsed_reference_t;
4251 struct parsed_reference_t {
4252 construct_type_t construct_type;
4255 typedef struct construct_function_type_t construct_function_type_t;
4256 struct construct_function_type_t {
4257 construct_type_t construct_type;
4258 type_t *function_type;
4261 typedef struct parsed_array_t parsed_array_t;
4262 struct parsed_array_t {
4263 construct_type_t construct_type;
4264 type_qualifiers_t type_qualifiers;
4270 typedef struct construct_base_type_t construct_base_type_t;
4271 struct construct_base_type_t {
4272 construct_type_t construct_type;
4276 static construct_type_t *parse_pointer_declarator(variable_t *base_variable)
4280 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4281 memset(pointer, 0, sizeof(pointer[0]));
4282 pointer->construct_type.kind = CONSTRUCT_POINTER;
4283 pointer->type_qualifiers = parse_type_qualifiers();
4284 pointer->base_variable = base_variable;
4286 return &pointer->construct_type;
4289 static construct_type_t *parse_reference_declarator(void)
4293 parsed_reference_t *reference = obstack_alloc(&temp_obst, sizeof(reference[0]));
4294 memset(reference, 0, sizeof(reference[0]));
4295 reference->construct_type.kind = CONSTRUCT_REFERENCE;
4297 return (construct_type_t*)reference;
4300 static construct_type_t *parse_array_declarator(void)
4303 add_anchor_token(']');
4305 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4306 memset(array, 0, sizeof(array[0]));
4307 array->construct_type.kind = CONSTRUCT_ARRAY;
4309 if (token.type == T_static) {
4310 array->is_static = true;
4314 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4315 if (type_qualifiers != 0) {
4316 if (token.type == T_static) {
4317 array->is_static = true;
4321 array->type_qualifiers = type_qualifiers;
4323 if (token.type == '*' && look_ahead(1)->type == ']') {
4324 array->is_variable = true;
4326 } else if (token.type != ']') {
4327 expression_t *const size = parse_assignment_expression();
4329 mark_vars_read(size, NULL);
4332 rem_anchor_token(']');
4333 expect(']', end_error);
4336 return &array->construct_type;
4339 static construct_type_t *parse_function_declarator(scope_t *scope,
4340 decl_modifiers_t modifiers)
4342 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4343 function_type_t *ftype = &type->function;
4345 ftype->linkage = current_linkage;
4347 switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
4348 case DM_NONE: break;
4349 case DM_CDECL: ftype->calling_convention = CC_CDECL; break;
4350 case DM_STDCALL: ftype->calling_convention = CC_STDCALL; break;
4351 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
4352 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
4355 errorf(HERE, "multiple calling conventions in declaration");
4359 parse_parameters(ftype, scope);
4361 construct_function_type_t *construct_function_type =
4362 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4363 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4364 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4365 construct_function_type->function_type = type;
4367 return &construct_function_type->construct_type;
4370 typedef struct parse_declarator_env_t {
4371 decl_modifiers_t modifiers;
4373 source_position_t source_position;
4375 } parse_declarator_env_t;
4377 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4378 bool may_be_abstract)
4380 /* construct a single linked list of construct_type_t's which describe
4381 * how to construct the final declarator type */
4382 construct_type_t *first = NULL;
4383 construct_type_t *last = NULL;
4384 gnu_attribute_t *attributes = NULL;
4386 decl_modifiers_t modifiers = parse_attributes(&attributes);
4388 /* MS __based extension */
4389 based_spec_t base_spec;
4390 base_spec.base_variable = NULL;
4393 construct_type_t *type;
4394 switch (token.type) {
4396 if (!(c_mode & _CXX))
4397 errorf(HERE, "references are only available for C++");
4398 if (base_spec.base_variable != NULL && warning.other) {
4399 warningf(&base_spec.source_position,
4400 "__based does not precede a pointer operator, ignored");
4402 type = parse_reference_declarator();
4404 base_spec.base_variable = NULL;
4408 type = parse_pointer_declarator(base_spec.base_variable);
4410 base_spec.base_variable = NULL;
4415 expect('(', end_error);
4416 add_anchor_token(')');
4417 parse_microsoft_based(&base_spec);
4418 rem_anchor_token(')');
4419 expect(')', end_error);
4423 goto ptr_operator_end;
4434 /* TODO: find out if this is correct */
4435 modifiers |= parse_attributes(&attributes);
4438 if (base_spec.base_variable != NULL && warning.other) {
4439 warningf(&base_spec.source_position,
4440 "__based does not precede a pointer operator, ignored");
4444 modifiers |= env->modifiers;
4445 env->modifiers = modifiers;
4448 construct_type_t *inner_types = NULL;
4450 switch (token.type) {
4453 errorf(HERE, "no identifier expected in typename");
4455 env->symbol = token.v.symbol;
4456 env->source_position = token.source_position;
4461 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
4462 * interpreted as ``function with no parameter specification'', rather
4463 * than redundant parentheses around the omitted identifier. */
4464 if (look_ahead(1)->type != ')') {
4466 add_anchor_token(')');
4467 inner_types = parse_inner_declarator(env, may_be_abstract);
4468 if (inner_types != NULL) {
4469 /* All later declarators only modify the return type */
4472 rem_anchor_token(')');
4473 expect(')', end_error);
4477 if (may_be_abstract)
4479 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4484 construct_type_t *p = last;
4487 construct_type_t *type;
4488 switch (token.type) {
4490 scope_t *scope = NULL;
4492 scope = &env->parameters;
4494 type = parse_function_declarator(scope, modifiers);
4498 type = parse_array_declarator();
4501 goto declarator_finished;
4504 /* insert in the middle of the list (behind p) */
4506 type->next = p->next;
4517 declarator_finished:
4518 /* append inner_types at the end of the list, we don't to set last anymore
4519 * as it's not needed anymore */
4521 assert(first == NULL);
4522 first = inner_types;
4524 last->next = inner_types;
4532 static void parse_declaration_attributes(entity_t *entity)
4534 gnu_attribute_t *attributes = NULL;
4535 decl_modifiers_t modifiers = parse_attributes(&attributes);
4541 if (entity->kind == ENTITY_TYPEDEF) {
4542 modifiers |= entity->typedefe.modifiers;
4543 type = entity->typedefe.type;
4545 assert(is_declaration(entity));
4546 modifiers |= entity->declaration.modifiers;
4547 type = entity->declaration.type;
4552 /* handle these strange/stupid mode attributes */
4553 gnu_attribute_t *attribute = attributes;
4554 for ( ; attribute != NULL; attribute = attribute->next) {
4555 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4558 atomic_type_kind_t akind = attribute->u.akind;
4559 if (!is_type_signed(type)) {
4561 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4562 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4563 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4564 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4566 panic("invalid akind in mode attribute");
4570 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_SCHAR; break;
4571 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_SHORT; break;
4572 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_INT; break;
4573 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_LONGLONG; break;
4575 panic("invalid akind in mode attribute");
4579 type = make_atomic_type(akind, type->base.qualifiers);
4582 type_modifiers_t type_modifiers = type->base.modifiers;
4583 if (modifiers & DM_TRANSPARENT_UNION)
4584 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4586 if (type->base.modifiers != type_modifiers) {
4587 type_t *copy = duplicate_type(type);
4588 copy->base.modifiers = type_modifiers;
4590 type = typehash_insert(copy);
4592 obstack_free(type_obst, copy);
4596 if (entity->kind == ENTITY_TYPEDEF) {
4597 entity->typedefe.type = type;
4598 entity->typedefe.modifiers = modifiers;
4600 entity->declaration.type = type;
4601 entity->declaration.modifiers = modifiers;
4605 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
4607 construct_type_t *iter = construct_list;
4608 for (; iter != NULL; iter = iter->next) {
4609 switch (iter->kind) {
4610 case CONSTRUCT_INVALID:
4611 internal_errorf(HERE, "invalid type construction found");
4612 case CONSTRUCT_FUNCTION: {
4613 construct_function_type_t *construct_function_type
4614 = (construct_function_type_t*) iter;
4616 type_t *function_type = construct_function_type->function_type;
4618 function_type->function.return_type = type;
4620 type_t *skipped_return_type = skip_typeref(type);
4622 if (is_type_function(skipped_return_type)) {
4623 errorf(HERE, "function returning function is not allowed");
4624 } else if (is_type_array(skipped_return_type)) {
4625 errorf(HERE, "function returning array is not allowed");
4627 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4629 "type qualifiers in return type of function type are meaningless");
4633 type = function_type;
4637 case CONSTRUCT_POINTER: {
4638 if (is_type_reference(skip_typeref(type)))
4639 errorf(HERE, "cannot declare a pointer to reference");
4641 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4642 type = make_based_pointer_type(type, parsed_pointer->type_qualifiers, parsed_pointer->base_variable);
4646 case CONSTRUCT_REFERENCE:
4647 if (is_type_reference(skip_typeref(type)))
4648 errorf(HERE, "cannot declare a reference to reference");
4650 type = make_reference_type(type);
4653 case CONSTRUCT_ARRAY: {
4654 if (is_type_reference(skip_typeref(type)))
4655 errorf(HERE, "cannot declare an array of references");
4657 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4658 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4660 expression_t *size_expression = parsed_array->size;
4661 if (size_expression != NULL) {
4663 = create_implicit_cast(size_expression, type_size_t);
4666 array_type->base.qualifiers = parsed_array->type_qualifiers;
4667 array_type->array.element_type = type;
4668 array_type->array.is_static = parsed_array->is_static;
4669 array_type->array.is_variable = parsed_array->is_variable;
4670 array_type->array.size_expression = size_expression;
4672 if (size_expression != NULL) {
4673 if (is_constant_expression(size_expression)) {
4674 array_type->array.size_constant = true;
4675 array_type->array.size
4676 = fold_constant(size_expression);
4678 array_type->array.is_vla = true;
4682 type_t *skipped_type = skip_typeref(type);
4684 if (is_type_incomplete(skipped_type)) {
4685 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4686 } else if (is_type_function(skipped_type)) {
4687 errorf(HERE, "array of functions is not allowed");
4694 type_t *hashed_type = typehash_insert(type);
4695 if (hashed_type != type) {
4696 /* the function type was constructed earlier freeing it here will
4697 * destroy other types... */
4698 if (iter->kind != CONSTRUCT_FUNCTION) {
4708 static type_t *automatic_type_conversion(type_t *orig_type);
4710 static type_t *semantic_parameter(const source_position_t *pos,
4712 const declaration_specifiers_t *specifiers,
4715 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
4716 * shall be adjusted to ``qualified pointer to type'',
4718 * §6.7.5.3:8 A declaration of a parameter as ``function returning
4719 * type'' shall be adjusted to ``pointer to function
4720 * returning type'', as in 6.3.2.1. */
4721 type = automatic_type_conversion(type);
4723 if (specifiers->is_inline && is_type_valid(type)) {
4724 errorf(pos, "parameter '%Y' declared 'inline'", symbol);
4727 /* §6.9.1:6 The declarations in the declaration list shall contain
4728 * no storage-class specifier other than register and no
4729 * initializations. */
4730 if (specifiers->thread_local || (
4731 specifiers->storage_class != STORAGE_CLASS_NONE &&
4732 specifiers->storage_class != STORAGE_CLASS_REGISTER)
4734 errorf(pos, "invalid storage class for parameter '%Y'", symbol);
4737 /* delay test for incomplete type, because we might have (void)
4738 * which is legal but incomplete... */
4743 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4744 declarator_flags_t flags)
4746 parse_declarator_env_t env;
4747 memset(&env, 0, sizeof(env));
4748 env.modifiers = specifiers->modifiers;
4750 construct_type_t *construct_type =
4751 parse_inner_declarator(&env, (flags & DECL_MAY_BE_ABSTRACT) != 0);
4753 construct_declarator_type(construct_type, specifiers->type);
4754 type_t *type = skip_typeref(orig_type);
4756 if (construct_type != NULL) {
4757 obstack_free(&temp_obst, construct_type);
4761 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4762 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4763 entity->base.symbol = env.symbol;
4764 entity->base.source_position = env.source_position;
4765 entity->typedefe.type = orig_type;
4767 if (anonymous_entity != NULL) {
4768 if (is_type_compound(type)) {
4769 assert(anonymous_entity->compound.alias == NULL);
4770 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4771 anonymous_entity->kind == ENTITY_UNION);
4772 anonymous_entity->compound.alias = entity;
4773 anonymous_entity = NULL;
4774 } else if (is_type_enum(type)) {
4775 assert(anonymous_entity->enume.alias == NULL);
4776 assert(anonymous_entity->kind == ENTITY_ENUM);
4777 anonymous_entity->enume.alias = entity;
4778 anonymous_entity = NULL;
4782 /* create a declaration type entity */
4783 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
4784 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4786 if (env.symbol != NULL) {
4787 if (specifiers->is_inline && is_type_valid(type)) {
4788 errorf(&env.source_position,
4789 "compound member '%Y' declared 'inline'", env.symbol);
4792 if (specifiers->thread_local ||
4793 specifiers->storage_class != STORAGE_CLASS_NONE) {
4794 errorf(&env.source_position,
4795 "compound member '%Y' must have no storage class",
4799 } else if (flags & DECL_IS_PARAMETER) {
4800 orig_type = semantic_parameter(&env.source_position, orig_type,
4801 specifiers, env.symbol);
4803 entity = allocate_entity_zero(ENTITY_PARAMETER);
4804 } else if (is_type_function(type)) {
4805 entity = allocate_entity_zero(ENTITY_FUNCTION);
4807 entity->function.is_inline = specifiers->is_inline;
4808 entity->function.parameters = env.parameters;
4810 if (env.symbol != NULL) {
4811 if (specifiers->thread_local || (
4812 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4813 specifiers->storage_class != STORAGE_CLASS_NONE &&
4814 specifiers->storage_class != STORAGE_CLASS_STATIC
4816 errorf(&env.source_position,
4817 "invalid storage class for function '%Y'", env.symbol);
4821 entity = allocate_entity_zero(ENTITY_VARIABLE);
4823 entity->variable.get_property_sym = specifiers->get_property_sym;
4824 entity->variable.put_property_sym = specifiers->put_property_sym;
4825 if (specifiers->alignment != 0) {
4826 /* TODO: add checks here */
4827 entity->variable.alignment = specifiers->alignment;
4830 entity->variable.thread_local = specifiers->thread_local;
4832 if (env.symbol != NULL) {
4833 if (specifiers->is_inline && is_type_valid(type)) {
4834 errorf(&env.source_position,
4835 "variable '%Y' declared 'inline'", env.symbol);
4838 bool invalid_storage_class = false;
4839 if (current_scope == file_scope) {
4840 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4841 specifiers->storage_class != STORAGE_CLASS_NONE &&
4842 specifiers->storage_class != STORAGE_CLASS_STATIC) {
4843 invalid_storage_class = true;
4846 if (specifiers->thread_local &&
4847 specifiers->storage_class == STORAGE_CLASS_NONE) {
4848 invalid_storage_class = true;
4851 if (invalid_storage_class) {
4852 errorf(&env.source_position,
4853 "invalid storage class for variable '%Y'", env.symbol);
4858 if (env.symbol != NULL) {
4859 entity->base.symbol = env.symbol;
4860 entity->base.source_position = env.source_position;
4862 entity->base.source_position = specifiers->source_position;
4864 entity->base.namespc = NAMESPACE_NORMAL;
4865 entity->declaration.type = orig_type;
4866 entity->declaration.modifiers = env.modifiers;
4867 entity->declaration.deprecated_string = specifiers->deprecated_string;
4869 storage_class_t storage_class = specifiers->storage_class;
4870 entity->declaration.declared_storage_class = storage_class;
4872 if (storage_class == STORAGE_CLASS_NONE && current_scope != file_scope)
4873 storage_class = STORAGE_CLASS_AUTO;
4874 entity->declaration.storage_class = storage_class;
4877 parse_declaration_attributes(entity);
4882 static type_t *parse_abstract_declarator(type_t *base_type)
4884 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4886 type_t *result = construct_declarator_type(construct_type, base_type);
4887 if (construct_type != NULL) {
4888 obstack_free(&temp_obst, construct_type);
4895 * Check if the declaration of main is suspicious. main should be a
4896 * function with external linkage, returning int, taking either zero
4897 * arguments, two, or three arguments of appropriate types, ie.
4899 * int main([ int argc, char **argv [, char **env ] ]).
4901 * @param decl the declaration to check
4902 * @param type the function type of the declaration
4904 static void check_type_of_main(const entity_t *entity)
4906 const source_position_t *pos = &entity->base.source_position;
4907 if (entity->kind != ENTITY_FUNCTION) {
4908 warningf(pos, "'main' is not a function");
4912 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4913 warningf(pos, "'main' is normally a non-static function");
4916 type_t *type = skip_typeref(entity->declaration.type);
4917 assert(is_type_function(type));
4919 function_type_t *func_type = &type->function;
4920 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4921 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4922 func_type->return_type);
4924 const function_parameter_t *parm = func_type->parameters;
4926 type_t *const first_type = parm->type;
4927 if (!types_compatible(skip_typeref(first_type), type_int)) {
4929 "first argument of 'main' should be 'int', but is '%T'",
4934 type_t *const second_type = parm->type;
4935 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4936 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4940 type_t *const third_type = parm->type;
4941 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4942 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4946 goto warn_arg_count;
4950 warningf(pos, "'main' takes only zero, two or three arguments");
4956 * Check if a symbol is the equal to "main".
4958 static bool is_sym_main(const symbol_t *const sym)
4960 return strcmp(sym->string, "main") == 0;
4963 static void error_redefined_as_different_kind(const source_position_t *pos,
4964 const entity_t *old, entity_kind_t new_kind)
4966 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4967 get_entity_kind_name(old->kind), old->base.symbol,
4968 get_entity_kind_name(new_kind), &old->base.source_position);
4972 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4973 * for various problems that occur for multiple definitions
4975 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4977 const symbol_t *const symbol = entity->base.symbol;
4978 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4979 const source_position_t *pos = &entity->base.source_position;
4981 /* can happen in error cases */
4985 entity_t *previous_entity = get_entity(symbol, namespc);
4986 /* pushing the same entity twice will break the stack structure */
4987 assert(previous_entity != entity);
4989 if (entity->kind == ENTITY_FUNCTION) {
4990 type_t *const orig_type = entity->declaration.type;
4991 type_t *const type = skip_typeref(orig_type);
4993 assert(is_type_function(type));
4994 if (type->function.unspecified_parameters &&
4995 warning.strict_prototypes &&
4996 previous_entity == NULL) {
4997 warningf(pos, "function declaration '%#T' is not a prototype",
5001 if (warning.main && current_scope == file_scope
5002 && is_sym_main(symbol)) {
5003 check_type_of_main(entity);
5007 if (is_declaration(entity) &&
5008 warning.nested_externs &&
5009 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
5010 current_scope != file_scope) {
5011 warningf(pos, "nested extern declaration of '%#T'",
5012 entity->declaration.type, symbol);
5015 if (previous_entity != NULL &&
5016 previous_entity->base.parent_scope == ¤t_function->parameters &&
5017 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
5018 assert(previous_entity->kind == ENTITY_PARAMETER);
5020 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
5021 entity->declaration.type, symbol,
5022 previous_entity->declaration.type, symbol,
5023 &previous_entity->base.source_position);
5027 if (previous_entity != NULL &&
5028 previous_entity->base.parent_scope == current_scope) {
5029 if (previous_entity->kind != entity->kind) {
5030 error_redefined_as_different_kind(pos, previous_entity,
5034 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
5035 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
5036 symbol, &previous_entity->base.source_position);
5039 if (previous_entity->kind == ENTITY_TYPEDEF) {
5040 /* TODO: C++ allows this for exactly the same type */
5041 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
5042 symbol, &previous_entity->base.source_position);
5046 /* at this point we should have only VARIABLES or FUNCTIONS */
5047 assert(is_declaration(previous_entity) && is_declaration(entity));
5049 declaration_t *const prev_decl = &previous_entity->declaration;
5050 declaration_t *const decl = &entity->declaration;
5052 /* can happen for K&R style declarations */
5053 if (prev_decl->type == NULL &&
5054 previous_entity->kind == ENTITY_PARAMETER &&
5055 entity->kind == ENTITY_PARAMETER) {
5056 prev_decl->type = decl->type;
5057 prev_decl->storage_class = decl->storage_class;
5058 prev_decl->declared_storage_class = decl->declared_storage_class;
5059 prev_decl->modifiers = decl->modifiers;
5060 prev_decl->deprecated_string = decl->deprecated_string;
5061 return previous_entity;
5064 type_t *const orig_type = decl->type;
5065 assert(orig_type != NULL);
5066 type_t *const type = skip_typeref(orig_type);
5067 type_t * prev_type = skip_typeref(prev_decl->type);
5069 if (!types_compatible(type, prev_type)) {
5071 "declaration '%#T' is incompatible with '%#T' (declared %P)",
5072 orig_type, symbol, prev_decl->type, symbol,
5073 &previous_entity->base.source_position);
5075 unsigned old_storage_class = prev_decl->storage_class;
5076 if (warning.redundant_decls &&
5079 !(prev_decl->modifiers & DM_USED) &&
5080 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
5081 warningf(&previous_entity->base.source_position,
5082 "unnecessary static forward declaration for '%#T'",
5083 prev_decl->type, symbol);
5086 unsigned new_storage_class = decl->storage_class;
5087 if (is_type_incomplete(prev_type)) {
5088 prev_decl->type = type;
5092 /* pretend no storage class means extern for function
5093 * declarations (except if the previous declaration is neither
5094 * none nor extern) */
5095 if (entity->kind == ENTITY_FUNCTION) {
5096 if (prev_type->function.unspecified_parameters) {
5097 prev_decl->type = type;
5101 switch (old_storage_class) {
5102 case STORAGE_CLASS_NONE:
5103 old_storage_class = STORAGE_CLASS_EXTERN;
5106 case STORAGE_CLASS_EXTERN:
5107 if (is_definition) {
5108 if (warning.missing_prototypes &&
5109 prev_type->function.unspecified_parameters &&
5110 !is_sym_main(symbol)) {
5111 warningf(pos, "no previous prototype for '%#T'",
5114 } else if (new_storage_class == STORAGE_CLASS_NONE) {
5115 new_storage_class = STORAGE_CLASS_EXTERN;
5124 if (old_storage_class == STORAGE_CLASS_EXTERN &&
5125 new_storage_class == STORAGE_CLASS_EXTERN) {
5126 warn_redundant_declaration:
5127 if (!is_definition &&
5128 warning.redundant_decls &&
5129 is_type_valid(prev_type) &&
5130 strcmp(previous_entity->base.source_position.input_name,
5131 "<builtin>") != 0) {
5133 "redundant declaration for '%Y' (declared %P)",
5134 symbol, &previous_entity->base.source_position);
5136 } else if (current_function == NULL) {
5137 if (old_storage_class != STORAGE_CLASS_STATIC &&
5138 new_storage_class == STORAGE_CLASS_STATIC) {
5140 "static declaration of '%Y' follows non-static declaration (declared %P)",
5141 symbol, &previous_entity->base.source_position);
5142 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
5143 prev_decl->storage_class = STORAGE_CLASS_NONE;
5144 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
5146 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
5148 goto error_redeclaration;
5149 goto warn_redundant_declaration;
5151 } else if (is_type_valid(prev_type)) {
5152 if (old_storage_class == new_storage_class) {
5153 error_redeclaration:
5154 errorf(pos, "redeclaration of '%Y' (declared %P)",
5155 symbol, &previous_entity->base.source_position);
5158 "redeclaration of '%Y' with different linkage (declared %P)",
5159 symbol, &previous_entity->base.source_position);
5164 prev_decl->modifiers |= decl->modifiers;
5165 if (entity->kind == ENTITY_FUNCTION) {
5166 previous_entity->function.is_inline |= entity->function.is_inline;
5168 return previous_entity;
5171 if (entity->kind == ENTITY_FUNCTION) {
5172 if (is_definition &&
5173 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
5174 if (warning.missing_prototypes && !is_sym_main(symbol)) {
5175 warningf(pos, "no previous prototype for '%#T'",
5176 entity->declaration.type, symbol);
5177 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
5178 warningf(pos, "no previous declaration for '%#T'",
5179 entity->declaration.type, symbol);
5182 } else if (warning.missing_declarations &&
5183 entity->kind == ENTITY_VARIABLE &&
5184 current_scope == file_scope) {
5185 declaration_t *declaration = &entity->declaration;
5186 if (declaration->storage_class == STORAGE_CLASS_NONE) {
5187 warningf(pos, "no previous declaration for '%#T'",
5188 declaration->type, symbol);
5193 assert(entity->base.parent_scope == NULL);
5194 assert(current_scope != NULL);
5196 entity->base.parent_scope = current_scope;
5197 entity->base.namespc = NAMESPACE_NORMAL;
5198 environment_push(entity);
5199 append_entity(current_scope, entity);
5204 static void parser_error_multiple_definition(entity_t *entity,
5205 const source_position_t *source_position)
5207 errorf(source_position, "multiple definition of '%Y' (declared %P)",
5208 entity->base.symbol, &entity->base.source_position);
5211 static bool is_declaration_specifier(const token_t *token,
5212 bool only_specifiers_qualifiers)
5214 switch (token->type) {
5219 return is_typedef_symbol(token->v.symbol);
5221 case T___extension__:
5223 return !only_specifiers_qualifiers;
5230 static void parse_init_declarator_rest(entity_t *entity)
5232 assert(is_declaration(entity));
5233 declaration_t *const declaration = &entity->declaration;
5237 type_t *orig_type = declaration->type;
5238 type_t *type = skip_typeref(orig_type);
5240 if (entity->kind == ENTITY_VARIABLE
5241 && entity->variable.initializer != NULL) {
5242 parser_error_multiple_definition(entity, HERE);
5245 bool must_be_constant = false;
5246 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5247 entity->base.parent_scope == file_scope) {
5248 must_be_constant = true;
5251 if (is_type_function(type)) {
5252 errorf(&entity->base.source_position,
5253 "function '%#T' is initialized like a variable",
5254 orig_type, entity->base.symbol);
5255 orig_type = type_error_type;
5258 parse_initializer_env_t env;
5259 env.type = orig_type;
5260 env.must_be_constant = must_be_constant;
5261 env.entity = entity;
5262 current_init_decl = entity;
5264 initializer_t *initializer = parse_initializer(&env);
5265 current_init_decl = NULL;
5267 if (entity->kind == ENTITY_VARIABLE) {
5268 /* § 6.7.5 (22) array initializers for arrays with unknown size
5269 * determine the array type size */
5270 declaration->type = env.type;
5271 entity->variable.initializer = initializer;
5275 /* parse rest of a declaration without any declarator */
5276 static void parse_anonymous_declaration_rest(
5277 const declaration_specifiers_t *specifiers)
5280 anonymous_entity = NULL;
5282 if (warning.other) {
5283 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
5284 specifiers->thread_local) {
5285 warningf(&specifiers->source_position,
5286 "useless storage class in empty declaration");
5289 type_t *type = specifiers->type;
5290 switch (type->kind) {
5291 case TYPE_COMPOUND_STRUCT:
5292 case TYPE_COMPOUND_UNION: {
5293 if (type->compound.compound->base.symbol == NULL) {
5294 warningf(&specifiers->source_position,
5295 "unnamed struct/union that defines no instances");
5304 warningf(&specifiers->source_position, "empty declaration");
5310 static void check_variable_type_complete(entity_t *ent)
5312 if (ent->kind != ENTITY_VARIABLE)
5315 /* §6.7:7 If an identifier for an object is declared with no linkage, the
5316 * type for the object shall be complete [...] */
5317 declaration_t *decl = &ent->declaration;
5318 if (decl->storage_class != STORAGE_CLASS_NONE)
5321 type_t *const orig_type = decl->type;
5322 type_t *const type = skip_typeref(orig_type);
5323 if (!is_type_incomplete(type))
5326 /* GCC allows global arrays without size and assigns them a length of one,
5327 * if no different declaration follows */
5328 if (is_type_array(type) &&
5330 ent->base.parent_scope == file_scope) {
5331 ARR_APP1(declaration_t*, incomplete_arrays, decl);
5335 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
5336 orig_type, ent->base.symbol);
5340 static void parse_declaration_rest(entity_t *ndeclaration,
5341 const declaration_specifiers_t *specifiers,
5342 parsed_declaration_func finished_declaration,
5343 declarator_flags_t flags)
5345 add_anchor_token(';');
5346 add_anchor_token(',');
5348 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5350 if (token.type == '=') {
5351 parse_init_declarator_rest(entity);
5352 } else if (entity->kind == ENTITY_VARIABLE) {
5353 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
5354 * [...] where the extern specifier is explicitly used. */
5355 declaration_t *decl = &entity->declaration;
5356 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
5357 type_t *type = decl->type;
5358 if (is_type_reference(skip_typeref(type))) {
5359 errorf(&entity->base.source_position,
5360 "reference '%#T' must be initialized",
5361 type, entity->base.symbol);
5366 check_variable_type_complete(entity);
5368 if (token.type != ',')
5372 add_anchor_token('=');
5373 ndeclaration = parse_declarator(specifiers, flags);
5374 rem_anchor_token('=');
5376 expect(';', end_error);
5379 anonymous_entity = NULL;
5380 rem_anchor_token(';');
5381 rem_anchor_token(',');
5384 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5386 symbol_t *symbol = entity->base.symbol;
5387 if (symbol == NULL) {
5388 errorf(HERE, "anonymous declaration not valid as function parameter");
5392 assert(entity->base.namespc == NAMESPACE_NORMAL);
5393 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5394 if (previous_entity == NULL
5395 || previous_entity->base.parent_scope != current_scope) {
5396 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5401 if (is_definition) {
5402 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
5405 return record_entity(entity, false);
5408 static void parse_declaration(parsed_declaration_func finished_declaration,
5409 declarator_flags_t flags)
5411 declaration_specifiers_t specifiers;
5412 memset(&specifiers, 0, sizeof(specifiers));
5414 add_anchor_token(';');
5415 parse_declaration_specifiers(&specifiers);
5416 rem_anchor_token(';');
5418 if (token.type == ';') {
5419 parse_anonymous_declaration_rest(&specifiers);
5421 entity_t *entity = parse_declarator(&specifiers, flags);
5422 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
5426 static type_t *get_default_promoted_type(type_t *orig_type)
5428 type_t *result = orig_type;
5430 type_t *type = skip_typeref(orig_type);
5431 if (is_type_integer(type)) {
5432 result = promote_integer(type);
5433 } else if (type == type_float) {
5434 result = type_double;
5440 static void parse_kr_declaration_list(entity_t *entity)
5442 if (entity->kind != ENTITY_FUNCTION)
5445 type_t *type = skip_typeref(entity->declaration.type);
5446 assert(is_type_function(type));
5447 if (!type->function.kr_style_parameters)
5451 add_anchor_token('{');
5453 /* push function parameters */
5454 size_t const top = environment_top();
5455 scope_t *old_scope = scope_push(&entity->function.parameters);
5457 entity_t *parameter = entity->function.parameters.entities;
5458 for ( ; parameter != NULL; parameter = parameter->base.next) {
5459 assert(parameter->base.parent_scope == NULL);
5460 parameter->base.parent_scope = current_scope;
5461 environment_push(parameter);
5464 /* parse declaration list */
5466 switch (token.type) {
5468 case T___extension__:
5469 /* This covers symbols, which are no type, too, and results in
5470 * better error messages. The typical cases are misspelled type
5471 * names and missing includes. */
5473 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
5481 /* pop function parameters */
5482 assert(current_scope == &entity->function.parameters);
5483 scope_pop(old_scope);
5484 environment_pop_to(top);
5486 /* update function type */
5487 type_t *new_type = duplicate_type(type);
5489 function_parameter_t *parameters = NULL;
5490 function_parameter_t *last_parameter = NULL;
5492 parameter = entity->function.parameters.entities;
5493 for (; parameter != NULL; parameter = parameter->base.next) {
5494 type_t *parameter_type = parameter->declaration.type;
5495 if (parameter_type == NULL) {
5497 errorf(HERE, "no type specified for function parameter '%Y'",
5498 parameter->base.symbol);
5500 if (warning.implicit_int) {
5501 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5502 parameter->base.symbol);
5504 parameter_type = type_int;
5505 parameter->declaration.type = parameter_type;
5509 semantic_parameter_incomplete(parameter);
5510 parameter_type = parameter->declaration.type;
5513 * we need the default promoted types for the function type
5515 parameter_type = get_default_promoted_type(parameter_type);
5517 function_parameter_t *function_parameter
5518 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5519 memset(function_parameter, 0, sizeof(function_parameter[0]));
5521 function_parameter->type = parameter_type;
5522 if (last_parameter != NULL) {
5523 last_parameter->next = function_parameter;
5525 parameters = function_parameter;
5527 last_parameter = function_parameter;
5530 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5532 new_type->function.parameters = parameters;
5533 new_type->function.unspecified_parameters = true;
5535 type = typehash_insert(new_type);
5536 if (type != new_type) {
5537 obstack_free(type_obst, new_type);
5540 entity->declaration.type = type;
5542 rem_anchor_token('{');
5545 static bool first_err = true;
5548 * When called with first_err set, prints the name of the current function,
5551 static void print_in_function(void)
5555 diagnosticf("%s: In function '%Y':\n",
5556 current_function->base.base.source_position.input_name,
5557 current_function->base.base.symbol);
5562 * Check if all labels are defined in the current function.
5563 * Check if all labels are used in the current function.
5565 static void check_labels(void)
5567 for (const goto_statement_t *goto_statement = goto_first;
5568 goto_statement != NULL;
5569 goto_statement = goto_statement->next) {
5570 /* skip computed gotos */
5571 if (goto_statement->expression != NULL)
5574 label_t *label = goto_statement->label;
5577 if (label->base.source_position.input_name == NULL) {
5578 print_in_function();
5579 errorf(&goto_statement->base.source_position,
5580 "label '%Y' used but not defined", label->base.symbol);
5584 if (warning.unused_label) {
5585 for (const label_statement_t *label_statement = label_first;
5586 label_statement != NULL;
5587 label_statement = label_statement->next) {
5588 label_t *label = label_statement->label;
5590 if (! label->used) {
5591 print_in_function();
5592 warningf(&label_statement->base.source_position,
5593 "label '%Y' defined but not used", label->base.symbol);
5599 static void warn_unused_entity(entity_t *entity, entity_t *last)
5601 entity_t const *const end = last != NULL ? last->base.next : NULL;
5602 for (; entity != end; entity = entity->base.next) {
5603 if (!is_declaration(entity))
5606 declaration_t *declaration = &entity->declaration;
5607 if (declaration->implicit)
5610 if (!declaration->used) {
5611 print_in_function();
5612 const char *what = get_entity_kind_name(entity->kind);
5613 warningf(&entity->base.source_position, "%s '%Y' is unused",
5614 what, entity->base.symbol);
5615 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5616 print_in_function();
5617 const char *what = get_entity_kind_name(entity->kind);
5618 warningf(&entity->base.source_position, "%s '%Y' is never read",
5619 what, entity->base.symbol);
5624 static void check_unused_variables(statement_t *const stmt, void *const env)
5628 switch (stmt->kind) {
5629 case STATEMENT_DECLARATION: {
5630 declaration_statement_t const *const decls = &stmt->declaration;
5631 warn_unused_entity(decls->declarations_begin,
5632 decls->declarations_end);
5637 warn_unused_entity(stmt->fors.scope.entities, NULL);
5646 * Check declarations of current_function for unused entities.
5648 static void check_declarations(void)
5650 if (warning.unused_parameter) {
5651 const scope_t *scope = ¤t_function->parameters;
5653 /* do not issue unused warnings for main */
5654 if (!is_sym_main(current_function->base.base.symbol)) {
5655 warn_unused_entity(scope->entities, NULL);
5658 if (warning.unused_variable) {
5659 walk_statements(current_function->statement, check_unused_variables,
5664 static int determine_truth(expression_t const* const cond)
5667 !is_constant_expression(cond) ? 0 :
5668 fold_constant(cond) != 0 ? 1 :
5672 static void check_reachable(statement_t *);
5673 static bool reaches_end;
5675 static bool expression_returns(expression_t const *const expr)
5677 switch (expr->kind) {
5679 expression_t const *const func = expr->call.function;
5680 if (func->kind == EXPR_REFERENCE) {
5681 entity_t *entity = func->reference.entity;
5682 if (entity->kind == ENTITY_FUNCTION
5683 && entity->declaration.modifiers & DM_NORETURN)
5687 if (!expression_returns(func))
5690 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5691 if (!expression_returns(arg->expression))
5698 case EXPR_REFERENCE:
5699 case EXPR_REFERENCE_ENUM_VALUE:
5701 case EXPR_CHARACTER_CONSTANT:
5702 case EXPR_WIDE_CHARACTER_CONSTANT:
5703 case EXPR_STRING_LITERAL:
5704 case EXPR_WIDE_STRING_LITERAL:
5705 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5706 case EXPR_LABEL_ADDRESS:
5707 case EXPR_CLASSIFY_TYPE:
5708 case EXPR_SIZEOF: // TODO handle obscure VLA case
5711 case EXPR_BUILTIN_SYMBOL:
5712 case EXPR_BUILTIN_CONSTANT_P:
5713 case EXPR_BUILTIN_PREFETCH:
5718 case EXPR_STATEMENT: {
5719 bool old_reaches_end = reaches_end;
5720 reaches_end = false;
5721 check_reachable(expr->statement.statement);
5722 bool returns = reaches_end;
5723 reaches_end = old_reaches_end;
5727 case EXPR_CONDITIONAL:
5728 // TODO handle constant expression
5730 if (!expression_returns(expr->conditional.condition))
5733 if (expr->conditional.true_expression != NULL
5734 && expression_returns(expr->conditional.true_expression))
5737 return expression_returns(expr->conditional.false_expression);
5740 return expression_returns(expr->select.compound);
5742 case EXPR_ARRAY_ACCESS:
5744 expression_returns(expr->array_access.array_ref) &&
5745 expression_returns(expr->array_access.index);
5748 return expression_returns(expr->va_starte.ap);
5751 return expression_returns(expr->va_arge.ap);
5753 EXPR_UNARY_CASES_MANDATORY
5754 return expression_returns(expr->unary.value);
5756 case EXPR_UNARY_THROW:
5760 // TODO handle constant lhs of && and ||
5762 expression_returns(expr->binary.left) &&
5763 expression_returns(expr->binary.right);
5769 panic("unhandled expression");
5772 static bool initializer_returns(initializer_t const *const init)
5774 switch (init->kind) {
5775 case INITIALIZER_VALUE:
5776 return expression_returns(init->value.value);
5778 case INITIALIZER_LIST: {
5779 initializer_t * const* i = init->list.initializers;
5780 initializer_t * const* const end = i + init->list.len;
5781 bool returns = true;
5782 for (; i != end; ++i) {
5783 if (!initializer_returns(*i))
5789 case INITIALIZER_STRING:
5790 case INITIALIZER_WIDE_STRING:
5791 case INITIALIZER_DESIGNATOR: // designators have no payload
5794 panic("unhandled initializer");
5797 static bool noreturn_candidate;
5799 static void check_reachable(statement_t *const stmt)
5801 if (stmt->base.reachable)
5803 if (stmt->kind != STATEMENT_DO_WHILE)
5804 stmt->base.reachable = true;
5806 statement_t *last = stmt;
5808 switch (stmt->kind) {
5809 case STATEMENT_INVALID:
5810 case STATEMENT_EMPTY:
5812 next = stmt->base.next;
5815 case STATEMENT_DECLARATION: {
5816 declaration_statement_t const *const decl = &stmt->declaration;
5817 entity_t const * ent = decl->declarations_begin;
5818 entity_t const *const last = decl->declarations_end;
5820 for (;; ent = ent->base.next) {
5821 if (ent->kind == ENTITY_VARIABLE &&
5822 ent->variable.initializer != NULL &&
5823 !initializer_returns(ent->variable.initializer)) {
5830 next = stmt->base.next;
5834 case STATEMENT_COMPOUND:
5835 next = stmt->compound.statements;
5837 next = stmt->base.next;
5840 case STATEMENT_RETURN: {
5841 expression_t const *const val = stmt->returns.value;
5842 if (val == NULL || expression_returns(val))
5843 noreturn_candidate = false;
5847 case STATEMENT_IF: {
5848 if_statement_t const *const ifs = &stmt->ifs;
5849 expression_t const *const cond = ifs->condition;
5851 if (!expression_returns(cond))
5854 int const val = determine_truth(cond);
5857 check_reachable(ifs->true_statement);
5862 if (ifs->false_statement != NULL) {
5863 check_reachable(ifs->false_statement);
5867 next = stmt->base.next;
5871 case STATEMENT_SWITCH: {
5872 switch_statement_t const *const switchs = &stmt->switchs;
5873 expression_t const *const expr = switchs->expression;
5875 if (!expression_returns(expr))
5878 if (is_constant_expression(expr)) {
5879 long const val = fold_constant(expr);
5880 case_label_statement_t * defaults = NULL;
5881 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5882 if (i->expression == NULL) {
5887 if (i->first_case <= val && val <= i->last_case) {
5888 check_reachable((statement_t*)i);
5893 if (defaults != NULL) {
5894 check_reachable((statement_t*)defaults);
5898 bool has_default = false;
5899 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5900 if (i->expression == NULL)
5903 check_reachable((statement_t*)i);
5910 next = stmt->base.next;
5914 case STATEMENT_EXPRESSION: {
5915 /* Check for noreturn function call */
5916 expression_t const *const expr = stmt->expression.expression;
5917 if (!expression_returns(expr))
5920 next = stmt->base.next;
5924 case STATEMENT_CONTINUE: {
5925 statement_t *parent = stmt;
5927 parent = parent->base.parent;
5928 if (parent == NULL) /* continue not within loop */
5932 switch (parent->kind) {
5933 case STATEMENT_WHILE: goto continue_while;
5934 case STATEMENT_DO_WHILE: goto continue_do_while;
5935 case STATEMENT_FOR: goto continue_for;
5942 case STATEMENT_BREAK: {
5943 statement_t *parent = stmt;
5945 parent = parent->base.parent;
5946 if (parent == NULL) /* break not within loop/switch */
5949 switch (parent->kind) {
5950 case STATEMENT_SWITCH:
5951 case STATEMENT_WHILE:
5952 case STATEMENT_DO_WHILE:
5955 next = parent->base.next;
5956 goto found_break_parent;
5965 case STATEMENT_GOTO:
5966 if (stmt->gotos.expression) {
5967 if (!expression_returns(stmt->gotos.expression))
5970 statement_t *parent = stmt->base.parent;
5971 if (parent == NULL) /* top level goto */
5975 next = stmt->gotos.label->statement;
5976 if (next == NULL) /* missing label */
5981 case STATEMENT_LABEL:
5982 next = stmt->label.statement;
5985 case STATEMENT_CASE_LABEL:
5986 next = stmt->case_label.statement;
5989 case STATEMENT_WHILE: {
5990 while_statement_t const *const whiles = &stmt->whiles;
5991 expression_t const *const cond = whiles->condition;
5993 if (!expression_returns(cond))
5996 int const val = determine_truth(cond);
5999 check_reachable(whiles->body);
6004 next = stmt->base.next;
6008 case STATEMENT_DO_WHILE:
6009 next = stmt->do_while.body;
6012 case STATEMENT_FOR: {
6013 for_statement_t *const fors = &stmt->fors;
6015 if (fors->condition_reachable)
6017 fors->condition_reachable = true;
6019 expression_t const *const cond = fors->condition;
6024 } else if (expression_returns(cond)) {
6025 val = determine_truth(cond);
6031 check_reachable(fors->body);
6036 next = stmt->base.next;
6040 case STATEMENT_MS_TRY: {
6041 ms_try_statement_t const *const ms_try = &stmt->ms_try;
6042 check_reachable(ms_try->try_statement);
6043 next = ms_try->final_statement;
6047 case STATEMENT_LEAVE: {
6048 statement_t *parent = stmt;
6050 parent = parent->base.parent;
6051 if (parent == NULL) /* __leave not within __try */
6054 if (parent->kind == STATEMENT_MS_TRY) {
6056 next = parent->ms_try.final_statement;
6064 panic("invalid statement kind");
6067 while (next == NULL) {
6068 next = last->base.parent;
6070 noreturn_candidate = false;
6072 type_t *const type = current_function->base.type;
6073 assert(is_type_function(type));
6074 type_t *const ret = skip_typeref(type->function.return_type);
6075 if (warning.return_type &&
6076 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
6077 is_type_valid(ret) &&
6078 !is_sym_main(current_function->base.base.symbol)) {
6079 warningf(&stmt->base.source_position,
6080 "control reaches end of non-void function");
6085 switch (next->kind) {
6086 case STATEMENT_INVALID:
6087 case STATEMENT_EMPTY:
6088 case STATEMENT_DECLARATION:
6089 case STATEMENT_EXPRESSION:
6091 case STATEMENT_RETURN:
6092 case STATEMENT_CONTINUE:
6093 case STATEMENT_BREAK:
6094 case STATEMENT_GOTO:
6095 case STATEMENT_LEAVE:
6096 panic("invalid control flow in function");
6098 case STATEMENT_COMPOUND:
6099 if (next->compound.stmt_expr) {
6105 case STATEMENT_SWITCH:
6106 case STATEMENT_LABEL:
6107 case STATEMENT_CASE_LABEL:
6109 next = next->base.next;
6112 case STATEMENT_WHILE: {
6114 if (next->base.reachable)
6116 next->base.reachable = true;
6118 while_statement_t const *const whiles = &next->whiles;
6119 expression_t const *const cond = whiles->condition;
6121 if (!expression_returns(cond))
6124 int const val = determine_truth(cond);
6127 check_reachable(whiles->body);
6133 next = next->base.next;
6137 case STATEMENT_DO_WHILE: {
6139 if (next->base.reachable)
6141 next->base.reachable = true;
6143 do_while_statement_t const *const dw = &next->do_while;
6144 expression_t const *const cond = dw->condition;
6146 if (!expression_returns(cond))
6149 int const val = determine_truth(cond);
6152 check_reachable(dw->body);
6158 next = next->base.next;
6162 case STATEMENT_FOR: {
6164 for_statement_t *const fors = &next->fors;
6166 fors->step_reachable = true;
6168 if (fors->condition_reachable)
6170 fors->condition_reachable = true;
6172 expression_t const *const cond = fors->condition;
6177 } else if (expression_returns(cond)) {
6178 val = determine_truth(cond);
6184 check_reachable(fors->body);
6190 next = next->base.next;
6194 case STATEMENT_MS_TRY:
6196 next = next->ms_try.final_statement;
6201 check_reachable(next);
6204 static void check_unreachable(statement_t* const stmt, void *const env)
6208 switch (stmt->kind) {
6209 case STATEMENT_DO_WHILE:
6210 if (!stmt->base.reachable) {
6211 expression_t const *const cond = stmt->do_while.condition;
6212 if (determine_truth(cond) >= 0) {
6213 warningf(&cond->base.source_position,
6214 "condition of do-while-loop is unreachable");
6219 case STATEMENT_FOR: {
6220 for_statement_t const* const fors = &stmt->fors;
6222 // if init and step are unreachable, cond is unreachable, too
6223 if (!stmt->base.reachable && !fors->step_reachable) {
6224 warningf(&stmt->base.source_position, "statement is unreachable");
6226 if (!stmt->base.reachable && fors->initialisation != NULL) {
6227 warningf(&fors->initialisation->base.source_position,
6228 "initialisation of for-statement is unreachable");
6231 if (!fors->condition_reachable && fors->condition != NULL) {
6232 warningf(&fors->condition->base.source_position,
6233 "condition of for-statement is unreachable");
6236 if (!fors->step_reachable && fors->step != NULL) {
6237 warningf(&fors->step->base.source_position,
6238 "step of for-statement is unreachable");
6244 case STATEMENT_COMPOUND:
6245 if (stmt->compound.statements != NULL)
6247 goto warn_unreachable;
6249 case STATEMENT_DECLARATION: {
6250 /* Only warn if there is at least one declarator with an initializer.
6251 * This typically occurs in switch statements. */
6252 declaration_statement_t const *const decl = &stmt->declaration;
6253 entity_t const * ent = decl->declarations_begin;
6254 entity_t const *const last = decl->declarations_end;
6256 for (;; ent = ent->base.next) {
6257 if (ent->kind == ENTITY_VARIABLE &&
6258 ent->variable.initializer != NULL) {
6259 goto warn_unreachable;
6269 if (!stmt->base.reachable)
6270 warningf(&stmt->base.source_position, "statement is unreachable");
6275 static void parse_external_declaration(void)
6277 /* function-definitions and declarations both start with declaration
6279 declaration_specifiers_t specifiers;
6280 memset(&specifiers, 0, sizeof(specifiers));
6282 add_anchor_token(';');
6283 parse_declaration_specifiers(&specifiers);
6284 rem_anchor_token(';');
6286 /* must be a declaration */
6287 if (token.type == ';') {
6288 parse_anonymous_declaration_rest(&specifiers);
6292 add_anchor_token(',');
6293 add_anchor_token('=');
6294 add_anchor_token(';');
6295 add_anchor_token('{');
6297 /* declarator is common to both function-definitions and declarations */
6298 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
6300 rem_anchor_token('{');
6301 rem_anchor_token(';');
6302 rem_anchor_token('=');
6303 rem_anchor_token(',');
6305 /* must be a declaration */
6306 switch (token.type) {
6310 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
6315 /* must be a function definition */
6316 parse_kr_declaration_list(ndeclaration);
6318 if (token.type != '{') {
6319 parse_error_expected("while parsing function definition", '{', NULL);
6320 eat_until_matching_token(';');
6324 assert(is_declaration(ndeclaration));
6325 type_t *type = skip_typeref(ndeclaration->declaration.type);
6327 if (!is_type_function(type)) {
6328 if (is_type_valid(type)) {
6329 errorf(HERE, "declarator '%#T' has a body but is not a function type",
6330 type, ndeclaration->base.symbol);
6336 if (warning.aggregate_return &&
6337 is_type_compound(skip_typeref(type->function.return_type))) {
6338 warningf(HERE, "function '%Y' returns an aggregate",
6339 ndeclaration->base.symbol);
6341 if (warning.traditional && !type->function.unspecified_parameters) {
6342 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6343 ndeclaration->base.symbol);
6345 if (warning.old_style_definition && type->function.unspecified_parameters) {
6346 warningf(HERE, "old-style function definition '%Y'",
6347 ndeclaration->base.symbol);
6350 /* § 6.7.5.3 (14) a function definition with () means no
6351 * parameters (and not unspecified parameters) */
6352 if (type->function.unspecified_parameters
6353 && type->function.parameters == NULL
6354 && !type->function.kr_style_parameters) {
6355 type_t *duplicate = duplicate_type(type);
6356 duplicate->function.unspecified_parameters = false;
6358 type = typehash_insert(duplicate);
6359 if (type != duplicate) {
6360 obstack_free(type_obst, duplicate);
6362 ndeclaration->declaration.type = type;
6365 entity_t *const entity = record_entity(ndeclaration, true);
6366 assert(entity->kind == ENTITY_FUNCTION);
6367 assert(ndeclaration->kind == ENTITY_FUNCTION);
6369 function_t *function = &entity->function;
6370 if (ndeclaration != entity) {
6371 function->parameters = ndeclaration->function.parameters;
6373 assert(is_declaration(entity));
6374 type = skip_typeref(entity->declaration.type);
6376 /* push function parameters and switch scope */
6377 size_t const top = environment_top();
6378 scope_t *old_scope = scope_push(&function->parameters);
6380 entity_t *parameter = function->parameters.entities;
6381 for (; parameter != NULL; parameter = parameter->base.next) {
6382 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6383 parameter->base.parent_scope = current_scope;
6385 assert(parameter->base.parent_scope == NULL
6386 || parameter->base.parent_scope == current_scope);
6387 parameter->base.parent_scope = current_scope;
6388 if (parameter->base.symbol == NULL) {
6389 errorf(¶meter->base.source_position, "parameter name omitted");
6392 environment_push(parameter);
6395 if (function->statement != NULL) {
6396 parser_error_multiple_definition(entity, HERE);
6399 /* parse function body */
6400 int label_stack_top = label_top();
6401 function_t *old_current_function = current_function;
6402 current_function = function;
6403 current_parent = NULL;
6406 goto_anchor = &goto_first;
6408 label_anchor = &label_first;
6410 statement_t *const body = parse_compound_statement(false);
6411 function->statement = body;
6414 check_declarations();
6415 if (warning.return_type ||
6416 warning.unreachable_code ||
6417 (warning.missing_noreturn
6418 && !(function->base.modifiers & DM_NORETURN))) {
6419 noreturn_candidate = true;
6420 check_reachable(body);
6421 if (warning.unreachable_code)
6422 walk_statements(body, check_unreachable, NULL);
6423 if (warning.missing_noreturn &&
6424 noreturn_candidate &&
6425 !(function->base.modifiers & DM_NORETURN)) {
6426 warningf(&body->base.source_position,
6427 "function '%#T' is candidate for attribute 'noreturn'",
6428 type, entity->base.symbol);
6432 assert(current_parent == NULL);
6433 assert(current_function == function);
6434 current_function = old_current_function;
6435 label_pop_to(label_stack_top);
6438 assert(current_scope == &function->parameters);
6439 scope_pop(old_scope);
6440 environment_pop_to(top);
6443 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6444 source_position_t *source_position,
6445 const symbol_t *symbol)
6447 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6449 type->bitfield.base_type = base_type;
6450 type->bitfield.size_expression = size;
6453 type_t *skipped_type = skip_typeref(base_type);
6454 if (!is_type_integer(skipped_type)) {
6455 errorf(HERE, "bitfield base type '%T' is not an integer type",
6459 bit_size = skipped_type->base.size * 8;
6462 if (is_constant_expression(size)) {
6463 long v = fold_constant(size);
6466 errorf(source_position, "negative width in bit-field '%Y'", symbol);
6467 } else if (v == 0) {
6468 errorf(source_position, "zero width for bit-field '%Y'", symbol);
6469 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6470 errorf(source_position, "width of '%Y' exceeds its type", symbol);
6472 type->bitfield.bit_size = v;
6479 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6481 entity_t *iter = compound->members.entities;
6482 for (; iter != NULL; iter = iter->base.next) {
6483 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6486 if (iter->base.symbol == symbol) {
6488 } else if (iter->base.symbol == NULL) {
6489 type_t *type = skip_typeref(iter->declaration.type);
6490 if (is_type_compound(type)) {
6492 = find_compound_entry(type->compound.compound, symbol);
6503 static void parse_compound_declarators(compound_t *compound,
6504 const declaration_specifiers_t *specifiers)
6509 if (token.type == ':') {
6510 source_position_t source_position = *HERE;
6513 type_t *base_type = specifiers->type;
6514 expression_t *size = parse_constant_expression();
6516 type_t *type = make_bitfield_type(base_type, size,
6517 &source_position, sym_anonymous);
6519 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6520 entity->base.namespc = NAMESPACE_NORMAL;
6521 entity->base.source_position = source_position;
6522 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6523 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6524 entity->declaration.modifiers = specifiers->modifiers;
6525 entity->declaration.type = type;
6526 append_entity(&compound->members, entity);
6528 entity = parse_declarator(specifiers,
6529 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
6530 if (entity->kind == ENTITY_TYPEDEF) {
6531 errorf(&entity->base.source_position,
6532 "typedef not allowed as compound member");
6534 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6536 /* make sure we don't define a symbol multiple times */
6537 symbol_t *symbol = entity->base.symbol;
6538 if (symbol != NULL) {
6539 entity_t *prev = find_compound_entry(compound, symbol);
6541 errorf(&entity->base.source_position,
6542 "multiple declarations of symbol '%Y' (declared %P)",
6543 symbol, &prev->base.source_position);
6547 if (token.type == ':') {
6548 source_position_t source_position = *HERE;
6550 expression_t *size = parse_constant_expression();
6552 type_t *type = entity->declaration.type;
6553 type_t *bitfield_type = make_bitfield_type(type, size,
6554 &source_position, entity->base.symbol);
6555 entity->declaration.type = bitfield_type;
6557 type_t *orig_type = entity->declaration.type;
6558 type_t *type = skip_typeref(orig_type);
6559 if (is_type_function(type)) {
6560 errorf(&entity->base.source_position,
6561 "compound member '%Y' must not have function type '%T'",
6562 entity->base.symbol, orig_type);
6563 } else if (is_type_incomplete(type)) {
6564 /* §6.7.2.1:16 flexible array member */
6565 if (is_type_array(type) &&
6566 token.type == ';' &&
6567 look_ahead(1)->type == '}') {
6568 compound->has_flexible_member = true;
6570 errorf(&entity->base.source_position,
6571 "compound member '%Y' has incomplete type '%T'",
6572 entity->base.symbol, orig_type);
6577 append_entity(&compound->members, entity);
6581 if (token.type != ',')
6585 expect(';', end_error);
6588 anonymous_entity = NULL;
6591 static void parse_compound_type_entries(compound_t *compound)
6594 add_anchor_token('}');
6596 while (token.type != '}') {
6597 if (token.type == T_EOF) {
6598 errorf(HERE, "EOF while parsing struct");
6601 declaration_specifiers_t specifiers;
6602 memset(&specifiers, 0, sizeof(specifiers));
6603 parse_declaration_specifiers(&specifiers);
6605 parse_compound_declarators(compound, &specifiers);
6607 rem_anchor_token('}');
6611 compound->complete = true;
6614 static type_t *parse_typename(void)
6616 declaration_specifiers_t specifiers;
6617 memset(&specifiers, 0, sizeof(specifiers));
6618 parse_declaration_specifiers(&specifiers);
6619 if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6620 specifiers.thread_local) {
6621 /* TODO: improve error message, user does probably not know what a
6622 * storage class is...
6624 errorf(HERE, "typename may not have a storage class");
6627 type_t *result = parse_abstract_declarator(specifiers.type);
6635 typedef expression_t* (*parse_expression_function)(void);
6636 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6638 typedef struct expression_parser_function_t expression_parser_function_t;
6639 struct expression_parser_function_t {
6640 parse_expression_function parser;
6641 precedence_t infix_precedence;
6642 parse_expression_infix_function infix_parser;
6645 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6648 * Prints an error message if an expression was expected but not read
6650 static expression_t *expected_expression_error(void)
6652 /* skip the error message if the error token was read */
6653 if (token.type != T_ERROR) {
6654 errorf(HERE, "expected expression, got token %K", &token);
6658 return create_invalid_expression();
6662 * Parse a string constant.
6664 static expression_t *parse_string_const(void)
6667 if (token.type == T_STRING_LITERAL) {
6668 string_t res = token.v.string;
6670 while (token.type == T_STRING_LITERAL) {
6671 res = concat_strings(&res, &token.v.string);
6674 if (token.type != T_WIDE_STRING_LITERAL) {
6675 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6676 /* note: that we use type_char_ptr here, which is already the
6677 * automatic converted type. revert_automatic_type_conversion
6678 * will construct the array type */
6679 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6680 cnst->string.value = res;
6684 wres = concat_string_wide_string(&res, &token.v.wide_string);
6686 wres = token.v.wide_string;
6691 switch (token.type) {
6692 case T_WIDE_STRING_LITERAL:
6693 wres = concat_wide_strings(&wres, &token.v.wide_string);
6696 case T_STRING_LITERAL:
6697 wres = concat_wide_string_string(&wres, &token.v.string);
6701 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6702 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6703 cnst->wide_string.value = wres;
6712 * Parse a boolean constant.
6714 static expression_t *parse_bool_const(bool value)
6716 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6717 cnst->base.type = type_bool;
6718 cnst->conste.v.int_value = value;
6726 * Parse an integer constant.
6728 static expression_t *parse_int_const(void)
6730 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6731 cnst->base.type = token.datatype;
6732 cnst->conste.v.int_value = token.v.intvalue;
6740 * Parse a character constant.
6742 static expression_t *parse_character_constant(void)
6744 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6745 cnst->base.type = token.datatype;
6746 cnst->conste.v.character = token.v.string;
6748 if (cnst->conste.v.character.size != 1) {
6750 errorf(HERE, "more than 1 character in character constant");
6751 } else if (warning.multichar) {
6752 warningf(HERE, "multi-character character constant");
6761 * Parse a wide character constant.
6763 static expression_t *parse_wide_character_constant(void)
6765 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6766 cnst->base.type = token.datatype;
6767 cnst->conste.v.wide_character = token.v.wide_string;
6769 if (cnst->conste.v.wide_character.size != 1) {
6771 errorf(HERE, "more than 1 character in character constant");
6772 } else if (warning.multichar) {
6773 warningf(HERE, "multi-character character constant");
6782 * Parse a float constant.
6784 static expression_t *parse_float_const(void)
6786 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6787 cnst->base.type = token.datatype;
6788 cnst->conste.v.float_value = token.v.floatvalue;
6795 static entity_t *create_implicit_function(symbol_t *symbol,
6796 const source_position_t *source_position)
6798 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6799 ntype->function.return_type = type_int;
6800 ntype->function.unspecified_parameters = true;
6801 ntype->function.linkage = LINKAGE_C;
6803 type_t *type = typehash_insert(ntype);
6804 if (type != ntype) {
6808 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6809 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6810 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6811 entity->declaration.type = type;
6812 entity->declaration.implicit = true;
6813 entity->base.symbol = symbol;
6814 entity->base.source_position = *source_position;
6816 bool strict_prototypes_old = warning.strict_prototypes;
6817 warning.strict_prototypes = false;
6818 record_entity(entity, false);
6819 warning.strict_prototypes = strict_prototypes_old;
6825 * Creates a return_type (func)(argument_type) function type if not
6828 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6829 type_t *argument_type2)
6831 function_parameter_t *parameter2
6832 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6833 memset(parameter2, 0, sizeof(parameter2[0]));
6834 parameter2->type = argument_type2;
6836 function_parameter_t *parameter1
6837 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6838 memset(parameter1, 0, sizeof(parameter1[0]));
6839 parameter1->type = argument_type1;
6840 parameter1->next = parameter2;
6842 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6843 type->function.return_type = return_type;
6844 type->function.parameters = parameter1;
6846 type_t *result = typehash_insert(type);
6847 if (result != type) {
6855 * Creates a return_type (func)(argument_type) function type if not
6858 * @param return_type the return type
6859 * @param argument_type the argument type
6861 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6863 function_parameter_t *parameter
6864 = obstack_alloc(type_obst, sizeof(parameter[0]));
6865 memset(parameter, 0, sizeof(parameter[0]));
6866 parameter->type = argument_type;
6868 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6869 type->function.return_type = return_type;
6870 type->function.parameters = parameter;
6872 type_t *result = typehash_insert(type);
6873 if (result != type) {
6880 static type_t *make_function_0_type(type_t *return_type)
6882 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6883 type->function.return_type = return_type;
6884 type->function.parameters = NULL;
6886 type_t *result = typehash_insert(type);
6887 if (result != type) {
6895 * Creates a function type for some function like builtins.
6897 * @param symbol the symbol describing the builtin
6899 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6901 switch (symbol->ID) {
6902 case T___builtin_alloca:
6903 return make_function_1_type(type_void_ptr, type_size_t);
6904 case T___builtin_huge_val:
6905 return make_function_0_type(type_double);
6906 case T___builtin_inf:
6907 return make_function_0_type(type_double);
6908 case T___builtin_inff:
6909 return make_function_0_type(type_float);
6910 case T___builtin_infl:
6911 return make_function_0_type(type_long_double);
6912 case T___builtin_nan:
6913 return make_function_1_type(type_double, type_char_ptr);
6914 case T___builtin_nanf:
6915 return make_function_1_type(type_float, type_char_ptr);
6916 case T___builtin_nanl:
6917 return make_function_1_type(type_long_double, type_char_ptr);
6918 case T___builtin_va_end:
6919 return make_function_1_type(type_void, type_valist);
6920 case T___builtin_expect:
6921 return make_function_2_type(type_long, type_long, type_long);
6923 internal_errorf(HERE, "not implemented builtin identifier found");
6928 * Performs automatic type cast as described in § 6.3.2.1.
6930 * @param orig_type the original type
6932 static type_t *automatic_type_conversion(type_t *orig_type)
6934 type_t *type = skip_typeref(orig_type);
6935 if (is_type_array(type)) {
6936 array_type_t *array_type = &type->array;
6937 type_t *element_type = array_type->element_type;
6938 unsigned qualifiers = array_type->base.qualifiers;
6940 return make_pointer_type(element_type, qualifiers);
6943 if (is_type_function(type)) {
6944 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6951 * reverts the automatic casts of array to pointer types and function
6952 * to function-pointer types as defined § 6.3.2.1
6954 type_t *revert_automatic_type_conversion(const expression_t *expression)
6956 switch (expression->kind) {
6957 case EXPR_REFERENCE: {
6958 entity_t *entity = expression->reference.entity;
6959 if (is_declaration(entity)) {
6960 return entity->declaration.type;
6961 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6962 return entity->enum_value.enum_type;
6964 panic("no declaration or enum in reference");
6969 entity_t *entity = expression->select.compound_entry;
6970 assert(is_declaration(entity));
6971 type_t *type = entity->declaration.type;
6972 return get_qualified_type(type,
6973 expression->base.type->base.qualifiers);
6976 case EXPR_UNARY_DEREFERENCE: {
6977 const expression_t *const value = expression->unary.value;
6978 type_t *const type = skip_typeref(value->base.type);
6979 if (!is_type_pointer(type))
6980 return type_error_type;
6981 return type->pointer.points_to;
6984 case EXPR_BUILTIN_SYMBOL:
6985 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6987 case EXPR_ARRAY_ACCESS: {
6988 const expression_t *array_ref = expression->array_access.array_ref;
6989 type_t *type_left = skip_typeref(array_ref->base.type);
6990 if (!is_type_pointer(type_left))
6991 return type_error_type;
6992 return type_left->pointer.points_to;
6995 case EXPR_STRING_LITERAL: {
6996 size_t size = expression->string.value.size;
6997 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
7000 case EXPR_WIDE_STRING_LITERAL: {
7001 size_t size = expression->wide_string.value.size;
7002 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
7005 case EXPR_COMPOUND_LITERAL:
7006 return expression->compound_literal.type;
7009 return expression->base.type;
7013 static expression_t *parse_reference(void)
7015 symbol_t *const symbol = token.v.symbol;
7017 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
7019 if (entity == NULL) {
7020 if (!strict_mode && look_ahead(1)->type == '(') {
7021 /* an implicitly declared function */
7022 if (warning.error_implicit_function_declaration) {
7023 errorf(HERE, "implicit declaration of function '%Y'", symbol);
7024 } else if (warning.implicit_function_declaration) {
7025 warningf(HERE, "implicit declaration of function '%Y'", symbol);
7028 entity = create_implicit_function(symbol, HERE);
7030 errorf(HERE, "unknown identifier '%Y' found.", symbol);
7031 entity = create_error_entity(symbol, ENTITY_VARIABLE);
7037 if (is_declaration(entity)) {
7038 orig_type = entity->declaration.type;
7039 } else if (entity->kind == ENTITY_ENUM_VALUE) {
7040 orig_type = entity->enum_value.enum_type;
7041 } else if (entity->kind == ENTITY_TYPEDEF) {
7042 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
7045 return create_invalid_expression();
7047 panic("expected declaration or enum value in reference");
7050 /* we always do the auto-type conversions; the & and sizeof parser contains
7051 * code to revert this! */
7052 type_t *type = automatic_type_conversion(orig_type);
7054 expression_kind_t kind = EXPR_REFERENCE;
7055 if (entity->kind == ENTITY_ENUM_VALUE)
7056 kind = EXPR_REFERENCE_ENUM_VALUE;
7058 expression_t *expression = allocate_expression_zero(kind);
7059 expression->reference.entity = entity;
7060 expression->base.type = type;
7062 /* this declaration is used */
7063 if (is_declaration(entity)) {
7064 entity->declaration.used = true;
7067 if (entity->base.parent_scope != file_scope
7068 && entity->base.parent_scope->depth < current_function->parameters.depth
7069 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
7070 if (entity->kind == ENTITY_VARIABLE) {
7071 /* access of a variable from an outer function */
7072 entity->variable.address_taken = true;
7073 } else if (entity->kind == ENTITY_PARAMETER) {
7074 entity->parameter.address_taken = true;
7076 current_function->need_closure = true;
7079 /* check for deprecated functions */
7080 if (warning.deprecated_declarations
7081 && is_declaration(entity)
7082 && entity->declaration.modifiers & DM_DEPRECATED) {
7083 declaration_t *declaration = &entity->declaration;
7085 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
7086 "function" : "variable";
7088 if (declaration->deprecated_string != NULL) {
7089 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
7090 prefix, entity->base.symbol, &entity->base.source_position,
7091 declaration->deprecated_string);
7093 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
7094 entity->base.symbol, &entity->base.source_position);
7098 if (warning.init_self && entity == current_init_decl && !in_type_prop
7099 && entity->kind == ENTITY_VARIABLE) {
7100 current_init_decl = NULL;
7101 warningf(HERE, "variable '%#T' is initialized by itself",
7102 entity->declaration.type, entity->base.symbol);
7109 static bool semantic_cast(expression_t *cast)
7111 expression_t *expression = cast->unary.value;
7112 type_t *orig_dest_type = cast->base.type;
7113 type_t *orig_type_right = expression->base.type;
7114 type_t const *dst_type = skip_typeref(orig_dest_type);
7115 type_t const *src_type = skip_typeref(orig_type_right);
7116 source_position_t const *pos = &cast->base.source_position;
7118 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
7119 if (dst_type == type_void)
7122 /* only integer and pointer can be casted to pointer */
7123 if (is_type_pointer(dst_type) &&
7124 !is_type_pointer(src_type) &&
7125 !is_type_integer(src_type) &&
7126 is_type_valid(src_type)) {
7127 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
7131 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
7132 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
7136 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
7137 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
7141 if (warning.cast_qual &&
7142 is_type_pointer(src_type) &&
7143 is_type_pointer(dst_type)) {
7144 type_t *src = skip_typeref(src_type->pointer.points_to);
7145 type_t *dst = skip_typeref(dst_type->pointer.points_to);
7146 unsigned missing_qualifiers =
7147 src->base.qualifiers & ~dst->base.qualifiers;
7148 if (missing_qualifiers != 0) {
7150 "cast discards qualifiers '%Q' in pointer target type of '%T'",
7151 missing_qualifiers, orig_type_right);
7157 static expression_t *parse_compound_literal(type_t *type)
7159 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
7161 parse_initializer_env_t env;
7164 env.must_be_constant = false;
7165 initializer_t *initializer = parse_initializer(&env);
7168 expression->compound_literal.initializer = initializer;
7169 expression->compound_literal.type = type;
7170 expression->base.type = automatic_type_conversion(type);
7176 * Parse a cast expression.
7178 static expression_t *parse_cast(void)
7180 add_anchor_token(')');
7182 source_position_t source_position = token.source_position;
7184 type_t *type = parse_typename();
7186 rem_anchor_token(')');
7187 expect(')', end_error);
7189 if (token.type == '{') {
7190 return parse_compound_literal(type);
7193 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
7194 cast->base.source_position = source_position;
7196 expression_t *value = parse_sub_expression(PREC_CAST);
7197 cast->base.type = type;
7198 cast->unary.value = value;
7200 if (! semantic_cast(cast)) {
7201 /* TODO: record the error in the AST. else it is impossible to detect it */
7206 return create_invalid_expression();
7210 * Parse a statement expression.
7212 static expression_t *parse_statement_expression(void)
7214 add_anchor_token(')');
7216 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
7218 statement_t *statement = parse_compound_statement(true);
7219 statement->compound.stmt_expr = true;
7220 expression->statement.statement = statement;
7222 /* find last statement and use its type */
7223 type_t *type = type_void;
7224 const statement_t *stmt = statement->compound.statements;
7226 while (stmt->base.next != NULL)
7227 stmt = stmt->base.next;
7229 if (stmt->kind == STATEMENT_EXPRESSION) {
7230 type = stmt->expression.expression->base.type;
7232 } else if (warning.other) {
7233 warningf(&expression->base.source_position, "empty statement expression ({})");
7235 expression->base.type = type;
7237 rem_anchor_token(')');
7238 expect(')', end_error);
7245 * Parse a parenthesized expression.
7247 static expression_t *parse_parenthesized_expression(void)
7251 switch (token.type) {
7253 /* gcc extension: a statement expression */
7254 return parse_statement_expression();
7258 return parse_cast();
7260 if (is_typedef_symbol(token.v.symbol)) {
7261 return parse_cast();
7265 add_anchor_token(')');
7266 expression_t *result = parse_expression();
7267 result->base.parenthesized = true;
7268 rem_anchor_token(')');
7269 expect(')', end_error);
7275 static expression_t *parse_function_keyword(void)
7279 if (current_function == NULL) {
7280 errorf(HERE, "'__func__' used outside of a function");
7283 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7284 expression->base.type = type_char_ptr;
7285 expression->funcname.kind = FUNCNAME_FUNCTION;
7292 static expression_t *parse_pretty_function_keyword(void)
7294 if (current_function == NULL) {
7295 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
7298 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7299 expression->base.type = type_char_ptr;
7300 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
7302 eat(T___PRETTY_FUNCTION__);
7307 static expression_t *parse_funcsig_keyword(void)
7309 if (current_function == NULL) {
7310 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7313 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7314 expression->base.type = type_char_ptr;
7315 expression->funcname.kind = FUNCNAME_FUNCSIG;
7322 static expression_t *parse_funcdname_keyword(void)
7324 if (current_function == NULL) {
7325 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7328 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7329 expression->base.type = type_char_ptr;
7330 expression->funcname.kind = FUNCNAME_FUNCDNAME;
7332 eat(T___FUNCDNAME__);
7337 static designator_t *parse_designator(void)
7339 designator_t *result = allocate_ast_zero(sizeof(result[0]));
7340 result->source_position = *HERE;
7342 if (token.type != T_IDENTIFIER) {
7343 parse_error_expected("while parsing member designator",
7344 T_IDENTIFIER, NULL);
7347 result->symbol = token.v.symbol;
7350 designator_t *last_designator = result;
7352 if (token.type == '.') {
7354 if (token.type != T_IDENTIFIER) {
7355 parse_error_expected("while parsing member designator",
7356 T_IDENTIFIER, NULL);
7359 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7360 designator->source_position = *HERE;
7361 designator->symbol = token.v.symbol;
7364 last_designator->next = designator;
7365 last_designator = designator;
7368 if (token.type == '[') {
7370 add_anchor_token(']');
7371 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7372 designator->source_position = *HERE;
7373 designator->array_index = parse_expression();
7374 rem_anchor_token(']');
7375 expect(']', end_error);
7376 if (designator->array_index == NULL) {
7380 last_designator->next = designator;
7381 last_designator = designator;
7393 * Parse the __builtin_offsetof() expression.
7395 static expression_t *parse_offsetof(void)
7397 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7398 expression->base.type = type_size_t;
7400 eat(T___builtin_offsetof);
7402 expect('(', end_error);
7403 add_anchor_token(',');
7404 type_t *type = parse_typename();
7405 rem_anchor_token(',');
7406 expect(',', end_error);
7407 add_anchor_token(')');
7408 designator_t *designator = parse_designator();
7409 rem_anchor_token(')');
7410 expect(')', end_error);
7412 expression->offsetofe.type = type;
7413 expression->offsetofe.designator = designator;
7416 memset(&path, 0, sizeof(path));
7417 path.top_type = type;
7418 path.path = NEW_ARR_F(type_path_entry_t, 0);
7420 descend_into_subtype(&path);
7422 if (!walk_designator(&path, designator, true)) {
7423 return create_invalid_expression();
7426 DEL_ARR_F(path.path);
7430 return create_invalid_expression();
7434 * Parses a _builtin_va_start() expression.
7436 static expression_t *parse_va_start(void)
7438 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7440 eat(T___builtin_va_start);
7442 expect('(', end_error);
7443 add_anchor_token(',');
7444 expression->va_starte.ap = parse_assignment_expression();
7445 rem_anchor_token(',');
7446 expect(',', end_error);
7447 expression_t *const expr = parse_assignment_expression();
7448 if (expr->kind == EXPR_REFERENCE) {
7449 entity_t *const entity = expr->reference.entity;
7450 if (entity->base.parent_scope != ¤t_function->parameters
7451 || entity->base.next != NULL
7452 || entity->kind != ENTITY_PARAMETER) {
7453 errorf(&expr->base.source_position,
7454 "second argument of 'va_start' must be last parameter of the current function");
7456 expression->va_starte.parameter = &entity->variable;
7458 expect(')', end_error);
7461 expect(')', end_error);
7463 return create_invalid_expression();
7467 * Parses a _builtin_va_arg() expression.
7469 static expression_t *parse_va_arg(void)
7471 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7473 eat(T___builtin_va_arg);
7475 expect('(', end_error);
7476 expression->va_arge.ap = parse_assignment_expression();
7477 expect(',', end_error);
7478 expression->base.type = parse_typename();
7479 expect(')', end_error);
7483 return create_invalid_expression();
7486 static expression_t *parse_builtin_symbol(void)
7488 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7490 symbol_t *symbol = token.v.symbol;
7492 expression->builtin_symbol.symbol = symbol;
7495 type_t *type = get_builtin_symbol_type(symbol);
7496 type = automatic_type_conversion(type);
7498 expression->base.type = type;
7503 * Parses a __builtin_constant() expression.
7505 static expression_t *parse_builtin_constant(void)
7507 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7509 eat(T___builtin_constant_p);
7511 expect('(', end_error);
7512 add_anchor_token(')');
7513 expression->builtin_constant.value = parse_assignment_expression();
7514 rem_anchor_token(')');
7515 expect(')', end_error);
7516 expression->base.type = type_int;
7520 return create_invalid_expression();
7524 * Parses a __builtin_prefetch() expression.
7526 static expression_t *parse_builtin_prefetch(void)
7528 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7530 eat(T___builtin_prefetch);
7532 expect('(', end_error);
7533 add_anchor_token(')');
7534 expression->builtin_prefetch.adr = parse_assignment_expression();
7535 if (token.type == ',') {
7537 expression->builtin_prefetch.rw = parse_assignment_expression();
7539 if (token.type == ',') {
7541 expression->builtin_prefetch.locality = parse_assignment_expression();
7543 rem_anchor_token(')');
7544 expect(')', end_error);
7545 expression->base.type = type_void;
7549 return create_invalid_expression();
7553 * Parses a __builtin_is_*() compare expression.
7555 static expression_t *parse_compare_builtin(void)
7557 expression_t *expression;
7559 switch (token.type) {
7560 case T___builtin_isgreater:
7561 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7563 case T___builtin_isgreaterequal:
7564 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7566 case T___builtin_isless:
7567 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7569 case T___builtin_islessequal:
7570 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7572 case T___builtin_islessgreater:
7573 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7575 case T___builtin_isunordered:
7576 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7579 internal_errorf(HERE, "invalid compare builtin found");
7581 expression->base.source_position = *HERE;
7584 expect('(', end_error);
7585 expression->binary.left = parse_assignment_expression();
7586 expect(',', end_error);
7587 expression->binary.right = parse_assignment_expression();
7588 expect(')', end_error);
7590 type_t *const orig_type_left = expression->binary.left->base.type;
7591 type_t *const orig_type_right = expression->binary.right->base.type;
7593 type_t *const type_left = skip_typeref(orig_type_left);
7594 type_t *const type_right = skip_typeref(orig_type_right);
7595 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7596 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7597 type_error_incompatible("invalid operands in comparison",
7598 &expression->base.source_position, orig_type_left, orig_type_right);
7601 semantic_comparison(&expression->binary);
7606 return create_invalid_expression();
7611 * Parses a __builtin_expect(, end_error) expression.
7613 static expression_t *parse_builtin_expect(void, end_error)
7615 expression_t *expression
7616 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7618 eat(T___builtin_expect);
7620 expect('(', end_error);
7621 expression->binary.left = parse_assignment_expression();
7622 expect(',', end_error);
7623 expression->binary.right = parse_constant_expression();
7624 expect(')', end_error);
7626 expression->base.type = expression->binary.left->base.type;
7630 return create_invalid_expression();
7635 * Parses a MS assume() expression.
7637 static expression_t *parse_assume(void)
7639 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7643 expect('(', end_error);
7644 add_anchor_token(')');
7645 expression->unary.value = parse_assignment_expression();
7646 rem_anchor_token(')');
7647 expect(')', end_error);
7649 expression->base.type = type_void;
7652 return create_invalid_expression();
7656 * Return the declaration for a given label symbol or create a new one.
7658 * @param symbol the symbol of the label
7660 static label_t *get_label(symbol_t *symbol)
7663 assert(current_function != NULL);
7665 label = get_entity(symbol, NAMESPACE_LABEL);
7666 /* if we found a local label, we already created the declaration */
7667 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7668 if (label->base.parent_scope != current_scope) {
7669 assert(label->base.parent_scope->depth < current_scope->depth);
7670 current_function->goto_to_outer = true;
7672 return &label->label;
7675 label = get_entity(symbol, NAMESPACE_LABEL);
7676 /* if we found a label in the same function, then we already created the
7679 && label->base.parent_scope == ¤t_function->parameters) {
7680 return &label->label;
7683 /* otherwise we need to create a new one */
7684 label = allocate_entity_zero(ENTITY_LABEL);
7685 label->base.namespc = NAMESPACE_LABEL;
7686 label->base.symbol = symbol;
7690 return &label->label;
7694 * Parses a GNU && label address expression.
7696 static expression_t *parse_label_address(void)
7698 source_position_t source_position = token.source_position;
7700 if (token.type != T_IDENTIFIER) {
7701 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7704 symbol_t *symbol = token.v.symbol;
7707 label_t *label = get_label(symbol);
7709 label->address_taken = true;
7711 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7712 expression->base.source_position = source_position;
7714 /* label address is threaten as a void pointer */
7715 expression->base.type = type_void_ptr;
7716 expression->label_address.label = label;
7719 return create_invalid_expression();
7723 * Parse a microsoft __noop expression.
7725 static expression_t *parse_noop_expression(void)
7727 /* the result is a (int)0 */
7728 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7729 cnst->base.type = type_int;
7730 cnst->conste.v.int_value = 0;
7731 cnst->conste.is_ms_noop = true;
7735 if (token.type == '(') {
7736 /* parse arguments */
7738 add_anchor_token(')');
7739 add_anchor_token(',');
7741 if (token.type != ')') {
7743 (void)parse_assignment_expression();
7744 if (token.type != ',')
7750 rem_anchor_token(',');
7751 rem_anchor_token(')');
7752 expect(')', end_error);
7759 * Parses a primary expression.
7761 static expression_t *parse_primary_expression(void)
7763 switch (token.type) {
7764 case T_false: return parse_bool_const(false);
7765 case T_true: return parse_bool_const(true);
7766 case T_INTEGER: return parse_int_const();
7767 case T_CHARACTER_CONSTANT: return parse_character_constant();
7768 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7769 case T_FLOATINGPOINT: return parse_float_const();
7770 case T_STRING_LITERAL:
7771 case T_WIDE_STRING_LITERAL: return parse_string_const();
7772 case T_IDENTIFIER: return parse_reference();
7773 case T___FUNCTION__:
7774 case T___func__: return parse_function_keyword();
7775 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7776 case T___FUNCSIG__: return parse_funcsig_keyword();
7777 case T___FUNCDNAME__: return parse_funcdname_keyword();
7778 case T___builtin_offsetof: return parse_offsetof();
7779 case T___builtin_va_start: return parse_va_start();
7780 case T___builtin_va_arg: return parse_va_arg();
7781 case T___builtin_expect:
7782 case T___builtin_alloca:
7783 case T___builtin_inf:
7784 case T___builtin_inff:
7785 case T___builtin_infl:
7786 case T___builtin_nan:
7787 case T___builtin_nanf:
7788 case T___builtin_nanl:
7789 case T___builtin_huge_val:
7790 case T___builtin_va_end: return parse_builtin_symbol();
7791 case T___builtin_isgreater:
7792 case T___builtin_isgreaterequal:
7793 case T___builtin_isless:
7794 case T___builtin_islessequal:
7795 case T___builtin_islessgreater:
7796 case T___builtin_isunordered: return parse_compare_builtin();
7797 case T___builtin_constant_p: return parse_builtin_constant();
7798 case T___builtin_prefetch: return parse_builtin_prefetch();
7799 case T__assume: return parse_assume();
7802 return parse_label_address();
7805 case '(': return parse_parenthesized_expression();
7806 case T___noop: return parse_noop_expression();
7809 errorf(HERE, "unexpected token %K, expected an expression", &token);
7810 return create_invalid_expression();
7814 * Check if the expression has the character type and issue a warning then.
7816 static void check_for_char_index_type(const expression_t *expression)
7818 type_t *const type = expression->base.type;
7819 const type_t *const base_type = skip_typeref(type);
7821 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7822 warning.char_subscripts) {
7823 warningf(&expression->base.source_position,
7824 "array subscript has type '%T'", type);
7828 static expression_t *parse_array_expression(expression_t *left)
7830 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7833 add_anchor_token(']');
7835 expression_t *inside = parse_expression();
7837 type_t *const orig_type_left = left->base.type;
7838 type_t *const orig_type_inside = inside->base.type;
7840 type_t *const type_left = skip_typeref(orig_type_left);
7841 type_t *const type_inside = skip_typeref(orig_type_inside);
7843 type_t *return_type;
7844 array_access_expression_t *array_access = &expression->array_access;
7845 if (is_type_pointer(type_left)) {
7846 return_type = type_left->pointer.points_to;
7847 array_access->array_ref = left;
7848 array_access->index = inside;
7849 check_for_char_index_type(inside);
7850 } else if (is_type_pointer(type_inside)) {
7851 return_type = type_inside->pointer.points_to;
7852 array_access->array_ref = inside;
7853 array_access->index = left;
7854 array_access->flipped = true;
7855 check_for_char_index_type(left);
7857 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7859 "array access on object with non-pointer types '%T', '%T'",
7860 orig_type_left, orig_type_inside);
7862 return_type = type_error_type;
7863 array_access->array_ref = left;
7864 array_access->index = inside;
7867 expression->base.type = automatic_type_conversion(return_type);
7869 rem_anchor_token(']');
7870 expect(']', end_error);
7875 static expression_t *parse_typeprop(expression_kind_t const kind)
7877 expression_t *tp_expression = allocate_expression_zero(kind);
7878 tp_expression->base.type = type_size_t;
7880 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7882 /* we only refer to a type property, mark this case */
7883 bool old = in_type_prop;
7884 in_type_prop = true;
7887 expression_t *expression;
7888 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7890 add_anchor_token(')');
7891 orig_type = parse_typename();
7892 rem_anchor_token(')');
7893 expect(')', end_error);
7895 if (token.type == '{') {
7896 /* It was not sizeof(type) after all. It is sizeof of an expression
7897 * starting with a compound literal */
7898 expression = parse_compound_literal(orig_type);
7899 goto typeprop_expression;
7902 expression = parse_sub_expression(PREC_UNARY);
7904 typeprop_expression:
7905 tp_expression->typeprop.tp_expression = expression;
7907 orig_type = revert_automatic_type_conversion(expression);
7908 expression->base.type = orig_type;
7911 tp_expression->typeprop.type = orig_type;
7912 type_t const* const type = skip_typeref(orig_type);
7913 char const* const wrong_type =
7914 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7915 is_type_incomplete(type) ? "incomplete" :
7916 type->kind == TYPE_FUNCTION ? "function designator" :
7917 type->kind == TYPE_BITFIELD ? "bitfield" :
7919 if (wrong_type != NULL) {
7920 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7921 errorf(&tp_expression->base.source_position,
7922 "operand of %s expression must not be of %s type '%T'",
7923 what, wrong_type, orig_type);
7928 return tp_expression;
7931 static expression_t *parse_sizeof(void)
7933 return parse_typeprop(EXPR_SIZEOF);
7936 static expression_t *parse_alignof(void)
7938 return parse_typeprop(EXPR_ALIGNOF);
7941 static expression_t *parse_select_expression(expression_t *compound)
7943 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7944 select->select.compound = compound;
7946 assert(token.type == '.' || token.type == T_MINUSGREATER);
7947 bool is_pointer = (token.type == T_MINUSGREATER);
7950 if (token.type != T_IDENTIFIER) {
7951 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7954 symbol_t *symbol = token.v.symbol;
7957 type_t *const orig_type = compound->base.type;
7958 type_t *const type = skip_typeref(orig_type);
7961 bool saw_error = false;
7962 if (is_type_pointer(type)) {
7965 "request for member '%Y' in something not a struct or union, but '%T'",
7969 type_left = skip_typeref(type->pointer.points_to);
7971 if (is_pointer && is_type_valid(type)) {
7972 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7979 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7980 type_left->kind == TYPE_COMPOUND_UNION) {
7981 compound_t *compound = type_left->compound.compound;
7983 if (!compound->complete) {
7984 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7986 goto create_error_entry;
7989 entry = find_compound_entry(compound, symbol);
7990 if (entry == NULL) {
7991 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7992 goto create_error_entry;
7995 if (is_type_valid(type_left) && !saw_error) {
7997 "request for member '%Y' in something not a struct or union, but '%T'",
8001 entry = create_error_entity(symbol, ENTITY_COMPOUND_MEMBER);
8004 assert(is_declaration(entry));
8005 select->select.compound_entry = entry;
8007 type_t *entry_type = entry->declaration.type;
8009 = get_qualified_type(entry_type, type_left->base.qualifiers);
8011 /* we always do the auto-type conversions; the & and sizeof parser contains
8012 * code to revert this! */
8013 select->base.type = automatic_type_conversion(res_type);
8015 type_t *skipped = skip_typeref(res_type);
8016 if (skipped->kind == TYPE_BITFIELD) {
8017 select->base.type = skipped->bitfield.base_type;
8023 static void check_call_argument(const function_parameter_t *parameter,
8024 call_argument_t *argument, unsigned pos)
8026 type_t *expected_type = parameter->type;
8027 type_t *expected_type_skip = skip_typeref(expected_type);
8028 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
8029 expression_t *arg_expr = argument->expression;
8030 type_t *arg_type = skip_typeref(arg_expr->base.type);
8032 /* handle transparent union gnu extension */
8033 if (is_type_union(expected_type_skip)
8034 && (expected_type_skip->base.modifiers
8035 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
8036 compound_t *union_decl = expected_type_skip->compound.compound;
8037 type_t *best_type = NULL;
8038 entity_t *entry = union_decl->members.entities;
8039 for ( ; entry != NULL; entry = entry->base.next) {
8040 assert(is_declaration(entry));
8041 type_t *decl_type = entry->declaration.type;
8042 error = semantic_assign(decl_type, arg_expr);
8043 if (error == ASSIGN_ERROR_INCOMPATIBLE
8044 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
8047 if (error == ASSIGN_SUCCESS) {
8048 best_type = decl_type;
8049 } else if (best_type == NULL) {
8050 best_type = decl_type;
8054 if (best_type != NULL) {
8055 expected_type = best_type;
8059 error = semantic_assign(expected_type, arg_expr);
8060 argument->expression = create_implicit_cast(argument->expression,
8063 if (error != ASSIGN_SUCCESS) {
8064 /* report exact scope in error messages (like "in argument 3") */
8066 snprintf(buf, sizeof(buf), "call argument %u", pos);
8067 report_assign_error(error, expected_type, arg_expr, buf,
8068 &arg_expr->base.source_position);
8069 } else if (warning.traditional || warning.conversion) {
8070 type_t *const promoted_type = get_default_promoted_type(arg_type);
8071 if (!types_compatible(expected_type_skip, promoted_type) &&
8072 !types_compatible(expected_type_skip, type_void_ptr) &&
8073 !types_compatible(type_void_ptr, promoted_type)) {
8074 /* Deliberately show the skipped types in this warning */
8075 warningf(&arg_expr->base.source_position,
8076 "passing call argument %u as '%T' rather than '%T' due to prototype",
8077 pos, expected_type_skip, promoted_type);
8083 * Parse a call expression, ie. expression '( ... )'.
8085 * @param expression the function address
8087 static expression_t *parse_call_expression(expression_t *expression)
8089 expression_t *result = allocate_expression_zero(EXPR_CALL);
8090 call_expression_t *call = &result->call;
8091 call->function = expression;
8093 type_t *const orig_type = expression->base.type;
8094 type_t *const type = skip_typeref(orig_type);
8096 function_type_t *function_type = NULL;
8097 if (is_type_pointer(type)) {
8098 type_t *const to_type = skip_typeref(type->pointer.points_to);
8100 if (is_type_function(to_type)) {
8101 function_type = &to_type->function;
8102 call->base.type = function_type->return_type;
8106 if (function_type == NULL && is_type_valid(type)) {
8107 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
8110 /* parse arguments */
8112 add_anchor_token(')');
8113 add_anchor_token(',');
8115 if (token.type != ')') {
8116 call_argument_t *last_argument = NULL;
8119 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8121 argument->expression = parse_assignment_expression();
8122 if (last_argument == NULL) {
8123 call->arguments = argument;
8125 last_argument->next = argument;
8127 last_argument = argument;
8129 if (token.type != ',')
8134 rem_anchor_token(',');
8135 rem_anchor_token(')');
8136 expect(')', end_error);
8138 if (function_type == NULL)
8141 function_parameter_t *parameter = function_type->parameters;
8142 call_argument_t *argument = call->arguments;
8143 if (!function_type->unspecified_parameters) {
8144 for (unsigned pos = 0; parameter != NULL && argument != NULL;
8145 parameter = parameter->next, argument = argument->next) {
8146 check_call_argument(parameter, argument, ++pos);
8149 if (parameter != NULL) {
8150 errorf(HERE, "too few arguments to function '%E'", expression);
8151 } else if (argument != NULL && !function_type->variadic) {
8152 errorf(HERE, "too many arguments to function '%E'", expression);
8156 /* do default promotion */
8157 for (; argument != NULL; argument = argument->next) {
8158 type_t *type = argument->expression->base.type;
8160 type = get_default_promoted_type(type);
8162 argument->expression
8163 = create_implicit_cast(argument->expression, type);
8166 check_format(&result->call);
8168 if (warning.aggregate_return &&
8169 is_type_compound(skip_typeref(function_type->return_type))) {
8170 warningf(&result->base.source_position,
8171 "function call has aggregate value");
8178 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
8180 static bool same_compound_type(const type_t *type1, const type_t *type2)
8183 is_type_compound(type1) &&
8184 type1->kind == type2->kind &&
8185 type1->compound.compound == type2->compound.compound;
8188 static expression_t const *get_reference_address(expression_t const *expr)
8190 bool regular_take_address = true;
8192 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8193 expr = expr->unary.value;
8195 regular_take_address = false;
8198 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8201 expr = expr->unary.value;
8204 if (expr->kind != EXPR_REFERENCE)
8207 /* special case for functions which are automatically converted to a
8208 * pointer to function without an extra TAKE_ADDRESS operation */
8209 if (!regular_take_address &&
8210 expr->reference.entity->kind != ENTITY_FUNCTION) {
8217 static void warn_reference_address_as_bool(expression_t const* expr)
8219 if (!warning.address)
8222 expr = get_reference_address(expr);
8224 warningf(&expr->base.source_position,
8225 "the address of '%Y' will always evaluate as 'true'",
8226 expr->reference.entity->base.symbol);
8230 static void warn_assignment_in_condition(const expression_t *const expr)
8232 if (!warning.parentheses)
8234 if (expr->base.kind != EXPR_BINARY_ASSIGN)
8236 if (expr->base.parenthesized)
8238 warningf(&expr->base.source_position,
8239 "suggest parentheses around assignment used as truth value");
8242 static void semantic_condition(expression_t const *const expr,
8243 char const *const context)
8245 type_t *const type = skip_typeref(expr->base.type);
8246 if (is_type_scalar(type)) {
8247 warn_reference_address_as_bool(expr);
8248 warn_assignment_in_condition(expr);
8249 } else if (is_type_valid(type)) {
8250 errorf(&expr->base.source_position,
8251 "%s must have scalar type", context);
8256 * Parse a conditional expression, ie. 'expression ? ... : ...'.
8258 * @param expression the conditional expression
8260 static expression_t *parse_conditional_expression(expression_t *expression)
8262 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
8264 conditional_expression_t *conditional = &result->conditional;
8265 conditional->condition = expression;
8268 add_anchor_token(':');
8270 /* §6.5.15:2 The first operand shall have scalar type. */
8271 semantic_condition(expression, "condition of conditional operator");
8273 expression_t *true_expression = expression;
8274 bool gnu_cond = false;
8275 if (GNU_MODE && token.type == ':') {
8278 true_expression = parse_expression();
8280 rem_anchor_token(':');
8281 expect(':', end_error);
8283 expression_t *false_expression =
8284 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
8286 type_t *const orig_true_type = true_expression->base.type;
8287 type_t *const orig_false_type = false_expression->base.type;
8288 type_t *const true_type = skip_typeref(orig_true_type);
8289 type_t *const false_type = skip_typeref(orig_false_type);
8292 type_t *result_type;
8293 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8294 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
8295 /* ISO/IEC 14882:1998(E) §5.16:2 */
8296 if (true_expression->kind == EXPR_UNARY_THROW) {
8297 result_type = false_type;
8298 } else if (false_expression->kind == EXPR_UNARY_THROW) {
8299 result_type = true_type;
8301 if (warning.other && (
8302 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8303 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
8305 warningf(&conditional->base.source_position,
8306 "ISO C forbids conditional expression with only one void side");
8308 result_type = type_void;
8310 } else if (is_type_arithmetic(true_type)
8311 && is_type_arithmetic(false_type)) {
8312 result_type = semantic_arithmetic(true_type, false_type);
8314 true_expression = create_implicit_cast(true_expression, result_type);
8315 false_expression = create_implicit_cast(false_expression, result_type);
8317 conditional->true_expression = true_expression;
8318 conditional->false_expression = false_expression;
8319 conditional->base.type = result_type;
8320 } else if (same_compound_type(true_type, false_type)) {
8321 /* just take 1 of the 2 types */
8322 result_type = true_type;
8323 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
8324 type_t *pointer_type;
8326 expression_t *other_expression;
8327 if (is_type_pointer(true_type) &&
8328 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
8329 pointer_type = true_type;
8330 other_type = false_type;
8331 other_expression = false_expression;
8333 pointer_type = false_type;
8334 other_type = true_type;
8335 other_expression = true_expression;
8338 if (is_null_pointer_constant(other_expression)) {
8339 result_type = pointer_type;
8340 } else if (is_type_pointer(other_type)) {
8341 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8342 type_t *to2 = skip_typeref(other_type->pointer.points_to);
8345 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8346 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8348 } else if (types_compatible(get_unqualified_type(to1),
8349 get_unqualified_type(to2))) {
8352 if (warning.other) {
8353 warningf(&conditional->base.source_position,
8354 "pointer types '%T' and '%T' in conditional expression are incompatible",
8355 true_type, false_type);
8360 type_t *const type =
8361 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8362 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8363 } else if (is_type_integer(other_type)) {
8364 if (warning.other) {
8365 warningf(&conditional->base.source_position,
8366 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8368 result_type = pointer_type;
8370 if (is_type_valid(other_type)) {
8371 type_error_incompatible("while parsing conditional",
8372 &expression->base.source_position, true_type, false_type);
8374 result_type = type_error_type;
8377 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8378 type_error_incompatible("while parsing conditional",
8379 &conditional->base.source_position, true_type,
8382 result_type = type_error_type;
8385 conditional->true_expression
8386 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8387 conditional->false_expression
8388 = create_implicit_cast(false_expression, result_type);
8389 conditional->base.type = result_type;
8394 * Parse an extension expression.
8396 static expression_t *parse_extension(void)
8398 eat(T___extension__);
8400 bool old_gcc_extension = in_gcc_extension;
8401 in_gcc_extension = true;
8402 expression_t *expression = parse_sub_expression(PREC_UNARY);
8403 in_gcc_extension = old_gcc_extension;
8408 * Parse a __builtin_classify_type() expression.
8410 static expression_t *parse_builtin_classify_type(void)
8412 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8413 result->base.type = type_int;
8415 eat(T___builtin_classify_type);
8417 expect('(', end_error);
8418 add_anchor_token(')');
8419 expression_t *expression = parse_expression();
8420 rem_anchor_token(')');
8421 expect(')', end_error);
8422 result->classify_type.type_expression = expression;
8426 return create_invalid_expression();
8430 * Parse a delete expression
8431 * ISO/IEC 14882:1998(E) §5.3.5
8433 static expression_t *parse_delete(void)
8435 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8436 result->base.type = type_void;
8440 if (token.type == '[') {
8442 result->kind = EXPR_UNARY_DELETE_ARRAY;
8443 expect(']', end_error);
8447 expression_t *const value = parse_sub_expression(PREC_CAST);
8448 result->unary.value = value;
8450 type_t *const type = skip_typeref(value->base.type);
8451 if (!is_type_pointer(type)) {
8452 if (is_type_valid(type)) {
8453 errorf(&value->base.source_position,
8454 "operand of delete must have pointer type");
8456 } else if (warning.other &&
8457 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8458 warningf(&value->base.source_position,
8459 "deleting 'void*' is undefined");
8466 * Parse a throw expression
8467 * ISO/IEC 14882:1998(E) §15:1
8469 static expression_t *parse_throw(void)
8471 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8472 result->base.type = type_void;
8476 expression_t *value = NULL;
8477 switch (token.type) {
8479 value = parse_assignment_expression();
8480 /* ISO/IEC 14882:1998(E) §15.1:3 */
8481 type_t *const orig_type = value->base.type;
8482 type_t *const type = skip_typeref(orig_type);
8483 if (is_type_incomplete(type)) {
8484 errorf(&value->base.source_position,
8485 "cannot throw object of incomplete type '%T'", orig_type);
8486 } else if (is_type_pointer(type)) {
8487 type_t *const points_to = skip_typeref(type->pointer.points_to);
8488 if (is_type_incomplete(points_to) &&
8489 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8490 errorf(&value->base.source_position,
8491 "cannot throw pointer to incomplete type '%T'", orig_type);
8499 result->unary.value = value;
8504 static bool check_pointer_arithmetic(const source_position_t *source_position,
8505 type_t *pointer_type,
8506 type_t *orig_pointer_type)
8508 type_t *points_to = pointer_type->pointer.points_to;
8509 points_to = skip_typeref(points_to);
8511 if (is_type_incomplete(points_to)) {
8512 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8513 errorf(source_position,
8514 "arithmetic with pointer to incomplete type '%T' not allowed",
8517 } else if (warning.pointer_arith) {
8518 warningf(source_position,
8519 "pointer of type '%T' used in arithmetic",
8522 } else if (is_type_function(points_to)) {
8524 errorf(source_position,
8525 "arithmetic with pointer to function type '%T' not allowed",
8528 } else if (warning.pointer_arith) {
8529 warningf(source_position,
8530 "pointer to a function '%T' used in arithmetic",
8537 static bool is_lvalue(const expression_t *expression)
8539 /* TODO: doesn't seem to be consistent with §6.3.2.1 (1) */
8540 switch (expression->kind) {
8541 case EXPR_ARRAY_ACCESS:
8542 case EXPR_COMPOUND_LITERAL:
8543 case EXPR_REFERENCE:
8545 case EXPR_UNARY_DEREFERENCE:
8549 type_t *type = skip_typeref(expression->base.type);
8551 /* ISO/IEC 14882:1998(E) §3.10:3 */
8552 is_type_reference(type) ||
8553 /* Claim it is an lvalue, if the type is invalid. There was a parse
8554 * error before, which maybe prevented properly recognizing it as
8556 !is_type_valid(type);
8561 static void semantic_incdec(unary_expression_t *expression)
8563 type_t *const orig_type = expression->value->base.type;
8564 type_t *const type = skip_typeref(orig_type);
8565 if (is_type_pointer(type)) {
8566 if (!check_pointer_arithmetic(&expression->base.source_position,
8570 } else if (!is_type_real(type) && is_type_valid(type)) {
8571 /* TODO: improve error message */
8572 errorf(&expression->base.source_position,
8573 "operation needs an arithmetic or pointer type");
8576 if (!is_lvalue(expression->value)) {
8577 /* TODO: improve error message */
8578 errorf(&expression->base.source_position, "lvalue required as operand");
8580 expression->base.type = orig_type;
8583 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8585 type_t *const orig_type = expression->value->base.type;
8586 type_t *const type = skip_typeref(orig_type);
8587 if (!is_type_arithmetic(type)) {
8588 if (is_type_valid(type)) {
8589 /* TODO: improve error message */
8590 errorf(&expression->base.source_position,
8591 "operation needs an arithmetic type");
8596 expression->base.type = orig_type;
8599 static void semantic_unexpr_plus(unary_expression_t *expression)
8601 semantic_unexpr_arithmetic(expression);
8602 if (warning.traditional)
8603 warningf(&expression->base.source_position,
8604 "traditional C rejects the unary plus operator");
8607 static void semantic_not(unary_expression_t *expression)
8609 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8610 semantic_condition(expression->value, "operand of !");
8611 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8614 static void semantic_unexpr_integer(unary_expression_t *expression)
8616 type_t *const orig_type = expression->value->base.type;
8617 type_t *const type = skip_typeref(orig_type);
8618 if (!is_type_integer(type)) {
8619 if (is_type_valid(type)) {
8620 errorf(&expression->base.source_position,
8621 "operand of ~ must be of integer type");
8626 expression->base.type = orig_type;
8629 static void semantic_dereference(unary_expression_t *expression)
8631 type_t *const orig_type = expression->value->base.type;
8632 type_t *const type = skip_typeref(orig_type);
8633 if (!is_type_pointer(type)) {
8634 if (is_type_valid(type)) {
8635 errorf(&expression->base.source_position,
8636 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8641 type_t *result_type = type->pointer.points_to;
8642 result_type = automatic_type_conversion(result_type);
8643 expression->base.type = result_type;
8647 * Record that an address is taken (expression represents an lvalue).
8649 * @param expression the expression
8650 * @param may_be_register if true, the expression might be an register
8652 static void set_address_taken(expression_t *expression, bool may_be_register)
8654 if (expression->kind != EXPR_REFERENCE)
8657 entity_t *const entity = expression->reference.entity;
8659 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8662 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8663 && !may_be_register) {
8664 errorf(&expression->base.source_position,
8665 "address of register %s '%Y' requested",
8666 get_entity_kind_name(entity->kind), entity->base.symbol);
8669 if (entity->kind == ENTITY_VARIABLE) {
8670 entity->variable.address_taken = true;
8672 assert(entity->kind == ENTITY_PARAMETER);
8673 entity->parameter.address_taken = true;
8678 * Check the semantic of the address taken expression.
8680 static void semantic_take_addr(unary_expression_t *expression)
8682 expression_t *value = expression->value;
8683 value->base.type = revert_automatic_type_conversion(value);
8685 type_t *orig_type = value->base.type;
8686 type_t *type = skip_typeref(orig_type);
8687 if (!is_type_valid(type))
8691 if (!is_lvalue(value)) {
8692 errorf(&expression->base.source_position, "'&' requires an lvalue");
8694 if (type->kind == TYPE_BITFIELD) {
8695 errorf(&expression->base.source_position,
8696 "'&' not allowed on object with bitfield type '%T'",
8700 set_address_taken(value, false);
8702 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8705 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8706 static expression_t *parse_##unexpression_type(void) \
8708 expression_t *unary_expression \
8709 = allocate_expression_zero(unexpression_type); \
8711 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8713 sfunc(&unary_expression->unary); \
8715 return unary_expression; \
8718 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8719 semantic_unexpr_arithmetic)
8720 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8721 semantic_unexpr_plus)
8722 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8724 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8725 semantic_dereference)
8726 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8728 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8729 semantic_unexpr_integer)
8730 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8732 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8735 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8737 static expression_t *parse_##unexpression_type(expression_t *left) \
8739 expression_t *unary_expression \
8740 = allocate_expression_zero(unexpression_type); \
8742 unary_expression->unary.value = left; \
8744 sfunc(&unary_expression->unary); \
8746 return unary_expression; \
8749 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8750 EXPR_UNARY_POSTFIX_INCREMENT,
8752 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8753 EXPR_UNARY_POSTFIX_DECREMENT,
8756 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8758 /* TODO: handle complex + imaginary types */
8760 type_left = get_unqualified_type(type_left);
8761 type_right = get_unqualified_type(type_right);
8763 /* § 6.3.1.8 Usual arithmetic conversions */
8764 if (type_left == type_long_double || type_right == type_long_double) {
8765 return type_long_double;
8766 } else if (type_left == type_double || type_right == type_double) {
8768 } else if (type_left == type_float || type_right == type_float) {
8772 type_left = promote_integer(type_left);
8773 type_right = promote_integer(type_right);
8775 if (type_left == type_right)
8778 bool const signed_left = is_type_signed(type_left);
8779 bool const signed_right = is_type_signed(type_right);
8780 int const rank_left = get_rank(type_left);
8781 int const rank_right = get_rank(type_right);
8783 if (signed_left == signed_right)
8784 return rank_left >= rank_right ? type_left : type_right;
8793 u_rank = rank_right;
8794 u_type = type_right;
8796 s_rank = rank_right;
8797 s_type = type_right;
8802 if (u_rank >= s_rank)
8805 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8807 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8808 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8812 case ATOMIC_TYPE_INT: return type_unsigned_int;
8813 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8814 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8816 default: panic("invalid atomic type");
8821 * Check the semantic restrictions for a binary expression.
8823 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8825 expression_t *const left = expression->left;
8826 expression_t *const right = expression->right;
8827 type_t *const orig_type_left = left->base.type;
8828 type_t *const orig_type_right = right->base.type;
8829 type_t *const type_left = skip_typeref(orig_type_left);
8830 type_t *const type_right = skip_typeref(orig_type_right);
8832 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8833 /* TODO: improve error message */
8834 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8835 errorf(&expression->base.source_position,
8836 "operation needs arithmetic types");
8841 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8842 expression->left = create_implicit_cast(left, arithmetic_type);
8843 expression->right = create_implicit_cast(right, arithmetic_type);
8844 expression->base.type = arithmetic_type;
8847 static void warn_div_by_zero(binary_expression_t const *const expression)
8849 if (!warning.div_by_zero ||
8850 !is_type_integer(expression->base.type))
8853 expression_t const *const right = expression->right;
8854 /* The type of the right operand can be different for /= */
8855 if (is_type_integer(right->base.type) &&
8856 is_constant_expression(right) &&
8857 fold_constant(right) == 0) {
8858 warningf(&expression->base.source_position, "division by zero");
8863 * Check the semantic restrictions for a div/mod expression.
8865 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8866 semantic_binexpr_arithmetic(expression);
8867 warn_div_by_zero(expression);
8870 static void warn_addsub_in_shift(const expression_t *const expr)
8872 if (expr->base.parenthesized)
8876 switch (expr->kind) {
8877 case EXPR_BINARY_ADD: op = '+'; break;
8878 case EXPR_BINARY_SUB: op = '-'; break;
8882 warningf(&expr->base.source_position,
8883 "suggest parentheses around '%c' inside shift", op);
8886 static void semantic_shift_op(binary_expression_t *expression)
8888 expression_t *const left = expression->left;
8889 expression_t *const right = expression->right;
8890 type_t *const orig_type_left = left->base.type;
8891 type_t *const orig_type_right = right->base.type;
8892 type_t * type_left = skip_typeref(orig_type_left);
8893 type_t * type_right = skip_typeref(orig_type_right);
8895 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8896 /* TODO: improve error message */
8897 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8898 errorf(&expression->base.source_position,
8899 "operands of shift operation must have integer types");
8904 if (warning.parentheses) {
8905 warn_addsub_in_shift(left);
8906 warn_addsub_in_shift(right);
8909 type_left = promote_integer(type_left);
8910 type_right = promote_integer(type_right);
8912 expression->left = create_implicit_cast(left, type_left);
8913 expression->right = create_implicit_cast(right, type_right);
8914 expression->base.type = type_left;
8917 static void semantic_add(binary_expression_t *expression)
8919 expression_t *const left = expression->left;
8920 expression_t *const right = expression->right;
8921 type_t *const orig_type_left = left->base.type;
8922 type_t *const orig_type_right = right->base.type;
8923 type_t *const type_left = skip_typeref(orig_type_left);
8924 type_t *const type_right = skip_typeref(orig_type_right);
8927 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8928 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8929 expression->left = create_implicit_cast(left, arithmetic_type);
8930 expression->right = create_implicit_cast(right, arithmetic_type);
8931 expression->base.type = arithmetic_type;
8932 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8933 check_pointer_arithmetic(&expression->base.source_position,
8934 type_left, orig_type_left);
8935 expression->base.type = type_left;
8936 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8937 check_pointer_arithmetic(&expression->base.source_position,
8938 type_right, orig_type_right);
8939 expression->base.type = type_right;
8940 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8941 errorf(&expression->base.source_position,
8942 "invalid operands to binary + ('%T', '%T')",
8943 orig_type_left, orig_type_right);
8947 static void semantic_sub(binary_expression_t *expression)
8949 expression_t *const left = expression->left;
8950 expression_t *const right = expression->right;
8951 type_t *const orig_type_left = left->base.type;
8952 type_t *const orig_type_right = right->base.type;
8953 type_t *const type_left = skip_typeref(orig_type_left);
8954 type_t *const type_right = skip_typeref(orig_type_right);
8955 source_position_t const *const pos = &expression->base.source_position;
8958 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8959 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8960 expression->left = create_implicit_cast(left, arithmetic_type);
8961 expression->right = create_implicit_cast(right, arithmetic_type);
8962 expression->base.type = arithmetic_type;
8963 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8964 check_pointer_arithmetic(&expression->base.source_position,
8965 type_left, orig_type_left);
8966 expression->base.type = type_left;
8967 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8968 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8969 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8970 if (!types_compatible(unqual_left, unqual_right)) {
8972 "subtracting pointers to incompatible types '%T' and '%T'",
8973 orig_type_left, orig_type_right);
8974 } else if (!is_type_object(unqual_left)) {
8975 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8976 errorf(pos, "subtracting pointers to non-object types '%T'",
8978 } else if (warning.other) {
8979 warningf(pos, "subtracting pointers to void");
8982 expression->base.type = type_ptrdiff_t;
8983 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8984 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8985 orig_type_left, orig_type_right);
8989 static void warn_string_literal_address(expression_t const* expr)
8991 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8992 expr = expr->unary.value;
8993 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8995 expr = expr->unary.value;
8998 if (expr->kind == EXPR_STRING_LITERAL ||
8999 expr->kind == EXPR_WIDE_STRING_LITERAL) {
9000 warningf(&expr->base.source_position,
9001 "comparison with string literal results in unspecified behaviour");
9005 static void warn_comparison_in_comparison(const expression_t *const expr)
9007 if (expr->base.parenthesized)
9009 switch (expr->base.kind) {
9010 case EXPR_BINARY_LESS:
9011 case EXPR_BINARY_GREATER:
9012 case EXPR_BINARY_LESSEQUAL:
9013 case EXPR_BINARY_GREATEREQUAL:
9014 case EXPR_BINARY_NOTEQUAL:
9015 case EXPR_BINARY_EQUAL:
9016 warningf(&expr->base.source_position,
9017 "comparisons like 'x <= y < z' do not have their mathematical meaning");
9024 static bool maybe_negative(expression_t const *const expr)
9027 !is_constant_expression(expr) ||
9028 fold_constant(expr) < 0;
9032 * Check the semantics of comparison expressions.
9034 * @param expression The expression to check.
9036 static void semantic_comparison(binary_expression_t *expression)
9038 expression_t *left = expression->left;
9039 expression_t *right = expression->right;
9041 if (warning.address) {
9042 warn_string_literal_address(left);
9043 warn_string_literal_address(right);
9045 expression_t const* const func_left = get_reference_address(left);
9046 if (func_left != NULL && is_null_pointer_constant(right)) {
9047 warningf(&expression->base.source_position,
9048 "the address of '%Y' will never be NULL",
9049 func_left->reference.entity->base.symbol);
9052 expression_t const* const func_right = get_reference_address(right);
9053 if (func_right != NULL && is_null_pointer_constant(right)) {
9054 warningf(&expression->base.source_position,
9055 "the address of '%Y' will never be NULL",
9056 func_right->reference.entity->base.symbol);
9060 if (warning.parentheses) {
9061 warn_comparison_in_comparison(left);
9062 warn_comparison_in_comparison(right);
9065 type_t *orig_type_left = left->base.type;
9066 type_t *orig_type_right = right->base.type;
9067 type_t *type_left = skip_typeref(orig_type_left);
9068 type_t *type_right = skip_typeref(orig_type_right);
9070 /* TODO non-arithmetic types */
9071 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9072 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9074 /* test for signed vs unsigned compares */
9075 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
9076 bool const signed_left = is_type_signed(type_left);
9077 bool const signed_right = is_type_signed(type_right);
9078 if (signed_left != signed_right) {
9079 /* FIXME long long needs better const folding magic */
9080 /* TODO check whether constant value can be represented by other type */
9081 if ((signed_left && maybe_negative(left)) ||
9082 (signed_right && maybe_negative(right))) {
9083 warningf(&expression->base.source_position,
9084 "comparison between signed and unsigned");
9089 expression->left = create_implicit_cast(left, arithmetic_type);
9090 expression->right = create_implicit_cast(right, arithmetic_type);
9091 expression->base.type = arithmetic_type;
9092 if (warning.float_equal &&
9093 (expression->base.kind == EXPR_BINARY_EQUAL ||
9094 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
9095 is_type_float(arithmetic_type)) {
9096 warningf(&expression->base.source_position,
9097 "comparing floating point with == or != is unsafe");
9099 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
9100 /* TODO check compatibility */
9101 } else if (is_type_pointer(type_left)) {
9102 expression->right = create_implicit_cast(right, type_left);
9103 } else if (is_type_pointer(type_right)) {
9104 expression->left = create_implicit_cast(left, type_right);
9105 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9106 type_error_incompatible("invalid operands in comparison",
9107 &expression->base.source_position,
9108 type_left, type_right);
9110 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9114 * Checks if a compound type has constant fields.
9116 static bool has_const_fields(const compound_type_t *type)
9118 compound_t *compound = type->compound;
9119 entity_t *entry = compound->members.entities;
9121 for (; entry != NULL; entry = entry->base.next) {
9122 if (!is_declaration(entry))
9125 const type_t *decl_type = skip_typeref(entry->declaration.type);
9126 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
9133 static bool is_valid_assignment_lhs(expression_t const* const left)
9135 type_t *const orig_type_left = revert_automatic_type_conversion(left);
9136 type_t *const type_left = skip_typeref(orig_type_left);
9138 if (!is_lvalue(left)) {
9139 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
9144 if (left->kind == EXPR_REFERENCE
9145 && left->reference.entity->kind == ENTITY_FUNCTION) {
9146 errorf(HERE, "cannot assign to function '%E'", left);
9150 if (is_type_array(type_left)) {
9151 errorf(HERE, "cannot assign to array '%E'", left);
9154 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
9155 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
9159 if (is_type_incomplete(type_left)) {
9160 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
9161 left, orig_type_left);
9164 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
9165 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
9166 left, orig_type_left);
9173 static void semantic_arithmetic_assign(binary_expression_t *expression)
9175 expression_t *left = expression->left;
9176 expression_t *right = expression->right;
9177 type_t *orig_type_left = left->base.type;
9178 type_t *orig_type_right = right->base.type;
9180 if (!is_valid_assignment_lhs(left))
9183 type_t *type_left = skip_typeref(orig_type_left);
9184 type_t *type_right = skip_typeref(orig_type_right);
9186 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
9187 /* TODO: improve error message */
9188 if (is_type_valid(type_left) && is_type_valid(type_right)) {
9189 errorf(&expression->base.source_position,
9190 "operation needs arithmetic types");
9195 /* combined instructions are tricky. We can't create an implicit cast on
9196 * the left side, because we need the uncasted form for the store.
9197 * The ast2firm pass has to know that left_type must be right_type
9198 * for the arithmetic operation and create a cast by itself */
9199 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9200 expression->right = create_implicit_cast(right, arithmetic_type);
9201 expression->base.type = type_left;
9204 static void semantic_divmod_assign(binary_expression_t *expression)
9206 semantic_arithmetic_assign(expression);
9207 warn_div_by_zero(expression);
9210 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
9212 expression_t *const left = expression->left;
9213 expression_t *const right = expression->right;
9214 type_t *const orig_type_left = left->base.type;
9215 type_t *const orig_type_right = right->base.type;
9216 type_t *const type_left = skip_typeref(orig_type_left);
9217 type_t *const type_right = skip_typeref(orig_type_right);
9219 if (!is_valid_assignment_lhs(left))
9222 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9223 /* combined instructions are tricky. We can't create an implicit cast on
9224 * the left side, because we need the uncasted form for the store.
9225 * The ast2firm pass has to know that left_type must be right_type
9226 * for the arithmetic operation and create a cast by itself */
9227 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
9228 expression->right = create_implicit_cast(right, arithmetic_type);
9229 expression->base.type = type_left;
9230 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9231 check_pointer_arithmetic(&expression->base.source_position,
9232 type_left, orig_type_left);
9233 expression->base.type = type_left;
9234 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9235 errorf(&expression->base.source_position,
9236 "incompatible types '%T' and '%T' in assignment",
9237 orig_type_left, orig_type_right);
9241 static void warn_logical_and_within_or(const expression_t *const expr)
9243 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
9245 if (expr->base.parenthesized)
9247 warningf(&expr->base.source_position,
9248 "suggest parentheses around && within ||");
9252 * Check the semantic restrictions of a logical expression.
9254 static void semantic_logical_op(binary_expression_t *expression)
9256 /* §6.5.13:2 Each of the operands shall have scalar type.
9257 * §6.5.14:2 Each of the operands shall have scalar type. */
9258 semantic_condition(expression->left, "left operand of logical operator");
9259 semantic_condition(expression->right, "right operand of logical operator");
9260 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
9261 warning.parentheses) {
9262 warn_logical_and_within_or(expression->left);
9263 warn_logical_and_within_or(expression->right);
9265 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9269 * Check the semantic restrictions of a binary assign expression.
9271 static void semantic_binexpr_assign(binary_expression_t *expression)
9273 expression_t *left = expression->left;
9274 type_t *orig_type_left = left->base.type;
9276 if (!is_valid_assignment_lhs(left))
9279 assign_error_t error = semantic_assign(orig_type_left, expression->right);
9280 report_assign_error(error, orig_type_left, expression->right,
9281 "assignment", &left->base.source_position);
9282 expression->right = create_implicit_cast(expression->right, orig_type_left);
9283 expression->base.type = orig_type_left;
9287 * Determine if the outermost operation (or parts thereof) of the given
9288 * expression has no effect in order to generate a warning about this fact.
9289 * Therefore in some cases this only examines some of the operands of the
9290 * expression (see comments in the function and examples below).
9292 * f() + 23; // warning, because + has no effect
9293 * x || f(); // no warning, because x controls execution of f()
9294 * x ? y : f(); // warning, because y has no effect
9295 * (void)x; // no warning to be able to suppress the warning
9296 * This function can NOT be used for an "expression has definitely no effect"-
9298 static bool expression_has_effect(const expression_t *const expr)
9300 switch (expr->kind) {
9301 case EXPR_UNKNOWN: break;
9302 case EXPR_INVALID: return true; /* do NOT warn */
9303 case EXPR_REFERENCE: return false;
9304 case EXPR_REFERENCE_ENUM_VALUE: return false;
9305 /* suppress the warning for microsoft __noop operations */
9306 case EXPR_CONST: return expr->conste.is_ms_noop;
9307 case EXPR_CHARACTER_CONSTANT: return false;
9308 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
9309 case EXPR_STRING_LITERAL: return false;
9310 case EXPR_WIDE_STRING_LITERAL: return false;
9311 case EXPR_LABEL_ADDRESS: return false;
9314 const call_expression_t *const call = &expr->call;
9315 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
9318 switch (call->function->builtin_symbol.symbol->ID) {
9319 case T___builtin_va_end: return true;
9320 default: return false;
9324 /* Generate the warning if either the left or right hand side of a
9325 * conditional expression has no effect */
9326 case EXPR_CONDITIONAL: {
9327 const conditional_expression_t *const cond = &expr->conditional;
9329 expression_has_effect(cond->true_expression) &&
9330 expression_has_effect(cond->false_expression);
9333 case EXPR_SELECT: return false;
9334 case EXPR_ARRAY_ACCESS: return false;
9335 case EXPR_SIZEOF: return false;
9336 case EXPR_CLASSIFY_TYPE: return false;
9337 case EXPR_ALIGNOF: return false;
9339 case EXPR_FUNCNAME: return false;
9340 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
9341 case EXPR_BUILTIN_CONSTANT_P: return false;
9342 case EXPR_BUILTIN_PREFETCH: return true;
9343 case EXPR_OFFSETOF: return false;
9344 case EXPR_VA_START: return true;
9345 case EXPR_VA_ARG: return true;
9346 case EXPR_STATEMENT: return true; // TODO
9347 case EXPR_COMPOUND_LITERAL: return false;
9349 case EXPR_UNARY_NEGATE: return false;
9350 case EXPR_UNARY_PLUS: return false;
9351 case EXPR_UNARY_BITWISE_NEGATE: return false;
9352 case EXPR_UNARY_NOT: return false;
9353 case EXPR_UNARY_DEREFERENCE: return false;
9354 case EXPR_UNARY_TAKE_ADDRESS: return false;
9355 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
9356 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
9357 case EXPR_UNARY_PREFIX_INCREMENT: return true;
9358 case EXPR_UNARY_PREFIX_DECREMENT: return true;
9360 /* Treat void casts as if they have an effect in order to being able to
9361 * suppress the warning */
9362 case EXPR_UNARY_CAST: {
9363 type_t *const type = skip_typeref(expr->base.type);
9364 return is_type_atomic(type, ATOMIC_TYPE_VOID);
9367 case EXPR_UNARY_CAST_IMPLICIT: return true;
9368 case EXPR_UNARY_ASSUME: return true;
9369 case EXPR_UNARY_DELETE: return true;
9370 case EXPR_UNARY_DELETE_ARRAY: return true;
9371 case EXPR_UNARY_THROW: return true;
9373 case EXPR_BINARY_ADD: return false;
9374 case EXPR_BINARY_SUB: return false;
9375 case EXPR_BINARY_MUL: return false;
9376 case EXPR_BINARY_DIV: return false;
9377 case EXPR_BINARY_MOD: return false;
9378 case EXPR_BINARY_EQUAL: return false;
9379 case EXPR_BINARY_NOTEQUAL: return false;
9380 case EXPR_BINARY_LESS: return false;
9381 case EXPR_BINARY_LESSEQUAL: return false;
9382 case EXPR_BINARY_GREATER: return false;
9383 case EXPR_BINARY_GREATEREQUAL: return false;
9384 case EXPR_BINARY_BITWISE_AND: return false;
9385 case EXPR_BINARY_BITWISE_OR: return false;
9386 case EXPR_BINARY_BITWISE_XOR: return false;
9387 case EXPR_BINARY_SHIFTLEFT: return false;
9388 case EXPR_BINARY_SHIFTRIGHT: return false;
9389 case EXPR_BINARY_ASSIGN: return true;
9390 case EXPR_BINARY_MUL_ASSIGN: return true;
9391 case EXPR_BINARY_DIV_ASSIGN: return true;
9392 case EXPR_BINARY_MOD_ASSIGN: return true;
9393 case EXPR_BINARY_ADD_ASSIGN: return true;
9394 case EXPR_BINARY_SUB_ASSIGN: return true;
9395 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
9396 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
9397 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9398 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9399 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
9401 /* Only examine the right hand side of && and ||, because the left hand
9402 * side already has the effect of controlling the execution of the right
9404 case EXPR_BINARY_LOGICAL_AND:
9405 case EXPR_BINARY_LOGICAL_OR:
9406 /* Only examine the right hand side of a comma expression, because the left
9407 * hand side has a separate warning */
9408 case EXPR_BINARY_COMMA:
9409 return expression_has_effect(expr->binary.right);
9411 case EXPR_BINARY_ISGREATER: return false;
9412 case EXPR_BINARY_ISGREATEREQUAL: return false;
9413 case EXPR_BINARY_ISLESS: return false;
9414 case EXPR_BINARY_ISLESSEQUAL: return false;
9415 case EXPR_BINARY_ISLESSGREATER: return false;
9416 case EXPR_BINARY_ISUNORDERED: return false;
9419 internal_errorf(HERE, "unexpected expression");
9422 static void semantic_comma(binary_expression_t *expression)
9424 if (warning.unused_value) {
9425 const expression_t *const left = expression->left;
9426 if (!expression_has_effect(left)) {
9427 warningf(&left->base.source_position,
9428 "left-hand operand of comma expression has no effect");
9431 expression->base.type = expression->right->base.type;
9435 * @param prec_r precedence of the right operand
9437 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9438 static expression_t *parse_##binexpression_type(expression_t *left) \
9440 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9441 binexpr->binary.left = left; \
9444 expression_t *right = parse_sub_expression(prec_r); \
9446 binexpr->binary.right = right; \
9447 sfunc(&binexpr->binary); \
9452 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9453 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9454 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9455 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9456 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9457 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9458 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9459 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9460 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9461 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9462 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9463 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9464 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9465 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9466 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9467 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9468 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9469 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9470 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9471 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9472 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9473 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9474 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9475 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9476 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9477 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9478 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9479 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9480 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9481 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9484 static expression_t *parse_sub_expression(precedence_t precedence)
9486 if (token.type < 0) {
9487 return expected_expression_error();
9490 expression_parser_function_t *parser
9491 = &expression_parsers[token.type];
9492 source_position_t source_position = token.source_position;
9495 if (parser->parser != NULL) {
9496 left = parser->parser();
9498 left = parse_primary_expression();
9500 assert(left != NULL);
9501 left->base.source_position = source_position;
9504 if (token.type < 0) {
9505 return expected_expression_error();
9508 parser = &expression_parsers[token.type];
9509 if (parser->infix_parser == NULL)
9511 if (parser->infix_precedence < precedence)
9514 left = parser->infix_parser(left);
9516 assert(left != NULL);
9517 assert(left->kind != EXPR_UNKNOWN);
9518 left->base.source_position = source_position;
9525 * Parse an expression.
9527 static expression_t *parse_expression(void)
9529 return parse_sub_expression(PREC_EXPRESSION);
9533 * Register a parser for a prefix-like operator.
9535 * @param parser the parser function
9536 * @param token_type the token type of the prefix token
9538 static void register_expression_parser(parse_expression_function parser,
9541 expression_parser_function_t *entry = &expression_parsers[token_type];
9543 if (entry->parser != NULL) {
9544 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9545 panic("trying to register multiple expression parsers for a token");
9547 entry->parser = parser;
9551 * Register a parser for an infix operator with given precedence.
9553 * @param parser the parser function
9554 * @param token_type the token type of the infix operator
9555 * @param precedence the precedence of the operator
9557 static void register_infix_parser(parse_expression_infix_function parser,
9558 int token_type, precedence_t precedence)
9560 expression_parser_function_t *entry = &expression_parsers[token_type];
9562 if (entry->infix_parser != NULL) {
9563 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9564 panic("trying to register multiple infix expression parsers for a "
9567 entry->infix_parser = parser;
9568 entry->infix_precedence = precedence;
9572 * Initialize the expression parsers.
9574 static void init_expression_parsers(void)
9576 memset(&expression_parsers, 0, sizeof(expression_parsers));
9578 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9579 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9580 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9581 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9582 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9583 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9584 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9585 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9586 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9587 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9588 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9589 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9590 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9591 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9592 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9593 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9594 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9595 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9596 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9597 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9598 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9599 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9600 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9601 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9602 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9603 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9604 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9605 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9606 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9607 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9608 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9609 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9610 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9611 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9612 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9613 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9614 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9616 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9617 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9618 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9619 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9620 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9621 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9622 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9623 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9624 register_expression_parser(parse_sizeof, T_sizeof);
9625 register_expression_parser(parse_alignof, T___alignof__);
9626 register_expression_parser(parse_extension, T___extension__);
9627 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9628 register_expression_parser(parse_delete, T_delete);
9629 register_expression_parser(parse_throw, T_throw);
9633 * Parse a asm statement arguments specification.
9635 static asm_argument_t *parse_asm_arguments(bool is_out)
9637 asm_argument_t *result = NULL;
9638 asm_argument_t **anchor = &result;
9640 while (token.type == T_STRING_LITERAL || token.type == '[') {
9641 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9642 memset(argument, 0, sizeof(argument[0]));
9644 if (token.type == '[') {
9646 if (token.type != T_IDENTIFIER) {
9647 parse_error_expected("while parsing asm argument",
9648 T_IDENTIFIER, NULL);
9651 argument->symbol = token.v.symbol;
9653 expect(']', end_error);
9656 argument->constraints = parse_string_literals();
9657 expect('(', end_error);
9658 add_anchor_token(')');
9659 expression_t *expression = parse_expression();
9660 rem_anchor_token(')');
9662 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9663 * change size or type representation (e.g. int -> long is ok, but
9664 * int -> float is not) */
9665 if (expression->kind == EXPR_UNARY_CAST) {
9666 type_t *const type = expression->base.type;
9667 type_kind_t const kind = type->kind;
9668 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9671 if (kind == TYPE_ATOMIC) {
9672 atomic_type_kind_t const akind = type->atomic.akind;
9673 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9674 size = get_atomic_type_size(akind);
9676 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9677 size = get_atomic_type_size(get_intptr_kind());
9681 expression_t *const value = expression->unary.value;
9682 type_t *const value_type = value->base.type;
9683 type_kind_t const value_kind = value_type->kind;
9685 unsigned value_flags;
9686 unsigned value_size;
9687 if (value_kind == TYPE_ATOMIC) {
9688 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9689 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9690 value_size = get_atomic_type_size(value_akind);
9691 } else if (value_kind == TYPE_POINTER) {
9692 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9693 value_size = get_atomic_type_size(get_intptr_kind());
9698 if (value_flags != flags || value_size != size)
9702 } while (expression->kind == EXPR_UNARY_CAST);
9706 if (!is_lvalue(expression)) {
9707 errorf(&expression->base.source_position,
9708 "asm output argument is not an lvalue");
9711 if (argument->constraints.begin[0] == '+')
9712 mark_vars_read(expression, NULL);
9714 mark_vars_read(expression, NULL);
9716 argument->expression = expression;
9717 expect(')', end_error);
9719 set_address_taken(expression, true);
9722 anchor = &argument->next;
9724 if (token.type != ',')
9735 * Parse a asm statement clobber specification.
9737 static asm_clobber_t *parse_asm_clobbers(void)
9739 asm_clobber_t *result = NULL;
9740 asm_clobber_t *last = NULL;
9742 while (token.type == T_STRING_LITERAL) {
9743 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9744 clobber->clobber = parse_string_literals();
9747 last->next = clobber;
9753 if (token.type != ',')
9762 * Parse an asm statement.
9764 static statement_t *parse_asm_statement(void)
9766 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9767 asm_statement_t *asm_statement = &statement->asms;
9771 if (token.type == T_volatile) {
9773 asm_statement->is_volatile = true;
9776 expect('(', end_error);
9777 add_anchor_token(')');
9778 add_anchor_token(':');
9779 asm_statement->asm_text = parse_string_literals();
9781 if (token.type != ':') {
9782 rem_anchor_token(':');
9787 asm_statement->outputs = parse_asm_arguments(true);
9788 if (token.type != ':') {
9789 rem_anchor_token(':');
9794 asm_statement->inputs = parse_asm_arguments(false);
9795 if (token.type != ':') {
9796 rem_anchor_token(':');
9799 rem_anchor_token(':');
9802 asm_statement->clobbers = parse_asm_clobbers();
9805 rem_anchor_token(')');
9806 expect(')', end_error);
9807 expect(';', end_error);
9809 if (asm_statement->outputs == NULL) {
9810 /* GCC: An 'asm' instruction without any output operands will be treated
9811 * identically to a volatile 'asm' instruction. */
9812 asm_statement->is_volatile = true;
9817 return create_invalid_statement();
9821 * Parse a case statement.
9823 static statement_t *parse_case_statement(void)
9825 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9826 source_position_t *const pos = &statement->base.source_position;
9830 expression_t *const expression = parse_expression();
9831 statement->case_label.expression = expression;
9832 if (!is_constant_expression(expression)) {
9833 /* This check does not prevent the error message in all cases of an
9834 * prior error while parsing the expression. At least it catches the
9835 * common case of a mistyped enum entry. */
9836 if (is_type_valid(skip_typeref(expression->base.type))) {
9837 errorf(pos, "case label does not reduce to an integer constant");
9839 statement->case_label.is_bad = true;
9841 long const val = fold_constant(expression);
9842 statement->case_label.first_case = val;
9843 statement->case_label.last_case = val;
9847 if (token.type == T_DOTDOTDOT) {
9849 expression_t *const end_range = parse_expression();
9850 statement->case_label.end_range = end_range;
9851 if (!is_constant_expression(end_range)) {
9852 /* This check does not prevent the error message in all cases of an
9853 * prior error while parsing the expression. At least it catches the
9854 * common case of a mistyped enum entry. */
9855 if (is_type_valid(skip_typeref(end_range->base.type))) {
9856 errorf(pos, "case range does not reduce to an integer constant");
9858 statement->case_label.is_bad = true;
9860 long const val = fold_constant(end_range);
9861 statement->case_label.last_case = val;
9863 if (warning.other && val < statement->case_label.first_case) {
9864 statement->case_label.is_empty_range = true;
9865 warningf(pos, "empty range specified");
9871 PUSH_PARENT(statement);
9873 expect(':', end_error);
9876 if (current_switch != NULL) {
9877 if (! statement->case_label.is_bad) {
9878 /* Check for duplicate case values */
9879 case_label_statement_t *c = &statement->case_label;
9880 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9881 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9884 if (c->last_case < l->first_case || c->first_case > l->last_case)
9887 errorf(pos, "duplicate case value (previously used %P)",
9888 &l->base.source_position);
9892 /* link all cases into the switch statement */
9893 if (current_switch->last_case == NULL) {
9894 current_switch->first_case = &statement->case_label;
9896 current_switch->last_case->next = &statement->case_label;
9898 current_switch->last_case = &statement->case_label;
9900 errorf(pos, "case label not within a switch statement");
9903 statement_t *const inner_stmt = parse_statement();
9904 statement->case_label.statement = inner_stmt;
9905 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9906 errorf(&inner_stmt->base.source_position, "declaration after case label");
9914 * Parse a default statement.
9916 static statement_t *parse_default_statement(void)
9918 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9922 PUSH_PARENT(statement);
9924 expect(':', end_error);
9925 if (current_switch != NULL) {
9926 const case_label_statement_t *def_label = current_switch->default_label;
9927 if (def_label != NULL) {
9928 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9929 &def_label->base.source_position);
9931 current_switch->default_label = &statement->case_label;
9933 /* link all cases into the switch statement */
9934 if (current_switch->last_case == NULL) {
9935 current_switch->first_case = &statement->case_label;
9937 current_switch->last_case->next = &statement->case_label;
9939 current_switch->last_case = &statement->case_label;
9942 errorf(&statement->base.source_position,
9943 "'default' label not within a switch statement");
9946 statement_t *const inner_stmt = parse_statement();
9947 statement->case_label.statement = inner_stmt;
9948 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9949 errorf(&inner_stmt->base.source_position, "declaration after default label");
9956 return create_invalid_statement();
9960 * Parse a label statement.
9962 static statement_t *parse_label_statement(void)
9964 assert(token.type == T_IDENTIFIER);
9965 symbol_t *symbol = token.v.symbol;
9966 label_t *label = get_label(symbol);
9968 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9969 statement->label.label = label;
9973 PUSH_PARENT(statement);
9975 /* if statement is already set then the label is defined twice,
9976 * otherwise it was just mentioned in a goto/local label declaration so far
9978 if (label->statement != NULL) {
9979 errorf(HERE, "duplicate label '%Y' (declared %P)",
9980 symbol, &label->base.source_position);
9982 label->base.source_position = token.source_position;
9983 label->statement = statement;
9988 if (token.type == '}') {
9989 /* TODO only warn? */
9990 if (warning.other && false) {
9991 warningf(HERE, "label at end of compound statement");
9992 statement->label.statement = create_empty_statement();
9994 errorf(HERE, "label at end of compound statement");
9995 statement->label.statement = create_invalid_statement();
9997 } else if (token.type == ';') {
9998 /* Eat an empty statement here, to avoid the warning about an empty
9999 * statement after a label. label:; is commonly used to have a label
10000 * before a closing brace. */
10001 statement->label.statement = create_empty_statement();
10004 statement_t *const inner_stmt = parse_statement();
10005 statement->label.statement = inner_stmt;
10006 if (inner_stmt->kind == STATEMENT_DECLARATION) {
10007 errorf(&inner_stmt->base.source_position, "declaration after label");
10011 /* remember the labels in a list for later checking */
10012 *label_anchor = &statement->label;
10013 label_anchor = &statement->label.next;
10020 * Parse an if statement.
10022 static statement_t *parse_if(void)
10024 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
10028 PUSH_PARENT(statement);
10030 add_anchor_token('{');
10032 expect('(', end_error);
10033 add_anchor_token(')');
10034 expression_t *const expr = parse_expression();
10035 statement->ifs.condition = expr;
10036 /* §6.8.4.1:1 The controlling expression of an if statement shall have
10038 semantic_condition(expr, "condition of 'if'-statment");
10039 mark_vars_read(expr, NULL);
10040 rem_anchor_token(')');
10041 expect(')', end_error);
10044 rem_anchor_token('{');
10046 add_anchor_token(T_else);
10047 statement_t *const true_stmt = parse_statement();
10048 statement->ifs.true_statement = true_stmt;
10049 rem_anchor_token(T_else);
10051 if (token.type == T_else) {
10053 statement->ifs.false_statement = parse_statement();
10054 } else if (warning.parentheses &&
10055 true_stmt->kind == STATEMENT_IF &&
10056 true_stmt->ifs.false_statement != NULL) {
10057 warningf(&true_stmt->base.source_position,
10058 "suggest explicit braces to avoid ambiguous 'else'");
10066 * Check that all enums are handled in a switch.
10068 * @param statement the switch statement to check
10070 static void check_enum_cases(const switch_statement_t *statement) {
10071 const type_t *type = skip_typeref(statement->expression->base.type);
10072 if (! is_type_enum(type))
10074 const enum_type_t *enumt = &type->enumt;
10076 /* if we have a default, no warnings */
10077 if (statement->default_label != NULL)
10080 /* FIXME: calculation of value should be done while parsing */
10081 /* TODO: quadratic algorithm here. Change to an n log n one */
10082 long last_value = -1;
10083 const entity_t *entry = enumt->enume->base.next;
10084 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
10085 entry = entry->base.next) {
10086 const expression_t *expression = entry->enum_value.value;
10087 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
10088 bool found = false;
10089 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
10090 if (l->expression == NULL)
10092 if (l->first_case <= value && value <= l->last_case) {
10098 warningf(&statement->base.source_position,
10099 "enumeration value '%Y' not handled in switch",
10100 entry->base.symbol);
10102 last_value = value;
10107 * Parse a switch statement.
10109 static statement_t *parse_switch(void)
10111 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
10115 PUSH_PARENT(statement);
10117 expect('(', end_error);
10118 add_anchor_token(')');
10119 expression_t *const expr = parse_expression();
10120 mark_vars_read(expr, NULL);
10121 type_t * type = skip_typeref(expr->base.type);
10122 if (is_type_integer(type)) {
10123 type = promote_integer(type);
10124 if (warning.traditional) {
10125 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
10126 warningf(&expr->base.source_position,
10127 "'%T' switch expression not converted to '%T' in ISO C",
10131 } else if (is_type_valid(type)) {
10132 errorf(&expr->base.source_position,
10133 "switch quantity is not an integer, but '%T'", type);
10134 type = type_error_type;
10136 statement->switchs.expression = create_implicit_cast(expr, type);
10137 expect(')', end_error);
10138 rem_anchor_token(')');
10140 switch_statement_t *rem = current_switch;
10141 current_switch = &statement->switchs;
10142 statement->switchs.body = parse_statement();
10143 current_switch = rem;
10145 if (warning.switch_default &&
10146 statement->switchs.default_label == NULL) {
10147 warningf(&statement->base.source_position, "switch has no default case");
10149 if (warning.switch_enum)
10150 check_enum_cases(&statement->switchs);
10156 return create_invalid_statement();
10159 static statement_t *parse_loop_body(statement_t *const loop)
10161 statement_t *const rem = current_loop;
10162 current_loop = loop;
10164 statement_t *const body = parse_statement();
10166 current_loop = rem;
10171 * Parse a while statement.
10173 static statement_t *parse_while(void)
10175 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
10179 PUSH_PARENT(statement);
10181 expect('(', end_error);
10182 add_anchor_token(')');
10183 expression_t *const cond = parse_expression();
10184 statement->whiles.condition = cond;
10185 /* §6.8.5:2 The controlling expression of an iteration statement shall
10186 * have scalar type. */
10187 semantic_condition(cond, "condition of 'while'-statement");
10188 mark_vars_read(cond, NULL);
10189 rem_anchor_token(')');
10190 expect(')', end_error);
10192 statement->whiles.body = parse_loop_body(statement);
10198 return create_invalid_statement();
10202 * Parse a do statement.
10204 static statement_t *parse_do(void)
10206 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
10210 PUSH_PARENT(statement);
10212 add_anchor_token(T_while);
10213 statement->do_while.body = parse_loop_body(statement);
10214 rem_anchor_token(T_while);
10216 expect(T_while, end_error);
10217 expect('(', end_error);
10218 add_anchor_token(')');
10219 expression_t *const cond = parse_expression();
10220 statement->do_while.condition = cond;
10221 /* §6.8.5:2 The controlling expression of an iteration statement shall
10222 * have scalar type. */
10223 semantic_condition(cond, "condition of 'do-while'-statement");
10224 mark_vars_read(cond, NULL);
10225 rem_anchor_token(')');
10226 expect(')', end_error);
10227 expect(';', end_error);
10233 return create_invalid_statement();
10237 * Parse a for statement.
10239 static statement_t *parse_for(void)
10241 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
10245 expect('(', end_error1);
10246 add_anchor_token(')');
10248 PUSH_PARENT(statement);
10250 size_t const top = environment_top();
10251 scope_t *old_scope = scope_push(&statement->fors.scope);
10253 if (token.type == ';') {
10255 } else if (is_declaration_specifier(&token, false)) {
10256 parse_declaration(record_entity, DECL_FLAGS_NONE);
10258 add_anchor_token(';');
10259 expression_t *const init = parse_expression();
10260 statement->fors.initialisation = init;
10261 mark_vars_read(init, ENT_ANY);
10262 if (warning.unused_value && !expression_has_effect(init)) {
10263 warningf(&init->base.source_position,
10264 "initialisation of 'for'-statement has no effect");
10266 rem_anchor_token(';');
10267 expect(';', end_error2);
10270 if (token.type != ';') {
10271 add_anchor_token(';');
10272 expression_t *const cond = parse_expression();
10273 statement->fors.condition = cond;
10274 /* §6.8.5:2 The controlling expression of an iteration statement
10275 * shall have scalar type. */
10276 semantic_condition(cond, "condition of 'for'-statement");
10277 mark_vars_read(cond, NULL);
10278 rem_anchor_token(';');
10280 expect(';', end_error2);
10281 if (token.type != ')') {
10282 expression_t *const step = parse_expression();
10283 statement->fors.step = step;
10284 mark_vars_read(step, ENT_ANY);
10285 if (warning.unused_value && !expression_has_effect(step)) {
10286 warningf(&step->base.source_position,
10287 "step of 'for'-statement has no effect");
10290 expect(')', end_error2);
10291 rem_anchor_token(')');
10292 statement->fors.body = parse_loop_body(statement);
10294 assert(current_scope == &statement->fors.scope);
10295 scope_pop(old_scope);
10296 environment_pop_to(top);
10303 rem_anchor_token(')');
10304 assert(current_scope == &statement->fors.scope);
10305 scope_pop(old_scope);
10306 environment_pop_to(top);
10310 return create_invalid_statement();
10314 * Parse a goto statement.
10316 static statement_t *parse_goto(void)
10318 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
10321 if (GNU_MODE && token.type == '*') {
10323 expression_t *expression = parse_expression();
10324 mark_vars_read(expression, NULL);
10326 /* Argh: although documentation says the expression must be of type void*,
10327 * gcc accepts anything that can be casted into void* without error */
10328 type_t *type = expression->base.type;
10330 if (type != type_error_type) {
10331 if (!is_type_pointer(type) && !is_type_integer(type)) {
10332 errorf(&expression->base.source_position,
10333 "cannot convert to a pointer type");
10334 } else if (warning.other && type != type_void_ptr) {
10335 warningf(&expression->base.source_position,
10336 "type of computed goto expression should be 'void*' not '%T'", type);
10338 expression = create_implicit_cast(expression, type_void_ptr);
10341 statement->gotos.expression = expression;
10343 if (token.type != T_IDENTIFIER) {
10345 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
10347 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
10348 eat_until_anchor();
10351 symbol_t *symbol = token.v.symbol;
10354 statement->gotos.label = get_label(symbol);
10357 /* remember the goto's in a list for later checking */
10358 *goto_anchor = &statement->gotos;
10359 goto_anchor = &statement->gotos.next;
10361 expect(';', end_error);
10365 return create_invalid_statement();
10369 * Parse a continue statement.
10371 static statement_t *parse_continue(void)
10373 if (current_loop == NULL) {
10374 errorf(HERE, "continue statement not within loop");
10377 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
10380 expect(';', end_error);
10387 * Parse a break statement.
10389 static statement_t *parse_break(void)
10391 if (current_switch == NULL && current_loop == NULL) {
10392 errorf(HERE, "break statement not within loop or switch");
10395 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10398 expect(';', end_error);
10405 * Parse a __leave statement.
10407 static statement_t *parse_leave_statement(void)
10409 if (current_try == NULL) {
10410 errorf(HERE, "__leave statement not within __try");
10413 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10416 expect(';', end_error);
10423 * Check if a given entity represents a local variable.
10425 static bool is_local_variable(const entity_t *entity)
10427 if (entity->kind != ENTITY_VARIABLE)
10430 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10431 case STORAGE_CLASS_AUTO:
10432 case STORAGE_CLASS_REGISTER: {
10433 const type_t *type = skip_typeref(entity->declaration.type);
10434 if (is_type_function(type)) {
10446 * Check if a given expression represents a local variable.
10448 static bool expression_is_local_variable(const expression_t *expression)
10450 if (expression->base.kind != EXPR_REFERENCE) {
10453 const entity_t *entity = expression->reference.entity;
10454 return is_local_variable(entity);
10458 * Check if a given expression represents a local variable and
10459 * return its declaration then, else return NULL.
10461 entity_t *expression_is_variable(const expression_t *expression)
10463 if (expression->base.kind != EXPR_REFERENCE) {
10466 entity_t *entity = expression->reference.entity;
10467 if (entity->kind != ENTITY_VARIABLE)
10474 * Parse a return statement.
10476 static statement_t *parse_return(void)
10480 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10482 expression_t *return_value = NULL;
10483 if (token.type != ';') {
10484 return_value = parse_expression();
10485 mark_vars_read(return_value, NULL);
10488 const type_t *const func_type = skip_typeref(current_function->base.type);
10489 assert(is_type_function(func_type));
10490 type_t *const return_type = skip_typeref(func_type->function.return_type);
10492 source_position_t const *const pos = &statement->base.source_position;
10493 if (return_value != NULL) {
10494 type_t *return_value_type = skip_typeref(return_value->base.type);
10496 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10497 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10498 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10499 /* Only warn in C mode, because GCC does the same */
10500 if (c_mode & _CXX || strict_mode) {
10502 "'return' with a value, in function returning 'void'");
10503 } else if (warning.other) {
10505 "'return' with a value, in function returning 'void'");
10507 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10508 /* Only warn in C mode, because GCC does the same */
10511 "'return' with expression in function return 'void'");
10512 } else if (warning.other) {
10514 "'return' with expression in function return 'void'");
10518 assign_error_t error = semantic_assign(return_type, return_value);
10519 report_assign_error(error, return_type, return_value, "'return'",
10522 return_value = create_implicit_cast(return_value, return_type);
10523 /* check for returning address of a local var */
10524 if (warning.other && return_value != NULL
10525 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10526 const expression_t *expression = return_value->unary.value;
10527 if (expression_is_local_variable(expression)) {
10528 warningf(pos, "function returns address of local variable");
10531 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10532 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10533 if (c_mode & _CXX || strict_mode) {
10535 "'return' without value, in function returning non-void");
10538 "'return' without value, in function returning non-void");
10541 statement->returns.value = return_value;
10543 expect(';', end_error);
10550 * Parse a declaration statement.
10552 static statement_t *parse_declaration_statement(void)
10554 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10556 entity_t *before = current_scope->last_entity;
10558 parse_external_declaration();
10560 parse_declaration(record_entity, DECL_FLAGS_NONE);
10563 if (before == NULL) {
10564 statement->declaration.declarations_begin = current_scope->entities;
10566 statement->declaration.declarations_begin = before->base.next;
10568 statement->declaration.declarations_end = current_scope->last_entity;
10574 * Parse an expression statement, ie. expr ';'.
10576 static statement_t *parse_expression_statement(void)
10578 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10580 expression_t *const expr = parse_expression();
10581 statement->expression.expression = expr;
10582 mark_vars_read(expr, ENT_ANY);
10584 expect(';', end_error);
10591 * Parse a microsoft __try { } __finally { } or
10592 * __try{ } __except() { }
10594 static statement_t *parse_ms_try_statment(void)
10596 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10599 PUSH_PARENT(statement);
10601 ms_try_statement_t *rem = current_try;
10602 current_try = &statement->ms_try;
10603 statement->ms_try.try_statement = parse_compound_statement(false);
10608 if (token.type == T___except) {
10610 expect('(', end_error);
10611 add_anchor_token(')');
10612 expression_t *const expr = parse_expression();
10613 mark_vars_read(expr, NULL);
10614 type_t * type = skip_typeref(expr->base.type);
10615 if (is_type_integer(type)) {
10616 type = promote_integer(type);
10617 } else if (is_type_valid(type)) {
10618 errorf(&expr->base.source_position,
10619 "__expect expression is not an integer, but '%T'", type);
10620 type = type_error_type;
10622 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10623 rem_anchor_token(')');
10624 expect(')', end_error);
10625 statement->ms_try.final_statement = parse_compound_statement(false);
10626 } else if (token.type == T__finally) {
10628 statement->ms_try.final_statement = parse_compound_statement(false);
10630 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10631 return create_invalid_statement();
10635 return create_invalid_statement();
10638 static statement_t *parse_empty_statement(void)
10640 if (warning.empty_statement) {
10641 warningf(HERE, "statement is empty");
10643 statement_t *const statement = create_empty_statement();
10648 static statement_t *parse_local_label_declaration(void)
10650 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10654 entity_t *begin = NULL, *end = NULL;
10657 if (token.type != T_IDENTIFIER) {
10658 parse_error_expected("while parsing local label declaration",
10659 T_IDENTIFIER, NULL);
10662 symbol_t *symbol = token.v.symbol;
10663 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10664 if (entity != NULL && entity->base.parent_scope == current_scope) {
10665 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10666 symbol, &entity->base.source_position);
10668 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10670 entity->base.parent_scope = current_scope;
10671 entity->base.namespc = NAMESPACE_LABEL;
10672 entity->base.source_position = token.source_position;
10673 entity->base.symbol = symbol;
10676 end->base.next = entity;
10681 environment_push(entity);
10685 if (token.type != ',')
10691 statement->declaration.declarations_begin = begin;
10692 statement->declaration.declarations_end = end;
10696 static void parse_namespace_definition(void)
10700 entity_t *entity = NULL;
10701 symbol_t *symbol = NULL;
10703 if (token.type == T_IDENTIFIER) {
10704 symbol = token.v.symbol;
10707 entity = get_entity(symbol, NAMESPACE_NORMAL);
10708 if (entity != NULL && entity->kind != ENTITY_NAMESPACE
10709 && entity->base.parent_scope == current_scope) {
10710 error_redefined_as_different_kind(&token.source_position,
10711 entity, ENTITY_NAMESPACE);
10716 if (entity == NULL) {
10717 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10718 entity->base.symbol = symbol;
10719 entity->base.source_position = token.source_position;
10720 entity->base.namespc = NAMESPACE_NORMAL;
10721 entity->base.parent_scope = current_scope;
10724 if (token.type == '=') {
10725 /* TODO: parse namespace alias */
10726 panic("namespace alias definition not supported yet");
10729 environment_push(entity);
10730 append_entity(current_scope, entity);
10732 size_t const top = environment_top();
10733 scope_t *old_scope = scope_push(&entity->namespacee.members);
10735 expect('{', end_error);
10737 expect('}', end_error);
10740 assert(current_scope == &entity->namespacee.members);
10741 scope_pop(old_scope);
10742 environment_pop_to(top);
10746 * Parse a statement.
10747 * There's also parse_statement() which additionally checks for
10748 * "statement has no effect" warnings
10750 static statement_t *intern_parse_statement(void)
10752 statement_t *statement = NULL;
10754 /* declaration or statement */
10755 add_anchor_token(';');
10756 switch (token.type) {
10757 case T_IDENTIFIER: {
10758 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10759 if (la1_type == ':') {
10760 statement = parse_label_statement();
10761 } else if (is_typedef_symbol(token.v.symbol)) {
10762 statement = parse_declaration_statement();
10764 /* it's an identifier, the grammar says this must be an
10765 * expression statement. However it is common that users mistype
10766 * declaration types, so we guess a bit here to improve robustness
10767 * for incorrect programs */
10768 switch (la1_type) {
10771 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10772 goto expression_statment;
10777 statement = parse_declaration_statement();
10781 expression_statment:
10782 statement = parse_expression_statement();
10789 case T___extension__:
10790 /* This can be a prefix to a declaration or an expression statement.
10791 * We simply eat it now and parse the rest with tail recursion. */
10794 } while (token.type == T___extension__);
10795 bool old_gcc_extension = in_gcc_extension;
10796 in_gcc_extension = true;
10797 statement = intern_parse_statement();
10798 in_gcc_extension = old_gcc_extension;
10802 statement = parse_declaration_statement();
10806 statement = parse_local_label_declaration();
10809 case ';': statement = parse_empty_statement(); break;
10810 case '{': statement = parse_compound_statement(false); break;
10811 case T___leave: statement = parse_leave_statement(); break;
10812 case T___try: statement = parse_ms_try_statment(); break;
10813 case T_asm: statement = parse_asm_statement(); break;
10814 case T_break: statement = parse_break(); break;
10815 case T_case: statement = parse_case_statement(); break;
10816 case T_continue: statement = parse_continue(); break;
10817 case T_default: statement = parse_default_statement(); break;
10818 case T_do: statement = parse_do(); break;
10819 case T_for: statement = parse_for(); break;
10820 case T_goto: statement = parse_goto(); break;
10821 case T_if: statement = parse_if(); break;
10822 case T_return: statement = parse_return(); break;
10823 case T_switch: statement = parse_switch(); break;
10824 case T_while: statement = parse_while(); break;
10827 statement = parse_expression_statement();
10831 errorf(HERE, "unexpected token %K while parsing statement", &token);
10832 statement = create_invalid_statement();
10837 rem_anchor_token(';');
10839 assert(statement != NULL
10840 && statement->base.source_position.input_name != NULL);
10846 * parse a statement and emits "statement has no effect" warning if needed
10847 * (This is really a wrapper around intern_parse_statement with check for 1
10848 * single warning. It is needed, because for statement expressions we have
10849 * to avoid the warning on the last statement)
10851 static statement_t *parse_statement(void)
10853 statement_t *statement = intern_parse_statement();
10855 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10856 expression_t *expression = statement->expression.expression;
10857 if (!expression_has_effect(expression)) {
10858 warningf(&expression->base.source_position,
10859 "statement has no effect");
10867 * Parse a compound statement.
10869 static statement_t *parse_compound_statement(bool inside_expression_statement)
10871 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10873 PUSH_PARENT(statement);
10876 add_anchor_token('}');
10877 /* tokens, which can start a statement */
10878 /* TODO MS, __builtin_FOO */
10879 add_anchor_token('!');
10880 add_anchor_token('&');
10881 add_anchor_token('(');
10882 add_anchor_token('*');
10883 add_anchor_token('+');
10884 add_anchor_token('-');
10885 add_anchor_token('{');
10886 add_anchor_token('~');
10887 add_anchor_token(T_CHARACTER_CONSTANT);
10888 add_anchor_token(T_COLONCOLON);
10889 add_anchor_token(T_FLOATINGPOINT);
10890 add_anchor_token(T_IDENTIFIER);
10891 add_anchor_token(T_INTEGER);
10892 add_anchor_token(T_MINUSMINUS);
10893 add_anchor_token(T_PLUSPLUS);
10894 add_anchor_token(T_STRING_LITERAL);
10895 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10896 add_anchor_token(T_WIDE_STRING_LITERAL);
10897 add_anchor_token(T__Bool);
10898 add_anchor_token(T__Complex);
10899 add_anchor_token(T__Imaginary);
10900 add_anchor_token(T___FUNCTION__);
10901 add_anchor_token(T___PRETTY_FUNCTION__);
10902 add_anchor_token(T___alignof__);
10903 add_anchor_token(T___attribute__);
10904 add_anchor_token(T___builtin_va_start);
10905 add_anchor_token(T___extension__);
10906 add_anchor_token(T___func__);
10907 add_anchor_token(T___imag__);
10908 add_anchor_token(T___label__);
10909 add_anchor_token(T___real__);
10910 add_anchor_token(T___thread);
10911 add_anchor_token(T_asm);
10912 add_anchor_token(T_auto);
10913 add_anchor_token(T_bool);
10914 add_anchor_token(T_break);
10915 add_anchor_token(T_case);
10916 add_anchor_token(T_char);
10917 add_anchor_token(T_class);
10918 add_anchor_token(T_const);
10919 add_anchor_token(T_const_cast);
10920 add_anchor_token(T_continue);
10921 add_anchor_token(T_default);
10922 add_anchor_token(T_delete);
10923 add_anchor_token(T_double);
10924 add_anchor_token(T_do);
10925 add_anchor_token(T_dynamic_cast);
10926 add_anchor_token(T_enum);
10927 add_anchor_token(T_extern);
10928 add_anchor_token(T_false);
10929 add_anchor_token(T_float);
10930 add_anchor_token(T_for);
10931 add_anchor_token(T_goto);
10932 add_anchor_token(T_if);
10933 add_anchor_token(T_inline);
10934 add_anchor_token(T_int);
10935 add_anchor_token(T_long);
10936 add_anchor_token(T_new);
10937 add_anchor_token(T_operator);
10938 add_anchor_token(T_register);
10939 add_anchor_token(T_reinterpret_cast);
10940 add_anchor_token(T_restrict);
10941 add_anchor_token(T_return);
10942 add_anchor_token(T_short);
10943 add_anchor_token(T_signed);
10944 add_anchor_token(T_sizeof);
10945 add_anchor_token(T_static);
10946 add_anchor_token(T_static_cast);
10947 add_anchor_token(T_struct);
10948 add_anchor_token(T_switch);
10949 add_anchor_token(T_template);
10950 add_anchor_token(T_this);
10951 add_anchor_token(T_throw);
10952 add_anchor_token(T_true);
10953 add_anchor_token(T_try);
10954 add_anchor_token(T_typedef);
10955 add_anchor_token(T_typeid);
10956 add_anchor_token(T_typename);
10957 add_anchor_token(T_typeof);
10958 add_anchor_token(T_union);
10959 add_anchor_token(T_unsigned);
10960 add_anchor_token(T_using);
10961 add_anchor_token(T_void);
10962 add_anchor_token(T_volatile);
10963 add_anchor_token(T_wchar_t);
10964 add_anchor_token(T_while);
10966 size_t const top = environment_top();
10967 scope_t *old_scope = scope_push(&statement->compound.scope);
10969 statement_t **anchor = &statement->compound.statements;
10970 bool only_decls_so_far = true;
10971 while (token.type != '}') {
10972 if (token.type == T_EOF) {
10973 errorf(&statement->base.source_position,
10974 "EOF while parsing compound statement");
10977 statement_t *sub_statement = intern_parse_statement();
10978 if (is_invalid_statement(sub_statement)) {
10979 /* an error occurred. if we are at an anchor, return */
10985 if (warning.declaration_after_statement) {
10986 if (sub_statement->kind != STATEMENT_DECLARATION) {
10987 only_decls_so_far = false;
10988 } else if (!only_decls_so_far) {
10989 warningf(&sub_statement->base.source_position,
10990 "ISO C90 forbids mixed declarations and code");
10994 *anchor = sub_statement;
10996 while (sub_statement->base.next != NULL)
10997 sub_statement = sub_statement->base.next;
10999 anchor = &sub_statement->base.next;
11003 /* look over all statements again to produce no effect warnings */
11004 if (warning.unused_value) {
11005 statement_t *sub_statement = statement->compound.statements;
11006 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
11007 if (sub_statement->kind != STATEMENT_EXPRESSION)
11009 /* don't emit a warning for the last expression in an expression
11010 * statement as it has always an effect */
11011 if (inside_expression_statement && sub_statement->base.next == NULL)
11014 expression_t *expression = sub_statement->expression.expression;
11015 if (!expression_has_effect(expression)) {
11016 warningf(&expression->base.source_position,
11017 "statement has no effect");
11023 rem_anchor_token(T_while);
11024 rem_anchor_token(T_wchar_t);
11025 rem_anchor_token(T_volatile);
11026 rem_anchor_token(T_void);
11027 rem_anchor_token(T_using);
11028 rem_anchor_token(T_unsigned);
11029 rem_anchor_token(T_union);
11030 rem_anchor_token(T_typeof);
11031 rem_anchor_token(T_typename);
11032 rem_anchor_token(T_typeid);
11033 rem_anchor_token(T_typedef);
11034 rem_anchor_token(T_try);
11035 rem_anchor_token(T_true);
11036 rem_anchor_token(T_throw);
11037 rem_anchor_token(T_this);
11038 rem_anchor_token(T_template);
11039 rem_anchor_token(T_switch);
11040 rem_anchor_token(T_struct);
11041 rem_anchor_token(T_static_cast);
11042 rem_anchor_token(T_static);
11043 rem_anchor_token(T_sizeof);
11044 rem_anchor_token(T_signed);
11045 rem_anchor_token(T_short);
11046 rem_anchor_token(T_return);
11047 rem_anchor_token(T_restrict);
11048 rem_anchor_token(T_reinterpret_cast);
11049 rem_anchor_token(T_register);
11050 rem_anchor_token(T_operator);
11051 rem_anchor_token(T_new);
11052 rem_anchor_token(T_long);
11053 rem_anchor_token(T_int);
11054 rem_anchor_token(T_inline);
11055 rem_anchor_token(T_if);
11056 rem_anchor_token(T_goto);
11057 rem_anchor_token(T_for);
11058 rem_anchor_token(T_float);
11059 rem_anchor_token(T_false);
11060 rem_anchor_token(T_extern);
11061 rem_anchor_token(T_enum);
11062 rem_anchor_token(T_dynamic_cast);
11063 rem_anchor_token(T_do);
11064 rem_anchor_token(T_double);
11065 rem_anchor_token(T_delete);
11066 rem_anchor_token(T_default);
11067 rem_anchor_token(T_continue);
11068 rem_anchor_token(T_const_cast);
11069 rem_anchor_token(T_const);
11070 rem_anchor_token(T_class);
11071 rem_anchor_token(T_char);
11072 rem_anchor_token(T_case);
11073 rem_anchor_token(T_break);
11074 rem_anchor_token(T_bool);
11075 rem_anchor_token(T_auto);
11076 rem_anchor_token(T_asm);
11077 rem_anchor_token(T___thread);
11078 rem_anchor_token(T___real__);
11079 rem_anchor_token(T___label__);
11080 rem_anchor_token(T___imag__);
11081 rem_anchor_token(T___func__);
11082 rem_anchor_token(T___extension__);
11083 rem_anchor_token(T___builtin_va_start);
11084 rem_anchor_token(T___attribute__);
11085 rem_anchor_token(T___alignof__);
11086 rem_anchor_token(T___PRETTY_FUNCTION__);
11087 rem_anchor_token(T___FUNCTION__);
11088 rem_anchor_token(T__Imaginary);
11089 rem_anchor_token(T__Complex);
11090 rem_anchor_token(T__Bool);
11091 rem_anchor_token(T_WIDE_STRING_LITERAL);
11092 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
11093 rem_anchor_token(T_STRING_LITERAL);
11094 rem_anchor_token(T_PLUSPLUS);
11095 rem_anchor_token(T_MINUSMINUS);
11096 rem_anchor_token(T_INTEGER);
11097 rem_anchor_token(T_IDENTIFIER);
11098 rem_anchor_token(T_FLOATINGPOINT);
11099 rem_anchor_token(T_COLONCOLON);
11100 rem_anchor_token(T_CHARACTER_CONSTANT);
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 rem_anchor_token('&');
11108 rem_anchor_token('!');
11109 rem_anchor_token('}');
11110 assert(current_scope == &statement->compound.scope);
11111 scope_pop(old_scope);
11112 environment_pop_to(top);
11119 * Check for unused global static functions and variables
11121 static void check_unused_globals(void)
11123 if (!warning.unused_function && !warning.unused_variable)
11126 for (const entity_t *entity = file_scope->entities; entity != NULL;
11127 entity = entity->base.next) {
11128 if (!is_declaration(entity))
11131 const declaration_t *declaration = &entity->declaration;
11132 if (declaration->used ||
11133 declaration->modifiers & DM_UNUSED ||
11134 declaration->modifiers & DM_USED ||
11135 declaration->storage_class != STORAGE_CLASS_STATIC)
11138 type_t *const type = declaration->type;
11140 if (entity->kind == ENTITY_FUNCTION) {
11141 /* inhibit warning for static inline functions */
11142 if (entity->function.is_inline)
11145 s = entity->function.statement != NULL ? "defined" : "declared";
11150 warningf(&declaration->base.source_position, "'%#T' %s but not used",
11151 type, declaration->base.symbol, s);
11155 static void parse_global_asm(void)
11157 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
11160 expect('(', end_error);
11162 statement->asms.asm_text = parse_string_literals();
11163 statement->base.next = unit->global_asm;
11164 unit->global_asm = statement;
11166 expect(')', end_error);
11167 expect(';', end_error);
11172 static void parse_linkage_specification(void)
11175 assert(token.type == T_STRING_LITERAL);
11177 const char *linkage = parse_string_literals().begin;
11179 linkage_kind_t old_linkage = current_linkage;
11180 linkage_kind_t new_linkage;
11181 if (strcmp(linkage, "C") == 0) {
11182 new_linkage = LINKAGE_C;
11183 } else if (strcmp(linkage, "C++") == 0) {
11184 new_linkage = LINKAGE_CXX;
11186 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
11187 new_linkage = LINKAGE_INVALID;
11189 current_linkage = new_linkage;
11191 if (token.type == '{') {
11194 expect('}', end_error);
11200 assert(current_linkage == new_linkage);
11201 current_linkage = old_linkage;
11204 static void parse_external(void)
11206 switch (token.type) {
11207 DECLARATION_START_NO_EXTERN
11209 case T___extension__:
11210 /* tokens below are for implicit int */
11211 case '&': /* & x; -> int& x; (and error later, because C++ has no
11213 case '*': /* * x; -> int* x; */
11214 case '(': /* (x); -> int (x); */
11215 parse_external_declaration();
11219 if (look_ahead(1)->type == T_STRING_LITERAL) {
11220 parse_linkage_specification();
11222 parse_external_declaration();
11227 parse_global_asm();
11231 parse_namespace_definition();
11235 if (!strict_mode) {
11237 warningf(HERE, "stray ';' outside of function");
11244 errorf(HERE, "stray %K outside of function", &token);
11245 if (token.type == '(' || token.type == '{' || token.type == '[')
11246 eat_until_matching_token(token.type);
11252 static void parse_externals(void)
11254 add_anchor_token('}');
11255 add_anchor_token(T_EOF);
11258 unsigned char token_anchor_copy[T_LAST_TOKEN];
11259 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
11262 while (token.type != T_EOF && token.type != '}') {
11264 bool anchor_leak = false;
11265 for (int i = 0; i != T_LAST_TOKEN; ++i) {
11266 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
11268 errorf(HERE, "Leaked anchor token %k %d times", i, count);
11269 anchor_leak = true;
11272 if (in_gcc_extension) {
11273 errorf(HERE, "Leaked __extension__");
11274 anchor_leak = true;
11284 rem_anchor_token(T_EOF);
11285 rem_anchor_token('}');
11289 * Parse a translation unit.
11291 static void parse_translation_unit(void)
11293 add_anchor_token(T_EOF);
11298 if (token.type == T_EOF)
11301 errorf(HERE, "stray %K outside of function", &token);
11302 if (token.type == '(' || token.type == '{' || token.type == '[')
11303 eat_until_matching_token(token.type);
11311 * @return the translation unit or NULL if errors occurred.
11313 void start_parsing(void)
11315 environment_stack = NEW_ARR_F(stack_entry_t, 0);
11316 label_stack = NEW_ARR_F(stack_entry_t, 0);
11317 diagnostic_count = 0;
11321 type_set_output(stderr);
11322 ast_set_output(stderr);
11324 assert(unit == NULL);
11325 unit = allocate_ast_zero(sizeof(unit[0]));
11327 assert(file_scope == NULL);
11328 file_scope = &unit->scope;
11330 assert(current_scope == NULL);
11331 scope_push(&unit->scope);
11334 translation_unit_t *finish_parsing(void)
11336 assert(current_scope == &unit->scope);
11339 assert(file_scope == &unit->scope);
11340 check_unused_globals();
11343 DEL_ARR_F(environment_stack);
11344 DEL_ARR_F(label_stack);
11346 translation_unit_t *result = unit;
11351 /* GCC allows global arrays without size and assigns them a length of one,
11352 * if no different declaration follows */
11353 static void complete_incomplete_arrays(void)
11355 size_t n = ARR_LEN(incomplete_arrays);
11356 for (size_t i = 0; i != n; ++i) {
11357 declaration_t *const decl = incomplete_arrays[i];
11358 type_t *const orig_type = decl->type;
11359 type_t *const type = skip_typeref(orig_type);
11361 if (!is_type_incomplete(type))
11364 if (warning.other) {
11365 warningf(&decl->base.source_position,
11366 "array '%#T' assumed to have one element",
11367 orig_type, decl->base.symbol);
11370 type_t *const new_type = duplicate_type(type);
11371 new_type->array.size_constant = true;
11372 new_type->array.has_implicit_size = true;
11373 new_type->array.size = 1;
11375 type_t *const result = typehash_insert(new_type);
11376 if (type != result)
11379 decl->type = result;
11385 lookahead_bufpos = 0;
11386 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
11389 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
11390 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
11391 parse_translation_unit();
11392 complete_incomplete_arrays();
11393 DEL_ARR_F(incomplete_arrays);
11394 incomplete_arrays = NULL;
11398 * Initialize the parser.
11400 void init_parser(void)
11402 sym_anonymous = symbol_table_insert("<anonymous>");
11404 if (c_mode & _MS) {
11405 /* add predefined symbols for extended-decl-modifier */
11406 sym_align = symbol_table_insert("align");
11407 sym_allocate = symbol_table_insert("allocate");
11408 sym_dllimport = symbol_table_insert("dllimport");
11409 sym_dllexport = symbol_table_insert("dllexport");
11410 sym_naked = symbol_table_insert("naked");
11411 sym_noinline = symbol_table_insert("noinline");
11412 sym_returns_twice = symbol_table_insert("returns_twice");
11413 sym_noreturn = symbol_table_insert("noreturn");
11414 sym_nothrow = symbol_table_insert("nothrow");
11415 sym_novtable = symbol_table_insert("novtable");
11416 sym_property = symbol_table_insert("property");
11417 sym_get = symbol_table_insert("get");
11418 sym_put = symbol_table_insert("put");
11419 sym_selectany = symbol_table_insert("selectany");
11420 sym_thread = symbol_table_insert("thread");
11421 sym_uuid = symbol_table_insert("uuid");
11422 sym_deprecated = symbol_table_insert("deprecated");
11423 sym_restrict = symbol_table_insert("restrict");
11424 sym_noalias = symbol_table_insert("noalias");
11426 memset(token_anchor_set, 0, sizeof(token_anchor_set));
11428 init_expression_parsers();
11429 obstack_init(&temp_obst);
11431 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11432 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11436 * Terminate the parser.
11438 void exit_parser(void)
11440 obstack_free(&temp_obst, NULL);