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_noreturn = NULL;
160 static const symbol_t *sym_nothrow = NULL;
161 static const symbol_t *sym_novtable = NULL;
162 static const symbol_t *sym_property = NULL;
163 static const symbol_t *sym_get = NULL;
164 static const symbol_t *sym_put = NULL;
165 static const symbol_t *sym_selectany = NULL;
166 static const symbol_t *sym_thread = NULL;
167 static const symbol_t *sym_uuid = NULL;
168 static const symbol_t *sym_deprecated = NULL;
169 static const symbol_t *sym_restrict = NULL;
170 static const symbol_t *sym_noalias = NULL;
172 /** The token anchor set */
173 static unsigned char token_anchor_set[T_LAST_TOKEN];
175 /** The current source position. */
176 #define HERE (&token.source_position)
178 /** true if we are in GCC mode. */
179 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
181 static type_t *type_valist;
183 static statement_t *parse_compound_statement(bool inside_expression_statement);
184 static statement_t *parse_statement(void);
186 static expression_t *parse_sub_expression(precedence_t);
187 static expression_t *parse_expression(void);
188 static type_t *parse_typename(void);
189 static void parse_externals(void);
190 static void parse_external(void);
192 static void parse_compound_type_entries(compound_t *compound_declaration);
194 typedef enum declarator_flags_t {
196 DECL_MAY_BE_ABSTRACT = 1U << 0,
197 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
198 DECL_IS_PARAMETER = 1U << 2
199 } declarator_flags_t;
201 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
202 declarator_flags_t flags);
204 static entity_t *record_entity(entity_t *entity, bool is_definition);
206 static void semantic_comparison(binary_expression_t *expression);
208 #define STORAGE_CLASSES \
209 STORAGE_CLASSES_NO_EXTERN \
212 #define STORAGE_CLASSES_NO_EXTERN \
219 #define TYPE_QUALIFIERS \
224 case T__forceinline: \
225 case T___attribute__:
227 #define COMPLEX_SPECIFIERS \
229 #define IMAGINARY_SPECIFIERS \
232 #define TYPE_SPECIFIERS \
234 case T___builtin_va_list: \
254 #define DECLARATION_START \
259 #define DECLARATION_START_NO_EXTERN \
260 STORAGE_CLASSES_NO_EXTERN \
264 #define TYPENAME_START \
268 #define EXPRESSION_START \
277 case T_CHARACTER_CONSTANT: \
278 case T_FLOATINGPOINT: \
282 case T_STRING_LITERAL: \
283 case T_WIDE_CHARACTER_CONSTANT: \
284 case T_WIDE_STRING_LITERAL: \
285 case T___FUNCDNAME__: \
286 case T___FUNCSIG__: \
287 case T___FUNCTION__: \
288 case T___PRETTY_FUNCTION__: \
289 case T___alignof__: \
290 case T___builtin_alloca: \
291 case T___builtin_classify_type: \
292 case T___builtin_constant_p: \
293 case T___builtin_expect: \
294 case T___builtin_huge_val: \
295 case T___builtin_inf: \
296 case T___builtin_inff: \
297 case T___builtin_infl: \
298 case T___builtin_isgreater: \
299 case T___builtin_isgreaterequal: \
300 case T___builtin_isless: \
301 case T___builtin_islessequal: \
302 case T___builtin_islessgreater: \
303 case T___builtin_isunordered: \
304 case T___builtin_nan: \
305 case T___builtin_nanf: \
306 case T___builtin_nanl: \
307 case T___builtin_offsetof: \
308 case T___builtin_prefetch: \
309 case T___builtin_va_arg: \
310 case T___builtin_va_end: \
311 case T___builtin_va_start: \
322 * Allocate an AST node with given size and
323 * initialize all fields with zero.
325 static void *allocate_ast_zero(size_t size)
327 void *res = allocate_ast(size);
328 memset(res, 0, size);
333 * Returns the size of an entity node.
335 * @param kind the entity kind
337 static size_t get_entity_struct_size(entity_kind_t kind)
339 static const size_t sizes[] = {
340 [ENTITY_VARIABLE] = sizeof(variable_t),
341 [ENTITY_PARAMETER] = sizeof(parameter_t),
342 [ENTITY_COMPOUND_MEMBER] = sizeof(compound_member_t),
343 [ENTITY_FUNCTION] = sizeof(function_t),
344 [ENTITY_TYPEDEF] = sizeof(typedef_t),
345 [ENTITY_STRUCT] = sizeof(compound_t),
346 [ENTITY_UNION] = sizeof(compound_t),
347 [ENTITY_ENUM] = sizeof(enum_t),
348 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
349 [ENTITY_LABEL] = sizeof(label_t),
350 [ENTITY_LOCAL_LABEL] = sizeof(label_t),
351 [ENTITY_NAMESPACE] = sizeof(namespace_t)
353 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
354 assert(sizes[kind] != 0);
359 * Allocate an entity of given kind and initialize all
362 static entity_t *allocate_entity_zero(entity_kind_t kind)
364 size_t size = get_entity_struct_size(kind);
365 entity_t *entity = allocate_ast_zero(size);
371 * Returns the size of a statement node.
373 * @param kind the statement kind
375 static size_t get_statement_struct_size(statement_kind_t kind)
377 static const size_t sizes[] = {
378 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
379 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
380 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
381 [STATEMENT_RETURN] = sizeof(return_statement_t),
382 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
383 [STATEMENT_LOCAL_LABEL] = sizeof(local_label_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_NORETURN] = "noreturn",
1245 [GNU_AK_NAKED] = "naked",
1246 [GNU_AK_PURE] = "pure",
1247 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1248 [GNU_AK_MALLOC] = "malloc",
1249 [GNU_AK_WEAK] = "weak",
1250 [GNU_AK_CONSTRUCTOR] = "constructor",
1251 [GNU_AK_DESTRUCTOR] = "destructor",
1252 [GNU_AK_NOTHROW] = "nothrow",
1253 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1254 [GNU_AK_COMMON] = "common",
1255 [GNU_AK_NOCOMMON] = "nocommon",
1256 [GNU_AK_PACKED] = "packed",
1257 [GNU_AK_SHARED] = "shared",
1258 [GNU_AK_NOTSHARED] = "notshared",
1259 [GNU_AK_USED] = "used",
1260 [GNU_AK_UNUSED] = "unused",
1261 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1262 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1263 [GNU_AK_LONGCALL] = "longcall",
1264 [GNU_AK_SHORTCALL] = "shortcall",
1265 [GNU_AK_LONG_CALL] = "long_call",
1266 [GNU_AK_SHORT_CALL] = "short_call",
1267 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1268 [GNU_AK_INTERRUPT] = "interrupt",
1269 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1270 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1271 [GNU_AK_NESTING] = "nesting",
1272 [GNU_AK_NEAR] = "near",
1273 [GNU_AK_FAR] = "far",
1274 [GNU_AK_SIGNAL] = "signal",
1275 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1276 [GNU_AK_TINY_DATA] = "tiny_data",
1277 [GNU_AK_SAVEALL] = "saveall",
1278 [GNU_AK_FLATTEN] = "flatten",
1279 [GNU_AK_SSEREGPARM] = "sseregparm",
1280 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1281 [GNU_AK_RETURN_TWICE] = "return_twice",
1282 [GNU_AK_MAY_ALIAS] = "may_alias",
1283 [GNU_AK_MS_STRUCT] = "ms_struct",
1284 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1285 [GNU_AK_DLLIMPORT] = "dllimport",
1286 [GNU_AK_DLLEXPORT] = "dllexport",
1287 [GNU_AK_ALIGNED] = "aligned",
1288 [GNU_AK_ALIAS] = "alias",
1289 [GNU_AK_SECTION] = "section",
1290 [GNU_AK_FORMAT] = "format",
1291 [GNU_AK_FORMAT_ARG] = "format_arg",
1292 [GNU_AK_WEAKREF] = "weakref",
1293 [GNU_AK_NONNULL] = "nonnull",
1294 [GNU_AK_TLS_MODEL] = "tls_model",
1295 [GNU_AK_VISIBILITY] = "visibility",
1296 [GNU_AK_REGPARM] = "regparm",
1297 [GNU_AK_MODE] = "mode",
1298 [GNU_AK_MODEL] = "model",
1299 [GNU_AK_TRAP_EXIT] = "trap_exit",
1300 [GNU_AK_SP_SWITCH] = "sp_switch",
1301 [GNU_AK_SENTINEL] = "sentinel"
1305 * compare two string, ignoring double underscores on the second.
1307 static int strcmp_underscore(const char *s1, const char *s2)
1309 if (s2[0] == '_' && s2[1] == '_') {
1310 size_t len2 = strlen(s2);
1311 size_t len1 = strlen(s1);
1312 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1313 return strncmp(s1, s2+2, len2-4);
1317 return strcmp(s1, s2);
1321 * Allocate a new gnu temporal attribute of given kind.
1323 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1325 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1326 attribute->kind = kind;
1327 attribute->next = NULL;
1328 attribute->invalid = false;
1329 attribute->have_arguments = false;
1335 * Parse one constant expression argument of the given attribute.
1337 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1339 expression_t *expression;
1340 add_anchor_token(')');
1341 expression = parse_constant_expression();
1342 rem_anchor_token(')');
1343 expect(')', end_error);
1344 attribute->u.argument = fold_constant(expression);
1347 attribute->invalid = true;
1351 * Parse a list of constant expressions arguments of the given attribute.
1353 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1355 argument_list_t **list = &attribute->u.arguments;
1356 argument_list_t *entry;
1357 expression_t *expression;
1358 add_anchor_token(')');
1359 add_anchor_token(',');
1361 expression = parse_constant_expression();
1362 entry = obstack_alloc(&temp_obst, sizeof(entry));
1363 entry->argument = fold_constant(expression);
1366 list = &entry->next;
1367 if (token.type != ',')
1371 rem_anchor_token(',');
1372 rem_anchor_token(')');
1373 expect(')', end_error);
1376 attribute->invalid = true;
1380 * Parse one string literal argument of the given attribute.
1382 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1385 add_anchor_token('(');
1386 if (token.type != T_STRING_LITERAL) {
1387 parse_error_expected("while parsing attribute directive",
1388 T_STRING_LITERAL, NULL);
1391 *string = parse_string_literals();
1392 rem_anchor_token('(');
1393 expect(')', end_error);
1396 attribute->invalid = true;
1400 * Parse one tls model of the given attribute.
1402 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1404 static const char *const tls_models[] = {
1410 string_t string = { NULL, 0 };
1411 parse_gnu_attribute_string_arg(attribute, &string);
1412 if (string.begin != NULL) {
1413 for (size_t i = 0; i < 4; ++i) {
1414 if (strcmp(tls_models[i], string.begin) == 0) {
1415 attribute->u.value = i;
1419 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1421 attribute->invalid = true;
1425 * Parse one tls model of the given attribute.
1427 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1429 static const char *const visibilities[] = {
1435 string_t string = { NULL, 0 };
1436 parse_gnu_attribute_string_arg(attribute, &string);
1437 if (string.begin != NULL) {
1438 for (size_t i = 0; i < 4; ++i) {
1439 if (strcmp(visibilities[i], string.begin) == 0) {
1440 attribute->u.value = i;
1444 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1446 attribute->invalid = true;
1450 * Parse one (code) model of the given attribute.
1452 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1454 static const char *const visibilities[] = {
1459 string_t string = { NULL, 0 };
1460 parse_gnu_attribute_string_arg(attribute, &string);
1461 if (string.begin != NULL) {
1462 for (int i = 0; i < 3; ++i) {
1463 if (strcmp(visibilities[i], string.begin) == 0) {
1464 attribute->u.value = i;
1468 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1470 attribute->invalid = true;
1474 * Parse one mode of the given attribute.
1476 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1478 /* TODO: find out what is allowed here... */
1480 /* at least: byte, word, pointer, list of machine modes
1481 * __XXX___ is interpreted as XXX */
1482 add_anchor_token(')');
1484 if (token.type != T_IDENTIFIER) {
1485 expect(T_IDENTIFIER, end_error);
1488 /* This isn't really correct, the backend should provide a list of machine
1489 * specific modes (according to gcc philosophy that is...) */
1490 const char *symbol_str = token.v.symbol->string;
1491 if (strcmp_underscore("QI", symbol_str) == 0 ||
1492 strcmp_underscore("byte", symbol_str) == 0) {
1493 attribute->u.akind = ATOMIC_TYPE_CHAR;
1494 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1495 attribute->u.akind = ATOMIC_TYPE_SHORT;
1496 } else if (strcmp_underscore("SI", symbol_str) == 0
1497 || strcmp_underscore("word", symbol_str) == 0
1498 || strcmp_underscore("pointer", symbol_str) == 0) {
1499 attribute->u.akind = ATOMIC_TYPE_INT;
1500 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1501 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1504 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1505 attribute->invalid = true;
1509 rem_anchor_token(')');
1510 expect(')', end_error);
1513 attribute->invalid = true;
1517 * Parse one interrupt argument of the given attribute.
1519 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1521 static const char *const interrupts[] = {
1528 string_t string = { NULL, 0 };
1529 parse_gnu_attribute_string_arg(attribute, &string);
1530 if (string.begin != NULL) {
1531 for (size_t i = 0; i < 5; ++i) {
1532 if (strcmp(interrupts[i], string.begin) == 0) {
1533 attribute->u.value = i;
1537 errorf(HERE, "'%s' is not an interrupt", string.begin);
1539 attribute->invalid = true;
1543 * Parse ( identifier, const expression, const expression )
1545 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1547 static const char *const format_names[] = {
1555 if (token.type != T_IDENTIFIER) {
1556 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1559 const char *name = token.v.symbol->string;
1560 for (i = 0; i < 4; ++i) {
1561 if (strcmp_underscore(format_names[i], name) == 0)
1565 if (warning.attribute)
1566 warningf(HERE, "'%s' is an unrecognized format function type", name);
1570 expect(',', end_error);
1571 add_anchor_token(')');
1572 add_anchor_token(',');
1573 parse_constant_expression();
1574 rem_anchor_token(',');
1575 rem_anchor_token(')');
1577 expect(',', end_error);
1578 add_anchor_token(')');
1579 parse_constant_expression();
1580 rem_anchor_token(')');
1581 expect(')', end_error);
1584 attribute->u.value = true;
1588 * Check that a given GNU attribute has no arguments.
1590 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1592 if (!attribute->have_arguments)
1595 /* should have no arguments */
1596 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1597 eat_until_matching_token('(');
1598 /* we have already consumed '(', so we stop before ')', eat it */
1600 attribute->invalid = true;
1604 * Parse one GNU attribute.
1606 * Note that attribute names can be specified WITH or WITHOUT
1607 * double underscores, ie const or __const__.
1609 * The following attributes are parsed without arguments
1634 * no_instrument_function
1635 * warn_unused_result
1652 * externally_visible
1660 * The following attributes are parsed with arguments
1661 * aligned( const expression )
1662 * alias( string literal )
1663 * section( string literal )
1664 * format( identifier, const expression, const expression )
1665 * format_arg( const expression )
1666 * tls_model( string literal )
1667 * visibility( string literal )
1668 * regparm( const expression )
1669 * model( string leteral )
1670 * trap_exit( const expression )
1671 * sp_switch( string literal )
1673 * The following attributes might have arguments
1674 * weak_ref( string literal )
1675 * non_null( const expression // ',' )
1676 * interrupt( string literal )
1677 * sentinel( constant expression )
1679 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1681 gnu_attribute_t *head = *attributes;
1682 gnu_attribute_t *last = *attributes;
1683 decl_modifiers_t modifiers = 0;
1684 gnu_attribute_t *attribute;
1686 eat(T___attribute__);
1687 expect('(', end_error);
1688 expect('(', end_error);
1690 if (token.type != ')') {
1691 /* find the end of the list */
1693 while (last->next != NULL)
1697 /* non-empty attribute list */
1700 if (token.type == T_const) {
1702 } else if (token.type == T_volatile) {
1704 } else if (token.type == T_cdecl) {
1705 /* __attribute__((cdecl)), WITH ms mode */
1707 } else if (token.type == T_IDENTIFIER) {
1708 const symbol_t *sym = token.v.symbol;
1711 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1718 for (i = 0; i < GNU_AK_LAST; ++i) {
1719 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1722 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1725 if (kind == GNU_AK_LAST) {
1726 if (warning.attribute)
1727 warningf(HERE, "'%s' attribute directive ignored", name);
1729 /* skip possible arguments */
1730 if (token.type == '(') {
1731 eat_until_matching_token(')');
1734 /* check for arguments */
1735 attribute = allocate_gnu_attribute(kind);
1736 if (token.type == '(') {
1738 if (token.type == ')') {
1739 /* empty args are allowed */
1742 attribute->have_arguments = true;
1746 case GNU_AK_VOLATILE:
1751 case GNU_AK_NOCOMMON:
1753 case GNU_AK_NOTSHARED:
1754 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1755 case GNU_AK_WARN_UNUSED_RESULT:
1756 case GNU_AK_LONGCALL:
1757 case GNU_AK_SHORTCALL:
1758 case GNU_AK_LONG_CALL:
1759 case GNU_AK_SHORT_CALL:
1760 case GNU_AK_FUNCTION_VECTOR:
1761 case GNU_AK_INTERRUPT_HANDLER:
1762 case GNU_AK_NMI_HANDLER:
1763 case GNU_AK_NESTING:
1767 case GNU_AK_EIGTHBIT_DATA:
1768 case GNU_AK_TINY_DATA:
1769 case GNU_AK_SAVEALL:
1770 case GNU_AK_FLATTEN:
1771 case GNU_AK_SSEREGPARM:
1772 case GNU_AK_EXTERNALLY_VISIBLE:
1773 case GNU_AK_RETURN_TWICE:
1774 case GNU_AK_MAY_ALIAS:
1775 case GNU_AK_MS_STRUCT:
1776 case GNU_AK_GCC_STRUCT:
1779 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1780 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1781 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1782 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1783 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1784 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1785 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1786 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1787 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1788 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1789 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1790 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1791 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1792 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1793 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1794 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1795 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1796 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1798 case GNU_AK_ALIGNED:
1799 /* __align__ may be used without an argument */
1800 if (attribute->have_arguments) {
1801 parse_gnu_attribute_const_arg(attribute);
1805 case GNU_AK_FORMAT_ARG:
1806 case GNU_AK_REGPARM:
1807 case GNU_AK_TRAP_EXIT:
1808 if (!attribute->have_arguments) {
1809 /* should have arguments */
1810 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1811 attribute->invalid = true;
1813 parse_gnu_attribute_const_arg(attribute);
1816 case GNU_AK_SECTION:
1817 case GNU_AK_SP_SWITCH:
1818 if (!attribute->have_arguments) {
1819 /* should have arguments */
1820 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1821 attribute->invalid = true;
1823 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1826 if (!attribute->have_arguments) {
1827 /* should have arguments */
1828 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1829 attribute->invalid = true;
1831 parse_gnu_attribute_format_args(attribute);
1833 case GNU_AK_WEAKREF:
1834 /* may have one string argument */
1835 if (attribute->have_arguments)
1836 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1838 case GNU_AK_NONNULL:
1839 if (attribute->have_arguments)
1840 parse_gnu_attribute_const_arg_list(attribute);
1842 case GNU_AK_TLS_MODEL:
1843 if (!attribute->have_arguments) {
1844 /* should have arguments */
1845 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1847 parse_gnu_attribute_tls_model_arg(attribute);
1849 case GNU_AK_VISIBILITY:
1850 if (!attribute->have_arguments) {
1851 /* should have arguments */
1852 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1854 parse_gnu_attribute_visibility_arg(attribute);
1857 if (!attribute->have_arguments) {
1858 /* should have arguments */
1859 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1861 parse_gnu_attribute_model_arg(attribute);
1865 if (!attribute->have_arguments) {
1866 /* should have arguments */
1867 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1869 parse_gnu_attribute_mode_arg(attribute);
1872 case GNU_AK_INTERRUPT:
1873 /* may have one string argument */
1874 if (attribute->have_arguments)
1875 parse_gnu_attribute_interrupt_arg(attribute);
1877 case GNU_AK_SENTINEL:
1878 /* may have one string argument */
1879 if (attribute->have_arguments)
1880 parse_gnu_attribute_const_arg(attribute);
1883 /* already handled */
1887 check_no_argument(attribute, name);
1890 if (attribute != NULL) {
1892 last->next = attribute;
1895 head = last = attribute;
1899 if (token.type != ',')
1904 expect(')', end_error);
1905 expect(')', end_error);
1913 * Parse GNU attributes.
1915 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1917 decl_modifiers_t modifiers = 0;
1920 switch (token.type) {
1921 case T___attribute__:
1922 modifiers |= parse_gnu_attribute(attributes);
1927 expect('(', end_error);
1928 if (token.type != T_STRING_LITERAL) {
1929 parse_error_expected("while parsing assembler attribute",
1930 T_STRING_LITERAL, NULL);
1931 eat_until_matching_token('(');
1934 parse_string_literals();
1936 expect(')', end_error);
1939 case T_cdecl: modifiers |= DM_CDECL; break;
1940 case T__fastcall: modifiers |= DM_FASTCALL; break;
1941 case T__stdcall: modifiers |= DM_STDCALL; break;
1944 /* TODO record modifier */
1946 warningf(HERE, "Ignoring declaration modifier %K", &token);
1950 default: return modifiers;
1957 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1959 static entity_t *determine_lhs_ent(expression_t *const expr,
1962 switch (expr->kind) {
1963 case EXPR_REFERENCE: {
1964 entity_t *const entity = expr->reference.entity;
1965 /* we should only find variables as lvalues... */
1966 if (entity->base.kind != ENTITY_VARIABLE
1967 && entity->base.kind != ENTITY_PARAMETER)
1973 case EXPR_ARRAY_ACCESS: {
1974 expression_t *const ref = expr->array_access.array_ref;
1975 entity_t * ent = NULL;
1976 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1977 ent = determine_lhs_ent(ref, lhs_ent);
1980 mark_vars_read(expr->select.compound, lhs_ent);
1982 mark_vars_read(expr->array_access.index, lhs_ent);
1987 if (is_type_compound(skip_typeref(expr->base.type))) {
1988 return determine_lhs_ent(expr->select.compound, lhs_ent);
1990 mark_vars_read(expr->select.compound, lhs_ent);
1995 case EXPR_UNARY_DEREFERENCE: {
1996 expression_t *const val = expr->unary.value;
1997 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1999 return determine_lhs_ent(val->unary.value, lhs_ent);
2001 mark_vars_read(val, NULL);
2007 mark_vars_read(expr, NULL);
2012 #define ENT_ANY ((entity_t*)-1)
2015 * Mark declarations, which are read. This is used to detect variables, which
2019 * x is not marked as "read", because it is only read to calculate its own new
2023 * x and y are not detected as "not read", because multiple variables are
2026 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
2028 switch (expr->kind) {
2029 case EXPR_REFERENCE: {
2030 entity_t *const entity = expr->reference.entity;
2031 if (entity->kind != ENTITY_VARIABLE
2032 && entity->kind != ENTITY_PARAMETER)
2035 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
2036 if (entity->kind == ENTITY_VARIABLE) {
2037 entity->variable.read = true;
2039 entity->parameter.read = true;
2046 // TODO respect pure/const
2047 mark_vars_read(expr->call.function, NULL);
2048 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
2049 mark_vars_read(arg->expression, NULL);
2053 case EXPR_CONDITIONAL:
2054 // TODO lhs_decl should depend on whether true/false have an effect
2055 mark_vars_read(expr->conditional.condition, NULL);
2056 if (expr->conditional.true_expression != NULL)
2057 mark_vars_read(expr->conditional.true_expression, lhs_ent);
2058 mark_vars_read(expr->conditional.false_expression, lhs_ent);
2062 if (lhs_ent == ENT_ANY
2063 && !is_type_compound(skip_typeref(expr->base.type)))
2065 mark_vars_read(expr->select.compound, lhs_ent);
2068 case EXPR_ARRAY_ACCESS: {
2069 expression_t *const ref = expr->array_access.array_ref;
2070 mark_vars_read(ref, lhs_ent);
2071 lhs_ent = determine_lhs_ent(ref, lhs_ent);
2072 mark_vars_read(expr->array_access.index, lhs_ent);
2077 mark_vars_read(expr->va_arge.ap, lhs_ent);
2080 case EXPR_UNARY_CAST:
2081 /* Special case: Use void cast to mark a variable as "read" */
2082 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2087 case EXPR_UNARY_THROW:
2088 if (expr->unary.value == NULL)
2091 case EXPR_UNARY_DEREFERENCE:
2092 case EXPR_UNARY_DELETE:
2093 case EXPR_UNARY_DELETE_ARRAY:
2094 if (lhs_ent == ENT_ANY)
2098 case EXPR_UNARY_NEGATE:
2099 case EXPR_UNARY_PLUS:
2100 case EXPR_UNARY_BITWISE_NEGATE:
2101 case EXPR_UNARY_NOT:
2102 case EXPR_UNARY_TAKE_ADDRESS:
2103 case EXPR_UNARY_POSTFIX_INCREMENT:
2104 case EXPR_UNARY_POSTFIX_DECREMENT:
2105 case EXPR_UNARY_PREFIX_INCREMENT:
2106 case EXPR_UNARY_PREFIX_DECREMENT:
2107 case EXPR_UNARY_CAST_IMPLICIT:
2108 case EXPR_UNARY_ASSUME:
2110 mark_vars_read(expr->unary.value, lhs_ent);
2113 case EXPR_BINARY_ADD:
2114 case EXPR_BINARY_SUB:
2115 case EXPR_BINARY_MUL:
2116 case EXPR_BINARY_DIV:
2117 case EXPR_BINARY_MOD:
2118 case EXPR_BINARY_EQUAL:
2119 case EXPR_BINARY_NOTEQUAL:
2120 case EXPR_BINARY_LESS:
2121 case EXPR_BINARY_LESSEQUAL:
2122 case EXPR_BINARY_GREATER:
2123 case EXPR_BINARY_GREATEREQUAL:
2124 case EXPR_BINARY_BITWISE_AND:
2125 case EXPR_BINARY_BITWISE_OR:
2126 case EXPR_BINARY_BITWISE_XOR:
2127 case EXPR_BINARY_LOGICAL_AND:
2128 case EXPR_BINARY_LOGICAL_OR:
2129 case EXPR_BINARY_SHIFTLEFT:
2130 case EXPR_BINARY_SHIFTRIGHT:
2131 case EXPR_BINARY_COMMA:
2132 case EXPR_BINARY_ISGREATER:
2133 case EXPR_BINARY_ISGREATEREQUAL:
2134 case EXPR_BINARY_ISLESS:
2135 case EXPR_BINARY_ISLESSEQUAL:
2136 case EXPR_BINARY_ISLESSGREATER:
2137 case EXPR_BINARY_ISUNORDERED:
2138 mark_vars_read(expr->binary.left, lhs_ent);
2139 mark_vars_read(expr->binary.right, lhs_ent);
2142 case EXPR_BINARY_ASSIGN:
2143 case EXPR_BINARY_MUL_ASSIGN:
2144 case EXPR_BINARY_DIV_ASSIGN:
2145 case EXPR_BINARY_MOD_ASSIGN:
2146 case EXPR_BINARY_ADD_ASSIGN:
2147 case EXPR_BINARY_SUB_ASSIGN:
2148 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2149 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2150 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2151 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2152 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2153 if (lhs_ent == ENT_ANY)
2155 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
2156 mark_vars_read(expr->binary.right, lhs_ent);
2161 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
2167 case EXPR_CHARACTER_CONSTANT:
2168 case EXPR_WIDE_CHARACTER_CONSTANT:
2169 case EXPR_STRING_LITERAL:
2170 case EXPR_WIDE_STRING_LITERAL:
2171 case EXPR_COMPOUND_LITERAL: // TODO init?
2173 case EXPR_CLASSIFY_TYPE:
2176 case EXPR_BUILTIN_SYMBOL:
2177 case EXPR_BUILTIN_CONSTANT_P:
2178 case EXPR_BUILTIN_PREFETCH:
2180 case EXPR_STATEMENT: // TODO
2181 case EXPR_LABEL_ADDRESS:
2182 case EXPR_REFERENCE_ENUM_VALUE:
2186 panic("unhandled expression");
2189 static designator_t *parse_designation(void)
2191 designator_t *result = NULL;
2192 designator_t *last = NULL;
2195 designator_t *designator;
2196 switch (token.type) {
2198 designator = allocate_ast_zero(sizeof(designator[0]));
2199 designator->source_position = token.source_position;
2201 add_anchor_token(']');
2202 designator->array_index = parse_constant_expression();
2203 rem_anchor_token(']');
2204 expect(']', end_error);
2207 designator = allocate_ast_zero(sizeof(designator[0]));
2208 designator->source_position = token.source_position;
2210 if (token.type != T_IDENTIFIER) {
2211 parse_error_expected("while parsing designator",
2212 T_IDENTIFIER, NULL);
2215 designator->symbol = token.v.symbol;
2219 expect('=', end_error);
2223 assert(designator != NULL);
2225 last->next = designator;
2227 result = designator;
2235 static initializer_t *initializer_from_string(array_type_t *type,
2236 const string_t *const string)
2238 /* TODO: check len vs. size of array type */
2241 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2242 initializer->string.string = *string;
2247 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2248 wide_string_t *const string)
2250 /* TODO: check len vs. size of array type */
2253 initializer_t *const initializer =
2254 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2255 initializer->wide_string.string = *string;
2261 * Build an initializer from a given expression.
2263 static initializer_t *initializer_from_expression(type_t *orig_type,
2264 expression_t *expression)
2266 /* TODO check that expression is a constant expression */
2268 /* § 6.7.8.14/15 char array may be initialized by string literals */
2269 type_t *type = skip_typeref(orig_type);
2270 type_t *expr_type_orig = expression->base.type;
2271 type_t *expr_type = skip_typeref(expr_type_orig);
2272 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2273 array_type_t *const array_type = &type->array;
2274 type_t *const element_type = skip_typeref(array_type->element_type);
2276 if (element_type->kind == TYPE_ATOMIC) {
2277 atomic_type_kind_t akind = element_type->atomic.akind;
2278 switch (expression->kind) {
2279 case EXPR_STRING_LITERAL:
2280 if (akind == ATOMIC_TYPE_CHAR
2281 || akind == ATOMIC_TYPE_SCHAR
2282 || akind == ATOMIC_TYPE_UCHAR) {
2283 return initializer_from_string(array_type,
2284 &expression->string.value);
2287 case EXPR_WIDE_STRING_LITERAL: {
2288 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2289 if (get_unqualified_type(element_type) == bare_wchar_type) {
2290 return initializer_from_wide_string(array_type,
2291 &expression->wide_string.value);
2301 assign_error_t error = semantic_assign(type, expression);
2302 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2304 report_assign_error(error, type, expression, "initializer",
2305 &expression->base.source_position);
2307 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2309 if (type->kind == TYPE_BITFIELD) {
2310 type = type->bitfield.base_type;
2313 result->value.value = create_implicit_cast(expression, type);
2319 * Checks if a given expression can be used as an constant initializer.
2321 static bool is_initializer_constant(const expression_t *expression)
2323 return is_constant_expression(expression)
2324 || is_address_constant(expression);
2328 * Parses an scalar initializer.
2330 * § 6.7.8.11; eat {} without warning
2332 static initializer_t *parse_scalar_initializer(type_t *type,
2333 bool must_be_constant)
2335 /* there might be extra {} hierarchies */
2337 if (token.type == '{') {
2339 warningf(HERE, "extra curly braces around scalar initializer");
2343 } while (token.type == '{');
2346 expression_t *expression = parse_assignment_expression();
2347 mark_vars_read(expression, NULL);
2348 if (must_be_constant && !is_initializer_constant(expression)) {
2349 errorf(&expression->base.source_position,
2350 "Initialisation expression '%E' is not constant",
2354 initializer_t *initializer = initializer_from_expression(type, expression);
2356 if (initializer == NULL) {
2357 errorf(&expression->base.source_position,
2358 "expression '%E' (type '%T') doesn't match expected type '%T'",
2359 expression, expression->base.type, type);
2364 bool additional_warning_displayed = false;
2365 while (braces > 0) {
2366 if (token.type == ',') {
2369 if (token.type != '}') {
2370 if (!additional_warning_displayed && warning.other) {
2371 warningf(HERE, "additional elements in scalar initializer");
2372 additional_warning_displayed = true;
2383 * An entry in the type path.
2385 typedef struct type_path_entry_t type_path_entry_t;
2386 struct type_path_entry_t {
2387 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2389 size_t index; /**< For array types: the current index. */
2390 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2395 * A type path expression a position inside compound or array types.
2397 typedef struct type_path_t type_path_t;
2398 struct type_path_t {
2399 type_path_entry_t *path; /**< An flexible array containing the current path. */
2400 type_t *top_type; /**< type of the element the path points */
2401 size_t max_index; /**< largest index in outermost array */
2405 * Prints a type path for debugging.
2407 static __attribute__((unused)) void debug_print_type_path(
2408 const type_path_t *path)
2410 size_t len = ARR_LEN(path->path);
2412 for (size_t i = 0; i < len; ++i) {
2413 const type_path_entry_t *entry = & path->path[i];
2415 type_t *type = skip_typeref(entry->type);
2416 if (is_type_compound(type)) {
2417 /* in gcc mode structs can have no members */
2418 if (entry->v.compound_entry == NULL) {
2422 fprintf(stderr, ".%s",
2423 entry->v.compound_entry->base.symbol->string);
2424 } else if (is_type_array(type)) {
2425 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
2427 fprintf(stderr, "-INVALID-");
2430 if (path->top_type != NULL) {
2431 fprintf(stderr, " (");
2432 print_type(path->top_type);
2433 fprintf(stderr, ")");
2438 * Return the top type path entry, ie. in a path
2439 * (type).a.b returns the b.
2441 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2443 size_t len = ARR_LEN(path->path);
2445 return &path->path[len-1];
2449 * Enlarge the type path by an (empty) element.
2451 static type_path_entry_t *append_to_type_path(type_path_t *path)
2453 size_t len = ARR_LEN(path->path);
2454 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2456 type_path_entry_t *result = & path->path[len];
2457 memset(result, 0, sizeof(result[0]));
2462 * Descending into a sub-type. Enter the scope of the current top_type.
2464 static void descend_into_subtype(type_path_t *path)
2466 type_t *orig_top_type = path->top_type;
2467 type_t *top_type = skip_typeref(orig_top_type);
2469 type_path_entry_t *top = append_to_type_path(path);
2470 top->type = top_type;
2472 if (is_type_compound(top_type)) {
2473 compound_t *compound = top_type->compound.compound;
2474 entity_t *entry = compound->members.entities;
2476 if (entry != NULL) {
2477 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2478 top->v.compound_entry = &entry->declaration;
2479 path->top_type = entry->declaration.type;
2481 path->top_type = NULL;
2483 } else if (is_type_array(top_type)) {
2485 path->top_type = top_type->array.element_type;
2487 assert(!is_type_valid(top_type));
2492 * Pop an entry from the given type path, ie. returning from
2493 * (type).a.b to (type).a
2495 static void ascend_from_subtype(type_path_t *path)
2497 type_path_entry_t *top = get_type_path_top(path);
2499 path->top_type = top->type;
2501 size_t len = ARR_LEN(path->path);
2502 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2506 * Pop entries from the given type path until the given
2507 * path level is reached.
2509 static void ascend_to(type_path_t *path, size_t top_path_level)
2511 size_t len = ARR_LEN(path->path);
2513 while (len > top_path_level) {
2514 ascend_from_subtype(path);
2515 len = ARR_LEN(path->path);
2519 static bool walk_designator(type_path_t *path, const designator_t *designator,
2520 bool used_in_offsetof)
2522 for (; designator != NULL; designator = designator->next) {
2523 type_path_entry_t *top = get_type_path_top(path);
2524 type_t *orig_type = top->type;
2526 type_t *type = skip_typeref(orig_type);
2528 if (designator->symbol != NULL) {
2529 symbol_t *symbol = designator->symbol;
2530 if (!is_type_compound(type)) {
2531 if (is_type_valid(type)) {
2532 errorf(&designator->source_position,
2533 "'.%Y' designator used for non-compound type '%T'",
2537 top->type = type_error_type;
2538 top->v.compound_entry = NULL;
2539 orig_type = type_error_type;
2541 compound_t *compound = type->compound.compound;
2542 entity_t *iter = compound->members.entities;
2543 for (; iter != NULL; iter = iter->base.next) {
2544 if (iter->base.symbol == symbol) {
2549 errorf(&designator->source_position,
2550 "'%T' has no member named '%Y'", orig_type, symbol);
2553 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2554 if (used_in_offsetof) {
2555 type_t *real_type = skip_typeref(iter->declaration.type);
2556 if (real_type->kind == TYPE_BITFIELD) {
2557 errorf(&designator->source_position,
2558 "offsetof designator '%Y' may not specify bitfield",
2564 top->type = orig_type;
2565 top->v.compound_entry = &iter->declaration;
2566 orig_type = iter->declaration.type;
2569 expression_t *array_index = designator->array_index;
2570 assert(designator->array_index != NULL);
2572 if (!is_type_array(type)) {
2573 if (is_type_valid(type)) {
2574 errorf(&designator->source_position,
2575 "[%E] designator used for non-array type '%T'",
2576 array_index, orig_type);
2581 long index = fold_constant(array_index);
2582 if (!used_in_offsetof) {
2584 errorf(&designator->source_position,
2585 "array index [%E] must be positive", array_index);
2586 } else if (type->array.size_constant) {
2587 long array_size = type->array.size;
2588 if (index >= array_size) {
2589 errorf(&designator->source_position,
2590 "designator [%E] (%d) exceeds array size %d",
2591 array_index, index, array_size);
2596 top->type = orig_type;
2597 top->v.index = (size_t) index;
2598 orig_type = type->array.element_type;
2600 path->top_type = orig_type;
2602 if (designator->next != NULL) {
2603 descend_into_subtype(path);
2612 static void advance_current_object(type_path_t *path, size_t top_path_level)
2614 type_path_entry_t *top = get_type_path_top(path);
2616 type_t *type = skip_typeref(top->type);
2617 if (is_type_union(type)) {
2618 /* in unions only the first element is initialized */
2619 top->v.compound_entry = NULL;
2620 } else if (is_type_struct(type)) {
2621 declaration_t *entry = top->v.compound_entry;
2623 entity_t *next_entity = entry->base.next;
2624 if (next_entity != NULL) {
2625 assert(is_declaration(next_entity));
2626 entry = &next_entity->declaration;
2631 top->v.compound_entry = entry;
2632 if (entry != NULL) {
2633 path->top_type = entry->type;
2636 } else if (is_type_array(type)) {
2637 assert(is_type_array(type));
2641 if (!type->array.size_constant || top->v.index < type->array.size) {
2645 assert(!is_type_valid(type));
2649 /* we're past the last member of the current sub-aggregate, try if we
2650 * can ascend in the type hierarchy and continue with another subobject */
2651 size_t len = ARR_LEN(path->path);
2653 if (len > top_path_level) {
2654 ascend_from_subtype(path);
2655 advance_current_object(path, top_path_level);
2657 path->top_type = NULL;
2662 * skip until token is found.
2664 static void skip_until(int type)
2666 while (token.type != type) {
2667 if (token.type == T_EOF)
2674 * skip any {...} blocks until a closing bracket is reached.
2676 static void skip_initializers(void)
2678 if (token.type == '{')
2681 while (token.type != '}') {
2682 if (token.type == T_EOF)
2684 if (token.type == '{') {
2692 static initializer_t *create_empty_initializer(void)
2694 static initializer_t empty_initializer
2695 = { .list = { { INITIALIZER_LIST }, 0 } };
2696 return &empty_initializer;
2700 * Parse a part of an initialiser for a struct or union,
2702 static initializer_t *parse_sub_initializer(type_path_t *path,
2703 type_t *outer_type, size_t top_path_level,
2704 parse_initializer_env_t *env)
2706 if (token.type == '}') {
2707 /* empty initializer */
2708 return create_empty_initializer();
2711 type_t *orig_type = path->top_type;
2712 type_t *type = NULL;
2714 if (orig_type == NULL) {
2715 /* We are initializing an empty compound. */
2717 type = skip_typeref(orig_type);
2720 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2723 designator_t *designator = NULL;
2724 if (token.type == '.' || token.type == '[') {
2725 designator = parse_designation();
2726 goto finish_designator;
2727 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2728 /* GNU-style designator ("identifier: value") */
2729 designator = allocate_ast_zero(sizeof(designator[0]));
2730 designator->source_position = token.source_position;
2731 designator->symbol = token.v.symbol;
2736 /* reset path to toplevel, evaluate designator from there */
2737 ascend_to(path, top_path_level);
2738 if (!walk_designator(path, designator, false)) {
2739 /* can't continue after designation error */
2743 initializer_t *designator_initializer
2744 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2745 designator_initializer->designator.designator = designator;
2746 ARR_APP1(initializer_t*, initializers, designator_initializer);
2748 orig_type = path->top_type;
2749 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2754 if (token.type == '{') {
2755 if (type != NULL && is_type_scalar(type)) {
2756 sub = parse_scalar_initializer(type, env->must_be_constant);
2760 if (env->entity != NULL) {
2762 "extra brace group at end of initializer for '%Y'",
2763 env->entity->base.symbol);
2765 errorf(HERE, "extra brace group at end of initializer");
2768 descend_into_subtype(path);
2770 add_anchor_token('}');
2771 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2773 rem_anchor_token('}');
2776 ascend_from_subtype(path);
2777 expect('}', end_error);
2779 expect('}', end_error);
2780 goto error_parse_next;
2784 /* must be an expression */
2785 expression_t *expression = parse_assignment_expression();
2787 if (env->must_be_constant && !is_initializer_constant(expression)) {
2788 errorf(&expression->base.source_position,
2789 "Initialisation expression '%E' is not constant",
2794 /* we are already outside, ... */
2795 type_t *const outer_type_skip = skip_typeref(outer_type);
2796 if (is_type_compound(outer_type_skip) &&
2797 !outer_type_skip->compound.compound->complete) {
2798 goto error_parse_next;
2803 /* handle { "string" } special case */
2804 if ((expression->kind == EXPR_STRING_LITERAL
2805 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2806 && outer_type != NULL) {
2807 sub = initializer_from_expression(outer_type, expression);
2809 if (token.type == ',') {
2812 if (token.type != '}' && warning.other) {
2813 warningf(HERE, "excessive elements in initializer for type '%T'",
2816 /* TODO: eat , ... */
2821 /* descend into subtypes until expression matches type */
2823 orig_type = path->top_type;
2824 type = skip_typeref(orig_type);
2826 sub = initializer_from_expression(orig_type, expression);
2830 if (!is_type_valid(type)) {
2833 if (is_type_scalar(type)) {
2834 errorf(&expression->base.source_position,
2835 "expression '%E' doesn't match expected type '%T'",
2836 expression, orig_type);
2840 descend_into_subtype(path);
2844 /* update largest index of top array */
2845 const type_path_entry_t *first = &path->path[0];
2846 type_t *first_type = first->type;
2847 first_type = skip_typeref(first_type);
2848 if (is_type_array(first_type)) {
2849 size_t index = first->v.index;
2850 if (index > path->max_index)
2851 path->max_index = index;
2855 /* append to initializers list */
2856 ARR_APP1(initializer_t*, initializers, sub);
2859 if (warning.other) {
2860 if (env->entity != NULL) {
2861 warningf(HERE, "excess elements in struct initializer for '%Y'",
2862 env->entity->base.symbol);
2864 warningf(HERE, "excess elements in struct initializer");
2870 if (token.type == '}') {
2873 expect(',', end_error);
2874 if (token.type == '}') {
2879 /* advance to the next declaration if we are not at the end */
2880 advance_current_object(path, top_path_level);
2881 orig_type = path->top_type;
2882 if (orig_type != NULL)
2883 type = skip_typeref(orig_type);
2889 size_t len = ARR_LEN(initializers);
2890 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2891 initializer_t *result = allocate_ast_zero(size);
2892 result->kind = INITIALIZER_LIST;
2893 result->list.len = len;
2894 memcpy(&result->list.initializers, initializers,
2895 len * sizeof(initializers[0]));
2897 DEL_ARR_F(initializers);
2898 ascend_to(path, top_path_level+1);
2903 skip_initializers();
2904 DEL_ARR_F(initializers);
2905 ascend_to(path, top_path_level+1);
2910 * Parses an initializer. Parsers either a compound literal
2911 * (env->declaration == NULL) or an initializer of a declaration.
2913 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2915 type_t *type = skip_typeref(env->type);
2916 initializer_t *result = NULL;
2919 if (is_type_scalar(type)) {
2920 result = parse_scalar_initializer(type, env->must_be_constant);
2921 } else if (token.type == '{') {
2925 memset(&path, 0, sizeof(path));
2926 path.top_type = env->type;
2927 path.path = NEW_ARR_F(type_path_entry_t, 0);
2929 descend_into_subtype(&path);
2931 add_anchor_token('}');
2932 result = parse_sub_initializer(&path, env->type, 1, env);
2933 rem_anchor_token('}');
2935 max_index = path.max_index;
2936 DEL_ARR_F(path.path);
2938 expect('}', end_error);
2940 /* parse_scalar_initializer() also works in this case: we simply
2941 * have an expression without {} around it */
2942 result = parse_scalar_initializer(type, env->must_be_constant);
2945 /* § 6.7.8 (22) array initializers for arrays with unknown size determine
2946 * the array type size */
2947 if (is_type_array(type) && type->array.size_expression == NULL
2948 && result != NULL) {
2950 switch (result->kind) {
2951 case INITIALIZER_LIST:
2952 size = max_index + 1;
2955 case INITIALIZER_STRING:
2956 size = result->string.string.size;
2959 case INITIALIZER_WIDE_STRING:
2960 size = result->wide_string.string.size;
2963 case INITIALIZER_DESIGNATOR:
2964 case INITIALIZER_VALUE:
2965 /* can happen for parse errors */
2970 internal_errorf(HERE, "invalid initializer type");
2973 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2974 cnst->base.type = type_size_t;
2975 cnst->conste.v.int_value = size;
2977 type_t *new_type = duplicate_type(type);
2979 new_type->array.size_expression = cnst;
2980 new_type->array.size_constant = true;
2981 new_type->array.has_implicit_size = true;
2982 new_type->array.size = size;
2983 env->type = new_type;
2991 static void append_entity(scope_t *scope, entity_t *entity)
2993 if (scope->last_entity != NULL) {
2994 scope->last_entity->base.next = entity;
2996 scope->entities = entity;
2998 scope->last_entity = entity;
3002 static compound_t *parse_compound_type_specifier(bool is_struct)
3004 gnu_attribute_t *attributes = NULL;
3005 decl_modifiers_t modifiers = 0;
3012 symbol_t *symbol = NULL;
3013 compound_t *compound = NULL;
3015 if (token.type == T___attribute__) {
3016 modifiers |= parse_attributes(&attributes);
3019 if (token.type == T_IDENTIFIER) {
3020 symbol = token.v.symbol;
3023 namespace_tag_t const namespc =
3024 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
3025 entity_t *entity = get_entity(symbol, namespc);
3026 if (entity != NULL) {
3027 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
3028 compound = &entity->compound;
3029 if (compound->base.parent_scope != current_scope &&
3030 (token.type == '{' || token.type == ';')) {
3031 /* we're in an inner scope and have a definition. Override
3032 existing definition in outer scope */
3034 } else if (compound->complete && token.type == '{') {
3035 assert(symbol != NULL);
3036 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
3037 is_struct ? "struct" : "union", symbol,
3038 &compound->base.source_position);
3039 /* clear members in the hope to avoid further errors */
3040 compound->members.entities = NULL;
3043 } else if (token.type != '{') {
3045 parse_error_expected("while parsing struct type specifier",
3046 T_IDENTIFIER, '{', NULL);
3048 parse_error_expected("while parsing union type specifier",
3049 T_IDENTIFIER, '{', NULL);
3055 if (compound == NULL) {
3056 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
3057 entity_t *entity = allocate_entity_zero(kind);
3058 compound = &entity->compound;
3060 compound->base.namespc =
3061 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
3062 compound->base.source_position = token.source_position;
3063 compound->base.symbol = symbol;
3064 compound->base.parent_scope = current_scope;
3065 if (symbol != NULL) {
3066 environment_push(entity);
3068 append_entity(current_scope, entity);
3071 if (token.type == '{') {
3072 parse_compound_type_entries(compound);
3073 modifiers |= parse_attributes(&attributes);
3075 if (symbol == NULL) {
3076 assert(anonymous_entity == NULL);
3077 anonymous_entity = (entity_t*)compound;
3081 compound->modifiers |= modifiers;
3085 static void parse_enum_entries(type_t *const enum_type)
3089 if (token.type == '}') {
3090 errorf(HERE, "empty enum not allowed");
3095 add_anchor_token('}');
3097 if (token.type != T_IDENTIFIER) {
3098 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3100 rem_anchor_token('}');
3104 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3105 entity->enum_value.enum_type = enum_type;
3106 entity->base.symbol = token.v.symbol;
3107 entity->base.source_position = token.source_position;
3110 if (token.type == '=') {
3112 expression_t *value = parse_constant_expression();
3114 value = create_implicit_cast(value, enum_type);
3115 entity->enum_value.value = value;
3120 record_entity(entity, false);
3122 if (token.type != ',')
3125 } while (token.type != '}');
3126 rem_anchor_token('}');
3128 expect('}', end_error);
3134 static type_t *parse_enum_specifier(void)
3136 gnu_attribute_t *attributes = NULL;
3141 if (token.type == T_IDENTIFIER) {
3142 symbol = token.v.symbol;
3145 entity = get_entity(symbol, NAMESPACE_ENUM);
3146 assert(entity == NULL || entity->kind == ENTITY_ENUM);
3147 } else if (token.type != '{') {
3148 parse_error_expected("while parsing enum type specifier",
3149 T_IDENTIFIER, '{', NULL);
3156 if (entity == NULL) {
3157 entity = allocate_entity_zero(ENTITY_ENUM);
3158 entity->base.namespc = NAMESPACE_ENUM;
3159 entity->base.source_position = token.source_position;
3160 entity->base.symbol = symbol;
3161 entity->base.parent_scope = current_scope;
3164 type_t *const type = allocate_type_zero(TYPE_ENUM);
3165 type->enumt.enume = &entity->enume;
3167 if (token.type == '{') {
3168 if (entity->enume.complete) {
3169 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
3170 symbol, &entity->base.source_position);
3172 if (symbol != NULL) {
3173 environment_push(entity);
3175 append_entity(current_scope, entity);
3176 entity->enume.complete = true;
3178 parse_enum_entries(type);
3179 parse_attributes(&attributes);
3181 if (symbol == NULL) {
3182 assert(anonymous_entity == NULL);
3183 anonymous_entity = entity;
3185 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
3186 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
3194 * if a symbol is a typedef to another type, return true
3196 static bool is_typedef_symbol(symbol_t *symbol)
3198 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3199 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3202 static type_t *parse_typeof(void)
3208 expect('(', end_error);
3209 add_anchor_token(')');
3211 expression_t *expression = NULL;
3213 bool old_type_prop = in_type_prop;
3214 bool old_gcc_extension = in_gcc_extension;
3215 in_type_prop = true;
3217 while (token.type == T___extension__) {
3218 /* This can be a prefix to a typename or an expression. */
3220 in_gcc_extension = true;
3222 switch (token.type) {
3224 if (is_typedef_symbol(token.v.symbol)) {
3225 type = parse_typename();
3227 expression = parse_expression();
3228 type = expression->base.type;
3233 type = parse_typename();
3237 expression = parse_expression();
3238 type = expression->base.type;
3241 in_type_prop = old_type_prop;
3242 in_gcc_extension = old_gcc_extension;
3244 rem_anchor_token(')');
3245 expect(')', end_error);
3247 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3248 typeof_type->typeoft.expression = expression;
3249 typeof_type->typeoft.typeof_type = type;
3256 typedef enum specifiers_t {
3257 SPECIFIER_SIGNED = 1 << 0,
3258 SPECIFIER_UNSIGNED = 1 << 1,
3259 SPECIFIER_LONG = 1 << 2,
3260 SPECIFIER_INT = 1 << 3,
3261 SPECIFIER_DOUBLE = 1 << 4,
3262 SPECIFIER_CHAR = 1 << 5,
3263 SPECIFIER_WCHAR_T = 1 << 6,
3264 SPECIFIER_SHORT = 1 << 7,
3265 SPECIFIER_LONG_LONG = 1 << 8,
3266 SPECIFIER_FLOAT = 1 << 9,
3267 SPECIFIER_BOOL = 1 << 10,
3268 SPECIFIER_VOID = 1 << 11,
3269 SPECIFIER_INT8 = 1 << 12,
3270 SPECIFIER_INT16 = 1 << 13,
3271 SPECIFIER_INT32 = 1 << 14,
3272 SPECIFIER_INT64 = 1 << 15,
3273 SPECIFIER_INT128 = 1 << 16,
3274 SPECIFIER_COMPLEX = 1 << 17,
3275 SPECIFIER_IMAGINARY = 1 << 18,
3278 static type_t *create_builtin_type(symbol_t *const symbol,
3279 type_t *const real_type)
3281 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3282 type->builtin.symbol = symbol;
3283 type->builtin.real_type = real_type;
3285 type_t *result = typehash_insert(type);
3286 if (type != result) {
3293 static type_t *get_typedef_type(symbol_t *symbol)
3295 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3296 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3299 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3300 type->typedeft.typedefe = &entity->typedefe;
3306 * check for the allowed MS alignment values.
3308 static bool check_alignment_value(long long intvalue)
3310 if (intvalue < 1 || intvalue > 8192) {
3311 errorf(HERE, "illegal alignment value");
3314 unsigned v = (unsigned)intvalue;
3315 for (unsigned i = 1; i <= 8192; i += i) {
3319 errorf(HERE, "alignment must be power of two");
3323 #define DET_MOD(name, tag) do { \
3324 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3325 *modifiers |= tag; \
3328 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3330 decl_modifiers_t *modifiers = &specifiers->modifiers;
3333 if (token.type == T_restrict) {
3335 DET_MOD(restrict, DM_RESTRICT);
3337 } else if (token.type != T_IDENTIFIER)
3339 symbol_t *symbol = token.v.symbol;
3340 if (symbol == sym_align) {
3342 expect('(', end_error);
3343 if (token.type != T_INTEGER)
3345 if (check_alignment_value(token.v.intvalue)) {
3346 if (specifiers->alignment != 0 && warning.other)
3347 warningf(HERE, "align used more than once");
3348 specifiers->alignment = (unsigned char)token.v.intvalue;
3351 expect(')', end_error);
3352 } else if (symbol == sym_allocate) {
3354 expect('(', end_error);
3355 if (token.type != T_IDENTIFIER)
3357 (void)token.v.symbol;
3358 expect(')', end_error);
3359 } else if (symbol == sym_dllimport) {
3361 DET_MOD(dllimport, DM_DLLIMPORT);
3362 } else if (symbol == sym_dllexport) {
3364 DET_MOD(dllexport, DM_DLLEXPORT);
3365 } else if (symbol == sym_thread) {
3367 DET_MOD(thread, DM_THREAD);
3368 } else if (symbol == sym_naked) {
3370 DET_MOD(naked, DM_NAKED);
3371 } else if (symbol == sym_noinline) {
3373 DET_MOD(noinline, DM_NOINLINE);
3374 } else if (symbol == sym_noreturn) {
3376 DET_MOD(noreturn, DM_NORETURN);
3377 } else if (symbol == sym_nothrow) {
3379 DET_MOD(nothrow, DM_NOTHROW);
3380 } else if (symbol == sym_novtable) {
3382 DET_MOD(novtable, DM_NOVTABLE);
3383 } else if (symbol == sym_property) {
3385 expect('(', end_error);
3387 bool is_get = false;
3388 if (token.type != T_IDENTIFIER)
3390 if (token.v.symbol == sym_get) {
3392 } else if (token.v.symbol == sym_put) {
3394 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3398 expect('=', end_error);
3399 if (token.type != T_IDENTIFIER)
3402 if (specifiers->get_property_sym != NULL) {
3403 errorf(HERE, "get property name already specified");
3405 specifiers->get_property_sym = token.v.symbol;
3408 if (specifiers->put_property_sym != NULL) {
3409 errorf(HERE, "put property name already specified");
3411 specifiers->put_property_sym = token.v.symbol;
3415 if (token.type == ',') {
3421 expect(')', end_error);
3422 } else if (symbol == sym_selectany) {
3424 DET_MOD(selectany, DM_SELECTANY);
3425 } else if (symbol == sym_uuid) {
3427 expect('(', end_error);
3428 if (token.type != T_STRING_LITERAL)
3431 expect(')', end_error);
3432 } else if (symbol == sym_deprecated) {
3434 if (specifiers->deprecated != 0 && warning.other)
3435 warningf(HERE, "deprecated used more than once");
3436 specifiers->deprecated = true;
3437 if (token.type == '(') {
3439 if (token.type == T_STRING_LITERAL) {
3440 specifiers->deprecated_string = token.v.string.begin;
3443 errorf(HERE, "string literal expected");
3445 expect(')', end_error);
3447 } else if (symbol == sym_noalias) {
3449 DET_MOD(noalias, DM_NOALIAS);
3452 warningf(HERE, "Unknown modifier '%Y' ignored", token.v.symbol);
3454 if (token.type == '(')
3458 if (token.type == ',')
3465 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3467 entity_t *entity = allocate_entity_zero(kind);
3468 entity->base.source_position = *HERE;
3469 entity->base.symbol = symbol;
3470 if (is_declaration(entity)) {
3471 entity->declaration.type = type_error_type;
3472 entity->declaration.implicit = true;
3473 } else if (kind == ENTITY_TYPEDEF) {
3474 entity->typedefe.type = type_error_type;
3475 entity->typedefe.builtin = true;
3477 record_entity(entity, false);
3481 static void parse_microsoft_based(based_spec_t *based_spec)
3483 if (token.type != T_IDENTIFIER) {
3484 parse_error_expected("while parsing __based", T_IDENTIFIER, NULL);
3487 symbol_t *symbol = token.v.symbol;
3488 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3490 if (entity == NULL || entity->base.kind != ENTITY_VARIABLE) {
3491 errorf(HERE, "'%Y' is not a variable name.", symbol);
3492 entity = create_error_entity(symbol, ENTITY_VARIABLE);
3494 variable_t *variable = &entity->variable;
3496 if (based_spec->base_variable != NULL) {
3497 errorf(HERE, "__based type qualifier specified more than once");
3499 based_spec->source_position = token.source_position;
3500 based_spec->base_variable = variable;
3502 type_t *const type = variable->base.type;
3504 if (is_type_valid(type)) {
3505 if (! is_type_pointer(skip_typeref(type))) {
3506 errorf(HERE, "variable in __based modifier must have pointer type instead of '%T'", type);
3508 if (variable->base.base.parent_scope != file_scope) {
3509 errorf(HERE, "a nonstatic local variable may not be used in a __based specification");
3517 * Finish the construction of a struct type by calculating
3518 * its size, offsets, alignment.
3520 static void finish_struct_type(compound_type_t *type)
3522 assert(type->compound != NULL);
3524 compound_t *compound = type->compound;
3525 if (!compound->complete)
3530 il_alignment_t alignment = 1;
3531 bool need_pad = false;
3533 entity_t *entry = compound->members.entities;
3534 for (; entry != NULL; entry = entry->base.next) {
3535 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3538 type_t *m_type = skip_typeref(entry->declaration.type);
3539 if (! is_type_valid(m_type)) {
3540 /* simply ignore errors here */
3543 il_alignment_t m_alignment = m_type->base.alignment;
3544 if (m_alignment > alignment)
3545 alignment = m_alignment;
3547 offset = (size + m_alignment - 1) & -m_alignment;
3551 entry->compound_member.offset = offset;
3552 size = offset + m_type->base.size;
3554 if (type->base.alignment != 0) {
3555 alignment = type->base.alignment;
3558 offset = (size + alignment - 1) & -alignment;
3563 if (warning.padded) {
3564 warningf(&compound->base.source_position, "'%T' needs padding", type);
3567 if (compound->modifiers & DM_PACKED && warning.packed) {
3568 warningf(&compound->base.source_position,
3569 "superfluous packed attribute on '%T'", type);
3573 type->base.size = offset;
3574 type->base.alignment = alignment;
3578 * Finish the construction of an union type by calculating
3579 * its size and alignment.
3581 static void finish_union_type(compound_type_t *type)
3583 assert(type->compound != NULL);
3585 compound_t *compound = type->compound;
3586 if (! compound->complete)
3590 il_alignment_t alignment = 1;
3592 entity_t *entry = compound->members.entities;
3593 for (; entry != NULL; entry = entry->base.next) {
3594 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3597 type_t *m_type = skip_typeref(entry->declaration.type);
3598 if (! is_type_valid(m_type))
3601 entry->compound_member.offset = 0;
3602 if (m_type->base.size > size)
3603 size = m_type->base.size;
3604 if (m_type->base.alignment > alignment)
3605 alignment = m_type->base.alignment;
3607 if (type->base.alignment != 0) {
3608 alignment = type->base.alignment;
3610 size = (size + alignment - 1) & -alignment;
3611 type->base.size = size;
3612 type->base.alignment = alignment;
3615 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3617 type_t *type = NULL;
3618 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3619 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3620 unsigned type_specifiers = 0;
3621 bool newtype = false;
3622 bool saw_error = false;
3623 bool old_gcc_extension = in_gcc_extension;
3625 specifiers->source_position = token.source_position;
3628 specifiers->modifiers
3629 |= parse_attributes(&specifiers->gnu_attributes);
3630 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3631 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3633 switch (token.type) {
3635 #define MATCH_STORAGE_CLASS(token, class) \
3637 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3638 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3640 specifiers->storage_class = class; \
3641 if (specifiers->thread_local) \
3642 goto check_thread_storage_class; \
3646 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3647 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3648 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3649 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3650 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3654 expect('(', end_error);
3655 add_anchor_token(')');
3656 parse_microsoft_extended_decl_modifier(specifiers);
3657 rem_anchor_token(')');
3658 expect(')', end_error);
3662 if (specifiers->thread_local) {
3663 errorf(HERE, "duplicate '__thread'");
3665 specifiers->thread_local = true;
3666 check_thread_storage_class:
3667 switch (specifiers->storage_class) {
3668 case STORAGE_CLASS_EXTERN:
3669 case STORAGE_CLASS_NONE:
3670 case STORAGE_CLASS_STATIC:
3674 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
3675 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
3676 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
3677 wrong_thread_stoarge_class:
3678 errorf(HERE, "'__thread' used with '%s'", wrong);
3685 /* type qualifiers */
3686 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3688 qualifiers |= qualifier; \
3692 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3693 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3694 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3695 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3696 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3697 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3698 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3699 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3701 case T___extension__:
3703 in_gcc_extension = true;
3706 /* type specifiers */
3707 #define MATCH_SPECIFIER(token, specifier, name) \
3709 if (type_specifiers & specifier) { \
3710 errorf(HERE, "multiple " name " type specifiers given"); \
3712 type_specifiers |= specifier; \
3717 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3718 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3719 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3720 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3721 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3722 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3723 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3724 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3725 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3726 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3727 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3728 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3729 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3730 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3731 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3732 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3733 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3734 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
3736 case T__forceinline:
3737 /* only in microsoft mode */
3738 specifiers->modifiers |= DM_FORCEINLINE;
3743 specifiers->is_inline = true;
3747 if (type_specifiers & SPECIFIER_LONG_LONG) {
3748 errorf(HERE, "multiple type specifiers given");
3749 } else if (type_specifiers & SPECIFIER_LONG) {
3750 type_specifiers |= SPECIFIER_LONG_LONG;
3752 type_specifiers |= SPECIFIER_LONG;
3758 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3760 type->compound.compound = parse_compound_type_specifier(true);
3761 finish_struct_type(&type->compound);
3765 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3766 type->compound.compound = parse_compound_type_specifier(false);
3767 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3768 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3769 finish_union_type(&type->compound);
3773 type = parse_enum_specifier();
3776 type = parse_typeof();
3778 case T___builtin_va_list:
3779 type = duplicate_type(type_valist);
3783 case T_IDENTIFIER: {
3784 /* only parse identifier if we haven't found a type yet */
3785 if (type != NULL || type_specifiers != 0) {
3786 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3787 * declaration, so it doesn't generate errors about expecting '(' or
3789 switch (look_ahead(1)->type) {
3796 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3800 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3805 goto finish_specifiers;
3809 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3810 if (typedef_type == NULL) {
3811 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3812 * declaration, so it doesn't generate 'implicit int' followed by more
3813 * errors later on. */
3814 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3820 errorf(HERE, "%K does not name a type", &token);
3823 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3825 type = allocate_type_zero(TYPE_TYPEDEF);
3826 type->typedeft.typedefe = &entity->typedefe;
3830 if (la1_type == '&' || la1_type == '*')
3831 goto finish_specifiers;
3836 goto finish_specifiers;
3841 type = typedef_type;
3845 /* function specifier */
3847 goto finish_specifiers;
3852 in_gcc_extension = old_gcc_extension;
3854 if (type == NULL || (saw_error && type_specifiers != 0)) {
3855 atomic_type_kind_t atomic_type;
3857 /* match valid basic types */
3858 switch (type_specifiers) {
3859 case SPECIFIER_VOID:
3860 atomic_type = ATOMIC_TYPE_VOID;
3862 case SPECIFIER_WCHAR_T:
3863 atomic_type = ATOMIC_TYPE_WCHAR_T;
3865 case SPECIFIER_CHAR:
3866 atomic_type = ATOMIC_TYPE_CHAR;
3868 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3869 atomic_type = ATOMIC_TYPE_SCHAR;
3871 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3872 atomic_type = ATOMIC_TYPE_UCHAR;
3874 case SPECIFIER_SHORT:
3875 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3876 case SPECIFIER_SHORT | SPECIFIER_INT:
3877 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3878 atomic_type = ATOMIC_TYPE_SHORT;
3880 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3881 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3882 atomic_type = ATOMIC_TYPE_USHORT;
3885 case SPECIFIER_SIGNED:
3886 case SPECIFIER_SIGNED | SPECIFIER_INT:
3887 atomic_type = ATOMIC_TYPE_INT;
3889 case SPECIFIER_UNSIGNED:
3890 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3891 atomic_type = ATOMIC_TYPE_UINT;
3893 case SPECIFIER_LONG:
3894 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3895 case SPECIFIER_LONG | SPECIFIER_INT:
3896 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3897 atomic_type = ATOMIC_TYPE_LONG;
3899 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3900 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3901 atomic_type = ATOMIC_TYPE_ULONG;
3904 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3905 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3906 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3907 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3909 atomic_type = ATOMIC_TYPE_LONGLONG;
3910 goto warn_about_long_long;
3912 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3913 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3915 atomic_type = ATOMIC_TYPE_ULONGLONG;
3916 warn_about_long_long:
3917 if (warning.long_long) {
3918 warningf(&specifiers->source_position,
3919 "ISO C90 does not support 'long long'");
3923 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3924 atomic_type = unsigned_int8_type_kind;
3927 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3928 atomic_type = unsigned_int16_type_kind;
3931 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3932 atomic_type = unsigned_int32_type_kind;
3935 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3936 atomic_type = unsigned_int64_type_kind;
3939 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3940 atomic_type = unsigned_int128_type_kind;
3943 case SPECIFIER_INT8:
3944 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3945 atomic_type = int8_type_kind;
3948 case SPECIFIER_INT16:
3949 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3950 atomic_type = int16_type_kind;
3953 case SPECIFIER_INT32:
3954 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3955 atomic_type = int32_type_kind;
3958 case SPECIFIER_INT64:
3959 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3960 atomic_type = int64_type_kind;
3963 case SPECIFIER_INT128:
3964 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3965 atomic_type = int128_type_kind;
3968 case SPECIFIER_FLOAT:
3969 atomic_type = ATOMIC_TYPE_FLOAT;
3971 case SPECIFIER_DOUBLE:
3972 atomic_type = ATOMIC_TYPE_DOUBLE;
3974 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3975 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3977 case SPECIFIER_BOOL:
3978 atomic_type = ATOMIC_TYPE_BOOL;
3980 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3981 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3982 atomic_type = ATOMIC_TYPE_FLOAT;
3984 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3985 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3986 atomic_type = ATOMIC_TYPE_DOUBLE;
3988 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3989 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3990 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3993 /* invalid specifier combination, give an error message */
3994 if (type_specifiers == 0) {
3998 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3999 if (!(c_mode & _CXX) && !strict_mode) {
4000 if (warning.implicit_int) {
4001 warningf(HERE, "no type specifiers in declaration, using 'int'");
4003 atomic_type = ATOMIC_TYPE_INT;
4006 errorf(HERE, "no type specifiers given in declaration");
4008 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
4009 (type_specifiers & SPECIFIER_UNSIGNED)) {
4010 errorf(HERE, "signed and unsigned specifiers given");
4011 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
4012 errorf(HERE, "only integer types can be signed or unsigned");
4014 errorf(HERE, "multiple datatypes in declaration");
4019 if (type_specifiers & SPECIFIER_COMPLEX) {
4020 type = allocate_type_zero(TYPE_COMPLEX);
4021 type->complex.akind = atomic_type;
4022 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
4023 type = allocate_type_zero(TYPE_IMAGINARY);
4024 type->imaginary.akind = atomic_type;
4026 type = allocate_type_zero(TYPE_ATOMIC);
4027 type->atomic.akind = atomic_type;
4030 } else if (type_specifiers != 0) {
4031 errorf(HERE, "multiple datatypes in declaration");
4034 /* FIXME: check type qualifiers here */
4036 type->base.qualifiers = qualifiers;
4037 type->base.modifiers = modifiers;
4039 type_t *result = typehash_insert(type);
4040 if (newtype && result != type) {
4044 specifiers->type = result;
4048 specifiers->type = type_error_type;
4052 static type_qualifiers_t parse_type_qualifiers(void)
4054 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
4057 switch (token.type) {
4058 /* type qualifiers */
4059 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
4060 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
4061 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
4062 /* microsoft extended type modifiers */
4063 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
4064 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
4065 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
4066 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
4067 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
4076 * Parses an K&R identifier list
4078 static void parse_identifier_list(scope_t *scope)
4081 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
4082 entity->base.source_position = token.source_position;
4083 entity->base.namespc = NAMESPACE_NORMAL;
4084 entity->base.symbol = token.v.symbol;
4085 /* a K&R parameter has no type, yet */
4089 append_entity(scope, entity);
4091 if (token.type != ',') {
4095 } while (token.type == T_IDENTIFIER);
4098 static entity_t *parse_parameter(void)
4100 declaration_specifiers_t specifiers;
4101 memset(&specifiers, 0, sizeof(specifiers));
4103 parse_declaration_specifiers(&specifiers);
4105 entity_t *entity = parse_declarator(&specifiers,
4106 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
4107 anonymous_entity = NULL;
4111 static void semantic_parameter_incomplete(const entity_t *entity)
4113 assert(entity->kind == ENTITY_PARAMETER);
4115 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
4116 * list in a function declarator that is part of a
4117 * definition of that function shall not have
4118 * incomplete type. */
4119 type_t *type = skip_typeref(entity->declaration.type);
4120 if (is_type_incomplete(type)) {
4121 errorf(&entity->base.source_position,
4122 "parameter '%Y' has incomplete type '%T'", entity->base.symbol,
4123 entity->declaration.type);
4128 * Parses function type parameters (and optionally creates variable_t entities
4129 * for them in a scope)
4131 static void parse_parameters(function_type_t *type, scope_t *scope)
4134 add_anchor_token(')');
4135 int saved_comma_state = save_and_reset_anchor_state(',');
4137 if (token.type == T_IDENTIFIER &&
4138 !is_typedef_symbol(token.v.symbol)) {
4139 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4140 if (la1_type == ',' || la1_type == ')') {
4141 type->kr_style_parameters = true;
4142 type->unspecified_parameters = true;
4143 parse_identifier_list(scope);
4144 goto parameters_finished;
4148 if (token.type == ')') {
4149 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4150 if (!(c_mode & _CXX))
4151 type->unspecified_parameters = true;
4152 goto parameters_finished;
4155 function_parameter_t *parameter;
4156 function_parameter_t *last_parameter = NULL;
4159 switch (token.type) {
4162 type->variadic = true;
4163 goto parameters_finished;
4166 case T___extension__:
4169 entity_t *entity = parse_parameter();
4170 if (entity->kind == ENTITY_TYPEDEF) {
4171 errorf(&entity->base.source_position,
4172 "typedef not allowed as function parameter");
4175 assert(is_declaration(entity));
4177 /* func(void) is not a parameter */
4178 if (last_parameter == NULL
4179 && token.type == ')'
4180 && entity->base.symbol == NULL
4181 && skip_typeref(entity->declaration.type) == type_void) {
4182 goto parameters_finished;
4184 semantic_parameter_incomplete(entity);
4186 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4187 memset(parameter, 0, sizeof(parameter[0]));
4188 parameter->type = entity->declaration.type;
4190 if (scope != NULL) {
4191 append_entity(scope, entity);
4194 if (last_parameter != NULL) {
4195 last_parameter->next = parameter;
4197 type->parameters = parameter;
4199 last_parameter = parameter;
4204 goto parameters_finished;
4206 if (token.type != ',') {
4207 goto parameters_finished;
4213 parameters_finished:
4214 rem_anchor_token(')');
4215 expect(')', end_error);
4218 restore_anchor_state(',', saved_comma_state);
4221 typedef enum construct_type_kind_t {
4224 CONSTRUCT_REFERENCE,
4227 } construct_type_kind_t;
4229 typedef struct construct_type_t construct_type_t;
4230 struct construct_type_t {
4231 construct_type_kind_t kind;
4232 construct_type_t *next;
4235 typedef struct parsed_pointer_t parsed_pointer_t;
4236 struct parsed_pointer_t {
4237 construct_type_t construct_type;
4238 type_qualifiers_t type_qualifiers;
4239 variable_t *base_variable; /**< MS __based extension. */
4242 typedef struct parsed_reference_t parsed_reference_t;
4243 struct parsed_reference_t {
4244 construct_type_t construct_type;
4247 typedef struct construct_function_type_t construct_function_type_t;
4248 struct construct_function_type_t {
4249 construct_type_t construct_type;
4250 type_t *function_type;
4253 typedef struct parsed_array_t parsed_array_t;
4254 struct parsed_array_t {
4255 construct_type_t construct_type;
4256 type_qualifiers_t type_qualifiers;
4262 typedef struct construct_base_type_t construct_base_type_t;
4263 struct construct_base_type_t {
4264 construct_type_t construct_type;
4268 static construct_type_t *parse_pointer_declarator(variable_t *base_variable)
4272 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4273 memset(pointer, 0, sizeof(pointer[0]));
4274 pointer->construct_type.kind = CONSTRUCT_POINTER;
4275 pointer->type_qualifiers = parse_type_qualifiers();
4276 pointer->base_variable = base_variable;
4278 return &pointer->construct_type;
4281 static construct_type_t *parse_reference_declarator(void)
4285 parsed_reference_t *reference = obstack_alloc(&temp_obst, sizeof(reference[0]));
4286 memset(reference, 0, sizeof(reference[0]));
4287 reference->construct_type.kind = CONSTRUCT_REFERENCE;
4289 return (construct_type_t*)reference;
4292 static construct_type_t *parse_array_declarator(void)
4295 add_anchor_token(']');
4297 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4298 memset(array, 0, sizeof(array[0]));
4299 array->construct_type.kind = CONSTRUCT_ARRAY;
4301 if (token.type == T_static) {
4302 array->is_static = true;
4306 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4307 if (type_qualifiers != 0) {
4308 if (token.type == T_static) {
4309 array->is_static = true;
4313 array->type_qualifiers = type_qualifiers;
4315 if (token.type == '*' && look_ahead(1)->type == ']') {
4316 array->is_variable = true;
4318 } else if (token.type != ']') {
4319 array->size = parse_assignment_expression();
4322 rem_anchor_token(']');
4323 expect(']', end_error);
4326 return &array->construct_type;
4329 static construct_type_t *parse_function_declarator(scope_t *scope,
4330 decl_modifiers_t modifiers)
4332 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4333 function_type_t *ftype = &type->function;
4335 ftype->linkage = current_linkage;
4337 switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
4338 case DM_NONE: break;
4339 case DM_CDECL: ftype->calling_convention = CC_CDECL; break;
4340 case DM_STDCALL: ftype->calling_convention = CC_STDCALL; break;
4341 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
4342 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
4345 errorf(HERE, "multiple calling conventions in declaration");
4349 parse_parameters(ftype, scope);
4351 construct_function_type_t *construct_function_type =
4352 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4353 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4354 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4355 construct_function_type->function_type = type;
4357 return &construct_function_type->construct_type;
4360 typedef struct parse_declarator_env_t {
4361 decl_modifiers_t modifiers;
4363 source_position_t source_position;
4365 } parse_declarator_env_t;
4367 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4368 bool may_be_abstract)
4370 /* construct a single linked list of construct_type_t's which describe
4371 * how to construct the final declarator type */
4372 construct_type_t *first = NULL;
4373 construct_type_t *last = NULL;
4374 gnu_attribute_t *attributes = NULL;
4376 decl_modifiers_t modifiers = parse_attributes(&attributes);
4378 /* MS __based extension */
4379 based_spec_t base_spec;
4380 base_spec.base_variable = NULL;
4383 construct_type_t *type;
4384 switch (token.type) {
4386 if (!(c_mode & _CXX))
4387 errorf(HERE, "references are only available for C++");
4388 if (base_spec.base_variable != NULL && warning.other) {
4389 warningf(&base_spec.source_position,
4390 "__based does not precede a pointer operator, ignored");
4392 type = parse_reference_declarator();
4394 base_spec.base_variable = NULL;
4398 type = parse_pointer_declarator(base_spec.base_variable);
4400 base_spec.base_variable = NULL;
4405 expect('(', end_error);
4406 add_anchor_token(')');
4407 parse_microsoft_based(&base_spec);
4408 rem_anchor_token(')');
4409 expect(')', end_error);
4413 goto ptr_operator_end;
4424 /* TODO: find out if this is correct */
4425 modifiers |= parse_attributes(&attributes);
4428 if (base_spec.base_variable != NULL && warning.other) {
4429 warningf(&base_spec.source_position,
4430 "__based does not precede a pointer operator, ignored");
4434 modifiers |= env->modifiers;
4435 env->modifiers = modifiers;
4438 construct_type_t *inner_types = NULL;
4440 switch (token.type) {
4443 errorf(HERE, "no identifier expected in typename");
4445 env->symbol = token.v.symbol;
4446 env->source_position = token.source_position;
4451 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
4452 * interpreted as ``function with no parameter specification'', rather
4453 * than redundant parentheses around the omitted identifier. */
4454 if (look_ahead(1)->type != ')') {
4456 add_anchor_token(')');
4457 inner_types = parse_inner_declarator(env, may_be_abstract);
4458 if (inner_types != NULL) {
4459 /* All later declarators only modify the return type */
4462 rem_anchor_token(')');
4463 expect(')', end_error);
4467 if (may_be_abstract)
4469 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4474 construct_type_t *p = last;
4477 construct_type_t *type;
4478 switch (token.type) {
4480 scope_t *scope = NULL;
4482 scope = &env->parameters;
4484 type = parse_function_declarator(scope, modifiers);
4488 type = parse_array_declarator();
4491 goto declarator_finished;
4494 /* insert in the middle of the list (behind p) */
4496 type->next = p->next;
4507 declarator_finished:
4508 /* append inner_types at the end of the list, we don't to set last anymore
4509 * as it's not needed anymore */
4511 assert(first == NULL);
4512 first = inner_types;
4514 last->next = inner_types;
4522 static void parse_declaration_attributes(entity_t *entity)
4524 gnu_attribute_t *attributes = NULL;
4525 decl_modifiers_t modifiers = parse_attributes(&attributes);
4531 if (entity->kind == ENTITY_TYPEDEF) {
4532 modifiers |= entity->typedefe.modifiers;
4533 type = entity->typedefe.type;
4535 assert(is_declaration(entity));
4536 modifiers |= entity->declaration.modifiers;
4537 type = entity->declaration.type;
4542 /* handle these strange/stupid mode attributes */
4543 gnu_attribute_t *attribute = attributes;
4544 for ( ; attribute != NULL; attribute = attribute->next) {
4545 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4548 atomic_type_kind_t akind = attribute->u.akind;
4549 if (!is_type_signed(type)) {
4551 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4552 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4553 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4554 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4556 panic("invalid akind in mode attribute");
4560 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_SCHAR; break;
4561 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_SHORT; break;
4562 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_INT; break;
4563 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_LONGLONG; break;
4565 panic("invalid akind in mode attribute");
4569 type = make_atomic_type(akind, type->base.qualifiers);
4572 type_modifiers_t type_modifiers = type->base.modifiers;
4573 if (modifiers & DM_TRANSPARENT_UNION)
4574 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4576 if (type->base.modifiers != type_modifiers) {
4577 type_t *copy = duplicate_type(type);
4578 copy->base.modifiers = type_modifiers;
4580 type = typehash_insert(copy);
4582 obstack_free(type_obst, copy);
4586 if (entity->kind == ENTITY_TYPEDEF) {
4587 entity->typedefe.type = type;
4588 entity->typedefe.modifiers = modifiers;
4590 entity->declaration.type = type;
4591 entity->declaration.modifiers = modifiers;
4595 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
4597 construct_type_t *iter = construct_list;
4598 for (; iter != NULL; iter = iter->next) {
4599 switch (iter->kind) {
4600 case CONSTRUCT_INVALID:
4601 internal_errorf(HERE, "invalid type construction found");
4602 case CONSTRUCT_FUNCTION: {
4603 construct_function_type_t *construct_function_type
4604 = (construct_function_type_t*) iter;
4606 type_t *function_type = construct_function_type->function_type;
4608 function_type->function.return_type = type;
4610 type_t *skipped_return_type = skip_typeref(type);
4612 if (is_type_function(skipped_return_type)) {
4613 errorf(HERE, "function returning function is not allowed");
4614 } else if (is_type_array(skipped_return_type)) {
4615 errorf(HERE, "function returning array is not allowed");
4617 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4619 "type qualifiers in return type of function type are meaningless");
4623 type = function_type;
4627 case CONSTRUCT_POINTER: {
4628 if (is_type_reference(skip_typeref(type)))
4629 errorf(HERE, "cannot declare a pointer to reference");
4631 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4632 type = make_based_pointer_type(type, parsed_pointer->type_qualifiers, parsed_pointer->base_variable);
4636 case CONSTRUCT_REFERENCE:
4637 if (is_type_reference(skip_typeref(type)))
4638 errorf(HERE, "cannot declare a reference to reference");
4640 type = make_reference_type(type);
4643 case CONSTRUCT_ARRAY: {
4644 if (is_type_reference(skip_typeref(type)))
4645 errorf(HERE, "cannot declare an array of references");
4647 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4648 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4650 expression_t *size_expression = parsed_array->size;
4651 if (size_expression != NULL) {
4653 = create_implicit_cast(size_expression, type_size_t);
4656 array_type->base.qualifiers = parsed_array->type_qualifiers;
4657 array_type->array.element_type = type;
4658 array_type->array.is_static = parsed_array->is_static;
4659 array_type->array.is_variable = parsed_array->is_variable;
4660 array_type->array.size_expression = size_expression;
4662 if (size_expression != NULL) {
4663 if (is_constant_expression(size_expression)) {
4664 array_type->array.size_constant = true;
4665 array_type->array.size
4666 = fold_constant(size_expression);
4668 array_type->array.is_vla = true;
4672 type_t *skipped_type = skip_typeref(type);
4674 if (is_type_incomplete(skipped_type)) {
4675 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4676 } else if (is_type_function(skipped_type)) {
4677 errorf(HERE, "array of functions is not allowed");
4684 type_t *hashed_type = typehash_insert(type);
4685 if (hashed_type != type) {
4686 /* the function type was constructed earlier freeing it here will
4687 * destroy other types... */
4688 if (iter->kind != CONSTRUCT_FUNCTION) {
4698 static type_t *automatic_type_conversion(type_t *orig_type);
4700 static type_t *semantic_parameter(const source_position_t *pos,
4702 const declaration_specifiers_t *specifiers,
4705 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
4706 * shall be adjusted to ``qualified pointer to type'',
4708 * §6.7.5.3:8 A declaration of a parameter as ``function returning
4709 * type'' shall be adjusted to ``pointer to function
4710 * returning type'', as in 6.3.2.1. */
4711 type = automatic_type_conversion(type);
4713 if (specifiers->is_inline && is_type_valid(type)) {
4714 errorf(pos, "parameter '%Y' declared 'inline'", symbol);
4717 /* §6.9.1:6 The declarations in the declaration list shall contain
4718 * no storage-class specifier other than register and no
4719 * initializations. */
4720 if (specifiers->thread_local || (
4721 specifiers->storage_class != STORAGE_CLASS_NONE &&
4722 specifiers->storage_class != STORAGE_CLASS_REGISTER)
4724 errorf(pos, "invalid storage class for parameter '%Y'", symbol);
4727 /* delay test for incomplete type, because we might have (void)
4728 * which is legal but incomplete... */
4733 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4734 declarator_flags_t flags)
4736 parse_declarator_env_t env;
4737 memset(&env, 0, sizeof(env));
4738 env.modifiers = specifiers->modifiers;
4740 construct_type_t *construct_type =
4741 parse_inner_declarator(&env, (flags & DECL_MAY_BE_ABSTRACT) != 0);
4743 construct_declarator_type(construct_type, specifiers->type);
4744 type_t *type = skip_typeref(orig_type);
4746 if (construct_type != NULL) {
4747 obstack_free(&temp_obst, construct_type);
4751 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4752 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4753 entity->base.symbol = env.symbol;
4754 entity->base.source_position = env.source_position;
4755 entity->typedefe.type = orig_type;
4757 if (anonymous_entity != NULL) {
4758 if (is_type_compound(type)) {
4759 assert(anonymous_entity->compound.alias == NULL);
4760 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4761 anonymous_entity->kind == ENTITY_UNION);
4762 anonymous_entity->compound.alias = entity;
4763 anonymous_entity = NULL;
4764 } else if (is_type_enum(type)) {
4765 assert(anonymous_entity->enume.alias == NULL);
4766 assert(anonymous_entity->kind == ENTITY_ENUM);
4767 anonymous_entity->enume.alias = entity;
4768 anonymous_entity = NULL;
4772 /* create a declaration type entity */
4773 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
4774 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4776 if (specifiers->is_inline && is_type_valid(type)) {
4777 errorf(&env.source_position,
4778 "compound member '%Y' declared 'inline'", env.symbol);
4781 if (specifiers->thread_local ||
4782 specifiers->storage_class != STORAGE_CLASS_NONE) {
4783 errorf(&env.source_position,
4784 "compound member '%Y' must have no storage class",
4787 } else if (flags & DECL_IS_PARAMETER) {
4788 orig_type = semantic_parameter(&env.source_position, orig_type,
4789 specifiers, env.symbol);
4791 entity = allocate_entity_zero(ENTITY_PARAMETER);
4792 } else if (is_type_function(type)) {
4793 entity = allocate_entity_zero(ENTITY_FUNCTION);
4795 entity->function.is_inline = specifiers->is_inline;
4796 entity->function.parameters = env.parameters;
4798 if (specifiers->thread_local || (
4799 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4800 specifiers->storage_class != STORAGE_CLASS_NONE &&
4801 specifiers->storage_class != STORAGE_CLASS_STATIC)
4803 errorf(&env.source_position,
4804 "invalid storage class for function '%Y'", env.symbol);
4807 entity = allocate_entity_zero(ENTITY_VARIABLE);
4809 entity->variable.get_property_sym = specifiers->get_property_sym;
4810 entity->variable.put_property_sym = specifiers->put_property_sym;
4811 if (specifiers->alignment != 0) {
4812 /* TODO: add checks here */
4813 entity->variable.alignment = specifiers->alignment;
4816 if (specifiers->is_inline && is_type_valid(type)) {
4817 errorf(&env.source_position,
4818 "variable '%Y' declared 'inline'", env.symbol);
4821 entity->variable.thread_local = specifiers->thread_local;
4823 bool invalid_storage_class = false;
4824 if (current_scope == file_scope) {
4825 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4826 specifiers->storage_class != STORAGE_CLASS_NONE &&
4827 specifiers->storage_class != STORAGE_CLASS_STATIC) {
4828 invalid_storage_class = true;
4831 if (specifiers->thread_local &&
4832 specifiers->storage_class == STORAGE_CLASS_NONE) {
4833 invalid_storage_class = true;
4836 if (invalid_storage_class) {
4837 errorf(&env.source_position,
4838 "invalid storage class for variable '%Y'", env.symbol);
4842 entity->base.source_position = env.source_position;
4843 entity->base.symbol = env.symbol;
4844 entity->base.namespc = NAMESPACE_NORMAL;
4845 entity->declaration.type = orig_type;
4846 entity->declaration.modifiers = env.modifiers;
4847 entity->declaration.deprecated_string = specifiers->deprecated_string;
4849 storage_class_t storage_class = specifiers->storage_class;
4850 entity->declaration.declared_storage_class = storage_class;
4852 if (storage_class == STORAGE_CLASS_NONE && current_scope != file_scope)
4853 storage_class = STORAGE_CLASS_AUTO;
4854 entity->declaration.storage_class = storage_class;
4857 parse_declaration_attributes(entity);
4862 static type_t *parse_abstract_declarator(type_t *base_type)
4864 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4866 type_t *result = construct_declarator_type(construct_type, base_type);
4867 if (construct_type != NULL) {
4868 obstack_free(&temp_obst, construct_type);
4875 * Check if the declaration of main is suspicious. main should be a
4876 * function with external linkage, returning int, taking either zero
4877 * arguments, two, or three arguments of appropriate types, ie.
4879 * int main([ int argc, char **argv [, char **env ] ]).
4881 * @param decl the declaration to check
4882 * @param type the function type of the declaration
4884 static void check_type_of_main(const entity_t *entity)
4886 const source_position_t *pos = &entity->base.source_position;
4887 if (entity->kind != ENTITY_FUNCTION) {
4888 warningf(pos, "'main' is not a function");
4892 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4893 warningf(pos, "'main' is normally a non-static function");
4896 type_t *type = skip_typeref(entity->declaration.type);
4897 assert(is_type_function(type));
4899 function_type_t *func_type = &type->function;
4900 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4901 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4902 func_type->return_type);
4904 const function_parameter_t *parm = func_type->parameters;
4906 type_t *const first_type = parm->type;
4907 if (!types_compatible(skip_typeref(first_type), type_int)) {
4909 "first argument of 'main' should be 'int', but is '%T'",
4914 type_t *const second_type = parm->type;
4915 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4916 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4920 type_t *const third_type = parm->type;
4921 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4922 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4926 goto warn_arg_count;
4930 warningf(pos, "'main' takes only zero, two or three arguments");
4936 * Check if a symbol is the equal to "main".
4938 static bool is_sym_main(const symbol_t *const sym)
4940 return strcmp(sym->string, "main") == 0;
4943 static void error_redefined_as_different_kind(const source_position_t *pos,
4944 const entity_t *old, entity_kind_t new_kind)
4946 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4947 get_entity_kind_name(old->kind), old->base.symbol,
4948 get_entity_kind_name(new_kind), &old->base.source_position);
4952 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4953 * for various problems that occur for multiple definitions
4955 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4957 const symbol_t *const symbol = entity->base.symbol;
4958 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4959 const source_position_t *pos = &entity->base.source_position;
4961 /* can happen in error cases */
4965 entity_t *previous_entity = get_entity(symbol, namespc);
4966 /* pushing the same entity twice will break the stack structure */
4967 assert(previous_entity != entity);
4969 if (entity->kind == ENTITY_FUNCTION) {
4970 type_t *const orig_type = entity->declaration.type;
4971 type_t *const type = skip_typeref(orig_type);
4973 assert(is_type_function(type));
4974 if (type->function.unspecified_parameters &&
4975 warning.strict_prototypes &&
4976 previous_entity == NULL) {
4977 warningf(pos, "function declaration '%#T' is not a prototype",
4981 if (warning.main && current_scope == file_scope
4982 && is_sym_main(symbol)) {
4983 check_type_of_main(entity);
4987 if (is_declaration(entity) &&
4988 warning.nested_externs &&
4989 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4990 current_scope != file_scope) {
4991 warningf(pos, "nested extern declaration of '%#T'",
4992 entity->declaration.type, symbol);
4995 if (previous_entity != NULL &&
4996 previous_entity->base.parent_scope == ¤t_function->parameters &&
4997 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4998 assert(previous_entity->kind == ENTITY_PARAMETER);
5000 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
5001 entity->declaration.type, symbol,
5002 previous_entity->declaration.type, symbol,
5003 &previous_entity->base.source_position);
5007 if (previous_entity != NULL &&
5008 previous_entity->base.parent_scope == current_scope) {
5009 if (previous_entity->kind != entity->kind) {
5010 error_redefined_as_different_kind(pos, previous_entity,
5014 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
5015 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
5016 symbol, &previous_entity->base.source_position);
5019 if (previous_entity->kind == ENTITY_TYPEDEF) {
5020 /* TODO: C++ allows this for exactly the same type */
5021 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
5022 symbol, &previous_entity->base.source_position);
5026 /* at this point we should have only VARIABLES or FUNCTIONS */
5027 assert(is_declaration(previous_entity) && is_declaration(entity));
5029 declaration_t *const prev_decl = &previous_entity->declaration;
5030 declaration_t *const decl = &entity->declaration;
5032 /* can happen for K&R style declarations */
5033 if (prev_decl->type == NULL &&
5034 previous_entity->kind == ENTITY_PARAMETER &&
5035 entity->kind == ENTITY_PARAMETER) {
5036 prev_decl->type = decl->type;
5037 prev_decl->storage_class = decl->storage_class;
5038 prev_decl->declared_storage_class = decl->declared_storage_class;
5039 prev_decl->modifiers = decl->modifiers;
5040 prev_decl->deprecated_string = decl->deprecated_string;
5041 return previous_entity;
5044 type_t *const orig_type = decl->type;
5045 assert(orig_type != NULL);
5046 type_t *const type = skip_typeref(orig_type);
5047 type_t * prev_type = skip_typeref(prev_decl->type);
5049 if (!types_compatible(type, prev_type)) {
5051 "declaration '%#T' is incompatible with '%#T' (declared %P)",
5052 orig_type, symbol, prev_decl->type, symbol,
5053 &previous_entity->base.source_position);
5055 unsigned old_storage_class = prev_decl->storage_class;
5056 if (warning.redundant_decls &&
5059 !(prev_decl->modifiers & DM_USED) &&
5060 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
5061 warningf(&previous_entity->base.source_position,
5062 "unnecessary static forward declaration for '%#T'",
5063 prev_decl->type, symbol);
5066 unsigned new_storage_class = decl->storage_class;
5067 if (is_type_incomplete(prev_type)) {
5068 prev_decl->type = type;
5072 /* pretend no storage class means extern for function
5073 * declarations (except if the previous declaration is neither
5074 * none nor extern) */
5075 if (entity->kind == ENTITY_FUNCTION) {
5076 if (prev_type->function.unspecified_parameters) {
5077 prev_decl->type = type;
5081 switch (old_storage_class) {
5082 case STORAGE_CLASS_NONE:
5083 old_storage_class = STORAGE_CLASS_EXTERN;
5086 case STORAGE_CLASS_EXTERN:
5087 if (is_definition) {
5088 if (warning.missing_prototypes &&
5089 prev_type->function.unspecified_parameters &&
5090 !is_sym_main(symbol)) {
5091 warningf(pos, "no previous prototype for '%#T'",
5094 } else if (new_storage_class == STORAGE_CLASS_NONE) {
5095 new_storage_class = STORAGE_CLASS_EXTERN;
5104 if (old_storage_class == STORAGE_CLASS_EXTERN &&
5105 new_storage_class == STORAGE_CLASS_EXTERN) {
5106 warn_redundant_declaration:
5107 if (!is_definition &&
5108 warning.redundant_decls &&
5109 is_type_valid(prev_type) &&
5110 strcmp(previous_entity->base.source_position.input_name,
5111 "<builtin>") != 0) {
5113 "redundant declaration for '%Y' (declared %P)",
5114 symbol, &previous_entity->base.source_position);
5116 } else if (current_function == NULL) {
5117 if (old_storage_class != STORAGE_CLASS_STATIC &&
5118 new_storage_class == STORAGE_CLASS_STATIC) {
5120 "static declaration of '%Y' follows non-static declaration (declared %P)",
5121 symbol, &previous_entity->base.source_position);
5122 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
5123 prev_decl->storage_class = STORAGE_CLASS_NONE;
5124 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
5126 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
5128 goto error_redeclaration;
5129 goto warn_redundant_declaration;
5131 } else if (is_type_valid(prev_type)) {
5132 if (old_storage_class == new_storage_class) {
5133 error_redeclaration:
5134 errorf(pos, "redeclaration of '%Y' (declared %P)",
5135 symbol, &previous_entity->base.source_position);
5138 "redeclaration of '%Y' with different linkage (declared %P)",
5139 symbol, &previous_entity->base.source_position);
5144 prev_decl->modifiers |= decl->modifiers;
5145 if (entity->kind == ENTITY_FUNCTION) {
5146 previous_entity->function.is_inline |= entity->function.is_inline;
5148 return previous_entity;
5151 if (entity->kind == ENTITY_FUNCTION) {
5152 if (is_definition &&
5153 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
5154 if (warning.missing_prototypes && !is_sym_main(symbol)) {
5155 warningf(pos, "no previous prototype for '%#T'",
5156 entity->declaration.type, symbol);
5157 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
5158 warningf(pos, "no previous declaration for '%#T'",
5159 entity->declaration.type, symbol);
5162 } else if (warning.missing_declarations &&
5163 entity->kind == ENTITY_VARIABLE &&
5164 current_scope == file_scope) {
5165 declaration_t *declaration = &entity->declaration;
5166 if (declaration->storage_class == STORAGE_CLASS_NONE) {
5167 warningf(pos, "no previous declaration for '%#T'",
5168 declaration->type, symbol);
5173 assert(entity->base.parent_scope == NULL);
5174 assert(current_scope != NULL);
5176 entity->base.parent_scope = current_scope;
5177 entity->base.namespc = NAMESPACE_NORMAL;
5178 environment_push(entity);
5179 append_entity(current_scope, entity);
5184 static void parser_error_multiple_definition(entity_t *entity,
5185 const source_position_t *source_position)
5187 errorf(source_position, "multiple definition of '%Y' (declared %P)",
5188 entity->base.symbol, &entity->base.source_position);
5191 static bool is_declaration_specifier(const token_t *token,
5192 bool only_specifiers_qualifiers)
5194 switch (token->type) {
5199 return is_typedef_symbol(token->v.symbol);
5201 case T___extension__:
5203 return !only_specifiers_qualifiers;
5210 static void parse_init_declarator_rest(entity_t *entity)
5212 assert(is_declaration(entity));
5213 declaration_t *const declaration = &entity->declaration;
5217 type_t *orig_type = declaration->type;
5218 type_t *type = skip_typeref(orig_type);
5220 if (entity->kind == ENTITY_VARIABLE
5221 && entity->variable.initializer != NULL) {
5222 parser_error_multiple_definition(entity, HERE);
5225 bool must_be_constant = false;
5226 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5227 entity->base.parent_scope == file_scope) {
5228 must_be_constant = true;
5231 if (is_type_function(type)) {
5232 errorf(&entity->base.source_position,
5233 "function '%#T' is initialized like a variable",
5234 orig_type, entity->base.symbol);
5235 orig_type = type_error_type;
5238 parse_initializer_env_t env;
5239 env.type = orig_type;
5240 env.must_be_constant = must_be_constant;
5241 env.entity = entity;
5242 current_init_decl = entity;
5244 initializer_t *initializer = parse_initializer(&env);
5245 current_init_decl = NULL;
5247 if (entity->kind == ENTITY_VARIABLE) {
5248 /* § 6.7.5 (22) array initializers for arrays with unknown size
5249 * determine the array type size */
5250 declaration->type = env.type;
5251 entity->variable.initializer = initializer;
5255 /* parse rest of a declaration without any declarator */
5256 static void parse_anonymous_declaration_rest(
5257 const declaration_specifiers_t *specifiers)
5260 anonymous_entity = NULL;
5262 if (warning.other) {
5263 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
5264 specifiers->thread_local) {
5265 warningf(&specifiers->source_position,
5266 "useless storage class in empty declaration");
5269 type_t *type = specifiers->type;
5270 switch (type->kind) {
5271 case TYPE_COMPOUND_STRUCT:
5272 case TYPE_COMPOUND_UNION: {
5273 if (type->compound.compound->base.symbol == NULL) {
5274 warningf(&specifiers->source_position,
5275 "unnamed struct/union that defines no instances");
5284 warningf(&specifiers->source_position, "empty declaration");
5290 static void check_variable_type_complete(entity_t *ent)
5292 if (ent->kind != ENTITY_VARIABLE)
5295 /* §6.7:7 If an identifier for an object is declared with no linkage, the
5296 * type for the object shall be complete [...] */
5297 declaration_t *decl = &ent->declaration;
5298 if (decl->storage_class != STORAGE_CLASS_NONE)
5301 type_t *const orig_type = decl->type;
5302 type_t *const type = skip_typeref(orig_type);
5303 if (!is_type_incomplete(type))
5306 /* GCC allows global arrays without size and assigns them a length of one,
5307 * if no different declaration follows */
5308 if (is_type_array(type) &&
5310 ent->base.parent_scope == file_scope) {
5311 ARR_APP1(declaration_t*, incomplete_arrays, decl);
5315 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
5316 orig_type, ent->base.symbol);
5320 static void parse_declaration_rest(entity_t *ndeclaration,
5321 const declaration_specifiers_t *specifiers,
5322 parsed_declaration_func finished_declaration,
5323 declarator_flags_t flags)
5325 add_anchor_token(';');
5326 add_anchor_token(',');
5328 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5330 if (token.type == '=') {
5331 parse_init_declarator_rest(entity);
5332 } else if (entity->kind == ENTITY_VARIABLE) {
5333 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
5334 * [...] where the extern specifier is explicitly used. */
5335 declaration_t *decl = &entity->declaration;
5336 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
5337 type_t *type = decl->type;
5338 if (is_type_reference(skip_typeref(type))) {
5339 errorf(&entity->base.source_position,
5340 "reference '%#T' must be initialized",
5341 type, entity->base.symbol);
5346 check_variable_type_complete(entity);
5348 if (token.type != ',')
5352 add_anchor_token('=');
5353 ndeclaration = parse_declarator(specifiers, flags);
5354 rem_anchor_token('=');
5356 expect(';', end_error);
5359 anonymous_entity = NULL;
5360 rem_anchor_token(';');
5361 rem_anchor_token(',');
5364 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5366 symbol_t *symbol = entity->base.symbol;
5367 if (symbol == NULL) {
5368 errorf(HERE, "anonymous declaration not valid as function parameter");
5372 assert(entity->base.namespc == NAMESPACE_NORMAL);
5373 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5374 if (previous_entity == NULL
5375 || previous_entity->base.parent_scope != current_scope) {
5376 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5381 if (is_definition) {
5382 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
5385 return record_entity(entity, false);
5388 static void parse_declaration(parsed_declaration_func finished_declaration,
5389 declarator_flags_t flags)
5391 declaration_specifiers_t specifiers;
5392 memset(&specifiers, 0, sizeof(specifiers));
5394 add_anchor_token(';');
5395 parse_declaration_specifiers(&specifiers);
5396 rem_anchor_token(';');
5398 if (token.type == ';') {
5399 parse_anonymous_declaration_rest(&specifiers);
5401 entity_t *entity = parse_declarator(&specifiers, flags);
5402 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
5406 static type_t *get_default_promoted_type(type_t *orig_type)
5408 type_t *result = orig_type;
5410 type_t *type = skip_typeref(orig_type);
5411 if (is_type_integer(type)) {
5412 result = promote_integer(type);
5413 } else if (type == type_float) {
5414 result = type_double;
5420 static void parse_kr_declaration_list(entity_t *entity)
5422 if (entity->kind != ENTITY_FUNCTION)
5425 type_t *type = skip_typeref(entity->declaration.type);
5426 assert(is_type_function(type));
5427 if (!type->function.kr_style_parameters)
5431 add_anchor_token('{');
5433 /* push function parameters */
5434 size_t const top = environment_top();
5435 scope_t *old_scope = scope_push(&entity->function.parameters);
5437 entity_t *parameter = entity->function.parameters.entities;
5438 for ( ; parameter != NULL; parameter = parameter->base.next) {
5439 assert(parameter->base.parent_scope == NULL);
5440 parameter->base.parent_scope = current_scope;
5441 environment_push(parameter);
5444 /* parse declaration list */
5446 switch (token.type) {
5448 case T___extension__:
5449 /* This covers symbols, which are no type, too, and results in
5450 * better error messages. The typical cases are misspelled type
5451 * names and missing includes. */
5453 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
5461 /* pop function parameters */
5462 assert(current_scope == &entity->function.parameters);
5463 scope_pop(old_scope);
5464 environment_pop_to(top);
5466 /* update function type */
5467 type_t *new_type = duplicate_type(type);
5469 function_parameter_t *parameters = NULL;
5470 function_parameter_t *last_parameter = NULL;
5472 parameter = entity->function.parameters.entities;
5473 for (; parameter != NULL; parameter = parameter->base.next) {
5474 type_t *parameter_type = parameter->declaration.type;
5475 if (parameter_type == NULL) {
5477 errorf(HERE, "no type specified for function parameter '%Y'",
5478 parameter->base.symbol);
5480 if (warning.implicit_int) {
5481 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5482 parameter->base.symbol);
5484 parameter_type = type_int;
5485 parameter->declaration.type = parameter_type;
5489 semantic_parameter_incomplete(parameter);
5490 parameter_type = parameter->declaration.type;
5493 * we need the default promoted types for the function type
5495 parameter_type = get_default_promoted_type(parameter_type);
5497 function_parameter_t *function_parameter
5498 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5499 memset(function_parameter, 0, sizeof(function_parameter[0]));
5501 function_parameter->type = parameter_type;
5502 if (last_parameter != NULL) {
5503 last_parameter->next = function_parameter;
5505 parameters = function_parameter;
5507 last_parameter = function_parameter;
5510 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5512 new_type->function.parameters = parameters;
5513 new_type->function.unspecified_parameters = true;
5515 type = typehash_insert(new_type);
5516 if (type != new_type) {
5517 obstack_free(type_obst, new_type);
5520 entity->declaration.type = type;
5522 rem_anchor_token('{');
5525 static bool first_err = true;
5528 * When called with first_err set, prints the name of the current function,
5531 static void print_in_function(void)
5535 diagnosticf("%s: In function '%Y':\n",
5536 current_function->base.base.source_position.input_name,
5537 current_function->base.base.symbol);
5542 * Check if all labels are defined in the current function.
5543 * Check if all labels are used in the current function.
5545 static void check_labels(void)
5547 for (const goto_statement_t *goto_statement = goto_first;
5548 goto_statement != NULL;
5549 goto_statement = goto_statement->next) {
5550 /* skip computed gotos */
5551 if (goto_statement->expression != NULL)
5554 label_t *label = goto_statement->label;
5557 if (label->base.source_position.input_name == NULL) {
5558 print_in_function();
5559 errorf(&goto_statement->base.source_position,
5560 "label '%Y' used but not defined", label->base.symbol);
5564 if (warning.unused_label) {
5565 for (const label_statement_t *label_statement = label_first;
5566 label_statement != NULL;
5567 label_statement = label_statement->next) {
5568 label_t *label = label_statement->label;
5570 if (! label->used) {
5571 print_in_function();
5572 warningf(&label_statement->base.source_position,
5573 "label '%Y' defined but not used", label->base.symbol);
5579 static void warn_unused_entity(entity_t *entity, entity_t *end)
5581 for (; entity != NULL; entity = entity->base.next) {
5582 if (!is_declaration(entity))
5585 declaration_t *declaration = &entity->declaration;
5586 if (declaration->implicit)
5589 if (!declaration->used) {
5590 print_in_function();
5591 const char *what = get_entity_kind_name(entity->kind);
5592 warningf(&entity->base.source_position, "%s '%Y' is unused",
5593 what, entity->base.symbol);
5594 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5595 print_in_function();
5596 const char *what = get_entity_kind_name(entity->kind);
5597 warningf(&entity->base.source_position, "%s '%Y' is never read",
5598 what, entity->base.symbol);
5606 static void check_unused_variables(statement_t *const stmt, void *const env)
5610 switch (stmt->kind) {
5611 case STATEMENT_DECLARATION: {
5612 declaration_statement_t const *const decls = &stmt->declaration;
5613 warn_unused_entity(decls->declarations_begin,
5614 decls->declarations_end);
5619 warn_unused_entity(stmt->fors.scope.entities, NULL);
5628 * Check declarations of current_function for unused entities.
5630 static void check_declarations(void)
5632 if (warning.unused_parameter) {
5633 const scope_t *scope = ¤t_function->parameters;
5635 /* do not issue unused warnings for main */
5636 if (!is_sym_main(current_function->base.base.symbol)) {
5637 warn_unused_entity(scope->entities, NULL);
5640 if (warning.unused_variable) {
5641 walk_statements(current_function->statement, check_unused_variables,
5646 static int determine_truth(expression_t const* const cond)
5649 !is_constant_expression(cond) ? 0 :
5650 fold_constant(cond) != 0 ? 1 :
5654 static void check_reachable(statement_t *);
5656 static bool expression_returns(expression_t const *const expr)
5658 switch (expr->kind) {
5660 expression_t const *const func = expr->call.function;
5661 if (func->kind == EXPR_REFERENCE) {
5662 entity_t *entity = func->reference.entity;
5663 if (entity->kind == ENTITY_FUNCTION
5664 && entity->declaration.modifiers & DM_NORETURN)
5668 if (!expression_returns(func))
5671 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5672 if (!expression_returns(arg->expression))
5679 case EXPR_REFERENCE:
5680 case EXPR_REFERENCE_ENUM_VALUE:
5682 case EXPR_CHARACTER_CONSTANT:
5683 case EXPR_WIDE_CHARACTER_CONSTANT:
5684 case EXPR_STRING_LITERAL:
5685 case EXPR_WIDE_STRING_LITERAL:
5686 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5687 case EXPR_LABEL_ADDRESS:
5688 case EXPR_CLASSIFY_TYPE:
5689 case EXPR_SIZEOF: // TODO handle obscure VLA case
5692 case EXPR_BUILTIN_SYMBOL:
5693 case EXPR_BUILTIN_CONSTANT_P:
5694 case EXPR_BUILTIN_PREFETCH:
5699 case EXPR_STATEMENT:
5700 check_reachable(expr->statement.statement);
5701 // TODO check if statement can be left
5704 case EXPR_CONDITIONAL:
5705 // TODO handle constant expression
5707 if (!expression_returns(expr->conditional.condition))
5710 if (expr->conditional.true_expression != NULL
5711 && expression_returns(expr->conditional.true_expression))
5714 return expression_returns(expr->conditional.false_expression);
5717 return expression_returns(expr->select.compound);
5719 case EXPR_ARRAY_ACCESS:
5721 expression_returns(expr->array_access.array_ref) &&
5722 expression_returns(expr->array_access.index);
5725 return expression_returns(expr->va_starte.ap);
5728 return expression_returns(expr->va_arge.ap);
5730 EXPR_UNARY_CASES_MANDATORY
5731 return expression_returns(expr->unary.value);
5733 case EXPR_UNARY_THROW:
5737 // TODO handle constant lhs of && and ||
5739 expression_returns(expr->binary.left) &&
5740 expression_returns(expr->binary.right);
5746 panic("unhandled expression");
5749 static bool initializer_returns(initializer_t const *const init)
5751 switch (init->kind) {
5752 case INITIALIZER_VALUE:
5753 return expression_returns(init->value.value);
5755 case INITIALIZER_LIST: {
5756 initializer_t * const* i = init->list.initializers;
5757 initializer_t * const* const end = i + init->list.len;
5758 bool returns = true;
5759 for (; i != end; ++i) {
5760 if (!initializer_returns(*i))
5766 case INITIALIZER_STRING:
5767 case INITIALIZER_WIDE_STRING:
5768 case INITIALIZER_DESIGNATOR: // designators have no payload
5771 panic("unhandled initializer");
5774 static bool noreturn_candidate;
5776 static void check_reachable(statement_t *const stmt)
5778 if (stmt->base.reachable)
5780 if (stmt->kind != STATEMENT_DO_WHILE)
5781 stmt->base.reachable = true;
5783 statement_t *last = stmt;
5785 switch (stmt->kind) {
5786 case STATEMENT_INVALID:
5787 case STATEMENT_EMPTY:
5788 case STATEMENT_LOCAL_LABEL:
5790 next = stmt->base.next;
5793 case STATEMENT_DECLARATION: {
5794 declaration_statement_t const *const decl = &stmt->declaration;
5795 entity_t const * ent = decl->declarations_begin;
5796 entity_t const *const last = decl->declarations_end;
5798 for (;; ent = ent->base.next) {
5799 if (ent->kind == ENTITY_VARIABLE &&
5800 ent->variable.initializer != NULL &&
5801 !initializer_returns(ent->variable.initializer)) {
5808 next = stmt->base.next;
5812 case STATEMENT_COMPOUND:
5813 next = stmt->compound.statements;
5816 case STATEMENT_RETURN: {
5817 expression_t const *const val = stmt->returns.value;
5818 if (val == NULL || expression_returns(val))
5819 noreturn_candidate = false;
5823 case STATEMENT_IF: {
5824 if_statement_t const *const ifs = &stmt->ifs;
5825 expression_t const *const cond = ifs->condition;
5827 if (!expression_returns(cond))
5830 int const val = determine_truth(cond);
5833 check_reachable(ifs->true_statement);
5838 if (ifs->false_statement != NULL) {
5839 check_reachable(ifs->false_statement);
5843 next = stmt->base.next;
5847 case STATEMENT_SWITCH: {
5848 switch_statement_t const *const switchs = &stmt->switchs;
5849 expression_t const *const expr = switchs->expression;
5851 if (!expression_returns(expr))
5854 if (is_constant_expression(expr)) {
5855 long const val = fold_constant(expr);
5856 case_label_statement_t * defaults = NULL;
5857 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5858 if (i->expression == NULL) {
5863 if (i->first_case <= val && val <= i->last_case) {
5864 check_reachable((statement_t*)i);
5869 if (defaults != NULL) {
5870 check_reachable((statement_t*)defaults);
5874 bool has_default = false;
5875 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5876 if (i->expression == NULL)
5879 check_reachable((statement_t*)i);
5886 next = stmt->base.next;
5890 case STATEMENT_EXPRESSION: {
5891 /* Check for noreturn function call */
5892 expression_t const *const expr = stmt->expression.expression;
5893 if (!expression_returns(expr))
5896 next = stmt->base.next;
5900 case STATEMENT_CONTINUE: {
5901 statement_t *parent = stmt;
5903 parent = parent->base.parent;
5904 if (parent == NULL) /* continue not within loop */
5908 switch (parent->kind) {
5909 case STATEMENT_WHILE: goto continue_while;
5910 case STATEMENT_DO_WHILE: goto continue_do_while;
5911 case STATEMENT_FOR: goto continue_for;
5918 case STATEMENT_BREAK: {
5919 statement_t *parent = stmt;
5921 parent = parent->base.parent;
5922 if (parent == NULL) /* break not within loop/switch */
5925 switch (parent->kind) {
5926 case STATEMENT_SWITCH:
5927 case STATEMENT_WHILE:
5928 case STATEMENT_DO_WHILE:
5931 next = parent->base.next;
5932 goto found_break_parent;
5941 case STATEMENT_GOTO:
5942 if (stmt->gotos.expression) {
5943 if (!expression_returns(stmt->gotos.expression))
5946 statement_t *parent = stmt->base.parent;
5947 if (parent == NULL) /* top level goto */
5951 next = stmt->gotos.label->statement;
5952 if (next == NULL) /* missing label */
5957 case STATEMENT_LABEL:
5958 next = stmt->label.statement;
5961 case STATEMENT_CASE_LABEL:
5962 next = stmt->case_label.statement;
5965 case STATEMENT_WHILE: {
5966 while_statement_t const *const whiles = &stmt->whiles;
5967 expression_t const *const cond = whiles->condition;
5969 if (!expression_returns(cond))
5972 int const val = determine_truth(cond);
5975 check_reachable(whiles->body);
5980 next = stmt->base.next;
5984 case STATEMENT_DO_WHILE:
5985 next = stmt->do_while.body;
5988 case STATEMENT_FOR: {
5989 for_statement_t *const fors = &stmt->fors;
5991 if (fors->condition_reachable)
5993 fors->condition_reachable = true;
5995 expression_t const *const cond = fors->condition;
6000 } else if (expression_returns(cond)) {
6001 val = determine_truth(cond);
6007 check_reachable(fors->body);
6012 next = stmt->base.next;
6016 case STATEMENT_MS_TRY: {
6017 ms_try_statement_t const *const ms_try = &stmt->ms_try;
6018 check_reachable(ms_try->try_statement);
6019 next = ms_try->final_statement;
6023 case STATEMENT_LEAVE: {
6024 statement_t *parent = stmt;
6026 parent = parent->base.parent;
6027 if (parent == NULL) /* __leave not within __try */
6030 if (parent->kind == STATEMENT_MS_TRY) {
6032 next = parent->ms_try.final_statement;
6040 while (next == NULL) {
6041 next = last->base.parent;
6043 noreturn_candidate = false;
6045 type_t *const type = current_function->base.type;
6046 assert(is_type_function(type));
6047 type_t *const ret = skip_typeref(type->function.return_type);
6048 if (warning.return_type &&
6049 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
6050 is_type_valid(ret) &&
6051 !is_sym_main(current_function->base.base.symbol)) {
6052 warningf(&stmt->base.source_position,
6053 "control reaches end of non-void function");
6058 switch (next->kind) {
6059 case STATEMENT_INVALID:
6060 case STATEMENT_EMPTY:
6061 case STATEMENT_DECLARATION:
6062 case STATEMENT_LOCAL_LABEL:
6063 case STATEMENT_EXPRESSION:
6065 case STATEMENT_RETURN:
6066 case STATEMENT_CONTINUE:
6067 case STATEMENT_BREAK:
6068 case STATEMENT_GOTO:
6069 case STATEMENT_LEAVE:
6070 panic("invalid control flow in function");
6072 case STATEMENT_COMPOUND:
6074 case STATEMENT_SWITCH:
6075 case STATEMENT_LABEL:
6076 case STATEMENT_CASE_LABEL:
6078 next = next->base.next;
6081 case STATEMENT_WHILE: {
6083 if (next->base.reachable)
6085 next->base.reachable = true;
6087 while_statement_t const *const whiles = &next->whiles;
6088 expression_t const *const cond = whiles->condition;
6090 if (!expression_returns(cond))
6093 int const val = determine_truth(cond);
6096 check_reachable(whiles->body);
6102 next = next->base.next;
6106 case STATEMENT_DO_WHILE: {
6108 if (next->base.reachable)
6110 next->base.reachable = true;
6112 do_while_statement_t const *const dw = &next->do_while;
6113 expression_t const *const cond = dw->condition;
6115 if (!expression_returns(cond))
6118 int const val = determine_truth(cond);
6121 check_reachable(dw->body);
6127 next = next->base.next;
6131 case STATEMENT_FOR: {
6133 for_statement_t *const fors = &next->fors;
6135 fors->step_reachable = true;
6137 if (fors->condition_reachable)
6139 fors->condition_reachable = true;
6141 expression_t const *const cond = fors->condition;
6146 } else if (expression_returns(cond)) {
6147 val = determine_truth(cond);
6153 check_reachable(fors->body);
6159 next = next->base.next;
6163 case STATEMENT_MS_TRY:
6165 next = next->ms_try.final_statement;
6170 check_reachable(next);
6173 static void check_unreachable(statement_t* const stmt, void *const env)
6177 switch (stmt->kind) {
6178 case STATEMENT_DO_WHILE:
6179 if (!stmt->base.reachable) {
6180 expression_t const *const cond = stmt->do_while.condition;
6181 if (determine_truth(cond) >= 0) {
6182 warningf(&cond->base.source_position,
6183 "condition of do-while-loop is unreachable");
6188 case STATEMENT_FOR: {
6189 for_statement_t const* const fors = &stmt->fors;
6191 // if init and step are unreachable, cond is unreachable, too
6192 if (!stmt->base.reachable && !fors->step_reachable) {
6193 warningf(&stmt->base.source_position, "statement is unreachable");
6195 if (!stmt->base.reachable && fors->initialisation != NULL) {
6196 warningf(&fors->initialisation->base.source_position,
6197 "initialisation of for-statement is unreachable");
6200 if (!fors->condition_reachable && fors->condition != NULL) {
6201 warningf(&fors->condition->base.source_position,
6202 "condition of for-statement is unreachable");
6205 if (!fors->step_reachable && fors->step != NULL) {
6206 warningf(&fors->step->base.source_position,
6207 "step of for-statement is unreachable");
6213 case STATEMENT_COMPOUND:
6214 if (stmt->compound.statements != NULL)
6216 goto warn_unreachable;
6218 case STATEMENT_DECLARATION: {
6219 /* Only warn if there is at least one declarator with an initializer.
6220 * This typically occurs in switch statements. */
6221 declaration_statement_t const *const decl = &stmt->declaration;
6222 entity_t const * ent = decl->declarations_begin;
6223 entity_t const *const last = decl->declarations_end;
6225 for (;; ent = ent->base.next) {
6226 if (ent->kind == ENTITY_VARIABLE &&
6227 ent->variable.initializer != NULL) {
6228 goto warn_unreachable;
6238 if (!stmt->base.reachable)
6239 warningf(&stmt->base.source_position, "statement is unreachable");
6244 static void parse_external_declaration(void)
6246 /* function-definitions and declarations both start with declaration
6248 declaration_specifiers_t specifiers;
6249 memset(&specifiers, 0, sizeof(specifiers));
6251 add_anchor_token(';');
6252 parse_declaration_specifiers(&specifiers);
6253 rem_anchor_token(';');
6255 /* must be a declaration */
6256 if (token.type == ';') {
6257 parse_anonymous_declaration_rest(&specifiers);
6261 add_anchor_token(',');
6262 add_anchor_token('=');
6263 add_anchor_token(';');
6264 add_anchor_token('{');
6266 /* declarator is common to both function-definitions and declarations */
6267 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
6269 rem_anchor_token('{');
6270 rem_anchor_token(';');
6271 rem_anchor_token('=');
6272 rem_anchor_token(',');
6274 /* must be a declaration */
6275 switch (token.type) {
6279 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
6284 /* must be a function definition */
6285 parse_kr_declaration_list(ndeclaration);
6287 if (token.type != '{') {
6288 parse_error_expected("while parsing function definition", '{', NULL);
6289 eat_until_matching_token(';');
6293 assert(is_declaration(ndeclaration));
6294 type_t *type = skip_typeref(ndeclaration->declaration.type);
6296 if (!is_type_function(type)) {
6297 if (is_type_valid(type)) {
6298 errorf(HERE, "declarator '%#T' has a body but is not a function type",
6299 type, ndeclaration->base.symbol);
6305 if (warning.aggregate_return &&
6306 is_type_compound(skip_typeref(type->function.return_type))) {
6307 warningf(HERE, "function '%Y' returns an aggregate",
6308 ndeclaration->base.symbol);
6310 if (warning.traditional && !type->function.unspecified_parameters) {
6311 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6312 ndeclaration->base.symbol);
6314 if (warning.old_style_definition && type->function.unspecified_parameters) {
6315 warningf(HERE, "old-style function definition '%Y'",
6316 ndeclaration->base.symbol);
6319 /* § 6.7.5.3 (14) a function definition with () means no
6320 * parameters (and not unspecified parameters) */
6321 if (type->function.unspecified_parameters
6322 && type->function.parameters == NULL
6323 && !type->function.kr_style_parameters) {
6324 type_t *duplicate = duplicate_type(type);
6325 duplicate->function.unspecified_parameters = false;
6327 type = typehash_insert(duplicate);
6328 if (type != duplicate) {
6329 obstack_free(type_obst, duplicate);
6331 ndeclaration->declaration.type = type;
6334 entity_t *const entity = record_entity(ndeclaration, true);
6335 assert(entity->kind == ENTITY_FUNCTION);
6336 assert(ndeclaration->kind == ENTITY_FUNCTION);
6338 function_t *function = &entity->function;
6339 if (ndeclaration != entity) {
6340 function->parameters = ndeclaration->function.parameters;
6342 assert(is_declaration(entity));
6343 type = skip_typeref(entity->declaration.type);
6345 /* push function parameters and switch scope */
6346 size_t const top = environment_top();
6347 scope_t *old_scope = scope_push(&function->parameters);
6349 entity_t *parameter = function->parameters.entities;
6350 for (; parameter != NULL; parameter = parameter->base.next) {
6351 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6352 parameter->base.parent_scope = current_scope;
6354 assert(parameter->base.parent_scope == NULL
6355 || parameter->base.parent_scope == current_scope);
6356 parameter->base.parent_scope = current_scope;
6357 if (parameter->base.symbol == NULL) {
6358 errorf(¶meter->base.source_position, "parameter name omitted");
6361 environment_push(parameter);
6364 if (function->statement != NULL) {
6365 parser_error_multiple_definition(entity, HERE);
6368 /* parse function body */
6369 int label_stack_top = label_top();
6370 function_t *old_current_function = current_function;
6371 current_function = function;
6372 current_parent = NULL;
6375 goto_anchor = &goto_first;
6377 label_anchor = &label_first;
6379 statement_t *const body = parse_compound_statement(false);
6380 function->statement = body;
6383 check_declarations();
6384 if (warning.return_type ||
6385 warning.unreachable_code ||
6386 (warning.missing_noreturn
6387 && !(function->base.modifiers & DM_NORETURN))) {
6388 noreturn_candidate = true;
6389 check_reachable(body);
6390 if (warning.unreachable_code)
6391 walk_statements(body, check_unreachable, NULL);
6392 if (warning.missing_noreturn &&
6393 noreturn_candidate &&
6394 !(function->base.modifiers & DM_NORETURN)) {
6395 warningf(&body->base.source_position,
6396 "function '%#T' is candidate for attribute 'noreturn'",
6397 type, entity->base.symbol);
6401 assert(current_parent == NULL);
6402 assert(current_function == function);
6403 current_function = old_current_function;
6404 label_pop_to(label_stack_top);
6407 assert(current_scope == &function->parameters);
6408 scope_pop(old_scope);
6409 environment_pop_to(top);
6412 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6413 source_position_t *source_position,
6414 const symbol_t *symbol)
6416 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6418 type->bitfield.base_type = base_type;
6419 type->bitfield.size_expression = size;
6422 type_t *skipped_type = skip_typeref(base_type);
6423 if (!is_type_integer(skipped_type)) {
6424 errorf(HERE, "bitfield base type '%T' is not an integer type",
6428 bit_size = skipped_type->base.size * 8;
6431 if (is_constant_expression(size)) {
6432 long v = fold_constant(size);
6435 errorf(source_position, "negative width in bit-field '%Y'", symbol);
6436 } else if (v == 0) {
6437 errorf(source_position, "zero width for bit-field '%Y'", symbol);
6438 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6439 errorf(source_position, "width of '%Y' exceeds its type", symbol);
6441 type->bitfield.bit_size = v;
6448 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6450 entity_t *iter = compound->members.entities;
6451 for (; iter != NULL; iter = iter->base.next) {
6452 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6455 if (iter->base.symbol == symbol) {
6457 } else if (iter->base.symbol == NULL) {
6458 type_t *type = skip_typeref(iter->declaration.type);
6459 if (is_type_compound(type)) {
6461 = find_compound_entry(type->compound.compound, symbol);
6472 static void parse_compound_declarators(compound_t *compound,
6473 const declaration_specifiers_t *specifiers)
6478 if (token.type == ':') {
6479 source_position_t source_position = *HERE;
6482 type_t *base_type = specifiers->type;
6483 expression_t *size = parse_constant_expression();
6485 type_t *type = make_bitfield_type(base_type, size,
6486 &source_position, sym_anonymous);
6488 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6489 entity->base.namespc = NAMESPACE_NORMAL;
6490 entity->base.source_position = source_position;
6491 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6492 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6493 entity->declaration.modifiers = specifiers->modifiers;
6494 entity->declaration.type = type;
6496 entity = parse_declarator(specifiers,
6497 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
6498 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6500 if (token.type == ':') {
6501 source_position_t source_position = *HERE;
6503 expression_t *size = parse_constant_expression();
6505 type_t *type = entity->declaration.type;
6506 type_t *bitfield_type = make_bitfield_type(type, size,
6507 &source_position, entity->base.symbol);
6508 entity->declaration.type = bitfield_type;
6512 /* make sure we don't define a symbol multiple times */
6513 symbol_t *symbol = entity->base.symbol;
6514 if (symbol != NULL) {
6515 entity_t *prev = find_compound_entry(compound, symbol);
6518 errorf(&entity->base.source_position,
6519 "multiple declarations of symbol '%Y' (declared %P)",
6520 symbol, &prev->base.source_position);
6524 append_entity(&compound->members, entity);
6526 type_t *orig_type = entity->declaration.type;
6527 type_t *type = skip_typeref(orig_type);
6528 if (is_type_function(type)) {
6529 errorf(&entity->base.source_position,
6530 "compound member '%Y' must not have function type '%T'",
6531 entity->base.symbol, orig_type);
6532 } else if (is_type_incomplete(type)) {
6533 /* §6.7.2.1:16 flexible array member */
6534 if (is_type_array(type) &&
6535 token.type == ';' &&
6536 look_ahead(1)->type == '}') {
6537 compound->has_flexible_member = true;
6539 errorf(&entity->base.source_position,
6540 "compound member '%Y' has incomplete type '%T'",
6541 entity->base.symbol, orig_type);
6545 if (token.type != ',')
6549 expect(';', end_error);
6552 anonymous_entity = NULL;
6555 static void parse_compound_type_entries(compound_t *compound)
6558 add_anchor_token('}');
6560 while (token.type != '}') {
6561 if (token.type == T_EOF) {
6562 errorf(HERE, "EOF while parsing struct");
6565 declaration_specifiers_t specifiers;
6566 memset(&specifiers, 0, sizeof(specifiers));
6567 parse_declaration_specifiers(&specifiers);
6569 parse_compound_declarators(compound, &specifiers);
6571 rem_anchor_token('}');
6575 compound->complete = true;
6578 static type_t *parse_typename(void)
6580 declaration_specifiers_t specifiers;
6581 memset(&specifiers, 0, sizeof(specifiers));
6582 parse_declaration_specifiers(&specifiers);
6583 if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6584 specifiers.thread_local) {
6585 /* TODO: improve error message, user does probably not know what a
6586 * storage class is...
6588 errorf(HERE, "typename may not have a storage class");
6591 type_t *result = parse_abstract_declarator(specifiers.type);
6599 typedef expression_t* (*parse_expression_function)(void);
6600 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6602 typedef struct expression_parser_function_t expression_parser_function_t;
6603 struct expression_parser_function_t {
6604 parse_expression_function parser;
6605 unsigned infix_precedence;
6606 parse_expression_infix_function infix_parser;
6609 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6612 * Prints an error message if an expression was expected but not read
6614 static expression_t *expected_expression_error(void)
6616 /* skip the error message if the error token was read */
6617 if (token.type != T_ERROR) {
6618 errorf(HERE, "expected expression, got token %K", &token);
6622 return create_invalid_expression();
6626 * Parse a string constant.
6628 static expression_t *parse_string_const(void)
6631 if (token.type == T_STRING_LITERAL) {
6632 string_t res = token.v.string;
6634 while (token.type == T_STRING_LITERAL) {
6635 res = concat_strings(&res, &token.v.string);
6638 if (token.type != T_WIDE_STRING_LITERAL) {
6639 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6640 /* note: that we use type_char_ptr here, which is already the
6641 * automatic converted type. revert_automatic_type_conversion
6642 * will construct the array type */
6643 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6644 cnst->string.value = res;
6648 wres = concat_string_wide_string(&res, &token.v.wide_string);
6650 wres = token.v.wide_string;
6655 switch (token.type) {
6656 case T_WIDE_STRING_LITERAL:
6657 wres = concat_wide_strings(&wres, &token.v.wide_string);
6660 case T_STRING_LITERAL:
6661 wres = concat_wide_string_string(&wres, &token.v.string);
6665 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6666 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6667 cnst->wide_string.value = wres;
6676 * Parse a boolean constant.
6678 static expression_t *parse_bool_const(bool value)
6680 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6681 cnst->base.type = type_bool;
6682 cnst->conste.v.int_value = value;
6690 * Parse an integer constant.
6692 static expression_t *parse_int_const(void)
6694 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6695 cnst->base.type = token.datatype;
6696 cnst->conste.v.int_value = token.v.intvalue;
6704 * Parse a character constant.
6706 static expression_t *parse_character_constant(void)
6708 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6709 cnst->base.type = token.datatype;
6710 cnst->conste.v.character = token.v.string;
6712 if (cnst->conste.v.character.size != 1) {
6714 errorf(HERE, "more than 1 character in character constant");
6715 } else if (warning.multichar) {
6716 warningf(HERE, "multi-character character constant");
6725 * Parse a wide character constant.
6727 static expression_t *parse_wide_character_constant(void)
6729 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6730 cnst->base.type = token.datatype;
6731 cnst->conste.v.wide_character = token.v.wide_string;
6733 if (cnst->conste.v.wide_character.size != 1) {
6735 errorf(HERE, "more than 1 character in character constant");
6736 } else if (warning.multichar) {
6737 warningf(HERE, "multi-character character constant");
6746 * Parse a float constant.
6748 static expression_t *parse_float_const(void)
6750 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6751 cnst->base.type = token.datatype;
6752 cnst->conste.v.float_value = token.v.floatvalue;
6759 static entity_t *create_implicit_function(symbol_t *symbol,
6760 const source_position_t *source_position)
6762 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6763 ntype->function.return_type = type_int;
6764 ntype->function.unspecified_parameters = true;
6766 type_t *type = typehash_insert(ntype);
6767 if (type != ntype) {
6771 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6772 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6773 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6774 entity->declaration.type = type;
6775 entity->declaration.implicit = true;
6776 entity->base.symbol = symbol;
6777 entity->base.source_position = *source_position;
6779 bool strict_prototypes_old = warning.strict_prototypes;
6780 warning.strict_prototypes = false;
6781 record_entity(entity, false);
6782 warning.strict_prototypes = strict_prototypes_old;
6788 * Creates a return_type (func)(argument_type) function type if not
6791 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6792 type_t *argument_type2)
6794 function_parameter_t *parameter2
6795 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6796 memset(parameter2, 0, sizeof(parameter2[0]));
6797 parameter2->type = argument_type2;
6799 function_parameter_t *parameter1
6800 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6801 memset(parameter1, 0, sizeof(parameter1[0]));
6802 parameter1->type = argument_type1;
6803 parameter1->next = parameter2;
6805 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6806 type->function.return_type = return_type;
6807 type->function.parameters = parameter1;
6809 type_t *result = typehash_insert(type);
6810 if (result != type) {
6818 * Creates a return_type (func)(argument_type) function type if not
6821 * @param return_type the return type
6822 * @param argument_type the argument type
6824 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6826 function_parameter_t *parameter
6827 = obstack_alloc(type_obst, sizeof(parameter[0]));
6828 memset(parameter, 0, sizeof(parameter[0]));
6829 parameter->type = argument_type;
6831 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6832 type->function.return_type = return_type;
6833 type->function.parameters = parameter;
6835 type_t *result = typehash_insert(type);
6836 if (result != type) {
6843 static type_t *make_function_0_type(type_t *return_type)
6845 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6846 type->function.return_type = return_type;
6847 type->function.parameters = NULL;
6849 type_t *result = typehash_insert(type);
6850 if (result != type) {
6858 * Creates a function type for some function like builtins.
6860 * @param symbol the symbol describing the builtin
6862 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6864 switch (symbol->ID) {
6865 case T___builtin_alloca:
6866 return make_function_1_type(type_void_ptr, type_size_t);
6867 case T___builtin_huge_val:
6868 return make_function_0_type(type_double);
6869 case T___builtin_inf:
6870 return make_function_0_type(type_double);
6871 case T___builtin_inff:
6872 return make_function_0_type(type_float);
6873 case T___builtin_infl:
6874 return make_function_0_type(type_long_double);
6875 case T___builtin_nan:
6876 return make_function_1_type(type_double, type_char_ptr);
6877 case T___builtin_nanf:
6878 return make_function_1_type(type_float, type_char_ptr);
6879 case T___builtin_nanl:
6880 return make_function_1_type(type_long_double, type_char_ptr);
6881 case T___builtin_va_end:
6882 return make_function_1_type(type_void, type_valist);
6883 case T___builtin_expect:
6884 return make_function_2_type(type_long, type_long, type_long);
6886 internal_errorf(HERE, "not implemented builtin identifier found");
6891 * Performs automatic type cast as described in § 6.3.2.1.
6893 * @param orig_type the original type
6895 static type_t *automatic_type_conversion(type_t *orig_type)
6897 type_t *type = skip_typeref(orig_type);
6898 if (is_type_array(type)) {
6899 array_type_t *array_type = &type->array;
6900 type_t *element_type = array_type->element_type;
6901 unsigned qualifiers = array_type->base.qualifiers;
6903 return make_pointer_type(element_type, qualifiers);
6906 if (is_type_function(type)) {
6907 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6914 * reverts the automatic casts of array to pointer types and function
6915 * to function-pointer types as defined § 6.3.2.1
6917 type_t *revert_automatic_type_conversion(const expression_t *expression)
6919 switch (expression->kind) {
6920 case EXPR_REFERENCE: {
6921 entity_t *entity = expression->reference.entity;
6922 if (is_declaration(entity)) {
6923 return entity->declaration.type;
6924 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6925 return entity->enum_value.enum_type;
6927 panic("no declaration or enum in reference");
6932 entity_t *entity = expression->select.compound_entry;
6933 assert(is_declaration(entity));
6934 type_t *type = entity->declaration.type;
6935 return get_qualified_type(type,
6936 expression->base.type->base.qualifiers);
6939 case EXPR_UNARY_DEREFERENCE: {
6940 const expression_t *const value = expression->unary.value;
6941 type_t *const type = skip_typeref(value->base.type);
6942 assert(is_type_pointer(type));
6943 return type->pointer.points_to;
6946 case EXPR_BUILTIN_SYMBOL:
6947 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6949 case EXPR_ARRAY_ACCESS: {
6950 const expression_t *array_ref = expression->array_access.array_ref;
6951 type_t *type_left = skip_typeref(array_ref->base.type);
6952 if (!is_type_valid(type_left))
6954 assert(is_type_pointer(type_left));
6955 return type_left->pointer.points_to;
6958 case EXPR_STRING_LITERAL: {
6959 size_t size = expression->string.value.size;
6960 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6963 case EXPR_WIDE_STRING_LITERAL: {
6964 size_t size = expression->wide_string.value.size;
6965 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6968 case EXPR_COMPOUND_LITERAL:
6969 return expression->compound_literal.type;
6974 return expression->base.type;
6977 static expression_t *parse_reference(void)
6979 symbol_t *const symbol = token.v.symbol;
6981 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6983 if (entity == NULL) {
6984 if (!strict_mode && look_ahead(1)->type == '(') {
6985 /* an implicitly declared function */
6986 if (warning.error_implicit_function_declaration) {
6987 errorf(HERE, "implicit declaration of function '%Y'", symbol);
6988 } else if (warning.implicit_function_declaration) {
6989 warningf(HERE, "implicit declaration of function '%Y'", symbol);
6992 entity = create_implicit_function(symbol, HERE);
6994 errorf(HERE, "unknown identifier '%Y' found.", symbol);
6995 entity = create_error_entity(symbol, ENTITY_VARIABLE);
7001 if (is_declaration(entity)) {
7002 orig_type = entity->declaration.type;
7003 } else if (entity->kind == ENTITY_ENUM_VALUE) {
7004 orig_type = entity->enum_value.enum_type;
7005 } else if (entity->kind == ENTITY_TYPEDEF) {
7006 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
7009 return create_invalid_expression();
7011 panic("expected declaration or enum value in reference");
7014 /* we always do the auto-type conversions; the & and sizeof parser contains
7015 * code to revert this! */
7016 type_t *type = automatic_type_conversion(orig_type);
7018 expression_kind_t kind = EXPR_REFERENCE;
7019 if (entity->kind == ENTITY_ENUM_VALUE)
7020 kind = EXPR_REFERENCE_ENUM_VALUE;
7022 expression_t *expression = allocate_expression_zero(kind);
7023 expression->reference.entity = entity;
7024 expression->base.type = type;
7026 /* this declaration is used */
7027 if (is_declaration(entity)) {
7028 entity->declaration.used = true;
7031 if (entity->base.parent_scope != file_scope
7032 && entity->base.parent_scope->depth < current_function->parameters.depth
7033 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
7034 if (entity->kind == ENTITY_VARIABLE) {
7035 /* access of a variable from an outer function */
7036 entity->variable.address_taken = true;
7037 } else if (entity->kind == ENTITY_PARAMETER) {
7038 entity->parameter.address_taken = true;
7040 current_function->need_closure = true;
7043 /* check for deprecated functions */
7044 if (warning.deprecated_declarations
7045 && is_declaration(entity)
7046 && entity->declaration.modifiers & DM_DEPRECATED) {
7047 declaration_t *declaration = &entity->declaration;
7049 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
7050 "function" : "variable";
7052 if (declaration->deprecated_string != NULL) {
7053 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
7054 prefix, entity->base.symbol, &entity->base.source_position,
7055 declaration->deprecated_string);
7057 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
7058 entity->base.symbol, &entity->base.source_position);
7062 if (warning.init_self && entity == current_init_decl && !in_type_prop
7063 && entity->kind == ENTITY_VARIABLE) {
7064 current_init_decl = NULL;
7065 warningf(HERE, "variable '%#T' is initialized by itself",
7066 entity->declaration.type, entity->base.symbol);
7073 static bool semantic_cast(expression_t *cast)
7075 expression_t *expression = cast->unary.value;
7076 type_t *orig_dest_type = cast->base.type;
7077 type_t *orig_type_right = expression->base.type;
7078 type_t const *dst_type = skip_typeref(orig_dest_type);
7079 type_t const *src_type = skip_typeref(orig_type_right);
7080 source_position_t const *pos = &cast->base.source_position;
7082 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
7083 if (dst_type == type_void)
7086 /* only integer and pointer can be casted to pointer */
7087 if (is_type_pointer(dst_type) &&
7088 !is_type_pointer(src_type) &&
7089 !is_type_integer(src_type) &&
7090 is_type_valid(src_type)) {
7091 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
7095 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
7096 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
7100 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
7101 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
7105 if (warning.cast_qual &&
7106 is_type_pointer(src_type) &&
7107 is_type_pointer(dst_type)) {
7108 type_t *src = skip_typeref(src_type->pointer.points_to);
7109 type_t *dst = skip_typeref(dst_type->pointer.points_to);
7110 unsigned missing_qualifiers =
7111 src->base.qualifiers & ~dst->base.qualifiers;
7112 if (missing_qualifiers != 0) {
7114 "cast discards qualifiers '%Q' in pointer target type of '%T'",
7115 missing_qualifiers, orig_type_right);
7121 static expression_t *parse_compound_literal(type_t *type)
7123 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
7125 parse_initializer_env_t env;
7128 env.must_be_constant = false;
7129 initializer_t *initializer = parse_initializer(&env);
7132 expression->compound_literal.initializer = initializer;
7133 expression->compound_literal.type = type;
7134 expression->base.type = automatic_type_conversion(type);
7140 * Parse a cast expression.
7142 static expression_t *parse_cast(void)
7144 add_anchor_token(')');
7146 source_position_t source_position = token.source_position;
7148 type_t *type = parse_typename();
7150 rem_anchor_token(')');
7151 expect(')', end_error);
7153 if (token.type == '{') {
7154 return parse_compound_literal(type);
7157 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
7158 cast->base.source_position = source_position;
7160 expression_t *value = parse_sub_expression(PREC_CAST);
7161 cast->base.type = type;
7162 cast->unary.value = value;
7164 if (! semantic_cast(cast)) {
7165 /* TODO: record the error in the AST. else it is impossible to detect it */
7170 return create_invalid_expression();
7174 * Parse a statement expression.
7176 static expression_t *parse_statement_expression(void)
7178 add_anchor_token(')');
7180 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
7182 statement_t *statement = parse_compound_statement(true);
7183 expression->statement.statement = statement;
7185 /* find last statement and use its type */
7186 type_t *type = type_void;
7187 const statement_t *stmt = statement->compound.statements;
7189 while (stmt->base.next != NULL)
7190 stmt = stmt->base.next;
7192 if (stmt->kind == STATEMENT_EXPRESSION) {
7193 type = stmt->expression.expression->base.type;
7195 } else if (warning.other) {
7196 warningf(&expression->base.source_position, "empty statement expression ({})");
7198 expression->base.type = type;
7200 rem_anchor_token(')');
7201 expect(')', end_error);
7208 * Parse a parenthesized expression.
7210 static expression_t *parse_parenthesized_expression(void)
7214 switch (token.type) {
7216 /* gcc extension: a statement expression */
7217 return parse_statement_expression();
7221 return parse_cast();
7223 if (is_typedef_symbol(token.v.symbol)) {
7224 return parse_cast();
7228 add_anchor_token(')');
7229 expression_t *result = parse_expression();
7230 result->base.parenthesized = true;
7231 rem_anchor_token(')');
7232 expect(')', end_error);
7238 static expression_t *parse_function_keyword(void)
7242 if (current_function == NULL) {
7243 errorf(HERE, "'__func__' used outside of a function");
7246 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7247 expression->base.type = type_char_ptr;
7248 expression->funcname.kind = FUNCNAME_FUNCTION;
7255 static expression_t *parse_pretty_function_keyword(void)
7257 if (current_function == NULL) {
7258 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
7261 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7262 expression->base.type = type_char_ptr;
7263 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
7265 eat(T___PRETTY_FUNCTION__);
7270 static expression_t *parse_funcsig_keyword(void)
7272 if (current_function == NULL) {
7273 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7276 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7277 expression->base.type = type_char_ptr;
7278 expression->funcname.kind = FUNCNAME_FUNCSIG;
7285 static expression_t *parse_funcdname_keyword(void)
7287 if (current_function == NULL) {
7288 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7291 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7292 expression->base.type = type_char_ptr;
7293 expression->funcname.kind = FUNCNAME_FUNCDNAME;
7295 eat(T___FUNCDNAME__);
7300 static designator_t *parse_designator(void)
7302 designator_t *result = allocate_ast_zero(sizeof(result[0]));
7303 result->source_position = *HERE;
7305 if (token.type != T_IDENTIFIER) {
7306 parse_error_expected("while parsing member designator",
7307 T_IDENTIFIER, NULL);
7310 result->symbol = token.v.symbol;
7313 designator_t *last_designator = result;
7315 if (token.type == '.') {
7317 if (token.type != T_IDENTIFIER) {
7318 parse_error_expected("while parsing member designator",
7319 T_IDENTIFIER, NULL);
7322 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7323 designator->source_position = *HERE;
7324 designator->symbol = token.v.symbol;
7327 last_designator->next = designator;
7328 last_designator = designator;
7331 if (token.type == '[') {
7333 add_anchor_token(']');
7334 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7335 designator->source_position = *HERE;
7336 designator->array_index = parse_expression();
7337 rem_anchor_token(']');
7338 expect(']', end_error);
7339 if (designator->array_index == NULL) {
7343 last_designator->next = designator;
7344 last_designator = designator;
7356 * Parse the __builtin_offsetof() expression.
7358 static expression_t *parse_offsetof(void)
7360 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7361 expression->base.type = type_size_t;
7363 eat(T___builtin_offsetof);
7365 expect('(', end_error);
7366 add_anchor_token(',');
7367 type_t *type = parse_typename();
7368 rem_anchor_token(',');
7369 expect(',', end_error);
7370 add_anchor_token(')');
7371 designator_t *designator = parse_designator();
7372 rem_anchor_token(')');
7373 expect(')', end_error);
7375 expression->offsetofe.type = type;
7376 expression->offsetofe.designator = designator;
7379 memset(&path, 0, sizeof(path));
7380 path.top_type = type;
7381 path.path = NEW_ARR_F(type_path_entry_t, 0);
7383 descend_into_subtype(&path);
7385 if (!walk_designator(&path, designator, true)) {
7386 return create_invalid_expression();
7389 DEL_ARR_F(path.path);
7393 return create_invalid_expression();
7397 * Parses a _builtin_va_start() expression.
7399 static expression_t *parse_va_start(void)
7401 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7403 eat(T___builtin_va_start);
7405 expect('(', end_error);
7406 add_anchor_token(',');
7407 expression->va_starte.ap = parse_assignment_expression();
7408 rem_anchor_token(',');
7409 expect(',', end_error);
7410 expression_t *const expr = parse_assignment_expression();
7411 if (expr->kind == EXPR_REFERENCE) {
7412 entity_t *const entity = expr->reference.entity;
7413 if (entity->base.parent_scope != ¤t_function->parameters
7414 || entity->base.next != NULL
7415 || entity->kind != ENTITY_PARAMETER) {
7416 errorf(&expr->base.source_position,
7417 "second argument of 'va_start' must be last parameter of the current function");
7419 expression->va_starte.parameter = &entity->variable;
7421 expect(')', end_error);
7424 expect(')', end_error);
7426 return create_invalid_expression();
7430 * Parses a _builtin_va_arg() expression.
7432 static expression_t *parse_va_arg(void)
7434 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7436 eat(T___builtin_va_arg);
7438 expect('(', end_error);
7439 expression->va_arge.ap = parse_assignment_expression();
7440 expect(',', end_error);
7441 expression->base.type = parse_typename();
7442 expect(')', end_error);
7446 return create_invalid_expression();
7449 static expression_t *parse_builtin_symbol(void)
7451 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7453 symbol_t *symbol = token.v.symbol;
7455 expression->builtin_symbol.symbol = symbol;
7458 type_t *type = get_builtin_symbol_type(symbol);
7459 type = automatic_type_conversion(type);
7461 expression->base.type = type;
7466 * Parses a __builtin_constant() expression.
7468 static expression_t *parse_builtin_constant(void)
7470 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7472 eat(T___builtin_constant_p);
7474 expect('(', end_error);
7475 add_anchor_token(')');
7476 expression->builtin_constant.value = parse_assignment_expression();
7477 rem_anchor_token(')');
7478 expect(')', end_error);
7479 expression->base.type = type_int;
7483 return create_invalid_expression();
7487 * Parses a __builtin_prefetch() expression.
7489 static expression_t *parse_builtin_prefetch(void)
7491 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7493 eat(T___builtin_prefetch);
7495 expect('(', end_error);
7496 add_anchor_token(')');
7497 expression->builtin_prefetch.adr = parse_assignment_expression();
7498 if (token.type == ',') {
7500 expression->builtin_prefetch.rw = parse_assignment_expression();
7502 if (token.type == ',') {
7504 expression->builtin_prefetch.locality = parse_assignment_expression();
7506 rem_anchor_token(')');
7507 expect(')', end_error);
7508 expression->base.type = type_void;
7512 return create_invalid_expression();
7516 * Parses a __builtin_is_*() compare expression.
7518 static expression_t *parse_compare_builtin(void)
7520 expression_t *expression;
7522 switch (token.type) {
7523 case T___builtin_isgreater:
7524 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7526 case T___builtin_isgreaterequal:
7527 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7529 case T___builtin_isless:
7530 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7532 case T___builtin_islessequal:
7533 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7535 case T___builtin_islessgreater:
7536 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7538 case T___builtin_isunordered:
7539 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7542 internal_errorf(HERE, "invalid compare builtin found");
7544 expression->base.source_position = *HERE;
7547 expect('(', end_error);
7548 expression->binary.left = parse_assignment_expression();
7549 expect(',', end_error);
7550 expression->binary.right = parse_assignment_expression();
7551 expect(')', end_error);
7553 type_t *const orig_type_left = expression->binary.left->base.type;
7554 type_t *const orig_type_right = expression->binary.right->base.type;
7556 type_t *const type_left = skip_typeref(orig_type_left);
7557 type_t *const type_right = skip_typeref(orig_type_right);
7558 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7559 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7560 type_error_incompatible("invalid operands in comparison",
7561 &expression->base.source_position, orig_type_left, orig_type_right);
7564 semantic_comparison(&expression->binary);
7569 return create_invalid_expression();
7574 * Parses a __builtin_expect(, end_error) expression.
7576 static expression_t *parse_builtin_expect(void, end_error)
7578 expression_t *expression
7579 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7581 eat(T___builtin_expect);
7583 expect('(', end_error);
7584 expression->binary.left = parse_assignment_expression();
7585 expect(',', end_error);
7586 expression->binary.right = parse_constant_expression();
7587 expect(')', end_error);
7589 expression->base.type = expression->binary.left->base.type;
7593 return create_invalid_expression();
7598 * Parses a MS assume() expression.
7600 static expression_t *parse_assume(void)
7602 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7606 expect('(', end_error);
7607 add_anchor_token(')');
7608 expression->unary.value = parse_assignment_expression();
7609 rem_anchor_token(')');
7610 expect(')', end_error);
7612 expression->base.type = type_void;
7615 return create_invalid_expression();
7619 * Return the declaration for a given label symbol or create a new one.
7621 * @param symbol the symbol of the label
7623 static label_t *get_label(symbol_t *symbol)
7626 assert(current_function != NULL);
7628 label = get_entity(symbol, NAMESPACE_LABEL);
7629 /* if we found a local label, we already created the declaration */
7630 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7631 if (label->base.parent_scope != current_scope) {
7632 assert(label->base.parent_scope->depth < current_scope->depth);
7633 current_function->goto_to_outer = true;
7635 return &label->label;
7638 label = get_entity(symbol, NAMESPACE_LABEL);
7639 /* if we found a label in the same function, then we already created the
7642 && label->base.parent_scope == ¤t_function->parameters) {
7643 return &label->label;
7646 /* otherwise we need to create a new one */
7647 label = allocate_entity_zero(ENTITY_LABEL);
7648 label->base.namespc = NAMESPACE_LABEL;
7649 label->base.symbol = symbol;
7653 return &label->label;
7657 * Parses a GNU && label address expression.
7659 static expression_t *parse_label_address(void)
7661 source_position_t source_position = token.source_position;
7663 if (token.type != T_IDENTIFIER) {
7664 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7667 symbol_t *symbol = token.v.symbol;
7670 label_t *label = get_label(symbol);
7672 label->address_taken = true;
7674 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7675 expression->base.source_position = source_position;
7677 /* label address is threaten as a void pointer */
7678 expression->base.type = type_void_ptr;
7679 expression->label_address.label = label;
7682 return create_invalid_expression();
7686 * Parse a microsoft __noop expression.
7688 static expression_t *parse_noop_expression(void)
7690 /* the result is a (int)0 */
7691 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7692 cnst->base.type = type_int;
7693 cnst->conste.v.int_value = 0;
7694 cnst->conste.is_ms_noop = true;
7698 if (token.type == '(') {
7699 /* parse arguments */
7701 add_anchor_token(')');
7702 add_anchor_token(',');
7704 if (token.type != ')') {
7706 (void)parse_assignment_expression();
7707 if (token.type != ',')
7713 rem_anchor_token(',');
7714 rem_anchor_token(')');
7715 expect(')', end_error);
7722 * Parses a primary expression.
7724 static expression_t *parse_primary_expression(void)
7726 switch (token.type) {
7727 case T_false: return parse_bool_const(false);
7728 case T_true: return parse_bool_const(true);
7729 case T_INTEGER: return parse_int_const();
7730 case T_CHARACTER_CONSTANT: return parse_character_constant();
7731 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7732 case T_FLOATINGPOINT: return parse_float_const();
7733 case T_STRING_LITERAL:
7734 case T_WIDE_STRING_LITERAL: return parse_string_const();
7735 case T_IDENTIFIER: return parse_reference();
7736 case T___FUNCTION__:
7737 case T___func__: return parse_function_keyword();
7738 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7739 case T___FUNCSIG__: return parse_funcsig_keyword();
7740 case T___FUNCDNAME__: return parse_funcdname_keyword();
7741 case T___builtin_offsetof: return parse_offsetof();
7742 case T___builtin_va_start: return parse_va_start();
7743 case T___builtin_va_arg: return parse_va_arg();
7744 case T___builtin_expect:
7745 case T___builtin_alloca:
7746 case T___builtin_inf:
7747 case T___builtin_inff:
7748 case T___builtin_infl:
7749 case T___builtin_nan:
7750 case T___builtin_nanf:
7751 case T___builtin_nanl:
7752 case T___builtin_huge_val:
7753 case T___builtin_va_end: return parse_builtin_symbol();
7754 case T___builtin_isgreater:
7755 case T___builtin_isgreaterequal:
7756 case T___builtin_isless:
7757 case T___builtin_islessequal:
7758 case T___builtin_islessgreater:
7759 case T___builtin_isunordered: return parse_compare_builtin();
7760 case T___builtin_constant_p: return parse_builtin_constant();
7761 case T___builtin_prefetch: return parse_builtin_prefetch();
7762 case T__assume: return parse_assume();
7765 return parse_label_address();
7768 case '(': return parse_parenthesized_expression();
7769 case T___noop: return parse_noop_expression();
7772 errorf(HERE, "unexpected token %K, expected an expression", &token);
7773 return create_invalid_expression();
7777 * Check if the expression has the character type and issue a warning then.
7779 static void check_for_char_index_type(const expression_t *expression)
7781 type_t *const type = expression->base.type;
7782 const type_t *const base_type = skip_typeref(type);
7784 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7785 warning.char_subscripts) {
7786 warningf(&expression->base.source_position,
7787 "array subscript has type '%T'", type);
7791 static expression_t *parse_array_expression(expression_t *left)
7793 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7796 add_anchor_token(']');
7798 expression_t *inside = parse_expression();
7800 type_t *const orig_type_left = left->base.type;
7801 type_t *const orig_type_inside = inside->base.type;
7803 type_t *const type_left = skip_typeref(orig_type_left);
7804 type_t *const type_inside = skip_typeref(orig_type_inside);
7806 type_t *return_type;
7807 array_access_expression_t *array_access = &expression->array_access;
7808 if (is_type_pointer(type_left)) {
7809 return_type = type_left->pointer.points_to;
7810 array_access->array_ref = left;
7811 array_access->index = inside;
7812 check_for_char_index_type(inside);
7813 } else if (is_type_pointer(type_inside)) {
7814 return_type = type_inside->pointer.points_to;
7815 array_access->array_ref = inside;
7816 array_access->index = left;
7817 array_access->flipped = true;
7818 check_for_char_index_type(left);
7820 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7822 "array access on object with non-pointer types '%T', '%T'",
7823 orig_type_left, orig_type_inside);
7825 return_type = type_error_type;
7826 array_access->array_ref = left;
7827 array_access->index = inside;
7830 expression->base.type = automatic_type_conversion(return_type);
7832 rem_anchor_token(']');
7833 expect(']', end_error);
7838 static expression_t *parse_typeprop(expression_kind_t const kind)
7840 expression_t *tp_expression = allocate_expression_zero(kind);
7841 tp_expression->base.type = type_size_t;
7843 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7845 /* we only refer to a type property, mark this case */
7846 bool old = in_type_prop;
7847 in_type_prop = true;
7850 expression_t *expression;
7851 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7853 add_anchor_token(')');
7854 orig_type = parse_typename();
7855 rem_anchor_token(')');
7856 expect(')', end_error);
7858 if (token.type == '{') {
7859 /* It was not sizeof(type) after all. It is sizeof of an expression
7860 * starting with a compound literal */
7861 expression = parse_compound_literal(orig_type);
7862 goto typeprop_expression;
7865 expression = parse_sub_expression(PREC_UNARY);
7867 typeprop_expression:
7868 tp_expression->typeprop.tp_expression = expression;
7870 orig_type = revert_automatic_type_conversion(expression);
7871 expression->base.type = orig_type;
7874 tp_expression->typeprop.type = orig_type;
7875 type_t const* const type = skip_typeref(orig_type);
7876 char const* const wrong_type =
7877 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7878 is_type_incomplete(type) ? "incomplete" :
7879 type->kind == TYPE_FUNCTION ? "function designator" :
7880 type->kind == TYPE_BITFIELD ? "bitfield" :
7882 if (wrong_type != NULL) {
7883 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7884 errorf(&tp_expression->base.source_position,
7885 "operand of %s expression must not be of %s type '%T'",
7886 what, wrong_type, orig_type);
7891 return tp_expression;
7894 static expression_t *parse_sizeof(void)
7896 return parse_typeprop(EXPR_SIZEOF);
7899 static expression_t *parse_alignof(void)
7901 return parse_typeprop(EXPR_ALIGNOF);
7904 static expression_t *parse_select_expression(expression_t *compound)
7906 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7907 select->select.compound = compound;
7909 assert(token.type == '.' || token.type == T_MINUSGREATER);
7910 bool is_pointer = (token.type == T_MINUSGREATER);
7913 if (token.type != T_IDENTIFIER) {
7914 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7917 symbol_t *symbol = token.v.symbol;
7920 type_t *const orig_type = compound->base.type;
7921 type_t *const type = skip_typeref(orig_type);
7924 bool saw_error = false;
7925 if (is_type_pointer(type)) {
7928 "request for member '%Y' in something not a struct or union, but '%T'",
7932 type_left = skip_typeref(type->pointer.points_to);
7934 if (is_pointer && is_type_valid(type)) {
7935 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7942 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7943 type_left->kind == TYPE_COMPOUND_UNION) {
7944 compound_t *compound = type_left->compound.compound;
7946 if (!compound->complete) {
7947 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7949 goto create_error_entry;
7952 entry = find_compound_entry(compound, symbol);
7953 if (entry == NULL) {
7954 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7955 goto create_error_entry;
7958 if (is_type_valid(type_left) && !saw_error) {
7960 "request for member '%Y' in something not a struct or union, but '%T'",
7964 entry = create_error_entity(symbol, ENTITY_COMPOUND_MEMBER);
7967 assert(is_declaration(entry));
7968 select->select.compound_entry = entry;
7970 type_t *entry_type = entry->declaration.type;
7972 = get_qualified_type(entry_type, type_left->base.qualifiers);
7974 /* we always do the auto-type conversions; the & and sizeof parser contains
7975 * code to revert this! */
7976 select->base.type = automatic_type_conversion(res_type);
7978 type_t *skipped = skip_typeref(res_type);
7979 if (skipped->kind == TYPE_BITFIELD) {
7980 select->base.type = skipped->bitfield.base_type;
7986 static void check_call_argument(const function_parameter_t *parameter,
7987 call_argument_t *argument, unsigned pos)
7989 type_t *expected_type = parameter->type;
7990 type_t *expected_type_skip = skip_typeref(expected_type);
7991 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7992 expression_t *arg_expr = argument->expression;
7993 type_t *arg_type = skip_typeref(arg_expr->base.type);
7995 /* handle transparent union gnu extension */
7996 if (is_type_union(expected_type_skip)
7997 && (expected_type_skip->base.modifiers
7998 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7999 compound_t *union_decl = expected_type_skip->compound.compound;
8000 type_t *best_type = NULL;
8001 entity_t *entry = union_decl->members.entities;
8002 for ( ; entry != NULL; entry = entry->base.next) {
8003 assert(is_declaration(entry));
8004 type_t *decl_type = entry->declaration.type;
8005 error = semantic_assign(decl_type, arg_expr);
8006 if (error == ASSIGN_ERROR_INCOMPATIBLE
8007 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
8010 if (error == ASSIGN_SUCCESS) {
8011 best_type = decl_type;
8012 } else if (best_type == NULL) {
8013 best_type = decl_type;
8017 if (best_type != NULL) {
8018 expected_type = best_type;
8022 error = semantic_assign(expected_type, arg_expr);
8023 argument->expression = create_implicit_cast(argument->expression,
8026 if (error != ASSIGN_SUCCESS) {
8027 /* report exact scope in error messages (like "in argument 3") */
8029 snprintf(buf, sizeof(buf), "call argument %u", pos);
8030 report_assign_error(error, expected_type, arg_expr, buf,
8031 &arg_expr->base.source_position);
8032 } else if (warning.traditional || warning.conversion) {
8033 type_t *const promoted_type = get_default_promoted_type(arg_type);
8034 if (!types_compatible(expected_type_skip, promoted_type) &&
8035 !types_compatible(expected_type_skip, type_void_ptr) &&
8036 !types_compatible(type_void_ptr, promoted_type)) {
8037 /* Deliberately show the skipped types in this warning */
8038 warningf(&arg_expr->base.source_position,
8039 "passing call argument %u as '%T' rather than '%T' due to prototype",
8040 pos, expected_type_skip, promoted_type);
8046 * Parse a call expression, ie. expression '( ... )'.
8048 * @param expression the function address
8050 static expression_t *parse_call_expression(expression_t *expression)
8052 expression_t *result = allocate_expression_zero(EXPR_CALL);
8053 call_expression_t *call = &result->call;
8054 call->function = expression;
8056 type_t *const orig_type = expression->base.type;
8057 type_t *const type = skip_typeref(orig_type);
8059 function_type_t *function_type = NULL;
8060 if (is_type_pointer(type)) {
8061 type_t *const to_type = skip_typeref(type->pointer.points_to);
8063 if (is_type_function(to_type)) {
8064 function_type = &to_type->function;
8065 call->base.type = function_type->return_type;
8069 if (function_type == NULL && is_type_valid(type)) {
8070 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
8073 /* parse arguments */
8075 add_anchor_token(')');
8076 add_anchor_token(',');
8078 if (token.type != ')') {
8079 call_argument_t *last_argument = NULL;
8082 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8084 argument->expression = parse_assignment_expression();
8085 if (last_argument == NULL) {
8086 call->arguments = argument;
8088 last_argument->next = argument;
8090 last_argument = argument;
8092 if (token.type != ',')
8097 rem_anchor_token(',');
8098 rem_anchor_token(')');
8099 expect(')', end_error);
8101 if (function_type == NULL)
8104 function_parameter_t *parameter = function_type->parameters;
8105 call_argument_t *argument = call->arguments;
8106 if (!function_type->unspecified_parameters) {
8107 for (unsigned pos = 0; parameter != NULL && argument != NULL;
8108 parameter = parameter->next, argument = argument->next) {
8109 check_call_argument(parameter, argument, ++pos);
8112 if (parameter != NULL) {
8113 errorf(HERE, "too few arguments to function '%E'", expression);
8114 } else if (argument != NULL && !function_type->variadic) {
8115 errorf(HERE, "too many arguments to function '%E'", expression);
8119 /* do default promotion */
8120 for (; argument != NULL; argument = argument->next) {
8121 type_t *type = argument->expression->base.type;
8123 type = get_default_promoted_type(type);
8125 argument->expression
8126 = create_implicit_cast(argument->expression, type);
8129 check_format(&result->call);
8131 if (warning.aggregate_return &&
8132 is_type_compound(skip_typeref(function_type->return_type))) {
8133 warningf(&result->base.source_position,
8134 "function call has aggregate value");
8141 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
8143 static bool same_compound_type(const type_t *type1, const type_t *type2)
8146 is_type_compound(type1) &&
8147 type1->kind == type2->kind &&
8148 type1->compound.compound == type2->compound.compound;
8151 static expression_t const *get_reference_address(expression_t const *expr)
8153 bool regular_take_address = true;
8155 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8156 expr = expr->unary.value;
8158 regular_take_address = false;
8161 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8164 expr = expr->unary.value;
8167 if (expr->kind != EXPR_REFERENCE)
8170 /* special case for functions which are automatically converted to a
8171 * pointer to function without an extra TAKE_ADDRESS operation */
8172 if (!regular_take_address &&
8173 expr->reference.entity->kind != ENTITY_FUNCTION) {
8180 static void warn_reference_address_as_bool(expression_t const* expr)
8182 if (!warning.address)
8185 expr = get_reference_address(expr);
8187 warningf(&expr->base.source_position,
8188 "the address of '%Y' will always evaluate as 'true'",
8189 expr->reference.entity->base.symbol);
8193 static void warn_assignment_in_condition(const expression_t *const expr)
8195 if (!warning.parentheses)
8197 if (expr->base.kind != EXPR_BINARY_ASSIGN)
8199 if (expr->base.parenthesized)
8201 warningf(&expr->base.source_position,
8202 "suggest parentheses around assignment used as truth value");
8205 static void semantic_condition(expression_t const *const expr,
8206 char const *const context)
8208 type_t *const type = skip_typeref(expr->base.type);
8209 if (is_type_scalar(type)) {
8210 warn_reference_address_as_bool(expr);
8211 warn_assignment_in_condition(expr);
8212 } else if (is_type_valid(type)) {
8213 errorf(&expr->base.source_position,
8214 "%s must have scalar type", context);
8219 * Parse a conditional expression, ie. 'expression ? ... : ...'.
8221 * @param expression the conditional expression
8223 static expression_t *parse_conditional_expression(expression_t *expression)
8225 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
8227 conditional_expression_t *conditional = &result->conditional;
8228 conditional->condition = expression;
8231 add_anchor_token(':');
8233 /* §6.5.15:2 The first operand shall have scalar type. */
8234 semantic_condition(expression, "condition of conditional operator");
8236 expression_t *true_expression = expression;
8237 bool gnu_cond = false;
8238 if (GNU_MODE && token.type == ':') {
8241 true_expression = parse_expression();
8243 rem_anchor_token(':');
8244 expect(':', end_error);
8245 expression_t *false_expression =
8246 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
8248 type_t *const orig_true_type = true_expression->base.type;
8249 type_t *const orig_false_type = false_expression->base.type;
8250 type_t *const true_type = skip_typeref(orig_true_type);
8251 type_t *const false_type = skip_typeref(orig_false_type);
8254 type_t *result_type;
8255 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8256 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
8257 /* ISO/IEC 14882:1998(E) §5.16:2 */
8258 if (true_expression->kind == EXPR_UNARY_THROW) {
8259 result_type = false_type;
8260 } else if (false_expression->kind == EXPR_UNARY_THROW) {
8261 result_type = true_type;
8263 if (warning.other && (
8264 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8265 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
8267 warningf(&conditional->base.source_position,
8268 "ISO C forbids conditional expression with only one void side");
8270 result_type = type_void;
8272 } else if (is_type_arithmetic(true_type)
8273 && is_type_arithmetic(false_type)) {
8274 result_type = semantic_arithmetic(true_type, false_type);
8276 true_expression = create_implicit_cast(true_expression, result_type);
8277 false_expression = create_implicit_cast(false_expression, result_type);
8279 conditional->true_expression = true_expression;
8280 conditional->false_expression = false_expression;
8281 conditional->base.type = result_type;
8282 } else if (same_compound_type(true_type, false_type)) {
8283 /* just take 1 of the 2 types */
8284 result_type = true_type;
8285 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
8286 type_t *pointer_type;
8288 expression_t *other_expression;
8289 if (is_type_pointer(true_type) &&
8290 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
8291 pointer_type = true_type;
8292 other_type = false_type;
8293 other_expression = false_expression;
8295 pointer_type = false_type;
8296 other_type = true_type;
8297 other_expression = true_expression;
8300 if (is_null_pointer_constant(other_expression)) {
8301 result_type = pointer_type;
8302 } else if (is_type_pointer(other_type)) {
8303 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8304 type_t *to2 = skip_typeref(other_type->pointer.points_to);
8307 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8308 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8310 } else if (types_compatible(get_unqualified_type(to1),
8311 get_unqualified_type(to2))) {
8314 if (warning.other) {
8315 warningf(&conditional->base.source_position,
8316 "pointer types '%T' and '%T' in conditional expression are incompatible",
8317 true_type, false_type);
8322 type_t *const type =
8323 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8324 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8325 } else if (is_type_integer(other_type)) {
8326 if (warning.other) {
8327 warningf(&conditional->base.source_position,
8328 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8330 result_type = pointer_type;
8332 if (is_type_valid(other_type)) {
8333 type_error_incompatible("while parsing conditional",
8334 &expression->base.source_position, true_type, false_type);
8336 result_type = type_error_type;
8339 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8340 type_error_incompatible("while parsing conditional",
8341 &conditional->base.source_position, true_type,
8344 result_type = type_error_type;
8347 conditional->true_expression
8348 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8349 conditional->false_expression
8350 = create_implicit_cast(false_expression, result_type);
8351 conditional->base.type = result_type;
8354 return create_invalid_expression();
8358 * Parse an extension expression.
8360 static expression_t *parse_extension(void)
8362 eat(T___extension__);
8364 bool old_gcc_extension = in_gcc_extension;
8365 in_gcc_extension = true;
8366 expression_t *expression = parse_sub_expression(PREC_UNARY);
8367 in_gcc_extension = old_gcc_extension;
8372 * Parse a __builtin_classify_type() expression.
8374 static expression_t *parse_builtin_classify_type(void)
8376 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8377 result->base.type = type_int;
8379 eat(T___builtin_classify_type);
8381 expect('(', end_error);
8382 add_anchor_token(')');
8383 expression_t *expression = parse_expression();
8384 rem_anchor_token(')');
8385 expect(')', end_error);
8386 result->classify_type.type_expression = expression;
8390 return create_invalid_expression();
8394 * Parse a delete expression
8395 * ISO/IEC 14882:1998(E) §5.3.5
8397 static expression_t *parse_delete(void)
8399 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8400 result->base.type = type_void;
8404 if (token.type == '[') {
8406 result->kind = EXPR_UNARY_DELETE_ARRAY;
8407 expect(']', end_error);
8411 expression_t *const value = parse_sub_expression(PREC_CAST);
8412 result->unary.value = value;
8414 type_t *const type = skip_typeref(value->base.type);
8415 if (!is_type_pointer(type)) {
8416 errorf(&value->base.source_position,
8417 "operand of delete must have pointer type");
8418 } else if (warning.other &&
8419 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8420 warningf(&value->base.source_position,
8421 "deleting 'void*' is undefined");
8428 * Parse a throw expression
8429 * ISO/IEC 14882:1998(E) §15:1
8431 static expression_t *parse_throw(void)
8433 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8434 result->base.type = type_void;
8438 expression_t *value = NULL;
8439 switch (token.type) {
8441 value = parse_assignment_expression();
8442 /* ISO/IEC 14882:1998(E) §15.1:3 */
8443 type_t *const orig_type = value->base.type;
8444 type_t *const type = skip_typeref(orig_type);
8445 if (is_type_incomplete(type)) {
8446 errorf(&value->base.source_position,
8447 "cannot throw object of incomplete type '%T'", orig_type);
8448 } else if (is_type_pointer(type)) {
8449 type_t *const points_to = skip_typeref(type->pointer.points_to);
8450 if (is_type_incomplete(points_to) &&
8451 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8452 errorf(&value->base.source_position,
8453 "cannot throw pointer to incomplete type '%T'", orig_type);
8461 result->unary.value = value;
8466 static bool check_pointer_arithmetic(const source_position_t *source_position,
8467 type_t *pointer_type,
8468 type_t *orig_pointer_type)
8470 type_t *points_to = pointer_type->pointer.points_to;
8471 points_to = skip_typeref(points_to);
8473 if (is_type_incomplete(points_to)) {
8474 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8475 errorf(source_position,
8476 "arithmetic with pointer to incomplete type '%T' not allowed",
8479 } else if (warning.pointer_arith) {
8480 warningf(source_position,
8481 "pointer of type '%T' used in arithmetic",
8484 } else if (is_type_function(points_to)) {
8486 errorf(source_position,
8487 "arithmetic with pointer to function type '%T' not allowed",
8490 } else if (warning.pointer_arith) {
8491 warningf(source_position,
8492 "pointer to a function '%T' used in arithmetic",
8499 static bool is_lvalue(const expression_t *expression)
8501 /* TODO: doesn't seem to be consistent with §6.3.2.1 (1) */
8502 switch (expression->kind) {
8503 case EXPR_ARRAY_ACCESS:
8504 case EXPR_COMPOUND_LITERAL:
8505 case EXPR_REFERENCE:
8507 case EXPR_UNARY_DEREFERENCE:
8511 type_t *type = skip_typeref(expression->base.type);
8513 /* ISO/IEC 14882:1998(E) §3.10:3 */
8514 is_type_reference(type) ||
8515 /* Claim it is an lvalue, if the type is invalid. There was a parse
8516 * error before, which maybe prevented properly recognizing it as
8518 !is_type_valid(type);
8523 static void semantic_incdec(unary_expression_t *expression)
8525 type_t *const orig_type = expression->value->base.type;
8526 type_t *const type = skip_typeref(orig_type);
8527 if (is_type_pointer(type)) {
8528 if (!check_pointer_arithmetic(&expression->base.source_position,
8532 } else if (!is_type_real(type) && is_type_valid(type)) {
8533 /* TODO: improve error message */
8534 errorf(&expression->base.source_position,
8535 "operation needs an arithmetic or pointer type");
8538 if (!is_lvalue(expression->value)) {
8539 /* TODO: improve error message */
8540 errorf(&expression->base.source_position, "lvalue required as operand");
8542 expression->base.type = orig_type;
8545 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8547 type_t *const orig_type = expression->value->base.type;
8548 type_t *const type = skip_typeref(orig_type);
8549 if (!is_type_arithmetic(type)) {
8550 if (is_type_valid(type)) {
8551 /* TODO: improve error message */
8552 errorf(&expression->base.source_position,
8553 "operation needs an arithmetic type");
8558 expression->base.type = orig_type;
8561 static void semantic_unexpr_plus(unary_expression_t *expression)
8563 semantic_unexpr_arithmetic(expression);
8564 if (warning.traditional)
8565 warningf(&expression->base.source_position,
8566 "traditional C rejects the unary plus operator");
8569 static void semantic_not(unary_expression_t *expression)
8571 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8572 semantic_condition(expression->value, "operand of !");
8573 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8576 static void semantic_unexpr_integer(unary_expression_t *expression)
8578 type_t *const orig_type = expression->value->base.type;
8579 type_t *const type = skip_typeref(orig_type);
8580 if (!is_type_integer(type)) {
8581 if (is_type_valid(type)) {
8582 errorf(&expression->base.source_position,
8583 "operand of ~ must be of integer type");
8588 expression->base.type = orig_type;
8591 static void semantic_dereference(unary_expression_t *expression)
8593 type_t *const orig_type = expression->value->base.type;
8594 type_t *const type = skip_typeref(orig_type);
8595 if (!is_type_pointer(type)) {
8596 if (is_type_valid(type)) {
8597 errorf(&expression->base.source_position,
8598 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8603 type_t *result_type = type->pointer.points_to;
8604 result_type = automatic_type_conversion(result_type);
8605 expression->base.type = result_type;
8609 * Record that an address is taken (expression represents an lvalue).
8611 * @param expression the expression
8612 * @param may_be_register if true, the expression might be an register
8614 static void set_address_taken(expression_t *expression, bool may_be_register)
8616 if (expression->kind != EXPR_REFERENCE)
8619 entity_t *const entity = expression->reference.entity;
8621 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8624 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8625 && !may_be_register) {
8626 errorf(&expression->base.source_position,
8627 "address of register %s '%Y' requested",
8628 get_entity_kind_name(entity->kind), entity->base.symbol);
8631 if (entity->kind == ENTITY_VARIABLE) {
8632 entity->variable.address_taken = true;
8634 assert(entity->kind == ENTITY_PARAMETER);
8635 entity->parameter.address_taken = true;
8640 * Check the semantic of the address taken expression.
8642 static void semantic_take_addr(unary_expression_t *expression)
8644 expression_t *value = expression->value;
8645 value->base.type = revert_automatic_type_conversion(value);
8647 type_t *orig_type = value->base.type;
8648 type_t *type = skip_typeref(orig_type);
8649 if (!is_type_valid(type))
8653 if (!is_lvalue(value)) {
8654 errorf(&expression->base.source_position, "'&' requires an lvalue");
8656 if (type->kind == TYPE_BITFIELD) {
8657 errorf(&expression->base.source_position,
8658 "'&' not allowed on object with bitfield type '%T'",
8662 set_address_taken(value, false);
8664 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8667 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8668 static expression_t *parse_##unexpression_type(void) \
8670 expression_t *unary_expression \
8671 = allocate_expression_zero(unexpression_type); \
8673 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8675 sfunc(&unary_expression->unary); \
8677 return unary_expression; \
8680 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8681 semantic_unexpr_arithmetic)
8682 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8683 semantic_unexpr_plus)
8684 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8686 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8687 semantic_dereference)
8688 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8690 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8691 semantic_unexpr_integer)
8692 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8694 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8697 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8699 static expression_t *parse_##unexpression_type(expression_t *left) \
8701 expression_t *unary_expression \
8702 = allocate_expression_zero(unexpression_type); \
8704 unary_expression->unary.value = left; \
8706 sfunc(&unary_expression->unary); \
8708 return unary_expression; \
8711 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8712 EXPR_UNARY_POSTFIX_INCREMENT,
8714 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8715 EXPR_UNARY_POSTFIX_DECREMENT,
8718 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8720 /* TODO: handle complex + imaginary types */
8722 type_left = get_unqualified_type(type_left);
8723 type_right = get_unqualified_type(type_right);
8725 /* § 6.3.1.8 Usual arithmetic conversions */
8726 if (type_left == type_long_double || type_right == type_long_double) {
8727 return type_long_double;
8728 } else if (type_left == type_double || type_right == type_double) {
8730 } else if (type_left == type_float || type_right == type_float) {
8734 type_left = promote_integer(type_left);
8735 type_right = promote_integer(type_right);
8737 if (type_left == type_right)
8740 bool const signed_left = is_type_signed(type_left);
8741 bool const signed_right = is_type_signed(type_right);
8742 int const rank_left = get_rank(type_left);
8743 int const rank_right = get_rank(type_right);
8745 if (signed_left == signed_right)
8746 return rank_left >= rank_right ? type_left : type_right;
8755 u_rank = rank_right;
8756 u_type = type_right;
8758 s_rank = rank_right;
8759 s_type = type_right;
8764 if (u_rank >= s_rank)
8767 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8769 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8770 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8774 case ATOMIC_TYPE_INT: return type_unsigned_int;
8775 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8776 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8778 default: panic("invalid atomic type");
8783 * Check the semantic restrictions for a binary expression.
8785 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8787 expression_t *const left = expression->left;
8788 expression_t *const right = expression->right;
8789 type_t *const orig_type_left = left->base.type;
8790 type_t *const orig_type_right = right->base.type;
8791 type_t *const type_left = skip_typeref(orig_type_left);
8792 type_t *const type_right = skip_typeref(orig_type_right);
8794 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8795 /* TODO: improve error message */
8796 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8797 errorf(&expression->base.source_position,
8798 "operation needs arithmetic types");
8803 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8804 expression->left = create_implicit_cast(left, arithmetic_type);
8805 expression->right = create_implicit_cast(right, arithmetic_type);
8806 expression->base.type = arithmetic_type;
8809 static void warn_div_by_zero(binary_expression_t const *const expression)
8811 if (!warning.div_by_zero ||
8812 !is_type_integer(expression->base.type))
8815 expression_t const *const right = expression->right;
8816 /* The type of the right operand can be different for /= */
8817 if (is_type_integer(right->base.type) &&
8818 is_constant_expression(right) &&
8819 fold_constant(right) == 0) {
8820 warningf(&expression->base.source_position, "division by zero");
8825 * Check the semantic restrictions for a div/mod expression.
8827 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8828 semantic_binexpr_arithmetic(expression);
8829 warn_div_by_zero(expression);
8832 static void semantic_shift_op(binary_expression_t *expression)
8834 expression_t *const left = expression->left;
8835 expression_t *const right = expression->right;
8836 type_t *const orig_type_left = left->base.type;
8837 type_t *const orig_type_right = right->base.type;
8838 type_t * type_left = skip_typeref(orig_type_left);
8839 type_t * type_right = skip_typeref(orig_type_right);
8841 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8842 /* TODO: improve error message */
8843 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8844 errorf(&expression->base.source_position,
8845 "operands of shift operation must have integer types");
8850 type_left = promote_integer(type_left);
8851 type_right = promote_integer(type_right);
8853 expression->left = create_implicit_cast(left, type_left);
8854 expression->right = create_implicit_cast(right, type_right);
8855 expression->base.type = type_left;
8858 static void semantic_add(binary_expression_t *expression)
8860 expression_t *const left = expression->left;
8861 expression_t *const right = expression->right;
8862 type_t *const orig_type_left = left->base.type;
8863 type_t *const orig_type_right = right->base.type;
8864 type_t *const type_left = skip_typeref(orig_type_left);
8865 type_t *const type_right = skip_typeref(orig_type_right);
8868 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8869 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8870 expression->left = create_implicit_cast(left, arithmetic_type);
8871 expression->right = create_implicit_cast(right, arithmetic_type);
8872 expression->base.type = arithmetic_type;
8874 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8875 check_pointer_arithmetic(&expression->base.source_position,
8876 type_left, orig_type_left);
8877 expression->base.type = type_left;
8878 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8879 check_pointer_arithmetic(&expression->base.source_position,
8880 type_right, orig_type_right);
8881 expression->base.type = type_right;
8882 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8883 errorf(&expression->base.source_position,
8884 "invalid operands to binary + ('%T', '%T')",
8885 orig_type_left, orig_type_right);
8889 static void semantic_sub(binary_expression_t *expression)
8891 expression_t *const left = expression->left;
8892 expression_t *const right = expression->right;
8893 type_t *const orig_type_left = left->base.type;
8894 type_t *const orig_type_right = right->base.type;
8895 type_t *const type_left = skip_typeref(orig_type_left);
8896 type_t *const type_right = skip_typeref(orig_type_right);
8897 source_position_t const *const pos = &expression->base.source_position;
8900 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8901 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8902 expression->left = create_implicit_cast(left, arithmetic_type);
8903 expression->right = create_implicit_cast(right, arithmetic_type);
8904 expression->base.type = arithmetic_type;
8906 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8907 check_pointer_arithmetic(&expression->base.source_position,
8908 type_left, orig_type_left);
8909 expression->base.type = type_left;
8910 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8911 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8912 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8913 if (!types_compatible(unqual_left, unqual_right)) {
8915 "subtracting pointers to incompatible types '%T' and '%T'",
8916 orig_type_left, orig_type_right);
8917 } else if (!is_type_object(unqual_left)) {
8918 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8919 errorf(pos, "subtracting pointers to non-object types '%T'",
8921 } else if (warning.other) {
8922 warningf(pos, "subtracting pointers to void");
8925 expression->base.type = type_ptrdiff_t;
8926 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8927 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8928 orig_type_left, orig_type_right);
8932 static void warn_string_literal_address(expression_t const* expr)
8934 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8935 expr = expr->unary.value;
8936 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8938 expr = expr->unary.value;
8941 if (expr->kind == EXPR_STRING_LITERAL ||
8942 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8943 warningf(&expr->base.source_position,
8944 "comparison with string literal results in unspecified behaviour");
8948 static void warn_comparison_in_comparison(const expression_t *const expr)
8950 if (expr->base.parenthesized)
8952 switch (expr->base.kind) {
8953 case EXPR_BINARY_LESS:
8954 case EXPR_BINARY_GREATER:
8955 case EXPR_BINARY_LESSEQUAL:
8956 case EXPR_BINARY_GREATEREQUAL:
8957 case EXPR_BINARY_NOTEQUAL:
8958 case EXPR_BINARY_EQUAL:
8959 warningf(&expr->base.source_position,
8960 "comparisons like 'x <= y < z' do not have their mathematical meaning");
8968 * Check the semantics of comparison expressions.
8970 * @param expression The expression to check.
8972 static void semantic_comparison(binary_expression_t *expression)
8974 expression_t *left = expression->left;
8975 expression_t *right = expression->right;
8977 if (warning.address) {
8978 warn_string_literal_address(left);
8979 warn_string_literal_address(right);
8981 expression_t const* const func_left = get_reference_address(left);
8982 if (func_left != NULL && is_null_pointer_constant(right)) {
8983 warningf(&expression->base.source_position,
8984 "the address of '%Y' will never be NULL",
8985 func_left->reference.entity->base.symbol);
8988 expression_t const* const func_right = get_reference_address(right);
8989 if (func_right != NULL && is_null_pointer_constant(right)) {
8990 warningf(&expression->base.source_position,
8991 "the address of '%Y' will never be NULL",
8992 func_right->reference.entity->base.symbol);
8996 if (warning.parentheses) {
8997 warn_comparison_in_comparison(left);
8998 warn_comparison_in_comparison(right);
9001 type_t *orig_type_left = left->base.type;
9002 type_t *orig_type_right = right->base.type;
9003 type_t *type_left = skip_typeref(orig_type_left);
9004 type_t *type_right = skip_typeref(orig_type_right);
9006 /* TODO non-arithmetic types */
9007 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9008 /* test for signed vs unsigned compares */
9009 if (warning.sign_compare &&
9010 (expression->base.kind != EXPR_BINARY_EQUAL &&
9011 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
9012 (is_type_signed(type_left) != is_type_signed(type_right))) {
9014 /* check if 1 of the operands is a constant, in this case we just
9015 * check wether we can safely represent the resulting constant in
9016 * the type of the other operand. */
9017 expression_t *const_expr = NULL;
9018 expression_t *other_expr = NULL;
9020 if (is_constant_expression(left)) {
9023 } else if (is_constant_expression(right)) {
9028 if (const_expr != NULL) {
9029 type_t *other_type = skip_typeref(other_expr->base.type);
9030 long val = fold_constant(const_expr);
9031 /* TODO: check if val can be represented by other_type */
9035 warningf(&expression->base.source_position,
9036 "comparison between signed and unsigned");
9038 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9039 expression->left = create_implicit_cast(left, arithmetic_type);
9040 expression->right = create_implicit_cast(right, arithmetic_type);
9041 expression->base.type = arithmetic_type;
9042 if (warning.float_equal &&
9043 (expression->base.kind == EXPR_BINARY_EQUAL ||
9044 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
9045 is_type_float(arithmetic_type)) {
9046 warningf(&expression->base.source_position,
9047 "comparing floating point with == or != is unsafe");
9049 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
9050 /* TODO check compatibility */
9051 } else if (is_type_pointer(type_left)) {
9052 expression->right = create_implicit_cast(right, type_left);
9053 } else if (is_type_pointer(type_right)) {
9054 expression->left = create_implicit_cast(left, type_right);
9055 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9056 type_error_incompatible("invalid operands in comparison",
9057 &expression->base.source_position,
9058 type_left, type_right);
9060 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9064 * Checks if a compound type has constant fields.
9066 static bool has_const_fields(const compound_type_t *type)
9068 compound_t *compound = type->compound;
9069 entity_t *entry = compound->members.entities;
9071 for (; entry != NULL; entry = entry->base.next) {
9072 if (!is_declaration(entry))
9075 const type_t *decl_type = skip_typeref(entry->declaration.type);
9076 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
9083 static bool is_valid_assignment_lhs(expression_t const* const left)
9085 type_t *const orig_type_left = revert_automatic_type_conversion(left);
9086 type_t *const type_left = skip_typeref(orig_type_left);
9088 if (!is_lvalue(left)) {
9089 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
9094 if (left->kind == EXPR_REFERENCE
9095 && left->reference.entity->kind == ENTITY_FUNCTION) {
9096 errorf(HERE, "cannot assign to function '%E'", left);
9100 if (is_type_array(type_left)) {
9101 errorf(HERE, "cannot assign to array '%E'", left);
9104 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
9105 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
9109 if (is_type_incomplete(type_left)) {
9110 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
9111 left, orig_type_left);
9114 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
9115 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
9116 left, orig_type_left);
9123 static void semantic_arithmetic_assign(binary_expression_t *expression)
9125 expression_t *left = expression->left;
9126 expression_t *right = expression->right;
9127 type_t *orig_type_left = left->base.type;
9128 type_t *orig_type_right = right->base.type;
9130 if (!is_valid_assignment_lhs(left))
9133 type_t *type_left = skip_typeref(orig_type_left);
9134 type_t *type_right = skip_typeref(orig_type_right);
9136 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
9137 /* TODO: improve error message */
9138 if (is_type_valid(type_left) && is_type_valid(type_right)) {
9139 errorf(&expression->base.source_position,
9140 "operation needs arithmetic types");
9145 /* combined instructions are tricky. We can't create an implicit cast on
9146 * the left side, because we need the uncasted form for the store.
9147 * The ast2firm pass has to know that left_type must be right_type
9148 * for the arithmetic operation and create a cast by itself */
9149 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9150 expression->right = create_implicit_cast(right, arithmetic_type);
9151 expression->base.type = type_left;
9154 static void semantic_divmod_assign(binary_expression_t *expression)
9156 semantic_arithmetic_assign(expression);
9157 warn_div_by_zero(expression);
9160 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
9162 expression_t *const left = expression->left;
9163 expression_t *const right = expression->right;
9164 type_t *const orig_type_left = left->base.type;
9165 type_t *const orig_type_right = right->base.type;
9166 type_t *const type_left = skip_typeref(orig_type_left);
9167 type_t *const type_right = skip_typeref(orig_type_right);
9169 if (!is_valid_assignment_lhs(left))
9172 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9173 /* combined instructions are tricky. We can't create an implicit cast on
9174 * the left side, because we need the uncasted form for the store.
9175 * The ast2firm pass has to know that left_type must be right_type
9176 * for the arithmetic operation and create a cast by itself */
9177 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
9178 expression->right = create_implicit_cast(right, arithmetic_type);
9179 expression->base.type = type_left;
9180 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9181 check_pointer_arithmetic(&expression->base.source_position,
9182 type_left, orig_type_left);
9183 expression->base.type = type_left;
9184 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9185 errorf(&expression->base.source_position,
9186 "incompatible types '%T' and '%T' in assignment",
9187 orig_type_left, orig_type_right);
9191 static void warn_logical_and_within_or(const expression_t *const expr)
9193 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
9195 if (expr->base.parenthesized)
9197 warningf(&expr->base.source_position,
9198 "suggest parentheses around && within ||");
9202 * Check the semantic restrictions of a logical expression.
9204 static void semantic_logical_op(binary_expression_t *expression)
9206 /* §6.5.13:2 Each of the operands shall have scalar type.
9207 * §6.5.14:2 Each of the operands shall have scalar type. */
9208 semantic_condition(expression->left, "left operand of logical operator");
9209 semantic_condition(expression->right, "right operand of logical operator");
9210 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
9211 warning.parentheses) {
9212 warn_logical_and_within_or(expression->left);
9213 warn_logical_and_within_or(expression->right);
9215 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9219 * Check the semantic restrictions of a binary assign expression.
9221 static void semantic_binexpr_assign(binary_expression_t *expression)
9223 expression_t *left = expression->left;
9224 type_t *orig_type_left = left->base.type;
9226 if (!is_valid_assignment_lhs(left))
9229 assign_error_t error = semantic_assign(orig_type_left, expression->right);
9230 report_assign_error(error, orig_type_left, expression->right,
9231 "assignment", &left->base.source_position);
9232 expression->right = create_implicit_cast(expression->right, orig_type_left);
9233 expression->base.type = orig_type_left;
9237 * Determine if the outermost operation (or parts thereof) of the given
9238 * expression has no effect in order to generate a warning about this fact.
9239 * Therefore in some cases this only examines some of the operands of the
9240 * expression (see comments in the function and examples below).
9242 * f() + 23; // warning, because + has no effect
9243 * x || f(); // no warning, because x controls execution of f()
9244 * x ? y : f(); // warning, because y has no effect
9245 * (void)x; // no warning to be able to suppress the warning
9246 * This function can NOT be used for an "expression has definitely no effect"-
9248 static bool expression_has_effect(const expression_t *const expr)
9250 switch (expr->kind) {
9251 case EXPR_UNKNOWN: break;
9252 case EXPR_INVALID: return true; /* do NOT warn */
9253 case EXPR_REFERENCE: return false;
9254 case EXPR_REFERENCE_ENUM_VALUE: return false;
9255 /* suppress the warning for microsoft __noop operations */
9256 case EXPR_CONST: return expr->conste.is_ms_noop;
9257 case EXPR_CHARACTER_CONSTANT: return false;
9258 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
9259 case EXPR_STRING_LITERAL: return false;
9260 case EXPR_WIDE_STRING_LITERAL: return false;
9261 case EXPR_LABEL_ADDRESS: return false;
9264 const call_expression_t *const call = &expr->call;
9265 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
9268 switch (call->function->builtin_symbol.symbol->ID) {
9269 case T___builtin_va_end: return true;
9270 default: return false;
9274 /* Generate the warning if either the left or right hand side of a
9275 * conditional expression has no effect */
9276 case EXPR_CONDITIONAL: {
9277 const conditional_expression_t *const cond = &expr->conditional;
9279 expression_has_effect(cond->true_expression) &&
9280 expression_has_effect(cond->false_expression);
9283 case EXPR_SELECT: return false;
9284 case EXPR_ARRAY_ACCESS: return false;
9285 case EXPR_SIZEOF: return false;
9286 case EXPR_CLASSIFY_TYPE: return false;
9287 case EXPR_ALIGNOF: return false;
9289 case EXPR_FUNCNAME: return false;
9290 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
9291 case EXPR_BUILTIN_CONSTANT_P: return false;
9292 case EXPR_BUILTIN_PREFETCH: return true;
9293 case EXPR_OFFSETOF: return false;
9294 case EXPR_VA_START: return true;
9295 case EXPR_VA_ARG: return true;
9296 case EXPR_STATEMENT: return true; // TODO
9297 case EXPR_COMPOUND_LITERAL: return false;
9299 case EXPR_UNARY_NEGATE: return false;
9300 case EXPR_UNARY_PLUS: return false;
9301 case EXPR_UNARY_BITWISE_NEGATE: return false;
9302 case EXPR_UNARY_NOT: return false;
9303 case EXPR_UNARY_DEREFERENCE: return false;
9304 case EXPR_UNARY_TAKE_ADDRESS: return false;
9305 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
9306 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
9307 case EXPR_UNARY_PREFIX_INCREMENT: return true;
9308 case EXPR_UNARY_PREFIX_DECREMENT: return true;
9310 /* Treat void casts as if they have an effect in order to being able to
9311 * suppress the warning */
9312 case EXPR_UNARY_CAST: {
9313 type_t *const type = skip_typeref(expr->base.type);
9314 return is_type_atomic(type, ATOMIC_TYPE_VOID);
9317 case EXPR_UNARY_CAST_IMPLICIT: return true;
9318 case EXPR_UNARY_ASSUME: return true;
9319 case EXPR_UNARY_DELETE: return true;
9320 case EXPR_UNARY_DELETE_ARRAY: return true;
9321 case EXPR_UNARY_THROW: return true;
9323 case EXPR_BINARY_ADD: return false;
9324 case EXPR_BINARY_SUB: return false;
9325 case EXPR_BINARY_MUL: return false;
9326 case EXPR_BINARY_DIV: return false;
9327 case EXPR_BINARY_MOD: return false;
9328 case EXPR_BINARY_EQUAL: return false;
9329 case EXPR_BINARY_NOTEQUAL: return false;
9330 case EXPR_BINARY_LESS: return false;
9331 case EXPR_BINARY_LESSEQUAL: return false;
9332 case EXPR_BINARY_GREATER: return false;
9333 case EXPR_BINARY_GREATEREQUAL: return false;
9334 case EXPR_BINARY_BITWISE_AND: return false;
9335 case EXPR_BINARY_BITWISE_OR: return false;
9336 case EXPR_BINARY_BITWISE_XOR: return false;
9337 case EXPR_BINARY_SHIFTLEFT: return false;
9338 case EXPR_BINARY_SHIFTRIGHT: return false;
9339 case EXPR_BINARY_ASSIGN: return true;
9340 case EXPR_BINARY_MUL_ASSIGN: return true;
9341 case EXPR_BINARY_DIV_ASSIGN: return true;
9342 case EXPR_BINARY_MOD_ASSIGN: return true;
9343 case EXPR_BINARY_ADD_ASSIGN: return true;
9344 case EXPR_BINARY_SUB_ASSIGN: return true;
9345 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
9346 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
9347 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9348 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9349 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
9351 /* Only examine the right hand side of && and ||, because the left hand
9352 * side already has the effect of controlling the execution of the right
9354 case EXPR_BINARY_LOGICAL_AND:
9355 case EXPR_BINARY_LOGICAL_OR:
9356 /* Only examine the right hand side of a comma expression, because the left
9357 * hand side has a separate warning */
9358 case EXPR_BINARY_COMMA:
9359 return expression_has_effect(expr->binary.right);
9361 case EXPR_BINARY_ISGREATER: return false;
9362 case EXPR_BINARY_ISGREATEREQUAL: return false;
9363 case EXPR_BINARY_ISLESS: return false;
9364 case EXPR_BINARY_ISLESSEQUAL: return false;
9365 case EXPR_BINARY_ISLESSGREATER: return false;
9366 case EXPR_BINARY_ISUNORDERED: return false;
9369 internal_errorf(HERE, "unexpected expression");
9372 static void semantic_comma(binary_expression_t *expression)
9374 if (warning.unused_value) {
9375 const expression_t *const left = expression->left;
9376 if (!expression_has_effect(left)) {
9377 warningf(&left->base.source_position,
9378 "left-hand operand of comma expression has no effect");
9381 expression->base.type = expression->right->base.type;
9385 * @param prec_r precedence of the right operand
9387 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9388 static expression_t *parse_##binexpression_type(expression_t *left) \
9390 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9391 binexpr->binary.left = left; \
9394 expression_t *right = parse_sub_expression(prec_r); \
9396 binexpr->binary.right = right; \
9397 sfunc(&binexpr->binary); \
9402 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9403 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9404 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9405 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9406 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9407 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9408 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9409 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9410 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9411 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9412 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9413 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9414 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9415 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9416 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9417 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9418 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9419 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9420 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9421 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9422 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9423 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9424 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9425 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9426 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9427 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9428 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9429 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9430 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9431 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9434 static expression_t *parse_sub_expression(precedence_t precedence)
9436 if (token.type < 0) {
9437 return expected_expression_error();
9440 expression_parser_function_t *parser
9441 = &expression_parsers[token.type];
9442 source_position_t source_position = token.source_position;
9445 if (parser->parser != NULL) {
9446 left = parser->parser();
9448 left = parse_primary_expression();
9450 assert(left != NULL);
9451 left->base.source_position = source_position;
9454 if (token.type < 0) {
9455 return expected_expression_error();
9458 parser = &expression_parsers[token.type];
9459 if (parser->infix_parser == NULL)
9461 if (parser->infix_precedence < precedence)
9464 left = parser->infix_parser(left);
9466 assert(left != NULL);
9467 assert(left->kind != EXPR_UNKNOWN);
9468 left->base.source_position = source_position;
9475 * Parse an expression.
9477 static expression_t *parse_expression(void)
9479 return parse_sub_expression(PREC_EXPRESSION);
9483 * Register a parser for a prefix-like operator.
9485 * @param parser the parser function
9486 * @param token_type the token type of the prefix token
9488 static void register_expression_parser(parse_expression_function parser,
9491 expression_parser_function_t *entry = &expression_parsers[token_type];
9493 if (entry->parser != NULL) {
9494 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9495 panic("trying to register multiple expression parsers for a token");
9497 entry->parser = parser;
9501 * Register a parser for an infix operator with given precedence.
9503 * @param parser the parser function
9504 * @param token_type the token type of the infix operator
9505 * @param precedence the precedence of the operator
9507 static void register_infix_parser(parse_expression_infix_function parser,
9508 int token_type, unsigned precedence)
9510 expression_parser_function_t *entry = &expression_parsers[token_type];
9512 if (entry->infix_parser != NULL) {
9513 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9514 panic("trying to register multiple infix expression parsers for a "
9517 entry->infix_parser = parser;
9518 entry->infix_precedence = precedence;
9522 * Initialize the expression parsers.
9524 static void init_expression_parsers(void)
9526 memset(&expression_parsers, 0, sizeof(expression_parsers));
9528 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9529 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9530 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9531 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9532 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9533 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9534 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9535 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9536 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9537 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9538 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9539 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9540 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9541 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9542 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9543 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9544 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9545 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9546 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9547 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9548 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9549 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9550 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9551 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9552 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9553 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9554 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9555 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9556 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9557 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9558 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9559 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9560 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9561 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9562 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9563 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9564 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9566 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9567 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9568 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9569 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9570 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9571 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9572 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9573 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9574 register_expression_parser(parse_sizeof, T_sizeof);
9575 register_expression_parser(parse_alignof, T___alignof__);
9576 register_expression_parser(parse_extension, T___extension__);
9577 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9578 register_expression_parser(parse_delete, T_delete);
9579 register_expression_parser(parse_throw, T_throw);
9583 * Parse a asm statement arguments specification.
9585 static asm_argument_t *parse_asm_arguments(bool is_out)
9587 asm_argument_t *result = NULL;
9588 asm_argument_t **anchor = &result;
9590 while (token.type == T_STRING_LITERAL || token.type == '[') {
9591 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9592 memset(argument, 0, sizeof(argument[0]));
9594 if (token.type == '[') {
9596 if (token.type != T_IDENTIFIER) {
9597 parse_error_expected("while parsing asm argument",
9598 T_IDENTIFIER, NULL);
9601 argument->symbol = token.v.symbol;
9603 expect(']', end_error);
9606 argument->constraints = parse_string_literals();
9607 expect('(', end_error);
9608 add_anchor_token(')');
9609 expression_t *expression = parse_expression();
9610 rem_anchor_token(')');
9612 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9613 * change size or type representation (e.g. int -> long is ok, but
9614 * int -> float is not) */
9615 if (expression->kind == EXPR_UNARY_CAST) {
9616 type_t *const type = expression->base.type;
9617 type_kind_t const kind = type->kind;
9618 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9621 if (kind == TYPE_ATOMIC) {
9622 atomic_type_kind_t const akind = type->atomic.akind;
9623 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9624 size = get_atomic_type_size(akind);
9626 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9627 size = get_atomic_type_size(get_intptr_kind());
9631 expression_t *const value = expression->unary.value;
9632 type_t *const value_type = value->base.type;
9633 type_kind_t const value_kind = value_type->kind;
9635 unsigned value_flags;
9636 unsigned value_size;
9637 if (value_kind == TYPE_ATOMIC) {
9638 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9639 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9640 value_size = get_atomic_type_size(value_akind);
9641 } else if (value_kind == TYPE_POINTER) {
9642 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9643 value_size = get_atomic_type_size(get_intptr_kind());
9648 if (value_flags != flags || value_size != size)
9652 } while (expression->kind == EXPR_UNARY_CAST);
9656 if (!is_lvalue(expression)) {
9657 errorf(&expression->base.source_position,
9658 "asm output argument is not an lvalue");
9661 if (argument->constraints.begin[0] == '+')
9662 mark_vars_read(expression, NULL);
9664 mark_vars_read(expression, NULL);
9666 argument->expression = expression;
9667 expect(')', end_error);
9669 set_address_taken(expression, true);
9672 anchor = &argument->next;
9674 if (token.type != ',')
9685 * Parse a asm statement clobber specification.
9687 static asm_clobber_t *parse_asm_clobbers(void)
9689 asm_clobber_t *result = NULL;
9690 asm_clobber_t *last = NULL;
9692 while (token.type == T_STRING_LITERAL) {
9693 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9694 clobber->clobber = parse_string_literals();
9697 last->next = clobber;
9703 if (token.type != ',')
9712 * Parse an asm statement.
9714 static statement_t *parse_asm_statement(void)
9716 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9717 asm_statement_t *asm_statement = &statement->asms;
9721 if (token.type == T_volatile) {
9723 asm_statement->is_volatile = true;
9726 expect('(', end_error);
9727 add_anchor_token(')');
9728 add_anchor_token(':');
9729 asm_statement->asm_text = parse_string_literals();
9731 if (token.type != ':') {
9732 rem_anchor_token(':');
9737 asm_statement->outputs = parse_asm_arguments(true);
9738 if (token.type != ':') {
9739 rem_anchor_token(':');
9744 asm_statement->inputs = parse_asm_arguments(false);
9745 if (token.type != ':') {
9746 rem_anchor_token(':');
9749 rem_anchor_token(':');
9752 asm_statement->clobbers = parse_asm_clobbers();
9755 rem_anchor_token(')');
9756 expect(')', end_error);
9757 expect(';', end_error);
9759 if (asm_statement->outputs == NULL) {
9760 /* GCC: An 'asm' instruction without any output operands will be treated
9761 * identically to a volatile 'asm' instruction. */
9762 asm_statement->is_volatile = true;
9767 return create_invalid_statement();
9771 * Parse a case statement.
9773 static statement_t *parse_case_statement(void)
9775 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9776 source_position_t *const pos = &statement->base.source_position;
9780 expression_t *const expression = parse_expression();
9781 statement->case_label.expression = expression;
9782 if (!is_constant_expression(expression)) {
9783 /* This check does not prevent the error message in all cases of an
9784 * prior error while parsing the expression. At least it catches the
9785 * common case of a mistyped enum entry. */
9786 if (is_type_valid(skip_typeref(expression->base.type))) {
9787 errorf(pos, "case label does not reduce to an integer constant");
9789 statement->case_label.is_bad = true;
9791 long const val = fold_constant(expression);
9792 statement->case_label.first_case = val;
9793 statement->case_label.last_case = val;
9797 if (token.type == T_DOTDOTDOT) {
9799 expression_t *const end_range = parse_expression();
9800 statement->case_label.end_range = end_range;
9801 if (!is_constant_expression(end_range)) {
9802 /* This check does not prevent the error message in all cases of an
9803 * prior error while parsing the expression. At least it catches the
9804 * common case of a mistyped enum entry. */
9805 if (is_type_valid(skip_typeref(end_range->base.type))) {
9806 errorf(pos, "case range does not reduce to an integer constant");
9808 statement->case_label.is_bad = true;
9810 long const val = fold_constant(end_range);
9811 statement->case_label.last_case = val;
9813 if (warning.other && val < statement->case_label.first_case) {
9814 statement->case_label.is_empty_range = true;
9815 warningf(pos, "empty range specified");
9821 PUSH_PARENT(statement);
9823 expect(':', end_error);
9826 if (current_switch != NULL) {
9827 if (! statement->case_label.is_bad) {
9828 /* Check for duplicate case values */
9829 case_label_statement_t *c = &statement->case_label;
9830 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9831 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9834 if (c->last_case < l->first_case || c->first_case > l->last_case)
9837 errorf(pos, "duplicate case value (previously used %P)",
9838 &l->base.source_position);
9842 /* link all cases into the switch statement */
9843 if (current_switch->last_case == NULL) {
9844 current_switch->first_case = &statement->case_label;
9846 current_switch->last_case->next = &statement->case_label;
9848 current_switch->last_case = &statement->case_label;
9850 errorf(pos, "case label not within a switch statement");
9853 statement_t *const inner_stmt = parse_statement();
9854 statement->case_label.statement = inner_stmt;
9855 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9856 errorf(&inner_stmt->base.source_position, "declaration after case label");
9864 * Parse a default statement.
9866 static statement_t *parse_default_statement(void)
9868 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9872 PUSH_PARENT(statement);
9874 expect(':', end_error);
9875 if (current_switch != NULL) {
9876 const case_label_statement_t *def_label = current_switch->default_label;
9877 if (def_label != NULL) {
9878 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9879 &def_label->base.source_position);
9881 current_switch->default_label = &statement->case_label;
9883 /* link all cases into the switch statement */
9884 if (current_switch->last_case == NULL) {
9885 current_switch->first_case = &statement->case_label;
9887 current_switch->last_case->next = &statement->case_label;
9889 current_switch->last_case = &statement->case_label;
9892 errorf(&statement->base.source_position,
9893 "'default' label not within a switch statement");
9896 statement_t *const inner_stmt = parse_statement();
9897 statement->case_label.statement = inner_stmt;
9898 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9899 errorf(&inner_stmt->base.source_position, "declaration after default label");
9906 return create_invalid_statement();
9910 * Parse a label statement.
9912 static statement_t *parse_label_statement(void)
9914 assert(token.type == T_IDENTIFIER);
9915 symbol_t *symbol = token.v.symbol;
9916 label_t *label = get_label(symbol);
9918 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9919 statement->label.label = label;
9923 PUSH_PARENT(statement);
9925 /* if statement is already set then the label is defined twice,
9926 * otherwise it was just mentioned in a goto/local label declaration so far
9928 if (label->statement != NULL) {
9929 errorf(HERE, "duplicate label '%Y' (declared %P)",
9930 symbol, &label->base.source_position);
9932 label->base.source_position = token.source_position;
9933 label->statement = statement;
9938 if (token.type == '}') {
9939 /* TODO only warn? */
9940 if (warning.other && false) {
9941 warningf(HERE, "label at end of compound statement");
9942 statement->label.statement = create_empty_statement();
9944 errorf(HERE, "label at end of compound statement");
9945 statement->label.statement = create_invalid_statement();
9947 } else if (token.type == ';') {
9948 /* Eat an empty statement here, to avoid the warning about an empty
9949 * statement after a label. label:; is commonly used to have a label
9950 * before a closing brace. */
9951 statement->label.statement = create_empty_statement();
9954 statement_t *const inner_stmt = parse_statement();
9955 statement->label.statement = inner_stmt;
9956 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9957 errorf(&inner_stmt->base.source_position, "declaration after label");
9961 /* remember the labels in a list for later checking */
9962 *label_anchor = &statement->label;
9963 label_anchor = &statement->label.next;
9970 * Parse an if statement.
9972 static statement_t *parse_if(void)
9974 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9978 PUSH_PARENT(statement);
9980 add_anchor_token('{');
9982 expect('(', end_error);
9983 add_anchor_token(')');
9984 expression_t *const expr = parse_expression();
9985 statement->ifs.condition = expr;
9986 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9988 semantic_condition(expr, "condition of 'if'-statment");
9989 mark_vars_read(expr, NULL);
9990 rem_anchor_token(')');
9991 expect(')', end_error);
9994 rem_anchor_token('{');
9996 add_anchor_token(T_else);
9997 statement_t *const true_stmt = parse_statement();
9998 statement->ifs.true_statement = true_stmt;
9999 rem_anchor_token(T_else);
10001 if (token.type == T_else) {
10003 statement->ifs.false_statement = parse_statement();
10004 } else if (warning.parentheses &&
10005 true_stmt->kind == STATEMENT_IF &&
10006 true_stmt->ifs.false_statement != NULL) {
10007 warningf(&true_stmt->base.source_position,
10008 "suggest explicit braces to avoid ambiguous 'else'");
10016 * Check that all enums are handled in a switch.
10018 * @param statement the switch statement to check
10020 static void check_enum_cases(const switch_statement_t *statement) {
10021 const type_t *type = skip_typeref(statement->expression->base.type);
10022 if (! is_type_enum(type))
10024 const enum_type_t *enumt = &type->enumt;
10026 /* if we have a default, no warnings */
10027 if (statement->default_label != NULL)
10030 /* FIXME: calculation of value should be done while parsing */
10031 /* TODO: quadratic algorithm here. Change to an n log n one */
10032 long last_value = -1;
10033 const entity_t *entry = enumt->enume->base.next;
10034 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
10035 entry = entry->base.next) {
10036 const expression_t *expression = entry->enum_value.value;
10037 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
10038 bool found = false;
10039 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
10040 if (l->expression == NULL)
10042 if (l->first_case <= value && value <= l->last_case) {
10048 warningf(&statement->base.source_position,
10049 "enumeration value '%Y' not handled in switch",
10050 entry->base.symbol);
10052 last_value = value;
10057 * Parse a switch statement.
10059 static statement_t *parse_switch(void)
10061 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
10065 PUSH_PARENT(statement);
10067 expect('(', end_error);
10068 add_anchor_token(')');
10069 expression_t *const expr = parse_expression();
10070 mark_vars_read(expr, NULL);
10071 type_t * type = skip_typeref(expr->base.type);
10072 if (is_type_integer(type)) {
10073 type = promote_integer(type);
10074 if (warning.traditional) {
10075 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
10076 warningf(&expr->base.source_position,
10077 "'%T' switch expression not converted to '%T' in ISO C",
10081 } else if (is_type_valid(type)) {
10082 errorf(&expr->base.source_position,
10083 "switch quantity is not an integer, but '%T'", type);
10084 type = type_error_type;
10086 statement->switchs.expression = create_implicit_cast(expr, type);
10087 expect(')', end_error);
10088 rem_anchor_token(')');
10090 switch_statement_t *rem = current_switch;
10091 current_switch = &statement->switchs;
10092 statement->switchs.body = parse_statement();
10093 current_switch = rem;
10095 if (warning.switch_default &&
10096 statement->switchs.default_label == NULL) {
10097 warningf(&statement->base.source_position, "switch has no default case");
10099 if (warning.switch_enum)
10100 check_enum_cases(&statement->switchs);
10106 return create_invalid_statement();
10109 static statement_t *parse_loop_body(statement_t *const loop)
10111 statement_t *const rem = current_loop;
10112 current_loop = loop;
10114 statement_t *const body = parse_statement();
10116 current_loop = rem;
10121 * Parse a while statement.
10123 static statement_t *parse_while(void)
10125 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
10129 PUSH_PARENT(statement);
10131 expect('(', end_error);
10132 add_anchor_token(')');
10133 expression_t *const cond = parse_expression();
10134 statement->whiles.condition = cond;
10135 /* §6.8.5:2 The controlling expression of an iteration statement shall
10136 * have scalar type. */
10137 semantic_condition(cond, "condition of 'while'-statement");
10138 mark_vars_read(cond, NULL);
10139 rem_anchor_token(')');
10140 expect(')', end_error);
10142 statement->whiles.body = parse_loop_body(statement);
10148 return create_invalid_statement();
10152 * Parse a do statement.
10154 static statement_t *parse_do(void)
10156 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
10160 PUSH_PARENT(statement);
10162 add_anchor_token(T_while);
10163 statement->do_while.body = parse_loop_body(statement);
10164 rem_anchor_token(T_while);
10166 expect(T_while, end_error);
10167 expect('(', end_error);
10168 add_anchor_token(')');
10169 expression_t *const cond = parse_expression();
10170 statement->do_while.condition = cond;
10171 /* §6.8.5:2 The controlling expression of an iteration statement shall
10172 * have scalar type. */
10173 semantic_condition(cond, "condition of 'do-while'-statement");
10174 mark_vars_read(cond, NULL);
10175 rem_anchor_token(')');
10176 expect(')', end_error);
10177 expect(';', end_error);
10183 return create_invalid_statement();
10187 * Parse a for statement.
10189 static statement_t *parse_for(void)
10191 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
10195 expect('(', end_error1);
10196 add_anchor_token(')');
10198 PUSH_PARENT(statement);
10200 size_t const top = environment_top();
10201 scope_t *old_scope = scope_push(&statement->fors.scope);
10203 if (token.type == ';') {
10205 } else if (is_declaration_specifier(&token, false)) {
10206 parse_declaration(record_entity, DECL_FLAGS_NONE);
10208 add_anchor_token(';');
10209 expression_t *const init = parse_expression();
10210 statement->fors.initialisation = init;
10211 mark_vars_read(init, ENT_ANY);
10212 if (warning.unused_value && !expression_has_effect(init)) {
10213 warningf(&init->base.source_position,
10214 "initialisation of 'for'-statement has no effect");
10216 rem_anchor_token(';');
10217 expect(';', end_error2);
10220 if (token.type != ';') {
10221 add_anchor_token(';');
10222 expression_t *const cond = parse_expression();
10223 statement->fors.condition = cond;
10224 /* §6.8.5:2 The controlling expression of an iteration statement
10225 * shall have scalar type. */
10226 semantic_condition(cond, "condition of 'for'-statement");
10227 mark_vars_read(cond, NULL);
10228 rem_anchor_token(';');
10230 expect(';', end_error2);
10231 if (token.type != ')') {
10232 expression_t *const step = parse_expression();
10233 statement->fors.step = step;
10234 mark_vars_read(step, ENT_ANY);
10235 if (warning.unused_value && !expression_has_effect(step)) {
10236 warningf(&step->base.source_position,
10237 "step of 'for'-statement has no effect");
10240 expect(')', end_error2);
10241 rem_anchor_token(')');
10242 statement->fors.body = parse_loop_body(statement);
10244 assert(current_scope == &statement->fors.scope);
10245 scope_pop(old_scope);
10246 environment_pop_to(top);
10253 rem_anchor_token(')');
10254 assert(current_scope == &statement->fors.scope);
10255 scope_pop(old_scope);
10256 environment_pop_to(top);
10260 return create_invalid_statement();
10264 * Parse a goto statement.
10266 static statement_t *parse_goto(void)
10268 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
10271 if (GNU_MODE && token.type == '*') {
10273 expression_t *expression = parse_expression();
10274 mark_vars_read(expression, NULL);
10276 /* Argh: although documentation says the expression must be of type void*,
10277 * gcc accepts anything that can be casted into void* without error */
10278 type_t *type = expression->base.type;
10280 if (type != type_error_type) {
10281 if (!is_type_pointer(type) && !is_type_integer(type)) {
10282 errorf(&expression->base.source_position,
10283 "cannot convert to a pointer type");
10284 } else if (warning.other && type != type_void_ptr) {
10285 warningf(&expression->base.source_position,
10286 "type of computed goto expression should be 'void*' not '%T'", type);
10288 expression = create_implicit_cast(expression, type_void_ptr);
10291 statement->gotos.expression = expression;
10293 if (token.type != T_IDENTIFIER) {
10295 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
10297 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
10298 eat_until_anchor();
10301 symbol_t *symbol = token.v.symbol;
10304 statement->gotos.label = get_label(symbol);
10307 /* remember the goto's in a list for later checking */
10308 *goto_anchor = &statement->gotos;
10309 goto_anchor = &statement->gotos.next;
10311 expect(';', end_error);
10315 return create_invalid_statement();
10319 * Parse a continue statement.
10321 static statement_t *parse_continue(void)
10323 if (current_loop == NULL) {
10324 errorf(HERE, "continue statement not within loop");
10327 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
10330 expect(';', end_error);
10337 * Parse a break statement.
10339 static statement_t *parse_break(void)
10341 if (current_switch == NULL && current_loop == NULL) {
10342 errorf(HERE, "break statement not within loop or switch");
10345 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10348 expect(';', end_error);
10355 * Parse a __leave statement.
10357 static statement_t *parse_leave_statement(void)
10359 if (current_try == NULL) {
10360 errorf(HERE, "__leave statement not within __try");
10363 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10366 expect(';', end_error);
10373 * Check if a given entity represents a local variable.
10375 static bool is_local_variable(const entity_t *entity)
10377 if (entity->kind != ENTITY_VARIABLE)
10380 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10381 case STORAGE_CLASS_AUTO:
10382 case STORAGE_CLASS_REGISTER: {
10383 const type_t *type = skip_typeref(entity->declaration.type);
10384 if (is_type_function(type)) {
10396 * Check if a given expression represents a local variable.
10398 static bool expression_is_local_variable(const expression_t *expression)
10400 if (expression->base.kind != EXPR_REFERENCE) {
10403 const entity_t *entity = expression->reference.entity;
10404 return is_local_variable(entity);
10408 * Check if a given expression represents a local variable and
10409 * return its declaration then, else return NULL.
10411 entity_t *expression_is_variable(const expression_t *expression)
10413 if (expression->base.kind != EXPR_REFERENCE) {
10416 entity_t *entity = expression->reference.entity;
10417 if (entity->kind != ENTITY_VARIABLE)
10424 * Parse a return statement.
10426 static statement_t *parse_return(void)
10430 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10432 expression_t *return_value = NULL;
10433 if (token.type != ';') {
10434 return_value = parse_expression();
10435 mark_vars_read(return_value, NULL);
10438 const type_t *const func_type = skip_typeref(current_function->base.type);
10439 assert(is_type_function(func_type));
10440 type_t *const return_type = skip_typeref(func_type->function.return_type);
10442 source_position_t const *const pos = &statement->base.source_position;
10443 if (return_value != NULL) {
10444 type_t *return_value_type = skip_typeref(return_value->base.type);
10446 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10447 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10448 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10449 /* Only warn in C mode, because GCC does the same */
10450 if (c_mode & _CXX || strict_mode) {
10452 "'return' with a value, in function returning 'void'");
10453 } else if (warning.other) {
10455 "'return' with a value, in function returning 'void'");
10457 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10458 /* Only warn in C mode, because GCC does the same */
10461 "'return' with expression in function return 'void'");
10462 } else if (warning.other) {
10464 "'return' with expression in function return 'void'");
10468 assign_error_t error = semantic_assign(return_type, return_value);
10469 report_assign_error(error, return_type, return_value, "'return'",
10472 return_value = create_implicit_cast(return_value, return_type);
10473 /* check for returning address of a local var */
10474 if (warning.other && return_value != NULL
10475 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10476 const expression_t *expression = return_value->unary.value;
10477 if (expression_is_local_variable(expression)) {
10478 warningf(pos, "function returns address of local variable");
10481 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10482 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10483 if (c_mode & _CXX || strict_mode) {
10485 "'return' without value, in function returning non-void");
10488 "'return' without value, in function returning non-void");
10491 statement->returns.value = return_value;
10493 expect(';', end_error);
10500 * Parse a declaration statement.
10502 static statement_t *parse_declaration_statement(void)
10504 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10506 entity_t *before = current_scope->last_entity;
10508 parse_external_declaration();
10510 parse_declaration(record_entity, DECL_FLAGS_NONE);
10513 if (before == NULL) {
10514 statement->declaration.declarations_begin = current_scope->entities;
10516 statement->declaration.declarations_begin = before->base.next;
10518 statement->declaration.declarations_end = current_scope->last_entity;
10524 * Parse an expression statement, ie. expr ';'.
10526 static statement_t *parse_expression_statement(void)
10528 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10530 expression_t *const expr = parse_expression();
10531 statement->expression.expression = expr;
10532 mark_vars_read(expr, ENT_ANY);
10534 expect(';', end_error);
10541 * Parse a microsoft __try { } __finally { } or
10542 * __try{ } __except() { }
10544 static statement_t *parse_ms_try_statment(void)
10546 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10549 PUSH_PARENT(statement);
10551 ms_try_statement_t *rem = current_try;
10552 current_try = &statement->ms_try;
10553 statement->ms_try.try_statement = parse_compound_statement(false);
10558 if (token.type == T___except) {
10560 expect('(', end_error);
10561 add_anchor_token(')');
10562 expression_t *const expr = parse_expression();
10563 mark_vars_read(expr, NULL);
10564 type_t * type = skip_typeref(expr->base.type);
10565 if (is_type_integer(type)) {
10566 type = promote_integer(type);
10567 } else if (is_type_valid(type)) {
10568 errorf(&expr->base.source_position,
10569 "__expect expression is not an integer, but '%T'", type);
10570 type = type_error_type;
10572 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10573 rem_anchor_token(')');
10574 expect(')', end_error);
10575 statement->ms_try.final_statement = parse_compound_statement(false);
10576 } else if (token.type == T__finally) {
10578 statement->ms_try.final_statement = parse_compound_statement(false);
10580 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10581 return create_invalid_statement();
10585 return create_invalid_statement();
10588 static statement_t *parse_empty_statement(void)
10590 if (warning.empty_statement) {
10591 warningf(HERE, "statement is empty");
10593 statement_t *const statement = create_empty_statement();
10598 static statement_t *parse_local_label_declaration(void)
10600 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10604 entity_t *begin = NULL, *end = NULL;
10607 if (token.type != T_IDENTIFIER) {
10608 parse_error_expected("while parsing local label declaration",
10609 T_IDENTIFIER, NULL);
10612 symbol_t *symbol = token.v.symbol;
10613 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10614 if (entity != NULL && entity->base.parent_scope == current_scope) {
10615 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10616 symbol, &entity->base.source_position);
10618 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10620 entity->base.parent_scope = current_scope;
10621 entity->base.namespc = NAMESPACE_LABEL;
10622 entity->base.source_position = token.source_position;
10623 entity->base.symbol = symbol;
10626 end->base.next = entity;
10631 environment_push(entity);
10635 if (token.type != ',')
10641 statement->declaration.declarations_begin = begin;
10642 statement->declaration.declarations_end = end;
10646 static void parse_namespace_definition(void)
10650 entity_t *entity = NULL;
10651 symbol_t *symbol = NULL;
10653 if (token.type == T_IDENTIFIER) {
10654 symbol = token.v.symbol;
10657 entity = get_entity(symbol, NAMESPACE_NORMAL);
10658 if (entity != NULL && entity->kind != ENTITY_NAMESPACE
10659 && entity->base.parent_scope == current_scope) {
10660 error_redefined_as_different_kind(&token.source_position,
10661 entity, ENTITY_NAMESPACE);
10666 if (entity == NULL) {
10667 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10668 entity->base.symbol = symbol;
10669 entity->base.source_position = token.source_position;
10670 entity->base.namespc = NAMESPACE_NORMAL;
10671 entity->base.parent_scope = current_scope;
10674 if (token.type == '=') {
10675 /* TODO: parse namespace alias */
10676 panic("namespace alias definition not supported yet");
10679 environment_push(entity);
10680 append_entity(current_scope, entity);
10682 size_t const top = environment_top();
10683 scope_t *old_scope = scope_push(&entity->namespacee.members);
10685 expect('{', end_error);
10687 expect('}', end_error);
10690 assert(current_scope == &entity->namespacee.members);
10691 scope_pop(old_scope);
10692 environment_pop_to(top);
10696 * Parse a statement.
10697 * There's also parse_statement() which additionally checks for
10698 * "statement has no effect" warnings
10700 static statement_t *intern_parse_statement(void)
10702 statement_t *statement = NULL;
10704 /* declaration or statement */
10705 add_anchor_token(';');
10706 switch (token.type) {
10707 case T_IDENTIFIER: {
10708 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10709 if (la1_type == ':') {
10710 statement = parse_label_statement();
10711 } else if (is_typedef_symbol(token.v.symbol)) {
10712 statement = parse_declaration_statement();
10714 /* it's an identifier, the grammar says this must be an
10715 * expression statement. However it is common that users mistype
10716 * declaration types, so we guess a bit here to improve robustness
10717 * for incorrect programs */
10718 switch (la1_type) {
10721 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10722 goto expression_statment;
10727 statement = parse_declaration_statement();
10731 expression_statment:
10732 statement = parse_expression_statement();
10739 case T___extension__:
10740 /* This can be a prefix to a declaration or an expression statement.
10741 * We simply eat it now and parse the rest with tail recursion. */
10744 } while (token.type == T___extension__);
10745 bool old_gcc_extension = in_gcc_extension;
10746 in_gcc_extension = true;
10747 statement = intern_parse_statement();
10748 in_gcc_extension = old_gcc_extension;
10752 statement = parse_declaration_statement();
10756 statement = parse_local_label_declaration();
10759 case ';': statement = parse_empty_statement(); break;
10760 case '{': statement = parse_compound_statement(false); break;
10761 case T___leave: statement = parse_leave_statement(); break;
10762 case T___try: statement = parse_ms_try_statment(); break;
10763 case T_asm: statement = parse_asm_statement(); break;
10764 case T_break: statement = parse_break(); break;
10765 case T_case: statement = parse_case_statement(); break;
10766 case T_continue: statement = parse_continue(); break;
10767 case T_default: statement = parse_default_statement(); break;
10768 case T_do: statement = parse_do(); break;
10769 case T_for: statement = parse_for(); break;
10770 case T_goto: statement = parse_goto(); break;
10771 case T_if: statement = parse_if(); break;
10772 case T_return: statement = parse_return(); break;
10773 case T_switch: statement = parse_switch(); break;
10774 case T_while: statement = parse_while(); break;
10777 statement = parse_expression_statement();
10781 errorf(HERE, "unexpected token %K while parsing statement", &token);
10782 statement = create_invalid_statement();
10787 rem_anchor_token(';');
10789 assert(statement != NULL
10790 && statement->base.source_position.input_name != NULL);
10796 * parse a statement and emits "statement has no effect" warning if needed
10797 * (This is really a wrapper around intern_parse_statement with check for 1
10798 * single warning. It is needed, because for statement expressions we have
10799 * to avoid the warning on the last statement)
10801 static statement_t *parse_statement(void)
10803 statement_t *statement = intern_parse_statement();
10805 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10806 expression_t *expression = statement->expression.expression;
10807 if (!expression_has_effect(expression)) {
10808 warningf(&expression->base.source_position,
10809 "statement has no effect");
10817 * Parse a compound statement.
10819 static statement_t *parse_compound_statement(bool inside_expression_statement)
10821 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10823 PUSH_PARENT(statement);
10826 add_anchor_token('}');
10827 /* tokens, which can start a statement */
10828 /* TODO MS, __builtin_FOO */
10829 add_anchor_token('!');
10830 add_anchor_token('&');
10831 add_anchor_token('(');
10832 add_anchor_token('*');
10833 add_anchor_token('+');
10834 add_anchor_token('-');
10835 add_anchor_token('{');
10836 add_anchor_token('~');
10837 add_anchor_token(T_CHARACTER_CONSTANT);
10838 add_anchor_token(T_COLONCOLON);
10839 add_anchor_token(T_FLOATINGPOINT);
10840 add_anchor_token(T_IDENTIFIER);
10841 add_anchor_token(T_INTEGER);
10842 add_anchor_token(T_MINUSMINUS);
10843 add_anchor_token(T_PLUSPLUS);
10844 add_anchor_token(T_STRING_LITERAL);
10845 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10846 add_anchor_token(T_WIDE_STRING_LITERAL);
10847 add_anchor_token(T__Bool);
10848 add_anchor_token(T__Complex);
10849 add_anchor_token(T__Imaginary);
10850 add_anchor_token(T___FUNCTION__);
10851 add_anchor_token(T___PRETTY_FUNCTION__);
10852 add_anchor_token(T___alignof__);
10853 add_anchor_token(T___attribute__);
10854 add_anchor_token(T___builtin_va_start);
10855 add_anchor_token(T___extension__);
10856 add_anchor_token(T___func__);
10857 add_anchor_token(T___imag__);
10858 add_anchor_token(T___label__);
10859 add_anchor_token(T___real__);
10860 add_anchor_token(T___thread);
10861 add_anchor_token(T_asm);
10862 add_anchor_token(T_auto);
10863 add_anchor_token(T_bool);
10864 add_anchor_token(T_break);
10865 add_anchor_token(T_case);
10866 add_anchor_token(T_char);
10867 add_anchor_token(T_class);
10868 add_anchor_token(T_const);
10869 add_anchor_token(T_const_cast);
10870 add_anchor_token(T_continue);
10871 add_anchor_token(T_default);
10872 add_anchor_token(T_delete);
10873 add_anchor_token(T_double);
10874 add_anchor_token(T_do);
10875 add_anchor_token(T_dynamic_cast);
10876 add_anchor_token(T_enum);
10877 add_anchor_token(T_extern);
10878 add_anchor_token(T_false);
10879 add_anchor_token(T_float);
10880 add_anchor_token(T_for);
10881 add_anchor_token(T_goto);
10882 add_anchor_token(T_if);
10883 add_anchor_token(T_inline);
10884 add_anchor_token(T_int);
10885 add_anchor_token(T_long);
10886 add_anchor_token(T_new);
10887 add_anchor_token(T_operator);
10888 add_anchor_token(T_register);
10889 add_anchor_token(T_reinterpret_cast);
10890 add_anchor_token(T_restrict);
10891 add_anchor_token(T_return);
10892 add_anchor_token(T_short);
10893 add_anchor_token(T_signed);
10894 add_anchor_token(T_sizeof);
10895 add_anchor_token(T_static);
10896 add_anchor_token(T_static_cast);
10897 add_anchor_token(T_struct);
10898 add_anchor_token(T_switch);
10899 add_anchor_token(T_template);
10900 add_anchor_token(T_this);
10901 add_anchor_token(T_throw);
10902 add_anchor_token(T_true);
10903 add_anchor_token(T_try);
10904 add_anchor_token(T_typedef);
10905 add_anchor_token(T_typeid);
10906 add_anchor_token(T_typename);
10907 add_anchor_token(T_typeof);
10908 add_anchor_token(T_union);
10909 add_anchor_token(T_unsigned);
10910 add_anchor_token(T_using);
10911 add_anchor_token(T_void);
10912 add_anchor_token(T_volatile);
10913 add_anchor_token(T_wchar_t);
10914 add_anchor_token(T_while);
10916 size_t const top = environment_top();
10917 scope_t *old_scope = scope_push(&statement->compound.scope);
10919 statement_t **anchor = &statement->compound.statements;
10920 bool only_decls_so_far = true;
10921 while (token.type != '}') {
10922 if (token.type == T_EOF) {
10923 errorf(&statement->base.source_position,
10924 "EOF while parsing compound statement");
10927 statement_t *sub_statement = intern_parse_statement();
10928 if (is_invalid_statement(sub_statement)) {
10929 /* an error occurred. if we are at an anchor, return */
10935 if (warning.declaration_after_statement) {
10936 if (sub_statement->kind != STATEMENT_DECLARATION) {
10937 only_decls_so_far = false;
10938 } else if (!only_decls_so_far) {
10939 warningf(&sub_statement->base.source_position,
10940 "ISO C90 forbids mixed declarations and code");
10944 *anchor = sub_statement;
10946 while (sub_statement->base.next != NULL)
10947 sub_statement = sub_statement->base.next;
10949 anchor = &sub_statement->base.next;
10953 /* look over all statements again to produce no effect warnings */
10954 if (warning.unused_value) {
10955 statement_t *sub_statement = statement->compound.statements;
10956 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10957 if (sub_statement->kind != STATEMENT_EXPRESSION)
10959 /* don't emit a warning for the last expression in an expression
10960 * statement as it has always an effect */
10961 if (inside_expression_statement && sub_statement->base.next == NULL)
10964 expression_t *expression = sub_statement->expression.expression;
10965 if (!expression_has_effect(expression)) {
10966 warningf(&expression->base.source_position,
10967 "statement has no effect");
10973 rem_anchor_token(T_while);
10974 rem_anchor_token(T_wchar_t);
10975 rem_anchor_token(T_volatile);
10976 rem_anchor_token(T_void);
10977 rem_anchor_token(T_using);
10978 rem_anchor_token(T_unsigned);
10979 rem_anchor_token(T_union);
10980 rem_anchor_token(T_typeof);
10981 rem_anchor_token(T_typename);
10982 rem_anchor_token(T_typeid);
10983 rem_anchor_token(T_typedef);
10984 rem_anchor_token(T_try);
10985 rem_anchor_token(T_true);
10986 rem_anchor_token(T_throw);
10987 rem_anchor_token(T_this);
10988 rem_anchor_token(T_template);
10989 rem_anchor_token(T_switch);
10990 rem_anchor_token(T_struct);
10991 rem_anchor_token(T_static_cast);
10992 rem_anchor_token(T_static);
10993 rem_anchor_token(T_sizeof);
10994 rem_anchor_token(T_signed);
10995 rem_anchor_token(T_short);
10996 rem_anchor_token(T_return);
10997 rem_anchor_token(T_restrict);
10998 rem_anchor_token(T_reinterpret_cast);
10999 rem_anchor_token(T_register);
11000 rem_anchor_token(T_operator);
11001 rem_anchor_token(T_new);
11002 rem_anchor_token(T_long);
11003 rem_anchor_token(T_int);
11004 rem_anchor_token(T_inline);
11005 rem_anchor_token(T_if);
11006 rem_anchor_token(T_goto);
11007 rem_anchor_token(T_for);
11008 rem_anchor_token(T_float);
11009 rem_anchor_token(T_false);
11010 rem_anchor_token(T_extern);
11011 rem_anchor_token(T_enum);
11012 rem_anchor_token(T_dynamic_cast);
11013 rem_anchor_token(T_do);
11014 rem_anchor_token(T_double);
11015 rem_anchor_token(T_delete);
11016 rem_anchor_token(T_default);
11017 rem_anchor_token(T_continue);
11018 rem_anchor_token(T_const_cast);
11019 rem_anchor_token(T_const);
11020 rem_anchor_token(T_class);
11021 rem_anchor_token(T_char);
11022 rem_anchor_token(T_case);
11023 rem_anchor_token(T_break);
11024 rem_anchor_token(T_bool);
11025 rem_anchor_token(T_auto);
11026 rem_anchor_token(T_asm);
11027 rem_anchor_token(T___thread);
11028 rem_anchor_token(T___real__);
11029 rem_anchor_token(T___label__);
11030 rem_anchor_token(T___imag__);
11031 rem_anchor_token(T___func__);
11032 rem_anchor_token(T___extension__);
11033 rem_anchor_token(T___builtin_va_start);
11034 rem_anchor_token(T___attribute__);
11035 rem_anchor_token(T___alignof__);
11036 rem_anchor_token(T___PRETTY_FUNCTION__);
11037 rem_anchor_token(T___FUNCTION__);
11038 rem_anchor_token(T__Imaginary);
11039 rem_anchor_token(T__Complex);
11040 rem_anchor_token(T__Bool);
11041 rem_anchor_token(T_WIDE_STRING_LITERAL);
11042 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
11043 rem_anchor_token(T_STRING_LITERAL);
11044 rem_anchor_token(T_PLUSPLUS);
11045 rem_anchor_token(T_MINUSMINUS);
11046 rem_anchor_token(T_INTEGER);
11047 rem_anchor_token(T_IDENTIFIER);
11048 rem_anchor_token(T_FLOATINGPOINT);
11049 rem_anchor_token(T_COLONCOLON);
11050 rem_anchor_token(T_CHARACTER_CONSTANT);
11051 rem_anchor_token('~');
11052 rem_anchor_token('{');
11053 rem_anchor_token('-');
11054 rem_anchor_token('+');
11055 rem_anchor_token('*');
11056 rem_anchor_token('(');
11057 rem_anchor_token('&');
11058 rem_anchor_token('!');
11059 rem_anchor_token('}');
11060 assert(current_scope == &statement->compound.scope);
11061 scope_pop(old_scope);
11062 environment_pop_to(top);
11069 * Check for unused global static functions and variables
11071 static void check_unused_globals(void)
11073 if (!warning.unused_function && !warning.unused_variable)
11076 for (const entity_t *entity = file_scope->entities; entity != NULL;
11077 entity = entity->base.next) {
11078 if (!is_declaration(entity))
11081 const declaration_t *declaration = &entity->declaration;
11082 if (declaration->used ||
11083 declaration->modifiers & DM_UNUSED ||
11084 declaration->modifiers & DM_USED ||
11085 declaration->storage_class != STORAGE_CLASS_STATIC)
11088 type_t *const type = declaration->type;
11090 if (entity->kind == ENTITY_FUNCTION) {
11091 /* inhibit warning for static inline functions */
11092 if (entity->function.is_inline)
11095 s = entity->function.statement != NULL ? "defined" : "declared";
11100 warningf(&declaration->base.source_position, "'%#T' %s but not used",
11101 type, declaration->base.symbol, s);
11105 static void parse_global_asm(void)
11107 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
11110 expect('(', end_error);
11112 statement->asms.asm_text = parse_string_literals();
11113 statement->base.next = unit->global_asm;
11114 unit->global_asm = statement;
11116 expect(')', end_error);
11117 expect(';', end_error);
11122 static void parse_linkage_specification(void)
11125 assert(token.type == T_STRING_LITERAL);
11127 const char *linkage = parse_string_literals().begin;
11129 linkage_kind_t old_linkage = current_linkage;
11130 linkage_kind_t new_linkage;
11131 if (strcmp(linkage, "C") == 0) {
11132 new_linkage = LINKAGE_C;
11133 } else if (strcmp(linkage, "C++") == 0) {
11134 new_linkage = LINKAGE_CXX;
11136 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
11137 new_linkage = LINKAGE_INVALID;
11139 current_linkage = new_linkage;
11141 if (token.type == '{') {
11144 expect('}', end_error);
11150 assert(current_linkage == new_linkage);
11151 current_linkage = old_linkage;
11154 static void parse_external(void)
11156 switch (token.type) {
11157 DECLARATION_START_NO_EXTERN
11159 case T___extension__:
11160 /* tokens below are for implicit int */
11161 case '&': /* & x; -> int& x; (and error later, because C++ has no
11163 case '*': /* * x; -> int* x; */
11164 case '(': /* (x); -> int (x); */
11165 parse_external_declaration();
11169 if (look_ahead(1)->type == T_STRING_LITERAL) {
11170 parse_linkage_specification();
11172 parse_external_declaration();
11177 parse_global_asm();
11181 parse_namespace_definition();
11185 if (!strict_mode) {
11187 warningf(HERE, "stray ';' outside of function");
11194 errorf(HERE, "stray %K outside of function", &token);
11195 if (token.type == '(' || token.type == '{' || token.type == '[')
11196 eat_until_matching_token(token.type);
11202 static void parse_externals(void)
11204 add_anchor_token('}');
11205 add_anchor_token(T_EOF);
11208 unsigned char token_anchor_copy[T_LAST_TOKEN];
11209 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
11212 while (token.type != T_EOF && token.type != '}') {
11214 bool anchor_leak = false;
11215 for (int i = 0; i != T_LAST_TOKEN; ++i) {
11216 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
11218 errorf(HERE, "Leaked anchor token %k %d times", i, count);
11219 anchor_leak = true;
11222 if (in_gcc_extension) {
11223 errorf(HERE, "Leaked __extension__");
11224 anchor_leak = true;
11234 rem_anchor_token(T_EOF);
11235 rem_anchor_token('}');
11239 * Parse a translation unit.
11241 static void parse_translation_unit(void)
11243 add_anchor_token(T_EOF);
11248 if (token.type == T_EOF)
11251 errorf(HERE, "stray %K outside of function", &token);
11252 if (token.type == '(' || token.type == '{' || token.type == '[')
11253 eat_until_matching_token(token.type);
11261 * @return the translation unit or NULL if errors occurred.
11263 void start_parsing(void)
11265 environment_stack = NEW_ARR_F(stack_entry_t, 0);
11266 label_stack = NEW_ARR_F(stack_entry_t, 0);
11267 diagnostic_count = 0;
11271 type_set_output(stderr);
11272 ast_set_output(stderr);
11274 assert(unit == NULL);
11275 unit = allocate_ast_zero(sizeof(unit[0]));
11277 assert(file_scope == NULL);
11278 file_scope = &unit->scope;
11280 assert(current_scope == NULL);
11281 scope_push(&unit->scope);
11284 translation_unit_t *finish_parsing(void)
11286 assert(current_scope == &unit->scope);
11289 assert(file_scope == &unit->scope);
11290 check_unused_globals();
11293 DEL_ARR_F(environment_stack);
11294 DEL_ARR_F(label_stack);
11296 translation_unit_t *result = unit;
11301 /* GCC allows global arrays without size and assigns them a length of one,
11302 * if no different declaration follows */
11303 static void complete_incomplete_arrays(void)
11305 size_t n = ARR_LEN(incomplete_arrays);
11306 for (size_t i = 0; i != n; ++i) {
11307 declaration_t *const decl = incomplete_arrays[i];
11308 type_t *const orig_type = decl->type;
11309 type_t *const type = skip_typeref(orig_type);
11311 if (!is_type_incomplete(type))
11314 if (warning.other) {
11315 warningf(&decl->base.source_position,
11316 "array '%#T' assumed to have one element",
11317 orig_type, decl->base.symbol);
11320 type_t *const new_type = duplicate_type(type);
11321 new_type->array.size_constant = true;
11322 new_type->array.has_implicit_size = true;
11323 new_type->array.size = 1;
11325 type_t *const result = typehash_insert(new_type);
11326 if (type != result)
11329 decl->type = result;
11335 lookahead_bufpos = 0;
11336 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
11339 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
11340 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
11341 parse_translation_unit();
11342 complete_incomplete_arrays();
11343 DEL_ARR_F(incomplete_arrays);
11344 incomplete_arrays = NULL;
11348 * Initialize the parser.
11350 void init_parser(void)
11352 sym_anonymous = symbol_table_insert("<anonymous>");
11354 if (c_mode & _MS) {
11355 /* add predefined symbols for extended-decl-modifier */
11356 sym_align = symbol_table_insert("align");
11357 sym_allocate = symbol_table_insert("allocate");
11358 sym_dllimport = symbol_table_insert("dllimport");
11359 sym_dllexport = symbol_table_insert("dllexport");
11360 sym_naked = symbol_table_insert("naked");
11361 sym_noinline = symbol_table_insert("noinline");
11362 sym_noreturn = symbol_table_insert("noreturn");
11363 sym_nothrow = symbol_table_insert("nothrow");
11364 sym_novtable = symbol_table_insert("novtable");
11365 sym_property = symbol_table_insert("property");
11366 sym_get = symbol_table_insert("get");
11367 sym_put = symbol_table_insert("put");
11368 sym_selectany = symbol_table_insert("selectany");
11369 sym_thread = symbol_table_insert("thread");
11370 sym_uuid = symbol_table_insert("uuid");
11371 sym_deprecated = symbol_table_insert("deprecated");
11372 sym_restrict = symbol_table_insert("restrict");
11373 sym_noalias = symbol_table_insert("noalias");
11375 memset(token_anchor_set, 0, sizeof(token_anchor_set));
11377 init_expression_parsers();
11378 obstack_init(&temp_obst);
11380 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11381 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11385 * Terminate the parser.
11387 void exit_parser(void)
11389 obstack_free(&temp_obst, NULL);