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 has_arguments; /**< True, if this attribute has arguments. */
69 long argument; /**< Single argument. */
70 argument_list_t *arguments; /**< List of argument expressions. */
74 typedef struct declaration_specifiers_t declaration_specifiers_t;
75 struct declaration_specifiers_t {
76 source_position_t source_position;
77 storage_class_t storage_class;
78 unsigned char alignment; /**< Alignment, 0 if not set. */
80 bool thread_local : 1; /**< GCC __thread */
82 decl_modifiers_t modifiers; /**< declaration modifiers */
83 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
84 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
85 symbol_t *get_property_sym; /**< the name of the get property if set. */
86 symbol_t *put_property_sym; /**< the name of the put property if set. */
91 * An environment for parsing initializers (and compound literals).
93 typedef struct parse_initializer_env_t {
94 type_t *type; /**< the type of the initializer. In case of an
95 array type with unspecified size this gets
96 adjusted to the actual size. */
97 entity_t *entity; /**< the variable that is initialized if any */
98 bool must_be_constant;
99 } parse_initializer_env_t;
102 * Capture a MS __base extension.
104 typedef struct based_spec_t {
105 source_position_t source_position;
106 variable_t *base_variable;
109 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
111 /** The current token. */
112 static token_t token;
113 /** The lookahead ring-buffer. */
114 static token_t lookahead_buffer[MAX_LOOKAHEAD];
115 /** Position of the next token in the lookahead buffer. */
116 static int lookahead_bufpos;
117 static stack_entry_t *environment_stack = NULL;
118 static stack_entry_t *label_stack = NULL;
119 static scope_t *file_scope = NULL;
120 static scope_t *current_scope = NULL;
121 /** Point to the current function declaration if inside a function. */
122 static function_t *current_function = NULL;
123 static entity_t *current_init_decl = NULL;
124 static switch_statement_t *current_switch = NULL;
125 static statement_t *current_loop = NULL;
126 static statement_t *current_parent = NULL;
127 static ms_try_statement_t *current_try = NULL;
128 static linkage_kind_t current_linkage = LINKAGE_INVALID;
129 static goto_statement_t *goto_first = NULL;
130 static goto_statement_t **goto_anchor = NULL;
131 static label_statement_t *label_first = NULL;
132 static label_statement_t **label_anchor = NULL;
133 /** current translation unit. */
134 static translation_unit_t *unit = NULL;
135 /** true if we are in a type property context (evaluation only for type. */
136 static bool in_type_prop = false;
137 /** true in we are in a __extension__ context. */
138 static bool in_gcc_extension = false;
139 static struct obstack temp_obst;
140 static entity_t *anonymous_entity;
141 static declaration_t **incomplete_arrays;
144 #define PUSH_PARENT(stmt) \
145 statement_t *const prev_parent = current_parent; \
146 ((void)(current_parent = (stmt)))
147 #define POP_PARENT ((void)(current_parent = prev_parent))
149 /** special symbol used for anonymous entities. */
150 static const symbol_t *sym_anonymous = NULL;
152 /* symbols for Microsoft extended-decl-modifier */
153 static const symbol_t *sym_align = NULL;
154 static const symbol_t *sym_allocate = NULL;
155 static const symbol_t *sym_dllimport = NULL;
156 static const symbol_t *sym_dllexport = NULL;
157 static const symbol_t *sym_naked = NULL;
158 static const symbol_t *sym_noinline = NULL;
159 static const symbol_t *sym_returns_twice = NULL;
160 static const symbol_t *sym_noreturn = NULL;
161 static const symbol_t *sym_nothrow = NULL;
162 static const symbol_t *sym_novtable = NULL;
163 static const symbol_t *sym_property = NULL;
164 static const symbol_t *sym_get = NULL;
165 static const symbol_t *sym_put = NULL;
166 static const symbol_t *sym_selectany = NULL;
167 static const symbol_t *sym_thread = NULL;
168 static const symbol_t *sym_uuid = NULL;
169 static const symbol_t *sym_deprecated = NULL;
170 static const symbol_t *sym_restrict = NULL;
171 static const symbol_t *sym_noalias = NULL;
173 /** The token anchor set */
174 static unsigned char token_anchor_set[T_LAST_TOKEN];
176 /** The current source position. */
177 #define HERE (&token.source_position)
179 /** true if we are in GCC mode. */
180 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
182 static type_t *type_valist;
184 static statement_t *parse_compound_statement(bool inside_expression_statement);
185 static statement_t *parse_statement(void);
187 static expression_t *parse_sub_expression(precedence_t);
188 static expression_t *parse_expression(void);
189 static type_t *parse_typename(void);
190 static void parse_externals(void);
191 static void parse_external(void);
193 static void parse_compound_type_entries(compound_t *compound_declaration);
195 typedef enum declarator_flags_t {
197 DECL_MAY_BE_ABSTRACT = 1U << 0,
198 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
199 DECL_IS_PARAMETER = 1U << 2
200 } declarator_flags_t;
202 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
203 declarator_flags_t flags);
205 static entity_t *record_entity(entity_t *entity, bool is_definition);
207 static void semantic_comparison(binary_expression_t *expression);
209 #define STORAGE_CLASSES \
210 STORAGE_CLASSES_NO_EXTERN \
213 #define STORAGE_CLASSES_NO_EXTERN \
220 #define TYPE_QUALIFIERS \
225 case T__forceinline: \
226 case T___attribute__:
228 #define COMPLEX_SPECIFIERS \
230 #define IMAGINARY_SPECIFIERS \
233 #define TYPE_SPECIFIERS \
235 case T___builtin_va_list: \
255 #define DECLARATION_START \
260 #define DECLARATION_START_NO_EXTERN \
261 STORAGE_CLASSES_NO_EXTERN \
265 #define TYPENAME_START \
269 #define EXPRESSION_START \
278 case T_CHARACTER_CONSTANT: \
279 case T_FLOATINGPOINT: \
283 case T_STRING_LITERAL: \
284 case T_WIDE_CHARACTER_CONSTANT: \
285 case T_WIDE_STRING_LITERAL: \
286 case T___FUNCDNAME__: \
287 case T___FUNCSIG__: \
288 case T___FUNCTION__: \
289 case T___PRETTY_FUNCTION__: \
290 case T___alignof__: \
291 case T___builtin_alloca: \
292 case T___builtin_classify_type: \
293 case T___builtin_constant_p: \
294 case T___builtin_expect: \
295 case T___builtin_huge_val: \
296 case T___builtin_inf: \
297 case T___builtin_inff: \
298 case T___builtin_infl: \
299 case T___builtin_isgreater: \
300 case T___builtin_isgreaterequal: \
301 case T___builtin_isless: \
302 case T___builtin_islessequal: \
303 case T___builtin_islessgreater: \
304 case T___builtin_isunordered: \
305 case T___builtin_nan: \
306 case T___builtin_nanf: \
307 case T___builtin_nanl: \
308 case T___builtin_offsetof: \
309 case T___builtin_prefetch: \
310 case T___builtin_va_arg: \
311 case T___builtin_va_end: \
312 case T___builtin_va_start: \
323 * Allocate an AST node with given size and
324 * initialize all fields with zero.
326 static void *allocate_ast_zero(size_t size)
328 void *res = allocate_ast(size);
329 memset(res, 0, size);
334 * Returns the size of an entity node.
336 * @param kind the entity kind
338 static size_t get_entity_struct_size(entity_kind_t kind)
340 static const size_t sizes[] = {
341 [ENTITY_VARIABLE] = sizeof(variable_t),
342 [ENTITY_PARAMETER] = sizeof(parameter_t),
343 [ENTITY_COMPOUND_MEMBER] = sizeof(compound_member_t),
344 [ENTITY_FUNCTION] = sizeof(function_t),
345 [ENTITY_TYPEDEF] = sizeof(typedef_t),
346 [ENTITY_STRUCT] = sizeof(compound_t),
347 [ENTITY_UNION] = sizeof(compound_t),
348 [ENTITY_ENUM] = sizeof(enum_t),
349 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
350 [ENTITY_LABEL] = sizeof(label_t),
351 [ENTITY_LOCAL_LABEL] = sizeof(label_t),
352 [ENTITY_NAMESPACE] = sizeof(namespace_t)
354 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
355 assert(sizes[kind] != 0);
360 * Allocate an entity of given kind and initialize all
363 static entity_t *allocate_entity_zero(entity_kind_t kind)
365 size_t size = get_entity_struct_size(kind);
366 entity_t *entity = allocate_ast_zero(size);
372 * Returns the size of a statement node.
374 * @param kind the statement kind
376 static size_t get_statement_struct_size(statement_kind_t kind)
378 static const size_t sizes[] = {
379 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
380 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
381 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
382 [STATEMENT_RETURN] = sizeof(return_statement_t),
383 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
384 [STATEMENT_IF] = sizeof(if_statement_t),
385 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
386 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
387 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
388 [STATEMENT_BREAK] = sizeof(statement_base_t),
389 [STATEMENT_GOTO] = sizeof(goto_statement_t),
390 [STATEMENT_LABEL] = sizeof(label_statement_t),
391 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
392 [STATEMENT_WHILE] = sizeof(while_statement_t),
393 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
394 [STATEMENT_FOR] = sizeof(for_statement_t),
395 [STATEMENT_ASM] = sizeof(asm_statement_t),
396 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
397 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
399 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
400 assert(sizes[kind] != 0);
405 * Returns the size of an expression node.
407 * @param kind the expression kind
409 static size_t get_expression_struct_size(expression_kind_t kind)
411 static const size_t sizes[] = {
412 [EXPR_INVALID] = sizeof(expression_base_t),
413 [EXPR_REFERENCE] = sizeof(reference_expression_t),
414 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
415 [EXPR_CONST] = sizeof(const_expression_t),
416 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
417 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
418 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
419 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
420 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
421 [EXPR_CALL] = sizeof(call_expression_t),
422 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
423 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
424 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
425 [EXPR_SELECT] = sizeof(select_expression_t),
426 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
427 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
428 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
429 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
430 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
431 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
432 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
433 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
434 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
435 [EXPR_VA_START] = sizeof(va_start_expression_t),
436 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
437 [EXPR_STATEMENT] = sizeof(statement_expression_t),
438 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
440 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
441 return sizes[EXPR_UNARY_FIRST];
443 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
444 return sizes[EXPR_BINARY_FIRST];
446 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
447 assert(sizes[kind] != 0);
452 * Allocate a statement node of given kind and initialize all
453 * fields with zero. Sets its source position to the position
454 * of the current token.
456 static statement_t *allocate_statement_zero(statement_kind_t kind)
458 size_t size = get_statement_struct_size(kind);
459 statement_t *res = allocate_ast_zero(size);
461 res->base.kind = kind;
462 res->base.parent = current_parent;
463 res->base.source_position = token.source_position;
468 * Allocate an expression node of given kind and initialize all
471 static expression_t *allocate_expression_zero(expression_kind_t kind)
473 size_t size = get_expression_struct_size(kind);
474 expression_t *res = allocate_ast_zero(size);
476 res->base.kind = kind;
477 res->base.type = type_error_type;
478 res->base.source_position = token.source_position;
483 * Creates a new invalid expression at the source position
484 * of the current token.
486 static expression_t *create_invalid_expression(void)
488 return allocate_expression_zero(EXPR_INVALID);
492 * Creates a new invalid statement.
494 static statement_t *create_invalid_statement(void)
496 return allocate_statement_zero(STATEMENT_INVALID);
500 * Allocate a new empty statement.
502 static statement_t *create_empty_statement(void)
504 return allocate_statement_zero(STATEMENT_EMPTY);
508 * Returns the size of a type node.
510 * @param kind the type kind
512 static size_t get_type_struct_size(type_kind_t kind)
514 static const size_t sizes[] = {
515 [TYPE_ATOMIC] = sizeof(atomic_type_t),
516 [TYPE_COMPLEX] = sizeof(complex_type_t),
517 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
518 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
519 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
520 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
521 [TYPE_ENUM] = sizeof(enum_type_t),
522 [TYPE_FUNCTION] = sizeof(function_type_t),
523 [TYPE_POINTER] = sizeof(pointer_type_t),
524 [TYPE_ARRAY] = sizeof(array_type_t),
525 [TYPE_BUILTIN] = sizeof(builtin_type_t),
526 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
527 [TYPE_TYPEOF] = sizeof(typeof_type_t),
529 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
530 assert(kind <= TYPE_TYPEOF);
531 assert(sizes[kind] != 0);
536 * Allocate a type node of given kind and initialize all
539 * @param kind type kind to allocate
541 static type_t *allocate_type_zero(type_kind_t kind)
543 size_t size = get_type_struct_size(kind);
544 type_t *res = obstack_alloc(type_obst, size);
545 memset(res, 0, size);
546 res->base.kind = kind;
552 * Returns the size of an initializer node.
554 * @param kind the initializer kind
556 static size_t get_initializer_size(initializer_kind_t kind)
558 static const size_t sizes[] = {
559 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
560 [INITIALIZER_STRING] = sizeof(initializer_string_t),
561 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
562 [INITIALIZER_LIST] = sizeof(initializer_list_t),
563 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
565 assert(kind < sizeof(sizes) / sizeof(*sizes));
566 assert(sizes[kind] != 0);
571 * Allocate an initializer node of given kind and initialize all
574 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
576 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
583 * Returns the index of the top element of the environment stack.
585 static size_t environment_top(void)
587 return ARR_LEN(environment_stack);
591 * Returns the index of the top element of the global label stack.
593 static size_t label_top(void)
595 return ARR_LEN(label_stack);
599 * Return the next token.
601 static inline void next_token(void)
603 token = lookahead_buffer[lookahead_bufpos];
604 lookahead_buffer[lookahead_bufpos] = lexer_token;
607 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
610 print_token(stderr, &token);
611 fprintf(stderr, "\n");
616 * Return the next token with a given lookahead.
618 static inline const token_t *look_ahead(int num)
620 assert(num > 0 && num <= MAX_LOOKAHEAD);
621 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
622 return &lookahead_buffer[pos];
626 * Adds a token type to the token type anchor set (a multi-set).
628 static void add_anchor_token(int token_type)
630 assert(0 <= token_type && token_type < T_LAST_TOKEN);
631 ++token_anchor_set[token_type];
635 * Set the number of tokens types of the given type
636 * to zero and return the old count.
638 static int save_and_reset_anchor_state(int token_type)
640 assert(0 <= token_type && token_type < T_LAST_TOKEN);
641 int count = token_anchor_set[token_type];
642 token_anchor_set[token_type] = 0;
647 * Restore the number of token types to the given count.
649 static void restore_anchor_state(int token_type, int count)
651 assert(0 <= token_type && token_type < T_LAST_TOKEN);
652 token_anchor_set[token_type] = count;
656 * Remove a token type from the token type anchor set (a multi-set).
658 static void rem_anchor_token(int token_type)
660 assert(0 <= token_type && token_type < T_LAST_TOKEN);
661 assert(token_anchor_set[token_type] != 0);
662 --token_anchor_set[token_type];
666 * Return true if the token type of the current token is
669 static bool at_anchor(void)
673 return token_anchor_set[token.type];
677 * Eat tokens until a matching token type is found.
679 static void eat_until_matching_token(int type)
683 case '(': end_token = ')'; break;
684 case '{': end_token = '}'; break;
685 case '[': end_token = ']'; break;
686 default: end_token = type; break;
689 unsigned parenthesis_count = 0;
690 unsigned brace_count = 0;
691 unsigned bracket_count = 0;
692 while (token.type != end_token ||
693 parenthesis_count != 0 ||
695 bracket_count != 0) {
696 switch (token.type) {
698 case '(': ++parenthesis_count; break;
699 case '{': ++brace_count; break;
700 case '[': ++bracket_count; break;
703 if (parenthesis_count > 0)
713 if (bracket_count > 0)
716 if (token.type == end_token &&
717 parenthesis_count == 0 &&
731 * Eat input tokens until an anchor is found.
733 static void eat_until_anchor(void)
735 while (token_anchor_set[token.type] == 0) {
736 if (token.type == '(' || token.type == '{' || token.type == '[')
737 eat_until_matching_token(token.type);
743 * Eat a whole block from input tokens.
745 static void eat_block(void)
747 eat_until_matching_token('{');
748 if (token.type == '}')
752 #define eat(token_type) (assert(token.type == (token_type)), next_token())
755 * Report a parse error because an expected token was not found.
758 #if defined __GNUC__ && __GNUC__ >= 4
759 __attribute__((sentinel))
761 void parse_error_expected(const char *message, ...)
763 if (message != NULL) {
764 errorf(HERE, "%s", message);
767 va_start(ap, message);
768 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
773 * Report an incompatible type.
775 static void type_error_incompatible(const char *msg,
776 const source_position_t *source_position, type_t *type1, type_t *type2)
778 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
783 * Expect the current token is the expected token.
784 * If not, generate an error, eat the current statement,
785 * and goto the end_error label.
787 #define expect(expected, error_label) \
789 if (UNLIKELY(token.type != (expected))) { \
790 parse_error_expected(NULL, (expected), NULL); \
791 add_anchor_token(expected); \
792 eat_until_anchor(); \
793 if (token.type == expected) \
795 rem_anchor_token(expected); \
802 * Push a given scope on the scope stack and make it the
805 static scope_t *scope_push(scope_t *new_scope)
807 if (current_scope != NULL) {
808 new_scope->depth = current_scope->depth + 1;
811 scope_t *old_scope = current_scope;
812 current_scope = new_scope;
817 * Pop the current scope from the scope stack.
819 static void scope_pop(scope_t *old_scope)
821 current_scope = old_scope;
825 * Search an entity by its symbol in a given namespace.
827 static entity_t *get_entity(const symbol_t *const symbol,
828 namespace_tag_t namespc)
830 entity_t *entity = symbol->entity;
831 for (; entity != NULL; entity = entity->base.symbol_next) {
832 if (entity->base.namespc == namespc)
840 * pushs an entity on the environment stack and links the corresponding symbol
843 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
845 symbol_t *symbol = entity->base.symbol;
846 entity_namespace_t namespc = entity->base.namespc;
847 assert(namespc != NAMESPACE_INVALID);
849 /* replace/add entity into entity list of the symbol */
852 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
857 /* replace an entry? */
858 if (iter->base.namespc == namespc) {
859 entity->base.symbol_next = iter->base.symbol_next;
865 /* remember old declaration */
867 entry.symbol = symbol;
868 entry.old_entity = iter;
869 entry.namespc = namespc;
870 ARR_APP1(stack_entry_t, *stack_ptr, entry);
874 * Push an entity on the environment stack.
876 static void environment_push(entity_t *entity)
878 assert(entity->base.source_position.input_name != NULL);
879 assert(entity->base.parent_scope != NULL);
880 stack_push(&environment_stack, entity);
884 * Push a declaration on the global label stack.
886 * @param declaration the declaration
888 static void label_push(entity_t *label)
890 /* we abuse the parameters scope as parent for the labels */
891 label->base.parent_scope = ¤t_function->parameters;
892 stack_push(&label_stack, label);
896 * pops symbols from the environment stack until @p new_top is the top element
898 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
900 stack_entry_t *stack = *stack_ptr;
901 size_t top = ARR_LEN(stack);
904 assert(new_top <= top);
908 for (i = top; i > new_top; --i) {
909 stack_entry_t *entry = &stack[i - 1];
911 entity_t *old_entity = entry->old_entity;
912 symbol_t *symbol = entry->symbol;
913 entity_namespace_t namespc = entry->namespc;
915 /* replace with old_entity/remove */
918 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
920 assert(iter != NULL);
921 /* replace an entry? */
922 if (iter->base.namespc == namespc)
926 /* restore definition from outer scopes (if there was one) */
927 if (old_entity != NULL) {
928 old_entity->base.symbol_next = iter->base.symbol_next;
929 *anchor = old_entity;
931 /* remove entry from list */
932 *anchor = iter->base.symbol_next;
936 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
940 * Pop all entries from the environment stack until the new_top
943 * @param new_top the new stack top
945 static void environment_pop_to(size_t new_top)
947 stack_pop_to(&environment_stack, new_top);
951 * Pop all entries from the global label stack until the new_top
954 * @param new_top the new stack top
956 static void label_pop_to(size_t new_top)
958 stack_pop_to(&label_stack, new_top);
961 static int get_akind_rank(atomic_type_kind_t akind)
967 * Return the type rank for an atomic type.
969 static int get_rank(const type_t *type)
971 assert(!is_typeref(type));
972 if (type->kind == TYPE_ENUM)
973 return get_akind_rank(type->enumt.akind);
975 assert(type->kind == TYPE_ATOMIC);
976 return get_akind_rank(type->atomic.akind);
980 * Do integer promotion for a given type.
982 * @param type the type to promote
983 * @return the promoted type
985 static type_t *promote_integer(type_t *type)
987 if (type->kind == TYPE_BITFIELD)
988 type = type->bitfield.base_type;
990 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
997 * Create a cast expression.
999 * @param expression the expression to cast
1000 * @param dest_type the destination type
1002 static expression_t *create_cast_expression(expression_t *expression,
1005 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
1007 cast->unary.value = expression;
1008 cast->base.type = dest_type;
1014 * Check if a given expression represents a null pointer constant.
1016 * @param expression the expression to check
1018 static bool is_null_pointer_constant(const expression_t *expression)
1020 /* skip void* cast */
1021 if (expression->kind == EXPR_UNARY_CAST ||
1022 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
1023 type_t *const type = skip_typeref(expression->base.type);
1024 if (types_compatible(type, type_void_ptr))
1025 expression = expression->unary.value;
1028 type_t *const type = skip_typeref(expression->base.type);
1030 is_type_integer(type) &&
1031 is_constant_expression(expression) &&
1032 fold_constant(expression) == 0;
1036 * Create an implicit cast expression.
1038 * @param expression the expression to cast
1039 * @param dest_type the destination type
1041 static expression_t *create_implicit_cast(expression_t *expression,
1044 type_t *const source_type = expression->base.type;
1046 if (source_type == dest_type)
1049 return create_cast_expression(expression, dest_type);
1052 typedef enum assign_error_t {
1054 ASSIGN_ERROR_INCOMPATIBLE,
1055 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1056 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1057 ASSIGN_WARNING_POINTER_FROM_INT,
1058 ASSIGN_WARNING_INT_FROM_POINTER
1061 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1062 const expression_t *const right,
1063 const char *context,
1064 const source_position_t *source_position)
1066 type_t *const orig_type_right = right->base.type;
1067 type_t *const type_left = skip_typeref(orig_type_left);
1068 type_t *const type_right = skip_typeref(orig_type_right);
1071 case ASSIGN_SUCCESS:
1073 case ASSIGN_ERROR_INCOMPATIBLE:
1074 errorf(source_position,
1075 "destination type '%T' in %s is incompatible with type '%T'",
1076 orig_type_left, context, orig_type_right);
1079 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1080 if (warning.other) {
1081 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1082 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1084 /* the left type has all qualifiers from the right type */
1085 unsigned missing_qualifiers
1086 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1087 warningf(source_position,
1088 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1089 orig_type_left, context, orig_type_right, missing_qualifiers);
1094 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1095 if (warning.other) {
1096 warningf(source_position,
1097 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1098 orig_type_left, context, right, orig_type_right);
1102 case ASSIGN_WARNING_POINTER_FROM_INT:
1103 if (warning.other) {
1104 warningf(source_position,
1105 "%s makes pointer '%T' from integer '%T' without a cast",
1106 context, orig_type_left, orig_type_right);
1110 case ASSIGN_WARNING_INT_FROM_POINTER:
1111 if (warning.other) {
1112 warningf(source_position,
1113 "%s makes integer '%T' from pointer '%T' without a cast",
1114 context, orig_type_left, orig_type_right);
1119 panic("invalid error value");
1123 /** Implements the rules from § 6.5.16.1 */
1124 static assign_error_t semantic_assign(type_t *orig_type_left,
1125 const expression_t *const right)
1127 type_t *const orig_type_right = right->base.type;
1128 type_t *const type_left = skip_typeref(orig_type_left);
1129 type_t *const type_right = skip_typeref(orig_type_right);
1131 if (is_type_pointer(type_left)) {
1132 if (is_null_pointer_constant(right)) {
1133 return ASSIGN_SUCCESS;
1134 } else if (is_type_pointer(type_right)) {
1135 type_t *points_to_left
1136 = skip_typeref(type_left->pointer.points_to);
1137 type_t *points_to_right
1138 = skip_typeref(type_right->pointer.points_to);
1139 assign_error_t res = ASSIGN_SUCCESS;
1141 /* the left type has all qualifiers from the right type */
1142 unsigned missing_qualifiers
1143 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1144 if (missing_qualifiers != 0) {
1145 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1148 points_to_left = get_unqualified_type(points_to_left);
1149 points_to_right = get_unqualified_type(points_to_right);
1151 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1154 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1155 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1156 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1159 if (!types_compatible(points_to_left, points_to_right)) {
1160 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1164 } else if (is_type_integer(type_right)) {
1165 return ASSIGN_WARNING_POINTER_FROM_INT;
1167 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1168 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1169 && is_type_pointer(type_right))) {
1170 return ASSIGN_SUCCESS;
1171 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1172 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1173 type_t *const unqual_type_left = get_unqualified_type(type_left);
1174 type_t *const unqual_type_right = get_unqualified_type(type_right);
1175 if (types_compatible(unqual_type_left, unqual_type_right)) {
1176 return ASSIGN_SUCCESS;
1178 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1179 return ASSIGN_WARNING_INT_FROM_POINTER;
1182 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1183 return ASSIGN_SUCCESS;
1185 return ASSIGN_ERROR_INCOMPATIBLE;
1188 static expression_t *parse_constant_expression(void)
1190 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1192 if (!is_constant_expression(result)) {
1193 errorf(&result->base.source_position,
1194 "expression '%E' is not constant", result);
1200 static expression_t *parse_assignment_expression(void)
1202 return parse_sub_expression(PREC_ASSIGNMENT);
1205 static string_t parse_string_literals(void)
1207 assert(token.type == T_STRING_LITERAL);
1208 string_t result = token.v.string;
1212 while (token.type == T_STRING_LITERAL) {
1213 result = concat_strings(&result, &token.v.string);
1220 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1221 [GNU_AK_CONST] = "const",
1222 [GNU_AK_VOLATILE] = "volatile",
1223 [GNU_AK_CDECL] = "cdecl",
1224 [GNU_AK_STDCALL] = "stdcall",
1225 [GNU_AK_FASTCALL] = "fastcall",
1226 [GNU_AK_DEPRECATED] = "deprecated",
1227 [GNU_AK_NOINLINE] = "noinline",
1228 [GNU_AK_RETURNS_TWICE] = "returns_twice",
1229 [GNU_AK_NORETURN] = "noreturn",
1230 [GNU_AK_NAKED] = "naked",
1231 [GNU_AK_PURE] = "pure",
1232 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1233 [GNU_AK_MALLOC] = "malloc",
1234 [GNU_AK_WEAK] = "weak",
1235 [GNU_AK_CONSTRUCTOR] = "constructor",
1236 [GNU_AK_DESTRUCTOR] = "destructor",
1237 [GNU_AK_NOTHROW] = "nothrow",
1238 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1239 [GNU_AK_COMMON] = "common",
1240 [GNU_AK_NOCOMMON] = "nocommon",
1241 [GNU_AK_PACKED] = "packed",
1242 [GNU_AK_SHARED] = "shared",
1243 [GNU_AK_NOTSHARED] = "notshared",
1244 [GNU_AK_USED] = "used",
1245 [GNU_AK_UNUSED] = "unused",
1246 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1247 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1248 [GNU_AK_LONGCALL] = "longcall",
1249 [GNU_AK_SHORTCALL] = "shortcall",
1250 [GNU_AK_LONG_CALL] = "long_call",
1251 [GNU_AK_SHORT_CALL] = "short_call",
1252 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1253 [GNU_AK_INTERRUPT] = "interrupt",
1254 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1255 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1256 [GNU_AK_NESTING] = "nesting",
1257 [GNU_AK_NEAR] = "near",
1258 [GNU_AK_FAR] = "far",
1259 [GNU_AK_SIGNAL] = "signal",
1260 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1261 [GNU_AK_TINY_DATA] = "tiny_data",
1262 [GNU_AK_SAVEALL] = "saveall",
1263 [GNU_AK_FLATTEN] = "flatten",
1264 [GNU_AK_SSEREGPARM] = "sseregparm",
1265 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1266 [GNU_AK_RETURN_TWICE] = "return_twice",
1267 [GNU_AK_MAY_ALIAS] = "may_alias",
1268 [GNU_AK_MS_STRUCT] = "ms_struct",
1269 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1270 [GNU_AK_DLLIMPORT] = "dllimport",
1271 [GNU_AK_DLLEXPORT] = "dllexport",
1272 [GNU_AK_ALIGNED] = "aligned",
1273 [GNU_AK_ALIAS] = "alias",
1274 [GNU_AK_SECTION] = "section",
1275 [GNU_AK_FORMAT] = "format",
1276 [GNU_AK_FORMAT_ARG] = "format_arg",
1277 [GNU_AK_WEAKREF] = "weakref",
1278 [GNU_AK_NONNULL] = "nonnull",
1279 [GNU_AK_TLS_MODEL] = "tls_model",
1280 [GNU_AK_VISIBILITY] = "visibility",
1281 [GNU_AK_REGPARM] = "regparm",
1282 [GNU_AK_MODE] = "mode",
1283 [GNU_AK_MODEL] = "model",
1284 [GNU_AK_TRAP_EXIT] = "trap_exit",
1285 [GNU_AK_SP_SWITCH] = "sp_switch",
1286 [GNU_AK_SENTINEL] = "sentinel"
1290 * compare two string, ignoring double underscores on the second.
1292 static int strcmp_underscore(const char *s1, const char *s2)
1294 if (s2[0] == '_' && s2[1] == '_') {
1295 size_t len2 = strlen(s2);
1296 size_t len1 = strlen(s1);
1297 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1298 return strncmp(s1, s2+2, len2-4);
1302 return strcmp(s1, s2);
1306 * Allocate a new gnu temporal attribute of given kind.
1308 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1310 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1311 attribute->kind = kind;
1312 attribute->next = NULL;
1313 attribute->invalid = false;
1314 attribute->has_arguments = false;
1320 * Parse one constant expression argument of the given attribute.
1322 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1324 expression_t *expression;
1325 add_anchor_token(')');
1326 expression = parse_constant_expression();
1327 rem_anchor_token(')');
1328 expect(')', end_error);
1329 attribute->u.argument = fold_constant(expression);
1332 attribute->invalid = true;
1336 * Parse a list of constant expressions arguments of the given attribute.
1338 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1340 argument_list_t **list = &attribute->u.arguments;
1341 argument_list_t *entry;
1342 expression_t *expression;
1343 add_anchor_token(')');
1344 add_anchor_token(',');
1346 expression = parse_constant_expression();
1347 entry = obstack_alloc(&temp_obst, sizeof(entry));
1348 entry->argument = fold_constant(expression);
1351 list = &entry->next;
1352 if (token.type != ',')
1356 rem_anchor_token(',');
1357 rem_anchor_token(')');
1358 expect(')', end_error);
1361 attribute->invalid = true;
1365 * Parse one string literal argument of the given attribute.
1367 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1370 add_anchor_token('(');
1371 if (token.type != T_STRING_LITERAL) {
1372 parse_error_expected("while parsing attribute directive",
1373 T_STRING_LITERAL, NULL);
1376 *string = parse_string_literals();
1377 rem_anchor_token('(');
1378 expect(')', end_error);
1381 attribute->invalid = true;
1385 * Parse one tls model of the given attribute.
1387 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1389 static const char *const tls_models[] = {
1395 string_t string = { NULL, 0 };
1396 parse_gnu_attribute_string_arg(attribute, &string);
1397 if (string.begin != NULL) {
1398 for (size_t i = 0; i < 4; ++i) {
1399 if (strcmp(tls_models[i], string.begin) == 0) {
1400 attribute->u.value = i;
1404 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1406 attribute->invalid = true;
1410 * Parse one tls model of the given attribute.
1412 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1414 static const char *const visibilities[] = {
1420 string_t string = { NULL, 0 };
1421 parse_gnu_attribute_string_arg(attribute, &string);
1422 if (string.begin != NULL) {
1423 for (size_t i = 0; i < 4; ++i) {
1424 if (strcmp(visibilities[i], string.begin) == 0) {
1425 attribute->u.value = i;
1429 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1431 attribute->invalid = true;
1435 * Parse one (code) model of the given attribute.
1437 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1439 static const char *const visibilities[] = {
1444 string_t string = { NULL, 0 };
1445 parse_gnu_attribute_string_arg(attribute, &string);
1446 if (string.begin != NULL) {
1447 for (int i = 0; i < 3; ++i) {
1448 if (strcmp(visibilities[i], string.begin) == 0) {
1449 attribute->u.value = i;
1453 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1455 attribute->invalid = true;
1459 * Parse one mode of the given attribute.
1461 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1463 add_anchor_token(')');
1465 if (token.type != T_IDENTIFIER) {
1466 expect(T_IDENTIFIER, end_error);
1469 attribute->u.symbol = token.v.symbol;
1472 rem_anchor_token(')');
1473 expect(')', end_error);
1476 attribute->invalid = true;
1480 * Parse one interrupt argument of the given attribute.
1482 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1484 static const char *const interrupts[] = {
1491 string_t string = { NULL, 0 };
1492 parse_gnu_attribute_string_arg(attribute, &string);
1493 if (string.begin != NULL) {
1494 for (size_t i = 0; i < 5; ++i) {
1495 if (strcmp(interrupts[i], string.begin) == 0) {
1496 attribute->u.value = i;
1500 errorf(HERE, "'%s' is not an interrupt", string.begin);
1502 attribute->invalid = true;
1506 * Parse ( identifier, const expression, const expression )
1508 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1510 static const char *const format_names[] = {
1518 if (token.type != T_IDENTIFIER) {
1519 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1522 const char *name = token.v.symbol->string;
1523 for (i = 0; i < 4; ++i) {
1524 if (strcmp_underscore(format_names[i], name) == 0)
1528 if (warning.attribute)
1529 warningf(HERE, "'%s' is an unrecognized format function type", name);
1533 expect(',', end_error);
1534 add_anchor_token(')');
1535 add_anchor_token(',');
1536 parse_constant_expression();
1537 rem_anchor_token(',');
1538 rem_anchor_token(')');
1540 expect(',', end_error);
1541 add_anchor_token(')');
1542 parse_constant_expression();
1543 rem_anchor_token(')');
1544 expect(')', end_error);
1547 attribute->u.value = true;
1551 * Check that a given GNU attribute has no arguments.
1553 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1555 if (!attribute->has_arguments)
1558 /* should have no arguments */
1559 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1560 eat_until_matching_token('(');
1561 /* we have already consumed '(', so we stop before ')', eat it */
1563 attribute->invalid = true;
1567 * Parse one GNU attribute.
1569 * Note that attribute names can be specified WITH or WITHOUT
1570 * double underscores, ie const or __const__.
1572 * The following attributes are parsed without arguments
1597 * no_instrument_function
1598 * warn_unused_result
1615 * externally_visible
1623 * The following attributes are parsed with arguments
1624 * aligned( const expression )
1625 * alias( string literal )
1626 * section( string literal )
1627 * format( identifier, const expression, const expression )
1628 * format_arg( const expression )
1629 * tls_model( string literal )
1630 * visibility( string literal )
1631 * regparm( const expression )
1632 * model( string leteral )
1633 * trap_exit( const expression )
1634 * sp_switch( string literal )
1636 * The following attributes might have arguments
1637 * weak_ref( string literal )
1638 * non_null( const expression // ',' )
1639 * interrupt( string literal )
1640 * sentinel( constant expression )
1642 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1644 gnu_attribute_t *head = *attributes;
1645 gnu_attribute_t *last = *attributes;
1646 decl_modifiers_t modifiers = 0;
1647 gnu_attribute_t *attribute;
1649 eat(T___attribute__);
1650 expect('(', end_error);
1651 expect('(', end_error);
1653 if (token.type != ')') {
1654 /* find the end of the list */
1656 while (last->next != NULL)
1660 /* non-empty attribute list */
1663 if (token.type == T_const) {
1665 } else if (token.type == T_volatile) {
1667 } else if (token.type == T_cdecl) {
1668 /* __attribute__((cdecl)), WITH ms mode */
1670 } else if (token.type == T_IDENTIFIER) {
1671 const symbol_t *sym = token.v.symbol;
1674 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1681 for (i = 0; i < GNU_AK_LAST; ++i) {
1682 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1685 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1688 if (kind == GNU_AK_LAST) {
1689 if (warning.attribute)
1690 warningf(HERE, "'%s' attribute directive ignored", name);
1692 /* skip possible arguments */
1693 if (token.type == '(') {
1694 eat_until_matching_token(')');
1697 /* check for arguments */
1698 attribute = allocate_gnu_attribute(kind);
1699 if (token.type == '(') {
1701 if (token.type == ')') {
1702 /* empty args are allowed */
1705 attribute->has_arguments = true;
1709 case GNU_AK_VOLATILE:
1714 case GNU_AK_NOCOMMON:
1716 case GNU_AK_NOTSHARED:
1717 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1718 case GNU_AK_WARN_UNUSED_RESULT:
1719 case GNU_AK_LONGCALL:
1720 case GNU_AK_SHORTCALL:
1721 case GNU_AK_LONG_CALL:
1722 case GNU_AK_SHORT_CALL:
1723 case GNU_AK_FUNCTION_VECTOR:
1724 case GNU_AK_INTERRUPT_HANDLER:
1725 case GNU_AK_NMI_HANDLER:
1726 case GNU_AK_NESTING:
1730 case GNU_AK_EIGTHBIT_DATA:
1731 case GNU_AK_TINY_DATA:
1732 case GNU_AK_SAVEALL:
1733 case GNU_AK_FLATTEN:
1734 case GNU_AK_SSEREGPARM:
1735 case GNU_AK_EXTERNALLY_VISIBLE:
1736 case GNU_AK_RETURN_TWICE:
1737 case GNU_AK_MAY_ALIAS:
1738 case GNU_AK_MS_STRUCT:
1739 case GNU_AK_GCC_STRUCT:
1742 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1743 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1744 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1745 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1746 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1747 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1748 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1749 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1750 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1751 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1752 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1753 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1754 case GNU_AK_RETURNS_TWICE: modifiers |= DM_RETURNS_TWICE; goto no_arg;
1755 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1756 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1757 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1758 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1759 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1760 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1762 case GNU_AK_ALIGNED:
1763 /* __align__ may be used without an argument */
1764 if (attribute->has_arguments) {
1765 parse_gnu_attribute_const_arg(attribute);
1769 case GNU_AK_FORMAT_ARG:
1770 case GNU_AK_REGPARM:
1771 case GNU_AK_TRAP_EXIT:
1772 if (!attribute->has_arguments) {
1773 /* should have arguments */
1774 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1775 attribute->invalid = true;
1777 parse_gnu_attribute_const_arg(attribute);
1780 case GNU_AK_SECTION:
1781 case GNU_AK_SP_SWITCH:
1782 if (!attribute->has_arguments) {
1783 /* should have arguments */
1784 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1785 attribute->invalid = true;
1787 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1790 if (!attribute->has_arguments) {
1791 /* should have arguments */
1792 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1793 attribute->invalid = true;
1795 parse_gnu_attribute_format_args(attribute);
1797 case GNU_AK_WEAKREF:
1798 /* may have one string argument */
1799 if (attribute->has_arguments)
1800 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1802 case GNU_AK_NONNULL:
1803 if (attribute->has_arguments)
1804 parse_gnu_attribute_const_arg_list(attribute);
1806 case GNU_AK_TLS_MODEL:
1807 if (!attribute->has_arguments) {
1808 /* should have arguments */
1809 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1811 parse_gnu_attribute_tls_model_arg(attribute);
1813 case GNU_AK_VISIBILITY:
1814 if (!attribute->has_arguments) {
1815 /* should have arguments */
1816 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1818 parse_gnu_attribute_visibility_arg(attribute);
1821 if (!attribute->has_arguments) {
1822 /* should have arguments */
1823 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1825 parse_gnu_attribute_model_arg(attribute);
1829 if (!attribute->has_arguments) {
1830 /* should have arguments */
1831 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1833 parse_gnu_attribute_mode_arg(attribute);
1836 case GNU_AK_INTERRUPT:
1837 /* may have one string argument */
1838 if (attribute->has_arguments)
1839 parse_gnu_attribute_interrupt_arg(attribute);
1841 case GNU_AK_SENTINEL:
1842 /* may have one string argument */
1843 if (attribute->has_arguments)
1844 parse_gnu_attribute_const_arg(attribute);
1847 /* already handled */
1851 check_no_argument(attribute, name);
1854 if (attribute != NULL) {
1856 last->next = attribute;
1859 head = last = attribute;
1863 if (token.type != ',')
1868 expect(')', end_error);
1869 expect(')', end_error);
1877 * Parse GNU attributes.
1879 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1881 decl_modifiers_t modifiers = 0;
1884 switch (token.type) {
1885 case T___attribute__:
1886 modifiers |= parse_gnu_attribute(attributes);
1891 expect('(', end_error);
1892 if (token.type != T_STRING_LITERAL) {
1893 parse_error_expected("while parsing assembler attribute",
1894 T_STRING_LITERAL, NULL);
1895 eat_until_matching_token('(');
1898 parse_string_literals();
1900 expect(')', end_error);
1903 case T_cdecl: modifiers |= DM_CDECL; break;
1904 case T__fastcall: modifiers |= DM_FASTCALL; break;
1905 case T__stdcall: modifiers |= DM_STDCALL; break;
1908 /* TODO record modifier */
1910 warningf(HERE, "Ignoring declaration modifier %K", &token);
1914 default: return modifiers;
1921 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1923 static entity_t *determine_lhs_ent(expression_t *const expr,
1926 switch (expr->kind) {
1927 case EXPR_REFERENCE: {
1928 entity_t *const entity = expr->reference.entity;
1929 /* we should only find variables as lvalues... */
1930 if (entity->base.kind != ENTITY_VARIABLE
1931 && entity->base.kind != ENTITY_PARAMETER)
1937 case EXPR_ARRAY_ACCESS: {
1938 expression_t *const ref = expr->array_access.array_ref;
1939 entity_t * ent = NULL;
1940 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1941 ent = determine_lhs_ent(ref, lhs_ent);
1944 mark_vars_read(expr->select.compound, lhs_ent);
1946 mark_vars_read(expr->array_access.index, lhs_ent);
1951 if (is_type_compound(skip_typeref(expr->base.type))) {
1952 return determine_lhs_ent(expr->select.compound, lhs_ent);
1954 mark_vars_read(expr->select.compound, lhs_ent);
1959 case EXPR_UNARY_DEREFERENCE: {
1960 expression_t *const val = expr->unary.value;
1961 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1963 return determine_lhs_ent(val->unary.value, lhs_ent);
1965 mark_vars_read(val, NULL);
1971 mark_vars_read(expr, NULL);
1976 #define ENT_ANY ((entity_t*)-1)
1979 * Mark declarations, which are read. This is used to detect variables, which
1983 * x is not marked as "read", because it is only read to calculate its own new
1987 * x and y are not detected as "not read", because multiple variables are
1990 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1992 switch (expr->kind) {
1993 case EXPR_REFERENCE: {
1994 entity_t *const entity = expr->reference.entity;
1995 if (entity->kind != ENTITY_VARIABLE
1996 && entity->kind != ENTITY_PARAMETER)
1999 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
2000 if (entity->kind == ENTITY_VARIABLE) {
2001 entity->variable.read = true;
2003 entity->parameter.read = true;
2010 // TODO respect pure/const
2011 mark_vars_read(expr->call.function, NULL);
2012 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
2013 mark_vars_read(arg->expression, NULL);
2017 case EXPR_CONDITIONAL:
2018 // TODO lhs_decl should depend on whether true/false have an effect
2019 mark_vars_read(expr->conditional.condition, NULL);
2020 if (expr->conditional.true_expression != NULL)
2021 mark_vars_read(expr->conditional.true_expression, lhs_ent);
2022 mark_vars_read(expr->conditional.false_expression, lhs_ent);
2026 if (lhs_ent == ENT_ANY
2027 && !is_type_compound(skip_typeref(expr->base.type)))
2029 mark_vars_read(expr->select.compound, lhs_ent);
2032 case EXPR_ARRAY_ACCESS: {
2033 expression_t *const ref = expr->array_access.array_ref;
2034 mark_vars_read(ref, lhs_ent);
2035 lhs_ent = determine_lhs_ent(ref, lhs_ent);
2036 mark_vars_read(expr->array_access.index, lhs_ent);
2041 mark_vars_read(expr->va_arge.ap, lhs_ent);
2044 case EXPR_UNARY_CAST:
2045 /* Special case: Use void cast to mark a variable as "read" */
2046 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2051 case EXPR_UNARY_THROW:
2052 if (expr->unary.value == NULL)
2055 case EXPR_UNARY_DEREFERENCE:
2056 case EXPR_UNARY_DELETE:
2057 case EXPR_UNARY_DELETE_ARRAY:
2058 if (lhs_ent == ENT_ANY)
2062 case EXPR_UNARY_NEGATE:
2063 case EXPR_UNARY_PLUS:
2064 case EXPR_UNARY_BITWISE_NEGATE:
2065 case EXPR_UNARY_NOT:
2066 case EXPR_UNARY_TAKE_ADDRESS:
2067 case EXPR_UNARY_POSTFIX_INCREMENT:
2068 case EXPR_UNARY_POSTFIX_DECREMENT:
2069 case EXPR_UNARY_PREFIX_INCREMENT:
2070 case EXPR_UNARY_PREFIX_DECREMENT:
2071 case EXPR_UNARY_CAST_IMPLICIT:
2072 case EXPR_UNARY_ASSUME:
2074 mark_vars_read(expr->unary.value, lhs_ent);
2077 case EXPR_BINARY_ADD:
2078 case EXPR_BINARY_SUB:
2079 case EXPR_BINARY_MUL:
2080 case EXPR_BINARY_DIV:
2081 case EXPR_BINARY_MOD:
2082 case EXPR_BINARY_EQUAL:
2083 case EXPR_BINARY_NOTEQUAL:
2084 case EXPR_BINARY_LESS:
2085 case EXPR_BINARY_LESSEQUAL:
2086 case EXPR_BINARY_GREATER:
2087 case EXPR_BINARY_GREATEREQUAL:
2088 case EXPR_BINARY_BITWISE_AND:
2089 case EXPR_BINARY_BITWISE_OR:
2090 case EXPR_BINARY_BITWISE_XOR:
2091 case EXPR_BINARY_LOGICAL_AND:
2092 case EXPR_BINARY_LOGICAL_OR:
2093 case EXPR_BINARY_SHIFTLEFT:
2094 case EXPR_BINARY_SHIFTRIGHT:
2095 case EXPR_BINARY_COMMA:
2096 case EXPR_BINARY_ISGREATER:
2097 case EXPR_BINARY_ISGREATEREQUAL:
2098 case EXPR_BINARY_ISLESS:
2099 case EXPR_BINARY_ISLESSEQUAL:
2100 case EXPR_BINARY_ISLESSGREATER:
2101 case EXPR_BINARY_ISUNORDERED:
2102 mark_vars_read(expr->binary.left, lhs_ent);
2103 mark_vars_read(expr->binary.right, lhs_ent);
2106 case EXPR_BINARY_ASSIGN:
2107 case EXPR_BINARY_MUL_ASSIGN:
2108 case EXPR_BINARY_DIV_ASSIGN:
2109 case EXPR_BINARY_MOD_ASSIGN:
2110 case EXPR_BINARY_ADD_ASSIGN:
2111 case EXPR_BINARY_SUB_ASSIGN:
2112 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2113 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2114 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2115 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2116 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2117 if (lhs_ent == ENT_ANY)
2119 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
2120 mark_vars_read(expr->binary.right, lhs_ent);
2125 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
2131 case EXPR_CHARACTER_CONSTANT:
2132 case EXPR_WIDE_CHARACTER_CONSTANT:
2133 case EXPR_STRING_LITERAL:
2134 case EXPR_WIDE_STRING_LITERAL:
2135 case EXPR_COMPOUND_LITERAL: // TODO init?
2137 case EXPR_CLASSIFY_TYPE:
2140 case EXPR_BUILTIN_SYMBOL:
2141 case EXPR_BUILTIN_CONSTANT_P:
2142 case EXPR_BUILTIN_PREFETCH:
2144 case EXPR_STATEMENT: // TODO
2145 case EXPR_LABEL_ADDRESS:
2146 case EXPR_REFERENCE_ENUM_VALUE:
2150 panic("unhandled expression");
2153 static designator_t *parse_designation(void)
2155 designator_t *result = NULL;
2156 designator_t *last = NULL;
2159 designator_t *designator;
2160 switch (token.type) {
2162 designator = allocate_ast_zero(sizeof(designator[0]));
2163 designator->source_position = token.source_position;
2165 add_anchor_token(']');
2166 designator->array_index = parse_constant_expression();
2167 rem_anchor_token(']');
2168 expect(']', end_error);
2171 designator = allocate_ast_zero(sizeof(designator[0]));
2172 designator->source_position = token.source_position;
2174 if (token.type != T_IDENTIFIER) {
2175 parse_error_expected("while parsing designator",
2176 T_IDENTIFIER, NULL);
2179 designator->symbol = token.v.symbol;
2183 expect('=', end_error);
2187 assert(designator != NULL);
2189 last->next = designator;
2191 result = designator;
2199 static initializer_t *initializer_from_string(array_type_t *type,
2200 const string_t *const string)
2202 /* TODO: check len vs. size of array type */
2205 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2206 initializer->string.string = *string;
2211 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2212 wide_string_t *const string)
2214 /* TODO: check len vs. size of array type */
2217 initializer_t *const initializer =
2218 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2219 initializer->wide_string.string = *string;
2225 * Build an initializer from a given expression.
2227 static initializer_t *initializer_from_expression(type_t *orig_type,
2228 expression_t *expression)
2230 /* TODO check that expression is a constant expression */
2232 /* § 6.7.8.14/15 char array may be initialized by string literals */
2233 type_t *type = skip_typeref(orig_type);
2234 type_t *expr_type_orig = expression->base.type;
2235 type_t *expr_type = skip_typeref(expr_type_orig);
2236 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2237 array_type_t *const array_type = &type->array;
2238 type_t *const element_type = skip_typeref(array_type->element_type);
2240 if (element_type->kind == TYPE_ATOMIC) {
2241 atomic_type_kind_t akind = element_type->atomic.akind;
2242 switch (expression->kind) {
2243 case EXPR_STRING_LITERAL:
2244 if (akind == ATOMIC_TYPE_CHAR
2245 || akind == ATOMIC_TYPE_SCHAR
2246 || akind == ATOMIC_TYPE_UCHAR) {
2247 return initializer_from_string(array_type,
2248 &expression->string.value);
2252 case EXPR_WIDE_STRING_LITERAL: {
2253 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2254 if (get_unqualified_type(element_type) == bare_wchar_type) {
2255 return initializer_from_wide_string(array_type,
2256 &expression->wide_string.value);
2267 assign_error_t error = semantic_assign(type, expression);
2268 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2270 report_assign_error(error, type, expression, "initializer",
2271 &expression->base.source_position);
2273 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2275 if (type->kind == TYPE_BITFIELD) {
2276 type = type->bitfield.base_type;
2279 result->value.value = create_implicit_cast(expression, type);
2285 * Checks if a given expression can be used as an constant initializer.
2287 static bool is_initializer_constant(const expression_t *expression)
2289 return is_constant_expression(expression)
2290 || is_address_constant(expression);
2294 * Parses an scalar initializer.
2296 * § 6.7.8.11; eat {} without warning
2298 static initializer_t *parse_scalar_initializer(type_t *type,
2299 bool must_be_constant)
2301 /* there might be extra {} hierarchies */
2303 if (token.type == '{') {
2305 warningf(HERE, "extra curly braces around scalar initializer");
2309 } while (token.type == '{');
2312 expression_t *expression = parse_assignment_expression();
2313 mark_vars_read(expression, NULL);
2314 if (must_be_constant && !is_initializer_constant(expression)) {
2315 errorf(&expression->base.source_position,
2316 "Initialisation expression '%E' is not constant",
2320 initializer_t *initializer = initializer_from_expression(type, expression);
2322 if (initializer == NULL) {
2323 errorf(&expression->base.source_position,
2324 "expression '%E' (type '%T') doesn't match expected type '%T'",
2325 expression, expression->base.type, type);
2330 bool additional_warning_displayed = false;
2331 while (braces > 0) {
2332 if (token.type == ',') {
2335 if (token.type != '}') {
2336 if (!additional_warning_displayed && warning.other) {
2337 warningf(HERE, "additional elements in scalar initializer");
2338 additional_warning_displayed = true;
2349 * An entry in the type path.
2351 typedef struct type_path_entry_t type_path_entry_t;
2352 struct type_path_entry_t {
2353 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2355 size_t index; /**< For array types: the current index. */
2356 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2361 * A type path expression a position inside compound or array types.
2363 typedef struct type_path_t type_path_t;
2364 struct type_path_t {
2365 type_path_entry_t *path; /**< An flexible array containing the current path. */
2366 type_t *top_type; /**< type of the element the path points */
2367 size_t max_index; /**< largest index in outermost array */
2371 * Prints a type path for debugging.
2373 static __attribute__((unused)) void debug_print_type_path(
2374 const type_path_t *path)
2376 size_t len = ARR_LEN(path->path);
2378 for (size_t i = 0; i < len; ++i) {
2379 const type_path_entry_t *entry = & path->path[i];
2381 type_t *type = skip_typeref(entry->type);
2382 if (is_type_compound(type)) {
2383 /* in gcc mode structs can have no members */
2384 if (entry->v.compound_entry == NULL) {
2388 fprintf(stderr, ".%s",
2389 entry->v.compound_entry->base.symbol->string);
2390 } else if (is_type_array(type)) {
2391 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
2393 fprintf(stderr, "-INVALID-");
2396 if (path->top_type != NULL) {
2397 fprintf(stderr, " (");
2398 print_type(path->top_type);
2399 fprintf(stderr, ")");
2404 * Return the top type path entry, ie. in a path
2405 * (type).a.b returns the b.
2407 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2409 size_t len = ARR_LEN(path->path);
2411 return &path->path[len-1];
2415 * Enlarge the type path by an (empty) element.
2417 static type_path_entry_t *append_to_type_path(type_path_t *path)
2419 size_t len = ARR_LEN(path->path);
2420 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2422 type_path_entry_t *result = & path->path[len];
2423 memset(result, 0, sizeof(result[0]));
2428 * Descending into a sub-type. Enter the scope of the current top_type.
2430 static void descend_into_subtype(type_path_t *path)
2432 type_t *orig_top_type = path->top_type;
2433 type_t *top_type = skip_typeref(orig_top_type);
2435 type_path_entry_t *top = append_to_type_path(path);
2436 top->type = top_type;
2438 if (is_type_compound(top_type)) {
2439 compound_t *compound = top_type->compound.compound;
2440 entity_t *entry = compound->members.entities;
2442 if (entry != NULL) {
2443 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2444 top->v.compound_entry = &entry->declaration;
2445 path->top_type = entry->declaration.type;
2447 path->top_type = NULL;
2449 } else if (is_type_array(top_type)) {
2451 path->top_type = top_type->array.element_type;
2453 assert(!is_type_valid(top_type));
2458 * Pop an entry from the given type path, ie. returning from
2459 * (type).a.b to (type).a
2461 static void ascend_from_subtype(type_path_t *path)
2463 type_path_entry_t *top = get_type_path_top(path);
2465 path->top_type = top->type;
2467 size_t len = ARR_LEN(path->path);
2468 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2472 * Pop entries from the given type path until the given
2473 * path level is reached.
2475 static void ascend_to(type_path_t *path, size_t top_path_level)
2477 size_t len = ARR_LEN(path->path);
2479 while (len > top_path_level) {
2480 ascend_from_subtype(path);
2481 len = ARR_LEN(path->path);
2485 static bool walk_designator(type_path_t *path, const designator_t *designator,
2486 bool used_in_offsetof)
2488 for (; designator != NULL; designator = designator->next) {
2489 type_path_entry_t *top = get_type_path_top(path);
2490 type_t *orig_type = top->type;
2492 type_t *type = skip_typeref(orig_type);
2494 if (designator->symbol != NULL) {
2495 symbol_t *symbol = designator->symbol;
2496 if (!is_type_compound(type)) {
2497 if (is_type_valid(type)) {
2498 errorf(&designator->source_position,
2499 "'.%Y' designator used for non-compound type '%T'",
2503 top->type = type_error_type;
2504 top->v.compound_entry = NULL;
2505 orig_type = type_error_type;
2507 compound_t *compound = type->compound.compound;
2508 entity_t *iter = compound->members.entities;
2509 for (; iter != NULL; iter = iter->base.next) {
2510 if (iter->base.symbol == symbol) {
2515 errorf(&designator->source_position,
2516 "'%T' has no member named '%Y'", orig_type, symbol);
2519 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2520 if (used_in_offsetof) {
2521 type_t *real_type = skip_typeref(iter->declaration.type);
2522 if (real_type->kind == TYPE_BITFIELD) {
2523 errorf(&designator->source_position,
2524 "offsetof designator '%Y' may not specify bitfield",
2530 top->type = orig_type;
2531 top->v.compound_entry = &iter->declaration;
2532 orig_type = iter->declaration.type;
2535 expression_t *array_index = designator->array_index;
2536 assert(designator->array_index != NULL);
2538 if (!is_type_array(type)) {
2539 if (is_type_valid(type)) {
2540 errorf(&designator->source_position,
2541 "[%E] designator used for non-array type '%T'",
2542 array_index, orig_type);
2547 long index = fold_constant(array_index);
2548 if (!used_in_offsetof) {
2550 errorf(&designator->source_position,
2551 "array index [%E] must be positive", array_index);
2552 } else if (type->array.size_constant) {
2553 long array_size = type->array.size;
2554 if (index >= array_size) {
2555 errorf(&designator->source_position,
2556 "designator [%E] (%d) exceeds array size %d",
2557 array_index, index, array_size);
2562 top->type = orig_type;
2563 top->v.index = (size_t) index;
2564 orig_type = type->array.element_type;
2566 path->top_type = orig_type;
2568 if (designator->next != NULL) {
2569 descend_into_subtype(path);
2578 static void advance_current_object(type_path_t *path, size_t top_path_level)
2580 type_path_entry_t *top = get_type_path_top(path);
2582 type_t *type = skip_typeref(top->type);
2583 if (is_type_union(type)) {
2584 /* in unions only the first element is initialized */
2585 top->v.compound_entry = NULL;
2586 } else if (is_type_struct(type)) {
2587 declaration_t *entry = top->v.compound_entry;
2589 entity_t *next_entity = entry->base.next;
2590 if (next_entity != NULL) {
2591 assert(is_declaration(next_entity));
2592 entry = &next_entity->declaration;
2597 top->v.compound_entry = entry;
2598 if (entry != NULL) {
2599 path->top_type = entry->type;
2602 } else if (is_type_array(type)) {
2603 assert(is_type_array(type));
2607 if (!type->array.size_constant || top->v.index < type->array.size) {
2611 assert(!is_type_valid(type));
2615 /* we're past the last member of the current sub-aggregate, try if we
2616 * can ascend in the type hierarchy and continue with another subobject */
2617 size_t len = ARR_LEN(path->path);
2619 if (len > top_path_level) {
2620 ascend_from_subtype(path);
2621 advance_current_object(path, top_path_level);
2623 path->top_type = NULL;
2628 * skip until token is found.
2630 static void skip_until(int type)
2632 while (token.type != type) {
2633 if (token.type == T_EOF)
2640 * skip any {...} blocks until a closing bracket is reached.
2642 static void skip_initializers(void)
2644 if (token.type == '{')
2647 while (token.type != '}') {
2648 if (token.type == T_EOF)
2650 if (token.type == '{') {
2658 static initializer_t *create_empty_initializer(void)
2660 static initializer_t empty_initializer
2661 = { .list = { { INITIALIZER_LIST }, 0 } };
2662 return &empty_initializer;
2666 * Parse a part of an initialiser for a struct or union,
2668 static initializer_t *parse_sub_initializer(type_path_t *path,
2669 type_t *outer_type, size_t top_path_level,
2670 parse_initializer_env_t *env)
2672 if (token.type == '}') {
2673 /* empty initializer */
2674 return create_empty_initializer();
2677 type_t *orig_type = path->top_type;
2678 type_t *type = NULL;
2680 if (orig_type == NULL) {
2681 /* We are initializing an empty compound. */
2683 type = skip_typeref(orig_type);
2686 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2689 designator_t *designator = NULL;
2690 if (token.type == '.' || token.type == '[') {
2691 designator = parse_designation();
2692 goto finish_designator;
2693 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2694 /* GNU-style designator ("identifier: value") */
2695 designator = allocate_ast_zero(sizeof(designator[0]));
2696 designator->source_position = token.source_position;
2697 designator->symbol = token.v.symbol;
2702 /* reset path to toplevel, evaluate designator from there */
2703 ascend_to(path, top_path_level);
2704 if (!walk_designator(path, designator, false)) {
2705 /* can't continue after designation error */
2709 initializer_t *designator_initializer
2710 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2711 designator_initializer->designator.designator = designator;
2712 ARR_APP1(initializer_t*, initializers, designator_initializer);
2714 orig_type = path->top_type;
2715 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2720 if (token.type == '{') {
2721 if (type != NULL && is_type_scalar(type)) {
2722 sub = parse_scalar_initializer(type, env->must_be_constant);
2726 if (env->entity != NULL) {
2728 "extra brace group at end of initializer for '%Y'",
2729 env->entity->base.symbol);
2731 errorf(HERE, "extra brace group at end of initializer");
2734 descend_into_subtype(path);
2736 add_anchor_token('}');
2737 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2739 rem_anchor_token('}');
2742 ascend_from_subtype(path);
2743 expect('}', end_error);
2745 expect('}', end_error);
2746 goto error_parse_next;
2750 /* must be an expression */
2751 expression_t *expression = parse_assignment_expression();
2752 mark_vars_read(expression, NULL);
2754 if (env->must_be_constant && !is_initializer_constant(expression)) {
2755 errorf(&expression->base.source_position,
2756 "Initialisation expression '%E' is not constant",
2761 /* we are already outside, ... */
2762 type_t *const outer_type_skip = skip_typeref(outer_type);
2763 if (is_type_compound(outer_type_skip) &&
2764 !outer_type_skip->compound.compound->complete) {
2765 goto error_parse_next;
2770 /* handle { "string" } special case */
2771 if ((expression->kind == EXPR_STRING_LITERAL
2772 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2773 && outer_type != NULL) {
2774 sub = initializer_from_expression(outer_type, expression);
2776 if (token.type == ',') {
2779 if (token.type != '}' && warning.other) {
2780 warningf(HERE, "excessive elements in initializer for type '%T'",
2783 /* TODO: eat , ... */
2788 /* descend into subtypes until expression matches type */
2790 orig_type = path->top_type;
2791 type = skip_typeref(orig_type);
2793 sub = initializer_from_expression(orig_type, expression);
2797 if (!is_type_valid(type)) {
2800 if (is_type_scalar(type)) {
2801 errorf(&expression->base.source_position,
2802 "expression '%E' doesn't match expected type '%T'",
2803 expression, orig_type);
2807 descend_into_subtype(path);
2811 /* update largest index of top array */
2812 const type_path_entry_t *first = &path->path[0];
2813 type_t *first_type = first->type;
2814 first_type = skip_typeref(first_type);
2815 if (is_type_array(first_type)) {
2816 size_t index = first->v.index;
2817 if (index > path->max_index)
2818 path->max_index = index;
2822 /* append to initializers list */
2823 ARR_APP1(initializer_t*, initializers, sub);
2826 if (warning.other) {
2827 if (env->entity != NULL) {
2828 warningf(HERE, "excess elements in struct initializer for '%Y'",
2829 env->entity->base.symbol);
2831 warningf(HERE, "excess elements in struct initializer");
2837 if (token.type == '}') {
2840 expect(',', end_error);
2841 if (token.type == '}') {
2846 /* advance to the next declaration if we are not at the end */
2847 advance_current_object(path, top_path_level);
2848 orig_type = path->top_type;
2849 if (orig_type != NULL)
2850 type = skip_typeref(orig_type);
2856 size_t len = ARR_LEN(initializers);
2857 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2858 initializer_t *result = allocate_ast_zero(size);
2859 result->kind = INITIALIZER_LIST;
2860 result->list.len = len;
2861 memcpy(&result->list.initializers, initializers,
2862 len * sizeof(initializers[0]));
2864 DEL_ARR_F(initializers);
2865 ascend_to(path, top_path_level+1);
2870 skip_initializers();
2871 DEL_ARR_F(initializers);
2872 ascend_to(path, top_path_level+1);
2877 * Parses an initializer. Parsers either a compound literal
2878 * (env->declaration == NULL) or an initializer of a declaration.
2880 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2882 type_t *type = skip_typeref(env->type);
2883 size_t max_index = 0xdeadbeaf; // TODO: Resolve this uninitialized variable problem
2884 initializer_t *result;
2886 if (is_type_scalar(type)) {
2887 result = parse_scalar_initializer(type, env->must_be_constant);
2888 } else if (token.type == '{') {
2892 memset(&path, 0, sizeof(path));
2893 path.top_type = env->type;
2894 path.path = NEW_ARR_F(type_path_entry_t, 0);
2896 descend_into_subtype(&path);
2898 add_anchor_token('}');
2899 result = parse_sub_initializer(&path, env->type, 1, env);
2900 rem_anchor_token('}');
2902 max_index = path.max_index;
2903 DEL_ARR_F(path.path);
2905 expect('}', end_error);
2907 /* parse_scalar_initializer() also works in this case: we simply
2908 * have an expression without {} around it */
2909 result = parse_scalar_initializer(type, env->must_be_constant);
2912 /* § 6.7.8:22 array initializers for arrays with unknown size determine
2913 * the array type size */
2914 if (is_type_array(type) && type->array.size_expression == NULL
2915 && result != NULL) {
2917 switch (result->kind) {
2918 case INITIALIZER_LIST:
2919 assert(max_index != 0xdeadbeaf);
2920 size = max_index + 1;
2923 case INITIALIZER_STRING:
2924 size = result->string.string.size;
2927 case INITIALIZER_WIDE_STRING:
2928 size = result->wide_string.string.size;
2931 case INITIALIZER_DESIGNATOR:
2932 case INITIALIZER_VALUE:
2933 /* can happen for parse errors */
2938 internal_errorf(HERE, "invalid initializer type");
2941 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2942 cnst->base.type = type_size_t;
2943 cnst->conste.v.int_value = size;
2945 type_t *new_type = duplicate_type(type);
2947 new_type->array.size_expression = cnst;
2948 new_type->array.size_constant = true;
2949 new_type->array.has_implicit_size = true;
2950 new_type->array.size = size;
2951 env->type = new_type;
2959 static void append_entity(scope_t *scope, entity_t *entity)
2961 if (scope->last_entity != NULL) {
2962 scope->last_entity->base.next = entity;
2964 scope->entities = entity;
2966 scope->last_entity = entity;
2970 static compound_t *parse_compound_type_specifier(bool is_struct)
2972 gnu_attribute_t *attributes = NULL;
2973 decl_modifiers_t modifiers = 0;
2980 symbol_t *symbol = NULL;
2981 compound_t *compound = NULL;
2983 if (token.type == T___attribute__) {
2984 modifiers |= parse_attributes(&attributes);
2987 if (token.type == T_IDENTIFIER) {
2988 symbol = token.v.symbol;
2991 namespace_tag_t const namespc =
2992 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2993 entity_t *entity = get_entity(symbol, namespc);
2994 if (entity != NULL) {
2995 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
2996 compound = &entity->compound;
2997 if (compound->base.parent_scope != current_scope &&
2998 (token.type == '{' || token.type == ';')) {
2999 /* we're in an inner scope and have a definition. Shadow
3000 * existing definition in outer scope */
3002 } else if (compound->complete && token.type == '{') {
3003 assert(symbol != NULL);
3004 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
3005 is_struct ? "struct" : "union", symbol,
3006 &compound->base.source_position);
3007 /* clear members in the hope to avoid further errors */
3008 compound->members.entities = NULL;
3011 } else if (token.type != '{') {
3013 parse_error_expected("while parsing struct type specifier",
3014 T_IDENTIFIER, '{', NULL);
3016 parse_error_expected("while parsing union type specifier",
3017 T_IDENTIFIER, '{', NULL);
3023 if (compound == NULL) {
3024 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
3025 entity_t *entity = allocate_entity_zero(kind);
3026 compound = &entity->compound;
3028 compound->base.namespc =
3029 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
3030 compound->base.source_position = token.source_position;
3031 compound->base.symbol = symbol;
3032 compound->base.parent_scope = current_scope;
3033 if (symbol != NULL) {
3034 environment_push(entity);
3036 append_entity(current_scope, entity);
3039 if (token.type == '{') {
3040 parse_compound_type_entries(compound);
3041 modifiers |= parse_attributes(&attributes);
3043 if (symbol == NULL) {
3044 assert(anonymous_entity == NULL);
3045 anonymous_entity = (entity_t*)compound;
3049 compound->modifiers |= modifiers;
3053 static void parse_enum_entries(type_t *const enum_type)
3057 if (token.type == '}') {
3058 errorf(HERE, "empty enum not allowed");
3063 add_anchor_token('}');
3065 if (token.type != T_IDENTIFIER) {
3066 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3068 rem_anchor_token('}');
3072 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3073 entity->enum_value.enum_type = enum_type;
3074 entity->base.symbol = token.v.symbol;
3075 entity->base.source_position = token.source_position;
3078 if (token.type == '=') {
3080 expression_t *value = parse_constant_expression();
3082 value = create_implicit_cast(value, enum_type);
3083 entity->enum_value.value = value;
3088 record_entity(entity, false);
3090 if (token.type != ',')
3093 } while (token.type != '}');
3094 rem_anchor_token('}');
3096 expect('}', end_error);
3102 static type_t *parse_enum_specifier(void)
3104 gnu_attribute_t *attributes = NULL;
3109 if (token.type == T_IDENTIFIER) {
3110 symbol = token.v.symbol;
3113 entity = get_entity(symbol, NAMESPACE_ENUM);
3114 if (entity != NULL) {
3115 assert(entity->kind == ENTITY_ENUM);
3116 if (entity->base.parent_scope != current_scope &&
3117 (token.type == '{' || token.type == ';')) {
3118 /* we're in an inner scope and have a definition. Shadow
3119 * existing definition in outer scope */
3121 } else if (entity->enume.complete && token.type == '{') {
3122 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
3123 symbol, &entity->base.source_position);
3126 } else if (token.type != '{') {
3127 parse_error_expected("while parsing enum type specifier",
3128 T_IDENTIFIER, '{', NULL);
3135 if (entity == NULL) {
3136 entity = allocate_entity_zero(ENTITY_ENUM);
3137 entity->base.namespc = NAMESPACE_ENUM;
3138 entity->base.source_position = token.source_position;
3139 entity->base.symbol = symbol;
3140 entity->base.parent_scope = current_scope;
3143 type_t *const type = allocate_type_zero(TYPE_ENUM);
3144 type->enumt.enume = &entity->enume;
3145 type->enumt.akind = ATOMIC_TYPE_INT;
3147 if (token.type == '{') {
3148 if (symbol != NULL) {
3149 environment_push(entity);
3151 append_entity(current_scope, entity);
3152 entity->enume.complete = true;
3154 parse_enum_entries(type);
3155 parse_attributes(&attributes);
3157 if (symbol == NULL) {
3158 assert(anonymous_entity == NULL);
3159 anonymous_entity = entity;
3161 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
3162 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
3170 * if a symbol is a typedef to another type, return true
3172 static bool is_typedef_symbol(symbol_t *symbol)
3174 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3175 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3178 static type_t *parse_typeof(void)
3184 expect('(', end_error);
3185 add_anchor_token(')');
3187 expression_t *expression = NULL;
3189 bool old_type_prop = in_type_prop;
3190 bool old_gcc_extension = in_gcc_extension;
3191 in_type_prop = true;
3193 while (token.type == T___extension__) {
3194 /* This can be a prefix to a typename or an expression. */
3196 in_gcc_extension = true;
3198 switch (token.type) {
3200 if (is_typedef_symbol(token.v.symbol)) {
3201 type = parse_typename();
3203 expression = parse_expression();
3204 type = expression->base.type;
3209 type = parse_typename();
3213 expression = parse_expression();
3214 type = expression->base.type;
3217 in_type_prop = old_type_prop;
3218 in_gcc_extension = old_gcc_extension;
3220 rem_anchor_token(')');
3221 expect(')', end_error);
3223 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3224 typeof_type->typeoft.expression = expression;
3225 typeof_type->typeoft.typeof_type = type;
3232 typedef enum specifiers_t {
3233 SPECIFIER_SIGNED = 1 << 0,
3234 SPECIFIER_UNSIGNED = 1 << 1,
3235 SPECIFIER_LONG = 1 << 2,
3236 SPECIFIER_INT = 1 << 3,
3237 SPECIFIER_DOUBLE = 1 << 4,
3238 SPECIFIER_CHAR = 1 << 5,
3239 SPECIFIER_WCHAR_T = 1 << 6,
3240 SPECIFIER_SHORT = 1 << 7,
3241 SPECIFIER_LONG_LONG = 1 << 8,
3242 SPECIFIER_FLOAT = 1 << 9,
3243 SPECIFIER_BOOL = 1 << 10,
3244 SPECIFIER_VOID = 1 << 11,
3245 SPECIFIER_INT8 = 1 << 12,
3246 SPECIFIER_INT16 = 1 << 13,
3247 SPECIFIER_INT32 = 1 << 14,
3248 SPECIFIER_INT64 = 1 << 15,
3249 SPECIFIER_INT128 = 1 << 16,
3250 SPECIFIER_COMPLEX = 1 << 17,
3251 SPECIFIER_IMAGINARY = 1 << 18,
3254 static type_t *create_builtin_type(symbol_t *const symbol,
3255 type_t *const real_type)
3257 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3258 type->builtin.symbol = symbol;
3259 type->builtin.real_type = real_type;
3260 return identify_new_type(type);
3263 static type_t *get_typedef_type(symbol_t *symbol)
3265 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3266 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3269 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3270 type->typedeft.typedefe = &entity->typedefe;
3276 * check for the allowed MS alignment values.
3278 static bool check_alignment_value(long long intvalue)
3280 if (intvalue < 1 || intvalue > 8192) {
3281 errorf(HERE, "illegal alignment value");
3284 unsigned v = (unsigned)intvalue;
3285 for (unsigned i = 1; i <= 8192; i += i) {
3289 errorf(HERE, "alignment must be power of two");
3293 #define DET_MOD(name, tag) do { \
3294 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3295 *modifiers |= tag; \
3298 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3300 decl_modifiers_t *modifiers = &specifiers->modifiers;
3303 if (token.type == T_restrict) {
3305 DET_MOD(restrict, DM_RESTRICT);
3307 } else if (token.type != T_IDENTIFIER)
3309 symbol_t *symbol = token.v.symbol;
3310 if (symbol == sym_align) {
3312 expect('(', end_error);
3313 if (token.type != T_INTEGER)
3315 if (check_alignment_value(token.v.intvalue)) {
3316 if (specifiers->alignment != 0 && warning.other)
3317 warningf(HERE, "align used more than once");
3318 specifiers->alignment = (unsigned char)token.v.intvalue;
3321 expect(')', end_error);
3322 } else if (symbol == sym_allocate) {
3324 expect('(', end_error);
3325 if (token.type != T_IDENTIFIER)
3327 (void)token.v.symbol;
3328 expect(')', end_error);
3329 } else if (symbol == sym_dllimport) {
3331 DET_MOD(dllimport, DM_DLLIMPORT);
3332 } else if (symbol == sym_dllexport) {
3334 DET_MOD(dllexport, DM_DLLEXPORT);
3335 } else if (symbol == sym_thread) {
3337 DET_MOD(thread, DM_THREAD);
3338 } else if (symbol == sym_naked) {
3340 DET_MOD(naked, DM_NAKED);
3341 } else if (symbol == sym_noinline) {
3343 DET_MOD(noinline, DM_NOINLINE);
3344 } else if (symbol == sym_returns_twice) {
3346 DET_MOD(returns_twice, DM_RETURNS_TWICE);
3347 } else if (symbol == sym_noreturn) {
3349 DET_MOD(noreturn, DM_NORETURN);
3350 } else if (symbol == sym_nothrow) {
3352 DET_MOD(nothrow, DM_NOTHROW);
3353 } else if (symbol == sym_novtable) {
3355 DET_MOD(novtable, DM_NOVTABLE);
3356 } else if (symbol == sym_property) {
3358 expect('(', end_error);
3360 bool is_get = false;
3361 if (token.type != T_IDENTIFIER)
3363 if (token.v.symbol == sym_get) {
3365 } else if (token.v.symbol == sym_put) {
3367 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3371 expect('=', end_error);
3372 if (token.type != T_IDENTIFIER)
3375 if (specifiers->get_property_sym != NULL) {
3376 errorf(HERE, "get property name already specified");
3378 specifiers->get_property_sym = token.v.symbol;
3381 if (specifiers->put_property_sym != NULL) {
3382 errorf(HERE, "put property name already specified");
3384 specifiers->put_property_sym = token.v.symbol;
3388 if (token.type == ',') {
3394 expect(')', end_error);
3395 } else if (symbol == sym_selectany) {
3397 DET_MOD(selectany, DM_SELECTANY);
3398 } else if (symbol == sym_uuid) {
3400 expect('(', end_error);
3401 if (token.type != T_STRING_LITERAL)
3404 expect(')', end_error);
3405 } else if (symbol == sym_deprecated) {
3407 if (specifiers->deprecated != 0 && warning.other)
3408 warningf(HERE, "deprecated used more than once");
3409 specifiers->deprecated = true;
3410 if (token.type == '(') {
3412 if (token.type == T_STRING_LITERAL) {
3413 specifiers->deprecated_string = token.v.string.begin;
3416 errorf(HERE, "string literal expected");
3418 expect(')', end_error);
3420 } else if (symbol == sym_noalias) {
3422 DET_MOD(noalias, DM_NOALIAS);
3425 warningf(HERE, "Unknown modifier '%Y' ignored", token.v.symbol);
3427 if (token.type == '(')
3431 if (token.type == ',')
3438 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3440 entity_t *entity = allocate_entity_zero(kind);
3441 entity->base.source_position = *HERE;
3442 entity->base.symbol = symbol;
3443 if (is_declaration(entity)) {
3444 entity->declaration.type = type_error_type;
3445 entity->declaration.implicit = true;
3446 } else if (kind == ENTITY_TYPEDEF) {
3447 entity->typedefe.type = type_error_type;
3448 entity->typedefe.builtin = true;
3450 if (kind != ENTITY_COMPOUND_MEMBER)
3451 record_entity(entity, false);
3455 static void parse_microsoft_based(based_spec_t *based_spec)
3457 if (token.type != T_IDENTIFIER) {
3458 parse_error_expected("while parsing __based", T_IDENTIFIER, NULL);
3461 symbol_t *symbol = token.v.symbol;
3462 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3464 if (entity == NULL || entity->base.kind != ENTITY_VARIABLE) {
3465 errorf(HERE, "'%Y' is not a variable name.", symbol);
3466 entity = create_error_entity(symbol, ENTITY_VARIABLE);
3468 variable_t *variable = &entity->variable;
3470 if (based_spec->base_variable != NULL) {
3471 errorf(HERE, "__based type qualifier specified more than once");
3473 based_spec->source_position = token.source_position;
3474 based_spec->base_variable = variable;
3476 type_t *const type = variable->base.type;
3478 if (is_type_valid(type)) {
3479 if (! is_type_pointer(skip_typeref(type))) {
3480 errorf(HERE, "variable in __based modifier must have pointer type instead of '%T'", type);
3482 if (variable->base.base.parent_scope != file_scope) {
3483 errorf(HERE, "a nonstatic local variable may not be used in a __based specification");
3491 * Finish the construction of a struct type by calculating
3492 * its size, offsets, alignment.
3494 static void finish_struct_type(compound_type_t *type)
3496 assert(type->compound != NULL);
3498 compound_t *compound = type->compound;
3499 if (!compound->complete)
3504 il_alignment_t alignment = 1;
3505 bool need_pad = false;
3507 entity_t *entry = compound->members.entities;
3508 for (; entry != NULL; entry = entry->base.next) {
3509 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3512 type_t *m_type = skip_typeref(entry->declaration.type);
3513 if (! is_type_valid(m_type)) {
3514 /* simply ignore errors here */
3517 il_alignment_t m_alignment = m_type->base.alignment;
3518 if (m_alignment > alignment)
3519 alignment = m_alignment;
3521 offset = (size + m_alignment - 1) & -m_alignment;
3525 entry->compound_member.offset = offset;
3526 size = offset + m_type->base.size;
3528 if (type->base.alignment != 0) {
3529 alignment = type->base.alignment;
3532 offset = (size + alignment - 1) & -alignment;
3537 if (warning.padded) {
3538 warningf(&compound->base.source_position, "'%T' needs padding", type);
3541 if (compound->modifiers & DM_PACKED && warning.packed) {
3542 warningf(&compound->base.source_position,
3543 "superfluous packed attribute on '%T'", type);
3547 type->base.size = offset;
3548 type->base.alignment = alignment;
3552 * Finish the construction of an union type by calculating
3553 * its size and alignment.
3555 static void finish_union_type(compound_type_t *type)
3557 assert(type->compound != NULL);
3559 compound_t *compound = type->compound;
3560 if (! compound->complete)
3564 il_alignment_t alignment = 1;
3566 entity_t *entry = compound->members.entities;
3567 for (; entry != NULL; entry = entry->base.next) {
3568 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3571 type_t *m_type = skip_typeref(entry->declaration.type);
3572 if (! is_type_valid(m_type))
3575 entry->compound_member.offset = 0;
3576 if (m_type->base.size > size)
3577 size = m_type->base.size;
3578 if (m_type->base.alignment > alignment)
3579 alignment = m_type->base.alignment;
3581 if (type->base.alignment != 0) {
3582 alignment = type->base.alignment;
3584 size = (size + alignment - 1) & -alignment;
3585 type->base.size = size;
3586 type->base.alignment = alignment;
3589 static type_t *handle_attribute_mode(const gnu_attribute_t *attribute,
3592 type_t *type = skip_typeref(orig_type);
3594 /* at least: byte, word, pointer, list of machine modes
3595 * __XXX___ is interpreted as XXX */
3597 /* This isn't really correct, the backend should provide a list of machine
3598 * specific modes (according to gcc philosophy that is...) */
3599 const char *symbol_str = attribute->u.symbol->string;
3600 bool sign = is_type_signed(type);
3601 atomic_type_kind_t akind;
3602 if (strcmp_underscore("QI", symbol_str) == 0 ||
3603 strcmp_underscore("byte", symbol_str) == 0) {
3604 akind = sign ? ATOMIC_TYPE_CHAR : ATOMIC_TYPE_UCHAR;
3605 } else if (strcmp_underscore("HI", symbol_str) == 0) {
3606 akind = sign ? ATOMIC_TYPE_SHORT : ATOMIC_TYPE_USHORT;
3607 } else if (strcmp_underscore("SI", symbol_str) == 0
3608 || strcmp_underscore("word", symbol_str) == 0
3609 || strcmp_underscore("pointer", symbol_str) == 0) {
3610 akind = sign ? ATOMIC_TYPE_INT : ATOMIC_TYPE_UINT;
3611 } else if (strcmp_underscore("DI", symbol_str) == 0) {
3612 akind = sign ? ATOMIC_TYPE_LONGLONG : ATOMIC_TYPE_ULONGLONG;
3615 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
3619 if (type->kind == TYPE_ATOMIC) {
3620 type_t *copy = duplicate_type(type);
3621 copy->atomic.akind = akind;
3622 return identify_new_type(copy);
3623 } else if (type->kind == TYPE_ENUM) {
3624 type_t *copy = duplicate_type(type);
3625 copy->enumt.akind = akind;
3626 return identify_new_type(copy);
3627 } else if (is_type_pointer(type)) {
3628 warningf(HERE, "__attribute__((mode)) on pointers not implemented yet (ignored)");
3632 errorf(HERE, "__attribute__((mode)) only allowed on integer, enum or pointer type");
3636 static type_t *handle_type_attributes(const gnu_attribute_t *attributes,
3639 const gnu_attribute_t *attribute = attributes;
3640 for ( ; attribute != NULL; attribute = attribute->next) {
3641 if (attribute->invalid)
3644 if (attribute->kind == GNU_AK_MODE) {
3645 type = handle_attribute_mode(attribute, type);
3646 } else if (attribute->kind == GNU_AK_ALIGNED) {
3647 int alignment = 32; /* TODO: fill in maximum useful alignment for
3649 if (attribute->has_arguments)
3650 alignment = attribute->u.argument;
3652 type_t *copy = duplicate_type(type);
3653 copy->base.alignment = attribute->u.argument;
3654 type = identify_new_type(copy);
3661 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3663 type_t *type = NULL;
3664 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3665 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3666 unsigned type_specifiers = 0;
3667 bool newtype = false;
3668 bool saw_error = false;
3669 bool old_gcc_extension = in_gcc_extension;
3671 specifiers->source_position = token.source_position;
3674 specifiers->modifiers
3675 |= parse_attributes(&specifiers->gnu_attributes);
3677 switch (token.type) {
3679 #define MATCH_STORAGE_CLASS(token, class) \
3681 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3682 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3684 specifiers->storage_class = class; \
3685 if (specifiers->thread_local) \
3686 goto check_thread_storage_class; \
3690 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3691 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3692 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3693 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3694 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3698 expect('(', end_error);
3699 add_anchor_token(')');
3700 parse_microsoft_extended_decl_modifier(specifiers);
3701 rem_anchor_token(')');
3702 expect(')', end_error);
3706 if (specifiers->thread_local) {
3707 errorf(HERE, "duplicate '__thread'");
3709 specifiers->thread_local = true;
3710 check_thread_storage_class:
3711 switch (specifiers->storage_class) {
3712 case STORAGE_CLASS_EXTERN:
3713 case STORAGE_CLASS_NONE:
3714 case STORAGE_CLASS_STATIC:
3718 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
3719 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
3720 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
3721 wrong_thread_stoarge_class:
3722 errorf(HERE, "'__thread' used with '%s'", wrong);
3729 /* type qualifiers */
3730 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3732 qualifiers |= qualifier; \
3736 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3737 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3738 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3739 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3740 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3741 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3742 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3743 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3745 case T___extension__:
3747 in_gcc_extension = true;
3750 /* type specifiers */
3751 #define MATCH_SPECIFIER(token, specifier, name) \
3753 if (type_specifiers & specifier) { \
3754 errorf(HERE, "multiple " name " type specifiers given"); \
3756 type_specifiers |= specifier; \
3761 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3762 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3763 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3764 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3765 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3766 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3767 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3768 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3769 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3770 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3771 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3772 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3773 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3774 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3775 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3776 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3777 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3778 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
3780 case T__forceinline:
3781 /* only in microsoft mode */
3782 specifiers->modifiers |= DM_FORCEINLINE;
3787 specifiers->is_inline = true;
3791 if (type_specifiers & SPECIFIER_LONG_LONG) {
3792 errorf(HERE, "multiple type specifiers given");
3793 } else if (type_specifiers & SPECIFIER_LONG) {
3794 type_specifiers |= SPECIFIER_LONG_LONG;
3796 type_specifiers |= SPECIFIER_LONG;
3802 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3804 type->compound.compound = parse_compound_type_specifier(true);
3805 finish_struct_type(&type->compound);
3809 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3810 type->compound.compound = parse_compound_type_specifier(false);
3811 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3812 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3813 finish_union_type(&type->compound);
3817 type = parse_enum_specifier();
3820 type = parse_typeof();
3822 case T___builtin_va_list:
3823 type = duplicate_type(type_valist);
3827 case T_IDENTIFIER: {
3828 /* only parse identifier if we haven't found a type yet */
3829 if (type != NULL || type_specifiers != 0) {
3830 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3831 * declaration, so it doesn't generate errors about expecting '(' or
3833 switch (look_ahead(1)->type) {
3840 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3844 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3849 goto finish_specifiers;
3853 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3854 if (typedef_type == NULL) {
3855 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3856 * declaration, so it doesn't generate 'implicit int' followed by more
3857 * errors later on. */
3858 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3864 errorf(HERE, "%K does not name a type", &token);
3867 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3869 type = allocate_type_zero(TYPE_TYPEDEF);
3870 type->typedeft.typedefe = &entity->typedefe;
3874 if (la1_type == '&' || la1_type == '*')
3875 goto finish_specifiers;
3880 goto finish_specifiers;
3885 type = typedef_type;
3889 /* function specifier */
3891 goto finish_specifiers;
3896 specifiers->modifiers
3897 |= parse_attributes(&specifiers->gnu_attributes);
3899 in_gcc_extension = old_gcc_extension;
3901 if (type == NULL || (saw_error && type_specifiers != 0)) {
3902 atomic_type_kind_t atomic_type;
3904 /* match valid basic types */
3905 switch (type_specifiers) {
3906 case SPECIFIER_VOID:
3907 atomic_type = ATOMIC_TYPE_VOID;
3909 case SPECIFIER_WCHAR_T:
3910 atomic_type = ATOMIC_TYPE_WCHAR_T;
3912 case SPECIFIER_CHAR:
3913 atomic_type = ATOMIC_TYPE_CHAR;
3915 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3916 atomic_type = ATOMIC_TYPE_SCHAR;
3918 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3919 atomic_type = ATOMIC_TYPE_UCHAR;
3921 case SPECIFIER_SHORT:
3922 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3923 case SPECIFIER_SHORT | SPECIFIER_INT:
3924 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3925 atomic_type = ATOMIC_TYPE_SHORT;
3927 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3928 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3929 atomic_type = ATOMIC_TYPE_USHORT;
3932 case SPECIFIER_SIGNED:
3933 case SPECIFIER_SIGNED | SPECIFIER_INT:
3934 atomic_type = ATOMIC_TYPE_INT;
3936 case SPECIFIER_UNSIGNED:
3937 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3938 atomic_type = ATOMIC_TYPE_UINT;
3940 case SPECIFIER_LONG:
3941 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3942 case SPECIFIER_LONG | SPECIFIER_INT:
3943 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3944 atomic_type = ATOMIC_TYPE_LONG;
3946 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3947 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3948 atomic_type = ATOMIC_TYPE_ULONG;
3951 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3952 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3953 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3954 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3956 atomic_type = ATOMIC_TYPE_LONGLONG;
3957 goto warn_about_long_long;
3959 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3960 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3962 atomic_type = ATOMIC_TYPE_ULONGLONG;
3963 warn_about_long_long:
3964 if (warning.long_long) {
3965 warningf(&specifiers->source_position,
3966 "ISO C90 does not support 'long long'");
3970 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3971 atomic_type = unsigned_int8_type_kind;
3974 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3975 atomic_type = unsigned_int16_type_kind;
3978 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3979 atomic_type = unsigned_int32_type_kind;
3982 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3983 atomic_type = unsigned_int64_type_kind;
3986 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3987 atomic_type = unsigned_int128_type_kind;
3990 case SPECIFIER_INT8:
3991 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3992 atomic_type = int8_type_kind;
3995 case SPECIFIER_INT16:
3996 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3997 atomic_type = int16_type_kind;
4000 case SPECIFIER_INT32:
4001 case SPECIFIER_SIGNED | SPECIFIER_INT32:
4002 atomic_type = int32_type_kind;
4005 case SPECIFIER_INT64:
4006 case SPECIFIER_SIGNED | SPECIFIER_INT64:
4007 atomic_type = int64_type_kind;
4010 case SPECIFIER_INT128:
4011 case SPECIFIER_SIGNED | SPECIFIER_INT128:
4012 atomic_type = int128_type_kind;
4015 case SPECIFIER_FLOAT:
4016 atomic_type = ATOMIC_TYPE_FLOAT;
4018 case SPECIFIER_DOUBLE:
4019 atomic_type = ATOMIC_TYPE_DOUBLE;
4021 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
4022 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
4024 case SPECIFIER_BOOL:
4025 atomic_type = ATOMIC_TYPE_BOOL;
4027 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
4028 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
4029 atomic_type = ATOMIC_TYPE_FLOAT;
4031 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
4032 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
4033 atomic_type = ATOMIC_TYPE_DOUBLE;
4035 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
4036 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
4037 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
4040 /* invalid specifier combination, give an error message */
4041 if (type_specifiers == 0) {
4045 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
4046 if (!(c_mode & _CXX) && !strict_mode) {
4047 if (warning.implicit_int) {
4048 warningf(HERE, "no type specifiers in declaration, using 'int'");
4050 atomic_type = ATOMIC_TYPE_INT;
4053 errorf(HERE, "no type specifiers given in declaration");
4055 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
4056 (type_specifiers & SPECIFIER_UNSIGNED)) {
4057 errorf(HERE, "signed and unsigned specifiers given");
4058 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
4059 errorf(HERE, "only integer types can be signed or unsigned");
4061 errorf(HERE, "multiple datatypes in declaration");
4066 if (type_specifiers & SPECIFIER_COMPLEX) {
4067 type = allocate_type_zero(TYPE_COMPLEX);
4068 type->complex.akind = atomic_type;
4069 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
4070 type = allocate_type_zero(TYPE_IMAGINARY);
4071 type->imaginary.akind = atomic_type;
4073 type = allocate_type_zero(TYPE_ATOMIC);
4074 type->atomic.akind = atomic_type;
4076 type->base.alignment = get_atomic_type_alignment(atomic_type);
4077 unsigned const size = get_atomic_type_size(atomic_type);
4079 type_specifiers & SPECIFIER_COMPLEX ? size * 2 : size;
4081 } else if (type_specifiers != 0) {
4082 errorf(HERE, "multiple datatypes in declaration");
4085 /* FIXME: check type qualifiers here */
4087 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
4088 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4089 type->base.qualifiers = qualifiers;
4090 type->base.modifiers = modifiers;
4092 type = identify_new_type(type);
4094 type = handle_type_attributes(specifiers->gnu_attributes, type);
4095 specifiers->type = type;
4099 specifiers->type = type_error_type;
4103 static type_qualifiers_t parse_type_qualifiers(void)
4105 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
4108 switch (token.type) {
4109 /* type qualifiers */
4110 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
4111 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
4112 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
4113 /* microsoft extended type modifiers */
4114 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
4115 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
4116 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
4117 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
4118 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
4127 * Parses an K&R identifier list
4129 static void parse_identifier_list(scope_t *scope)
4132 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
4133 entity->base.source_position = token.source_position;
4134 entity->base.namespc = NAMESPACE_NORMAL;
4135 entity->base.symbol = token.v.symbol;
4136 /* a K&R parameter has no type, yet */
4140 append_entity(scope, entity);
4142 if (token.type != ',') {
4146 } while (token.type == T_IDENTIFIER);
4149 static entity_t *parse_parameter(void)
4151 declaration_specifiers_t specifiers;
4152 memset(&specifiers, 0, sizeof(specifiers));
4154 parse_declaration_specifiers(&specifiers);
4156 entity_t *entity = parse_declarator(&specifiers,
4157 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
4158 anonymous_entity = NULL;
4162 static void semantic_parameter_incomplete(const entity_t *entity)
4164 assert(entity->kind == ENTITY_PARAMETER);
4166 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
4167 * list in a function declarator that is part of a
4168 * definition of that function shall not have
4169 * incomplete type. */
4170 type_t *type = skip_typeref(entity->declaration.type);
4171 if (is_type_incomplete(type)) {
4172 errorf(&entity->base.source_position,
4173 "parameter '%Y' has incomplete type '%T'", entity->base.symbol,
4174 entity->declaration.type);
4179 * Parses function type parameters (and optionally creates variable_t entities
4180 * for them in a scope)
4182 static void parse_parameters(function_type_t *type, scope_t *scope)
4185 add_anchor_token(')');
4186 int saved_comma_state = save_and_reset_anchor_state(',');
4188 if (token.type == T_IDENTIFIER &&
4189 !is_typedef_symbol(token.v.symbol)) {
4190 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4191 if (la1_type == ',' || la1_type == ')') {
4192 type->kr_style_parameters = true;
4193 type->unspecified_parameters = true;
4194 parse_identifier_list(scope);
4195 goto parameters_finished;
4199 if (token.type == ')') {
4200 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4201 if (!(c_mode & _CXX))
4202 type->unspecified_parameters = true;
4203 goto parameters_finished;
4206 function_parameter_t *parameter;
4207 function_parameter_t *last_parameter = NULL;
4210 switch (token.type) {
4213 type->variadic = true;
4214 goto parameters_finished;
4217 case T___extension__:
4220 entity_t *entity = parse_parameter();
4221 if (entity->kind == ENTITY_TYPEDEF) {
4222 errorf(&entity->base.source_position,
4223 "typedef not allowed as function parameter");
4226 assert(is_declaration(entity));
4228 /* func(void) is not a parameter */
4229 if (last_parameter == NULL
4230 && token.type == ')'
4231 && entity->base.symbol == NULL
4232 && skip_typeref(entity->declaration.type) == type_void) {
4233 goto parameters_finished;
4235 semantic_parameter_incomplete(entity);
4237 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4238 memset(parameter, 0, sizeof(parameter[0]));
4239 parameter->type = entity->declaration.type;
4241 if (scope != NULL) {
4242 append_entity(scope, entity);
4245 if (last_parameter != NULL) {
4246 last_parameter->next = parameter;
4248 type->parameters = parameter;
4250 last_parameter = parameter;
4255 goto parameters_finished;
4257 if (token.type != ',') {
4258 goto parameters_finished;
4264 parameters_finished:
4265 rem_anchor_token(')');
4266 expect(')', end_error);
4269 restore_anchor_state(',', saved_comma_state);
4272 typedef enum construct_type_kind_t {
4275 CONSTRUCT_REFERENCE,
4278 } construct_type_kind_t;
4280 typedef struct construct_type_t construct_type_t;
4281 struct construct_type_t {
4282 construct_type_kind_t kind;
4283 construct_type_t *next;
4286 typedef struct parsed_pointer_t parsed_pointer_t;
4287 struct parsed_pointer_t {
4288 construct_type_t construct_type;
4289 type_qualifiers_t type_qualifiers;
4290 variable_t *base_variable; /**< MS __based extension. */
4293 typedef struct parsed_reference_t parsed_reference_t;
4294 struct parsed_reference_t {
4295 construct_type_t construct_type;
4298 typedef struct construct_function_type_t construct_function_type_t;
4299 struct construct_function_type_t {
4300 construct_type_t construct_type;
4301 type_t *function_type;
4304 typedef struct parsed_array_t parsed_array_t;
4305 struct parsed_array_t {
4306 construct_type_t construct_type;
4307 type_qualifiers_t type_qualifiers;
4313 typedef struct construct_base_type_t construct_base_type_t;
4314 struct construct_base_type_t {
4315 construct_type_t construct_type;
4319 static construct_type_t *parse_pointer_declarator(variable_t *base_variable)
4323 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4324 memset(pointer, 0, sizeof(pointer[0]));
4325 pointer->construct_type.kind = CONSTRUCT_POINTER;
4326 pointer->type_qualifiers = parse_type_qualifiers();
4327 pointer->base_variable = base_variable;
4329 return &pointer->construct_type;
4332 static construct_type_t *parse_reference_declarator(void)
4336 parsed_reference_t *reference = obstack_alloc(&temp_obst, sizeof(reference[0]));
4337 memset(reference, 0, sizeof(reference[0]));
4338 reference->construct_type.kind = CONSTRUCT_REFERENCE;
4340 return (construct_type_t*)reference;
4343 static construct_type_t *parse_array_declarator(void)
4346 add_anchor_token(']');
4348 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4349 memset(array, 0, sizeof(array[0]));
4350 array->construct_type.kind = CONSTRUCT_ARRAY;
4352 if (token.type == T_static) {
4353 array->is_static = true;
4357 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4358 if (type_qualifiers != 0) {
4359 if (token.type == T_static) {
4360 array->is_static = true;
4364 array->type_qualifiers = type_qualifiers;
4366 if (token.type == '*' && look_ahead(1)->type == ']') {
4367 array->is_variable = true;
4369 } else if (token.type != ']') {
4370 expression_t *const size = parse_assignment_expression();
4372 mark_vars_read(size, NULL);
4375 rem_anchor_token(']');
4376 expect(']', end_error);
4379 return &array->construct_type;
4382 static construct_type_t *parse_function_declarator(scope_t *scope,
4383 decl_modifiers_t modifiers)
4385 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4386 function_type_t *ftype = &type->function;
4388 ftype->linkage = current_linkage;
4390 switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
4391 case DM_NONE: break;
4392 case DM_CDECL: ftype->calling_convention = CC_CDECL; break;
4393 case DM_STDCALL: ftype->calling_convention = CC_STDCALL; break;
4394 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
4395 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
4398 errorf(HERE, "multiple calling conventions in declaration");
4402 parse_parameters(ftype, scope);
4404 construct_function_type_t *construct_function_type =
4405 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4406 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4407 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4408 construct_function_type->function_type = type;
4410 return &construct_function_type->construct_type;
4413 typedef struct parse_declarator_env_t {
4414 decl_modifiers_t modifiers;
4416 source_position_t source_position;
4418 } parse_declarator_env_t;
4420 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4421 bool may_be_abstract)
4423 /* construct a single linked list of construct_type_t's which describe
4424 * how to construct the final declarator type */
4425 construct_type_t *first = NULL;
4426 construct_type_t *last = NULL;
4427 gnu_attribute_t *attributes = NULL;
4429 decl_modifiers_t modifiers = parse_attributes(&attributes);
4431 /* MS __based extension */
4432 based_spec_t base_spec;
4433 base_spec.base_variable = NULL;
4436 construct_type_t *type;
4437 switch (token.type) {
4439 if (!(c_mode & _CXX))
4440 errorf(HERE, "references are only available for C++");
4441 if (base_spec.base_variable != NULL && warning.other) {
4442 warningf(&base_spec.source_position,
4443 "__based does not precede a pointer operator, ignored");
4445 type = parse_reference_declarator();
4447 base_spec.base_variable = NULL;
4451 type = parse_pointer_declarator(base_spec.base_variable);
4453 base_spec.base_variable = NULL;
4458 expect('(', end_error);
4459 add_anchor_token(')');
4460 parse_microsoft_based(&base_spec);
4461 rem_anchor_token(')');
4462 expect(')', end_error);
4466 goto ptr_operator_end;
4477 /* TODO: find out if this is correct */
4478 modifiers |= parse_attributes(&attributes);
4481 if (base_spec.base_variable != NULL && warning.other) {
4482 warningf(&base_spec.source_position,
4483 "__based does not precede a pointer operator, ignored");
4487 modifiers |= env->modifiers;
4488 env->modifiers = modifiers;
4491 construct_type_t *inner_types = NULL;
4493 switch (token.type) {
4496 errorf(HERE, "no identifier expected in typename");
4498 env->symbol = token.v.symbol;
4499 env->source_position = token.source_position;
4504 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
4505 * interpreted as ``function with no parameter specification'', rather
4506 * than redundant parentheses around the omitted identifier. */
4507 if (look_ahead(1)->type != ')') {
4509 add_anchor_token(')');
4510 inner_types = parse_inner_declarator(env, may_be_abstract);
4511 if (inner_types != NULL) {
4512 /* All later declarators only modify the return type */
4515 rem_anchor_token(')');
4516 expect(')', end_error);
4520 if (may_be_abstract)
4522 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4527 construct_type_t *p = last;
4530 construct_type_t *type;
4531 switch (token.type) {
4533 scope_t *scope = NULL;
4535 scope = &env->parameters;
4537 type = parse_function_declarator(scope, modifiers);
4541 type = parse_array_declarator();
4544 goto declarator_finished;
4547 /* insert in the middle of the list (behind p) */
4549 type->next = p->next;
4560 declarator_finished:
4561 /* append inner_types at the end of the list, we don't to set last anymore
4562 * as it's not needed anymore */
4564 assert(first == NULL);
4565 first = inner_types;
4567 last->next = inner_types;
4575 static void parse_declaration_attributes(entity_t *entity)
4577 gnu_attribute_t *attributes = NULL;
4578 decl_modifiers_t modifiers = parse_attributes(&attributes);
4584 if (entity->kind == ENTITY_TYPEDEF) {
4585 modifiers |= entity->typedefe.modifiers;
4586 type = entity->typedefe.type;
4588 assert(is_declaration(entity));
4589 modifiers |= entity->declaration.modifiers;
4590 type = entity->declaration.type;
4595 gnu_attribute_t *attribute = attributes;
4596 for ( ; attribute != NULL; attribute = attribute->next) {
4597 if (attribute->invalid)
4600 if (attribute->kind == GNU_AK_MODE) {
4601 type = handle_attribute_mode(attribute, type);
4602 } else if (attribute->kind == GNU_AK_ALIGNED) {
4603 int alignment = 32; /* TODO: fill in maximum usefull alignment for target machine */
4604 if (attribute->has_arguments)
4605 alignment = attribute->u.argument;
4607 if (entity->kind == ENTITY_TYPEDEF) {
4608 type_t *copy = duplicate_type(type);
4609 copy->base.alignment = attribute->u.argument;
4610 type = identify_new_type(copy);
4611 } else if(entity->kind == ENTITY_VARIABLE) {
4612 entity->variable.alignment = alignment;
4613 } else if(entity->kind == ENTITY_COMPOUND_MEMBER) {
4614 entity->compound_member.alignment = alignment;
4619 type_modifiers_t type_modifiers = type->base.modifiers;
4620 if (modifiers & DM_TRANSPARENT_UNION)
4621 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4623 if (type->base.modifiers != type_modifiers) {
4624 type_t *copy = duplicate_type(type);
4625 copy->base.modifiers = type_modifiers;
4626 type = identify_new_type(copy);
4629 if (entity->kind == ENTITY_TYPEDEF) {
4630 entity->typedefe.type = type;
4631 entity->typedefe.modifiers = modifiers;
4633 entity->declaration.type = type;
4634 entity->declaration.modifiers = modifiers;
4638 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
4640 construct_type_t *iter = construct_list;
4641 for (; iter != NULL; iter = iter->next) {
4642 switch (iter->kind) {
4643 case CONSTRUCT_INVALID:
4644 internal_errorf(HERE, "invalid type construction found");
4645 case CONSTRUCT_FUNCTION: {
4646 construct_function_type_t *construct_function_type
4647 = (construct_function_type_t*) iter;
4649 type_t *function_type = construct_function_type->function_type;
4651 function_type->function.return_type = type;
4653 type_t *skipped_return_type = skip_typeref(type);
4655 if (is_type_function(skipped_return_type)) {
4656 errorf(HERE, "function returning function is not allowed");
4657 } else if (is_type_array(skipped_return_type)) {
4658 errorf(HERE, "function returning array is not allowed");
4660 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4662 "type qualifiers in return type of function type are meaningless");
4666 type = function_type;
4670 case CONSTRUCT_POINTER: {
4671 if (is_type_reference(skip_typeref(type)))
4672 errorf(HERE, "cannot declare a pointer to reference");
4674 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4675 type = make_based_pointer_type(type, parsed_pointer->type_qualifiers, parsed_pointer->base_variable);
4679 case CONSTRUCT_REFERENCE:
4680 if (is_type_reference(skip_typeref(type)))
4681 errorf(HERE, "cannot declare a reference to reference");
4683 type = make_reference_type(type);
4686 case CONSTRUCT_ARRAY: {
4687 if (is_type_reference(skip_typeref(type)))
4688 errorf(HERE, "cannot declare an array of references");
4690 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4691 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4693 expression_t *size_expression = parsed_array->size;
4694 if (size_expression != NULL) {
4696 = create_implicit_cast(size_expression, type_size_t);
4699 array_type->base.qualifiers = parsed_array->type_qualifiers;
4700 array_type->array.element_type = type;
4701 array_type->array.is_static = parsed_array->is_static;
4702 array_type->array.is_variable = parsed_array->is_variable;
4703 array_type->array.size_expression = size_expression;
4705 if (size_expression != NULL) {
4706 if (is_constant_expression(size_expression)) {
4707 array_type->array.size_constant = true;
4708 array_type->array.size
4709 = fold_constant(size_expression);
4711 array_type->array.is_vla = true;
4715 type_t *skipped_type = skip_typeref(type);
4717 if (is_type_incomplete(skipped_type)) {
4718 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4719 } else if (is_type_function(skipped_type)) {
4720 errorf(HERE, "array of functions is not allowed");
4727 /* The function type was constructed earlier. Freeing it here will
4728 * destroy other types. */
4729 if (iter->kind == CONSTRUCT_FUNCTION) {
4730 type = typehash_insert(type);
4732 type = identify_new_type(type);
4739 static type_t *automatic_type_conversion(type_t *orig_type);
4741 static type_t *semantic_parameter(const source_position_t *pos,
4743 const declaration_specifiers_t *specifiers,
4746 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
4747 * shall be adjusted to ``qualified pointer to type'',
4749 * §6.7.5.3:8 A declaration of a parameter as ``function returning
4750 * type'' shall be adjusted to ``pointer to function
4751 * returning type'', as in 6.3.2.1. */
4752 type = automatic_type_conversion(type);
4754 if (specifiers->is_inline && is_type_valid(type)) {
4755 errorf(pos, "parameter '%Y' declared 'inline'", symbol);
4758 /* §6.9.1:6 The declarations in the declaration list shall contain
4759 * no storage-class specifier other than register and no
4760 * initializations. */
4761 if (specifiers->thread_local || (
4762 specifiers->storage_class != STORAGE_CLASS_NONE &&
4763 specifiers->storage_class != STORAGE_CLASS_REGISTER)
4765 errorf(pos, "invalid storage class for parameter '%Y'", symbol);
4768 /* delay test for incomplete type, because we might have (void)
4769 * which is legal but incomplete... */
4774 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4775 declarator_flags_t flags)
4777 parse_declarator_env_t env;
4778 memset(&env, 0, sizeof(env));
4779 env.modifiers = specifiers->modifiers;
4781 construct_type_t *construct_type =
4782 parse_inner_declarator(&env, (flags & DECL_MAY_BE_ABSTRACT) != 0);
4784 construct_declarator_type(construct_type, specifiers->type);
4785 type_t *type = skip_typeref(orig_type);
4787 if (construct_type != NULL) {
4788 obstack_free(&temp_obst, construct_type);
4792 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4793 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4794 entity->base.symbol = env.symbol;
4795 entity->base.source_position = env.source_position;
4796 entity->typedefe.type = orig_type;
4798 if (anonymous_entity != NULL) {
4799 if (is_type_compound(type)) {
4800 assert(anonymous_entity->compound.alias == NULL);
4801 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4802 anonymous_entity->kind == ENTITY_UNION);
4803 anonymous_entity->compound.alias = entity;
4804 anonymous_entity = NULL;
4805 } else if (is_type_enum(type)) {
4806 assert(anonymous_entity->enume.alias == NULL);
4807 assert(anonymous_entity->kind == ENTITY_ENUM);
4808 anonymous_entity->enume.alias = entity;
4809 anonymous_entity = NULL;
4813 /* create a declaration type entity */
4814 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
4815 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4817 if (env.symbol != NULL) {
4818 if (specifiers->is_inline && is_type_valid(type)) {
4819 errorf(&env.source_position,
4820 "compound member '%Y' declared 'inline'", env.symbol);
4823 if (specifiers->thread_local ||
4824 specifiers->storage_class != STORAGE_CLASS_NONE) {
4825 errorf(&env.source_position,
4826 "compound member '%Y' must have no storage class",
4830 } else if (flags & DECL_IS_PARAMETER) {
4831 orig_type = semantic_parameter(&env.source_position, orig_type,
4832 specifiers, env.symbol);
4834 entity = allocate_entity_zero(ENTITY_PARAMETER);
4835 } else if (is_type_function(type)) {
4836 entity = allocate_entity_zero(ENTITY_FUNCTION);
4838 entity->function.is_inline = specifiers->is_inline;
4839 entity->function.parameters = env.parameters;
4841 if (env.symbol != NULL) {
4842 if (specifiers->thread_local || (
4843 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4844 specifiers->storage_class != STORAGE_CLASS_NONE &&
4845 specifiers->storage_class != STORAGE_CLASS_STATIC
4847 errorf(&env.source_position,
4848 "invalid storage class for function '%Y'", env.symbol);
4852 entity = allocate_entity_zero(ENTITY_VARIABLE);
4854 entity->variable.get_property_sym = specifiers->get_property_sym;
4855 entity->variable.put_property_sym = specifiers->put_property_sym;
4857 entity->variable.thread_local = specifiers->thread_local;
4859 if (env.symbol != NULL) {
4860 if (specifiers->is_inline && is_type_valid(type)) {
4861 errorf(&env.source_position,
4862 "variable '%Y' declared 'inline'", env.symbol);
4865 bool invalid_storage_class = false;
4866 if (current_scope == file_scope) {
4867 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4868 specifiers->storage_class != STORAGE_CLASS_NONE &&
4869 specifiers->storage_class != STORAGE_CLASS_STATIC) {
4870 invalid_storage_class = true;
4873 if (specifiers->thread_local &&
4874 specifiers->storage_class == STORAGE_CLASS_NONE) {
4875 invalid_storage_class = true;
4878 if (invalid_storage_class) {
4879 errorf(&env.source_position,
4880 "invalid storage class for variable '%Y'", env.symbol);
4885 if (env.symbol != NULL) {
4886 entity->base.symbol = env.symbol;
4887 entity->base.source_position = env.source_position;
4889 entity->base.source_position = specifiers->source_position;
4891 entity->base.namespc = NAMESPACE_NORMAL;
4892 entity->declaration.type = orig_type;
4893 entity->declaration.modifiers = env.modifiers;
4894 entity->declaration.deprecated_string = specifiers->deprecated_string;
4896 storage_class_t storage_class = specifiers->storage_class;
4897 entity->declaration.declared_storage_class = storage_class;
4899 if (storage_class == STORAGE_CLASS_NONE && current_scope != file_scope)
4900 storage_class = STORAGE_CLASS_AUTO;
4901 entity->declaration.storage_class = storage_class;
4904 parse_declaration_attributes(entity);
4909 static type_t *parse_abstract_declarator(type_t *base_type)
4911 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4913 type_t *result = construct_declarator_type(construct_type, base_type);
4914 if (construct_type != NULL) {
4915 obstack_free(&temp_obst, construct_type);
4922 * Check if the declaration of main is suspicious. main should be a
4923 * function with external linkage, returning int, taking either zero
4924 * arguments, two, or three arguments of appropriate types, ie.
4926 * int main([ int argc, char **argv [, char **env ] ]).
4928 * @param decl the declaration to check
4929 * @param type the function type of the declaration
4931 static void check_type_of_main(const entity_t *entity)
4933 const source_position_t *pos = &entity->base.source_position;
4934 if (entity->kind != ENTITY_FUNCTION) {
4935 warningf(pos, "'main' is not a function");
4939 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4940 warningf(pos, "'main' is normally a non-static function");
4943 type_t *type = skip_typeref(entity->declaration.type);
4944 assert(is_type_function(type));
4946 function_type_t *func_type = &type->function;
4947 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4948 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4949 func_type->return_type);
4951 const function_parameter_t *parm = func_type->parameters;
4953 type_t *const first_type = parm->type;
4954 if (!types_compatible(skip_typeref(first_type), type_int)) {
4956 "first argument of 'main' should be 'int', but is '%T'",
4961 type_t *const second_type = parm->type;
4962 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4963 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4967 type_t *const third_type = parm->type;
4968 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4969 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4973 goto warn_arg_count;
4977 warningf(pos, "'main' takes only zero, two or three arguments");
4983 * Check if a symbol is the equal to "main".
4985 static bool is_sym_main(const symbol_t *const sym)
4987 return strcmp(sym->string, "main") == 0;
4990 static void error_redefined_as_different_kind(const source_position_t *pos,
4991 const entity_t *old, entity_kind_t new_kind)
4993 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4994 get_entity_kind_name(old->kind), old->base.symbol,
4995 get_entity_kind_name(new_kind), &old->base.source_position);
4999 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
5000 * for various problems that occur for multiple definitions
5002 static entity_t *record_entity(entity_t *entity, const bool is_definition)
5004 const symbol_t *const symbol = entity->base.symbol;
5005 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
5006 const source_position_t *pos = &entity->base.source_position;
5008 /* can happen in error cases */
5012 entity_t *previous_entity = get_entity(symbol, namespc);
5013 /* pushing the same entity twice will break the stack structure */
5014 assert(previous_entity != entity);
5016 if (entity->kind == ENTITY_FUNCTION) {
5017 type_t *const orig_type = entity->declaration.type;
5018 type_t *const type = skip_typeref(orig_type);
5020 assert(is_type_function(type));
5021 if (type->function.unspecified_parameters &&
5022 warning.strict_prototypes &&
5023 previous_entity == NULL) {
5024 warningf(pos, "function declaration '%#T' is not a prototype",
5028 if (warning.main && current_scope == file_scope
5029 && is_sym_main(symbol)) {
5030 check_type_of_main(entity);
5034 if (is_declaration(entity) &&
5035 warning.nested_externs &&
5036 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
5037 current_scope != file_scope) {
5038 warningf(pos, "nested extern declaration of '%#T'",
5039 entity->declaration.type, symbol);
5042 if (previous_entity != NULL &&
5043 previous_entity->base.parent_scope == ¤t_function->parameters &&
5044 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
5045 assert(previous_entity->kind == ENTITY_PARAMETER);
5047 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
5048 entity->declaration.type, symbol,
5049 previous_entity->declaration.type, symbol,
5050 &previous_entity->base.source_position);
5054 if (previous_entity != NULL &&
5055 previous_entity->base.parent_scope == current_scope) {
5056 if (previous_entity->kind != entity->kind) {
5057 error_redefined_as_different_kind(pos, previous_entity,
5061 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
5062 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
5063 symbol, &previous_entity->base.source_position);
5066 if (previous_entity->kind == ENTITY_TYPEDEF) {
5067 /* TODO: C++ allows this for exactly the same type */
5068 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
5069 symbol, &previous_entity->base.source_position);
5073 /* at this point we should have only VARIABLES or FUNCTIONS */
5074 assert(is_declaration(previous_entity) && is_declaration(entity));
5076 declaration_t *const prev_decl = &previous_entity->declaration;
5077 declaration_t *const decl = &entity->declaration;
5079 /* can happen for K&R style declarations */
5080 if (prev_decl->type == NULL &&
5081 previous_entity->kind == ENTITY_PARAMETER &&
5082 entity->kind == ENTITY_PARAMETER) {
5083 prev_decl->type = decl->type;
5084 prev_decl->storage_class = decl->storage_class;
5085 prev_decl->declared_storage_class = decl->declared_storage_class;
5086 prev_decl->modifiers = decl->modifiers;
5087 prev_decl->deprecated_string = decl->deprecated_string;
5088 return previous_entity;
5091 type_t *const orig_type = decl->type;
5092 assert(orig_type != NULL);
5093 type_t *const type = skip_typeref(orig_type);
5094 type_t * prev_type = skip_typeref(prev_decl->type);
5096 if (!types_compatible(type, prev_type)) {
5098 "declaration '%#T' is incompatible with '%#T' (declared %P)",
5099 orig_type, symbol, prev_decl->type, symbol,
5100 &previous_entity->base.source_position);
5102 unsigned old_storage_class = prev_decl->storage_class;
5103 if (warning.redundant_decls &&
5106 !(prev_decl->modifiers & DM_USED) &&
5107 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
5108 warningf(&previous_entity->base.source_position,
5109 "unnecessary static forward declaration for '%#T'",
5110 prev_decl->type, symbol);
5113 unsigned new_storage_class = decl->storage_class;
5114 if (is_type_incomplete(prev_type)) {
5115 prev_decl->type = type;
5119 /* pretend no storage class means extern for function
5120 * declarations (except if the previous declaration is neither
5121 * none nor extern) */
5122 if (entity->kind == ENTITY_FUNCTION) {
5123 if (prev_type->function.unspecified_parameters) {
5124 prev_decl->type = type;
5128 switch (old_storage_class) {
5129 case STORAGE_CLASS_NONE:
5130 old_storage_class = STORAGE_CLASS_EXTERN;
5133 case STORAGE_CLASS_EXTERN:
5134 if (is_definition) {
5135 if (warning.missing_prototypes &&
5136 prev_type->function.unspecified_parameters &&
5137 !is_sym_main(symbol)) {
5138 warningf(pos, "no previous prototype for '%#T'",
5141 } else if (new_storage_class == STORAGE_CLASS_NONE) {
5142 new_storage_class = STORAGE_CLASS_EXTERN;
5151 if (old_storage_class == STORAGE_CLASS_EXTERN &&
5152 new_storage_class == STORAGE_CLASS_EXTERN) {
5153 warn_redundant_declaration:
5154 if (!is_definition &&
5155 warning.redundant_decls &&
5156 is_type_valid(prev_type) &&
5157 strcmp(previous_entity->base.source_position.input_name,
5158 "<builtin>") != 0) {
5160 "redundant declaration for '%Y' (declared %P)",
5161 symbol, &previous_entity->base.source_position);
5163 } else if (current_function == NULL) {
5164 if (old_storage_class != STORAGE_CLASS_STATIC &&
5165 new_storage_class == STORAGE_CLASS_STATIC) {
5167 "static declaration of '%Y' follows non-static declaration (declared %P)",
5168 symbol, &previous_entity->base.source_position);
5169 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
5170 prev_decl->storage_class = STORAGE_CLASS_NONE;
5171 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
5173 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
5175 goto error_redeclaration;
5176 goto warn_redundant_declaration;
5178 } else if (is_type_valid(prev_type)) {
5179 if (old_storage_class == new_storage_class) {
5180 error_redeclaration:
5181 errorf(pos, "redeclaration of '%Y' (declared %P)",
5182 symbol, &previous_entity->base.source_position);
5185 "redeclaration of '%Y' with different linkage (declared %P)",
5186 symbol, &previous_entity->base.source_position);
5191 prev_decl->modifiers |= decl->modifiers;
5192 if (entity->kind == ENTITY_FUNCTION) {
5193 previous_entity->function.is_inline |= entity->function.is_inline;
5195 return previous_entity;
5198 if (entity->kind == ENTITY_FUNCTION) {
5199 if (is_definition &&
5200 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
5201 if (warning.missing_prototypes && !is_sym_main(symbol)) {
5202 warningf(pos, "no previous prototype for '%#T'",
5203 entity->declaration.type, symbol);
5204 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
5205 warningf(pos, "no previous declaration for '%#T'",
5206 entity->declaration.type, symbol);
5209 } else if (warning.missing_declarations &&
5210 entity->kind == ENTITY_VARIABLE &&
5211 current_scope == file_scope) {
5212 declaration_t *declaration = &entity->declaration;
5213 if (declaration->storage_class == STORAGE_CLASS_NONE) {
5214 warningf(pos, "no previous declaration for '%#T'",
5215 declaration->type, symbol);
5220 assert(entity->base.parent_scope == NULL);
5221 assert(current_scope != NULL);
5223 entity->base.parent_scope = current_scope;
5224 entity->base.namespc = NAMESPACE_NORMAL;
5225 environment_push(entity);
5226 append_entity(current_scope, entity);
5231 static void parser_error_multiple_definition(entity_t *entity,
5232 const source_position_t *source_position)
5234 errorf(source_position, "multiple definition of '%Y' (declared %P)",
5235 entity->base.symbol, &entity->base.source_position);
5238 static bool is_declaration_specifier(const token_t *token,
5239 bool only_specifiers_qualifiers)
5241 switch (token->type) {
5246 return is_typedef_symbol(token->v.symbol);
5248 case T___extension__:
5250 return !only_specifiers_qualifiers;
5257 static void parse_init_declarator_rest(entity_t *entity)
5259 assert(is_declaration(entity));
5260 declaration_t *const declaration = &entity->declaration;
5264 type_t *orig_type = declaration->type;
5265 type_t *type = skip_typeref(orig_type);
5267 if (entity->kind == ENTITY_VARIABLE
5268 && entity->variable.initializer != NULL) {
5269 parser_error_multiple_definition(entity, HERE);
5272 bool must_be_constant = false;
5273 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5274 entity->base.parent_scope == file_scope) {
5275 must_be_constant = true;
5278 if (is_type_function(type)) {
5279 errorf(&entity->base.source_position,
5280 "function '%#T' is initialized like a variable",
5281 orig_type, entity->base.symbol);
5282 orig_type = type_error_type;
5285 parse_initializer_env_t env;
5286 env.type = orig_type;
5287 env.must_be_constant = must_be_constant;
5288 env.entity = entity;
5289 current_init_decl = entity;
5291 initializer_t *initializer = parse_initializer(&env);
5292 current_init_decl = NULL;
5294 if (entity->kind == ENTITY_VARIABLE) {
5295 /* § 6.7.5:22 array initializers for arrays with unknown size
5296 * determine the array type size */
5297 declaration->type = env.type;
5298 entity->variable.initializer = initializer;
5302 /* parse rest of a declaration without any declarator */
5303 static void parse_anonymous_declaration_rest(
5304 const declaration_specifiers_t *specifiers)
5307 anonymous_entity = NULL;
5309 if (warning.other) {
5310 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
5311 specifiers->thread_local) {
5312 warningf(&specifiers->source_position,
5313 "useless storage class in empty declaration");
5316 type_t *type = specifiers->type;
5317 switch (type->kind) {
5318 case TYPE_COMPOUND_STRUCT:
5319 case TYPE_COMPOUND_UNION: {
5320 if (type->compound.compound->base.symbol == NULL) {
5321 warningf(&specifiers->source_position,
5322 "unnamed struct/union that defines no instances");
5331 warningf(&specifiers->source_position, "empty declaration");
5337 static void check_variable_type_complete(entity_t *ent)
5339 if (ent->kind != ENTITY_VARIABLE)
5342 /* §6.7:7 If an identifier for an object is declared with no linkage, the
5343 * type for the object shall be complete [...] */
5344 declaration_t *decl = &ent->declaration;
5345 if (decl->storage_class != STORAGE_CLASS_NONE)
5348 type_t *const orig_type = decl->type;
5349 type_t *const type = skip_typeref(orig_type);
5350 if (!is_type_incomplete(type))
5353 /* GCC allows global arrays without size and assigns them a length of one,
5354 * if no different declaration follows */
5355 if (is_type_array(type) &&
5357 ent->base.parent_scope == file_scope) {
5358 ARR_APP1(declaration_t*, incomplete_arrays, decl);
5362 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
5363 orig_type, ent->base.symbol);
5367 static void parse_declaration_rest(entity_t *ndeclaration,
5368 const declaration_specifiers_t *specifiers,
5369 parsed_declaration_func finished_declaration,
5370 declarator_flags_t flags)
5372 add_anchor_token(';');
5373 add_anchor_token(',');
5375 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5377 if (token.type == '=') {
5378 parse_init_declarator_rest(entity);
5379 } else if (entity->kind == ENTITY_VARIABLE) {
5380 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
5381 * [...] where the extern specifier is explicitly used. */
5382 declaration_t *decl = &entity->declaration;
5383 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
5384 type_t *type = decl->type;
5385 if (is_type_reference(skip_typeref(type))) {
5386 errorf(&entity->base.source_position,
5387 "reference '%#T' must be initialized",
5388 type, entity->base.symbol);
5393 check_variable_type_complete(entity);
5395 if (token.type != ',')
5399 add_anchor_token('=');
5400 ndeclaration = parse_declarator(specifiers, flags);
5401 rem_anchor_token('=');
5403 expect(';', end_error);
5406 anonymous_entity = NULL;
5407 rem_anchor_token(';');
5408 rem_anchor_token(',');
5411 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5413 symbol_t *symbol = entity->base.symbol;
5414 if (symbol == NULL) {
5415 errorf(HERE, "anonymous declaration not valid as function parameter");
5419 assert(entity->base.namespc == NAMESPACE_NORMAL);
5420 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5421 if (previous_entity == NULL
5422 || previous_entity->base.parent_scope != current_scope) {
5423 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5428 if (is_definition) {
5429 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
5432 return record_entity(entity, false);
5435 static void parse_declaration(parsed_declaration_func finished_declaration,
5436 declarator_flags_t flags)
5438 declaration_specifiers_t specifiers;
5439 memset(&specifiers, 0, sizeof(specifiers));
5441 add_anchor_token(';');
5442 parse_declaration_specifiers(&specifiers);
5443 rem_anchor_token(';');
5445 if (token.type == ';') {
5446 parse_anonymous_declaration_rest(&specifiers);
5448 entity_t *entity = parse_declarator(&specifiers, flags);
5449 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
5453 static type_t *get_default_promoted_type(type_t *orig_type)
5455 type_t *result = orig_type;
5457 type_t *type = skip_typeref(orig_type);
5458 if (is_type_integer(type)) {
5459 result = promote_integer(type);
5460 } else if (type == type_float) {
5461 result = type_double;
5467 static void parse_kr_declaration_list(entity_t *entity)
5469 if (entity->kind != ENTITY_FUNCTION)
5472 type_t *type = skip_typeref(entity->declaration.type);
5473 assert(is_type_function(type));
5474 if (!type->function.kr_style_parameters)
5478 add_anchor_token('{');
5480 /* push function parameters */
5481 size_t const top = environment_top();
5482 scope_t *old_scope = scope_push(&entity->function.parameters);
5484 entity_t *parameter = entity->function.parameters.entities;
5485 for ( ; parameter != NULL; parameter = parameter->base.next) {
5486 assert(parameter->base.parent_scope == NULL);
5487 parameter->base.parent_scope = current_scope;
5488 environment_push(parameter);
5491 /* parse declaration list */
5493 switch (token.type) {
5495 case T___extension__:
5496 /* This covers symbols, which are no type, too, and results in
5497 * better error messages. The typical cases are misspelled type
5498 * names and missing includes. */
5500 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
5508 /* pop function parameters */
5509 assert(current_scope == &entity->function.parameters);
5510 scope_pop(old_scope);
5511 environment_pop_to(top);
5513 /* update function type */
5514 type_t *new_type = duplicate_type(type);
5516 function_parameter_t *parameters = NULL;
5517 function_parameter_t *last_parameter = NULL;
5519 parameter = entity->function.parameters.entities;
5520 for (; parameter != NULL; parameter = parameter->base.next) {
5521 type_t *parameter_type = parameter->declaration.type;
5522 if (parameter_type == NULL) {
5524 errorf(HERE, "no type specified for function parameter '%Y'",
5525 parameter->base.symbol);
5527 if (warning.implicit_int) {
5528 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5529 parameter->base.symbol);
5531 parameter_type = type_int;
5532 parameter->declaration.type = parameter_type;
5536 semantic_parameter_incomplete(parameter);
5537 parameter_type = parameter->declaration.type;
5540 * we need the default promoted types for the function type
5542 parameter_type = get_default_promoted_type(parameter_type);
5544 function_parameter_t *function_parameter
5545 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5546 memset(function_parameter, 0, sizeof(function_parameter[0]));
5548 function_parameter->type = parameter_type;
5549 if (last_parameter != NULL) {
5550 last_parameter->next = function_parameter;
5552 parameters = function_parameter;
5554 last_parameter = function_parameter;
5557 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5559 new_type->function.parameters = parameters;
5560 new_type->function.unspecified_parameters = true;
5562 new_type = identify_new_type(new_type);
5564 entity->declaration.type = new_type;
5566 rem_anchor_token('{');
5569 static bool first_err = true;
5572 * When called with first_err set, prints the name of the current function,
5575 static void print_in_function(void)
5579 diagnosticf("%s: In function '%Y':\n",
5580 current_function->base.base.source_position.input_name,
5581 current_function->base.base.symbol);
5586 * Check if all labels are defined in the current function.
5587 * Check if all labels are used in the current function.
5589 static void check_labels(void)
5591 for (const goto_statement_t *goto_statement = goto_first;
5592 goto_statement != NULL;
5593 goto_statement = goto_statement->next) {
5594 /* skip computed gotos */
5595 if (goto_statement->expression != NULL)
5598 label_t *label = goto_statement->label;
5601 if (label->base.source_position.input_name == NULL) {
5602 print_in_function();
5603 errorf(&goto_statement->base.source_position,
5604 "label '%Y' used but not defined", label->base.symbol);
5608 if (warning.unused_label) {
5609 for (const label_statement_t *label_statement = label_first;
5610 label_statement != NULL;
5611 label_statement = label_statement->next) {
5612 label_t *label = label_statement->label;
5614 if (! label->used) {
5615 print_in_function();
5616 warningf(&label_statement->base.source_position,
5617 "label '%Y' defined but not used", label->base.symbol);
5623 static void warn_unused_entity(entity_t *entity, entity_t *last)
5625 entity_t const *const end = last != NULL ? last->base.next : NULL;
5626 for (; entity != end; entity = entity->base.next) {
5627 if (!is_declaration(entity))
5630 declaration_t *declaration = &entity->declaration;
5631 if (declaration->implicit)
5634 if (!declaration->used) {
5635 print_in_function();
5636 const char *what = get_entity_kind_name(entity->kind);
5637 warningf(&entity->base.source_position, "%s '%Y' is unused",
5638 what, entity->base.symbol);
5639 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5640 print_in_function();
5641 const char *what = get_entity_kind_name(entity->kind);
5642 warningf(&entity->base.source_position, "%s '%Y' is never read",
5643 what, entity->base.symbol);
5648 static void check_unused_variables(statement_t *const stmt, void *const env)
5652 switch (stmt->kind) {
5653 case STATEMENT_DECLARATION: {
5654 declaration_statement_t const *const decls = &stmt->declaration;
5655 warn_unused_entity(decls->declarations_begin,
5656 decls->declarations_end);
5661 warn_unused_entity(stmt->fors.scope.entities, NULL);
5670 * Check declarations of current_function for unused entities.
5672 static void check_declarations(void)
5674 if (warning.unused_parameter) {
5675 const scope_t *scope = ¤t_function->parameters;
5677 /* do not issue unused warnings for main */
5678 if (!is_sym_main(current_function->base.base.symbol)) {
5679 warn_unused_entity(scope->entities, NULL);
5682 if (warning.unused_variable) {
5683 walk_statements(current_function->statement, check_unused_variables,
5688 static int determine_truth(expression_t const* const cond)
5691 !is_constant_expression(cond) ? 0 :
5692 fold_constant(cond) != 0 ? 1 :
5696 static void check_reachable(statement_t *);
5697 static bool reaches_end;
5699 static bool expression_returns(expression_t const *const expr)
5701 switch (expr->kind) {
5703 expression_t const *const func = expr->call.function;
5704 if (func->kind == EXPR_REFERENCE) {
5705 entity_t *entity = func->reference.entity;
5706 if (entity->kind == ENTITY_FUNCTION
5707 && entity->declaration.modifiers & DM_NORETURN)
5711 if (!expression_returns(func))
5714 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5715 if (!expression_returns(arg->expression))
5722 case EXPR_REFERENCE:
5723 case EXPR_REFERENCE_ENUM_VALUE:
5725 case EXPR_CHARACTER_CONSTANT:
5726 case EXPR_WIDE_CHARACTER_CONSTANT:
5727 case EXPR_STRING_LITERAL:
5728 case EXPR_WIDE_STRING_LITERAL:
5729 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5730 case EXPR_LABEL_ADDRESS:
5731 case EXPR_CLASSIFY_TYPE:
5732 case EXPR_SIZEOF: // TODO handle obscure VLA case
5735 case EXPR_BUILTIN_SYMBOL:
5736 case EXPR_BUILTIN_CONSTANT_P:
5737 case EXPR_BUILTIN_PREFETCH:
5742 case EXPR_STATEMENT: {
5743 bool old_reaches_end = reaches_end;
5744 reaches_end = false;
5745 check_reachable(expr->statement.statement);
5746 bool returns = reaches_end;
5747 reaches_end = old_reaches_end;
5751 case EXPR_CONDITIONAL:
5752 // TODO handle constant expression
5754 if (!expression_returns(expr->conditional.condition))
5757 if (expr->conditional.true_expression != NULL
5758 && expression_returns(expr->conditional.true_expression))
5761 return expression_returns(expr->conditional.false_expression);
5764 return expression_returns(expr->select.compound);
5766 case EXPR_ARRAY_ACCESS:
5768 expression_returns(expr->array_access.array_ref) &&
5769 expression_returns(expr->array_access.index);
5772 return expression_returns(expr->va_starte.ap);
5775 return expression_returns(expr->va_arge.ap);
5777 EXPR_UNARY_CASES_MANDATORY
5778 return expression_returns(expr->unary.value);
5780 case EXPR_UNARY_THROW:
5784 // TODO handle constant lhs of && and ||
5786 expression_returns(expr->binary.left) &&
5787 expression_returns(expr->binary.right);
5793 panic("unhandled expression");
5796 static bool initializer_returns(initializer_t const *const init)
5798 switch (init->kind) {
5799 case INITIALIZER_VALUE:
5800 return expression_returns(init->value.value);
5802 case INITIALIZER_LIST: {
5803 initializer_t * const* i = init->list.initializers;
5804 initializer_t * const* const end = i + init->list.len;
5805 bool returns = true;
5806 for (; i != end; ++i) {
5807 if (!initializer_returns(*i))
5813 case INITIALIZER_STRING:
5814 case INITIALIZER_WIDE_STRING:
5815 case INITIALIZER_DESIGNATOR: // designators have no payload
5818 panic("unhandled initializer");
5821 static bool noreturn_candidate;
5823 static void check_reachable(statement_t *const stmt)
5825 if (stmt->base.reachable)
5827 if (stmt->kind != STATEMENT_DO_WHILE)
5828 stmt->base.reachable = true;
5830 statement_t *last = stmt;
5832 switch (stmt->kind) {
5833 case STATEMENT_INVALID:
5834 case STATEMENT_EMPTY:
5836 next = stmt->base.next;
5839 case STATEMENT_DECLARATION: {
5840 declaration_statement_t const *const decl = &stmt->declaration;
5841 entity_t const * ent = decl->declarations_begin;
5842 entity_t const *const last = decl->declarations_end;
5844 for (;; ent = ent->base.next) {
5845 if (ent->kind == ENTITY_VARIABLE &&
5846 ent->variable.initializer != NULL &&
5847 !initializer_returns(ent->variable.initializer)) {
5854 next = stmt->base.next;
5858 case STATEMENT_COMPOUND:
5859 next = stmt->compound.statements;
5861 next = stmt->base.next;
5864 case STATEMENT_RETURN: {
5865 expression_t const *const val = stmt->returns.value;
5866 if (val == NULL || expression_returns(val))
5867 noreturn_candidate = false;
5871 case STATEMENT_IF: {
5872 if_statement_t const *const ifs = &stmt->ifs;
5873 expression_t const *const cond = ifs->condition;
5875 if (!expression_returns(cond))
5878 int const val = determine_truth(cond);
5881 check_reachable(ifs->true_statement);
5886 if (ifs->false_statement != NULL) {
5887 check_reachable(ifs->false_statement);
5891 next = stmt->base.next;
5895 case STATEMENT_SWITCH: {
5896 switch_statement_t const *const switchs = &stmt->switchs;
5897 expression_t const *const expr = switchs->expression;
5899 if (!expression_returns(expr))
5902 if (is_constant_expression(expr)) {
5903 long const val = fold_constant(expr);
5904 case_label_statement_t * defaults = NULL;
5905 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5906 if (i->expression == NULL) {
5911 if (i->first_case <= val && val <= i->last_case) {
5912 check_reachable((statement_t*)i);
5917 if (defaults != NULL) {
5918 check_reachable((statement_t*)defaults);
5922 bool has_default = false;
5923 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5924 if (i->expression == NULL)
5927 check_reachable((statement_t*)i);
5934 next = stmt->base.next;
5938 case STATEMENT_EXPRESSION: {
5939 /* Check for noreturn function call */
5940 expression_t const *const expr = stmt->expression.expression;
5941 if (!expression_returns(expr))
5944 next = stmt->base.next;
5948 case STATEMENT_CONTINUE: {
5949 statement_t *parent = stmt;
5951 parent = parent->base.parent;
5952 if (parent == NULL) /* continue not within loop */
5956 switch (parent->kind) {
5957 case STATEMENT_WHILE: goto continue_while;
5958 case STATEMENT_DO_WHILE: goto continue_do_while;
5959 case STATEMENT_FOR: goto continue_for;
5966 case STATEMENT_BREAK: {
5967 statement_t *parent = stmt;
5969 parent = parent->base.parent;
5970 if (parent == NULL) /* break not within loop/switch */
5973 switch (parent->kind) {
5974 case STATEMENT_SWITCH:
5975 case STATEMENT_WHILE:
5976 case STATEMENT_DO_WHILE:
5979 next = parent->base.next;
5980 goto found_break_parent;
5989 case STATEMENT_GOTO:
5990 if (stmt->gotos.expression) {
5991 if (!expression_returns(stmt->gotos.expression))
5994 statement_t *parent = stmt->base.parent;
5995 if (parent == NULL) /* top level goto */
5999 next = stmt->gotos.label->statement;
6000 if (next == NULL) /* missing label */
6005 case STATEMENT_LABEL:
6006 next = stmt->label.statement;
6009 case STATEMENT_CASE_LABEL:
6010 next = stmt->case_label.statement;
6013 case STATEMENT_WHILE: {
6014 while_statement_t const *const whiles = &stmt->whiles;
6015 expression_t const *const cond = whiles->condition;
6017 if (!expression_returns(cond))
6020 int const val = determine_truth(cond);
6023 check_reachable(whiles->body);
6028 next = stmt->base.next;
6032 case STATEMENT_DO_WHILE:
6033 next = stmt->do_while.body;
6036 case STATEMENT_FOR: {
6037 for_statement_t *const fors = &stmt->fors;
6039 if (fors->condition_reachable)
6041 fors->condition_reachable = true;
6043 expression_t const *const cond = fors->condition;
6048 } else if (expression_returns(cond)) {
6049 val = determine_truth(cond);
6055 check_reachable(fors->body);
6060 next = stmt->base.next;
6064 case STATEMENT_MS_TRY: {
6065 ms_try_statement_t const *const ms_try = &stmt->ms_try;
6066 check_reachable(ms_try->try_statement);
6067 next = ms_try->final_statement;
6071 case STATEMENT_LEAVE: {
6072 statement_t *parent = stmt;
6074 parent = parent->base.parent;
6075 if (parent == NULL) /* __leave not within __try */
6078 if (parent->kind == STATEMENT_MS_TRY) {
6080 next = parent->ms_try.final_statement;
6088 panic("invalid statement kind");
6091 while (next == NULL) {
6092 next = last->base.parent;
6094 noreturn_candidate = false;
6096 type_t *const type = current_function->base.type;
6097 assert(is_type_function(type));
6098 type_t *const ret = skip_typeref(type->function.return_type);
6099 if (warning.return_type &&
6100 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
6101 is_type_valid(ret) &&
6102 !is_sym_main(current_function->base.base.symbol)) {
6103 warningf(&stmt->base.source_position,
6104 "control reaches end of non-void function");
6109 switch (next->kind) {
6110 case STATEMENT_INVALID:
6111 case STATEMENT_EMPTY:
6112 case STATEMENT_DECLARATION:
6113 case STATEMENT_EXPRESSION:
6115 case STATEMENT_RETURN:
6116 case STATEMENT_CONTINUE:
6117 case STATEMENT_BREAK:
6118 case STATEMENT_GOTO:
6119 case STATEMENT_LEAVE:
6120 panic("invalid control flow in function");
6122 case STATEMENT_COMPOUND:
6123 if (next->compound.stmt_expr) {
6129 case STATEMENT_SWITCH:
6130 case STATEMENT_LABEL:
6131 case STATEMENT_CASE_LABEL:
6133 next = next->base.next;
6136 case STATEMENT_WHILE: {
6138 if (next->base.reachable)
6140 next->base.reachable = true;
6142 while_statement_t const *const whiles = &next->whiles;
6143 expression_t const *const cond = whiles->condition;
6145 if (!expression_returns(cond))
6148 int const val = determine_truth(cond);
6151 check_reachable(whiles->body);
6157 next = next->base.next;
6161 case STATEMENT_DO_WHILE: {
6163 if (next->base.reachable)
6165 next->base.reachable = true;
6167 do_while_statement_t const *const dw = &next->do_while;
6168 expression_t const *const cond = dw->condition;
6170 if (!expression_returns(cond))
6173 int const val = determine_truth(cond);
6176 check_reachable(dw->body);
6182 next = next->base.next;
6186 case STATEMENT_FOR: {
6188 for_statement_t *const fors = &next->fors;
6190 fors->step_reachable = true;
6192 if (fors->condition_reachable)
6194 fors->condition_reachable = true;
6196 expression_t const *const cond = fors->condition;
6201 } else if (expression_returns(cond)) {
6202 val = determine_truth(cond);
6208 check_reachable(fors->body);
6214 next = next->base.next;
6218 case STATEMENT_MS_TRY:
6220 next = next->ms_try.final_statement;
6225 check_reachable(next);
6228 static void check_unreachable(statement_t* const stmt, void *const env)
6232 switch (stmt->kind) {
6233 case STATEMENT_DO_WHILE:
6234 if (!stmt->base.reachable) {
6235 expression_t const *const cond = stmt->do_while.condition;
6236 if (determine_truth(cond) >= 0) {
6237 warningf(&cond->base.source_position,
6238 "condition of do-while-loop is unreachable");
6243 case STATEMENT_FOR: {
6244 for_statement_t const* const fors = &stmt->fors;
6246 // if init and step are unreachable, cond is unreachable, too
6247 if (!stmt->base.reachable && !fors->step_reachable) {
6248 warningf(&stmt->base.source_position, "statement is unreachable");
6250 if (!stmt->base.reachable && fors->initialisation != NULL) {
6251 warningf(&fors->initialisation->base.source_position,
6252 "initialisation of for-statement is unreachable");
6255 if (!fors->condition_reachable && fors->condition != NULL) {
6256 warningf(&fors->condition->base.source_position,
6257 "condition of for-statement is unreachable");
6260 if (!fors->step_reachable && fors->step != NULL) {
6261 warningf(&fors->step->base.source_position,
6262 "step of for-statement is unreachable");
6268 case STATEMENT_COMPOUND:
6269 if (stmt->compound.statements != NULL)
6271 goto warn_unreachable;
6273 case STATEMENT_DECLARATION: {
6274 /* Only warn if there is at least one declarator with an initializer.
6275 * This typically occurs in switch statements. */
6276 declaration_statement_t const *const decl = &stmt->declaration;
6277 entity_t const * ent = decl->declarations_begin;
6278 entity_t const *const last = decl->declarations_end;
6280 for (;; ent = ent->base.next) {
6281 if (ent->kind == ENTITY_VARIABLE &&
6282 ent->variable.initializer != NULL) {
6283 goto warn_unreachable;
6293 if (!stmt->base.reachable)
6294 warningf(&stmt->base.source_position, "statement is unreachable");
6299 static void parse_external_declaration(void)
6301 /* function-definitions and declarations both start with declaration
6303 declaration_specifiers_t specifiers;
6304 memset(&specifiers, 0, sizeof(specifiers));
6306 add_anchor_token(';');
6307 parse_declaration_specifiers(&specifiers);
6308 rem_anchor_token(';');
6310 /* must be a declaration */
6311 if (token.type == ';') {
6312 parse_anonymous_declaration_rest(&specifiers);
6316 add_anchor_token(',');
6317 add_anchor_token('=');
6318 add_anchor_token(';');
6319 add_anchor_token('{');
6321 /* declarator is common to both function-definitions and declarations */
6322 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
6324 rem_anchor_token('{');
6325 rem_anchor_token(';');
6326 rem_anchor_token('=');
6327 rem_anchor_token(',');
6329 /* must be a declaration */
6330 switch (token.type) {
6334 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
6339 /* must be a function definition */
6340 parse_kr_declaration_list(ndeclaration);
6342 if (token.type != '{') {
6343 parse_error_expected("while parsing function definition", '{', NULL);
6344 eat_until_matching_token(';');
6348 assert(is_declaration(ndeclaration));
6349 type_t *type = skip_typeref(ndeclaration->declaration.type);
6351 if (!is_type_function(type)) {
6352 if (is_type_valid(type)) {
6353 errorf(HERE, "declarator '%#T' has a body but is not a function type",
6354 type, ndeclaration->base.symbol);
6360 if (warning.aggregate_return &&
6361 is_type_compound(skip_typeref(type->function.return_type))) {
6362 warningf(HERE, "function '%Y' returns an aggregate",
6363 ndeclaration->base.symbol);
6365 if (warning.traditional && !type->function.unspecified_parameters) {
6366 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6367 ndeclaration->base.symbol);
6369 if (warning.old_style_definition && type->function.unspecified_parameters) {
6370 warningf(HERE, "old-style function definition '%Y'",
6371 ndeclaration->base.symbol);
6374 /* § 6.7.5.3:14 a function definition with () means no
6375 * parameters (and not unspecified parameters) */
6376 if (type->function.unspecified_parameters &&
6377 type->function.parameters == NULL &&
6378 !type->function.kr_style_parameters) {
6379 type_t *copy = duplicate_type(type);
6380 copy->function.unspecified_parameters = false;
6381 type = identify_new_type(copy);
6383 ndeclaration->declaration.type = type;
6386 entity_t *const entity = record_entity(ndeclaration, true);
6387 assert(entity->kind == ENTITY_FUNCTION);
6388 assert(ndeclaration->kind == ENTITY_FUNCTION);
6390 function_t *function = &entity->function;
6391 if (ndeclaration != entity) {
6392 function->parameters = ndeclaration->function.parameters;
6394 assert(is_declaration(entity));
6395 type = skip_typeref(entity->declaration.type);
6397 /* push function parameters and switch scope */
6398 size_t const top = environment_top();
6399 scope_t *old_scope = scope_push(&function->parameters);
6401 entity_t *parameter = function->parameters.entities;
6402 for (; parameter != NULL; parameter = parameter->base.next) {
6403 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6404 parameter->base.parent_scope = current_scope;
6406 assert(parameter->base.parent_scope == NULL
6407 || parameter->base.parent_scope == current_scope);
6408 parameter->base.parent_scope = current_scope;
6409 if (parameter->base.symbol == NULL) {
6410 errorf(¶meter->base.source_position, "parameter name omitted");
6413 environment_push(parameter);
6416 if (function->statement != NULL) {
6417 parser_error_multiple_definition(entity, HERE);
6420 /* parse function body */
6421 int label_stack_top = label_top();
6422 function_t *old_current_function = current_function;
6423 current_function = function;
6424 current_parent = NULL;
6427 goto_anchor = &goto_first;
6429 label_anchor = &label_first;
6431 statement_t *const body = parse_compound_statement(false);
6432 function->statement = body;
6435 check_declarations();
6436 if (warning.return_type ||
6437 warning.unreachable_code ||
6438 (warning.missing_noreturn
6439 && !(function->base.modifiers & DM_NORETURN))) {
6440 noreturn_candidate = true;
6441 check_reachable(body);
6442 if (warning.unreachable_code)
6443 walk_statements(body, check_unreachable, NULL);
6444 if (warning.missing_noreturn &&
6445 noreturn_candidate &&
6446 !(function->base.modifiers & DM_NORETURN)) {
6447 warningf(&body->base.source_position,
6448 "function '%#T' is candidate for attribute 'noreturn'",
6449 type, entity->base.symbol);
6453 assert(current_parent == NULL);
6454 assert(current_function == function);
6455 current_function = old_current_function;
6456 label_pop_to(label_stack_top);
6459 assert(current_scope == &function->parameters);
6460 scope_pop(old_scope);
6461 environment_pop_to(top);
6464 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6465 source_position_t *source_position,
6466 const symbol_t *symbol)
6468 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6470 type->bitfield.base_type = base_type;
6471 type->bitfield.size_expression = size;
6474 type_t *skipped_type = skip_typeref(base_type);
6475 if (!is_type_integer(skipped_type)) {
6476 errorf(HERE, "bitfield base type '%T' is not an integer type",
6480 bit_size = skipped_type->base.size * 8;
6483 if (is_constant_expression(size)) {
6484 long v = fold_constant(size);
6487 errorf(source_position, "negative width in bit-field '%Y'", symbol);
6488 } else if (v == 0) {
6489 errorf(source_position, "zero width for bit-field '%Y'", symbol);
6490 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6491 errorf(source_position, "width of '%Y' exceeds its type", symbol);
6493 type->bitfield.bit_size = v;
6500 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6502 entity_t *iter = compound->members.entities;
6503 for (; iter != NULL; iter = iter->base.next) {
6504 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6507 if (iter->base.symbol == symbol) {
6509 } else if (iter->base.symbol == NULL) {
6510 type_t *type = skip_typeref(iter->declaration.type);
6511 if (is_type_compound(type)) {
6513 = find_compound_entry(type->compound.compound, symbol);
6524 static void parse_compound_declarators(compound_t *compound,
6525 const declaration_specifiers_t *specifiers)
6530 if (token.type == ':') {
6531 source_position_t source_position = *HERE;
6534 type_t *base_type = specifiers->type;
6535 expression_t *size = parse_constant_expression();
6537 type_t *type = make_bitfield_type(base_type, size,
6538 &source_position, sym_anonymous);
6540 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6541 entity->base.namespc = NAMESPACE_NORMAL;
6542 entity->base.source_position = source_position;
6543 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6544 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6545 entity->declaration.modifiers = specifiers->modifiers;
6546 entity->declaration.type = type;
6547 append_entity(&compound->members, entity);
6549 entity = parse_declarator(specifiers,
6550 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
6551 if (entity->kind == ENTITY_TYPEDEF) {
6552 errorf(&entity->base.source_position,
6553 "typedef not allowed as compound member");
6555 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6557 /* make sure we don't define a symbol multiple times */
6558 symbol_t *symbol = entity->base.symbol;
6559 if (symbol != NULL) {
6560 entity_t *prev = find_compound_entry(compound, symbol);
6562 errorf(&entity->base.source_position,
6563 "multiple declarations of symbol '%Y' (declared %P)",
6564 symbol, &prev->base.source_position);
6568 if (token.type == ':') {
6569 source_position_t source_position = *HERE;
6571 expression_t *size = parse_constant_expression();
6573 type_t *type = entity->declaration.type;
6574 type_t *bitfield_type = make_bitfield_type(type, size,
6575 &source_position, entity->base.symbol);
6576 entity->declaration.type = bitfield_type;
6578 type_t *orig_type = entity->declaration.type;
6579 type_t *type = skip_typeref(orig_type);
6580 if (is_type_function(type)) {
6581 errorf(&entity->base.source_position,
6582 "compound member '%Y' must not have function type '%T'",
6583 entity->base.symbol, orig_type);
6584 } else if (is_type_incomplete(type)) {
6585 /* §6.7.2.1:16 flexible array member */
6586 if (is_type_array(type) &&
6587 token.type == ';' &&
6588 look_ahead(1)->type == '}') {
6589 compound->has_flexible_member = true;
6591 errorf(&entity->base.source_position,
6592 "compound member '%Y' has incomplete type '%T'",
6593 entity->base.symbol, orig_type);
6598 append_entity(&compound->members, entity);
6602 if (token.type != ',')
6606 expect(';', end_error);
6609 anonymous_entity = NULL;
6612 static void parse_compound_type_entries(compound_t *compound)
6615 add_anchor_token('}');
6617 while (token.type != '}') {
6618 if (token.type == T_EOF) {
6619 errorf(HERE, "EOF while parsing struct");
6622 declaration_specifiers_t specifiers;
6623 memset(&specifiers, 0, sizeof(specifiers));
6624 parse_declaration_specifiers(&specifiers);
6626 parse_compound_declarators(compound, &specifiers);
6628 rem_anchor_token('}');
6632 compound->complete = true;
6635 static type_t *parse_typename(void)
6637 declaration_specifiers_t specifiers;
6638 memset(&specifiers, 0, sizeof(specifiers));
6639 parse_declaration_specifiers(&specifiers);
6640 if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6641 specifiers.thread_local) {
6642 /* TODO: improve error message, user does probably not know what a
6643 * storage class is...
6645 errorf(HERE, "typename may not have a storage class");
6648 type_t *result = parse_abstract_declarator(specifiers.type);
6656 typedef expression_t* (*parse_expression_function)(void);
6657 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6659 typedef struct expression_parser_function_t expression_parser_function_t;
6660 struct expression_parser_function_t {
6661 parse_expression_function parser;
6662 precedence_t infix_precedence;
6663 parse_expression_infix_function infix_parser;
6666 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6669 * Prints an error message if an expression was expected but not read
6671 static expression_t *expected_expression_error(void)
6673 /* skip the error message if the error token was read */
6674 if (token.type != T_ERROR) {
6675 errorf(HERE, "expected expression, got token %K", &token);
6679 return create_invalid_expression();
6683 * Parse a string constant.
6685 static expression_t *parse_string_const(void)
6688 if (token.type == T_STRING_LITERAL) {
6689 string_t res = token.v.string;
6691 while (token.type == T_STRING_LITERAL) {
6692 res = concat_strings(&res, &token.v.string);
6695 if (token.type != T_WIDE_STRING_LITERAL) {
6696 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6697 /* note: that we use type_char_ptr here, which is already the
6698 * automatic converted type. revert_automatic_type_conversion
6699 * will construct the array type */
6700 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6701 cnst->string.value = res;
6705 wres = concat_string_wide_string(&res, &token.v.wide_string);
6707 wres = token.v.wide_string;
6712 switch (token.type) {
6713 case T_WIDE_STRING_LITERAL:
6714 wres = concat_wide_strings(&wres, &token.v.wide_string);
6717 case T_STRING_LITERAL:
6718 wres = concat_wide_string_string(&wres, &token.v.string);
6722 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6723 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6724 cnst->wide_string.value = wres;
6733 * Parse a boolean constant.
6735 static expression_t *parse_bool_const(bool value)
6737 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6738 cnst->base.type = type_bool;
6739 cnst->conste.v.int_value = value;
6747 * Parse an integer constant.
6749 static expression_t *parse_int_const(void)
6751 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6752 cnst->base.type = token.datatype;
6753 cnst->conste.v.int_value = token.v.intvalue;
6761 * Parse a character constant.
6763 static expression_t *parse_character_constant(void)
6765 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6766 cnst->base.type = token.datatype;
6767 cnst->conste.v.character = token.v.string;
6769 if (cnst->conste.v.character.size != 1) {
6771 errorf(HERE, "more than 1 character in character constant");
6772 } else if (warning.multichar) {
6773 warningf(HERE, "multi-character character constant");
6782 * Parse a wide character constant.
6784 static expression_t *parse_wide_character_constant(void)
6786 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6787 cnst->base.type = token.datatype;
6788 cnst->conste.v.wide_character = token.v.wide_string;
6790 if (cnst->conste.v.wide_character.size != 1) {
6792 errorf(HERE, "more than 1 character in character constant");
6793 } else if (warning.multichar) {
6794 warningf(HERE, "multi-character character constant");
6803 * Parse a float constant.
6805 static expression_t *parse_float_const(void)
6807 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6808 cnst->base.type = token.datatype;
6809 cnst->conste.v.float_value = token.v.floatvalue;
6816 static entity_t *create_implicit_function(symbol_t *symbol,
6817 const source_position_t *source_position)
6819 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6820 ntype->function.return_type = type_int;
6821 ntype->function.unspecified_parameters = true;
6822 ntype->function.linkage = LINKAGE_C;
6823 type_t *type = identify_new_type(ntype);
6825 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6826 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6827 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6828 entity->declaration.type = type;
6829 entity->declaration.implicit = true;
6830 entity->base.symbol = symbol;
6831 entity->base.source_position = *source_position;
6833 bool strict_prototypes_old = warning.strict_prototypes;
6834 warning.strict_prototypes = false;
6835 record_entity(entity, false);
6836 warning.strict_prototypes = strict_prototypes_old;
6842 * Creates a return_type (func)(argument_type) function type if not
6845 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6846 type_t *argument_type2)
6848 function_parameter_t *parameter2
6849 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6850 memset(parameter2, 0, sizeof(parameter2[0]));
6851 parameter2->type = argument_type2;
6853 function_parameter_t *parameter1
6854 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6855 memset(parameter1, 0, sizeof(parameter1[0]));
6856 parameter1->type = argument_type1;
6857 parameter1->next = parameter2;
6859 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6860 type->function.return_type = return_type;
6861 type->function.parameters = parameter1;
6863 return identify_new_type(type);
6867 * Creates a return_type (func)(argument_type) function type if not
6870 * @param return_type the return type
6871 * @param argument_type the argument type
6873 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6875 function_parameter_t *parameter
6876 = obstack_alloc(type_obst, sizeof(parameter[0]));
6877 memset(parameter, 0, sizeof(parameter[0]));
6878 parameter->type = argument_type;
6880 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6881 type->function.return_type = return_type;
6882 type->function.parameters = parameter;
6884 return identify_new_type(type);
6887 static type_t *make_function_0_type(type_t *return_type)
6889 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6890 type->function.return_type = return_type;
6891 type->function.parameters = NULL;
6893 return identify_new_type(type);
6897 * Creates a function type for some function like builtins.
6899 * @param symbol the symbol describing the builtin
6901 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6903 switch (symbol->ID) {
6904 case T___builtin_alloca:
6905 return make_function_1_type(type_void_ptr, type_size_t);
6906 case T___builtin_huge_val:
6907 return make_function_0_type(type_double);
6908 case T___builtin_inf:
6909 return make_function_0_type(type_double);
6910 case T___builtin_inff:
6911 return make_function_0_type(type_float);
6912 case T___builtin_infl:
6913 return make_function_0_type(type_long_double);
6914 case T___builtin_nan:
6915 return make_function_1_type(type_double, type_char_ptr);
6916 case T___builtin_nanf:
6917 return make_function_1_type(type_float, type_char_ptr);
6918 case T___builtin_nanl:
6919 return make_function_1_type(type_long_double, type_char_ptr);
6920 case T___builtin_va_end:
6921 return make_function_1_type(type_void, type_valist);
6922 case T___builtin_expect:
6923 return make_function_2_type(type_long, type_long, type_long);
6925 internal_errorf(HERE, "not implemented builtin identifier found");
6930 * Performs automatic type cast as described in § 6.3.2.1.
6932 * @param orig_type the original type
6934 static type_t *automatic_type_conversion(type_t *orig_type)
6936 type_t *type = skip_typeref(orig_type);
6937 if (is_type_array(type)) {
6938 array_type_t *array_type = &type->array;
6939 type_t *element_type = array_type->element_type;
6940 unsigned qualifiers = array_type->base.qualifiers;
6942 return make_pointer_type(element_type, qualifiers);
6945 if (is_type_function(type)) {
6946 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6953 * reverts the automatic casts of array to pointer types and function
6954 * to function-pointer types as defined § 6.3.2.1
6956 type_t *revert_automatic_type_conversion(const expression_t *expression)
6958 switch (expression->kind) {
6959 case EXPR_REFERENCE: {
6960 entity_t *entity = expression->reference.entity;
6961 if (is_declaration(entity)) {
6962 return entity->declaration.type;
6963 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6964 return entity->enum_value.enum_type;
6966 panic("no declaration or enum in reference");
6971 entity_t *entity = expression->select.compound_entry;
6972 assert(is_declaration(entity));
6973 type_t *type = entity->declaration.type;
6974 return get_qualified_type(type,
6975 expression->base.type->base.qualifiers);
6978 case EXPR_UNARY_DEREFERENCE: {
6979 const expression_t *const value = expression->unary.value;
6980 type_t *const type = skip_typeref(value->base.type);
6981 if (!is_type_pointer(type))
6982 return type_error_type;
6983 return type->pointer.points_to;
6986 case EXPR_BUILTIN_SYMBOL:
6987 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6989 case EXPR_ARRAY_ACCESS: {
6990 const expression_t *array_ref = expression->array_access.array_ref;
6991 type_t *type_left = skip_typeref(array_ref->base.type);
6992 if (!is_type_pointer(type_left))
6993 return type_error_type;
6994 return type_left->pointer.points_to;
6997 case EXPR_STRING_LITERAL: {
6998 size_t size = expression->string.value.size;
6999 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
7002 case EXPR_WIDE_STRING_LITERAL: {
7003 size_t size = expression->wide_string.value.size;
7004 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
7007 case EXPR_COMPOUND_LITERAL:
7008 return expression->compound_literal.type;
7011 return expression->base.type;
7015 static expression_t *parse_reference(void)
7017 symbol_t *const symbol = token.v.symbol;
7019 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
7021 if (entity == NULL) {
7022 if (!strict_mode && look_ahead(1)->type == '(') {
7023 /* an implicitly declared function */
7024 if (warning.error_implicit_function_declaration) {
7025 errorf(HERE, "implicit declaration of function '%Y'", symbol);
7026 } else if (warning.implicit_function_declaration) {
7027 warningf(HERE, "implicit declaration of function '%Y'", symbol);
7030 entity = create_implicit_function(symbol, HERE);
7032 errorf(HERE, "unknown identifier '%Y' found.", symbol);
7033 entity = create_error_entity(symbol, ENTITY_VARIABLE);
7039 if (is_declaration(entity)) {
7040 orig_type = entity->declaration.type;
7041 } else if (entity->kind == ENTITY_ENUM_VALUE) {
7042 orig_type = entity->enum_value.enum_type;
7043 } else if (entity->kind == ENTITY_TYPEDEF) {
7044 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
7047 return create_invalid_expression();
7049 panic("expected declaration or enum value in reference");
7052 /* we always do the auto-type conversions; the & and sizeof parser contains
7053 * code to revert this! */
7054 type_t *type = automatic_type_conversion(orig_type);
7056 expression_kind_t kind = EXPR_REFERENCE;
7057 if (entity->kind == ENTITY_ENUM_VALUE)
7058 kind = EXPR_REFERENCE_ENUM_VALUE;
7060 expression_t *expression = allocate_expression_zero(kind);
7061 expression->reference.entity = entity;
7062 expression->base.type = type;
7064 /* this declaration is used */
7065 if (is_declaration(entity)) {
7066 entity->declaration.used = true;
7069 if (entity->base.parent_scope != file_scope
7070 && entity->base.parent_scope->depth < current_function->parameters.depth
7071 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
7072 if (entity->kind == ENTITY_VARIABLE) {
7073 /* access of a variable from an outer function */
7074 entity->variable.address_taken = true;
7075 } else if (entity->kind == ENTITY_PARAMETER) {
7076 entity->parameter.address_taken = true;
7078 current_function->need_closure = true;
7081 /* check for deprecated functions */
7082 if (warning.deprecated_declarations
7083 && is_declaration(entity)
7084 && entity->declaration.modifiers & DM_DEPRECATED) {
7085 declaration_t *declaration = &entity->declaration;
7087 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
7088 "function" : "variable";
7090 if (declaration->deprecated_string != NULL) {
7091 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
7092 prefix, entity->base.symbol, &entity->base.source_position,
7093 declaration->deprecated_string);
7095 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
7096 entity->base.symbol, &entity->base.source_position);
7100 if (warning.init_self && entity == current_init_decl && !in_type_prop
7101 && entity->kind == ENTITY_VARIABLE) {
7102 current_init_decl = NULL;
7103 warningf(HERE, "variable '%#T' is initialized by itself",
7104 entity->declaration.type, entity->base.symbol);
7111 static bool semantic_cast(expression_t *cast)
7113 expression_t *expression = cast->unary.value;
7114 type_t *orig_dest_type = cast->base.type;
7115 type_t *orig_type_right = expression->base.type;
7116 type_t const *dst_type = skip_typeref(orig_dest_type);
7117 type_t const *src_type = skip_typeref(orig_type_right);
7118 source_position_t const *pos = &cast->base.source_position;
7120 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
7121 if (dst_type == type_void)
7124 /* only integer and pointer can be casted to pointer */
7125 if (is_type_pointer(dst_type) &&
7126 !is_type_pointer(src_type) &&
7127 !is_type_integer(src_type) &&
7128 is_type_valid(src_type)) {
7129 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
7133 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
7134 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
7138 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
7139 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
7143 if (warning.cast_qual &&
7144 is_type_pointer(src_type) &&
7145 is_type_pointer(dst_type)) {
7146 type_t *src = skip_typeref(src_type->pointer.points_to);
7147 type_t *dst = skip_typeref(dst_type->pointer.points_to);
7148 unsigned missing_qualifiers =
7149 src->base.qualifiers & ~dst->base.qualifiers;
7150 if (missing_qualifiers != 0) {
7152 "cast discards qualifiers '%Q' in pointer target type of '%T'",
7153 missing_qualifiers, orig_type_right);
7159 static expression_t *parse_compound_literal(type_t *type)
7161 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
7163 parse_initializer_env_t env;
7166 env.must_be_constant = false;
7167 initializer_t *initializer = parse_initializer(&env);
7170 expression->compound_literal.initializer = initializer;
7171 expression->compound_literal.type = type;
7172 expression->base.type = automatic_type_conversion(type);
7178 * Parse a cast expression.
7180 static expression_t *parse_cast(void)
7182 add_anchor_token(')');
7184 source_position_t source_position = token.source_position;
7186 type_t *type = parse_typename();
7188 rem_anchor_token(')');
7189 expect(')', end_error);
7191 if (token.type == '{') {
7192 return parse_compound_literal(type);
7195 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
7196 cast->base.source_position = source_position;
7198 expression_t *value = parse_sub_expression(PREC_CAST);
7199 cast->base.type = type;
7200 cast->unary.value = value;
7202 if (! semantic_cast(cast)) {
7203 /* TODO: record the error in the AST. else it is impossible to detect it */
7208 return create_invalid_expression();
7212 * Parse a statement expression.
7214 static expression_t *parse_statement_expression(void)
7216 add_anchor_token(')');
7218 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
7220 statement_t *statement = parse_compound_statement(true);
7221 statement->compound.stmt_expr = true;
7222 expression->statement.statement = statement;
7224 /* find last statement and use its type */
7225 type_t *type = type_void;
7226 const statement_t *stmt = statement->compound.statements;
7228 while (stmt->base.next != NULL)
7229 stmt = stmt->base.next;
7231 if (stmt->kind == STATEMENT_EXPRESSION) {
7232 type = stmt->expression.expression->base.type;
7234 } else if (warning.other) {
7235 warningf(&expression->base.source_position, "empty statement expression ({})");
7237 expression->base.type = type;
7239 rem_anchor_token(')');
7240 expect(')', end_error);
7247 * Parse a parenthesized expression.
7249 static expression_t *parse_parenthesized_expression(void)
7253 switch (token.type) {
7255 /* gcc extension: a statement expression */
7256 return parse_statement_expression();
7260 return parse_cast();
7262 if (is_typedef_symbol(token.v.symbol)) {
7263 return parse_cast();
7267 add_anchor_token(')');
7268 expression_t *result = parse_expression();
7269 result->base.parenthesized = true;
7270 rem_anchor_token(')');
7271 expect(')', end_error);
7277 static expression_t *parse_function_keyword(void)
7281 if (current_function == NULL) {
7282 errorf(HERE, "'__func__' used outside of a function");
7285 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7286 expression->base.type = type_char_ptr;
7287 expression->funcname.kind = FUNCNAME_FUNCTION;
7294 static expression_t *parse_pretty_function_keyword(void)
7296 if (current_function == NULL) {
7297 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
7300 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7301 expression->base.type = type_char_ptr;
7302 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
7304 eat(T___PRETTY_FUNCTION__);
7309 static expression_t *parse_funcsig_keyword(void)
7311 if (current_function == NULL) {
7312 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7315 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7316 expression->base.type = type_char_ptr;
7317 expression->funcname.kind = FUNCNAME_FUNCSIG;
7324 static expression_t *parse_funcdname_keyword(void)
7326 if (current_function == NULL) {
7327 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7330 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7331 expression->base.type = type_char_ptr;
7332 expression->funcname.kind = FUNCNAME_FUNCDNAME;
7334 eat(T___FUNCDNAME__);
7339 static designator_t *parse_designator(void)
7341 designator_t *result = allocate_ast_zero(sizeof(result[0]));
7342 result->source_position = *HERE;
7344 if (token.type != T_IDENTIFIER) {
7345 parse_error_expected("while parsing member designator",
7346 T_IDENTIFIER, NULL);
7349 result->symbol = token.v.symbol;
7352 designator_t *last_designator = result;
7354 if (token.type == '.') {
7356 if (token.type != T_IDENTIFIER) {
7357 parse_error_expected("while parsing member designator",
7358 T_IDENTIFIER, NULL);
7361 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7362 designator->source_position = *HERE;
7363 designator->symbol = token.v.symbol;
7366 last_designator->next = designator;
7367 last_designator = designator;
7370 if (token.type == '[') {
7372 add_anchor_token(']');
7373 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7374 designator->source_position = *HERE;
7375 designator->array_index = parse_expression();
7376 rem_anchor_token(']');
7377 expect(']', end_error);
7378 if (designator->array_index == NULL) {
7382 last_designator->next = designator;
7383 last_designator = designator;
7395 * Parse the __builtin_offsetof() expression.
7397 static expression_t *parse_offsetof(void)
7399 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7400 expression->base.type = type_size_t;
7402 eat(T___builtin_offsetof);
7404 expect('(', end_error);
7405 add_anchor_token(',');
7406 type_t *type = parse_typename();
7407 rem_anchor_token(',');
7408 expect(',', end_error);
7409 add_anchor_token(')');
7410 designator_t *designator = parse_designator();
7411 rem_anchor_token(')');
7412 expect(')', end_error);
7414 expression->offsetofe.type = type;
7415 expression->offsetofe.designator = designator;
7418 memset(&path, 0, sizeof(path));
7419 path.top_type = type;
7420 path.path = NEW_ARR_F(type_path_entry_t, 0);
7422 descend_into_subtype(&path);
7424 if (!walk_designator(&path, designator, true)) {
7425 return create_invalid_expression();
7428 DEL_ARR_F(path.path);
7432 return create_invalid_expression();
7436 * Parses a _builtin_va_start() expression.
7438 static expression_t *parse_va_start(void)
7440 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7442 eat(T___builtin_va_start);
7444 expect('(', end_error);
7445 add_anchor_token(',');
7446 expression->va_starte.ap = parse_assignment_expression();
7447 rem_anchor_token(',');
7448 expect(',', end_error);
7449 expression_t *const expr = parse_assignment_expression();
7450 if (expr->kind == EXPR_REFERENCE) {
7451 entity_t *const entity = expr->reference.entity;
7452 if (entity->base.parent_scope != ¤t_function->parameters
7453 || entity->base.next != NULL
7454 || entity->kind != ENTITY_PARAMETER) {
7455 errorf(&expr->base.source_position,
7456 "second argument of 'va_start' must be last parameter of the current function");
7458 expression->va_starte.parameter = &entity->variable;
7460 expect(')', end_error);
7463 expect(')', end_error);
7465 return create_invalid_expression();
7469 * Parses a _builtin_va_arg() expression.
7471 static expression_t *parse_va_arg(void)
7473 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7475 eat(T___builtin_va_arg);
7477 expect('(', end_error);
7478 expression->va_arge.ap = parse_assignment_expression();
7479 expect(',', end_error);
7480 expression->base.type = parse_typename();
7481 expect(')', end_error);
7485 return create_invalid_expression();
7488 static expression_t *parse_builtin_symbol(void)
7490 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7492 symbol_t *symbol = token.v.symbol;
7494 expression->builtin_symbol.symbol = symbol;
7497 type_t *type = get_builtin_symbol_type(symbol);
7498 type = automatic_type_conversion(type);
7500 expression->base.type = type;
7505 * Parses a __builtin_constant() expression.
7507 static expression_t *parse_builtin_constant(void)
7509 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7511 eat(T___builtin_constant_p);
7513 expect('(', end_error);
7514 add_anchor_token(')');
7515 expression->builtin_constant.value = parse_assignment_expression();
7516 rem_anchor_token(')');
7517 expect(')', end_error);
7518 expression->base.type = type_int;
7522 return create_invalid_expression();
7526 * Parses a __builtin_prefetch() expression.
7528 static expression_t *parse_builtin_prefetch(void)
7530 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7532 eat(T___builtin_prefetch);
7534 expect('(', end_error);
7535 add_anchor_token(')');
7536 expression->builtin_prefetch.adr = parse_assignment_expression();
7537 if (token.type == ',') {
7539 expression->builtin_prefetch.rw = parse_assignment_expression();
7541 if (token.type == ',') {
7543 expression->builtin_prefetch.locality = parse_assignment_expression();
7545 rem_anchor_token(')');
7546 expect(')', end_error);
7547 expression->base.type = type_void;
7551 return create_invalid_expression();
7555 * Parses a __builtin_is_*() compare expression.
7557 static expression_t *parse_compare_builtin(void)
7559 expression_t *expression;
7561 switch (token.type) {
7562 case T___builtin_isgreater:
7563 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7565 case T___builtin_isgreaterequal:
7566 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7568 case T___builtin_isless:
7569 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7571 case T___builtin_islessequal:
7572 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7574 case T___builtin_islessgreater:
7575 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7577 case T___builtin_isunordered:
7578 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7581 internal_errorf(HERE, "invalid compare builtin found");
7583 expression->base.source_position = *HERE;
7586 expect('(', end_error);
7587 expression->binary.left = parse_assignment_expression();
7588 expect(',', end_error);
7589 expression->binary.right = parse_assignment_expression();
7590 expect(')', end_error);
7592 type_t *const orig_type_left = expression->binary.left->base.type;
7593 type_t *const orig_type_right = expression->binary.right->base.type;
7595 type_t *const type_left = skip_typeref(orig_type_left);
7596 type_t *const type_right = skip_typeref(orig_type_right);
7597 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7598 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7599 type_error_incompatible("invalid operands in comparison",
7600 &expression->base.source_position, orig_type_left, orig_type_right);
7603 semantic_comparison(&expression->binary);
7608 return create_invalid_expression();
7613 * Parses a __builtin_expect(, end_error) expression.
7615 static expression_t *parse_builtin_expect(void, end_error)
7617 expression_t *expression
7618 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7620 eat(T___builtin_expect);
7622 expect('(', end_error);
7623 expression->binary.left = parse_assignment_expression();
7624 expect(',', end_error);
7625 expression->binary.right = parse_constant_expression();
7626 expect(')', end_error);
7628 expression->base.type = expression->binary.left->base.type;
7632 return create_invalid_expression();
7637 * Parses a MS assume() expression.
7639 static expression_t *parse_assume(void)
7641 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7645 expect('(', end_error);
7646 add_anchor_token(')');
7647 expression->unary.value = parse_assignment_expression();
7648 rem_anchor_token(')');
7649 expect(')', end_error);
7651 expression->base.type = type_void;
7654 return create_invalid_expression();
7658 * Return the declaration for a given label symbol or create a new one.
7660 * @param symbol the symbol of the label
7662 static label_t *get_label(symbol_t *symbol)
7665 assert(current_function != NULL);
7667 label = get_entity(symbol, NAMESPACE_LABEL);
7668 /* if we found a local label, we already created the declaration */
7669 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7670 if (label->base.parent_scope != current_scope) {
7671 assert(label->base.parent_scope->depth < current_scope->depth);
7672 current_function->goto_to_outer = true;
7674 return &label->label;
7677 label = get_entity(symbol, NAMESPACE_LABEL);
7678 /* if we found a label in the same function, then we already created the
7681 && label->base.parent_scope == ¤t_function->parameters) {
7682 return &label->label;
7685 /* otherwise we need to create a new one */
7686 label = allocate_entity_zero(ENTITY_LABEL);
7687 label->base.namespc = NAMESPACE_LABEL;
7688 label->base.symbol = symbol;
7692 return &label->label;
7696 * Parses a GNU && label address expression.
7698 static expression_t *parse_label_address(void)
7700 source_position_t source_position = token.source_position;
7702 if (token.type != T_IDENTIFIER) {
7703 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7706 symbol_t *symbol = token.v.symbol;
7709 label_t *label = get_label(symbol);
7711 label->address_taken = true;
7713 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7714 expression->base.source_position = source_position;
7716 /* label address is threaten as a void pointer */
7717 expression->base.type = type_void_ptr;
7718 expression->label_address.label = label;
7721 return create_invalid_expression();
7725 * Parse a microsoft __noop expression.
7727 static expression_t *parse_noop_expression(void)
7729 /* the result is a (int)0 */
7730 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7731 cnst->base.type = type_int;
7732 cnst->conste.v.int_value = 0;
7733 cnst->conste.is_ms_noop = true;
7737 if (token.type == '(') {
7738 /* parse arguments */
7740 add_anchor_token(')');
7741 add_anchor_token(',');
7743 if (token.type != ')') {
7745 (void)parse_assignment_expression();
7746 if (token.type != ',')
7752 rem_anchor_token(',');
7753 rem_anchor_token(')');
7754 expect(')', end_error);
7761 * Parses a primary expression.
7763 static expression_t *parse_primary_expression(void)
7765 switch (token.type) {
7766 case T_false: return parse_bool_const(false);
7767 case T_true: return parse_bool_const(true);
7768 case T_INTEGER: return parse_int_const();
7769 case T_CHARACTER_CONSTANT: return parse_character_constant();
7770 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7771 case T_FLOATINGPOINT: return parse_float_const();
7772 case T_STRING_LITERAL:
7773 case T_WIDE_STRING_LITERAL: return parse_string_const();
7774 case T_IDENTIFIER: return parse_reference();
7775 case T___FUNCTION__:
7776 case T___func__: return parse_function_keyword();
7777 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7778 case T___FUNCSIG__: return parse_funcsig_keyword();
7779 case T___FUNCDNAME__: return parse_funcdname_keyword();
7780 case T___builtin_offsetof: return parse_offsetof();
7781 case T___builtin_va_start: return parse_va_start();
7782 case T___builtin_va_arg: return parse_va_arg();
7783 case T___builtin_expect:
7784 case T___builtin_alloca:
7785 case T___builtin_inf:
7786 case T___builtin_inff:
7787 case T___builtin_infl:
7788 case T___builtin_nan:
7789 case T___builtin_nanf:
7790 case T___builtin_nanl:
7791 case T___builtin_huge_val:
7792 case T___builtin_va_end: return parse_builtin_symbol();
7793 case T___builtin_isgreater:
7794 case T___builtin_isgreaterequal:
7795 case T___builtin_isless:
7796 case T___builtin_islessequal:
7797 case T___builtin_islessgreater:
7798 case T___builtin_isunordered: return parse_compare_builtin();
7799 case T___builtin_constant_p: return parse_builtin_constant();
7800 case T___builtin_prefetch: return parse_builtin_prefetch();
7801 case T__assume: return parse_assume();
7804 return parse_label_address();
7807 case '(': return parse_parenthesized_expression();
7808 case T___noop: return parse_noop_expression();
7811 errorf(HERE, "unexpected token %K, expected an expression", &token);
7812 return create_invalid_expression();
7816 * Check if the expression has the character type and issue a warning then.
7818 static void check_for_char_index_type(const expression_t *expression)
7820 type_t *const type = expression->base.type;
7821 const type_t *const base_type = skip_typeref(type);
7823 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7824 warning.char_subscripts) {
7825 warningf(&expression->base.source_position,
7826 "array subscript has type '%T'", type);
7830 static expression_t *parse_array_expression(expression_t *left)
7832 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7835 add_anchor_token(']');
7837 expression_t *inside = parse_expression();
7839 type_t *const orig_type_left = left->base.type;
7840 type_t *const orig_type_inside = inside->base.type;
7842 type_t *const type_left = skip_typeref(orig_type_left);
7843 type_t *const type_inside = skip_typeref(orig_type_inside);
7845 type_t *return_type;
7846 array_access_expression_t *array_access = &expression->array_access;
7847 if (is_type_pointer(type_left)) {
7848 return_type = type_left->pointer.points_to;
7849 array_access->array_ref = left;
7850 array_access->index = inside;
7851 check_for_char_index_type(inside);
7852 } else if (is_type_pointer(type_inside)) {
7853 return_type = type_inside->pointer.points_to;
7854 array_access->array_ref = inside;
7855 array_access->index = left;
7856 array_access->flipped = true;
7857 check_for_char_index_type(left);
7859 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7861 "array access on object with non-pointer types '%T', '%T'",
7862 orig_type_left, orig_type_inside);
7864 return_type = type_error_type;
7865 array_access->array_ref = left;
7866 array_access->index = inside;
7869 expression->base.type = automatic_type_conversion(return_type);
7871 rem_anchor_token(']');
7872 expect(']', end_error);
7877 static expression_t *parse_typeprop(expression_kind_t const kind)
7879 expression_t *tp_expression = allocate_expression_zero(kind);
7880 tp_expression->base.type = type_size_t;
7882 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7884 /* we only refer to a type property, mark this case */
7885 bool old = in_type_prop;
7886 in_type_prop = true;
7889 expression_t *expression;
7890 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7892 add_anchor_token(')');
7893 orig_type = parse_typename();
7894 rem_anchor_token(')');
7895 expect(')', end_error);
7897 if (token.type == '{') {
7898 /* It was not sizeof(type) after all. It is sizeof of an expression
7899 * starting with a compound literal */
7900 expression = parse_compound_literal(orig_type);
7901 goto typeprop_expression;
7904 expression = parse_sub_expression(PREC_UNARY);
7906 typeprop_expression:
7907 tp_expression->typeprop.tp_expression = expression;
7909 orig_type = revert_automatic_type_conversion(expression);
7910 expression->base.type = orig_type;
7913 tp_expression->typeprop.type = orig_type;
7914 type_t const* const type = skip_typeref(orig_type);
7915 char const* const wrong_type =
7916 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7917 is_type_incomplete(type) ? "incomplete" :
7918 type->kind == TYPE_FUNCTION ? "function designator" :
7919 type->kind == TYPE_BITFIELD ? "bitfield" :
7921 if (wrong_type != NULL) {
7922 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7923 errorf(&tp_expression->base.source_position,
7924 "operand of %s expression must not be of %s type '%T'",
7925 what, wrong_type, orig_type);
7930 return tp_expression;
7933 static expression_t *parse_sizeof(void)
7935 return parse_typeprop(EXPR_SIZEOF);
7938 static expression_t *parse_alignof(void)
7940 return parse_typeprop(EXPR_ALIGNOF);
7943 static expression_t *parse_select_expression(expression_t *compound)
7945 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7946 select->select.compound = compound;
7948 assert(token.type == '.' || token.type == T_MINUSGREATER);
7949 bool is_pointer = (token.type == T_MINUSGREATER);
7952 if (token.type != T_IDENTIFIER) {
7953 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7956 symbol_t *symbol = token.v.symbol;
7959 type_t *const orig_type = compound->base.type;
7960 type_t *const type = skip_typeref(orig_type);
7963 bool saw_error = false;
7964 if (is_type_pointer(type)) {
7967 "request for member '%Y' in something not a struct or union, but '%T'",
7971 type_left = skip_typeref(type->pointer.points_to);
7973 if (is_pointer && is_type_valid(type)) {
7974 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7981 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7982 type_left->kind == TYPE_COMPOUND_UNION) {
7983 compound_t *compound = type_left->compound.compound;
7985 if (!compound->complete) {
7986 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7988 goto create_error_entry;
7991 entry = find_compound_entry(compound, symbol);
7992 if (entry == NULL) {
7993 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7994 goto create_error_entry;
7997 if (is_type_valid(type_left) && !saw_error) {
7999 "request for member '%Y' in something not a struct or union, but '%T'",
8003 entry = create_error_entity(symbol, ENTITY_COMPOUND_MEMBER);
8006 assert(is_declaration(entry));
8007 select->select.compound_entry = entry;
8009 type_t *entry_type = entry->declaration.type;
8011 = get_qualified_type(entry_type, type_left->base.qualifiers);
8013 /* we always do the auto-type conversions; the & and sizeof parser contains
8014 * code to revert this! */
8015 select->base.type = automatic_type_conversion(res_type);
8017 type_t *skipped = skip_typeref(res_type);
8018 if (skipped->kind == TYPE_BITFIELD) {
8019 select->base.type = skipped->bitfield.base_type;
8025 static void check_call_argument(const function_parameter_t *parameter,
8026 call_argument_t *argument, unsigned pos)
8028 type_t *expected_type = parameter->type;
8029 type_t *expected_type_skip = skip_typeref(expected_type);
8030 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
8031 expression_t *arg_expr = argument->expression;
8032 type_t *arg_type = skip_typeref(arg_expr->base.type);
8034 /* handle transparent union gnu extension */
8035 if (is_type_union(expected_type_skip)
8036 && (expected_type_skip->base.modifiers
8037 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
8038 compound_t *union_decl = expected_type_skip->compound.compound;
8039 type_t *best_type = NULL;
8040 entity_t *entry = union_decl->members.entities;
8041 for ( ; entry != NULL; entry = entry->base.next) {
8042 assert(is_declaration(entry));
8043 type_t *decl_type = entry->declaration.type;
8044 error = semantic_assign(decl_type, arg_expr);
8045 if (error == ASSIGN_ERROR_INCOMPATIBLE
8046 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
8049 if (error == ASSIGN_SUCCESS) {
8050 best_type = decl_type;
8051 } else if (best_type == NULL) {
8052 best_type = decl_type;
8056 if (best_type != NULL) {
8057 expected_type = best_type;
8061 error = semantic_assign(expected_type, arg_expr);
8062 argument->expression = create_implicit_cast(argument->expression,
8065 if (error != ASSIGN_SUCCESS) {
8066 /* report exact scope in error messages (like "in argument 3") */
8068 snprintf(buf, sizeof(buf), "call argument %u", pos);
8069 report_assign_error(error, expected_type, arg_expr, buf,
8070 &arg_expr->base.source_position);
8071 } else if (warning.traditional || warning.conversion) {
8072 type_t *const promoted_type = get_default_promoted_type(arg_type);
8073 if (!types_compatible(expected_type_skip, promoted_type) &&
8074 !types_compatible(expected_type_skip, type_void_ptr) &&
8075 !types_compatible(type_void_ptr, promoted_type)) {
8076 /* Deliberately show the skipped types in this warning */
8077 warningf(&arg_expr->base.source_position,
8078 "passing call argument %u as '%T' rather than '%T' due to prototype",
8079 pos, expected_type_skip, promoted_type);
8085 * Parse a call expression, ie. expression '( ... )'.
8087 * @param expression the function address
8089 static expression_t *parse_call_expression(expression_t *expression)
8091 expression_t *result = allocate_expression_zero(EXPR_CALL);
8092 call_expression_t *call = &result->call;
8093 call->function = expression;
8095 type_t *const orig_type = expression->base.type;
8096 type_t *const type = skip_typeref(orig_type);
8098 function_type_t *function_type = NULL;
8099 if (is_type_pointer(type)) {
8100 type_t *const to_type = skip_typeref(type->pointer.points_to);
8102 if (is_type_function(to_type)) {
8103 function_type = &to_type->function;
8104 call->base.type = function_type->return_type;
8108 if (function_type == NULL && is_type_valid(type)) {
8109 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
8112 /* parse arguments */
8114 add_anchor_token(')');
8115 add_anchor_token(',');
8117 if (token.type != ')') {
8118 call_argument_t *last_argument = NULL;
8121 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8123 argument->expression = parse_assignment_expression();
8124 if (last_argument == NULL) {
8125 call->arguments = argument;
8127 last_argument->next = argument;
8129 last_argument = argument;
8131 if (token.type != ',')
8136 rem_anchor_token(',');
8137 rem_anchor_token(')');
8138 expect(')', end_error);
8140 if (function_type == NULL)
8143 function_parameter_t *parameter = function_type->parameters;
8144 call_argument_t *argument = call->arguments;
8145 if (!function_type->unspecified_parameters) {
8146 for (unsigned pos = 0; parameter != NULL && argument != NULL;
8147 parameter = parameter->next, argument = argument->next) {
8148 check_call_argument(parameter, argument, ++pos);
8151 if (parameter != NULL) {
8152 errorf(HERE, "too few arguments to function '%E'", expression);
8153 } else if (argument != NULL && !function_type->variadic) {
8154 errorf(HERE, "too many arguments to function '%E'", expression);
8158 /* do default promotion */
8159 for (; argument != NULL; argument = argument->next) {
8160 type_t *type = argument->expression->base.type;
8162 type = get_default_promoted_type(type);
8164 argument->expression
8165 = create_implicit_cast(argument->expression, type);
8168 check_format(&result->call);
8170 if (warning.aggregate_return &&
8171 is_type_compound(skip_typeref(function_type->return_type))) {
8172 warningf(&result->base.source_position,
8173 "function call has aggregate value");
8180 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
8182 static bool same_compound_type(const type_t *type1, const type_t *type2)
8185 is_type_compound(type1) &&
8186 type1->kind == type2->kind &&
8187 type1->compound.compound == type2->compound.compound;
8190 static expression_t const *get_reference_address(expression_t const *expr)
8192 bool regular_take_address = true;
8194 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8195 expr = expr->unary.value;
8197 regular_take_address = false;
8200 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8203 expr = expr->unary.value;
8206 if (expr->kind != EXPR_REFERENCE)
8209 /* special case for functions which are automatically converted to a
8210 * pointer to function without an extra TAKE_ADDRESS operation */
8211 if (!regular_take_address &&
8212 expr->reference.entity->kind != ENTITY_FUNCTION) {
8219 static void warn_reference_address_as_bool(expression_t const* expr)
8221 if (!warning.address)
8224 expr = get_reference_address(expr);
8226 warningf(&expr->base.source_position,
8227 "the address of '%Y' will always evaluate as 'true'",
8228 expr->reference.entity->base.symbol);
8232 static void warn_assignment_in_condition(const expression_t *const expr)
8234 if (!warning.parentheses)
8236 if (expr->base.kind != EXPR_BINARY_ASSIGN)
8238 if (expr->base.parenthesized)
8240 warningf(&expr->base.source_position,
8241 "suggest parentheses around assignment used as truth value");
8244 static void semantic_condition(expression_t const *const expr,
8245 char const *const context)
8247 type_t *const type = skip_typeref(expr->base.type);
8248 if (is_type_scalar(type)) {
8249 warn_reference_address_as_bool(expr);
8250 warn_assignment_in_condition(expr);
8251 } else if (is_type_valid(type)) {
8252 errorf(&expr->base.source_position,
8253 "%s must have scalar type", context);
8258 * Parse a conditional expression, ie. 'expression ? ... : ...'.
8260 * @param expression the conditional expression
8262 static expression_t *parse_conditional_expression(expression_t *expression)
8264 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
8266 conditional_expression_t *conditional = &result->conditional;
8267 conditional->condition = expression;
8270 add_anchor_token(':');
8272 /* §6.5.15:2 The first operand shall have scalar type. */
8273 semantic_condition(expression, "condition of conditional operator");
8275 expression_t *true_expression = expression;
8276 bool gnu_cond = false;
8277 if (GNU_MODE && token.type == ':') {
8280 true_expression = parse_expression();
8282 rem_anchor_token(':');
8283 expect(':', end_error);
8285 expression_t *false_expression =
8286 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
8288 type_t *const orig_true_type = true_expression->base.type;
8289 type_t *const orig_false_type = false_expression->base.type;
8290 type_t *const true_type = skip_typeref(orig_true_type);
8291 type_t *const false_type = skip_typeref(orig_false_type);
8294 type_t *result_type;
8295 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8296 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
8297 /* ISO/IEC 14882:1998(E) §5.16:2 */
8298 if (true_expression->kind == EXPR_UNARY_THROW) {
8299 result_type = false_type;
8300 } else if (false_expression->kind == EXPR_UNARY_THROW) {
8301 result_type = true_type;
8303 if (warning.other && (
8304 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8305 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
8307 warningf(&conditional->base.source_position,
8308 "ISO C forbids conditional expression with only one void side");
8310 result_type = type_void;
8312 } else if (is_type_arithmetic(true_type)
8313 && is_type_arithmetic(false_type)) {
8314 result_type = semantic_arithmetic(true_type, false_type);
8316 true_expression = create_implicit_cast(true_expression, result_type);
8317 false_expression = create_implicit_cast(false_expression, result_type);
8319 conditional->true_expression = true_expression;
8320 conditional->false_expression = false_expression;
8321 conditional->base.type = result_type;
8322 } else if (same_compound_type(true_type, false_type)) {
8323 /* just take 1 of the 2 types */
8324 result_type = true_type;
8325 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
8326 type_t *pointer_type;
8328 expression_t *other_expression;
8329 if (is_type_pointer(true_type) &&
8330 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
8331 pointer_type = true_type;
8332 other_type = false_type;
8333 other_expression = false_expression;
8335 pointer_type = false_type;
8336 other_type = true_type;
8337 other_expression = true_expression;
8340 if (is_null_pointer_constant(other_expression)) {
8341 result_type = pointer_type;
8342 } else if (is_type_pointer(other_type)) {
8343 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8344 type_t *to2 = skip_typeref(other_type->pointer.points_to);
8347 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8348 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8350 } else if (types_compatible(get_unqualified_type(to1),
8351 get_unqualified_type(to2))) {
8354 if (warning.other) {
8355 warningf(&conditional->base.source_position,
8356 "pointer types '%T' and '%T' in conditional expression are incompatible",
8357 true_type, false_type);
8362 type_t *const type =
8363 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8364 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8365 } else if (is_type_integer(other_type)) {
8366 if (warning.other) {
8367 warningf(&conditional->base.source_position,
8368 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8370 result_type = pointer_type;
8372 if (is_type_valid(other_type)) {
8373 type_error_incompatible("while parsing conditional",
8374 &expression->base.source_position, true_type, false_type);
8376 result_type = type_error_type;
8379 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8380 type_error_incompatible("while parsing conditional",
8381 &conditional->base.source_position, true_type,
8384 result_type = type_error_type;
8387 conditional->true_expression
8388 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8389 conditional->false_expression
8390 = create_implicit_cast(false_expression, result_type);
8391 conditional->base.type = result_type;
8396 * Parse an extension expression.
8398 static expression_t *parse_extension(void)
8400 eat(T___extension__);
8402 bool old_gcc_extension = in_gcc_extension;
8403 in_gcc_extension = true;
8404 expression_t *expression = parse_sub_expression(PREC_UNARY);
8405 in_gcc_extension = old_gcc_extension;
8410 * Parse a __builtin_classify_type() expression.
8412 static expression_t *parse_builtin_classify_type(void)
8414 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8415 result->base.type = type_int;
8417 eat(T___builtin_classify_type);
8419 expect('(', end_error);
8420 add_anchor_token(')');
8421 expression_t *expression = parse_expression();
8422 rem_anchor_token(')');
8423 expect(')', end_error);
8424 result->classify_type.type_expression = expression;
8428 return create_invalid_expression();
8432 * Parse a delete expression
8433 * ISO/IEC 14882:1998(E) §5.3.5
8435 static expression_t *parse_delete(void)
8437 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8438 result->base.type = type_void;
8442 if (token.type == '[') {
8444 result->kind = EXPR_UNARY_DELETE_ARRAY;
8445 expect(']', end_error);
8449 expression_t *const value = parse_sub_expression(PREC_CAST);
8450 result->unary.value = value;
8452 type_t *const type = skip_typeref(value->base.type);
8453 if (!is_type_pointer(type)) {
8454 if (is_type_valid(type)) {
8455 errorf(&value->base.source_position,
8456 "operand of delete must have pointer type");
8458 } else if (warning.other &&
8459 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8460 warningf(&value->base.source_position,
8461 "deleting 'void*' is undefined");
8468 * Parse a throw expression
8469 * ISO/IEC 14882:1998(E) §15:1
8471 static expression_t *parse_throw(void)
8473 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8474 result->base.type = type_void;
8478 expression_t *value = NULL;
8479 switch (token.type) {
8481 value = parse_assignment_expression();
8482 /* ISO/IEC 14882:1998(E) §15.1:3 */
8483 type_t *const orig_type = value->base.type;
8484 type_t *const type = skip_typeref(orig_type);
8485 if (is_type_incomplete(type)) {
8486 errorf(&value->base.source_position,
8487 "cannot throw object of incomplete type '%T'", orig_type);
8488 } else if (is_type_pointer(type)) {
8489 type_t *const points_to = skip_typeref(type->pointer.points_to);
8490 if (is_type_incomplete(points_to) &&
8491 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8492 errorf(&value->base.source_position,
8493 "cannot throw pointer to incomplete type '%T'", orig_type);
8501 result->unary.value = value;
8506 static bool check_pointer_arithmetic(const source_position_t *source_position,
8507 type_t *pointer_type,
8508 type_t *orig_pointer_type)
8510 type_t *points_to = pointer_type->pointer.points_to;
8511 points_to = skip_typeref(points_to);
8513 if (is_type_incomplete(points_to)) {
8514 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8515 errorf(source_position,
8516 "arithmetic with pointer to incomplete type '%T' not allowed",
8519 } else if (warning.pointer_arith) {
8520 warningf(source_position,
8521 "pointer of type '%T' used in arithmetic",
8524 } else if (is_type_function(points_to)) {
8526 errorf(source_position,
8527 "arithmetic with pointer to function type '%T' not allowed",
8530 } else if (warning.pointer_arith) {
8531 warningf(source_position,
8532 "pointer to a function '%T' used in arithmetic",
8539 static bool is_lvalue(const expression_t *expression)
8541 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
8542 switch (expression->kind) {
8543 case EXPR_ARRAY_ACCESS:
8544 case EXPR_COMPOUND_LITERAL:
8545 case EXPR_REFERENCE:
8547 case EXPR_UNARY_DEREFERENCE:
8551 type_t *type = skip_typeref(expression->base.type);
8553 /* ISO/IEC 14882:1998(E) §3.10:3 */
8554 is_type_reference(type) ||
8555 /* Claim it is an lvalue, if the type is invalid. There was a parse
8556 * error before, which maybe prevented properly recognizing it as
8558 !is_type_valid(type);
8563 static void semantic_incdec(unary_expression_t *expression)
8565 type_t *const orig_type = expression->value->base.type;
8566 type_t *const type = skip_typeref(orig_type);
8567 if (is_type_pointer(type)) {
8568 if (!check_pointer_arithmetic(&expression->base.source_position,
8572 } else if (!is_type_real(type) && is_type_valid(type)) {
8573 /* TODO: improve error message */
8574 errorf(&expression->base.source_position,
8575 "operation needs an arithmetic or pointer type");
8578 if (!is_lvalue(expression->value)) {
8579 /* TODO: improve error message */
8580 errorf(&expression->base.source_position, "lvalue required as operand");
8582 expression->base.type = orig_type;
8585 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8587 type_t *const orig_type = expression->value->base.type;
8588 type_t *const type = skip_typeref(orig_type);
8589 if (!is_type_arithmetic(type)) {
8590 if (is_type_valid(type)) {
8591 /* TODO: improve error message */
8592 errorf(&expression->base.source_position,
8593 "operation needs an arithmetic type");
8598 expression->base.type = orig_type;
8601 static void semantic_unexpr_plus(unary_expression_t *expression)
8603 semantic_unexpr_arithmetic(expression);
8604 if (warning.traditional)
8605 warningf(&expression->base.source_position,
8606 "traditional C rejects the unary plus operator");
8609 static void semantic_not(unary_expression_t *expression)
8611 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8612 semantic_condition(expression->value, "operand of !");
8613 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8616 static void semantic_unexpr_integer(unary_expression_t *expression)
8618 type_t *const orig_type = expression->value->base.type;
8619 type_t *const type = skip_typeref(orig_type);
8620 if (!is_type_integer(type)) {
8621 if (is_type_valid(type)) {
8622 errorf(&expression->base.source_position,
8623 "operand of ~ must be of integer type");
8628 expression->base.type = orig_type;
8631 static void semantic_dereference(unary_expression_t *expression)
8633 type_t *const orig_type = expression->value->base.type;
8634 type_t *const type = skip_typeref(orig_type);
8635 if (!is_type_pointer(type)) {
8636 if (is_type_valid(type)) {
8637 errorf(&expression->base.source_position,
8638 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8643 type_t *result_type = type->pointer.points_to;
8644 result_type = automatic_type_conversion(result_type);
8645 expression->base.type = result_type;
8649 * Record that an address is taken (expression represents an lvalue).
8651 * @param expression the expression
8652 * @param may_be_register if true, the expression might be an register
8654 static void set_address_taken(expression_t *expression, bool may_be_register)
8656 if (expression->kind != EXPR_REFERENCE)
8659 entity_t *const entity = expression->reference.entity;
8661 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8664 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8665 && !may_be_register) {
8666 errorf(&expression->base.source_position,
8667 "address of register %s '%Y' requested",
8668 get_entity_kind_name(entity->kind), entity->base.symbol);
8671 if (entity->kind == ENTITY_VARIABLE) {
8672 entity->variable.address_taken = true;
8674 assert(entity->kind == ENTITY_PARAMETER);
8675 entity->parameter.address_taken = true;
8680 * Check the semantic of the address taken expression.
8682 static void semantic_take_addr(unary_expression_t *expression)
8684 expression_t *value = expression->value;
8685 value->base.type = revert_automatic_type_conversion(value);
8687 type_t *orig_type = value->base.type;
8688 type_t *type = skip_typeref(orig_type);
8689 if (!is_type_valid(type))
8693 if (!is_lvalue(value)) {
8694 errorf(&expression->base.source_position, "'&' requires an lvalue");
8696 if (type->kind == TYPE_BITFIELD) {
8697 errorf(&expression->base.source_position,
8698 "'&' not allowed on object with bitfield type '%T'",
8702 set_address_taken(value, false);
8704 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8707 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8708 static expression_t *parse_##unexpression_type(void) \
8710 expression_t *unary_expression \
8711 = allocate_expression_zero(unexpression_type); \
8713 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8715 sfunc(&unary_expression->unary); \
8717 return unary_expression; \
8720 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8721 semantic_unexpr_arithmetic)
8722 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8723 semantic_unexpr_plus)
8724 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8726 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8727 semantic_dereference)
8728 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8730 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8731 semantic_unexpr_integer)
8732 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8734 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8737 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8739 static expression_t *parse_##unexpression_type(expression_t *left) \
8741 expression_t *unary_expression \
8742 = allocate_expression_zero(unexpression_type); \
8744 unary_expression->unary.value = left; \
8746 sfunc(&unary_expression->unary); \
8748 return unary_expression; \
8751 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8752 EXPR_UNARY_POSTFIX_INCREMENT,
8754 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8755 EXPR_UNARY_POSTFIX_DECREMENT,
8758 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8760 /* TODO: handle complex + imaginary types */
8762 type_left = get_unqualified_type(type_left);
8763 type_right = get_unqualified_type(type_right);
8765 /* § 6.3.1.8 Usual arithmetic conversions */
8766 if (type_left == type_long_double || type_right == type_long_double) {
8767 return type_long_double;
8768 } else if (type_left == type_double || type_right == type_double) {
8770 } else if (type_left == type_float || type_right == type_float) {
8774 type_left = promote_integer(type_left);
8775 type_right = promote_integer(type_right);
8777 if (type_left == type_right)
8780 bool const signed_left = is_type_signed(type_left);
8781 bool const signed_right = is_type_signed(type_right);
8782 int const rank_left = get_rank(type_left);
8783 int const rank_right = get_rank(type_right);
8785 if (signed_left == signed_right)
8786 return rank_left >= rank_right ? type_left : type_right;
8795 u_rank = rank_right;
8796 u_type = type_right;
8798 s_rank = rank_right;
8799 s_type = type_right;
8804 if (u_rank >= s_rank)
8807 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8809 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8810 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8814 case ATOMIC_TYPE_INT: return type_unsigned_int;
8815 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8816 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8818 default: panic("invalid atomic type");
8823 * Check the semantic restrictions for a binary expression.
8825 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8827 expression_t *const left = expression->left;
8828 expression_t *const right = expression->right;
8829 type_t *const orig_type_left = left->base.type;
8830 type_t *const orig_type_right = right->base.type;
8831 type_t *const type_left = skip_typeref(orig_type_left);
8832 type_t *const type_right = skip_typeref(orig_type_right);
8834 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8835 /* TODO: improve error message */
8836 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8837 errorf(&expression->base.source_position,
8838 "operation needs arithmetic types");
8843 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8844 expression->left = create_implicit_cast(left, arithmetic_type);
8845 expression->right = create_implicit_cast(right, arithmetic_type);
8846 expression->base.type = arithmetic_type;
8849 static void warn_div_by_zero(binary_expression_t const *const expression)
8851 if (!warning.div_by_zero ||
8852 !is_type_integer(expression->base.type))
8855 expression_t const *const right = expression->right;
8856 /* The type of the right operand can be different for /= */
8857 if (is_type_integer(right->base.type) &&
8858 is_constant_expression(right) &&
8859 fold_constant(right) == 0) {
8860 warningf(&expression->base.source_position, "division by zero");
8865 * Check the semantic restrictions for a div/mod expression.
8867 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8868 semantic_binexpr_arithmetic(expression);
8869 warn_div_by_zero(expression);
8872 static void warn_addsub_in_shift(const expression_t *const expr)
8874 if (expr->base.parenthesized)
8878 switch (expr->kind) {
8879 case EXPR_BINARY_ADD: op = '+'; break;
8880 case EXPR_BINARY_SUB: op = '-'; break;
8884 warningf(&expr->base.source_position,
8885 "suggest parentheses around '%c' inside shift", op);
8888 static void semantic_shift_op(binary_expression_t *expression)
8890 expression_t *const left = expression->left;
8891 expression_t *const right = expression->right;
8892 type_t *const orig_type_left = left->base.type;
8893 type_t *const orig_type_right = right->base.type;
8894 type_t * type_left = skip_typeref(orig_type_left);
8895 type_t * type_right = skip_typeref(orig_type_right);
8897 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8898 /* TODO: improve error message */
8899 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8900 errorf(&expression->base.source_position,
8901 "operands of shift operation must have integer types");
8906 if (warning.parentheses) {
8907 warn_addsub_in_shift(left);
8908 warn_addsub_in_shift(right);
8911 type_left = promote_integer(type_left);
8912 type_right = promote_integer(type_right);
8914 expression->left = create_implicit_cast(left, type_left);
8915 expression->right = create_implicit_cast(right, type_right);
8916 expression->base.type = type_left;
8919 static void semantic_add(binary_expression_t *expression)
8921 expression_t *const left = expression->left;
8922 expression_t *const right = expression->right;
8923 type_t *const orig_type_left = left->base.type;
8924 type_t *const orig_type_right = right->base.type;
8925 type_t *const type_left = skip_typeref(orig_type_left);
8926 type_t *const type_right = skip_typeref(orig_type_right);
8929 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8930 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8931 expression->left = create_implicit_cast(left, arithmetic_type);
8932 expression->right = create_implicit_cast(right, arithmetic_type);
8933 expression->base.type = arithmetic_type;
8934 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8935 check_pointer_arithmetic(&expression->base.source_position,
8936 type_left, orig_type_left);
8937 expression->base.type = type_left;
8938 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8939 check_pointer_arithmetic(&expression->base.source_position,
8940 type_right, orig_type_right);
8941 expression->base.type = type_right;
8942 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8943 errorf(&expression->base.source_position,
8944 "invalid operands to binary + ('%T', '%T')",
8945 orig_type_left, orig_type_right);
8949 static void semantic_sub(binary_expression_t *expression)
8951 expression_t *const left = expression->left;
8952 expression_t *const right = expression->right;
8953 type_t *const orig_type_left = left->base.type;
8954 type_t *const orig_type_right = right->base.type;
8955 type_t *const type_left = skip_typeref(orig_type_left);
8956 type_t *const type_right = skip_typeref(orig_type_right);
8957 source_position_t const *const pos = &expression->base.source_position;
8960 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8961 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8962 expression->left = create_implicit_cast(left, arithmetic_type);
8963 expression->right = create_implicit_cast(right, arithmetic_type);
8964 expression->base.type = arithmetic_type;
8965 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8966 check_pointer_arithmetic(&expression->base.source_position,
8967 type_left, orig_type_left);
8968 expression->base.type = type_left;
8969 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8970 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8971 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8972 if (!types_compatible(unqual_left, unqual_right)) {
8974 "subtracting pointers to incompatible types '%T' and '%T'",
8975 orig_type_left, orig_type_right);
8976 } else if (!is_type_object(unqual_left)) {
8977 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8978 errorf(pos, "subtracting pointers to non-object types '%T'",
8980 } else if (warning.other) {
8981 warningf(pos, "subtracting pointers to void");
8984 expression->base.type = type_ptrdiff_t;
8985 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8986 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8987 orig_type_left, orig_type_right);
8991 static void warn_string_literal_address(expression_t const* expr)
8993 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8994 expr = expr->unary.value;
8995 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8997 expr = expr->unary.value;
9000 if (expr->kind == EXPR_STRING_LITERAL ||
9001 expr->kind == EXPR_WIDE_STRING_LITERAL) {
9002 warningf(&expr->base.source_position,
9003 "comparison with string literal results in unspecified behaviour");
9007 static void warn_comparison_in_comparison(const expression_t *const expr)
9009 if (expr->base.parenthesized)
9011 switch (expr->base.kind) {
9012 case EXPR_BINARY_LESS:
9013 case EXPR_BINARY_GREATER:
9014 case EXPR_BINARY_LESSEQUAL:
9015 case EXPR_BINARY_GREATEREQUAL:
9016 case EXPR_BINARY_NOTEQUAL:
9017 case EXPR_BINARY_EQUAL:
9018 warningf(&expr->base.source_position,
9019 "comparisons like 'x <= y < z' do not have their mathematical meaning");
9026 static bool maybe_negative(expression_t const *const expr)
9029 !is_constant_expression(expr) ||
9030 fold_constant(expr) < 0;
9034 * Check the semantics of comparison expressions.
9036 * @param expression The expression to check.
9038 static void semantic_comparison(binary_expression_t *expression)
9040 expression_t *left = expression->left;
9041 expression_t *right = expression->right;
9043 if (warning.address) {
9044 warn_string_literal_address(left);
9045 warn_string_literal_address(right);
9047 expression_t const* const func_left = get_reference_address(left);
9048 if (func_left != NULL && is_null_pointer_constant(right)) {
9049 warningf(&expression->base.source_position,
9050 "the address of '%Y' will never be NULL",
9051 func_left->reference.entity->base.symbol);
9054 expression_t const* const func_right = get_reference_address(right);
9055 if (func_right != NULL && is_null_pointer_constant(right)) {
9056 warningf(&expression->base.source_position,
9057 "the address of '%Y' will never be NULL",
9058 func_right->reference.entity->base.symbol);
9062 if (warning.parentheses) {
9063 warn_comparison_in_comparison(left);
9064 warn_comparison_in_comparison(right);
9067 type_t *orig_type_left = left->base.type;
9068 type_t *orig_type_right = right->base.type;
9069 type_t *type_left = skip_typeref(orig_type_left);
9070 type_t *type_right = skip_typeref(orig_type_right);
9072 /* TODO non-arithmetic types */
9073 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9074 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9076 /* test for signed vs unsigned compares */
9077 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
9078 bool const signed_left = is_type_signed(type_left);
9079 bool const signed_right = is_type_signed(type_right);
9080 if (signed_left != signed_right) {
9081 /* FIXME long long needs better const folding magic */
9082 /* TODO check whether constant value can be represented by other type */
9083 if ((signed_left && maybe_negative(left)) ||
9084 (signed_right && maybe_negative(right))) {
9085 warningf(&expression->base.source_position,
9086 "comparison between signed and unsigned");
9091 expression->left = create_implicit_cast(left, arithmetic_type);
9092 expression->right = create_implicit_cast(right, arithmetic_type);
9093 expression->base.type = arithmetic_type;
9094 if (warning.float_equal &&
9095 (expression->base.kind == EXPR_BINARY_EQUAL ||
9096 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
9097 is_type_float(arithmetic_type)) {
9098 warningf(&expression->base.source_position,
9099 "comparing floating point with == or != is unsafe");
9101 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
9102 /* TODO check compatibility */
9103 } else if (is_type_pointer(type_left)) {
9104 expression->right = create_implicit_cast(right, type_left);
9105 } else if (is_type_pointer(type_right)) {
9106 expression->left = create_implicit_cast(left, type_right);
9107 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9108 type_error_incompatible("invalid operands in comparison",
9109 &expression->base.source_position,
9110 type_left, type_right);
9112 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9116 * Checks if a compound type has constant fields.
9118 static bool has_const_fields(const compound_type_t *type)
9120 compound_t *compound = type->compound;
9121 entity_t *entry = compound->members.entities;
9123 for (; entry != NULL; entry = entry->base.next) {
9124 if (!is_declaration(entry))
9127 const type_t *decl_type = skip_typeref(entry->declaration.type);
9128 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
9135 static bool is_valid_assignment_lhs(expression_t const* const left)
9137 type_t *const orig_type_left = revert_automatic_type_conversion(left);
9138 type_t *const type_left = skip_typeref(orig_type_left);
9140 if (!is_lvalue(left)) {
9141 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
9146 if (left->kind == EXPR_REFERENCE
9147 && left->reference.entity->kind == ENTITY_FUNCTION) {
9148 errorf(HERE, "cannot assign to function '%E'", left);
9152 if (is_type_array(type_left)) {
9153 errorf(HERE, "cannot assign to array '%E'", left);
9156 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
9157 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
9161 if (is_type_incomplete(type_left)) {
9162 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
9163 left, orig_type_left);
9166 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
9167 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
9168 left, orig_type_left);
9175 static void semantic_arithmetic_assign(binary_expression_t *expression)
9177 expression_t *left = expression->left;
9178 expression_t *right = expression->right;
9179 type_t *orig_type_left = left->base.type;
9180 type_t *orig_type_right = right->base.type;
9182 if (!is_valid_assignment_lhs(left))
9185 type_t *type_left = skip_typeref(orig_type_left);
9186 type_t *type_right = skip_typeref(orig_type_right);
9188 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
9189 /* TODO: improve error message */
9190 if (is_type_valid(type_left) && is_type_valid(type_right)) {
9191 errorf(&expression->base.source_position,
9192 "operation needs arithmetic types");
9197 /* combined instructions are tricky. We can't create an implicit cast on
9198 * the left side, because we need the uncasted form for the store.
9199 * The ast2firm pass has to know that left_type must be right_type
9200 * for the arithmetic operation and create a cast by itself */
9201 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9202 expression->right = create_implicit_cast(right, arithmetic_type);
9203 expression->base.type = type_left;
9206 static void semantic_divmod_assign(binary_expression_t *expression)
9208 semantic_arithmetic_assign(expression);
9209 warn_div_by_zero(expression);
9212 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
9214 expression_t *const left = expression->left;
9215 expression_t *const right = expression->right;
9216 type_t *const orig_type_left = left->base.type;
9217 type_t *const orig_type_right = right->base.type;
9218 type_t *const type_left = skip_typeref(orig_type_left);
9219 type_t *const type_right = skip_typeref(orig_type_right);
9221 if (!is_valid_assignment_lhs(left))
9224 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9225 /* combined instructions are tricky. We can't create an implicit cast on
9226 * the left side, because we need the uncasted form for the store.
9227 * The ast2firm pass has to know that left_type must be right_type
9228 * for the arithmetic operation and create a cast by itself */
9229 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
9230 expression->right = create_implicit_cast(right, arithmetic_type);
9231 expression->base.type = type_left;
9232 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9233 check_pointer_arithmetic(&expression->base.source_position,
9234 type_left, orig_type_left);
9235 expression->base.type = type_left;
9236 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9237 errorf(&expression->base.source_position,
9238 "incompatible types '%T' and '%T' in assignment",
9239 orig_type_left, orig_type_right);
9243 static void warn_logical_and_within_or(const expression_t *const expr)
9245 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
9247 if (expr->base.parenthesized)
9249 warningf(&expr->base.source_position,
9250 "suggest parentheses around && within ||");
9254 * Check the semantic restrictions of a logical expression.
9256 static void semantic_logical_op(binary_expression_t *expression)
9258 /* §6.5.13:2 Each of the operands shall have scalar type.
9259 * §6.5.14:2 Each of the operands shall have scalar type. */
9260 semantic_condition(expression->left, "left operand of logical operator");
9261 semantic_condition(expression->right, "right operand of logical operator");
9262 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
9263 warning.parentheses) {
9264 warn_logical_and_within_or(expression->left);
9265 warn_logical_and_within_or(expression->right);
9267 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9271 * Check the semantic restrictions of a binary assign expression.
9273 static void semantic_binexpr_assign(binary_expression_t *expression)
9275 expression_t *left = expression->left;
9276 type_t *orig_type_left = left->base.type;
9278 if (!is_valid_assignment_lhs(left))
9281 assign_error_t error = semantic_assign(orig_type_left, expression->right);
9282 report_assign_error(error, orig_type_left, expression->right,
9283 "assignment", &left->base.source_position);
9284 expression->right = create_implicit_cast(expression->right, orig_type_left);
9285 expression->base.type = orig_type_left;
9289 * Determine if the outermost operation (or parts thereof) of the given
9290 * expression has no effect in order to generate a warning about this fact.
9291 * Therefore in some cases this only examines some of the operands of the
9292 * expression (see comments in the function and examples below).
9294 * f() + 23; // warning, because + has no effect
9295 * x || f(); // no warning, because x controls execution of f()
9296 * x ? y : f(); // warning, because y has no effect
9297 * (void)x; // no warning to be able to suppress the warning
9298 * This function can NOT be used for an "expression has definitely no effect"-
9300 static bool expression_has_effect(const expression_t *const expr)
9302 switch (expr->kind) {
9303 case EXPR_UNKNOWN: break;
9304 case EXPR_INVALID: return true; /* do NOT warn */
9305 case EXPR_REFERENCE: return false;
9306 case EXPR_REFERENCE_ENUM_VALUE: return false;
9307 /* suppress the warning for microsoft __noop operations */
9308 case EXPR_CONST: return expr->conste.is_ms_noop;
9309 case EXPR_CHARACTER_CONSTANT: return false;
9310 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
9311 case EXPR_STRING_LITERAL: return false;
9312 case EXPR_WIDE_STRING_LITERAL: return false;
9313 case EXPR_LABEL_ADDRESS: return false;
9316 const call_expression_t *const call = &expr->call;
9317 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
9320 switch (call->function->builtin_symbol.symbol->ID) {
9321 case T___builtin_va_end: return true;
9322 default: return false;
9326 /* Generate the warning if either the left or right hand side of a
9327 * conditional expression has no effect */
9328 case EXPR_CONDITIONAL: {
9329 const conditional_expression_t *const cond = &expr->conditional;
9331 expression_has_effect(cond->true_expression) &&
9332 expression_has_effect(cond->false_expression);
9335 case EXPR_SELECT: return false;
9336 case EXPR_ARRAY_ACCESS: return false;
9337 case EXPR_SIZEOF: return false;
9338 case EXPR_CLASSIFY_TYPE: return false;
9339 case EXPR_ALIGNOF: return false;
9341 case EXPR_FUNCNAME: return false;
9342 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
9343 case EXPR_BUILTIN_CONSTANT_P: return false;
9344 case EXPR_BUILTIN_PREFETCH: return true;
9345 case EXPR_OFFSETOF: return false;
9346 case EXPR_VA_START: return true;
9347 case EXPR_VA_ARG: return true;
9348 case EXPR_STATEMENT: return true; // TODO
9349 case EXPR_COMPOUND_LITERAL: return false;
9351 case EXPR_UNARY_NEGATE: return false;
9352 case EXPR_UNARY_PLUS: return false;
9353 case EXPR_UNARY_BITWISE_NEGATE: return false;
9354 case EXPR_UNARY_NOT: return false;
9355 case EXPR_UNARY_DEREFERENCE: return false;
9356 case EXPR_UNARY_TAKE_ADDRESS: return false;
9357 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
9358 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
9359 case EXPR_UNARY_PREFIX_INCREMENT: return true;
9360 case EXPR_UNARY_PREFIX_DECREMENT: return true;
9362 /* Treat void casts as if they have an effect in order to being able to
9363 * suppress the warning */
9364 case EXPR_UNARY_CAST: {
9365 type_t *const type = skip_typeref(expr->base.type);
9366 return is_type_atomic(type, ATOMIC_TYPE_VOID);
9369 case EXPR_UNARY_CAST_IMPLICIT: return true;
9370 case EXPR_UNARY_ASSUME: return true;
9371 case EXPR_UNARY_DELETE: return true;
9372 case EXPR_UNARY_DELETE_ARRAY: return true;
9373 case EXPR_UNARY_THROW: return true;
9375 case EXPR_BINARY_ADD: return false;
9376 case EXPR_BINARY_SUB: return false;
9377 case EXPR_BINARY_MUL: return false;
9378 case EXPR_BINARY_DIV: return false;
9379 case EXPR_BINARY_MOD: return false;
9380 case EXPR_BINARY_EQUAL: return false;
9381 case EXPR_BINARY_NOTEQUAL: return false;
9382 case EXPR_BINARY_LESS: return false;
9383 case EXPR_BINARY_LESSEQUAL: return false;
9384 case EXPR_BINARY_GREATER: return false;
9385 case EXPR_BINARY_GREATEREQUAL: return false;
9386 case EXPR_BINARY_BITWISE_AND: return false;
9387 case EXPR_BINARY_BITWISE_OR: return false;
9388 case EXPR_BINARY_BITWISE_XOR: return false;
9389 case EXPR_BINARY_SHIFTLEFT: return false;
9390 case EXPR_BINARY_SHIFTRIGHT: return false;
9391 case EXPR_BINARY_ASSIGN: return true;
9392 case EXPR_BINARY_MUL_ASSIGN: return true;
9393 case EXPR_BINARY_DIV_ASSIGN: return true;
9394 case EXPR_BINARY_MOD_ASSIGN: return true;
9395 case EXPR_BINARY_ADD_ASSIGN: return true;
9396 case EXPR_BINARY_SUB_ASSIGN: return true;
9397 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
9398 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
9399 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9400 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9401 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
9403 /* Only examine the right hand side of && and ||, because the left hand
9404 * side already has the effect of controlling the execution of the right
9406 case EXPR_BINARY_LOGICAL_AND:
9407 case EXPR_BINARY_LOGICAL_OR:
9408 /* Only examine the right hand side of a comma expression, because the left
9409 * hand side has a separate warning */
9410 case EXPR_BINARY_COMMA:
9411 return expression_has_effect(expr->binary.right);
9413 case EXPR_BINARY_ISGREATER: return false;
9414 case EXPR_BINARY_ISGREATEREQUAL: return false;
9415 case EXPR_BINARY_ISLESS: return false;
9416 case EXPR_BINARY_ISLESSEQUAL: return false;
9417 case EXPR_BINARY_ISLESSGREATER: return false;
9418 case EXPR_BINARY_ISUNORDERED: return false;
9421 internal_errorf(HERE, "unexpected expression");
9424 static void semantic_comma(binary_expression_t *expression)
9426 if (warning.unused_value) {
9427 const expression_t *const left = expression->left;
9428 if (!expression_has_effect(left)) {
9429 warningf(&left->base.source_position,
9430 "left-hand operand of comma expression has no effect");
9433 expression->base.type = expression->right->base.type;
9437 * @param prec_r precedence of the right operand
9439 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9440 static expression_t *parse_##binexpression_type(expression_t *left) \
9442 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9443 binexpr->binary.left = left; \
9446 expression_t *right = parse_sub_expression(prec_r); \
9448 binexpr->binary.right = right; \
9449 sfunc(&binexpr->binary); \
9454 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9455 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9456 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9457 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9458 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9459 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9460 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9461 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9462 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9463 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9464 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9465 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9466 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9467 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9468 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9469 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9470 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9471 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9472 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9473 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9474 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9475 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9476 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9477 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9478 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9479 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9480 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9481 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9482 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9483 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9486 static expression_t *parse_sub_expression(precedence_t precedence)
9488 if (token.type < 0) {
9489 return expected_expression_error();
9492 expression_parser_function_t *parser
9493 = &expression_parsers[token.type];
9494 source_position_t source_position = token.source_position;
9497 if (parser->parser != NULL) {
9498 left = parser->parser();
9500 left = parse_primary_expression();
9502 assert(left != NULL);
9503 left->base.source_position = source_position;
9506 if (token.type < 0) {
9507 return expected_expression_error();
9510 parser = &expression_parsers[token.type];
9511 if (parser->infix_parser == NULL)
9513 if (parser->infix_precedence < precedence)
9516 left = parser->infix_parser(left);
9518 assert(left != NULL);
9519 assert(left->kind != EXPR_UNKNOWN);
9520 left->base.source_position = source_position;
9527 * Parse an expression.
9529 static expression_t *parse_expression(void)
9531 return parse_sub_expression(PREC_EXPRESSION);
9535 * Register a parser for a prefix-like operator.
9537 * @param parser the parser function
9538 * @param token_type the token type of the prefix token
9540 static void register_expression_parser(parse_expression_function parser,
9543 expression_parser_function_t *entry = &expression_parsers[token_type];
9545 if (entry->parser != NULL) {
9546 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9547 panic("trying to register multiple expression parsers for a token");
9549 entry->parser = parser;
9553 * Register a parser for an infix operator with given precedence.
9555 * @param parser the parser function
9556 * @param token_type the token type of the infix operator
9557 * @param precedence the precedence of the operator
9559 static void register_infix_parser(parse_expression_infix_function parser,
9560 int token_type, precedence_t precedence)
9562 expression_parser_function_t *entry = &expression_parsers[token_type];
9564 if (entry->infix_parser != NULL) {
9565 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9566 panic("trying to register multiple infix expression parsers for a "
9569 entry->infix_parser = parser;
9570 entry->infix_precedence = precedence;
9574 * Initialize the expression parsers.
9576 static void init_expression_parsers(void)
9578 memset(&expression_parsers, 0, sizeof(expression_parsers));
9580 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9581 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9582 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9583 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9584 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9585 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9586 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9587 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9588 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9589 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9590 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9591 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9592 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9593 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9594 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9595 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9596 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9597 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9598 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9599 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9600 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9601 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9602 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9603 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9604 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9605 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9606 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9607 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9608 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9609 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9610 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9611 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9612 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9613 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9614 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9615 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9616 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9618 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9619 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9620 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9621 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9622 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9623 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9624 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9625 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9626 register_expression_parser(parse_sizeof, T_sizeof);
9627 register_expression_parser(parse_alignof, T___alignof__);
9628 register_expression_parser(parse_extension, T___extension__);
9629 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9630 register_expression_parser(parse_delete, T_delete);
9631 register_expression_parser(parse_throw, T_throw);
9635 * Parse a asm statement arguments specification.
9637 static asm_argument_t *parse_asm_arguments(bool is_out)
9639 asm_argument_t *result = NULL;
9640 asm_argument_t **anchor = &result;
9642 while (token.type == T_STRING_LITERAL || token.type == '[') {
9643 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9644 memset(argument, 0, sizeof(argument[0]));
9646 if (token.type == '[') {
9648 if (token.type != T_IDENTIFIER) {
9649 parse_error_expected("while parsing asm argument",
9650 T_IDENTIFIER, NULL);
9653 argument->symbol = token.v.symbol;
9655 expect(']', end_error);
9658 argument->constraints = parse_string_literals();
9659 expect('(', end_error);
9660 add_anchor_token(')');
9661 expression_t *expression = parse_expression();
9662 rem_anchor_token(')');
9664 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9665 * change size or type representation (e.g. int -> long is ok, but
9666 * int -> float is not) */
9667 if (expression->kind == EXPR_UNARY_CAST) {
9668 type_t *const type = expression->base.type;
9669 type_kind_t const kind = type->kind;
9670 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9673 if (kind == TYPE_ATOMIC) {
9674 atomic_type_kind_t const akind = type->atomic.akind;
9675 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9676 size = get_atomic_type_size(akind);
9678 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9679 size = get_atomic_type_size(get_intptr_kind());
9683 expression_t *const value = expression->unary.value;
9684 type_t *const value_type = value->base.type;
9685 type_kind_t const value_kind = value_type->kind;
9687 unsigned value_flags;
9688 unsigned value_size;
9689 if (value_kind == TYPE_ATOMIC) {
9690 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9691 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9692 value_size = get_atomic_type_size(value_akind);
9693 } else if (value_kind == TYPE_POINTER) {
9694 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9695 value_size = get_atomic_type_size(get_intptr_kind());
9700 if (value_flags != flags || value_size != size)
9704 } while (expression->kind == EXPR_UNARY_CAST);
9708 if (!is_lvalue(expression)) {
9709 errorf(&expression->base.source_position,
9710 "asm output argument is not an lvalue");
9713 if (argument->constraints.begin[0] == '+')
9714 mark_vars_read(expression, NULL);
9716 mark_vars_read(expression, NULL);
9718 argument->expression = expression;
9719 expect(')', end_error);
9721 set_address_taken(expression, true);
9724 anchor = &argument->next;
9726 if (token.type != ',')
9737 * Parse a asm statement clobber specification.
9739 static asm_clobber_t *parse_asm_clobbers(void)
9741 asm_clobber_t *result = NULL;
9742 asm_clobber_t *last = NULL;
9744 while (token.type == T_STRING_LITERAL) {
9745 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9746 clobber->clobber = parse_string_literals();
9749 last->next = clobber;
9755 if (token.type != ',')
9764 * Parse an asm statement.
9766 static statement_t *parse_asm_statement(void)
9768 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9769 asm_statement_t *asm_statement = &statement->asms;
9773 if (token.type == T_volatile) {
9775 asm_statement->is_volatile = true;
9778 expect('(', end_error);
9779 add_anchor_token(')');
9780 add_anchor_token(':');
9781 asm_statement->asm_text = parse_string_literals();
9783 if (token.type != ':') {
9784 rem_anchor_token(':');
9789 asm_statement->outputs = parse_asm_arguments(true);
9790 if (token.type != ':') {
9791 rem_anchor_token(':');
9796 asm_statement->inputs = parse_asm_arguments(false);
9797 if (token.type != ':') {
9798 rem_anchor_token(':');
9801 rem_anchor_token(':');
9804 asm_statement->clobbers = parse_asm_clobbers();
9807 rem_anchor_token(')');
9808 expect(')', end_error);
9809 expect(';', end_error);
9811 if (asm_statement->outputs == NULL) {
9812 /* GCC: An 'asm' instruction without any output operands will be treated
9813 * identically to a volatile 'asm' instruction. */
9814 asm_statement->is_volatile = true;
9819 return create_invalid_statement();
9823 * Parse a case statement.
9825 static statement_t *parse_case_statement(void)
9827 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9828 source_position_t *const pos = &statement->base.source_position;
9832 expression_t *const expression = parse_expression();
9833 statement->case_label.expression = expression;
9834 if (!is_constant_expression(expression)) {
9835 /* This check does not prevent the error message in all cases of an
9836 * prior error while parsing the expression. At least it catches the
9837 * common case of a mistyped enum entry. */
9838 if (is_type_valid(skip_typeref(expression->base.type))) {
9839 errorf(pos, "case label does not reduce to an integer constant");
9841 statement->case_label.is_bad = true;
9843 long const val = fold_constant(expression);
9844 statement->case_label.first_case = val;
9845 statement->case_label.last_case = val;
9849 if (token.type == T_DOTDOTDOT) {
9851 expression_t *const end_range = parse_expression();
9852 statement->case_label.end_range = end_range;
9853 if (!is_constant_expression(end_range)) {
9854 /* This check does not prevent the error message in all cases of an
9855 * prior error while parsing the expression. At least it catches the
9856 * common case of a mistyped enum entry. */
9857 if (is_type_valid(skip_typeref(end_range->base.type))) {
9858 errorf(pos, "case range does not reduce to an integer constant");
9860 statement->case_label.is_bad = true;
9862 long const val = fold_constant(end_range);
9863 statement->case_label.last_case = val;
9865 if (warning.other && val < statement->case_label.first_case) {
9866 statement->case_label.is_empty_range = true;
9867 warningf(pos, "empty range specified");
9873 PUSH_PARENT(statement);
9875 expect(':', end_error);
9878 if (current_switch != NULL) {
9879 if (! statement->case_label.is_bad) {
9880 /* Check for duplicate case values */
9881 case_label_statement_t *c = &statement->case_label;
9882 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9883 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9886 if (c->last_case < l->first_case || c->first_case > l->last_case)
9889 errorf(pos, "duplicate case value (previously used %P)",
9890 &l->base.source_position);
9894 /* link all cases into the switch statement */
9895 if (current_switch->last_case == NULL) {
9896 current_switch->first_case = &statement->case_label;
9898 current_switch->last_case->next = &statement->case_label;
9900 current_switch->last_case = &statement->case_label;
9902 errorf(pos, "case label not within a switch statement");
9905 statement_t *const inner_stmt = parse_statement();
9906 statement->case_label.statement = inner_stmt;
9907 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9908 errorf(&inner_stmt->base.source_position, "declaration after case label");
9916 * Parse a default statement.
9918 static statement_t *parse_default_statement(void)
9920 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9924 PUSH_PARENT(statement);
9926 expect(':', end_error);
9927 if (current_switch != NULL) {
9928 const case_label_statement_t *def_label = current_switch->default_label;
9929 if (def_label != NULL) {
9930 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9931 &def_label->base.source_position);
9933 current_switch->default_label = &statement->case_label;
9935 /* link all cases into the switch statement */
9936 if (current_switch->last_case == NULL) {
9937 current_switch->first_case = &statement->case_label;
9939 current_switch->last_case->next = &statement->case_label;
9941 current_switch->last_case = &statement->case_label;
9944 errorf(&statement->base.source_position,
9945 "'default' label not within a switch statement");
9948 statement_t *const inner_stmt = parse_statement();
9949 statement->case_label.statement = inner_stmt;
9950 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9951 errorf(&inner_stmt->base.source_position, "declaration after default label");
9958 return create_invalid_statement();
9962 * Parse a label statement.
9964 static statement_t *parse_label_statement(void)
9966 assert(token.type == T_IDENTIFIER);
9967 symbol_t *symbol = token.v.symbol;
9968 label_t *label = get_label(symbol);
9970 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9971 statement->label.label = label;
9975 PUSH_PARENT(statement);
9977 /* if statement is already set then the label is defined twice,
9978 * otherwise it was just mentioned in a goto/local label declaration so far
9980 if (label->statement != NULL) {
9981 errorf(HERE, "duplicate label '%Y' (declared %P)",
9982 symbol, &label->base.source_position);
9984 label->base.source_position = token.source_position;
9985 label->statement = statement;
9990 if (token.type == '}') {
9991 /* TODO only warn? */
9992 if (warning.other && false) {
9993 warningf(HERE, "label at end of compound statement");
9994 statement->label.statement = create_empty_statement();
9996 errorf(HERE, "label at end of compound statement");
9997 statement->label.statement = create_invalid_statement();
9999 } else if (token.type == ';') {
10000 /* Eat an empty statement here, to avoid the warning about an empty
10001 * statement after a label. label:; is commonly used to have a label
10002 * before a closing brace. */
10003 statement->label.statement = create_empty_statement();
10006 statement_t *const inner_stmt = parse_statement();
10007 statement->label.statement = inner_stmt;
10008 if (inner_stmt->kind == STATEMENT_DECLARATION) {
10009 errorf(&inner_stmt->base.source_position, "declaration after label");
10013 /* remember the labels in a list for later checking */
10014 *label_anchor = &statement->label;
10015 label_anchor = &statement->label.next;
10022 * Parse an if statement.
10024 static statement_t *parse_if(void)
10026 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
10030 PUSH_PARENT(statement);
10032 add_anchor_token('{');
10034 expect('(', end_error);
10035 add_anchor_token(')');
10036 expression_t *const expr = parse_expression();
10037 statement->ifs.condition = expr;
10038 /* §6.8.4.1:1 The controlling expression of an if statement shall have
10040 semantic_condition(expr, "condition of 'if'-statment");
10041 mark_vars_read(expr, NULL);
10042 rem_anchor_token(')');
10043 expect(')', end_error);
10046 rem_anchor_token('{');
10048 add_anchor_token(T_else);
10049 statement_t *const true_stmt = parse_statement();
10050 statement->ifs.true_statement = true_stmt;
10051 rem_anchor_token(T_else);
10053 if (token.type == T_else) {
10055 statement->ifs.false_statement = parse_statement();
10056 } else if (warning.parentheses &&
10057 true_stmt->kind == STATEMENT_IF &&
10058 true_stmt->ifs.false_statement != NULL) {
10059 warningf(&true_stmt->base.source_position,
10060 "suggest explicit braces to avoid ambiguous 'else'");
10068 * Check that all enums are handled in a switch.
10070 * @param statement the switch statement to check
10072 static void check_enum_cases(const switch_statement_t *statement) {
10073 const type_t *type = skip_typeref(statement->expression->base.type);
10074 if (! is_type_enum(type))
10076 const enum_type_t *enumt = &type->enumt;
10078 /* if we have a default, no warnings */
10079 if (statement->default_label != NULL)
10082 /* FIXME: calculation of value should be done while parsing */
10083 /* TODO: quadratic algorithm here. Change to an n log n one */
10084 long last_value = -1;
10085 const entity_t *entry = enumt->enume->base.next;
10086 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
10087 entry = entry->base.next) {
10088 const expression_t *expression = entry->enum_value.value;
10089 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
10090 bool found = false;
10091 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
10092 if (l->expression == NULL)
10094 if (l->first_case <= value && value <= l->last_case) {
10100 warningf(&statement->base.source_position,
10101 "enumeration value '%Y' not handled in switch",
10102 entry->base.symbol);
10104 last_value = value;
10109 * Parse a switch statement.
10111 static statement_t *parse_switch(void)
10113 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
10117 PUSH_PARENT(statement);
10119 expect('(', end_error);
10120 add_anchor_token(')');
10121 expression_t *const expr = parse_expression();
10122 mark_vars_read(expr, NULL);
10123 type_t * type = skip_typeref(expr->base.type);
10124 if (is_type_integer(type)) {
10125 type = promote_integer(type);
10126 if (warning.traditional) {
10127 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
10128 warningf(&expr->base.source_position,
10129 "'%T' switch expression not converted to '%T' in ISO C",
10133 } else if (is_type_valid(type)) {
10134 errorf(&expr->base.source_position,
10135 "switch quantity is not an integer, but '%T'", type);
10136 type = type_error_type;
10138 statement->switchs.expression = create_implicit_cast(expr, type);
10139 expect(')', end_error);
10140 rem_anchor_token(')');
10142 switch_statement_t *rem = current_switch;
10143 current_switch = &statement->switchs;
10144 statement->switchs.body = parse_statement();
10145 current_switch = rem;
10147 if (warning.switch_default &&
10148 statement->switchs.default_label == NULL) {
10149 warningf(&statement->base.source_position, "switch has no default case");
10151 if (warning.switch_enum)
10152 check_enum_cases(&statement->switchs);
10158 return create_invalid_statement();
10161 static statement_t *parse_loop_body(statement_t *const loop)
10163 statement_t *const rem = current_loop;
10164 current_loop = loop;
10166 statement_t *const body = parse_statement();
10168 current_loop = rem;
10173 * Parse a while statement.
10175 static statement_t *parse_while(void)
10177 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
10181 PUSH_PARENT(statement);
10183 expect('(', end_error);
10184 add_anchor_token(')');
10185 expression_t *const cond = parse_expression();
10186 statement->whiles.condition = cond;
10187 /* §6.8.5:2 The controlling expression of an iteration statement shall
10188 * have scalar type. */
10189 semantic_condition(cond, "condition of 'while'-statement");
10190 mark_vars_read(cond, NULL);
10191 rem_anchor_token(')');
10192 expect(')', end_error);
10194 statement->whiles.body = parse_loop_body(statement);
10200 return create_invalid_statement();
10204 * Parse a do statement.
10206 static statement_t *parse_do(void)
10208 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
10212 PUSH_PARENT(statement);
10214 add_anchor_token(T_while);
10215 statement->do_while.body = parse_loop_body(statement);
10216 rem_anchor_token(T_while);
10218 expect(T_while, end_error);
10219 expect('(', end_error);
10220 add_anchor_token(')');
10221 expression_t *const cond = parse_expression();
10222 statement->do_while.condition = cond;
10223 /* §6.8.5:2 The controlling expression of an iteration statement shall
10224 * have scalar type. */
10225 semantic_condition(cond, "condition of 'do-while'-statement");
10226 mark_vars_read(cond, NULL);
10227 rem_anchor_token(')');
10228 expect(')', end_error);
10229 expect(';', end_error);
10235 return create_invalid_statement();
10239 * Parse a for statement.
10241 static statement_t *parse_for(void)
10243 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
10247 expect('(', end_error1);
10248 add_anchor_token(')');
10250 PUSH_PARENT(statement);
10252 size_t const top = environment_top();
10253 scope_t *old_scope = scope_push(&statement->fors.scope);
10255 if (token.type == ';') {
10257 } else if (is_declaration_specifier(&token, false)) {
10258 parse_declaration(record_entity, DECL_FLAGS_NONE);
10260 add_anchor_token(';');
10261 expression_t *const init = parse_expression();
10262 statement->fors.initialisation = init;
10263 mark_vars_read(init, ENT_ANY);
10264 if (warning.unused_value && !expression_has_effect(init)) {
10265 warningf(&init->base.source_position,
10266 "initialisation of 'for'-statement has no effect");
10268 rem_anchor_token(';');
10269 expect(';', end_error2);
10272 if (token.type != ';') {
10273 add_anchor_token(';');
10274 expression_t *const cond = parse_expression();
10275 statement->fors.condition = cond;
10276 /* §6.8.5:2 The controlling expression of an iteration statement
10277 * shall have scalar type. */
10278 semantic_condition(cond, "condition of 'for'-statement");
10279 mark_vars_read(cond, NULL);
10280 rem_anchor_token(';');
10282 expect(';', end_error2);
10283 if (token.type != ')') {
10284 expression_t *const step = parse_expression();
10285 statement->fors.step = step;
10286 mark_vars_read(step, ENT_ANY);
10287 if (warning.unused_value && !expression_has_effect(step)) {
10288 warningf(&step->base.source_position,
10289 "step of 'for'-statement has no effect");
10292 expect(')', end_error2);
10293 rem_anchor_token(')');
10294 statement->fors.body = parse_loop_body(statement);
10296 assert(current_scope == &statement->fors.scope);
10297 scope_pop(old_scope);
10298 environment_pop_to(top);
10305 rem_anchor_token(')');
10306 assert(current_scope == &statement->fors.scope);
10307 scope_pop(old_scope);
10308 environment_pop_to(top);
10312 return create_invalid_statement();
10316 * Parse a goto statement.
10318 static statement_t *parse_goto(void)
10320 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
10323 if (GNU_MODE && token.type == '*') {
10325 expression_t *expression = parse_expression();
10326 mark_vars_read(expression, NULL);
10328 /* Argh: although documentation says the expression must be of type void*,
10329 * gcc accepts anything that can be casted into void* without error */
10330 type_t *type = expression->base.type;
10332 if (type != type_error_type) {
10333 if (!is_type_pointer(type) && !is_type_integer(type)) {
10334 errorf(&expression->base.source_position,
10335 "cannot convert to a pointer type");
10336 } else if (warning.other && type != type_void_ptr) {
10337 warningf(&expression->base.source_position,
10338 "type of computed goto expression should be 'void*' not '%T'", type);
10340 expression = create_implicit_cast(expression, type_void_ptr);
10343 statement->gotos.expression = expression;
10345 if (token.type != T_IDENTIFIER) {
10347 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
10349 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
10350 eat_until_anchor();
10353 symbol_t *symbol = token.v.symbol;
10356 statement->gotos.label = get_label(symbol);
10359 /* remember the goto's in a list for later checking */
10360 *goto_anchor = &statement->gotos;
10361 goto_anchor = &statement->gotos.next;
10363 expect(';', end_error);
10367 return create_invalid_statement();
10371 * Parse a continue statement.
10373 static statement_t *parse_continue(void)
10375 if (current_loop == NULL) {
10376 errorf(HERE, "continue statement not within loop");
10379 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
10382 expect(';', end_error);
10389 * Parse a break statement.
10391 static statement_t *parse_break(void)
10393 if (current_switch == NULL && current_loop == NULL) {
10394 errorf(HERE, "break statement not within loop or switch");
10397 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10400 expect(';', end_error);
10407 * Parse a __leave statement.
10409 static statement_t *parse_leave_statement(void)
10411 if (current_try == NULL) {
10412 errorf(HERE, "__leave statement not within __try");
10415 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10418 expect(';', end_error);
10425 * Check if a given entity represents a local variable.
10427 static bool is_local_variable(const entity_t *entity)
10429 if (entity->kind != ENTITY_VARIABLE)
10432 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10433 case STORAGE_CLASS_AUTO:
10434 case STORAGE_CLASS_REGISTER: {
10435 const type_t *type = skip_typeref(entity->declaration.type);
10436 if (is_type_function(type)) {
10448 * Check if a given expression represents a local variable.
10450 static bool expression_is_local_variable(const expression_t *expression)
10452 if (expression->base.kind != EXPR_REFERENCE) {
10455 const entity_t *entity = expression->reference.entity;
10456 return is_local_variable(entity);
10460 * Check if a given expression represents a local variable and
10461 * return its declaration then, else return NULL.
10463 entity_t *expression_is_variable(const expression_t *expression)
10465 if (expression->base.kind != EXPR_REFERENCE) {
10468 entity_t *entity = expression->reference.entity;
10469 if (entity->kind != ENTITY_VARIABLE)
10476 * Parse a return statement.
10478 static statement_t *parse_return(void)
10482 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10484 expression_t *return_value = NULL;
10485 if (token.type != ';') {
10486 return_value = parse_expression();
10487 mark_vars_read(return_value, NULL);
10490 const type_t *const func_type = skip_typeref(current_function->base.type);
10491 assert(is_type_function(func_type));
10492 type_t *const return_type = skip_typeref(func_type->function.return_type);
10494 source_position_t const *const pos = &statement->base.source_position;
10495 if (return_value != NULL) {
10496 type_t *return_value_type = skip_typeref(return_value->base.type);
10498 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10499 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10500 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10501 /* Only warn in C mode, because GCC does the same */
10502 if (c_mode & _CXX || strict_mode) {
10504 "'return' with a value, in function returning 'void'");
10505 } else if (warning.other) {
10507 "'return' with a value, in function returning 'void'");
10509 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10510 /* Only warn in C mode, because GCC does the same */
10513 "'return' with expression in function return 'void'");
10514 } else if (warning.other) {
10516 "'return' with expression in function return 'void'");
10520 assign_error_t error = semantic_assign(return_type, return_value);
10521 report_assign_error(error, return_type, return_value, "'return'",
10524 return_value = create_implicit_cast(return_value, return_type);
10525 /* check for returning address of a local var */
10526 if (warning.other && return_value != NULL
10527 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10528 const expression_t *expression = return_value->unary.value;
10529 if (expression_is_local_variable(expression)) {
10530 warningf(pos, "function returns address of local variable");
10533 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10534 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10535 if (c_mode & _CXX || strict_mode) {
10537 "'return' without value, in function returning non-void");
10540 "'return' without value, in function returning non-void");
10543 statement->returns.value = return_value;
10545 expect(';', end_error);
10552 * Parse a declaration statement.
10554 static statement_t *parse_declaration_statement(void)
10556 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10558 entity_t *before = current_scope->last_entity;
10560 parse_external_declaration();
10562 parse_declaration(record_entity, DECL_FLAGS_NONE);
10565 if (before == NULL) {
10566 statement->declaration.declarations_begin = current_scope->entities;
10568 statement->declaration.declarations_begin = before->base.next;
10570 statement->declaration.declarations_end = current_scope->last_entity;
10576 * Parse an expression statement, ie. expr ';'.
10578 static statement_t *parse_expression_statement(void)
10580 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10582 expression_t *const expr = parse_expression();
10583 statement->expression.expression = expr;
10584 mark_vars_read(expr, ENT_ANY);
10586 expect(';', end_error);
10593 * Parse a microsoft __try { } __finally { } or
10594 * __try{ } __except() { }
10596 static statement_t *parse_ms_try_statment(void)
10598 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10601 PUSH_PARENT(statement);
10603 ms_try_statement_t *rem = current_try;
10604 current_try = &statement->ms_try;
10605 statement->ms_try.try_statement = parse_compound_statement(false);
10610 if (token.type == T___except) {
10612 expect('(', end_error);
10613 add_anchor_token(')');
10614 expression_t *const expr = parse_expression();
10615 mark_vars_read(expr, NULL);
10616 type_t * type = skip_typeref(expr->base.type);
10617 if (is_type_integer(type)) {
10618 type = promote_integer(type);
10619 } else if (is_type_valid(type)) {
10620 errorf(&expr->base.source_position,
10621 "__expect expression is not an integer, but '%T'", type);
10622 type = type_error_type;
10624 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10625 rem_anchor_token(')');
10626 expect(')', end_error);
10627 statement->ms_try.final_statement = parse_compound_statement(false);
10628 } else if (token.type == T__finally) {
10630 statement->ms_try.final_statement = parse_compound_statement(false);
10632 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10633 return create_invalid_statement();
10637 return create_invalid_statement();
10640 static statement_t *parse_empty_statement(void)
10642 if (warning.empty_statement) {
10643 warningf(HERE, "statement is empty");
10645 statement_t *const statement = create_empty_statement();
10650 static statement_t *parse_local_label_declaration(void)
10652 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10656 entity_t *begin = NULL, *end = NULL;
10659 if (token.type != T_IDENTIFIER) {
10660 parse_error_expected("while parsing local label declaration",
10661 T_IDENTIFIER, NULL);
10664 symbol_t *symbol = token.v.symbol;
10665 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10666 if (entity != NULL && entity->base.parent_scope == current_scope) {
10667 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10668 symbol, &entity->base.source_position);
10670 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10672 entity->base.parent_scope = current_scope;
10673 entity->base.namespc = NAMESPACE_LABEL;
10674 entity->base.source_position = token.source_position;
10675 entity->base.symbol = symbol;
10678 end->base.next = entity;
10683 environment_push(entity);
10687 if (token.type != ',')
10693 statement->declaration.declarations_begin = begin;
10694 statement->declaration.declarations_end = end;
10698 static void parse_namespace_definition(void)
10702 entity_t *entity = NULL;
10703 symbol_t *symbol = NULL;
10705 if (token.type == T_IDENTIFIER) {
10706 symbol = token.v.symbol;
10709 entity = get_entity(symbol, NAMESPACE_NORMAL);
10710 if (entity != NULL && entity->kind != ENTITY_NAMESPACE
10711 && entity->base.parent_scope == current_scope) {
10712 error_redefined_as_different_kind(&token.source_position,
10713 entity, ENTITY_NAMESPACE);
10718 if (entity == NULL) {
10719 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10720 entity->base.symbol = symbol;
10721 entity->base.source_position = token.source_position;
10722 entity->base.namespc = NAMESPACE_NORMAL;
10723 entity->base.parent_scope = current_scope;
10726 if (token.type == '=') {
10727 /* TODO: parse namespace alias */
10728 panic("namespace alias definition not supported yet");
10731 environment_push(entity);
10732 append_entity(current_scope, entity);
10734 size_t const top = environment_top();
10735 scope_t *old_scope = scope_push(&entity->namespacee.members);
10737 expect('{', end_error);
10739 expect('}', end_error);
10742 assert(current_scope == &entity->namespacee.members);
10743 scope_pop(old_scope);
10744 environment_pop_to(top);
10748 * Parse a statement.
10749 * There's also parse_statement() which additionally checks for
10750 * "statement has no effect" warnings
10752 static statement_t *intern_parse_statement(void)
10754 statement_t *statement = NULL;
10756 /* declaration or statement */
10757 add_anchor_token(';');
10758 switch (token.type) {
10759 case T_IDENTIFIER: {
10760 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10761 if (la1_type == ':') {
10762 statement = parse_label_statement();
10763 } else if (is_typedef_symbol(token.v.symbol)) {
10764 statement = parse_declaration_statement();
10766 /* it's an identifier, the grammar says this must be an
10767 * expression statement. However it is common that users mistype
10768 * declaration types, so we guess a bit here to improve robustness
10769 * for incorrect programs */
10770 switch (la1_type) {
10773 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10774 goto expression_statment;
10779 statement = parse_declaration_statement();
10783 expression_statment:
10784 statement = parse_expression_statement();
10791 case T___extension__:
10792 /* This can be a prefix to a declaration or an expression statement.
10793 * We simply eat it now and parse the rest with tail recursion. */
10796 } while (token.type == T___extension__);
10797 bool old_gcc_extension = in_gcc_extension;
10798 in_gcc_extension = true;
10799 statement = intern_parse_statement();
10800 in_gcc_extension = old_gcc_extension;
10804 statement = parse_declaration_statement();
10808 statement = parse_local_label_declaration();
10811 case ';': statement = parse_empty_statement(); break;
10812 case '{': statement = parse_compound_statement(false); break;
10813 case T___leave: statement = parse_leave_statement(); break;
10814 case T___try: statement = parse_ms_try_statment(); break;
10815 case T_asm: statement = parse_asm_statement(); break;
10816 case T_break: statement = parse_break(); break;
10817 case T_case: statement = parse_case_statement(); break;
10818 case T_continue: statement = parse_continue(); break;
10819 case T_default: statement = parse_default_statement(); break;
10820 case T_do: statement = parse_do(); break;
10821 case T_for: statement = parse_for(); break;
10822 case T_goto: statement = parse_goto(); break;
10823 case T_if: statement = parse_if(); break;
10824 case T_return: statement = parse_return(); break;
10825 case T_switch: statement = parse_switch(); break;
10826 case T_while: statement = parse_while(); break;
10829 statement = parse_expression_statement();
10833 errorf(HERE, "unexpected token %K while parsing statement", &token);
10834 statement = create_invalid_statement();
10839 rem_anchor_token(';');
10841 assert(statement != NULL
10842 && statement->base.source_position.input_name != NULL);
10848 * parse a statement and emits "statement has no effect" warning if needed
10849 * (This is really a wrapper around intern_parse_statement with check for 1
10850 * single warning. It is needed, because for statement expressions we have
10851 * to avoid the warning on the last statement)
10853 static statement_t *parse_statement(void)
10855 statement_t *statement = intern_parse_statement();
10857 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10858 expression_t *expression = statement->expression.expression;
10859 if (!expression_has_effect(expression)) {
10860 warningf(&expression->base.source_position,
10861 "statement has no effect");
10869 * Parse a compound statement.
10871 static statement_t *parse_compound_statement(bool inside_expression_statement)
10873 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10875 PUSH_PARENT(statement);
10878 add_anchor_token('}');
10879 /* tokens, which can start a statement */
10880 /* TODO MS, __builtin_FOO */
10881 add_anchor_token('!');
10882 add_anchor_token('&');
10883 add_anchor_token('(');
10884 add_anchor_token('*');
10885 add_anchor_token('+');
10886 add_anchor_token('-');
10887 add_anchor_token('{');
10888 add_anchor_token('~');
10889 add_anchor_token(T_CHARACTER_CONSTANT);
10890 add_anchor_token(T_COLONCOLON);
10891 add_anchor_token(T_FLOATINGPOINT);
10892 add_anchor_token(T_IDENTIFIER);
10893 add_anchor_token(T_INTEGER);
10894 add_anchor_token(T_MINUSMINUS);
10895 add_anchor_token(T_PLUSPLUS);
10896 add_anchor_token(T_STRING_LITERAL);
10897 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10898 add_anchor_token(T_WIDE_STRING_LITERAL);
10899 add_anchor_token(T__Bool);
10900 add_anchor_token(T__Complex);
10901 add_anchor_token(T__Imaginary);
10902 add_anchor_token(T___FUNCTION__);
10903 add_anchor_token(T___PRETTY_FUNCTION__);
10904 add_anchor_token(T___alignof__);
10905 add_anchor_token(T___attribute__);
10906 add_anchor_token(T___builtin_va_start);
10907 add_anchor_token(T___extension__);
10908 add_anchor_token(T___func__);
10909 add_anchor_token(T___imag__);
10910 add_anchor_token(T___label__);
10911 add_anchor_token(T___real__);
10912 add_anchor_token(T___thread);
10913 add_anchor_token(T_asm);
10914 add_anchor_token(T_auto);
10915 add_anchor_token(T_bool);
10916 add_anchor_token(T_break);
10917 add_anchor_token(T_case);
10918 add_anchor_token(T_char);
10919 add_anchor_token(T_class);
10920 add_anchor_token(T_const);
10921 add_anchor_token(T_const_cast);
10922 add_anchor_token(T_continue);
10923 add_anchor_token(T_default);
10924 add_anchor_token(T_delete);
10925 add_anchor_token(T_double);
10926 add_anchor_token(T_do);
10927 add_anchor_token(T_dynamic_cast);
10928 add_anchor_token(T_enum);
10929 add_anchor_token(T_extern);
10930 add_anchor_token(T_false);
10931 add_anchor_token(T_float);
10932 add_anchor_token(T_for);
10933 add_anchor_token(T_goto);
10934 add_anchor_token(T_if);
10935 add_anchor_token(T_inline);
10936 add_anchor_token(T_int);
10937 add_anchor_token(T_long);
10938 add_anchor_token(T_new);
10939 add_anchor_token(T_operator);
10940 add_anchor_token(T_register);
10941 add_anchor_token(T_reinterpret_cast);
10942 add_anchor_token(T_restrict);
10943 add_anchor_token(T_return);
10944 add_anchor_token(T_short);
10945 add_anchor_token(T_signed);
10946 add_anchor_token(T_sizeof);
10947 add_anchor_token(T_static);
10948 add_anchor_token(T_static_cast);
10949 add_anchor_token(T_struct);
10950 add_anchor_token(T_switch);
10951 add_anchor_token(T_template);
10952 add_anchor_token(T_this);
10953 add_anchor_token(T_throw);
10954 add_anchor_token(T_true);
10955 add_anchor_token(T_try);
10956 add_anchor_token(T_typedef);
10957 add_anchor_token(T_typeid);
10958 add_anchor_token(T_typename);
10959 add_anchor_token(T_typeof);
10960 add_anchor_token(T_union);
10961 add_anchor_token(T_unsigned);
10962 add_anchor_token(T_using);
10963 add_anchor_token(T_void);
10964 add_anchor_token(T_volatile);
10965 add_anchor_token(T_wchar_t);
10966 add_anchor_token(T_while);
10968 size_t const top = environment_top();
10969 scope_t *old_scope = scope_push(&statement->compound.scope);
10971 statement_t **anchor = &statement->compound.statements;
10972 bool only_decls_so_far = true;
10973 while (token.type != '}') {
10974 if (token.type == T_EOF) {
10975 errorf(&statement->base.source_position,
10976 "EOF while parsing compound statement");
10979 statement_t *sub_statement = intern_parse_statement();
10980 if (is_invalid_statement(sub_statement)) {
10981 /* an error occurred. if we are at an anchor, return */
10987 if (warning.declaration_after_statement) {
10988 if (sub_statement->kind != STATEMENT_DECLARATION) {
10989 only_decls_so_far = false;
10990 } else if (!only_decls_so_far) {
10991 warningf(&sub_statement->base.source_position,
10992 "ISO C90 forbids mixed declarations and code");
10996 *anchor = sub_statement;
10998 while (sub_statement->base.next != NULL)
10999 sub_statement = sub_statement->base.next;
11001 anchor = &sub_statement->base.next;
11005 /* look over all statements again to produce no effect warnings */
11006 if (warning.unused_value) {
11007 statement_t *sub_statement = statement->compound.statements;
11008 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
11009 if (sub_statement->kind != STATEMENT_EXPRESSION)
11011 /* don't emit a warning for the last expression in an expression
11012 * statement as it has always an effect */
11013 if (inside_expression_statement && sub_statement->base.next == NULL)
11016 expression_t *expression = sub_statement->expression.expression;
11017 if (!expression_has_effect(expression)) {
11018 warningf(&expression->base.source_position,
11019 "statement has no effect");
11025 rem_anchor_token(T_while);
11026 rem_anchor_token(T_wchar_t);
11027 rem_anchor_token(T_volatile);
11028 rem_anchor_token(T_void);
11029 rem_anchor_token(T_using);
11030 rem_anchor_token(T_unsigned);
11031 rem_anchor_token(T_union);
11032 rem_anchor_token(T_typeof);
11033 rem_anchor_token(T_typename);
11034 rem_anchor_token(T_typeid);
11035 rem_anchor_token(T_typedef);
11036 rem_anchor_token(T_try);
11037 rem_anchor_token(T_true);
11038 rem_anchor_token(T_throw);
11039 rem_anchor_token(T_this);
11040 rem_anchor_token(T_template);
11041 rem_anchor_token(T_switch);
11042 rem_anchor_token(T_struct);
11043 rem_anchor_token(T_static_cast);
11044 rem_anchor_token(T_static);
11045 rem_anchor_token(T_sizeof);
11046 rem_anchor_token(T_signed);
11047 rem_anchor_token(T_short);
11048 rem_anchor_token(T_return);
11049 rem_anchor_token(T_restrict);
11050 rem_anchor_token(T_reinterpret_cast);
11051 rem_anchor_token(T_register);
11052 rem_anchor_token(T_operator);
11053 rem_anchor_token(T_new);
11054 rem_anchor_token(T_long);
11055 rem_anchor_token(T_int);
11056 rem_anchor_token(T_inline);
11057 rem_anchor_token(T_if);
11058 rem_anchor_token(T_goto);
11059 rem_anchor_token(T_for);
11060 rem_anchor_token(T_float);
11061 rem_anchor_token(T_false);
11062 rem_anchor_token(T_extern);
11063 rem_anchor_token(T_enum);
11064 rem_anchor_token(T_dynamic_cast);
11065 rem_anchor_token(T_do);
11066 rem_anchor_token(T_double);
11067 rem_anchor_token(T_delete);
11068 rem_anchor_token(T_default);
11069 rem_anchor_token(T_continue);
11070 rem_anchor_token(T_const_cast);
11071 rem_anchor_token(T_const);
11072 rem_anchor_token(T_class);
11073 rem_anchor_token(T_char);
11074 rem_anchor_token(T_case);
11075 rem_anchor_token(T_break);
11076 rem_anchor_token(T_bool);
11077 rem_anchor_token(T_auto);
11078 rem_anchor_token(T_asm);
11079 rem_anchor_token(T___thread);
11080 rem_anchor_token(T___real__);
11081 rem_anchor_token(T___label__);
11082 rem_anchor_token(T___imag__);
11083 rem_anchor_token(T___func__);
11084 rem_anchor_token(T___extension__);
11085 rem_anchor_token(T___builtin_va_start);
11086 rem_anchor_token(T___attribute__);
11087 rem_anchor_token(T___alignof__);
11088 rem_anchor_token(T___PRETTY_FUNCTION__);
11089 rem_anchor_token(T___FUNCTION__);
11090 rem_anchor_token(T__Imaginary);
11091 rem_anchor_token(T__Complex);
11092 rem_anchor_token(T__Bool);
11093 rem_anchor_token(T_WIDE_STRING_LITERAL);
11094 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
11095 rem_anchor_token(T_STRING_LITERAL);
11096 rem_anchor_token(T_PLUSPLUS);
11097 rem_anchor_token(T_MINUSMINUS);
11098 rem_anchor_token(T_INTEGER);
11099 rem_anchor_token(T_IDENTIFIER);
11100 rem_anchor_token(T_FLOATINGPOINT);
11101 rem_anchor_token(T_COLONCOLON);
11102 rem_anchor_token(T_CHARACTER_CONSTANT);
11103 rem_anchor_token('~');
11104 rem_anchor_token('{');
11105 rem_anchor_token('-');
11106 rem_anchor_token('+');
11107 rem_anchor_token('*');
11108 rem_anchor_token('(');
11109 rem_anchor_token('&');
11110 rem_anchor_token('!');
11111 rem_anchor_token('}');
11112 assert(current_scope == &statement->compound.scope);
11113 scope_pop(old_scope);
11114 environment_pop_to(top);
11121 * Check for unused global static functions and variables
11123 static void check_unused_globals(void)
11125 if (!warning.unused_function && !warning.unused_variable)
11128 for (const entity_t *entity = file_scope->entities; entity != NULL;
11129 entity = entity->base.next) {
11130 if (!is_declaration(entity))
11133 const declaration_t *declaration = &entity->declaration;
11134 if (declaration->used ||
11135 declaration->modifiers & DM_UNUSED ||
11136 declaration->modifiers & DM_USED ||
11137 declaration->storage_class != STORAGE_CLASS_STATIC)
11140 type_t *const type = declaration->type;
11142 if (entity->kind == ENTITY_FUNCTION) {
11143 /* inhibit warning for static inline functions */
11144 if (entity->function.is_inline)
11147 s = entity->function.statement != NULL ? "defined" : "declared";
11152 warningf(&declaration->base.source_position, "'%#T' %s but not used",
11153 type, declaration->base.symbol, s);
11157 static void parse_global_asm(void)
11159 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
11162 expect('(', end_error);
11164 statement->asms.asm_text = parse_string_literals();
11165 statement->base.next = unit->global_asm;
11166 unit->global_asm = statement;
11168 expect(')', end_error);
11169 expect(';', end_error);
11174 static void parse_linkage_specification(void)
11177 assert(token.type == T_STRING_LITERAL);
11179 const char *linkage = parse_string_literals().begin;
11181 linkage_kind_t old_linkage = current_linkage;
11182 linkage_kind_t new_linkage;
11183 if (strcmp(linkage, "C") == 0) {
11184 new_linkage = LINKAGE_C;
11185 } else if (strcmp(linkage, "C++") == 0) {
11186 new_linkage = LINKAGE_CXX;
11188 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
11189 new_linkage = LINKAGE_INVALID;
11191 current_linkage = new_linkage;
11193 if (token.type == '{') {
11196 expect('}', end_error);
11202 assert(current_linkage == new_linkage);
11203 current_linkage = old_linkage;
11206 static void parse_external(void)
11208 switch (token.type) {
11209 DECLARATION_START_NO_EXTERN
11211 case T___extension__:
11212 /* tokens below are for implicit int */
11213 case '&': /* & x; -> int& x; (and error later, because C++ has no
11215 case '*': /* * x; -> int* x; */
11216 case '(': /* (x); -> int (x); */
11217 parse_external_declaration();
11221 if (look_ahead(1)->type == T_STRING_LITERAL) {
11222 parse_linkage_specification();
11224 parse_external_declaration();
11229 parse_global_asm();
11233 parse_namespace_definition();
11237 if (!strict_mode) {
11239 warningf(HERE, "stray ';' outside of function");
11246 errorf(HERE, "stray %K outside of function", &token);
11247 if (token.type == '(' || token.type == '{' || token.type == '[')
11248 eat_until_matching_token(token.type);
11254 static void parse_externals(void)
11256 add_anchor_token('}');
11257 add_anchor_token(T_EOF);
11260 unsigned char token_anchor_copy[T_LAST_TOKEN];
11261 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
11264 while (token.type != T_EOF && token.type != '}') {
11266 bool anchor_leak = false;
11267 for (int i = 0; i != T_LAST_TOKEN; ++i) {
11268 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
11270 errorf(HERE, "Leaked anchor token %k %d times", i, count);
11271 anchor_leak = true;
11274 if (in_gcc_extension) {
11275 errorf(HERE, "Leaked __extension__");
11276 anchor_leak = true;
11286 rem_anchor_token(T_EOF);
11287 rem_anchor_token('}');
11291 * Parse a translation unit.
11293 static void parse_translation_unit(void)
11295 add_anchor_token(T_EOF);
11300 if (token.type == T_EOF)
11303 errorf(HERE, "stray %K outside of function", &token);
11304 if (token.type == '(' || token.type == '{' || token.type == '[')
11305 eat_until_matching_token(token.type);
11313 * @return the translation unit or NULL if errors occurred.
11315 void start_parsing(void)
11317 environment_stack = NEW_ARR_F(stack_entry_t, 0);
11318 label_stack = NEW_ARR_F(stack_entry_t, 0);
11319 diagnostic_count = 0;
11323 type_set_output(stderr);
11324 ast_set_output(stderr);
11326 assert(unit == NULL);
11327 unit = allocate_ast_zero(sizeof(unit[0]));
11329 assert(file_scope == NULL);
11330 file_scope = &unit->scope;
11332 assert(current_scope == NULL);
11333 scope_push(&unit->scope);
11336 translation_unit_t *finish_parsing(void)
11338 assert(current_scope == &unit->scope);
11341 assert(file_scope == &unit->scope);
11342 check_unused_globals();
11345 DEL_ARR_F(environment_stack);
11346 DEL_ARR_F(label_stack);
11348 translation_unit_t *result = unit;
11353 /* GCC allows global arrays without size and assigns them a length of one,
11354 * if no different declaration follows */
11355 static void complete_incomplete_arrays(void)
11357 size_t n = ARR_LEN(incomplete_arrays);
11358 for (size_t i = 0; i != n; ++i) {
11359 declaration_t *const decl = incomplete_arrays[i];
11360 type_t *const orig_type = decl->type;
11361 type_t *const type = skip_typeref(orig_type);
11363 if (!is_type_incomplete(type))
11366 if (warning.other) {
11367 warningf(&decl->base.source_position,
11368 "array '%#T' assumed to have one element",
11369 orig_type, decl->base.symbol);
11372 type_t *const new_type = duplicate_type(type);
11373 new_type->array.size_constant = true;
11374 new_type->array.has_implicit_size = true;
11375 new_type->array.size = 1;
11377 type_t *const result = identify_new_type(new_type);
11379 decl->type = result;
11385 lookahead_bufpos = 0;
11386 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
11389 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
11390 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
11391 parse_translation_unit();
11392 complete_incomplete_arrays();
11393 DEL_ARR_F(incomplete_arrays);
11394 incomplete_arrays = NULL;
11398 * Initialize the parser.
11400 void init_parser(void)
11402 sym_anonymous = symbol_table_insert("<anonymous>");
11404 if (c_mode & _MS) {
11405 /* add predefined symbols for extended-decl-modifier */
11406 sym_align = symbol_table_insert("align");
11407 sym_allocate = symbol_table_insert("allocate");
11408 sym_dllimport = symbol_table_insert("dllimport");
11409 sym_dllexport = symbol_table_insert("dllexport");
11410 sym_naked = symbol_table_insert("naked");
11411 sym_noinline = symbol_table_insert("noinline");
11412 sym_returns_twice = symbol_table_insert("returns_twice");
11413 sym_noreturn = symbol_table_insert("noreturn");
11414 sym_nothrow = symbol_table_insert("nothrow");
11415 sym_novtable = symbol_table_insert("novtable");
11416 sym_property = symbol_table_insert("property");
11417 sym_get = symbol_table_insert("get");
11418 sym_put = symbol_table_insert("put");
11419 sym_selectany = symbol_table_insert("selectany");
11420 sym_thread = symbol_table_insert("thread");
11421 sym_uuid = symbol_table_insert("uuid");
11422 sym_deprecated = symbol_table_insert("deprecated");
11423 sym_restrict = symbol_table_insert("restrict");
11424 sym_noalias = symbol_table_insert("noalias");
11426 memset(token_anchor_set, 0, sizeof(token_anchor_set));
11428 init_expression_parsers();
11429 obstack_init(&temp_obst);
11431 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11432 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11436 * Terminate the parser.
11438 void exit_parser(void)
11440 obstack_free(&temp_obst, NULL);